From 4e2d22a71d0542105c66e329e5fe295b0905b0d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Fri, 17 Aug 2018 15:15:24 +0100 Subject: [PATCH] YAPC::EU 2018 Glasgow Update! --- Lang/360-Assembly/Literals-Floating-point | 1 + Lang/360-Assembly/Nth-root | 1 + Lang/360-Assembly/Palindrome-detection | 1 + Lang/8th/Accumulator-factory | 1 + Lang/8th/Array-concatenation | 1 + Lang/8th/Associative-array-Creation | 1 + Lang/8th/Associative-array-Iteration | 1 + Lang/8th/Atomic-updates | 1 + Lang/ABAP/Guess-the-number | 1 + Lang/ALGOL-60/Loops-Do-while | 1 + Lang/ALGOL-60/Loops-Downward-for | 1 + Lang/ALGOL-60/Loops-Infinite | 1 + Lang/ARM-Assembly/Binary-digits | 1 + Lang/ARM-Assembly/Bitwise-operations | 1 + Lang/ARM-Assembly/Factors-of-an-integer | 1 + Lang/ARM-Assembly/Function-definition | 1 + Lang/ARM-Assembly/Integer-comparison | 1 + Lang/ARM-Assembly/Loops-For | 1 + Lang/ARM-Assembly/String-comparison | 1 + Lang/ARM-Assembly/User-input-Text | 1 + Lang/Agda/Extend-your-language | 1 + Lang/Astro/00DESCRIPTION | 4 +- Lang/BASIC/Pi | 1 + Lang/BASIC256/00DESCRIPTION | 2 +- Lang/BaCon/HTTPS | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/Bc/Zero-to-the-zero-power | 1 + Lang/Beeswax/Empty-program | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Befunge/Amicable-pairs | 1 + Lang/Befunge/Colour-pinstripe-Display | 1 + Lang/Befunge/Conways-Game-of-Life | 1 + Lang/Befunge/Dragon-curve | 1 + Lang/Befunge/Draw-a-cuboid | 1 + .../Befunge/Fibonacci-n-step-number-sequences | 1 + Lang/Befunge/Find-limit-of-recursion | 1 + Lang/Befunge/Fractran | 1 + Lang/Befunge/Guess-the-number-With-feedback | 1 + Lang/Befunge/IBAN | 1 + Lang/Befunge/Iterated-digits-squaring | 1 + Lang/Befunge/Langtons-ant | 1 + Lang/Befunge/Least-common-multiple | 1 + Lang/Befunge/Munching-squares | 1 + Lang/Befunge/N-queens-problem | 1 + Lang/Befunge/Narcissistic-decimal-number | 1 + Lang/Befunge/Pangram-checker | 1 + Lang/Befunge/Pinstripe-Display | 1 + Lang/Befunge/Sudoku | 1 + Lang/C++/Count-the-coins | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/C++/Zhang-Suen-thinning-algorithm | 1 + Lang/C-sharp/Longest-increasing-subsequence | 1 + .../Use-another-language-to-call-a-function | 1 + .../Dinesmans-multiple-dwelling-problem | 1 + Lang/Ceylon/Dutch-national-flag-problem | 1 + Lang/Ceylon/Fractal-tree | 1 + Lang/Crystal/Combinations | 1 + Lang/Crystal/Flatten-a-list | 1 + Lang/Crystal/Hailstone-sequence | 1 + Lang/Crystal/JSON | 1 + Lang/Crystal/Number-reversal-game | 1 + Lang/Crystal/Palindrome-detection | 1 + Lang/Crystal/Pick-random-element | 1 + Lang/Crystal/Repeat-a-string | 1 + Lang/Crystal/Sort-an-integer-array | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Crystal/Sum-and-product-of-an-array | 1 + Lang/Crystal/Sum-multiples-of-3-and-5 | 1 + Lang/Crystal/Sum-of-squares | 1 + Lang/Dart/Leap-year | 1 + Lang/Elena/00DESCRIPTION | 30 +- Lang/Elm/00DESCRIPTION | 2 +- Lang/Emacs-Lisp/99-Bottles-of-Beer | 1 + Lang/Emacs-Lisp/Character-codes | 1 + Lang/Emacs-Lisp/Copy-a-string | 1 + Lang/Emacs-Lisp/Create-a-file | 1 + Lang/Emacs-Lisp/Delete-a-file | 1 + Lang/Emacs-Lisp/Execute-a-system-command | 1 + Lang/Emacs-Lisp/FizzBuzz | 1 + Lang/Emacs-Lisp/Guess-the-number | 1 + .../Emacs-Lisp/Guess-the-number-With-feedback | 1 + Lang/Emacs-Lisp/Josephus-problem | 1 + Lang/Factor/Aliquot-sequence-classifications | 1 + Lang/Factor/Define-a-primitive-data-type | 1 + Lang/Factor/Identity-matrix | 1 + Lang/Factor/Object-serialization | 1 + Lang/Factor/Quaternion-type | 1 + Lang/Factor/Queue-Usage | 1 + Lang/Factor/Rep-string | 1 + Lang/Factor/SHA-256 | 1 + Lang/Factor/Stern-Brocot-sequence | 1 + Lang/Factor/Strip-comments-from-a-string | 1 + Lang/Forth/Define-a-primitive-data-type | 1 + Lang/Forth/Dutch-national-flag-problem | 1 + Lang/Forth/Metaprogramming | 1 + Lang/Forth/Strip-comments-from-a-string | 1 + Lang/Forth/Terminal-control-Coloured-text | 1 + Lang/Forth/Terminal-control-Cursor-movement | 1 + Lang/FreeBASIC/Check-Machin-like-formulas | 1 + Lang/FreeBASIC/Evolutionary-algorithm | 1 + .../Hofstadter-Conway-$10,000-sequence | 1 + Lang/FreeBASIC/Image-noise | 1 + Lang/FreeBASIC/Modular-inverse | 1 + Lang/FreeBASIC/Pi | 1 + Lang/FreeBASIC/Resistor-mesh | 1 + Lang/Futhark/Apply-a-callback-to-an-array | 1 + .../Go/Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Go/Bitwise-IO | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + ...ithmetic-G-matrix-NG,-Contined-Fraction-N- | 1 + ...ontined-Fraction-N1,-Contined-Fraction-N2- | 1 + Lang/Go/First-class-environments | 1 + Lang/Go/Galton-box-animation | 1 + Lang/Go/Inverted-syntax | 1 + Lang/Go/Jensens-Device | 1 + Lang/Go/Solve-a-Hidato-puzzle | 1 + Lang/Go/Solve-a-Hopido-puzzle | 1 + Lang/Go/Solve-a-Numbrix-puzzle | 1 + Lang/Go/Terminal-control-Preserve-screen | 1 + Lang/Go/Video-display-modes | 1 + Lang/Groovy/Integer-sequence | 1 + Lang/Java/00DESCRIPTION | 1 + Lang/Java/QR-decomposition | 1 + Lang/Java/Set-of-real-numbers | 1 + Lang/Java/Terminal-control-Preserve-screen | 1 + Lang/K/Digital-root | 1 + Lang/K/Even-or-odd | 1 + Lang/K/Harshad-or-Niven-series | 1 + Lang/K/Hello-world-Text | 1 + Lang/K/Hostname | 1 + Lang/K/Loops-While | 1 + Lang/K/Reverse-a-string | 1 + Lang/K/String-concatenation | 1 + Lang/K/String-length | 1 + Lang/K/String-prepend | 1 + Lang/K/Substring-Top-and-tail | 1 + Lang/Lambdatalk/Hello-world-Text | 1 + Lang/Lua/00DESCRIPTION | 24 +- Lang/Lua/DNS-query | 1 + Lang/Lua/HTTPS | 1 + Lang/Lua/HTTPS-Authenticated | 1 + Lang/Maple/Almost-prime | 1 + Lang/Maple/Hough-transform | 1 + Lang/Maple/I-before-E-except-after-C | 1 + Lang/Maple/Image-convolution | 1 + Lang/Maple/Knapsack-problem-0-1 | 1 + Lang/Maple/Order-two-numerical-lists | 1 + Lang/Maple/Phrase-reversals | 1 + Lang/Maple/Plot-coordinate-pairs | 1 + Lang/Maple/Queue-Usage | 1 + Lang/Maple/Range-extraction | 1 + Lang/Maple/Read-a-specific-line-from-a-file | 1 + Lang/Maple/Reverse-words-in-a-string | 1 + Lang/Maple/Short-circuit-evaluation | 1 + Lang/Maple/Sort-disjoint-sublist | 1 + Lang/Maple/Sorting-algorithms-Pancake-sort | 1 + Lang/Maple/Vector-products | 1 + Lang/Mathematica/MD4 | 1 + Lang/Mathematica/RIPEMD-160 | 1 + Lang/Modula-2/Binary-digits | 1 + Lang/NewLISP/Ackermann-function | 1 + Lang/NewLISP/Detect-division-by-zero | 1 + Lang/NewLISP/Null-object | 1 + Lang/Nial/Zero-to-the-zero-power | 1 + Lang/Ol/Matrix-multiplication | 1 + Lang/PARI-GP/00DESCRIPTION | 5 + Lang/PHP/Strip-block-comments | 1 + Lang/PL-I/Jump-anywhere | 1 + Lang/Perl/Solve-a-Numbrix-puzzle | 1 + Lang/Phix/Bitcoin-address-validation | 1 + Lang/Phix/Bitcoin-public-point-to-address | 1 + Lang/Phix/Delegates | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Phix/HTTP | 1 + Lang/Phix/HTTPS | 1 + Lang/Phix/HTTPS-Authenticated | 1 + Lang/Phix/HTTPS-Client-authenticated | 1 + Lang/Phix/History-variables | 1 + Lang/Phix/Huffman-coding | 1 + Lang/Phix/Keyboard-macros | 1 + Lang/Phix/Knuths-algorithm-S | 1 + Lang/Phix/LU-decomposition | 1 + Lang/Phix/MD4 | 1 + Lang/Phix/Main-step-of-GOST-28147-89 | 1 + Lang/Phix/Metronome | 1 + Lang/Phix/Minesweeper-game | 1 + Lang/Phix/Nautical-bell | 1 + Lang/Phix/Parametrized-SQL-statement | 1 + Lang/Phix/Pascals-triangle-Puzzle | 1 + Lang/Phix/RIPEMD-160 | 1 + Lang/Phix/Random-number-generator--device- | 1 + Lang/Phix/Respond-to-an-unknown-method-call | 1 + Lang/Phix/SHA-1 | 1 + ...odes-and-extended-characters-from-a-string | 1 + Lang/Phix/Table-creation-Postal-addresses | 1 + Lang/Phix/Terminal-control-Preserve-screen | 1 + Lang/Phix/Terminal-control-Unicode-output | 1 + Lang/Phix/Video-display-modes | 1 + Lang/Python/99-Bottles-of-Beer | 1 + Lang/Python/Bitmap-Histogram | 1 + Lang/REXX/00DESCRIPTION | 3 + Lang/Ring/Amb | 1 + Lang/Ring/CSV-data-manipulation | 1 + Lang/Ring/Calendar---for-REAL-programmers | 1 + Lang/Ring/Create-an-HTML-table | 1 + .../Determine-if-only-one-instance-is-running | 1 + Lang/Ring/Flipping-bits-game | 1 + Lang/Ring/Function-composition | 1 + Lang/Ring/Inheritance-Multiple | 1 + Lang/Ring/Introspection | 1 + .../Keyboard-input-Flush-the-keyboard-buffer | 1 + Lang/Ring/Queue-Definition | 1 + Lang/Ring/Stack | 1 + Lang/Ring/Terminal-control-Hiding-the-cursor | 1 + Lang/Ring/Terminal-control-Preserve-screen | 1 + Lang/Rust/Fast-Fourier-transform | 1 + Lang/Scala/Active-Directory-Search-for-a-user | 1 + Lang/Scala/Brownian-tree | 1 + Lang/Scala/Checkpoint-synchronization | 1 + Lang/Scala/Chinese-remainder-theorem | 1 + Lang/Scala/Colour-pinstripe-Display | 1 + Lang/Scala/Convert-decimal-number-to-rational | 1 + Lang/Scala/Deconvolution-1D | 1 + Lang/Scala/Delegates | 1 + .../Determine-if-only-one-instance-is-running | 1 + Lang/Scala/Documentation | 1 + Lang/Scala/Doubly-linked-list-Traversal | 1 + Lang/Scala/Draw-a-cuboid | 1 + ...est-left-truncatable-prime-in-a-given-base | 1 + Lang/Scala/Horizontal-sundial-calculations | 1 + Lang/Scala/Iterated-digits-squaring | 1 + Lang/Scala/Keyboard-macros | 1 + Lang/Scala/Non-continuous-subsequences | 1 + Lang/Scala/Parametrized-SQL-statement | 1 + Lang/Scala/Permutation-test | 1 + Lang/Scala/Permutations-Rank-of-a-permutation | 1 + Lang/Scala/Pinstripe-Display | 1 + Lang/Scala/Polymorphism | 1 + Lang/Scala/Pythagorean-triples | 1 + Lang/Scala/QR-decomposition | 1 + .../Seven-sided-dice-from-five-sided-dice | 1 + Lang/Scala/Sorting-algorithms-Cocktail-sort | 1 + Lang/Scala/Sorting-algorithms-Gnome-sort | 1 + Lang/Scala/Sorting-algorithms-Radix-sort | 1 + .../Scala/Text-processing-Max-licenses-in-use | 1 + Lang/Scala/World-Cup-group-stage | 1 + Lang/Sed/Comma-quibbling | 1 + Lang/Shen/Luhn-test-of-credit-card-numbers | 1 + Lang/Swift/Averages-Mode | 1 + Lang/Swift/Catalan-numbers | 1 + Lang/Swift/Entropy | 1 + Lang/Swift/Safe-addition | 1 + Lang/TI-83-BASIC/Inverted-syntax | 1 + Lang/Transact-SQL/Repeat-a-string | 1 + Lang/VAX-Assembly/100-doors | 1 + Lang/VAX-Assembly/CRC-32 | 1 + Lang/VAX-Assembly/Delete-a-file | 1 + Lang/VAX-Assembly/Detect-division-by-zero | 1 + Lang/VAX-Assembly/Empty-program | 1 + Lang/VAX-Assembly/Empty-string | 1 + Lang/VAX-Assembly/Fibonacci-sequence | 1 + Lang/VAX-Assembly/FizzBuzz | 1 + Lang/VAX-Assembly/Hello-world-Text | 1 + .../Loops-For-with-a-specified-step | 1 + Lang/VAX-Assembly/Loops-Infinite | 1 + Lang/VAX-Assembly/Sieve-of-Eratosthenes | 1 + Lang/VBA/Aliquot-sequence-classifications | 1 + Lang/VBA/Formatted-numeric-output | 1 + Lang/VBA/Greatest-element-of-a-list | 1 + Lang/VBA/Harshad-or-Niven-series | 1 + Lang/VBScript/Draw-a-cuboid | 1 + Lang/VBScript/Draw-a-sphere | 1 + .../Sorting-algorithms-Insertion-sort | 1 + Lang/Vala/GUI-component-interaction | 1 + Lang/Vala/GUI-enabling-disabling-of-controls | 1 + Lang/Visual-Basic-.NET/Munching-squares | 1 + Task/100-doors/Astro/100-doors.astro | 4 +- Task/100-doors/C++/100-doors-4.cpp | 125 +++++++++ Task/100-doors/Elena/100-doors.elena | 4 +- Task/100-doors/Ruby/100-doors-1.rb | 50 +--- Task/100-doors/Ruby/100-doors-2.rb | 52 +++- Task/100-doors/Ruby/100-doors-3.rb | 18 +- Task/100-doors/Ruby/100-doors-4.rb | 9 +- Task/100-doors/Ruby/100-doors-5.rb | 7 + Task/100-doors/VAX-Assembly/100-doors.vax | 28 ++ Task/24-game/Elena/24-game.elena | 4 +- Task/24-game/Ring/24-game.ring | 3 - .../9-billion-names-of-god-the-integer.erl | 48 ++-- .../Astro/99-bottles-of-beer.astro | 8 +- .../C/99-bottles-of-beer-1.c | 33 ++- .../Elena/99-bottles-of-beer.elena | 4 +- .../Emacs-Lisp/99-bottles-of-beer.l | 4 + .../Forth/99-bottles-of-beer-2.fth | 65 +++-- .../Python/99-bottles-of-beer-1.py | 28 ++ .../Python/99-bottles-of-beer-2.py | 26 ++ .../REBOL/99-bottles-of-beer-1.rebol | 2 - Task/A+B/Elena/a+b-1.elena | 6 +- Task/A+B/Elena/a+b-2.elena | 6 +- Task/A+B/Swift/{a+b.swift => a+b-1.swift} | 0 Task/A+B/Swift/a+b-2.swift | 14 + Task/ABC-Problem/Astro/abc-problem.astro | 9 +- Task/ABC-Problem/Elena/abc-problem.elena | 6 +- .../Elena/aks-test-for-primes.elena | 6 +- Task/Abstract-type/REBOL/abstract-type.rebol | 2 - ...ient-and-perfect-number-classifications.bf | 4 + ...t-and-perfect-number-classifications.elena | 6 +- .../8th/accumulator-factory.8th | 25 ++ .../Astro/accumulator-factory.astro | 4 +- .../Elena/accumulator-factory.elena | 14 +- .../Perl/accumulator-factory.pl | 2 +- .../Elena/ackermann-function.elena | 10 +- .../Go/ackermann-function-3.go | 107 ++++--- .../NewLISP/ackermann-function.newlisp | 6 + .../active-directory-search-for-a-user.scala | 36 +++ ...iable-to-a-class-instance-at-runtime.elena | 6 +- ...iable-to-a-class-instance-at-runtime.rebol | 2 - .../Astro/address-of-a-variable.astro | 6 +- Task/Align-columns/REBOL/align-columns.rebol | 2 - .../00DESCRIPTION | 2 +- .../C/aliquot-sequence-classifications-1.c | 2 - .../C/aliquot-sequence-classifications-2.c | 2 - .../aliquot-sequence-classifications.factor | 54 ++++ .../aliquot-sequence-classifications.ring | 3 - .../VBA/aliquot-sequence-classifications.vba | 66 +++++ Task/Almost-prime/Maple/almost-prime.maple | 16 ++ Task/Amb/Elena/amb.elena | 37 ++- Task/Amb/REXX/amb-1.rexx | 30 +- Task/Amb/Ring/amb.ring | 32 +++ Task/Amicable-pairs/Befunge/amicable-pairs.bf | 6 + ...ble-pairs.elena => amicable-pairs-1.elena} | 0 .../Elena/amicable-pairs-2.elena | 33 +++ .../Ring/anagrams-deranged-anagrams.ring | 3 - Task/Anagrams/Elena/anagrams.elena | 16 +- Task/Anagrams/Ring/anagrams.ring | 3 - .../Phix/animate-a-pendulum.phix | 66 +++-- .../Ring/animate-a-pendulum.ring | 3 - Task/Animation/Phix/animation.phix | 56 ++-- Task/Animation/REBOL/animation.rebol | 2 - Task/Animation/Ring/animation.ring | 3 - .../Elena/anonymous-recursion.elena | 37 +-- .../Ring/anonymous-recursion.ring | 3 - .../Elena/apply-a-callback-to-an-array.elena | 4 +- .../apply-a-callback-to-an-array-1.futhark | 1 + .../apply-a-callback-to-an-array-2.futhark | 1 + .../apply-a-callback-to-an-array-3.futhark | 1 + .../REBOL/apply-a-callback-to-an-array.rebol | 2 - ...arbitrary-precision-integers--included-.go | 23 +- .../C/arena-storage-pool-7.c | 142 ++++++++++ .../Elena/arithmetic-integer.elena | 4 +- .../REBOL/arithmetic-integer.rebol | 2 - .../Elena/arithmetic-evaluation.elena | 105 +++---- .../arithmetic-geometric-mean-calculate-pi.go | 39 +++ .../8th/array-concatenation.8th | 1 + .../Elena/array-concatenation.elena | 6 +- .../Perl-6/array-concatenation.pl6 | 24 +- .../8th/associative-array-creation-1.8th | 1 + .../8th/associative-array-creation-2.8th | 1 + ...ena => associative-array-creation-1.elena} | 4 +- .../Elena/associative-array-creation-2.elena | 12 + .../Perl/associative-array-creation-4.pl | 6 +- .../Ring/associative-array-creation.ring | 3 - .../8th/associative-array-iteration-1.8th | 3 + .../8th/associative-array-iteration-2.8th | 3 + .../associative-array-iteration-6.lisp | 3 - ...na => associative-array-iteration-1.elena} | 4 +- .../Elena/associative-array-iteration-2.elena | 18 ++ .../Ring/associative-array-iteration.ring | 3 - Task/Atomic-updates/8th/atomic-updates.8th | 93 +++++++ Task/Atomic-updates/Ring/atomic-updates.ring | 3 - .../Elena/averages-arithmetic-mean.elena | 6 +- .../Perl/averages-arithmetic-mean.pl | 8 + .../REBOL/averages-arithmetic-mean.rebol | 2 - .../Ring/averages-mean-angle.ring | 3 - .../Elena/averages-median.elena | 4 +- ...{averages-median.k => averages-median-1.k} | 0 Task/Averages-Median/K/averages-median-2.k | 4 + .../Averages-Median/REXX/averages-median.rexx | 24 +- Task/Averages-Mode/Elena/averages-mode.elena | 4 +- Task/Averages-Mode/Ring/averages-mode.ring | 3 - Task/Averages-Mode/Swift/averages-mode.swift | 27 ++ .../Elena/averages-root-mean-square.elena | 4 +- .../averages-simple-moving-average.elena | 4 +- .../Elena/balanced-brackets.elena | 39 ++- Task/Benfords-law/Ring/benfords-law.ring | 3 - .../Bernoulli-numbers/Go/bernoulli-numbers.go | 40 ++- Task/Best-shuffle/Elena/best-shuffle.elena | 12 +- Task/Best-shuffle/REXX/best-shuffle.rexx | 36 +-- Task/Best-shuffle/Ring/best-shuffle-1.ring | 3 - .../ARM-Assembly/binary-digits.arm | 161 +++++++++++ Task/Binary-digits/Elena/binary-digits.elena | 4 +- .../Binary-digits/Modula-2/binary-digits.mod2 | 29 ++ .../Pascal/binary-search-1.pascal | 4 +- .../Binary-strings/Forth/binary-strings-1.fth | 20 +- Task/Binary-strings/Nim/binary-strings.nim | 2 +- Task/Binary-strings/REXX/binary-strings.rexx | 19 +- .../Phix/bitcoin-address-validation.phix | 84 ++++++ .../Phix/bitcoin-public-point-to-address.phix | 42 +++ ... => bitmap-b-zier-curves-quadratic-1.math} | 0 .../bitmap-b-zier-curves-quadratic-2.math | 2 + .../Python/bitmap-histogram.py | 42 +++ ...itmap-ppm-conversion-through-a-pipe-1.math | 13 +- .../bitmap-read-an-image-through-a-pipe.math | 2 +- Task/Bitmap/Scala/bitmap-3.scala | 61 ++-- Task/Bitwise-IO/Go/bitwise-io-1.go | 203 ++++++++++++++ Task/Bitwise-IO/Go/bitwise-io-2.go | 65 +++++ .../ARM-Assembly/bitwise-operations.arm | 158 +++++++++++ .../Box-the-compass/Ring/box-the-compass.ring | 3 - Task/Break-OO-privacy/00DESCRIPTION | 1 + Task/Brownian-tree/Perl/brownian-tree.pl | 12 +- Task/Brownian-tree/Ring/brownian-tree.ring | 4 - Task/Brownian-tree/Scala/brownian-tree.scala | 50 ++++ .../Ring/bulls-and-cows-player.ring | 3 - Task/Bulls-and-cows/Ring/bulls-and-cows.ring | 3 - Task/CRC-32/Mathematica/crc-32.math | 8 +- Task/CRC-32/VAX-Assembly/crc-32.vax | 24 ++ .../Perl/csv-data-manipulation-1.pl | 2 +- .../Ring/csv-data-manipulation.ring | 34 +++ Task/Caesar-cipher/Astro/caesar-cipher.astro | 8 +- Task/Caesar-cipher/Ring/caesar-cipher.ring | 3 - .../{caesar-cipher.zx => caesar-cipher-1.zx} | 0 .../ZX-Spectrum-Basic/caesar-cipher-2.zx | 30 ++ .../Ring/calendar---for-real-programmers.ring | 158 +++++++++++ .../calendar---for-real-programmers.sh | 6 +- Task/Calendar/C/calendar.c | 2 +- Task/Calendar/Ring/calendar.ring | 3 - .../carmichael-3-strong-pseudoprimes.ring | 3 - .../Nim/casting-out-nines.nim | 4 +- .../Ring/casting-out-nines.ring | 3 - .../Swift/catalan-numbers.swift | 12 + Task/Catamorphism/Nim/catamorphism.nim | 4 +- .../Emacs-Lisp/character-codes.l | 2 + .../check-machin-like-formulas.freebasic | 153 ++++++++++ .../Scala/checkpoint-synchronization.scala | 84 ++++++ .../Perl/chinese-remainder-theorem-3.pl | 2 +- .../Rust/chinese-remainder-theorem.rust | 1 - .../Scala/chinese-remainder-theorem.scala | 41 +++ .../Sidef/chinese-remainder-theorem.sidef | 19 +- .../Ring/cholesky-decomposition.ring | 3 - ...les-of-given-radius-through-two-points.nim | 8 +- ...es-of-given-radius-through-two-points.ring | 3 - Task/Classes/REBOL/classes.rebol | 2 - .../Perl/closest-pair-problem.pl | 2 +- .../Ring/color-of-a-screen-pixel.ring | 65 +++-- .../C/colour-bars-display-1.c | 2 - .../C/colour-bars-display-2.c | 1 - .../Befunge/colour-pinstripe-display.bf | 3 + .../C/colour-pinstripe-display.c | 2 - .../Phix/colour-pinstripe-display.phix | 41 ++- .../Ring/colour-pinstripe-display.ring | 3 - .../Scala/colour-pinstripe-display.scala | 39 +++ .../Ring/combinations-with-repetitions.ring | 3 - Task/Combinations/C/combinations-2.c | 3 +- .../Crystal/combinations-1.crystal | 3 + .../Crystal/combinations-2.crystal | 10 + Task/Combinations/Ring/combinations.ring | 3 - .../Astro/comma-quibbling.astro | 15 +- Task/Comma-quibbling/Nim/comma-quibbling.nim | 2 +- .../Comma-quibbling/Ring/comma-quibbling.ring | 3 - .../Comma-quibbling/Sed/comma-quibbling-1.sed | 6 + .../Comma-quibbling/Sed/comma-quibbling-2.sed | 4 + .../Astro/concurrent-computing.astro | 6 +- .../Astro/conditional-structures.astro | 22 +- .../Go/conditional-structures-4.go | 2 +- .../C/conjugate-transpose.c | 5 +- .../constrained-random-points-on-a-circle.nim | 13 +- ...rithmetic-construct-from-rational-number.c | 2 - ...hmetic-construct-from-rational-number-1.go | 75 +++++ ...hmetic-construct-from-rational-number-2.go | 31 +++ ...hmetic-construct-from-rational-number-3.go | 47 ++++ ...tic-g-matrix-ng,-contined-fraction-n--1.go | 84 ++++++ ...tic-g-matrix-ng,-contined-fraction-n--2.go | 36 +++ ...ed-fraction-n1,-contined-fraction-n2--1.go | 141 ++++++++++ ...ed-fraction-n1,-contined-fraction-n2--2.go | 35 +++ .../Ring/continued-fraction.ring | 3 - .../convert-decimal-number-to-rational.scala | 8 + .../Befunge/conways-game-of-life.bf | 8 + .../Java/conways-game-of-life-3.java | 92 ++++++ Task/Copy-a-string/Emacs-Lisp/copy-a-string.l | 3 + Task/Copy-a-string/REBOL/copy-a-string.rebol | 2 - .../Count-in-factors/Nim/count-in-factors.nim | 4 +- Task/Count-in-octal/Nim/count-in-octal.nim | 2 +- .../Nim/count-occurrences-of-a-substring.nim | 2 +- Task/Count-the-coins/C++/count-the-coins.cpp | 34 +++ Task/Count-the-coins/Nim/count-the-coins.nim | 2 +- .../C/create-a-file-on-magnetic-tape.c | 2 - .../Ring/create-a-file-on-magnetic-tape.ring | 3 - Task/Create-a-file/Emacs-Lisp/create-a-file.l | 3 + .../Ring/create-an-html-table.ring | 34 +++ Task/Currying/C/currying.c | 1 - Task/DNS-query/Lasso/dns-query.lasso | 1 + Task/DNS-query/Lua/dns-query-1.lua | 6 + Task/DNS-query/Lua/dns-query-2.lua | 13 + Task/DNS-query/Lua/dns-query-3.lua | 11 + .../{date-format.fth => date-format-1.fth} | 0 Task/Date-format/Forth/date-format-2.fth | 61 ++++ Task/Date-format/Forth/date-format-3.fth | 3 + Task/Date-format/REBOL/date-format.rebol | 2 - .../REBOL/date-manipulation.rebol | 2 - .../Ring/date-manipulation.ring | 3 - .../REBOL/day-of-the-week.rebol | 2 - .../Scala/deconvolution-1d.scala | 23 ++ Task/Deepcopy/C/deepcopy-1.c | 2 - Task/Deepcopy/C/deepcopy-2.c | 2 - .../define-a-primitive-data-type-1.factor | 1 + .../define-a-primitive-data-type-2.factor | 3 + .../define-a-primitive-data-type-3.factor | 6 + .../Forth/define-a-primitive-data-type-1.fth | 9 + .../Forth/define-a-primitive-data-type-2.fth | 10 + .../Forth/define-a-primitive-data-type-3.fth | 9 + .../Forth/define-a-primitive-data-type-4.fth | 22 ++ .../Forth/define-a-primitive-data-type-5.fth | 9 + .../Forth/define-a-primitive-data-type-6.fth | 10 + Task/Delegates/Phix/delegates-1.phix | 44 +++ Task/Delegates/Phix/delegates-2.phix | 7 + Task/Delegates/Scala/delegates.scala | 32 +++ Task/Delete-a-file/Emacs-Lisp/delete-a-file.l | 8 + .../VAX-Assembly/delete-a-file.vax | 18 ++ .../NewLISP/detect-division-by-zero.newlisp | 15 + .../REBOL/detect-division-by-zero.rebol | 2 - .../REXX/detect-division-by-zero.rexx | 45 +-- .../VAX-Assembly/detect-division-by-zero.vax | 15 + .../determine-if-a-string-is-numeric.rebol | 2 - ...rmine-if-only-one-instance-is-running.java | 42 ++- ...rmine-if-only-one-instance-is-running.ring | 22 ++ ...mine-if-only-one-instance-is-running.scala | 23 ++ ...ital-root-multiplicative-digital-root.phix | 39 +++ ...ital-root-multiplicative-digital-root.ring | 3 - Task/Digital-root/K/digital-root.k | 6 + ...dinesmans-multiple-dwelling-problem.ceylon | 24 ++ .../Nim/dining-philosophers.nim | 30 +- Task/Documentation/REBOL/documentation.rebol | 2 - Task/Documentation/Scala/documentation.scala | 22 ++ .../Ring/doubly-linked-list-definition.ring | 3 - .../Ring/doubly-linked-list-traversal.ring | 3 - .../Scala/doubly-linked-list-traversal.scala | 12 + Task/Dragon-curve/Befunge/dragon-curve.bf | 7 + Task/Dragon-curve/Perl-6/dragon-curve.pl6 | 36 +-- Task/Draw-a-cuboid/Befunge/draw-a-cuboid.bf | 4 + Task/Draw-a-cuboid/C/draw-a-cuboid.c | 1 - Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring | 3 - Task/Draw-a-cuboid/Scala/draw-a-cuboid.scala | 91 ++++++ Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb | 48 ++++ Task/Draw-a-sphere/VBScript/draw-a-sphere.vb | 51 ++++ .../Ceylon/dutch-national-flag-problem.ceylon | 82 ++++++ .../Forth/dutch-national-flag-problem.fth | 148 ++++++++++ .../Ring/dutch-national-flag-problem.ring | 3 - .../REBOL/dynamic-variable-names.rebol | 2 - Task/Empty-program/00DESCRIPTION | 2 - Task/Empty-program/00META.yaml | 1 + .../Beeswax/empty-program-1.beeswax | 1 + .../Beeswax/empty-program-2.beeswax | 1 + .../Beeswax/empty-program-3.beeswax | 1 + .../Beeswax/empty-program-4.beeswax | 1 + .../VAX-Assembly/empty-program.vax | 3 + .../VAX-Assembly/empty-string.vax | 10 + .../Ring/enforced-immutability.ring | 3 - Task/Entropy/Swift/entropy.swift | 14 + .../VBA/ethiopian-multiplication-3.vba | 1 + .../Nim/evaluate-binomial-coefficients.nim | 2 +- .../Common-Lisp/even-or-odd-2.lisp | 3 - Task/Even-or-odd/K/even-or-odd.k | 8 + .../evolutionary-algorithm.freebasic | 84 ++++++ .../Ring/evolutionary-algorithm.ring | 3 - .../00DESCRIPTION | 1 - Task/Exceptions/00DESCRIPTION | 1 - Task/Execute-HQ9+/Ring/execute-hq9+.ring | 3 - .../Emacs-Lisp/execute-a-system-command-1.l | 1 + .../Emacs-Lisp/execute-a-system-command-2.l | 1 + .../Agda/extend-your-language.agda | 16 ++ .../Perl/extend-your-language-1.pl | 10 +- .../Ring/extend-your-language.ring | 3 - .../Pascal/extensible-prime-generator.pascal | 36 +-- Task/Factorial/C/factorial-5.c | 2 - Task/Factorial/Common-Lisp/factorial-4.lisp | 3 - .../{factorial.mips => factorial-1.mips} | 0 Task/Factorial/MIPS-Assembly/factorial-2.mips | 42 +++ Task/Factorial/REBOL/factorial.rebol | 2 - .../Ring/factors-of-a-mersenne-number.ring | 3 - .../ARM-Assembly/factors-of-an-integer.arm | 184 ++++++++++++ .../Rust/fast-fourier-transform.rust | 61 ++++ .../SystemVerilog/fast-fourier-transform-1.v | 4 - .../fibonacci-n-step-number-sequences.bf | 8 + .../C/fibonacci-n-step-number-sequences.c | 4 +- .../Go/fibonacci-n-step-number-sequences.go | 61 ++-- .../fibonacci-n-step-number-sequences.ring | 3 - .../360-Assembly/fibonacci-sequence-1.360 | 51 ++++ .../360-Assembly/fibonacci-sequence-2.360 | 48 ++++ .../360-Assembly/fibonacci-sequence.360 | 49 ---- .../Common-Lisp/fibonacci-sequence-7.lisp | 3 - .../Fortran/fibonacci-sequence-1.f | 44 ++- .../Fortran/fibonacci-sequence-2.f | 33 ++- .../Fortran/fibonacci-sequence-3.f | 23 +- .../Fortran/fibonacci-sequence-4.f | 26 +- .../Fortran/fibonacci-sequence-5.f | 25 +- .../Fortran/fibonacci-sequence-6.f | 7 + .../PARI-GP/fibonacci-sequence-2.pari | 2 +- .../VAX-Assembly/fibonacci-sequence.vax | 34 +++ .../fibonacci-sequence-3.visual | 28 ++ Task/Fibonacci-word/Ring/fibonacci-word.ring | 3 - .../Ring/find-common-directory-path.ring | 2 - ...eft-truncatable-prime-in-a-given-base.java | 21 +- ...ft-truncatable-prime-in-a-given-base.scala | 48 ++++ .../Befunge/find-limit-of-recursion.bf | 1 + .../Go/first-class-environments.go | 59 ++++ .../REBOL/first-class-functions.rebol | 2 - Task/Five-weekends/Ruby/five-weekends.rb | 26 +- Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp | 3 - Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l | 10 + .../{fizzbuzz.factor => fizzbuzz-1.factor} | 0 Task/FizzBuzz/Factor/fizzbuzz-2.factor | 18 ++ Task/FizzBuzz/Haskell/fizzbuzz-1.hs | 16 +- Task/FizzBuzz/Haskell/fizzbuzz-2.hs | 22 +- Task/FizzBuzz/REBOL/fizzbuzz-1.rebol | 2 - Task/FizzBuzz/VAX-Assembly/fizzbuzz.vax | 43 +++ .../Crystal/flatten-a-list-1.crystal | 1 + .../Crystal/flatten-a-list-2.crystal | 1 + .../Ring/flipping-bits-game.ring | 109 ++++++++ .../REBOL/flow-control-structures.rebol | 2 - .../Haskell/floyds-triangle-3.hs | 6 +- Task/Floyds-triangle/Nim/floyds-triangle.nim | 2 +- Task/Forest-fire/Ring/forest-fire.ring | 4 - .../REBOL/formatted-numeric-output.rebol | 2 - .../VBA/formatted-numeric-output.vba | 24 ++ .../Perl/forward-difference.pl | 7 +- .../Ring/forward-difference.ring | 3 - Task/Fractal-tree/Ceylon/fractal-tree.ceylon | 45 +++ Task/Fractran/Befunge/fractran.bf | 5 + .../REBOL/function-composition-1.rebol | 2 - .../Ring/function-composition.ring | 13 + .../ARM-Assembly/function-definition.arm | 134 +++++++++ .../C/gui-maximum-window-dimensions.c | 2 - .../Vala/gui-component-interaction.vala | 80 ++++++ .../gui-enabling-disabling-of-controls.vala | 110 ++++++++ .../Go/galton-box-animation.go | 127 +++++++++ .../C/generate-chess960-starting-position.c | 2 - Task/Generic-swap/REBOL/generic-swap.rebol | 2 - Task/Gray-code/Ring/gray-code.ring | 3 - .../REBOL/greatest-element-of-a-list.rebol | 2 - .../VBA/greatest-element-of-a-list.vba | 16 ++ .../Nim/greatest-subsequential-sum.nim | 2 +- .../Ring/greatest-subsequential-sum.ring | 3 - .../Ring/greyscale-bars-display.ring | 3 - .../Befunge/guess-the-number-with-feedback.bf | 4 + .../guess-the-number-with-feedback.l | 13 + .../ABAP/guess-the-number.abap | 25 ++ .../Dart/guess-the-number.dart | 17 +- .../Emacs-Lisp/guess-the-number.l | 6 + .../Kotlin/guess-the-number.kotlin | 16 +- Task/HTTP/BaCon/http.bacon | 11 +- Task/HTTP/Phix/http.phix | 9 + .../Lua/https-authenticated.lua | 7 + .../Phix/https-authenticated.phix | 9 + .../Phix/https-client-authenticated.phix | 12 + Task/HTTPS/BaCon/https.bacon | 69 +++++ Task/HTTPS/Lua/https.lua | 5 + Task/HTTPS/Phix/https.phix | 9 + .../Crystal/hailstone-sequence.crystal | 17 ++ .../Java/hamming-numbers-2.java | 1 - Task/Happy-numbers/Sidef/happy-numbers.sidef | 10 +- .../K/harshad-or-niven-series.k | 6 + .../VBA/harshad-or-niven-series.vba | 25 ++ .../Ring/hash-from-two-arrays.ring | 3 - .../Fortran/hello-world-graphical-1.f | 2 +- .../Common-Lisp/hello-world-text-3.lisp | 3 - Task/Hello-world-Text/K/hello-world-text-1.k | 1 + Task/Hello-world-Text/K/hello-world-text-2.k | 1 + Task/Hello-world-Text/K/hello-world-text-3.k | 2 + Task/Hello-world-Text/K/hello-world-text-4.k | 1 + .../Lambdatalk/hello-world-text.lambdatalk | 3 + .../VAX-Assembly/hello-world-text.vax | 6 + Task/Here-document/C/here-document.c | 2 - .../Heronian-triangles/C/heronian-triangles.c | 2 - .../Ring/heronian-triangles.ring | 3 - .../REBOL/higher-order-functions.rebol | 2 - .../Ring/higher-order-functions.ring | 3 - .../Phix/history-variables-1.phix | 12 + .../Phix/history-variables-2.phix | 19 ++ .../Phix/history-variables-3.phix | 7 + ...fstadter-conway-$10,000-sequence.freebasic | 32 +++ .../hofstadter-figure-figure-sequences.ring | 3 - .../Java/horizontal-sundial-calculations.java | 3 +- .../Ring/horizontal-sundial-calculations.ring | 3 - .../horizontal-sundial-calculations.scala | 27 ++ Task/Hostname/K/hostname.k | 1 + .../Maple/hough-transform.maple | 43 +++ Task/Huffman-coding/Phix/huffman-coding.phix | 98 +++++++ .../Maple/i-before-e-except-after-c.maple | 23 ++ .../Ring/i-before-e-except-after-c.ring | 3 - Task/IBAN/Befunge/iban.bf | 8 + Task/IBAN/PowerShell/iban-1.psh | 82 ++---- Task/IBAN/PowerShell/iban-2.psh | 64 ++++- Task/IBAN/PowerShell/iban-3.psh | 10 + Task/IBAN/Ring/iban.ring | 3 - .../Burlesque/identity-matrix-3.blq | 1 + .../Factor/identity-matrix.factor | 10 + .../Haskell/identity-matrix-4.hs | 3 - .../Haskell/identity-matrix-5.hs | 7 + .../Maple/image-convolution.maple | 3 + .../FreeBASIC/image-noise.freebasic | 36 +++ .../REBOL/increment-a-numerical-string.rebol | 2 - .../REXX/increment-a-numerical-string-2.rexx | 1 - Task/Infinity/Perl/infinity-6.pl | 2 +- .../Ring/inheritance-multiple.ring | 34 +++ .../REBOL/inheritance-single.rebol | 2 - Task/Input-loop/REBOL/input-loop.rebol | 2 - .../ARM-Assembly/integer-comparison.arm | 181 ++++++++++++ .../REBOL/integer-comparison.rebol | 2 - .../Groovy/integer-sequence.groovy | 8 + Task/Introspection/Perl/introspection-4.pl | 10 +- Task/Introspection/Perl/introspection-5.pl | 21 +- Task/Introspection/Perl/introspection-6.pl | 27 +- Task/Introspection/Perl/introspection-7.pl | 11 +- Task/Introspection/Ring/introspection.ring | 31 +++ .../Factor/inverted-syntax-2.factor | 7 +- .../Factor/inverted-syntax-3.factor | 1 + .../Factor/inverted-syntax-4.factor | 3 + .../Factor/inverted-syntax-5.factor | 4 + Task/Inverted-syntax/Go/inverted-syntax.go | 30 ++ .../TI-83-BASIC/inverted-syntax.ti-83 | 1 + .../Befunge/iterated-digits-squaring.bf | 5 + .../Scala/iterated-digits-squaring.scala | 43 +++ Task/JSON/Crystal/json-1.crystal | 14 + Task/JSON/Crystal/json-2.crystal | 2 + Task/JSON/Haskell/json-3.hs | 17 ++ Task/Jensens-Device/Go/jensens-device.go | 17 ++ Task/Jensens-Device/Ring/jensens-device.ring | 3 - .../Emacs-Lisp/josephus-problem.l | 4 + Task/Jump-anywhere/PL-I/jump-anywhere.pli | 1 + ...board-input-flush-the-keyboard-buffer.ring | 3 + .../Phix/keyboard-macros-1.phix | 27 ++ .../Phix/keyboard-macros-2.phix | 144 ++++++++++ .../REBOL/keyboard-macros.rebol | 2 - .../Scala/keyboard-macros.scala | 24 ++ Task/Knapsack-problem-0-1/00DESCRIPTION | 1 + .../Maple/knapsack-problem-0-1.maple | 29 ++ .../Ring/knapsack-problem-0-1.ring | 3 - Task/Knuth-shuffle/Ring/knuth-shuffle.ring | 3 - .../Java/knuths-algorithm-s-1.java | 34 ++- .../Java/knuths-algorithm-s-2.java | 42 ++- ...m-s.kotlin => knuths-algorithm-s-1.kotlin} | 15 +- .../Kotlin/knuths-algorithm-s-2.kotlin | 27 ++ .../Phix/knuths-algorithm-s-1.phix | 44 +++ .../Phix/knuths-algorithm-s-2.phix | 9 + .../Phix/lu-decomposition.phix | 77 +++++ ...zw-compression.js => lzw-compression-1.js} | 0 .../JavaScript/lzw-compression-2.js | 110 ++++++++ .../LZW-compression/Ring/lzw-compression.ring | 3 - Task/Langtons-ant/Befunge/langtons-ant.bf | 5 + .../Ring/last-letter-first-letter.ring | 3 - Task/Leap-year/Dart/leap-year.dart | 5 + .../Befunge/least-common-multiple.bf | 4 + .../Ring/levenshtein-distance.ring | 3 - .../Scala/levenshtein-distance-1.scala | 24 ++ .../Scala/levenshtein-distance-2.scala | 34 +++ .../Scala/levenshtein-distance.scala | 21 -- .../360-Assembly/literals-floating-point.360 | 15 + .../Phix/longest-common-subsequence-1.phix | 4 +- .../longest-increasing-subsequence-1.cs | 48 ++++ .../longest-increasing-subsequence-2.cs | 22 ++ .../Ring/longest-increasing-subsequence.ring | 3 - .../longest-increasing-subsequence-1.scala | 7 +- .../Ring/longest-string-challenge.ring | 3 - .../C++/look-and-say-sequence.cpp | 6 +- Task/Loops-Break/REBOL/loops-break.rebol | 2 - .../Loops-Continue/REBOL/loops-continue.rebol | 2 - .../ALGOL-60/loops-do-while.alg | 10 + .../Loops-Do-while/Fortran/loops-do-while-3.f | 7 + .../Loops-Do-while/Fortran/loops-do-while-4.f | 7 + .../Julia/loops-do-while-1.julia | 2 +- .../Loops-Do-while/REBOL/loops-do-while.rebol | 2 - .../ALGOL-60/loops-downward-for.alg | 5 + .../loops-for-with-a-specified-step.vax | 8 + Task/Loops-For/ARM-Assembly/loops-for.arm | 66 +++++ Task/Loops-Foreach/REBOL/loops-foreach.rebol | 2 - .../ALGOL-60/loops-infinite.alg | 5 + Task/Loops-Infinite/C/loops-infinite-5.c | 1 - .../VAX-Assembly/loops-infinite.vax | 10 + .../REBOL/loops-n-plus-one-half.rebol | 2 - Task/Loops-Nested/REBOL/loops-nested.rebol | 2 - Task/Loops-While/K/loops-while.k | 1 + Task/Loops-While/REBOL/loops-while.rebol | 2 - Task/Ludic-numbers/Ring/ludic-numbers.ring | 3 - .../luhn-test-of-credit-card-numbers.ceylon | 44 +-- .../luhn-test-of-credit-card-numbers.factor | 2 +- .../luhn-test-of-credit-card-numbers.shen | 20 ++ Task/MD4/Mathematica/md4.math | 1 + Task/MD4/Phix/md4.phix | 77 +++++ Task/MD5/Mathematica/md5-1.math | 8 +- Task/MD5/Mathematica/md5-2.math | 2 +- .../Phix/main-step-of-gost-28147-89.phix | 40 +++ .../Mathematica/mandelbrot-set-3.math | 1 + Task/Map-range/Ring/map-range.ring | 3 - .../Ol/matrix-multiplication.ol | 8 + .../Astro/maximum-triangle-path-sum.astro | 54 ++-- .../Ring/maximum-triangle-path-sum.ring | 3 - Task/Menu/REBOL/menu.rebol | 2 - .../Forth/metaprogramming-1.fth | 35 +++ .../Forth/metaprogramming-2.fth | 10 + Task/Metronome/Phix/metronome.phix | 35 +++ .../Phix/minesweeper-game.phix | 172 ++++++++++++ Task/Modular-inverse/Ada/modular-inverse.ada | 3 +- .../FreeBASIC/modular-inverse.freebasic | 75 +++++ Task/Morse-code/Forth/morse-code.fth | 3 +- .../Factor/mouse-position.factor | 2 +- .../Mouse-position/Python/mouse-position-2.py | 2 +- .../Ring/move-to-front-algorithm.ring | 3 - .../JavaScript/multiplication-tables-4.js | 18 +- .../REBOL/multiplication-tables.rebol | 2 - Task/Multisplit/Ring/multisplit.ring | 3 - .../Befunge/munching-squares.bf | 3 + .../Ring/munching-squares.ring | 3 - .../Scala/munching-squares.scala | 31 +-- .../Sidef/munching-squares.sidef | 2 +- .../Visual-Basic-.NET/munching-squares.visual | 22 ++ .../REBOL/mutual-recursion.rebol | 2 - .../Befunge/n-queens-problem.bf | 4 + ...ueens-problem.go => n-queens-problem-1.go} | 0 .../N-queens-problem/Go/n-queens-problem-2.go | 136 +++++++++ .../Befunge/narcissistic-decimal-number.bf | 4 + Task/Nautical-bell/C/nautical-bell.c | 2 - .../Mathematica/nautical-bell.math | 6 +- Task/Nautical-bell/Phix/nautical-bell.phix | 37 +++ Task/Nautical-bell/Ring/nautical-bell.ring | 3 - .../Ring/non-continuous-subsequences.ring | 3 - .../Scala/non-continuous-subsequences.scala | 13 + .../Ring/non-decimal-radices-convert.ring | 3 - .../Ring/non-decimal-radices-output.ring | 3 - Task/Nth-root/360-Assembly/nth-root.360 | 59 ++++ Task/Null-object/NewLISP/null-object.newlisp | 4 + Task/Number-names/Phix/number-names.phix | 3 +- .../Astro/number-reversal-game.astro | 13 +- .../Crystal/number-reversal-game.crystal | 21 ++ .../Ring/number-reversal-game.ring | 3 - .../Ring/numerical-integration.ring | 3 - .../Factor/object-serialization.factor | 45 +++ .../Ring/odd-word-problem.ring | 3 - .../one-dimensional-cellular-automata.ceylon | 89 +++--- .../one-dimensional-cellular-automata.ring | 3 - Task/OpenGL/Ring/opengl.ring | 3 - ...rameters.pl6 => optional-parameters-1.pl6} | 0 .../Perl-6/optional-parameters-2.pl6 | 4 + .../C++/order-disjoint-list-items.cpp | 4 - .../Maple/order-two-numerical-lists.maple | 10 + .../C++/ordered-partitions.cpp | 4 - Task/Ordered-words/BaCon/ordered-words.bacon | 10 +- .../360-Assembly/palindrome-detection.360 | 32 +++ .../Common-Lisp/palindrome-detection-2.lisp | 3 - .../Crystal/palindrome-detection-1.crystal | 3 + .../Crystal/palindrome-detection-2.crystal | 11 + .../Crystal/palindrome-detection-3.crystal | 5 + .../Crystal/palindrome-detection-4.crystal | 2 + .../Nim/palindrome-detection.nim | 4 +- .../REBOL/palindrome-detection.rebol | 2 - .../Befunge/pangram-checker.bf | 4 + Task/Pangram-checker/Nim/pangram-checker.nim | 2 +- .../Haskell/parallel-calculations-1.hs | 61 ++-- .../Java/parallel-calculations.java | 61 ++-- .../Perl-6/parallel-calculations.pl6 | 41 ++- .../Phix/parametrized-sql-statement.phix | 27 ++ .../Scala/parametrized-sql-statement.scala | 57 ++++ .../parsing-rpn-calculator-algorithm-1.n | 4 - .../C++/parsing-rpn-to-infix-conversion.cpp | 1 - .../C/parsing-rpn-to-infix-conversion.c | 2 - .../Java/parsing-rpn-to-infix-conversion.java | 2 + .../Phix/pascals-triangle-puzzle.phix | 73 +++++ .../PicoLisp/pascals-triangle-puzzle.l | 3 +- .../REXX/pascals-triangle-puzzle.rexx | 52 ++-- ...percentage-difference-between-images.rebol | 2 - .../Scala/permutation-test.scala | 23 ++ .../permutations-rank-of-a-permutation.ring | 3 - ...permutations-rank-of-a-permutation-1.scala | 23 ++ ...permutations-rank-of-a-permutation-2.scala | 12 + .../C/permutations-by-swapping.c | 2 - Task/Permutations/C/permutations-1.c | 54 ++++ Task/Permutations/C/permutations-2.c | 25 ++ .../C/{permutations.c => permutations-3.c} | 0 Task/Permutations/C/permutations-4.c | 100 +++++++ .../Ring/pernicious-numbers.ring | 3 - .../Maple/phrase-reversals.maple | 11 + Task/Pi/BASIC/pi-1.basic | 59 ++++ Task/Pi/BASIC/pi-2.basic | 51 ++++ Task/Pi/FreeBASIC/pi.freebasic | 54 ++++ Task/Pi/Nim/pi.nim | 2 +- .../C/pick-random-element.c | 2 - .../Crystal/pick-random-element.crystal | 1 + .../Ring/pig-the-dice-game.ring | 3 - .../Befunge/pinstripe-display.bf | 3 + Task/Pinstripe-Display/C/pinstripe-display.c | 1 - .../Ring/pinstripe-display.ring | 3 - .../Scala/pinstripe-display.scala | 37 +++ .../Playing-cards/Factor/playing-cards.factor | 2 +- .../Maple/plot-coordinate-pairs.maple | 3 + .../Ring/plot-coordinate-pairs.ring | 3 - Task/Polymorphism/Scala/polymorphism.scala | 36 +++ ...sion.math => polynomial-regression-1.math} | 0 .../Mathematica/polynomial-regression-2.math | 1 + Task/Power-set/Ring/power-set.ring | 3 - .../C/pragmatic-directives.c | 2 - .../primality-by-trial-division-2.lisp | 3 - .../Scala/primality-by-trial-division-1.scala | 4 +- .../Scala/primality-by-trial-division-2.scala | 22 +- .../Scala/primality-by-trial-division-3.scala | 24 +- .../Ring/probabilistic-choice.ring | 3 - .../Nim/pythagorean-triples.nim | 2 +- .../Scala/pythagorean-triples.scala | 25 ++ .../Java/qr-decomposition.java | 25 ++ .../QR-decomposition/SAS/qr-decomposition.sas | 1 - .../Scala/qr-decomposition.scala | 22 ++ .../Factor/quaternion-type.factor | 27 ++ .../Haskell/quaternion-type-1.hs | 32 ++- .../Haskell/quaternion-type-2.hs | 47 +++- .../Haskell/quaternion-type-3.hs | 55 +--- .../Quaternion-type/REXX/quaternion-type.rexx | 80 +++--- .../Scala/quaternion-type-1.scala | 37 ++- .../REBOL/queue-definition.rebol | 2 - .../Ring/queue-definition.ring | 19 ++ Task/Queue-Usage/Astro/queue-usage.astro | 16 +- Task/Queue-Usage/Factor/queue-usage-1.factor | 13 + Task/Queue-Usage/Factor/queue-usage-2.factor | 6 + Task/Queue-Usage/Maple/queue-usage.maple | 14 + .../Nim/quickselect-algorithm.nim | 2 +- Task/Quine/Nim/quine-2.nim | 4 +- Task/Quine/Nim/quine-3.nim | 4 +- Task/RIPEMD-160/Mathematica/ripemd-160.math | 1 + Task/RIPEMD-160/Phix/ripemd-160-1.phix | 4 + Task/RIPEMD-160/Phix/ripemd-160-2.phix | 108 ++++++++ .../random-number-generator--device--1.phix | 55 ++++ .../random-number-generator--device--2.phix | 11 + .../Range-expansion/Ring/range-expansion.ring | 3 - .../Maple/range-extraction.maple | 12 + .../Ring/range-extraction.ring | 3 - Task/Ranking-methods/C/ranking-methods.c | 2 - Task/Rate-counter/Ring/rate-counter.ring | 3 - .../Ada/read-a-file-line-by-line.ada | 3 +- .../Astro/read-a-file-line-by-line.astro | 5 +- .../C/read-a-file-line-by-line-1.c | 41 +-- .../C/read-a-file-line-by-line-2.c | 86 ++---- .../C/read-a-file-line-by-line-3.c | 75 +++++ .../read-a-specific-line-from-a-file.maple | 10 + .../Ring/reduced-row-echelon-form.ring | 3 - .../REBOL/regular-expressions.rebol | 2 - .../Ring/regular-expressions.ring | 3 - .../C-sharp/remove-lines-from-a-file.cs | 1 + Task/Rep-string/Factor/rep-string.factor | 15 + Task/Rep-string/Ring/rep-string.ring | 4 - .../Crystal/repeat-a-string-1.crystal | 1 + .../Crystal/repeat-a-string-2.crystal | 1 + .../Transact-SQL/repeat-a-string.sql | 1 + .../FreeBASIC/resistor-mesh.freebasic | 81 ++++++ .../respond-to-an-unknown-method-call.phix | 30 ++ Task/Reverse-a-string/K/reverse-a-string.k | 5 + .../Maple/reverse-words-in-a-string.maple | 7 + .../Ring/rock-paper-scissors.ring | 3 - .../Ceylon/roman-numerals-encode.ceylon | 52 ++-- .../Perl-6/roots-of-a-function.pl6 | 2 +- .../Scala/roots-of-a-function-1.scala | 25 ++ ...tion.scala => roots-of-a-function-2.scala} | 0 Task/Rot-13/REBOL/rot-13.rebol | 2 - .../C++/run-length-encoding-1.cpp | 162 +++++++++++ ...encoding.cpp => run-length-encoding-2.cpp} | 0 .../Ring/run-length-encoding.ring | 3 - Task/S-Expressions/Haskell/s-expressions.hs | 10 +- Task/SHA-1/Mathematica/sha-1.math | 4 +- Task/SHA-1/Phix/sha-1.phix | 87 ++++++ Task/SHA-1/Ring/sha-1.ring | 3 - Task/SHA-256/Factor/sha-256.factor | 3 + Task/SHA-256/Mathematica/sha-256.math | 2 +- Task/SHA-256/Phix/sha-256-1.phix | 19 +- Task/SHA-256/Phix/sha-256-2.phix | 3 +- Task/SHA-256/Ring/sha-256.ring | 3 - Task/SOAP/C/soap-1.c | 2 - Task/Safe-addition/Swift/safe-addition.swift | 4 + .../C/scope-function-names-and-labels.c | 1 - .../Ring/scope-function-names-and-labels.ring | 3 - Task/Search-a-list/REBOL/search-a-list.rebol | 2 - .../Ring/self-describing-numbers.ring | 3 - Task/Semordnilap/Ring/semordnilap.ring | 3 - Task/Send-email/C/send-email.c | 2 - .../Nim/sequence-of-non-squares.nim | 8 +- .../Ring/set-consolidation.ring | 3 - .../Java/set-of-real-numbers.java | 113 ++++++++ .../REXX/set-of-real-numbers-1.rexx | 86 +++--- .../REXX/set-of-real-numbers-2.rexx | 110 ++++---- Task/Set/Ring/set.ring | 3 - ...seven-sided-dice-from-five-sided-dice.ring | 3 - ...even-sided-dice-from-five-sided-dice.scala | 17 ++ .../seven-sided-dice-from-five-sided-dice.v | 3 - .../Maple/short-circuit-evaluation.maple | 16 ++ .../Ring/short-circuit-evaluation.ring | 3 - ...iangle.math => sierpinski-triangle-1.math} | 0 .../Mathematica/sierpinski-triangle-2.math | 1 + .../Ring/sierpinski-triangle.ring | 3 - .../VAX-Assembly/sieve-of-eratosthenes.vax | 29 ++ .../REBOL/simple-windowed-application.rebol | 2 - .../C/simulate-input-mouse.c | 2 - .../Ring/simulate-input-mouse.ring | 3 - .../singly-linked-list-element-insertion.pl6 | 16 +- Task/Sleep/REBOL/sleep.rebol | 2 - .../Go/solve-a-hidato-puzzle.go | 118 ++++++++ .../Elixir/solve-a-hopido-puzzle.elixir | 13 + .../Go/solve-a-hopido-puzzle-1.go | 123 ++++++++ .../Go/solve-a-hopido-puzzle-2.go | 98 +++++++ .../Elixir/solve-a-numbrix-puzzle.elixir | 29 ++ .../Go/solve-a-numbrix-puzzle-1.go | 119 ++++++++ .../Go/solve-a-numbrix-puzzle-2.go | 90 ++++++ .../Perl/solve-a-numbrix-puzzle.pl | 40 +++ .../SystemVerilog/solve-a-numbrix-puzzle.v | 5 - .../Crystal/sort-an-integer-array.crystal | 10 + ...-array.fth => sort-an-integer-array-1.fth} | 0 .../Forth/sort-an-integer-array-2.fth | 41 +++ .../Forth/sort-an-integer-array-3.fth | 2 + .../REXX/sort-an-integer-array-1.rexx | 50 ++-- .../REXX/sort-an-integer-array-2.rexx | 18 +- .../Maple/sort-disjoint-sublist.maple | 10 + .../Ring/sorting-algorithms-bogosort.ring | 3 - .../sorting-algorithms-bubble-sort-2.basic | 24 +- .../sorting-algorithms-bubble-sort-3.basic | 14 + .../sorting-algorithms-cocktail-sort.scala | 26 ++ .../Scala/sorting-algorithms-gnome-sort.scala | 13 + .../Ring/sorting-algorithms-heapsort.ring | 3 - .../sorting-algorithms-insertion-sort.vb | 36 +++ .../sorting-algorithms-merge-sort-1.astro | 16 +- .../sorting-algorithms-pancake-sort.maple | 30 ++ .../sorting-algorithms-permutation-sort.ring | 3 - .../Ring/sorting-algorithms-quicksort.ring | 3 - .../Scala/sorting-algorithms-radix-sort.scala | 26 ++ .../sorting-algorithms-sleep-sort-3.js | 13 + .../Ring/sorting-algorithms-strand-sort.ring | 3 - Task/Soundex/Ring/soundex.ring | 3 - .../C/sparkline-in-unicode.c | 2 - .../AppleScript/spiral-matrix.applescript | 262 +++++++++++++----- Task/Spiral-matrix/Haskell/spiral-matrix-4.hs | 32 ++- .../JavaScript/spiral-matrix-4.js | 169 +++++++---- Task/Spiral-matrix/Ring/spiral-matrix.ring | 93 ++++--- Task/Stack/REBOL/stack.rebol | 2 - Task/Stack/Ring/stack.ring | 17 ++ .../REBOL/stair-climbing-puzzle.rebol | 2 - .../C/start-from-a-main-routine.c | 1 - Task/Statistics-Basic/R/statistics-basic.r | 2 - .../Ring/statistics-basic.ring | 3 - .../Perl/stem-and-leaf-plot-1.pl | 24 +- .../Perl/stem-and-leaf-plot-2.pl | 51 +++- .../Perl/stem-and-leaf-plot-3.pl | 12 + .../Ring/stem-and-leaf-plot.ring | 3 - .../Factor/stern-brocot-sequence.factor | 31 +++ .../Ring/stern-brocot-sequence.ring | 3 - Task/String-append/Forth/string-append-1.fth | 2 +- .../ARM-Assembly/string-comparison.arm | 179 ++++++++++++ .../Astro/string-comparison.astro | 2 +- .../K/string-concatenation.k | 3 + .../C++/string-interpolation--included-.cpp | 51 +++- Task/String-length/K/string-length.k | 4 + Task/String-prepend/K/string-prepend.k | 4 + .../PHP/strip-block-comments.php | 23 ++ .../strip-comments-from-a-string.factor | 3 + .../Forth/strip-comments-from-a-string-1.fth | 24 ++ .../Forth/strip-comments-from-a-string-2.fth | 2 + .../strip-comments-from-a-string-3.js | 62 +++++ ...and-extended-characters-from-a-string.phix | 20 ++ ...tespace-from-a-string-top-and-tail.crystal | 10 + ...hitespace-from-a-string-top-and-tail-1.fth | 15 +- ...hitespace-from-a-string-top-and-tail-2.fth | 2 +- .../Factor/substring-top-and-tail.factor | 4 +- .../K/substring-top-and-tail-1.k | 8 + .../K/substring-top-and-tail-2.k | 8 + Task/Substring/REBOL/substring.rebol | 2 - Task/Sudoku/Befunge/sudoku.bf | 8 + Task/Sudoku/SystemVerilog/sudoku.v | 4 - .../sum-and-product-of-an-array-1.crystal | 3 + .../sum-and-product-of-an-array-2.crystal | 9 + .../sum-and-product-of-an-array-3.crystal | 5 + .../sum-and-product-of-an-array-4.crystal | 2 + .../REBOL/sum-and-product-of-an-array.rebol | 2 - .../Crystal/sum-multiples-of-3-and-5.crystal | 8 + .../Crystal/sum-of-squares.crystal | 6 + .../Phix/table-creation-postal-addresses.phix | 17 ++ .../Ring/table-creation-postal-addresses.ring | 3 - .../take-notes-on-the-command-line.rebol | 2 - .../PHP/temperature-conversion.php | 4 +- .../terminal-control-coloured-text-1.fth | 20 ++ .../terminal-control-coloured-text-2.fth | 3 + .../Ring/terminal-control-coloured-text.ring | 3 - .../C/terminal-control-cursor-movement.c | 1 - .../terminal-control-cursor-movement-1.fth | 24 ++ .../terminal-control-cursor-movement-2.fth | 8 + .../terminal-control-cursor-positioning.ring | 3 - ...control-display-an-extended-character.ring | 3 - .../C/terminal-control-hiding-the-cursor.c | 5 +- .../terminal-control-hiding-the-cursor.ring | 9 + .../Go/terminal-control-preserve-screen.go | 20 ++ .../terminal-control-preserve-screen.java | 13 + .../terminal-control-preserve-screen-1.phix | 6 + .../terminal-control-preserve-screen-2.phix | 8 + .../terminal-control-preserve-screen.ring | 10 + ...minal-control-ringing-the-terminal-bell.bc | 1 + ...inal-control-ringing-the-terminal-bell.cpp | 6 + .../C/terminal-control-unicode-output.c | 3 - .../terminal-control-unicode-output-1.phix | 57 ++++ .../terminal-control-unicode-output-2.phix | 10 + .../text-processing-max-licenses-in-use.pl6 | 5 +- ...ext-processing-max-licenses-in-use-1.scala | 29 ++ ...ext-processing-max-licenses-in-use-2.scala | 25 ++ ...ext-processing-max-licenses-in-use-3.scala | 47 ++++ ...ext-processing-max-licenses-in-use-4.scala | 26 ++ .../text-processing-max-licenses-in-use.sidef | 26 +- Task/Textonyms/Perl/textonyms.pl | 22 +- .../C/the-twelve-days-of-christmas.c | 2 - .../Ring/the-twelve-days-of-christmas.ring | 3 - .../Mathematica/tokenize-a-string.math | 2 +- .../Perl/top-rank-per-group.pl | 5 +- .../Ring/top-rank-per-group.ring | 3 - Task/Topic-variable/Perl/topic-variable-1.pl | 3 +- Task/Topic-variable/Perl/topic-variable-2.pl | 21 +- Task/Topswops/C++/topswops.cpp | 4 - .../Java/total-circles-area.java | 2 +- .../Groovy/towers-of-hanoi-1.groovy | 2 +- .../REBOL/towers-of-hanoi.rebol | 2 - .../Trabb-Pardo-Knuth-algorithm/00DESCRIPTION | 2 +- .../C/trabb-pardo-knuth-algorithm.c | 3 - .../Haskell/trabb-pardo-knuth-algorithm.hs | 18 +- .../Perl/trabb-pardo-knuth-algorithm.pl | 23 +- .../REXX/trabb-pardo-knuth-algorithm.rexx | 2 +- .../Ring/trabb-pardo-knuth-algorithm.ring | 3 - .../REBOL/trigonometric-functions.rebol | 2 - .../REXX/trigonometric-functions.rexx | 81 ++++++ .../Ring/truncatable-primes.ring | 3 - .../Ring/ulam-spiral--for-primes-.ring | 3 - .../Sidef/ulam-spiral--for-primes-.sidef | 21 +- .../Ring/undefined-values.ring | 3 - .../C/unicode-variable-names.c | 2 - .../Perl-6/unicode-variable-names-2.pl6 | 2 + .../Ring/unicode-variable-names.ring | 3 - ...-another-language-to-call-a-function.cobol | 33 +++ .../REBOL/user-input-graphical.rebol | 2 - .../ARM-Assembly/user-input-text.arm | 149 ++++++++++ .../REBOL/user-input-text.rebol | 2 - Task/Vampire-number/C++/vampire-number.cpp | 12 +- Task/Vampire-number/Ring/vampire-number.ring | 3 - Task/Variable-size-Get/00DESCRIPTION | 3 +- .../Perl/variable-size-get.pl | 6 +- .../Ring/variadic-function.ring | 3 - .../Maple/vector-products.maple | 12 + .../Vector-products/Ring/vector-products.ring | 3 - .../verify-distribution-uniformity-naive.ring | 3 - .../Go/video-display-modes.go | 31 +++ .../Phix/video-display-modes.phix | 10 + Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl | 6 +- .../Vigen-re-cipher/Ring/vigen-re-cipher.ring | 3 - .../Voronoi-diagram/Ring/voronoi-diagram.ring | 3 - .../Sidef/voronoi-diagram.sidef | 17 +- .../walk-a-directory-non-recursively-1.pl | 5 +- .../Haskell/walk-a-directory-recursively-2.hs | 93 ++----- .../Haskell/walk-a-directory-recursively-3.hs | 73 +++++ Task/Web-scraping/REBOL/web-scraping.rebol | 2 - Task/Word-wrap/REXX/word-wrap-1.rexx | 4 +- Task/Word-wrap/REXX/word-wrap-2.rexx | 50 ++-- Task/Word-wrap/Ring/word-wrap.ring | 3 - .../Scala/world-cup-group-stage.scala | 39 +++ .../write-float-arrays-to-a-text-file.ring | 3 - .../C/write-to-windows-event-log.c | 2 - Task/XML-Input/REBOL/xml-input.rebol | 2 - Task/XML-XPath/C/xml-xpath.c | 2 - Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro | 54 ++++ Task/Zebra-puzzle/Python/zebra-puzzle-4.py | 61 ++++ .../zeckendorf-number-representation.ring | 3 - .../Bc/zero-to-the-zero-power.bc | 1 + .../Nial/zero-to-the-zero-power.nial | 8 + .../C++/zhang-suen-thinning-algorithm.cpp | 241 ++++++++++++++++ .../C/zhang-suen-thinning-algorithm.c | 2 - Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring | 120 ++++---- 1170 files changed, 15042 insertions(+), 3047 deletions(-) create mode 120000 Lang/360-Assembly/Literals-Floating-point create mode 120000 Lang/360-Assembly/Nth-root create mode 120000 Lang/360-Assembly/Palindrome-detection create mode 120000 Lang/8th/Accumulator-factory create mode 120000 Lang/8th/Array-concatenation create mode 120000 Lang/8th/Associative-array-Creation create mode 120000 Lang/8th/Associative-array-Iteration create mode 120000 Lang/8th/Atomic-updates create mode 120000 Lang/ABAP/Guess-the-number create mode 120000 Lang/ALGOL-60/Loops-Do-while create mode 120000 Lang/ALGOL-60/Loops-Downward-for create mode 120000 Lang/ALGOL-60/Loops-Infinite create mode 120000 Lang/ARM-Assembly/Binary-digits create mode 120000 Lang/ARM-Assembly/Bitwise-operations create mode 120000 Lang/ARM-Assembly/Factors-of-an-integer create mode 120000 Lang/ARM-Assembly/Function-definition create mode 120000 Lang/ARM-Assembly/Integer-comparison create mode 120000 Lang/ARM-Assembly/Loops-For create mode 120000 Lang/ARM-Assembly/String-comparison create mode 120000 Lang/ARM-Assembly/User-input-Text create mode 120000 Lang/Agda/Extend-your-language create mode 120000 Lang/BASIC/Pi create mode 120000 Lang/BaCon/HTTPS create mode 120000 Lang/Bc/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/Bc/Zero-to-the-zero-power create mode 120000 Lang/Beeswax/Empty-program create mode 120000 Lang/Befunge/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Befunge/Amicable-pairs create mode 120000 Lang/Befunge/Colour-pinstripe-Display create mode 120000 Lang/Befunge/Conways-Game-of-Life create mode 120000 Lang/Befunge/Dragon-curve create mode 120000 Lang/Befunge/Draw-a-cuboid create mode 120000 Lang/Befunge/Fibonacci-n-step-number-sequences create mode 120000 Lang/Befunge/Find-limit-of-recursion create mode 120000 Lang/Befunge/Fractran create mode 120000 Lang/Befunge/Guess-the-number-With-feedback create mode 120000 Lang/Befunge/IBAN create mode 120000 Lang/Befunge/Iterated-digits-squaring create mode 120000 Lang/Befunge/Langtons-ant create mode 120000 Lang/Befunge/Least-common-multiple create mode 120000 Lang/Befunge/Munching-squares create mode 120000 Lang/Befunge/N-queens-problem create mode 120000 Lang/Befunge/Narcissistic-decimal-number create mode 120000 Lang/Befunge/Pangram-checker create mode 120000 Lang/Befunge/Pinstripe-Display create mode 120000 Lang/Befunge/Sudoku create mode 120000 Lang/C++/Count-the-coins create mode 120000 Lang/C++/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/C++/Zhang-Suen-thinning-algorithm create mode 120000 Lang/C-sharp/Longest-increasing-subsequence create mode 120000 Lang/COBOL/Use-another-language-to-call-a-function create mode 120000 Lang/Ceylon/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Ceylon/Dutch-national-flag-problem create mode 120000 Lang/Ceylon/Fractal-tree create mode 120000 Lang/Crystal/Combinations create mode 120000 Lang/Crystal/Flatten-a-list create mode 120000 Lang/Crystal/Hailstone-sequence create mode 120000 Lang/Crystal/JSON create mode 120000 Lang/Crystal/Number-reversal-game create mode 120000 Lang/Crystal/Palindrome-detection create mode 120000 Lang/Crystal/Pick-random-element create mode 120000 Lang/Crystal/Repeat-a-string create mode 120000 Lang/Crystal/Sort-an-integer-array create mode 120000 Lang/Crystal/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Crystal/Sum-and-product-of-an-array create mode 120000 Lang/Crystal/Sum-multiples-of-3-and-5 create mode 120000 Lang/Crystal/Sum-of-squares create mode 120000 Lang/Dart/Leap-year create mode 120000 Lang/Emacs-Lisp/99-Bottles-of-Beer create mode 120000 Lang/Emacs-Lisp/Character-codes create mode 120000 Lang/Emacs-Lisp/Copy-a-string create mode 120000 Lang/Emacs-Lisp/Create-a-file create mode 120000 Lang/Emacs-Lisp/Delete-a-file create mode 120000 Lang/Emacs-Lisp/Execute-a-system-command create mode 120000 Lang/Emacs-Lisp/FizzBuzz create mode 120000 Lang/Emacs-Lisp/Guess-the-number create mode 120000 Lang/Emacs-Lisp/Guess-the-number-With-feedback create mode 120000 Lang/Emacs-Lisp/Josephus-problem create mode 120000 Lang/Factor/Aliquot-sequence-classifications create mode 120000 Lang/Factor/Define-a-primitive-data-type create mode 120000 Lang/Factor/Identity-matrix create mode 120000 Lang/Factor/Object-serialization create mode 120000 Lang/Factor/Quaternion-type create mode 120000 Lang/Factor/Queue-Usage create mode 120000 Lang/Factor/Rep-string create mode 120000 Lang/Factor/SHA-256 create mode 120000 Lang/Factor/Stern-Brocot-sequence create mode 120000 Lang/Factor/Strip-comments-from-a-string create mode 120000 Lang/Forth/Define-a-primitive-data-type create mode 120000 Lang/Forth/Dutch-national-flag-problem create mode 120000 Lang/Forth/Metaprogramming create mode 120000 Lang/Forth/Strip-comments-from-a-string create mode 120000 Lang/Forth/Terminal-control-Coloured-text create mode 120000 Lang/Forth/Terminal-control-Cursor-movement create mode 120000 Lang/FreeBASIC/Check-Machin-like-formulas create mode 120000 Lang/FreeBASIC/Evolutionary-algorithm create mode 120000 Lang/FreeBASIC/Hofstadter-Conway-$10,000-sequence create mode 120000 Lang/FreeBASIC/Image-noise create mode 120000 Lang/FreeBASIC/Modular-inverse create mode 120000 Lang/FreeBASIC/Pi create mode 120000 Lang/FreeBASIC/Resistor-mesh create mode 120000 Lang/Futhark/Apply-a-callback-to-an-array create mode 120000 Lang/Go/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Go/Bitwise-IO create mode 120000 Lang/Go/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- create mode 120000 Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- create mode 120000 Lang/Go/First-class-environments create mode 120000 Lang/Go/Galton-box-animation create mode 120000 Lang/Go/Inverted-syntax create mode 120000 Lang/Go/Jensens-Device create mode 120000 Lang/Go/Solve-a-Hidato-puzzle create mode 120000 Lang/Go/Solve-a-Hopido-puzzle create mode 120000 Lang/Go/Solve-a-Numbrix-puzzle create mode 120000 Lang/Go/Terminal-control-Preserve-screen create mode 120000 Lang/Go/Video-display-modes create mode 120000 Lang/Groovy/Integer-sequence create mode 120000 Lang/Java/QR-decomposition create mode 120000 Lang/Java/Set-of-real-numbers create mode 120000 Lang/Java/Terminal-control-Preserve-screen create mode 120000 Lang/K/Digital-root create mode 120000 Lang/K/Even-or-odd create mode 120000 Lang/K/Harshad-or-Niven-series create mode 120000 Lang/K/Hello-world-Text create mode 120000 Lang/K/Hostname create mode 120000 Lang/K/Loops-While create mode 120000 Lang/K/Reverse-a-string create mode 120000 Lang/K/String-concatenation create mode 120000 Lang/K/String-length create mode 120000 Lang/K/String-prepend create mode 120000 Lang/K/Substring-Top-and-tail create mode 120000 Lang/Lambdatalk/Hello-world-Text create mode 120000 Lang/Lua/DNS-query create mode 120000 Lang/Lua/HTTPS create mode 120000 Lang/Lua/HTTPS-Authenticated create mode 120000 Lang/Maple/Almost-prime create mode 120000 Lang/Maple/Hough-transform create mode 120000 Lang/Maple/I-before-E-except-after-C create mode 120000 Lang/Maple/Image-convolution create mode 120000 Lang/Maple/Knapsack-problem-0-1 create mode 120000 Lang/Maple/Order-two-numerical-lists create mode 120000 Lang/Maple/Phrase-reversals create mode 120000 Lang/Maple/Plot-coordinate-pairs create mode 120000 Lang/Maple/Queue-Usage create mode 120000 Lang/Maple/Range-extraction create mode 120000 Lang/Maple/Read-a-specific-line-from-a-file create mode 120000 Lang/Maple/Reverse-words-in-a-string create mode 120000 Lang/Maple/Short-circuit-evaluation create mode 120000 Lang/Maple/Sort-disjoint-sublist create mode 120000 Lang/Maple/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Maple/Vector-products create mode 120000 Lang/Mathematica/MD4 create mode 120000 Lang/Mathematica/RIPEMD-160 create mode 120000 Lang/Modula-2/Binary-digits create mode 120000 Lang/NewLISP/Ackermann-function create mode 120000 Lang/NewLISP/Detect-division-by-zero create mode 120000 Lang/NewLISP/Null-object create mode 120000 Lang/Nial/Zero-to-the-zero-power create mode 120000 Lang/Ol/Matrix-multiplication create mode 120000 Lang/PHP/Strip-block-comments create mode 120000 Lang/PL-I/Jump-anywhere create mode 120000 Lang/Perl/Solve-a-Numbrix-puzzle create mode 120000 Lang/Phix/Bitcoin-address-validation create mode 120000 Lang/Phix/Bitcoin-public-point-to-address create mode 120000 Lang/Phix/Delegates create mode 120000 Lang/Phix/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Phix/HTTP create mode 120000 Lang/Phix/HTTPS create mode 120000 Lang/Phix/HTTPS-Authenticated create mode 120000 Lang/Phix/HTTPS-Client-authenticated create mode 120000 Lang/Phix/History-variables create mode 120000 Lang/Phix/Huffman-coding create mode 120000 Lang/Phix/Keyboard-macros create mode 120000 Lang/Phix/Knuths-algorithm-S create mode 120000 Lang/Phix/LU-decomposition create mode 120000 Lang/Phix/MD4 create mode 120000 Lang/Phix/Main-step-of-GOST-28147-89 create mode 120000 Lang/Phix/Metronome create mode 120000 Lang/Phix/Minesweeper-game create mode 120000 Lang/Phix/Nautical-bell create mode 120000 Lang/Phix/Parametrized-SQL-statement create mode 120000 Lang/Phix/Pascals-triangle-Puzzle create mode 120000 Lang/Phix/RIPEMD-160 create mode 120000 Lang/Phix/Random-number-generator--device- create mode 120000 Lang/Phix/Respond-to-an-unknown-method-call create mode 120000 Lang/Phix/SHA-1 create mode 120000 Lang/Phix/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/Phix/Table-creation-Postal-addresses create mode 120000 Lang/Phix/Terminal-control-Preserve-screen create mode 120000 Lang/Phix/Terminal-control-Unicode-output create mode 120000 Lang/Phix/Video-display-modes create mode 120000 Lang/Python/99-Bottles-of-Beer create mode 120000 Lang/Python/Bitmap-Histogram create mode 120000 Lang/Ring/Amb create mode 120000 Lang/Ring/CSV-data-manipulation create mode 120000 Lang/Ring/Calendar---for-REAL-programmers create mode 120000 Lang/Ring/Create-an-HTML-table create mode 120000 Lang/Ring/Determine-if-only-one-instance-is-running create mode 120000 Lang/Ring/Flipping-bits-game create mode 120000 Lang/Ring/Function-composition create mode 120000 Lang/Ring/Inheritance-Multiple create mode 120000 Lang/Ring/Introspection create mode 120000 Lang/Ring/Keyboard-input-Flush-the-keyboard-buffer create mode 120000 Lang/Ring/Queue-Definition create mode 120000 Lang/Ring/Stack create mode 120000 Lang/Ring/Terminal-control-Hiding-the-cursor create mode 120000 Lang/Ring/Terminal-control-Preserve-screen create mode 120000 Lang/Rust/Fast-Fourier-transform create mode 120000 Lang/Scala/Active-Directory-Search-for-a-user create mode 120000 Lang/Scala/Brownian-tree create mode 120000 Lang/Scala/Checkpoint-synchronization create mode 120000 Lang/Scala/Chinese-remainder-theorem create mode 120000 Lang/Scala/Colour-pinstripe-Display create mode 120000 Lang/Scala/Convert-decimal-number-to-rational create mode 120000 Lang/Scala/Deconvolution-1D create mode 120000 Lang/Scala/Delegates create mode 120000 Lang/Scala/Determine-if-only-one-instance-is-running create mode 120000 Lang/Scala/Documentation create mode 120000 Lang/Scala/Doubly-linked-list-Traversal create mode 120000 Lang/Scala/Draw-a-cuboid create mode 120000 Lang/Scala/Find-largest-left-truncatable-prime-in-a-given-base create mode 120000 Lang/Scala/Horizontal-sundial-calculations create mode 120000 Lang/Scala/Iterated-digits-squaring create mode 120000 Lang/Scala/Keyboard-macros create mode 120000 Lang/Scala/Non-continuous-subsequences create mode 120000 Lang/Scala/Parametrized-SQL-statement create mode 120000 Lang/Scala/Permutation-test create mode 120000 Lang/Scala/Permutations-Rank-of-a-permutation create mode 120000 Lang/Scala/Pinstripe-Display create mode 120000 Lang/Scala/Polymorphism create mode 120000 Lang/Scala/Pythagorean-triples create mode 120000 Lang/Scala/QR-decomposition create mode 120000 Lang/Scala/Seven-sided-dice-from-five-sided-dice create mode 120000 Lang/Scala/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Scala/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Scala/Sorting-algorithms-Radix-sort create mode 120000 Lang/Scala/Text-processing-Max-licenses-in-use create mode 120000 Lang/Scala/World-Cup-group-stage create mode 120000 Lang/Sed/Comma-quibbling create mode 120000 Lang/Shen/Luhn-test-of-credit-card-numbers create mode 120000 Lang/Swift/Averages-Mode create mode 120000 Lang/Swift/Catalan-numbers create mode 120000 Lang/Swift/Entropy create mode 120000 Lang/Swift/Safe-addition create mode 120000 Lang/TI-83-BASIC/Inverted-syntax create mode 120000 Lang/Transact-SQL/Repeat-a-string create mode 120000 Lang/VAX-Assembly/100-doors create mode 120000 Lang/VAX-Assembly/CRC-32 create mode 120000 Lang/VAX-Assembly/Delete-a-file create mode 120000 Lang/VAX-Assembly/Detect-division-by-zero create mode 120000 Lang/VAX-Assembly/Empty-program create mode 120000 Lang/VAX-Assembly/Empty-string create mode 120000 Lang/VAX-Assembly/Fibonacci-sequence create mode 120000 Lang/VAX-Assembly/FizzBuzz create mode 120000 Lang/VAX-Assembly/Hello-world-Text create mode 120000 Lang/VAX-Assembly/Loops-For-with-a-specified-step create mode 120000 Lang/VAX-Assembly/Loops-Infinite create mode 120000 Lang/VAX-Assembly/Sieve-of-Eratosthenes create mode 120000 Lang/VBA/Aliquot-sequence-classifications create mode 120000 Lang/VBA/Formatted-numeric-output create mode 120000 Lang/VBA/Greatest-element-of-a-list create mode 120000 Lang/VBA/Harshad-or-Niven-series create mode 120000 Lang/VBScript/Draw-a-cuboid create mode 120000 Lang/VBScript/Draw-a-sphere create mode 120000 Lang/VBScript/Sorting-algorithms-Insertion-sort create mode 120000 Lang/Vala/GUI-component-interaction create mode 120000 Lang/Vala/GUI-enabling-disabling-of-controls create mode 120000 Lang/Visual-Basic-.NET/Munching-squares create mode 100644 Task/100-doors/C++/100-doors-4.cpp create mode 100644 Task/100-doors/Ruby/100-doors-5.rb create mode 100644 Task/100-doors/VAX-Assembly/100-doors.vax create mode 100644 Task/99-Bottles-of-Beer/Emacs-Lisp/99-bottles-of-beer.l create mode 100644 Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py create mode 100644 Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py rename Task/A+B/Swift/{a+b.swift => a+b-1.swift} (100%) create mode 100644 Task/A+B/Swift/a+b-2.swift create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Befunge/abundant,-deficient-and-perfect-number-classifications.bf create mode 100644 Task/Accumulator-factory/8th/accumulator-factory.8th create mode 100644 Task/Ackermann-function/NewLISP/ackermann-function.newlisp create mode 100644 Task/Active-Directory-Search-for-a-user/Scala/active-directory-search-for-a-user.scala create mode 100644 Task/Aliquot-sequence-classifications/Factor/aliquot-sequence-classifications.factor create mode 100644 Task/Aliquot-sequence-classifications/VBA/aliquot-sequence-classifications.vba create mode 100644 Task/Almost-prime/Maple/almost-prime.maple create mode 100644 Task/Amb/Ring/amb.ring create mode 100644 Task/Amicable-pairs/Befunge/amicable-pairs.bf rename Task/Amicable-pairs/Elena/{amicable-pairs.elena => amicable-pairs-1.elena} (100%) create mode 100644 Task/Amicable-pairs/Elena/amicable-pairs-2.elena create mode 100644 Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-1.futhark create mode 100644 Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-2.futhark create mode 100644 Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-3.futhark create mode 100644 Task/Arena-storage-pool/C/arena-storage-pool-7.c create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Go/arithmetic-geometric-mean-calculate-pi.go create mode 100644 Task/Array-concatenation/8th/array-concatenation.8th create mode 100644 Task/Associative-array-Creation/8th/associative-array-creation-1.8th create mode 100644 Task/Associative-array-Creation/8th/associative-array-creation-2.8th rename Task/Associative-array-Creation/Elena/{associative-array-creation.elena => associative-array-creation-1.elena} (91%) create mode 100644 Task/Associative-array-Creation/Elena/associative-array-creation-2.elena create mode 100644 Task/Associative-array-Iteration/8th/associative-array-iteration-1.8th create mode 100644 Task/Associative-array-Iteration/8th/associative-array-iteration-2.8th rename Task/Associative-array-Iteration/Elena/{associative-array-iteration.elena => associative-array-iteration-1.elena} (94%) create mode 100644 Task/Associative-array-Iteration/Elena/associative-array-iteration-2.elena create mode 100644 Task/Atomic-updates/8th/atomic-updates.8th create mode 100644 Task/Averages-Arithmetic-mean/Perl/averages-arithmetic-mean.pl rename Task/Averages-Median/K/{averages-median.k => averages-median-1.k} (100%) create mode 100644 Task/Averages-Median/K/averages-median-2.k create mode 100644 Task/Averages-Mode/Swift/averages-mode.swift create mode 100644 Task/Binary-digits/ARM-Assembly/binary-digits.arm create mode 100644 Task/Binary-digits/Modula-2/binary-digits.mod2 create mode 100644 Task/Bitcoin-address-validation/Phix/bitcoin-address-validation.phix create mode 100644 Task/Bitcoin-public-point-to-address/Phix/bitcoin-public-point-to-address.phix rename Task/Bitmap-B-zier-curves-Quadratic/Mathematica/{bitmap-b-zier-curves-quadratic.math => bitmap-b-zier-curves-quadratic-1.math} (100%) create mode 100644 Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic-2.math create mode 100644 Task/Bitmap-Histogram/Python/bitmap-histogram.py create mode 100644 Task/Bitwise-IO/Go/bitwise-io-1.go create mode 100644 Task/Bitwise-IO/Go/bitwise-io-2.go create mode 100644 Task/Bitwise-operations/ARM-Assembly/bitwise-operations.arm create mode 100644 Task/Brownian-tree/Scala/brownian-tree.scala create mode 100644 Task/CRC-32/VAX-Assembly/crc-32.vax create mode 100644 Task/CSV-data-manipulation/Ring/csv-data-manipulation.ring rename Task/Caesar-cipher/ZX-Spectrum-Basic/{caesar-cipher.zx => caesar-cipher-1.zx} (100%) create mode 100644 Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher-2.zx create mode 100644 Task/Calendar---for-REAL-programmers/Ring/calendar---for-real-programmers.ring create mode 100644 Task/Catalan-numbers/Swift/catalan-numbers.swift create mode 100644 Task/Character-codes/Emacs-Lisp/character-codes.l create mode 100644 Task/Check-Machin-like-formulas/FreeBASIC/check-machin-like-formulas.freebasic create mode 100644 Task/Checkpoint-synchronization/Scala/checkpoint-synchronization.scala create mode 100644 Task/Chinese-remainder-theorem/Scala/chinese-remainder-theorem.scala create mode 100644 Task/Colour-pinstripe-Display/Befunge/colour-pinstripe-display.bf create mode 100644 Task/Colour-pinstripe-Display/Scala/colour-pinstripe-display.scala create mode 100644 Task/Combinations/Crystal/combinations-1.crystal create mode 100644 Task/Combinations/Crystal/combinations-2.crystal create mode 100644 Task/Comma-quibbling/Sed/comma-quibbling-1.sed create mode 100644 Task/Comma-quibbling/Sed/comma-quibbling-2.sed create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-1.go create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-2.go create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-3.go create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.go create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.go create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--1.go create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--2.go create mode 100644 Task/Convert-decimal-number-to-rational/Scala/convert-decimal-number-to-rational.scala create mode 100644 Task/Conways-Game-of-Life/Befunge/conways-game-of-life.bf create mode 100644 Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java create mode 100644 Task/Copy-a-string/Emacs-Lisp/copy-a-string.l create mode 100644 Task/Count-the-coins/C++/count-the-coins.cpp create mode 100644 Task/Create-a-file/Emacs-Lisp/create-a-file.l create mode 100644 Task/Create-an-HTML-table/Ring/create-an-html-table.ring create mode 100644 Task/DNS-query/Lasso/dns-query.lasso create mode 100644 Task/DNS-query/Lua/dns-query-1.lua create mode 100644 Task/DNS-query/Lua/dns-query-2.lua create mode 100644 Task/DNS-query/Lua/dns-query-3.lua rename Task/Date-format/Forth/{date-format.fth => date-format-1.fth} (100%) create mode 100644 Task/Date-format/Forth/date-format-2.fth create mode 100644 Task/Date-format/Forth/date-format-3.fth create mode 100644 Task/Deconvolution-1D/Scala/deconvolution-1d.scala create mode 100644 Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-1.factor create mode 100644 Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-2.factor create mode 100644 Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-3.factor create mode 100644 Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-1.fth create mode 100644 Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-2.fth create mode 100644 Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-3.fth create mode 100644 Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-4.fth create mode 100644 Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-5.fth create mode 100644 Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-6.fth create mode 100644 Task/Delegates/Phix/delegates-1.phix create mode 100644 Task/Delegates/Phix/delegates-2.phix create mode 100644 Task/Delegates/Scala/delegates.scala create mode 100644 Task/Delete-a-file/Emacs-Lisp/delete-a-file.l create mode 100644 Task/Delete-a-file/VAX-Assembly/delete-a-file.vax create mode 100644 Task/Detect-division-by-zero/NewLISP/detect-division-by-zero.newlisp create mode 100644 Task/Detect-division-by-zero/VAX-Assembly/detect-division-by-zero.vax create mode 100644 Task/Determine-if-only-one-instance-is-running/Ring/determine-if-only-one-instance-is-running.ring create mode 100644 Task/Determine-if-only-one-instance-is-running/Scala/determine-if-only-one-instance-is-running.scala create mode 100644 Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root.phix create mode 100644 Task/Digital-root/K/digital-root.k create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Ceylon/dinesmans-multiple-dwelling-problem.ceylon create mode 100644 Task/Documentation/Scala/documentation.scala create mode 100644 Task/Doubly-linked-list-Traversal/Scala/doubly-linked-list-traversal.scala create mode 100644 Task/Dragon-curve/Befunge/dragon-curve.bf create mode 100644 Task/Draw-a-cuboid/Befunge/draw-a-cuboid.bf create mode 100644 Task/Draw-a-cuboid/Scala/draw-a-cuboid.scala create mode 100644 Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb create mode 100644 Task/Draw-a-sphere/VBScript/draw-a-sphere.vb create mode 100644 Task/Dutch-national-flag-problem/Ceylon/dutch-national-flag-problem.ceylon create mode 100644 Task/Dutch-national-flag-problem/Forth/dutch-national-flag-problem.fth create mode 100644 Task/Empty-program/Beeswax/empty-program-1.beeswax create mode 100644 Task/Empty-program/Beeswax/empty-program-2.beeswax create mode 100644 Task/Empty-program/Beeswax/empty-program-3.beeswax create mode 100644 Task/Empty-program/Beeswax/empty-program-4.beeswax create mode 100644 Task/Empty-program/VAX-Assembly/empty-program.vax create mode 100644 Task/Empty-string/VAX-Assembly/empty-string.vax create mode 100644 Task/Entropy/Swift/entropy.swift create mode 100644 Task/Even-or-odd/K/even-or-odd.k create mode 100644 Task/Evolutionary-algorithm/FreeBASIC/evolutionary-algorithm.freebasic create mode 100644 Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l create mode 100644 Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l create mode 100644 Task/Extend-your-language/Agda/extend-your-language.agda rename Task/Factorial/MIPS-Assembly/{factorial.mips => factorial-1.mips} (100%) create mode 100644 Task/Factorial/MIPS-Assembly/factorial-2.mips create mode 100644 Task/Factors-of-an-integer/ARM-Assembly/factors-of-an-integer.arm create mode 100644 Task/Fast-Fourier-transform/Rust/fast-fourier-transform.rust create mode 100644 Task/Fibonacci-n-step-number-sequences/Befunge/fibonacci-n-step-number-sequences.bf create mode 100644 Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-1.360 create mode 100644 Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-2.360 delete mode 100644 Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 create mode 100644 Task/Fibonacci-sequence/Fortran/fibonacci-sequence-6.f create mode 100644 Task/Fibonacci-sequence/VAX-Assembly/fibonacci-sequence.vax create mode 100644 Task/Fibonacci-sequence/Visual-Basic-.NET/fibonacci-sequence-3.visual create mode 100644 Task/Find-largest-left-truncatable-prime-in-a-given-base/Scala/find-largest-left-truncatable-prime-in-a-given-base.scala create mode 100644 Task/Find-limit-of-recursion/Befunge/find-limit-of-recursion.bf create mode 100644 Task/First-class-environments/Go/first-class-environments.go create mode 100644 Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l rename Task/FizzBuzz/Factor/{fizzbuzz.factor => fizzbuzz-1.factor} (100%) create mode 100644 Task/FizzBuzz/Factor/fizzbuzz-2.factor create mode 100644 Task/FizzBuzz/VAX-Assembly/fizzbuzz.vax create mode 100644 Task/Flatten-a-list/Crystal/flatten-a-list-1.crystal create mode 100644 Task/Flatten-a-list/Crystal/flatten-a-list-2.crystal create mode 100644 Task/Flipping-bits-game/Ring/flipping-bits-game.ring create mode 100644 Task/Formatted-numeric-output/VBA/formatted-numeric-output.vba create mode 100644 Task/Fractal-tree/Ceylon/fractal-tree.ceylon create mode 100644 Task/Fractran/Befunge/fractran.bf create mode 100644 Task/Function-composition/Ring/function-composition.ring create mode 100644 Task/Function-definition/ARM-Assembly/function-definition.arm create mode 100644 Task/GUI-component-interaction/Vala/gui-component-interaction.vala create mode 100644 Task/GUI-enabling-disabling-of-controls/Vala/gui-enabling-disabling-of-controls.vala create mode 100644 Task/Galton-box-animation/Go/galton-box-animation.go create mode 100644 Task/Greatest-element-of-a-list/VBA/greatest-element-of-a-list.vba create mode 100644 Task/Guess-the-number-With-feedback/Befunge/guess-the-number-with-feedback.bf create mode 100644 Task/Guess-the-number-With-feedback/Emacs-Lisp/guess-the-number-with-feedback.l create mode 100644 Task/Guess-the-number/ABAP/guess-the-number.abap create mode 100644 Task/Guess-the-number/Emacs-Lisp/guess-the-number.l create mode 100644 Task/HTTP/Phix/http.phix create mode 100644 Task/HTTPS-Authenticated/Lua/https-authenticated.lua create mode 100644 Task/HTTPS-Authenticated/Phix/https-authenticated.phix create mode 100644 Task/HTTPS-Client-authenticated/Phix/https-client-authenticated.phix create mode 100644 Task/HTTPS/BaCon/https.bacon create mode 100644 Task/HTTPS/Lua/https.lua create mode 100644 Task/HTTPS/Phix/https.phix create mode 100644 Task/Hailstone-sequence/Crystal/hailstone-sequence.crystal create mode 100644 Task/Harshad-or-Niven-series/K/harshad-or-niven-series.k create mode 100644 Task/Harshad-or-Niven-series/VBA/harshad-or-niven-series.vba create mode 100644 Task/Hello-world-Text/K/hello-world-text-1.k create mode 100644 Task/Hello-world-Text/K/hello-world-text-2.k create mode 100644 Task/Hello-world-Text/K/hello-world-text-3.k create mode 100644 Task/Hello-world-Text/K/hello-world-text-4.k create mode 100644 Task/Hello-world-Text/Lambdatalk/hello-world-text.lambdatalk create mode 100644 Task/Hello-world-Text/VAX-Assembly/hello-world-text.vax create mode 100644 Task/History-variables/Phix/history-variables-1.phix create mode 100644 Task/History-variables/Phix/history-variables-2.phix create mode 100644 Task/History-variables/Phix/history-variables-3.phix create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/FreeBASIC/hofstadter-conway-$10,000-sequence.freebasic create mode 100644 Task/Horizontal-sundial-calculations/Scala/horizontal-sundial-calculations.scala create mode 100644 Task/Hostname/K/hostname.k create mode 100644 Task/Hough-transform/Maple/hough-transform.maple create mode 100644 Task/Huffman-coding/Phix/huffman-coding.phix create mode 100644 Task/I-before-E-except-after-C/Maple/i-before-e-except-after-c.maple create mode 100644 Task/IBAN/Befunge/iban.bf create mode 100644 Task/IBAN/PowerShell/iban-3.psh create mode 100644 Task/Identity-matrix/Burlesque/identity-matrix-3.blq create mode 100644 Task/Identity-matrix/Factor/identity-matrix.factor create mode 100644 Task/Identity-matrix/Haskell/identity-matrix-5.hs create mode 100644 Task/Image-convolution/Maple/image-convolution.maple create mode 100644 Task/Image-noise/FreeBASIC/image-noise.freebasic create mode 100644 Task/Inheritance-Multiple/Ring/inheritance-multiple.ring create mode 100644 Task/Integer-comparison/ARM-Assembly/integer-comparison.arm create mode 100644 Task/Integer-sequence/Groovy/integer-sequence.groovy create mode 100644 Task/Introspection/Ring/introspection.ring create mode 100644 Task/Inverted-syntax/Factor/inverted-syntax-3.factor create mode 100644 Task/Inverted-syntax/Factor/inverted-syntax-4.factor create mode 100644 Task/Inverted-syntax/Factor/inverted-syntax-5.factor create mode 100644 Task/Inverted-syntax/Go/inverted-syntax.go create mode 100644 Task/Inverted-syntax/TI-83-BASIC/inverted-syntax.ti-83 create mode 100644 Task/Iterated-digits-squaring/Befunge/iterated-digits-squaring.bf create mode 100644 Task/Iterated-digits-squaring/Scala/iterated-digits-squaring.scala create mode 100644 Task/JSON/Crystal/json-1.crystal create mode 100644 Task/JSON/Crystal/json-2.crystal create mode 100644 Task/JSON/Haskell/json-3.hs create mode 100644 Task/Jensens-Device/Go/jensens-device.go create mode 100644 Task/Josephus-problem/Emacs-Lisp/josephus-problem.l create mode 100644 Task/Jump-anywhere/PL-I/jump-anywhere.pli create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Ring/keyboard-input-flush-the-keyboard-buffer.ring create mode 100644 Task/Keyboard-macros/Phix/keyboard-macros-1.phix create mode 100644 Task/Keyboard-macros/Phix/keyboard-macros-2.phix create mode 100644 Task/Keyboard-macros/Scala/keyboard-macros.scala create mode 100644 Task/Knapsack-problem-0-1/Maple/knapsack-problem-0-1.maple rename Task/Knuths-algorithm-S/Kotlin/{knuths-algorithm-s.kotlin => knuths-algorithm-s-1.kotlin} (63%) create mode 100644 Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-2.kotlin create mode 100644 Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-1.phix create mode 100644 Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-2.phix create mode 100644 Task/LU-decomposition/Phix/lu-decomposition.phix rename Task/LZW-compression/JavaScript/{lzw-compression.js => lzw-compression-1.js} (100%) create mode 100644 Task/LZW-compression/JavaScript/lzw-compression-2.js create mode 100644 Task/Langtons-ant/Befunge/langtons-ant.bf create mode 100644 Task/Leap-year/Dart/leap-year.dart create mode 100644 Task/Least-common-multiple/Befunge/least-common-multiple.bf create mode 100644 Task/Levenshtein-distance/Scala/levenshtein-distance-1.scala create mode 100644 Task/Levenshtein-distance/Scala/levenshtein-distance-2.scala delete mode 100644 Task/Levenshtein-distance/Scala/levenshtein-distance.scala create mode 100644 Task/Literals-Floating-point/360-Assembly/literals-floating-point.360 create mode 100644 Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-1.cs create mode 100644 Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-2.cs create mode 100644 Task/Loops-Do-while/ALGOL-60/loops-do-while.alg create mode 100644 Task/Loops-Do-while/Fortran/loops-do-while-3.f create mode 100644 Task/Loops-Do-while/Fortran/loops-do-while-4.f create mode 100644 Task/Loops-Downward-for/ALGOL-60/loops-downward-for.alg create mode 100644 Task/Loops-For-with-a-specified-step/VAX-Assembly/loops-for-with-a-specified-step.vax create mode 100644 Task/Loops-For/ARM-Assembly/loops-for.arm create mode 100644 Task/Loops-Infinite/ALGOL-60/loops-infinite.alg create mode 100644 Task/Loops-Infinite/VAX-Assembly/loops-infinite.vax create mode 100644 Task/Loops-While/K/loops-while.k create mode 100644 Task/Luhn-test-of-credit-card-numbers/Shen/luhn-test-of-credit-card-numbers.shen create mode 100644 Task/MD4/Mathematica/md4.math create mode 100644 Task/MD4/Phix/md4.phix create mode 100644 Task/Main-step-of-GOST-28147-89/Phix/main-step-of-gost-28147-89.phix create mode 100644 Task/Mandelbrot-set/Mathematica/mandelbrot-set-3.math create mode 100644 Task/Matrix-multiplication/Ol/matrix-multiplication.ol create mode 100644 Task/Metaprogramming/Forth/metaprogramming-1.fth create mode 100644 Task/Metaprogramming/Forth/metaprogramming-2.fth create mode 100644 Task/Metronome/Phix/metronome.phix create mode 100644 Task/Minesweeper-game/Phix/minesweeper-game.phix create mode 100644 Task/Modular-inverse/FreeBASIC/modular-inverse.freebasic create mode 100644 Task/Munching-squares/Befunge/munching-squares.bf create mode 100644 Task/Munching-squares/Visual-Basic-.NET/munching-squares.visual create mode 100644 Task/N-queens-problem/Befunge/n-queens-problem.bf rename Task/N-queens-problem/Go/{n-queens-problem.go => n-queens-problem-1.go} (100%) create mode 100644 Task/N-queens-problem/Go/n-queens-problem-2.go create mode 100644 Task/Narcissistic-decimal-number/Befunge/narcissistic-decimal-number.bf create mode 100644 Task/Nautical-bell/Phix/nautical-bell.phix create mode 100644 Task/Non-continuous-subsequences/Scala/non-continuous-subsequences.scala create mode 100644 Task/Nth-root/360-Assembly/nth-root.360 create mode 100644 Task/Null-object/NewLISP/null-object.newlisp create mode 100644 Task/Number-reversal-game/Crystal/number-reversal-game.crystal create mode 100644 Task/Object-serialization/Factor/object-serialization.factor rename Task/Optional-parameters/Perl-6/{optional-parameters.pl6 => optional-parameters-1.pl6} (100%) create mode 100644 Task/Optional-parameters/Perl-6/optional-parameters-2.pl6 create mode 100644 Task/Order-two-numerical-lists/Maple/order-two-numerical-lists.maple create mode 100644 Task/Palindrome-detection/360-Assembly/palindrome-detection.360 create mode 100644 Task/Palindrome-detection/Crystal/palindrome-detection-1.crystal create mode 100644 Task/Palindrome-detection/Crystal/palindrome-detection-2.crystal create mode 100644 Task/Palindrome-detection/Crystal/palindrome-detection-3.crystal create mode 100644 Task/Palindrome-detection/Crystal/palindrome-detection-4.crystal create mode 100644 Task/Pangram-checker/Befunge/pangram-checker.bf create mode 100644 Task/Parametrized-SQL-statement/Phix/parametrized-sql-statement.phix create mode 100644 Task/Parametrized-SQL-statement/Scala/parametrized-sql-statement.scala create mode 100644 Task/Pascals-triangle-Puzzle/Phix/pascals-triangle-puzzle.phix create mode 100644 Task/Permutation-test/Scala/permutation-test.scala create mode 100644 Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-1.scala create mode 100644 Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-2.scala create mode 100644 Task/Permutations/C/permutations-1.c create mode 100644 Task/Permutations/C/permutations-2.c rename Task/Permutations/C/{permutations.c => permutations-3.c} (100%) create mode 100644 Task/Permutations/C/permutations-4.c create mode 100644 Task/Phrase-reversals/Maple/phrase-reversals.maple create mode 100644 Task/Pi/BASIC/pi-1.basic create mode 100644 Task/Pi/BASIC/pi-2.basic create mode 100644 Task/Pi/FreeBASIC/pi.freebasic create mode 100644 Task/Pick-random-element/Crystal/pick-random-element.crystal create mode 100644 Task/Pinstripe-Display/Befunge/pinstripe-display.bf create mode 100644 Task/Pinstripe-Display/Scala/pinstripe-display.scala create mode 100644 Task/Plot-coordinate-pairs/Maple/plot-coordinate-pairs.maple create mode 100644 Task/Polymorphism/Scala/polymorphism.scala rename Task/Polynomial-regression/Mathematica/{polynomial-regression.math => polynomial-regression-1.math} (100%) create mode 100644 Task/Polynomial-regression/Mathematica/polynomial-regression-2.math create mode 100644 Task/Pythagorean-triples/Scala/pythagorean-triples.scala create mode 100644 Task/QR-decomposition/Java/qr-decomposition.java create mode 100644 Task/QR-decomposition/Scala/qr-decomposition.scala create mode 100644 Task/Quaternion-type/Factor/quaternion-type.factor create mode 100644 Task/Queue-Definition/Ring/queue-definition.ring create mode 100644 Task/Queue-Usage/Factor/queue-usage-1.factor create mode 100644 Task/Queue-Usage/Factor/queue-usage-2.factor create mode 100644 Task/Queue-Usage/Maple/queue-usage.maple create mode 100644 Task/RIPEMD-160/Mathematica/ripemd-160.math create mode 100644 Task/RIPEMD-160/Phix/ripemd-160-1.phix create mode 100644 Task/RIPEMD-160/Phix/ripemd-160-2.phix create mode 100644 Task/Random-number-generator--device-/Phix/random-number-generator--device--1.phix create mode 100644 Task/Random-number-generator--device-/Phix/random-number-generator--device--2.phix create mode 100644 Task/Range-extraction/Maple/range-extraction.maple create mode 100644 Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c create mode 100644 Task/Read-a-specific-line-from-a-file/Maple/read-a-specific-line-from-a-file.maple create mode 100644 Task/Rep-string/Factor/rep-string.factor create mode 100644 Task/Repeat-a-string/Crystal/repeat-a-string-1.crystal create mode 100644 Task/Repeat-a-string/Crystal/repeat-a-string-2.crystal create mode 100644 Task/Repeat-a-string/Transact-SQL/repeat-a-string.sql create mode 100644 Task/Resistor-mesh/FreeBASIC/resistor-mesh.freebasic create mode 100644 Task/Respond-to-an-unknown-method-call/Phix/respond-to-an-unknown-method-call.phix create mode 100644 Task/Reverse-a-string/K/reverse-a-string.k create mode 100644 Task/Reverse-words-in-a-string/Maple/reverse-words-in-a-string.maple create mode 100644 Task/Roots-of-a-function/Scala/roots-of-a-function-1.scala rename Task/Roots-of-a-function/Scala/{roots-of-a-function.scala => roots-of-a-function-2.scala} (100%) create mode 100644 Task/Run-length-encoding/C++/run-length-encoding-1.cpp rename Task/Run-length-encoding/C++/{run-length-encoding.cpp => run-length-encoding-2.cpp} (100%) create mode 100644 Task/SHA-1/Phix/sha-1.phix create mode 100644 Task/SHA-256/Factor/sha-256.factor create mode 100644 Task/Safe-addition/Swift/safe-addition.swift create mode 100644 Task/Set-of-real-numbers/Java/set-of-real-numbers.java create mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Scala/seven-sided-dice-from-five-sided-dice.scala create mode 100644 Task/Short-circuit-evaluation/Maple/short-circuit-evaluation.maple rename Task/Sierpinski-triangle/Mathematica/{sierpinski-triangle.math => sierpinski-triangle-1.math} (100%) create mode 100644 Task/Sierpinski-triangle/Mathematica/sierpinski-triangle-2.math create mode 100644 Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax create mode 100644 Task/Solve-a-Hidato-puzzle/Go/solve-a-hidato-puzzle.go create mode 100644 Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.elixir create mode 100644 Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-1.go create mode 100644 Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-2.go create mode 100644 Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.elixir create mode 100644 Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-1.go create mode 100644 Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-2.go create mode 100644 Task/Solve-a-Numbrix-puzzle/Perl/solve-a-numbrix-puzzle.pl create mode 100644 Task/Sort-an-integer-array/Crystal/sort-an-integer-array.crystal rename Task/Sort-an-integer-array/Forth/{sort-an-integer-array.fth => sort-an-integer-array-1.fth} (100%) create mode 100644 Task/Sort-an-integer-array/Forth/sort-an-integer-array-2.fth create mode 100644 Task/Sort-an-integer-array/Forth/sort-an-integer-array-3.fth create mode 100644 Task/Sort-disjoint-sublist/Maple/sort-disjoint-sublist.maple create mode 100644 Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-3.basic create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Scala/sorting-algorithms-cocktail-sort.scala create mode 100644 Task/Sorting-algorithms-Gnome-sort/Scala/sorting-algorithms-gnome-sort.scala create mode 100644 Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vb create mode 100644 Task/Sorting-algorithms-Pancake-sort/Maple/sorting-algorithms-pancake-sort.maple create mode 100644 Task/Sorting-algorithms-Radix-sort/Scala/sorting-algorithms-radix-sort.scala create mode 100644 Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-3.js create mode 100644 Task/Stack/Ring/stack.ring create mode 100644 Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-3.pl create mode 100644 Task/Stern-Brocot-sequence/Factor/stern-brocot-sequence.factor create mode 100644 Task/String-comparison/ARM-Assembly/string-comparison.arm create mode 100644 Task/String-concatenation/K/string-concatenation.k create mode 100644 Task/String-length/K/string-length.k create mode 100644 Task/String-prepend/K/string-prepend.k create mode 100644 Task/Strip-block-comments/PHP/strip-block-comments.php create mode 100644 Task/Strip-comments-from-a-string/Factor/strip-comments-from-a-string.factor create mode 100644 Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-1.fth create mode 100644 Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-2.fth create mode 100644 Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-3.js create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Phix/strip-control-codes-and-extended-characters-from-a-string.phix create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.crystal create mode 100644 Task/Substring-Top-and-tail/K/substring-top-and-tail-1.k create mode 100644 Task/Substring-Top-and-tail/K/substring-top-and-tail-2.k create mode 100644 Task/Sudoku/Befunge/sudoku.bf create mode 100644 Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.crystal create mode 100644 Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.crystal create mode 100644 Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.crystal create mode 100644 Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-4.crystal create mode 100644 Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5.crystal create mode 100644 Task/Sum-of-squares/Crystal/sum-of-squares.crystal create mode 100644 Task/Table-creation-Postal-addresses/Phix/table-creation-postal-addresses.phix create mode 100644 Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-1.fth create mode 100644 Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-2.fth create mode 100644 Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-1.fth create mode 100644 Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-2.fth create mode 100644 Task/Terminal-control-Hiding-the-cursor/Ring/terminal-control-hiding-the-cursor.ring create mode 100644 Task/Terminal-control-Preserve-screen/Go/terminal-control-preserve-screen.go create mode 100644 Task/Terminal-control-Preserve-screen/Java/terminal-control-preserve-screen.java create mode 100644 Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-1.phix create mode 100644 Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-2.phix create mode 100644 Task/Terminal-control-Preserve-screen/Ring/terminal-control-preserve-screen.ring create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Bc/terminal-control-ringing-the-terminal-bell.bc create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/C++/terminal-control-ringing-the-terminal-bell.cpp create mode 100644 Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-1.phix create mode 100644 Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-2.phix create mode 100644 Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-1.scala create mode 100644 Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-2.scala create mode 100644 Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-3.scala create mode 100644 Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-4.scala create mode 100644 Task/Trigonometric-functions/REXX/trigonometric-functions.rexx create mode 100644 Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol create mode 100644 Task/User-input-Text/ARM-Assembly/user-input-text.arm create mode 100644 Task/Vector-products/Maple/vector-products.maple create mode 100644 Task/Video-display-modes/Go/video-display-modes.go create mode 100644 Task/Video-display-modes/Phix/video-display-modes.phix create mode 100644 Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-3.hs create mode 100644 Task/World-Cup-group-stage/Scala/world-cup-group-stage.scala create mode 100644 Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro create mode 100644 Task/Zebra-puzzle/Python/zebra-puzzle-4.py create mode 100644 Task/Zero-to-the-zero-power/Bc/zero-to-the-zero-power.bc create mode 100644 Task/Zero-to-the-zero-power/Nial/zero-to-the-zero-power.nial create mode 100644 Task/Zhang-Suen-thinning-algorithm/C++/zhang-suen-thinning-algorithm.cpp diff --git a/Lang/360-Assembly/Literals-Floating-point b/Lang/360-Assembly/Literals-Floating-point new file mode 120000 index 0000000000..01064f82c5 --- /dev/null +++ b/Lang/360-Assembly/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Nth-root b/Lang/360-Assembly/Nth-root new file mode 120000 index 0000000000..b91fbfd472 --- /dev/null +++ b/Lang/360-Assembly/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Palindrome-detection b/Lang/360-Assembly/Palindrome-detection new file mode 120000 index 0000000000..81586162d3 --- /dev/null +++ b/Lang/360-Assembly/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/360-Assembly \ No newline at end of file diff --git a/Lang/8th/Accumulator-factory b/Lang/8th/Accumulator-factory new file mode 120000 index 0000000000..22140d46d0 --- /dev/null +++ b/Lang/8th/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/8th \ No newline at end of file diff --git a/Lang/8th/Array-concatenation b/Lang/8th/Array-concatenation new file mode 120000 index 0000000000..dc5fffb8cb --- /dev/null +++ b/Lang/8th/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/8th \ No newline at end of file diff --git a/Lang/8th/Associative-array-Creation b/Lang/8th/Associative-array-Creation new file mode 120000 index 0000000000..9680be3841 --- /dev/null +++ b/Lang/8th/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/8th \ No newline at end of file diff --git a/Lang/8th/Associative-array-Iteration b/Lang/8th/Associative-array-Iteration new file mode 120000 index 0000000000..e6d867447f --- /dev/null +++ b/Lang/8th/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/8th \ No newline at end of file diff --git a/Lang/8th/Atomic-updates b/Lang/8th/Atomic-updates new file mode 120000 index 0000000000..07c9511fe1 --- /dev/null +++ b/Lang/8th/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/8th \ No newline at end of file diff --git a/Lang/ABAP/Guess-the-number b/Lang/ABAP/Guess-the-number new file mode 120000 index 0000000000..0eaf1424ad --- /dev/null +++ b/Lang/ABAP/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/ABAP \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Do-while b/Lang/ALGOL-60/Loops-Do-while new file mode 120000 index 0000000000..f59417278a --- /dev/null +++ b/Lang/ALGOL-60/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Downward-for b/Lang/ALGOL-60/Loops-Downward-for new file mode 120000 index 0000000000..cfae9b2326 --- /dev/null +++ b/Lang/ALGOL-60/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Infinite b/Lang/ALGOL-60/Loops-Infinite new file mode 120000 index 0000000000..527a9ee1fd --- /dev/null +++ b/Lang/ALGOL-60/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/ALGOL-60 \ No newline at end of file diff --git a/Lang/ARM-Assembly/Binary-digits b/Lang/ARM-Assembly/Binary-digits new file mode 120000 index 0000000000..e6ec8ee128 --- /dev/null +++ b/Lang/ARM-Assembly/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Bitwise-operations b/Lang/ARM-Assembly/Bitwise-operations new file mode 120000 index 0000000000..e5d1c540b0 --- /dev/null +++ b/Lang/ARM-Assembly/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Factors-of-an-integer b/Lang/ARM-Assembly/Factors-of-an-integer new file mode 120000 index 0000000000..ef3544ccb0 --- /dev/null +++ b/Lang/ARM-Assembly/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Function-definition b/Lang/ARM-Assembly/Function-definition new file mode 120000 index 0000000000..2fcaa36e07 --- /dev/null +++ b/Lang/ARM-Assembly/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Integer-comparison b/Lang/ARM-Assembly/Integer-comparison new file mode 120000 index 0000000000..d41039d2bb --- /dev/null +++ b/Lang/ARM-Assembly/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Loops-For b/Lang/ARM-Assembly/Loops-For new file mode 120000 index 0000000000..dcf153a07b --- /dev/null +++ b/Lang/ARM-Assembly/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/String-comparison b/Lang/ARM-Assembly/String-comparison new file mode 120000 index 0000000000..33e8219c93 --- /dev/null +++ b/Lang/ARM-Assembly/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/User-input-Text b/Lang/ARM-Assembly/User-input-Text new file mode 120000 index 0000000000..fa591ac931 --- /dev/null +++ b/Lang/ARM-Assembly/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/ARM-Assembly \ No newline at end of file diff --git a/Lang/Agda/Extend-your-language b/Lang/Agda/Extend-your-language new file mode 120000 index 0000000000..032b1b833e --- /dev/null +++ b/Lang/Agda/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Agda \ No newline at end of file diff --git a/Lang/Astro/00DESCRIPTION b/Lang/Astro/00DESCRIPTION index 86ec27c6f4..b143e85320 100644 --- a/Lang/Astro/00DESCRIPTION +++ b/Lang/Astro/00DESCRIPTION @@ -1,4 +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 is a fun safe language for rapid prototyping and high performance applications. 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 +It pushes multiple dispatch as its primary paradigm but borrows from several other paradigms as well. \ No newline at end of file diff --git a/Lang/BASIC/Pi b/Lang/BASIC/Pi new file mode 120000 index 0000000000..c33dc27db2 --- /dev/null +++ b/Lang/BASIC/Pi @@ -0,0 +1 @@ +../../Task/Pi/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/00DESCRIPTION b/Lang/BASIC256/00DESCRIPTION index 657286ba6f..09f744afea 100644 --- a/Lang/BASIC256/00DESCRIPTION +++ b/Lang/BASIC256/00DESCRIPTION @@ -19,7 +19,7 @@ ; Disadvantages * BASIC-256 does not support three- and N-dimensional arrays in general (N>2) - +
BASIC256 is open source and available for [[Linux]], [[Windows]] and [[Mac]]. For more information see [http://www.basic256.org basic256.org] or to download and install [http://sourceforge.net/projects/kidbasic/ sourceforge]. \ No newline at end of file diff --git a/Lang/BaCon/HTTPS b/Lang/BaCon/HTTPS new file mode 120000 index 0000000000..ff91156f1b --- /dev/null +++ b/Lang/BaCon/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/BaCon \ No newline at end of file diff --git a/Lang/Bc/Terminal-control-Ringing-the-terminal-bell b/Lang/Bc/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..a5b9130f66 --- /dev/null +++ b/Lang/Bc/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Bc \ No newline at end of file diff --git a/Lang/Bc/Zero-to-the-zero-power b/Lang/Bc/Zero-to-the-zero-power new file mode 120000 index 0000000000..f863fa8d27 --- /dev/null +++ b/Lang/Bc/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Bc \ No newline at end of file diff --git a/Lang/Beeswax/Empty-program b/Lang/Beeswax/Empty-program new file mode 120000 index 0000000000..b4c88a0407 --- /dev/null +++ b/Lang/Beeswax/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Beeswax \ No newline at end of file diff --git a/Lang/Befunge/Abundant,-deficient-and-perfect-number-classifications b/Lang/Befunge/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..1f652c2bc8 --- /dev/null +++ b/Lang/Befunge/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Amicable-pairs b/Lang/Befunge/Amicable-pairs new file mode 120000 index 0000000000..9a97cf47fb --- /dev/null +++ b/Lang/Befunge/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Colour-pinstripe-Display b/Lang/Befunge/Colour-pinstripe-Display new file mode 120000 index 0000000000..152b2a659e --- /dev/null +++ b/Lang/Befunge/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Conways-Game-of-Life b/Lang/Befunge/Conways-Game-of-Life new file mode 120000 index 0000000000..da55d0a6b2 --- /dev/null +++ b/Lang/Befunge/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Dragon-curve b/Lang/Befunge/Dragon-curve new file mode 120000 index 0000000000..08a902b8e9 --- /dev/null +++ b/Lang/Befunge/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Draw-a-cuboid b/Lang/Befunge/Draw-a-cuboid new file mode 120000 index 0000000000..7d18c7b0de --- /dev/null +++ b/Lang/Befunge/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Fibonacci-n-step-number-sequences b/Lang/Befunge/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..c36ecf57b6 --- /dev/null +++ b/Lang/Befunge/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Find-limit-of-recursion b/Lang/Befunge/Find-limit-of-recursion new file mode 120000 index 0000000000..981ebe1f9a --- /dev/null +++ b/Lang/Befunge/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Fractran b/Lang/Befunge/Fractran new file mode 120000 index 0000000000..8fcab2511d --- /dev/null +++ b/Lang/Befunge/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Guess-the-number-With-feedback b/Lang/Befunge/Guess-the-number-With-feedback new file mode 120000 index 0000000000..2a965cfc06 --- /dev/null +++ b/Lang/Befunge/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Befunge \ No newline at end of file diff --git a/Lang/Befunge/IBAN b/Lang/Befunge/IBAN new file mode 120000 index 0000000000..2ea2a8025e --- /dev/null +++ b/Lang/Befunge/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Iterated-digits-squaring b/Lang/Befunge/Iterated-digits-squaring new file mode 120000 index 0000000000..2f6a14c87d --- /dev/null +++ b/Lang/Befunge/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Langtons-ant b/Lang/Befunge/Langtons-ant new file mode 120000 index 0000000000..494309eb28 --- /dev/null +++ b/Lang/Befunge/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Least-common-multiple b/Lang/Befunge/Least-common-multiple new file mode 120000 index 0000000000..59f5a57639 --- /dev/null +++ b/Lang/Befunge/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Munching-squares b/Lang/Befunge/Munching-squares new file mode 120000 index 0000000000..e426f04729 --- /dev/null +++ b/Lang/Befunge/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Befunge \ No newline at end of file diff --git a/Lang/Befunge/N-queens-problem b/Lang/Befunge/N-queens-problem new file mode 120000 index 0000000000..f168d6747c --- /dev/null +++ b/Lang/Befunge/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Narcissistic-decimal-number b/Lang/Befunge/Narcissistic-decimal-number new file mode 120000 index 0000000000..1b5f8ca3b8 --- /dev/null +++ b/Lang/Befunge/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Pangram-checker b/Lang/Befunge/Pangram-checker new file mode 120000 index 0000000000..cde527f366 --- /dev/null +++ b/Lang/Befunge/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Pinstripe-Display b/Lang/Befunge/Pinstripe-Display new file mode 120000 index 0000000000..19575058ca --- /dev/null +++ b/Lang/Befunge/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Sudoku b/Lang/Befunge/Sudoku new file mode 120000 index 0000000000..fc1dd98746 --- /dev/null +++ b/Lang/Befunge/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Befunge \ No newline at end of file diff --git a/Lang/C++/Count-the-coins b/Lang/C++/Count-the-coins new file mode 120000 index 0000000000..54262a6e1b --- /dev/null +++ b/Lang/C++/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/C++ \ No newline at end of file diff --git a/Lang/C++/Terminal-control-Ringing-the-terminal-bell b/Lang/C++/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..99b1c293aa --- /dev/null +++ b/Lang/C++/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/C++ \ No newline at end of file diff --git a/Lang/C++/Zhang-Suen-thinning-algorithm b/Lang/C++/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..602f125a70 --- /dev/null +++ b/Lang/C++/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Longest-increasing-subsequence b/Lang/C-sharp/Longest-increasing-subsequence new file mode 120000 index 0000000000..865c569e57 --- /dev/null +++ b/Lang/C-sharp/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/C-sharp \ No newline at end of file diff --git a/Lang/COBOL/Use-another-language-to-call-a-function b/Lang/COBOL/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..d6e0801841 --- /dev/null +++ b/Lang/COBOL/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/COBOL \ No newline at end of file diff --git a/Lang/Ceylon/Dinesmans-multiple-dwelling-problem b/Lang/Ceylon/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..505625acc2 --- /dev/null +++ b/Lang/Ceylon/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Dutch-national-flag-problem b/Lang/Ceylon/Dutch-national-flag-problem new file mode 120000 index 0000000000..666bd0c238 --- /dev/null +++ b/Lang/Ceylon/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Fractal-tree b/Lang/Ceylon/Fractal-tree new file mode 120000 index 0000000000..b3028ba31a --- /dev/null +++ b/Lang/Ceylon/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Ceylon \ No newline at end of file diff --git a/Lang/Crystal/Combinations b/Lang/Crystal/Combinations new file mode 120000 index 0000000000..8d31c4a681 --- /dev/null +++ b/Lang/Crystal/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Flatten-a-list b/Lang/Crystal/Flatten-a-list new file mode 120000 index 0000000000..34605151f7 --- /dev/null +++ b/Lang/Crystal/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hailstone-sequence b/Lang/Crystal/Hailstone-sequence new file mode 120000 index 0000000000..227464f110 --- /dev/null +++ b/Lang/Crystal/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Crystal \ No newline at end of file diff --git a/Lang/Crystal/JSON b/Lang/Crystal/JSON new file mode 120000 index 0000000000..9b4132ba47 --- /dev/null +++ b/Lang/Crystal/JSON @@ -0,0 +1 @@ +../../Task/JSON/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Number-reversal-game b/Lang/Crystal/Number-reversal-game new file mode 120000 index 0000000000..0145396ddd --- /dev/null +++ b/Lang/Crystal/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Palindrome-detection b/Lang/Crystal/Palindrome-detection new file mode 120000 index 0000000000..fbfbc73018 --- /dev/null +++ b/Lang/Crystal/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Pick-random-element b/Lang/Crystal/Pick-random-element new file mode 120000 index 0000000000..16afd14838 --- /dev/null +++ b/Lang/Crystal/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Repeat-a-string b/Lang/Crystal/Repeat-a-string new file mode 120000 index 0000000000..ebe4863849 --- /dev/null +++ b/Lang/Crystal/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-an-integer-array b/Lang/Crystal/Sort-an-integer-array new file mode 120000 index 0000000000..0299152820 --- /dev/null +++ b/Lang/Crystal/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Crystal/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..1ec1cd5c89 --- /dev/null +++ b/Lang/Crystal/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sum-and-product-of-an-array b/Lang/Crystal/Sum-and-product-of-an-array new file mode 120000 index 0000000000..aeb9d36ebd --- /dev/null +++ b/Lang/Crystal/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sum-multiples-of-3-and-5 b/Lang/Crystal/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..d1ae495698 --- /dev/null +++ b/Lang/Crystal/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sum-of-squares b/Lang/Crystal/Sum-of-squares new file mode 120000 index 0000000000..d340fdf27e --- /dev/null +++ b/Lang/Crystal/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Crystal \ No newline at end of file diff --git a/Lang/Dart/Leap-year b/Lang/Dart/Leap-year new file mode 120000 index 0000000000..a584da204a --- /dev/null +++ b/Lang/Dart/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Dart \ No newline at end of file diff --git a/Lang/Elena/00DESCRIPTION b/Lang/Elena/00DESCRIPTION index 77f6f39b97..c6835bacac 100644 --- a/Lang/Elena/00DESCRIPTION +++ b/Lang/Elena/00DESCRIPTION @@ -15,27 +15,27 @@ ELENA is a general-purpose, object-oriented, polymorphic language with late bind To create a simple console program we have to declare the program symbol in the project root namespace: - public program = + public program [ - ]. + ] Everything in ELENA is an object. To interact with it we have to send a message. The simplest (generic, i.e. without an explicit signature) message consists of an action and a parameter list. The statement should be terminated by a dot (ELENA is inspired by Smalltalk and uses its syntax notations). - public program = + public program [ - console writeLine("Hello!"). - ]. + console writeLine("Hello!") + ] In our example the action is writeLine and the parameter list consists of a single literal constant. The message target is console object (implementing input / output operations with a program console). Several message operations can be done in a single statement separated by a semicolon: - public program = + public program [ console writeLine("Hello!"); writeLine("How are you?"). - ]. + ] The result will be: @@ -44,10 +44,10 @@ The result will be: We may read a user input by sending readLine message without parameters: - public program = + public program [ console write("What is your name:"); writeLine("Hello " + console readLine). - ]. + ] The result will be: @@ -66,22 +66,22 @@ where we declare a variable myVariable and initialize it with a literal constant The assigning value can be an expression itself: - public program = + public program [ console writeLine("Hello!"); writeLine("How are you?"). var s := console readLine. - ]. + ] ELENA is a dynamic language and in normal case we may not specify the variable type: - public program = + public program [ var s := "Hello". console writeLine(s). s := 2. console writeLine(s). - ]. + ] The output will be: @@ -133,7 +133,7 @@ Boolean type is used in conditional operations and may accept only two Boolean l import extensions. - public program = + public program [ bool b1 := true. bool b2 := false. @@ -142,7 +142,7 @@ Boolean type is used in conditional operations and may accept only two Boolean l console printLine(b2,"==",b2," is ",b2==b2). console printLine(b1,"==",b2," is ",b1==b2). console printLine(b2,"==",b1," is ",b1==b2). - ]. + ] Note that implicit extension method - extensions'outputOp.printLine[] - was used to simplify the output operations. diff --git a/Lang/Elm/00DESCRIPTION b/Lang/Elm/00DESCRIPTION index 7cc7e43bbd..67674dd63b 100644 --- a/Lang/Elm/00DESCRIPTION +++ b/Lang/Elm/00DESCRIPTION @@ -7,7 +7,7 @@ |LCT = yes }} -'''Elm''' is a programming language for developping browser-based applications and graphical user interfaces that strictly adheres to the functional paradigm. This means that Elm does not rely on mutability or destructive updates. +'''Elm''' is a programming language for developing browser-based applications and graphical user interfaces that strictly adheres to the functional paradigm. This means that Elm does not rely on mutability or destructive updates. In order to run web applications, Elm compiles to Javascript, HTML, and CSS. The Functional model-view-update architecture is used in lieu of event handlers and callbacks. For right markup, Elm allows to embed Markdown directly in the language. diff --git a/Lang/Emacs-Lisp/99-Bottles-of-Beer b/Lang/Emacs-Lisp/99-Bottles-of-Beer new file mode 120000 index 0000000000..62dc5891f6 --- /dev/null +++ b/Lang/Emacs-Lisp/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Character-codes b/Lang/Emacs-Lisp/Character-codes new file mode 120000 index 0000000000..89687ab57b --- /dev/null +++ b/Lang/Emacs-Lisp/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Copy-a-string b/Lang/Emacs-Lisp/Copy-a-string new file mode 120000 index 0000000000..febae5aad9 --- /dev/null +++ b/Lang/Emacs-Lisp/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Create-a-file b/Lang/Emacs-Lisp/Create-a-file new file mode 120000 index 0000000000..c2dba20f7b --- /dev/null +++ b/Lang/Emacs-Lisp/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Delete-a-file b/Lang/Emacs-Lisp/Delete-a-file new file mode 120000 index 0000000000..2f1ec27e89 --- /dev/null +++ b/Lang/Emacs-Lisp/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Execute-a-system-command b/Lang/Emacs-Lisp/Execute-a-system-command new file mode 120000 index 0000000000..9f47b33257 --- /dev/null +++ b/Lang/Emacs-Lisp/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/FizzBuzz b/Lang/Emacs-Lisp/FizzBuzz new file mode 120000 index 0000000000..7b3555f3b5 --- /dev/null +++ b/Lang/Emacs-Lisp/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Guess-the-number b/Lang/Emacs-Lisp/Guess-the-number new file mode 120000 index 0000000000..2307d99d03 --- /dev/null +++ b/Lang/Emacs-Lisp/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Guess-the-number-With-feedback b/Lang/Emacs-Lisp/Guess-the-number-With-feedback new file mode 120000 index 0000000000..5a64b8fe00 --- /dev/null +++ b/Lang/Emacs-Lisp/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Josephus-problem b/Lang/Emacs-Lisp/Josephus-problem new file mode 120000 index 0000000000..64d53d8476 --- /dev/null +++ b/Lang/Emacs-Lisp/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Factor/Aliquot-sequence-classifications b/Lang/Factor/Aliquot-sequence-classifications new file mode 120000 index 0000000000..b7b6c52c58 --- /dev/null +++ b/Lang/Factor/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Factor \ No newline at end of file diff --git a/Lang/Factor/Define-a-primitive-data-type b/Lang/Factor/Define-a-primitive-data-type new file mode 120000 index 0000000000..6c06b8f1e8 --- /dev/null +++ b/Lang/Factor/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Factor \ No newline at end of file diff --git a/Lang/Factor/Identity-matrix b/Lang/Factor/Identity-matrix new file mode 120000 index 0000000000..ae1bd0627f --- /dev/null +++ b/Lang/Factor/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Factor \ No newline at end of file diff --git a/Lang/Factor/Object-serialization b/Lang/Factor/Object-serialization new file mode 120000 index 0000000000..196fe7a9b4 --- /dev/null +++ b/Lang/Factor/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Factor \ No newline at end of file diff --git a/Lang/Factor/Quaternion-type b/Lang/Factor/Quaternion-type new file mode 120000 index 0000000000..47f0548ea8 --- /dev/null +++ b/Lang/Factor/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Factor \ No newline at end of file diff --git a/Lang/Factor/Queue-Usage b/Lang/Factor/Queue-Usage new file mode 120000 index 0000000000..605effa02a --- /dev/null +++ b/Lang/Factor/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Factor \ No newline at end of file diff --git a/Lang/Factor/Rep-string b/Lang/Factor/Rep-string new file mode 120000 index 0000000000..f67e820d7d --- /dev/null +++ b/Lang/Factor/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Factor \ No newline at end of file diff --git a/Lang/Factor/SHA-256 b/Lang/Factor/SHA-256 new file mode 120000 index 0000000000..7f52fd8640 --- /dev/null +++ b/Lang/Factor/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Factor \ No newline at end of file diff --git a/Lang/Factor/Stern-Brocot-sequence b/Lang/Factor/Stern-Brocot-sequence new file mode 120000 index 0000000000..5cfa153922 --- /dev/null +++ b/Lang/Factor/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Factor \ No newline at end of file diff --git a/Lang/Factor/Strip-comments-from-a-string b/Lang/Factor/Strip-comments-from-a-string new file mode 120000 index 0000000000..6673b8a8ed --- /dev/null +++ b/Lang/Factor/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Factor \ No newline at end of file diff --git a/Lang/Forth/Define-a-primitive-data-type b/Lang/Forth/Define-a-primitive-data-type new file mode 120000 index 0000000000..ae326051f1 --- /dev/null +++ b/Lang/Forth/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Forth \ No newline at end of file diff --git a/Lang/Forth/Dutch-national-flag-problem b/Lang/Forth/Dutch-national-flag-problem new file mode 120000 index 0000000000..ffd8469ad0 --- /dev/null +++ b/Lang/Forth/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Forth \ No newline at end of file diff --git a/Lang/Forth/Metaprogramming b/Lang/Forth/Metaprogramming new file mode 120000 index 0000000000..b7d6700b5b --- /dev/null +++ b/Lang/Forth/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Forth \ No newline at end of file diff --git a/Lang/Forth/Strip-comments-from-a-string b/Lang/Forth/Strip-comments-from-a-string new file mode 120000 index 0000000000..cf768dc597 --- /dev/null +++ b/Lang/Forth/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Coloured-text b/Lang/Forth/Terminal-control-Coloured-text new file mode 120000 index 0000000000..91b9c27b59 --- /dev/null +++ b/Lang/Forth/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Cursor-movement b/Lang/Forth/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..2002f5b06e --- /dev/null +++ b/Lang/Forth/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Forth \ No newline at end of file diff --git a/Lang/FreeBASIC/Check-Machin-like-formulas b/Lang/FreeBASIC/Check-Machin-like-formulas new file mode 120000 index 0000000000..465e258511 --- /dev/null +++ b/Lang/FreeBASIC/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Evolutionary-algorithm b/Lang/FreeBASIC/Evolutionary-algorithm new file mode 120000 index 0000000000..20bf7c0fdf --- /dev/null +++ b/Lang/FreeBASIC/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Hofstadter-Conway-$10,000-sequence b/Lang/FreeBASIC/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..c85f0405f7 --- /dev/null +++ b/Lang/FreeBASIC/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Image-noise b/Lang/FreeBASIC/Image-noise new file mode 120000 index 0000000000..3d87ac7c47 --- /dev/null +++ b/Lang/FreeBASIC/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Modular-inverse b/Lang/FreeBASIC/Modular-inverse new file mode 120000 index 0000000000..e118b44614 --- /dev/null +++ b/Lang/FreeBASIC/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pi b/Lang/FreeBASIC/Pi new file mode 120000 index 0000000000..4b7a27b994 --- /dev/null +++ b/Lang/FreeBASIC/Pi @@ -0,0 +1 @@ +../../Task/Pi/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Resistor-mesh b/Lang/FreeBASIC/Resistor-mesh new file mode 120000 index 0000000000..72ab98fdc7 --- /dev/null +++ b/Lang/FreeBASIC/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/FreeBASIC \ No newline at end of file diff --git a/Lang/Futhark/Apply-a-callback-to-an-array b/Lang/Futhark/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..adad5dc876 --- /dev/null +++ b/Lang/Futhark/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Futhark \ No newline at end of file diff --git a/Lang/Go/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Go/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..c5890cc072 --- /dev/null +++ b/Lang/Go/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Go \ No newline at end of file diff --git a/Lang/Go/Bitwise-IO b/Lang/Go/Bitwise-IO new file mode 120000 index 0000000000..dea68c4ccf --- /dev/null +++ b/Lang/Go/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Go \ No newline at end of file diff --git a/Lang/Go/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Go/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..cbafc8eb43 --- /dev/null +++ b/Lang/Go/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go \ No newline at end of file diff --git a/Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- b/Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- new file mode 120000 index 0000000000..c87171a72e --- /dev/null +++ b/Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go \ No newline at end of file diff --git a/Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- b/Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- new file mode 120000 index 0000000000..307f3f5451 --- /dev/null +++ b/Lang/Go/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go \ No newline at end of file diff --git a/Lang/Go/First-class-environments b/Lang/Go/First-class-environments new file mode 120000 index 0000000000..e4762546eb --- /dev/null +++ b/Lang/Go/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Go \ No newline at end of file diff --git a/Lang/Go/Galton-box-animation b/Lang/Go/Galton-box-animation new file mode 120000 index 0000000000..60187adcfc --- /dev/null +++ b/Lang/Go/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Go \ No newline at end of file diff --git a/Lang/Go/Inverted-syntax b/Lang/Go/Inverted-syntax new file mode 120000 index 0000000000..cac5a1eceb --- /dev/null +++ b/Lang/Go/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Go \ No newline at end of file diff --git a/Lang/Go/Jensens-Device b/Lang/Go/Jensens-Device new file mode 120000 index 0000000000..d12942b079 --- /dev/null +++ b/Lang/Go/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Go \ No newline at end of file diff --git a/Lang/Go/Solve-a-Hidato-puzzle b/Lang/Go/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..d1918de413 --- /dev/null +++ b/Lang/Go/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Solve-a-Hopido-puzzle b/Lang/Go/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..994e822765 --- /dev/null +++ b/Lang/Go/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Solve-a-Numbrix-puzzle b/Lang/Go/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..ffc4893813 --- /dev/null +++ b/Lang/Go/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Preserve-screen b/Lang/Go/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..30316ce076 --- /dev/null +++ b/Lang/Go/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Go \ No newline at end of file diff --git a/Lang/Go/Video-display-modes b/Lang/Go/Video-display-modes new file mode 120000 index 0000000000..5c88d2f2c3 --- /dev/null +++ b/Lang/Go/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Go \ No newline at end of file diff --git a/Lang/Groovy/Integer-sequence b/Lang/Groovy/Integer-sequence new file mode 120000 index 0000000000..84cfa7f843 --- /dev/null +++ b/Lang/Groovy/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Groovy \ No newline at end of file diff --git a/Lang/Java/00DESCRIPTION b/Lang/Java/00DESCRIPTION index e774c36704..7a1836ab77 100644 --- a/Lang/Java/00DESCRIPTION +++ b/Lang/Java/00DESCRIPTION @@ -41,6 +41,7 @@ Useful Java links: * [http://www.java.net java.net] * [http://openjdk.java.net OpenJDK] * [https://hackr.io/tutorials/learn-java Hackr.io] +* [https://reactdom.com/java ReactDOM] ==Todo== [[Reports:Tasks_not_implemented_in_Java]] \ No newline at end of file diff --git a/Lang/Java/QR-decomposition b/Lang/Java/QR-decomposition new file mode 120000 index 0000000000..6727c0afee --- /dev/null +++ b/Lang/Java/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Java \ No newline at end of file diff --git a/Lang/Java/Set-of-real-numbers b/Lang/Java/Set-of-real-numbers new file mode 120000 index 0000000000..a66f5154b6 --- /dev/null +++ b/Lang/Java/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Terminal-control-Preserve-screen b/Lang/Java/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..7877bf33e0 --- /dev/null +++ b/Lang/Java/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Java \ No newline at end of file diff --git a/Lang/K/Digital-root b/Lang/K/Digital-root new file mode 120000 index 0000000000..5d10f44bf6 --- /dev/null +++ b/Lang/K/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/K \ No newline at end of file diff --git a/Lang/K/Even-or-odd b/Lang/K/Even-or-odd new file mode 120000 index 0000000000..73aabe8e67 --- /dev/null +++ b/Lang/K/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/K \ No newline at end of file diff --git a/Lang/K/Harshad-or-Niven-series b/Lang/K/Harshad-or-Niven-series new file mode 120000 index 0000000000..1fb6025473 --- /dev/null +++ b/Lang/K/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/K \ No newline at end of file diff --git a/Lang/K/Hello-world-Text b/Lang/K/Hello-world-Text new file mode 120000 index 0000000000..aa64b5d31a --- /dev/null +++ b/Lang/K/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/K \ No newline at end of file diff --git a/Lang/K/Hostname b/Lang/K/Hostname new file mode 120000 index 0000000000..7ec5e2e255 --- /dev/null +++ b/Lang/K/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/K \ No newline at end of file diff --git a/Lang/K/Loops-While b/Lang/K/Loops-While new file mode 120000 index 0000000000..d180cdb514 --- /dev/null +++ b/Lang/K/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/K \ No newline at end of file diff --git a/Lang/K/Reverse-a-string b/Lang/K/Reverse-a-string new file mode 120000 index 0000000000..c48b912019 --- /dev/null +++ b/Lang/K/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/K \ No newline at end of file diff --git a/Lang/K/String-concatenation b/Lang/K/String-concatenation new file mode 120000 index 0000000000..abce1fdd53 --- /dev/null +++ b/Lang/K/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/K \ No newline at end of file diff --git a/Lang/K/String-length b/Lang/K/String-length new file mode 120000 index 0000000000..6ed1e9d2d3 --- /dev/null +++ b/Lang/K/String-length @@ -0,0 +1 @@ +../../Task/String-length/K \ No newline at end of file diff --git a/Lang/K/String-prepend b/Lang/K/String-prepend new file mode 120000 index 0000000000..d618cbdcbe --- /dev/null +++ b/Lang/K/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/K \ No newline at end of file diff --git a/Lang/K/Substring-Top-and-tail b/Lang/K/Substring-Top-and-tail new file mode 120000 index 0000000000..febe6ba8c6 --- /dev/null +++ b/Lang/K/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/K \ No newline at end of file diff --git a/Lang/Lambdatalk/Hello-world-Text b/Lang/Lambdatalk/Hello-world-Text new file mode 120000 index 0000000000..49821676df --- /dev/null +++ b/Lang/Lambdatalk/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Lambdatalk \ No newline at end of file diff --git a/Lang/Lua/00DESCRIPTION b/Lang/Lua/00DESCRIPTION index e9b2b8d8e6..54480e0394 100644 --- a/Lang/Lua/00DESCRIPTION +++ b/Lang/Lua/00DESCRIPTION @@ -23,7 +23,7 @@ As a result, the base language is lightβ€”in fact, the full reference interprete ==Unimplemented programming tasks== Output from [[Find_unimplemented_tasks]] : -Lua has 334 unimplemented programming tasks: +Lua has 338 unimplemented programming tasks: 15 puzzle solver 2048 4-rings or 4-squares puzzle @@ -32,6 +32,7 @@ Lua has 334 unimplemented programming tasks: Active Directory/Connect Active Directory/Search for a user Active object + Address of a variable Aliquot sequence classifications Anagrams/Deranged anagrams Animation @@ -82,12 +83,14 @@ Lua has 334 unimplemented programming tasks: Combinations and permutations Commatizing numbers Compare sorting algorithms' performance + Compile-time calculation Compiler/AST interpreter Compiler/code generator Compiler/lexical analyzer Compiler/syntax analyzer Compiler/virtual machine interpreter Conjugate transpose + Constrained genericity Constrained random points on a circle Continued fraction Continued fraction/Arithmetic/Construct from rational number @@ -95,7 +98,6 @@ Lua has 334 unimplemented programming tasks: Create a file on magnetic tape Create an object at a given address Cut a rectangle - DNS query Death Star Deconvolution/2D+ Define a primitive data type @@ -131,26 +133,26 @@ Lua has 334 unimplemented programming tasks: Find largest left truncatable prime in a given base Find palindromic numbers in both binary and ternary bases Floyd-Warshall algorithm + Four is the number of letters in the ... Fractran Function frequency - GUI/Maximum window dimensions GUI component interaction GUI enabling/disabling of controls + GUI/Maximum window dimensions Galton box animation Gaussian elimination Go Fish Greyscale bars/Display - HTTPS - HTTPS/Authenticated HTTPS/Client-authenticated Handle a signal Hash join Hello world/Line printer Hello world/Web server Hickerson series of almost integers - Hofstadter-Conway $10,000 sequence + History variables Hofstadter Figure-Figure sequences Hofstadter Q sequence + Hofstadter-Conway $10,000 sequence Honeycombs Horizontal sundial calculations Host introspection @@ -167,7 +169,6 @@ Lua has 334 unimplemented programming tasks: Julia set K-d tree K-means++ clustering - Kernighans large earthquake problem Keyboard input/Flush the keyboard buffer Keyboard input/Keypress check Keyboard input/Obtain a Y or N response @@ -213,6 +214,7 @@ Lua has 334 unimplemented programming tasks: Object serialization Odd word problem Old lady swallowed a fly + OpenWebNet Password Paraffins Parallel Brute Force Parallel calculations @@ -249,6 +251,7 @@ Lua has 334 unimplemented programming tasks: Pythagorean triples QR decomposition RCRPG + RPG Attributes Generator RSA code Ramer-Douglas-Peucker line simplification Random number generator (device) @@ -265,7 +268,6 @@ Lua has 334 unimplemented programming tasks: Retrieve and search chat history Rosetta Code/Count examples Rosetta Code/Find bare lang tags - Rosetta Code/Find unimplemented tasks Rosetta Code/Rank languages by popularity Runge-Kutta method S-Expressions @@ -275,8 +277,9 @@ Lua has 334 unimplemented programming tasks: Safe addition Sailors, coconuts and a monkey problem Same Fringe - Scope/Function names and labels Scope modifiers + Scope/Function names and labels + Sequence of primorial primes Set consolidation Set of real numbers Set puzzle @@ -300,6 +303,7 @@ Lua has 334 unimplemented programming tasks: Sorting algorithms/Strand sort Sparkline in unicode Speech synthesis + Spinning rod animation/Text Start from a main routine State name puzzle Stream Merge @@ -336,9 +340,9 @@ Lua has 334 unimplemented programming tasks: Use another language to call a function User input/Graphical Vampire number - Variable-length quantity Variable size/Get Variable size/Set + Variable-length quantity Verify distribution uniformity/Chi-squared test Verify distribution uniformity/Naive Video display modes diff --git a/Lang/Lua/DNS-query b/Lang/Lua/DNS-query new file mode 120000 index 0000000000..a0ab5d1c1f --- /dev/null +++ b/Lang/Lua/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Lua \ No newline at end of file diff --git a/Lang/Lua/HTTPS b/Lang/Lua/HTTPS new file mode 120000 index 0000000000..d1caff47f0 --- /dev/null +++ b/Lang/Lua/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Lua \ No newline at end of file diff --git a/Lang/Lua/HTTPS-Authenticated b/Lang/Lua/HTTPS-Authenticated new file mode 120000 index 0000000000..12b2e7345a --- /dev/null +++ b/Lang/Lua/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Lua \ No newline at end of file diff --git a/Lang/Maple/Almost-prime b/Lang/Maple/Almost-prime new file mode 120000 index 0000000000..dafd6b33ab --- /dev/null +++ b/Lang/Maple/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Maple \ No newline at end of file diff --git a/Lang/Maple/Hough-transform b/Lang/Maple/Hough-transform new file mode 120000 index 0000000000..b41e4b7874 --- /dev/null +++ b/Lang/Maple/Hough-transform @@ -0,0 +1 @@ +../../Task/Hough-transform/Maple \ No newline at end of file diff --git a/Lang/Maple/I-before-E-except-after-C b/Lang/Maple/I-before-E-except-after-C new file mode 120000 index 0000000000..24c603bac9 --- /dev/null +++ b/Lang/Maple/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Maple \ No newline at end of file diff --git a/Lang/Maple/Image-convolution b/Lang/Maple/Image-convolution new file mode 120000 index 0000000000..361a9b3b17 --- /dev/null +++ b/Lang/Maple/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/Maple \ No newline at end of file diff --git a/Lang/Maple/Knapsack-problem-0-1 b/Lang/Maple/Knapsack-problem-0-1 new file mode 120000 index 0000000000..b2ff7a1a24 --- /dev/null +++ b/Lang/Maple/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Maple \ No newline at end of file diff --git a/Lang/Maple/Order-two-numerical-lists b/Lang/Maple/Order-two-numerical-lists new file mode 120000 index 0000000000..f0255eda8b --- /dev/null +++ b/Lang/Maple/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Maple \ No newline at end of file diff --git a/Lang/Maple/Phrase-reversals b/Lang/Maple/Phrase-reversals new file mode 120000 index 0000000000..ae181465e1 --- /dev/null +++ b/Lang/Maple/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Maple \ No newline at end of file diff --git a/Lang/Maple/Plot-coordinate-pairs b/Lang/Maple/Plot-coordinate-pairs new file mode 120000 index 0000000000..72efdae0b6 --- /dev/null +++ b/Lang/Maple/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Maple \ No newline at end of file diff --git a/Lang/Maple/Queue-Usage b/Lang/Maple/Queue-Usage new file mode 120000 index 0000000000..d85470f3e8 --- /dev/null +++ b/Lang/Maple/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Maple \ No newline at end of file diff --git a/Lang/Maple/Range-extraction b/Lang/Maple/Range-extraction new file mode 120000 index 0000000000..b4ecd1a817 --- /dev/null +++ b/Lang/Maple/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Maple \ No newline at end of file diff --git a/Lang/Maple/Read-a-specific-line-from-a-file b/Lang/Maple/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..ebcfc533a2 --- /dev/null +++ b/Lang/Maple/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Maple \ No newline at end of file diff --git a/Lang/Maple/Reverse-words-in-a-string b/Lang/Maple/Reverse-words-in-a-string new file mode 120000 index 0000000000..99690e9139 --- /dev/null +++ b/Lang/Maple/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Maple \ No newline at end of file diff --git a/Lang/Maple/Short-circuit-evaluation b/Lang/Maple/Short-circuit-evaluation new file mode 120000 index 0000000000..612a37ee51 --- /dev/null +++ b/Lang/Maple/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Maple \ No newline at end of file diff --git a/Lang/Maple/Sort-disjoint-sublist b/Lang/Maple/Sort-disjoint-sublist new file mode 120000 index 0000000000..557a81f30d --- /dev/null +++ b/Lang/Maple/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Pancake-sort b/Lang/Maple/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..fc44056d2d --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Vector-products b/Lang/Maple/Vector-products new file mode 120000 index 0000000000..22c24bc796 --- /dev/null +++ b/Lang/Maple/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Maple \ No newline at end of file diff --git a/Lang/Mathematica/MD4 b/Lang/Mathematica/MD4 new file mode 120000 index 0000000000..89f8ffcde9 --- /dev/null +++ b/Lang/Mathematica/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/RIPEMD-160 b/Lang/Mathematica/RIPEMD-160 new file mode 120000 index 0000000000..210a84478d --- /dev/null +++ b/Lang/Mathematica/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Mathematica \ No newline at end of file diff --git a/Lang/Modula-2/Binary-digits b/Lang/Modula-2/Binary-digits new file mode 120000 index 0000000000..fcb321c51f --- /dev/null +++ b/Lang/Modula-2/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Modula-2 \ No newline at end of file diff --git a/Lang/NewLISP/Ackermann-function b/Lang/NewLISP/Ackermann-function new file mode 120000 index 0000000000..29a3ab2ae4 --- /dev/null +++ b/Lang/NewLISP/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Detect-division-by-zero b/Lang/NewLISP/Detect-division-by-zero new file mode 120000 index 0000000000..09378a641b --- /dev/null +++ b/Lang/NewLISP/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Null-object b/Lang/NewLISP/Null-object new file mode 120000 index 0000000000..14cb161161 --- /dev/null +++ b/Lang/NewLISP/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/NewLISP \ No newline at end of file diff --git a/Lang/Nial/Zero-to-the-zero-power b/Lang/Nial/Zero-to-the-zero-power new file mode 120000 index 0000000000..7993d98c3e --- /dev/null +++ b/Lang/Nial/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Nial \ No newline at end of file diff --git a/Lang/Ol/Matrix-multiplication b/Lang/Ol/Matrix-multiplication new file mode 120000 index 0000000000..2f923b35de --- /dev/null +++ b/Lang/Ol/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Ol \ No newline at end of file diff --git a/Lang/PARI-GP/00DESCRIPTION b/Lang/PARI-GP/00DESCRIPTION index 573c623854..21b73ea162 100644 --- a/Lang/PARI-GP/00DESCRIPTION +++ b/Lang/PARI-GP/00DESCRIPTION @@ -57,6 +57,11 @@ PARI/GP can be used in many different operating systems. For other systems, see | [https://apps.fedoraproject.org/packages/pari-gp Fedora packages] | sudo dnf install pari-gp |- +| Arch +| package manager +| [https://www.archlinux.org/packages/community/x86_64/pari/ Arch packages] +| sudo pacman -S pari +|- | RHEL/CentOS | package manager | diff --git a/Lang/PHP/Strip-block-comments b/Lang/PHP/Strip-block-comments new file mode 120000 index 0000000000..669304c826 --- /dev/null +++ b/Lang/PHP/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/PHP \ No newline at end of file diff --git a/Lang/PL-I/Jump-anywhere b/Lang/PL-I/Jump-anywhere new file mode 120000 index 0000000000..0ca40a4bf0 --- /dev/null +++ b/Lang/PL-I/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/PL-I \ No newline at end of file diff --git a/Lang/Perl/Solve-a-Numbrix-puzzle b/Lang/Perl/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..a62987d728 --- /dev/null +++ b/Lang/Perl/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Perl \ No newline at end of file diff --git a/Lang/Phix/Bitcoin-address-validation b/Lang/Phix/Bitcoin-address-validation new file mode 120000 index 0000000000..fc9c43cb6c --- /dev/null +++ b/Lang/Phix/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Phix \ No newline at end of file diff --git a/Lang/Phix/Bitcoin-public-point-to-address b/Lang/Phix/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..58b94c353b --- /dev/null +++ b/Lang/Phix/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Phix \ No newline at end of file diff --git a/Lang/Phix/Delegates b/Lang/Phix/Delegates new file mode 120000 index 0000000000..df72f53574 --- /dev/null +++ b/Lang/Phix/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Phix \ No newline at end of file diff --git a/Lang/Phix/Digital-root-Multiplicative-digital-root b/Lang/Phix/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..af7a305341 --- /dev/null +++ b/Lang/Phix/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Phix \ No newline at end of file diff --git a/Lang/Phix/HTTP b/Lang/Phix/HTTP new file mode 120000 index 0000000000..25ad186f8b --- /dev/null +++ b/Lang/Phix/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Phix \ No newline at end of file diff --git a/Lang/Phix/HTTPS b/Lang/Phix/HTTPS new file mode 120000 index 0000000000..7362e42cee --- /dev/null +++ b/Lang/Phix/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Phix \ No newline at end of file diff --git a/Lang/Phix/HTTPS-Authenticated b/Lang/Phix/HTTPS-Authenticated new file mode 120000 index 0000000000..d94110f147 --- /dev/null +++ b/Lang/Phix/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Phix \ No newline at end of file diff --git a/Lang/Phix/HTTPS-Client-authenticated b/Lang/Phix/HTTPS-Client-authenticated new file mode 120000 index 0000000000..ac61134afd --- /dev/null +++ b/Lang/Phix/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Phix \ No newline at end of file diff --git a/Lang/Phix/History-variables b/Lang/Phix/History-variables new file mode 120000 index 0000000000..273625d527 --- /dev/null +++ b/Lang/Phix/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Phix \ No newline at end of file diff --git a/Lang/Phix/Huffman-coding b/Lang/Phix/Huffman-coding new file mode 120000 index 0000000000..fb52b2dd3f --- /dev/null +++ b/Lang/Phix/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Phix \ No newline at end of file diff --git a/Lang/Phix/Keyboard-macros b/Lang/Phix/Keyboard-macros new file mode 120000 index 0000000000..53c66e1cff --- /dev/null +++ b/Lang/Phix/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Phix \ No newline at end of file diff --git a/Lang/Phix/Knuths-algorithm-S b/Lang/Phix/Knuths-algorithm-S new file mode 120000 index 0000000000..1f38123be8 --- /dev/null +++ b/Lang/Phix/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Phix \ No newline at end of file diff --git a/Lang/Phix/LU-decomposition b/Lang/Phix/LU-decomposition new file mode 120000 index 0000000000..f8fb43cd8f --- /dev/null +++ b/Lang/Phix/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Phix \ No newline at end of file diff --git a/Lang/Phix/MD4 b/Lang/Phix/MD4 new file mode 120000 index 0000000000..b953e7d57f --- /dev/null +++ b/Lang/Phix/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Phix \ No newline at end of file diff --git a/Lang/Phix/Main-step-of-GOST-28147-89 b/Lang/Phix/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..2447b051be --- /dev/null +++ b/Lang/Phix/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Phix \ No newline at end of file diff --git a/Lang/Phix/Metronome b/Lang/Phix/Metronome new file mode 120000 index 0000000000..f190448f2e --- /dev/null +++ b/Lang/Phix/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Phix \ No newline at end of file diff --git a/Lang/Phix/Minesweeper-game b/Lang/Phix/Minesweeper-game new file mode 120000 index 0000000000..9f7e6af8d7 --- /dev/null +++ b/Lang/Phix/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Phix \ No newline at end of file diff --git a/Lang/Phix/Nautical-bell b/Lang/Phix/Nautical-bell new file mode 120000 index 0000000000..685a87f59b --- /dev/null +++ b/Lang/Phix/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Phix \ No newline at end of file diff --git a/Lang/Phix/Parametrized-SQL-statement b/Lang/Phix/Parametrized-SQL-statement new file mode 120000 index 0000000000..499522211a --- /dev/null +++ b/Lang/Phix/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Phix \ No newline at end of file diff --git a/Lang/Phix/Pascals-triangle-Puzzle b/Lang/Phix/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..2044a99191 --- /dev/null +++ b/Lang/Phix/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Phix \ No newline at end of file diff --git a/Lang/Phix/RIPEMD-160 b/Lang/Phix/RIPEMD-160 new file mode 120000 index 0000000000..6f1a61d55d --- /dev/null +++ b/Lang/Phix/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Phix \ No newline at end of file diff --git a/Lang/Phix/Random-number-generator--device- b/Lang/Phix/Random-number-generator--device- new file mode 120000 index 0000000000..45e3b31431 --- /dev/null +++ b/Lang/Phix/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Phix \ No newline at end of file diff --git a/Lang/Phix/Respond-to-an-unknown-method-call b/Lang/Phix/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..d5f6108f88 --- /dev/null +++ b/Lang/Phix/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Phix \ No newline at end of file diff --git a/Lang/Phix/SHA-1 b/Lang/Phix/SHA-1 new file mode 120000 index 0000000000..b95b39bf4c --- /dev/null +++ b/Lang/Phix/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Phix \ No newline at end of file diff --git a/Lang/Phix/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Phix/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..bf4070d360 --- /dev/null +++ b/Lang/Phix/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Phix \ No newline at end of file diff --git a/Lang/Phix/Table-creation-Postal-addresses b/Lang/Phix/Table-creation-Postal-addresses new file mode 120000 index 0000000000..f9d33edb5a --- /dev/null +++ b/Lang/Phix/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Preserve-screen b/Lang/Phix/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..e540e84aa1 --- /dev/null +++ b/Lang/Phix/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Unicode-output b/Lang/Phix/Terminal-control-Unicode-output new file mode 120000 index 0000000000..93c326d4b9 --- /dev/null +++ b/Lang/Phix/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Phix \ No newline at end of file diff --git a/Lang/Phix/Video-display-modes b/Lang/Phix/Video-display-modes new file mode 120000 index 0000000000..e6245a129f --- /dev/null +++ b/Lang/Phix/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Phix \ No newline at end of file diff --git a/Lang/Python/99-Bottles-of-Beer b/Lang/Python/99-Bottles-of-Beer new file mode 120000 index 0000000000..7f8b6fa2de --- /dev/null +++ b/Lang/Python/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Python \ No newline at end of file diff --git a/Lang/Python/Bitmap-Histogram b/Lang/Python/Bitmap-Histogram new file mode 120000 index 0000000000..8487bc20be --- /dev/null +++ b/Lang/Python/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Python \ No newline at end of file diff --git a/Lang/REXX/00DESCRIPTION b/Lang/REXX/00DESCRIPTION index 33d950dd4e..05071df6e0 100644 --- a/Lang/REXX/00DESCRIPTION +++ b/Lang/REXX/00DESCRIPTION @@ -8,8 +8,11 @@ |checking=dynamic |parampass=value}} {{Wikipedia|REXX}} + + REXX (REstructured eXtended eXecutor) is an interpreted programming language which was developed at IBM.   It is a structured high-level programming language which was designed to be both easy to learn and easy to read.   Both proprietary and open source interpreters for REXX are available on a wide range of computing platforms, and compilers are available for IBM mainframes. + * '''[[wp:ARexx|ARexx]]''' is a classic REXX implementation (with extensions) for the AmigaOS, given in bundle since AmigaOS 2.   (Regina REXX has specific support for the extended functions that were introduced in ARexx.)   ARexx was written in 1987 by William S. Hawes. * '''[[Brexx]]''' a classic REXX written by Vassilis N. Vlachoudis, it is free and it's open source and available under the GNU General Public License. diff --git a/Lang/Ring/Amb b/Lang/Ring/Amb new file mode 120000 index 0000000000..054928ac3a --- /dev/null +++ b/Lang/Ring/Amb @@ -0,0 +1 @@ +../../Task/Amb/Ring \ No newline at end of file diff --git a/Lang/Ring/CSV-data-manipulation b/Lang/Ring/CSV-data-manipulation new file mode 120000 index 0000000000..802809aa5f --- /dev/null +++ b/Lang/Ring/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Ring \ No newline at end of file diff --git a/Lang/Ring/Calendar---for-REAL-programmers b/Lang/Ring/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..c46a701e0f --- /dev/null +++ b/Lang/Ring/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Ring \ No newline at end of file diff --git a/Lang/Ring/Create-an-HTML-table b/Lang/Ring/Create-an-HTML-table new file mode 120000 index 0000000000..39dda35fc9 --- /dev/null +++ b/Lang/Ring/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Ring \ No newline at end of file diff --git a/Lang/Ring/Determine-if-only-one-instance-is-running b/Lang/Ring/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..f6941be5e3 --- /dev/null +++ b/Lang/Ring/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/Ring \ No newline at end of file diff --git a/Lang/Ring/Flipping-bits-game b/Lang/Ring/Flipping-bits-game new file mode 120000 index 0000000000..b74a924c17 --- /dev/null +++ b/Lang/Ring/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Ring \ No newline at end of file diff --git a/Lang/Ring/Function-composition b/Lang/Ring/Function-composition new file mode 120000 index 0000000000..e63b2ac6ed --- /dev/null +++ b/Lang/Ring/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Ring \ No newline at end of file diff --git a/Lang/Ring/Inheritance-Multiple b/Lang/Ring/Inheritance-Multiple new file mode 120000 index 0000000000..cf39ee60b1 --- /dev/null +++ b/Lang/Ring/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Ring \ No newline at end of file diff --git a/Lang/Ring/Introspection b/Lang/Ring/Introspection new file mode 120000 index 0000000000..7fd026aea8 --- /dev/null +++ b/Lang/Ring/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Ring \ No newline at end of file diff --git a/Lang/Ring/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Ring/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..b253b6e247 --- /dev/null +++ b/Lang/Ring/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Ring \ No newline at end of file diff --git a/Lang/Ring/Queue-Definition b/Lang/Ring/Queue-Definition new file mode 120000 index 0000000000..dcf9046fb7 --- /dev/null +++ b/Lang/Ring/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Ring \ No newline at end of file diff --git a/Lang/Ring/Stack b/Lang/Ring/Stack new file mode 120000 index 0000000000..a471895a70 --- /dev/null +++ b/Lang/Ring/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ring \ No newline at end of file diff --git a/Lang/Ring/Terminal-control-Hiding-the-cursor b/Lang/Ring/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..9757137481 --- /dev/null +++ b/Lang/Ring/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Ring \ No newline at end of file diff --git a/Lang/Ring/Terminal-control-Preserve-screen b/Lang/Ring/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..7f3c74876b --- /dev/null +++ b/Lang/Ring/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Ring \ No newline at end of file diff --git a/Lang/Rust/Fast-Fourier-transform b/Lang/Rust/Fast-Fourier-transform new file mode 120000 index 0000000000..d498a7cdfb --- /dev/null +++ b/Lang/Rust/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Rust \ No newline at end of file diff --git a/Lang/Scala/Active-Directory-Search-for-a-user b/Lang/Scala/Active-Directory-Search-for-a-user new file mode 120000 index 0000000000..d705b38b40 --- /dev/null +++ b/Lang/Scala/Active-Directory-Search-for-a-user @@ -0,0 +1 @@ +../../Task/Active-Directory-Search-for-a-user/Scala \ No newline at end of file diff --git a/Lang/Scala/Brownian-tree b/Lang/Scala/Brownian-tree new file mode 120000 index 0000000000..bbbe8dbd8f --- /dev/null +++ b/Lang/Scala/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Scala \ No newline at end of file diff --git a/Lang/Scala/Checkpoint-synchronization b/Lang/Scala/Checkpoint-synchronization new file mode 120000 index 0000000000..4d11ae0dad --- /dev/null +++ b/Lang/Scala/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Scala \ No newline at end of file diff --git a/Lang/Scala/Chinese-remainder-theorem b/Lang/Scala/Chinese-remainder-theorem new file mode 120000 index 0000000000..702958d3b9 --- /dev/null +++ b/Lang/Scala/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Scala \ No newline at end of file diff --git a/Lang/Scala/Colour-pinstripe-Display b/Lang/Scala/Colour-pinstripe-Display new file mode 120000 index 0000000000..3a5dfbc46f --- /dev/null +++ b/Lang/Scala/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Scala \ No newline at end of file diff --git a/Lang/Scala/Convert-decimal-number-to-rational b/Lang/Scala/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..57717b1780 --- /dev/null +++ b/Lang/Scala/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Scala \ No newline at end of file diff --git a/Lang/Scala/Deconvolution-1D b/Lang/Scala/Deconvolution-1D new file mode 120000 index 0000000000..760cc093c6 --- /dev/null +++ b/Lang/Scala/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Scala \ No newline at end of file diff --git a/Lang/Scala/Delegates b/Lang/Scala/Delegates new file mode 120000 index 0000000000..8ecbf43a52 --- /dev/null +++ b/Lang/Scala/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Scala \ No newline at end of file diff --git a/Lang/Scala/Determine-if-only-one-instance-is-running b/Lang/Scala/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..02db7696c5 --- /dev/null +++ b/Lang/Scala/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/Scala \ No newline at end of file diff --git a/Lang/Scala/Documentation b/Lang/Scala/Documentation new file mode 120000 index 0000000000..d17e2d35a5 --- /dev/null +++ b/Lang/Scala/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Scala \ No newline at end of file diff --git a/Lang/Scala/Doubly-linked-list-Traversal b/Lang/Scala/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..f467abe4c2 --- /dev/null +++ b/Lang/Scala/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Scala \ No newline at end of file diff --git a/Lang/Scala/Draw-a-cuboid b/Lang/Scala/Draw-a-cuboid new file mode 120000 index 0000000000..2a551a56e2 --- /dev/null +++ b/Lang/Scala/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Scala \ No newline at end of file diff --git a/Lang/Scala/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Scala/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..b2ad83a6e5 --- /dev/null +++ b/Lang/Scala/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Scala \ No newline at end of file diff --git a/Lang/Scala/Horizontal-sundial-calculations b/Lang/Scala/Horizontal-sundial-calculations new file mode 120000 index 0000000000..910f813674 --- /dev/null +++ b/Lang/Scala/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Scala \ No newline at end of file diff --git a/Lang/Scala/Iterated-digits-squaring b/Lang/Scala/Iterated-digits-squaring new file mode 120000 index 0000000000..14d795856f --- /dev/null +++ b/Lang/Scala/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Scala \ No newline at end of file diff --git a/Lang/Scala/Keyboard-macros b/Lang/Scala/Keyboard-macros new file mode 120000 index 0000000000..b8f0c0e2c7 --- /dev/null +++ b/Lang/Scala/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Scala \ No newline at end of file diff --git a/Lang/Scala/Non-continuous-subsequences b/Lang/Scala/Non-continuous-subsequences new file mode 120000 index 0000000000..5179798a7e --- /dev/null +++ b/Lang/Scala/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Scala \ No newline at end of file diff --git a/Lang/Scala/Parametrized-SQL-statement b/Lang/Scala/Parametrized-SQL-statement new file mode 120000 index 0000000000..b6611d7464 --- /dev/null +++ b/Lang/Scala/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Scala \ No newline at end of file diff --git a/Lang/Scala/Permutation-test b/Lang/Scala/Permutation-test new file mode 120000 index 0000000000..39b37d1866 --- /dev/null +++ b/Lang/Scala/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Scala \ No newline at end of file diff --git a/Lang/Scala/Permutations-Rank-of-a-permutation b/Lang/Scala/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..bf447d0086 --- /dev/null +++ b/Lang/Scala/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Scala \ No newline at end of file diff --git a/Lang/Scala/Pinstripe-Display b/Lang/Scala/Pinstripe-Display new file mode 120000 index 0000000000..79fda534ff --- /dev/null +++ b/Lang/Scala/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Scala \ No newline at end of file diff --git a/Lang/Scala/Polymorphism b/Lang/Scala/Polymorphism new file mode 120000 index 0000000000..bbb8c1591b --- /dev/null +++ b/Lang/Scala/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Scala \ No newline at end of file diff --git a/Lang/Scala/Pythagorean-triples b/Lang/Scala/Pythagorean-triples new file mode 120000 index 0000000000..78821a2509 --- /dev/null +++ b/Lang/Scala/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Scala \ No newline at end of file diff --git a/Lang/Scala/QR-decomposition b/Lang/Scala/QR-decomposition new file mode 120000 index 0000000000..96e125a09e --- /dev/null +++ b/Lang/Scala/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Scala \ No newline at end of file diff --git a/Lang/Scala/Seven-sided-dice-from-five-sided-dice b/Lang/Scala/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..d82ba56bc4 --- /dev/null +++ b/Lang/Scala/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Cocktail-sort b/Lang/Scala/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..51cd486dc0 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Gnome-sort b/Lang/Scala/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..a2567c66fd --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Radix-sort b/Lang/Scala/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..89689a00e6 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Text-processing-Max-licenses-in-use b/Lang/Scala/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..02f3f00dd0 --- /dev/null +++ b/Lang/Scala/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Scala \ No newline at end of file diff --git a/Lang/Scala/World-Cup-group-stage b/Lang/Scala/World-Cup-group-stage new file mode 120000 index 0000000000..5857d00032 --- /dev/null +++ b/Lang/Scala/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Scala \ No newline at end of file diff --git a/Lang/Sed/Comma-quibbling b/Lang/Sed/Comma-quibbling new file mode 120000 index 0000000000..84c0bf9737 --- /dev/null +++ b/Lang/Sed/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Sed \ No newline at end of file diff --git a/Lang/Shen/Luhn-test-of-credit-card-numbers b/Lang/Shen/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..cb9f49ea24 --- /dev/null +++ b/Lang/Shen/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Shen \ No newline at end of file diff --git a/Lang/Swift/Averages-Mode b/Lang/Swift/Averages-Mode new file mode 120000 index 0000000000..52c21b9b3e --- /dev/null +++ b/Lang/Swift/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Swift \ No newline at end of file diff --git a/Lang/Swift/Catalan-numbers b/Lang/Swift/Catalan-numbers new file mode 120000 index 0000000000..729bd93156 --- /dev/null +++ b/Lang/Swift/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Swift \ No newline at end of file diff --git a/Lang/Swift/Entropy b/Lang/Swift/Entropy new file mode 120000 index 0000000000..8e0a6b8538 --- /dev/null +++ b/Lang/Swift/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Swift \ No newline at end of file diff --git a/Lang/Swift/Safe-addition b/Lang/Swift/Safe-addition new file mode 120000 index 0000000000..1f4660a0eb --- /dev/null +++ b/Lang/Swift/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Swift \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Inverted-syntax b/Lang/TI-83-BASIC/Inverted-syntax new file mode 120000 index 0000000000..0f3d0ed8d1 --- /dev/null +++ b/Lang/TI-83-BASIC/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/TI-83-BASIC \ No newline at end of file diff --git a/Lang/Transact-SQL/Repeat-a-string b/Lang/Transact-SQL/Repeat-a-string new file mode 120000 index 0000000000..948f753387 --- /dev/null +++ b/Lang/Transact-SQL/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Transact-SQL \ No newline at end of file diff --git a/Lang/VAX-Assembly/100-doors b/Lang/VAX-Assembly/100-doors new file mode 120000 index 0000000000..a2dd20893f --- /dev/null +++ b/Lang/VAX-Assembly/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/CRC-32 b/Lang/VAX-Assembly/CRC-32 new file mode 120000 index 0000000000..0a8ba9dd4d --- /dev/null +++ b/Lang/VAX-Assembly/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Delete-a-file b/Lang/VAX-Assembly/Delete-a-file new file mode 120000 index 0000000000..2bbb1ed7e4 --- /dev/null +++ b/Lang/VAX-Assembly/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Detect-division-by-zero b/Lang/VAX-Assembly/Detect-division-by-zero new file mode 120000 index 0000000000..f1eea2a754 --- /dev/null +++ b/Lang/VAX-Assembly/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Empty-program b/Lang/VAX-Assembly/Empty-program new file mode 120000 index 0000000000..190a5c6fe8 --- /dev/null +++ b/Lang/VAX-Assembly/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Empty-string b/Lang/VAX-Assembly/Empty-string new file mode 120000 index 0000000000..9c355b241a --- /dev/null +++ b/Lang/VAX-Assembly/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Fibonacci-sequence b/Lang/VAX-Assembly/Fibonacci-sequence new file mode 120000 index 0000000000..c58fdcd042 --- /dev/null +++ b/Lang/VAX-Assembly/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/FizzBuzz b/Lang/VAX-Assembly/FizzBuzz new file mode 120000 index 0000000000..ac00a3403c --- /dev/null +++ b/Lang/VAX-Assembly/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Hello-world-Text b/Lang/VAX-Assembly/Hello-world-Text new file mode 120000 index 0000000000..fb60e404d4 --- /dev/null +++ b/Lang/VAX-Assembly/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Loops-For-with-a-specified-step b/Lang/VAX-Assembly/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..1fd30b94c2 --- /dev/null +++ b/Lang/VAX-Assembly/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Loops-Infinite b/Lang/VAX-Assembly/Loops-Infinite new file mode 120000 index 0000000000..af28e94776 --- /dev/null +++ b/Lang/VAX-Assembly/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/VAX-Assembly \ No newline at end of file diff --git a/Lang/VAX-Assembly/Sieve-of-Eratosthenes b/Lang/VAX-Assembly/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ece7741700 --- /dev/null +++ b/Lang/VAX-Assembly/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/VAX-Assembly \ No newline at end of file diff --git a/Lang/VBA/Aliquot-sequence-classifications b/Lang/VBA/Aliquot-sequence-classifications new file mode 120000 index 0000000000..0a7b097b2c --- /dev/null +++ b/Lang/VBA/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/VBA \ No newline at end of file diff --git a/Lang/VBA/Formatted-numeric-output b/Lang/VBA/Formatted-numeric-output new file mode 120000 index 0000000000..fd80b42d80 --- /dev/null +++ b/Lang/VBA/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/VBA \ No newline at end of file diff --git a/Lang/VBA/Greatest-element-of-a-list b/Lang/VBA/Greatest-element-of-a-list new file mode 120000 index 0000000000..2c93b24188 --- /dev/null +++ b/Lang/VBA/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/VBA \ No newline at end of file diff --git a/Lang/VBA/Harshad-or-Niven-series b/Lang/VBA/Harshad-or-Niven-series new file mode 120000 index 0000000000..1d1f74c61f --- /dev/null +++ b/Lang/VBA/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/VBA \ No newline at end of file diff --git a/Lang/VBScript/Draw-a-cuboid b/Lang/VBScript/Draw-a-cuboid new file mode 120000 index 0000000000..89c706445d --- /dev/null +++ b/Lang/VBScript/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Draw-a-sphere b/Lang/VBScript/Draw-a-sphere new file mode 120000 index 0000000000..badc7a19b8 --- /dev/null +++ b/Lang/VBScript/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Insertion-sort b/Lang/VBScript/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..2a9a947a16 --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/VBScript \ No newline at end of file diff --git a/Lang/Vala/GUI-component-interaction b/Lang/Vala/GUI-component-interaction new file mode 120000 index 0000000000..039d85f999 --- /dev/null +++ b/Lang/Vala/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Vala \ No newline at end of file diff --git a/Lang/Vala/GUI-enabling-disabling-of-controls b/Lang/Vala/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..48a14fba26 --- /dev/null +++ b/Lang/Vala/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Vala \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Munching-squares b/Lang/Visual-Basic-.NET/Munching-squares new file mode 120000 index 0000000000..7f827487b8 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Visual-Basic-.NET \ No newline at end of file diff --git a/Task/100-doors/Astro/100-doors.astro b/Task/100-doors/Astro/100-doors.astro index 1ef6705711..51b9960768 100644 --- a/Task/100-doors/Astro/100-doors.astro +++ b/Task/100-doors/Astro/100-doors.astro @@ -1,5 +1,7 @@ var doors = falses(100) + for a in 1..100: for b in a..a..100: doors[b] = not doors[b] + for a in 1..100: - print "Door $a is $((doors[a]) ? 'open.': 'closed.')" + print "Door $a is ${(doors[a]) ? 'open.': 'closed.'}" diff --git a/Task/100-doors/C++/100-doors-4.cpp b/Task/100-doors/C++/100-doors-4.cpp new file mode 100644 index 0000000000..a03bf3692a --- /dev/null +++ b/Task/100-doors/C++/100-doors-4.cpp @@ -0,0 +1,125 @@ +#include // compiled with clang (tags/RELEASE_600/final) +#include // or g++ (GCC) 7.3.1 20180406 -- from hare1039 +namespace functional_list // basic building block for template meta programming +{ +struct NIL +{ + using head = NIL; + using tail = NIL; + friend std::ostream& operator << (std::ostream& os, NIL const) { return os; } +}; + +template +struct list +{ + using head = H; + using tail = T; +}; + +template +struct integer +{ + static constexpr int value = i; + friend std::ostream& operator << (std::ostream& os, integer const) { os << integer::value; return os;} +}; + +template constexpr +auto at() +{ + if constexpr (nTH == 0) + return (typename L::head){}; + else if constexpr (not std::is_same_v) + return at(); + else + return NIL{}; +} +template +using at_t = decltype(at()); + +template constexpr +auto prepend() { return list{}; } + +template +using prepend_t = decltype(prepend()); + +template > constexpr +auto gen_list() +{ + if constexpr (Size == 0) + return NIL{}; + else + { + using next = decltype(gen_list()); + return prepend(); + } +} +template > +using gen_list_t = decltype(gen_list()); + +} namespace fl = functional_list; + +constexpr int door_amount = 101; // index from 1 to 100 + +template constexpr +auto construct_loop() +{ + using val_t = fl::at_t; + if constexpr (std::is_same_v) + return fl::NIL{}; + else + { + constexpr int val = val_t::value; + using val_add_t = fl::integer; + using val_old_t = fl::integer; + + if constexpr (current == door_amount) + { + if constexpr(current % moder == 0) + return fl::list{}; + else + return fl::list{}; + } + else + { + using sub_list = decltype(construct_loop()); + if constexpr(current % moder == 0) + return fl::prepend(); + else + return fl::prepend(); + } + } +} + +template constexpr +auto construct() +{ + if constexpr (iteration == 1) // door index = 1 + { + using l = fl::gen_list_t; + return construct_loop(); + } + else + { + using prev_iter_list = decltype(construct()); + return construct_loop(); + } +} + +template constexpr +void show_ans() +{ + if constexpr (std::is_same_v) + return; + else + { + if constexpr (L::head::value % 2 == 1) + std::cout << "Door " << pos << " is opened.\n"; + show_ans(); + } +} + +int main() +{ + using result = decltype(construct<100>()); + show_ans(); +} diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena index 24d125de68..1fd4bddfa8 100644 --- a/Task/100-doors/Elena/100-doors.elena +++ b/Task/100-doors/Elena/100-doors.elena @@ -1,7 +1,7 @@ import system'routines. import extensions. -public program = +public program [ var Doors := Array new:100; populate(:n)( false ). @@ -19,4 +19,4 @@ public program = ]. console readChar. -]. +] diff --git a/Task/100-doors/Ruby/100-doors-1.rb b/Task/100-doors/Ruby/100-doors-1.rb index 6bd684abd4..cd56f1ac0a 100644 --- a/Task/100-doors/Ruby/100-doors-1.rb +++ b/Task/100-doors/Ruby/100-doors-1.rb @@ -1,40 +1,10 @@ -class Door - attr_reader :state - - def initialize - @state = :closed - end - - def close - @state = :closed - end - - def open - @state = :open - end - - def closed? - @state == :closed - end - - def open? - @state == :open - end - - def toggle - if closed? then open else close end - end - - def to_s - @state.to_s - end -end - -doors = Array.new(100) { Door.new } -1.upto(100) do |multiplier| - doors.each_with_index do |door, i| - door.toggle if (i + 1) % multiplier == 0 - end -end - -doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." } +doors = Array.new(101,0) +print "Open doors " +(1..100).step(){ |i| +(i..100).step(i) { |d| + doors[d] = doors[d]^= 1 + if i == d and doors[d] == 1 then + print "#{i} " + end + } +} diff --git a/Task/100-doors/Ruby/100-doors-2.rb b/Task/100-doors/Ruby/100-doors-2.rb index 6376d1cd8d..6bd684abd4 100644 --- a/Task/100-doors/Ruby/100-doors-2.rb +++ b/Task/100-doors/Ruby/100-doors-2.rb @@ -1,18 +1,40 @@ -n = 100 -Open = "open" -Closed = "closed" -def Open.toggle - Closed -end -def Closed.toggle - Open -end -doors = [Closed] * (n + 1) -for mul in 1..n - for x in (mul..n).step(mul) - doors[x] = doors[x].toggle +class Door + attr_reader :state + + def initialize + @state = :closed + end + + def close + @state = :closed + end + + def open + @state = :open + end + + def closed? + @state == :closed + end + + def open? + @state == :open + end + + def toggle + if closed? then open else close end + end + + def to_s + @state.to_s end end -doors.each_with_index do |b, i| - puts "Door #{i} is #{b}" if i > 0 + +doors = Array.new(100) { Door.new } +1.upto(100) do |multiplier| + doors.each_with_index do |door, i| + door.toggle if (i + 1) % multiplier == 0 + end end + +doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." } diff --git a/Task/100-doors/Ruby/100-doors-3.rb b/Task/100-doors/Ruby/100-doors-3.rb index 5a572783e7..6376d1cd8d 100644 --- a/Task/100-doors/Ruby/100-doors-3.rb +++ b/Task/100-doors/Ruby/100-doors-3.rb @@ -1,4 +1,18 @@ n = 100 -(1..n).each do |i| - puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}" +Open = "open" +Closed = "closed" +def Open.toggle + Closed +end +def Closed.toggle + Open +end +doors = [Closed] * (n + 1) +for mul in 1..n + for x in (mul..n).step(mul) + doors[x] = doors[x].toggle + end +end +doors.each_with_index do |b, i| + puts "Door #{i} is #{b}" if i > 0 end diff --git a/Task/100-doors/Ruby/100-doors-4.rb b/Task/100-doors/Ruby/100-doors-4.rb index 98bc59f7f1..5a572783e7 100644 --- a/Task/100-doors/Ruby/100-doors-4.rb +++ b/Task/100-doors/Ruby/100-doors-4.rb @@ -1,7 +1,4 @@ -doors = [false] * 100 -100.times do |i| - (i ... doors.length).step(i + 1) do |j| - doors[j] = !doors[j] - end +n = 100 +(1..n).each do |i| + puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}" end -puts doors.map.with_index(1){|d,i| "Door #{i} is #{d ? 'open' : 'closed'}."} diff --git a/Task/100-doors/Ruby/100-doors-5.rb b/Task/100-doors/Ruby/100-doors-5.rb new file mode 100644 index 0000000000..98bc59f7f1 --- /dev/null +++ b/Task/100-doors/Ruby/100-doors-5.rb @@ -0,0 +1,7 @@ +doors = [false] * 100 +100.times do |i| + (i ... doors.length).step(i + 1) do |j| + doors[j] = !doors[j] + end +end +puts doors.map.with_index(1){|d,i| "Door #{i} is #{d ? 'open' : 'closed'}."} diff --git a/Task/100-doors/VAX-Assembly/100-doors.vax b/Task/100-doors/VAX-Assembly/100-doors.vax new file mode 100644 index 0000000000..5bccdce977 --- /dev/null +++ b/Task/100-doors/VAX-Assembly/100-doors.vax @@ -0,0 +1,28 @@ + 00000064 0000 1 n = 100 + 0000 0000 2 .entry doors, ^m<> + 26'AF 9F 0002 3 pushab b^arr ; offset signed byte + 50 64 8F 9A 0005 4 movzbl #n, r0 + 50 DD 0009 5 pushl r0 ; (sp) -> .ascid arr + 000B 6 10$: + 51 50 D0 000B 7 movl r0, r1 ; step = start index + 000E 8 20$: + 25'AF41 01 8C 000E 9 xorb2 #^a"0" \^a"1", b^arr-1[r1] ; \ xor toggle "1"<->"0" + FFF5 51 50 6E F1 0013 10 acbl (sp), r0, r1, 20$ ; limit, step, index + EF 50 F5 0019 11 sobgtr r0, 10$ ; n..1 + 001C 12 + 5E DD 001C 13 pushl sp ; descriptor by reference + 00000000'GF 01 FB 001E 14 calls #1, g^lib$put_output ; show result + 04 0025 15 ret + 0026 16 +30'30'30'30'30'30'30'30'30'30'30'30' 0026 17 arr: .byte ^a"0"[n] +30'30'30'30'30'30'30'30'30'30'30'30' 0032 +30'30'30'30'30'30'30'30'30'30'30'30' 003E +30'30'30'30'30'30'30'30'30'30'30'30' 004A +30'30'30'30'30'30'30'30'30'30'30'30' 0056 +30'30'30'30'30'30'30'30'30'30'30'30' 0062 +30'30'30'30'30'30'30'30'30'30'30'30' 006E +30'30'30'30'30'30'30'30'30'30'30'30' 007A + 30'30'30'30' 0086 + 008A 18 .end doors +$ run doors +1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001 diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index a02c7fb7ad..5a5fdc386f 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -167,9 +167,9 @@ extension gameOp ] } -public program = +public program [ var aGame := TwentyFourGame new; help. while (aGame prompt; playRound(console readLine)) []. -]. +] diff --git a/Task/24-game/Ring/24-game.ring b/Task/24-game/Ring/24-game.ring index a77bd070f6..d6ff95e921 100644 --- a/Task/24-game/Ring/24-game.ring +++ b/Task/24-game/Ring/24-game.ring @@ -1,7 +1,4 @@ # Project : 24 game -# Date : 2018/02/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" digits = list(4) diff --git a/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl b/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl index 1280760e09..f5d9a0d553 100644 --- a/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl +++ b/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl @@ -1,29 +1,21 @@ --module(god_the_integer). --export([example/0, names/1, print_pyramid/1]). +-module(triangle). +-export([start/1]). +start(N)-> + print(1,1,N). +print(N,N,N)-> +1; +print(A,B,N) when A>=B-> + io:format("~p ",[formula(A,B)]), + print(A,B+1,N); +print(A,B,N) when B>A-> + io:format("~n"), + print(A+1,1,N). -example() -> - Names = names( 10 ), - print_pyramid( Names ). - -names( N ) -> - [names_row(X) || X <- lists:seq(1, N)]. - -print_pyramid( Names ) -> - Width = erlang:length( lists:last(Names) ), - [print_pyramid_row(Width, X) || X <- Names]. - - - -names_row( M ) -> - [p(M, X) || X <- lists:seq(1, M)]. - -p( N, K ) when K > N -> 0; -p( N, N ) -> 1; -p( _N, 0 ) -> 0; -p( N, K ) -> - p( N - 1, K - 1 ) + p( N - K, K ). - -print_pyramid_row( Width, Row ) -> - io:fwrite( "~*s", [Width - erlang:length(Row), " "] ), - [io:fwrite("~p ", [X]) || X <- Row], - io:nl(). +formula(_,0)-> + 0; +formula(B,B)-> + 1; +formula(A,B) when B>A-> + 0; +formula(A1,B1)-> + formula(A1-1,B1-1)+formula(A1-B1,B1). 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 index 634e60e7ae..90aad36c81 100644 --- a/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro +++ b/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro @@ -3,10 +3,10 @@ fun bottles(n): | 1 => "1 bottle" | _ => "$n bottles" -for n in !99..1: +for n in 99..-1..1: print """ - $(bottles n) of beer on the wall - $(bottles n) of beer + ${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 + ${bottles n-1} of beer on the wall\n """ diff --git a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-1.c b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-1.c index 40042b3568..4749d04c7d 100644 --- a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-1.c +++ b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-1.c @@ -1,15 +1,28 @@ -#include +/* + * 99 Bottles, C, KISS (i.e. keep it simple and straightforward) version + */ + #include int main(void) { - unsigned int bottles = 99; - do - { - printf("%u bottles of beer on the wall\n", bottles); - printf("%u bottles of beer\n", bottles); - printf("Take one down, pass it around\n"); - printf("%u bottles of beer on the wall\n\n", --bottles); - } while(bottles > 0); - return EXIT_SUCCESS; + int n; + + for( n = 99; n > 2; n-- ) + printf( + "%d bottles of beer on the wall, %d bottles of beer.\n" + "Take one down and pass it around, %d bottles of beer on the wall.\n\n", + n, n, n - 1); + + printf( + "2 bottles of beer on the wall, 2 bottles of beer.\n" + "Take one down and pass it around, 1 bottle of beer on the wall.\n\n" + + "1 bottle of beer on the wall, 1 bottle of beer.\n" + "Take one down and pass it around, no more bottles of beer on the wall.\n\n" + + "No more bottles of beer on the wall, no more bottles of beer.\n" + "Go to the store and buy some more, 99 bottles of beer on the wall.\n"); + + return 0; } 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 cdd9d6bb39..db355327c0 100644 --- a/Task/99-Bottles-of-Beer/Elena/99-bottles-of-beer.elena +++ b/Task/99-Bottles-of-Beer/Elena/99-bottles-of-beer.elena @@ -27,9 +27,9 @@ extension bottleOp ]. } -public program = +public program [ var bottles := 99. bottles bottleEnumerator; forEach:printingLn. -]. +] diff --git a/Task/99-Bottles-of-Beer/Emacs-Lisp/99-bottles-of-beer.l b/Task/99-Bottles-of-Beer/Emacs-Lisp/99-bottles-of-beer.l new file mode 100644 index 0000000000..a357c2d00b --- /dev/null +++ b/Task/99-Bottles-of-Beer/Emacs-Lisp/99-bottles-of-beer.l @@ -0,0 +1,4 @@ + (let ((i 99)) + (while (> i 0) + (princ-list i " bottles of beer on the wall" "\n Take one down, pass it around") + (setq i (1- i)))) diff --git a/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth index 36a3defd7c..b7f337961c 100644 --- a/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth +++ b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth @@ -1,36 +1,35 @@ -: bottles ( n -- ) \ select the right grammar based on 'n' - dup - case - 1 of ." One more bottle " drop endof - 0 of ." No more bottles " drop endof - . ." bottles " \ default case - endcase ; +DECIMAL +: BOTTLES ( n -- ) + DUP + CASE + 1 OF ." One more bottle " DROP ENDOF + 0 OF ." NO MORE bottles " DROP ENDOF + . ." bottles " \ DEFAULT CASE + ENDCASE ; -\ create punctuation with delay for artistic effect -: , [char] , emit 100 ms ; -: . [char] . emit 300 ms ; +: , [CHAR] , EMIT SPACE 100 MS CR ; +: . [CHAR] . EMIT 300 MS CR CR CR ; -\ create the words to write the program -: of ." of " ; -: beer ." beer " ; -: on ." on " ; -: the ." the " ; -: wall ." wall" ; -: take ." take " ; -: one ." one " ; -: down ." down" ; -: pass ." pass " ; -: it ." it " ; -: around ." around" ; +: OF ." of " ; : BEER ." beer " ; +: ON ." on " ; : THE ." the " ; +: WALL ." wall" ; : TAKE ." take " ; +: ONE ." one " ; : DOWN ." down, " ; +: PASS ." pass " ; : IT ." it " ; +: AROUND ." around" ; -\ who said Forth is write only? -: beers ( n -- ) \ USAGE: 99 beers - 1 swap - cr - do - I bottles of beer on the wall , cr - I bottles of beer , cr - take one down , pass it around , cr - I 1- bottles of beer on the wall . cr - cr - -1 +loop ; +: POPONE 1 SWAP CR ; +: DRINK POSTPONE DO ; IMMEDIATE +: ANOTHER S" -1 +LOOP" EVALUATE ; IMMEDIATE +: HOWMANY S" I " EVALUATE ; IMMEDIATE +: ONELESS S" I 1- " EVALUATE ; IMMEDIATE +: HANGOVER ." :-(" CR QUIT ; + +: BEERS ( n -- ) \ Usage: 99 BEERS + POPONE + DRINK + HOWMANY BOTTLES OF BEER ON THE WALL , + HOWMANY BOTTLES OF BEER , + TAKE ONE DOWN PASS IT AROUND , + ONELESS BOTTLES OF BEER ON THE WALL . + ANOTHER + HANGOVER ; 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 new file mode 100644 index 0000000000..5050e6e77d --- /dev/null +++ b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py @@ -0,0 +1,28 @@ +"""Pythonic 99 beer song (readability counts).""" + +regular_verse = '''\ +{n} bottles of beer on the wall, {n} bottles of beer +Take one down and pass it around, {n_minus_1} bottles of beer on the wall. + +''' + +ending_verses = '''\ +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, 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, 99 bottles of beer on the wall. + +''' + +# @todo: It is possible to refactor the code to avoid n-1 in the code, +# notice that the last line of any verse and the first line of the next +# verse share the same number of bottles. Nevertheless the code +# would be less readliable. + +for n in range(99, 2, -1): + print(regular_verse.format(n=n, n_minus_1=n - 1)) +print(ending_verses) 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 new file mode 100644 index 0000000000..a5518fdf9b --- /dev/null +++ b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py @@ -0,0 +1,26 @@ +"""Pythonic 99 beer song (readability counts).""" + +first = '''\ +99 bottles of beer on the wall, 99 bottles of beer +''' + +middle = '''\ +Take one down and pass it around, {n} bottles of beer on the wall. + +{n} bottles of beer on the wall, {n} bottles of beer +''' + +last = '''\ +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, 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, 99 bottles of beer on the wall. +''' + +print(first) +for n in range(98, 1, -1): + print(middle.format(n=n)) +print(last) diff --git a/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-1.rebol b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-1.rebol index d2825dbf2c..cb2d53ca48 100644 --- a/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-1.rebol +++ b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-1.rebol @@ -1,7 +1,5 @@ rebol [ Title: "99 Bottles of Beer" - Author: oofoe - Date: 2009-12-11 URL: http://rosettacode.org/wiki/99_Bottles_of_Beer ] diff --git a/Task/A+B/Elena/a+b-1.elena b/Task/A+B/Elena/a+b-1.elena index 96e82bd3dd..aab3069454 100644 --- a/Task/A+B/Elena/a+b-1.elena +++ b/Task/A+B/Elena/a+b-1.elena @@ -1,9 +1,9 @@ import extensions. -public program = +public program [ var A := Integer new. var B := Integer new. - console readLine(A,B); writeLine(A + B). -]. + console readLine(A,B); writeLine(A + B) +] diff --git a/Task/A+B/Elena/a+b-2.elena b/Task/A+B/Elena/a+b-2.elena index 1f1ab29612..4b158dd2e7 100644 --- a/Task/A+B/Elena/a+b-2.elena +++ b/Task/A+B/Elena/a+b-2.elena @@ -1,10 +1,10 @@ import system'routines. import extensions. -public program = +public program [ console writeLine(console readLine; split; selectBy(%"convertorOp.toInt[0]"); - summarize). -]. + summarize) +] diff --git a/Task/A+B/Swift/a+b.swift b/Task/A+B/Swift/a+b-1.swift similarity index 100% rename from Task/A+B/Swift/a+b.swift rename to Task/A+B/Swift/a+b-1.swift diff --git a/Task/A+B/Swift/a+b-2.swift b/Task/A+B/Swift/a+b-2.swift new file mode 100644 index 0000000000..a297f9bf15 --- /dev/null +++ b/Task/A+B/Swift/a+b-2.swift @@ -0,0 +1,14 @@ +import Foundation + +let input = FileHandle.standardInput + +let data = input.availableData +let str = String(data: data, encoding: .utf8)! +let nums = str.split(separator: " ") + .map { String($0.unicodeScalars + .filter { CharacterSet.decimalDigits.contains($0) }) } + +let a = Int(nums[0])! +let b = Int(nums[1])! + +print(" \(a + b)") diff --git a/Task/ABC-Problem/Astro/abc-problem.astro b/Task/ABC-Problem/Astro/abc-problem.astro index 7420d9f430..93196c9d5e 100644 --- a/Task/ABC-Problem/Astro/abc-problem.astro +++ b/Task/ABC-Problem/Astro/abc-problem.astro @@ -1,7 +1,8 @@ fun abc(str, list): - if list.isEmpty: return true - for i in indices(list) where s[!1] in list[i]: - return abc(str[:!2], remove(val list, i)) + if list.isempty: + return true + for i in indices(list) where s[end] in list[i]: + return abc(str[end-1:], remove(val list, i)) false let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"] @@ -9,4 +10,4 @@ let list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] for str in test: - print "$:>8(s) | $(abc(s, list))" + print "$|>8|{s} | ${abc(s, list)}" diff --git a/Task/ABC-Problem/Elena/abc-problem.elena b/Task/ABC-Problem/Elena/abc-problem.elena index b6773ec09c..aea653d4db 100644 --- a/Task/ABC-Problem/Elena/abc-problem.elena +++ b/Task/ABC-Problem/Elena/abc-problem.elena @@ -21,7 +21,7 @@ extension op ] } -public program = +public program [ var blocks := ("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", @@ -33,5 +33,5 @@ public program = words forEach(:word) [ console printLine("can make '",word,"' : ",word canMakeWordFrom:blocks). - ]. -]. + ] +] diff --git a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena index 1e3297daff..7227c0ffac 100644 --- a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena +++ b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena @@ -59,7 +59,7 @@ singleton AksTest ] } -public program = +public program [ 0 till:10 do(:n) [ @@ -78,5 +78,5 @@ public program = ] ]. - console printLine; readLine -]. + console printLine; readChar +] diff --git a/Task/Abstract-type/REBOL/abstract-type.rebol b/Task/Abstract-type/REBOL/abstract-type.rebol index c5dabc81ea..353bba0dd1 100644 --- a/Task/Abstract-type/REBOL/abstract-type.rebol +++ b/Task/Abstract-type/REBOL/abstract-type.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Abstract Type" - Author: oofoe - Date: 2009-12-05 URL: http://rosettacode.org/wiki/Abstract_type ] diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Befunge/abundant,-deficient-and-perfect-number-classifications.bf b/Task/Abundant,-deficient-and-perfect-number-classifications/Befunge/abundant,-deficient-and-perfect-number-classifications.bf new file mode 100644 index 0000000000..3162314e3a --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Befunge/abundant,-deficient-and-perfect-number-classifications.bf @@ -0,0 +1,4 @@ +p0"2":*8*>::2/\:2/\28*:*:**+>::28*:*:*/\28*:*:*%%#v_\:28*:*:*%v>00p:0`\0\`-1v +++\1-:1`#^_$:28*:*:*/\28*vv_^#<<*:*:**\2-!#+ +v"There are "0\g00+1%*:*:<>28*:*:*/\28*:*:*/:0\`28*:*:**+-:!00g^^82!:g01\p01< +>:#,_\." ,tneicifed">:#,_\." dna ,tcefrep">:#,_\.55+".srebmun tnadnuba">:#,_@ diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena b/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena index 4fa19b9994..2eb688c5b3 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena @@ -31,11 +31,11 @@ classifyNumbers = ] }. -public program = +public program [ int abundant := 0. int deficient := 0. int perfect := 0. classifyNumbers eval(20000, &abundant, &deficient, &perfect). - console printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect). -]. + console printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect) +] diff --git a/Task/Accumulator-factory/8th/accumulator-factory.8th b/Task/Accumulator-factory/8th/accumulator-factory.8th new file mode 100644 index 0000000000..4f0e7e202c --- /dev/null +++ b/Task/Accumulator-factory/8th/accumulator-factory.8th @@ -0,0 +1,25 @@ +\ RossetaCode 'accumulator factory' + +\ The 'accumulate' word stores the accumulated value in an array, because arrays +\ are mutable: +: accumulate \ n [m] -- n+m \ [m] -> [n+m] + a:pop rot n:+ + tuck a:push swap ; + +\ To comply with the rules, this takes a number and wraps it in an array, and +\ then curries it. Since 'curry:' is "immediate", we need to postpone its +\ action using 'p:. + +: make-accumulator + 1 a:close + ' accumulate + p: curry: ; + +\ We 'curry' the initial value along with 'accumulate' to create +\ a new word, '+10', which will give us the accumulated values +10 make-accumulator +10 + +\ This loop will add 1, then 2, then 3, to the accumulator, which prints the +\ results 11,13,16: +( +10 . cr ) 1 3 loop +bye diff --git a/Task/Accumulator-factory/Astro/accumulator-factory.astro b/Task/Accumulator-factory/Astro/accumulator-factory.astro index d3658b04cb..64f5488404 100644 --- a/Task/Accumulator-factory/Astro/accumulator-factory.astro +++ b/Task/Accumulator-factory/Astro/accumulator-factory.astro @@ -1,5 +1,7 @@ -fun accumulator(sum) = |n| => sum += n +fun accumulator(sum): n => sum += n + let f = accumulator(5.) + print f(5) # 10.0 print f(10) # 20.0 print f(2.4) # 22.4 diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index 8a2bba9eb0..a44ae1f558 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -1,10 +1,10 @@ -function = - (:acc)((:n)(acc append:n)). +function(acc) + = (:n)(acc append:n). -accumulator = - (:n)(function(Variable new(n))). +accumulator(n) + = function(Variable new(n)). -public program = +public program [ var x := accumulator(1). @@ -12,5 +12,5 @@ public program = var y := accumulator(3). - console write(x(2.3r)). -]. + console write(x(2.3r)) +] diff --git a/Task/Accumulator-factory/Perl/accumulator-factory.pl b/Task/Accumulator-factory/Perl/accumulator-factory.pl index b217520dc2..30d2c10823 100644 --- a/Task/Accumulator-factory/Perl/accumulator-factory.pl +++ b/Task/Accumulator-factory/Perl/accumulator-factory.pl @@ -5,5 +5,5 @@ sub accumulator { my $x = accumulator(1); $x->(5); -print accumulator(3), "\n"; +accumulator(3); print $x->(2.3), "\n"; diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index 176b20b961..2d23faeec2 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -1,6 +1,6 @@ import extensions. -ackermann = (:m:n) +ackermann(m,n) [ if((n < 0)||(m < 0)) [ @@ -14,9 +14,9 @@ ackermann = (:m:n) 0 [ ^ackermann(m - 1,1) ]; ! [ ^ackermann(m - 1,ackermann(m,n-1)) ] ] -]. +] -public program = +public program [ 0 to:3 do(:i) [ @@ -26,5 +26,5 @@ public program = ] ]. - console readChar. -]. + console readChar +] diff --git a/Task/Ackermann-function/Go/ackermann-function-3.go b/Task/Ackermann-function/Go/ackermann-function-3.go index dafdf5cea5..aeb84f1490 100644 --- a/Task/Ackermann-function/Go/ackermann-function-3.go +++ b/Task/Ackermann-function/Go/ackermann-function-3.go @@ -1,53 +1,90 @@ package main import ( - "fmt" - "math/big" - "unsafe" + "fmt" + "math/big" + "math/bits" // Added in Go 1.9 ) var one = big.NewInt(1) var two = big.NewInt(2) var three = big.NewInt(3) var eight = big.NewInt(8) -var u uint -var uBits = int(unsafe.Sizeof(u))*8 - 1 func Ackermann2(m, n *big.Int) *big.Int { - if m.Cmp(three) <= 0 { - switch m.Int64() { - case 0: - return new(big.Int).Add(n, one) - case 1: - return new(big.Int).Add(n, two) - case 2: - r := new(big.Int).Lsh(n, 1) - return r.Add(r, three) - case 3: - if n.BitLen() > uBits { - panic("way too big") - } - r := new(big.Int).Lsh(eight, uint(n.Int64())) - return r.Sub(r, three) - } - } - if n.BitLen() == 0 { - return Ackermann2(new(big.Int).Sub(m, one), one) - } - return Ackermann2(new(big.Int).Sub(m, one), - Ackermann2(m, new(big.Int).Sub(n, one))) + if m.Cmp(three) <= 0 { + switch m.Int64() { + case 0: + return new(big.Int).Add(n, one) + case 1: + return new(big.Int).Add(n, two) + case 2: + r := new(big.Int).Lsh(n, 1) + return r.Add(r, three) + case 3: + if nb := n.BitLen(); nb > bits.UintSize { + // n is too large to represent as a + // uint for use in the Lsh method. + panic(TooBigError(nb)) + + // If we tried to continue anyway, doing + // 8*2^n-3 as bellow, we'd use hundreds + // of megabytes and lots of CPU time + // without the Exp call even returning. + r := new(big.Int).Exp(two, n, nil) + r.Mul(eight, r) + return r.Sub(r, three) + } + r := new(big.Int).Lsh(eight, uint(n.Int64())) + return r.Sub(r, three) + } + } + if n.BitLen() == 0 { + return Ackermann2(new(big.Int).Sub(m, one), one) + } + return Ackermann2(new(big.Int).Sub(m, one), + Ackermann2(m, new(big.Int).Sub(n, one))) +} + +type TooBigError int + +func (e TooBigError) Error() string { + return fmt.Sprintf("A(m,n) had n of %d bits; too large", int(e)) } func main() { - show(0, 0) - show(1, 2) - show(2, 4) - show(3, 100) - show(4, 1) - show(4, 3) + show(0, 0) + show(1, 2) + show(2, 4) + show(3, 100) + show(3, 1e6) + show(4, 1) + show(4, 2) + show(4, 3) } func show(m, n int64) { - fmt.Printf("A(%d, %d) = ", m, n) - fmt.Println(Ackermann2(big.NewInt(m), big.NewInt(n))) + defer func() { + // Ackermann2 could/should have returned an error + // instead of a panic. But here's how to recover + // from the panic, and report "expected" errors. + if e := recover(); e != nil { + if err, ok := e.(TooBigError); ok { + fmt.Println("Error:", err) + } else { + panic(e) + } + } + }() + + fmt.Printf("A(%d, %d) = ", m, n) + a := Ackermann2(big.NewInt(m), big.NewInt(n)) + if a.BitLen() <= 256 { + fmt.Println(a) + } else { + s := a.String() + fmt.Printf("%d digits starting/ending with: %s...%s\n", + len(s), s[:20], s[len(s)-20:], + ) + } } diff --git a/Task/Ackermann-function/NewLISP/ackermann-function.newlisp b/Task/Ackermann-function/NewLISP/ackermann-function.newlisp new file mode 100644 index 0000000000..e3eb315dc6 --- /dev/null +++ b/Task/Ackermann-function/NewLISP/ackermann-function.newlisp @@ -0,0 +1,6 @@ +#! /usr/local/bin/newlisp + +(define (ackermann m n) + (cond ((zero? m) (inc n)) + ((zero? n) (ackermann (dec m) 1)) + (true (ackermann (- m 1) (ackermann m (dec n)))))) diff --git a/Task/Active-Directory-Search-for-a-user/Scala/active-directory-search-for-a-user.scala b/Task/Active-Directory-Search-for-a-user/Scala/active-directory-search-for-a-user.scala new file mode 100644 index 0000000000..f3db265780 --- /dev/null +++ b/Task/Active-Directory-Search-for-a-user/Scala/active-directory-search-for-a-user.scala @@ -0,0 +1,36 @@ +import org.apache.directory.api.ldap.model.message.SearchScope +import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection} + +object LdapSearchDemo extends App { + + class LdapSearch { + + def demonstrateSearch(): Unit = { + + val conn = new LdapNetworkConnection("localhost", 11389) + try { + conn.bind("uid=admin,ou=system", "********") + search(conn, "*mil*") + conn.unBind() + } finally if (conn != null) conn.close() + + } + + private def search(connection: LdapConnection, uid: String): Unit = { + val baseDn = "ou=users,o=mojo" + val filter = "(&(objectClass=person)(&(uid=" + uid + ")))" + val scope = SearchScope.SUBTREE + val attributes = List("dn", "cn", "sn", "uid") + var ksearch = 0 + val cursor = connection.search(baseDn, filter, scope, attributes: _*) + while (cursor.next) { + ksearch += 1 + val entry = cursor.get + printf("Search entry %d = %s%n", ksearch, entry) + } + } + } + + new LdapSearch().demonstrateSearch() + +} 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 d2355e7508..cd43de70fd 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena @@ -10,7 +10,7 @@ class Extender :: BaseExtender ] } -public program = +public program [ var anObject := 234. @@ -21,5 +21,5 @@ public program = console printLine(anObject,".foo=",anObject foo). - console readChar. -]. + console readChar +] diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL/add-a-variable-to-a-class-instance-at-runtime.rebol b/Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL/add-a-variable-to-a-class-instance-at-runtime.rebol index af63b13b99..33314fab90 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL/add-a-variable-to-a-class-instance-at-runtime.rebol +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL/add-a-variable-to-a-class-instance-at-runtime.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Add Variables to Class at Runtime" - Author: oofoe - Date: 2009-12-04 URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime ] 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 index 56bfc0a4a5..3207ba694c 100644 --- a/Task/Address-of-a-variable/Astro/address-of-a-variable.astro +++ b/Task/Address-of-a-variable/Astro/address-of-a-variable.astro @@ -1,5 +1,7 @@ var num = 12 var pointer = ptr(num) # get pointer + print pointer # print address -unsafe: # bad idea! - pointer.addr = 0xFFFE # set the address + +@unsafe # bad idea! +pointer.addr = 0xFFFE # set the address diff --git a/Task/Align-columns/REBOL/align-columns.rebol b/Task/Align-columns/REBOL/align-columns.rebol index 66225e00ca..ed5d84b741 100644 --- a/Task/Align-columns/REBOL/align-columns.rebol +++ b/Task/Align-columns/REBOL/align-columns.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Align Columns" - Author: oofoe - Date: 2010-09-29 URL: http://rosettacode.org/wiki/Align_columns ] diff --git a/Task/Aliquot-sequence-classifications/00DESCRIPTION b/Task/Aliquot-sequence-classifications/00DESCRIPTION index e9a534234a..cdcca6720c 100644 --- a/Task/Aliquot-sequence-classifications/00DESCRIPTION +++ b/Task/Aliquot-sequence-classifications/00DESCRIPTION @@ -12,7 +12,7 @@ being K and subsequent members being the sum of the [[Proper divisors]] of the p :* 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 = 140,737,488,355,328. +:* 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: diff --git a/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c index d4eedffef7..9754432257 100644 --- a/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c +++ b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 1st November 2017*/ - #include #include #include diff --git a/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c index 8813dcf239..8f5d340156 100644 --- a/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c +++ b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 7th November 2017*/ - #include #include #include diff --git a/Task/Aliquot-sequence-classifications/Factor/aliquot-sequence-classifications.factor b/Task/Aliquot-sequence-classifications/Factor/aliquot-sequence-classifications.factor new file mode 100644 index 0000000000..1388c92a9b --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Factor/aliquot-sequence-classifications.factor @@ -0,0 +1,54 @@ +USING: combinators combinators.short-circuit formatting kernel +literals locals math math.functions math.primes.factors +math.ranges namespaces pair-rocket sequences sets ; +FROM: namespaces => set ; +IN: rosetta-code.aliquot + +SYMBOL: terms +CONSTANT: 2^47 $[ 2 47 ^ ] +CONSTANT: test-cases { + 11 12 28 496 220 1184 12496 1264460 790 + 909 562 1064 1488 15355717786080 +} + +: next-term ( n -- m ) dup divisors sum swap - ; + +: continue-aliquot? ( hs term -- hs term ? ) + { + [ terms get 15 < ] + [ swap in? not ] + [ nip zero? not ] + [ nip 2^47 < ] + } 2&& ; + +: next-aliquot ( hs term -- hs next-term term ) + [ swap [ adjoin ] keep ] + [ dup [ next-term ] dip ] bi terms inc ; + +: aliquot ( k -- seq ) + 0 terms set HS{ } clone swap + [ continue-aliquot? ] [ next-aliquot ] produce + [ drop ] 2dip swap suffix ; + +: non-terminating? ( seq -- ? ) + { [ length 15 > ] [ [ 2^47 > ] any? ] } 1|| ; + +:: classify ( seq -- classification-str ) + { + [ seq non-terminating? ] => [ "non-terminating" ] + [ seq last zero? ] => [ "terminating" ] + [ seq length 2 = ] => [ "perfect" ] + [ seq length 3 = ] => [ "amicable" ] + [ seq first seq last = ] => [ "sociable" ] + [ seq 2 tail* first2 = ] => [ "aspiring" ] + [ "cyclic" ] + } cond ; + +: .classify ( k -- ) + dup aliquot [ classify ] keep "%14u: %15s: %[%d, %]\n" + printf ; + +: main ( -- ) + 10 [1,b] test-cases append [ .classify ] each ; + +MAIN: main diff --git a/Task/Aliquot-sequence-classifications/Ring/aliquot-sequence-classifications.ring b/Task/Aliquot-sequence-classifications/Ring/aliquot-sequence-classifications.ring index b145e50f8a..2425975c2d 100644 --- a/Task/Aliquot-sequence-classifications/Ring/aliquot-sequence-classifications.ring +++ b/Task/Aliquot-sequence-classifications/Ring/aliquot-sequence-classifications.ring @@ -1,7 +1,4 @@ # Project : Aliquot sequence classnifications -# Date : 2017/11/16 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "Rosetta Code - aliquot sequence classnifications" + nl while true diff --git a/Task/Aliquot-sequence-classifications/VBA/aliquot-sequence-classifications.vba b/Task/Aliquot-sequence-classifications/VBA/aliquot-sequence-classifications.vba new file mode 100644 index 0000000000..6fcf47bdab --- /dev/null +++ b/Task/Aliquot-sequence-classifications/VBA/aliquot-sequence-classifications.vba @@ -0,0 +1,66 @@ +Option Explicit + +Private Type Aliquot + Sequence() As Double + Classification As String +End Type + +Sub Main() +Dim result As Aliquot, i As Long, j As Double, temp As String +'display the classification and sequences of the numbers one to ten inclusive + For j = 1 To 10 + result = Aliq(j) + temp = vbNullString + For i = 0 To UBound(result.Sequence) + temp = temp & result.Sequence(i) & ", " + Next i + Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) + Next j +'show the classification and sequences of the following integers, in order: +Dim a + '15 355 717 786 080 : impossible in VBA ==> out of memory + a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) + For j = LBound(a) To UBound(a) + result = Aliq(CDbl(a(j))) + temp = vbNullString + For i = 0 To UBound(result.Sequence) + temp = temp & result.Sequence(i) & ", " + Next i + Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) + Next +End Sub + +Private Function Aliq(Nb As Double) As Aliquot +Dim s() As Double, i As Long, temp, j As Long, cpt As Long + temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") + ReDim s(0) + s(0) = Nb + For i = 1 To 15 + cpt = cpt + 1 + ReDim Preserve s(cpt) + s(i) = SumPDiv(s(i - 1)) + If s(i) > 140737488355328# Then Exit For + If s(i) = 0 Then j = 1 + If s(1) = s(0) Then j = 2 + If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 + If s(i) = s(i - 1) And i > 1 Then j = 5 + If i >= 2 Then + If s(2) = s(0) Then j = 3 + If s(i) = s(i - 2) And i <> 2 Then j = 6 + End If + If j > 0 Then Exit For + Next + Aliq.Classification = temp(j) + Aliq.Sequence = s +End Function + +Private Function SumPDiv(n As Double) As Double +'returns the sum of the Proper divisors of n +Dim j As Long, t As Long + If n > 1 Then + For j = 1 To n \ 2 + If n Mod j = 0 Then t = t + j + Next + End If + SumPDiv = t +End Function diff --git a/Task/Almost-prime/Maple/almost-prime.maple b/Task/Almost-prime/Maple/almost-prime.maple new file mode 100644 index 0000000000..196bdcb30a --- /dev/null +++ b/Task/Almost-prime/Maple/almost-prime.maple @@ -0,0 +1,16 @@ +AlmostPrimes:=proc(k, numvalues::posint:=10) + local aprimes, i, intfactors; + aprimes := Array([]); + i := 0; + + do + i := i + 1; + intfactors := ifactors(i)[2]; + intfactors := [seq(seq(intfactors[i][1], j=1..intfactors[i][2]),i = 1..numelems(intfactors))]; + if numelems(intfactors) = k then + ArrayTools:-Append(aprimes,i); + end if; + until numelems(aprimes) = 10: + aprimes; +end proc: +; diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena index 849f4f087f..3497ddca76 100644 --- a/Task/Amb/Elena/amb.elena +++ b/Task/Amb/Elena/amb.elena @@ -2,46 +2,45 @@ import system'routines. import extensions. import extensions'routines. -joinable = (:aFormer:aLater)(aFormer[aFormer length - 1] == aLater[0]). +joinable(former,later) = (former[former length - 1] == later[0]). dispatcher = { - eval(object anArray, Func2 aFunction) + eval(object a, Func2 f) [ - ^ aFunction(anArray[0],anArray[1]). + ^ f(a[0],a[1]). ] - eval(object anArray, Func3 aFunction) + eval(object a, Func3 f) [ - ^ aFunction(anArray[0], anArray[1],anArray[2]). + ^ f(a[0], a[1],a[2]). ] - eval(object anArray, Func4 aFunction) + eval(object a, Func4 f) [ - ^ aFunction(anArray[0],anArray[1],anArray[2],anArray[3]). + ^ f(a[0],a[1],a[2],a[3]). ] - eval(object anArray, Func5 aFunction) + eval(object a, Func5 f) [ - ^ aFunction(anArray[0],anArray[1],anArray[2],anArray[3],anArray[4]). + ^ f(a[0],a[1],a[2],a[3],a[4]). ] - }. class AmbValueCollection { object theCombinator. - constructor new(V Arguments) + generic constructor new(V args) [ - theCombinator := SequentialEnumerator new(Arguments). + theCombinator := SequentialEnumerator new(args). ] - seek : aCondition + seek : cond [ theCombinator reset. - theCombinator seekEach(:v)(dispatcher eval(v,aCondition)) + theCombinator seekEach(:v)(dispatcher eval(v,cond)) ] do : aFunction @@ -55,11 +54,11 @@ class AmbValueCollection ambOperator = { - generic for(V Arguments) - = AmbValueCollection new(Arguments). + generic for(V args) + = AmbValueCollection new(args). }. -public program = +public program [ try(ambOperator for(("the","that","a"),("frog", "elephant", "thing"),("walked", "treaded", "grows"),("slowly", "quickly")); @@ -72,5 +71,5 @@ public program = ] }. - console readChar. -]. + console readChar +] diff --git a/Task/Amb/REXX/amb-1.rexx b/Task/Amb/REXX/amb-1.rexx index 3de6b6c7fa..7b4a0231a7 100644 --- a/Task/Amb/REXX/amb-1.rexx +++ b/Task/Amb/REXX/amb-1.rexx @@ -1,22 +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" +@.=; @.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) +Amb: procedure expose @.; parse arg # x; arg . u /*ARG uppercases U values. */ + do j=1 until @.j=='' /*locate a null string. */ + end /*j*/ + t= j-1 /*define number of sets. */ + if #>t then do; y=word(u, 1) /*Y: is a uppercased U. */ + do n=2 to words(u); ?=word(u, n) + if left(?, 1) \== right(y, 1) then return; y=? + end /*n*/ + say space(x) /*Β¬show superfluous blanks.*/ end - do k=1 for words(@.#) /*process words in sets.*/ - call Amb #+1 x word(@.#, k) /*generate combinations,*/ - end /*k*/ /* [↑] (recursively).*/ - return + do k=1 for words(@.#); call Amb #+1 x word(@.#, k) + end /*k*/ /* [↑] generate all combs */ + return /* recursively. */ diff --git a/Task/Amb/Ring/amb.ring b/Task/Amb/Ring/amb.ring new file mode 100644 index 0000000000..615c9946ab --- /dev/null +++ b/Task/Amb/Ring/amb.ring @@ -0,0 +1,32 @@ +# Project : Amb + +set1 = ["the","that","a"] +set2 = ["frog","elephant","thing"] +set3 = ["walked","treaded","grows"] +set4 = ["slowly","quickly"] +text = amb(set1,set2,set3,set4) +if text != "" + see "Correct sentence would be: " + nl + text + nl +else + see "Failed to fine a correct sentence." +ok + +func wordsok(string1, string2) + if substr(string1,len(string1),1) = substr(string2,1,1) + return true + ok + return false + +func amb(a,b,c,d) + for a2 = 1 to len(a) + for b2 =1 to len(b) + for c2 = 1 to len(c) + for d2 = 1 to len(d) + if wordsok(a[a2],b[b2]) and wordsok(b[b2],c[c2]) and wordsok(c[c2],d[d2]) + return a[a2]+" "+b[b2]+" "+c[c2]+" "+d[d2] + ok + next + next + next + next + return "" diff --git a/Task/Amicable-pairs/Befunge/amicable-pairs.bf b/Task/Amicable-pairs/Befunge/amicable-pairs.bf new file mode 100644 index 0000000000..0aaef3822b --- /dev/null +++ b/Task/Amicable-pairs/Befunge/amicable-pairs.bf @@ -0,0 +1,6 @@ +v_@#-*8*:"2":$_:#!2#*8#g*#6:#0*#!:#-*#*/.55+, +1>$$:28*:*:*%\28*:*:*/`06p28*:*:*/\2v %%^:*:<>*v ++|!:-1g60/*:*:*82::+**:*:<<>:#**#8:#<*^>.28*^8 : +:v>>*:*%/\28*:*:*%+\v>8+#$^#_+#`\:#0<:\`1/*:*2#< +2v^:*82\/*:*:*82:::_v#!%%*:*:*82\/*:*:*82::<_^#< +>>06p:28*:*:**1+01-\>1+::28*:*:*/\28*:*:*%:*\`!^ diff --git a/Task/Amicable-pairs/Elena/amicable-pairs.elena b/Task/Amicable-pairs/Elena/amicable-pairs-1.elena similarity index 100% rename from Task/Amicable-pairs/Elena/amicable-pairs.elena rename to Task/Amicable-pairs/Elena/amicable-pairs-1.elena diff --git a/Task/Amicable-pairs/Elena/amicable-pairs-2.elena b/Task/Amicable-pairs/Elena/amicable-pairs-2.elena new file mode 100644 index 0000000000..4244b052c8 --- /dev/null +++ b/Task/Amicable-pairs/Elena/amicable-pairs-2.elena @@ -0,0 +1,33 @@ +import extensions. +import system'routines'stex. +import system'math. +import system'collections. + +const int Limit = 20000. + +extension op +{ + properDivisors + = Range new(1,self / 2); filterBy(:n)(self mod:n == 0). + + amicablePairs + [ + auto divsums := List(Range new(0, self); selectBy(:i)(i properDivisors; summarize)). + + ^ Range from:1 till(divsums length); + filterBy(:i) + [ + var sum := divsums[i]. + ^ (i < sum) && (sum < divsums length) && (divsums[sum] == i) + ]; + selectBy(:i)>(Tuple(i,divsums[i])). + ] +} + +public program +[ + Limit amicablePairs; forEach(:pair)> + [ + console printLine(pair item1, " ", pair item2). + ] +] diff --git a/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring b/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring index d884b23800..dae3fade3a 100644 --- a/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring +++ b/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring @@ -1,7 +1,4 @@ # Project : Anagrams/Deranged anagrams -# Date : 2017/11/28 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" fn1 = "unixdict.txt" diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 3f7fe37a88..d88d5b0b09 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -7,13 +7,13 @@ import extensions'text. extension op { - normalized - = self toArray; ascendant; summarize(StringWriter new); literal. + T normalized + = self toArray; ascendant; summarize(StringWriter new). } -public program = +public program [ - var aDictionary := Dictionary new. + auto aDictionary := Map(). File new("unixdict.txt"); forEachLine(:aWord) [ var s := aWord. @@ -29,8 +29,8 @@ public program = ]. aDictionary values; - sort(:aFormer:aLater)( aFormer length > aLater length ); - top:20; forEach(:aPair)[ console printLine(aPair value) ]. + sort(:aFormer:aLater)( aFormer item2; length > aLater item2; length ); + top:20; forEach(:aPair)[ console printLine(aPair item2) ]. - console readChar. -]. + console readChar +] diff --git a/Task/Anagrams/Ring/anagrams.ring b/Task/Anagrams/Ring/anagrams.ring index 8833f3320e..2aa755a43c 100644 --- a/Task/Anagrams/Ring/anagrams.ring +++ b/Task/Anagrams/Ring/anagrams.ring @@ -1,7 +1,4 @@ # Project : Anagrams -# Date : 2017/11/28 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" fn1 = "unixdict.txt" diff --git a/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix b/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix index 9c22c5e07d..f51ffcb0dc 100644 --- a/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix +++ b/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix @@ -5,46 +5,61 @@ include pGUI.e Ihandle dlg, canvas, timer -cdCanvas cddbuffer, cdcanvas +cdCanvas cdcanvas constant g = 50 -atom alpha = PI/2, - omega = 0 +atom angle = PI/2, + velocity = 0 +integer w, h, len = 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 + {w, h} = IupGetIntInt(canvas, "DRAWSIZE") + cdCanvasActivate(cdcanvas) + cdCanvasClear(cdcanvas) + -- new suspension point: 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 + integer sY = floor(h/16) -- 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) + integer eX = floor(len*sin(angle)+sX) + integer eY = floor(len*cos(angle)+sY) + cdCanvasSetForeground(cdcanvas, CD_CYAN) + cdCanvasLine(cdcanvas, sX, h-sY, eX, h-eY) + cdCanvasSetForeground(cdcanvas, CD_DARK_GREEN) + cdCanvasSector(cdcanvas, sX, h-sY, 5, 5, 0, 360) + cdCanvasSetForeground(cdcanvas, CD_BLUE) + cdCanvasSector(cdcanvas, eX, h-eY, 35, 35, 0, 360) + cdCanvasFlush(cdcanvas) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) + integer newlen = floor(w/2)-30 + if newlen!=len then + len = newlen + atom tmp = 2*g*len*(cos(angle)) + velocity = iff(tmp<0?0:sqrt(tmp)*sign(velocity)) + end if + atom dt = 0.2/w + atom delta = -len*sin(angle)*g + velocity += dt*delta + angle += dt*velocity 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) + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + IupGLMakeCurrent(canvas) + cdcanvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) + cdCanvasSetBackground(cdcanvas, CD_PARCHMENT) + 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(cdcanvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function @@ -56,10 +71,11 @@ end function procedure main() IupOpen() - canvas = IupCanvas(NULL) + canvas = IupGLCanvas() IupSetAttribute(canvas, "RASTERSIZE", "640x380") IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + IupSetCallback(canvas, "RESIZE_CB", Icallback("canvas_resize_cb")) timer = IupTimer(Icallback("timer_cb"), 20) diff --git a/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring b/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring index e693c9325c..82391004c7 100644 --- a/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring +++ b/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring @@ -1,7 +1,4 @@ # Project : Animate a pendulum -# Date : 2018/04/09 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "guilib.ring" load "stdlib.ring" diff --git a/Task/Animation/Phix/animation.phix b/Task/Animation/Phix/animation.phix index dc52cd23a2..683a8daca6 100644 --- a/Task/Animation/Phix/animation.phix +++ b/Task/Animation/Phix/animation.phix @@ -1,33 +1,33 @@ -include arwen.ew +-- +-- demo\rosetta\Animation.exw +-- +include pGUI.e string hw = "Hello World! " -integer direction = 1 +bool direction = true +Ihandle label -constant main = create(Window, "Animation", 0, 0, 20, 20, 300, 150, 0), - label = create(Label,hw,0,main,65,40,200,40,0), - MainTimer = createTimer() - setFont(label, "Verdana", 18, Normal) - removeStyle(main,WS_THICKFRAME+WS_MINIMIZEBOX+WS_MAXIMIZEBOX) - -function mainHandler(integer id, integer msg, atom wParam, object lParam) - if msg=WM_SHOWWINDOW then - startTimer(MainTimer,main,160) - elsif msg=WM_TIMER then - if direction then - hw = hw[$]&hw[1..-2] - else - hw = hw[2..$]&hw[1] - end if - setText(label,hw) - elsif msg=WM_LBUTTONUP then - direction = 1-direction - 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 timer_cb(Ihandle /*ih*/) + hw = iff(direction?hw[$]&hw[1..-2]:hw[2..$]&hw[1]) + IupSetAttribute(label,"TITLE",hw) + return IUP_IGNORE end function -setHandler({main},routine_id("mainHandler")) -WinMain(main, SW_NORMAL) +function key_cb(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + if c=K_UP then direction = not direction end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + label = IupLabel(hw,"FONT=\"Verdana, 18\"") + Ihandle dlg = IupDialog(label,"TITLE=Animation, DIALOGFRAME=YES, CHILDOFFSET=70x40, SIZE=200x80") + IupSetCallback(dlg, "K_ANY", Icallback("key_cb")) + IupShow(dlg) + Ihandle hTimer = IupTimer(Icallback("timer_cb"), 160) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Animation/REBOL/animation.rebol b/Task/Animation/REBOL/animation.rebol index c4c7196413..aef23ea365 100644 --- a/Task/Animation/REBOL/animation.rebol +++ b/Task/Animation/REBOL/animation.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Basic Animation" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Basic_Animation ] diff --git a/Task/Animation/Ring/animation.ring b/Task/Animation/Ring/animation.ring index 301386de58..6630cc8324 100644 --- a/Task/Animation/Ring/animation.ring +++ b/Task/Animation/Ring/animation.ring @@ -1,7 +1,4 @@ # Project : Animation -# Date : 2018/01/18 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : Load "guilib.ring" load "stdlib.ring" diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index b7066df3f2..b9a090b64e 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -1,35 +1,28 @@ import extensions. -extension mathOp -{ - fib - [ - if (self < 0) - [ InvalidArgumentException new:"Must be non negative"; raise ]. +fib(n) +[ + if (n < 0) + [ InvalidArgumentException new:"Must be non negative"; raise ]. - ^ target evalSelf(:n) - [ - if (n > 1) - [ ^ @self(n - 2) + @self(n - 1) ]; - [ ^ n ] - ]. - ] -} + ^ (:n) + [ + if (n > 1) + [ ^ @self(n - 2) + @self(n - 1) ];[ ^ n ] + ](n) +] -public program = +public program [ -1 to:10 do(:i) [ - console print("fib(",i,")="). - - try (console printLine(i fib)) + try (console printLine("fib(",i,")=",fib(i))) { on(Exception e) [ console printLine:"invalid" ] - }. + } ]. - - console readChar. -]. + console readChar +] diff --git a/Task/Anonymous-recursion/Ring/anonymous-recursion.ring b/Task/Anonymous-recursion/Ring/anonymous-recursion.ring index 3506c51532..fcf1509211 100644 --- a/Task/Anonymous-recursion/Ring/anonymous-recursion.ring +++ b/Task/Anonymous-recursion/Ring/anonymous-recursion.ring @@ -1,7 +1,4 @@ # Project : Anonymous recursion -# Date : 2018/01/03 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : t=0 for x = -2 to 12 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 932559578d..ad65a9716e 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,6 +1,6 @@ import system'routines. -public program = +public program [ (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/Futhark/apply-a-callback-to-an-array-1.futhark b/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-1.futhark new file mode 100644 index 0000000000..10c40dcc03 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-1.futhark @@ -0,0 +1 @@ +map f l diff --git a/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-2.futhark b/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-2.futhark new file mode 100644 index 0000000000..45a0641d79 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-2.futhark @@ -0,0 +1 @@ +map (\x->x+1) [1,2,3] -- [2,3,4] diff --git a/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-3.futhark b/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-3.futhark new file mode 100644 index 0000000000..f30e0c03fd --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Futhark/apply-a-callback-to-an-array-3.futhark @@ -0,0 +1 @@ +map (+1) [1,2,3] -- [2,3,4] diff --git a/Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol b/Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol index 23ffc3d668..ec06fa4564 100644 --- a/Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol +++ b/Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Array Callback" - Date: 2010-01-04 - Author: oofoe URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array ] diff --git a/Task/Arbitrary-precision-integers--included-/Go/arbitrary-precision-integers--included-.go b/Task/Arbitrary-precision-integers--included-/Go/arbitrary-precision-integers--included-.go index 91527a94ce..4977ee6c96 100644 --- a/Task/Arbitrary-precision-integers--included-/Go/arbitrary-precision-integers--included-.go +++ b/Task/Arbitrary-precision-integers--included-/Go/arbitrary-precision-integers--included-.go @@ -1,18 +1,19 @@ package main import ( - "fmt" - "math/big" + "fmt" + "math/big" ) func main() { - answer := big.NewInt(42) - answer.Exp(big.NewInt(5), answer.Exp(big.NewInt(4), - answer.Exp(big.NewInt(3), big.NewInt(2), nil), nil), nil) - answer_string := answer.String() - length := len(answer_string) - fmt.Printf("has %d digits: %s ... %s\n", - length, - answer_string[0:20], - answer_string[length-20:]) + x := big.NewInt(2) + x = x.Exp(big.NewInt(3), x, nil) + x = x.Exp(big.NewInt(4), x, nil) + x = x.Exp(big.NewInt(5), x, nil) + str := x.String() + fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", + len(str), + str[:20], + str[len(str)-20:], + ) } diff --git a/Task/Arena-storage-pool/C/arena-storage-pool-7.c b/Task/Arena-storage-pool/C/arena-storage-pool-7.c new file mode 100644 index 0000000000..3177915633 --- /dev/null +++ b/Task/Arena-storage-pool/C/arena-storage-pool-7.c @@ -0,0 +1,142 @@ +#include +#include +#include + +// VERY rudimentary C memory management independent of C library's malloc. + +// Linked list (yes, this is inefficient) +struct __ALLOCC_ENTRY__ +{ + void * allocatedAddr; + size_t size; + struct __ALLOCC_ENTRY__ * next; +}; +typedef struct __ALLOCC_ENTRY__ __ALLOCC_ENTRY__; + +// Keeps track of allocated memory and metadata +__ALLOCC_ENTRY__ * __ALLOCC_ROOT__ = NULL; +__ALLOCC_ENTRY__ * __ALLOCC_TAIL__ = NULL; + +// Add new metadata to the table +void _add_mem_entry(void * location, size_t size) +{ + + __ALLOCC_ENTRY__ * newEntry = (__ALLOCC_ENTRY__ *) mmap(NULL, sizeof(__ALLOCC_ENTRY__), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + + if (__ALLOCC_TAIL__ != NULL) + { + __ALLOCC_TAIL__ -> next = newEntry; + __ALLOCC_TAIL__ = __ALLOCC_TAIL__ -> next; + } + else + { + // Create new table + __ALLOCC_ROOT__ = newEntry; + __ALLOCC_TAIL__ = newEntry; + } + + __ALLOCC_ENTRY__ * tail = __ALLOCC_TAIL__; + tail -> allocatedAddr = location; + tail -> size = size; + tail -> next = NULL; + __ALLOCC_TAIL__ = tail; +} + +// Remove metadata from the table given pointer +size_t _remove_mem_entry(void * location) +{ + __ALLOCC_ENTRY__ * curNode = __ALLOCC_ROOT__; + + // Nothing to do + if (curNode == NULL) + { + return 0; + } + + // First entry matches + if (curNode -> allocatedAddr == location) + { + __ALLOCC_ROOT__ = curNode -> next; + size_t chunkSize = curNode -> size; + + // No nodes left + if (__ALLOCC_ROOT__ == NULL) + { + __ALLOCC_TAIL__ = NULL; + } + munmap(curNode, sizeof(__ALLOCC_ENTRY__)); + + return chunkSize; + } + + // If next node is null, remove it + while (curNode -> next != NULL) + { + __ALLOCC_ENTRY__ * nextNode = curNode -> next; + + if (nextNode -> allocatedAddr == location) + { + size_t chunkSize = nextNode -> size; + + if(curNode -> next == __ALLOCC_TAIL__) + { + __ALLOCC_TAIL__ = curNode; + } + curNode -> next = nextNode -> next; + munmap(nextNode, sizeof(__ALLOCC_ENTRY__)); + + return chunkSize; + } + + curNode = nextNode; + } + + // Nothing was found + return 0; +} + +// Allocate a block of memory with size +// When customMalloc an already mapped location, causes undefined behavior +void * customMalloc(size_t size) +{ + // Now we can use 0 as our error state + if (size == 0) + { + return NULL; + } + + void * mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + + // Store metadata + _add_mem_entry(mapped, size); + + return mapped; +} + +// Free a block of memory that has been customMalloc'ed +void customFree(void * addr) +{ + size_t size = _remove_mem_entry(addr); + + munmap(addr, size); +} + +int main(int argc, char const *argv[]) +{ + int *p1 = customMalloc(4*sizeof(int)); // allocates enough for an array of 4 int + int *p2 = customMalloc(sizeof(int[4])); // same, naming the type directly + int *p3 = customMalloc(4*sizeof *p3); // same, without repeating the type name + + if(p1) { + for(int n=0; n<4; ++n) // populate the array + p1[n] = n*n; + for(int n=0; n<4; ++n) // print it back out + printf("p1[%d] == %d\n", n, p1[n]); + } + + customFree(p1); + customFree(p2); + customFree(p3); + + return 0; +} diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index fe084f7417..a11dba95bd 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -1,7 +1,7 @@ import system'math. import extensions. -public program = +public program [ var a := console readLineTo(Integer new). var b := console readLineTo(Integer new). @@ -11,4 +11,4 @@ public program = 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/REBOL/arithmetic-integer.rebol b/Task/Arithmetic-Integer/REBOL/arithmetic-integer.rebol index 7d18c9e6bb..15b474d2b8 100644 --- a/Task/Arithmetic-Integer/REBOL/arithmetic-integer.rebol +++ b/Task/Arithmetic-Integer/REBOL/arithmetic-integer.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Integer" - Author: oofoe - Date: 2010-09-29 URL: http://rosettacode.org/wiki/Arithmetic/Integer ] diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena index 31bb6b4cbe..7d32ee7fae 100644 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena @@ -83,53 +83,62 @@ class Expression number => theTop. } -operatorState : ch -[ - ch => - $40 [ // ( - ^ target newBracket; gotoStarting - ]; - ! [ - ^ target newToken; append:ch; gotoToken - ]. -] +singleton operatorState +{ + eval(ch) + [ + ch => + $40 [ // ( + ^ target newBracket; gotoStarting + ]; + ! [ + ^ target newToken; append:ch; gotoToken + ]. + ] +} -tokenState : ch -[ - ch => - $41 [ // ) - ^ target closeBracket; gotoToken - ]; - $42 [ // * - ^ target newProduct; gotoOperator - ]; - $43 [ // + - ^ target newSummary; gotoOperator - ]; - $45 [ // - - ^ target newDifference; gotoOperator - ]; - $47 [ // / - ^ target newFraction; gotoOperator - ]; - ! [ - ^ target append:ch - ]. -] +singleton tokenState +{ + eval(ch) + [ + ch => + $41 [ // ) + ^ target closeBracket; gotoToken + ]; + $42 [ // * + ^ target newProduct; gotoOperator + ]; + $43 [ // + + ^ target newSummary; gotoOperator + ]; + $45 [ // - + ^ target newDifference; gotoOperator + ]; + $47 [ // / + ^ target newFraction; gotoOperator + ]; + ! [ + ^ target append:ch + ]. + ] +} -startState : ch -[ - ch => - $40 [ // ( - ^ target newBracket; gotoStarting - ]; - $45 [ // - - ^ target newToken; append:"0"; newDifference; gotoOperator - ]; - ! [ - ^ target newToken; append:ch; gotoToken - ]. -] +singleton startState +{ + eval(ch) + [ + ch => + $40 [ // ( + ^ target newBracket; gotoStarting + ]; + $45 [ // - + ^ target newToken; append:"0"; newDifference; gotoOperator + ]; + ! [ + ^ target newToken; append:ch; gotoToken + ]. + ] +} class Scope { @@ -295,7 +304,7 @@ class Parser ] } -public program = +public program [ var aText := StringWriter new. var aParser := Parser new. @@ -311,5 +320,5 @@ public program = }. aText clear - ]. -]. + ] +] diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Go/arithmetic-geometric-mean-calculate-pi.go b/Task/Arithmetic-geometric-mean-Calculate-Pi/Go/arithmetic-geometric-mean-calculate-pi.go new file mode 100644 index 0000000000..ac496afe94 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Go/arithmetic-geometric-mean-calculate-pi.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + one := big.NewFloat(1) + two := big.NewFloat(2) + four := big.NewFloat(4) + prec := uint(768) // say + + a := big.NewFloat(1).SetPrec(prec) + g := new(big.Float).SetPrec(prec) + + // temporary variables + t := new(big.Float).SetPrec(prec) + u := new(big.Float).SetPrec(prec) + + g.Quo(a, t.Sqrt(two)) + sum := new(big.Float) + pow := big.NewFloat(2) + + for a.Cmp(g) != 0 { + t.Add(a, g) + t.Quo(t, two) + g.Sqrt(u.Mul(a, g)) + a.Set(t) + pow.Mul(pow, two) + t.Sub(t.Mul(a, a), u.Mul(g, g)) + sum.Add(sum, t.Mul(t, pow)) + } + + t.Mul(a, a) + t.Mul(t, four) + pi := t.Quo(t, u.Sub(one, sum)) + fmt.Println(pi) +} diff --git a/Task/Array-concatenation/8th/array-concatenation.8th b/Task/Array-concatenation/8th/array-concatenation.8th new file mode 100644 index 0000000000..924b695bfc --- /dev/null +++ b/Task/Array-concatenation/8th/array-concatenation.8th @@ -0,0 +1 @@ +[1,2,3] [4,5,6] a:+ . diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 042dea4f07..04b610f416 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -1,9 +1,9 @@ import extensions. -public program = +public program [ var a := (1,2,3). var b := (4,5). - console printLine("(",a,") + (",b,") = (",a + b,")"); readChar. -]. + console printLine("(",a,") + (",b,") = (",a + b,")"); readChar +] diff --git a/Task/Array-concatenation/Perl-6/array-concatenation.pl6 b/Task/Array-concatenation/Perl-6/array-concatenation.pl6 index f23db7bf62..89f60964f1 100644 --- a/Task/Array-concatenation/Perl-6/array-concatenation.pl6 +++ b/Task/Array-concatenation/Perl-6/array-concatenation.pl6 @@ -1,8 +1,18 @@ -# the prefix:<|> operator (called "slip") can be used to interpolate arrays into a list: -sub cat-arrays(@a, @b) { - |@a, |@b -} +my @array1 = 1, 2, 3; +my @array2 = 4, 5, 6; -my @a1 = (1,2,3); -my @a2 = (2,3,4); -cat-arrays(@a1,@a2).join(", ").say; +# If you want to concatenate two array to form a third, +# either use the slip operator "|", to flatten each array. + +my @array3 = |@array1, |@array2; +say @array3; + +# or just flatten both arrays in one fell swoop + +@array3 = flat @array1, @array2; +say @array3; + +# On the other hand, if you just want to add the elements +# of the second array to the first, use the .append method. + +say @array1.append: @array2; diff --git a/Task/Associative-array-Creation/8th/associative-array-creation-1.8th b/Task/Associative-array-Creation/8th/associative-array-creation-1.8th new file mode 100644 index 0000000000..cc4ea7d371 --- /dev/null +++ b/Task/Associative-array-Creation/8th/associative-array-creation-1.8th @@ -0,0 +1 @@ +{ "one" : 1, "two" : "bad" } diff --git a/Task/Associative-array-Creation/8th/associative-array-creation-2.8th b/Task/Associative-array-Creation/8th/associative-array-creation-2.8th new file mode 100644 index 0000000000..af09bf70ee --- /dev/null +++ b/Task/Associative-array-Creation/8th/associative-array-creation-2.8th @@ -0,0 +1 @@ +m:new "one" 1 m:! "two" "bad" m:! diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation.elena b/Task/Associative-array-Creation/Elena/associative-array-creation-1.elena similarity index 91% rename from Task/Associative-array-Creation/Elena/associative-array-creation.elena rename to Task/Associative-array-Creation/Elena/associative-array-creation-1.elena index 9443d082cf..63fe22d918 100644 --- a/Task/Associative-array-Creation/Elena/associative-array-creation.elena +++ b/Task/Associative-array-Creation/Elena/associative-array-creation-1.elena @@ -1,6 +1,6 @@ import system'collections. -public program = +public program [ // 1. Create var aMap := Dictionary new. @@ -9,4 +9,4 @@ public program = aMap["key2"]:= "foo2". aMap["key3"]:= "foo3". aMap["key4"]:= "foo4". -]. +] diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation-2.elena b/Task/Associative-array-Creation/Elena/associative-array-creation-2.elena new file mode 100644 index 0000000000..1160339167 --- /dev/null +++ b/Task/Associative-array-Creation/Elena/associative-array-creation-2.elena @@ -0,0 +1,12 @@ +import system'collections. + +public program +[ + // 1. Create + auto aMap := Map(). + aMap["key"] := "foox". + aMap["key"] := "foo". + aMap["key2"]:= "foo2". + aMap["key3"]:= "foo3". + aMap["key4"]:= "foo4". +] diff --git a/Task/Associative-array-Creation/Perl/associative-array-creation-4.pl b/Task/Associative-array-Creation/Perl/associative-array-creation-4.pl index 3b001f8baf..2117fe92b7 100644 --- a/Task/Associative-array-Creation/Perl/associative-array-creation-4.pl +++ b/Task/Associative-array-Creation/Perl/associative-array-creation-4.pl @@ -1,5 +1,5 @@ -print $hash->{key1}; +print $hashref->{key1}; -$hash->{key1} = 'val1'; +$hashref->{key1} = 'val1'; -@hash->{'key1', 'three'} = ('val1', -238.83); +@{$hashref}{('key1', 'three')} = ('val1', -238.83); diff --git a/Task/Associative-array-Creation/Ring/associative-array-creation.ring b/Task/Associative-array-Creation/Ring/associative-array-creation.ring index 015cfa4861..00faf6ac0f 100644 --- a/Task/Associative-array-Creation/Ring/associative-array-creation.ring +++ b/Task/Associative-array-Creation/Ring/associative-array-creation.ring @@ -1,7 +1,4 @@ # Project Associative array/Creation -# Date 2018/03/24 -# Author Gal Zsolt [~ CalmoSoft ~] -# Email myarray = [["one",1], ["two",2], diff --git a/Task/Associative-array-Iteration/8th/associative-array-iteration-1.8th b/Task/Associative-array-Iteration/8th/associative-array-iteration-1.8th new file mode 100644 index 0000000000..14bc74e4c9 --- /dev/null +++ b/Task/Associative-array-Iteration/8th/associative-array-iteration-1.8th @@ -0,0 +1,3 @@ +{"one": 1, "two": "bad"} +( swap . space . cr ) +m:each diff --git a/Task/Associative-array-Iteration/8th/associative-array-iteration-2.8th b/Task/Associative-array-Iteration/8th/associative-array-iteration-2.8th new file mode 100644 index 0000000000..4d4d2e1840 --- /dev/null +++ b/Task/Associative-array-Iteration/8th/associative-array-iteration-2.8th @@ -0,0 +1,3 @@ +{"one": 1, "two": "bad"} m:keys +( . cr ) +a:each diff --git a/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp b/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp index 181ea93d7d..47b7990535 100644 --- a/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp +++ b/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp @@ -1,7 +1,4 @@ ;; Project : Associative array/Iteration -;; Date : 2018/03/08 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (setf x (make-array '(3 2) :initial-contents '(("hello" 13 ) ("world" 31) ("!" 71)))) diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena similarity index 94% rename from Task/Associative-array-Iteration/Elena/associative-array-iteration.elena rename to Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena index 673f855c76..710b3fa8fd 100644 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena @@ -2,7 +2,7 @@ import system'collections. import system'routines. import extensions. -public program = +public program [ // 1. Create var aMap := Dictionary new. @@ -15,4 +15,4 @@ public program = // Enumerate aMap forEach (:aKeyValue)[ console printLine(aKeyValue key," : ",aKeyValue value) ]. -]. +] diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration-2.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration-2.elena new file mode 100644 index 0000000000..f2dbf83005 --- /dev/null +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration-2.elena @@ -0,0 +1,18 @@ +import system'collections. +import system'routines. +import extensions. + +public program +[ + // 1. Create + auto aMap := Map(). + aMap["key"] := "foox". + aMap["key"] := "foo". + aMap["key2"]:= "foo2". + aMap["key3"]:= "foo3". + aMap["key4"]:= "foo4". + + // Enumerate + aMap forEach + (:tuple)[ console printLine(tuple item1," : ",tuple item2) ]. +] diff --git a/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring b/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring index 66f6fb651d..9000d8559b 100644 --- a/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring +++ b/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring @@ -1,7 +1,4 @@ # Project : Associative array/Iteration -# Date : 2017/10/22 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : lst = [["hello", 13], ["world", 31], ["!", 71]] for n = 1 to len(lst) diff --git a/Task/Atomic-updates/8th/atomic-updates.8th b/Task/Atomic-updates/8th/atomic-updates.8th new file mode 100644 index 0000000000..e000dba006 --- /dev/null +++ b/Task/Atomic-updates/8th/atomic-updates.8th @@ -0,0 +1,93 @@ +var bucket +var bucket-size + +\ The 'bucket' will be a simple array of some values: +: genbucket \ n -- + a:new swap + ( + \ make a random int up to 1000 + rand-pcg n:abs 1000 n:mod + a:push + ) swap times + bucket ! ; + +\ display bucket and its total: +: .bucket + bucket lock @ + dup . space + ' n:+ 0 a:reduce . cr + bucket unlock drop ; + +\ Get current value of bucket #x +: bucket@ \ n -- bucket[n] + bucket @ + swap a:@ nip ; + +\ Transfer x from bucket n to bucket m +: bucket-xfer \ m n x -- + >r bucket @ + \ m n bucket + over a:@ r@ n:- + rot swap a:! + \ m bucket + over a:@ r> n:+ + rot swap a:! + drop ; + +\ Get two random indices to check (ensure they're not the same): +: pick2 + rand-pcg n:abs bucket-size @ n:mod dup >r + repeat + drop + rand-pcg n:abs bucket-size @ n:mod + r@ over n:= + while! + r> ; + +\ Pick two buckets and make them more equal (by a quarter of their difference): +: make-equal + repeat + pick2 + bucket lock @ + third a:@ >r + over a:@ r> n:- + \ if they are equal, do nothing + dup not if + \ equal, so do nothing + drop -rot 2drop + else + 4 n:/ n:int + >r -rot r> + bucket-xfer + then + drop + bucket unlock drop + again ; + +\ Moves a quarter of the smaller value from one (random) bucket to another: +: make-redist + repeat + pick2 bucket lock @ + \ n m bucket + over a:@ >r \ n m b b[m] + third a:@ r> \ n m b b[n] + n:min 4 n:/ n:int + nip bucket-xfer + + bucket unlock drop + again ; + +: app:main + \ create 10 buckets with random positive integer values: + 10 genbucket bucket @ a:len bucket-size ! drop + + \ print the bucket + .bucket + + \ the problem's tasks: + ' make-equal t:task + ' make-redist t:task + + \ the print-the-bucket task. We'll do it just 10 times and then quit: + ( 1 sleep .bucket ) 10 times + bye ; diff --git a/Task/Atomic-updates/Ring/atomic-updates.ring b/Task/Atomic-updates/Ring/atomic-updates.ring index d48b251e53..cf52c74cb9 100644 --- a/Task/Atomic-updates/Ring/atomic-updates.ring +++ b/Task/Atomic-updates/Ring/atomic-updates.ring @@ -1,7 +1,4 @@ # Project : Atomic updates -# Date : 2018/01/01 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : bucket = list(10) f2 = 0 diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index ae9281582b..b212e9364c 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -18,8 +18,8 @@ extension op ^ aSum / aCount. ] } -public program = +public program [ var anArray := (1, 2, 3, 4, 5, 6, 7, 8). - console printLine("Arithmetic mean of {",anArray,"} is ",anArray average); readChar. -]. + console printLine("Arithmetic mean of {",anArray,"} is ",anArray average); readChar +] diff --git a/Task/Averages-Arithmetic-mean/Perl/averages-arithmetic-mean.pl b/Task/Averages-Arithmetic-mean/Perl/averages-arithmetic-mean.pl new file mode 100644 index 0000000000..3dbf35d6ae --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Perl/averages-arithmetic-mean.pl @@ -0,0 +1,8 @@ +sub avg { + @_ or return 0; + my $sum = 0; + $sum += $_ foreach @_; + return $sum/@_; +} + +print avg(qw(3 1 4 1 5 9)), "\n"; diff --git a/Task/Averages-Arithmetic-mean/REBOL/averages-arithmetic-mean.rebol b/Task/Averages-Arithmetic-mean/REBOL/averages-arithmetic-mean.rebol index 2bdbafe8ba..ca58cf86ef 100644 --- a/Task/Averages-Arithmetic-mean/REBOL/averages-arithmetic-mean.rebol +++ b/Task/Averages-Arithmetic-mean/REBOL/averages-arithmetic-mean.rebol @@ -1,7 +1,5 @@ rebol [ Title: "Arithmetic Mean (Average)" - Author: oofoe - Date: 2009-12-11 URL: http://rosettacode.org/wiki/Average/Arithmetic_mean ] diff --git a/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring b/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring index 07152d44c4..e627d2336a 100644 --- a/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring +++ b/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring @@ -1,7 +1,4 @@ # Project : Averages/Mean angle -# Date : 2018/01/08 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" decimals(6) diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index bef896f86a..a9a7132fff 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -20,7 +20,7 @@ extension op ] } -public program = +public 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). @@ -29,4 +29,4 @@ public program = console printLine("median of (",a2,") is ",a2 median). console readChar. -]. +] diff --git a/Task/Averages-Median/K/averages-median.k b/Task/Averages-Median/K/averages-median-1.k similarity index 100% rename from Task/Averages-Median/K/averages-median.k rename to Task/Averages-Median/K/averages-median-1.k diff --git a/Task/Averages-Median/K/averages-median-2.k b/Task/Averages-Median/K/averages-median-2.k new file mode 100644 index 0000000000..9610bc1d59 --- /dev/null +++ b/Task/Averages-Median/K/averages-median-2.k @@ -0,0 +1,4 @@ +med:{a:x@1; h=h % 2 /*cut entries by half.*/ - do i=1 for #-h; j=i; k=h + i /*sort lower section. */ + do while h>1; h= h % 2 /*cut entries by half.*/ + do i=1 for #-h; j= i; k= h + i /*sort lower section. */ do while @.k<@.j; parse value @.j @.k with @.k @.j /*swap.*/ - if h>=j then leave; j=j - h; k=k - h /*diminish J and K.*/ + if h>=j then leave; j= j - h; k= k - h /*diminish J and K.*/ end /*while @.k<@.j*/ end /*i*/ end /*while h>1*/ /*end of exchange sort*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ -median: procedure; call eSORT arg(1); m=# % 2 /* % is REXX's integer division.*/ - n=m + 1 /*N: the next element after M. */ +median: procedure; call eSORT arg(1); m= # % 2 /* % is REXX's integer division.*/ + n= m + 1 /*N: the next element after M. */ if # // 2 then return @.n /*[odd?] // ◄───REXX's Γ· remainder*/ - return (@.m + @.n) / 2 /*process an even─element vector. */ + return (@.m + @.n) / 2 /*process an even─element vector. */ diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index 65ebd78cf5..f8c1308ba7 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -23,7 +23,7 @@ extension op ] } -public program = +public program [ var anArray1 := (1, 1, 2, 4, 4). var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17). @@ -34,4 +34,4 @@ public program = printLine("mode of (",anArray2,") is (",anArray2 mode,")"); printLine("mode of (",anArray3,") is (",anArray3 mode,")"); readChar. -]. +] diff --git a/Task/Averages-Mode/Ring/averages-mode.ring b/Task/Averages-Mode/Ring/averages-mode.ring index bfe7725803..88fc8aa988 100644 --- a/Task/Averages-Mode/Ring/averages-mode.ring +++ b/Task/Averages-Mode/Ring/averages-mode.ring @@ -1,7 +1,4 @@ # Project : Averages/Mode -# Date : 2018/04/11 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17] b = [1, 2, 4, 4, 1] diff --git a/Task/Averages-Mode/Swift/averages-mode.swift b/Task/Averages-Mode/Swift/averages-mode.swift new file mode 100644 index 0000000000..e6460e3237 --- /dev/null +++ b/Task/Averages-Mode/Swift/averages-mode.swift @@ -0,0 +1,27 @@ +// Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method. +extension Collection where Element: Hashable { + + /// Return a Mode of the function, or nil if none exist. + func mode() -> Element? { + var frequencies = [Element: Int]() + + // Standard for loop. Can also use the forEach(_:) or reduce(into:) methods on self. + for element in self { + frequencies[element] = (frequencies[element] ?? 0) + 1 + } + + // The max(by:) method used here to find one of the elements with the highest associated count. + if let ( mode, _ ) = frequencies.max(by: { $0.value < $1.value }) { + return mode + } else { + return nil + } + } + +} + +["q", "a", "a", "a", "a", "b", "b", "z", "c", "c", "c"].mode() // returns "a" +[1, 1, 2, 3, 3, 3, 3, 4, 4, 4].mode() // returns 3 + +let emptyArray: [Int] = [] +emptyArray.mode() // returns nil diff --git a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena index 0529e3112f..3d25d786c5 100644 --- a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena +++ b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena @@ -10,7 +10,7 @@ extension op ] } -public program = +public program [ console printLine(Range new(1, 10); rootMeanSquare) -]. +] 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 ba40125915..6c051dec9b 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 @@ -35,7 +35,7 @@ class SMA ] } -public program = +public program [ var SMA3 := SMA new:3. var SMA5 := SMA new:5. @@ -53,4 +53,4 @@ public program = ]. console readChar. -]. +] diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 3ae169e2bf..4ce979b687 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -2,24 +2,21 @@ import system'routines. import extensions. import extensions'text. -randomBrackets = -{ - new : aLength - [ - if (0 == aLength) - [ ^emptyLiteral ]; - [ - var aBrackets := - Array new(aLength); populate(:i)($91) - + - Array new(aLength); populate(:i)($93). +randomBrackets(len) +[ + if (0 == len) + [ ^emptyLiteral ]; + [ + var aBrackets := + Array new(len); populate(:i)($91) + + + Array new(len); populate(:i)($93). - aBrackets := aBrackets randomize:(aLength * 2). + aBrackets := aBrackets randomize(len * 2). - ^ aBrackets summarize:(StringWriter new); toLiteral - ] - ] -}. + ^ aBrackets summarize(StringWriter new); toLiteral + ] +] extension op { @@ -33,14 +30,14 @@ extension op ] } -public program = +public program [ - 0 to:9 do(:aLength) + 0 to:9 do(:len) [ - var anStr := randomBrackets new:aLength. + var str:= randomBrackets(len). - console printLine("""",anStr,"""",anStr isBalanced; iif(" is balanced"," is not balanced")) + console printLine("""",str,"""",str isBalanced; iif(" is balanced"," is not balanced")) ]. console readChar -]. +] diff --git a/Task/Benfords-law/Ring/benfords-law.ring b/Task/Benfords-law/Ring/benfords-law.ring index 90e95533f9..20d820bd3c 100644 --- a/Task/Benfords-law/Ring/benfords-law.ring +++ b/Task/Benfords-law/Ring/benfords-law.ring @@ -1,7 +1,4 @@ # Project : Benford's law -# Date : 2017/11/29 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(3) n= 1000 diff --git a/Task/Bernoulli-numbers/Go/bernoulli-numbers.go b/Task/Bernoulli-numbers/Go/bernoulli-numbers.go index c7497d868a..16aa02d52b 100644 --- a/Task/Bernoulli-numbers/Go/bernoulli-numbers.go +++ b/Task/Bernoulli-numbers/Go/bernoulli-numbers.go @@ -1,33 +1,27 @@ package main import ( - "fmt" - "math/big" - "strings" + "fmt" + "math/big" ) func b(n int) *big.Rat { - var f big.Rat - a := make([]big.Rat, n+1) - for m := range a { - a[m].SetFrac64(1, int64(m+1)) - for j := m; j >= 1; j-- { - d := &a[j-1] - d.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j])) - } - } - return f.Set(&a[0]) -} - -func align(b *big.Rat, w int) string { - s := b.String() - return strings.Repeat(" ", w-strings.Index(s, "/")) + s + var f big.Rat + a := make([]big.Rat, n+1) + for m := range a { + a[m].SetFrac64(1, int64(m+1)) + for j := m; j >= 1; j-- { + d := &a[j-1] + d.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j])) + } + } + return f.Set(&a[0]) } func main() { - for n := 0; n <= 60; n++ { - if b := b(n); b.Num().BitLen() > 0 { - fmt.Printf("B(%2d) =%s\n", n, align(b, 45)) - } - } + for n := 0; n <= 60; n++ { + if b := b(n); b.Num().BitLen() > 0 { + fmt.Printf("B(%2d) =%45s/%s\n", n, b.Num(), b.Denom()) + } + } } diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index 88e32344db..cca31f56d6 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -36,14 +36,14 @@ extension op ] } -public program = +public program [ - ("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") forEach(:aWord) + ("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") forEach(:s) [ - var aShuffled := aWord shuffled. + var shuffled_s := s shuffled. - console printLine("The best shuffle of ",aWord," is ",aShuffled,"(",aShuffled score:aWord,")"). + console printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s score:s,")"). ]. - console readChar. -]. + console readChar +] diff --git a/Task/Best-shuffle/REXX/best-shuffle.rexx b/Task/Best-shuffle/REXX/best-shuffle.rexx index 070045a39c..4a93c8625d 100644 --- a/Task/Best-shuffle/REXX/best-shuffle.rexx +++ b/Task/Best-shuffle/REXX/best-shuffle.rexx @@ -1,30 +1,30 @@ -/*REXX program determines and displays the best shuffle for any list of words/characters*/ +/*REXX program determines and displays the best shuffle for any list of words or tokens.*/ parse arg $ /*get some words from the command line.*/ if $='' then $= 'tree abracadabra seesaw elk grrrrrr up a' /*use the defaults?*/ w=0; #=words($) /* [↑] finds the widest word in $ list*/ - do i=1 for #; @.i=word($,i); w=max(w, length(@.i) ); end /*i*/ -w=w+9 /*add 9 blanks for output indentation. */ - do n=1 for #; new=bestShuffle(@.n) /*process the examples in the @ array. */ + do i=1 for #; @.i=word($,i); w=max(w, length(@.i) ); end /*i*/ +w= w+9 /*add 9 blanks for output indentation. */ + do n=1 for #; new= bestShuffle(@.n) /*process the examples in the @ array. */ same=0; do m=1 for length(@.n) same=same + (substr(@.n, m, 1) == substr(new, m, 1) ) end /*m*/ - say 'original:' left(@.n, w) 'new:' left(new,w) 'count:' same + say ' original:' left(@.n, w) 'new:' left(new,w) 'score:' same end /*n*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bestShuffle: procedure; parse arg x 1 ox; L=length(x); if L<3 then return reverse(x) /*[↑] fast track short strs*/ - do j=1 for L-1; parse var x =(j) a +1 b +1 /*get A,B at Jth & J+1 pos.*/ - if a\==b then iterate /*ignore any replicates. */ - c=verify(x,a); if c==0 then iterate /* " " " */ - x=overlay( substr(x,c,1), overlay(a,x,c), j) /*swap the x,c characters*/ - rx=reverse(x) /*obtain the reverse of X. */ - y=substr(rx, verify(rx,a), 1) /*get 2nd replicated char. */ - x=overlay(y, overlay(a,x, lastpos(y,x)),j+1) /*fast swap of 2 characters*/ - end /*j*/ - do k=1 for L; a=substr(x,k,1) /*handle a possible rep. */ - if a\==substr(ox,k,1) then iterate /*skip non-replications*/ - if k==L then x=left(x,k-2)a || substr(x,k-1,1) /*last case*/ - else x=left(x,k-1)substr(x,k+1,1)a || substr(x, k+2) - end /*k*/ + do j=1 for L-1; parse var x =(j) a +1 b +1 /*get A,B at Jth & J+1 pos.*/ + if a\==b then iterate /*ignore any replicates. */ + c= verify(x,a); if c==0 then iterate /* " " " */ + x= overlay( substr(x,c,1), overlay(a,x,c), j) /*swap the x,c characters*/ + rx= reverse(x) /*obtain the reverse of X. */ + y= substr(rx, verify(rx, a), 1) /*get 2nd replicated char. */ + x= overlay(y, overlay(a,x, lastpos(y,x)),j+1) /*fast swap of 2 characters*/ + end /*j*/ + do k=1 for L; a=substr(x, k, 1) /*handle a possible rep*/ + if a\==substr(ox, k, 1) then iterate /*skip non-replications*/ + if k==L then x= left(x, k-2)a || substr(x, k-1,1) /*last case*/ + else x= left(x, k-1)substr(x, k+1, 1)a || substr(x,k+2) + end /*k*/ return x diff --git a/Task/Best-shuffle/Ring/best-shuffle-1.ring b/Task/Best-shuffle/Ring/best-shuffle-1.ring index 6ffbc4acb7..f806495c99 100644 --- a/Task/Best-shuffle/Ring/best-shuffle-1.ring +++ b/Task/Best-shuffle/Ring/best-shuffle-1.ring @@ -1,7 +1,4 @@ # Project : Best shuffle -# Date : 2018/02/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : test = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"] diff --git a/Task/Binary-digits/ARM-Assembly/binary-digits.arm b/Task/Binary-digits/ARM-Assembly/binary-digits.arm new file mode 100644 index 0000000000..92939ba80c --- /dev/null +++ b/Task/Binary-digits/ARM-Assembly/binary-digits.arm @@ -0,0 +1,161 @@ +/* ARM assembly Raspberry PI */ +/* program binarydigit.s */ + +/* Constantes */ +.equ STDOUT, 1 +.equ WRITE, 4 +.equ EXIT, 1 +/* Initialized data */ +.data + +sMessAffBin: .ascii "The decimal value " +sZoneDec: .space 12,' ' + .ascii " should produce an output of " +sZoneBin: .space 36,' ' + .asciz "\n" + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* save des 2 registres */ + mov r0,#5 + ldr r1,iAdrsZoneDec + bl conversion10S @ decimal conversion + bl conversion2 @ binary conversion and display rΓ©sult + mov r0,#50 + ldr r1,iAdrsZoneDec + bl conversion10S + bl conversion2 + mov r0,#-1 + ldr r1,iAdrsZoneDec + bl conversion10S + bl conversion2 + mov r0,#1 + ldr r1,iAdrsZoneDec + bl conversion10S + bl conversion2 + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrsZoneDec: .int sZoneDec +/******************************************************************/ +/* register conversion in binary */ +/******************************************************************/ +/* r0 contains the register */ +conversion2: + push {r0,lr} /* save registers */ + push {r1-r5} /* save others registers */ + ldr r1,iAdrsZoneBin @ address reception area + clz r2,r0 @ number of left zeros bits + rsb r2,#32 @ number of significant bits + mov r4,#' ' @ space + add r3,r2,#1 @ position counter in reception area +1: + strb r4,[r1,r3] @ space in other location of reception area + add r3,#1 + cmp r3,#32 @ end of area ? + ble 1b @ no! loop + mov r3,r2 @ position counter of the written character +2: @ loop + lsrs r0,#1 @ shift right one bit with flags + movcc r4,#48 @ carry clear => character 0 + movcs r4,#49 @ carry set => character 1 + strb r4,[r1,r3] @ character in reception area at position counter + sub r3,r3,#1 @ + subs r2,r2,#1 @ 0 bits ? + bgt 2b @ no! loop + + ldr r0,iAdrsZoneMessBin + bl affichageMess + +100: + pop {r1-r5} /* restaur others registers */ + pop {r0,lr} + bx lr +iAdrsZoneBin: .int sZoneBin +iAdrsZoneMessBin: .int sMessAffBin + +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registres */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registres */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ +/***************************************************/ +/* conversion registre en dΓ©cimal signΓ© */ +/***************************************************/ +/* r0 contient le registre */ +/* r1 contient l adresse de la zone de conversion */ +conversion10S: + push {fp,lr} /* save des 2 registres frame et retour */ + push {r0-r5} /* save autres registres */ + mov r2,r1 /* debut zone stockage */ + mov r5,#'+' /* par defaut le signe est + */ + cmp r0,#0 /* nombre nΓ©gatif ? */ + movlt r5,#'-' /* oui le signe est - */ + mvnlt r0,r0 /* et inversion en valeur positive */ + addlt r0,#1 + mov r4,#10 /* longueur de la zone */ +1: /* debut de boucle de conversion */ + bl divisionpar10 /* division */ + add r1,#48 /* ajout de 48 au reste pour conversion ascii */ + strb r1,[r2,r4] /* stockage du byte en dΓ©but de zone r5 + la position r4 */ + sub r4,r4,#1 /* position prΓ©cedente */ + cmp r0,#0 + bne 1b /* boucle si quotient different de zΓ©ro */ + strb r5,[r2,r4] /* stockage du signe Γ  la position courante */ + subs r4,r4,#1 /* position prΓ©cedente */ + blt 100f /* si r4 < 0 fin */ + /* sinon il faut completer le debut de la zone avec des blancs */ + mov r3,#' ' /* caractere espace */ +2: + strb r3,[r2,r4] /* stockage du byte */ + subs r4,r4,#1 /* position prΓ©cedente */ + bge 2b /* boucle si r4 plus grand ou egal a zero */ +100: /* fin standard de la fonction */ + pop {r0-r5} /*restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres frame et retour */ + bx lr + +/***************************************************/ +/* division par 10 signΓ© */ +/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* +/* and http://www.hackersdelight.org/ */ +/***************************************************/ +/* r0 contient le dividende */ +/* r0 retourne le quotient */ +/* r1 retourne le reste */ +divisionpar10: + /* r0 contains the argument to be divided by 10 */ + push {r2-r4} /* save others registers */ + mov r4,r0 + ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ + smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ + mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ + mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ + add r0, r2, r1 /* r0 <- r2 + r1 */ + add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ + sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ + pop {r2-r4} + bx lr /* leave function */ + .align 4 +.Ls_magic_number_10: .word 0x66666667 diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index c986cb9dde..4f9a5fb9f8 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -1,10 +1,10 @@ import system'routines. import extensions. -public program = +public program [ (5,50,9000) forEach(:n) [ console printLine(n toLiteral(2)). ]. -]. +] diff --git a/Task/Binary-digits/Modula-2/binary-digits.mod2 b/Task/Binary-digits/Modula-2/binary-digits.mod2 new file mode 100644 index 0000000000..14572e7329 --- /dev/null +++ b/Task/Binary-digits/Modula-2/binary-digits.mod2 @@ -0,0 +1,29 @@ +MODULE Binary; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT Write,WriteLn,ReadChar; + +PROCEDURE PrintByte(b : INTEGER); +VAR v : INTEGER; +BEGIN + v := 080H; + WHILE v#0 DO + IF (b BAND v) # 0 THEN + Write('1') + ELSE + Write('0') + END; + v := v SHR 1 + END +END PrintByte; + +VAR + buf : ARRAY[0..15] OF CHAR; + i : INTEGER; +BEGIN + FOR i:=0 TO 15 DO + PrintByte(i); + WriteLn + END; + + ReadChar +END Binary. diff --git a/Task/Binary-search/Pascal/binary-search-1.pascal b/Task/Binary-search/Pascal/binary-search-1.pascal index c9f9d1ea92..ccbe115e6c 100644 --- a/Task/Binary-search/Pascal/binary-search-1.pascal +++ b/Task/Binary-search/Pascal/binary-search-1.pascal @@ -2,8 +2,8 @@ function binary_search(element: real; list: array of real): integer; var l, m, h: integer; begin - l := 0; - h := High(list) - 1; + l := Low(list); + h := High(list); binary_search := -1; while l <= h do begin diff --git a/Task/Binary-strings/Forth/binary-strings-1.fth b/Task/Binary-strings/Forth/binary-strings-1.fth index 51ec7bdb7d..13cee9ae38 100644 --- a/Task/Binary-strings/Forth/binary-strings-1.fth +++ b/Task/Binary-strings/Forth/binary-strings-1.fth @@ -9,8 +9,8 @@ : STRLEN ( addr -- length) c@ ; \ alias the "character fetch" operator -: COUNT ( addr -- addr+1 length) \ returns the address+1 and the length byte on the stack - dup strlen swap 1+ swap ; +: COUNT ( addr -- addr+1 length) \ Standard word. Shown for explanation + dup strlen swap 1+ swap ; \ returns the address+1 and the length byte on the stack : ENDSTR ( str -- addr) \ calculate the address at the end of a string COUNT + ; @@ -25,10 +25,10 @@ >r COUNT R> APPEND ; : PLACE ( addr1 len addr2 -- ) \ addr1 and length, placed at addr2 as counted string - 2dup 2>r 1+ swap move 2r> c! ; + 2dup 2>r char+ swap move 2r> c! ; : STRING, ( addr len -- ) \ compile a string at the next available memory (called 'HERE') - here over 1+ allot place ; + here over char+ allot place ; : APPEND-CHAR ( char string -- ) \ append char to string dup >r count dup 1+ r> c! + c! ; @@ -72,12 +72,12 @@ string: strpad \ general purpose storage buffer : substr ( string1 start length -- strpad) \ Extract a substring of string and return an output string - strpad ="" \ clear strpad - >r \ push the length - + \ calc the new start addr - r> strpad append \ pop the length and append to strpad - strpad ; \ return the address of strpad. - + >r >r \ push start,length + count \ compute addr,len + r> 1- /string \ pop start, subtract 1, cut string + drop r> \ drop existing length, pop new length + strpad place \ place new stack string in strpad + strpad ; \ return address of strpad \ COMPARE takes the 4 inputs from the stack (addr1 len1 addr2 len2 ) \ and returns a flag for equal (0) , less-than (1) or greater-than (-1) on the stack diff --git a/Task/Binary-strings/Nim/binary-strings.nim b/Task/Binary-strings/Nim/binary-strings.nim index a6b541c6f4..5bc3a24cd8 100644 --- a/Task/Binary-strings/Nim/binary-strings.nim +++ b/Task/Binary-strings/Nim/binary-strings.nim @@ -14,7 +14,7 @@ if x.len == 0: echo "empty" # check if empty x.add('!') # append a byte echo x[5..8] # substring -echo x[8 .. -1] # substring +echo x[8 .. ^1] # substring z = x & y # join strings diff --git a/Task/Binary-strings/REXX/binary-strings.rexx b/Task/Binary-strings/REXX/binary-strings.rexx index ee973cc943..cfe60b4964 100644 --- a/Task/Binary-strings/REXX/binary-strings.rexx +++ b/Task/Binary-strings/REXX/binary-strings.rexx @@ -3,16 +3,17 @@ dingsta= '11110101'b /*four versions, bit string ass dingsta= "11110101"b /*this is the same assignment as above.*/ dingsta= '11110101'B /* " " " " " " " */ dingsta= '1111 0101'B /* " " " " " " */ -dingsta2=dingsta /*clone one string to another (a copy).*/ + +dingsta2= dingsta /*clone one string to another (a copy).*/ other= '1001 0101 1111 0111'b /*another binary (or bit) string. */ -if dingsta=other then say 'they are equal' /*compare the two (binary) strings. */ -if other=='' then say 'OTHER is empty.' /*see if the OTHER string is empty.*/ -otherA=other || '$' /*append a dollar sign ($) to OTHER. */ -otherB=other'$' /*same as above, but with less fuss. */ -guts=substr(c2b(other), 10, 3) /*obtain the 10th through 12th bits.*/ -new=changeStr('A', other, "Z") /*change the upper letter A ──► Z. */ -tt=changeStr('~~', other, ";") /*change two tildes ──► one semicolon.*/ -joined=dignsta || dingsta2 /*join two strings together (concat). */ +if dingsta= other then say 'they are equal' /*compare the two (binary) strings. */ +if other== '' then say "OTHER is empty." /*see if the OTHER string is empty.*/ +otherA= other || '$' /*append a dollar sign ($) to OTHER. */ +otherB= other'$' /*same as above, but with less fuss. */ + guts= substr(c2b(other), 10, 3) /*obtain the 10th through 12th bits.*/ + new= changeStr('A' , other, "Z") /*change the upper letter A ──► Z. */ + tt= changeStr('~~', other, ";") /*change two tildes ──► one semicolon.*/ +joined= dingsta || dingsta2 /*join two strings together (concat). */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ c2b: return x2b( c2x( arg(1) ) ) /*return the string as a binary string.*/ diff --git a/Task/Bitcoin-address-validation/Phix/bitcoin-address-validation.phix b/Task/Bitcoin-address-validation/Phix/bitcoin-address-validation.phix new file mode 100644 index 0000000000..6996fbf33c --- /dev/null +++ b/Task/Bitcoin-address-validation/Phix/bitcoin-address-validation.phix @@ -0,0 +1,84 @@ +-- +-- demo\rosetta\bitcoin_address_validation.exw +-- +string coin_err + +constant b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +string charmap = "" + +function unbase58(string s) +string out = repeat('\0',25) + if length(charmap)=0 then + charmap = repeat('\0',256) + for i=1 to length(b58) do + charmap[b58[i]] = i + end for + end if +-- not at all sure about this: +-- if length(s)!=34 then +-- coin_err = "bad length" +-- return 0 +-- end if + if s[1]!='1' and s[1]!='3' then + coin_err = "first character is not 1 or 3" + return 0 + end if + for i=1 to length(s) do + integer c = charmap[s[i]] + if c=0 then + coin_err = "bad char" + return 0 + end if + c -= 1 + for j=25 to 1 by -1 do + c += 58 * out[j]; + out[j] = and_bits(c,#FF) + c = floor(c/#100) + end for + if c!=0 then + coin_err = "address too long" + return 0 + end if + end for + if out[1]!='\0' then + coin_err = "not version 0" + return 0 + end if + return out +end function + +include builtins\sha256.e + +procedure valid(string s) +object dec + coin_err = "OK" + dec = unbase58(s) + if string(dec) then + if dec[22..$]!=sha256(sha256(dec[1..21]))[1..4] then + coin_err = "bad digest" + end if + end if +end procedure + +constant tests = { + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", -- OK + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", -- bad digest + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", -- OK + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", -- bad digest (checksum changed, original data.) + "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", -- bad digest (data changed, original checksum.) + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", -- not version 0 + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", -- address too long + "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", -- bad char + "1111111111111111111114oLvT2", -- OK? + "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j", -- OK (*NB*: apparently differs to Python solution, + -- but does agree with Racket and Rust entries) + "1badbadbadbadbadbadbadbadbadbadbad", -- not version 0 + "BZbvjr", -- first character is not 1 or 3 (checksum is fine, address too short) + "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", -- OK (from public_point_to_address) + $} + + for i=1 to length(tests) do + valid(tests[i]); + printf(1,"%s: %s\n", {tests[i], coin_err}) + end for +{} = wait_key() diff --git a/Task/Bitcoin-public-point-to-address/Phix/bitcoin-public-point-to-address.phix b/Task/Bitcoin-public-point-to-address/Phix/bitcoin-public-point-to-address.phix new file mode 100644 index 0000000000..b96c9daabe --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Phix/bitcoin-public-point-to-address.phix @@ -0,0 +1,42 @@ +include builtins\sha256.e +include builtins\ripemd160.e + +constant b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + +function base58(string s) +string out = "" + if length(s)!=25 then ?9/0 end if + for n=1 to 34 do + integer c = 0 + for i=1 to 25 do + c = c*256+s[i] + s[i] = floor(c/58) + c = mod(c,58) + end for + out &= b58[c+1] + end for + if out[$]='1' then + for i=length(out)-1 to 1 by -1 do + if out[i]!='1' then + out = out[1..i+1] + exit + end if + end for + end if + return reverse(out) +end function + +function coin_encode(string x, y) + if length(x)!=32 + or length(y)!=32 then + return "bad public point string" + end if + string s = "\x04" & x & y + string rmd = '\0'&ripemd160(sha256(s),false) + rmd &= sha256(sha256(rmd))[1..4] + string res = base58(rmd) + return res +end function + +?coin_encode(x"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", + x"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6") diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic.math b/Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic-1.math similarity index 100% rename from Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic.math rename to Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic-1.math diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic-2.math b/Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic-2.math new file mode 100644 index 0000000000..eddc3e1c2a --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Mathematica/bitmap-b-zier-curves-quadratic-2.math @@ -0,0 +1,2 @@ +pts = {{0, 0}, {1, -1}, {2, 1}}; +Graphics[{BezierCurve[pts], Green, Line[pts], Red, Point[pts]}] diff --git a/Task/Bitmap-Histogram/Python/bitmap-histogram.py b/Task/Bitmap-Histogram/Python/bitmap-histogram.py new file mode 100644 index 0000000000..bf1377665d --- /dev/null +++ b/Task/Bitmap-Histogram/Python/bitmap-histogram.py @@ -0,0 +1,42 @@ +from PIL import Image + +# Open the image +image = Image.open("lena.jpg") +# Get the width and height of the image +width, height = image.size +# Calculate the amount of pixels +amount = width * height + +# Total amount of greyscale +total = 0 +# B/W image +bw_image = Image.new('L', (width, height), 0) +# Bitmap image +bm_image = Image.new('1', (width, height), 0) + +for h in range(0, height): + for w in range(0, width): + r, g, b = image.getpixel((w, h)) + + greyscale = int((r + g + b) / 3) + total += greyscale + + bw_image.putpixel((w, h), gray_scale) + +# The average greyscale +avg = total / amount + +black = 0 +white = 1 + +for h in range(0, height): + for w in range(0, width): + v = bw_image.getpixel((w, h)) + + if v >= avg: + bm_image.putpixel((w, h), white) + else: + bm_image.putpixel((w, h), black) + +bw_image.show() +bm_image.show() diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math b/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math index d194d92cf6..21bcf03b16 100644 --- a/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math @@ -1,6 +1,7 @@ -convert[img_, out_] := - Module[{pipe = - StartProcess[{"WolframKernel", "-noinit", "-noprompt", "-run", - "Export[\"out.jpg\",ImportString[InputString[],\"PPM\"]]"}]}, - WriteString[pipe, ExportString[Image[Graphics[]], "PPM"]]; - Close[pipe];]; +convert[image_,out_]:=Module[{process=StartProcess[{ +"wolfram","-noinit","-noprompt","-run", +"Export[FromCharacterCode["~~ToString[ToCharacterCode[out]]~~"],ImportString[StringRiffle[Table[InputString[],{4}],FromCharacterCode[10]],FromCharacterCode[{80,80,77}]]]" +}]}, +WriteLine[process,image]; +WriteLine[process,"Quit[]"]; +]; diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math b/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math index 417ea1c7ed..7ccce54830 100644 --- a/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math @@ -1 +1 @@ -Export["out.bmp", ImportString[InputString[], "PPM"]]; +Export["data/bitmapOutputTest.ppm",Import["data/bitmapOutputTest.jpg"]]; diff --git a/Task/Bitmap/Scala/bitmap-3.scala b/Task/Bitmap/Scala/bitmap-3.scala index 2cd9f728ca..13e2876d32 100644 --- a/Task/Bitmap/Scala/bitmap-3.scala +++ b/Task/Bitmap/Scala/bitmap-3.scala @@ -1,11 +1,7 @@ -package org.rosettacode -package bitmapstore - -object RgbBitmap { - - import java.awt.image.BufferedImage - import java.awt.Color +import java.awt.image.BufferedImage +import java.awt.Color +object RgbBitmap extends App { class RgbBitmap(val dim: (Int, Int)) { def width = dim._1 def height = dim._2 @@ -14,44 +10,33 @@ object RgbBitmap { def apply(x: Int, y: Int) = new Color(image.getRGB(x, y)) - def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB) - def fill(c: Color) = - { - val g = image.getGraphics() - g.setColor(c) - g.fillRect(0, 0, width, height) - } + def fill(c: Color) = { + val g = image.getGraphics + g.setColor(c) + g.fillRect(0, 0, width, height) + } } object RgbBitmap { def apply(width: Int, height: Int) = new RgbBitmap(width, height) } - def main(args: Array[String]): Unit = { // Test Scala style - val img = RgbBitmap(50, 60) // Calls the apply function in companion object - img.fill(Color.CYAN) - img(5, 6) = Color.BLUE - assert(img(0, 1) == Color.CYAN) // Calls automagically the apply method in the class - assert(img(5, 6) == Color.BLUE) - assert(img.dim == (50, 60)) - - /** Even Javanese style testing is still possible. - */ - import language.reflectiveCalls // Just to satisfy a polite warning - val img0 = new RgbBitmap(50, 60) { // Wrappers to enable adhoc Javanese style - def getPixel(x: Int, y: Int) = this(x, y) - def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c - } - - img0.fill(Color.CYAN) - img0.setPixel(5, 6, Color.BLUE) - // Testing java style - assert(img0.getPixel(0, 1) == Color.CYAN) - assert(img0.getPixel(5, 6) == Color.BLUE) - assert(img0.width == 50) - assert(img0.height == 60) - println("No errors found.") + /** Even Javanese style testing is still possible. + */ + private val img0 = new RgbBitmap(50, 60) { // Wrappers to enable adhoc Javanese style + def getPixel(x: Int, y: Int) = this(x, y) + def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c } + + img0.fill(Color.CYAN) + img0.setPixel(5, 6, Color.BLUE) + // Testing in Java style + assert(img0.getPixel(0, 1) == Color.CYAN) + assert(img0.getPixel(5, 6) == Color.BLUE) + assert(img0.width == 50) + assert(img0.height == 60) + println("Tests successfully completed with no errors found.") } diff --git a/Task/Bitwise-IO/Go/bitwise-io-1.go b/Task/Bitwise-IO/Go/bitwise-io-1.go new file mode 100644 index 0000000000..0df7f60b41 --- /dev/null +++ b/Task/Bitwise-IO/Go/bitwise-io-1.go @@ -0,0 +1,203 @@ +// Package bit provides bit-wise IO to an io.Writer and from an io.Reader. +package bit + +import ( + "bufio" + "errors" + "io" +) + +// Order specifies the bit ordering within a byte stream. +type Order int + +const ( + // LSB is for Least Significant Bits first + LSB Order = iota + // MSB is for Most Significant Bits first + MSB +) + +// ==== Writing / Encoding ==== + +type writer interface { + io.ByteWriter + Flush() error +} + +// Writer implements bit-wise writing to an io.Writer. +type Writer struct { + w writer + order Order + write func(uint32, uint) error // writeLSB or writeMSB + bits uint32 + nBits uint + err error +} + +// writeLSB writes `width` bits of `c` in LSB order. +func (w *Writer) writeLSB(c uint32, width uint) error { + w.bits |= c << w.nBits + w.nBits += width + for w.nBits >= 8 { + if err := w.w.WriteByte(uint8(w.bits)); err != nil { + return err + } + w.bits >>= 8 + w.nBits -= 8 + } + return nil +} + +// writeMSB writes `width` bits of `c` in MSB order. +func (w *Writer) writeMSB(c uint32, width uint) error { + w.bits |= c << (32 - width - w.nBits) + w.nBits += width + for w.nBits >= 8 { + if err := w.w.WriteByte(uint8(w.bits >> 24)); err != nil { + return err + } + w.bits <<= 8 + w.nBits -= 8 + } + return nil +} + +// WriteBits writes up to 16 bits of `c` to the underlying writer. +// Even for MSB ordering the bits are taken from the lower bits of `c`. +// (e.g.Β WriteBits(0x0f,4) writes four 1 bits). +func (w *Writer) WriteBits(c uint16, width uint) error { + if w.err == nil { + w.err = w.write(uint32(c), width) + } + return w.err +} + +var errClosed = errors.New("bit reader/writer is closed") + +// Close closes the writer, flushing any pending output. +// It does not close the underlying writer. +func (w *Writer) Close() error { + if w.err != nil { + if w.err == errClosed { + return nil + } + return w.err + } + // Write the final bits (zero padded). + if w.nBits > 0 { + if w.order == MSB { + w.bits >>= 24 + } + if w.err = w.w.WriteByte(uint8(w.bits)); w.err != nil { + return w.err + } + } + w.err = w.w.Flush() + if w.err != nil { + return w.err + } + + // Make any future calls to Write return errClosed. + w.err = errClosed + return nil +} + +// NewWriter returns a new bit Writer that writes completed bytes to `w`. +func NewWriter(w io.Writer, order Order) *Writer { + bw := &Writer{order: order} + switch order { + case LSB: + bw.write = bw.writeLSB + case MSB: + bw.write = bw.writeMSB + default: + bw.err = errors.New("bit writer: unknown order") + return bw + } + if byteWriter, ok := w.(writer); ok { + bw.w = byteWriter + } else { + bw.w = bufio.NewWriter(w) + } + return bw +} + +// ==== Reading / Decoding ==== + +// Reader implements bit-wise reading from an io.Reader. +type Reader struct { + r io.ByteReader + bits uint32 + nBits uint + read func(width uint) (uint16, error) // readLSB or readMSB + err error +} + +func (r *Reader) readLSB(width uint) (uint16, error) { + for r.nBits < width { + x, err := r.r.ReadByte() + if err != nil { + return 0, err + } + r.bits |= uint32(x) << r.nBits + r.nBits += 8 + } + bits := uint16(r.bits & (1<>= width + r.nBits -= width + return bits, nil +} + +func (r *Reader) readMSB(width uint) (uint16, error) { + for r.nBits < width { + x, err := r.r.ReadByte() + if err != nil { + return 0, err + } + r.bits |= uint32(x) << (24 - r.nBits) + r.nBits += 8 + } + bits := uint16(r.bits >> (32 - width)) + r.bits <<= width + r.nBits -= width + return bits, nil +} + +// ReadBits reads up to 16 bits from the underlying reader. +func (r *Reader) ReadBits(width uint) (uint16, error) { + var bits uint16 + if r.err == nil { + bits, r.err = r.read(width) + } + return bits, r.err +} + +// Close closes the reader. +// It does not close the underlying reader. +func (r *Reader) Close() error { + if r.err != nil && r.err != errClosed { + return r.err + } + r.err = errClosed + return nil +} + +// NewReader returns a new bit Reader that reads bytes from `r`. +func NewReader(r io.Reader, order Order) *Reader { + br := new(Reader) + switch order { + case LSB: + br.read = br.readLSB + case MSB: + br.read = br.readMSB + default: + br.err = errors.New("bit writer: unknown order") + return br + } + if byteReader, ok := r.(io.ByteReader); ok { + br.r = byteReader + } else { + br.r = bufio.NewReader(r) + } + return br +} diff --git a/Task/Bitwise-IO/Go/bitwise-io-2.go b/Task/Bitwise-IO/Go/bitwise-io-2.go new file mode 100644 index 0000000000..6f6d3ebebd --- /dev/null +++ b/Task/Bitwise-IO/Go/bitwise-io-2.go @@ -0,0 +1,65 @@ +package bit + +import ( + "bytes" + "fmt" + "io" + "log" +) + +func ExampleWriter_WriteBits() { + var buf bytes.Buffer + bw := NewWriter(&buf, MSB) + bw.WriteBits(0x0f, 4) // Writes 1111 + bw.WriteBits(0x00, 1) // 0 + bw.WriteBits(0x13, 5) // 1001 1 + // Close will flush with zero bits, in this case + // 0000 00 + if err := bw.Close(); err != nil { + log.Fatal(err) + } + fmt.Printf("%08b", buf.Bytes()) + // Output: + // [11110100 11000000] +} + +func Example() { + const message = "This is a test." + fmt.Printf("%q as bytes: % 02[1]X\n", message, []byte(message)) + fmt.Printf(" original bits: %08b\n", []byte(message)) + + // Re-write in 7 bit chunks to buf: + var buf bytes.Buffer + bw := NewWriter(&buf, MSB) + for _, r := range message { + bw.WriteBits(uint16(r), 7) // nolint: errcheck + } + if err := bw.Close(); err != nil { + log.Fatal(err) + } + fmt.Printf("Written bitstream: %08b\n", buf.Bytes()) + fmt.Printf("Written bytes: % 02X\n", buf.Bytes()) + + // Read back in 7 bit chunks: + br := NewReader(&buf, MSB) + var result []byte + for { + v, err := br.ReadBits(7) + if err != nil { + if err != io.EOF { + log.Fatal(err) + } + break + } + if v != 0 { + result = append(result, byte(v)) + } + } + fmt.Printf("Read back as \"%s\"\n", result) + // Output: + // "This is a test." as bytes: 54 68 69 73 20 69 73 20 61 20 74 65 73 74 2E + // original bits: [01010100 01101000 01101001 01110011 00100000 01101001 01110011 00100000 01100001 00100000 01110100 01100101 01110011 01110100 00101110] + // Written bitstream: [10101001 10100011 01001111 00110100 00011010 01111001 10100000 11000010 10000011 10100110 01011110 01111101 00010111 00000000] + // Written bytes: A9 A3 4F 34 1A 79 A0 C2 83 A6 5E 7D 17 00 + // Read back as "This is a test." +} diff --git a/Task/Bitwise-operations/ARM-Assembly/bitwise-operations.arm b/Task/Bitwise-operations/ARM-Assembly/bitwise-operations.arm new file mode 100644 index 0000000000..af8d83ea9a --- /dev/null +++ b/Task/Bitwise-operations/ARM-Assembly/bitwise-operations.arm @@ -0,0 +1,158 @@ +/* ARM assembly Raspberry PI */ +/* program binarydigit.s */ +/* Constantes */ +.equ STDOUT, 1 +.equ WRITE, 4 +.equ EXIT, 1 +/* Initialized data */ +.data +szMessResultAnd: .asciz "Result of And : \n" +szMessResultOr: .asciz "Result of Or : \n" +szMessResultEor: .asciz "Result of Exclusif Or : \n" +szMessResultNot: .asciz "Result of Not : \n" +szMessResultLsl: .asciz "Result of left shift : \n" +szMessResultLsr: .asciz "Result of right shift : \n" +szMessResultAsr: .asciz "Result of Arithmetic right shift : \n" +szMessResultRor: .asciz "Result of rotate right : \n" +szMessResultRrx: .asciz "Result of rotate right with extend : \n" +szMessResultClear: .asciz "Result of Bit Clear : \n" + +sMessAffBin: .ascii "Register value : " +sZoneBin: .space 36,' ' + .asciz "\n" + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* save des 2 registres */ + ldr r0,iAdrszMessResultAnd + bl affichageMess + mov r0,#5 + and r0,#15 + bl affichage2 + ldr r0,iAdrszMessResultOr + bl affichageMess + mov r0,#5 + orr r0,#15 + bl affichage2 + ldr r0,iAdrszMessResultEor + bl affichageMess + mov r0,#5 + eor r0,#15 + bl affichage2 + ldr r0,iAdrszMessResultNot + bl affichageMess + mov r0,#5 + mvn r0,r0 + bl affichage2 + ldr r0,iAdrszMessResultLsl + bl affichageMess + mov r0,#5 + lsl r0,#1 + bl affichage2 + ldr r0,iAdrszMessResultLsr + bl affichageMess + mov r0,#5 + lsr r0,#1 + bl affichage2 + ldr r0,iAdrszMessResultAsr + bl affichageMess + mov r0,#-5 + bl affichage2 + mov r0,#-5 + asr r0,#1 + bl affichage2 + ldr r0,iAdrszMessResultRor + bl affichageMess + mov r0,#5 + ror r0,#1 + bl affichage2 + ldr r0,iAdrszMessResultRrx + bl affichageMess + mov r0,#5 + mov r1,#15 + rrx r0,r1 + bl affichage2 + ldr r0,iAdrszMessResultClear + bl affichageMess + mov r0,#5 + bic r0,#0b100 @ clear 3ieme bit + bl affichage2 + bic r0,#4 @ clear 3ieme bit ( 4 = 100 binary) + bl affichage2 + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrszMessResultAnd: .int szMessResultAnd +iAdrszMessResultOr: .int szMessResultOr +iAdrszMessResultEor: .int szMessResultEor +iAdrszMessResultNot: .int szMessResultNot +iAdrszMessResultLsl: .int szMessResultLsl +iAdrszMessResultLsr: .int szMessResultLsr +iAdrszMessResultAsr: .int szMessResultAsr +iAdrszMessResultRor: .int szMessResultRor +iAdrszMessResultRrx: .int szMessResultRrx +iAdrszMessResultClear: .int szMessResultClear +/******************************************************************/ +/* register display in binary */ +/******************************************************************/ +/* r0 contains the register */ +affichage2: + push {r0,lr} /* save registers */ + push {r1-r5} /* save others registers */ + mrs r5,cpsr /* saves state register in r5 */ + ldr r1,iAdrsZoneBin + mov r2,#0 @ read bit position counter + mov r3,#0 @ position counter of the written character +1: @ loop + lsls r0,#1 @ left shift with flags + movcc r4,#48 @ flag carry off character '0' + movcs r4,#49 @ flag carry on character '1' + strb r4,[r1,r3] @ character -> display zone + add r2,r2,#1 @ + 1 read bit position counter + add r3,r3,#1 @ + 1 position counter of the written character + cmp r2,#8 @ 8 bits read + addeq r3,r3,#1 @ + 1 position counter of the written character + cmp r2,#16 @ etc + addeq r3,r3,#1 + cmp r2,#24 + addeq r3,r3,#1 + cmp r2,#31 @ 32 bits shifted ? + ble 1b @ no -> loop + + ldr r0,iAdrsZoneMessBin @ address of message result + bl affichageMess @ display result + +100: + msr cpsr,r5 /*restaur state register */ + pop {r1-r5} /* restaur others registers */ + pop {r0,lr} + bx lr +iAdrsZoneBin: .int sZoneBin +iAdrsZoneMessBin: .int sMessAffBin + +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registres */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system write */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registres */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ diff --git a/Task/Box-the-compass/Ring/box-the-compass.ring b/Task/Box-the-compass/Ring/box-the-compass.ring index 8f3eeb0ee3..9ecfe61955 100644 --- a/Task/Box-the-compass/Ring/box-the-compass.ring +++ b/Task/Box-the-compass/Ring/box-the-compass.ring @@ -1,7 +1,4 @@ # Project : Box the compass -# Date : 2017/12/31 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : names = ["North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", diff --git a/Task/Break-OO-privacy/00DESCRIPTION b/Task/Break-OO-privacy/00DESCRIPTION index b781e233e5..937af5f996 100644 --- a/Task/Break-OO-privacy/00DESCRIPTION +++ b/Task/Break-OO-privacy/00DESCRIPTION @@ -8,6 +8,7 @@ {{omit from|Locomotive Basic}} {{omit from|Lotus 123 Macro Scripting}} {{omit from|Mathematica}} +{{omit from|Rust}} {{omit from|ZX Spectrum Basic}} Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. diff --git a/Task/Brownian-tree/Perl/brownian-tree.pl b/Task/Brownian-tree/Perl/brownian-tree.pl index fa3488b28d..0fb7f44d8c 100644 --- a/Task/Brownian-tree/Perl/brownian-tree.pl +++ b/Task/Brownian-tree/Perl/brownian-tree.pl @@ -101,13 +101,11 @@ my $count; PARTICLE: while (1) { my $a = rand(2 * PI); my $p = [ $r_start * cos($a), $r_start * sin($a) ]; - while ($_ = move($p)) { - given ($_) { - when (1) { next } - when (2) { $count++; last; } - when (3) { last PARTICLE } - default { last } - } + while (my $m = move($p)) { + if ($m == 1) { next } + elsif ($m == 2) { $count++; last; } + elsif ($m == 3) { last PARTICLE } + else { last } } print STDERR "$count $max_dist/@{[int($r_start)]}/@{[STOP_RADIUS]}\r" unless $count% 7; } diff --git a/Task/Brownian-tree/Ring/brownian-tree.ring b/Task/Brownian-tree/Ring/brownian-tree.ring index 0a35440ec6..67e6c82f50 100644 --- a/Task/Brownian-tree/Ring/brownian-tree.ring +++ b/Task/Brownian-tree/Ring/brownian-tree.ring @@ -1,8 +1,4 @@ # Project : Brownian tree -# Date : 2018/02/16 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : - load "stdlib.ring" load "guilib.ring" diff --git a/Task/Brownian-tree/Scala/brownian-tree.scala b/Task/Brownian-tree/Scala/brownian-tree.scala new file mode 100644 index 0000000000..1adb121bee --- /dev/null +++ b/Task/Brownian-tree/Scala/brownian-tree.scala @@ -0,0 +1,50 @@ +import java.awt.Graphics +import java.awt.image.BufferedImage + +import javax.swing.JFrame + +import scala.collection.mutable.ListBuffer + +object BrownianTree extends App { + val rand = scala.util.Random + + class BrownianTree extends JFrame("Brownian Tree") with Runnable { + setBounds(100, 100, 400, 300) + val img = new BufferedImage(getWidth, getHeight, BufferedImage.TYPE_INT_RGB) + + override def paint(g: Graphics): Unit = g.drawImage(img, 0, 0, this) + + override def run(): Unit = { + class Particle(var x: Int = rand.nextInt(img.getWidth), + var y: Int = rand.nextInt(img.getHeight)) { + + /* returns false if either out of bounds or collided with tree */ + def move: Boolean = { + val (dx, dy) = (rand.nextInt(3) - 1, rand.nextInt(3) - 1) + if ((x + dx < 0) || (y + dy < 0) || + (y + dy >= img.getHeight) || (x + dx >= img.getWidth)) false + else { + x += dx + y += dy + if ((img.getRGB(x, y) & 0xff00) == 0xff00) { + img.setRGB(x - dx, y - dy, 0xff00) + false + } else true + } + } + } + + var particles = ListBuffer.fill(20000)(new Particle) + while (particles.nonEmpty) { + particles = particles.filter(_.move) + repaint() + } + } + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE) + img.setRGB(img.getWidth / 2, img.getHeight / 2, 0xff00) + setVisible(true) + } + + new Thread(new BrownianTree).start() +} diff --git a/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring b/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring index 20eb362dfd..2a0439078c 100644 --- a/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring +++ b/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring @@ -1,7 +1,4 @@ # Project : Bulls and cows/Player -# Date : 2017/11/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : secret = "" while len(secret) != 4 diff --git a/Task/Bulls-and-cows/Ring/bulls-and-cows.ring b/Task/Bulls-and-cows/Ring/bulls-and-cows.ring index 2d50ebccce..45e8375400 100644 --- a/Task/Bulls-and-cows/Ring/bulls-and-cows.ring +++ b/Task/Bulls-and-cows/Ring/bulls-and-cows.ring @@ -1,7 +1,4 @@ # Project : Bulls and cows -# Date : 2017/11/19 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : secret = "" while len(secret) != 4 diff --git a/Task/CRC-32/Mathematica/crc-32.math b/Task/CRC-32/Mathematica/crc-32.math index a3a1c7c150..72305835d6 100644 --- a/Task/CRC-32/Mathematica/crc-32.math +++ b/Task/CRC-32/Mathematica/crc-32.math @@ -1,2 +1,6 @@ -IntegerString[Hash["The quick brown fox jumps over the lazy dog", "CRC32"], 16, 8] --> "414fa339" +type="CRC32"; (*pick one out of 13 predefined hash types*) +StringForm[ +"The "<>type<>" hash code of \"``\" is ``.", +s="The quick brown fox jumps over the lazy dog", +Hash[s,type,"HexString"] +] diff --git a/Task/CRC-32/VAX-Assembly/crc-32.vax b/Task/CRC-32/VAX-Assembly/crc-32.vax new file mode 100644 index 0000000000..bd2319d08f --- /dev/null +++ b/Task/CRC-32/VAX-Assembly/crc-32.vax @@ -0,0 +1,24 @@ + EDB88320 0000 1 poly: .long ^xedb88320 ;crc32 + 00000044 0004 2 table: .blkl 16 + 0044 3 + 4C 58 21 0000004C'010E0000' 0044 4 fmt: .ascid "!XL" ;result format +36 35 34 33 32 31 00000057'010E0000' 004F 5 result: .ascid "12345678" ; and buffer + 38 37 005D + 0000 005F 6 .entry crc,0 + A0 AF 7F 0061 7 pushaq table ;fill table + 99 AF DF 0064 8 pushal poly ; for + 00000000'GF 02 FB 0067 9 calls #2, g^lib$crc_table ; crc opcode + 2B' FFFFFFFF 8F 93 AF 0B 006E 10 crc table, #-1, s^#len, b^msg ;table,init,len,string + 98'AF 0077 + 50 50 D2 0079 11 mcoml r0, r0 ;invert result + 007C 12 $fao_s ctrstr = fmt, outbuf = result, p1 = r0 ; format + BF AF 7F 008D 13 pushaq result ;and show + 00000000'GF 01 FB 0090 14 calls #1, g^lib$put_output ; result 414fa339 + 04 0097 15 ret + 0098 16 +72 62 20 6B 63 69 75 71 20 65 68 54 0098 17 msg: .ascii "The quick brown fox jumps over the lazy dog" +70 6D 75 6A 20 78 6F 66 20 6E 77 6F 00A4 +6C 20 65 68 74 20 72 65 76 6F 20 73 00B0 + 67 6F 64 20 79 7A 61 00BC + 0000002B 00C3 18 len = .-msg + 00C3 19 .end crc diff --git a/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl b/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl index 074111c19e..17391318d8 100644 --- a/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl +++ b/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl @@ -25,7 +25,7 @@ $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $#header; -push $_, sum(@$_) for @rows; +push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; diff --git a/Task/CSV-data-manipulation/Ring/csv-data-manipulation.ring b/Task/CSV-data-manipulation/Ring/csv-data-manipulation.ring new file mode 100644 index 0000000000..1a4803e649 --- /dev/null +++ b/Task/CSV-data-manipulation/Ring/csv-data-manipulation.ring @@ -0,0 +1,34 @@ +# Project : CSV data manipulation + +load "stdlib.ring" +fnin = "input.csv" +fnout = "output.csv" +fpin = fopen(fnin,"r") +fpout = fopen(fnout,"r") +csv = read(fnin) +nr = 0 +csvstr = "" + +while not feof(fpin) + sum = 0 + nr = nr + 1 + line = readline(fpin) + if nr = 1 + line = substr(line,nl,"") + line = line + ",SUM" + csvstr = csvstr + line + windowsnl() + else + csvarr = split(line,",") + for n = 1 to len(csvarr) + sum = sum + csvarr[n] + next + line = substr(line,nl,"") + line = line + "," + string(sum) + csvstr = csvstr + line + windowsnl() + ok +end +write(fnout,csvstr) +csvend = read(fnout) +fclose(fpin) +fclose(fpout) +see csvend + nl diff --git a/Task/Caesar-cipher/Astro/caesar-cipher.astro b/Task/Caesar-cipher/Astro/caesar-cipher.astro index 9b6b670bbb..f17ce68cb2 100644 --- a/Task/Caesar-cipher/Astro/caesar-cipher.astro +++ b/Task/Caesar-cipher/Astro/caesar-cipher.astro @@ -1,8 +1,10 @@ fun caesar(s, k, decode: false): - if decode: k = 26 - k - char({(ord(c) - 65 + k) mod 26 + 65) | c in s.upper() where "a" <= c <= "A"}).join() + if decode: + k = 26 - k + char((ord(c) - 65 + k) mod 26 + 65) | c in uppercase(s) where 'a' <= c <= 'A').join() 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)) +print(enc), :(caesar(enc, 11, decode: true)) diff --git a/Task/Caesar-cipher/Ring/caesar-cipher.ring b/Task/Caesar-cipher/Ring/caesar-cipher.ring index c22a7efe42..3c1cdd1342 100644 --- a/Task/Caesar-cipher/Ring/caesar-cipher.ring +++ b/Task/Caesar-cipher/Ring/caesar-cipher.ring @@ -1,7 +1,4 @@ # Project : Caesar cipher -# Date : 2017/11/11 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : cipher = "pack my box with five dozen liquor jugs" abc = "abcdefghijklmnopqrstuvwxyz" diff --git a/Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher.zx b/Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher-1.zx similarity index 100% rename from Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher.zx rename to Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher-1.zx diff --git a/Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher-2.zx b/Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher-2.zx new file mode 100644 index 0000000000..12915b6deb --- /dev/null +++ b/Task/Caesar-cipher/ZX-Spectrum-Basic/caesar-cipher-2.zx @@ -0,0 +1,30 @@ +10 LET t$="Wonderful ZX Spectrum." +20 LET c$="a":REM more characters, more difficult for decript +30 LET CIFRA=1: LET DESCIFRA=-1 +40 PRINT t$'' +50 LET modo=CIFRA: GO SUB 1000 +60 PRINT r$'' +70 LET t$=r$: LET modo=DESCIFRA: GO SUB 1000 +80 PRINT r$'' +90 STOP +1000 REM Criptex +1010 LET p$="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 .,;:()-" +1020 LET longPatron=LEN p$ +1030 LET longTexto=LEN t$ +1040 LET longClave=LEN c$ +1045 LET k=0: LET r$="" +1050 FOR i=1 TO longTexto +1060 LET k=k+1: IF k>longClave THEN LET k=1 +1070 LET x$=t$(i) +1080 FOR j=1 TO longPatron +1090 IF x$=p$(j) THEN LET delta=j: GO TO 1110 +1100 NEXT j +1110 LET x$=c$(k) +1120 FOR j=1 TO longPatron +1130 IF x$=p$(j) THEN LET delta=delta+modo*j: GO TO 1150 +1140 NEXT j +1150 IF delta>longPatron THEN LET delta=delta-longPatron: GO TO 1170 +1160 IF delta<1 THEN LET delta=longPatron+delta +1170 LET r$=r$+p$(delta) +1180 NEXT i +1190 RETURN diff --git a/Task/Calendar---for-REAL-programmers/Ring/calendar---for-real-programmers.ring b/Task/Calendar---for-REAL-programmers/Ring/calendar---for-real-programmers.ring new file mode 100644 index 0000000000..89bce28408 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Ring/calendar---for-real-programmers.ring @@ -0,0 +1,158 @@ +# PROJECT : CALENDAR - FOR "REAL" PROGRAMMERS +# DATE : 2018/06/28 +# AUTHOR : GAL ZSOLT (~ CALMOSOFT ~) +# EMAIL : + +LOAD "GUILIB.RING" +LOAD "STDLIB.RING" + +NEW QAPP + { + WIN1 = NEW QWIDGET() { + DAY = LIST(12) + POS = NEWLIST(12,37) + MONTH = LIST(12) + WEEK = LIST(7) + WEEKDAY = LIST(7) + BUTTON = NEWLIST(7,6) + MONTHSNAMES = LIST(12) + WEEK = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"] + MONTHS = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", + "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"] + DAYSNEW = [[5,1], [6,2], [7,3], [1,4], [2,5], [3,6], [4,7]] + MO = [4,0,0,3,5,1,3,6,2,4,0,2] + MON = [31,28,31,30,31,30,31,31,30,31,30,31] + M2 = (((1969-1900)%7) + FLOOR((1969 - 1900)/4) % 7) % 7 + FOR N = 1 TO 12 + MONTH[N] = (MO[N] + M2) % 7 + X = (MONTH[N] + 1) % 7 + 1 + FOR M = 1 TO LEN(DAYSNEW) + IF DAYSNEW[M][1] = X + NR = M + OK + NEXT + DAY[N] = DAYSNEW[NR][2] + NEXT + FOR M = 1 TO 12 + FOR N = 1 TO DAY[M] - 1 + POS[M][N] = " " + NEXT + NEXT + FOR M = 1 TO 12 + FOR N = DAY[M] TO 37 + IF N < (MON[M] + DAY[M]) + POS[M][N] = N - DAY[M] + 1 + ELSE + POS[M][N] = " " + OK + NEXT + NEXT + SETWINDOWTITLE("CALENDAR") + SETGEOMETRY(100,100,650,800) + LABEL1 = NEW QLABEL(WIN1) { + SETGEOMETRY(10,10,800,600) + SETTEXT("") + } + YEAR = NEW QPUSHBUTTON(WIN1) + { + SETGEOMETRY(280,20,63,20) + YEAR.SETTEXT("1969") + } + FOR N = 1 TO 4 + NR = (N-1)*3+1 + SHOWMONTHS(NR) + NEXT + FOR N = 1 TO 12 + SHOWWEEKS(N) + NEXT + FOR N = 1 TO 12 + SHOWDAYS(N) + NEXT + SHOW() + } + EXEC() + } + +FUNC SHOWMONTHS(M) + FOR N = M TO M + 2 + MONTHSNAMES[N] = NEW QPUSHBUTTON(WIN1) + { + IF N%3 = 1 + COL = 120 + ROWNR = FLOOR(N/3) + IF ROWNR = 0 + ROWNR = N/3 + OK + IF N = 1 + ROW = 40 + ELSE + ROW = 40+ROWNR*180 + OK + ELSE + COLNR = N%3 + IF COLNR = 0 + COLNR = 3 + OK + ROWNR = FLOOR(N/3) + IF N%3 = 0 + ROWNR = FLOOR(N/3)-1 + OK + COL = 120 + (COLNR-1)*160 + ROW = 40 + ROWNR*180 + OK + SETGEOMETRY(COL,ROW,63,20) + MONTHSNAMES[N].SETTEXT(MONTHS[N]) + } + NEXT + +FUNC SHOWWEEKS(N) + FOR M = 1 TO 7 + COL = M%7 + IF COL = 0 COL = 7 OK + WEEKDAY[M] = NEW QPUSHBUTTON(WIN1) + { + COLNR = N % 3 + IF COLNR = 0 + COLNR = 3 + OK + ROWNR = FLOOR(N/3) + IF N%3 = 0 + ROWNR = FLOOR(N/3)-1 + OK + COLBEGIN = 60 + (COLNR-1)*160 + ROWBEGIN = 60 + (ROWNR)*180 + SETGEOMETRY(COLBEGIN+COL*20,ROWBEGIN,25,20) + WEEKDAY[M].SETTEXT(WEEK[M]) + } + NEXT + +FUNC SHOWDAYS(IND) + ROWNR = FLOOR(IND/3) + IF IND%3 = 0 + ROWNR = FLOOR(IND/3)-1 + OK + ROWBEGIN = 60+ROWNR*180 + FOR M = 1 TO 6 + FOR N = 1 TO 7 + COL = N%7 + IF COL = 0 COL = 7 OK + ROW = M + BUTTON[N][M] = NEW QPUSHBUTTON(WIN1) + { + IF IND%3 = 1 + COLBEGIN = 60 + ELSEIF IND%3 = 2 + COLBEGIN = 220 + ELSE + COLBEGIN = 380 + OK + SETGEOMETRY(COLBEGIN+COL*20,ROWBEGIN+ROW*20,25,20) + NR = (M-1)*7+N + IF NR <= 37 + IF POS[IND][NR] != " " + BUTTON[N][M].SETTEXT(STRING(POS[IND][NR])) + OK + OK + } + NEXT + NEXT diff --git a/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh b/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh index 0eb4b353a2..43cb1817a8 100644 --- a/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh +++ b/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh @@ -1 +1,5 @@ -cal -m 1969 | tr a-z A-Z +CAL=CAL +TR=TR +A=A +Z=Z +LANG=C ${CAL,,} 1969 | ${TR,,} ${A,}-${Z,} A-Z diff --git a/Task/Calendar/C/calendar.c b/Task/Calendar/C/calendar.c index 81a71da6fe..227957e25b 100644 --- a/Task/Calendar/C/calendar.c +++ b/Task/Calendar/C/calendar.c @@ -11,7 +11,7 @@ struct months { int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, - { "Februray", 28, 0, 0 }, + { "February", 28, 0, 0 }, { "March", 31, 0, 0 }, { "April", 30, 0, 0 }, { "May", 31, 0, 0 }, diff --git a/Task/Calendar/Ring/calendar.ring b/Task/Calendar/Ring/calendar.ring index b046866518..1326e7514b 100644 --- a/Task/Calendar/Ring/calendar.ring +++ b/Task/Calendar/Ring/calendar.ring @@ -1,7 +1,4 @@ # Project : Calendar -# Date : 2018/06/05 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "guilib.ring" load "stdlib.ring" diff --git a/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring b/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring index d57d667f5a..bdee86399e 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring +++ b/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring @@ -1,7 +1,4 @@ # Project : Carmichael 3 strong pseudoprimes -# Date : 2017/11/29 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "The following are Carmichael munbers for p1 <= 61:" + nl see "p1 p2 p3 product" + nl diff --git a/Task/Casting-out-nines/Nim/casting-out-nines.nim b/Task/Casting-out-nines/Nim/casting-out-nines.nim index 21d3200d68..0219578837 100644 --- a/Task/Casting-out-nines/Nim/casting-out-nines.nim +++ b/Task/Casting-out-nines/Nim/casting-out-nines.nim @@ -1,8 +1,8 @@ import sequtils -iterator castOut(base = 10, start = 1, ending = 999_999) = +iterator castOut(base = 10, start = 1, ending = 999_999): int = var ran: seq[int] = @[] - for y in 0 .. co9(1, 10, 99, [1,9,45,55,99]) co9(1, 10, 1000, [1,9,45,55,99,297,703,999]) diff --git a/Task/Catalan-numbers/Swift/catalan-numbers.swift b/Task/Catalan-numbers/Swift/catalan-numbers.swift new file mode 100644 index 0000000000..559b863bb5 --- /dev/null +++ b/Task/Catalan-numbers/Swift/catalan-numbers.swift @@ -0,0 +1,12 @@ +func catalan(_ n: Int) -> Int { + switch n { + case 0: + return 1 + case _: + return catalan(n - 1) * 2 * (2 * n - 1) / (n + 1) + } +} + +for i in 1..<16 { + print("catalan(\(i)) => \(catalan(i))") +} diff --git a/Task/Catamorphism/Nim/catamorphism.nim b/Task/Catamorphism/Nim/catamorphism.nim index 064178fb17..2f4015cafe 100644 --- a/Task/Catamorphism/Nim/catamorphism.nim +++ b/Task/Catamorphism/Nim/catamorphism.nim @@ -6,7 +6,7 @@ block: addition = foldl(numbers, a + b) substraction = foldl(numbers, a - b) multiplication = foldl(numbers, a * b) - words = @["nim", "rod", "is", "cool"] + words = @["nim", "is", "cool"] concatenation = foldl(words, a & b) block: @@ -15,5 +15,5 @@ block: addition = foldr(numbers, a + b) substraction = foldr(numbers, a - b) multiplication = foldr(numbers, a * b) - words = @["nim", "rod", "is", "cool"] + words = @["nim", "is", "cool"] concatenation = foldr(words, a & b) diff --git a/Task/Character-codes/Emacs-Lisp/character-codes.l b/Task/Character-codes/Emacs-Lisp/character-codes.l new file mode 100644 index 0000000000..57f13fcd13 --- /dev/null +++ b/Task/Character-codes/Emacs-Lisp/character-codes.l @@ -0,0 +1,2 @@ +(string-to-char "a") +(message "%c" 97) diff --git a/Task/Check-Machin-like-formulas/FreeBASIC/check-machin-like-formulas.freebasic b/Task/Check-Machin-like-formulas/FreeBASIC/check-machin-like-formulas.freebasic new file mode 100644 index 0000000000..365fa6b5ac --- /dev/null +++ b/Task/Check-Machin-like-formulas/FreeBASIC/check-machin-like-formulas.freebasic @@ -0,0 +1,153 @@ +' version 07-04-2018 +' compile with: fbc -s console + +#Include "gmp.bi" + +#Define _a(Q) (@(Q)->_mp_num) 'a +#Define _b(Q) (@(Q)->_mp_den) 'b + +Data "[1, 1, 2] [1, 1, 3]" +Data "[2, 1, 3] [1, 1, 7]" +Data "[4, 1, 5] [-1, 1, 239]" +Data "[5, 1, 7] [2, 3, 79]" +Data "[1, 1, 2] [1, 1, 5] [1, 1, 8]" +Data "[4, 1, 5] [-1, 1, 70] [1, 1, 99]" +Data "[5, 1, 7] [4, 1, 53] [2, 1, 4443]" +Data "[6, 1, 8] [2, 1, 57] [1, 1, 239]" +Data "[8, 1, 10] [-1, 1, 239] [-4, 1, 515]" +Data "[12, 1, 18] [8, 1, 57] [-5, 1, 239]" +Data "[16, 1, 21] [3, 1, 239] [4, 3, 1042]" +Data "[22, 1, 28] [2, 1, 443] [-5, 1, 1393] [-10, 1, 11018]" +Data "[22, 1, 38] [17, 7, 601] [10, 7, 8149]" +Data "[44, 1, 57] [7, 1, 239] [-12, 1, 682] [24, 1, 12943]" +Data "[88, 1, 172] [51, 1, 239] [32, 1, 682] [44, 1, 5357] [68, 1, 12943]" +Data "[88, 1, 172] [51, 1, 239] [32, 1, 682] [44, 1, 5357] [68, 1, 12944]" +Data "" + +Sub work2do (ByRef a As LongInt, f1 As mpq_ptr) + + Dim As LongInt flag = -1 + + Dim As Mpq_ptr x, y, z + x = Allocate(Len(__mpq_struct)) : Mpq_init(x) + y = Allocate(Len(__mpq_struct)) : Mpq_init(y) + z = Allocate(Len(__mpq_struct)) : Mpq_init(z) + + Dim As Mpz_ptr temp1, temp2 + temp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp1) + temp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp2) + + mpq_set(y, f1) + + While a > 0 + If (a And 1) = 1 Then + If flag = -1 Then + mpq_set(x, y) + flag = 0 + Else + Mpz_mul(temp1, _a(x), _b(y)) + Mpz_mul(temp2, _b(x), _a(y)) + Mpz_add(_a(z), temp1, temp2) + Mpz_mul(temp1, _b(x), _b(y)) + Mpz_mul(temp2, _a(x), _a(y)) + Mpz_sub(_b(z), temp1, temp2) + mpq_canonicalize(z) + mpq_set(x, z) + End If + End If + + Mpz_mul(temp1, _a(y), _b(y)) + Mpz_mul(temp2, _b(y), _a(y)) + Mpz_add(_a(z), temp1, temp2) + Mpz_mul(temp1, _b(y), _b(y)) + Mpz_mul(temp2, _a(y), _a(y)) + Mpz_sub(_b(z), temp1, temp2) + mpq_canonicalize(z) + mpq_set(y, z) + + a = a Shr 1 + Wend + + mpq_set(f1, x) + +End Sub + +' ------=< MAIN >=------ + +Dim As Mpq_ptr f1, f2, f3 +f1 = Allocate(Len(__mpq_struct)) : Mpq_init(f1) +f2 = Allocate(Len(__mpq_struct)) : Mpq_init(f2) +f3 = Allocate(Len(__mpq_struct)) : Mpq_init(f3) + +Dim As Mpz_ptr temp1, temp2 +temp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp1) +temp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp2) + +Dim As mpf_ptr float +float = Allocate(Len(__mpf_struct)) : Mpf_init(float) + +Dim As LongInt m1, a1, b1, flag, t1, t2, t3, t4 +Dim As String s, s1, s2, s3, sign +Dim As ZString Ptr zstr + +Do + + Read s + If s = "" Then Exit Do + flag = -1 + + While s <> "" + t1 = InStr(s, "[") +1 + t2 = InStr(t1, s, ",") +1 + t3 = InStr(t2, s, ",") +1 + t4 = InStr(t3, s, "]") + s1 = Trim(Mid(s, t1, t2 - t1 -1)) + s2 = Trim(Mid(s, t2, t3 - t2 -1)) + s3 = Trim(Mid(s, t3, t4 - t3)) + m1 = Val(s1) + a1 = Val(s2) + b1 = Val(s3) + + sign = IIf(m1 < 0, " - ", " + ") + If m1 < 0 Then a1 = -a1 : m1 = Abs(m1) + s = Mid(s, t4 +1) + Print IIf(flag = 0, sign, ""); IIf(m1 = 1, "", Str(m1)); + Print "Atn("; s2; "/" ;s3; ")"; + + If flag = -1 Then + flag = 0 + Mpz_set_si(_a(f1), a1) + Mpz_set_si(_b(f1), b1) + If m1 > 1 Then work2do(m1, f1) + Continue While + End If + + Mpz_set_si(_a(f2), a1) + Mpz_set_si(_b(f2), b1) + If m1 > 1 Then work2do(m1, f2) + + Mpz_mul(temp1, _a(f1), _b(f2)) + Mpz_mul(temp2, _b(f1), _a(f2)) + Mpz_add(_a(f3), temp1, temp2) + Mpz_mul(temp1, _b(f1), _b(f2)) + Mpz_mul(temp2, _a(f1), _a(f2)) + Mpz_sub(_b(f3), temp1, temp2) + mpq_canonicalize(f3) + mpq_set(f1, f3) + + Wend + + If Mpz_cmp_ui(_b(f1), 1) = 0 AndAlso Mpz_cmp(_a(f1), _b(f1)) = 0 Then + Print " = 1" + Else + Mpf_set_q(float, f1) + gmp_printf(!" = %.*Ff\n", 15, float) + End If + +Loop + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Checkpoint-synchronization/Scala/checkpoint-synchronization.scala b/Task/Checkpoint-synchronization/Scala/checkpoint-synchronization.scala new file mode 100644 index 0000000000..14f6d68ddf --- /dev/null +++ b/Task/Checkpoint-synchronization/Scala/checkpoint-synchronization.scala @@ -0,0 +1,84 @@ +import java.util.{Random, Scanner} + +object CheckpointSync extends App { + val in = new Scanner(System.in) + + /* + * Informs that workers started working on the task and + * starts running threads. Prior to proceeding with next + * task syncs using static Worker.checkpoint() method. + */ + private def runTasks(nTasks: Int): Unit = { + + for (i <- 0 until nTasks) { + println("Starting task number " + (i + 1) + ".") + runThreads() + Worker.checkpoint() + } + } + + /* + * Creates a thread for each worker and runs it. + */ + private def runThreads(): Unit = + for (i <- 0 until Worker.nWorkers) new Thread(new Worker(i + 1)).start() + + class Worker(/* inner class instance variables */ var threadID: Int) + extends Runnable { + override def run(): Unit = { + work() + } + + /* + * Notifies that thread started running for 100 to 1000 msec. + * Once finished increments static counter 'nFinished' + * that counts number of workers finished their work. + */ + private def work(): Unit = { + try { + val workTime = Worker.rgen.nextInt(900) + 100 + println("Worker " + threadID + " will work for " + workTime + " msec.") + Thread.sleep(workTime) //work for 'workTime' + + Worker.nFinished += 1 //increases work finished counter + + println("Worker " + threadID + " is ready") + } catch { + case e: InterruptedException => + System.err.println("Error: thread execution interrupted") + e.printStackTrace() + } + } + } + + /* + * Worker inner static class. + */ + object Worker { + private val rgen = new Random + var nWorkers = 0 + private var nFinished = 0 + + /* + * Used to synchronize Worker threads using 'nFinished' static integer. + * Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'. + * Once they are equal resets 'nFinished' counter. + */ + def checkpoint(): Unit = { + while (nFinished != nWorkers) + try Thread.sleep(10) + catch { + case e: InterruptedException => + System.err.println("Error: thread execution interrupted") + e.printStackTrace() + } + nFinished = 0 + } + } + + print("Enter number of workers to use: ") + Worker.nWorkers = in.nextInt + print("Enter number of tasks to complete:") + runTasks(in.nextInt) + +} diff --git a/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl index d40636dc15..8331270bf7 100644 --- a/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl +++ b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl @@ -1,2 +1,2 @@ -use ntheory qw/chinese/; +use ntheory qw/chinese lcm/; say chinese( [2328,16256], [410,5418] ), " mod ", lcm(16256,5418); diff --git a/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust b/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust index 94a00642f3..f7eb11dc2f 100644 --- a/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust +++ b/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust @@ -40,5 +40,4 @@ fn main() { let s = a.len(); println!("{}",chinese_remainder(&mut n,&mut a,s)); - } diff --git a/Task/Chinese-remainder-theorem/Scala/chinese-remainder-theorem.scala b/Task/Chinese-remainder-theorem/Scala/chinese-remainder-theorem.scala new file mode 100644 index 0000000000..f98f8cf8e0 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Scala/chinese-remainder-theorem.scala @@ -0,0 +1,41 @@ +import scala.util.{Success, Try} + +object ChineseRemainderTheorem extends App { + + def chineseRemainder(n: List[Int], a: List[Int]): Option[Int] = { + require(n.size == a.size) + val prod = n.product + + def iter(n: List[Int], a: List[Int], sm: Int): Int = { + def mulInv(a: Int, b: Int): Int = { + def loop(a: Int, b: Int, x0: Int, x1: Int): Int = { + if (a > 1) loop(b, a % b, x1 - (a / b) * x0, x0) else x1 + } + + if (b == 1) 1 + else { + val x1 = loop(a, b, 0, 1) + if (x1 < 0) x1 + b else x1 + } + } + + if (n.nonEmpty) { + val p = prod / n.head + + iter(n.tail, a.tail, sm + a.head * mulInv(p, n.head) * p) + } else sm + } + + Try { + iter(n, a, 0) % prod + } match { + case Success(v) => Some(v) + case _ => None + } + } + + println(chineseRemainder(List(3, 5, 7), List(2, 3, 2))) + println(chineseRemainder(List(11, 12, 13), List(10, 4, 12))) + println(chineseRemainder(List(11, 22, 19), List(10, 4, 9))) + +} diff --git a/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef b/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef index 7f1cac715f..2201824d39 100644 --- a/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef +++ b/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef @@ -1,19 +1,10 @@ -func mul_inv(a, b) { - b == 1 && return 1 - var (b0, x0, x1) = (0, 0, 1) - while (a > 1) { - (a, b, x0, x1) = (b, a % b, x1 - x0*int(a / b), x0) - } - x1 < 0 ? x1+b0 : x1 -} - func chinese_remainder(*n) { - var N = nΒ«*Β» + var N = n.prod func (*a) { - n.range.map { |i| - var p = int(N / n[i]) - a[i] * mul_inv(p, n[i]) * p - }.sum + n.range.sum { |i| + var p = (N / n[i]) + a[i] * p.invmod(n[i]) * p + } % N } } diff --git a/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring b/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring index c51e9d37af..0003149cc5 100644 --- a/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring +++ b/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring @@ -1,7 +1,4 @@ # Project : Cholesky decomposition -# Date : 2017/11/12 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" decimals(5) diff --git a/Task/Circles-of-given-radius-through-two-points/Nim/circles-of-given-radius-through-two-points.nim b/Task/Circles-of-given-radius-through-two-points/Nim/circles-of-given-radius-through-two-points.nim index 17cdf6b81f..6240ca0556 100644 --- a/Task/Circles-of-given-radius-through-two-points/Nim/circles-of-given-radius-through-two-points.nim +++ b/Task/Circles-of-given-radius-through-two-points/Nim/circles-of-given-radius-through-two-points.nim @@ -5,16 +5,16 @@ type Circle = tuple[x, y, r: float] proc circles(p1, p2: Point, r: float): tuple[c1, c2: Circle] = - if r == 0: raise newException(EInvalidValue, + if r == 0: raise newException(ValueError, "radius of zero") - if p1 == p2: raise newException(EInvalidValue, + if p1 == p2: raise newException(ValueError, "coincident points gives infinite number of Circles") # delta x, delta y between points let (dx, dy) = (p2.x - p1.x, p2.y - p1.y) # dist between points let q = sqrt(dx*dx + dy*dy) - if q > 2.0*r: raise newException(EInvalidValue, + if q > 2.0*r: raise newException(ValueError, "separation of points > diameter") # halfway point @@ -43,6 +43,6 @@ for p1, p2, r in tries.items: let (c1, c2) = circles(p1, p2, r) echo " ", c1 echo " ", c2 - except EInvalidValue: + except ValueError: echo " ERROR: ", getCurrentExceptionMsg() echo "" diff --git a/Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring b/Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring index 313f656730..1728cedd77 100644 --- a/Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring +++ b/Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring @@ -1,7 +1,4 @@ # Project : Circles of given radius through two points -# Date : 2018/01/05 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(4) x1 = 0.1234 diff --git a/Task/Classes/REBOL/classes.rebol b/Task/Classes/REBOL/classes.rebol index 43d12af41c..acb9e63913 100644 --- a/Task/Classes/REBOL/classes.rebol +++ b/Task/Classes/REBOL/classes.rebol @@ -1,7 +1,5 @@ rebol [ Title: "Classes" - Author: oofoe - Date: 2009-12-11 URL: http://rosettacode.org/wiki/Classes ] diff --git a/Task/Closest-pair-problem/Perl/closest-pair-problem.pl b/Task/Closest-pair-problem/Perl/closest-pair-problem.pl index 607a9744a8..7b514ba9f2 100644 --- a/Task/Closest-pair-problem/Perl/closest-pair-problem.pl +++ b/Task/Closest-pair-problem/Perl/closest-pair-problem.pl @@ -104,4 +104,4 @@ my ($a, $b, $d) = closest_pair_simple(\@points); print "$d\n"; my ($a1, $b1, $d1) = closest_pair(\@points); -#print "$d1\n"; +print "$d1\n"; diff --git a/Task/Color-of-a-screen-pixel/Ring/color-of-a-screen-pixel.ring b/Task/Color-of-a-screen-pixel/Ring/color-of-a-screen-pixel.ring index b8fac68a67..2d9fb02a9f 100644 --- a/Task/Color-of-a-screen-pixel/Ring/color-of-a-screen-pixel.ring +++ b/Task/Color-of-a-screen-pixel/Ring/color-of-a-screen-pixel.ring @@ -1,35 +1,34 @@ -Load "guilib.ring" -new qApp { +# Project : Color of a screen pixel - win1 = new qWidget() - { - setWindowTitle("Test using Event Filter!") - setGeometry(100,100,400,400) - setmousetracking(true) - myfilter = new qallevents(win1) - myfilter.setKeyPressEvent("pWork()") - myfilter.setMouseButtonPressevent("pClick()") - myfilter.setmousemoveevent("pMove()") +Load "gamelib.ring" +r = 0 +g = 0 +b = 0 +al_init() +al_init_image_addon() +display = al_create_display(1000,800) +al_set_target_bitmap(al_get_backbuffer(display)) +al_clear_to_color(al_map_rgb(255,255,255)) +image = al_load_bitmap("stock.jpg") +al_draw_rotated_bitmap(image,0,0,250,250,150,0) +al_draw_scaled_bitmap(image,0,0,250,250,20,20,400,400,0) +ring_getpixel(image,300,300) +see "r = " + r + nl +see "g = " + g + nl +see "b = " + b + nl +al_flip_display() +al_rest(2) +al_destroy_bitmap(image) +al_destroy_display(display) - installeventfilter(myfilter) - show() - } - exec() -} - -func pWork - win1.setwindowtitle('KeyPress! : ' + myfilter.getkeycode()) - -func pClick - new qmessagebox(win1) { - setgeometry(100,100,400,100) - setwindowtitle("click event!") - settext("x : " + myfilter.getx() + - " y : " + myfilter.gety() + " button : " + - myfilter.getbutton() ) - show() - } - -func pMove - win1.setwindowtitle("Mouse Move , X : " + myfilter.getx() + - " Y : " + myfilter.gety() ) +func ring_getpixel(image,x,y) + newcolor = al_get_pixel(image,x,y) + r=copy(" ",4) g=copy(" ",4) b=copy(" ",4) + p1 = VarPtr("r","float") + p2 = VarPtr("g","float") + p3 = VarPtr("b","float") + al_unmap_rgb_f(newcolor, p1 , p2 , p3 ) + r = bytes2float(r) + g = bytes2float(g) + b = bytes2float(b) + return [r,g,b] diff --git a/Task/Colour-bars-Display/C/colour-bars-display-1.c b/Task/Colour-bars-Display/C/colour-bars-display-1.c index cacdcc0fb8..cd5c921097 100644 --- a/Task/Colour-bars-Display/C/colour-bars-display-1.c +++ b/Task/Colour-bars-Display/C/colour-bars-display-1.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ - #include #define COLOURS 8 diff --git a/Task/Colour-bars-Display/C/colour-bars-display-2.c b/Task/Colour-bars-Display/C/colour-bars-display-2.c index 490c862901..7b4f3799d4 100644 --- a/Task/Colour-bars-Display/C/colour-bars-display-2.c +++ b/Task/Colour-bars-Display/C/colour-bars-display-2.c @@ -1,4 +1,3 @@ -/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ #include #include diff --git a/Task/Colour-pinstripe-Display/Befunge/colour-pinstripe-display.bf b/Task/Colour-pinstripe-Display/Befunge/colour-pinstripe-display.bf new file mode 100644 index 0000000000..103c3d4173 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Befunge/colour-pinstripe-display.bf @@ -0,0 +1,3 @@ +"%":*3-"`"8*>4/::8%00p8/10p4*\55+"3P",,,:.\.5v +5+:,1vv\%2:%8/-g025:\-1_$$55+,\:v1+*8g01g00_@> +024,.<>2/:2%\2/...1+\:>^<:\0:\-1_$20g1-:20p^1p diff --git a/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c b/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c index 2a1f03ca45..fca449af91 100644 --- a/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c +++ b/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ - #include #include diff --git a/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix b/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix index 0aea751c48..552e375485 100644 --- a/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix +++ b/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix @@ -6,23 +6,27 @@ 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") +procedure draw_to(cdCanvas cdcanvas) + cdCanvasActivate(cdcanvas) + integer {width, height} = cdCanvasGetSize(cdcanvas) for y=1 to 4 do integer x = 0, c = 1, h = floor(height/(5-y)) while x load "guilib.ring" diff --git a/Task/Colour-pinstripe-Display/Scala/colour-pinstripe-display.scala b/Task/Colour-pinstripe-Display/Scala/colour-pinstripe-display.scala new file mode 100644 index 0000000000..95d383668c --- /dev/null +++ b/Task/Colour-pinstripe-Display/Scala/colour-pinstripe-display.scala @@ -0,0 +1,39 @@ +import java.awt.Color._ +import java.awt._ + +import javax.swing._ + +object ColourPinstripeDisplay extends App { + private def palette = Seq(black, red, green, blue, magenta, cyan, yellow, white) + + SwingUtilities.invokeLater(() => + new JFrame("Colour Pinstripe") { + + class ColourPinstripe_Display extends JPanel { + + override def paintComponent(g: Graphics): Unit = { + val bands = 4 + + super.paintComponent(g) + for (b <- 1 to bands) { + var colIndex = 0 + for (x <- 0 until getWidth by b) { + g.setColor(ColourPinstripeDisplay.palette(colIndex % ColourPinstripeDisplay.palette.length)) + g.fillRect(x, (b - 1) * (getHeight / bands), x + b, b * (getHeight / bands)) + colIndex += 1 + } + } + } + + setPreferredSize(new Dimension(900, 600)) + } + + add(new ColourPinstripe_Display, BorderLayout.CENTER) + pack() + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) + setLocationRelativeTo(null) + setVisible(true) + } + ) + +} diff --git a/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring b/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring index 6297379cca..8108d16f5d 100644 --- a/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring +++ b/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring @@ -1,7 +1,4 @@ # Project : Combinations with repetitions -# Date : 2017/10/29 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : n = 2 k = 3 diff --git a/Task/Combinations/C/combinations-2.c b/Task/Combinations/C/combinations-2.c index d61cbab4a5..e0a74e89c7 100644 --- a/Task/Combinations/C/combinations-2.c +++ b/Task/Combinations/C/combinations-2.c @@ -11,9 +11,10 @@ void comb(int m, int n, unsigned char *c) /* this check is not strictly necessary, but if m is not close to n, it makes the whole thing quite a bit faster */ + i = 0; if (c[i]++ < m) continue; - for (i = 0; c[i] >= m - i;) if (++i >= n) return; + for (; c[i] >= m - i;) if (++i >= n) return; for (c[i]++; i; i--) c[i-1] = c[i] + 1; } } diff --git a/Task/Combinations/Crystal/combinations-1.crystal b/Task/Combinations/Crystal/combinations-1.crystal new file mode 100644 index 0000000000..93ec5aa513 --- /dev/null +++ b/Task/Combinations/Crystal/combinations-1.crystal @@ -0,0 +1,3 @@ +def comb(m, n) + (0...n).to_a.each_combination(m) { |p| puts(p) } +end diff --git a/Task/Combinations/Crystal/combinations-2.crystal b/Task/Combinations/Crystal/combinations-2.crystal new file mode 100644 index 0000000000..302d183940 --- /dev/null +++ b/Task/Combinations/Crystal/combinations-2.crystal @@ -0,0 +1,10 @@ +[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] diff --git a/Task/Combinations/Ring/combinations.ring b/Task/Combinations/Ring/combinations.ring index 9d167c387c..40c49fba52 100644 --- a/Task/Combinations/Ring/combinations.ring +++ b/Task/Combinations/Ring/combinations.ring @@ -1,7 +1,4 @@ # Project : Combinations -# Date : 2017/10/29 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : n = 5 k = 3 diff --git a/Task/Comma-quibbling/Astro/comma-quibbling.astro b/Task/Comma-quibbling/Astro/comma-quibbling.astro index 19e849afd0..26acb7ba4e 100644 --- a/Task/Comma-quibbling/Astro/comma-quibbling.astro +++ b/Task/Comma-quibbling/Astro/comma-quibbling.astro @@ -1,6 +1,13 @@ fun quibble(s): - let result = ' and '.join(s).replace(/ and /, ', ', len(s) - 1) - "{ $result }" + let result = " and ".join(s).replace(/ and /, ", ", length(s) - 1) + return "{ $result }" -let s = [ [] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] ] -for i in s: print(quibble i) +let s = [ + [] + ["ABC"] + ["ABC", "DEF"] + ["ABC", "DEF", "G", "H"] +] + +for i in s: + print(quibble i) diff --git a/Task/Comma-quibbling/Nim/comma-quibbling.nim b/Task/Comma-quibbling/Nim/comma-quibbling.nim index 9980bf833f..0d48347fec 100644 --- a/Task/Comma-quibbling/Nim/comma-quibbling.nim +++ b/Task/Comma-quibbling/Nim/comma-quibbling.nim @@ -1,4 +1,4 @@ -proc commaQuibble(s): string = +proc commaQuibble(s: openArray[string]): string = result = "" for i, c in s: if i > 0: result.add (if i < s.high: ", " else: " and ") diff --git a/Task/Comma-quibbling/Ring/comma-quibbling.ring b/Task/Comma-quibbling/Ring/comma-quibbling.ring index 3e1e6996f0..9b0e26a317 100644 --- a/Task/Comma-quibbling/Ring/comma-quibbling.ring +++ b/Task/Comma-quibbling/Ring/comma-quibbling.ring @@ -1,7 +1,4 @@ # Project : Comma Quibbling -# Date : 2017/11/12 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : text = list(4) text[1] = "{}" diff --git a/Task/Comma-quibbling/Sed/comma-quibbling-1.sed b/Task/Comma-quibbling/Sed/comma-quibbling-1.sed new file mode 100644 index 0000000000..8e37d6b065 --- /dev/null +++ b/Task/Comma-quibbling/Sed/comma-quibbling-1.sed @@ -0,0 +1,6 @@ +s/#.*$//g +y/[/{/ +y/]/}/ +s/"//g +s/ [A-Z][A-Z]*}/ and&/g +s/, and/ and/ diff --git a/Task/Comma-quibbling/Sed/comma-quibbling-2.sed b/Task/Comma-quibbling/Sed/comma-quibbling-2.sed new file mode 100644 index 0000000000..1529d8e7a5 --- /dev/null +++ b/Task/Comma-quibbling/Sed/comma-quibbling-2.sed @@ -0,0 +1,4 @@ +[] # (No input words). +["ABC"] +["ABC", "DEF"] +["ABC", "DEF", "G", "H"] diff --git a/Task/Concurrent-computing/Astro/concurrent-computing.astro b/Task/Concurrent-computing/Astro/concurrent-computing.astro index 0f97524a41..7d8bfd7acd 100644 --- a/Task/Concurrent-computing/Astro/concurrent-computing.astro +++ b/Task/Concurrent-computing/Astro/concurrent-computing.astro @@ -1,5 +1,7 @@ let words = ["Enjoy", "Rosetta", "Code"] + for word in words: - async (word) => + async (w) => ( sleep(random()) - print(word) + print(w) + )(word) diff --git a/Task/Conditional-structures/Astro/conditional-structures.astro b/Task/Conditional-structures/Astro/conditional-structures.astro index 2d4173ccb0..ba2d244ddc 100644 --- a/Task/Conditional-structures/Astro/conditional-structures.astro +++ b/Task/Conditional-structures/Astro/conditional-structures.astro @@ -1,12 +1,16 @@ -if x == 0: foo() -elif x == 1: bar() -elif x == 2: baz() -else: qux() +if x == 0: + foo() +elif x == 1: + bar() +elif x == 2: + baz() +else: + qux() -x -| 0 => foo() -| 1 => bar() -| 2 => baz() -| _ => qux() +match x: + | 0 => foo() + | 1 => bar() + | 2 => baz() + | _ => qux() (a) ? b : c diff --git a/Task/Conditional-structures/Go/conditional-structures-4.go b/Task/Conditional-structures/Go/conditional-structures-4.go index 2d3076b9cf..fdd55a3903 100644 --- a/Task/Conditional-structures/Go/conditional-structures-4.go +++ b/Task/Conditional-structures/Go/conditional-structures-4.go @@ -1,4 +1,4 @@ -if x := fetchSomething(); if x > 0 { +if x := fetchSomething(); x > 0 { DoPos(x) } else { DoNeg(x) diff --git a/Task/Conjugate-transpose/C/conjugate-transpose.c b/Task/Conjugate-transpose/C/conjugate-transpose.c index 9fff2c523a..22f5de06e2 100644 --- a/Task/Conjugate-transpose/C/conjugate-transpose.c +++ b/Task/Conjugate-transpose/C/conjugate-transpose.c @@ -1,7 +1,4 @@ -/*28th August, 2012 -Abhishek Ghosh - -Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */ +/* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */ #include #include diff --git a/Task/Constrained-random-points-on-a-circle/Nim/constrained-random-points-on-a-circle.nim b/Task/Constrained-random-points-on-a-circle/Nim/constrained-random-points-on-a-circle.nim index ab8cd71ec3..38535ee693 100644 --- a/Task/Constrained-random-points-on-a-circle/Nim/constrained-random-points-on-a-circle.nim +++ b/Task/Constrained-random-points-on-a-circle/Nim/constrained-random-points-on-a-circle.nim @@ -1,25 +1,26 @@ -import tables, math, strutils, complex -randomize() +import tables, math, strutils, complex, random proc random[T](a: openarray[T]): T = - result = a[random(low(a)..len(a))] + result = a[rand(low(a)..len(a))] type Point = tuple[x, y: int] var world = initCountTable[Point]() - var possiblePoints = newSeq[Point]() + for x in -15..15: for y in -15..15: if abs((x.float, y.float)) in 10.0..15.0: possiblePoints.add((x,y)) +randomize() for i in 0..100: world.inc possiblePoints.random for x in -15..15: for y in -15..15: - if world[(x,y)] > 0: - stdout.write min(9, world[(x,y)]) + let key = (x, y) + if key in world and world[key] > 0: + stdout.write min(9, world[key]) else: stdout.write ' ' echo "" diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c index 0e32ba4507..dae8ba5fbd 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 8th November 2013, Rotterdam*/ - #include typedef struct{ diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-1.go b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-1.go new file mode 100644 index 0000000000..20db1f250c --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-1.go @@ -0,0 +1,75 @@ +package cf + +import ( + "fmt" + "strings" +) + +// ContinuedFraction is a regular continued fraction. +type ContinuedFraction func() NextFn + +// NextFn is a function/closure that can return +// a posibly infinite sequence of values. +type NextFn func() (term int64, ok bool) + +// String implements fmt.Stringer. +// It formats a maximum of 20 values, ending the +// sequence with ", ..." if the sequence is longer. +func (cf ContinuedFraction) String() string { + var buf strings.Builder + buf.WriteByte('[') + sep := "; " + const maxTerms = 20 + next := cf() + for n := 0; ; n++ { + t, ok := next() + if !ok { + break + } + if n > 0 { + buf.WriteString(sep) + sep = ", " + } + if n >= maxTerms { + buf.WriteString("...") + break + } + fmt.Fprint(&buf, t) + } + buf.WriteByte(']') + return buf.String() +} + +// Sqrt2 is the continued fraction for √2, [1; 2, 2, 2, ...]. +func Sqrt2() NextFn { + first := true + return func() (int64, bool) { + if first { + first = false + return 1, true + } + return 2, true + } +} + +// Phi is the continued fraction for Ο•, [1; 1, 1, 1, ...]. +func Phi() NextFn { + return func() (int64, bool) { return 1, true } +} + +// E is the continued fraction for e, +// [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, ...]. +func E() NextFn { + var i int + return func() (int64, bool) { + i++ + switch { + case i == 1: + return 2, true + case i%3 == 0: + return int64(i/3) * 2, true + default: + return 1, true + } + } +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-2.go b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-2.go new file mode 100644 index 0000000000..1d28b8be50 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-2.go @@ -0,0 +1,31 @@ +package cf + +import "fmt" + +// A Rat represents a quotient N/D. +type Rat struct { + N, D int64 +} + +// String implements fmt.Stringer and returns a string +// representation of `r` in the form "N/D" (even if D == 1). +func (r Rat) String() string { + return fmt.Sprintf("%d/%d", r.N, r.D) +} + +// As ContinuedFraction returns a contined fraction representation of `r`. +func (r Rat) AsContinuedFraction() ContinuedFraction { return r.CFTerms } +func (r Rat) CFTerms() NextFn { + return func() (int64, bool) { + if r.D == 0 { + return 0, false + } + q := r.N / r.D + r.N, r.D = r.D, r.N-q*r.D + return q, true + } +} + +// Rosetta Code task explicitly asked for this function, +// so here it is. We'll just use the types above instead. +func r2cf(n1, n2 int64) ContinuedFraction { return Rat{n1, n2}.CFTerms } diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-3.go b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-3.go new file mode 100644 index 0000000000..20d0d98fe5 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Go/continued-fraction-arithmetic-construct-from-rational-number-3.go @@ -0,0 +1,47 @@ +package cf + +import ( + "fmt" + "math" +) + +func Example_ConstructFromRational() { + cases := [...]Rat{ + {1, 2}, + {3, 1}, + {23, 8}, + {13, 11}, + {22, 7}, + {-151, 77}, + } + for _, r := range cases { + fmt.Printf("%7s = %s\n", r, r.AsContinuedFraction()) + } + + for _, tc := range [...]struct { + name string + approx float64 + cf ContinuedFraction + d1, d2 int64 + }{ + {"√2", math.Sqrt2, Sqrt2, 1e4, 1e8}, + {"Ο€", math.Pi, nil, 10, 1e10}, + {"Ο•", math.Phi, Phi, 10, 1e5}, + {"e", math.E, E, 1e5, 1e9}, + } { + fmt.Printf("\nApproximating %s β‰… %v:\n", tc.name, tc.approx) + for d := tc.d1; d < tc.d2; d *= 10 { + n := int64(math.Round(tc.approx * float64(d))) + r := Rat{n, d} + fmt.Println(r, "=", r.AsContinuedFraction()) + } + if tc.cf != nil { + wid := int(math.Log10(float64(tc.d2)))*2 + 2 // ick + fmt.Printf("%*s: %v\n", wid, "Actual", tc.cf) + } + } + + // Output: + // [… commented output used by go test omitted for + // Rosetta Code listing; it is the same as below …] +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.go b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.go new file mode 100644 index 0000000000..2226a3b9af --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.go @@ -0,0 +1,84 @@ +package cf + +// A 2Γ—2 matix: +// [ a₁ a ] +// [ b₁ b ] +// +// which when "applied" to a continued fraction representing x +// gives a new continued fraction z such that: +// +// a₁ * x + a +// z = ---------- +// b₁ * x + b +// +// Examples: +// NG4{0, 1, 0, 4}.ApplyTo(x) gives 0*x + 1/4 -> 1/4 = [0; 4] +// NG4{0, 1, 1, 0}.ApplyTo(x) gives 1/x +// NG4{1, 1, 0, 2}.ApplyTo(x) gives (x+1)/2 +// +// Note that several operations (e.g.Β addition and division) +// can be efficiently done with a single matrix application. +// However, each matrix application may require +// several calculations for each outputed term. +type NG4 struct { + A1, A int64 + B1, B int64 +} + +func (ng NG4) needsIngest() bool { + if ng.isDone() { + panic("b₁==b==0") + } + return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B +} + +func (ng NG4) isDone() bool { + return ng.B1 == 0 && ng.B == 0 +} + +func (ng *NG4) ingest(t int64) { + // [ a₁ a ] becomes [ a + a₁×t a₁ ] + // [ b₁ b ] [ b + b₁×t b₁ ] + ng.A1, ng.A, ng.B1, ng.B = + ng.A+ng.A1*t, ng.A1, + ng.B+ng.B1*t, ng.B1 +} + +func (ng *NG4) ingestInfinite() { + // [ a₁ a ] becomes [ a₁ a₁ ] + // [ b₁ b ] [ b₁ b₁ ] + ng.A, ng.B = ng.A1, ng.B1 +} + +func (ng *NG4) egest(t int64) { + // [ a₁ a ] becomes [ b₁ b ] + // [ b₁ b ] [ a₁ - b₁×t a - bΓ—t ] + ng.A1, ng.A, ng.B1, ng.B = + ng.B1, ng.B, + ng.A1-ng.B1*t, ng.A-ng.B*t +} + +// ApplyTo "applies" the matrix `ng` to the continued fraction `cf`, +// returning the resulting continued fraction. +func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction { + return func() NextFn { + next := cf() + done := false + return func() (int64, bool) { + if done { + return 0, false + } + for ng.needsIngest() { + if t, ok := next(); ok { + ng.ingest(t) + } else { + ng.ingestInfinite() + } + } + t := ng.A1 / ng.B1 + ng.egest(t) + done = ng.isDone() + return t, true + } + } +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.go b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.go new file mode 100644 index 0000000000..4db1de5386 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.go @@ -0,0 +1,36 @@ +package cf + +import ( + "fmt" + "reflect" + "testing" +) + +func Example_NG4() { + cases := [...]struct { + r Rat + ng NG4 + }{ + {Rat{13, 11}, NG4{2, 1, 0, 2}}, + {Rat{22, 7}, NG4{2, 1, 0, 2}}, + {Rat{22, 7}, NG4{1, 0, 0, 4}}, + } + for _, tc := range cases { + cf := tc.r.AsContinuedFraction() + fmt.Printf("%5s = %-9s with %v gives %v\n", tc.r, cf.String(), tc.ng, + tc.ng.ApplyTo(cf), + ) + } + + invSqrt2 := NG4{0, 1, 1, 0}.ApplyTo(Sqrt2) + fmt.Println(" 1/√2 =", invSqrt2) + result := NG4{1, 1, 0, 2}.ApplyTo(Sqrt2) + fmt.Println("(1+√2)/2 =", result) + + // Output: + // 13/11 = [1; 5, 2] with {2 1 0 2} gives [1; 1, 2, 7] + // 22/7 = [3; 7] with {2 1 0 2} gives [3; 1, 1, 1, 4] + // 22/7 = [3; 7] with {1 0 0 4} gives [0; 1, 3, 1, 2] + // 1/√2 = [0; 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...] + // (1+√2)/2 = [1; 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, ...] +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--1.go b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--1.go new file mode 100644 index 0000000000..b092f628eb --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--1.go @@ -0,0 +1,141 @@ +package cf + +import "math" + +// A 2Γ—4 matix: +// [ a₁₂ a₁ aβ‚‚ a ] +// [ b₁₂ b₁ bβ‚‚ b ] +// +// which when "applied" to two continued fractions N1 and N2 +// gives a new continued fraction z such that: +// +// a₁₂ * N1 * N2 + a₁ * N1 + aβ‚‚ * N2 + a +// z = ------------------------------------------- +// b₁₂ * N1 * N2 + b₁ * N1 + bβ‚‚ * N2 + b +// +// Examples: +// NG8{0,1,1,0, 0,0,0,1} gives N1 + N2 +// NG8{0,1,-1,0, 0,0,0,1} gives N1 - N2 +// NG8{1,0,0,0, 0,0,0,1} gives N1 * N2 +// NG8{0,1,0,0, 0,0,1,0} gives N1 / N2 +// NG8{21,-15,28,-20, 0,0,0,1} gives 21*N1*N2 -15*N1 +28*N2 -20 +// which is (3*N1 + 4) * (7*N2 - 5) +type NG8 struct { + A12, A1, A2, A int64 + B12, B1, B2, B int64 +} + +// Basic identities as NG8 matrices. +var ( + NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1} + NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1} + NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1} + NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0} +) + +func (ng *NG8) needsIngest() bool { + if ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 { + return true + } + x := ng.A / ng.B + return ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x +} + +func (ng *NG8) isDone() bool { + return ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0 +} + +func (ng *NG8) ingestWhich() bool { // true for N1, false for N2 + if ng.B == 0 && ng.B2 == 0 { + return true + } + if ng.B == 0 || ng.B2 == 0 { + return false + } + x1 := float64(ng.A1) / float64(ng.B1) + x2 := float64(ng.A2) / float64(ng.B2) + x := float64(ng.A) / float64(ng.B) + return math.Abs(x1-x) > math.Abs(x2-x) +} + +func (ng *NG8) ingest(isN1 bool, t int64) { + if isN1 { + // [ a₁₂ a₁ aβ‚‚ a ] becomes [ aβ‚‚+a₁₂*t a+a₁*t a₁₂ a₁] + // [ b₁₂ b₁ bβ‚‚ b ] [ bβ‚‚+b₁₂*t b+b₁*t b₁₂ b₁] + ng.A12, ng.A1, ng.A2, ng.A, + ng.B12, ng.B1, ng.B2, ng.B = + ng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1, + ng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1 + } else { + // [ a₁₂ a₁ aβ‚‚ a ] becomes [ a₁+a₁₂*t a₁₂ a+aβ‚‚*t aβ‚‚] + // [ b₁₂ b₁ bβ‚‚ b ] [ b₁+b₁₂*t b₁₂ b+bβ‚‚*t bβ‚‚] + ng.A12, ng.A1, ng.A2, ng.A, + ng.B12, ng.B1, ng.B2, ng.B = + ng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2, + ng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2 + } +} + +func (ng *NG8) ingestInfinite(isN1 bool) { + if isN1 { + // [ a₁₂ a₁ aβ‚‚ a ] becomes [ a₁₂ a₁ a₁₂ a₁ ] + // [ b₁₂ b₁ bβ‚‚ b ] [ b₁₂ b₁ b₁₂ b₁ ] + ng.A2, ng.A, ng.B2, ng.B = + ng.A12, ng.A1, + ng.B12, ng.B1 + } else { + // [ a₁₂ a₁ aβ‚‚ a ] becomes [ a₁₂ a₁₂ aβ‚‚ aβ‚‚ ] + // [ b₁₂ b₁ bβ‚‚ b ] [ b₁₂ b₁₂ bβ‚‚ bβ‚‚ ] + ng.A1, ng.A, ng.B1, ng.B = + ng.A12, ng.A2, + ng.B12, ng.B2 + } +} + +func (ng *NG8) egest(t int64) { + // [ a₁₂ a₁ aβ‚‚ a ] becomes [ b₁₂ b₁ bβ‚‚ b ] + // [ b₁₂ b₁ bβ‚‚ b ] [ a₁₂-b₁₂*t a₁-b₁*t aβ‚‚-bβ‚‚*t a-b*t ] + ng.A12, ng.A1, ng.A2, ng.A, + ng.B12, ng.B1, ng.B2, ng.B = + ng.B12, ng.B1, ng.B2, ng.B, + ng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t +} + +// ApplyTo "applies" the matrix `ng` to the continued fractions +// `N1` and `N2`, returning the resulting continued fraction. +// After ingesting `limit` terms without any output terms the resulting +// continued fraction is terminated. +func (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction { + return func() NextFn { + next1, next2 := N1(), N2() + done := false + sinceEgest := 0 + return func() (int64, bool) { + if done { + return 0, false + } + for ng.needsIngest() { + sinceEgest++ + if sinceEgest > limit { + done = true + return 0, false + } + isN1 := ng.ingestWhich() + next := next2 + if isN1 { + next = next1 + } + if t, ok := next(); ok { + ng.ingest(isN1, t) + } else { + ng.ingestInfinite(isN1) + } + } + sinceEgest = 0 + t := ng.A / ng.B + ng.egest(t) + done = ng.isDone() + return t, true + } + } +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--2.go b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--2.go new file mode 100644 index 0000000000..d50916763c --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Go/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2--2.go @@ -0,0 +1,35 @@ +package cf + +import "fmt" + +func ExampleNG8() { + cases := [...]struct { + op string + r1, r2 Rat + ng NG8 + }{ + {"+", Rat{22, 7}, Rat{1, 2}, NG8Add}, + {"*", Rat{13, 11}, Rat{22, 7}, NG8Mul}, + {"-", Rat{13, 11}, Rat{22, 7}, NG8Sub}, + {"/", Rat{22 * 22, 7 * 7}, Rat{22, 7}, NG8Div}, + } + for _, tc := range cases { + n1 := tc.r1.AsContinuedFraction() + n2 := tc.r2.AsContinuedFraction() + z := tc.ng.ApplyTo(n1, n2, 1000) + fmt.Printf("%v %s %v is %v %v %v gives %v\n", + tc.r1, tc.op, tc.r2, + tc.ng, n1, n2, z, + ) + } + + z := NG8Mul.ApplyTo(Sqrt2, Sqrt2, 1000) + fmt.Println("√2 * √2 =", z) + + // Output: + // 22/7 + 1/2 is {0 1 1 0 0 0 0 1} [3; 7] [0; 2] gives [3; 1, 1, 1, 4] + // 13/11 * 22/7 is {1 0 0 0 0 0 0 1} [1; 5, 2] [3; 7] gives [3; 1, 2, 2] + // 13/11 - 22/7 is {0 1 -1 0 0 0 0 1} [1; 5, 2] [3; 7] gives [-1; -1, -24, -1, -2] + // 484/49 / 22/7 is {0 1 0 0 0 0 1 0} [9; 1, 7, 6] [3; 7] gives [3; 7] + // √2 * √2 = [1; 0, 1] +} diff --git a/Task/Continued-fraction/Ring/continued-fraction.ring b/Task/Continued-fraction/Ring/continued-fraction.ring index f858c00f85..83157890de 100644 --- a/Task/Continued-fraction/Ring/continued-fraction.ring +++ b/Task/Continued-fraction/Ring/continued-fraction.ring @@ -1,7 +1,4 @@ # Project : Continued fraction -# Date : 2018/03/17 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : see "SQR(2) = " + contfrac(1, 1, "2", "1") + nl see " e = " + contfrac(2, 1, "n", "n") + nl diff --git a/Task/Convert-decimal-number-to-rational/Scala/convert-decimal-number-to-rational.scala b/Task/Convert-decimal-number-to-rational/Scala/convert-decimal-number-to-rational.scala new file mode 100644 index 0000000000..c5457b8ebe --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Scala/convert-decimal-number-to-rational.scala @@ -0,0 +1,8 @@ +import org.apache.commons.math3.fraction.BigFraction + +object Number2Fraction extends App { + val n = Array(0.750000000, 0.518518000, 0.905405400, + 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536) + for (d <- n) + println(f"$d%-12s : ${new BigFraction(d, 0.00000002D, 10000)}%s") +} diff --git a/Task/Conways-Game-of-Life/Befunge/conways-game-of-life.bf b/Task/Conways-Game-of-Life/Befunge/conways-game-of-life.bf new file mode 100644 index 0000000000..f97f3cbe21 --- /dev/null +++ b/Task/Conways-Game-of-Life/Befunge/conways-game-of-life.bf @@ -0,0 +1,8 @@ +00p10p20p30p&>40p&>50p60p>$#v~>:55+-vv+`1:%3:+*g04p03< >3/"P"%\56v>p\56*8*/8+:v +v5\`\"~"::-*3p06!:!-+67:_^#!<*1+70g*\:3/"P"%v^ ^::+*g04%<*0v`1:%3\gp08< +>6*`*#v_55+-#v_p10g1+10p>^pg08g07+gp08:+8/*8*65\p07:<^ >/10g-50g^87>+1+:01p/8/v +>%#74#<-!!70p 00g::1+00p:20g\-:0`*+20p10g::30g\-:0`*+^ ^2+2+g03*<*:v+g06p09:%2< +.v,:*93"[2J"0<>"H["39*,,,50g0v!:-1,+55$_:40g3*20g+2+2/\-40g%50g3^/%\ >:3-\3-90v +O>"l52?[">:#,_^v/3+2:*g05g04$_>:10p40g0^!:-1,g+4\0%2/+1+`1:%3\g+8<^: $v10!*-g<< +g+70g80gp:#v_$^>1-:::"P"%\"P"/8+:10v >/10g+1-50g+50g%40g*+::3/"P"^>!|>g*70g80g +:p00%g04:-1<<$_^#!:pg01%"P"\*8%8gp<< ^3\%g04+g04-1+g00%3:%9+4:-1p06\<90p01/g04 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 new file mode 100644 index 0000000000..be57c229e3 --- /dev/null +++ b/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java @@ -0,0 +1,92 @@ +import static java.util.List.of; + +class GameOfLife { + + boolean[][] board = new boolean[3][3]; + + GameOfLife() {} + + GameOfLife(String[] board) { + set((i, j, s) -> board[i].charAt(j * 2) == 'β– '); + } + + void set(Setter setter) { + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[i].length; j++) { + board[i][j] = setter.set(i, j, board[i][j]); + } + } + } + + void get(Getter getter) { + set((i, j, s) -> { + getter.get(i, j, s); + return s; + }); + } + + int countNeighbors(int i, int j) { + var counter = new Getter() { + int count; + + @Override + public void get(int li, int lj, boolean state) { + if (distance(i, j, li, lj) == 1 && board[li][lj]) + count++; + } + }; + get(counter); + return counter.count; + } + + int distance(int i, int j, int li, int lj) { + return Math.max( + Math.abs(i - li), + Math.abs(j - lj)); + } + + GameOfLife makeNextGeneration() { + var n = new GameOfLife(); + n.set((i, j, s) -> { + var alive = board[i][j]; + int c = countNeighbors(i, j); + if (alive) { + return c == 2 || c == 3; + } else { + return c == 3; + } + }); + return n; + } + + void print() { + get((i, j, s) -> { + if (j == 0) + System.out.println(); + System.out.print(s ? "β–  " : "β–‘ "); + }); + } + + interface Setter { + boolean set(int i, int j, boolean state); + } + + interface Getter { + void get(int i, int j, boolean state); + } + + public static void main(String[] args) { + String[] board = { + "β–‘ β–  β–‘ ", + "β–‘ β–  β–‘ ", + "β–‘ β–  β–‘ ", + }; + var gol = new GameOfLife(board); + for (var generation : of(0, 1, 2)) { + gol.print(); + System.out.println("\n"); + gol = gol.makeNextGeneration(); + } + } + +} diff --git a/Task/Copy-a-string/Emacs-Lisp/copy-a-string.l b/Task/Copy-a-string/Emacs-Lisp/copy-a-string.l new file mode 100644 index 0000000000..95c0a9444a --- /dev/null +++ b/Task/Copy-a-string/Emacs-Lisp/copy-a-string.l @@ -0,0 +1,3 @@ +(setq str1 "hi") +(setq str2 str1) +(eq str1 str2) diff --git a/Task/Copy-a-string/REBOL/copy-a-string.rebol b/Task/Copy-a-string/REBOL/copy-a-string.rebol index cbdede8a50..07ad9d7e8b 100644 --- a/Task/Copy-a-string/REBOL/copy-a-string.rebol +++ b/Task/Copy-a-string/REBOL/copy-a-string.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "String Copy" - Date: 2009-12-16 - Author: oofoe URL: http://rosettacode.org/wiki/Copy_a_string ] diff --git a/Task/Count-in-factors/Nim/count-in-factors.nim b/Task/Count-in-factors/Nim/count-in-factors.nim index 75e2d5ca60..efc2d98289 100644 --- a/Task/Count-in-factors/Nim/count-in-factors.nim +++ b/Task/Count-in-factors/Nim/count-in-factors.nim @@ -18,12 +18,12 @@ proc getPrime(idx: int): int = return primes[idx] -for x in 1 .. < int32.high.int: +for x in 1 ..< int32.high.int: stdout.write x, " = " var n = x var first = 1 - for i in 0 .. < int32.high: + for i in 0 ..< int32.high: let p = getPrime(i) while n mod p == 0: n = n div p diff --git a/Task/Count-in-octal/Nim/count-in-octal.nim b/Task/Count-in-octal/Nim/count-in-octal.nim index 65b79e7606..58f497c1dd 100644 --- a/Task/Count-in-octal/Nim/count-in-octal.nim +++ b/Task/Count-in-octal/Nim/count-in-octal.nim @@ -1,3 +1,3 @@ import strutils -for i in 0 .. +#include +#include + +struct DataFrame { + int sum; + std::vector coins; + std::vector avail_coins; +}; + +int main() { + std::stack s; + s.push({ 100, {}, { 25, 10, 5, 1 } }); + int ways = 0; + while (!s.empty()) { + DataFrame top = s.top(); + s.pop(); + if (top.sum < 0) continue; + if (top.sum == 0) { + ++ways; + continue; + } + if (top.avail_coins.empty()) continue; + DataFrame d = top; + d.sum -= top.avail_coins[0]; + d.coins.push_back(top.avail_coins[0]); + s.push(d); + d = top; + d.avail_coins.erase(std::begin(d.avail_coins)); + s.push(d); + } + std::cout << ways << std::endl; + return 0; +} diff --git a/Task/Count-the-coins/Nim/count-the-coins.nim b/Task/Count-the-coins/Nim/count-the-coins.nim index 97d3f372a2..11713d45f7 100644 --- a/Task/Count-the-coins/Nim/count-the-coins.nim +++ b/Task/Count-the-coins/Nim/count-the-coins.nim @@ -1,4 +1,4 @@ -proc changes(amount, coins): int = +proc changes(amount: int, coins: openArray[int]): int = var ways = @[1] ways.setLen(amount+1) for coin in coins: diff --git a/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c b/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c index b069d3db50..b8fbfcbe16 100644 --- a/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c +++ b/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 24th September 2017*/ - #include int main() diff --git a/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring b/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring index db5dd6a3c6..df2b6af361 100644 --- a/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring +++ b/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring @@ -1,7 +1,4 @@ # Project : Create a file on magnetic tape -# Date : 2017/12/09 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : fn = "Tape.file" fp = fopen(fn,"w") diff --git a/Task/Create-a-file/Emacs-Lisp/create-a-file.l b/Task/Create-a-file/Emacs-Lisp/create-a-file.l new file mode 100644 index 0000000000..c53e317eae --- /dev/null +++ b/Task/Create-a-file/Emacs-Lisp/create-a-file.l @@ -0,0 +1,3 @@ +(shell-command "touch output.txt & mkdir docs") +(cd "~/") +(shell-command "touch output.txt & mkdir docs") diff --git a/Task/Create-an-HTML-table/Ring/create-an-html-table.ring b/Task/Create-an-HTML-table/Ring/create-an-html-table.ring new file mode 100644 index 0000000000..5f51682cf5 --- /dev/null +++ b/Task/Create-an-HTML-table/Ring/create-an-html-table.ring @@ -0,0 +1,34 @@ +# Project: Create an HTML table + +load "stdlib.ring" + +str = "" +ncols = 3 +nrows = 4 + +str = str + "" + windowsnl() +str = str + "" + windowsnl() + +for row = 0 to nrows + if row = 0 + str = str + "" + else + str = str + "" + ok + for col = 1 to ncols + if row = 0 + str = str + "" + else + str = str + "" + ok + next + str = str + windowsnl() + "" +windowsnl() +next + +str = str + "
" + row + "" + char(87 + col) + "" + random(9999) + "
" + windowsnl() +str = str + "" + windowsnl() + +remove("temp.htm") +write("temp.htm",str) +see str + nl +systemcmd("temp.htm") diff --git a/Task/Currying/C/currying.c b/Task/Currying/C/currying.c index b710662d3d..aacae30da8 100644 --- a/Task/Currying/C/currying.c +++ b/Task/Currying/C/currying.c @@ -1,4 +1,3 @@ -/*Abhishek Ghosh, 24th October 2017*/ #include #include diff --git a/Task/DNS-query/Lasso/dns-query.lasso b/Task/DNS-query/Lasso/dns-query.lasso new file mode 100644 index 0000000000..4bf5a2b99e --- /dev/null +++ b/Task/DNS-query/Lasso/dns-query.lasso @@ -0,0 +1 @@ +dns_lookup('www.kame.net', -type='A') diff --git a/Task/DNS-query/Lua/dns-query-1.lua b/Task/DNS-query/Lua/dns-query-1.lua new file mode 100644 index 0000000000..aaaf1f2100 --- /dev/null +++ b/Task/DNS-query/Lua/dns-query-1.lua @@ -0,0 +1,6 @@ +local socket = require('socket') +local ip_tbl = socket.dns.getaddrinfo('www.kame.net') + +for _, v in ipairs(ip_tbl) do + io.write(string.format('%s: %s\n', v.family, v.addr)) +end diff --git a/Task/DNS-query/Lua/dns-query-2.lua b/Task/DNS-query/Lua/dns-query-2.lua new file mode 100644 index 0000000000..73fb82ed12 --- /dev/null +++ b/Task/DNS-query/Lua/dns-query-2.lua @@ -0,0 +1,13 @@ +/* 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/Lua/dns-query-3.lua b/Task/DNS-query/Lua/dns-query-3.lua new file mode 100644 index 0000000000..435df1c890 --- /dev/null +++ b/Task/DNS-query/Lua/dns-query-3.lua @@ -0,0 +1,11 @@ +(define (dnsLookup site , ipv) + ;; captures current IPv mode + (set 'ipv (net-ipv)) + ;; IPv mode agnostic lookup + (println "IPv4: " (begin (net-ipv 4) (net-lookup site))) + (println "IPv6: " (begin (net-ipv 6) (net-lookup site))) + ;; returns newLISP to previous IPv mode + (net-ipv ipv) +) + +(dnsLookup "www.kame.net") diff --git a/Task/Date-format/Forth/date-format.fth b/Task/Date-format/Forth/date-format-1.fth similarity index 100% rename from Task/Date-format/Forth/date-format.fth rename to Task/Date-format/Forth/date-format-1.fth diff --git a/Task/Date-format/Forth/date-format-2.fth b/Task/Date-format/Forth/date-format-2.fth new file mode 100644 index 0000000000..31977a5ebd --- /dev/null +++ b/Task/Date-format/Forth/date-format-2.fth @@ -0,0 +1,61 @@ +\ Build up a "language" for date formatting + +\ utility words +: UNDER+ ( a b c -- a+c b ) ROT + SWAP ; +: 3DUP ( a b c -- a b c a b c ) 2 PICK 2 PICK 2 PICK ; +: WRITE$ ( caddr -- ) COUNT TYPE ; \ print a counted string +: ',' ( -- ) ." , " ; +: '-' ( -- ) ." -" ; + +\ day of week calculation +\ "This is an algorithm I've carried with me for 35 years, +\ originally in Assembler and Fortran II." +\ It counts the number of days from March 1, 1900." +\ Wil Baden R.I.P. +\ ***************************************************** +\ **WARNING** only good until 2078 on 16 bit machine ** +\ ***************************************************** +DECIMAL +: CDAY ( dd mm yyyy -- century_day ) + -3 UNDER+ OVER 0< + IF 12 UNDER+ 1- THEN + 1900 - 1461 4 */ SWAP 306 * 5 + 10 / + + ; + +: DOW ( cday -- day_of_week ) 2 + 7 MOD 1+ ; ( 7 is Sunday) + +\ formatted number printers +: ##. ( n -- ) 0 <# # # #> TYPE ; +: ####. ( n -- ) 0 <# # # # # #> TYPE ; + +\ make some string list words +: LIST[ ( -- ) !CSP 0 C, ; \ list starts with 0 bytes, record stack pos. +: ]LIST ( -- ) 0 C, ALIGN ?CSP ; \ '0' ends list, check stack + +: NEXT$ ( $[1] -- $[2] ) COUNT + ; \ get next string +: NTH$ ( n list -- $addr ) SWAP 0 DO NEXT$ LOOP ; \ get nth string + +: " ( -- ) [CHAR] " WORD C@ CHAR+ ALLOT ; \ compile text upto " + +\ make the lists +CREATE MONTHS + LIST[ " January" " February" " March" " April" " May" " June" " July" + " August" " September" " October" " November" " December" ]LIST + +CREATE DAYS + LIST[ " Monday" " Tuesday" " Wednesday" " Thursday" + " Friday" " Saturday" " Sunday" ]LIST + +\ expose lists as indexable arrays that print the string +: ]MONTH$. ( n -- ) MONTHS NTH$ WRITE$ ; +: ]DAY$. ( n -- ) DAYS NTH$ WRITE$ ; + + +\ =========================================== +\ Rosetta Task Code Begins + +\ Rosetta Date Format 1 +: Y-M-D. ( d m y -- ) ####. '-' ##. '-' ##. ; + +\ Rosetta Date Format 2 +: LONG.DATE ( d m y -- ) + 3DUP CDAY DOW ]DAY$. ',' -ROT ]MONTH$. SPACE ##. ',' ####. ; diff --git a/Task/Date-format/Forth/date-format-3.fth b/Task/Date-format/Forth/date-format-3.fth new file mode 100644 index 0000000000..537171a11e --- /dev/null +++ b/Task/Date-format/Forth/date-format-3.fth @@ -0,0 +1,3 @@ + 5 7 2018 Y-M-D. 2018-07-05 ok + ok +5 7 2018 LONG.DATE Thursday, July 05, 2018 ok diff --git a/Task/Date-format/REBOL/date-format.rebol b/Task/Date-format/REBOL/date-format.rebol index 8d79f278ce..5e950355d9 100644 --- a/Task/Date-format/REBOL/date-format.rebol +++ b/Task/Date-format/REBOL/date-format.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Date Formatting" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Date_format ] diff --git a/Task/Date-manipulation/REBOL/date-manipulation.rebol b/Task/Date-manipulation/REBOL/date-manipulation.rebol index 7679959ecc..e8bf43bec8 100644 --- a/Task/Date-manipulation/REBOL/date-manipulation.rebol +++ b/Task/Date-manipulation/REBOL/date-manipulation.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Date Manipulation" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Date_Manipulation ] diff --git a/Task/Date-manipulation/Ring/date-manipulation.ring b/Task/Date-manipulation/Ring/date-manipulation.ring index d5a2667e7b..74cd229257 100644 --- a/Task/Date-manipulation/Ring/date-manipulation.ring +++ b/Task/Date-manipulation/Ring/date-manipulation.ring @@ -1,7 +1,4 @@ # Project : Date manipulation -# Date : 2018/02/14 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" dateorigin = "March 7 2009 7:30pm EST" diff --git a/Task/Day-of-the-week/REBOL/day-of-the-week.rebol b/Task/Day-of-the-week/REBOL/day-of-the-week.rebol index c2adaf472f..2cd88e37a4 100644 --- a/Task/Day-of-the-week/REBOL/day-of-the-week.rebol +++ b/Task/Day-of-the-week/REBOL/day-of-the-week.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Yuletide Holiday" - Author: oofoe - Date: 2009-12-07 URL: http://rosettacode.org/wiki/Yuletide_Holiday ] diff --git a/Task/Deconvolution-1D/Scala/deconvolution-1d.scala b/Task/Deconvolution-1D/Scala/deconvolution-1d.scala new file mode 100644 index 0000000000..cbf6320b61 --- /dev/null +++ b/Task/Deconvolution-1D/Scala/deconvolution-1d.scala @@ -0,0 +1,23 @@ +object Deconvolution1D extends App { + val (h, f) = (Array(-8, -9, -3, -1, -6, 7), Array(-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1)) + val g = Array(24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7) + val sb = new StringBuilder + + private def deconv(g: Array[Int], f: Array[Int]) = { + val h = Array.ofDim[Int](g.length - f.length + 1) + + for (n <- h.indices) { + h(n) = g(n) + for (i <- math.max(n - f.length + 1, 0) until n) h(n) -= h(i) * f(n - i) + h(n) /= f(0) + } + h + } + + sb.append(s"h = ${h.mkString("[", ", ", "]")}\n") + .append(s"deconv(g, f) = ${deconv(g, f).mkString("[", ", ", "]")}\n") + .append(s"f = ${f.mkString("[", ", ", "]")}\n") + .append(s"deconv(g, h) = ${deconv(g, h).mkString("[", ", ", "]")}") + println(sb.result()) + +} diff --git a/Task/Deepcopy/C/deepcopy-1.c b/Task/Deepcopy/C/deepcopy-1.c index fa8f26e416..8080a46771 100644 --- a/Task/Deepcopy/C/deepcopy-1.c +++ b/Task/Deepcopy/C/deepcopy-1.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 15th November 2017*/ - #include typedef struct{ diff --git a/Task/Deepcopy/C/deepcopy-2.c b/Task/Deepcopy/C/deepcopy-2.c index 9854f0d30a..752b30f425 100644 --- a/Task/Deepcopy/C/deepcopy-2.c +++ b/Task/Deepcopy/C/deepcopy-2.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 15th November 2017*/ - #include #include diff --git a/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-1.factor b/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-1.factor new file mode 100644 index 0000000000..3066a432c3 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-1.factor @@ -0,0 +1 @@ +PREDICATE: my-int < integer [ 0 > ] [ 11 < ] bi and ; diff --git a/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-2.factor b/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-2.factor new file mode 100644 index 0000000000..a40514c03e --- /dev/null +++ b/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-2.factor @@ -0,0 +1,3 @@ +11 my-int? ! f +10 my-int? ! t +"hello" my-int? ! f diff --git a/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-3.factor b/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-3.factor new file mode 100644 index 0000000000..6fd01cb51d --- /dev/null +++ b/Task/Define-a-primitive-data-type/Factor/define-a-primitive-data-type-3.factor @@ -0,0 +1,6 @@ +GENERIC: ++ ( m -- n ) +M: integer ++ 1 + ; +M: my-int ++ 2/ ; + +10 ++ ! 5 +11 ++ ! 12 diff --git a/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-1.fth b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-1.fth new file mode 100644 index 0000000000..855af38880 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-1.fth @@ -0,0 +1,9 @@ +DECIMAL +: CLIP ( n lo hi -- n') ROT MIN MAX ; +: BETWEEN ( n lo hi -- flag) 1+ WITHIN ; + +\ programmer chooses CLIPPED or SAFE integer assignment +: CLIP! ( n addr -- ) SWAP 1 10 CLIP SWAP ! ; +: SAFE! ( n addr -- ) + OVER 1 10 BETWEEN 0= ABORT" out of range!" + ! ; diff --git a/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-2.fth b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-2.fth new file mode 100644 index 0000000000..070b629cf6 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-2.fth @@ -0,0 +1,10 @@ +VARIABLE X +7 X SAFE! X ? 7 ok +12 X CLIP! X ? 10 ok + +99 X SAFE! +:64: out of range! +99 X >>>SAFE!<<< +Backtrace: +$7FAA2B0C throw +$7FAD4698 c(abort") diff --git a/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-3.fth b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-3.fth new file mode 100644 index 0000000000..d16ef24c16 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-3.fth @@ -0,0 +1,9 @@ +DECIMAL +: FAST! ( n addr -- ) ! ; ( alias the standard version) + +DEFER ! + +\ commands to change the action of '!' +: LIMITS-ON ( -- ) ['] SAFE! IS ! ; +: LIMITS-OFF ( -- ) ['] FAST! IS ! ; +: CLIPPING-ON ( -- ) ['] CLIP! IS ! ; diff --git a/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-4.fth b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-4.fth new file mode 100644 index 0000000000..67e7827488 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-4.fth @@ -0,0 +1,22 @@ +VARIABLE Y + +LIMITS-OFF ok + 1 Y ! Y ? 1 ok + 10 Y ! Y ? 10 ok + 11 Y ! Y ? 11 ok + 0 Y ! Y ? 0 ok + LIMITS-ON ok + 1 Y ! Y ? 1 ok + 10 Y ! Y ? 10 ok + 11 Y ! Y ? +:25: out of range! + 11 Y >>>!<<< Y ? +Backtrace: +$7FAA2B0C throw +$7FAD4460 c(abort") + 0 Y ! Y ? +:26: out of range! + 0 Y >>>!<<< Y ? +Backtrace: +$7FAA2B0C throw +$7FAD4460 c(abort") diff --git a/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-5.fth b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-5.fth new file mode 100644 index 0000000000..bf918cdf49 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-5.fth @@ -0,0 +1,9 @@ +: (->) ( n -- ) + OVER 1 10 BETWEEN 0= ABORT" out of range!" + >BODY ! ; + +: -> ( n -- ) + STATE @ + IF POSTPONE ['] POSTPONE (->) \ compiling action + ELSE ' (->) \ interpret action + THEN ; IMMEDIATE diff --git a/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-6.fth b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-6.fth new file mode 100644 index 0000000000..503c795f49 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Forth/define-a-primitive-data-type-6.fth @@ -0,0 +1,10 @@ +0 VALUE Z ok +99 TO Z ok ( normal assignment) +Z . 99 ok +99 -> Z ( safe assignment) +:43: out of range! +99 -> >>>Z<<< +Backtrace: +$7FAA2B0C throw +$7FAD4570 c(abort") +$7FAD45DC (->) diff --git a/Task/Delegates/Phix/delegates-1.phix b/Task/Delegates/Phix/delegates-1.phix new file mode 100644 index 0000000000..bebf0eff23 --- /dev/null +++ b/Task/Delegates/Phix/delegates-1.phix @@ -0,0 +1,44 @@ +enum OTHER, OPERATION + +function operation(object o) + integer rid = o[OPERATION] + if rid!=NULL then + return call_func(rid,{}) + end if + return "no implementation" +end function + +function xthing() + return "default implementation" +end function + +function newX() + return {1,routine_id("xthing"),2} +end function + +function newY() + object res = newX() + res[OTHER] = "something else" + -- remove delegate: + res[OPERATION] = NULL + return res +end function + +function zthing() + return "delegate implementation" +end function + +function newZ() + object res = newX() + -- replace delegate: + res[OPERATION] = routine_id("zthing") + return res +end function + +object x = newX(), + y = newY(), + z = newZ() + +?operation(x) +?operation(y) +?operation(z) diff --git a/Task/Delegates/Phix/delegates-2.phix b/Task/Delegates/Phix/delegates-2.phix new file mode 100644 index 0000000000..8462c34de1 --- /dev/null +++ b/Task/Delegates/Phix/delegates-2.phix @@ -0,0 +1,7 @@ +?operation(x) +try -- (since rid=NULL check commented out) + ?operation(y) +catch e + ?"oops, no implementation" +end try +?operation(z) diff --git a/Task/Delegates/Scala/delegates.scala b/Task/Delegates/Scala/delegates.scala new file mode 100644 index 0000000000..e81e47e2d4 --- /dev/null +++ b/Task/Delegates/Scala/delegates.scala @@ -0,0 +1,32 @@ +trait Thingable { + def thing: String +} + +class Delegator { + var delegate: Thingable = _ + + def operation: String = if (delegate == null) "default implementation" + else delegate.thing +} + +class Delegate extends Thingable { + override def thing = "delegate implementation" +} + +// Example usage +// Memory management ignored for simplification +object DelegateExample extends App { + + val a = new Delegator + assert(a.operation == "default implementation") + // With a delegate: + val d = new Delegate + a.delegate = d + assert(a.operation == "delegate implementation") + // Same as the above, but with an anonymous class: + a.delegate = new Thingable() { + override def thing = "anonymous delegate implementation" + } + assert(a.operation == "anonymous delegate implementation") + +} diff --git a/Task/Delete-a-file/Emacs-Lisp/delete-a-file.l b/Task/Delete-a-file/Emacs-Lisp/delete-a-file.l new file mode 100644 index 0000000000..134788a375 --- /dev/null +++ b/Task/Delete-a-file/Emacs-Lisp/delete-a-file.l @@ -0,0 +1,8 @@ +;; function to remove file & directory +(defun my-files-rm () + (delete-file "input.txt") + (delete-directory "docs")) + +(my-files-rm) +(cd "~/") ;; change to home dir +(my-files-rm) diff --git a/Task/Delete-a-file/VAX-Assembly/delete-a-file.vax b/Task/Delete-a-file/VAX-Assembly/delete-a-file.vax new file mode 100644 index 0000000000..1e48af75de --- /dev/null +++ b/Task/Delete-a-file/VAX-Assembly/delete-a-file.vax @@ -0,0 +1,18 @@ +74 75 70 6E 69 20 65 74 65 6C 65 64 0000 1 dcl: .ascii "delete input.txt;,docs.dir;" +64 2E 73 63 6F 64 2C 3B 74 78 74 2E 000C + 3B 72 69 0018 +69 76 65 64 73 79 73 24 73 79 73 2C 001B 2 .ascii ",sys$sysdevice:[000000]input.txt;" +69 5D 30 30 30 30 30 30 5B 3A 65 63 0027 + 3B 74 78 74 2E 74 75 70 6E 0033 +69 76 65 64 73 79 73 24 73 79 73 2C 003C 3 .ascii ",sys$sysdevice:[000000]docs.dir;" +64 5D 30 30 30 30 30 30 5B 3A 65 63 0048 + 3B 72 69 64 2E 73 63 6F 0054 + 005C 4 + 0000005C 005C 5 desc: .long .-dcl ;character count + 00000000' 0060 6 .address dcl + 0064 7 + 0000 0064 8 .entry main,0 + F3 AF 7F 0066 9 pushaq desc + 00000000'GF 01 FB 0069 10 calls #1, g^lib$do_command ;execute shell command + 04 0070 11 ret + 0071 12 .end main diff --git a/Task/Detect-division-by-zero/NewLISP/detect-division-by-zero.newlisp b/Task/Detect-division-by-zero/NewLISP/detect-division-by-zero.newlisp new file mode 100644 index 0000000000..b6344b1727 --- /dev/null +++ b/Task/Detect-division-by-zero/NewLISP/detect-division-by-zero.newlisp @@ -0,0 +1,15 @@ +#! /usr/local/bin/newlisp + +(define (check-division x y) + (catch (/ x y) 'check-zero) + (if (not (integer? check-zero)) + (setq check-zero "Division by zero.")) + check-zero +) + +(println (check-division 10 4)) +(println (check-division 4 0)) +(println (check-division 20 5)) +(println (check-division 11 0)) + +(exit) diff --git a/Task/Detect-division-by-zero/REBOL/detect-division-by-zero.rebol b/Task/Detect-division-by-zero/REBOL/detect-division-by-zero.rebol index 95d1c1d272..66dbc195d7 100644 --- a/Task/Detect-division-by-zero/REBOL/detect-division-by-zero.rebol +++ b/Task/Detect-division-by-zero/REBOL/detect-division-by-zero.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Detect Divide by Zero" - Date: 2009-12-16 - Author: oofoe URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection ] diff --git a/Task/Detect-division-by-zero/REXX/detect-division-by-zero.rexx b/Task/Detect-division-by-zero/REXX/detect-division-by-zero.rexx index 36ebe3211f..dff4f115ed 100644 --- a/Task/Detect-division-by-zero/REXX/detect-division-by-zero.rexx +++ b/Task/Detect-division-by-zero/REXX/detect-division-by-zero.rexx @@ -1,22 +1,23 @@ -/*REXX program demonstrates detects and handles division by zero. */ - -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 /*this'll do it, furrrr shurrre. */ -exit /*We're kaput. Ja vohl ! */ - -/*───────────────────────────────error handling subroutines and others.─*/ -err: if rc==42 then do; say; say /*1st, check for a specific error*/ - say center(' division by zero is a no-no. ',79,'═') - say; say - exit 130 - end - - 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) +/*REXX program demonstrates detection and handling division by zero. */ +signal on syntax /*handle all REXX syntax errors. */ +x = sourceline() /*being cute, x=is the size of this pgm*/ +y = x - x /*setting to zero the obtuse way. */ +z = x / y /*this'll trigger it, furrrr shurrre. */ +exit /*We're kaput. Ja vohl ! */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +err: if rc==42 then do; say /*first, check for a specific error. */ + say center(' ***error*** ', 79, "═") + say 'Division by zero detected at line ' @ , + " and the REXX statement is:" + say sourceLine(@) + say + exit 42 + end + say + say center(' error! ', 79, "*") + do #=1 for arg(); say; say arg(#); say + end /*#*/ + exit 13 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +syntax: @=sigl; call err 'REXX program' condition("C") 'error', condition('D'), , + 'REXX source statement (line' sigl"):", sourceLine(sigl) diff --git a/Task/Detect-division-by-zero/VAX-Assembly/detect-division-by-zero.vax b/Task/Detect-division-by-zero/VAX-Assembly/detect-division-by-zero.vax new file mode 100644 index 0000000000..220fa7d398 --- /dev/null +++ b/Task/Detect-division-by-zero/VAX-Assembly/detect-division-by-zero.vax @@ -0,0 +1,15 @@ +65 64 69 76 69 64 00000008'010E0000' 0000 1 desc: .ascid "divide by zero" + 6F 72 65 7A 20 79 62 20 000E + 0000 0016 2 .entry handler,0 + E5 AF 7F 0018 3 pushaq desc + 00000000'GF 01 FB 001B 4 calls #1, g^lib$put_output + 04 0022 5 ret + 0023 6 + 0000 0023 7 .entry main,0 + 6D EE AF 9E 0025 8 movab handler, (fp) ;register exception handler + 50 01 00 C7 0029 9 divl3 #0, #1, r0 + 04 002D 10 ret + 002E 11 + 002E 12 .end main +$ run dv +divide by zero diff --git a/Task/Determine-if-a-string-is-numeric/REBOL/determine-if-a-string-is-numeric.rebol b/Task/Determine-if-a-string-is-numeric/REBOL/determine-if-a-string-is-numeric.rebol index 5a2f7a7a70..921a6ba020 100644 --- a/Task/Determine-if-a-string-is-numeric/REBOL/determine-if-a-string-is-numeric.rebol +++ b/Task/Determine-if-a-string-is-numeric/REBOL/determine-if-a-string-is-numeric.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Is Numeric?" - Author: oofoe - Date: 2009-12-04 URL: http://rosettacode.org/wiki/IsNumeric ] diff --git a/Task/Determine-if-only-one-instance-is-running/Java/determine-if-only-one-instance-is-running.java b/Task/Determine-if-only-one-instance-is-running/Java/determine-if-only-one-instance-is-running.java index c6029dcfba..10308f67a6 100644 --- a/Task/Determine-if-only-one-instance-is-running/Java/determine-if-only-one-instance-is-running.java +++ b/Task/Determine-if-only-one-instance-is-running/Java/determine-if-only-one-instance-is-running.java @@ -1,23 +1,35 @@ -import java.io.IOExeception; +import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; public class SingletonApp { - private static final int PORT = 12345; // random large port number - private static ServerSocket s; + private static final int PORT = 65000; // random large port number + private static ServerSocket s; - // static initializer - { - try { - s = new ServerSocket(PORT, 10, InetAddress.getLocalHost()); - } catch (UnknownHostException e) { - // shouldn't happen for localhost - } catch (IOException e) { - // port taken, so app is already running - System.exit(0); - } - } - // main() and rest of application... + // static initializer + static { + try { + s = new ServerSocket(PORT, 10, InetAddress.getLocalHost()); + } catch (UnknownHostException e) { + // shouldn't happen for localhost + } catch (IOException e) { + // port taken, so app is already running + System.out.print("Application is already running,"); + System.out.println(" so terminating this instance."); + System.exit(0); + } + } + + public static void main(String[] args) { + System.out.print("OK, only this instance is running"); + System.out.println(" but will terminate in 10 seconds."); + try { + Thread.sleep(10000); + if (s != null && !s.isClosed()) s.close(); + } catch (Exception e) { + System.err.println(e); + } + } } diff --git a/Task/Determine-if-only-one-instance-is-running/Ring/determine-if-only-one-instance-is-running.ring b/Task/Determine-if-only-one-instance-is-running/Ring/determine-if-only-one-instance-is-running.ring new file mode 100644 index 0000000000..1c823779f8 --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/Ring/determine-if-only-one-instance-is-running.ring @@ -0,0 +1,22 @@ +# Project : Determine if only one instance is running + +task = "ringw.exe" +taskname = "tasklist.txt" +remove(taskname) +system("tasklist >> tasklist.txt") +fp = fopen(taskname,"r") +tasks = read("tasklist.txt") +counttask = count(tasks,task) +if counttask > 0 + see task + " running in " + counttask + " instances" + nl +else + see task + " is not running" + nl +ok + +func count(cString,dString) + sum = 0 + while substr(cString,dString) > 0 + sum++ + cString = substr(cString,substr(cString,dString)+len(string(sum))) + end + return sum diff --git a/Task/Determine-if-only-one-instance-is-running/Scala/determine-if-only-one-instance-is-running.scala b/Task/Determine-if-only-one-instance-is-running/Scala/determine-if-only-one-instance-is-running.scala new file mode 100644 index 0000000000..e60aafbca6 --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/Scala/determine-if-only-one-instance-is-running.scala @@ -0,0 +1,23 @@ +import java.io.IOException +import java.net.{InetAddress, ServerSocket} + +object SingletonApp extends App { + private val port = 65000 + + try { + val s = new ServerSocket(port, 10, InetAddress.getLocalHost) + } + catch { + case _: IOException => + // port taken, so app is already running + println("Application is already running, so terminating this instance.") + sys.exit(-1) + } + + println("OK, only this instance is running but will terminate in 10 seconds.") + + Thread.sleep(10000) + + sys.exit(0) + +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root.phix b/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root.phix new file mode 100644 index 0000000000..d8fc48514e --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root.phix @@ -0,0 +1,39 @@ +function mdr_mp(integer m) +integer mp = 0 + while m>9 do + integer newm = 1 + while m do + newm *= remainder(m,10) + m = floor(m/10) + end while + m = newm + mp += 1 + end while + return {m,mp} +end function + +constant tests = {123321, 7739, 893, 899998} +printf(1,"Number MDR MP\n") +printf(1,"====== === ==\n") +for i=1 to length(tests) do + integer ti = tests[i] + printf(1,"%6d %6d %6d\n",ti&mdr_mp(ti)) +end for + +integer i=0, found = 0 +sequence res = repeat({},10) +while found<50 do + integer {mdr,mp} = mdr_mp(i) + if length(res[mdr+1])<5 then + res[mdr+1] &= i + found += 1 + end if + i += 1 +end while + +printf(1,"\nMDR 1 2 3 4 5") +printf(1,"\n=== ===========================\n") + +for i=1 to 10 do + printf(1,"%2d %5d %5d %5d %5d %5d\n",prepend(res[i],i-1)) +end for diff --git a/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring b/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring index 328477f6f1..6b22b33f48 100644 --- a/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring +++ b/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring @@ -1,7 +1,4 @@ # Project : Digital root/Multiplicative digital root -# Date : 2017/11/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" root = newlist(10, 5) diff --git a/Task/Digital-root/K/digital-root.k b/Task/Digital-root/K/digital-root.k new file mode 100644 index 0000000000..0352519707 --- /dev/null +++ b/Task/Digital-root/K/digital-root.k @@ -0,0 +1,6 @@ +/ print digital root and additive persistence +prt: {`"Digital root = ", x, `"Additive persistence = ",y} +/ sum of digits of an integer +sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d} +/ compute digital root and additive persistence +digroot: {sm::sumdig x; ap::0; (9<){sm::sumdig x;ap::ap+1; x:sm}/x; prt[sm;ap]} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ceylon/dinesmans-multiple-dwelling-problem.ceylon b/Task/Dinesmans-multiple-dwelling-problem/Ceylon/dinesmans-multiple-dwelling-problem.ceylon new file mode 100644 index 0000000000..f2e784ae4d --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Ceylon/dinesmans-multiple-dwelling-problem.ceylon @@ -0,0 +1,24 @@ +shared void run() { + + function notAdjacent(Integer a, Integer b) => (a - b).magnitude >= 2; + function allDifferent(Integer* ints) => ints.distinct.size == ints.size; + + value solutions = [ + for (baker in 1..4) + for (cooper in 2..5) + for (fletcher in 2..4) + for (miller in 2..5) + for (smith in 1..5) + if (miller > cooper && + notAdjacent(smith, fletcher) && + notAdjacent(fletcher, cooper) && + allDifferent(baker, cooper, fletcher, miller, smith)) + "baker lives on ``baker`` + cooper lives on ``cooper`` + fletcher lives on ``fletcher`` + miller lives on ``miller`` + smith lives on ``smith``" + ]; + + print(solutions.first else "No solution!"); +} diff --git a/Task/Dining-philosophers/Nim/dining-philosophers.nim b/Task/Dining-philosophers/Nim/dining-philosophers.nim index f083249723..ada034013f 100644 --- a/Task/Dining-philosophers/Nim/dining-philosophers.nim +++ b/Task/Dining-philosophers/Nim/dining-philosophers.nim @@ -1,41 +1,47 @@ -import threadpool, locks, math, os +import threadpool, locks, math, os, random +# to call randomize() as a seed, need to import random module randomize() type Philosopher = ref object name: string + food: string forkLeft, forkRight: int const n = 5 names = ["Aristotle", "Kant", "Spinoza", "Marx", "Russell"] + foods = [" rat poison", " cockroaches", " dog food", " lemon-curd toast", " baked worms"] var - forks: array[n, TLock] + forks: array[n, Lock] phils: array[n, Philosopher] - threads: array[n, TThread[Philosopher]] + threads: array[n, Thread[Philosopher]] proc run(p: Philosopher) {.thread.} = - sleep random(1 .. 10) * 500 + # random deprecated, use rand(x .. y) + sleep rand(1..10) * 500 echo p.name, " is hungry." acquire forks[min(p.forkLeft, p.forkRight)] - sleep random(1 .. 5) * 500 + sleep rand(1..5) * 500 acquire forks[max(p.forkLeft, p.forkRight)] - echo p.name, " starts eating." - sleep random(1 .. 10) * 500 + echo p.name, " starts eating", p.food, "." + sleep rand(1..10) * 500 - echo p.name, " finishes eating and leaves to think." + echo p.name, " finishes eating", p.food, " and leaves to think." release forks[p.forkLeft] release forks[p.forkRight] -for i in 0 .. test = [1, 5, 7, 0, 3, 2] insert(test, 0, 9) diff --git a/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring b/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring index 399f265a52..b29aae825f 100644 --- a/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring +++ b/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring @@ -1,7 +1,4 @@ # Project : Doubly-linked list/Traversal -# Date : 2018/03/13 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : trav = [123, 789, 456] travfor = sort(trav) diff --git a/Task/Doubly-linked-list-Traversal/Scala/doubly-linked-list-traversal.scala b/Task/Doubly-linked-list-Traversal/Scala/doubly-linked-list-traversal.scala new file mode 100644 index 0000000000..140ad381fb --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Scala/doubly-linked-list-traversal.scala @@ -0,0 +1,12 @@ +import java.util + +object DoublyLinkedListTraversal extends App { + + private val ll = new util.LinkedList[String] + + private def traverse(iter: util.Iterator[String]) = + while (iter.hasNext) iter.next + + traverse(ll.iterator) + traverse(ll.descendingIterator) +} diff --git a/Task/Dragon-curve/Befunge/dragon-curve.bf b/Task/Dragon-curve/Befunge/dragon-curve.bf new file mode 100644 index 0000000000..62ddc9d176 --- /dev/null +++ b/Task/Dragon-curve/Befunge/dragon-curve.bf @@ -0,0 +1,7 @@ +" :htpeD">:#,_&>:00p:2%10p:2/:1+1>\#<1#*-#2:#\_$:1-20p510g2*-*1+610g4vv!>0$#0\#$\_-10p20p::00g4/:1+1>\#<1#*-#4:#\_$1-2*3/\2%!>0$#0\#$\_--vv|+2 +v:\p06!*-1::p05>$$$1-\1->>:v:+1\:1+*!60g*!#v_!\!*50g0`*!40gg,::30g40g:2-#^_>>$>>:^:+1g02::\,+55_55+,@v":* +v%2/2+*">~":< ^\-1g05-*">~"/2+*"|~"-%*"|~"\/*"|~":\-*">~"/2+%*"|~"\/*<^<: +>60p\:"~>"*+2/2%60g+2%70p:"kI"*+2/2%60p\:"kI"*+2/2%60g+2%-\70g-"~|"**+"}"^ diff --git a/Task/Dragon-curve/Perl-6/dragon-curve.pl6 b/Task/Dragon-curve/Perl-6/dragon-curve.pl6 index 70f561a21b..65d40f60b8 100644 --- a/Task/Dragon-curve/Perl-6/dragon-curve.pl6 +++ b/Task/Dragon-curve/Perl-6/dragon-curve.pl6 @@ -1,35 +1,29 @@ +use SVG; + role Lindenmayer { has %.rules; method succ { - self.comb.map( - { %!rules{$^c} // $c } - ).join but Lindenmayer(%!rules) + self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } } -my $dragon = "FX" but Lindenmayer( - { X => 'X+YF+', Y => '-FX-Y' } -); +my $dragon = "FX" but Lindenmayer( { X => 'X+YF+', Y => '-FX-Y' } ); -$dragon++ for ^15; +$dragon++ xx ^15; -say " - -"; -say ''; +my @points = 215, 350; for $dragon.comb { - state ($x, $y) = 100, 100; + state ($x, $y) = @points[0,1]; state $d = 2 + 0i; - - if /F/ { - say ""; - } + if /'F'/ { @points.append: ($x += $d.re).round(.1), ($y += $d.im).round(.1) } elsif /< + - >/ { $d *= "{$_}1i" } } -say ""; +say SVG.serialize( + svg => [ + :600width, :450height, :style, + :rect[:width<100%>, :height<100%>, :fill], + :polyline[ :points(@points.join: ','), :fill ], + ], +); diff --git a/Task/Draw-a-cuboid/Befunge/draw-a-cuboid.bf b/Task/Draw-a-cuboid/Befunge/draw-a-cuboid.bf new file mode 100644 index 0000000000..b5c41f4784 --- /dev/null +++ b/Task/Draw-a-cuboid/Befunge/draw-a-cuboid.bf @@ -0,0 +1,4 @@ +" :htdiW">:#,_>&>00p" :thgieH">:#,_>&>:10p0" :htpeD">:#,_$>&>:20p55+,+:1`*:vv +v\-*`0:-g01\++*`\0:-\-1g01:\-*`0:-g02\+*`\0:-\-1g02<:::::<\g3`\g01:\1\+55\1-1_v +>":"\1\:20g\`!3g:30p\00g2*\::20g\`\20g1-\`+1+3g\1\30g\:20g-::0\`\2*1+*-\48*\:^v +/\_ @_\#!:!#$>#$_\#!:,#-\#1 <+1\<*84g02"_"+1*2g00+551$< diff --git a/Task/Draw-a-cuboid/C/draw-a-cuboid.c b/Task/Draw-a-cuboid/C/draw-a-cuboid.c index cbfc44eb32..dee16bab57 100644 --- a/Task/Draw-a-cuboid/C/draw-a-cuboid.c +++ b/Task/Draw-a-cuboid/C/draw-a-cuboid.c @@ -1,4 +1,3 @@ -/*Code verified and output corrected by Abhishek Ghosh, 23rd September 2017*/ #include #include #include diff --git a/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring b/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring index 7c55edf5e1..1dfbd7d9ef 100644 --- a/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring +++ b/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring @@ -1,7 +1,4 @@ # Project : Draw a cuboid -# Date : 2018/01/18 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "guilib.ring" diff --git a/Task/Draw-a-cuboid/Scala/draw-a-cuboid.scala b/Task/Draw-a-cuboid/Scala/draw-a-cuboid.scala new file mode 100644 index 0000000000..a83367b039 --- /dev/null +++ b/Task/Draw-a-cuboid/Scala/draw-a-cuboid.scala @@ -0,0 +1,91 @@ +import java.awt._ +import java.awt.event.{MouseAdapter, MouseEvent} + +import javax.swing._ + +import scala.math.{Pi, cos, sin} + +object Cuboid extends App { + SwingUtilities.invokeLater(() => { + + class Cuboid extends JPanel { + private val nodes: Array[Array[Double]] = + Array(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1), + Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1)) + private var mouseX, prevMouseX, mouseY, prevMouseY: Int = _ + + private def edges = + Seq(Seq(0, 1), Seq(1, 3), Seq(3, 2), Seq(2, 0), + Seq(4, 5), Seq(5, 7), Seq(7, 6), Seq(6, 4), + Seq(0, 4), Seq(1, 5), Seq(2, 6), Seq(3, 7)) + + override def paintComponent(gg: Graphics): Unit = { + val g = gg.asInstanceOf[Graphics2D] + + def drawCube(g: Graphics2D): Unit = { + g.translate(getWidth / 2, getHeight / 2) + for (edge <- edges) { + g.drawLine(nodes(edge.head)(0).round.toInt, nodes(edge.head)(1).round.toInt, + nodes(edge(1))(0).round.toInt, nodes(edge(1))(1).round.toInt) + } + for (node <- nodes) g.fillOval(node(0).round.toInt - 4, node(1).round.toInt - 4, 8, 8) + } + + super.paintComponent(gg) + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + drawCube(g) + } + + private def scale(sx: Double, sy: Double, sz: Double): Unit = { + for (node <- nodes) { + node(0) *= sx + node(1) *= sy + node(2) *= sz + } + } + + private def rotateCube(angleX: Double, angleY: Double): Unit = { + val (sinX, cosX, sinY, cosY) = (sin(angleX), cos(angleX), sin(angleY), cos(angleY)) + for (node <- nodes) { + val (x, y, z) = (node.head, node(1), node(2)) + node(0) = x * cosX - z * sinX + node(2) = z * cosX + x * sinX + node(1) = y * cosY - node(2) * sinY + node(2) = node(2) * cosY + y * sinY + } + } + + addMouseListener(new MouseAdapter() { + override def mousePressed(e: MouseEvent): Unit = { + mouseX = e.getX + mouseY = e.getY + } + }) + + addMouseMotionListener(new MouseAdapter() { + override def mouseDragged(e: MouseEvent): Unit = { + prevMouseX = mouseX + prevMouseY = mouseY + mouseX = e.getX + mouseY = e.getY + rotateCube((mouseX - prevMouseX) * 0.01, (mouseY - prevMouseY) * 0.01) + repaint() + } + }) + + scale(80, 120, 160) + rotateCube(Pi / 5, Pi / 9) + setPreferredSize(new Dimension(640, 640)) + setBackground(Color.white) + } + + new JFrame("Cuboid") { + add(new Cuboid, BorderLayout.CENTER) + pack() + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) + setLocationRelativeTo(null) + setResizable(false) + setVisible(true) + } + }) +} diff --git a/Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb b/Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb new file mode 100644 index 0000000000..7c1a6d8440 --- /dev/null +++ b/Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb @@ -0,0 +1,48 @@ +x = 6 : y = 2 : z = 3 + +Sub cuboid(nx, ny, nz) + WScript.StdOut.WriteLine "Cuboid " & nx & " " & ny & " " & nz & ":" + lx = X * nx : ly = y * ny : lz = z * nz + + 'define the array + Dim area(): ReDim area(ly+lz, lx+ly) + For i = 0 to ly+lz + For j = 0 to lx+ly : area(i,j) = " " : Next + Next + + 'drawing lines + For i = 0 to nz-1 : drawLine area, lx, 0, Z*i, "-" : Next + For i = 0 to ny : drawLine area, lx, y*i, lz+y*i, "-" : Next + For i = 0 to nx-1 : drawLine area, lz, x*i, 0, "|" : Next + For i = 0 to ny : drawLine area, lz, lx+y*i, y*i, "|" : Next + For i = 0 to nz-1 : drawLine area, ly, lx, z*i, "/" : Next + For i = 0 to nx : drawLine area, ly, x*i, lz, "/" : Next + + 'output the cuboid (in reverse) + For i = UBound(area,1) to 0 Step -1 + linOut = "" + For j = 0 to UBound(area,2) : linOut = linOut & area(i,j) : Next + WScript.StdOut.WriteLine linOut + Next +End Sub + +Sub drawLine(arr, n, sx, sy, c) + Select Case c + Case "-" + dx = 1 : dy = 0 + Case "|" + dx = 0 : dy = 1 + Case "/" + dx = 1 : dy = 1 + End Select + For i = 0 to n + xi = sx + (i * dx) : yi = sy + (i * dy) + If arr(yi, xi) = " " Then + arr(yi, xi) = c + Else + arr(yi, xi) = "+" + End If + Next +End Sub + +cuboid 2,3,4 diff --git a/Task/Draw-a-sphere/VBScript/draw-a-sphere.vb b/Task/Draw-a-sphere/VBScript/draw-a-sphere.vb new file mode 100644 index 0000000000..31889e47d7 --- /dev/null +++ b/Task/Draw-a-sphere/VBScript/draw-a-sphere.vb @@ -0,0 +1,51 @@ +shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") +light = Array(30, 30, -50) + +Sub Normalize(v) + length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) + v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length +End Sub + +Function Dot(x, y) + d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) + If d < 0 Then Dot = -d Else Dot = 0 End If +End Function + +'floor function is the Int function +'ceil function implementation +Function Ceil(x) + Ceil = Int(x) + If Ceil <> x Then Ceil = Ceil + 1 End if +End Function + +Sub DrawSphere(R, k, ambient) + Dim i, j, intensity, inten, b, x, y + Dim vec(3) + For i = Int(-R) to Ceil(R) + x = i + 0.5 + line = "" + For j = Int(-2*R) to Ceil(2*R) + y = j / 2 + 0.5 + If x * x + y * y <= R*R Then + vec(0) = x + vec(1) = y + vec(2) = Sqr(R * R - x * x - y * y) + Normalize vec + b = dot(light, vec)^k + ambient + intensity = Int((1 - b) * UBound(shades)) + If intensity < 0 Then intensity = 0 End If + If intensity >= UBound(shades) Then + intensity = UBound(shades) + End If + line = line & shades(intensity) + Else + line = line & " " + End If + Next + WScript.StdOut.WriteLine line + Next +End Sub + +Normalize light +DrawSphere 20, 4, 0.1 +DrawSphere 10,2,0.4 diff --git a/Task/Dutch-national-flag-problem/Ceylon/dutch-national-flag-problem.ceylon b/Task/Dutch-national-flag-problem/Ceylon/dutch-national-flag-problem.ceylon new file mode 100644 index 0000000000..3e5409ae8a --- /dev/null +++ b/Task/Dutch-national-flag-problem/Ceylon/dutch-national-flag-problem.ceylon @@ -0,0 +1,82 @@ +import ceylon.random { + + DefaultRandom +} + +abstract class Colour(name, ordinal) of red | white | blue satisfies Comparable { + shared String name; + shared Integer ordinal; + string => name; + compare(Colour other) => this.ordinal <=> other.ordinal; +} + +object red extends Colour("red", 0) {} +object white extends Colour("white", 1) {} +object blue extends Colour("blue", 2) {} + +Colour[] allColours = `Colour`.caseValues; + +shared void run() { + + function ordered({Colour*} colours) => + colours.paired.every(([c1, c2]) => c1 <= c2); + + value random = DefaultRandom(); + + function randomBalls(Integer length = 15) { + while (true) { + value balls = random.elements(allColours).take(length); + if (!ordered(balls)) { + return balls.sequence(); + } + } + } + + function dutchSort({Colour*} balls, Colour mid = white) { + value array = Array { *balls }; + if (array.empty) { + return []; + } + variable value i = 0; + variable value j = 0; + variable value n = array.size - 1; + while (j <= n) { + assert (exists ball = array[j]); + if (ball < mid) { + array.swap(i, j); + i ++; + j ++; + } + else if (ball > mid) { + array.swap(n, j); + n --; + } + else { + j ++; + } + } + return array; + } + + function idiomaticSort({Colour*} balls) => + balls.sort(increasing); + + value initialBalls = randomBalls(); + + "the initial balls are not randomized" + assert (!ordered(initialBalls)); + + print(initialBalls); + + value sortedBalls1 = idiomaticSort(initialBalls); + value sortedBalls2 = dutchSort(initialBalls); + + "the idiomatic sort didn't work" + assert (ordered(sortedBalls1)); + + "the dutch sort didn't work" + assert (ordered(sortedBalls2)); + + print(sortedBalls1); + print(sortedBalls2); +} diff --git a/Task/Dutch-national-flag-problem/Forth/dutch-national-flag-problem.fth b/Task/Dutch-national-flag-problem/Forth/dutch-national-flag-problem.fth new file mode 100644 index 0000000000..dd581f4ca9 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Forth/dutch-national-flag-problem.fth @@ -0,0 +1,148 @@ +\ Dutch flag DEMO for CAMEL99 Forth +\ *SORTS IN PLACE FROM Video MEMORY* + + INCLUDE DSK1.GRAFIX.F + INCLUDE DSK1.RANDOM.F + INCLUDE DSK1.CASE.F + +\ TMS9918 Video chip Specific code +HEX +FFFF FFFF FFFF FFFF PATTERN: SQUARE + +\ define colors and characters +DECIMAL +24 32 * CONSTANT SIZE \ flag will fill GRAPHICS screen +SIZE 3 / CONSTANT #256 \ 256 chars per segment of flag +1 CONSTANT REDSQR \ red character +9 CONSTANT WHTSQR \ white character +19 CONSTANT BLUSQR \ blue character + +\ color constants +1 CONSTANT TRANS +7 CONSTANT RED +5 CONSTANT BLU +16 CONSTANT WHT + +SQUARE REDSQR CHARDEF +SQUARE BLUSQR CHARDEF +SQUARE WHTSQR CHARDEF + +\ charset FG BG + 0 RED TRANS COLOR + 1 WHT TRANS COLOR + 2 BLU TRANS COLOR + +\ screen fillers +: RNDI ( -- n ) SIZE 1+ RND ; \ return a random VDP screen address + +: NOTRED ( -- n ) \ return rnd index that is not RED + BEGIN + RNDI DUP VC@ REDSQR = + WHILE DROP + REPEAT ; + +: NOTREDWHT ( -- n ) \ return rnd index that is not RED or WHITE + BEGIN RNDI DUP + VC@ DUP REDSQR = + SWAP WHTSQR = OR + WHILE + DROP + REPEAT ; + +: RNDRED ( -- ) \ Random RED on VDP screen + #256 0 DO REDSQR NOTRED VC! LOOP ; + +: RNDWHT ( -- ) \ place white where there is no red or white + #256 0 DO WHTSQR NOTREDWHT VC! LOOP ; + +: BLUSCREEN ( -- ) + 0 768 BLUSQR VFILL ; + +\ load the screen with random red,white&blue squares +: RNDSCREEN ( -- ) + BLUSCREEN RNDRED RNDWHT ; + +: CHECKERED ( -- ) \ red,wht,blue checker board + SIZE 0 + DO + BLUSQR I VC! + WHTSQR I 1+ VC! + REDSQR I 2+ VC! + 3 +LOOP ; + +: RUSSIAN \ Russian flag + 0 0 WHTSQR 256 HCHAR + 0 8 BLUSQR 256 HCHAR + 0 16 REDSQR 256 HCHAR ; + +: FRENCH \ kind of a French flag + 0 0 BLUSQR 256 VCHAR + 10 16 WHTSQR 256 VCHAR + 21 8 REDSQR 256 VCHAR ; + +\ ======================================================= +\ Algorithm Dijkstra(A) \ A is an array of three colors +\ begin +\ r <- 1; +\ b <- n; +\ w <- n; +\ while (w>=r) +\ check the color of A[w] +\ case 1: red +\ swap(A[r],A [w]); +\ r<-r+1; +\ case 2: white +\ w<-w-1 +\ case 3: blue +\ swap(A[w],A[b]); +\ w<-w-1; +\ b<-b-1; +\ end + +\ ====================================================== +\ Dijkstra three color Algorithm in Forth + +\ screen address pointers +VARIABLE R +VARIABLE B +VARIABLE W + +: XCHG ( vadr1 vadr2 -- ) \ Exchange chars in Video RAM + OVER VC@ OVER VC@ ( -- addr1 addr2 char1 char2) + SWAP ROT VC! SWAP VC! ; \ exchange chars in Video RAM + +: DIJKSTRA ( -- ) + 0 R ! + SIZE 1- DUP B ! W ! + BEGIN + W @ R @ 1- > + WHILE + W @ VC@ ( fetch Video char at pointer W) + CASE + REDSQR OF R @ W @ XCHG + 1 R +! ENDOF + + WHTSQR OF -1 W +! ENDOF + + BLUSQR OF W @ B @ XCHG + -1 W +! + -1 B +! ENDOF + ENDCASE + REPEAT ; + +: WAIT ( -- ) 11 11 AT-XY ." Finished!" 1500 MS ; + +: RUN ( -- ) + PAGE + CR ." Dijkstra Dutch flag Demo" CR + CR ." Sorted in-place in Video RAM" CR + CR + CR ." Using the 3 colour algorithm" CR + CR ." Press any key to begin" KEY DROP + RNDSCREEN DIJKSTRA WAIT + CHECKERED DIJKSTRA WAIT + RUSSIAN DIJKSTRA WAIT + FRENCH DIJKSTRA WAIT + 0 23 AT-XY + CR ." Completed" +; diff --git a/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring b/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring index 3adcf56985..2fcaae30b0 100644 --- a/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring +++ b/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring @@ -1,7 +1,4 @@ # Project : Dutch national flag problem -# Date : 2017/11/23 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : flag = ["Red","White","Blue"] balls = list(10) diff --git a/Task/Dynamic-variable-names/REBOL/dynamic-variable-names.rebol b/Task/Dynamic-variable-names/REBOL/dynamic-variable-names.rebol index bb16bf73dd..64b5bfaba8 100644 --- a/Task/Dynamic-variable-names/REBOL/dynamic-variable-names.rebol +++ b/Task/Dynamic-variable-names/REBOL/dynamic-variable-names.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Dynamic Variable Name" - Author: oofoe - Date: 2009-12-28 URL: http://rosettacode.org/wiki/Dynamic_variable_names ] diff --git a/Task/Empty-program/00DESCRIPTION b/Task/Empty-program/00DESCRIPTION index d14592b98c..4053b5e97e 100644 --- a/Task/Empty-program/00DESCRIPTION +++ b/Task/Empty-program/00DESCRIPTION @@ -1,5 +1,3 @@ ;Task: Create the simplest possible program that is still considered "correct."

- -=Programming Languages= diff --git a/Task/Empty-program/00META.yaml b/Task/Empty-program/00META.yaml index 3548159ac8..c5a231d1f7 100644 --- a/Task/Empty-program/00META.yaml +++ b/Task/Empty-program/00META.yaml @@ -1,4 +1,5 @@ --- category: +- Initialization - Simple note: Basic language learning diff --git a/Task/Empty-program/Beeswax/empty-program-1.beeswax b/Task/Empty-program/Beeswax/empty-program-1.beeswax new file mode 100644 index 0000000000..72e8ffc0db --- /dev/null +++ b/Task/Empty-program/Beeswax/empty-program-1.beeswax @@ -0,0 +1 @@ +* diff --git a/Task/Empty-program/Beeswax/empty-program-2.beeswax b/Task/Empty-program/Beeswax/empty-program-2.beeswax new file mode 100644 index 0000000000..57ddad2aec --- /dev/null +++ b/Task/Empty-program/Beeswax/empty-program-2.beeswax @@ -0,0 +1 @@ +\ diff --git a/Task/Empty-program/Beeswax/empty-program-3.beeswax b/Task/Empty-program/Beeswax/empty-program-3.beeswax new file mode 100644 index 0000000000..31354ec138 --- /dev/null +++ b/Task/Empty-program/Beeswax/empty-program-3.beeswax @@ -0,0 +1 @@ +_ diff --git a/Task/Empty-program/Beeswax/empty-program-4.beeswax b/Task/Empty-program/Beeswax/empty-program-4.beeswax new file mode 100644 index 0000000000..b498fd495d --- /dev/null +++ b/Task/Empty-program/Beeswax/empty-program-4.beeswax @@ -0,0 +1 @@ +/ diff --git a/Task/Empty-program/VAX-Assembly/empty-program.vax b/Task/Empty-program/VAX-Assembly/empty-program.vax new file mode 100644 index 0000000000..8ec3ade9ab --- /dev/null +++ b/Task/Empty-program/VAX-Assembly/empty-program.vax @@ -0,0 +1,3 @@ +0000 0000 1 .entry main,0 ;register save mask + 04 0002 2 ret ;return from main procedure + 0003 3 .end main ;start address for linker diff --git a/Task/Empty-string/VAX-Assembly/empty-string.vax b/Task/Empty-string/VAX-Assembly/empty-string.vax new file mode 100644 index 0000000000..6ccf20e25f --- /dev/null +++ b/Task/Empty-string/VAX-Assembly/empty-string.vax @@ -0,0 +1,10 @@ +desc: .ascid "not empty" ;descriptor (len+addr) and text +.entry empty, ^m<> + tstw desc ;check length field + beql is_empty + ;... not empty + clrw desc ;set length to zero -> empty +is_empty: + ;... empty + ret +.end empty diff --git a/Task/Enforced-immutability/Ring/enforced-immutability.ring b/Task/Enforced-immutability/Ring/enforced-immutability.ring index 85ef635ecb..5069df408b 100644 --- a/Task/Enforced-immutability/Ring/enforced-immutability.ring +++ b/Task/Enforced-immutability/Ring/enforced-immutability.ring @@ -1,7 +1,4 @@ # Project : Enforced immutability -# Date : 2017/11/29 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : x = 10 assert( x = 10) diff --git a/Task/Entropy/Swift/entropy.swift b/Task/Entropy/Swift/entropy.swift new file mode 100644 index 0000000000..2aa06068ad --- /dev/null +++ b/Task/Entropy/Swift/entropy.swift @@ -0,0 +1,14 @@ +import Foundation + +func entropy(of x: String) -> Double { + return x + .reduce(into: [String: Int](), {cur, char in + cur[String(char), default: 0] += 1 + }) + .values + .map({i in Double(i) / Double(x.count) } as (Int) -> Double) + .map({p in -p * log2(p) } as (Double) -> Double) + .reduce(0.0, +) +} + +print(entropy(of: "1223334444")) diff --git a/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba index 08bf04a586..47b37a8993 100644 --- a/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba +++ b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba @@ -4,4 +4,5 @@ Private Function Ethiopian_Multiplication(First As Long, Second As Long) As Long First = lngHalve(First) Second = lngDouble(Second) Loop While First >= 1 + Ethiopian_Multiplication = Mult_Eth End Function diff --git a/Task/Evaluate-binomial-coefficients/Nim/evaluate-binomial-coefficients.nim b/Task/Evaluate-binomial-coefficients/Nim/evaluate-binomial-coefficients.nim index 816bf281b5..a73a1defea 100644 --- a/Task/Evaluate-binomial-coefficients/Nim/evaluate-binomial-coefficients.nim +++ b/Task/Evaluate-binomial-coefficients/Nim/evaluate-binomial-coefficients.nim @@ -1,4 +1,4 @@ -proc binomialCoeff(n, k): int = +proc binomialCoeff(n, k: int): int = result = 1 for i in 1..k: result = result * (n-i+1) div i diff --git a/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp b/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp index b1370c37b9..d229145092 100644 --- a/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp +++ b/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp @@ -1,7 +1,4 @@ ;; Project : Even or odd -;; Date : 2018/03/05 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (defun evenodd (nr) (cond ((evenp nr) "even") diff --git a/Task/Even-or-odd/K/even-or-odd.k b/Task/Even-or-odd/K/even-or-odd.k new file mode 100644 index 0000000000..fbe0ac49ec --- /dev/null +++ b/Task/Even-or-odd/K/even-or-odd.k @@ -0,0 +1,8 @@ +oddp: {:[x!2;1;0]} /Returns 1 if arg. is odd +evenp: {~oddp[x]} /Returns 1 if arg. is even + +Examples: + oddp 32 +0 + evenp 32 +1 diff --git a/Task/Evolutionary-algorithm/FreeBASIC/evolutionary-algorithm.freebasic b/Task/Evolutionary-algorithm/FreeBASIC/evolutionary-algorithm.freebasic new file mode 100644 index 0000000000..7a647cca38 --- /dev/null +++ b/Task/Evolutionary-algorithm/FreeBASIC/evolutionary-algorithm.freebasic @@ -0,0 +1,84 @@ +' version 01-07-2018 +' compile with: fbc -s console + +Randomize Timer +Const As UInteger children = 100 +Const As Double mutate_rate = 0.05 + +Function fitness(target As String, tmp As String) As UInteger + + Dim As UInteger x, f + + For x = 0 To Len(tmp) -1 + If tmp[x] = target[x] Then f += 1 + Next + Return f + +End Function + +Sub mutate(tmp As String, chars As String, mute_rate As Double) + + If Rnd <= mute_rate Then + tmp[Int(Rnd * Len(tmp))] = chars[Int(Rnd * Len(chars))] + End If + +End Sub + +' ------=< MAIN >=------ + +Dim As String target = "METHINKS IT IS LIKE A WEASEL" +Dim As String chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" +Dim As String parent, mutation() +Dim As UInteger x, iter, f, fit(), best_fit, parent_fit + +For x = 1 To Len(target) + parent += Chr(chars[Int(Rnd * Len(chars))]) +Next + +f = fitness(target, parent) +parent_fit = f +best_fit = f + +Print "iteration best fit Parent" +Print "========= ======== ============================" +Print Using " #### #### ";iter; best_fit; +Print parent + +Do + iter += 1 + ReDim mutation(1 To children),fit(1 To children) + + For x = 1 To children + mutation(x) = parent + mutate(mutation(x), chars, mutate_rate) + Next + + For x = 1 To children + If mutation(x) <> parent Then + f = fitness(target, mutation(x)) + If best_fit < f Then + best_fit = f + fit(x) = f + Else + fit(x) = parent_fit + End If + End If + Next + + If best_fit > parent_fit Then + For x = 1 To children + If fit(x) = best_fit Then + parent = mutation(x) + Print Using " #### #### ";iter; best_fit; + Print parent + End If + Next + End If + +Loop Until parent = target + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring b/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring index 25a27cb715..40a225fdad 100644 --- a/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring +++ b/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring @@ -1,7 +1,4 @@ # Project : Evolutionary algorithm -# Date : 2018/03/28 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : target = "METHINKS IT IS LIKE A WEASEL" parent = "IU RFSGJABGOLYWF XSMFXNIABKT" diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION index 5c4e97501e..29cb1b69b5 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION @@ -1,7 +1,6 @@ {{omit from|GUISS}} {{omit from|M4}} {{omit from|Retro}} -{{omit from|Swift}} Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away. diff --git a/Task/Exceptions/00DESCRIPTION b/Task/Exceptions/00DESCRIPTION index 2c9e8e7569..c4818ad28e 100644 --- a/Task/Exceptions/00DESCRIPTION +++ b/Task/Exceptions/00DESCRIPTION @@ -2,7 +2,6 @@ {{omit from|Euphoria}} {{omit from|M4}} {{omit from|Retro}} -{{omit from|Swift|[Swift does not support exception handling]}} This task is to give an example of an exception handling routine and to "throw" a new exception. diff --git a/Task/Execute-HQ9+/Ring/execute-hq9+.ring b/Task/Execute-HQ9+/Ring/execute-hq9+.ring index a9a2c83f4d..f1f617f893 100644 --- a/Task/Execute-HQ9+/Ring/execute-hq9+.ring +++ b/Task/Execute-HQ9+/Ring/execute-hq9+.ring @@ -1,7 +1,4 @@ # Project : Execute HQ9 -# Date : 2017/09/12 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : bottle("hq9+HqQ+Qq") diff --git a/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l b/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l new file mode 100644 index 0000000000..1f525aca93 --- /dev/null +++ b/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l @@ -0,0 +1 @@ +(shell-command "ls") diff --git a/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l b/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l new file mode 100644 index 0000000000..66a2fb43a4 --- /dev/null +++ b/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l @@ -0,0 +1 @@ +(async-shell-command "ls") diff --git a/Task/Extend-your-language/Agda/extend-your-language.agda b/Task/Extend-your-language/Agda/extend-your-language.agda new file mode 100644 index 0000000000..c2ebba458a --- /dev/null +++ b/Task/Extend-your-language/Agda/extend-your-language.agda @@ -0,0 +1,16 @@ +data Bool : Set where + true : Bool + false : Bool + +if_then_else : βˆ€ {l} {A : Set l} -> Bool -> A -> A -> A +if true then t else e = t +if false then t else e = e + +if2_,_then_else1_else2_else_ : βˆ€ {l} {A : Set l} -> (b1 b2 : Bool) -> (t e1 e2 e : A) -> A +if2 true , true then t else1 e1 else2 e2 else e = t +if2 true , false then t else1 e1 else2 e2 else e = e1 +if2 false , true then t else1 e1 else2 e2 else e = e2 +if2 false , false then t else1 e1 else2 e2 else e = e + +example : Bool +example = if2 true , false then true else1 false else2 true else false diff --git a/Task/Extend-your-language/Perl/extend-your-language-1.pl b/Task/Extend-your-language/Perl/extend-your-language-1.pl index ec16a1ea76..90231a4bd6 100644 --- a/Task/Extend-your-language/Perl/extend-your-language-1.pl +++ b/Task/Extend-your-language/Perl/extend-your-language-1.pl @@ -100,12 +100,10 @@ sub if2($$@) { or grep {defined and ref $_ ne 'CODE'} @_; my $index; - given ([$cond1, $cond2]) { - when ([False, False]) {$index = IdxOrElse} - when ([False, True ]) {$index = IdxElse2 } - when ([True, False]) {$index = IdxElse1 } - when ([True, True ]) {$index = IdxThen } - } + if (!$cond1 && !$cond2) {$index = IdxOrElse} + if (!$cond1 && $cond2) {$index = IdxElse2 } + if ( $cond1 && !$cond2) {$index = IdxElse1 } + if ( $cond1 && $cond2) {$index = IdxThen } my $closure = $_[$index]; &$closure if defined $closure; diff --git a/Task/Extend-your-language/Ring/extend-your-language.ring b/Task/Extend-your-language/Ring/extend-your-language.ring index 035a5c410c..627f06d78b 100644 --- a/Task/Extend-your-language/Ring/extend-your-language.ring +++ b/Task/Extend-your-language/Ring/extend-your-language.ring @@ -1,7 +1,4 @@ # Project : Extend your language -# Date : 2017/11/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "a = 1, b = 1 => " test(1, 1) diff --git a/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal b/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal index cf747b748e..cab8643818 100644 --- a/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal +++ b/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal @@ -1,4 +1,4 @@ -program prime; +program emirp; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,REGVAR,PEEPHOLE,CSE,ASMCSE} @@ -319,7 +319,7 @@ var sievePr, PrimPos, srPrPos : NativeUint; - l: Uint64; + Begin Init; MaxPos := CalcPos(MaxUpperLimit); @@ -570,12 +570,11 @@ Begin end; end; -procedure GetEmirps(loLmt,HiLmt: Uint64); +function GetEmirps(loLmt,HiLmt: Uint64):NativeInt; var p1 :tRecPrime; - cnt: NativeUint; Begin - cnt := 0; + result := 0; IF HiLmt < loLmt then exit; IF loLmt > MaxUpperLimit then @@ -590,18 +589,16 @@ Begin repeat if isEmirp(p1.rpPrime) then - inc(cnt); + inc(result); iF not(NextPrime(p1)) then BREAK; until p1.rpPrime > HiLmt; - - write(cnt:10); end; var T1,T0: TDateTime; Anzahl :Uint64; - i,j : Uint64; + i,j,dgtCnt,totalCnt : Uint64; n : LongInt; Begin T0 := now; @@ -637,15 +634,22 @@ Begin writeln; writeln('Count Emirps'); + writeln(' Emirp Total'); + writeln('Decimals Count Count'); + totalCnt := 0; j := 10; + i := 2; + dgtCnt := 2; // 13 is not present so 13<->31 isnt found repeat - writeln(j:10); - GetEmirps( j, j+j-1);//10..00->19..99 - GetEmirps(3*j,3*j+j-1);//30..00->39..99 - GetEmirps(7*j,7*j+j-1);//70..00->79..99 - GetEmirps(9*j,9*j+j-1);//90..00->99..99 - writeln; + write(i:8); + inc(dgtCnt,GetEmirps( j, j+j-1));//10..00->19..99 + inc(dgtCnt,GetEmirps(3*j,3*j+j-1));//30..00->39..99 + inc(dgtCnt,GetEmirps(7*j,7*j+j-1));//70..00->79..99 + inc(dgtCnt,GetEmirps(9*j,9*j+j-1));//90..00->99..99 + inc(TotalCnt,dgtCnt); + writeln(dgtCnt:12,TotalCnt:14); j:=j*10; + inc(i); + dgtCnt := 0; until j >= MaxUpperLimit; - end. diff --git a/Task/Factorial/C/factorial-5.c b/Task/Factorial/C/factorial-5.c index e5bea4948c..06ccf9e620 100644 --- a/Task/Factorial/C/factorial-5.c +++ b/Task/Factorial/C/factorial-5.c @@ -2,8 +2,6 @@ int fac_aux(int n, int acc) { return n < 1 ? acc : fac_aux(n - 1, acc * n); } -/*Handles negative n, Abhishek Ghosh, 1st November 2017*/ - int fac_auxSafe(int n, int acc) { return n<0 ? -1 : n < 1 ? acc : fac_aux(n - 1, acc * n); } diff --git a/Task/Factorial/Common-Lisp/factorial-4.lisp b/Task/Factorial/Common-Lisp/factorial-4.lisp index aa6aa80cf3..d44f6ed168 100644 --- a/Task/Factorial/Common-Lisp/factorial-4.lisp +++ b/Task/Factorial/Common-Lisp/factorial-4.lisp @@ -1,7 +1,4 @@ ;; Project : Factorial -;; Date : 2018/03/09 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (defun factorial (n) (cond ((= n 1) 1) diff --git a/Task/Factorial/MIPS-Assembly/factorial.mips b/Task/Factorial/MIPS-Assembly/factorial-1.mips similarity index 100% rename from Task/Factorial/MIPS-Assembly/factorial.mips rename to Task/Factorial/MIPS-Assembly/factorial-1.mips diff --git a/Task/Factorial/MIPS-Assembly/factorial-2.mips b/Task/Factorial/MIPS-Assembly/factorial-2.mips new file mode 100644 index 0000000000..fb998c374a --- /dev/null +++ b/Task/Factorial/MIPS-Assembly/factorial-2.mips @@ -0,0 +1,42 @@ +#reference code +#int factorialRec(int n){ +# if(n<2){return 1;} +# else{ return n*factorial(n-1);} +#} +.data + n: .word 5 + result: .word +.text +main: + la $t0, n + lw $a0, 0($t0) + jal factorialRec + la $t0, result + sw $v0, 0($t0) + addi $v0, $0, 10 + syscall + +factorialRec: + addi $sp, $sp, -8 #calling convention + sw $a0, 0($sp) + sw $ra, 4($sp) + + addi $t0, $0, 2 #if (n < 2) do return 1 + slt $t0, $a0, $t0 #else return n*factorialRec(n-1) + beqz $t0, anotherCall + + lw $ra, 4($sp) #recursive anchor + lw $a0, 0($sp) + addi $sp, $sp, 8 + addi $v0, $0, 1 + jr $ra + +anotherCall: + addi $a0, $a0, -1 + jal factorialRec + + lw $ra, 4($sp) + lw $a0, 0($sp) + addi $sp, $sp, 8 + mul $v0, $a0, $v0 + jr $ra diff --git a/Task/Factorial/REBOL/factorial.rebol b/Task/Factorial/REBOL/factorial.rebol index 0dda819c93..b3ff15a290 100644 --- a/Task/Factorial/REBOL/factorial.rebol +++ b/Task/Factorial/REBOL/factorial.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Factorial" - Author: oofoe - Date: 2009-12-10 URL: http://rosettacode.org/wiki/Factorial_function ] diff --git a/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring b/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring index 1f2101edf8..2e2dce66c3 100644 --- a/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring +++ b/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring @@ -1,7 +1,4 @@ # Project : Factors of a Mersenne number -# Date : 2018/04/02 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : see "A factor of M929 is " + mersennefactor(929) + nl see "A factor of M937 is " + mersennefactor(937) + nl diff --git a/Task/Factors-of-an-integer/ARM-Assembly/factors-of-an-integer.arm b/Task/Factors-of-an-integer/ARM-Assembly/factors-of-an-integer.arm new file mode 100644 index 0000000000..121ad38f35 --- /dev/null +++ b/Task/Factors-of-an-integer/ARM-Assembly/factors-of-an-integer.arm @@ -0,0 +1,184 @@ +/* ARM assembly Raspberry PI */ +/* program factorst.s */ + +/* Constantes */ +.equ STDOUT, 1 @ Linux output console +.equ EXIT, 1 @ Linux syscall +.equ WRITE, 4 @ Linux syscall +/* Initialized data */ +.data +szMessDeb: .ascii "Factors of :" +sMessValeur: .fill 12, 1, ' ' + .asciz "are : \n" +sMessFactor: .fill 12, 1, ' ' + .asciz "\n" +szCarriageReturn: .asciz "\n" + +/* UnInitialized data */ +.bss + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* saves 2 registers */ + + mov r0,#100 + bl factors + mov r0,#97 + bl factors + ldr r0,iNumber + bl factors + + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call + +iNumber: .int 32767 +iAdrszCarriageReturn: .int szCarriageReturn +/******************************************************************/ +/* calcul factors of number */ +/******************************************************************/ +/* r0 contains the number */ +factors: + push {fp,lr} /* save registres */ + push {r1-r6} /* save others registers */ + mov r5,r0 @ limit calcul + ldr r1,iAdrsMessValeur @ conversion register in decimal string + bl conversion10S + ldr r0,iAdrszMessDeb @ display message + bl affichageMess + mov r6,#1 @ counter loop +1: @ loop + mov r0,r5 @ dividende + mov r1,r6 @ divisor + bl division + cmp r3,#0 @ remainder = zero ? + bne 2f + @ display result if yes + mov r0,r6 + ldr r1,iAdrsMessFactor + bl conversion10S + ldr r0,iAdrsMessFactor + bl affichageMess +2: + add r6,#1 @ add 1 to loop counter + cmp r6,r5 @ <= number ? + ble 1b @ yes loop +100: + pop {r1-r6} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ +iAdrsMessValeur: .int sMessValeur +iAdrszMessDeb: .int szMessDeb +iAdrsMessFactor: .int sMessFactor +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registers */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ +/*=============================================*/ +/* division integer unsigned */ +/*============================================*/ +division: + /* r0 contains N */ + /* r1 contains D */ + /* r2 contains Q */ + /* r3 contains R */ + push {r4, lr} + mov r2, #0 /* r2 ? 0 */ + mov r3, #0 /* r3 ? 0 */ + mov r4, #32 /* r4 ? 32 */ + b 2f +1: + movs r0, r0, LSL #1 /* r0 ? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) */ + adc r3, r3, r3 /* r3 ? r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C */ + + cmp r3, r1 /* compute r3 - r1 and update cpsr */ + subhs r3, r3, r1 /* if r3 >= r1 (C=1) then r3 ? r3 - r1 */ + adc r2, r2, r2 /* r2 ? r2 + r2 + C. This is equivalent to r2 ? (r2 << 1) + C */ +2: + subs r4, r4, #1 /* r4 ? r4 - 1 */ + bpl 1b /* if r4 >= 0 (N=0) then branch to .Lloop1 */ + + pop {r4, lr} + bx lr + +/***************************************************/ +/* conversion register in string dΓ©cimal signed */ +/***************************************************/ +/* r0 contains the register */ +/* r1 contains address of conversion area */ +conversion10S: + push {fp,lr} /* save registers frame and return */ + push {r0-r5} /* save other registers */ + mov r2,r1 /* early storage area */ + mov r5,#'+' /* default sign is + */ + cmp r0,#0 /* nΓ©gatif number ? */ + movlt r5,#'-' /* yes sign is - */ + mvnlt r0,r0 /* and inverse in positive value */ + addlt r0,#1 + mov r4,#10 /* area length */ +1: /* conversion loop */ + bl divisionpar10 /* division */ + add r1,#48 /* add 48 at remainder for conversion ascii */ + strb r1,[r2,r4] /* store byte area r5 + position r4 */ + sub r4,r4,#1 /* previous position */ + cmp r0,#0 + bne 1b /* loop if quotient not equal zΓ©ro */ + strb r5,[r2,r4] /* store sign at current position */ + subs r4,r4,#1 /* previous position */ + blt 100f /* if r4 < 0 end */ + /* else complete area with space */ + mov r3,#' ' /* character space */ +2: + strb r3,[r2,r4] /* store byte */ + subs r4,r4,#1 /* previous position */ + bge 2b /* loop if r4 greather or equal zero */ +100: /* standard end of function */ + pop {r0-r5} /*restaur others registers */ + pop {fp,lr} /* restaur des 2 registers frame et return */ + bx lr + +/***************************************************/ +/* division par 10 signΓ© */ +/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* +/* and http://www.hackersdelight.org/ */ +/***************************************************/ +/* r0 contient le dividende */ +/* r0 retourne le quotient */ +/* r1 retourne le reste */ +divisionpar10: + /* r0 contains the argument to be divided by 10 */ + push {r2-r4} /* save autres registres */ + mov r4,r0 + ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ + smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ + mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ + mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ + add r0, r2, r1 /* r0 <- r2 + r1 */ + add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ + sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ + pop {r2-r4} + bx lr /* leave function */ + .align 4 +.Ls_magic_number_10: .word 0x66666667 diff --git a/Task/Fast-Fourier-transform/Rust/fast-fourier-transform.rust b/Task/Fast-Fourier-transform/Rust/fast-fourier-transform.rust new file mode 100644 index 0000000000..a7d22c6fe6 --- /dev/null +++ b/Task/Fast-Fourier-transform/Rust/fast-fourier-transform.rust @@ -0,0 +1,61 @@ +extern crate num; +use num::complex::Complex; +use std::f64::consts::PI; + +const I: Complex = Complex { re: 0.0, im: 1.0 }; + +pub fn fft(input: &[Complex]) -> Vec> { + fn fft_inner( + buf_a: &mut [Complex], + buf_b: &mut [Complex], + n: usize, // total length of the input array + step: usize, // precalculated values for t + ) { + if step >= n { + return; + } + + fft_inner(buf_b, buf_a, n, step * 2); + fft_inner(&mut buf_b[step..], &mut buf_a[step..], n, step * 2); + // create a slice for each half of buf_a: + let (left, right) = buf_a.split_at_mut(n / 2); + + for i in (0..n).step_by(step * 2) { + let t = (-I * PI * (i as f64) / (n as f64)).exp() * buf_b[i + step]; + left[i / 2] = buf_b[i] + t; + right[i / 2] = buf_b[i] - t; + } + } + + // round n (length) up to a power of 2: + let n_orig = input.len(); + let n = n_orig.next_power_of_two(); + // copy the input into a buffer: + let mut buf_a = input.to_vec(); + // right pad with zeros to a power of two: + buf_a.append(&mut vec![Complex { re: 0.0, im: 0.0 }; n - n_orig]); + // alternate between buf_a and buf_b to avoid allocating a new vector each time: + let mut buf_b = buf_a.clone(); + fft_inner(&mut buf_a, &mut buf_b, n, 1); + buf_a +} + +fn show(label: &str, buf: &[Complex]) { + println!("{}", label); + let string = buf + .into_iter() + .map(|x| format!("{:.4}{:+.4}i", x.re, x.im)) + .collect::>() + .join(", "); + println!("{}", string); +} + +fn main() { + let input: Vec<_> = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0] + .into_iter() + .map(|x| Complex::from(x)) + .collect(); + show("input:", &input); + let output = fft(&input); + show("output:", &output); +} diff --git a/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v b/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v index 4f8bdf4ed8..d19f042b94 100644 --- a/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v +++ b/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v @@ -1,7 +1,3 @@ -/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com) -/// @Date: 2018-Jan-25 -/// - package math_pkg; // Inspired by the post // https://community.cadence.com/cadence_blogs_8/b/fv/posts/create-a-sine-wave-generator-using-systemverilog diff --git a/Task/Fibonacci-n-step-number-sequences/Befunge/fibonacci-n-step-number-sequences.bf b/Task/Fibonacci-n-step-number-sequences/Befunge/fibonacci-n-step-number-sequences.bf new file mode 100644 index 0000000000..a33bd81632 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Befunge/fibonacci-n-step-number-sequences.bf @@ -0,0 +1,8 @@ +110p>>55+109"iccanaceD"22099v +v9013"Tetranacci"9014"Lucas"< +>"iccanobirT"2109"iccanobiF"v +>>:#,_0p20p0>:01-\2>#v0>#g<>> + ^_@#:,+55$_^ JH v`1:v#\p03< + _$.1+:77+`^vg03:_0g+>\:1+#^ + 50p-\30v v\<>\30g1-\^$$_:1- + 05g04\g< >`#^_:40p30g0>^!:g diff --git a/Task/Fibonacci-n-step-number-sequences/C/fibonacci-n-step-number-sequences.c b/Task/Fibonacci-n-step-number-sequences/C/fibonacci-n-step-number-sequences.c index 99b9482504..76f87b0b47 100644 --- a/Task/Fibonacci-n-step-number-sequences/C/fibonacci-n-step-number-sequences.c +++ b/Task/Fibonacci-n-step-number-sequences/C/fibonacci-n-step-number-sequences.c @@ -1,6 +1,4 @@ -/*29th August, 2012 -Abhishek Ghosh - +/* The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/ #include diff --git a/Task/Fibonacci-n-step-number-sequences/Go/fibonacci-n-step-number-sequences.go b/Task/Fibonacci-n-step-number-sequences/Go/fibonacci-n-step-number-sequences.go index 55f6d56d46..e8612e25a5 100644 --- a/Task/Fibonacci-n-step-number-sequences/Go/fibonacci-n-step-number-sequences.go +++ b/Task/Fibonacci-n-step-number-sequences/Go/fibonacci-n-step-number-sequences.go @@ -2,37 +2,38 @@ package main import "fmt" -func g(i []int, c chan int) { - var sum int - b := append([]int{}, i...) - for _, t := range b { - c <- t - sum += t - } - for { - for j, t := range b { - c <- sum - b[j], sum = sum, sum+sum-t - } - } +func g(i []int, c chan<- int) { + var sum int + b := append([]int(nil), i...) // make a copy + for _, t := range b { + c <- t + sum += t + } + for { + for j, t := range b { + c <- sum + b[j], sum = sum, sum+sum-t + } + } } func main() { - for _, s := range []struct { - seq string - i []int - } { - {"Fibonacci", []int{1, 1}}, - {"Tribonacci", []int{1, 1, 2}}, - {"Tetranacci", []int{1, 1, 2, 4}}, - {"Lucas", []int{2, 1}}, - } { - fmt.Printf("%10s:", s.seq) - c := make(chan int) - go g(s.i, c) - for j := 0; j < 10; j++ { - fmt.Print(" ", <-c) - } - fmt.Println() - } + for _, s := range [...]struct { + seq string + i []int + }{ + {"Fibonacci", []int{1, 1}}, + {"Tribonacci", []int{1, 1, 2}}, + {"Tetranacci", []int{1, 1, 2, 4}}, + {"Lucas", []int{2, 1}}, + } { + fmt.Printf("%10s:", s.seq) + c := make(chan int) + // Note/warning: these goroutines are leaked. + go g(s.i, c) + for j := 0; j < 10; j++ { + fmt.Print(" ", <-c) + } + fmt.Println() + } } diff --git a/Task/Fibonacci-n-step-number-sequences/Ring/fibonacci-n-step-number-sequences.ring b/Task/Fibonacci-n-step-number-sequences/Ring/fibonacci-n-step-number-sequences.ring index db47564fe1..e1f05487b7 100644 --- a/Task/Fibonacci-n-step-number-sequences/Ring/fibonacci-n-step-number-sequences.ring +++ b/Task/Fibonacci-n-step-number-sequences/Ring/fibonacci-n-step-number-sequences.ring @@ -1,7 +1,4 @@ # Project : Fibonacci n-step number sequences -# Date : 2017/10/07 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : f = list(12) diff --git a/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-1.360 b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-1.360 new file mode 100644 index 0000000000..d8c7a1a7ba --- /dev/null +++ b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-1.360 @@ -0,0 +1,51 @@ +* Fibonacci sequence 05/11/2014 +* integer (31 bits) = 10 decimals -> max fibo(46) +FIBONACC CSECT + USING FIBONACC,R12 base register +SAVEAREA B STM-SAVEAREA(R15) skip savearea + DC 17F'0' savearea + DC CL8'FIBONACC' eyecatcher +STM STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R12,R15 set addressability +* ---- + LA R1,0 f(n-2)=0 + LA R2,1 f(n-1)=1 + LA R4,2 n=2 + LA R6,1 step + LH R7,NN limit +LOOP EQU * for n=2 to nn + LR R3,R2 f(n)=f(n-1) + AR R3,R1 f(n)=f(n-1)+f(n-2) + CVD R4,PW n convert binary to packed (PL8) + UNPK ZW,PW packed (PL8) to zoned (ZL16) + MVC CW,ZW zoned (ZL16) to char (CL16) + OI CW+L'CW-1,X'F0' zap sign + MVC WTOBUF+5(2),CW+14 output + CVD R3,PW f(n) binary to packed decimal (PL8) + MVC ZN,EM load mask + ED ZN,PW packed dec (PL8) to char (CL20) + MVC WTOBUF+9(14),ZN+6 output + WTO MF=(E,WTOMSG) write buffer + LR R1,R2 f(n-2)=f(n-1) + LR R2,R3 f(n-1)=f(n) + BXLE R4,R6,LOOP endfor n +* ---- + LM R14,R12,12(R13) restore previous savearea pointer + XR R15,R15 return code set to 0 + BR R14 return to caller +* ---- DATA +NN DC H'46' nn max n +PW DS PL8 15num +ZW DS ZL16 +CW DS CL16 +ZN DS CL20 +* ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num +EM DC XL20'402020206B2020206B2020206B2020206B202120' mask +WTOMSG DS 0F + DC H'80',XL2'0000' +* fibo(46)=1836311903 +WTOBUF DC CL80'fibo(12)=1234567890' + REGEQU + END FIBONACC diff --git a/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-2.360 b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-2.360 new file mode 100644 index 0000000000..5f59175243 --- /dev/null +++ b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence-2.360 @@ -0,0 +1,48 @@ +* Fibonacci sequence 31/07/2018 +* packed dec (PL8) = 15 decimals => max fibo(73) +FIBOWTOP CSECT + USING FIBOWTOP,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + SAVE (14,12) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability +* ---- + ZAP FNM2,=P'0' f(0)=0 + ZAP FNM1,=P'1' f(1)=1 + LA R4,2 n=2 + LA R6,1 step + LH R7,NN limit +LOOP EQU * for n=2 to nn + ZAP FN,FNM1 f(n)=f(n-2) + AP FN,FNM2 f(n)=f(n-1)+f(n-2) + CVD R4,PW n + MVC ZN,EM load mask + ED ZN,PW packed dec (PL8) to char (CL16) + MVC WTOBUF+5(2),ZN+L'ZN-2 output + MVC ZN,EM load mask + ED ZN,FN packed dec (PL8) to char (CL16) + MVC WTOBUF+9(L'ZN),ZN output + WTO MF=(E,WTOMSG) write buffer + ZAP FNM2,FNM1 f(n-2)=f(n-1) + ZAP FNM1,FN f(n-1)=f(n) + BXLE R4,R6,LOOP endfor n +* ---- + L R13,4(0,R13) restore previous savearea pointer + RETURN (14,12),RC=0 restore registers from calling sav +* ---- DATA +NN DC H'73' nn +FNM2 DS PL8 f(n-2) +FNM1 DS PL8 f(n-1) +FN DS PL8 f(n) +PW DS PL8 15num +ZN DS CL20 +* ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num +EM DC XL20'402020206B2020206B2020206B2020206B202120' mask +WTOMSG DS 0F + DC H'80',XL2'0000' +* fibo(73)=806515533049393 +WTOBUF DC CL80'fibo(12)=123456789012345 ' + REGEQU + END FIBOWTOP diff --git a/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 deleted file mode 100644 index 5b6b23f2fa..0000000000 --- a/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 +++ /dev/null @@ -1,49 +0,0 @@ -FIBONACC CSECT - USING FIBONACC,R12 -SAVEAREA B STM-SAVEAREA(R15) - DC 17F'0' - DC CL8'FIBONACC' -STM STM R14,R12,12(R13) - ST R13,4(R15) - ST R15,8(R13) - LR R12,R15 -* ---- CODE - LA R1,0 f1=0 - LA R2,1 f2=1 - LA R4,1 i=1 - LA R6,1 - LH R7,N -LOOP BXH R4,R6,ENDLOOP for i=2 to n - LR R3,R2 - AR R3,R1 f3=f1+f2 - CVD R4,P i - UNPK Z,P - MVC C,Z - OI C+L'C-1,X'F0' - MVC WTOBUF+5(5),C+11 - CVD R3,P f3 - UNPK Z,P - MVC C,Z - OI C+L'C-1,X'F0' - MVC WTOBUF+12(10),C+6 - WTO MF=(E,WTOMSG) - LR R1,R2 f1=f2 - LR R2,R3 f2=f3 - B LOOP next i -ENDLOOP EQU * -* ---- END CODE -RETURN EQU * - LM R14,R12,12(R13) - XR R15,R15 - BR R14 -* ---- DATA -N DC H'46' max i -P DS PL8 -Z DS ZL16 -C DS CL16 -WTOMSG DS 0F - DC H'80' - DC H'0' -WTOBUF DC CL80'fibo(12345)=1234567890 ' - YREGS - END FIBONACC diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp index e80aa75c73..fda013c3b9 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp @@ -1,7 +1,4 @@ ;; Project : Fibonacci sequence -;; Date : 2018/03/05 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : descriptor + 000C 6 + 7E 01 7D 000C 7 movq #1, -(sp) ;init 0,1 + 000F 8 loop: + 7E 6E 04 AE C1 000F 9 addl3 4(sp), (sp), -(sp) ;next element on stack + 17 1D 0014 10 bvs ret ;vs - overflow set, exit + 0016 11 + 5B DD 0016 12 pushl r11 ;-> descriptor by ref + 04 AE DF 0018 13 pushal 4(sp) ;-> fib on stack by ref + 00000000'GF 02 FB 001B 14 calls #2, g^ots$cvt_l_ti ;convert integer to string + 5B DD 0022 15 pushl r11 ; + 00000000'GF 01 FB 0024 16 calls #1, g^lib$put_output ;show result + E2 11 002B 17 brb loop + 002D 18 ret: + 04 002D 19 ret + 002E 20 .end main +$ run fib +... + 14930352 + 24157817 + 39088169 + 63245986 + 102334155 + 165580141 + 267914296 + 433494437 + 701408733 + 1134903170 + 1836311903 +$ diff --git a/Task/Fibonacci-sequence/Visual-Basic-.NET/fibonacci-sequence-3.visual b/Task/Fibonacci-sequence/Visual-Basic-.NET/fibonacci-sequence-3.visual new file mode 100644 index 0000000000..2a5127b81c --- /dev/null +++ b/Task/Fibonacci-sequence/Visual-Basic-.NET/fibonacci-sequence-3.visual @@ -0,0 +1,28 @@ + Function FiboBig(ByVal n As Integer) As BigInteger + ' Fibonacci sequence with BigInteger + Dim fibn2, fibn1, fibn As BigInteger + Dim i As Integer + fibn = 0 + fibn2 = 0 + fibn1 = 1 + If n = 0 Then + Return fibn2 + ElseIf n = 1 Then + Return fibn1 + ElseIf n >= 2 Then + For i = 2 To n + fibn = fibn2 + fibn1 + fibn2 = fibn1 + fibn1 = fibn + Next i + Return fibn + End If + Return 0 + End Function 'FiboBig + + Sub fibotest() + Dim i As Integer, s As String + i = 2000000 ' 2 millions + s = FiboBig(i).ToString + Console.WriteLine("fibo(" & i & ")=" & s & " - length=" & Len(s)) + End Sub 'fibotest diff --git a/Task/Fibonacci-word/Ring/fibonacci-word.ring b/Task/Fibonacci-word/Ring/fibonacci-word.ring index e987bf9ebb..c95d7f15e8 100644 --- a/Task/Fibonacci-word/Ring/fibonacci-word.ring +++ b/Task/Fibonacci-word/Ring/fibonacci-word.ring @@ -1,7 +1,4 @@ # Project : Fibonacci word -# Date : 2018/01/23 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : fw1 = "1" fw2 = "0" 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 index 4f2fb20500..b1bac1b189 100644 --- a/Task/Find-common-directory-path/Ring/find-common-directory-path.ring +++ b/Task/Find-common-directory-path/Ring/find-common-directory-path.ring @@ -1,6 +1,4 @@ # Project : Find common directory path -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" i = null diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Java/find-largest-left-truncatable-prime-in-a-given-base.java b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Java/find-largest-left-truncatable-prime-in-a-given-base.java index ba4a2ecd52..3f3e0cf133 100644 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Java/find-largest-left-truncatable-prime-in-a-given-base.java +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Java/find-largest-left-truncatable-prime-in-a-given-base.java @@ -35,8 +35,25 @@ class LeftTruncatablePrime public static void main(String[] args) { - int maxRadix = Integer.parseInt(args[0]); - int millerRabinCertainty = Integer.parseInt(args[1]); + if (args.length != 2) { + System.err.println("There must be exactly two command line arguments."); + return; + } + int maxRadix; + try { + maxRadix = Integer.parseInt(args[0]); + if (maxRadix < 3) throw new NumberFormatException(); + } catch (NumberFormatException e) { + System.err.println("Radix must be an integer greater than 2."); + return; + } + int millerRabinCertainty; + try { + millerRabinCertainty = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + System.err.println("Miiller-Rabin Certainty must be an integer."); + return; + } for (int radix = 3; radix <= maxRadix; radix++) { BigInteger largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty); diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Scala/find-largest-left-truncatable-prime-in-a-given-base.scala b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Scala/find-largest-left-truncatable-prime-in-a-given-base.scala new file mode 100644 index 0000000000..107933610d --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Scala/find-largest-left-truncatable-prime-in-a-given-base.scala @@ -0,0 +1,48 @@ +import scala.collection.parallel.immutable.ParSeq + +object LeftTruncatablePrime extends App { + private def leftTruncatablePrime(maxRadix: Int, millerRabinCertainty: Int) { + def getLargestLeftTruncatablePrime(radix: Int, millerRabinCertainty: Int): BigInt = { + def getNextLeftTruncatablePrimes(n: BigInt, radix: Int, millerRabinCertainty: Int) = { + def baseString = if (n == 0) "" else n.toString(radix) + + for {i <- (1 until radix).par + p = BigInt(Integer.toString(i, radix) + baseString, radix) + if p.isProbablePrime(millerRabinCertainty) + } yield p + } + + def iter(list: ParSeq[BigInt], lastList: ParSeq[BigInt]): ParSeq[BigInt] = { + if (list.isEmpty) lastList + else + iter((for (n <- list.par) yield getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty)).flatten, list) + } + + iter(getNextLeftTruncatablePrimes(0, radix, millerRabinCertainty), ParSeq.empty).max + } + + for (radix <- (3 to maxRadix).par) { + val largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty) + println(f"n=$radix%3d: " + + (if (largest == null) "No left-truncatable prime" + else f"$largest%35d (in base $radix%3d) ${largest.toString(radix)}")) + + } + } + + val argu: Array[String] = if (args.length >=2 ) args.slice(0, 2) else Array("17", "100") + val maxRadix = argu(0).toInt.ensuring(_ > 2, "Radix must be an integer greater than 2.") + + try { + val millerRabinCertainty = argu(1).toInt + + println(s"Run with maxRadix = $maxRadix and millerRabinCertainty = $millerRabinCertainty") + + leftTruncatablePrime(maxRadix, millerRabinCertainty) + println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") + } + catch { + case _: NumberFormatException => Console.err.println("Miller-Rabin Certainty must be an integer.") + } + +} diff --git a/Task/Find-limit-of-recursion/Befunge/find-limit-of-recursion.bf b/Task/Find-limit-of-recursion/Befunge/find-limit-of-recursion.bf new file mode 100644 index 0000000000..a8756ddd82 --- /dev/null +++ b/Task/Find-limit-of-recursion/Befunge/find-limit-of-recursion.bf @@ -0,0 +1 @@ +1>1#:+#.:_@ diff --git a/Task/First-class-environments/Go/first-class-environments.go b/Task/First-class-environments/Go/first-class-environments.go new file mode 100644 index 0000000000..9e27c233ac --- /dev/null +++ b/Task/First-class-environments/Go/first-class-environments.go @@ -0,0 +1,59 @@ +package main + +import "fmt" + +const jobs = 12 + +type environment struct{ seq, cnt int } + +var ( + env [jobs]environment + seq, cnt *int +) + +func hail() { + fmt.Printf("% 4d", *seq) + if *seq == 1 { + return + } + (*cnt)++ + if *seq&1 != 0 { + *seq = 3*(*seq) + 1 + } else { + *seq /= 2 + } +} + +func switchTo(id int) { + seq = &env[id].seq + cnt = &env[id].cnt +} + +func main() { + for i := 0; i < jobs; i++ { + switchTo(i) + env[i].seq = i + 1 + } + +again: + for i := 0; i < jobs; i++ { + switchTo(i) + hail() + } + fmt.Println() + + for j := 0; j < jobs; j++ { + switchTo(j) + if *seq != 1 { + goto again + } + } + fmt.Println() + + fmt.Println("COUNTS:") + for i := 0; i < jobs; i++ { + switchTo(i) + fmt.Printf("% 4d", *cnt) + } + fmt.Println() +} diff --git a/Task/First-class-functions/REBOL/first-class-functions.rebol b/Task/First-class-functions/REBOL/first-class-functions.rebol index 8e9882d827..41c1695b2b 100644 --- a/Task/First-class-functions/REBOL/first-class-functions.rebol +++ b/Task/First-class-functions/REBOL/first-class-functions.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "First Class Functions" - Author: oofoe - Date: 2009-12-05 URL: http://rosettacode.org/wiki/First-class_functions ] diff --git a/Task/Five-weekends/Ruby/five-weekends.rb b/Task/Five-weekends/Ruby/five-weekends.rb index 403ea78c65..4cbc5f429d 100644 --- a/Task/Five-weekends/Ruby/five-weekends.rb +++ b/Task/Five-weekends/Ruby/five-weekends.rb @@ -2,22 +2,14 @@ require 'date' # The only case where the month has 5 weekends is when the last day # of the month falls on a Sunday and the month has 31 days. -dates = [] -1900.upto(2100) do |year| - 1.upto(12) do |month| - d = Date.new(year, month, -1) # -1 is last day of month - dates << d if d.sunday? && d.day == 31 - end -end +LONG_MONTHS = [1,3,5,7,8,10,12] +YEARS = (1900..2100).to_a + +dates = YEARS.product(LONG_MONTHS).map{|y, m| Date.new(y,m,31)}.select(&:sunday?) +years_4w = YEARS - dates.map(&:year) puts "There are #{dates.size} months with 5 weekends from 1900 to 2100:" -puts dates.first(5).map { |d| d.strftime("%b %Y") } -puts "..." -puts dates.last(5).map { |d| d.strftime("%b %Y") } - -years_with_5w = dates.map(&:year) - -years = (1900..2100).to_a - years_with_5w - -puts "There are #{years.size} years without months with 5 weekends:" -puts years.join(", ") +puts dates.first(5).map {|d| d.strftime("%b %Y") }, "..." +puts dates.last(5).map {|d| d.strftime("%b %Y") } +puts "There are #{years_4w.size} years without months with 5 weekends:" +puts years_4w.join(", ") diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp index 1679fec4f9..2afcb58497 100644 --- a/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp @@ -1,7 +1,4 @@ ;; Project : FizzBuzz -;; Date : 2018/03/07 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (defun fizzbuzz (&optional n) (let ((n (or n 1))) diff --git a/Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l b/Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l new file mode 100644 index 0000000000..e7be97d51c --- /dev/null +++ b/Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l @@ -0,0 +1,10 @@ +(defun fizzbuzz (n) + (cond ((and + (eq (% n 5) 0) + (eq (% n 3) 0)) "FizzBuzz") + ((eq (% n 3) 0) "Fizz") + ((eq (% n 5) 0) "Buzz") + (t n))) + +;; loop & print from 0 to 100 +(dotimes (i 101) (princ-list (fizzbuzz i))) diff --git a/Task/FizzBuzz/Factor/fizzbuzz.factor b/Task/FizzBuzz/Factor/fizzbuzz-1.factor similarity index 100% rename from Task/FizzBuzz/Factor/fizzbuzz.factor rename to Task/FizzBuzz/Factor/fizzbuzz-1.factor diff --git a/Task/FizzBuzz/Factor/fizzbuzz-2.factor b/Task/FizzBuzz/Factor/fizzbuzz-2.factor new file mode 100644 index 0000000000..282d8fc2cf --- /dev/null +++ b/Task/FizzBuzz/Factor/fizzbuzz-2.factor @@ -0,0 +1,18 @@ +USING: kernel sequences arrays generalizations fry math math.parser prettyprint ; +IN: fizzbuzz + +: zz ( m seq -- v ) dup length 1 V{ } clone 4 -nrot 1 4 -nrot 3 nrot + '[ dup _ <= ] + 3 -nrot + '[ + "" _ [ _ [ swap execute( str n -- str n ) ] change-nth ] each-index + dup empty? [ drop dup number>string ] [ ] if swapd suffix! swap 1 + + ] + while drop ; + +: fizz ( str n -- str n ) dup 3 < [ 1 + ] [ drop "Fizz" append 1 ] if ; +: buzz ( str n -- str n ) dup 5 < [ 1 + ] [ drop "Buzz" append 1 ] if ; +: FizzBuzz ( m -- v ) { fizz buzz } zz ; +: FizzBuzz-100 ( -- ) 100 FizzBuzz . ; + +MAIN: FizzBuzz-100 diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-1.hs b/Task/FizzBuzz/Haskell/fizzbuzz-1.hs index 6930938df1..fc9619bdb0 100644 --- a/Task/FizzBuzz/Haskell/fizzbuzz-1.hs +++ b/Task/FizzBuzz/Haskell/fizzbuzz-1.hs @@ -1,7 +1,11 @@ -main = mapM_ (putStrLn . fizzbuzz) [1..100] - +fizzbuzz :: Int -> String fizzbuzz x - | x `mod` 15 == 0 = "FizzBuzz" - | x `mod` 3 == 0 = "Fizz" - | x `mod` 5 == 0 = "Buzz" - | otherwise = show x + | f 15 = "FizzBuzz" + | f 3 = "Fizz" + | f 5 = "Buzz" + | otherwise = show x + where + f = (0 ==) . rem x + +main :: IO () +main = mapM_ (putStrLn . fizzbuzz) [1 .. 100] diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-2.hs b/Task/FizzBuzz/Haskell/fizzbuzz-2.hs index 39de0e8416..4274c5fb0f 100644 --- a/Task/FizzBuzz/Haskell/fizzbuzz-2.hs +++ b/Task/FizzBuzz/Haskell/fizzbuzz-2.hs @@ -1,6 +1,18 @@ -main = putStr $ concat $ map fizzbuzz [1..100] - +fizzbuzz :: Int -> String fizzbuzz n = - "\n" ++ if null (fizz++buzz) then show n else fizz++buzz - where fizz = if mod n 3 == 0 then "Fizz" else "" - buzz = if mod n 5 == 0 then "Buzz" else "" + '\n' : + if null (fizz ++ buzz) + then show n + else fizz ++ buzz + where + fizz = + if mod n 3 == 0 + then "Fizz" + else "" + buzz = + if mod n 5 == 0 + then "Buzz" + else "" + +main :: IO () +main = putStr $ concatMap fizzbuzz [1 .. 100] diff --git a/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol b/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol index 1f70b346de..8d859d274d 100644 --- a/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol +++ b/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "FizzBuzz" - Author: oofoe - Date: 2009-12-10 URL: http://rosettacode.org/wiki/FizzBuzz ] diff --git a/Task/FizzBuzz/VAX-Assembly/fizzbuzz.vax b/Task/FizzBuzz/VAX-Assembly/fizzbuzz.vax new file mode 100644 index 0000000000..8915e70b60 --- /dev/null +++ b/Task/FizzBuzz/VAX-Assembly/fizzbuzz.vax @@ -0,0 +1,43 @@ + 00000008 0000 1 len =8 + 00000008 0000 2 msg: .blkb len ;output buffer + 0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field + 00000000' 000C 4 .address msg ;pointer to buffer + 00000012 0010 5 outlen: .blkw 1 + 4C 55 21 0000001A'010E0000' 0012 6 ctr: .ascid "!UL" + 001D 7 + 0000 001D 8 .entry start,0 + 52 7C 001F 9 clrq r2 ;r2+r3 64bit + 52 D6 0021 10 incl r2 ;start index 1 + 0023 11 loop: + E2 AF B4 0023 12 clrw desc ;assume not fizz and or buzz + 55 D7 AF 9E 0026 13 movab msg, r5 ;pointer to message buffer + 54 50 52 03 7B 002A 14 ediv #3,r2,r0,r4 ;divr.rl,divd.rq,quo.wl,rem.wl + 54 D5 002F 15 tstl r4 ;remainder + 0B 12 0031 16 bneq not_fizz ;not equal zero + 0033 17 + 85 7A7A6966 8F D0 0033 18 movl #^a"fizz", (r5)+ ;add to message + CA AF 04 A0 003A 19 addw2 #4, desc ;and update length + 003E 20 not_fizz: + 54 50 52 05 7B 003E 21 ediv #5,r2,r0,r4 + 54 D5 0043 22 tstl r4 + 0B 12 0045 23 bneq not_buzz + 0047 24 + 85 7A7A7562 8F D0 0047 25 movl #^a"buzz", (r5)+ + B6 AF 04 A0 004E 26 addw2 #4, desc + 0052 27 not_buzz: + B3 AF B5 0052 28 tstw desc ;fizz and or buzz? + 1B 12 0055 29 bneq show_buffer ;neq - yes + 0057 30 + AD AF 08 B0 0057 31 movw #len, desc ;fao length limit + 005B 32 $fao_s - ;eql -no + 005B 33 ctrstr = ctr, - ;show number + 005B 34 outlen = outlen, - + 005B 35 outbuf = desc, - + 005B 36 p1 = r2 + 96 AF A0 AF B0 006D 37 movw outlen, desc ;characters filled by fao + 0072 38 show_buffer: + 93 AF 7F 0072 39 pushaq desc + 00000000'GF 01 FB 0075 40 calls #1, g^lib$put_output + 9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml + 04 0084 42 ret + 0085 43 .end start diff --git a/Task/Flatten-a-list/Crystal/flatten-a-list-1.crystal b/Task/Flatten-a-list/Crystal/flatten-a-list-1.crystal new file mode 100644 index 0000000000..52bc493e66 --- /dev/null +++ b/Task/Flatten-a-list/Crystal/flatten-a-list-1.crystal @@ -0,0 +1 @@ +[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten() diff --git a/Task/Flatten-a-list/Crystal/flatten-a-list-2.crystal b/Task/Flatten-a-list/Crystal/flatten-a-list-2.crystal new file mode 100644 index 0000000000..7ab4e1500a --- /dev/null +++ b/Task/Flatten-a-list/Crystal/flatten-a-list-2.crystal @@ -0,0 +1 @@ +[1, 2, 3, 4, 5, 6, 7, 8] diff --git a/Task/Flipping-bits-game/Ring/flipping-bits-game.ring b/Task/Flipping-bits-game/Ring/flipping-bits-game.ring new file mode 100644 index 0000000000..d51d854393 --- /dev/null +++ b/Task/Flipping-bits-game/Ring/flipping-bits-game.ring @@ -0,0 +1,109 @@ +load "guilib.ring" +load "stdlib.ring" + +size = 3 +flip = newlist(size,size) +board = newlist(size,size) +colflip = list(size) +rowflip = list(size) + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Flipping bits game") + setgeometry(465,115,800,600) + label1 = new qlabel(win1) { + setgeometry(285,60,120,40) + settext("Target") + } + label2 = new qlabel(win1) { + setgeometry(285,220,120,40) + settext("Board") + } + for n = 1 to size + for m = 1 to size + flip[n][m] = new qpushbutton(win1) { + setgeometry(200+n*40,60+m*40,40,40) + settext(string(random(1))) + } + next + next + for n = 1 to size + for m = 1 to size + board[n][m] = new qpushbutton(win1) { + setgeometry(200+n*40,260+m*40,40,40) + setclickevent("draw(" + n + "," + m +")") + } + next + next + for n = 1 to size + colflip[n]= new qpushbutton(win1) { + setgeometry(200+n*40,260,40,40) + settext("Go") + setclickevent("coldraw(" + n + ")") + } + next + for n = 1 to size + rowflip[n]= new qpushbutton(win1) { + setgeometry(200,260+n*40,40,40) + settext("Go") + setclickevent("rowdraw(" + n + ")") + } + next + scramblebutton = new qpushbutton(win1) { + setgeometry(240,460,120,40) + settext("Scramble Board") + setclickevent("scramble(flip)") + } + scramblebegin(flip) + show() + } + exec() + } + +func coldraw(n) + for row = 1 to size + board[n][row] {temp = text()} + if temp = "0" + board[n][row].settext("1") + else + board[n][row].settext("0") + ok + next + +func rowdraw(n) + for col = 1 to size + board[col][n] {temp = text()} + if temp = "0" + board[col][n].settext("1") + else + board[col][n].settext("0") + ok + next + +func scramble(flip) + for col = 1 to size + for row = 1 to size + flip[col][row]{temp = text()} + board[col][row].settext(temp) + next + next + for mix = 1 to size*10 + colorrow = random(1) + 1 + colrow = random(size-1) + 1 + if colorrow = 1 + rc = "coldraw" + else + rc = "rowdraw" + ok + go = rc + "(" + colrow + ")" + eval(go) + next + +func scramblebegin(flip) + for col = 1 to size + for row = 1 to size + flip[col][row]{temp = text()} + board[col][row].settext(temp) + next + next diff --git a/Task/Flow-control-structures/REBOL/flow-control-structures.rebol b/Task/Flow-control-structures/REBOL/flow-control-structures.rebol index 0e69f29f6d..27a2bbcf83 100644 --- a/Task/Flow-control-structures/REBOL/flow-control-structures.rebol +++ b/Task/Flow-control-structures/REBOL/flow-control-structures.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Flow Control" - Author: oofoe - Date: 2009-12-05 URL: http://rosettacode.org/wiki/Flow_Control_Structures ] diff --git a/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs b/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs index 402668abe2..2f37f264e3 100644 --- a/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs +++ b/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs @@ -4,11 +4,13 @@ floyd :: Int -> [[Int]] floyd n = snd $ mapAccumL - (\start row -> (start + succ row, [start .. start + row])) + (\a x -> + let m = a + x + in (succ m, [a .. m])) 1 [0 .. pred n] --- TEST ----------------------------------------------------------------------- +-- TEST ------------------------------------- showFloyd :: [[Int]] -> String showFloyd xs = let padRight n = length >>= (<$> mappend (replicate n ' ')) . drop diff --git a/Task/Floyds-triangle/Nim/floyds-triangle.nim b/Task/Floyds-triangle/Nim/floyds-triangle.nim index 62df764557..f2187b8878 100644 --- a/Task/Floyds-triangle/Nim/floyds-triangle.nim +++ b/Task/Floyds-triangle/Nim/floyds-triangle.nim @@ -9,7 +9,7 @@ proc floyd(rowcount = 5): seq[seq[int]] = row.add i result.add row -proc pfloyd(rows) = +proc pfloyd(rows: seq[seq[int]]) = var colspace = newSeq[int]() for n in rows[rows.high]: colspace.add(($n).len) for row in rows: diff --git a/Task/Forest-fire/Ring/forest-fire.ring b/Task/Forest-fire/Ring/forest-fire.ring index bf5dd971a1..338adcaf14 100644 --- a/Task/Forest-fire/Ring/forest-fire.ring +++ b/Task/Forest-fire/Ring/forest-fire.ring @@ -1,8 +1,4 @@ # Project : Forest fire -# Date : 2018/01/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : - load "guilib.ring" load "stdlib.ring" diff --git a/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol b/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol index f4897a87eb..141b175e64 100644 --- a/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol +++ b/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Formatted Numeric Output" - Author: oofoe - Date: 2009-12-22 URL: http://rosettacode.org/wiki/Formatted_Numeric_Output ] diff --git a/Task/Formatted-numeric-output/VBA/formatted-numeric-output.vba b/Task/Formatted-numeric-output/VBA/formatted-numeric-output.vba new file mode 100644 index 0000000000..7e37aca6cf --- /dev/null +++ b/Task/Formatted-numeric-output/VBA/formatted-numeric-output.vba @@ -0,0 +1,24 @@ +Option Explicit + +Sub Main() +Debug.Print fFormat(13, 2, 1230.3333) +Debug.Print fFormat(2, 13, 1230.3333) +Debug.Print fFormat(10, 5, 0.3333) +Debug.Print fFormat(13, 2, 1230) +End Sub + +Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String +'NbInt : Lenght of integral part +'NbDec : Lenght of decimal part +'Nb : decimal on integer number +Dim u As String, v As String, i As Integer + u = CStr(Nb) + i = InStr(u, Application.DecimalSeparator) + If i > 0 Then + v = Mid(u, i + 1) + u = Left(u, i - 1) + fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & Left(v & String(NbDec, "0"), NbDec) + Else + fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & String(NbDec, "0") + End If +End Function diff --git a/Task/Forward-difference/Perl/forward-difference.pl b/Task/Forward-difference/Perl/forward-difference.pl index 48447b68f0..695a789050 100644 --- a/Task/Forward-difference/Perl/forward-difference.pl +++ b/Task/Forward-difference/Perl/forward-difference.pl @@ -3,8 +3,5 @@ sub dif { map { $s[$_+1] - $s[$_] } 0 .. $#s-1 } -sub difn { - my ($n, @s) = @_; - @s = dif @s foreach 1..$n; - @s -} +@a = qw<90 47 58 29 22 32 55 5 55 73>; +while (@a) { printf('%6d', $_) for @a = dif @a; print "\n" } diff --git a/Task/Forward-difference/Ring/forward-difference.ring b/Task/Forward-difference/Ring/forward-difference.ring index eebb363e9b..26b4ffbf9f 100644 --- a/Task/Forward-difference/Ring/forward-difference.ring +++ b/Task/Forward-difference/Ring/forward-difference.ring @@ -1,7 +1,4 @@ # Project : Forward difference -# Date : 2018/01/19 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] for p = 1 to 9 diff --git a/Task/Fractal-tree/Ceylon/fractal-tree.ceylon b/Task/Fractal-tree/Ceylon/fractal-tree.ceylon new file mode 100644 index 0000000000..c126854b3d --- /dev/null +++ b/Task/Fractal-tree/Ceylon/fractal-tree.ceylon @@ -0,0 +1,45 @@ +import javax.swing { + + JFrame { exitOnClose } +} +import java.awt { + + Color { white, black }, + Graphics +} +import ceylon.numeric.float { + + cos, + toRadians, + sin +} + +shared void run() { + + value fractalTree = object extends JFrame("fractal tree") { + + background = black; + setBounds(100, 100, 800, 600); + resizable = false; + defaultCloseOperation = exitOnClose; + + shared actual void paint(Graphics g) { + + void drawTree(Integer x1, Integer y1, Float angle, Integer depth) { + if (depth <= 0) { + return; + } + value x2 = x1 + (cos(toRadians(angle)) * depth * 10.0).integer; + value y2 = y1 + (sin(toRadians(angle)) * depth * 10.0).integer; + g.drawLine(x1, y1, x2, y2); + drawTree(x2, y2, angle - 20, depth - 1); + drawTree(x2, y2, angle + 20, depth - 1); + } + + g.color = white; + drawTree(400, 500, -90.0, 9); + } + }; + + fractalTree.visible = true; +} diff --git a/Task/Fractran/Befunge/fractran.bf b/Task/Fractran/Befunge/fractran.bf new file mode 100644 index 0000000000..ccdec8d2c1 --- /dev/null +++ b/Task/Fractran/Befunge/fractran.bf @@ -0,0 +1,5 @@ +p0" :snoitcarF">:#,_>&00g5p~$&00g:v +v"Starting value: "_^#-*84~p6p00+1< +>:#,_&0" :snoitaretI">:#,_#@>>$&\:v +:$_\:10g5g*:10g6g%v1:\1$\$<|!:-1\.< +g0^\010p00 diff --git a/Task/Function-composition/REBOL/function-composition-1.rebol b/Task/Function-composition/REBOL/function-composition-1.rebol index 38a1f59e40..8f31baeb19 100644 --- a/Task/Function-composition/REBOL/function-composition-1.rebol +++ b/Task/Function-composition/REBOL/function-composition-1.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Functional Composition" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Functional_Composition ] diff --git a/Task/Function-composition/Ring/function-composition.ring b/Task/Function-composition/Ring/function-composition.ring new file mode 100644 index 0000000000..3c91fd4c0e --- /dev/null +++ b/Task/Function-composition/Ring/function-composition.ring @@ -0,0 +1,13 @@ +# Project : Function composition + +sumprod = func1(:func2,2,3) +see sumprod + nl + +func func1(func2,x,y) + temp = call func2(x,y) + res = temp + x + y + return res + +func func2(x,y) + res = x * y + return res diff --git a/Task/Function-definition/ARM-Assembly/function-definition.arm b/Task/Function-definition/ARM-Assembly/function-definition.arm new file mode 100644 index 0000000000..0d0938ec8d --- /dev/null +++ b/Task/Function-definition/ARM-Assembly/function-definition.arm @@ -0,0 +1,134 @@ +/* ARM assembly Raspberry PI */ +/* program functMul.s */ +/* Constantes */ +.equ STDOUT, 1 +.equ WRITE, 4 +.equ EXIT, 1 + +/***********************/ +/* Initialized data */ +/***********************/ +.data +szRetourLigne: .asciz "\n" +szMessResult: .ascii "Resultat : " @ message result +sMessValeur: .fill 12, 1, ' ' + .asciz "\n" +/*********************** +/* No Initialized data */ +/***********************/ +.bss + +.text +.global main +main: + push {fp,lr} /* save 2 registers */ + + @ function multiply + mov r0,#8 + mov r1,#50 + bl multiply @ call function + ldr r1,iAdrsMessValeur + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,iAdrszMessResult + bl affichageMess @ display message + + mov r0, #0 @ return code + +100: /* end of program */ + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrsMessValeur: .int sMessValeur +iAdrszMessResult: .int szMessResult +/******************************************************************/ +/* Function multiply */ +/******************************************************************/ +/* r0 contains value 1 */ +/* r1 contains value 2 */ +/* r0 return rΓ©sult */ +multiply: + mul r0,r1,r0 + bx lr /* return function */ + +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registers */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ + + +/***************************************************/ +/* conversion register in string dΓ©cimal signed */ +/***************************************************/ +/* r0 contains the register */ +/* r1 contains address of conversion area */ +conversion10S: + push {fp,lr} /* save registers frame and return */ + push {r0-r5} /* save other registers */ + mov r2,r1 /* early storage area */ + mov r5,#'+' /* default sign is + */ + cmp r0,#0 /* nΓ©gatif number ? */ + movlt r5,#'-' /* yes sign is - */ + mvnlt r0,r0 /* and inverse in positive value */ + addlt r0,#1 + mov r4,#10 /* area length */ +1: /* conversion loop */ + bl divisionpar10 /* division */ + add r1,#48 /* add 48 at remainder for conversion ascii */ + strb r1,[r2,r4] /* store byte area r5 + position r4 */ + sub r4,r4,#1 /* previous position */ + cmp r0,#0 + bne 1b /* loop if quotient not equal zΓ©ro */ + strb r5,[r2,r4] /* store sign at current position */ + subs r4,r4,#1 /* previous position */ + blt 100f /* if r4 < 0 end */ + /* else complete area with space */ + mov r3,#' ' /* character space */ +2: + strb r3,[r2,r4] /* store byte */ + subs r4,r4,#1 /* previous position */ + bge 2b /* loop if r4 greather or equal zero */ +100: /* standard end of function */ + pop {r0-r5} /*restaur others registers */ + pop {fp,lr} /* restaur des 2 registers frame et return */ + bx lr + + +/***************************************************/ +/* division par 10 signΓ© */ +/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* +/* and http://www.hackersdelight.org/ */ +/***************************************************/ +/* r0 contient le dividende */ +/* r0 retourne le quotient */ +/* r1 retourne le reste */ +divisionpar10: + /* r0 contains the argument to be divided by 10 */ + push {r2-r4} /* save autres registres */ + mov r4,r0 + ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ + smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ + mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ + mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ + add r0, r2, r1 /* r0 <- r2 + r1 */ + add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ + sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ + pop {r2-r4} + bx lr /* leave function */ + .align 4 +.Ls_magic_number_10: .word 0x66666667 diff --git a/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c b/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c index 26d35b7d61..42b235ae10 100644 --- a/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c +++ b/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 3rd October 2017*/ - #include #include diff --git a/Task/GUI-component-interaction/Vala/gui-component-interaction.vala b/Task/GUI-component-interaction/Vala/gui-component-interaction.vala new file mode 100644 index 0000000000..fcb096ad8a --- /dev/null +++ b/Task/GUI-component-interaction/Vala/gui-component-interaction.vala @@ -0,0 +1,80 @@ +bool validate_input(Gtk.Window window, string str){ + int64 val; + bool ret = int64.try_parse(str,out val);; + + if(!ret){ + var dialog = new Gtk.MessageDialog(window, + Gtk.DialogFlags.MODAL, + Gtk.MessageType.ERROR, + Gtk.ButtonsType.OK, + "Invalid value"); + dialog.run(); + dialog.destroy(); + } + return ret; +} + + +int main (string[] args) { + Gtk.init (ref args); + + var window = new Gtk.Window(); + window.title = "Rosetta Code"; + window.window_position = Gtk.WindowPosition.CENTER; + window.destroy.connect(Gtk.main_quit); + + + var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1); + box.set_border_width(1); + + + var label = new Gtk.Label ("Value:"); + + + var entry = new Gtk.Entry(); + entry.set_text("0"); //initialize to zero + entry.activate.connect (() => { + // read and validate the entered value + validate_input(window, entry.get_text()); + }); + + + // button to increment + var ib = new Gtk.Button.with_label("increment"); + ib.clicked.connect(() => { + // read and validate the entered value + var str = entry.get_text(); + if(validate_input(window, str)){ + entry.set_text((int.parse(str)+1).to_string()); + } + }); + + + // button to put in a random value if confirmed + var rb = new Gtk.Button.with_label("random"); + rb.clicked.connect (() => { + var dialog = new Gtk.MessageDialog(window, + Gtk.DialogFlags.MODAL, + Gtk.MessageType.QUESTION, + Gtk.ButtonsType.YES_NO, + "set random value"); + var answer = dialog.run(); + dialog.destroy(); + if(answer == Gtk.ResponseType.YES){ + entry.set_text(Random.int_range(0,10000).to_string()); + } + }); + + + box.pack_start(label, false, false, 2); + box.pack_start(entry, false, false, 2); + box.pack_start(ib, false, false, 2); + box.pack_start(rb, false, false, 2); + + window.add(box); + + window.show_all(); + + Gtk.main (); + return 0; +} diff --git a/Task/GUI-enabling-disabling-of-controls/Vala/gui-enabling-disabling-of-controls.vala b/Task/GUI-enabling-disabling-of-controls/Vala/gui-enabling-disabling-of-controls.vala new file mode 100644 index 0000000000..dac23a6f22 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Vala/gui-enabling-disabling-of-controls.vala @@ -0,0 +1,110 @@ +bool validate_input(Gtk.Window window, string str){ + int64 val; + bool ret = int64.try_parse(str,out val);; + + if(!ret || str == ""){ + var dialog = new Gtk.MessageDialog(window, + Gtk.DialogFlags.MODAL, + Gtk.MessageType.ERROR, + Gtk.ButtonsType.OK, + "Invalid value"); + dialog.run(); + dialog.destroy(); + } + if(str == ""){ + ret = false; + } + + return ret; +} + +int main (string[] args) { + Gtk.init (ref args); + + var window = new Gtk.Window(); + window.title = "Rosetta Code"; + window.window_position = Gtk.WindowPosition.CENTER; + window.destroy.connect(Gtk.main_quit); + + var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1); + box.set_border_width(1); + + var label = new Gtk.Label("Value:"); + var entry = new Gtk.Entry(); + var ib = new Gtk.Button.with_label("inc"); + var db = new Gtk.Button.with_label("dec"); + + ib.set_sensitive(true); //enable the inc button + db.set_sensitive(false); //disable the dec button + + entry.set_text("0"); //initialize to zero + + entry.activate.connect(() => { + var str = entry.get_text(); + + if(!validate_input(window, str)){ + entry.set_text("0"); //initialize to zero on wrong input + }else{ + int num = int.parse(str); + if(num != 0){ + entry.set_sensitive(false); //disable the field + } + if(num > 0 && num < 10){ + ib.set_sensitive(true); //enable the inc button + db.set_sensitive(true); //enable the dec button + } + if(num > 9){ + ib.set_sensitive(false); //disable the inc button + db.set_sensitive(true); //enable the dec button + } + } + }); + + ib.clicked.connect(() => { + // read and validate the entered value + if(!validate_input(window, entry.get_text())){ + entry.set_text("0"); //initialize to zero on wrong input + }else{ + int num = int.parse(entry.get_text()) + 1; + entry.set_text(num.to_string()); + if(num > 9){ + ib.set_sensitive(false); //disable the inc button + } + if(num != 0){ + db.set_sensitive(true); //enable the dec button + entry.set_sensitive(false); //disable the field + } + if(num == 0){ + entry.set_sensitive(true); //enable the field + } + if(num < 0){ + db.set_sensitive(false); //disable the dec button + } + } + }); + + db.clicked.connect(() => { + // read and validate the entered value + int num = int.parse(entry.get_text()) - 1; + entry.set_text(num.to_string()); + if(num == 0){ + db.set_sensitive(false); //disable the dec button + entry.set_sensitive(true); //enable the field + } + if(num < 10){ + ib.set_sensitive(true); //enable the inc button + } + }); + + box.pack_start(label, false, false, 2); + box.pack_start(entry, false, false, 2); + box.pack_start(ib, false, false, 2); + box.pack_start(db, false, false, 2); + + window.add(box); + + window.show_all(); + + Gtk.main(); + return 0; +} diff --git a/Task/Galton-box-animation/Go/galton-box-animation.go b/Task/Galton-box-animation/Go/galton-box-animation.go new file mode 100644 index 0000000000..40579eb66b --- /dev/null +++ b/Task/Galton-box-animation/Go/galton-box-animation.go @@ -0,0 +1,127 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +const boxW = 41 // Galton box width +const boxH = 37 // Galton box height. +const pinsBaseW = 19 // Pins triangle base. +const nMaxBalls = 55 // Number of balls. + +const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 + +const ( + empty = ' ' + ball = 'o' + wall = '|' + corner = '+' + floor = '-' + pin = '.' +) + +type Ball struct{ x, y int } + +func newBall(x, y int) *Ball { + if box[y][x] != empty { + panic("Tried to create a new ball in a non-empty cell. Program terminated.") + } + b := Ball{x, y} + box[y][x] = ball + return &b +} + +func (b *Ball) doStep() { + if b.y <= 0 { + return // Reached the bottom of the box. + } + cell := box[b.y-1][b.x] + switch cell { + case empty: + box[b.y][b.x] = empty + b.y-- + box[b.y][b.x] = ball + case pin: + box[b.y][b.x] = empty + b.y-- + if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { + b.x += rand.Intn(2)*2 - 1 + box[b.y][b.x] = ball + return + } else if box[b.y][b.x-1] == empty { + b.x++ + } else { + b.x-- + } + box[b.y][b.x] = ball + default: + // It's frozen - it always piles on other balls. + } +} + +type Cell = byte + +/* Galton box. Will be printed upside down. */ +var box [boxH][boxW]Cell + +func initializeBox() { + // Set ceiling and floor + box[0][0] = corner + box[0][boxW-1] = corner + for i := 1; i < boxW-1; i++ { + box[0][i] = floor + } + for i := 0; i < boxW; i++ { + box[boxH-1][i] = box[0][i] + } + + // Set walls + for r := 1; r < boxH-1; r++ { + box[r][0] = wall + box[r][boxW-1] = wall + } + + // Set rest to empty initially + for i := 1; i < boxH-1; i++ { + for j := 1; j < boxW-1; j++ { + box[i][j] = empty + } + } + + // Set pins + for nPins := 1; nPins <= pinsBaseW; nPins++ { + for p := 0; p < nPins; p++ { + box[boxH-2-nPins][centerH+1-nPins+p*2] = pin + } + } +} + +func drawBox() { + for r := boxH - 1; r >= 0; r-- { + for c := 0; c < boxW; c++ { + fmt.Printf("%c", box[r][c]) + } + fmt.Println() + } +} + +func main() { + rand.Seed(time.Now().UnixNano()) + initializeBox() + var balls []*Ball + for i := 0; i < nMaxBalls+boxH; i++ { + fmt.Println("\nStep", i, ":") + if i < nMaxBalls { + balls = append(balls, newBall(centerH, boxH-2)) // add ball + } + drawBox() + + // Next step for the simulation. + // Frozen balls are kept in balls slice for simplicity + for _, b := range balls { + b.doStep() + } + } +} diff --git a/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c b/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c index bcaff01ed8..240f258bf2 100644 --- a/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c +++ b/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 10th October 2017*/ - #include #include #include diff --git a/Task/Generic-swap/REBOL/generic-swap.rebol b/Task/Generic-swap/REBOL/generic-swap.rebol index 0d1a1898b3..1489fb78d8 100644 --- a/Task/Generic-swap/REBOL/generic-swap.rebol +++ b/Task/Generic-swap/REBOL/generic-swap.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Generic Swap" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Generic_swap Reference: [http://reboltutorial.com/blog/rebol-words/] ] diff --git a/Task/Gray-code/Ring/gray-code.ring b/Task/Gray-code/Ring/gray-code.ring index 89a6712666..7fdd118155 100644 --- a/Task/Gray-code/Ring/gray-code.ring +++ b/Task/Gray-code/Ring/gray-code.ring @@ -1,7 +1,4 @@ # Project : Gray code -# Date : 2018/01/12 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : pos = 5 see "0 : 00000 => 00000 => 00000" + nl diff --git a/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol b/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol index b718e4c4d3..952008c20e 100644 --- a/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol +++ b/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Maximum Value" - Date: 2009-12-15 - Author: oofoe URL: http://rosettacode.org/wiki/Maximum_Value ] diff --git a/Task/Greatest-element-of-a-list/VBA/greatest-element-of-a-list.vba b/Task/Greatest-element-of-a-list/VBA/greatest-element-of-a-list.vba new file mode 100644 index 0000000000..897de9ec9f --- /dev/null +++ b/Task/Greatest-element-of-a-list/VBA/greatest-element-of-a-list.vba @@ -0,0 +1,16 @@ +Option Explicit + +Sub Main() +Dim a + a = Array(1, 15, 19, 25, 13, 0, -125, 9) + Debug.Print Max_VBA(a) +End Sub + +Function Max_VBA(Arr As Variant) As Long +Dim i As Long, temp As Long + temp = Arr(LBound(Arr)) + For i = LBound(Arr) + 1 To UBound(Arr) + If Arr(i) > temp Then temp = Arr(i) + Next i + Max_VBA = temp +End Function diff --git a/Task/Greatest-subsequential-sum/Nim/greatest-subsequential-sum.nim b/Task/Greatest-subsequential-sum/Nim/greatest-subsequential-sum.nim index bf0bae68f2..9425a82ef7 100644 --- a/Task/Greatest-subsequential-sum/Nim/greatest-subsequential-sum.nim +++ b/Task/Greatest-subsequential-sum/Nim/greatest-subsequential-sum.nim @@ -1,4 +1,4 @@ -proc maxsum(s): int = +proc maxsum(s: openArray[int]): int = var maxendinghere = 0 for x in s: maxendinghere = max(maxendinghere + x, 0) diff --git a/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring b/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring index d3395678b3..b584dc324f 100644 --- a/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring +++ b/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring @@ -1,7 +1,4 @@ # Project : Greatest subsequential sum -# Date : 2017/09/26 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : aList1 = [0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] see "[0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] -> " + sum(aList1) + nl diff --git a/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring b/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring index 425bd2b9a7..4d5595c79c 100644 --- a/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring +++ b/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring @@ -1,7 +1,4 @@ # Project : Greyscale bars/Display -# Date : 2018/01/09 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "guilib.ring" diff --git a/Task/Guess-the-number-With-feedback/Befunge/guess-the-number-with-feedback.bf b/Task/Guess-the-number-With-feedback/Befunge/guess-the-number-with-feedback.bf new file mode 100644 index 0000000000..89935791fb --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Befunge/guess-the-number-with-feedback.bf @@ -0,0 +1,4 @@ +1:"d">>048*"neewteb rebmun a sseuG">:#,_$\:.\"d na",,\,,:.55+,\-88+0v +<*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1? +\1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+> +:#,_@>"ess" >"eug uoY"> diff --git a/Task/Guess-the-number-With-feedback/Emacs-Lisp/guess-the-number-with-feedback.l b/Task/Guess-the-number-With-feedback/Emacs-Lisp/guess-the-number-with-feedback.l new file mode 100644 index 0000000000..1978ee24d2 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Emacs-Lisp/guess-the-number-with-feedback.l @@ -0,0 +1,13 @@ +(let ((num (1+ (random 100)))) + (princ "Guess the no: ") + (loop + (setq guess (read)) + (cond + ((not (numberp guess)) (print "Please enter a number")) + ((eq guess num) + (progn (princ-list "Guess was right! " num) + (return))) + ((> guess num) + (print "Too High!")) + ((< guess num) + (print "Too low!"))) ) ) diff --git a/Task/Guess-the-number/ABAP/guess-the-number.abap b/Task/Guess-the-number/ABAP/guess-the-number.abap new file mode 100644 index 0000000000..9d4591f75d --- /dev/null +++ b/Task/Guess-the-number/ABAP/guess-the-number.abap @@ -0,0 +1,25 @@ +REPORT guess_the_number. + +DATA prng TYPE REF TO cl_abap_random_int. + +cl_abap_random_int=>create( + EXPORTING + seed = cl_abap_random=>seed( ) + min = 1 + max = 10 + RECEIVING + prng = prng ). + +DATA(number) = prng->get_next( ). + +DATA(field) = VALUE i( ). + +cl_demo_input=>add_field( EXPORTING text = |Choice one number between 1 and 10| CHANGING field = field ). +cl_demo_input=>request( ). + +WHILE number <> field. + cl_demo_input=>add_field( EXPORTING text = |You miss, try again| CHANGING field = field ). + cl_demo_input=>request( ). +ENDWHILE. + +cl_demo_output=>display( |Well Done| ). diff --git a/Task/Guess-the-number/Dart/guess-the-number.dart b/Task/Guess-the-number/Dart/guess-the-number.dart index d15aee79db..350e6da6f2 100644 --- a/Task/Guess-the-number/Dart/guess-the-number.dart +++ b/Task/Guess-the-number/Dart/guess-the-number.dart @@ -1,12 +1,9 @@ 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'); +import 'dart:io'; + +main() { + final n = (1 + new Random().nextInt(10)).toString(); + print("Guess which number I've chosen in the range 1 to 10"); + do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync()); + print("\nWell guessed!"); } diff --git a/Task/Guess-the-number/Emacs-Lisp/guess-the-number.l b/Task/Guess-the-number/Emacs-Lisp/guess-the-number.l new file mode 100644 index 0000000000..8f7e096376 --- /dev/null +++ b/Task/Guess-the-number/Emacs-Lisp/guess-the-number.l @@ -0,0 +1,6 @@ +(let ((num (1+ (random 10)))) + (princ "Guess the no") + (loop + (setq guess (read)) + (if (eq guess num) + (progn(princ-list "Guess was right! " num) (return)) (print "Wrong, try again.") ) ) ) diff --git a/Task/Guess-the-number/Kotlin/guess-the-number.kotlin b/Task/Guess-the-number/Kotlin/guess-the-number.kotlin index afacbf1eb6..9c927ea120 100644 --- a/Task/Guess-the-number/Kotlin/guess-the-number.kotlin +++ b/Task/Guess-the-number/Kotlin/guess-the-number.kotlin @@ -1,16 +1,8 @@ // 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 - } - } + val n = (1 + java.util.Random().nextInt(10)).toString() + println("Guess which number I've chosen in the range 1 to 10\n") + do { print(" Your guess : ") } while (n != readLine()) + println("\nWell guessed!") } diff --git a/Task/HTTP/BaCon/http.bacon b/Task/HTTP/BaCon/http.bacon index 8ba5e4fce6..123fd45010 100644 --- a/Task/HTTP/BaCon/http.bacon +++ b/Task/HTTP/BaCon/http.bacon @@ -1,18 +1,17 @@ ' ' Read and display a website ' -SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim -IF dim < 2 THEN +IF AMOUNT(ARGUMENT$) = 1 THEN website$ = "www.basic-converter.org" ELSE - website$ = arg$[1] + website$ = TOKEN$(ARGUMENT$, 2) ENDIF -OPEN CONCAT$(website$, ":80") FOR NETWORK AS mynet -SEND CONCAT$("GET / HTTP/1.1\r\nHost: ", website$, "\r\n\r\n") TO mynet +OPEN website$ & ":80" FOR NETWORK AS mynet +SEND "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)) +UNTIL ISFALSE(WAIT(mynet, 500)) CLOSE NETWORK mynet PRINT total$ diff --git a/Task/HTTP/Phix/http.phix b/Task/HTTP/Phix/http.phix new file mode 100644 index 0000000000..b860c4cc2a --- /dev/null +++ b/Task/HTTP/Phix/http.phix @@ -0,0 +1,9 @@ +include builtins\libcurl.e +curl_global_init() +atom curl = curl_easy_init() +curl_easy_setopt(curl, CURLOPT_URL, "http://rosettacode.org/robots.txt") +object res = curl_easy_perform_ex(curl) +curl_easy_cleanup(curl) +curl_global_cleanup() + +puts(1,res) diff --git a/Task/HTTPS-Authenticated/Lua/https-authenticated.lua b/Task/HTTPS-Authenticated/Lua/https-authenticated.lua new file mode 100644 index 0000000000..824dcab6dc --- /dev/null +++ b/Task/HTTPS-Authenticated/Lua/https-authenticated.lua @@ -0,0 +1,7 @@ +local requests = require('requests') +local auth = requests.HTTPBasicAuth('admin', 'admin') +local resp, e = requests.get({ + url = 'https://httpbin.org/basic-auth/admin/admin', + auth = auth +}) +io.write(string.format('Status: %d', resp.status_code)) diff --git a/Task/HTTPS-Authenticated/Phix/https-authenticated.phix b/Task/HTTPS-Authenticated/Phix/https-authenticated.phix new file mode 100644 index 0000000000..01de91614c --- /dev/null +++ b/Task/HTTPS-Authenticated/Phix/https-authenticated.phix @@ -0,0 +1,9 @@ +include builtins\libcurl.e +curl_global_init() +atom curl = curl_easy_init() +curl_easy_setopt(curl, CURLOPT_URL, "https://user:password@example.com/") +object res = curl_easy_perform_ex(curl) +curl_easy_cleanup(curl) +curl_global_cleanup() + +puts(1,res) diff --git a/Task/HTTPS-Client-authenticated/Phix/https-client-authenticated.phix b/Task/HTTPS-Client-authenticated/Phix/https-client-authenticated.phix new file mode 100644 index 0000000000..8158793b75 --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Phix/https-client-authenticated.phix @@ -0,0 +1,12 @@ +include builtins\libcurl.e +curl_global_init() +atom curl = curl_easy_init() +curl_easy_setopt(curl, CURLOPT_URL, "https://sourceforge.net") +integer fn = open("myCert.pem","r") +curl_easy_setopt(curl, CURLOPT_SSLCERT, get_text(fn)) +close(fn) +object res = curl_easy_perform_ex(curl) +curl_easy_cleanup(curl) +curl_global_cleanup() + +puts(1,res) diff --git a/Task/HTTPS/BaCon/https.bacon b/Task/HTTPS/BaCon/https.bacon new file mode 100644 index 0000000000..eed5e0c56a --- /dev/null +++ b/Task/HTTPS/BaCon/https.bacon @@ -0,0 +1,69 @@ +' SSL library +PRAGMA INCLUDE +PRAGMA LDFLAGS -lcrypto -lssl + +' Using RAM disk as a string +OPTION MEMSTREAM TRUE + +' BaCon must not choke on SSL functions +OPTION PARSE FALSE + +' Request to send to remote webserver (CONST is a macro def) +CONST req$ = "GET / HTTP/1.1\r\nHost: " & TOKEN$(website$, 1, ":") & "\r\n\r\n" + +' Some SSL related variables +DECLARE ctx TYPE SSL_CTX* +DECLARE meth TYPE const SSL_METHOD* +DECLARE ssl TYPE SSL* +DECLARE sbio TYPE BIO* + +' Which website we need to fetch +IF AMOUNT(ARGUMENT$) = 1 THEN + website$ = "www.google.com:443" +ELSE + website$ = TOKEN$(ARGUMENT$, 2) +END IF + +' Initialize SSL +SSL_library_init() +SSL_load_error_strings() + +' Create SSL context object +meth = SSLv23_method() +ctx = SSL_CTX_new(meth) +ssl = SSL_new(ctx) + +' Cpnnect to website creating a socket +OPEN website$ FOR NETWORK AS mynet + +' Perform the SSL handshake using the socket +sbio = BIO_new_socket(mynet, BIO_NOCLOSE) +SSL_set_bio(ssl, sbio, sbio) +IF SSL_connect(ssl) <= 0 THEN + EPRINT "SSL connect error" + END 1 +END IF + +' Setup buffer for the data coming back +mem = MEMORY(1024) +OPEN mem FOR MEMORY AS buf$ + +' Send the GET request to the remote server +SSL_write(ssl, req$, LEN(req$)) +REPEAT + ' Fetch the response into the buffer + SSL_read(ssl, buf$, 1024) + total$ = total$ & buf$ + memset((void*)mem, 0, 1024) +UNTIL ISFALSE(WAIT(mynet, 500)) + +' Bring down SSL +SSL_shutdown(ssl) + +' Close handles and free memory +CLOSE MEMORY buf$ +CLOSE NETWORK mynet +FREE mem + +' Show result +PRINT total$ diff --git a/Task/HTTPS/Lua/https.lua b/Task/HTTPS/Lua/https.lua new file mode 100644 index 0000000000..8abe34c034 --- /dev/null +++ b/Task/HTTPS/Lua/https.lua @@ -0,0 +1,5 @@ +local request = require('http.request') +local headers, stream = request.new_from_uri("https://sourceforge.net/"):go() +local body = stream:get_body_as_string() +local status = headers:get(':status') +io.write(string.format('Status: %d\nBody: %s\n', status, body) diff --git a/Task/HTTPS/Phix/https.phix b/Task/HTTPS/Phix/https.phix new file mode 100644 index 0000000000..02e1806d42 --- /dev/null +++ b/Task/HTTPS/Phix/https.phix @@ -0,0 +1,9 @@ +include builtins\libcurl.e +curl_global_init() +atom curl = curl_easy_init() +curl_easy_setopt(curl, CURLOPT_URL, "https://sourceforge.net/") +object res = curl_easy_perform_ex(curl) +curl_easy_cleanup(curl) +curl_global_cleanup() + +puts(1,res) diff --git a/Task/Hailstone-sequence/Crystal/hailstone-sequence.crystal b/Task/Hailstone-sequence/Crystal/hailstone-sequence.crystal new file mode 100644 index 0000000000..809965e4e0 --- /dev/null +++ b/Task/Hailstone-sequence/Crystal/hailstone-sequence.crystal @@ -0,0 +1,17 @@ +def hailstone(n) + seq = [n] + until n == 1 + n = n.even? ? n / 2 : n * 3 + 1 + seq << n + end + seq +end + +max_len = (1...100_000).max_by{|n| hailstone(n).size } +max = hailstone(max_len) +puts ([max_len, max.size, max.max, max.first(4), max.last(4)]) +# => [77031, 351, 21933016, [77031, 231094, 115547, 346642], [8, 4, 2, 1]] + +twenty_seven = hailstone(27) +puts ([twenty_seven.size, twenty_seven.first(4), max.last(4)]) +# => [112, [27, 82, 41, 124], [8, 4, 2, 1]] diff --git a/Task/Hamming-numbers/Java/hamming-numbers-2.java b/Task/Hamming-numbers/Java/hamming-numbers-2.java index fbb7745824..0b54a34bfd 100644 --- a/Task/Hamming-numbers/Java/hamming-numbers-2.java +++ b/Task/Hamming-numbers/Java/hamming-numbers-2.java @@ -1,7 +1,6 @@ import java.math.BigInteger; import java.util.*; -// ilkka.kokkarinen@gmail.com public class HammingTriple implements Comparable { diff --git a/Task/Happy-numbers/Sidef/happy-numbers.sidef b/Task/Happy-numbers/Sidef/happy-numbers.sidef index 5022711514..fc799226c0 100644 --- a/Task/Happy-numbers/Sidef/happy-numbers.sidef +++ b/Task/Happy-numbers/Sidef/happy-numbers.sidef @@ -2,14 +2,12 @@ func happy(n) is cached { static seen = Hash() return true if n.is_one - return false if seen.has_key(n) + return false if seen.exists(n) seen{n} = 1 - happy(n.digits Β»**Β» 2 -> sum) + happy(n.digits.sum { _*_ }) } -var count = 0; -Inf.times { |i| - happy(i) ? say i : next - ++count == 8 && break +say 8.defs {|i| + happy(i) ? i : nil } diff --git a/Task/Harshad-or-Niven-series/K/harshad-or-niven-series.k b/Task/Harshad-or-Niven-series/K/harshad-or-niven-series.k new file mode 100644 index 0000000000..6514aa63ff --- /dev/null +++ b/Task/Harshad-or-Niven-series/K/harshad-or-niven-series.k @@ -0,0 +1,6 @@ +/ sum of digits of an integer +sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d} +/ Test if an integer is a Harshad number +isHarshad: {:[x!(sumdig x); 0; 1]} / Returns 1 if Harshad +/ Generate x Harshad numbers starting from y and display the list +hSeries: {harshad::();i:y;while[(x-#harshad)>0;:[isHarshad i; harshad::(harshad,i)]; i+:1];harshad} diff --git a/Task/Harshad-or-Niven-series/VBA/harshad-or-niven-series.vba b/Task/Harshad-or-Niven-series/VBA/harshad-or-niven-series.vba new file mode 100644 index 0000000000..ddb38aacbd --- /dev/null +++ b/Task/Harshad-or-Niven-series/VBA/harshad-or-niven-series.vba @@ -0,0 +1,25 @@ +Option Explicit + +Sub Main() +Dim i As Long, out As String, Count As Integer + Do + i = i + 1 + If IsHarshad(i) Then out = out & i & ", ": Count = Count + 1 + Loop While Count < 20 + Debug.Print "First twenty Harshad numbers are : " & vbCrLf & out & "..." + + i = 1000 + Do + i = i + 1 + Loop While Not IsHarshad(i) + Debug.Print "The first harshad number after 1000 is : " & i +End Sub + +Function IsHarshad(sNumber As Long) As Boolean +Dim Summ As Long, i As Long, temp + temp = Split(StrConv(sNumber, vbUnicode), Chr(0)) + For i = LBound(temp) To UBound(temp) - 1 + Summ = Summ + temp(i) + Next i + IsHarshad = sNumber Mod Summ = 0 +End Function diff --git a/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring b/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring index df3a9ba3f4..881b3a7912 100644 --- a/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring +++ b/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring @@ -1,7 +1,4 @@ # Project : Hash from two arrays -# Date : 2018/03/18 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : list1="one two three" list2="1 2 3" diff --git a/Task/Hello-world-Graphical/Fortran/hello-world-graphical-1.f b/Task/Hello-world-Graphical/Fortran/hello-world-graphical-1.f index 8a9c1b69a3..2c7eb2044a 100644 --- a/Task/Hello-world-Graphical/Fortran/hello-world-graphical-1.f +++ b/Task/Hello-world-Graphical/Fortran/hello-world-graphical-1.f @@ -1,5 +1,5 @@ program hello use windows integer :: res - res = MessageBox(0, LOC("Hello, World"), LOC("Window Title"), MB_OK) + res = MessageBoxA(0, LOC("Hello, World"), LOC("Window Title"), MB_OK) end program diff --git a/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp b/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp index 36973866b1..80cf6d64bb 100644 --- a/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp +++ b/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp @@ -1,6 +1,3 @@ ;; Project : Hello world/Text -;; Date : 2018/03/05 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (format t "~a" "Hello world!") diff --git a/Task/Hello-world-Text/K/hello-world-text-1.k b/Task/Hello-world-Text/K/hello-world-text-1.k new file mode 100644 index 0000000000..6ccebb9abe --- /dev/null +++ b/Task/Hello-world-Text/K/hello-world-text-1.k @@ -0,0 +1 @@ +"Hello world!" diff --git a/Task/Hello-world-Text/K/hello-world-text-2.k b/Task/Hello-world-Text/K/hello-world-text-2.k new file mode 100644 index 0000000000..0941f426f9 --- /dev/null +++ b/Task/Hello-world-Text/K/hello-world-text-2.k @@ -0,0 +1 @@ +`0: "Hello world!\n" diff --git a/Task/Hello-world-Text/K/hello-world-text-3.k b/Task/Hello-world-Text/K/hello-world-text-3.k new file mode 100644 index 0000000000..efdd936410 --- /dev/null +++ b/Task/Hello-world-Text/K/hello-world-text-3.k @@ -0,0 +1,2 @@ +s: "Hello world!" +s diff --git a/Task/Hello-world-Text/K/hello-world-text-4.k b/Task/Hello-world-Text/K/hello-world-text-4.k new file mode 100644 index 0000000000..015f771d63 --- /dev/null +++ b/Task/Hello-world-Text/K/hello-world-text-4.k @@ -0,0 +1 @@ +\echo "Hello world!" diff --git a/Task/Hello-world-Text/Lambdatalk/hello-world-text.lambdatalk b/Task/Hello-world-Text/Lambdatalk/hello-world-text.lambdatalk new file mode 100644 index 0000000000..26ed48d163 --- /dev/null +++ b/Task/Hello-world-Text/Lambdatalk/hello-world-text.lambdatalk @@ -0,0 +1,3 @@ +Hello world! +{h1 Hello world!} +_h1 Hello world!\n diff --git a/Task/Hello-world-Text/VAX-Assembly/hello-world-text.vax b/Task/Hello-world-Text/VAX-Assembly/hello-world-text.vax new file mode 100644 index 0000000000..8bf17dde59 --- /dev/null +++ b/Task/Hello-world-Text/VAX-Assembly/hello-world-text.vax @@ -0,0 +1,6 @@ +desc: .ascid "Hello World!" ;descriptor (len+addr) and text +.entry hello, ^m<> ;register save mask + pushaq desc ;address of descriptor + calls #1, g^lib$put_output ;call with one argument on stack + ret ;restore registers, clean stack & return +.end hello ;transfer address for linker diff --git a/Task/Here-document/C/here-document.c b/Task/Here-document/C/here-document.c index 5f7f2b8837..f0cd8dc878 100644 --- a/Task/Here-document/C/here-document.c +++ b/Task/Here-document/C/here-document.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 7th October 2017*/ - #include int main() diff --git a/Task/Heronian-triangles/C/heronian-triangles.c b/Task/Heronian-triangles/C/heronian-triangles.c index 09f9c0cd06..f2c1251916 100644 --- a/Task/Heronian-triangles/C/heronian-triangles.c +++ b/Task/Heronian-triangles/C/heronian-triangles.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 6th October 2017*/ - #include #include #include diff --git a/Task/Heronian-triangles/Ring/heronian-triangles.ring b/Task/Heronian-triangles/Ring/heronian-triangles.ring index 5d53faa367..0f4081c5b6 100644 --- a/Task/Heronian-triangles/Ring/heronian-triangles.ring +++ b/Task/Heronian-triangles/Ring/heronian-triangles.ring @@ -1,7 +1,4 @@ # Project : Heronian triangles -# Date : 2017/11/04 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "Heronian triangles with sides up to 200" + nl see "Sides Perimeter Area" + nl diff --git a/Task/Higher-order-functions/REBOL/higher-order-functions.rebol b/Task/Higher-order-functions/REBOL/higher-order-functions.rebol index 62257b9cef..c4a6f62608 100644 --- a/Task/Higher-order-functions/REBOL/higher-order-functions.rebol +++ b/Task/Higher-order-functions/REBOL/higher-order-functions.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Function Argument" - Author: oofoe - Date: 2009-12-19 URL: http://rosettacode.org/wiki/Function_as_an_Argument ] diff --git a/Task/Higher-order-functions/Ring/higher-order-functions.ring b/Task/Higher-order-functions/Ring/higher-order-functions.ring index 69022e5e07..722cb87e88 100644 --- a/Task/Higher-order-functions/Ring/higher-order-functions.ring +++ b/Task/Higher-order-functions/Ring/higher-order-functions.ring @@ -1,7 +1,4 @@ # Project : Higher-order functions -# Date : 2018/04/03 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : docalcs(1,10,"squares",:square) docalcs(1,10,"cubes",:cube) diff --git a/Task/History-variables/Phix/history-variables-1.phix b/Task/History-variables/Phix/history-variables-1.phix new file mode 100644 index 0000000000..428aa1fc96 --- /dev/null +++ b/Task/History-variables/Phix/history-variables-1.phix @@ -0,0 +1,12 @@ +sequence history = {} + +type hvt(object o) + history = append(history,o) + return true +end type + +hvt test = 1 +test = 2 +test = 3 +?{"current",test} +?{"history",history} diff --git a/Task/History-variables/Phix/history-variables-2.phix b/Task/History-variables/Phix/history-variables-2.phix new file mode 100644 index 0000000000..6ed44b9b5c --- /dev/null +++ b/Task/History-variables/Phix/history-variables-2.phix @@ -0,0 +1,19 @@ +-- history.e +sequence histories = {} + +global function new_history_id(object v) + histories = append(histories,{v}) + return length(histories) +end function + +global procedure set_hv(integer hv, object v) + histories[hv] = append(histories[hv],v) +end procedure + +global function get_hv(integer hv) + return histories[hv][$] +end function + +global function get_hv_full_history(integer hv) + return histories[hv] +end function diff --git a/Task/History-variables/Phix/history-variables-3.phix b/Task/History-variables/Phix/history-variables-3.phix new file mode 100644 index 0000000000..d53ccfc957 --- /dev/null +++ b/Task/History-variables/Phix/history-variables-3.phix @@ -0,0 +1,7 @@ +include history.e + +constant test2 = new_history_id(1) +set_hv(test2, 2) +set_hv(test2, 3) +?{"current",get_hv(test2)} +?{"history",get_hv_full_history(test2)} diff --git a/Task/Hofstadter-Conway-$10,000-sequence/FreeBASIC/hofstadter-conway-$10,000-sequence.freebasic b/Task/Hofstadter-Conway-$10,000-sequence/FreeBASIC/hofstadter-conway-$10,000-sequence.freebasic new file mode 100644 index 0000000000..133f0ecf36 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/FreeBASIC/hofstadter-conway-$10,000-sequence.freebasic @@ -0,0 +1,32 @@ +' version 13-07-2018 +' compile with: fbc -s console + +Dim As UInteger a(), pow2 = 2, p2 = 2 ^ pow2, peakpos, n, mallows +Dim As Double peak = 0.5, r +ReDim a(2 ^ 20) +a(1) = 1 +a(2) = 1 + +For n = 3 To 2 ^ 20 + a(n) = a(a(n -1)) + a(n - a(n -1)) + r = a(n) / n + If r >= 0.55 Then mallows = n + If r > peak Then peak = r : peakpos = n + If n = p2 Then + Print Using "Maximum between 2 ^ ## and 2 ^ ## is"; pow2 -1; pow2; + Print Using " #.##### at n = "; peak; + Print peakpos + pow2 += 1 + p2 = 2 ^ pow2 + peak = 0.5 + End If +Next + +Print +Print "Mallows number is "; mallows + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring b/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring index c6ca5c6eca..5f5798d546 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring +++ b/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring @@ -1,7 +1,4 @@ # Project : Hofstadter Figure-Figure sequences -# Date : 2018/01/17 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : hofr = list(20) hofr[1] = 1 diff --git a/Task/Horizontal-sundial-calculations/Java/horizontal-sundial-calculations.java b/Task/Horizontal-sundial-calculations/Java/horizontal-sundial-calculations.java index b7e7aefe83..8f1457ec4e 100644 --- a/Task/Horizontal-sundial-calculations/Java/horizontal-sundial-calculations.java +++ b/Task/Horizontal-sundial-calculations/Java/horizontal-sundial-calculations.java @@ -1,4 +1,5 @@ import java.util.Scanner; + public class Sundial { public static void main(String[] args) { double lat, slat, lng, ref; @@ -19,7 +20,7 @@ public class Sundial { System.out.printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n"); for (int h = -6; h <= 6; h++) { - double hla, hra; + double hla, hra, hraRad; hra = 15.0 * h; hra = hra - lng + ref; hraRad = Math.toRadians(hra); diff --git a/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring b/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring index e6f62908f0..5d4cff7a13 100644 --- a/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring +++ b/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring @@ -1,7 +1,4 @@ # Project : Horizontal sundial calculations -# Date : 2017/10/24 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" pi = 22/7 diff --git a/Task/Horizontal-sundial-calculations/Scala/horizontal-sundial-calculations.scala b/Task/Horizontal-sundial-calculations/Scala/horizontal-sundial-calculations.scala new file mode 100644 index 0000000000..3154011c77 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Scala/horizontal-sundial-calculations.scala @@ -0,0 +1,27 @@ +import java.util.Scanner + +import scala.math.{atan2, cos, sin, toDegrees, toRadians} + +object Sundial extends App { + var lat, slat,lng, ref = .0 + val sc = new Scanner(System.in) + print("Enter latitude: ") + lat = sc.nextDouble + print("Enter longitude: ") + lng = sc.nextDouble + print("Enter legal meridian: ") + ref = sc.nextDouble + println() + slat = Math.sin(Math.toRadians(lat)) + println(f"sine of latitude: $slat%.3f") + println(f"diff longitude: ${lng - ref}%.3f\n") + println("Hour, sun hour angle, dial hour line angle from 06h00 to 18h00") + + for (h <- -6 to 6) { + val hra = 15.0 * h - lng + ref + val hraRad = toRadians(hra) + val hla = toDegrees(atan2(Math.sin(hraRad) * sin(Math.toRadians(lat)), cos(hraRad))) + println(f"HR= $h%3d;\tHRA=$hra%7.3f;\tHLA= $hla%7.3f") + } + +} diff --git a/Task/Hostname/K/hostname.k b/Task/Hostname/K/hostname.k new file mode 100644 index 0000000000..cf0599706d --- /dev/null +++ b/Task/Hostname/K/hostname.k @@ -0,0 +1 @@ +_h diff --git a/Task/Hough-transform/Maple/hough-transform.maple b/Task/Hough-transform/Maple/hough-transform.maple new file mode 100644 index 0000000000..616e5fdf4b --- /dev/null +++ b/Task/Hough-transform/Maple/hough-transform.maple @@ -0,0 +1,43 @@ +with(ImageTools): +img := Read("pentagon.png")[..,..,1]: +img_x := Convolution (img, Matrix ([[1,2,1], [0,0,0],[-1,-2,-1]])): +img_y := Convolution (img, Matrix ([[-1,0,1],[-2,0,2],[-1,0,1]])): +img := Array (abs (img_x) + abs (img_y), datatype=float[8]): +countPixels := proc(M) + local r,c,i,j,row,col: + row := Array([]); + col := Array([]); + r,c := LinearAlgebra:-Dimensions(M); + for i from 1 to r do + for j from 1 to c do + if M[i,j] <> 0 then + ArrayTools:-Append(row, i, inplace=true): + ArrayTools:-Append(col, j, inplace=true): + end if: + end do: + end do: + return row,col: +end proc: +row,col := countPixels(img); +pTheta := proc(acc,r,c,x,y) + local j, pos: + for j from 1 to c do + pos := ceil(x*cos((j-1)*Pi/180)+y*sin((j-1)*Pi/180)+r/2): + acc[pos,j] := acc[pos,j]+1; + end do: +end proc: +HoughTransform := proc(img,row,col) + local r,c,pMax,theta,numThetas,numPs,acc,i: + r,c := LinearAlgebra:-Dimensions(img); + pMax := ceil(sqrt(r^2+c^2)): + theta := [seq(evalf(i), i = 1..181, 1)]: + numThetas := numelems(theta): + numPs := 2*pMax+1: + acc := Matrix(numPs, numThetas, fill=0,datatype=integer[4]): + for i from 1 to numelems(row) do + pTheta(acc,numPs,numThetas,col[i],row[i]): + end do: + return acc; +end proc: +result :=HoughTransform(img,row,col); +Embed(Scale(FitIntensity(Create(result)), 1..500,1..500)); diff --git a/Task/Huffman-coding/Phix/huffman-coding.phix b/Task/Huffman-coding/Phix/huffman-coding.phix new file mode 100644 index 0000000000..99646baa79 --- /dev/null +++ b/Task/Huffman-coding/Phix/huffman-coding.phix @@ -0,0 +1,98 @@ +function store_nodes(object key, object data, integer nodes) + setd({data,key},0,nodes) + return 1 +end function +constant r_store_nodes = routine_id("store_nodes") + +function build_freqtable(string data) +integer freq = new_dict(), + nodes = new_dict() + for i=1 to length(data) do + integer di = data[i] + setd(di,getd(di,freq)+1,freq) + end for + traverse_dict(r_store_nodes, nodes, freq) + destroy_dict(freq) + return nodes +end function + +function build_hufftree(integer nodes) +sequence lkey, rkey, node +integer lfreq, rfreq + while true do + lkey = getd_partial_key({0,0},nodes) + lfreq = lkey[1] + deld(lkey,nodes) + rkey = getd_partial_key({0,0},nodes) + rfreq = rkey[1] + deld(rkey,nodes) + + node = {lfreq+rfreq,{lkey,rkey}} + + if dict_size(nodes)=0 then exit end if + + setd(node,0,nodes) + end while + destroy_dict(nodes) + return node +end function + +procedure build_huffcodes(object node, string bits, integer d) + {integer freq, object data} = node + if sequence(data) then + build_huffcodes(data[1],bits&'0',d) + build_huffcodes(data[2],bits&'1',d) + else + setd(data,{freq,bits},d) + end if +end procedure + +function print_huffcode(integer key, sequence data, integer /*user_data*/) + printf(1,"'%c' [%d] %s\n",key&data) + return 1 +end function +constant r_print_huffcode = routine_id("print_huffcode") + +procedure print_huffcodes(integer d) + traverse_dict(r_print_huffcode, 0, d) +end procedure + +function invert_huffcode(integer key, sequence data, integer rd) + setd(data[2],key,rd) + return 1 +end function +constant r_invert_huffcode = routine_id("invert_huffcode") + +procedure main(string data) + if length(data)<2 then ?9/0 end if + integer nodes = build_freqtable(data) + sequence huff = build_hufftree(nodes) + integer d = new_dict() + build_huffcodes(huff, "", d) + print_huffcodes(d) + + string encoded = "" + for i=1 to length(data) do + encoded &= getd(data[i],d)[2] + end for + ?encoded + + integer rd = new_dict() + traverse_dict(r_invert_huffcode, rd, d) + string decoded = "" + integer done = 0 + while done 0 then + if searchtext("cie", item) <> 0 then + cie := cie + 1: + else + xie := xie + 1: + fi: + fi: + if searchtext("ei", item) <> 0 then + if searchtext("cei", item) <> 0 then + cei := cei + 1: + else + xei := xei + 1: + fi: + fi: +od: +p1, p2 := evalb(xie > 2*xei),evalb(cei > 2*cie); +printf("The first phrase is %s with supporting features %d, anti features %d\n", piecewise(p1, "plausible", "not plausible"), xie, xei); +printf("The seond phrase is %s with supporting features %d, anti features %d\n", piecewise(p2, "plausible", "not plausible"), cei, cie); +printf("The overall phrase is %s\n", piecewise(p1 and p2, "plausible", "not plausible")): diff --git a/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring b/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring index ad674aba8f..a08d69eb5c 100644 --- a/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring +++ b/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring @@ -1,7 +1,4 @@ # Project : I before E except after C -# Date : 2017/11/26 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : fn1 = "unixdict.txt" diff --git a/Task/IBAN/Befunge/iban.bf b/Task/IBAN/Befunge/iban.bf new file mode 100644 index 0000000000..389d3b0ecb --- /dev/null +++ b/Task/IBAN/Befunge/iban.bf @@ -0,0 +1,8 @@ +>>" :NABI">:#,_>:~:"`"`48**-:55+-#v_$0::6g0>>8g-!\7g18g-!*!v>v>> +<<_#v:#78#`8#+<^+!!*-*84\-9:g8:p8\1#$-#<0$>>>#v_"dilav" ^#<< +>>^ >*-:20p9`9*1+55+**20g+"a"%10g1+00g%:4-!|^g6::_v#-*88:+1_vv>> +<<^+`"Z"\+`\"0"\*`\"A"\`"9":::\-*86:g8p01:<<40p00_v#!--+99g5>" si rebmun tahT">:#,_ 55+".",,@ >0"dilavni">>> +"-(&(/$$*$(*.-*.('$)*%0-&**.$'(.'/.+,''&&*.)**&,-.&.(*(*-!(%01-) +BFBBBBFFTNRRGGCCGCGGSSKSKSSDDHDHCPLPTLLLLPPAAVEIIAAAIEMMMNGMMMMI +ERGAHRIONLSOTRZYBRLIKIWMZAEOKREUHSBTRIVTUKLEDGESTLTZESEDCOEKUTRL diff --git a/Task/IBAN/PowerShell/iban-1.psh b/Task/IBAN/PowerShell/iban-1.psh index aaed91360c..57124d35ec 100644 --- a/Task/IBAN/PowerShell/iban-1.psh +++ b/Task/IBAN/PowerShell/iban-1.psh @@ -1,60 +1,26 @@ -@' -"Country","Length","Example" -"Albania",28,"AL47212110090000000235698741" -"Andorra",24,"AD1200012030200359100100" -"Austria",20,"AT611904300235473201" -"Belgium",16,"BE68539007547034" -"Bosnia and Herzegovina",20,"BA391290079401028494" -"Bulgaria",22,"BG80BNBG96611020345678" -"Croatia",21,"HR1210010051863000160" -"Cyprus",28,"CY17002001280000001200527600" -"Czech Republic",24,"CZ6508000000192000145399" -"Denmark",18,"DK5000400440116243" -"Estonia",20,"EE382200221020145685" -"Faroe Islands",18,"FO1464600009692713" -"Finland",18,"FI2112345600000785" -"France",27,"FR1420041010050500013M02606" -"Georgia",22,"GE29NB0000000101904917" -"Germany",22,"DE89370400440532013000" -"Gibraltar",23,"GI75NWBK000000007099453" -"Greece",27,"GR1601101250000000012300695" -"Greenland",18,"GL8964710001000206" -"Hungary",28,"HU42117730161111101800000000" -"Iceland",26,"IS140159260076545510730339" -"Ireland",22,"IE29AIBK93115212345678" -"Italy",27,"IT60X0542811101000000123456" -"Kosovo",20,"XK051212012345678906" -"Latvia",21,"LV80BANK0000435195001" -"Liechtenstein",21,"LI21088100002324013AA" -"Lithuania",20,"LT121000011101001000" -"Luxembourg",20,"LU280019400644750000" -"Macedonia",19,"MK07300000000042425" -"Malta",31,"MT84MALT011000012345MTLCAST001S" -"Moldova",24,"MD24AG000225100013104168" -"Monaco",27,"MC5813488000010051108001292" -"Montenegro",22,"ME25505000012345678951" -"Netherlands",18,"NL91ABNA0417164300" -"Norway",15,"NO9386011117947" -"Poland",28,"PL27114020040000300201355387" -"Portugal",25,"PT50000201231234567890154" -"Romania",24,"RO49AAAA1B31007593840000" -"San Marino",27,"SM86U0322509800000000270100" -"Serbia",22,"RS35260005601001611379" -"Slovakia",24,"SK3112000000198742637541" -"Slovenia",19,"SI56191000000123438" -"Spain",24,"ES9121000418450200051332" -"Sweden",24,"SE3550000000054910000003" -"Switzerland",21,"CH9300762011623852957" -"Ukraine",29,"UA573543470006762462054925026" -"United Kingdom",22,"GB29NWBK60161331926819" -'@ -split "`r`n" | Set-Content -Path .\IBAN.csv -Force - -$ibans = foreach ($iban in Import-Csv -Path .\IBAN.csv) +function verifIBAN ([string]$ibanS) { - $iban | Select-Object -Property Country, - @{Name='Code' ; Expression={$iban.Example.Substring(0,2)}}, - @{Name='Length'; Expression={[int]$iban.Length}}, - Example +if ($ibanS.Length -ne 27) {return $false} else +{ +$ibanI="$($ibanS.Substring(4,23))$($ibanS.Substring(0,4))".ToUpper() +[int]$comptIBAN=0 +$NumIBAN="" +while ($comptIBAN -lt 27) + { + if ([byte]$ibanI[$comptIBAN] -ge 65 -and [byte]$ibanI[$comptIBAN] -le 90) + { + $NumIban+=([byte]$ibanI[$comptIBAN]-55) + } #pour transformer les lettres en chiffres (A=10, B=11...) + else + { + $NumIban+=$ibanI[$comptIBAN] + } + $comptIBAN++ + } + #cela fait un nombre de 30 chiffres : trop pour powershell, je dΓ©coupe donc les 9 premiers caractΓ¨res : +if ("$($NumIBAN.Substring(0,9)%97)$($NumIBAN.Substring(9,$NumIBAN.Length-9))"%97 -eq 1) + {return $true} + else + {return $false} } - -$ibans +} #fin fonction vΓ©rification IBAN / StΓ©phane RABANY 2018 diff --git a/Task/IBAN/PowerShell/iban-2.psh b/Task/IBAN/PowerShell/iban-2.psh index 1c437949ce..aaed91360c 100644 --- a/Task/IBAN/PowerShell/iban-2.psh +++ b/Task/IBAN/PowerShell/iban-2.psh @@ -1,10 +1,60 @@ -$regex = [regex]'[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{6}[0-9]{5}([a-zA-Z0-9]?){0,16}' +@' +"Country","Length","Example" +"Albania",28,"AL47212110090000000235698741" +"Andorra",24,"AD1200012030200359100100" +"Austria",20,"AT611904300235473201" +"Belgium",16,"BE68539007547034" +"Bosnia and Herzegovina",20,"BA391290079401028494" +"Bulgaria",22,"BG80BNBG96611020345678" +"Croatia",21,"HR1210010051863000160" +"Cyprus",28,"CY17002001280000001200527600" +"Czech Republic",24,"CZ6508000000192000145399" +"Denmark",18,"DK5000400440116243" +"Estonia",20,"EE382200221020145685" +"Faroe Islands",18,"FO1464600009692713" +"Finland",18,"FI2112345600000785" +"France",27,"FR1420041010050500013M02606" +"Georgia",22,"GE29NB0000000101904917" +"Germany",22,"DE89370400440532013000" +"Gibraltar",23,"GI75NWBK000000007099453" +"Greece",27,"GR1601101250000000012300695" +"Greenland",18,"GL8964710001000206" +"Hungary",28,"HU42117730161111101800000000" +"Iceland",26,"IS140159260076545510730339" +"Ireland",22,"IE29AIBK93115212345678" +"Italy",27,"IT60X0542811101000000123456" +"Kosovo",20,"XK051212012345678906" +"Latvia",21,"LV80BANK0000435195001" +"Liechtenstein",21,"LI21088100002324013AA" +"Lithuania",20,"LT121000011101001000" +"Luxembourg",20,"LU280019400644750000" +"Macedonia",19,"MK07300000000042425" +"Malta",31,"MT84MALT011000012345MTLCAST001S" +"Moldova",24,"MD24AG000225100013104168" +"Monaco",27,"MC5813488000010051108001292" +"Montenegro",22,"ME25505000012345678951" +"Netherlands",18,"NL91ABNA0417164300" +"Norway",15,"NO9386011117947" +"Poland",28,"PL27114020040000300201355387" +"Portugal",25,"PT50000201231234567890154" +"Romania",24,"RO49AAAA1B31007593840000" +"San Marino",27,"SM86U0322509800000000270100" +"Serbia",22,"RS35260005601001611379" +"Slovakia",24,"SK3112000000198742637541" +"Slovenia",19,"SI56191000000123438" +"Spain",24,"ES9121000418450200051332" +"Sweden",24,"SE3550000000054910000003" +"Switzerland",21,"CH9300762011623852957" +"Ukraine",29,"UA573543470006762462054925026" +"United Kingdom",22,"GB29NWBK60161331926819" +'@ -split "`r`n" | Set-Content -Path .\IBAN.csv -Force -foreach ($iban in $ibans) +$ibans = foreach ($iban in Import-Csv -Path .\IBAN.csv) { - [PSCustomObject]@{ - Country = $iban.Country - Example = $iban.Example - IsValid = $regex.IsMatch($iban.Example) - } + $iban | Select-Object -Property Country, + @{Name='Code' ; Expression={$iban.Example.Substring(0,2)}}, + @{Name='Length'; Expression={[int]$iban.Length}}, + Example } + +$ibans diff --git a/Task/IBAN/PowerShell/iban-3.psh b/Task/IBAN/PowerShell/iban-3.psh new file mode 100644 index 0000000000..1c437949ce --- /dev/null +++ b/Task/IBAN/PowerShell/iban-3.psh @@ -0,0 +1,10 @@ +$regex = [regex]'[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{6}[0-9]{5}([a-zA-Z0-9]?){0,16}' + +foreach ($iban in $ibans) +{ + [PSCustomObject]@{ + Country = $iban.Country + Example = $iban.Example + IsValid = $regex.IsMatch($iban.Example) + } +} diff --git a/Task/IBAN/Ring/iban.ring b/Task/IBAN/Ring/iban.ring index 05c604a6c2..0f19532705 100644 --- a/Task/IBAN/Ring/iban.ring +++ b/Task/IBAN/Ring/iban.ring @@ -1,7 +1,4 @@ # Project : IBAN -# Date : 2018/01/03 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : codes = list(5) codes[1] = "GB82 WEST 1234 5698 7654 32" diff --git a/Task/Identity-matrix/Burlesque/identity-matrix-3.blq b/Task/Identity-matrix/Burlesque/identity-matrix-3.blq new file mode 100644 index 0000000000..bb3a8fe1d5 --- /dev/null +++ b/Task/Identity-matrix/Burlesque/identity-matrix-3.blq @@ -0,0 +1 @@ +blsq ) 6 ^^^^10\/**XXcy\/co.+sp diff --git a/Task/Identity-matrix/Factor/identity-matrix.factor b/Task/Identity-matrix/Factor/identity-matrix.factor new file mode 100644 index 0000000000..753997be52 --- /dev/null +++ b/Task/Identity-matrix/Factor/identity-matrix.factor @@ -0,0 +1,10 @@ +USE: math.matrices +IN: scratchpad 6 identity-matrix . +{ + { 1 0 0 0 0 0 } + { 0 1 0 0 0 0 } + { 0 0 1 0 0 0 } + { 0 0 0 1 0 0 } + { 0 0 0 0 1 0 } + { 0 0 0 0 0 1 } +} diff --git a/Task/Identity-matrix/Haskell/identity-matrix-4.hs b/Task/Identity-matrix/Haskell/identity-matrix-4.hs index 4a681469eb..ac6071431b 100644 --- a/Task/Identity-matrix/Haskell/identity-matrix-4.hs +++ b/Task/Identity-matrix/Haskell/identity-matrix-4.hs @@ -2,6 +2,3 @@ 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/Haskell/identity-matrix-5.hs b/Task/Identity-matrix/Haskell/identity-matrix-5.hs new file mode 100644 index 0000000000..dd6873e9f8 --- /dev/null +++ b/Task/Identity-matrix/Haskell/identity-matrix-5.hs @@ -0,0 +1,7 @@ +idMatrix :: Int -> [[Int]] +idMatrix n = + let xs = [1 .. n] + in (\x -> fromEnum . (x ==) <$> xs) <$> xs + +main :: IO () +main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5 diff --git a/Task/Image-convolution/Maple/image-convolution.maple b/Task/Image-convolution/Maple/image-convolution.maple new file mode 100644 index 0000000000..e58f70cd3e --- /dev/null +++ b/Task/Image-convolution/Maple/image-convolution.maple @@ -0,0 +1,3 @@ +pic:=Import("smiling_dog.jpg"): +mask := Matrix([[1,2,3],[4,5,6],[7,8,9]]); +pic := ImageTools:-Convolution(pic, mask); diff --git a/Task/Image-noise/FreeBASIC/image-noise.freebasic b/Task/Image-noise/FreeBASIC/image-noise.freebasic new file mode 100644 index 0000000000..7ccb34f6a2 --- /dev/null +++ b/Task/Image-noise/FreeBASIC/image-noise.freebasic @@ -0,0 +1,36 @@ +' version 13-07-2018 +' compile with: fbc -s console +' or: fbc -s gui + +' hit any to key to stop program + +Randomize Timer +Screen 13 + +If ScreenPtr = 0 Then + Print "Error setting video mode!" + End +End If + +Palette 0, 0 ' black +Palette 1, RGB(255, 255, 255) ' white + +Dim As UInteger c, x, y, Col +Dim As Double fps, t = Timer + +' empty keyboard buffer +While InKey <> "" : Wend + +While InKey = "" + + For x = 0 To 319 + For y = 0 To 199 + ' color is as integer, a float gets rounded off by FreeBASIC + PSet(x, y), Rnd + Next + Next + c += 1 + fps = c / (Timer - t) + WindowTitle "fps = " + Str(fps) + +Wend diff --git a/Task/Increment-a-numerical-string/REBOL/increment-a-numerical-string.rebol b/Task/Increment-a-numerical-string/REBOL/increment-a-numerical-string.rebol index 6fddfa96be..666135300d 100644 --- a/Task/Increment-a-numerical-string/REBOL/increment-a-numerical-string.rebol +++ b/Task/Increment-a-numerical-string/REBOL/increment-a-numerical-string.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Increment Numerical String" - Author: oofoe - Date: 2009-12-23 URL: http://rosettacode.org/wiki/Increment_numerical_string ] diff --git a/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-2.rexx b/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-2.rexx index 8a4fa8f507..4aea430508 100644 --- a/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-2.rexx +++ b/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-2.rexx @@ -1,5 +1,4 @@ /* REXX ************************************************************ -* 11.12.2012 Walter Pachl * There is no equivalent to PL/I's SIZE condition in REXX. * The result of an arithmetic expression is rounded * according to the current setting of Numeric Digits. diff --git a/Task/Infinity/Perl/infinity-6.pl b/Task/Infinity/Perl/infinity-6.pl index b1e36a9650..1d9acb18f1 100644 --- a/Task/Infinity/Perl/infinity-6.pl +++ b/Task/Infinity/Perl/infinity-6.pl @@ -1,3 +1,3 @@ use bigint; my $x = 1e1000; -my $y = 10**10**10; +my $y = 10**10**10; # N.B. this will consume vast quantities of RAM diff --git a/Task/Inheritance-Multiple/Ring/inheritance-multiple.ring b/Task/Inheritance-Multiple/Ring/inheritance-multiple.ring new file mode 100644 index 0000000000..2d8d3734dc --- /dev/null +++ b/Task/Inheritance-Multiple/Ring/inheritance-multiple.ring @@ -0,0 +1,34 @@ +# Project : Inheritance/Multiple + +mergemethods(:CameraPhone,:MobilePhone) + +o1 = new CameraPhone +? o1 +? o1.testCamera() +? o1.testMobilePhone() + +func AddParentClassAttributes oObject,cClass + # Add Attributes + cCode = "oTempObject = new " + cClass + eval(cCode) + for cAttribute in Attributes(oTempObject) + AddAttribute(oObject,cAttribute) + cCode = "oObject." + cAttribute + " = oTempObject." + cAttribute + eval(cCode) + next + + +class Camera + Name = "Camera" + func testCamera + ? "Message from testCamera" + +class MobilePhone + Type = "Android" + func testMobilePhone + ? "Message from MobilePhone" + +class CameraPhone from Camera + + # Add MobilePhone Attributes + AddParentClassAttributes(self,:MobilePhone) diff --git a/Task/Inheritance-Single/REBOL/inheritance-single.rebol b/Task/Inheritance-Single/REBOL/inheritance-single.rebol index 61a42443e0..d11b94add5 100644 --- a/Task/Inheritance-Single/REBOL/inheritance-single.rebol +++ b/Task/Inheritance-Single/REBOL/inheritance-single.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Inheritance" - Author: oofoe - Date: 2009-12-08 URL: http://rosettacode.org/wiki/Inheritance ] diff --git a/Task/Input-loop/REBOL/input-loop.rebol b/Task/Input-loop/REBOL/input-loop.rebol index 4c4f21f5c4..0860e12a8d 100644 --- a/Task/Input-loop/REBOL/input-loop.rebol +++ b/Task/Input-loop/REBOL/input-loop.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Basic Input Loop" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Basic_input_loop ] diff --git a/Task/Integer-comparison/ARM-Assembly/integer-comparison.arm b/Task/Integer-comparison/ARM-Assembly/integer-comparison.arm new file mode 100644 index 0000000000..57a9532561 --- /dev/null +++ b/Task/Integer-comparison/ARM-Assembly/integer-comparison.arm @@ -0,0 +1,181 @@ +/* ARM assembly Raspberry PI */ +/* program comparNumber.s */ + +/* Constantes */ +.equ BUFFERSIZE, 100 +.equ STDIN, 0 @ Linux input console +.equ STDOUT, 1 @ Linux output console +.equ EXIT, 1 @ Linux syscall +.equ READ, 3 @ Linux syscall +.equ WRITE, 4 @ Linux syscall +/* Initialized data */ +.data +szMessNum1: .asciz "Enter number 1 : \n" +szMessNum2: .asciz "Enter number 2: \n" +szMessEqual: .asciz "Number 1 and number 2 are equals.\n" +szMessSmall: .asciz "Number 1 smaller than number 2.\n" +szMessLarge: .asciz "Number 1 larger than number 2.\n" +szCarriageReturn: .asciz "\n" + +/* UnInitialized data */ +.bss +sBuffer: .skip BUFFERSIZE + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* saves 2 registers */ + ldr r0,iAdrszMessNum1 @ message address + ldr r1,iAdrsBuffer @ buffer address + mov r2,#BUFFERSIZE + bl numberEntry + mov r5,r0 @ save number 1 -> r5 + ldr r0,iAdrszMessNum2 @ message address + ldr r1,iAdrsBuffer @ buffer address + mov r2,#BUFFERSIZE + bl numberEntry + cmp r5,r0 @ compar number 1 and number 2 + beq equal + blt small + bgt large + @ never !! + b 100f +equal: + ldr r0,iAdrszMessEqual @ message address + b aff +small: + ldr r0,iAdrszMessSmall @ message address + b aff +large: + ldr r0,iAdrszMessLarge @ message address + b aff +aff: + bl affichageMess @ display message + + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call + +iAdrszMessNum1: .int szMessNum1 +iAdrszMessNum2: .int szMessNum2 +iAdrszMessEqual: .int szMessEqual +iAdrszMessSmall: .int szMessSmall +iAdrszMessLarge: .int szMessLarge +iAdrsBuffer: .int sBuffer +iAdrszCarriageReturn: .int szCarriageReturn +/******************************************************************/ +/* Number entry with display message and conversion number */ +/******************************************************************/ +/* r0 contains message address */ +/* r1 contains buffer address +/* r2 contains buffersize */ +/* r0 return a number */ +numberEntry: + push {fp,lr} @ save registres */ + push {r4,r6,r7} @ save others registers + mov r4,r1 @ save buffer address -> r4 + bl affichageMess + mov r0,#STDIN @ Linux input console + //ldr r1,iAdrsBuffer @ buffer address + //mov r2,#BUFFERSIZE @ buffer size + mov r7, #READ @ request to read datas + swi 0 @ call system + mov r1,r4 @ buffer address + mov r2,#0 @ end of string + strb r2,[r1,r0] @ store byte at the end of input string (r0 + @ + mov r0,r4 @ buffer address + bl conversionAtoD @ conversion string in number in r0 + +100: + pop {r4,r6,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registers */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ + + /******************************************************************/ +/* Convert a string to a number stored in a registry */ +/******************************************************************/ +/* r0 contains the address of the area terminated by 0 or 0A */ +/* r0 returns a number */ +conversionAtoD: + push {fp,lr} @ save 2 registers + push {r1-r7} @ save others registers + mov r1,#0 + mov r2,#10 @ factor + mov r3,#0 @ counter + mov r4,r0 @ save address string -> r4 + mov r6,#0 @ positive sign by default + mov r0,#0 @ initialization to 0 +1: /* early space elimination loop */ + ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position + cmp r5,#0 @ end of string -> end routine + beq 100f + cmp r5,#0x0A @ end of string -> end routine + beq 100f + cmp r5,#' ' @ space ? + addeq r3,r3,#1 @ yes we loop by moving one byte + beq 1b + cmp r5,#'-' @ first character is - + moveq r6,#1 @ 1 -> r6 + beq 3f @ then move on to the next position +2: /* beginning of digit processing loop */ + cmp r5,#'0' @ character is not a number + blt 3f + cmp r5,#'9' @ character is not a number + bgt 3f + /* character is a number */ + sub r5,#48 + ldr r1,iMaxi @ check the overflow of the register + cmp r0,r1 + bgt 99f @ overflow error + mul r0,r2,r0 @ multiply par factor 10 + add r0,r5 @ add to r0 +3: + add r3,r3,#1 @ advance to the next position + ldrb r5,[r4,r3] @ load byte + cmp r5,#0 @ end of string -> end routine + beq 4f + cmp r5,#0x0A @ end of string -> end routine + beq 4f + b 2b @ loop +4: + cmp r6,#1 @ test r6 for sign + moveq r1,#-1 + muleq r0,r1,r0 @ if negatif, multiply par -1 + b 100f +99: /* overflow error */ + ldr r0,=szMessErrDep + bl affichageMess + mov r0,#0 @ return zero if error +100: + pop {r1-r7} @ restaur other registers + pop {fp,lr} @ restaur 2 registers + bx lr @return procedure +/* constante program */ +iMaxi: .int 1073741824 +szMessErrDep: .asciz "Too large: overflow 32 bits.\n" diff --git a/Task/Integer-comparison/REBOL/integer-comparison.rebol b/Task/Integer-comparison/REBOL/integer-comparison.rebol index 78950929fd..8afe43551e 100644 --- a/Task/Integer-comparison/REBOL/integer-comparison.rebol +++ b/Task/Integer-comparison/REBOL/integer-comparison.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Comparing Two Integers" - Author: oofoe - Date: 2009-12-04 URL: http://rosettacode.org/wiki/Comparing_two_integers ] diff --git a/Task/Integer-sequence/Groovy/integer-sequence.groovy b/Task/Integer-sequence/Groovy/integer-sequence.groovy new file mode 100644 index 0000000000..5e335c9531 --- /dev/null +++ b/Task/Integer-sequence/Groovy/integer-sequence.groovy @@ -0,0 +1,8 @@ +// 32-bit 2's-complement signed integer (int/Integer) +for (def i = 1; i > 0; i++) { println i } + +// 64-bit 2's-complement signed integer (long/Long) +for (def i = 1L; i > 0; i+=1L) { println i } + +// Arbitrarily-long binary signed integer (BigInteger) +for (def i = 1g; ; i+=1g) { println i } diff --git a/Task/Introspection/Perl/introspection-4.pl b/Task/Introspection/Perl/introspection-4.pl index eae2d931b4..fb7b21c7d0 100644 --- a/Task/Introspection/Perl/introspection-4.pl +++ b/Task/Introspection/Perl/introspection-4.pl @@ -1,2 +1,8 @@ -eval('system("rm -rf /")'); -print "system() doesn't seem to be available\n" if $@; +use Math::Complex; +my $cpl = Math::Complex->new(1,1); + +print "package Math::Complex has 'make' method\n" + if Math::Complex->can('make'); + +print "object \$cpl does not have 'explode' method\n" + unless $cpl->can('explode'); diff --git a/Task/Introspection/Perl/introspection-5.pl b/Task/Introspection/Perl/introspection-5.pl index fb7b21c7d0..ace47f7c75 100644 --- a/Task/Introspection/Perl/introspection-5.pl +++ b/Task/Introspection/Perl/introspection-5.pl @@ -1,8 +1,13 @@ -use Math::Complex; -my $cpl = Math::Complex->new(1,1); - -print "package Math::Complex has 'make' method\n" - if Math::Complex->can('make'); - -print "object \$cpl does not have 'explode' method\n" - unless $cpl->can('explode'); +use 5.010; +our $bloop = -12; +if (defined $::bloop) { + if (eval { abs(1) }) { + say 'abs($bloop) is ' . abs($::bloop); + } + else { + say 'abs() is not available'; + } +} +else { + say '$bloop is not defined'; +} diff --git a/Task/Introspection/Perl/introspection-6.pl b/Task/Introspection/Perl/introspection-6.pl index ace47f7c75..e3a23b9a0b 100644 --- a/Task/Introspection/Perl/introspection-6.pl +++ b/Task/Introspection/Perl/introspection-6.pl @@ -1,13 +1,16 @@ use 5.010; -our $bloop = -12; -if (defined $::bloop) { - if (eval { abs(1) }) { - say 'abs($bloop) is ' . abs($::bloop); - } - else { - say 'abs() is not available'; - } -} -else { - say '$bloop is not defined'; -} +package test; +use Regexp::Common; +use List::Util qw(sum); + +our $a = 7; +our $b = 1; +our $c = 2; +our $d = -5; +our $e = 'text'; +our $f = 0.25; + +my @ints = grep { /^$RE{num}{int}$/ } map { $$_ // '' } values %::test::; +my $num = @ints; +my $sum = sum @ints; +say "$num integers, sum = $sum"; diff --git a/Task/Introspection/Perl/introspection-7.pl b/Task/Introspection/Perl/introspection-7.pl index e3a23b9a0b..c1c8c2847d 100644 --- a/Task/Introspection/Perl/introspection-7.pl +++ b/Task/Introspection/Perl/introspection-7.pl @@ -1,16 +1,7 @@ use 5.010; -package test; use Regexp::Common; use List::Util qw(sum); - -our $a = 7; -our $b = 1; -our $c = 2; -our $d = -5; -our $e = 'text'; -our $f = 0.25; - -my @ints = grep { /^$RE{num}{int}$/ } map { $$_ // '' } values %::test::; +my @ints = grep { /^$RE{num}{int}$/ } map { $$_ // '' } values %::; my $num = @ints; my $sum = sum @ints; say "$num integers, sum = $sum"; diff --git a/Task/Introspection/Ring/introspection.ring b/Task/Introspection/Ring/introspection.ring new file mode 100644 index 0000000000..71ac3f05cc --- /dev/null +++ b/Task/Introspection/Ring/introspection.ring @@ -0,0 +1,31 @@ +# Project: Introspection + +if version() < 1.8 + see "Version is too old" + " (" + version() + ")" + nl +else + see "Version is uptodate" + " (" + version() + ")" + nl +ok +bloop = 5 +if isglobal("bloop") = 1 + see "Variable " + "'bloop'" + " exists" + nl +else + see "Variable " + "'bloop'" + " doesn't exist" + nl +ok +if isglobal("bleep") = 1 + see "Variable " + "'bleep'" + " exists" + nl +else + see "Variable " + "'bleep'" + " doesn't exist" + nl +ok +if isfunction("abs") = 1 + see "Function " + "'abs'" + " is defined" + nl +else + see "Function " + "'abs'" + " is not defined" + nl +ok +if isfunction("abc") = 1 + see "Function " + "'abc'" + " is defined" + nl +else + see "Function " + "'abc'" + " is not defined" + nl +ok + +func abs(bloop) + return fabs(bloop) diff --git a/Task/Inverted-syntax/Factor/inverted-syntax-2.factor b/Task/Inverted-syntax/Factor/inverted-syntax-2.factor index 3f4a24b68c..bbd9825fa9 100644 --- a/Task/Inverted-syntax/Factor/inverted-syntax-2.factor +++ b/Task/Inverted-syntax/Factor/inverted-syntax-2.factor @@ -1,4 +1,3 @@ -USE: infix -[infix - 5*(1+1) ! 10 -infix] +MACRO: pre ( quot -- quot ) reverse ; + +[ + 2 2 ] pre ! 4 diff --git a/Task/Inverted-syntax/Factor/inverted-syntax-3.factor b/Task/Inverted-syntax/Factor/inverted-syntax-3.factor new file mode 100644 index 0000000000..3599646a94 --- /dev/null +++ b/Task/Inverted-syntax/Factor/inverted-syntax-3.factor @@ -0,0 +1 @@ +[ + 3 + 2 2 ] pre ! 7 diff --git a/Task/Inverted-syntax/Factor/inverted-syntax-4.factor b/Task/Inverted-syntax/Factor/inverted-syntax-4.factor new file mode 100644 index 0000000000..e0f288f9d6 --- /dev/null +++ b/Task/Inverted-syntax/Factor/inverted-syntax-4.factor @@ -0,0 +1,3 @@ +MACRO: pre ( quot -- quot ) 1 cut swap [ 0 ] dip reduce 1quotation ; + +[ + 1 2 3 4 5 ] pre ! 15 diff --git a/Task/Inverted-syntax/Factor/inverted-syntax-5.factor b/Task/Inverted-syntax/Factor/inverted-syntax-5.factor new file mode 100644 index 0000000000..3f4a24b68c --- /dev/null +++ b/Task/Inverted-syntax/Factor/inverted-syntax-5.factor @@ -0,0 +1,4 @@ +USE: infix +[infix + 5*(1+1) ! 10 +infix] diff --git a/Task/Inverted-syntax/Go/inverted-syntax.go b/Task/Inverted-syntax/Go/inverted-syntax.go new file mode 100644 index 0000000000..7bac3abace --- /dev/null +++ b/Task/Inverted-syntax/Go/inverted-syntax.go @@ -0,0 +1,30 @@ +package main + +import "fmt" + +type ibool bool + +const itrue ibool = true + +func (ib ibool) iif(cond bool) bool { + if cond { + return bool(ib) + } + return bool(!ib) +} + +func main() { + var needUmbrella bool + raining := true + + // normal syntax + if raining { + needUmbrella = true + } + fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella) + + // inverted syntax + raining = false + needUmbrella = itrue.iif(raining) + fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella) +} diff --git a/Task/Inverted-syntax/TI-83-BASIC/inverted-syntax.ti-83 b/Task/Inverted-syntax/TI-83-BASIC/inverted-syntax.ti-83 new file mode 100644 index 0000000000..12dc34aded --- /dev/null +++ b/Task/Inverted-syntax/TI-83-BASIC/inverted-syntax.ti-83 @@ -0,0 +1 @@ +536β†’N diff --git a/Task/Iterated-digits-squaring/Befunge/iterated-digits-squaring.bf b/Task/Iterated-digits-squaring/Befunge/iterated-digits-squaring.bf new file mode 100644 index 0000000000..c0d7b659cd --- /dev/null +++ b/Task/Iterated-digits-squaring/Befunge/iterated-digits-squaring.bf @@ -0,0 +1,5 @@ +1-1\10v!:/+55\<>::**>>-!| +v0:\+<_:55+%:*^^"d":+1$<: +>\`!#^ _$:"Y"-#v_$\1+\:^0 +>01-\0^ @,+55.<>:1>-!>#^_ +>,,,$." >=",,,^ >>".1">#< diff --git a/Task/Iterated-digits-squaring/Scala/iterated-digits-squaring.scala b/Task/Iterated-digits-squaring/Scala/iterated-digits-squaring.scala new file mode 100644 index 0000000000..d5a80e82b3 --- /dev/null +++ b/Task/Iterated-digits-squaring/Scala/iterated-digits-squaring.scala @@ -0,0 +1,43 @@ +import scala.annotation.tailrec + +object Euler92 extends App { + override val executionStart = compat.Platform.currentTime + + @tailrec + private def calcRec(i: Int): Int = { + + @tailrec + def iter0(n: Int, total: Int): Int = + if (n > 0) { + val rest = n % 10 + iter0(n / 10, total + rest * rest) + } + else total + + + if (i == 89 || i == 1) i else calcRec(iter0(i, 0)) + } + + + private def calcConv(i: Int) = { + var n: Int = i + while (n != 89 && n != 1) { + var total = 0 + while (n > 0) { + val x = n % 10 + total += (x * x) + n /= 10 + } + n = total + } + n + } + + println((1 until 100000000).par.count(calcConv(_) == 89)) + println(s"Runtime conventional loop.[total ${compat.Platform.currentTime - executionStart} ms]") + + val executionStart0 = compat.Platform.currentTime + println((1 until 100000000).par.count(calcRec(_) == 89)) + println(s"Runtime recursive loop. [total ${compat.Platform.currentTime - executionStart0} ms]") + +} diff --git a/Task/JSON/Crystal/json-1.crystal b/Task/JSON/Crystal/json-1.crystal new file mode 100644 index 0000000000..b15c66b153 --- /dev/null +++ b/Task/JSON/Crystal/json-1.crystal @@ -0,0 +1,14 @@ +require "json" + +class Foo + JSON.mapping( + num: Int64, + array: Array(String), + ) +end + +def json + foo = Foo.from_json(%({"num": 1, "array": ["a", "b"]})) + puts("#{foo.num} #{foo.array}") + puts(foo.to_json) +end diff --git a/Task/JSON/Crystal/json-2.crystal b/Task/JSON/Crystal/json-2.crystal new file mode 100644 index 0000000000..56c0fa16f5 --- /dev/null +++ b/Task/JSON/Crystal/json-2.crystal @@ -0,0 +1,2 @@ +1 ["a", "b"] +{"num":1,"array":["a","b"]} diff --git a/Task/JSON/Haskell/json-3.hs b/Task/JSON/Haskell/json-3.hs new file mode 100644 index 0000000000..23a1202db5 --- /dev/null +++ b/Task/JSON/Haskell/json-3.hs @@ -0,0 +1,17 @@ +{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} +import Data.Aeson +import GHC.Generics + +data Person = Person { firstName :: String + , lastName :: String + , age :: Maybe Int + } deriving (Show, Eq, Generic) + +instance FromJSON Person +instance ToJSON Person + +main = do + let test1 = "{\"firstName\":\"Bob\", \"lastName\":\"Smith\"}" + test2 = "{\"firstName\":\"Miles\", \"lastName\":\"Davis\", \"age\": 45}" + print (decode test1 :: Maybe Person) + print (decode test2 :: Maybe Person) diff --git a/Task/Jensens-Device/Go/jensens-device.go b/Task/Jensens-Device/Go/jensens-device.go new file mode 100644 index 0000000000..53d8ca90a5 --- /dev/null +++ b/Task/Jensens-Device/Go/jensens-device.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +var i int + +func sum(i *int, lo, hi int, term func() float64) float64 { + temp := 0.0 + for *i = lo; *i <= hi; (*i)++ { + temp += term() + } + return temp +} + +func main() { + fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) })) +} diff --git a/Task/Jensens-Device/Ring/jensens-device.ring b/Task/Jensens-Device/Ring/jensens-device.ring index d517727b66..d29dc8a8c8 100644 --- a/Task/Jensens-Device/Ring/jensens-device.ring +++ b/Task/Jensens-Device/Ring/jensens-device.ring @@ -1,7 +1,4 @@ # Project : Jensen's Device -# Date : 2018/01/31 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : decimals(14) i = 100 diff --git a/Task/Josephus-problem/Emacs-Lisp/josephus-problem.l b/Task/Josephus-problem/Emacs-Lisp/josephus-problem.l new file mode 100644 index 0000000000..6b8ca29952 --- /dev/null +++ b/Task/Josephus-problem/Emacs-Lisp/josephus-problem.l @@ -0,0 +1,4 @@ +(defun jo(n k) + (if (= 1 n) 1 (1+ (% (+ (1- k) + (jo (1- n) k)) n ) ) )) +(princ-list (jo 50 2) "\n" (jo 60 3)) diff --git a/Task/Jump-anywhere/PL-I/jump-anywhere.pli b/Task/Jump-anywhere/PL-I/jump-anywhere.pli new file mode 100644 index 0000000000..35caaf9c53 --- /dev/null +++ b/Task/Jump-anywhere/PL-I/jump-anywhere.pli @@ -0,0 +1 @@ +on conversion goto restart; diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/Ring/keyboard-input-flush-the-keyboard-buffer.ring b/Task/Keyboard-input-Flush-the-keyboard-buffer/Ring/keyboard-input-flush-the-keyboard-buffer.ring new file mode 100644 index 0000000000..101ca991a6 --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/Ring/keyboard-input-flush-the-keyboard-buffer.ring @@ -0,0 +1,3 @@ +# Project: Keyboard input/Flush the keyboard buffer + +Fflush(stdin) diff --git a/Task/Keyboard-macros/Phix/keyboard-macros-1.phix b/Task/Keyboard-macros/Phix/keyboard-macros-1.phix new file mode 100644 index 0000000000..357564e2ce --- /dev/null +++ b/Task/Keyboard-macros/Phix/keyboard-macros-1.phix @@ -0,0 +1,27 @@ +include pGUI.e + +function C_Keyed(Ihandle /*ih*/, atom /*c*/) +-- (Note without K_c below this does not respond to 'c', just 'C') + ?"you pressed C" + return IUP_DEFAULT +end function + +procedure F2_keyed() + ?"you pressed F2" +end procedure + +function key_cb(Ihandle /*ih*/, atom c) + if c=K_F2 then F2_keyed() + elsif c=K_ESC then return IUP_CLOSE + end if + return IUP_DEFAULT +end function + +IupOpen() +Ihandle dlg = IupDialog(IupLabel("hello"),"TITLE=\"Press F2\"") +IupSetCallback(dlg, "K_C", Icallback("C_Keyed")) +--IupSetCallback(dlg, "K_c", Icallback("C_Keyed")) +IupSetCallback(dlg, "K_ANY", Icallback("key_cb")) +IupShow(dlg) +IupMainLoop() +IupClose() diff --git a/Task/Keyboard-macros/Phix/keyboard-macros-2.phix b/Task/Keyboard-macros/Phix/keyboard-macros-2.phix new file mode 100644 index 0000000000..3cd302b628 --- /dev/null +++ b/Task/Keyboard-macros/Phix/keyboard-macros-2.phix @@ -0,0 +1,144 @@ +-- +-- demo\arwendemo\hotkey.exw +-- ========================= +-- +-- Author: Pete Lomax, credit to Aku Saya for HotKey +-- and Thomas Parslow for sendkeys +-- +-- http://phix.x10.mx +-- +--/**/with gui +include arwen.ew + +constant + MOD_ALT = #1, + MOD_CONTROL = #2, + MOD_SHIFT = #4, + MOD_WIN = #8 + +integer Modifier, vKeyCode + +constant Main = create(Window, "Hotkey", 0, 0, 36, 99, 294, 201, 0) +constant MainHwnd = getHwnd(Main) +constant mFile = create(Menu,"File",0,Main,190,63,0,0,0) +constant mExit = create(MenuItem,"Exit",0,mFile,194,53,0,0,0) +constant mHelp = create(Menu,"Help",0,Main,182,57,0,0,0) +constant mAbout = create(MenuItem,"About",0,mHelp,184,45,0,0,0) +constant AltKey = create(CheckBox, "Alt", 0, Main, 8, 5, 62, 20, 0) +constant ShiftKey = create(CheckBox, "Shift", 0, Main, 8, 28, 56, 20, 0) +constant CtrlKey = create(CheckBox, "Ctrl", 0, Main, 8, 52, 70, 20, 0) +constant WinKey = create(CheckBox, "Windows", 0, Main, 8, 76, 72, 20, 0) +constant KeyList = create(ComboDropDown, "KeyList", 0, Main, 89, 11, 100, 652, 0) +constant KeyInfoText = create(Label, "", 0, Main, 90, 72, 186, 20, SS_LEFTNOWORDWRAP) +constant SetButton = create(Button, "setHotKey", 0, Main, 8, 99, 176, 40, BS_DEFPUSHBUTTON) +constant KillButton = create(Button, "killHotKey", 0, Main, 195, 99, 80, 40, 0) + +sequence KeyCodes + +procedure initialise() +string text + for f=1 to 11 do -- F1 to F11 (F12 is reserved) + text = sprintf("F%d",f) + void = insertItem(KeyList,text,0) + end for + KeyCodes = {VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11} + for ch='A' to 'Z' do + text = sprintf("%s",ch) + void = insertItem(KeyList,text,0) + KeyCodes &= ch -- (as char, not string) + end for + for i=1 to 9 do + text = sprintf("%d",i) + void = insertItem(KeyList,text,0) + KeyCodes &= i -- (as char, not string) + end for +end procedure +initialise() + +constant INPUT_KEYBOARD=1 + +procedure pokeKey(atom pKey, integer key) +-- see http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270(v=vs.85).aspx +-- and http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271(v=vs.85).aspx +integer ScanCode + ScanCode = c_func(xVkKeyScan,{key}) + poke4(pKey+KEYBDINPUT_type,INPUT_KEYBOARD) + poke2(pKey+KEYBDINPUT_wVk,key) + poke4(pKey+KEYBDINPUT_dwFlags,0) + poke4(pKey+KEYBDINPUT_wScan,ScanCode) + poke4(pKey+KEYBDINPUT_time,0) + poke4(pKey+KEYBDINPUT_dwExtraInfo,0) +end procedure + +function MainHandler(integer id, integer msg, atom wParam, object lParam) +string text +atom pKeys, pKey +integer nRes + + if msg=WM_SETFOCUS then + if id=SetButton then + if not getIndex(KeyList) then + setFocus(KeyList) + void = messageBox("HotKey","Select a key from the drop-down",MB_OK) + else + Modifier = isChecked(AltKey) * MOD_ALT + + isChecked(ShiftKey) * MOD_SHIFT + + isChecked(CtrlKey) * MOD_CONTROL + + isChecked(WinKey) * MOD_WIN + vKeyCode = KeyCodes[getIndex(KeyList)] + text = sprintf("setHotKey(Main, #%02x, #%02x) [%s]",{Modifier,vKeyCode,getText(KeyList)}) + setText(KeyInfoText, text) + end if + elsif id=KillButton then + text = sprintf("killHotKey(Main) [%s]",{getText(KeyList)}) + setText(KeyInfoText, text) + end if + elsif msg=WM_COMMAND then + if id=mExit then + closeWindow(Main) + elsif id=mAbout then + text = "Simple hotkey/sendinput wrapper.\n\n"& + + "Author Pete Lomax.\n"& + "Written in phix (http://phix.x10.mx) but could easily be ported\n"& + "to any language (that can invoke RegisterHotKey and SendInput).\n\n"& + + "First, use the checkboxes and dropdown to select a hotkey (eg F7).\n"& + "Currently always sends {delete,down}, but that could easily be changed.\n"& + "Used on build02 to perform the GUID stripping.\n\n"& + + "Note that Windows Server 2008 requires this to be run in admin mode, \n"& + "as otherwise something called UIPI will block it and not say why.\n" + void = messageBox("HotKey",text,MB_OK) + elsif id=SetButton then + -- see http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx + if c_func(xRegisterHotKey,{MainHwnd, 0, Modifier, vKeyCode})=0 then + void = messageBox("HotKey","Register Hotkey failed",MB_OK) + end if + elsif id=KillButton then + if c_func(xUnregisterHotKey,{MainHwnd, 0})=0 then + void = messageBox("HotKey","UnRegister Hotkey failed",MB_OK) + end if + end if + elsif msg=WM_HOTKEY then + setText(Main,sprintf("%g",time())) + pKeys = allocate(sizeofstruct(KEYBDINPUT)*2) + pKey = pKeys + pokeKey(pKey,VK_DELETE) + pKey += sizeofstruct(KEYBDINPUT) + pokeKey(pKey,VK_DOWN) + + -- see http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx + nRes = c_func(xSendInput,{2,pKeys,sizeofstruct(KEYBDINPUT)}) + if nRes!=2 then + nRes = c_func(xGetLastError,{}) + text = sprintf("SendInput failed[%d]",nRes) + void = messageBox("HotKey",text,MB_OK) + end if + end if + if wParam or object(lParam) then end if -- suppress warnings + return 0 +end function +setHandler({Main,SetButton,KillButton,mExit,mAbout},routine_id("MainHandler")) + +WinMain(Main,SW_NORMAL) diff --git a/Task/Keyboard-macros/REBOL/keyboard-macros.rebol b/Task/Keyboard-macros/REBOL/keyboard-macros.rebol index ddfe72b6a6..fee4bebcaf 100644 --- a/Task/Keyboard-macros/REBOL/keyboard-macros.rebol +++ b/Task/Keyboard-macros/REBOL/keyboard-macros.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Keyboard Macros" - Date: 2009-12-14 - Author: oofoe URL: http://rosettacode.org/wiki/Keyboard_macros ] diff --git a/Task/Keyboard-macros/Scala/keyboard-macros.scala b/Task/Keyboard-macros/Scala/keyboard-macros.scala new file mode 100644 index 0000000000..77279cbd2d --- /dev/null +++ b/Task/Keyboard-macros/Scala/keyboard-macros.scala @@ -0,0 +1,24 @@ +import java.awt.event.{KeyAdapter, KeyEvent} + +import javax.swing.{JFrame, JLabel, WindowConstants} + + +object KeyboardMacroDemo extends App { + val directions = "Ctrl-S to show frame title
" + "Ctrl-H to hide it" + + new JFrame { + add(new JLabel(directions)) + + addKeyListener(new KeyAdapter() { + override def keyReleased(e: KeyEvent): Unit = { + if (e.isControlDown && e.getKeyCode == KeyEvent.VK_S) setTitle("Hello there") + else if (e.isControlDown && e.getKeyCode == KeyEvent.VK_H) setTitle("") + } + }) + + pack() + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) + setVisible(true) + } + +} diff --git a/Task/Knapsack-problem-0-1/00DESCRIPTION b/Task/Knapsack-problem-0-1/00DESCRIPTION index 9a0f98a398..9e5c168413 100644 --- a/Task/Knapsack-problem-0-1/00DESCRIPTION +++ b/Task/Knapsack-problem-0-1/00DESCRIPTION @@ -82,4 +82,5 @@ exceed 400 dag [4 kg],   and their total value is maximized. *   [[Knapsack problem/Bounded]] *   [[Knapsack problem/Unbounded]] *   [[Knapsack problem/Continuous]] +*   [[A* search algorithm]]

diff --git a/Task/Knapsack-problem-0-1/Maple/knapsack-problem-0-1.maple b/Task/Knapsack-problem-0-1/Maple/knapsack-problem-0-1.maple new file mode 100644 index 0000000000..ff7f762fe2 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Maple/knapsack-problem-0-1.maple @@ -0,0 +1,29 @@ +weights := [9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30]: +vals := [150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10]: +items := ["map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","T-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book"]: +acc := Array(1..numelems(vals)+1,1..400+1,1,fill=0): +len := numelems(weights): +for i from 2 to len+1 do #number of items picked + 1 + for j from 2 to 401 do #weight capacity left + 1 + if weights[i-1] > j-1 then + acc[i,j] := acc[i-1, j]: + else + acc[i,j] := max(acc[i-1,j], acc[i-1, j-weights[i-1]]+vals[i-1]): + end if: + end do: +end do: +printf("Total Value is %d\n", acc[len+1, 401]): +count := 0: +i := len+1: +j := 401: +while (i>1 and j>1) do + if acc[i,j] <> acc[i-1,j] then + printf("Item: %s\n", items[i-1]): + count := count+weights[i-1]: + j := j-weights[i-1]: + i := i-1: + else + i := i-1: + end if: +end do: +printf("Total Weight is %d\n", count): diff --git a/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring b/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring index c013127be9..1b24ed0305 100644 --- a/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring +++ b/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring @@ -1,7 +1,4 @@ # Project : Knapsack problem/0-1 -# Date : 2018/01/27 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : knap = [["map",9,150], ["compass",13,35], diff --git a/Task/Knuth-shuffle/Ring/knuth-shuffle.ring b/Task/Knuth-shuffle/Ring/knuth-shuffle.ring index 1e5bdf82d2..309424b177 100644 --- a/Task/Knuth-shuffle/Ring/knuth-shuffle.ring +++ b/Task/Knuth-shuffle/Ring/knuth-shuffle.ring @@ -1,7 +1,4 @@ # Project : Knuth shuffle -# Date : 2017/11/08 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : items = list(52) for n = 1 to len(items) diff --git a/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-1.java b/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-1.java index ce01f2c656..1604356fea 100644 --- a/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-1.java +++ b/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-1.java @@ -6,32 +6,30 @@ class SOfN { private List sample; private int i = 0; private int n; + public SOfN(int _n) { - n = _n; - sample = new ArrayList(n); + n = _n; + sample = new ArrayList(n); } + public List process(T item) { - i++; - if (i <= n) { + if (++i <= n) { sample.add(item); - } else if (rand.nextInt(i) < n) { - sample.set(rand.nextInt(n), item); - } - return sample; + } else if (rand.nextInt(i) < n) { + sample.set(rand.nextInt(n), item); + } + return sample; } } public class AlgorithmS { public static void main(String[] args) { - int[] bin = new int[10]; - for (int trial = 0; trial < 100000; trial++) { - SOfN s_of_n = new SOfN(3); - List sample = null; - for (int i = 0; i < 10; i++) - sample = s_of_n.process(i); - for (int s : sample) - bin[s]++; - } - System.out.println(Arrays.toString(bin)); + int[] bin = new int[10]; + for (int trial = 0; trial < 100000; trial++) { + SOfN s_of_n = new SOfN(3); + for (int i = 0; i < 9; i++) s_of_n.process(i); + for (int s : s_of_n.process(9)) bin[s]++; + } + System.out.println(Arrays.toString(bin)); } } diff --git a/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-2.java b/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-2.java index 4824e58d81..c5a283e310 100644 --- a/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-2.java +++ b/Task/Knuths-algorithm-S/Java/knuths-algorithm-s-2.java @@ -7,31 +7,27 @@ interface Function { public class AlgorithmS { private static final Random rand = new Random(); public static Function> s_of_n_creator(final int n) { - return new Function>() { - private List sample = new ArrayList(n); - private int i = 0; - public List call(T item) { - i++; - if (i <= n) { - sample.add(item); - } else if (rand.nextInt(i) < n) { - sample.set(rand.nextInt(n), item); - } - return sample; - } - }; + return new Function>() { + private List sample = new ArrayList(n); + private int i = 0; + public List call(T item) { + if (++i <= n) { + sample.add(item); + } else if (rand.nextInt(i) < n) { + sample.set(rand.nextInt(n), item); + } + return sample; + } + }; } public static void main(String[] args) { - int[] bin = new int[10]; - for (int trial = 0; trial < 100000; trial++) { - Function> s_of_n = s_of_n_creator(3); - List sample = null; - for (int i = 0; i < 10; i++) - sample = s_of_n.call(i); - for (int s : sample) - bin[s]++; - } - System.out.println(Arrays.toString(bin)); + int[] bin = new int[10]; + for (int trial = 0; trial < 100000; trial++) { + Function> s_of_n = s_of_n_creator(3); + for (int i = 0; i < 9; i++) s_of_n.call(i); + for (int s : s_of_n.call(9)) bin[s]++; + } + System.out.println(Arrays.toString(bin)); } } diff --git a/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s.kotlin b/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-1.kotlin similarity index 63% rename from Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s.kotlin rename to Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-1.kotlin index d4c16aaa03..819f14f24b 100644 --- a/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s.kotlin +++ b/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-1.kotlin @@ -1,16 +1,14 @@ -// version 1.1.2 +// version 1.2.51 import java.util.Random +val rand = Random() + class SOfN(val n: Int) { private val sample = ArrayList(n) private var i = 0 - private companion object { - val rand = Random() - } - - fun process(item: T): ArrayList { + fun process(item: T): List { if (++i <= n) sample.add(item) else if (rand.nextInt(i) < n) @@ -23,9 +21,8 @@ fun main(args: Array) { val bin = IntArray(10) (1..100_000).forEach { val sOfn = SOfN(3) - var sample: ArrayList? = null - for (i in 0..9) sample = sOfn.process(i) - for (s in sample!!) bin[s]++ + for (d in 0..8) sOfn.process(d) + for (s in sOfn.process(9)) bin[s]++ } println(bin.contentToString()) } diff --git a/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-2.kotlin b/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-2.kotlin new file mode 100644 index 0000000000..1253c5e415 --- /dev/null +++ b/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-2.kotlin @@ -0,0 +1,27 @@ +// version 1.2.51 + +import java.util.Random + +val rand = Random() + +fun SOfNCreator(n: Int): (T) -> List { + val sample = ArrayList(n) + var i = 0 + return { + if (++i <= n) + sample.add(it) + else if (rand.nextInt(i) < n) + sample[rand.nextInt(n)] = it + sample + } +} + +fun main(args: Array) { + val bin = IntArray(10) + (1..100_000).forEach { + val sOfn = SOfNCreator(3) + for (d in 0..8) sOfn(d) + for (s in sOfn(9)) bin[s]++ + } + println(bin.contentToString()) +} diff --git a/Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-1.phix b/Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-1.phix new file mode 100644 index 0000000000..aa78e8a1bf --- /dev/null +++ b/Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-1.phix @@ -0,0 +1,44 @@ +enum RID, I, SAMPLE + +function s_of_n(sequence env, integer item) + integer i = env[I] + 1, + n = length(env[SAMPLE]) + env[I] = i + if i<=n then + env[SAMPLE][i] = item + elsif n/i>rnd() then + env[SAMPLE][rand(n)] = item + end if + return env +end function + +function s_of_n_creator(int n) + return {routine_id("s_of_n"),0,repeat(0,n)} +end function + +function invoke(sequence env, args) + env = call_func(env[RID],prepend(args,env)) + return env +end function + +function test(integer n, sequence items) + sequence env = s_of_n_creator(n) + for i=1 to length(items) do +-- env = s_of_n(env,items[i]) + env = invoke(env, {items[i]}) + end for + return env[SAMPLE] +end function + +procedure main() + sequence items_set = tagset(9,0) + sequence frequencies = repeat(0,length(items_set)) + for i=1 to 100000 do + sequence res = test(3, items_set) + for j=1 to length(res) do + frequencies[res[j]+1] += 1 + end for + end for + ?frequencies +end procedure +main() diff --git a/Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-2.phix b/Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-2.phix new file mode 100644 index 0000000000..1f160d88ca --- /dev/null +++ b/Task/Knuths-algorithm-S/Phix/knuths-algorithm-s-2.phix @@ -0,0 +1,9 @@ +enum RID, I, SAMPLE, CLOSURE_LEN=$ +... +function s_of_n_creator(int n) + sequence closure = repeat(0,CLOSURE_LEN) + closure[RID] = routine_id("s_of_n") + closure[I] = 0 + closure[SAMPLE] = repeat(0,n) + return closure +end function diff --git a/Task/LU-decomposition/Phix/lu-decomposition.phix b/Task/LU-decomposition/Phix/lu-decomposition.phix new file mode 100644 index 0000000000..46857f0073 --- /dev/null +++ b/Task/LU-decomposition/Phix/lu-decomposition.phix @@ -0,0 +1,77 @@ +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 pivotize(sequence m) + integer n = length(m) + sequence im = repeat(repeat(0,n),n) + for i=1 to n do + im[i][i] = 1 + end for + for i=1 to n do + atom mx = m[i][i] + integer row = i + for j=i to n do + if m[j][i]>mx then + mx = m[j][i] + row = j + end if + end for + if i!=row then + {im[i],im[row]} = {im[row],im[i]} + end if + end for + return im +end function + +function lu(sequence a) + integer n = length(a) + sequence l = repeat(repeat(0,n),n), + u = l, + p = pivotize(a), + a2 = matrix_mul(p,a) + + for j=1 to n do + l[j][j] = 1.0 + for i=1 to j do + atom sum1 = 0.0 + for k=1 to i do + sum1 += u[k][j] * l[i][k] + end for + u[i][j] = a2[i][j] - sum1 + end for + for i=j+1 to n do + atom sum2 = 0.0 + for k=1 to j do + sum2 += u[k][j] * l[i][k] + end for + l[i][j] = (a2[i][j] - sum2) / u[j][j] + end for + end for + return {a, l, u, p} +end function + +constant a = {{{1, 3, 5}, + {2, 4, 7}, + {1, 1, 0}}, + {{11, 9,24, 2}, + { 1, 5, 2, 6}, + { 3,17,18, 1}, + { 2, 5, 7, 1}}} +for i=1 to length(a) do + ?"== a,l,u,p: ==" + pp(lu(a[i]),{pp_Nest,2,pp_Pause,0}) +end for diff --git a/Task/LZW-compression/JavaScript/lzw-compression.js b/Task/LZW-compression/JavaScript/lzw-compression-1.js similarity index 100% rename from Task/LZW-compression/JavaScript/lzw-compression.js rename to Task/LZW-compression/JavaScript/lzw-compression-1.js diff --git a/Task/LZW-compression/JavaScript/lzw-compression-2.js b/Task/LZW-compression/JavaScript/lzw-compression-2.js new file mode 100644 index 0000000000..a53725affe --- /dev/null +++ b/Task/LZW-compression/JavaScript/lzw-compression-2.js @@ -0,0 +1,110 @@ +'use strict'; +/** + Namespace for LZW compression and decompression. + Methods: + LZW.compress(uncompressed) + LZW.decompress(compressed) +*/ +class LZW +{ + /** + Perform the LZW compression + uncompressed - String. The string on which to perform the compression. + */ + static compress(uncompressed) + { + // Initialize dictionary + let dictionary = {}; + for (let i = 0; i < 256; i++) + { + dictionary[String.fromCharCode(i)] = i; + } + + let word = ''; + let result = []; + let dictSize = 256; + + for (let i = 0, len = uncompressed.length; i < len; i++) + { + let curChar = uncompressed[i]; + let joinedWord = word + curChar; + + // Do not use dictionary[joinedWord] because javascript objects + // will return values for myObject['toString'] + if (dictionary.hasOwnProperty(joinedWord)) + { + word = joinedWord; + } + else + { + result.push(dictionary[word]); + // Add wc to the dictionary. + dictionary[joinedWord] = dictSize++; + word = curChar; + } + } + + if (word !== '') + { + result.push(dictionary[word]); + } + + return result; + } + + /** + Decompress LZW array generated by LZW.compress() + compressed - Array. The array that holds LZW compressed data. + */ + static decompress(compressed) + { + // Initialize Dictionary (inverse of compress) + let dictionary = {}; + for (let i = 0; i < 256; i++) + { + dictionary[i] = String.fromCharCode(i); + } + + let word = String.fromCharCode(compressed[0]); + let result = word; + let entry = ''; + let dictSize = 256; + + for (let i = 1, len = compressed.length; i < len; i++) + { + let curNumber = compressed[i]; + + if (dictionary[curNumber] !== undefined) + { + entry = dictionary[curNumber]; + } + else + { + if (curNumber === dictSize) + { + entry = word + word[0]; + } + else + { + throw 'Error in processing'; + return null; + } + } + + result += entry; + + // Add word + entry[0] to dictionary + dictionary[dictSize++] = word + entry[0]; + + word = entry; + } + + return result; + } +} + +let comp = LZW.compress('TOBEORNOTTOBEORTOBEORNOT'); +let decomp = LZW.decompress(comp); + +console.log(`${comp} +${decomp}`); diff --git a/Task/LZW-compression/Ring/lzw-compression.ring b/Task/LZW-compression/Ring/lzw-compression.ring index 3faae6e99d..78a8df0e85 100644 --- a/Task/LZW-compression/Ring/lzw-compression.ring +++ b/Task/LZW-compression/Ring/lzw-compression.ring @@ -1,7 +1,4 @@ # Project : LZW compression -# Date : 2018/04/07 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : plaintext = "TOBEORNOTTOBEORTOBEORNOT" result = [] diff --git a/Task/Langtons-ant/Befunge/langtons-ant.bf b/Task/Langtons-ant/Befunge/langtons-ant.bf new file mode 100644 index 0000000000..057c02be49 --- /dev/null +++ b/Task/Langtons-ant/Befunge/langtons-ant.bf @@ -0,0 +1,5 @@ +"22222 -"*>>>1-:0\:"P"%\v>\7%1g48*-/2%3*48*+,1+:20g`!v1g01+55p03:_$$$>@ +!"$(0@`vp00_^#!:p+7/"P"<<^g+7/*5"p"\%"P"/7::+g03*"d":_$,1+>:40g`!^1g03< +_::10g\v>00g+4%:00p::3\`\1-*50g+50p:2\-\0`*+::0\`\"c"`+50g:0\`\"c"`++#^ +-*84g1>-:0`!*+10p::20g\-:0`*+20p:"d"*50g::30g\-:0`!*+30p::40g\-:0`*+4 diff --git a/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring b/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring index 06d020eaf3..370158738f 100644 --- a/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring +++ b/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring @@ -1,7 +1,4 @@ # Project : Last letter-first letter -# Date : 2017/12/30 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : ready = [] names = ["audino", "bagon", "baltoy", "banette", diff --git a/Task/Leap-year/Dart/leap-year.dart b/Task/Leap-year/Dart/leap-year.dart new file mode 100644 index 0000000000..d94d3dd54b --- /dev/null +++ b/Task/Leap-year/Dart/leap-year.dart @@ -0,0 +1,5 @@ +class Leap { + bool leapYear(num year) { + return (year % 400 == 0) || (( year % 100 != 0) && (year % 4 == 0)); + } +} diff --git a/Task/Least-common-multiple/Befunge/least-common-multiple.bf b/Task/Least-common-multiple/Befunge/least-common-multiple.bf new file mode 100644 index 0000000000..cd4223e20a --- /dev/null +++ b/Task/Least-common-multiple/Befunge/least-common-multiple.bf @@ -0,0 +1,4 @@ +&>:0`2*1-*:&>:#@!#._:0`2*1v +>28*:*:**+:28*>:*:*/\:vv*-< +|<:%/*:*:*82\%*:*:*82<<>28v +>$/28*:*:*/*.@^82::+**:*:*< diff --git a/Task/Levenshtein-distance/Ring/levenshtein-distance.ring b/Task/Levenshtein-distance/Ring/levenshtein-distance.ring index 7b941d8855..01e9653bc6 100644 --- a/Task/Levenshtein-distance/Ring/levenshtein-distance.ring +++ b/Task/Levenshtein-distance/Ring/levenshtein-distance.ring @@ -1,7 +1,4 @@ # Project : Levenshtein distance -# Date : 2017/12/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" see "" + "distance(kitten, sitting) = " + levenshteindistance("kitten", "sitting") + nl diff --git a/Task/Levenshtein-distance/Scala/levenshtein-distance-1.scala b/Task/Levenshtein-distance/Scala/levenshtein-distance-1.scala new file mode 100644 index 0000000000..c8a78f6dbf --- /dev/null +++ b/Task/Levenshtein-distance/Scala/levenshtein-distance-1.scala @@ -0,0 +1,24 @@ +object Levenshtein0 extends App { + + def distance(s1: String, s2: String): Int = { + val dist = Array.tabulate(s2.length + 1, s1.length + 1) { (j, i) => if (j == 0) i else if (i == 0) j else 0 } + + @inline + def minimum(i: Int*): Int = i.min + + for {j <- dist.indices.tail + i <- dist(0).indices.tail} dist(j)(i) = + if (s2(j - 1) == s1(i - 1)) dist(j - 1)(i - 1) + else minimum(dist(j - 1)(i) + 1, dist(j)(i - 1) + 1, dist(j - 1)(i - 1) + 1) + + dist(s2.length)(s1.length) + } + + def printDistance(s1: String, s2: String) { + println("%s -> %s : %d".format(s1, s2, distance(s1, s2))) + } + + printDistance("kitten", "sitting") + printDistance("rosettacode", "raisethysword") + +} diff --git a/Task/Levenshtein-distance/Scala/levenshtein-distance-2.scala b/Task/Levenshtein-distance/Scala/levenshtein-distance-2.scala new file mode 100644 index 0000000000..d55ab0ed25 --- /dev/null +++ b/Task/Levenshtein-distance/Scala/levenshtein-distance-2.scala @@ -0,0 +1,34 @@ +import scala.collection.mutable +import scala.collection.parallel.ParSeq + +object Levenshtein extends App { + + def printDistance(s1: String, s2: String) = + println(f"$s1%s -> $s2%s : ${levenshtein(s1, s2)(s1.length, s2.length)}%d") + + def levenshtein(s1: String, s2: String): mutable.Map[(Int, Int), Int] = { + val memoizedCosts = mutable.Map[(Int, Int), Int]() + + def lev: ((Int, Int)) => Int = { + case (k1, k2) => + memoizedCosts.getOrElseUpdate((k1, k2), (k1, k2) match { + case (i, 0) => i + case (0, j) => j + case (i, j) => + ParSeq(1 + lev((i - 1, j)), + 1 + lev((i, j - 1)), + lev((i - 1, j - 1)) + + (if (s1(i - 1) != s2(j - 1)) 1 else 0)).min + }) + } + + lev((s1.length, s2.length)) + memoizedCosts + } + + printDistance("kitten", "sitting") + printDistance("rosettacode", "raisethysword") + printDistance("Here's a bunch of words", "to wring out this code") + printDistance("sleep", "fleeting") + +} diff --git a/Task/Levenshtein-distance/Scala/levenshtein-distance.scala b/Task/Levenshtein-distance/Scala/levenshtein-distance.scala deleted file mode 100644 index d1112e6c23..0000000000 --- a/Task/Levenshtein-distance/Scala/levenshtein-distance.scala +++ /dev/null @@ -1,21 +0,0 @@ -import scala.math._ - -object Levenshtein { - def minimum(i1: Int, i2: Int, i3: Int)=min(min(i1, i2), i3) - def distance(s1:String, s2:String)={ - val dist=Array.tabulate(s2.length+1, s1.length+1){(j,i)=>if(j==0) i else if (i==0) j else 0} - - for(j<-1 to s2.length; i<-1 to s1.length) - dist(j)(i)=if(s2(j-1)==s1(i-1)) dist(j-1)(i-1) - else minimum(dist(j-1)(i)+1, dist(j)(i-1)+1, dist(j-1)(i-1)+1) - - dist(s2.length)(s1.length) - } - - def main(args: Array[String]): Unit = { - printDistance("kitten", "sitting") - printDistance("rosettacode", "raisethysword") - } - - def printDistance(s1:String, s2:String)=println("%s -> %s : %d".format(s1, s2, distance(s1, s2))) -} diff --git a/Task/Literals-Floating-point/360-Assembly/literals-floating-point.360 b/Task/Literals-Floating-point/360-Assembly/literals-floating-point.360 new file mode 100644 index 0000000000..ffeaac743f --- /dev/null +++ b/Task/Literals-Floating-point/360-Assembly/literals-floating-point.360 @@ -0,0 +1,15 @@ +XS4 DC E'1.23456E-4' short floating-point + +XDPI DC D'3.141592653589793' long floating-point +XD1 DC D'0' long floating-point +XD2 DC D'1' long floating-point +XD3 DC D'-1' long floating-point +XD4 DC D'1.2345E-4' long floating-point + +XQPI DC L'3.14159265358979323846264338327950' extended + +* short floating-point - 32 bits - 4 bytes : 6 decimal digits +* long floating-point - 64 bits - 8 bytes : 16 decimal digits +* extended floating-point - 128 bits - 16 bytes : 33 decimal digits + +* absolute approximate range: 5e-79 to 7e75 diff --git a/Task/Longest-common-subsequence/Phix/longest-common-subsequence-1.phix b/Task/Longest-common-subsequence/Phix/longest-common-subsequence-1.phix index 3c1049ef41..9c6925f76e 100644 --- a/Task/Longest-common-subsequence/Phix/longest-common-subsequence-1.phix +++ b/Task/Longest-common-subsequence/Phix/longest-common-subsequence-1.phix @@ -4,8 +4,8 @@ sequence res = "" if a[$]=b[$] then res = lcs(a[1..-2],b[1..-2])&a[$] else - sequence l = lcs(a[1..-2],b), - r = lcs(a,b[1..-2]) + sequence l = lcs(a,b[1..-2]), + r = lcs(a[1..-2],b) res = iff(length(l)>length(r)?l:r) end if end if diff --git a/Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-1.cs b/Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-1.cs new file mode 100644 index 0000000000..65a59ff28d --- /dev/null +++ b/Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-1.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +public static class LIS +{ + public static IEnumerable FindRec(IList values, IComparer comparer = null) => + values == null ? throw new ArgumentNullException() : + FindRecImpl(values, Sequence.Empty, 0, comparer ?? Comparer.Default).Reverse(); + + private static Sequence FindRecImpl(IList values, Sequence current, int index, IComparer comparer) { + if (index == values.Count) return current; + if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) + return FindRecImpl(values, current, index + 1, comparer); + return Max( + FindRecImpl(values, current, index + 1, comparer), + FindRecImpl(values, current + values[index], index + 1, comparer) + ); + } + + private static Sequence Max(Sequence a, Sequence b) => a.Length < b.Length ? b : a; + + class Sequence : IEnumerable + { + public static readonly Sequence Empty = new Sequence(default(T), null); + + public Sequence(T value, Sequence tail) + { + Value = value; + Tail = tail; + Length = tail == null ? 0 : tail.Length + 1; + } + + public T Value { get; } + public Sequence Tail { get; } + public int Length { get; } + + public static Sequence operator +(Sequence s, T value) => new Sequence(value, s); + + public IEnumerator GetEnumerator() + { + for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } +} diff --git a/Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-2.cs b/Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-2.cs new file mode 100644 index 0000000000..9441cc1cf4 --- /dev/null +++ b/Task/Longest-increasing-subsequence/C-sharp/longest-increasing-subsequence-2.cs @@ -0,0 +1,22 @@ +public static class LIS +{ + public static T[] Find(IList values, IComparer comparer = null) { + if (values == null) throw new ArgumentNullException(); + if (comparer == null) comparer = Comparer.Default; + var pileTops = new List(); + var pileAssignments = new int[values.Count]; + for (int i = 0; i < values.Count; i++) { + T element = values[i]; + int pile = pileTops.BinarySearch(element, comparer); + if (pile < 0) pile = ~pile; + if (pile == pileTops.Count) pileTops.Add(element); + else pileTops[pile] = element; + pileAssignments[i] = pile; + } + T[] result = new T[pileTops.Count]; + for (int i = pileAssignments.Length - 1, p = pileTops.Count - 1; p >= 0; i--) { + if (pileAssignments[i] == p) result[p--] = values[i]; + } + return result; + } +} diff --git a/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring b/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring index dc5a4c180a..7c1f1814f3 100644 --- a/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring +++ b/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring @@ -1,7 +1,4 @@ # Project : Longest increasing subsequence -# Date : 2017/11/23 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : tests = [[3, 2, 6, 4, 5, 1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]] res = [] diff --git a/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala b/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala index 9d925be7d9..e778ae8d8e 100644 --- a/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala +++ b/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala @@ -1,8 +1,7 @@ object LongestIncreasingSubsequence extends App { val tests = Map( "3,2,6,4,5,1" -> Seq("2,4,5", "3,4,5"), - "0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> - Seq("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15") + "0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> Seq("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15") ) def lis(l: Array[Int]): Seq[Array[Int]] = @@ -28,9 +27,7 @@ object LongestIncreasingSubsequence extends App { val allLongests: Seq[Array[Int]] = lis(asInts(given)) println( s"$given has ${allLongests.length} longest increasing subsequences, e.g. ${ - allLongests.last - .mkString(",") - }") + allLongests.last.mkString(",")}") allLongests.forall(lis => expect.contains(lis.mkString(","))) }) } diff --git a/Task/Longest-string-challenge/Ring/longest-string-challenge.ring b/Task/Longest-string-challenge/Ring/longest-string-challenge.ring index 1cb8a43051..4f18c05fe7 100644 --- a/Task/Longest-string-challenge/Ring/longest-string-challenge.ring +++ b/Task/Longest-string-challenge/Ring/longest-string-challenge.ring @@ -1,7 +1,4 @@ # Project : Longest string challenge -# Date : 2017/10/11 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" diff --git a/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp b/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp index f044799d24..87c1231cd6 100644 --- a/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp +++ b/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp @@ -22,11 +22,9 @@ int main() { std::string laf = "1"; - std::cout << laf << std::endl; + std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); - std::cout << laf << std::endl; + std::cout << laf << '\n'; } - - return 0; } diff --git a/Task/Loops-Break/REBOL/loops-break.rebol b/Task/Loops-Break/REBOL/loops-break.rebol index e036d8e829..420aae0c6e 100644 --- a/Task/Loops-Break/REBOL/loops-break.rebol +++ b/Task/Loops-Break/REBOL/loops-break.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop/Break" - Author: oofoe - Date: 2009-12-19 URL: http://rosettacode.org/wiki/Loop/Break ] diff --git a/Task/Loops-Continue/REBOL/loops-continue.rebol b/Task/Loops-Continue/REBOL/loops-continue.rebol index 5efff26188..216f116666 100644 --- a/Task/Loops-Continue/REBOL/loops-continue.rebol +++ b/Task/Loops-Continue/REBOL/loops-continue.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop/Continue" - Author: oofoe - Date: 2010-01-05 URL: http://rosettacode.org/wiki/Loop/Continue ] diff --git a/Task/Loops-Do-while/ALGOL-60/loops-do-while.alg b/Task/Loops-Do-while/ALGOL-60/loops-do-while.alg new file mode 100644 index 0000000000..36bdb8a14f --- /dev/null +++ b/Task/Loops-Do-while/ALGOL-60/loops-do-while.alg @@ -0,0 +1,10 @@ +'BEGIN' 'COMMENT' Loops DoWhile - Algol60 - 22/06/2018; + 'INTEGER' I; + I:=0; +LOOP: + I:=I+1; + 'IF' I=I'/'6*6 'THEN' 'GOTO' LAB; + OUTINTEGER(1,I); + 'GOTO' LOOP; +LAB: +'END' diff --git a/Task/Loops-Do-while/Fortran/loops-do-while-3.f b/Task/Loops-Do-while/Fortran/loops-do-while-3.f new file mode 100644 index 0000000000..0db110d21c --- /dev/null +++ b/Task/Loops-Do-while/Fortran/loops-do-while-3.f @@ -0,0 +1,7 @@ + IVALUE = 0 + 10 CONTINUE + IVALUE=IVALUE+1 + WRITE(6,301) IVALUE + 301 FORMAT(I5) + IF(MOD(IVALUE,6).NE.0) GOTO 10 + END diff --git a/Task/Loops-Do-while/Fortran/loops-do-while-4.f b/Task/Loops-Do-while/Fortran/loops-do-while-4.f new file mode 100644 index 0000000000..9843449699 --- /dev/null +++ b/Task/Loops-Do-while/Fortran/loops-do-while-4.f @@ -0,0 +1,7 @@ + IVALUE = 0 + 10 IVALUE=IVALUE+1 + WRITE 301,IVALUE + 301 FORMAT(I5) + IF(IVALUE-IVALUE/6*6) 10,20,10 + 20 STOP + END diff --git a/Task/Loops-Do-while/Julia/loops-do-while-1.julia b/Task/Loops-Do-while/Julia/loops-do-while-1.julia index fcdef4f834..f8009edecf 100644 --- a/Task/Loops-Do-while/Julia/loops-do-while-1.julia +++ b/Task/Loops-Do-while/Julia/loops-do-while-1.julia @@ -4,7 +4,7 @@ julia> i = 0 julia> while true println(i) i += 1 - i % 6 == 0 || break + i % 6 == 0 && break end 0 1 diff --git a/Task/Loops-Do-while/REBOL/loops-do-while.rebol b/Task/Loops-Do-while/REBOL/loops-do-while.rebol index 0e3ea41fff..fd24b23f36 100644 --- a/Task/Loops-Do-while/REBOL/loops-do-while.rebol +++ b/Task/Loops-Do-while/REBOL/loops-do-while.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop/While" - Author: oofoe - Date: 2009-12-19 URL: http://rosettacode.org/wiki/Loop/Do_While ] diff --git a/Task/Loops-Downward-for/ALGOL-60/loops-downward-for.alg b/Task/Loops-Downward-for/ALGOL-60/loops-downward-for.alg new file mode 100644 index 0000000000..681dc803ae --- /dev/null +++ b/Task/Loops-Downward-for/ALGOL-60/loops-downward-for.alg @@ -0,0 +1,5 @@ +'BEGIN' 'COMMENT' Loops/Downward for - Algol60 - 23/06/2018; + 'INTEGER' I; + 'FOR' I := 10 'STEP' -1 'UNTIL' 0 'DO' + OUTINTEGER(1,I) +'END' diff --git a/Task/Loops-For-with-a-specified-step/VAX-Assembly/loops-for-with-a-specified-step.vax b/Task/Loops-For-with-a-specified-step/VAX-Assembly/loops-for-with-a-specified-step.vax new file mode 100644 index 0000000000..bcb0e363c1 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/VAX-Assembly/loops-for-with-a-specified-step.vax @@ -0,0 +1,8 @@ + 0000 0000 1 .entry main,0 + 50 D4 0002 2 clrf r0 ;init to 0.0 + 0004 3 loop: + 01 0004 4 nop ;do nothing + FFF9 50 0A 3E 4F 0005 5 acbf #112.0, #1.25, r0, loop ;limit, step + 000B 6 + 04 000B 7 ret + 000C 8 .end main diff --git a/Task/Loops-For/ARM-Assembly/loops-for.arm b/Task/Loops-For/ARM-Assembly/loops-for.arm new file mode 100644 index 0000000000..f21699224b --- /dev/null +++ b/Task/Loops-For/ARM-Assembly/loops-for.arm @@ -0,0 +1,66 @@ +/* ARM assembly Raspberry PI */ +/* program loop1.s */ + +/* Constantes */ +.equ STDOUT, 1 @ Linux output console +.equ EXIT, 1 @ Linux syscall +.equ WRITE, 4 @ Linux syscall +/* Initialized data */ +.data +szMessX: .asciz "X" +szCarriageReturn: .asciz "\n" + +/* UnInitialized data */ +.bss + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* saves 2 registers */ + + mov r2,#0 @ counter loop 1 +1: @ loop start 1 + mov r1,#0 @ counter loop 2 +2: @ loop start 2 + ldr r0,iAdrszMessX + bl affichageMess + add r1,#1 @ r1 + 1 + cmp r1,r2 @ compare r1 r2 + ble 2b @ loop label 2 before + ldr r0,iAdrszCarriageReturn + bl affichageMess + add r2,#1 @ r2 + 1 + cmp r2,#5 @ for five loop + blt 1b @ loop label 1 before + + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call + +iAdrszMessX: .int szMessX +iAdrszCarriageReturn: .int szCarriageReturn +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registers */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ diff --git a/Task/Loops-Foreach/REBOL/loops-foreach.rebol b/Task/Loops-Foreach/REBOL/loops-foreach.rebol index 51926ad6fc..20666e1f96 100644 --- a/Task/Loops-Foreach/REBOL/loops-foreach.rebol +++ b/Task/Loops-Foreach/REBOL/loops-foreach.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop/Foreach" - Author: oofoe - Date: 2009-12-19 URL: http://rosettacode.org/wiki/Loop/Foreach ] diff --git a/Task/Loops-Infinite/ALGOL-60/loops-infinite.alg b/Task/Loops-Infinite/ALGOL-60/loops-infinite.alg new file mode 100644 index 0000000000..4a6b5886dc --- /dev/null +++ b/Task/Loops-Infinite/ALGOL-60/loops-infinite.alg @@ -0,0 +1,5 @@ +'BEGIN' 'COMMENT' Loops/Infinite - Algol60 - 23/06/2018; + 'INTEGER' I; + 'FOR' I := 1 'STEP' 0 'UNTIL' 2 'DO' + OUTSTRING(1,'('SPAM')') +'END' diff --git a/Task/Loops-Infinite/C/loops-infinite-5.c b/Task/Loops-Infinite/C/loops-infinite-5.c index f29685d222..9961b54d96 100644 --- a/Task/Loops-Infinite/C/loops-infinite-5.c +++ b/Task/Loops-Infinite/C/loops-infinite-5.c @@ -1,3 +1,2 @@ -/*Abhishek Ghosh, 24th October 2017*/ spam: puts("SPAM"); goto spam; diff --git a/Task/Loops-Infinite/VAX-Assembly/loops-infinite.vax b/Task/Loops-Infinite/VAX-Assembly/loops-infinite.vax new file mode 100644 index 0000000000..5982778972 --- /dev/null +++ b/Task/Loops-Infinite/VAX-Assembly/loops-infinite.vax @@ -0,0 +1,10 @@ + 0000 0000 1 .entry main,0 + 4D415053 8F DD 0002 2 pushl #^a"SPAM" ;string on stack + 5E DD 0008 3 pushl sp ;reference to string + 04 DD 000A 4 pushl #4 ;+length = descriptor + 000C 5 loop: + 5E DD 000C 6 pushl sp ;descriptor by reference + 00000000'GF 01 FB 000E 7 calls #1, g^lib$put_output ;show message + F5 11 0015 8 brb loop ;forever + 0017 9 + 0017 10 .end main diff --git a/Task/Loops-N-plus-one-half/REBOL/loops-n-plus-one-half.rebol b/Task/Loops-N-plus-one-half/REBOL/loops-n-plus-one-half.rebol index ae8a5cb72c..9f5d37fe97 100644 --- a/Task/Loops-N-plus-one-half/REBOL/loops-n-plus-one-half.rebol +++ b/Task/Loops-N-plus-one-half/REBOL/loops-n-plus-one-half.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop Plus Half" - Date: 2009-12-16 - Author: oofoe URL: http://rosettacode.org/wiki/Loop/n_plus_one_half ] diff --git a/Task/Loops-Nested/REBOL/loops-nested.rebol b/Task/Loops-Nested/REBOL/loops-nested.rebol index bab3239eaa..0e0c58920f 100644 --- a/Task/Loops-Nested/REBOL/loops-nested.rebol +++ b/Task/Loops-Nested/REBOL/loops-nested.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop/Nested" - Author: oofoe - Date: 2010-01-05 URL: http://rosettacode.org/wiki/Loop/Nested ] diff --git a/Task/Loops-While/K/loops-while.k b/Task/Loops-While/K/loops-while.k new file mode 100644 index 0000000000..cfa6796503 --- /dev/null +++ b/Task/Loops-While/K/loops-while.k @@ -0,0 +1 @@ +{while[x>0; \echo x; x%:2]} 1024 diff --git a/Task/Loops-While/REBOL/loops-while.rebol b/Task/Loops-While/REBOL/loops-while.rebol index 698a3dceee..8c7f301587 100644 --- a/Task/Loops-While/REBOL/loops-while.rebol +++ b/Task/Loops-While/REBOL/loops-while.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Loop/While" - Author: oofoe - Date: 2009-12-19 URL: http://rosettacode.org/wiki/Loop/While ] diff --git a/Task/Ludic-numbers/Ring/ludic-numbers.ring b/Task/Ludic-numbers/Ring/ludic-numbers.ring index da6eb298e8..3befb49cf0 100644 --- a/Task/Ludic-numbers/Ring/ludic-numbers.ring +++ b/Task/Ludic-numbers/Ring/ludic-numbers.ring @@ -1,7 +1,4 @@ # Project : Ludic numbers -# Date : 2017/11/07 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : ludic = list(300) resludic = [] diff --git a/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon b/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon index 53248c8037..a5f2d5521c 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon +++ b/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon @@ -1,27 +1,27 @@ shared void run() { - value numbers = "49927398716 - 49927398717 - 1234567812345678 - 1234567812345670"; - for(number in numbers.lines) { - print("``number`` passes? ``luhn(number)``"); - } + value numbers = "49927398716 + 49927398717 + 1234567812345678 + 1234567812345670"; + for(number in numbers.lines) { + print("``number`` passes? ``luhn(number)``"); + } } shared Boolean luhn(String number) { - value digits = number - .reversed - .map(Character.string) - .map(parseInteger) - .coalesced; - value s1 = sum {0, *digits.by(2)}; - value s2 = sum { - 0, - *digits - .skip(1) - .by(2) - .map(curry(times)(2)) - .map((Integer element) => element / 10 + element % 10) - }; - return (s1 + s2) % 10 == 0; + value digits = number + .reversed + .map(Character.string) + .map(Integer.parse) + .narrow(); + value s1 = sum { 0, *digits.by(2) }; + value s2 = sum { + 0, + *digits + .skip(1) + .by(2) + .map(curry(times)(2)) + .map((Integer element) => element / 10 + element % 10) + }; + return (s1 + s2) % 10 == 0; } diff --git a/Task/Luhn-test-of-credit-card-numbers/Factor/luhn-test-of-credit-card-numbers.factor b/Task/Luhn-test-of-credit-card-numbers/Factor/luhn-test-of-credit-card-numbers.factor index aaf424489a..b03b6a5412 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Factor/luhn-test-of-credit-card-numbers.factor +++ b/Task/Luhn-test-of-credit-card-numbers/Factor/luhn-test-of-credit-card-numbers.factor @@ -8,7 +8,7 @@ IN: luhn while drop ; : luhn-digit ( n -- n ) - reversed-digits dup length iota [ + reversed-digits dup length [ 2dup swap nth swap odd? [ 2 * 10 /mod + ] when ] map sum 10 mod diff --git a/Task/Luhn-test-of-credit-card-numbers/Shen/luhn-test-of-credit-card-numbers.shen b/Task/Luhn-test-of-credit-card-numbers/Shen/luhn-test-of-credit-card-numbers.shen new file mode 100644 index 0000000000..dbe1984bb5 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Shen/luhn-test-of-credit-card-numbers.shen @@ -0,0 +1,20 @@ +(define mapi + _ _ [] -> [] + F N [X | Xs] -> [(F N X) | (mapi F (+ N 1) Xs)]) + +(define double + X -> (let Y (* 2 X) (if (> Y 9) (- Y 9) Y))) + +(define luhn? + Number -> + (let Exploded (explode Number) + Digits (map (/. H (- (string->n H) 48)) Exploded) + Reversed (reverse Digits) + Doubled (mapi (/. N X (if (= 1 (shen.mod N 2)) (double X) X)) 0 Reversed) + Summed (sum Doubled) + Modded (shen.mod Summed 10) + (= 0 Modded))) + +"Expected: [true false false true]" + +(map (function luhn?) ["49927398716" "49927398717" "1234567812345678" "1234567812345670"]) diff --git a/Task/MD4/Mathematica/md4.math b/Task/MD4/Mathematica/md4.math new file mode 100644 index 0000000000..937f51b929 --- /dev/null +++ b/Task/MD4/Mathematica/md4.math @@ -0,0 +1 @@ +Hash["Rosetta Code", "MD4", "HexString"] diff --git a/Task/MD4/Phix/md4.phix b/Task/MD4/Phix/md4.phix new file mode 100644 index 0000000000..164030ad9a --- /dev/null +++ b/Task/MD4/Phix/md4.phix @@ -0,0 +1,77 @@ +-- +-- demo\rosetta\md4.exw +-- ==================== +-- +function r32(atom a) + if a<0 then a+=#100000000 end if + return remainder(a,#100000000) +end function + +function rol(atom word, integer bits) +-- left rotate the bits of a 32-bit number by the specified number of bits + word = r32(word) -- trim to a 32-bit uint again + return r32(word*power(2,bits))+floor(word/power(2,32-bits)) +end function + +function f(atom x,y,z) + return or_bits(and_bits(x,y),and_bits(not_bits(x),z)) +end function + +function g(atom x,y,z) + return or_all({r32(and_bits(x,y)),and_bits(x,z),and_bits(y,z)}) +end function + +function h(atom x,y,z) + return xor_bits(r32(xor_bits(x,y)),z) +end function + +function md4(sequence data) + integer bytes_to_add = 64-remainder(length(data)+9,64) + if bytes_to_add=64 then bytes_to_add = 0 end if + data = dataP&repeat(0,bytes_to_add)& + int_to_bytes(length(data)*8,8) + + atom a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476 + + atom m64 = allocate(64,true) + integer i + for x=1 to length(data)-1 by 64 do + poke(m64,data[x..x+63]) + sequence z = peek4u({m64,16}) + atom a2 = a, b2 = b, c2 = c, d2 = d + for i=0 to 12 by 4 do + a = rol(a + f(b, c, d) + z[i+1], 3) + d = rol(d + f(a, b, c) + z[i+2], 7) + c = rol(c + f(d, a, b) + z[i+3], 11) + b = rol(b + f(c, d, a) + z[i+4], 19) + end for + for i=1 to 4 do + a = rol(a + g(b, c, d) + z[i+0] + 0x5a827999, 3) + d = rol(d + g(a, b, c) + z[i+4] + 0x5a827999, 5) + c = rol(c + g(d, a, b) + z[i+8] + 0x5a827999, 9) + b = rol(b + g(c, d, a) + z[i+12] + 0x5a827999, 13) + end for + for j=1 to 4 do + i = {1, 3, 2, 4}[j] + a = rol(a + h(b, c, d) + z[i+0] + 0x6ed9eba1, 3) + d = rol(d + h(a, b, c) + z[i+8] + 0x6ed9eba1, 9) + c = rol(c + h(d, a, b) + z[i+4] + 0x6ed9eba1, 11) + b = rol(b + h(c, d, a) + z[i+12] + 0x6ed9eba1, 15) + end for + a = r32(a+a2) + b = r32(b+b2) + c = r32(c+c2) + d = r32(d+d2) + end for + poke4(m64,{a,b,c,d}) + return peek({m64,16}) +end function + +function hexify(sequence s) + for i=1 to length(s) do + s[i] = sprintf("%02X",s[i]) + end for + return join(s,"") +end function + +?hexify(md4("Rosetta Code")) diff --git a/Task/MD5/Mathematica/md5-1.math b/Task/MD5/Mathematica/md5-1.math index c434f8c401..a3b07c8adf 100644 --- a/Task/MD5/Mathematica/md5-1.math +++ b/Task/MD5/Mathematica/md5-1.math @@ -1,7 +1 @@ - StringHash[string_String]:=Module[{stream=OpenWrite[],file,hash}, - WriteString[stream,string]; - file=Close[stream]; - hash=FileHash[file,"MD5"]; - DeleteFile[file]; - hash - ] + Hash["The quick brown fox jumped over the lazy dog's back","MD5","HexString"] diff --git a/Task/MD5/Mathematica/md5-2.math b/Task/MD5/Mathematica/md5-2.math index 433d28cab3..8d632f9056 100644 --- a/Task/MD5/Mathematica/md5-2.math +++ b/Task/MD5/Mathematica/md5-2.math @@ -1 +1 @@ - StringHash["The quick brown fox jumped over the lazy dog's back"] // BaseForm[#, 16] & + e38ca1d920c4b8b8d3946b2c72f01680 diff --git a/Task/Main-step-of-GOST-28147-89/Phix/main-step-of-gost-28147-89.phix b/Task/Main-step-of-GOST-28147-89/Phix/main-step-of-gost-28147-89.phix new file mode 100644 index 0000000000..a60cbb0d7a --- /dev/null +++ b/Task/Main-step-of-GOST-28147-89/Phix/main-step-of-gost-28147-89.phix @@ -0,0 +1,40 @@ +constant cbrf = { + { 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3}, + {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9}, + { 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11}, + { 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3}, + { 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2}, + { 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14}, + {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12}, + { 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12}} + +function generate(integer k) + sequence res = repeat(0,256) + for i=1 to length(res) do + res[i] = or_bits(cbrf[k][floor((i-1)/16)+1]*16,cbrf[k-1][and_bits(i-1,#F)+1]) + end for + return res +end function + +constant k87 = generate(8), + k65 = generate(6), + k43 = generate(4), + k21 = generate(2) + +function r32(atom a) + if a<0 then a+=#100000000 end if + return remainder(a,#100000000) +end function + +function mainstep(sequence input, atom key) + atom s = r32(input[1]+key) + s = or_all({k87[and_bits(floor(s/#1000000),#FF)+1]*#1000000, + k65[and_bits(floor(s/#10000),#FF)+1]*#10000, + k43[and_bits(floor(s/#100),#FF)+1]*#100, + k21[and_bits(s,#FF)+1]}) + s = r32(s*power(2,11))+floor(s/power(2,32-11)) + s = xor_bits(s,input[2]) + return {s,input[1]} +end function + +printf(1,"%08x %08x\n",mainstep({#043B0421, #04320430}, #E2C104F9)) diff --git a/Task/Mandelbrot-set/Mathematica/mandelbrot-set-3.math b/Task/Mandelbrot-set/Mathematica/mandelbrot-set-3.math new file mode 100644 index 0000000000..47fe4879ad --- /dev/null +++ b/Task/Mandelbrot-set/Mathematica/mandelbrot-set-3.math @@ -0,0 +1 @@ +MandelbrotSetPlot[] diff --git a/Task/Map-range/Ring/map-range.ring b/Task/Map-range/Ring/map-range.ring index 280bcede95..b6de87bad7 100644 --- a/Task/Map-range/Ring/map-range.ring +++ b/Task/Map-range/Ring/map-range.ring @@ -1,7 +1,4 @@ # Project : Map range -# Date : 2017/09/20 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(1) al = 0 diff --git a/Task/Matrix-multiplication/Ol/matrix-multiplication.ol b/Task/Matrix-multiplication/Ol/matrix-multiplication.ol new file mode 100644 index 0000000000..3829d5bfb8 --- /dev/null +++ b/Task/Matrix-multiplication/Ol/matrix-multiplication.ol @@ -0,0 +1,8 @@ +(define (matrix-multiply matrix1 matrix2) +(map + (lambda (row) + (apply map + (lambda column + (apply + (map * row column))) + matrix2)) + matrix1)) 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 index e5e1bfde2d..a9a7221d92 100644 --- a/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro +++ b/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro @@ -1,30 +1,28 @@ -fun solve(tri): - var tri = tri - while tri.len > 1: - let t0 = tri.pop() - for i, t in enumerate(tri[!1]): - tri[!1, i] = max(t0[i], t0[i]) + t - tri[1, 1] +fun maxpathsum(t): #: Array{Array{I}} + let a = val t + for i in a.length-1..-1..1, c in linearindices a[r]: + a[r, c] += max(a[r+1, c], a[r=1, c+1]) + return a[1, 1] -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 -""" +let test = [ + [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.split().map(int) +@print maxpathsum test diff --git a/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring b/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring index 0d9bf6d299..ba17a268b3 100644 --- a/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring +++ b/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring @@ -1,7 +1,4 @@ # Project : Maximum triangle path sum -# Date : 2018/02/06 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "stdlib.ring" ln = list(19) diff --git a/Task/Menu/REBOL/menu.rebol b/Task/Menu/REBOL/menu.rebol index 8fc00f851b..ba3a631351 100644 --- a/Task/Menu/REBOL/menu.rebol +++ b/Task/Menu/REBOL/menu.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Text Menu" - Author: oofoe - Date: 2009-12-08 URL: http://rosettacode.org/wiki/Select ] diff --git a/Task/Metaprogramming/Forth/metaprogramming-1.fth b/Task/Metaprogramming/Forth/metaprogramming-1.fth new file mode 100644 index 0000000000..59ce72f7ad --- /dev/null +++ b/Task/Metaprogramming/Forth/metaprogramming-1.fth @@ -0,0 +1,35 @@ +\ BRANCH and LOOP COMPILERS + +\ branch offset computation operators +: AHEAD ( -- addr) HERE 0 , ; +: BACK ( addr -- ) HERE - , ; +: RESOLVE ( addr -- ) HERE OVER - SWAP ! ; + +\ LEAVE stack is called L0. It is initialized by QUIT. +: >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; +: L> ( -- x ) ( L: x -- ) LP @ @ -2 LP +! ; + +\ finite loop compilers +: DO ( -- ) POSTPONE HERE 0 >L 3 ; IMMEDIATE +: ?DO ( -- ) POSTPONE HERE 0 >L 3 ; IMMEDIATE +: LEAVE ( -- ) ( L: -- addr ) + POSTPONE UNLOOP POSTPONE BRANCH AHEAD >L ; IMMEDIATE + +: RAKE ( -- ) ( L: 0 a1 a2 .. aN -- ) + BEGIN L> ?DUP WHILE RESOLVE REPEAT ; IMMEDIATE + +: LOOP ( -- ) 3 ?PAIRS POSTPONE BACK RAKE ; IMMEDIATE +: +LOOP ( -- ) 3 ?PAIRS POSTPONE <+LOOP> BACK RAKE ; IMMEDIATE + +\ conditional branches +: IF ( ? -- ) POSTPONE ?BRANCH AHEAD 2 ; IMMEDIATE +: THEN ( -- ) ?COMP 2 ?PAIRS RESOLVE ; IMMEDIATE +: ELSE ( -- ) 2 ?PAIRS POSTPONE BRANCH AHEAD SWAP 2 + POSTPONE THEN 2 ; IMMEDIATE + +\ infinite loop compilers +: BEGIN ( -- addr n) ?COMP HERE 1 ; IMMEDIATE +: AGAIN ( -- ) 1 ?PAIRS POSTPONE BRANCH BACK ; IMMEDIATE +: UNTIL ( ? -- ) 1 ?PAIRS POSTPONE ?BRANCH BACK ; IMMEDIATE +: WHILE ( ? -- ) POSTPONE IF 2+ ; IMMEDIATE +: REPEAT ( -- ) 2>R POSTPONE AGAIN 2R> 2- POSTPONE THEN ; IMMEDIATE diff --git a/Task/Metaprogramming/Forth/metaprogramming-2.fth b/Task/Metaprogramming/Forth/metaprogramming-2.fth new file mode 100644 index 0000000000..cb42efa99c --- /dev/null +++ b/Task/Metaprogramming/Forth/metaprogramming-2.fth @@ -0,0 +1,10 @@ + : CHARSET [CHAR] ~ [CHAR] ! DO I EMIT LOOP ; + +: >DIGIT ( n -- c) DUP 9 > IF 7 + THEN [CHAR] 0 + ; + +: -TRAILING ( adr len -- adr len') \ remove trailing blanks (spaces) + BEGIN + 2DUP + 1- C@ BL = \ test if last char = blank + WHILE + 1- \ dec. length + REPEAT ; diff --git a/Task/Metronome/Phix/metronome.phix b/Task/Metronome/Phix/metronome.phix new file mode 100644 index 0000000000..ea0ab8c0ac --- /dev/null +++ b/Task/Metronome/Phix/metronome.phix @@ -0,0 +1,35 @@ +integer tempo = 120, -- beats per minute (max 800) + measure = 4, -- beats per bar + runsecs = 5 -- total run time (rounded up to whole bars) + +integer low_freq = #200, low_duration = 20, + high_freq = #400, high_duration = 20 + +atom k32=0, xBeep +atom t0 = time(), count = 0 +atom duration = 60/tempo, + next = time()+duration + +while time()=1 and rx<=4 then + for cx=col-1 to col+1 do + if cx>=1 and cx<=6 then + if data[rx][cx]!=9 then + data[rx][cx] += 1 + end if + end if + end for + end if + end for + exit + end if + end while + end for + printf(1,"%d mines planted\n",mines) + row = 0 +end procedure + +procedure clear_cell(integer row, col, drc) + board[row*8+4+col] = iff(drc?drc+'0':' ') + cleared += 1 + if drc=0 then + for rx=row-1 to row+1 do + if rx>=1 and rx<=4 then + for cx=col-1 to col+1 do + if cx>=1 and cx<=6 then + drc = data[rx][cx] + if drc!=9 + and board[rx*8+4+cx]='.' then + clear_cell(rx,cx,drc) + end if + end if + end for + end if + end for + end if +end procedure + +function make_move() + integer brc = row*8+4+col + if flag then + if board[brc]='.' then + board[brc] = '?' + flagged += 1 + end if + else + integer drc = data[row][col] + if drc=9 then + board[brc] = 'X' + puts(1,"\n\n***BOOM!***") + return true + end if + if find(board[brc],".?") then + clear_cell(row,col,drc) + end if + end if + row = 0 + flag = false + -- nb: flagged and cleared may be wrong following incorrect input. + if flagged=mines + or cleared=6*4-mines then + puts(1,"\n\n***You Win!***") + return true + end if + return false -- no "BOOM" yet! +end function + +procedure disclose() + for row=1 to 4 do + for col=1 to 6 do + if data[row][col]=9 then + integer bdx = row*8+4+col, + bch = board[bdx] + if bch='.' then + bch = '*' + elsif bch='?' then + bch = '+' + elsif bch!='X' then + ?9/0 + end if + board[bdx] = bch + end if + end for + end for +end procedure + +plant_mines() +while 1 do + if not flag and row=0 then + puts(1,board) + puts(1,prompt) + end if + integer ch = upper(getc(0)) + puts(1,ch) + if ch='Q' then exit end if + if ch='?' then + puts(1,help) + elsif ch='F' then + flag = true + elsif ch>='A' + and ch<='D' then + row = ch-'@' + elsif ch>='1' + and ch<='6' then + col = ch-'0' + if make_move() then exit end if + else + printf(1,"\n\nunrecognised:%c\n\n",ch) + flag = false + row = 0 + end if +end while +disclose() +puts(1,board&"game over\n\n") +{} = wait_key() diff --git a/Task/Modular-inverse/Ada/modular-inverse.ada b/Task/Modular-inverse/Ada/modular-inverse.ada index d1baf768e9..0f941c9d0b 100644 --- a/Task/Modular-inverse/Ada/modular-inverse.ada +++ b/Task/Modular-inverse/Ada/modular-inverse.ada @@ -5,7 +5,8 @@ procedure modular_inverse is 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)); + 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; diff --git a/Task/Modular-inverse/FreeBASIC/modular-inverse.freebasic b/Task/Modular-inverse/FreeBASIC/modular-inverse.freebasic new file mode 100644 index 0000000000..dcee0be3a5 --- /dev/null +++ b/Task/Modular-inverse/FreeBASIC/modular-inverse.freebasic @@ -0,0 +1,75 @@ +' version 10-07-2018 +' compile with: fbc -s console + +Type ext_euclid + Dim As Integer a, b +End Type + +' "Table method" aka "The Magic Box" +Function magic_box(x As Integer, y As Integer) As ext_euclid + + Dim As Integer a(1 To 128), b(1 To 128), d(1 To 128), k(1 To 128) + + a(1) = 1 : b(1) = 0 : d(1) = x + a(2) = 0 : b(2) = 1 : d(2) = y : k(2) = x \ y + + Dim As Integer i = 2 + + While Abs(d(i)) <> 1 + i += 1 + a(i) = a(i -2) - k(i -1) * a(i -1) + b(i) = b(i -2) - k(i -1) * b(i -1) + d(i) = d(i -2) Mod d(i -1) + k(i) = d(i -1) \ d(i) + 'Print a(i),b(i),d(i),k(i) + If d(i -1) Mod d(i) = 0 Then Exit While + Wend + + If d(i) = -1 Then ' -1 * (ab + by) = -1 * -1 ==> -ab -by = 1 + a(i) = -a(i) + b(i) = -b(i) + End If + + Function = Type( a(i), b(i) ) + +End Function +' ------=< MAIN >=------ + +Dim As Integer x, y, gcd +Dim As ext_euclid result + +Do + Read x, y + If x = 0 AndAlso y = 0 Then Exit Do + result = magic_box(x, y) + With result + gcd = .a * x + .b * y + Print "a * "; Str(x); " + b * "; Str(y); + Print " = GCD("; Str(x); ", "; Str(y); ") ="; gcd + If gcd > 1 Then + Print "No solution, numbers are not coprime" + Else + Print "a = "; .a; ", b = ";.b + Print "The Modular inverse of "; x; " modulo "; y; " = "; + While .a < 0 : .a += IIf(y > 0, y, -y) : Wend + Print .a + 'Print "The Modular inverse of "; y; " modulo "; x; " = "; + 'While .b < 0 : .b += IIf(x > 0, x, -x) : Wend + 'Print .b + End if + End With + Print +Loop + +Data 42, 2017 +Data 40, 1 +Data 52, -217 +Data -486, 217 +Data 40, 2018 +Data 0, 0 + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Morse-code/Forth/morse-code.fth b/Task/Morse-code/Forth/morse-code.fth index 29bc851eef..4925d1a1c8 100644 --- a/Task/Morse-code/Forth/morse-code.fth +++ b/Task/Morse-code/Forth/morse-code.fth @@ -50,10 +50,9 @@ DECIMAL morse-emit \ send the morse code loop ; -NAMESPACE MORSE \ prevent name conflicts with letters and numbers +VOCABULARY MORSE \ prevent name conflicts with letters and numbers MORSE DEFINITIONS \ the following definitions go into MORSE namespace - : . ( -- ) sound dit_dur silence off_dur ; : - ( -- ) sound dah_dur silence off_dur ; diff --git a/Task/Mouse-position/Factor/mouse-position.factor b/Task/Mouse-position/Factor/mouse-position.factor index 27e2b0eca7..fa7e5d1c8d 100644 --- a/Task/Mouse-position/Factor/mouse-position.factor +++ b/Task/Mouse-position/Factor/mouse-position.factor @@ -1,5 +1,5 @@ : replace-text ( button text -- ) - [ drop children>> pop drop ] [ >label add-gadget drop ] 2bi; + [ drop children>> pop drop ] [ >label add-gadget drop ] 2bi ; : present-locations ( loc1 loc2 -- string ) [ first2 [ number>string ] bi@ "," glue diff --git a/Task/Mouse-position/Python/mouse-position-2.py b/Task/Mouse-position/Python/mouse-position-2.py index 0d4c5491ca..97c8707ba7 100644 --- a/Task/Mouse-position/Python/mouse-position-2.py +++ b/Task/Mouse-position/Python/mouse-position-2.py @@ -1,5 +1,5 @@ #simple way of ,get cursor xy data -#niwantha33@gmail.com + from Tkinter import * win=Tk() win.geometry("200x300") diff --git a/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring b/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring index 7822d0bf89..08956b4a25 100644 --- a/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring +++ b/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring @@ -1,7 +1,4 @@ # Project : Move-to-front algorithm -# Date : 2018/01/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : test("broood") test("bananaaa") diff --git a/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js b/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js index 99dcaf64be..5862c530ab 100644 --- a/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js +++ b/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js @@ -1,5 +1,13 @@ (() => { + // main :: () -> IO String + const main = () => + wikiTable( + multTable(1, 12), + true, + 'text-align:center;width:33em;height:33em;table-layout:fixed;' + ); + // multTable :: Int -> Int -> [[String]] const multTable = (m, n) => { const xs = enumFromToInt(m, n); @@ -17,14 +25,6 @@ ]; }; - // main :: () -> IO String - const main = () => { - return wikiTable( - multTable(1, 12), true, - 'text-align:center;width:33em;height:33em;table-layout:fixed;' - ); - }; - // GENERIC FUNCTIONS ----------------------------------------------------- // Tuple (,) :: a -> b -> (a, b) @@ -72,7 +72,7 @@ length: n }, () => x); - // FORMATTING ------------------------------------------------------------- + // FORMATTING ------------------------------------------------------------ // wikiTable :: [[a]] -> Bool -> String -> String const wikiTable = (rows, blnHeader, style) => diff --git a/Task/Multiplication-tables/REBOL/multiplication-tables.rebol b/Task/Multiplication-tables/REBOL/multiplication-tables.rebol index c8c8f6266b..102f412bd2 100644 --- a/Task/Multiplication-tables/REBOL/multiplication-tables.rebol +++ b/Task/Multiplication-tables/REBOL/multiplication-tables.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "12x12 Multiplication Table" - Author: oofoe - Date: 2009-12-26 URL: http://rosettacode.org/wiki/Print_a_Multiplication_Table ] diff --git a/Task/Multisplit/Ring/multisplit.ring b/Task/Multisplit/Ring/multisplit.ring index 26ab99fcb3..8cb2849ef3 100644 --- a/Task/Multisplit/Ring/multisplit.ring +++ b/Task/Multisplit/Ring/multisplit.ring @@ -1,7 +1,4 @@ # Project : Multisplit -# Date : 2017/12/26 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : str = "a!===b=!=c" sep = "=== != =! b =!=" diff --git a/Task/Munching-squares/Befunge/munching-squares.bf b/Task/Munching-squares/Befunge/munching-squares.bf new file mode 100644 index 0000000000..8f68b3ff4b --- /dev/null +++ b/Task/Munching-squares/Befunge/munching-squares.bf @@ -0,0 +1,3 @@ +55+::"3P",,,28*:*::..\,:.\,:v +>2%*28*:**-2/\1-:v<:8:-1<_@ v +^\-1*2%2/*:*82::\_$0.0..:^:*< diff --git a/Task/Munching-squares/Ring/munching-squares.ring b/Task/Munching-squares/Ring/munching-squares.ring index 928f632a92..7da3d855d2 100644 --- a/Task/Munching-squares/Ring/munching-squares.ring +++ b/Task/Munching-squares/Ring/munching-squares.ring @@ -1,7 +1,4 @@ # Project : Munching squares -# Date : 2018/01/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "guilib.ring" diff --git a/Task/Munching-squares/Scala/munching-squares.scala b/Task/Munching-squares/Scala/munching-squares.scala index c2277df3a6..4007bde680 100644 --- a/Task/Munching-squares/Scala/munching-squares.scala +++ b/Task/Munching-squares/Scala/munching-squares.scala @@ -1,26 +1,25 @@ import scala.swing.Swing.pair2Dimension -import scala.swing.{ Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication } +import scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication} object XorPattern extends SimpleSwingApplication { - val ui = new Panel { - - override def paintComponent(g: Graphics2D) = { - super.paintComponent(g) - for { - y <- 0 until size.getHeight().toInt - x <- 0 until size.getWidth().toInt - } { - g.setColor(new Color(0, (x ^ y) % 256, 0)) - g.drawLine(x, y, x, y) - } - } - } - def top = new MainFrame { preferredSize = (300, 300) title = "Rosetta Code >>> Task: Munching squares | Language: Scala" - contents = ui + contents = new Panel { + + protected override def paintComponent(g: Graphics2D) = { + super.paintComponent(g) + for { + y <- 0 until size.getHeight.toInt + x <- 0 until size.getWidth.toInt + } { + g.setColor(new Color(0, (x ^ y) % 256, 0)) + g.drawLine(x, y, x, y) + } + } + } + centerOnScreen() } } diff --git a/Task/Munching-squares/Sidef/munching-squares.sidef b/Task/Munching-squares/Sidef/munching-squares.sidef index 44d500a598..38baa9c96e 100644 --- a/Task/Munching-squares/Sidef/munching-squares.sidef +++ b/Task/Munching-squares/Sidef/munching-squares.sidef @@ -2,7 +2,7 @@ require('Imager') var img = %O.new(xsize => 256, ysize => 256) -for x,y in (^256 ~X ^256) { +for y=(^256), x=(^256) { var rgb = [(255 - x - y).abs, (255-x)^y, x^(255-y)] img.setpixel(x => x, y => y, color => rgb) } diff --git a/Task/Munching-squares/Visual-Basic-.NET/munching-squares.visual b/Task/Munching-squares/Visual-Basic-.NET/munching-squares.visual new file mode 100644 index 0000000000..495daf86a2 --- /dev/null +++ b/Task/Munching-squares/Visual-Basic-.NET/munching-squares.visual @@ -0,0 +1,22 @@ +' Munching squares - 27/07/2018 +Public Class MunchingSquares + Const xsize = 256 + Dim BMP As New Drawing.Bitmap(xsize, xsize) + Dim GFX As Graphics = Graphics.FromImage(BMP) + + Private Sub MunchingSquares_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint + 'draw + Dim MyGraph As Graphics = Me.CreateGraphics + Dim nColor As Color + Dim i, j, cp As Integer + xPictureBox.Image = BMP + For i = 0 To xsize - 1 + For j = 0 To xsize - 1 + cp = i Xor j + nColor = Color.FromArgb(cp, 0, cp) + BMP.SetPixel(i, j, nColor) + Next j + Next i + End Sub 'Paint + +End Class diff --git a/Task/Mutual-recursion/REBOL/mutual-recursion.rebol b/Task/Mutual-recursion/REBOL/mutual-recursion.rebol index 7fb2c0b58a..a03e5da3bd 100644 --- a/Task/Mutual-recursion/REBOL/mutual-recursion.rebol +++ b/Task/Mutual-recursion/REBOL/mutual-recursion.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Mutual Recursion" - Date: 2009-12-14 - Author: oofoe URL: http://rosettacode.org/wiki/Mutual_Recursion References: [http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences] ] diff --git a/Task/N-queens-problem/Befunge/n-queens-problem.bf b/Task/N-queens-problem/Befunge/n-queens-problem.bf new file mode 100644 index 0000000000..dd2695a783 --- /dev/null +++ b/Task/N-queens-problem/Befunge/n-queens-problem.bf @@ -0,0 +1,4 @@ +<+--XX@_v#!:-1,+55,g\1$_:00g2%-0vv:,+55<&,,,,,,"Size: " +"| Q"$$$>:01p:2%!00g0>>^<00p::2%-:40p2/50p2*1+ +!77**48*+31p\:1\g,::2\g:,\3\g,,^g>0g++40g%40g\-\40g\`*- +2g05\**!!%6g04-g052!:`\g05::-1/2<^4*2%g05\+*+1*!!%6g04- diff --git a/Task/N-queens-problem/Go/n-queens-problem.go b/Task/N-queens-problem/Go/n-queens-problem-1.go similarity index 100% rename from Task/N-queens-problem/Go/n-queens-problem.go rename to Task/N-queens-problem/Go/n-queens-problem-1.go diff --git a/Task/N-queens-problem/Go/n-queens-problem-2.go b/Task/N-queens-problem/Go/n-queens-problem-2.go new file mode 100644 index 0000000000..b399167911 --- /dev/null +++ b/Task/N-queens-problem/Go/n-queens-problem-2.go @@ -0,0 +1,136 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + "time" + + "rosettacode.org/dlx" // or where ever you put the dlx package +) + +func main() { + log.SetPrefix("N-queens: ") + log.SetFlags(0) + profile := flag.Bool("profile", false, "show DLX profile") + flag.Parse() + + for N := 2; N <= 18; N++ { + err := nqueens(N, N == 8, *profile) + if err != nil { + log.Fatal(err) + } + } +} + +func nqueens(N int, printFirst, profile bool) error { + // Build a new DLX matrix with 2N primary columns and 4N-6 secondary + // columns: R0..R(N-1), F0..F(N-1), A1..A(2N-3), B1..B(2N-3). + // We also know the number of cells and solution rows required. + m := dlx.NewWithHint(2*N, 4*N-6, N*N*4-4, 8) + + s := solution{ + N: N, + renumFwd: make([]int, 0, 2*N), + renumBack: make([]int, 2*N), + printFirst: printFirst, + } + + // column indexes + iR0 := 0 + iF0 := iR0 + N + iA1 := iF0 + N + iB1 := iA1 + 2*N - 3 + + // Use "organ-pipe" ordering. E.g.Β for N=8: + // R4 F4 R3 F3 R5 F5 R2 F2 R6 F6 R1 F1 R7 F7 R0 F0 + // This can reduce the number of link updates required by + // almost half for large N; see Knuth's paper for details. + mid := N / 2 + for off := 0; off <= N-mid; off++ { + i := mid - off + if i >= 0 { + s.renumBack[iR0+i] = len(s.renumFwd) + s.renumBack[iF0+i] = len(s.renumFwd) + 1 + s.renumFwd = append(s.renumFwd, iR0+i, iF0+i) + } + if i = mid + off; off != 0 && i < N { + s.renumBack[iR0+i] = len(s.renumFwd) + s.renumBack[iF0+i] = len(s.renumFwd) + 1 + s.renumFwd = append(s.renumFwd, iR0+i, iF0+i) + } + } + + // Add constraint rows. + // TODO: pre-eliminate symetrical possibilities. + cols := make([]int, 4) + for i := 0; i < N; i++ { + for j := 0; j < N; j++ { + cols[0] = iR0 + i // Ri, rank i + cols[1] = iF0 + j // Fj, file j + a := (i + j) // A(i+j), diagonals + b := (N - 1 - i + j) // B(N-1-i+j), reverse diagonals + cols = cols[:2] + // Do organ-pipe reordering for R and F. + for i, c := range cols { + cols[i] = s.renumBack[c] + } + + // Only add diagonals with more than one space; that + // is we omit the corners: A0, A(2N-2), B0, and B(2N-2) + if 0 < a && a < 2*N-2 { + cols = append(cols, iA1+a-1) + } + if 0 < b && b < 2*N-2 { + cols = append(cols, iB1+b-1) + } + + m.AddRow(cols) + } + } + + // Search for solutions. + start := time.Now() + err := m.Search(s.found) + if err != nil { + return err + } + elapsed := time.Since(start) + fmt.Printf("%dΓ—%d queens has %2d solutions, found in %v\n", N, N, s.count, elapsed) + if profile { + m.ProfileWrite(os.Stderr) + } + return nil +} + +type solution struct { + N int + count int + renumFwd []int // for "organ-pipe" column ordering + renumBack []int + printFirst bool +} + +func (s *solution) found(m *dlx.Matrix) error { + s.count++ + if s.printFirst && s.count == 1 { + fmt.Printf("First %dΓ—%d queens solution:\n", s.N, s.N) + for _, cols := range m.SolutionIDs(nil) { + var r, f int + for _, c := range cols { + // Undo organ-pipe reodering + if c < len(s.renumFwd) { + c = s.renumFwd[c] + } + if c < s.N { + r = c + 1 + } else if c < 2*s.N { + f = c - s.N + 1 + } + } + fmt.Printf(" R%d F%d\n", r, f) + } + } + return nil +} diff --git a/Task/Narcissistic-decimal-number/Befunge/narcissistic-decimal-number.bf b/Task/Narcissistic-decimal-number/Befunge/narcissistic-decimal-number.bf new file mode 100644 index 0000000000..b44a6c532a --- /dev/null +++ b/Task/Narcissistic-decimal-number/Befunge/narcissistic-decimal-number.bf @@ -0,0 +1,4 @@ +p55*\>:>:>:55+%\55+/00gvv_@ +>1>+>^v\_^#!:\> +>#-_>\>20p110g>\20g*\v>1-v| +^!p00:-1g00+$_^#!:<-1<^\.:< diff --git a/Task/Nautical-bell/C/nautical-bell.c b/Task/Nautical-bell/C/nautical-bell.c index 69277bcd28..09e610e7ac 100644 --- a/Task/Nautical-bell/C/nautical-bell.c +++ b/Task/Nautical-bell/C/nautical-bell.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, Original : 20th September 2017, Corrected : 25th September 2017*/ - #include #include #include diff --git a/Task/Nautical-bell/Mathematica/nautical-bell.math b/Task/Nautical-bell/Mathematica/nautical-bell.math index dedc1990fe..0e3c0859e9 100644 --- a/Task/Nautical-bell/Mathematica/nautical-bell.math +++ b/Task/Nautical-bell/Mathematica/nautical-bell.math @@ -1 +1,5 @@ -SessionSubmit[ScheduledTask[EmitSound[SoundNote["C", 1, "TubularBells"]], "Hourly"]] +LocalSubmit[ScheduledTask[ +EmitSound[Sound[Table[{ +SoundNote["C",750/1000,"TubularBells"],SoundNote[None,500/1000,"TubularBells"] +},Mod[Round[Total[DateList[][[{4,5}]]{2,1/30}]],8,1]]]] +,DateObject[{_,_,_,_,_,30|0}]]] diff --git a/Task/Nautical-bell/Phix/nautical-bell.phix b/Task/Nautical-bell/Phix/nautical-bell.phix new file mode 100644 index 0000000000..e9e3f9739c --- /dev/null +++ b/Task/Nautical-bell/Phix/nautical-bell.phix @@ -0,0 +1,37 @@ +constant watches = {"First","Middle","Morning","Forenoon","Afternoon","First dog","Last dog","First"}, + watch_ends = {"00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59"}, + bells = {"One","Two","Three","Four","Five","Six","Seven","Eight"}, + ding = "ding!" + +procedure nb(integer h,m) + integer bell = mod(floor((h*60+m)/30),8) + if bell==0 then bell = 8 end if + string hm = sprintf("%02d:%02d",{h,m}) + integer watch=1 + while hm>watch_ends[watch] do watch += 1 end while + string plural = iff(bell==1?" ":"s") + string dings = ding + for i=2 to bell do dings &= iff(mod(i,2)?" ":"")&ding end for + printf(1,"%s %9s watch %5s bell%s %s\n", + {hm,watches[watch],bells[bell],plural,dings}) +end procedure + +procedure simulate1day() + for h=0 to 23 do + for m=0 to 30 by 30 do + nb(h,m) + end for + end for + nb(0,0) -- (again) +end procedure + +simulate1day() + +while 1 do + sequence d = date(DT_GMT) + integer m = d[DT_SECOND] + mod(d[DT_MINUTE],30)*60 + if m=0 then + nb(d[DT_HOUR],d[DT_MINUTE]) + end if + sleep(30*60-m) +end while diff --git a/Task/Nautical-bell/Ring/nautical-bell.ring b/Task/Nautical-bell/Ring/nautical-bell.ring index 161d24c889..148932fc7a 100644 --- a/Task/Nautical-bell/Ring/nautical-bell.ring +++ b/Task/Nautical-bell/Ring/nautical-bell.ring @@ -1,7 +1,4 @@ # Project : Nautical bell -# Date : 2017/12/26 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : m = 0 for n = 0 to 23 diff --git a/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring b/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring index febd5c24c6..9d348b8648 100644 --- a/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring +++ b/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring @@ -1,7 +1,4 @@ # Project : Non-continuous subsequences -# Date : 2018/02/03 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "stdlib.ring" list = [1,2,3,4] diff --git a/Task/Non-continuous-subsequences/Scala/non-continuous-subsequences.scala b/Task/Non-continuous-subsequences/Scala/non-continuous-subsequences.scala new file mode 100644 index 0000000000..a244732c7d --- /dev/null +++ b/Task/Non-continuous-subsequences/Scala/non-continuous-subsequences.scala @@ -0,0 +1,13 @@ +object NonContinuousSubSequences extends App { + + private def seqR(s: String, c: String, i: Int, added: Int): Unit = { + if (i == s.length) { + if (c.trim.length > added) println(c) + } else { + seqR(s, c + s(i), i + 1, added + 1) + seqR(s, c + " ", i + 1, added) + } + } + + seqR("1234", "", 0, 0) +} diff --git a/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring b/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring index af7e3c688f..f23bfca42e 100644 --- a/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring +++ b/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring @@ -1,7 +1,4 @@ # Project : Non-decimal radices/Convert -# Date : 2017/10/20 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "0 (decimal) -> " + hex(0) + " (base 16)" + nl see "26 (decimal) -> " + hex(26) + " (base 16)" + nl 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 index f787b31f25..faa8f62ce2 100644 --- a/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring +++ b/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring @@ -1,7 +1,4 @@ # Project : Non Decimal radices/Output -# Date : 2017/09/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see string(0) + nl see string(123456789) + nl diff --git a/Task/Nth-root/360-Assembly/nth-root.360 b/Task/Nth-root/360-Assembly/nth-root.360 new file mode 100644 index 0000000000..0a1cbdc204 --- /dev/null +++ b/Task/Nth-root/360-Assembly/nth-root.360 @@ -0,0 +1,59 @@ +* Nth root - x**(1/n) - 29/07/2018 +NTHROOT CSECT + USING NTHROOT,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + SAVE (14,12) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + BAL R14,ROOTN call rootn(x,n) + LE F0,XN xn=rootn(x,n) + LA R0,6 decimals=6 + BAL R14,FORMATF edit xn + MVC PG(13),0(R1) output xn + XPRNT PG,L'PG print buffer + L R13,4(0,R13) restore previous savearea pointer + RETURN (14,12),RC=0 restore registers from calling sav +ROOTN MVC ZN,=E'0' zn=0 ---------------------------- + MVC ZN,N n + MVI ZN,X'46' zn=unnormalize(n) + LE F0,ZN zn + AE F0,=E'0' normalized + STE F0,ZN zn=normalize(n) + LE F6,=E'0' xm=0 + LE F0,X x + DE F0,ZN /zn + STE F0,XN xn=x/zn +WHILEA LE F0,XN xn + SER F0,F6 xn-xm + LPER F0,F0 abs((xn-xm) + DE F0,XN /xn + CE F0,EPSILON while abs((xn-xm)/xn)>epsilon + BNH EWHILEA ~ + LE F6,XN xm=xn + LE F0,ZN zn + SE F0,=E'1' zn-1 + MER F0,F6 f0=(zn-1)*xm + L R2,N n + BCTR R2,0 n-1 + LE F2,=E'1' xm +POW MER F2,F6 *xm + BCT R2,POW f2=xm**(n-1) + LE F4,X x + DER F4,F2 x/xm**(n-1) + AER F0,F4 (zn-1)*xm+x/xm**(n-1) + DE F0,ZN /zn + STE F0,XN xn=((zn-1)*xm+x/xm**(n-1))/zn + B WHILEA endwhile +EWHILEA LE F0,XN xn + BR R14 return --------------------------- + COPY FORMATF format a float +X DC E'2' x <== input +N DC F'2' n <== input +EPSILON DC E'1E-6' imprecision +XN DS E xn :: output +ZN DS E zn=float(n) +PG DC CL80' ' buffer + REGEQU + END NTHROOT diff --git a/Task/Null-object/NewLISP/null-object.newlisp b/Task/Null-object/NewLISP/null-object.newlisp new file mode 100644 index 0000000000..ff096e1506 --- /dev/null +++ b/Task/Null-object/NewLISP/null-object.newlisp @@ -0,0 +1,4 @@ +#! /usr/local/bin/newlisp +(setq myobject nil) +(println (nil? myobject)) +(exit) diff --git a/Task/Number-names/Phix/number-names.phix b/Task/Number-names/Phix/number-names.phix index ae317aff3c..8ea6b04635 100644 --- a/Task/Number-names/Phix/number-names.phix +++ b/Task/Number-names/Phix/number-names.phix @@ -32,7 +32,8 @@ function Thousand(integer N, string withand) return Twenty(floor(N/100)) & " hundred and " & Hundred(mod(N,100)) end function -constant orders = {{power(10,12),"trillion"}, +constant orders = {{power(10,15),"quadrillion"}, + {power(10,12),"trillion"}, {power(10,9),"billion"}, {power(10,6),"million"}, {power(10,3),"thousand"}} diff --git a/Task/Number-reversal-game/Astro/number-reversal-game.astro b/Task/Number-reversal-game/Astro/number-reversal-game.astro index 329cd8f5ad..56e2791b27 100644 --- a/Task/Number-reversal-game/Astro/number-reversal-game.astro +++ b/Task/Number-reversal-game/Astro/number-reversal-game.astro @@ -1,10 +1,13 @@ print '# Number reversal game' -var data, trials = list('123456789'), 0 -while data == sorted(data): + +var data, trials = list(1..9), 0 + +while data == sort data: random.shuffle data -while data != sorted(data): + +while data != sort data: trials += 1 - flip = int input '#$trials: LIST: $(join data) Flip how many?: ' - data[:flip] = data[!flip:] + flip = int input '#$trials: LIST: ${join data} Flip how many?: ' + data[:flip] = data[end:-1:flip] print '\nYou took $trials attempts to put digits in order!' diff --git a/Task/Number-reversal-game/Crystal/number-reversal-game.crystal b/Task/Number-reversal-game/Crystal/number-reversal-game.crystal new file mode 100644 index 0000000000..0c03b3586f --- /dev/null +++ b/Task/Number-reversal-game/Crystal/number-reversal-game.crystal @@ -0,0 +1,21 @@ +SIZE = 9 +ordered = (1..SIZE).to_a +shuffled = (1..SIZE).to_a + +while shuffled == ordered + shuffled.shuffle! +end + +score = 0 +until shuffled == ordered + print "#{shuffled} Enter items to reverse: " + + next unless guess = gets + next unless num = guess.to_i? + next if num < 2 || num > SIZE + + shuffled[0, num] = shuffled[0, num].reverse + score += 1 +end + +puts "#{shuffled} Your score: #{score}" diff --git a/Task/Number-reversal-game/Ring/number-reversal-game.ring b/Task/Number-reversal-game/Ring/number-reversal-game.ring index 686009cc68..35bc67639c 100644 --- a/Task/Number-reversal-game/Ring/number-reversal-game.ring +++ b/Task/Number-reversal-game/Ring/number-reversal-game.ring @@ -1,7 +1,4 @@ # Project : Number reversal game -# Date : 2017/12/02 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : rever = 1:9 leftrever = [] diff --git a/Task/Numerical-integration/Ring/numerical-integration.ring b/Task/Numerical-integration/Ring/numerical-integration.ring index 64653bb3d4..f7c444588d 100644 --- a/Task/Numerical-integration/Ring/numerical-integration.ring +++ b/Task/Numerical-integration/Ring/numerical-integration.ring @@ -1,7 +1,4 @@ # Project : Numerical integration -# Date : 2018/04/087 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(8) data = [["pow(x,3)",0,1,100], ["1/x",1, 100,1000], ["x",0,5000,5000000], ["x",0,6000,6000000]] diff --git a/Task/Object-serialization/Factor/object-serialization.factor b/Task/Object-serialization/Factor/object-serialization.factor new file mode 100644 index 0000000000..1105ebe445 --- /dev/null +++ b/Task/Object-serialization/Factor/object-serialization.factor @@ -0,0 +1,45 @@ +USING: accessors combinators.extras io io.encodings.binary +io.files io.files.info kernel prettyprint serialize ; +IN: rosetta-code.object-serialization + +! Define two classes, item and armor. armor is a subclass of +! item. + +TUPLE: item name value ; +TUPLE: armor < item physical-resistance fire-resistance ; + +! Define boa constructors for both classes using C: shorthand. +! boa means By Order of Arguments, and yes, this is a pun on boa +! constrictors. + +C: item +C: armor + +! Create three example items and print them out +! non-destructively. + +"Fish scales" 0.05 +"Gold piece" 1 +"Breastplate of Ashannar" 50,000 55 30 +[ [ . ] keep ] tri@ nl + +! Serialize the three objects to a binary file named +! objects.dat. + +"Serializing objects to objects.dat . . . " print +"objects.dat" binary [ [ serialize ] tri@ ] with-file-writer + +! Check that objects.dat exists. + +"objects.dat exists? " write "objects.dat" exists? . +"Size on disk: " write "objects.dat" file-info size>> pprint +" bytes" print nl + +! Deserialize three objects from objects.dat. + +"Deserializing objects from objects.dat . . . " print nl +"objects.dat" binary [ [ deserialize ] thrice ] with-file-reader + +! Print out deserialized objects. + +[ . ] tri@ diff --git a/Task/Odd-word-problem/Ring/odd-word-problem.ring b/Task/Odd-word-problem/Ring/odd-word-problem.ring index fd3fc9bfd3..2d3af1ed7b 100644 --- a/Task/Odd-word-problem/Ring/odd-word-problem.ring +++ b/Task/Odd-word-problem/Ring/odd-word-problem.ring @@ -1,7 +1,4 @@ # Project : Odd word problem -# Date : 2017/10/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : test = "what,is,the;meaning,of:life." n1 = 1 diff --git a/Task/One-dimensional-cellular-automata/Ceylon/one-dimensional-cellular-automata.ceylon b/Task/One-dimensional-cellular-automata/Ceylon/one-dimensional-cellular-automata.ceylon index 5f7a841054..cd31744412 100644 --- a/Task/One-dimensional-cellular-automata/Ceylon/one-dimensional-cellular-automata.ceylon +++ b/Task/One-dimensional-cellular-automata/Ceylon/one-dimensional-cellular-automata.ceylon @@ -1,45 +1,66 @@ -shared void run() { - - class Automata1D({Cell*} data, Cell alive, Cell dead) - given Cell satisfies Object { - - assert(data.every((Cell element) => element == alive || element == dead)); - - value imaginaryFirstCell = data.first else dead; - value imaginaryLastCell = data.last else dead; +shared abstract class Cell(character) of alive | dead { + shared Character character; + string => character.string; + shared formal Cell opposite; +} - value cells = Array {*data.rest.exceptLast}; +shared object alive extends Cell('#') { + opposite => dead; +} +shared object dead extends Cell('_') { + opposite => alive; +} + +shared Map cellsByCharacter = map { for (cell in `Cell`.caseValues) cell.character->cell }; + +shared class Automata1D({Cell*} initialCells) { + + + value permanentFirstCell = initialCells.first else dead; + value permanentLastCell = initialCells.last else dead; + + value cells = Array { *initialCells.rest.exceptLast }; + + shared Boolean evolve() { - function isAlive(Cell c) => c == alive; - function flipped(Cell c) => c == alive then dead else alive; + value newCells = Array { + for (index->cell in cells.indexed) + let (left = cells[index - 1] else permanentFirstCell, + right = cells[index + 1] else permanentLastCell, + neighbours = [left, right], + bothAlive = neighbours.every(alive.equals), + bothDead = neighbours.every(dead.equals)) + if (bothAlive) + then cell.opposite + else if (cell == alive && bothDead) + then dead + else cell + }; - shared Boolean evolve() { - value buffer = Array { - *cells.indexed.map((Integer->Cell element) { - value index->cell = element; - value left = cells[index - 1] else imaginaryFirstCell; - value right = cells[index + 1] else imaginaryLastCell; - if(isAlive(left) && isAlive(right)) { - return flipped(cell); - } - if(isAlive(cell) && !isAlive(left) && !isAlive(right)) { - return dead; - } - return cell; - } - )}; - value changed = buffer != cells; - buffer.copyTo(cells); - return changed; + if (newCells == cells) { + return false; } - string => imaginaryFirstCell.string + "".join(cells) + imaginaryLastCell.string; + newCells.copyTo(cells); + return true; } + + string => permanentFirstCell.string + "".join(cells) + permanentLastCell.string; +} - value automata = Automata1D("_###_##_#_#_#_#__#__", '#', '_'); +shared Automata1D? automata1d(String string) => + let (cells = string.map((Character element) => cellsByCharacter[element])) + if (cells.every((Cell? element) => element exists)) + then Automata1D(cells.coalesced) + else null; + +shared void run() { + + assert (exists automata = automata1d("__###__##_#_##_###__######_###_#####_#__##_____#_#_#######__")); + variable value generation = 0; print("generation ``generation`` ``automata``"); - while(automata.evolve() && generation < 10) { - print("generation ``++generation`` ``automata``"); + while (automata.evolve() && generation<10) { + print("generation `` ++generation `` ``automata``"); } } diff --git a/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring b/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring index 746e152a81..2374b1ee6e 100644 --- a/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring +++ b/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring @@ -1,7 +1,4 @@ # Project : One-dimensional cellular automata -# Date : 2017/10/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : rule = ["0", "0", "0", "1", "0", "1", "1", "0"] now = "01110110101010100100" diff --git a/Task/OpenGL/Ring/opengl.ring b/Task/OpenGL/Ring/opengl.ring index 22ee024a7b..dc5aea81b4 100644 --- a/Task/OpenGL/Ring/opengl.ring +++ b/Task/OpenGL/Ring/opengl.ring @@ -1,7 +1,4 @@ # Project: OpenGL -# Date : 2018/06/09 -# Author: Gal Zsolt [~ CalmoSoft ~] -# Email : load "freeglut.ring" load "opengl21lib.ring" diff --git a/Task/Optional-parameters/Perl-6/optional-parameters.pl6 b/Task/Optional-parameters/Perl-6/optional-parameters-1.pl6 similarity index 100% rename from Task/Optional-parameters/Perl-6/optional-parameters.pl6 rename to Task/Optional-parameters/Perl-6/optional-parameters-1.pl6 diff --git a/Task/Optional-parameters/Perl-6/optional-parameters-2.pl6 b/Task/Optional-parameters/Perl-6/optional-parameters-2.pl6 new file mode 100644 index 0000000000..0201273b4e --- /dev/null +++ b/Task/Optional-parameters/Perl-6/optional-parameters-2.pl6 @@ -0,0 +1,4 @@ +method sorttable-pos($column = 0, $reverse?, &ordering = &infix:) { + my @result = selfΒ»[$column].sort: &ordering; + return $reverse ?? @result.reverse !! @result; +} diff --git a/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp b/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp index 8348513254..df688516eb 100644 --- a/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp +++ b/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp @@ -1,7 +1,3 @@ -/* - Author: Kevin Bacon [haxifix (@gmail.com)] - Date: 2018-05-19 -*/ #include #include #include diff --git a/Task/Order-two-numerical-lists/Maple/order-two-numerical-lists.maple b/Task/Order-two-numerical-lists/Maple/order-two-numerical-lists.maple new file mode 100644 index 0000000000..c97a4ad423 --- /dev/null +++ b/Task/Order-two-numerical-lists/Maple/order-two-numerical-lists.maple @@ -0,0 +1,10 @@ +orderLists := proc(num1,num2) + local len1, len2,i: + len1,len2 := numelems(num1),numelems(num2): + for i to min(len1,len2) do + if num1[i] <> num2[i] then + return evalb(num1[i] #include #include diff --git a/Task/Ordered-words/BaCon/ordered-words.bacon b/Task/Ordered-words/BaCon/ordered-words.bacon index 0693d27efa..32167f783b 100644 --- a/Task/Ordered-words/BaCon/ordered-words.bacon +++ b/Task/Ordered-words/BaCon/ordered-words.bacon @@ -5,15 +5,13 @@ 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 + term$ = EXTRACT$(SORT$(EXPLODE$(word$, 1)), " ") IF word$ = term$ THEN - IF length > MaxLen THEN - MaxLen = length + IF LEN(term$) > MaxLen THEN + MaxLen = LEN(term$) result$ = word$ - ELIF length = MaxLen THEN + ELIF LEN(term$) = MaxLen THEN result$ = APPEND$(result$, 0, word$, NL$) END IF END IF diff --git a/Task/Palindrome-detection/360-Assembly/palindrome-detection.360 b/Task/Palindrome-detection/360-Assembly/palindrome-detection.360 new file mode 100644 index 0000000000..76eae6d437 --- /dev/null +++ b/Task/Palindrome-detection/360-Assembly/palindrome-detection.360 @@ -0,0 +1,32 @@ +* Reverse b string 25/06/2018 +PALINDRO CSECT + USING PALINDRO,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 " + LA R8,BB @b[1] + LA R9,AA+L'AA-1 @a[n-1] + LA R6,1 i=1 +LOOPI C R6,=A(L'AA) do i=1 to length(a) + BH ELOOPI leave i + MVC 0(1,R8),0(R9) substr(b,i,1)=substr(a,n-i+1,1) + LA R8,1(R8) @b=@b+1 + BCTR R9,0 @a=@a-1 + LA R6,1(R6) i=i+1 + B LOOPI end do +ELOOPI XPRNT AA,L'AA print a + CLC BB,AA if b=a + BNE SKIP + XPRNT MSG,L'MSG then print msg +SKIP L R13,4(0,R13) epilog + LM R14,R12,12(R13) " + XR R15,R15 " + BR R14 exit +AA DC CL32'INGIRUMIMUSNOCTEETCONSUMIMURIGNI' a +BB DS CL(L'AA) b +MSG DC CL23'IT IS A TRUE PALINDROME' + YREGS + END PALINDRO diff --git a/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp b/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp index 9b939e5b20..49254efd7b 100644 --- a/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp +++ b/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp @@ -1,7 +1,4 @@ ;; Project : Palindrome detection -;; Date : 2018/03/06 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (defun palindrome(x) (if (string= x (reverse x)) diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-1.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-1.crystal new file mode 100644 index 0000000000..feb5d56a09 --- /dev/null +++ b/Task/Palindrome-detection/Crystal/palindrome-detection-1.crystal @@ -0,0 +1,3 @@ +def palindrome(s) + s == s.reverse +end diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-2.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-2.crystal new file mode 100644 index 0000000000..c22e0a12a0 --- /dev/null +++ b/Task/Palindrome-detection/Crystal/palindrome-detection-2.crystal @@ -0,0 +1,11 @@ +def palindrome_imperative(s) : Bool + mid = s.size / 2 + last = s.size - 1 + (0...s.size).each do |i| + if s[i] != s[last - i] + return false + end + end + + true +end diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-3.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-3.crystal new file mode 100644 index 0000000000..83cff3a021 --- /dev/null +++ b/Task/Palindrome-detection/Crystal/palindrome-detection-3.crystal @@ -0,0 +1,5 @@ +require "benchmark" +Benchmark.ips do |x| + x.report("declarative") { palindrome("hannah") } + x.report("imperative") { palindrome_imperative("hannah")} +end diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-4.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-4.crystal new file mode 100644 index 0000000000..e5e1527f36 --- /dev/null +++ b/Task/Palindrome-detection/Crystal/palindrome-detection-4.crystal @@ -0,0 +1,2 @@ +declarative 21.96M ( 45.54ns) (Β± 6.90%) 32 B/op 1.49Γ— slower + imperative 32.8M ( 30.49ns) (Β± 3.29%) 0 B/op fastest diff --git a/Task/Palindrome-detection/Nim/palindrome-detection.nim b/Task/Palindrome-detection/Nim/palindrome-detection.nim index 9199caee0a..a5a5d5f1d8 100644 --- a/Task/Palindrome-detection/Nim/palindrome-detection.nim +++ b/Task/Palindrome-detection/Nim/palindrome-detection.nim @@ -1,9 +1,9 @@ -proc reverse(s): string = +proc reverse(s: string): string = result = newString(s.len) for i,c in s: result[s.high - i] = c -proc isPalindrome(s): bool = +proc isPalindrome(s: string): bool = s == reverse(s) echo isPalindrome("FoobooF") diff --git a/Task/Palindrome-detection/REBOL/palindrome-detection.rebol b/Task/Palindrome-detection/REBOL/palindrome-detection.rebol index 56bbaccf31..6202253550 100644 --- a/Task/Palindrome-detection/REBOL/palindrome-detection.rebol +++ b/Task/Palindrome-detection/REBOL/palindrome-detection.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Palindrome Recognizer" - Date: 2010-01-03 - Author: oofoe URL: http://rosettacode.org/wiki/Palindrome ] diff --git a/Task/Pangram-checker/Befunge/pangram-checker.bf b/Task/Pangram-checker/Befunge/pangram-checker.bf new file mode 100644 index 0000000000..ee4927a19c --- /dev/null +++ b/Task/Pangram-checker/Befunge/pangram-checker.bf @@ -0,0 +1,4 @@ +>~>:65*`!#v_:"`"`48*v>g+04p1\4p +^#*`\*93\`0<::-"@"-*<^40!%2g4:_ +"pangram.">:#,_55+,@>"ton">48*>"si tahT" diff --git a/Task/Pangram-checker/Nim/pangram-checker.nim b/Task/Pangram-checker/Nim/pangram-checker.nim index b2985fe34c..eb0bbc521c 100644 --- a/Task/Pangram-checker/Nim/pangram-checker.nim +++ b/Task/Pangram-checker/Nim/pangram-checker.nim @@ -1,6 +1,6 @@ import rdstdin -proc isPangram(sentence; alphabet = {'a'..'z'}): bool = +proc isPangram(sentence: string, alphabet = {'a'..'z'}): bool = var sentset: set[char] = {} for c in sentence: sentset.incl c alphabet <= sentset diff --git a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs index 42b741402f..7f039ebacf 100644 --- a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs +++ b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs @@ -1,30 +1,47 @@ -import Control.Parallel.Strategies -import Control.DeepSeq -import Data.List -import Data.Function +import Control.Parallel.Strategies (parMap, rdeepseq) +import Control.DeepSeq (NFData) +import Data.List (maximumBy) +import Data.Function (on) nums :: [Integer] -nums = [112272537195293 - ,112582718962171 - ,112272537095293 - ,115280098190773 - ,115797840077099 - ,1099726829285419] +nums = + [ 112272537195293 + , 112582718962171 + , 112272537095293 + , 115280098190773 + , 115797840077099 + , 1099726829285419 + ] -lowestFactor :: Integral a => a -> a -> a -lowestFactor s n | n `rem` 2 == 0 = 2 - | otherwise = head $ y - where y = [x | x <- [s..ceiling . sqrt $ fromIntegral n] - ++ [n], n `rem` x == 0, x `rem` 2 /= 0] +lowestFactor + :: Integral a + => a -> a -> a +lowestFactor s n + | even n = 2 + | otherwise = head y + where + y = + [ x + | x <- [s .. ceiling . sqrt $ fromIntegral n] ++ [n] + , n `rem` x == 0 + , odd x ] +primeFactors + :: Integral a + => a -> a -> [a] primeFactors l n = f n l [] - where f n l xs = if n > 1 then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l:xs) - else xs + where + f n l xs = + if n > 1 + then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l : xs) + else xs -minPrimes ns = (\(x,y) -> (x,primeFactors y x)) $ - maximumBy (compare `on` snd) $ - zip ns (parMap rdeepseq (lowestFactor 3) ns) +minPrimes + :: (Control.DeepSeq.NFData a, Integral a) + => [a] -> (a, [a]) +minPrimes ns = + (\(x, y) -> (x, primeFactors y x)) $ + maximumBy (compare `on` snd) $ zip ns (parMap rdeepseq (lowestFactor 3) ns) main :: IO () -main = do - print $ minPrimes nums +main = print $ minPrimes nums diff --git a/Task/Parallel-calculations/Java/parallel-calculations.java b/Task/Parallel-calculations/Java/parallel-calculations.java index d3f328e705..0340197035 100644 --- a/Task/Parallel-calculations/Java/parallel-calculations.java +++ b/Task/Parallel-calculations/Java/parallel-calculations.java @@ -1,40 +1,37 @@ import static java.lang.System.out; - import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { - public static final long[] NUMBERS = { - 12757923, - 12878611, - 12878893, - 12757923, - 15808973, - 15780709, - 197622519 - }; + public static final long[] NUMBERS = { + 12757923, + 12878611, + 12878893, + 12757923, + 15808973, + 15780709, + 197622519 + }; - public static void main(String... arguments) { - stream(NUMBERS) - .unordered() - .parallel() - .mapToObj(ParallelCalculations::minimalPrimeFactor) - .max(comparing(a -> a[0])) - .ifPresent(res -> out.printf( - "%d has the largest minimum prime factor: %d%n", - res[1], - res[0] - )) - ; - } + public static void main(String... arguments) { + stream(NUMBERS) + .unordered() + .parallel() + .mapToObj(ParallelCalculations::minimalPrimeFactor) + .max(comparing(a -> a[0])) + .ifPresent(res -> out.printf( + "%d has the largest minimum prime factor: %d%n", + res[1], + res[0] + )); + } - public static long[] minimalPrimeFactor(long n) { - return iterate(2, i -> i + 1) - .filter(i -> n >= i * i) - .filter(i -> n % i == 0) - .mapToObj(i -> new long[]{i, n}) - .findFirst() - .orElseGet(() -> new long[]{n, n}) - ; - } + public static long[] minimalPrimeFactor(long n) { + for (long i = 2; n >= i * i; i++) { + if (n % i == 0) { + return new long[]{i, n}; + } + } + return new long[]{n, n}; + } } diff --git a/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 b/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 index 59fdfc7c57..c3cffd1ac1 100644 --- a/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 +++ b/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 @@ -4,9 +4,42 @@ my @nums = 64921987050997300559, 70251412046988563035, 71774104902986066597, 259826672618677756753, 262872058330672763871, 267440136898665274575, 278352769033314050117, 281398154745309057242, 292057004737291582187; -my \factories = @nums.hyper.map: *.&prime-factors.cache; -say my $gmf = {}.append(factoriesΒ»[0] Β»=>Β« @nums).max: {+.key}; +my @factories = @nums.hyper(:3batch).map: *.&prime-factors; +printf "%21d factors: %s\n", |$_ for @nums Z @factories; +my $gmf = {}.append(@factoriesΒ»[0] Β»=>Β« @nums).max: +*.key; +say "\nGreatest minimum factor: ", $gmf.key; +say "from: { $gmf.value }\n"; +say 'Run time: ', now - INIT now; +say '-' x 80; +# For amusements sake and for relative comparison, using the same 100 +# numbers as in the SequenceL example, testing with different numbers of threads. + +@nums = <625070029 413238785 815577134 738415913 400125878 967798656 830022841 + 774153795 114250661 259366941 571026384 522503284 757673286 509866901 6303092 + 516535622 177377611 520078930 996973832 148686385 33604768 384564659 95268916 + 659700539 149740384 320999438 822361007 701572051 897604940 2091927 206462079 + 290027015 307100080 904465970 689995756 203175746 802376955 220768968 433644101 + 892007533 244830058 36338487 870509730 350043612 282189614 262732002 66723331 + 908238109 635738243 335338769 461336039 225527523 256718333 277834108 430753136 + 151142121 602303689 847642943 538451532 683561566 724473614 422235315 921779758 + 766603317 364366380 60185500 333804616 988528614 933855820 168694202 219881490 + 703969452 308390898 567869022 719881996 577182004 462330772 770409840 203075270 + 666478446 351859802 660783778 503851023 789751915 224633442 347265052 782142901 + 43731988 246754498 736887493 875621732 594506110 854991694 829661614 377470268 + 984990763 275192380 39848200 892766084 76503760>Β».Int; + +for 1..8 -> $degree { + my $start = now; + my \factories = @nums.hyper(:degree($degree), :3batch).map: *.&prime-factors; + my $gmf = {}.append(factoriesΒ»[0] Β»=>Β« @nums).max: +*.key; + say "\nFactoring {+@nums} numbers, greatest minimum factor: {$gmf.key}"; + say "Using: $degree thread{ $degree > 1 ?? 's' !! ''}"; + my $end = now; + say 'Run time: ', $end - $start, ' seconds.'; +} + +# Prime factoring routines from the Prime decomposition task sub prime-factors ( Int $n where * > 0 ) { return $n if $n.is-prime; return [] if $n == 1; @@ -15,6 +48,10 @@ sub prime-factors ( Int $n where * > 0 ) { } sub find-factor ( Int $n, $constant = 1 ) { + return 2 unless $n +& 1; + if (my $gcd = $n gcd 6541380665835015) > 1 { + return $gcd if $gcd != $n + } my $x = 2; my $rho = 1; my $factor = 1; diff --git a/Task/Parametrized-SQL-statement/Phix/parametrized-sql-statement.phix b/Task/Parametrized-SQL-statement/Phix/parametrized-sql-statement.phix new file mode 100644 index 0000000000..06562db311 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Phix/parametrized-sql-statement.phix @@ -0,0 +1,27 @@ +-- +-- demo\rosetta\Parametrized_SQL_statement.exw +-- +include pSQLite.e + +sqlite3 db = sqlite3_open(":memory:") + +integer res = sqlite3_exec(db,`create table players (name, score, active, jerseyNum)`) +res = sqlite3_exec(db,`insert into players values ('Roethlisberger, Ben', 94.1, 1, 7 )`) +res = sqlite3_exec(db,`insert into players values ('Smith, Alex', 85.3, 1, 11)`) +res = sqlite3_exec(db,`insert into players values ('Doe, John', 15, 0, 99)`) +res = sqlite3_exec(db,`insert into players values ('Manning, Payton', 96.5, 0, 123)`) + +pp({"Before",sqlite3_get_table(db, "select * from players")},{pp_Nest,2}) + +sqlite3_stmt pStmt = sqlite3_prepare(db, `update players set name=?, score=?, active=? where jerseyNum=?`) +sqlite3_bind_text(pStmt,1,"Smith, Steve") +sqlite3_bind_double(pStmt,2,42) +sqlite3_bind_int(pStmt,3,true) +sqlite3_bind_int(pStmt,4,99) +res = sqlite3_step(pStmt); +if res!=SQLITE_DONE then ?9/0 end if +if sqlite3_finalize(pStmt)!=SQLITE_OK then ?9/0 end if + +pp({"After",sqlite3_get_table(db, "select * from players")},{pp_Nest,2}) + +sqlite3_close(db) diff --git a/Task/Parametrized-SQL-statement/Scala/parametrized-sql-statement.scala b/Task/Parametrized-SQL-statement/Scala/parametrized-sql-statement.scala new file mode 100644 index 0000000000..79717b84f6 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Scala/parametrized-sql-statement.scala @@ -0,0 +1,57 @@ +import slick.jdbc.H2Profile.api._ +import slick.sql.SqlProfile.ColumnOption.SqlType + +import scala.concurrent.Await +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent.duration.Duration + +object PlayersApp extends App { + lazy val playerRecords = TableQuery[PlayerRecords] + val db = Database.forURL("jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver") + // Pre-compiled parameterized statement + val compiledUpdate = Compiled { jerseyN: Rep[Int] => + for {c <- playerRecords if c.jerseyNum === jerseyN} yield (c.name, c.score, c.active) + } + + def setup = DBIO.seq( + playerRecords.schema.create, + playerRecords ++= Seq( // JDBC batch update + (7, "Roethlisberger, Ben", 94.1f, true), + (11, "Smith, Alex", 85.3f, true), + (18, "Manning, Payton", 96.5f, false), + (99, "Doe, John", 15f, false)) + ) + + def queryPlayers(prelude: String) = { + println("\n " +prelude) + println( + "β”‚ Name β”‚Scorβ”‚ Active β”‚Jerseynumβ”‚\n" + + "β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€" + ) + DBIO.seq(playerRecords.result.map(_.map { + case (jerseyN, name, score, active) => + f"$name%32s $score ${(if (active) "" else "in") + "active"}%8s $jerseyN%8d" + }.foreach(println))) + } + + // Definition of the PLAYERS table + class PlayerRecords(tag: Tag) extends Table[(Int, String, Float, Boolean)](tag, "PLAYER_RECORDS") { + def active = column[Boolean]("ACTIVE") + def jerseyNum = column[Int]("JERSEY_NUM", O.PrimaryKey) + def name = column[String]("NAME", SqlType("VARCHAR2(32)")) + def score = column[Float]("SCORE") + + def * = (jerseyNum, name, score, active) + } + + println(s"The pre-compiled parameterized update DML:\n${compiledUpdate(0).updateStatement}") + + Await.result(db.run( + for { // Using the for comprehension + _ <- setup + _ <- queryPlayers("Before update:") + n <- compiledUpdate(99).update("Smith, Steve", 42f, true) + _ <- queryPlayers("After update:") + } yield n), Duration.Inf) + +} diff --git a/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n index 1c7a1f7cf2..8acef7c4da 100644 --- a/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n +++ b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n @@ -1,10 +1,6 @@ .ig RPN parser implementation in TROFF - Originally written on November 21, 2017. - Modified for Rosettacode on December 3, 2017. - - Stephanie BjΓΆrk (Katt) .. .\" \(*A stack implementation .nr Ac 0 diff --git a/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp b/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp index 3eb8ee9212..02823886b5 100644 --- a/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp +++ b/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp @@ -1,4 +1,3 @@ -/*Corrected by Abhishek Ghosh, 6th November 2017*/ #include #include #include diff --git a/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c b/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c index 2764e9b718..537f629a44 100644 --- a/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c +++ b/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 7th November 2017*/ - #include #include #include diff --git a/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java b/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java index ef4e19f0b2..79978fbb05 100644 --- a/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java +++ b/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java @@ -1,3 +1,5 @@ +import java.util.Stack; + public class PostfixToInfix { public static void main(String[] args) { diff --git a/Task/Pascals-triangle-Puzzle/Phix/pascals-triangle-puzzle.phix b/Task/Pascals-triangle-Puzzle/Phix/pascals-triangle-puzzle.phix new file mode 100644 index 0000000000..7bbbc91884 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Phix/pascals-triangle-puzzle.phix @@ -0,0 +1,73 @@ +--This little ditty converts the pyramid to rules quite nicely, however I will concede +--that solving those two rules (18=2x+z and 73=5x+6z) and specifically converting them +--into xrule(35=7x) and zrule(56=7z) is somewhat amateurish - suggestions welcome. + +sequence pyramid = { + {151}, + {"",""}, + {40,"",""}, + {"","","",""}, + {"x",11,"y",4,"z"}} + +sequence rules = {} + +-- each cell in the pyramid is either an integer final value or an equation. +-- initially the equations are strings, we substitute all with triplets of +-- the form {k,x,z} ie k+l*x+m*z, and known values < last row become rules. + +for r=5 to 1 by -1 do + for c=1 to length(pyramid[r]) do + object prc = pyramid[r][c], equ + if prc="x" then prc = {0,1,0} -- ie one x + elsif prc="y" then prc = {0,1,1} -- ie one x plus one z + elsif prc="z" then prc = {0,0,1} -- ie one z + else + if prc="" or r<=4 then + -- examples: x+11 is {0,1,0}+{11,0,0} -> {11,1,0}, + -- 11+y is {11,0,0}+{0,1,1} -> {11,1,1}, + -- 40=""+"" is {40,0,0}={22,2,1} ==> {18,2,1} + equ = sq_add(pyramid[r+1][c],pyramid[r+1][c+1]) + end if + if prc="" then prc = equ + else prc = {prc,0,0} + if r<=4 then + equ[1] = prc[1]-equ[1] + rules = append(rules,equ) + end if + end if + end if + pyramid[r][c] = prc + end for +end for + +ppOpt({pp_Nest,1,pp_StrFmt,1}) +?"equations" +pp(pyramid) +?"rules" +pp(rules) +puts(1,"=====\n") + +if length(rules)!=2 then ?9/0 end if -- more work needed!? + +-- admittedly this bit is rather amateurish, and maybe problem-specific: +sequence xrule = sq_sub(sq_mul(rules[1],rules[2][3]),sq_mul(rules[2],rules[1][3])), + zrule = sq_sub(sq_mul(rules[2],rules[1][2]),sq_mul(rules[1],rules[2][2])) + +?{"xrule",xrule} +?{"zrule",zrule} + +integer x = xrule[1]/xrule[2], + z = zrule[1]/zrule[3], + y = x+z + +printf(1,"x = %d, y=%d, z=%d\n",{x,y,z}) + +-- finally evaluate all the equations and print it. +for r=1 to length(pyramid) do + for c=1 to length(pyramid[r]) do + integer {k, l, m} = pyramid[r][c] + pyramid[r][c] = k+l*x+m*z + end for +end for + +pp(pyramid) diff --git a/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l b/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l index b3f657a8d9..31c1b9b949 100644 --- a/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l +++ b/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l @@ -40,4 +40,5 @@ (+ 11 @Y @F) (+ @Y 4 @G) (+ 4 @Z @H) - (+ @X @Z @Y) ) + (+ @X @Z @Y) + T ) diff --git a/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx b/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx index 4694e63479..bb3696c839 100644 --- a/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx +++ b/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx @@ -1,18 +1,22 @@ /*REXX program solves a (Pascal's) "Pyramid of Numbers" puzzle given four values. */ - /*β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ answer β”‚ - β”‚ mid / β”‚ - β”‚ \ / β”‚ - β”‚ \ 151 β”‚ - β”‚ \ Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± β”‚ - β”‚ 40 Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± β”‚ - β”‚ Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± β”‚ - β”‚ x 11 y 4 z β”‚ - β”‚ / \ β”‚ - β”‚ / \ β”‚ - β”‚ / \ β”‚ - β”‚Find: x y z b d β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜*/ + /*╔══════════════════════════════════════════════════╗ + β•‘ answer β•‘ + β•‘ mid / β•‘ + β•‘ \ / β•‘ + β•‘ \ 151 β•‘ + β•‘ \ Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± β•‘ + β•‘ 40 Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± β•‘ + β•‘ Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± Ξ±Ξ±Ξ± β•‘ + β•‘ x 11 y 4 z β•‘ + β•‘ / \ β•‘ + β•‘ / \ β•‘ + β•‘ / \ β•‘ + β•‘ Find: x y z b d β•‘ + β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•*/ + do #=2; _=sourceLine(#) /* [↓] this DO loop shows (above) box.*/ + if pos('#',_)\==0 then leave /*only display up to the above line. */ + say sourceLine(#) /*display one line of the above box. */ + end /*#*/ /* [↑] this is one cheap way for doc. */ parse arg b d mid answer . /*obtain optional variables from the CL*/ if b=='' | b=="," then b= 11 /*Not specified? Then use the default.*/ if d=='' | d=="," then d= 4 /* " " " " " " */ @@ -21,13 +25,13 @@ if answer='' | answer=="," then answer= 151 /* " " " " " pad= left('', 15) /*used for inserting spaces in output. */ big= answer - 4*b - 4*d /*calculate big number less constants*/ middle= mid - 2*b /* " middle " " " */ - - do x =-big to big - do y=-big to big - if x+y\==middle then iterate /*40 = x+2B+Y ──or── 40-2*11 = x+y */ - do z=-big to big - if z \== y - x then iterate /*z has to equal y-x (y=x+z) */ - if x+y*6+z == big then say pad 'x = ' x pad "y = " y pad 'z = ' z - end /*z*/ - end /*y*/ - end /*x*/ /*stick a fork in it, we're all done. */ +say + do x =-big to big + do y=-big to big + if x+y\==middle then iterate /*40 = x+2B+Y ──or── 40-2*11 = x+y */ + do z=-big to big + if z \== y - x then iterate /*z has to equal y-x (y=x+z) */ + if x+y*6+z == big then say pad 'x = ' x pad "y = " y pad 'z = ' z + end /*z*/ + end /*y*/ + end /*x*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Percentage-difference-between-images/REBOL/percentage-difference-between-images.rebol b/Task/Percentage-difference-between-images/REBOL/percentage-difference-between-images.rebol index 9b5fac5221..0f23d496d1 100644 --- a/Task/Percentage-difference-between-images/REBOL/percentage-difference-between-images.rebol +++ b/Task/Percentage-difference-between-images/REBOL/percentage-difference-between-images.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Percent Image Difference" - Author: oofoe - Date: 2009-12-31 URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images ] diff --git a/Task/Permutation-test/Scala/permutation-test.scala b/Task/Permutation-test/Scala/permutation-test.scala new file mode 100644 index 0000000000..e22a958998 --- /dev/null +++ b/Task/Permutation-test/Scala/permutation-test.scala @@ -0,0 +1,23 @@ +object PermutationTest extends App { + private val data = + Array(85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98) + private var (total, treat) = (1.0, 0) + + private def pick(at: Int, remain: Int, accu: Int, treat: Int): Int = { + if (remain == 0) return if (accu > treat) 1 else 0 + + pick(at - 1, remain - 1, accu + data(at - 1), treat) + + (if (at > remain) pick(at - 1, remain, accu, treat) else 0) + } + + for (i <- 0 to 8) treat += data(i) + for (j <- 19 to 11 by -1) total *= j + for (g <- 9 to 1 by -1) total /= g + + private val gt = pick(19, 9, 0, treat) + private val le = (total - gt).toInt + + println(f"<= : ${100.0 * le / total}%f%% ${le}%d") + println(f" > : ${100.0 * gt / total}%f%% ${gt}%d") + +} diff --git a/Task/Permutations-Rank-of-a-permutation/Ring/permutations-rank-of-a-permutation.ring b/Task/Permutations-Rank-of-a-permutation/Ring/permutations-rank-of-a-permutation.ring index df4c376cff..59ea75e6ef 100644 --- a/Task/Permutations-Rank-of-a-permutation/Ring/permutations-rank-of-a-permutation.ring +++ b/Task/Permutations-Rank-of-a-permutation/Ring/permutations-rank-of-a-permutation.ring @@ -1,7 +1,4 @@ # Project : Permutations/Rank of a permutation -# Date : 2017/10/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : list = [0, 1, 2, 3] for perm = 0 to 23 diff --git a/Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-1.scala b/Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-1.scala new file mode 100644 index 0000000000..79724b17de --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-1.scala @@ -0,0 +1,23 @@ +import scala.math._ + +def factorial(n: Int): BigInt = { + (1 to n).map(BigInt.apply).fold(BigInt(1))(_ * _) +} + +def indexToPermutation(n: Int, x: BigInt): List[Int] = { + indexToPermutation((0 until n).toList, x) +} + +def indexToPermutation(ns: List[Int], x: BigInt): List[Int] = ns match { + case Nil => Nil + case _ => { + val (iBig, xNew) = x /% factorial(ns.size - 1) + val i = iBig.toInt + ns(i) :: indexToPermutation(ns.take(i) ++ ns.drop(i + 1), xNew) + } +} + +def permutationToIndex[A](xs: List[A])(implicit ord: Ordering[A]): BigInt = xs match { + case Nil => BigInt(0) + case x :: rest => factorial(rest.size) * rest.count(ord.lt(_, x)) + permutationToIndex(rest) +} diff --git a/Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-2.scala b/Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-2.scala new file mode 100644 index 0000000000..78c46d0673 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Scala/permutations-rank-of-a-permutation-2.scala @@ -0,0 +1,12 @@ +def check(n: Int, x: BigInt): Boolean = { + val perm = indexToPermutation(n, x) + val xOut = permutationToIndex(perm) + println(s"$x -> $perm -> $xOut") + xOut == x +} + +if ((0 to 5).map(BigInt.apply).forall(check(3, _))) { + println("Success!") +} else { + println("Failed") +} diff --git a/Task/Permutations-by-swapping/C/permutations-by-swapping.c b/Task/Permutations-by-swapping/C/permutations-by-swapping.c index a232b547ca..865653c226 100644 --- a/Task/Permutations-by-swapping/C/permutations-by-swapping.c +++ b/Task/Permutations-by-swapping/C/permutations-by-swapping.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 25th October 2017*/ - #include #include #include diff --git a/Task/Permutations/C/permutations-1.c b/Task/Permutations/C/permutations-1.c new file mode 100644 index 0000000000..9312ae9af6 --- /dev/null +++ b/Task/Permutations/C/permutations-1.c @@ -0,0 +1,54 @@ +#include +int main (int argc, char *argv[]) { +//here we check arguments + if (argc < 2) { + printf("Enter an argument. Example 1234 or dcba:\n"); + return 0; + } +//it calculates an array's length + int x; + for (x = 0; argv[1][x] != '\0'; x++); +//buble sort the array + int f, v, m; + for(f=0; f < x; f++) { + for(v = x-1; v > f; v-- ) { + if (argv[1][v-1] > argv[1][v]) { + m=argv[1][v-1]; + argv[1][v-1]=argv[1][v]; + argv[1][v]=m; + } + } +} + +//it calculates a factorial to stop the algorithm + char a[x]; + int k=0; + int fact=k+1; + while (k!=x) { + a[k]=argv[1][k]; + k++; + fact = k*fact; + } + a[k]='\0'; +//Main part: here we permutate + int i, j; + int y=0; + char c; + while (y != fact) { + printf("%s\n", a); + i=x-2; + while(a[i] > a[i+1] ) i--; + j=x-1; + while(a[j] < a[i] ) j--; + c=a[j]; + a[j]=a[i]; + a[i]=c; +i++; +for (j = x-1; j > i; i++, j--) { + c = a[i]; + a[i] = a[j]; + a[j] = c; + } +y++; + } +} diff --git a/Task/Permutations/C/permutations-2.c b/Task/Permutations/C/permutations-2.c new file mode 100644 index 0000000000..d155652c12 --- /dev/null +++ b/Task/Permutations/C/permutations-2.c @@ -0,0 +1,25 @@ +#include +int main() { + char a[] = "4321"; + int fact = 24; + int i, j; + int y=0; + char c; + while (y != fact) { + printf("%s\n", a); + i=1; + while(a[i] > a[i-1]) i++; + j=0; + while(a[j] < a[i])j++; + c=a[j]; + a[j]=a[i]; + a[i]=c; +i--; +for (j = 0; j < i; i--, j++) { + c = a[i]; + a[i] = a[j]; + a[j] = c; + } +y++; + } +} diff --git a/Task/Permutations/C/permutations.c b/Task/Permutations/C/permutations-3.c similarity index 100% rename from Task/Permutations/C/permutations.c rename to Task/Permutations/C/permutations-3.c diff --git a/Task/Permutations/C/permutations-4.c b/Task/Permutations/C/permutations-4.c new file mode 100644 index 0000000000..771af27207 --- /dev/null +++ b/Task/Permutations/C/permutations-4.c @@ -0,0 +1,100 @@ +#include +#include + +/* print a list of ints */ +int show(int *x, int len) +{ + int i; + for (i = 0; i < len; i++) + printf("%d%c", x[i], i == len - 1 ? '\n' : ' '); + return 1; +} + +/* next lexicographical permutation */ +int next_lex_perm(int *a, int n) { +# define swap(i, j) {t = a[i]; a[i] = a[j]; a[j] = t;} + int k, l, t; + + /* 1. Find the largest index k such that a[k] < a[k + 1]. If no such + index exists, the permutation is the last permutation. */ + for (k = n - 1; k && a[k - 1] >= a[k]; k--); + if (!k--) return 0; + + /* 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is + such an index, l is well defined */ + for (l = n - 1; a[l] <= a[k]; l--); + + /* 3. Swap a[k] with a[l] */ + swap(k, l); + + /* 4. Reverse the sequence from a[k + 1] to the end */ + for (k++, l = n - 1; l > k; l--, k++) + swap(k, l); + return 1; +# undef swap +} + +void perm1(int *x, int n, int callback(int *, int)) +{ + do { + if (callback) callback(x, n); + } while (next_lex_perm(x, n)); +} + +/* Boothroyd method; exactly N! swaps, about as fast as it gets */ +void boothroyd(int *x, int n, int nn, int callback(int *, int)) +{ + int c = 0, i, t; + while (1) { + if (n > 2) boothroyd(x, n - 1, nn, callback); + if (c >= n - 1) return; + + i = (n & 1) ? 0 : c; + c++; + t = x[n - 1], x[n - 1] = x[i], x[i] = t; + if (callback) callback(x, nn); + } +} + +/* entry for Boothroyd method */ +void perm2(int *x, int n, int callback(int*, int)) +{ + if (callback) callback(x, n); + boothroyd(x, n, n, callback); +} + +/* same as perm2, but flattened recursions into iterations */ +void perm3(int *x, int n, int callback(int*, int)) +{ + /* calloc isn't strictly necessary, int c[32] would suffice + for most practical purposes */ + int d, i, t, *c = calloc(n, sizeof(int)); + + /* curiously, with GCC 4.6.1 -O3, removing next line makes + it ~25% slower */ + if (callback) callback(x, n); + for (d = 1; ; c[d]++) { + while (d > 1) c[--d] = 0; + while (c[d] >= d) + if (++d >= n) goto done; + + t = x[ i = (d & 1) ? c[d] : 0 ], x[i] = x[d], x[d] = t; + if (callback) callback(x, n); + } +done: free(c); +} + +#define N 4 + +int main() +{ + int i, x[N]; + for (i = 0; i < N; i++) x[i] = i + 1; + + /* three different methods */ + perm1(x, N, show); + perm2(x, N, show); + perm3(x, N, show); + + return 0; +} diff --git a/Task/Pernicious-numbers/Ring/pernicious-numbers.ring b/Task/Pernicious-numbers/Ring/pernicious-numbers.ring index 79fbc1293e..516c309533 100644 --- a/Task/Pernicious-numbers/Ring/pernicious-numbers.ring +++ b/Task/Pernicious-numbers/Ring/pernicious-numbers.ring @@ -1,7 +1,4 @@ # Project : Pernicious numbers -# Date : 2017/10/01 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "The first 25 pernicious numbers:" + nl nr = 0 diff --git a/Task/Phrase-reversals/Maple/phrase-reversals.maple b/Task/Phrase-reversals/Maple/phrase-reversals.maple new file mode 100644 index 0000000000..f56757fa93 --- /dev/null +++ b/Task/Phrase-reversals/Maple/phrase-reversals.maple @@ -0,0 +1,11 @@ +#reverse the string +str := "rosetta code phrase reversal": +print(StringTools:-Reverse(str)): +#reverse each word +lst := convert(StringTools:-Split(str, " "), Array): +for i to numelems(lst) do + lst[i] := StringTools:-Reverse(lst[i]): +end do: +print(StringTools:-Join(convert(lst,list)," ")): +#reverse word order +print(StringTools:-Join(ListTools:-Reverse(StringTools:-Split(str," ")), " ")): diff --git a/Task/Pi/BASIC/pi-1.basic b/Task/Pi/BASIC/pi-1.basic new file mode 100644 index 0000000000..a2c2e2b3ce --- /dev/null +++ b/Task/Pi/BASIC/pi-1.basic @@ -0,0 +1,59 @@ +cls + +n =1000 +len = 10*n \ 4 +needdecimal = true +dim a(len) +nines = 0 +predigit = 0 # {First predigit is a 0} + +for j = 1 to len + a[j-1] = 2 # {Start with 2s} +next j + +for j = 1 to n + q = 0 + for i = len to 1 step -1 + # {Work backwards} + x = 10*a[i-1] + q*i + a[i-1] = x % (2*i - 1) + q = x \ (2*i - 1) + next i + a[0] = q % 10 + q = q \ 10 + if q = 9 then + nines = nines + 1 + else + if q = 10 then + d = predigit+1: gosub outputd + if nines > 0 then + for k = 1 to nines + d = 0: gosub outputd + next k + end if + predigit = 0 + nines = 0 + else + d = predigit: gosub outputd + predigit = q + if nines <> 0 then + for k = 1 to nines + d = 9: gosub outputd + next k + nines = 0 + end if + end if + end if +next j +print predigit +end + +outputd: +if needdecimal then + if d = 0 then return + print d + "."; + needdecimal = false +else + print d; +end if +return diff --git a/Task/Pi/BASIC/pi-2.basic b/Task/Pi/BASIC/pi-2.basic new file mode 100644 index 0000000000..da5cbd5e16 --- /dev/null +++ b/Task/Pi/BASIC/pi-2.basic @@ -0,0 +1,51 @@ +10 PRINT CHR$(147) +20 n = 100 +30 ln = int(10*n/4) +40 nd = 1 +50 dim a(ln) +60 n9 = 0 +70 pd = 0 :rem First predigit is a 0 +80 : +90 for j = 1 to ln +100 a(j-1) = 2 :rem Start with 2s +110 next j +120 : +130 for j = 1 to n +140 q = 0 +150 for i = ln to 1 step -1 :rem Work backwards +160 x = 10*a(i-1) + q*i +170 a(i-1) = x - (2*i-1)*int(x/(2*i-1)) :rem X - INT ( X / Y) * Y +180 q = int(x/(2*i - 1)) +190 next i +200 a(0) = q-10*int(q/10) +210 q = int(q/10) +220 if q=9 then n9 = n9 + 1 : goto 450 +240 if q<>10 then 350 +250 rem q == 10 +260 d = pd+1 : gosub 500 +270 if n9 < 0 then 320 +280 for k = 1 to n9 +290 d = 0: gosub 500 +300 next k +310 rem end if +320 pd = 0 +330 n9 = 0 +335 goto 450 +340 rem q <> 10 +350 d = pd: gosub 500 +360 pd = q +370 if n9 = 0 then 450 +380 for k = 1 to n9 +390 d = 9 : gosub 500 +400 next k +410 n9 = 0 +450 next j +460 print mid$(str$(pd),2,1) +470 end +480 : +490 rem outputd +500 if nd=0 then print mid$(str$(d),2,1); : return +510 if d=0 then return +520 print mid$(str$(d),2,1);"."; +530 nd = 0 +550 return diff --git a/Task/Pi/FreeBASIC/pi.freebasic b/Task/Pi/FreeBASIC/pi.freebasic new file mode 100644 index 0000000000..bc0f6ed292 --- /dev/null +++ b/Task/Pi/FreeBASIC/pi.freebasic @@ -0,0 +1,54 @@ +' version 05-07-2018 +' compile with: fbc -s console + +' unbounded spigot +' Ctrl-c to end program or close console window + +#Include "gmp.bi" + +Dim As UInteger num, ndigit, fp = Not 0 +Dim As mpz_ptr q,r,t,k,n,l,tmp1,tmp2 + q = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(q,1) + r = Allocate(Len(__Mpz_struct)) : Mpz_init(r) + t = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(t,1) + k = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(k,1) + n = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(n,3) + l = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(l,3) +tmp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp1) +tmp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp2) + +Do + mpz_mul_2exp(tmp1, q, 2) + mpz_add(tmp1,tmp1,r) + mpz_sub(tmp1,tmp1,t) + mpz_mul(tmp2, n, t) + If mpz_cmp(tmp1, tmp2) < 0 Then + Print mpz_get_ui(n); : ndigit += 1 : If ndigit Mod 50 = 0 Then Print " :";ndigit + If fp Then Print "."; : fp = Not fp : Print :ndigit = 0 + mpz_sub(tmp1, r, tmp2) + mpz_mul_ui(tmp1, tmp1, 10) + mpz_mul_ui(tmp2, q, 3) + mpz_add(tmp2, tmp2, r) + mpz_mul_ui(tmp2, tmp2, 10) + mpz_set(r, tmp1) + mpz_mul_ui(tmp1, n, 10) + mpz_tdiv_q(tmp2, tmp2, t) + mpz_sub(n, tmp2, tmp1) + mpz_mul_ui(q, q, 10) + Else + mpz_mul(tmp2, r, l) + mpz_mul(tmp1, q, k) + mpz_mul_ui(tmp1, tmp1, 7) + mpz_add(tmp1, tmp1, tmp2) + mpz_mul_2exp(tmp2, q, 1) + mpz_add(tmp2, tmp2, r) + mpz_mul(tmp2, tmp2, l) + mpz_mul(t, t, l) + mpz_tdiv_q(tmp1, tmp1, t) + mpz_mul(q, q, k) + mpz_add_ui(k, k, 1) + mpz_add_ui(l, l, 2) + mpz_set(n, tmp1) + mpz_set(r, tmp2) + End If +Loop diff --git a/Task/Pi/Nim/pi.nim b/Task/Pi/Nim/pi.nim index 94cbccf79d..e21efd4871 100644 --- a/Task/Pi/Nim/pi.nim +++ b/Task/Pi/Nim/pi.nim @@ -1,4 +1,4 @@ -import strutils, unsigned, bigints +import strutils, bigints var tmp1, tmp2, tmp3, acc, k, dd = initBigInt(0) diff --git a/Task/Pick-random-element/C/pick-random-element.c b/Task/Pick-random-element/C/pick-random-element.c index a1a9a3a329..483c3677db 100644 --- a/Task/Pick-random-element/C/pick-random-element.c +++ b/Task/Pick-random-element/C/pick-random-element.c @@ -1,5 +1,3 @@ -/*Corrected by Abhishek Ghosh, Mahalaya (19th September) 2017*/ - #include #include #include diff --git a/Task/Pick-random-element/Crystal/pick-random-element.crystal b/Task/Pick-random-element/Crystal/pick-random-element.crystal new file mode 100644 index 0000000000..d44e054cf7 --- /dev/null +++ b/Task/Pick-random-element/Crystal/pick-random-element.crystal @@ -0,0 +1 @@ +puts [1, 2, 3, 4, 5].sample(1) diff --git a/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring b/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring index 4cfc2af858..003172905f 100644 --- a/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring +++ b/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring @@ -1,7 +1,4 @@ # Project : Pig the dice game -# Date : 2017/10/31 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : numPlayers = 2 maxScore = 100 diff --git a/Task/Pinstripe-Display/Befunge/pinstripe-display.bf b/Task/Pinstripe-Display/Befunge/pinstripe-display.bf new file mode 100644 index 0000000000..603ee63bec --- /dev/null +++ b/Task/Pinstripe-Display/Befunge/pinstripe-display.bf @@ -0,0 +1,3 @@ +"%":*3-"`"8*>4/::8%00p8/10p4*\55+"1P",,v +,:.\.5vv-g025:\-1_$$55+,\:v1+*8g01g00_@> +024,+5<>/2%.1+\:>^<:\0:\-1_$20g1-:20p^1p diff --git a/Task/Pinstripe-Display/C/pinstripe-display.c b/Task/Pinstripe-Display/C/pinstripe-display.c index 7841759927..fd8c83046f 100644 --- a/Task/Pinstripe-Display/C/pinstripe-display.c +++ b/Task/Pinstripe-Display/C/pinstripe-display.c @@ -1,4 +1,3 @@ -/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ #include #include diff --git a/Task/Pinstripe-Display/Ring/pinstripe-display.ring b/Task/Pinstripe-Display/Ring/pinstripe-display.ring index 0349ea65bd..29c5abac3a 100644 --- a/Task/Pinstripe-Display/Ring/pinstripe-display.ring +++ b/Task/Pinstripe-Display/Ring/pinstripe-display.ring @@ -1,7 +1,4 @@ # Project : Pinstripe/Display -# Date : 2018/01/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "guilib.ring" diff --git a/Task/Pinstripe-Display/Scala/pinstripe-display.scala b/Task/Pinstripe-Display/Scala/pinstripe-display.scala new file mode 100644 index 0000000000..d560f26cc2 --- /dev/null +++ b/Task/Pinstripe-Display/Scala/pinstripe-display.scala @@ -0,0 +1,37 @@ +import java.awt._ + +import javax.swing._ + +object PinstripeDisplay extends App { + + SwingUtilities.invokeLater(() => + new JFrame("Pinstripe") { + + class Pinstripe_Display extends JPanel { + + override def paintComponent(g: Graphics): Unit = { + val bands = 4 + + super.paintComponent(g) + for (b <- 1 to bands) { + var colIndex = 0 + for (x <- 0 until getWidth by b) { + g.setColor(if (colIndex % 2 == 0) Color.white + else Color.black) + g.fillRect(x, (b - 1) * (getHeight / bands), x + b, b * (getHeight / bands)) + colIndex += 1 + } + } + } + + setPreferredSize(new Dimension(900, 600)) + } + + add(new Pinstripe_Display, BorderLayout.CENTER) + pack() + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) + setLocationRelativeTo(null) + setVisible(true) + }) + +} diff --git a/Task/Playing-cards/Factor/playing-cards.factor b/Task/Playing-cards/Factor/playing-cards.factor index 8e23848f19..8a9908f3ec 100644 --- a/Task/Playing-cards/Factor/playing-cards.factor +++ b/Task/Playing-cards/Factor/playing-cards.factor @@ -5,7 +5,7 @@ IN: rosetta-code.playing-cards CONSTANT: pips qw{ A 2 3 4 5 6 7 8 9 10 J Q K } CONSTANT: suits qw{ β™₯ ♣ ♦ β™  } -: ( -- vec ) 52 iota >vector ; +: ( -- vec ) 52 >vector ; : card>str ( n -- str ) 13 /mod [ suits nth ] [ pips nth ] bi* prepend ; diff --git a/Task/Plot-coordinate-pairs/Maple/plot-coordinate-pairs.maple b/Task/Plot-coordinate-pairs/Maple/plot-coordinate-pairs.maple new file mode 100644 index 0000000000..1e6f423421 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Maple/plot-coordinate-pairs.maple @@ -0,0 +1,3 @@ +x := Vector([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): +y := Vector([2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]): +plot(x,y,style="point"); diff --git a/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring b/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring index 2596618e7d..a253288c5f 100644 --- a/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring +++ b/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring @@ -1,7 +1,4 @@ # Project : Plot coordinate pairs -# Date : 2018/01/11 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "guilib.ring" diff --git a/Task/Polymorphism/Scala/polymorphism.scala b/Task/Polymorphism/Scala/polymorphism.scala new file mode 100644 index 0000000000..d7c571fef8 --- /dev/null +++ b/Task/Polymorphism/Scala/polymorphism.scala @@ -0,0 +1,36 @@ +object PointCircle extends App { + + class Point(x: Int = 0, y: Int = 0) { + + def copy(x: Int = this.x, y: Int = this.y): Point = new Point(x, y) + + override def toString = s"Point x: $x, y: $y" + } + + object Point { + def apply(x: Int = 0, y: Int = 0): Point = new Point(x, y) + } + + case class Circle(x: Int = 0, y: Int = 0, r: Int = 0) extends Point(x, y) { + + def copy(r: Int): Circle = Circle(x, y, r) + + override def toString = s"Circle x: $x, y: $y, r: $r" + } + + val p = Point() + val c = Circle() + println("Instantiated ", p) + println("Instantiated ", c) + + val q = Point(5, 6) + println("Instantiated ", q) + val r = q.copy(y = 7) // change y coordinate + println(r, " changed y coordinate") + + val d = Circle(5, 6, 7) + println("Instantiated ", d) + val e = d.copy(r = 8) // change radius + println(e, " changed radius") + +} diff --git a/Task/Polynomial-regression/Mathematica/polynomial-regression.math b/Task/Polynomial-regression/Mathematica/polynomial-regression-1.math similarity index 100% rename from Task/Polynomial-regression/Mathematica/polynomial-regression.math rename to Task/Polynomial-regression/Mathematica/polynomial-regression-1.math diff --git a/Task/Polynomial-regression/Mathematica/polynomial-regression-2.math b/Task/Polynomial-regression/Mathematica/polynomial-regression-2.math new file mode 100644 index 0000000000..42efcb2d5a --- /dev/null +++ b/Task/Polynomial-regression/Mathematica/polynomial-regression-2.math @@ -0,0 +1 @@ +Simplify@InterpolatingPolynomial[{{0, 1}, {1, 6}, {2, 17}, {3, 34}, {4, 57}, {5, 86}, {6, 121}, {7, 162}, {8, 209}, {9, 262}, {10, 321}}, x] diff --git a/Task/Power-set/Ring/power-set.ring b/Task/Power-set/Ring/power-set.ring index e0d4196f75..ab76578d5c 100644 --- a/Task/Power-set/Ring/power-set.ring +++ b/Task/Power-set/Ring/power-set.ring @@ -1,7 +1,4 @@ # Project : Power set -# Date : 2018/01/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : list = ["1", "2", "3", "4"] see powerset(list) diff --git a/Task/Pragmatic-directives/C/pragmatic-directives.c b/Task/Pragmatic-directives/C/pragmatic-directives.c index facbc441a9..6be4ac474e 100644 --- a/Task/Pragmatic-directives/C/pragmatic-directives.c +++ b/Task/Pragmatic-directives/C/pragmatic-directives.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 7th October 2017*/ - /*Almost every C program has the below line, the #include preprocessor directive is used to instruct the compiler which files to load before compiling the program. 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 index 16b3948044..03a6792b30 100644 --- 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 @@ -1,7 +1,4 @@ ;; Project : Primality by trial division -;; Date : 2018/03/06 -;; Author : Gal Zsolt [~ CalmoSoft ~] -;; Email : (defun prime(n) (setq flag 0) diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala index 682979e812..28d07b2ad5 100644 --- a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala @@ -1,4 +1,2 @@ - def isPrime(n: Int) = { - assume(n <= Int.MaxValue - 1) + def isPrime(n: Int) = n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0)) - } diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala index 4c9a45ef38..0e55ab6792 100644 --- a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala @@ -1,6 +1,20 @@ - def isPrime(n: Long) = { - n > 1 && ((n % 2 != 0) || (n == 2)) && ((3 until Math.sqrt(n).toInt by 2).par forall (n % _ != 0)) - } +object IsPrimeTrialDivision extends App { + def isPrime(n: Long) = + n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) && + (5 to math.sqrt(n).toInt by 6).par.forall(d => n % d != 0 && n % (d + 2) != 0) + assert(!isPrime(-1)) + assert(!isPrime(1)) + assert(isPrime(2)) + assert(isPrime(100000000003L)) + assert(isPrime(100000000019L)) + assert(isPrime(100000000057L)) + assert(isPrime(100000000063L)) + assert(isPrime(100000000069L)) + assert(isPrime(100000000073L)) + assert(isPrime(100000000091L)) + println("10 Numbers tested. A moment please …\nNumber crunching biggest 63-bit prime …") assert(isPrime(9223372036854775783L)) // Biggest 63-bit prime - assert(!isPrime(Long.MaxValue)) + println("All done") + +} diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala index 36c68e86b2..79fcdac8e4 100644 --- a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala @@ -1,10 +1,22 @@ - def isPrime(n: Int) = { +import scala.annotation.tailrec +import scala.io.Source + +object PrimesTestery extends App { + val rawText = Source.fromURL("https://oeis.org/A000040/a000040.txt") + val oeisPrimes = rawText.getLines().take(100000).map(_.split(" ")(1)).toVector + + def isPrime(n: Long) = { @tailrec - def inner(n: Int, k: Int): Boolean = { - if (k * k > n) true - else if (n % k != 0) inner(n, k + 2) else false + def inner(d: Int, end: Int): Boolean = { + if (d > end) true + else if (n % d != 0 && n % (d + 2) != 0) inner(d + 6, end) else false } - assume(n <= Int.MaxValue - 1) - n > 1 && ((n % 2 != 0) || (n == 2)) && inner(n, 3) + n > 1 && ((n & 1) != 0 || n == 2) && + (n % 3 != 0 || n == 3) && inner(5, math.sqrt(n).toInt) } + + println(oeisPrimes.size) + for (i <- 0 to 1299709) assert(isPrime(i) == oeisPrimes.contains(i.toString), s"Wrong $i") + +} diff --git a/Task/Probabilistic-choice/Ring/probabilistic-choice.ring b/Task/Probabilistic-choice/Ring/probabilistic-choice.ring index a032b5a7a3..38d01fdc0c 100644 --- a/Task/Probabilistic-choice/Ring/probabilistic-choice.ring +++ b/Task/Probabilistic-choice/Ring/probabilistic-choice.ring @@ -1,7 +1,4 @@ # Project : Probabilistic choice -# Date : 2017/10/01 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : cnt = list(8) item = ["aleph","beth","gimel","daleth","he","waw","zayin","heth"] diff --git a/Task/Pythagorean-triples/Nim/pythagorean-triples.nim b/Task/Pythagorean-triples/Nim/pythagorean-triples.nim index ffcd30cebc..f13d6a0d3b 100644 --- a/Task/Pythagorean-triples/Nim/pythagorean-triples.nim +++ b/Task/Pythagorean-triples/Nim/pythagorean-triples.nim @@ -6,7 +6,7 @@ var total, prim = 0 maxPeri = 10 -proc newTri(ins) = +proc newTri(ins: array[0..2, int]) = var p = ins[0] + ins[1] + ins[2] if p > maxPeri: return inc(prim) diff --git a/Task/Pythagorean-triples/Scala/pythagorean-triples.scala b/Task/Pythagorean-triples/Scala/pythagorean-triples.scala new file mode 100644 index 0000000000..94fc7d9db1 --- /dev/null +++ b/Task/Pythagorean-triples/Scala/pythagorean-triples.scala @@ -0,0 +1,25 @@ +object PythagoreanTriples extends App { + + println(" Limit Primatives All") + + for {e <- 2 to 7 + limit = math.pow(10, e).longValue() + } { + var primCount, tripCount = 0 + + def parChild(a: BigInt, b: BigInt, c: BigInt): Unit = { + val perim = a + b + c + val (a2, b2, c2, c3) = (2 * a, 2 * b, 2 * c, 3 * c) + if (limit >= perim) { + primCount += 1 + tripCount += (limit / perim).toInt + parChild(a - b2 + c2, a2 - b + c2, a2 - b2 + c3) + parChild(a + b2 + c2, a2 + b + c2, a2 + b2 + c3) + parChild(-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3) + } + } + + parChild(BigInt(3), BigInt(4), BigInt(5)) + println(f"a + b + c <= ${limit.toFloat}%3.1e $primCount%9d $tripCount%12d") + } +} diff --git a/Task/QR-decomposition/Java/qr-decomposition.java b/Task/QR-decomposition/Java/qr-decomposition.java new file mode 100644 index 0000000000..bd34e98409 --- /dev/null +++ b/Task/QR-decomposition/Java/qr-decomposition.java @@ -0,0 +1,25 @@ +import Jama.Matrix; +import Jama.QRDecomposition; + +import java.io.StringWriter; +import java.io.PrintWriter; + +public class Decompose { + public static void main(String[] args) { + Matrix matrix = new Matrix(new double[][] { + { 12, -51, 4 }, + { 6, 167, -68 }, + { -4, 24, -41 }, + }); + + QRDecomposition d = new QRDecomposition(matrix); + System.out.print(toString(d.getQ())); + System.out.print(toString(d.getR())); + } + + public static String toString(Matrix m) { + StringWriter sw = new StringWriter(); + m.print(new PrintWriter(sw, true), 8, 6); + return sw.toString(); + } +} diff --git a/Task/QR-decomposition/SAS/qr-decomposition.sas b/Task/QR-decomposition/SAS/qr-decomposition.sas index 5bca34da98..bf13201d18 100644 --- a/Task/QR-decomposition/SAS/qr-decomposition.sas +++ b/Task/QR-decomposition/SAS/qr-decomposition.sas @@ -28,5 +28,4 @@ quit; -14 -21 14 0 -175 70 0 0 35 - */ diff --git a/Task/QR-decomposition/Scala/qr-decomposition.scala b/Task/QR-decomposition/Scala/qr-decomposition.scala new file mode 100644 index 0000000000..b264bf588f --- /dev/null +++ b/Task/QR-decomposition/Scala/qr-decomposition.scala @@ -0,0 +1,22 @@ +import java.io.{PrintWriter, StringWriter} + +import Jama.{Matrix, QRDecomposition} + +object QRDecomposition extends App { + val matrix = + new Matrix( + Array[Array[Double]](Array(12, -51, 4), + Array(6, 167, -68), + Array(-4, 24, -41))) + val d = new QRDecomposition(matrix) + + def toString(m: Matrix): String = { + val sw = new StringWriter + m.print(new PrintWriter(sw, true), 8, 6) + sw.toString + } + + print(toString(d.getQ)) + print(toString(d.getR)) + +} diff --git a/Task/Quaternion-type/Factor/quaternion-type.factor b/Task/Quaternion-type/Factor/quaternion-type.factor new file mode 100644 index 0000000000..2c64478589 --- /dev/null +++ b/Task/Quaternion-type/Factor/quaternion-type.factor @@ -0,0 +1,27 @@ +USING: generalizations io kernel locals math.quaternions +math.vectors prettyprint sequences ; +IN: rosetta-code.quaternion-type + +: show ( quot -- ) + [ unparse 2 tail but-last "= " append write ] [ call . ] bi + ; inline + +: 2show ( quots -- ) + [ 2curry show ] map-compose [ call ] each ; inline + +: q+n ( q n -- q+n ) n>q q+ ; + +[let + { 1 2 3 4 } 7 { 2 3 4 5 } { 3 4 5 6 } :> ( q r q1 q2 ) + q [ norm ] + q [ vneg ] + q [ qconjugate ] + [ curry show ] 2tri@ + { + [ q r [ q+n ] ] + [ q r [ q*n ] ] + [ q1 q2 [ q+ ] ] + [ q1 q2 [ q* ] ] + [ q2 q1 [ q* ] ] + } 2show +] diff --git a/Task/Quaternion-type/Haskell/quaternion-type-1.hs b/Task/Quaternion-type/Haskell/quaternion-type-1.hs index 6d1623e540..d2fdd9e921 100644 --- a/Task/Quaternion-type/Haskell/quaternion-type-1.hs +++ b/Task/Quaternion-type/Haskell/quaternion-type-1.hs @@ -1,8 +1,10 @@ -import Control.Monad -import Control.Arrow -import Data.List +import Control.Monad (join) -data Quaternion = Q Double Double Double Double +data Quaternion = + Q Double + Double + Double + Double deriving (Show, Ord, Eq) realQ :: Quaternion -> Double @@ -11,23 +13,29 @@ realQ (Q r _ _ _) = r imagQ :: Quaternion -> [Double] imagQ (Q _ i j k) = [i, j, k] +quaternionFromScalar :: Double -> Quaternion quaternionFromScalar s = Q s 0 0 0 -listFromQ (Q a b c d) = [a,b,c,d] +listFromQ :: Quaternion -> [Double] +listFromQ (Q a b c d) = [a, b, c, d] + +quaternionFromList :: [Double] -> Quaternion quaternionFromList [a, b, c, d] = Q a b c d addQ, subQ, mulQ :: Quaternion -> Quaternion -> Quaternion -addQ (Q a b c d) (Q p q r s) = Q (a+p) (b+q) (c+r) (d+s) +addQ (Q a b c d) (Q p q r s) = Q (a + p) (b + q) (c + r) (d + s) -subQ (Q a b c d) (Q p q r s) = Q (a-p) (b-q) (c-r) (d-s) +subQ (Q a b c d) (Q p q r s) = Q (a - p) (b - q) (c - r) (d - s) mulQ (Q a b c d) (Q p q r s) = - Q (a*p - b*q - c*r - d*s) - (a*q + b*p + c*s - d*r) - (a*r - b*s + c*p + d*q) - (a*s + b*r - c*q + d*p) + Q + (a * p - b * q - c * r - d * s) + (a * q + b * p + c * s - d * r) + (a * r - b * s + c * p + d * q) + (a * s + b * r - c * q + d * p) -normQ = sqrt. sum. join (zipWith (*)). listFromQ +normQ :: Quaternion -> Double +normQ = sqrt . sum . join (zipWith (*)) . listFromQ conjQ, negQ :: Quaternion -> Quaternion conjQ (Q a b c d) = Q a (-b) (-c) (-d) diff --git a/Task/Quaternion-type/Haskell/quaternion-type-2.hs b/Task/Quaternion-type/Haskell/quaternion-type-2.hs index c88097d899..967242e6e3 100644 --- a/Task/Quaternion-type/Haskell/quaternion-type-2.hs +++ b/Task/Quaternion-type/Haskell/quaternion-type-2.hs @@ -1,4 +1,43 @@ -[q,q1,q2] = map quaternionFromList [[1..4],[2..5],[3..6]] --- a*b == b*a -test :: Quaternion -> Quaternion -> Bool -test a b = a `mulQ` b == b `mulQ` a +class Quaternion(a, b, c, d) + + method norm () + return sqrt (a*a + b*b + c*c + d*d) + end + + method negative () + return Quaternion(-a, -b, -c, -d) + end + + method conjugate () + return Quaternion(a, -b, -c, -d) + end + + method add (n) + if type(n) == "Quaternion__state" + then return Quaternion(a+n.a, b+n.b, c+n.c, d+n.d) + else return Quaternion(a+n, b, c, d) + end + + method multiply (n) + if type(n) == "Quaternion__state" + then return Quaternion(a*n.a - b*n.b - c*n.c - d*n.d, + a*n.b + b*n.a + c*n.d - d*n.c, + a*n.c - b*n.d + c*n.a + d*n.b, + a*n.d + b*n.c - c*n.b + d*n.a) + else return Quaternion(a*n, b*n, c*n, d*n) + end + + method sign (n) + return if n >= 0 then "+" else "-" + end + + method string () + return ("" || a || sign(b) || abs(b) || "i" || sign(c) || abs(c) || "j" || sign(d) || abs(d) || "k"); + end + + initially(a, b, c, d) + self.a := if /a then 0 else a + self.b := if /b then 0 else b + self.c := if /c then 0 else c + self.d := if /d then 0 else d +end diff --git a/Task/Quaternion-type/Haskell/quaternion-type-3.hs b/Task/Quaternion-type/Haskell/quaternion-type-3.hs index 967242e6e3..39c472f34f 100644 --- a/Task/Quaternion-type/Haskell/quaternion-type-3.hs +++ b/Task/Quaternion-type/Haskell/quaternion-type-3.hs @@ -1,43 +1,16 @@ -class Quaternion(a, b, c, d) +procedure main () + q := Quaternion (1,2,3,4) + q1 := Quaternion (2,3,4,5) + q2 := Quaternion (3,4,5,6) + r := 7 - method norm () - return sqrt (a*a + b*b + c*c + d*d) - end - - method negative () - return Quaternion(-a, -b, -c, -d) - end - - method conjugate () - return Quaternion(a, -b, -c, -d) - end - - method add (n) - if type(n) == "Quaternion__state" - then return Quaternion(a+n.a, b+n.b, c+n.c, d+n.d) - else return Quaternion(a+n, b, c, d) - end - - method multiply (n) - if type(n) == "Quaternion__state" - then return Quaternion(a*n.a - b*n.b - c*n.c - d*n.d, - a*n.b + b*n.a + c*n.d - d*n.c, - a*n.c - b*n.d + c*n.a + d*n.b, - a*n.d + b*n.c - c*n.b + d*n.a) - else return Quaternion(a*n, b*n, c*n, d*n) - end - - method sign (n) - return if n >= 0 then "+" else "-" - end - - method string () - return ("" || a || sign(b) || abs(b) || "i" || sign(c) || abs(c) || "j" || sign(d) || abs(d) || "k"); - end - - initially(a, b, c, d) - self.a := if /a then 0 else a - self.b := if /b then 0 else b - self.c := if /c then 0 else c - self.d := if /d then 0 else d + write ("The norm of " || q.string() || " is " || q.norm ()) + write ("The negative of " || q.string() || " is " || q.negative().string ()) + write ("The conjugate of " || q.string() || " is " || q.conjugate().string ()) + write ("Sum of " || q.string() || " and " || r || " is " || q.add(r).string ()) + write ("Sum of " || q.string() || " and " || q1.string() || " is " || q.add(q1).string ()) + write ("Product of " || q.string() || " and " || r || " is " || q.multiply(r).string ()) + write ("Product of " || q.string() || " and " || q1.string() || " is " || q.multiply(q1).string ()) + write ("q1*q2 = " || q1.multiply(q2).string ()) + write ("q2*q1 = " || q2.multiply(q1).string ()) end diff --git a/Task/Quaternion-type/REXX/quaternion-type.rexx b/Task/Quaternion-type/REXX/quaternion-type.rexx index 331299b6c3..bf8ea57449 100644 --- a/Task/Quaternion-type/REXX/quaternion-type.rexx +++ b/Task/Quaternion-type/REXX/quaternion-type.rexx @@ -1,45 +1,43 @@ -/*REXX pgm performs some operations on quaternion type numbers and shows results*/ - q = 1 2 3 4 ; q1 = 2 3 4 5 - r = 7 ; q2 = 3 4 5 6 -call qShow q , 'q' -call qShow q1 , 'q1' -call qShow q2 , 'q2' -call qShow r , 'r' -call qShow qNorm(q) , 'norm q' , "task 1:" -call qShow qNeg(q) , 'negative q' , "task 2:" -call qShow qConj(q) , 'conjugate q' , "task 3:" -call qShow qAdd( r, q ) , 'addition r+q' , "task 4:" -call qShow qAdd(q1, q2 ) , 'addition q1+q2' , "task 5:" -call qShow qMul( q, r ) , 'multiplication q*r' , "task 6:" -call qShow qMul(q1, q2 ) , 'multiplication q1*q2' , "task 7:" -call qShow qMul(q2, q1 ) , 'multiplication q2*q1' , "task 8:" -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────*/ -qConj: procedure; parse arg x; call qXY; return x.1 (-x.2) (-x.3) (-x.4) -qNeg: procedure; parse arg x; call qXY; return -x.1 (-x.2) (-x.3) (-x.4) -/*──────────────────────────────────────────────────────────────────────────────*/ -qAdd: procedure; parse arg x,y; call qXY 2; return x.1+y.1 x.2+y.2 x.3+y.3 x.4+y.4 -/*──────────────────────────────────────────────────────────────────────────────*/ +/*REXX program performs some operations on quaternion type numbers and displays results*/ + q = 1 2 3 4 ; q1 = 2 3 4 5 + r = 7 ; q2 = 3 4 5 6 +call qShow q , 'q' +call qShow q1 , 'q1' +call qShow q2 , 'q2' +call qShow r , 'r' +call qShow qNorm(q) , 'norm q' , "task 1:" +call qShow qNeg(q) , 'negative q' , "task 2:" +call qShow qConj(q) , 'conjugate q' , "task 3:" +call qShow qAdd( r, q ) , 'addition r+q' , "task 4:" +call qShow qAdd(q1, q2 ) , 'addition q1+q2' , "task 5:" +call qShow qMul( q, r ) , 'multiplication q*r' , "task 6:" +call qShow qMul(q1, q2 ) , 'multiplication q1*q2' , "task 7:" +call qShow qMul(q2, q1 ) , 'multiplication q2*q1' , "task 8:" +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +qConj: procedure; parse arg x; call qXY; return x.1 (-x.2) (-x.3) (-x.4) +qNeg: procedure; parse arg x; call qXY; return -x.1 (-x.2) (-x.3) (-x.4) +qNorm: procedure; parse arg x; call qXY; return sqrt(x.1**2 +x.2**2 +x.3**2 +x.4**2) +qAdd: procedure; parse arg x,y; call qXY 2; return x.1+y.1 x.2+y.2 x.3+y.3 x.4+y.4 +/*──────────────────────────────────────────────────────────────────────────────────────*/ qMul: procedure; parse arg x,y; call qXY y - return x.1*y.1-x.2*y.2-x.3*y.3-x.4*y.4 x.1*y.2+x.2*y.1+x.3*y.4-x.4*y.3, - x.1*y.3-x.2*y.4+x.3*y.1+x.4*y.2 x.1*y.4+x.2*y.3-x.3*y.2+x.4*y.1 -/*──────────────────────────────────────────────────────────────────────────────*/ -qNorm: procedure; parse arg x; call qXY; return sqrt(x.1**2+x.2**2+x.3**2+x.4**2) -/*──────────────────────────────────────────────────────────────────────────────*/ -qShow: procedure; parse arg x; call qXY; $= - do m=1 for 4; _=x.m; if _==0 then iterate; if _>=0 then _='+'_ - if m\==1 then _=_ || substr('~ijk',m,1); $=strip($ || _,,'+') + return x.1*y.1 -x.2*y.2 -x.3*y.3 -x.4*y.4 x.1*y.2 +x.2*y.1 +x.3*y.4 -x.4*y.3 , + x.1*y.3 -x.2*y.4 +x.3*y.1 +x.4*y.2 x.1*y.4 +x.2*y.3 -x.3*y.2 +x.4*y.1 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +qShow: procedure; parse arg x; call qXY; $= + do m=1 for 4; _=x.m; if _==0 then iterate; if _>=0 then _="+"_ + if m\==1 then _= _ || substr('~ijk', m, 1); $=strip($ || _,,"+") end /*m*/ - say left(arg(3),9) right(arg(2),20) ' ──► ' $ + say left(arg(3), 9) right(arg(2), 20) ' ──► ' $ return $ -/*──────────────────────────────────────────────────────────────────────────────*/ -qXY: do n=1 for 4; x.n=word(word(x,n) 0,1)/1; end /*n*/ - if arg()==1 then do m=1 for 4; y.m=word(word(y,m) 0,1)/1; end /*m*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +qXY: do n=1 for 4; x.n= word( word(x, n) 0, 1) / 1; end /*n*/ + if arg()==1 then do m=1 for 4; y.m= word( word(y, m) 0, 1) / 1; end /*m*/ 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; if x=0 then return 0; d= digits(); i=; m.=9; h=d+6 + numeric digits; numeric form; 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/Quaternion-type/Scala/quaternion-type-1.scala b/Task/Quaternion-type/Scala/quaternion-type-1.scala index 8d912a8272..2b466a6cd9 100644 --- a/Task/Quaternion-type/Scala/quaternion-type-1.scala +++ b/Task/Quaternion-type/Scala/quaternion-type-1.scala @@ -1,36 +1,31 @@ -case class Quaternion(re:Double =0.0, i:Double =0.0, j:Double =0.0, k:Double =0.0) { - lazy val im=(i, j, k) - private lazy val norm2=re*re + i*i + j*j + k*k - lazy val norm=math.sqrt(norm2) +case class Quaternion(re: Double = 0.0, i: Double = 0.0, j: Double = 0.0, k: Double = 0.0) { + lazy val im = (i, j, k) + private lazy val norm2 = re*re + i*i + j*j + k*k + lazy val norm = math.sqrt(norm2) - def negative=new Quaternion(-re, -i, -j, -k) - def conjugate=new Quaternion(re, -i, -j, -k) - def reciprocal=new Quaternion(re/norm2, -i/norm2, -j/norm2, -k/norm2) + def negative = Quaternion(-re, -i, -j, -k) + def conjugate = Quaternion(re, -i, -j, -k) + def reciprocal = Quaternion(re/norm2, -i/norm2, -j/norm2, -k/norm2) - def +(q:Quaternion)=new Quaternion(re+q.re, i+q.i, j+q.j, k+q.k) - def -(q:Quaternion)=new Quaternion(re-q.re, i-q.i, j-q.j, k-q.k) - def *(q:Quaternion)=new Quaternion( + def +(q: Quaternion) = Quaternion(re+q.re, i+q.i, j+q.j, k+q.k) + def -(q: Quaternion) = Quaternion(re-q.re, i-q.i, j-q.j, k-q.k) + def *(q: Quaternion) = Quaternion( re*q.re - i*q.i - j*q.j - k*q.k, re*q.i + i*q.re + j*q.k - k*q.j, re*q.j - i*q.k + j*q.re + k*q.i, re*q.k + i*q.j - j*q.i + k*q.re ) - def /(q:Quaternion)=this*q.reciprocal + def /(q: Quaternion) = this * q.reciprocal def unary_- = negative def unary_~ = conjugate - override def equals(x:Any):Boolean=x match { - case Quaternion(re, i, j, k) => (Double.doubleToLongBits(this.re)==Double.doubleToLongBits(re)) && - Double.doubleToLongBits(this.i)==Double.doubleToLongBits(i) && - Double.doubleToLongBits(this.j)==Double.doubleToLongBits(j) && - Double.doubleToLongBits(this.k)==Double.doubleToLongBits(k) - case _ => false - } - - override def toString()="Q(%.2f, %.2fi, %.2fj, %.2fk)".formatLocal(Locale.ENGLISH, re,i,j,k) + override def toString = "Q(%.2f, %.2fi, %.2fj, %.2fk)".formatLocal(java.util.Locale.ENGLISH, re, i, j, k) } object Quaternion { - implicit def number2Quaternion[T <% Number](n:T):Quaternion = apply(n.doubleValue) + import scala.language.implicitConversions + import Numeric.Implicits._ + + implicit def number2Quaternion[T:Numeric](n: T) = Quaternion(n.toDouble) } diff --git a/Task/Queue-Definition/REBOL/queue-definition.rebol b/Task/Queue-Definition/REBOL/queue-definition.rebol index 4c6f1bd0e1..e8e0178e33 100644 --- a/Task/Queue-Definition/REBOL/queue-definition.rebol +++ b/Task/Queue-Definition/REBOL/queue-definition.rebol @@ -1,7 +1,5 @@ rebol [ Title: "FIFO" - Author: oofoe - Date: 2009-12-11 URL: http://rosettacode.org/wiki/FIFO ] diff --git a/Task/Queue-Definition/Ring/queue-definition.ring b/Task/Queue-Definition/Ring/queue-definition.ring new file mode 100644 index 0000000000..950c71743f --- /dev/null +++ b/Task/Queue-Definition/Ring/queue-definition.ring @@ -0,0 +1,19 @@ +# Project : Queue/Definition + +load "stdlib.ring" +oQueue = new Queue +for n = 5 to 7 + see "Push: " + n + nl + oQueue.add(n) +next +see "Pop: " + oQueue.remove() + nl +see "Push: 8" + nl +oQueue.add(8) +see "Pop: " + oQueue.remove() + nl +see "Pop: " + oQueue.remove() + nl +see "Pop: " + oQueue.remove() + nl +if len(oQueue) != 0 + oQueue.print() +else + see "Error: queue is empty" + nl +ok diff --git a/Task/Queue-Usage/Astro/queue-usage.astro b/Task/Queue-Usage/Astro/queue-usage.astro index 0e2ab25d31..a0899cb5b6 100644 --- a/Task/Queue-Usage/Astro/queue-usage.astro +++ b/Task/Queue-Usage/Astro/queue-usage.astro @@ -1,7 +1,9 @@ -let myQueue = Queue[Str]() -myQueue.push 'foo' -myQueue.push 'bar' -myQueue.push 'baz' -print myQueue.pop() # 'foo' -print myQueue.pop() # 'bar' -print myQueue.pop() # 'baz' +let my_queue = Queue[Str]() + +my_queue.push! 'foo' +my_queue.push! 'bar' +my_queue.push! 'baz' + +print my_queue.pop() # 'foo' +print my_queue.pop() # 'bar' +print my_queue.pop() # 'baz' diff --git a/Task/Queue-Usage/Factor/queue-usage-1.factor b/Task/Queue-Usage/Factor/queue-usage-1.factor new file mode 100644 index 0000000000..d3b3f23a09 --- /dev/null +++ b/Task/Queue-Usage/Factor/queue-usage-1.factor @@ -0,0 +1,13 @@ +USING: combinators deques dlists kernel prettyprint ; +IN: rosetta-code.queue-usage + +DL{ } clone { ! make new queue + [ [ 1 ] dip push-front ] ! push 1 + [ [ 2 ] dip push-front ] ! push 2 + [ [ 3 ] dip push-front ] ! push 3 + [ . ] ! DL{ 3 2 1 } + [ pop-back drop ] ! pop 1 (and discard) + [ pop-back drop ] ! pop 2 (and discard) + [ pop-back drop ] ! pop 3 (and discard) + [ deque-empty? . ] ! t +} cleave diff --git a/Task/Queue-Usage/Factor/queue-usage-2.factor b/Task/Queue-Usage/Factor/queue-usage-2.factor new file mode 100644 index 0000000000..46768a0ea3 --- /dev/null +++ b/Task/Queue-Usage/Factor/queue-usage-2.factor @@ -0,0 +1,6 @@ +DL{ } clone { + [ [ { 1 2 3 } ] dip push-all-front ] ! push all from sequence + [ . ] ! DL{ 3 2 1 } + [ [ drop ] slurp-deque ] ! pop and discard all + [ deque-empty? . ] ! t +} cleave diff --git a/Task/Queue-Usage/Maple/queue-usage.maple b/Task/Queue-Usage/Maple/queue-usage.maple new file mode 100644 index 0000000000..f11cc1b901 --- /dev/null +++ b/Task/Queue-Usage/Maple/queue-usage.maple @@ -0,0 +1,14 @@ +q := queue[new](); +queue[enqueue](q,1); +queue[enqueue](q,2); +queue[enqueue](q,3); +queue[empty](q); +>>>false +queue[dequeue](q); +>>>1 +queue[dequeue](q); +>>>2 +queue[dequeue](q); +>>>3 +queue[empty](q); +>>>true diff --git a/Task/Quickselect-algorithm/Nim/quickselect-algorithm.nim b/Task/Quickselect-algorithm/Nim/quickselect-algorithm.nim index 126b91ddeb..f7b97a840e 100644 --- a/Task/Quickselect-algorithm/Nim/quickselect-algorithm.nim +++ b/Task/Quickselect-algorithm/Nim/quickselect-algorithm.nim @@ -1,7 +1,7 @@ proc qselect[T](a: var openarray[T]; k: int, inl = 0, inr = -1): T = var r = if inr >= 0: inr else: a.high var st = 0 - for i in 0 .. < r: + for i in 0 ..< r: if a[i] > a[r]: continue swap a[i], a[st] inc st diff --git a/Task/Quine/Nim/quine-2.nim b/Task/Quine/Nim/quine-2.nim index 1e6464f902..fe3ddfa9a8 100644 --- a/Task/Quine/Nim/quine-2.nim +++ b/Task/Quine/Nim/quine-2.nim @@ -1,2 +1,2 @@ -const x = "var x = echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. -1]" -echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. -1] +const x = "var x = echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. ^1]" +echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. ^1] diff --git a/Task/Quine/Nim/quine-3.nim b/Task/Quine/Nim/quine-3.nim index a84a5df4f6..80c7f36374 100644 --- a/Task/Quine/Nim/quine-3.nim +++ b/Task/Quine/Nim/quine-3.nim @@ -1,4 +1,4 @@ -const x = "const x = |const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. -1]|static: echo y|echo y" -const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. -1] +const x = "const x = |const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. ^1]|static: echo y|echo y" +const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. ^1] static: echo y echo y diff --git a/Task/RIPEMD-160/Mathematica/ripemd-160.math b/Task/RIPEMD-160/Mathematica/ripemd-160.math new file mode 100644 index 0000000000..56404d1fa6 --- /dev/null +++ b/Task/RIPEMD-160/Mathematica/ripemd-160.math @@ -0,0 +1 @@ +Hash["Rosetta code","RIPEMD160","HexString"] diff --git a/Task/RIPEMD-160/Phix/ripemd-160-1.phix b/Task/RIPEMD-160/Phix/ripemd-160-1.phix new file mode 100644 index 0000000000..74593258fb --- /dev/null +++ b/Task/RIPEMD-160/Phix/ripemd-160-1.phix @@ -0,0 +1,4 @@ +include builtins\ripemd160.e + +constant test = "Rosetta Code" +printf(1,"\n%s => %s\n",{test,ripemd160(test)}) diff --git a/Task/RIPEMD-160/Phix/ripemd-160-2.phix b/Task/RIPEMD-160/Phix/ripemd-160-2.phix new file mode 100644 index 0000000000..ca2d577296 --- /dev/null +++ b/Task/RIPEMD-160/Phix/ripemd-160-2.phix @@ -0,0 +1,108 @@ +-- +-- builtins\ripemd160.e +-- ==================== +-- +function rol(atom v, integer n) +-- Programming note: this use of #ilASM{} is more for expediency than efficiency + #ilASM{ mov eax,[v] + call :%pLoadMint + mov ecx,[n] + rol eax,cl + lea edi,[v] + call :%pStoreMint } + return v +end function + +constant K = {#00000000,#5A827999,#6ED9EBA1,#8F1BBCDC,#A953FD4E}, + KK = {#50A28BE6,#5C4DD124,#6D703EF3,#7A6D76E9,#00000000}, + r = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }, + rr = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }, + s = {11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }, + ss = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 } + +global function ripemd160(string message, bool asString=true, atom pMem=NULL) +-- +-- Calculate the ripe-md-160 checksum. +-- +-- if asString is true (the default), returns a string representation of the +-- checksum (and pMem is ignored) +-- if asString is false, returns pMem (for want of anything better), which +-- must be a non-NULL pointer to at least 20 bytes of memory. +-- + atom h0 = #67452301, + h1 = #EFCDAB89, + h2 = #98BADCFE, + h3 = #10325476, + h4 = #C3D2E1F0, + mraw, t, tt + + integer l = length(message), + padding = 64 - mod(l+1,64) + if padding<8 then padding += 64 end if + + message &= #80 & repeat('\0',padding-8) + & int_to_bytes(l*8,8) + + #ilASM{ mov eax,[message] + lea edi,[mraw] + shl eax,2 -- ref -> raw address + call :%pStoreMint } + + for i=0 to length(message)-64 by 64 do + atom {a, b, c, d, e} = {h0, h1, h2, h3, h4} + atom {aa, bb, cc, dd, ee} = {h0, h1, h2, h3, h4} + for j = 1 to 80 do + integer k = floor((j-1)/16) + switch k + case 0: + t = xor_bits(xor_bits(b, c), d) + tt = xor_bits(bb,or_bits(cc,not_bits(dd))) + case 1: + t = or_bits(and_bits(b,c),and_bits(not_bits(b),d)) + tt = or_bits(and_bits(bb,dd),and_bits(cc,not_bits(dd))) + case 2: + t = xor_bits(or_bits(b,not_bits(c)),d) + tt = xor_bits(or_bits(bb,not_bits(cc)),dd) + case 3: + t = or_bits(and_bits(b,d),and_bits(c,not_bits(d))) + tt = or_bits(and_bits(bb,cc),and_bits(not_bits(bb),dd)) + case 4: + t = xor_bits(b,or_bits(c,not_bits(d))) + tt = xor_bits(xor_bits(bb, cc), dd) + end switch + t = rol( a + t + peek4u(mraw+i+ r[j]*4) + K[k+1], s[j]) + e + tt = rol(aa + tt + peek4u(mraw+i+rr[j]*4) + KK[k+1], ss[j]) + ee + {a, e, d, c, b } = {e, d, rol(c, 10), b, t } + {aa,ee,dd,cc,bb} = {ee,dd,rol(cc, 10),bb,tt} + end for + {h0, h1, h2, h3, h4} = {h1+c+dd, h2+d+ee, h3+e+aa, h4+a+bb, h0+b+cc} + end for + if not asString then + if pMem=NULL then ?9/0 end if + poke4(pMem,{h0,h1,h2,h3,h4}) + return pMem + end if + atom mem = allocate(20,true) + poke4(mem,{h0,h1,h2,h3,h4}) + string res = "" + for i=1 to 20 do + res &= sprintf("%02X",peek(mem+i-1)) + end for + return res +end function diff --git a/Task/Random-number-generator--device-/Phix/random-number-generator--device--1.phix b/Task/Random-number-generator--device-/Phix/random-number-generator--device--1.phix new file mode 100644 index 0000000000..e950e3241c --- /dev/null +++ b/Task/Random-number-generator--device-/Phix/random-number-generator--device--1.phix @@ -0,0 +1,55 @@ +integer res -- 1=failure, 0=success +atom rint = 0 -- random 32-bit int + +#ilASM{ + mov eax,1 + cpuid + bt ecx,30 + mov edi,1 -- exit code: failure + jnc :exit + + -- rdrand sets CF=0 if no random number + -- was available. Intel documentation + -- recommends 10 retries in a tight loop + mov ecx,11 + ::loop1 + sub ecx, 1 + jz :exit -- exit code is set already + rdrand eax + -- (the above generates exception #C000001D if not supported) +-- rdtsc + jnc :loop1 + + lea edi,[rint] + call :%pStoreMint + xor edi,edi + + ::exit + mov [res],edi + xor ebx,ebx -- important! + } + +?{res,rint} + +if res=0 then -- (success) + + -- + -- To convert a signed 32-bit int to an unsigned one: + -- + -- method 1 +-- atom urint1 = rint +-- if urint1<0 then urint1+=#100000000 end if + atom urint1 = rint+iff(rint<0?#100000000:0) + + -- method 2 + atom pMem = allocate(4) + poke4(pMem,rint) + atom urint2 = peek4u(pMem) + free(pMem) + + -- method 3 + atom urint3 = bytes_to_int(int_to_bytes(rint,4),signed:=false) + + ?{urint1,urint2,urint3} + +end if diff --git a/Task/Random-number-generator--device-/Phix/random-number-generator--device--2.phix b/Task/Random-number-generator--device-/Phix/random-number-generator--device--2.phix new file mode 100644 index 0000000000..f2c28bd158 --- /dev/null +++ b/Task/Random-number-generator--device-/Phix/random-number-generator--device--2.phix @@ -0,0 +1,11 @@ +integer fn = open("/dev/urandom","rb") +if fn=-1 then + puts(1,"cannot open /dev/urandom\n") +else + sequence s = {} + for i=1 to 4 do + s &= getc(fn) + end for + close(fn) + ?bytes_to_int(s,signed:=false) +end if diff --git a/Task/Range-expansion/Ring/range-expansion.ring b/Task/Range-expansion/Ring/range-expansion.ring index a1c7147d6c..640c3cee55 100644 --- a/Task/Range-expansion/Ring/range-expansion.ring +++ b/Task/Range-expansion/Ring/range-expansion.ring @@ -1,7 +1,4 @@ # Project : Range expansion -# Date : 2017/11/08 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : int = "-6,-3--1,3-5,7-11,14,15,17-20" int = str2list(substr(int, ",", nl)) diff --git a/Task/Range-extraction/Maple/range-extraction.maple b/Task/Range-extraction/Maple/range-extraction.maple new file mode 100644 index 0000000000..d6c044ce78 --- /dev/null +++ b/Task/Range-extraction/Maple/range-extraction.maple @@ -0,0 +1,12 @@ +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]: +r1,r2:= lst[1],lst[1]: +for i from 2 to numelems(lst) do + if lst[i] - lst[i-1] = 1 then #consecutive + r2 := lst[i]: + else #break + printf(piecewise(r2-r1=1, "%d,%d,", r2-r1>1,"%d-%d,", "%d,"), r1, r2): + r1,r2:= lst[i],lst[i]: + fi: +od: +printf(piecewise(r2-r1=1, "%d,%d", r2-r1>1,"%d-%d", "%d"), r1, r2): diff --git a/Task/Range-extraction/Ring/range-extraction.ring b/Task/Range-extraction/Ring/range-extraction.ring index 95bccc3895..f7e9677256 100644 --- a/Task/Range-extraction/Ring/range-extraction.ring +++ b/Task/Range-extraction/Ring/range-extraction.ring @@ -1,7 +1,4 @@ # Project : Range extraction -# Date : 2017/11/08 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : int = "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" int = str2list(substr(int, ",", nl)) diff --git a/Task/Ranking-methods/C/ranking-methods.c b/Task/Ranking-methods/C/ranking-methods.c index e48fa469a7..7a228a2212 100644 --- a/Task/Ranking-methods/C/ranking-methods.c +++ b/Task/Ranking-methods/C/ranking-methods.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 5th November 2017*/ - #include #include diff --git a/Task/Rate-counter/Ring/rate-counter.ring b/Task/Rate-counter/Ring/rate-counter.ring index f07ac21f5f..77aacd5b91 100644 --- a/Task/Rate-counter/Ring/rate-counter.ring +++ b/Task/Rate-counter/Ring/rate-counter.ring @@ -1,7 +1,4 @@ # 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 diff --git a/Task/Read-a-file-line-by-line/Ada/read-a-file-line-by-line.ada b/Task/Read-a-file-line-by-line/Ada/read-a-file-line-by-line.ada index ad07b813ee..c1ad59e290 100644 --- a/Task/Read-a-file-line-by-line/Ada/read-a-file-line-by-line.ada +++ b/Task/Read-a-file-line-by-line/Ada/read-a-file-line-by-line.ada @@ -6,8 +6,7 @@ begin Open (File => File, Mode => In_File, Name => "line_by_line.adb"); - loop - exit when End_Of_File (File); + While not End_Of_File (File) Loop Put_Line (Get_Line (File)); end loop; 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 index 27ec5a587d..b1c721c82b 100644 --- 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 @@ -1,3 +1,2 @@ -try f = open('foobar.txt'): - for line in lines f: - print line +for line in lines open('input.txt'): + print line 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 92a9d5b1ee..7c698fa614 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,25 +1,30 @@ -// From manpage for "getline" - +/* + * Read (and write) the standard input file + * linie-by-line. This version is for ASCII + * encoded text files. + */ #include -#include + +/* + * BUFSIZE is a max size of line plus 1. + * + * It would be nice to dynamically allocate bigger buffer for longer lines etc. + * - but this example is as simple as possible. Dynamic buffer allocation from + * the heap may not be a good idea as it seems, because it can cause memory + * segmentation in embeded systems. + */ +#define BUFSIZE 1024 int main(void) { - FILE *stream; - char *line = NULL; - size_t len = 0; - ssize_t read; + static char buffer[BUFSIZE]; - stream = fopen("file.txt", "r"); - if (stream == NULL) - exit(EXIT_FAILURE); + /* + * Never use gets() instead fgets(), because gets() + * is a really unsafe function. + */ + while (fgets(buffer, BUFSIZE, stdin)) + puts(buffer); - while ((read = getline(&line, &len, stream)) != -1) { - printf("Retrieved line of length %u :\n", read); - printf("%s", line); - } - - free(line); - fclose(stream); - exit(EXIT_SUCCESS); + return 0; } 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 c6c2bacffa..92a9d5b1ee 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,75 +1,25 @@ +// From manpage for "getline" + #include -#include -#include -#include -#include -#include -#include -#include +#include -int read_lines(const char * fname, int (*call_back)(const char*, const char*)) +int main(void) { - int fd = open(fname, O_RDONLY); - struct stat fs; - char *buf, *buf_end; - char *begin, *end, c; + FILE *stream; + char *line = NULL; + size_t len = 0; + ssize_t read; - if (fd == -1) { - err(1, "open: %s", fname); - return 0; - } + stream = fopen("file.txt", "r"); + if (stream == NULL) + exit(EXIT_FAILURE); - if (fstat(fd, &fs) == -1) { - err(1, "stat: %s", fname); - return 0; - } + while ((read = getline(&line, &len, stream)) != -1) { + printf("Retrieved line of length %u :\n", read); + printf("%s", line); + } - /* 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; + free(line); + fclose(stream); + exit(EXIT_SUCCESS); } 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 new file mode 100644 index 0000000000..c6c2bacffa --- /dev/null +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c @@ -0,0 +1,75 @@ +#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-specific-line-from-a-file/Maple/read-a-specific-line-from-a-file.maple b/Task/Read-a-specific-line-from-a-file/Maple/read-a-specific-line-from-a-file.maple new file mode 100644 index 0000000000..913a8f095d --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Maple/read-a-specific-line-from-a-file.maple @@ -0,0 +1,10 @@ +path := "file.txt": +specificLine := proc(path, num) + local i, input: + for i to num do + input := readline(path): + if input = 0 then break; end if: + end do: + if i = num+1 then printf("Line %d, %s", num, input): + elif i <= num then printf ("Line number %d is not reached",num): end if: +end proc: diff --git a/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring b/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring index 281a6642ae..1c6c93e827 100644 --- a/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring +++ b/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring @@ -1,7 +1,4 @@ # Project : Reduced row echelon form -# Date : 2017/12/27 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : matrix = [[1, 2, -1, -4], [2, 3, -1, -11], diff --git a/Task/Regular-expressions/REBOL/regular-expressions.rebol b/Task/Regular-expressions/REBOL/regular-expressions.rebol index 00cbde1272..c2f8ae8c94 100644 --- a/Task/Regular-expressions/REBOL/regular-expressions.rebol +++ b/Task/Regular-expressions/REBOL/regular-expressions.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Regular Expression Matching" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Regular_expression_matching ] diff --git a/Task/Regular-expressions/Ring/regular-expressions.ring b/Task/Regular-expressions/Ring/regular-expressions.ring index 88fb3cafd9..cca77df0f4 100644 --- a/Task/Regular-expressions/Ring/regular-expressions.ring +++ b/Task/Regular-expressions/Ring/regular-expressions.ring @@ -1,7 +1,4 @@ # Project : Regular expressions -# Date : 2018/01/23 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : text = "I am a text" if right(text,4) = "text" 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 467ff01f07..4c4a3596b1 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 @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; public class Rosetta { diff --git a/Task/Rep-string/Factor/rep-string.factor b/Task/Rep-string/Factor/rep-string.factor new file mode 100644 index 0000000000..729aea0b42 --- /dev/null +++ b/Task/Rep-string/Factor/rep-string.factor @@ -0,0 +1,15 @@ +USING: formatting grouping kernel math math.ranges qw sequences ; +IN: rosetta-code.rep-string + +: (find-rep-string) ( str -- str ) + dup dup length 2/ [1,b] + [ [ head? ] monotonic? ] with find nip dup + [ head ] [ 2drop "N/A" ] if ; + +: find-rep-string ( str -- str ) + dup length 1 <= [ drop "N/A" ] [ (find-rep-string) ] if ; + +qw{ 1001110011 1110111011 0010010010 1010101010 1111111111 + 0100101101 0100100 101 11 00 1 } +"Shortest cycle:\n\n" printf +[ dup find-rep-string "%-10s -> %s\n" printf ] each diff --git a/Task/Rep-string/Ring/rep-string.ring b/Task/Rep-string/Ring/rep-string.ring index 4d5e6850e7..f19b91fbd4 100644 --- a/Task/Rep-string/Ring/rep-string.ring +++ b/Task/Rep-string/Ring/rep-string.ring @@ -1,8 +1,4 @@ # Project : Rep-string -# Date : 2017/10/14 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : - test = ["1001110011", "1110111011", diff --git a/Task/Repeat-a-string/Crystal/repeat-a-string-1.crystal b/Task/Repeat-a-string/Crystal/repeat-a-string-1.crystal new file mode 100644 index 0000000000..40f0c9a626 --- /dev/null +++ b/Task/Repeat-a-string/Crystal/repeat-a-string-1.crystal @@ -0,0 +1 @@ +puts "ha" * 5 diff --git a/Task/Repeat-a-string/Crystal/repeat-a-string-2.crystal b/Task/Repeat-a-string/Crystal/repeat-a-string-2.crystal new file mode 100644 index 0000000000..d8dbb13079 --- /dev/null +++ b/Task/Repeat-a-string/Crystal/repeat-a-string-2.crystal @@ -0,0 +1 @@ +hahahahaha diff --git a/Task/Repeat-a-string/Transact-SQL/repeat-a-string.sql b/Task/Repeat-a-string/Transact-SQL/repeat-a-string.sql new file mode 100644 index 0000000000..5ab37270f5 --- /dev/null +++ b/Task/Repeat-a-string/Transact-SQL/repeat-a-string.sql @@ -0,0 +1 @@ +select REPLICATE( 'ha', 5 ) diff --git a/Task/Resistor-mesh/FreeBASIC/resistor-mesh.freebasic b/Task/Resistor-mesh/FreeBASIC/resistor-mesh.freebasic new file mode 100644 index 0000000000..7524497589 --- /dev/null +++ b/Task/Resistor-mesh/FreeBASIC/resistor-mesh.freebasic @@ -0,0 +1,81 @@ +' version 01-07-2018 +' compile with: fbc -s console + +#Define n 10 + +Dim As UInteger nn = n * n +Dim As Double g(-nn To nn +1, -nn To nn +1) +Dim As UInteger node, row, col + +For row = 1 To n + For col = 1 To n + node += 1 + If row > 1 Then + g(node, node) += 1 + g(node, node - n) = -1 + End If + If row < n Then + g(node, node) += 1 + g(node, node + n) = -1 + End If + If col > 1 Then + g(node, node) += 1 + g(node, node -1) = -1 + End If + If col < n Then + g(node, node) += 1 + g(node, node +1) = -1 + End If + Next +Next + +Dim As UInteger ar = 2, ac = 2 +Dim As UInteger br = 7, bc = 8 +Dim As UInteger a = ac + n * (ar -1) +Dim As UInteger b = bc + n * (br -1) + +g(a, nn +1) = -1 +g(b, nn +1) = 1 + +Print : Print "Nodes a: "; a, " b: "; b + +' solve linear system using Gauss-Seidel method with pivoting +Dim As UInteger i, j, k +Dim As Double y + +Do + For j = 1 To nn + For i = j To nn + If g(i, j) <> 0 Then Exit For + Next + If i = nn +1 Then + Print : Print "No solution" + Exit Do + End If + For k = 1 To nn +1 + Swap g(j, k), g(i, k) + Next + y = g(j, j) + For k = 1 To nn +1 + g(j, k) = g(j, k) / y + Next + For i = 1 To nn + If i <> j Then + y = -g(i, j) + For k = 1 To nn +1 + g(i, k) = g(i, k) + y * g(j, k) + Next + End If + Next + Next + + Print + Print "Resistance ="; Abs(g(a, nn +1) - g(b, nn +1)); " Ohm" + Exit Do +Loop + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Respond-to-an-unknown-method-call/Phix/respond-to-an-unknown-method-call.phix b/Task/Respond-to-an-unknown-method-call/Phix/respond-to-an-unknown-method-call.phix new file mode 100644 index 0000000000..be9e0aa49e --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Phix/respond-to-an-unknown-method-call.phix @@ -0,0 +1,30 @@ +enum METHODS + +function invoke(object o, string name, sequence args={}) +--(this works on any class, for any function, with any number or type of parameters) + integer mdict = o[METHODS] + integer node = getd_index(name,mdict) + if node!=0 then + return call_func(getd_by_index(node,mdict),args) + end if + return "no such method" -- or throw(), fatal(), etc +end function + +--class X: Xmethods emulates a vtable +constant Xmethods = new_dict() + +function exists() + return "exists" +end function + +setd("exists",routine_id("exists"),Xmethods) + +--class X: create new instances +function newX() + return {Xmethods} +end function + +object x = newX() + +?invoke(x,"exists") +?invoke(x,"non_existent_method") diff --git a/Task/Reverse-a-string/K/reverse-a-string.k b/Task/Reverse-a-string/K/reverse-a-string.k new file mode 100644 index 0000000000..52e5f6fcf9 --- /dev/null +++ b/Task/Reverse-a-string/K/reverse-a-string.k @@ -0,0 +1,5 @@ + |"asdf" +"fdsa" + + | 23 4 5 1 +1 5 4 23 diff --git a/Task/Reverse-words-in-a-string/Maple/reverse-words-in-a-string.maple b/Task/Reverse-words-in-a-string/Maple/reverse-words-in-a-string.maple new file mode 100644 index 0000000000..af9786b93f --- /dev/null +++ b/Task/Reverse-words-in-a-string/Maple/reverse-words-in-a-string.maple @@ -0,0 +1,7 @@ +while (true) do + input := readline("input.txt"): + if input = 0 then break: fi: + input := StringTools:-Trim(input): # remove leading/trailing space + input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "): + printf("%s\n", input): +od: diff --git a/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring b/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring index fadfe35cdf..3b12a26983 100644 --- a/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring +++ b/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring @@ -1,7 +1,4 @@ # Project : Rock-paper-scissors -# Date : 2018/03/25 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : see " welcome to the game of rock-paper-scissors. diff --git a/Task/Roman-numerals-Encode/Ceylon/roman-numerals-encode.ceylon b/Task/Roman-numerals-Encode/Ceylon/roman-numerals-encode.ceylon index 2acdeb9750..2ad00e5068 100644 --- a/Task/Roman-numerals-Encode/Ceylon/roman-numerals-encode.ceylon +++ b/Task/Roman-numerals-Encode/Ceylon/roman-numerals-encode.ceylon @@ -3,29 +3,43 @@ shared void run() { class Numeral(shared Character char, shared Integer int) {} value tiers = [ - [Numeral('I', 1), Numeral('V', 5), Numeral('X', 10)], - [Numeral('X', 10), Numeral('L', 50), Numeral('C', 100)], + [Numeral('I', 1), Numeral('V', 5), Numeral('X', 10)], + [Numeral('X', 10), Numeral('L', 50), Numeral('C', 100)], [Numeral('C', 100), Numeral('D', 500), Numeral('M', 1k)] ]; - - - String toRoman(Integer hindu, Integer power = 2) { - assert(exists tier = tiers[power]); - if(hindu <= 0) { + + String toRoman(Integer hindu, Integer tierIndex = 2) { + + assert (exists tier = tiers[tierIndex]); + + " Finds if it's a two character numeral like iv, ix, xl, xc, cd and cm." + function findTwoCharacterNumeral() => + if (exists bigNum = tier.rest.find((numeral) => numeral.int - tier.first.int <= hindu < numeral.int)) + then [tier.first, bigNum] + else null; + + if (hindu <= 0) { + // if it's zero then we are done! return ""; - } else if(exists num = tier.rest.find((Numeral elem) => elem.int - tier.first.int <= hindu < elem.int)) { - return "``tier.first.char````num.char````toRoman(hindu - (num.int - tier.first.int), power)``"; - } else if(exists num = tier.reversed.find((Numeral elem) => hindu >= elem.int)) { - return "``num.char````toRoman(hindu - num.int, power)``"; - } else { - return toRoman(hindu, power - 1); + } + else if (exists [smallNum, bigNum] = findTwoCharacterNumeral()) { + value twoCharSymbol = "``smallNum.char````bigNum.char``"; + value twoCharValue = bigNum.int - smallNum.int; + return "``twoCharSymbol````toRoman(hindu - twoCharValue, tierIndex)``"; + } + else if (exists num = tier.reversed.find((Numeral elem) => hindu >= elem.int)) { + return "``num.char````toRoman(hindu - num.int, tierIndex)``"; + } + else { + // nothing was found so move to the next smaller tier! + return toRoman(hindu, tierIndex - 1); } } - assert(toRoman(1) == "I"); - assert(toRoman(2) == "II"); - assert(toRoman(4) == "IV"); - assert(toRoman(1666) == "MDCLXVI"); - assert(toRoman(1990) == "MCMXC"); - assert(toRoman(2008) == "MMVIII"); + assert (toRoman(1) == "I"); + assert (toRoman(2) == "II"); + assert (toRoman(4) == "IV"); + assert (toRoman(1666) == "MDCLXVI"); + assert (toRoman(1990) == "MCMXC"); + assert (toRoman(2008) == "MMVIII"); } diff --git a/Task/Roots-of-a-function/Perl-6/roots-of-a-function.pl6 b/Task/Roots-of-a-function/Perl-6/roots-of-a-function.pl6 index 2564b55759..97526331b0 100644 --- a/Task/Roots-of-a-function/Perl-6/roots-of-a-function.pl6 +++ b/Task/Roots-of-a-function/Perl-6/roots-of-a-function.pl6 @@ -1,4 +1,4 @@ -sub f($x) { $x*$x*$x - 3*$x*$x + 2*$x } +sub f(\x) { xΒ³ - 3*xΒ² + 2*x } my $start = -1; my $stop = 3; diff --git a/Task/Roots-of-a-function/Scala/roots-of-a-function-1.scala b/Task/Roots-of-a-function/Scala/roots-of-a-function-1.scala new file mode 100644 index 0000000000..6743934ec6 --- /dev/null +++ b/Task/Roots-of-a-function/Scala/roots-of-a-function-1.scala @@ -0,0 +1,25 @@ +object Roots extends App { + val poly = (x: Double) => x * x * x - 3 * x * x + 2 * x + + private def printRoots(f: Double => Double, + lowerBound: Double, + upperBound: Double, + step: Double): Unit = { + val y = f(lowerBound) + var (ox, oy, os) = (lowerBound, y, math.signum(y)) + + for (x <- lowerBound to upperBound by step) { + val y = f(x) + val s = math.signum(y) + if (s == 0) println(x) + else if (s != os) println(s"~${x - (x - ox) * (y / (y - oy))}") + + ox = x + oy = y + os = s + } + } + + printRoots(poly, -1.0, 4, 0.002) + +} diff --git a/Task/Roots-of-a-function/Scala/roots-of-a-function.scala b/Task/Roots-of-a-function/Scala/roots-of-a-function-2.scala similarity index 100% rename from Task/Roots-of-a-function/Scala/roots-of-a-function.scala rename to Task/Roots-of-a-function/Scala/roots-of-a-function-2.scala diff --git a/Task/Rot-13/REBOL/rot-13.rebol b/Task/Rot-13/REBOL/rot-13.rebol index e4499383ef..2049136f22 100644 --- a/Task/Rot-13/REBOL/rot-13.rebol +++ b/Task/Rot-13/REBOL/rot-13.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Rot-13" - Date: 2009-12-14 - Author: oofoe URL: http://rosettacode.org/wiki/Rot-13 ] diff --git a/Task/Run-length-encoding/C++/run-length-encoding-1.cpp b/Task/Run-length-encoding/C++/run-length-encoding-1.cpp new file mode 100644 index 0000000000..ee459392d8 --- /dev/null +++ b/Task/Run-length-encoding/C++/run-length-encoding-1.cpp @@ -0,0 +1,162 @@ +#include +#include +#include +#include +#include + +namespace detail_ { + +// For constexpr digit<->number conversions. +constexpr auto digits = std::array{'0','1','2','3','4','5','6','7','8','9'}; + +// Helper function to encode a run-length. +template +constexpr auto encode_run_length(std::size_t n, OutputIterator out) +{ + constexpr auto base = digits.size(); + + // Determine the number of digits needed. + auto const num_digits = [base](auto n) + { + auto d = std::size_t{1}; + while ((n /= digits.size())) + ++d; + return d; + }(n); + + // Helper lambda to raise the base to an integer power. + auto base_power = [base](auto n) + { + auto res = decltype(base){1}; + for (auto i = decltype(n){1}; i < n; ++i) + res *= base; + return res; + }; + + // From the most significant digit to the least, output the digit. + for (auto i = decltype(num_digits){0}; i < num_digits; ++i) + *out++ = digits[(n / base_power(num_digits - i)) % base]; + + return out; +} + +// Helper function to decode a run-length. +// As of C++20, this can be constexpr, because std::find() is constexpr. +// Before C++20, it can be constexpr by emulating std::find(). +template +auto decode_run_length(InputIterator first, InputIterator last) +{ + auto count = std::size_t{0}; + + while (first != last) + { + // If the next input character is not a digit, we're done. + auto const p = std::find(digits.begin(), digits.end(), *first); + if (p == digits.end()) + break; + + // Convert the digit to a number, and append it to the size. + count *= digits.size(); + count += std::distance(digits.begin(), p); + + // Move on to the next input character. + ++first; + } + + return std::tuple{count, first}; +} + +} // namespace detail_ + +template +constexpr auto encode(InputIterator first, InputIterator last, OutputIterator out) +{ + while (first != last) + { + // Read the next value. + auto const value = *first++; + + // Increase the count as long as the next value is the same. + auto count = std::size_t{1}; + while (first != last && *first == value) + { + ++count; + ++first; + } + + // Write the value and its run length. + out = detail_::encode_run_length(count, out); + *out++ = value; + } + + return out; +} + +// As of C++20, this can be constexpr, because std::find() and +// std::fill_n() are constexpr (and decode_run_length() can be +// constexpr, too). +// Before C++20, it can be constexpr by emulating std::find() and +// std::fill_n(). +template +auto decode(InputIterator first, InputIterator last, OutputIterator out) +{ + while (first != last) + { + using detail_::digits; + + // Assume a run-length of 1, then try to decode the actual + // run-length, if any. + auto count = std::size_t{1}; + if (std::find(digits.begin(), digits.end(), *first) != digits.end()) + std::tie(count, first) = detail_::decode_run_length(first, last); + + // Write the run. + out = std::fill_n(out, count, *first++); + } + + return out; +} + +template +constexpr auto encode(Range&& range, OutputIterator out) +{ + using std::begin; + using std::end; + + return encode(begin(range), end(range), out); +} + +template +auto decode(Range&& range, OutputIterator out) +{ + using std::begin; + using std::end; + + return decode(begin(range), end(range), out); +} + +// Sample application and checking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +#include +#include + +int main() +{ + using namespace std::literals; + + constexpr auto test_string = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"sv; + + std::cout << "Input: \"" << test_string << "\"\n"; + std::cout << "Output: \""; + // No need for a temporary string - can encode directly to cout. + encode(test_string, std::ostreambuf_iterator{std::cout}); + std::cout << "\"\n"; + + auto encoded_str = std::string{}; + auto decoded_str = std::string{}; + encode(test_string, std::back_inserter(encoded_str)); + decode(encoded_str, std::back_inserter(decoded_str)); + + std::cout.setf(std::cout.boolalpha); + std::cout << "Round trip works: " << (test_string == decoded_str) << '\n'; +} diff --git a/Task/Run-length-encoding/C++/run-length-encoding.cpp b/Task/Run-length-encoding/C++/run-length-encoding-2.cpp similarity index 100% rename from Task/Run-length-encoding/C++/run-length-encoding.cpp rename to Task/Run-length-encoding/C++/run-length-encoding-2.cpp diff --git a/Task/Run-length-encoding/Ring/run-length-encoding.ring b/Task/Run-length-encoding/Ring/run-length-encoding.ring index 532fc2d7db..ab793480cb 100644 --- a/Task/Run-length-encoding/Ring/run-length-encoding.ring +++ b/Task/Run-length-encoding/Ring/run-length-encoding.ring @@ -1,7 +1,4 @@ # Project : Run-length encoding -# Date : 2017/12/04 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" test = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" diff --git a/Task/S-Expressions/Haskell/s-expressions.hs b/Task/S-Expressions/Haskell/s-expressions.hs index df2b3db540..252ea0cfb7 100644 --- a/Task/S-Expressions/Haskell/s-expressions.hs +++ b/Task/S-Expressions/Haskell/s-expressions.hs @@ -1,5 +1,5 @@ import Data.Functor -import Text.Parsec ((<|>), (), many, many1, char, try, parse, sepBy, choice) +import Text.Parsec ((<|>), (), many, many1, char, try, parse, sepBy, choice, between) import Text.Parsec.Char (noneOf) import Text.Parsec.Token (integer, float, whiteSpace, stringLiteral, makeTokenParser) import Text.Parsec.Language (haskell) @@ -13,10 +13,10 @@ data Val = Int Integer tProg = many tExpr "program" where tExpr = between ws ws (tList <|> tAtom) "expression" ws = whiteSpace haskell - tAtom = try (Int <$> integer haskell) "integer" - <|> try (Float <$> float haskell) "floating point number" - <|> String <$> stringLiteral haskell "string" - <|> Symbol <$> many1 (noneOf "()\"\t\n\r") "symbol" + tAtom = (try (Float <$> float haskell) "floating point number") + <|> (try (Int <$> integer haskell) "integer") + <|> (String <$> stringLiteral haskell "string") + <|> (Symbol <$> many1 (noneOf "()\"\t\n\r ") "symbol") "atomic expression" tList = List <$> between (char '(') (char ')') (many tExpr) "list" diff --git a/Task/SHA-1/Mathematica/sha-1.math b/Task/SHA-1/Mathematica/sha-1.math index 48a83a8f21..1a8793b451 100644 --- a/Task/SHA-1/Mathematica/sha-1.math +++ b/Task/SHA-1/Mathematica/sha-1.math @@ -1,3 +1 @@ -IntegerString[Hash["Rosetta Code", "SHA1"], 16] - --> 48c98f7e5a6e736d790ab740dfc3f51a61abe2b5 +Hash["Rosetta code","SHA1","HexString"] diff --git a/Task/SHA-1/Phix/sha-1.phix b/Task/SHA-1/Phix/sha-1.phix new file mode 100644 index 0000000000..661e68ed15 --- /dev/null +++ b/Task/SHA-1/Phix/sha-1.phix @@ -0,0 +1,87 @@ +-- +-- demo\rosetta\sha1.exw +-- ===================== +-- +-- NB no longer considered secure. Non-optimised. +-- +constant m4 = allocate(4) -- scratch area, for uint32 + +function uint32(atom v) + poke4(m4,v) + return peek4u(m4) +end function + +function sq_uint32(sequence s) + for i=1 to length(s) do + s[i] = uint32(s[i]) + end for + return s +end function + +function dword(string msg, integer i) +-- get dword as big-endian + return msg[i]*#1000000+msg[i+1]*#10000+msg[i+2]*#100+msg[i+3] +end function + +function xor_all(sequence s) +atom result = 0 + for i=1 to length(s) do + result = xor_bits(result, s[i]) + end for + result = uint32(result) + return result +end function + +function rol(atom word, integer bits) +-- left rotate the bits of a 32-bit number by the specified number of bits + return uint32(word*power(2,bits))+floor(word/power(2,32-bits)) +end function + +function sha1(string msg) +atom a,b,c,d,e,temp,k +sequence w = repeat(0,80) +atom h0 = 0x67452301, + h1 = 0xefcdab89, + h2 = 0x98badcfe, + h3 = 0x10325476, + h4 = 0xc3d2e1f0 + + integer bits = length(msg)*8 + msg &= #80 + while mod(length(msg),64)!=56 do msg &= '\0' end while + msg &= reverse(int_to_bytes(bits,8)) + + for chunk=1 to length(msg) by 64 do + for i=1 to 16 do + w[i] = dword(msg,chunk+(i-1)*4) + end for + for i=17 to 80 do + w[i] = rol(xor_all({w[i-3],w[i-8],w[i-14],w[i-16]}),1) + end for + {a,b,c,d,e} = {h0,h1,h2,h3,h4} + for i=1 to 80 do + if i<=20 then + temp = or_bits(and_bits(b,c),and_bits(not_bits(b),d)) + k = #5A827999 + elsif i<=40 then + temp = xor_bits(xor_bits(b,c),d) + k = #6ED9EBA1 + elsif i<=60 then + temp = or_bits(or_bits(and_bits(b,c),and_bits(b,d)),and_bits(c,d)) + k = #8F1BBCDC + else -- i<=80 + temp = xor_bits(xor_bits(b,c),d) + k = #CA62C1D6 + end if + {a,b,c,d,e} = {uint32(rol(a,5)+temp+e+k+w[i]),a,rol(b,30),c,d} + end for + {h0,h1,h2,h3,h4} = sq_uint32(sq_add({h0,h1,h2,h3,h4},{a,b,c,d,e})) + end for + sequence res = {h0, h1, h2, h3, h4} + for i=1 to length(res) do + res[i] = sprintf("%08X",res[i]) + end for + return join(res) +end function + +?sha1("Rosetta Code") diff --git a/Task/SHA-1/Ring/sha-1.ring b/Task/SHA-1/Ring/sha-1.ring index ee4798b6fd..b7c54084c8 100644 --- a/Task/SHA-1/Ring/sha-1.ring +++ b/Task/SHA-1/Ring/sha-1.ring @@ -1,7 +1,4 @@ # Project : SHA-1 -# Date : 2018/05/18 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "stdlib.ring" str = "Rosetta Code" diff --git a/Task/SHA-256/Factor/sha-256.factor b/Task/SHA-256/Factor/sha-256.factor new file mode 100644 index 0000000000..46b9d90a59 --- /dev/null +++ b/Task/SHA-256/Factor/sha-256.factor @@ -0,0 +1,3 @@ +USING: checksums checksums.sha io math.parser ; + +"Rosetta code" sha-256 checksum-bytes bytes>hex-string print diff --git a/Task/SHA-256/Mathematica/sha-256.math b/Task/SHA-256/Mathematica/sha-256.math index 657d5894c7..efae780524 100644 --- a/Task/SHA-256/Mathematica/sha-256.math +++ b/Task/SHA-256/Mathematica/sha-256.math @@ -1 +1 @@ -IntegerString[Hash["Rosetta code", "SHA256"], 16] +Hash["Rosetta code","SHA256","HexString"] diff --git a/Task/SHA-256/Phix/sha-256-1.phix b/Task/SHA-256/Phix/sha-256-1.phix index ee130d5a29..4270e46b20 100644 --- a/Task/SHA-256/Phix/sha-256-1.phix +++ b/Task/SHA-256/Phix/sha-256-1.phix @@ -1,16 +1,11 @@ -constant lib = open_dll("SHA.DLL") -constant SHA_HashBlock = define_c_proc(lib,"SHA_HashBlock",{C_PTR,C_PTR,C_INT}) +include builtins\sha256.e -function sha256(string s) -atom mem = allocate(32) -sequence res - c_proc(SHA_HashBlock,{s,mem,length(s)}) - res = peek4u({mem,8}) - free(mem) - for i=1 to length(res) do - res[i] = sprintf("%08x",res[i]) +function asHex(string s) +string res = "" + for i=1 to length(s) do + res &= sprintf("%02X",s[i]) end for - return join(res) + return res end function -?sha256("Rosetta code") +?asHex(sha256("Rosetta code")) diff --git a/Task/SHA-256/Phix/sha-256-2.phix b/Task/SHA-256/Phix/sha-256-2.phix index 8af95e313f..3ac6bfbedc 100644 --- a/Task/SHA-256/Phix/sha-256-2.phix +++ b/Task/SHA-256/Phix/sha-256-2.phix @@ -122,5 +122,4 @@ atom h0 = 0x6a09e667, return join(res) end function -string res = sha256("Rosetta code") -?res +?sha256("Rosetta code") diff --git a/Task/SHA-256/Ring/sha-256.ring b/Task/SHA-256/Ring/sha-256.ring index 08ab2d661a..fa4f0a2ea2 100644 --- a/Task/SHA-256/Ring/sha-256.ring +++ b/Task/SHA-256/Ring/sha-256.ring @@ -1,7 +1,4 @@ # Project: SHA-256 -# Date : 2018/06/09 -# Author: Gal Zsolt [~ CalmoSoft ~] -# Email : load "stdlib.ring" str = "Rosetta code" diff --git a/Task/SOAP/C/soap-1.c b/Task/SOAP/C/soap-1.c index 9b162e04c5..c757b47877 100644 --- a/Task/SOAP/C/soap-1.c +++ b/Task/SOAP/C/soap-1.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 26th October 2017*/ - #include #include #include diff --git a/Task/Safe-addition/Swift/safe-addition.swift b/Task/Safe-addition/Swift/safe-addition.swift new file mode 100644 index 0000000000..cb19693983 --- /dev/null +++ b/Task/Safe-addition/Swift/safe-addition.swift @@ -0,0 +1,4 @@ +let a = 1.2 +let b = 0.03 + +print("\(a) + \(b) is in the range \((a + b).nextDown)...\((a + b).nextUp)") 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 855816a5bb..77e614c103 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 @@ -1,4 +1,3 @@ -/* Abhishek Ghosh, 8th November 2013, Rotterdam */ #include #define sqr(x) ((x) * (x)) diff --git a/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring b/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring index b3ca13ac4a..9face685b3 100644 --- a/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring +++ b/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring @@ -1,7 +1,4 @@ # Project : Scope/Function names and labels -# Date : 2018/02/22 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "What is your name?" + nl give name diff --git a/Task/Search-a-list/REBOL/search-a-list.rebol b/Task/Search-a-list/REBOL/search-a-list.rebol index e0c08a59a3..ef6780c59e 100644 --- a/Task/Search-a-list/REBOL/search-a-list.rebol +++ b/Task/Search-a-list/REBOL/search-a-list.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "List Indexing" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Index_in_a_list ] diff --git a/Task/Self-describing-numbers/Ring/self-describing-numbers.ring b/Task/Self-describing-numbers/Ring/self-describing-numbers.ring index b33cdf9ef4..7df4592772 100644 --- a/Task/Self-describing-numbers/Ring/self-describing-numbers.ring +++ b/Task/Self-describing-numbers/Ring/self-describing-numbers.ring @@ -1,7 +1,4 @@ # Project : Self-describing numbers -# Date : 2017/11/18 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : for num = 1 to 45000000 res = 0 diff --git a/Task/Semordnilap/Ring/semordnilap.ring b/Task/Semordnilap/Ring/semordnilap.ring index 4a3b465a3c..d21df6fd69 100644 --- a/Task/Semordnilap/Ring/semordnilap.ring +++ b/Task/Semordnilap/Ring/semordnilap.ring @@ -1,7 +1,4 @@ # Project : Semordnilap -# Date : 2018/04/18 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" nr = 0 diff --git a/Task/Send-email/C/send-email.c b/Task/Send-email/C/send-email.c index 5fee6fbd49..c8f2b69444 100644 --- a/Task/Send-email/C/send-email.c +++ b/Task/Send-email/C/send-email.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 13th June 2018*/ - #include #include #include diff --git a/Task/Sequence-of-non-squares/Nim/sequence-of-non-squares.nim b/Task/Sequence-of-non-squares/Nim/sequence-of-non-squares.nim index cfc997a2b4..ca6ee85833 100644 --- a/Task/Sequence-of-non-squares/Nim/sequence-of-non-squares.nim +++ b/Task/Sequence-of-non-squares/Nim/sequence-of-non-squares.nim @@ -1,11 +1,11 @@ import math -proc nosqr(n): seq[int] = - result = @[] +proc nosqr(n: int): seq[int] = + result = newSeq[int] n for i in 1..n: - result.add(i + round(sqrt(float(i)))) + result[i - 1] = i + i.float.sqrt.round.int -proc issqr(n): bool = +proc issqr(n: int): bool = let sqr = sqrt(float(n)) let err = abs(sqr - float(round(sqr))) err < 1e-7 diff --git a/Task/Set-consolidation/Ring/set-consolidation.ring b/Task/Set-consolidation/Ring/set-consolidation.ring index 4155065081..08fa42d445 100644 --- a/Task/Set-consolidation/Ring/set-consolidation.ring +++ b/Task/Set-consolidation/Ring/set-consolidation.ring @@ -1,7 +1,4 @@ # Project : Set consolidation -# Date : 2018/03/29 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "stdlib.ring" test = ["AB","AB,CD","AB,CD,DB","HIK,AB,CD,DB,FGH"] diff --git a/Task/Set-of-real-numbers/Java/set-of-real-numbers.java b/Task/Set-of-real-numbers/Java/set-of-real-numbers.java new file mode 100644 index 0000000000..95d28f329d --- /dev/null +++ b/Task/Set-of-real-numbers/Java/set-of-real-numbers.java @@ -0,0 +1,113 @@ +import java.util.Objects; +import java.util.function.Predicate; + +public class RealNumberSet { + public enum RangeType { + CLOSED, + BOTH_OPEN, + LEFT_OPEN, + RIGHT_OPEN, + } + + public static class RealSet { + private Double low; + private Double high; + private Predicate predicate; + private double interval = 0.00001; + + public RealSet(Double low, Double high, Predicate predicate) { + this.low = low; + this.high = high; + this.predicate = predicate; + } + + public RealSet(Double start, Double end, RangeType rangeType) { + this(start, end, d -> { + switch (rangeType) { + case CLOSED: + return start <= d && d <= end; + case BOTH_OPEN: + return start < d && d < end; + case LEFT_OPEN: + return start < d && d <= end; + case RIGHT_OPEN: + return start <= d && d < end; + default: + throw new IllegalStateException("Unhandled range type encountered."); + } + }); + } + + public boolean contains(Double d) { + return predicate.test(d); + } + + public RealSet union(RealSet other) { + double low2 = Math.min(low, other.low); + double high2 = Math.max(high, other.high); + return new RealSet(low2, high2, d -> predicate.or(other.predicate).test(d)); + } + + public RealSet intersect(RealSet other) { + double low2 = Math.min(low, other.low); + double high2 = Math.max(high, other.high); + return new RealSet(low2, high2, d -> predicate.and(other.predicate).test(d)); + } + + public RealSet subtract(RealSet other) { + return new RealSet(low, high, d -> predicate.and(other.predicate.negate()).test(d)); + } + + public double length() { + if (low.isInfinite() || high.isInfinite()) return -1.0; // error value + if (high <= low) return 0.0; + Double p = low; + int count = 0; + do { + if (predicate.test(p)) count++; + p += interval; + } while (p < high); + return count * interval; + } + + public boolean isEmpty() { + if (Objects.equals(high, low)) { + return predicate.negate().test(low); + } + return length() == 0.0; + } + } + + public static void main(String[] args) { + RealSet a = new RealSet(0.0, 1.0, RangeType.LEFT_OPEN); + RealSet b = new RealSet(0.0, 2.0, RangeType.RIGHT_OPEN); + RealSet c = new RealSet(1.0, 2.0, RangeType.LEFT_OPEN); + RealSet d = new RealSet(0.0, 3.0, RangeType.RIGHT_OPEN); + RealSet e = new RealSet(0.0, 1.0, RangeType.BOTH_OPEN); + RealSet f = new RealSet(0.0, 1.0, RangeType.CLOSED); + RealSet g = new RealSet(0.0, 0.0, RangeType.CLOSED); + + for (int i = 0; i <= 2; i++) { + Double dd = (double) i; + System.out.printf("(0, 1] βˆͺ [0, 2) contains %d is %s\n", i, a.union(b).contains(dd)); + System.out.printf("[0, 2) ∩ (1, 2] contains %d is %s\n", i, b.intersect(c).contains(dd)); + System.out.printf("[0, 3) βˆ’ (0, 1) contains %d is %s\n", i, d.subtract(e).contains(dd)); + System.out.printf("[0, 3) βˆ’ [0, 1] contains %d is %s\n", i, d.subtract(f).contains(dd)); + System.out.println(); + } + + System.out.printf("[0, 0] is empty is %s\n", g.isEmpty()); + System.out.println(); + + RealSet aa = new RealSet( + 0.0, 10.0, + x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x * x)) > 0.5 + ); + RealSet bb = new RealSet( + 0.0, 10.0, + x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x)) > 0.5 + ); + RealSet cc = aa.subtract(bb); + System.out.printf("Approx length of A - B is %f\n", cc.length()); + } +} diff --git a/Task/Set-of-real-numbers/REXX/set-of-real-numbers-1.rexx b/Task/Set-of-real-numbers/REXX/set-of-real-numbers-1.rexx index d5cc95dbc9..9cfa9502f2 100644 --- a/Task/Set-of-real-numbers/REXX/set-of-real-numbers-1.rexx +++ b/Task/Set-of-real-numbers/REXX/set-of-real-numbers-1.rexx @@ -1,40 +1,46 @@ -/*REXX pgm demonstrates a way to represent any set of real #s and usage.*/ -call set_query , , '(0,1] union [0,2)' -call set_query , , '[0,2) ∩ (1,3)' -call set_query , , '[0,3] - (0,1)' -call set_query , , '[0,3] - [0,1]' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SET_empty subroutine────────────────*/ -set_empty: parse arg _; nam=set_val(_,00); return @.3>@.4 -/*──────────────────────────────────SET_ISIN subroutine─────────────────*/ -set_isin: parse arg #,x; call set_val x -if \datatype(#,'N') then call set_bad "number isn't not numeric:" # - if (@.1=='(' & #<=@.2) |, - (@.1=='[' & #< @.2) |, - (@.4==')' & #>=@.3) |, - (@.4==']' & #> @.3) then return 0 -return 1 -/*──────────────────────────────────SET_query subroutine────────────────*/ -set_query: parse arg lv,hv,s1 oop s2 .; op=oop; upper op; cop= -if lv=='' then lv=0; if hv=='' then hv=2; if op=='' then cop=0 -if wordpos(op,'| or UNION') \==0 then cop='|' -if wordpos(op,'& ∩ AND INTER INTERSECTION') \==0 then cop='&' -if wordpos(op,'\ - DIF DIFF DIFFERENCE') \==0 then cop='\' -say - do i=lv to hv; b =set_isin(i,s1) - if cop\==0 then do - b2=set_isin(i,s2) - if cop=='&' then b=b & b2 - if cop=='|' then b=b | b2 - if cop=='\' then b=b & \b2 - end - express = s1 center(oop,max(5,length(oop))) s2 - say right(i,5) ' is in set' express": " word('no yes',b+1) - end /*i*/ -return -/*──────────────────────────────────SET_VAL subroutine──────────────────*/ -set_val: parse arg q; q=space(q,0); L=length(q); @.0=',' -@.4=right(q,1) -parse var q @.1 2 @.2 ',' @.3 (@.4) -if @.2>@.3 then parse var L . @.0 @.2 @.3 -return space(@.1 @.2 @.0 @.3 @.4,0) +/*REXX program demonstrates a way to represent any set of real numbers and usage. */ +call quertySet 1, 3, '[1,2)' +call quertySet , , '[0,2) union (1,3)' +call quertySet , , '[0,1) union (2,3]' +call quertySet , , '[0,2] inter (1,3)' +call quertySet , , '(1,2) ∩ (2,3]' +call quertySet , , '[0,2) \ (1,3)' +say; say center(' start of required tasks ', 40, "═") +call quertySet , , '(0,1] union [0,2)' +call quertySet , , '[0,2) ∩ (1,3)' +call quertySet , , '[0,3] - (0,1)' +call quertySet , , '[0,3] - [0,1]' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +emptySet: parse arg _; nam= valSet(_, 00); return @.3>@.4 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isInSet: parse arg #,x; call valSet x + if \datatype(#, 'N') then call set_bad "number isn't not numeric:" # + if (@.1=='(' & #<=@.2) |, + (@.1=='[' & #< @.2) |, + (@.4==')' & #>=@.3) |, + (@.4==']' & #> @.3) then return 0 + return 1 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +quertySet: parse arg lv,hv,s1 oop s2 .; op=oop; upper op; cop= + if lv=='' then lv=0; if hv=="" then hv= 2; if op=='' then cop= 0 + if wordpos(op, '| or UNION') \==0 then cop= "|" + if wordpos(op, '& ∩ AND INTER INTERSECTION') \==0 then cop= "&" + if wordpos(op, '\ - DIF DIFF DIFFERENCE') \==0 then cop= "\" + say + do i=lv to hv; b = isInSet(i, s1) + if cop\==0 then do + b2= isInSet(i, s2) + if cop=='&' then b= b & b2 + if cop=='|' then b= b | b2 + if cop=='\' then b= b & \b2 + end + express = s1 center(oop, max(5, length(oop) ) ) s2 + say right(i, 5) ' is in set' express": " word('no yes', b+1) + end /*i*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +valSet: parse arg q; q=space(q, 0); L=length(q); @.0= ','; @.4= right(q,1) + parse var q @.1 2 @.2 ',' @.3 (@.4) + if @.2>@.3 then parse var L . @.0 @.2 @.3 + return space(@.1 @.2 @.0 @.3 @.4, 0) diff --git a/Task/Set-of-real-numbers/REXX/set-of-real-numbers-2.rexx b/Task/Set-of-real-numbers/REXX/set-of-real-numbers-2.rexx index ff59af2010..1e9cfa7f0c 100644 --- a/Task/Set-of-real-numbers/REXX/set-of-real-numbers-2.rexx +++ b/Task/Set-of-real-numbers/REXX/set-of-real-numbers-2.rexx @@ -1,53 +1,57 @@ -/*REXX pgm demonstrates a way to represent any set of real #s and usage.*/ -call set_query , , '(0,1] union [0,2)' -call set_query , , '[0,2) ∩ (1,3)' -call set_query , , '[0,3] - (0,1)' -call set_query , , '[0,3] - [0,1]' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SET_BAD subroutine─────────-────────*/ -set_bad: say; say '***error!*** bad format of SET_def: ('arg(1)")"; exit -/*──────────────────────────────────SET_empty subroutine────────────────*/ -set_empty: parse arg _; nam=set_val(_,00); return @.3>@.4 -/*──────────────────────────────────SET_ISIN subroutine─────────────────*/ -set_isin: parse arg #,x; call set_val x -if \datatype(#,'N') then call set_bad "number isn't not numeric:" # - if (@.1=='(' & #<=@.2) |, - (@.1=='[' & #< @.2) |, - (@.4==')' & #>=@.3) |, - (@.4==']' & #> @.3) then return 0 -return 1 -/*──────────────────────────────────SET_query subroutine────────────────*/ -set_query: parse arg lv,hv,s1 oop s2 .; op=oop; upper op; cop= -if lv=='' then lv=0; if hv=='' then hv=2; if op=='' then cop=0 -if wordpos(op,'| or UNION') \==0 then cop='|' -if wordpos(op,'& ∩ AND INTER INTERSECTION') \==0 then cop='&' -if wordpos(op,'\ - DIF DIFF DIFFERENCE') \==0 then cop='\' -if cop=='' then call set_bad 'invalid operation:' oop -say - do i=lv to hv; b =set_isin(i,s1) - if cop\==0 then do - b2=set_isin(i,s2) - if cop=='&' then b=b & b2 - if cop=='|' then b=b | b2 - if cop=='\' then b=b & \b2 - end - express = s1 center(oop,max(5,length(oop))) s2 - say right(i,5) ' is in set' express": " word('no yes',b+1) - end /*i*/ -return -/*──────────────────────────────────SET_VAL subroutine──────────────────*/ -set_val: parse arg q; q=space(q,0); L=length(q); @.0=',' -infinity = copies(9,digits()-1)'e'copies(9,digits()-1)'0' -if L<2 then call set_bad 'invalid expression' -@.4=right(q,1) -parse var q @.1 2 @.2 ',' @.3 (@.4) -if @.1\=='(' & @.1\=='[' then call set_bad 'left boundry' -if @.4\==')' & @.4\==']' then call set_bad 'right boundry' - - do j=2 to 3; u=@.j; upper u - if right(@.j,1)=='∞' | u="INFINITY" then @.j='-'infinity - if \datatype(@.j,'N') then call set_bad 'value not numeric:' @.j - end /*j*/ - -if @.2>@.3 then parse var L . @.0 @.2 @.3 -return space(@.1 @.2 @.0 @.3 @.4,0) +/*REXX program demonstrates a way to represent any set of real numbers and usage. */ +call quertySet 1, 3, '[1,2)' +call quertySet , , '[0,2) union (1,3)' +call quertySet , , '[0,1) union (2,3]' +call quertySet , , '[0,2] inter (1,3)' +call quertySet , , '(1,2) ∩ (2,3]' +call quertySet , , '[0,2) \ (1,3)' +say; say center(' start of required tasks ', 40, "═") +call quertySet , , '(0,1] union [0,2)' +call quertySet , , '[0,2) ∩ (1,3)' +call quertySet , , '[0,3] - (0,1)' +call quertySet , , '[0,3] - [0,1]' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +badSet: say; say '***error*** bad format of SET_def: ('arg(1)")"; exit +/*──────────────────────────────────────────────────────────────────────────────────────*/ +emptySet: parse arg _; nam= valSet(_, 00); return @.3>@.4 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isInSet: parse arg #,x; call valSet x + if \datatype(#, 'N') then call set_bad "number isn't not numeric:" # + if (@.1=='(' & #<=@.2) |, + (@.1=='[' & #< @.2) |, + (@.4==')' & #>=@.3) |, + (@.4==']' & #> @.3) then return 0 + return 1 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +quertySet: parse arg lv,hv,s1 oop s2 .; op=oop; upper op; cop= + if lv=='' then lv=0; if hv=="" then hv= 2; if op=='' then cop= 0 + if wordpos(op, '| or UNION') \==0 then cop= "|" + if wordpos(op, '& ∩ AND INTER INTERSECTION') \==0 then cop= "&" + if wordpos(op, '\ - DIF DIFF DIFFERENCE') \==0 then cop= "\" + say + do i=lv to hv; b = isInSet(i, s1) + if cop\==0 then do + b2= isInSet(i, s2) + if cop=='&' then b= b & b2 + if cop=='|' then b= b | b2 + if cop=='\' then b= b & \b2 + end + express = s1 center(oop, max(5, length(oop) ) ) s2 + say right(i, 5) ' is in set' express": " word('no yes', b+1) + end /*i*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +valSet: parse arg q; q=space(q, 0); L= length(q); @.0= ',' + infinity = copies(9, digits() - 1)'e'copies(9, digits() - 1)0 + if L<2 then call set_bad 'invalid expression' + @.4= right(q, 1) + parse var q @.1 2 @.2 ',' @.3 (@.4) + if @.1\=='(' & @.1\=="[" then call set_bad 'left boundry' + if @.4\==')' & @.4\=="]" then call set_bad 'right boundry' + do j=2 to 3; u=@.j; upper u + if right(@.j, 1)=='∞' | u="INFINITY" then @.j= '-'infinity + if \datatype(@.j, 'N') then call set_bad "value not numeric:" @.j + end /*j*/ + if @.2>@.3 then parse var L . @.0 @.2 @.3 + return space(@.1 @.2 @.0 @.3 @.4, 0) diff --git a/Task/Set/Ring/set.ring b/Task/Set/Ring/set.ring index 1a972dfb79..682928067c 100644 --- a/Task/Set/Ring/set.ring +++ b/Task/Set/Ring/set.ring @@ -1,7 +1,4 @@ # Project : Set -# Date : 2018/03/26 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : arr = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"] for n = 1 to 25 diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring b/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring index b98647dc58..3dda8cc922 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring @@ -1,7 +1,4 @@ # Project : Seven-sided dice from five-sided dice -# Date : 2018/02/02 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : for n = 1 to 20 d = dice7() diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Scala/seven-sided-dice-from-five-sided-dice.scala b/Task/Seven-sided-dice-from-five-sided-dice/Scala/seven-sided-dice-from-five-sided-dice.scala new file mode 100644 index 0000000000..c37065a054 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Scala/seven-sided-dice-from-five-sided-dice.scala @@ -0,0 +1,17 @@ +import scala.util.Random + +object SevenSidedDice extends App { + private val rnd = new Random + + private def seven = { + var v = 21 + + def five = 1 + rnd.nextInt(5) + + while (v > 20) v = five + five * 5 - 6 + 1 + v % 7 + } + + println("Random number from 1 to 7: " + seven) + +} 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 index b6402db519..ae55608e4a 100644 --- 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 @@ -1,6 +1,3 @@ -/// @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 /// diff --git a/Task/Short-circuit-evaluation/Maple/short-circuit-evaluation.maple b/Task/Short-circuit-evaluation/Maple/short-circuit-evaluation.maple new file mode 100644 index 0000000000..1a32ff7122 --- /dev/null +++ b/Task/Short-circuit-evaluation/Maple/short-circuit-evaluation.maple @@ -0,0 +1,16 @@ +a := proc(bool) + printf("a is called->%s\n", bool): + return bool: +end proc: +b := proc(bool) + printf("b is called->%s\n", bool): + return bool: +end proc: +for i in [true, false] do + for j in [true, false] do + printf("calculating x := a(i) and b(j)\n"): + x := a(i) and b(j): + printf("calculating x := a(i) or b(j)\n"): + y := a(i) or b(j): + od: +od: diff --git a/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring b/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring index 257a456724..68d884e003 100644 --- a/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring +++ b/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring @@ -1,7 +1,4 @@ # Project : Short-circuit evaluation -# Date : 2018/01/23 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : for k = 1 to 2 word = ["AND","OR"] diff --git a/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle.math b/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle-1.math similarity index 100% rename from Task/Sierpinski-triangle/Mathematica/sierpinski-triangle.math rename to Task/Sierpinski-triangle/Mathematica/sierpinski-triangle-1.math diff --git a/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle-2.math b/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle-2.math new file mode 100644 index 0000000000..848b2d3d92 --- /dev/null +++ b/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle-2.math @@ -0,0 +1 @@ +SierpinskiMesh[3] diff --git a/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring b/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring index bb9325691b..186ca2ec3b 100644 --- a/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring +++ b/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring @@ -1,7 +1,4 @@ # Project : Sierpinski triangle -# Date : 2017/09/20 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : norder=4 xy = list(40) diff --git a/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax b/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax new file mode 100644 index 0000000000..7beaf7b598 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax @@ -0,0 +1,29 @@ + 000F4240 0000 1 n=1000*1000 + 0000 0000 2 .entry main,0 + 7E 7CFD 0002 3 clro -(sp) ;result buffer + 5E DD 0005 4 pushl sp ;pointer to buffer + 10 DD 0007 5 pushl #16 ;descriptor -> len of buffer + 0009 6 + 02 DD 0009 7 pushl #2 ;1st candidate + 000B 8 test: + 09 46'AF 6E E1 000B 9 bbc (sp), b^bits, found ;bc - bit clear + 0010 10 next: + F3 6E 000F4240 8F F2 0010 11 aoblss #n, (sp), test ;+1: limit,index + 04 0018 12 ret + 0019 13 found: + 04 AE 7F 0019 14 pushaq 4(sp) ;-> descriptor by ref + 04 AE DF 001C 15 pushal 4(sp) ;-> prime on stack by ref + 00000000'GF 02 FB 001F 16 calls #2, g^ots$cvt_l_ti ;convert integer to string + 04 AE 7F 0026 17 pushaq 4(sp) ; + 00000000'GF 01 FB 0029 18 calls #1, g^lib$put_output ;show result + 0030 19 + 53 6E D0 0030 20 movl (sp), r3 + 0033 21 mult: + 0002 53 6E 000F4240 8F F1 0033 22 acbl #n, (sp), r3, set_mult ;limit,add,index + D1 11 003D 23 brb next + 003F 24 set_mult: ;set bits for multiples + EF 46'AF 53 E2 003F 25 bbss r3, b^bits, mult ;branch on bit set & set + ED 11 0044 26 brb mult + 0046 27 + 0001E892 0046 28 bits: .blkl /32 + E892 29 .end main diff --git a/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol b/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol index 5f332b87b9..f1d5c8440d 100644 --- a/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol +++ b/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Simple Windowed Application" - Author: oofoe - Date: 2009-12-07 URL: http://rosettacode.org/wiki/Simple_Windowed_Application ] diff --git a/Task/Simulate-input-Mouse/C/simulate-input-mouse.c b/Task/Simulate-input-Mouse/C/simulate-input-mouse.c index ea956a6320..d9888f03a6 100644 --- a/Task/Simulate-input-Mouse/C/simulate-input-mouse.c +++ b/Task/Simulate-input-Mouse/C/simulate-input-mouse.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 10th October 2017*/ - #define WINVER 0x500 #include diff --git a/Task/Simulate-input-Mouse/Ring/simulate-input-mouse.ring b/Task/Simulate-input-Mouse/Ring/simulate-input-mouse.ring index 83ab8f9813..22d3af9d9c 100644 --- a/Task/Simulate-input-Mouse/Ring/simulate-input-mouse.ring +++ b/Task/Simulate-input-Mouse/Ring/simulate-input-mouse.ring @@ -1,7 +1,4 @@ # Project : Simulate input/Mouse -# Date : 2018/02/02 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "guilib.ring" load "stdlib.ring" diff --git a/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 b/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 index 10c0cadc03..a0ef50bd2f 100644 --- a/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 +++ b/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 @@ -1,13 +1,3 @@ -my $letters = 'A' => 'C' => Mu; - -sub insert-after($list, $after, $new) { - loop (my $l = $list; $l; $l = $l.value) { - if $l.key eqv $after { - $l.value = $new => $l.value; - return; - } - } - die "Element $after not found"; -} - -$letters.&insert-after('A', 'B'); +my @list = ; +say @list.splice(1,0,'c'); +say @list; diff --git a/Task/Sleep/REBOL/sleep.rebol b/Task/Sleep/REBOL/sleep.rebol index 133d5be689..99c9399b39 100644 --- a/Task/Sleep/REBOL/sleep.rebol +++ b/Task/Sleep/REBOL/sleep.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Sleep Main Thread" - Date: 2009-12-15 - Author: oofoe URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread ] diff --git a/Task/Solve-a-Hidato-puzzle/Go/solve-a-hidato-puzzle.go b/Task/Solve-a-Hidato-puzzle/Go/solve-a-hidato-puzzle.go new file mode 100644 index 0000000000..aec4d08515 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Go/solve-a-hidato-puzzle.go @@ -0,0 +1,118 @@ +package main + +import ( + "fmt" + "sort" + "strconv" + "strings" +) + +var board [][]int +var start, given []int + +func setup(input []string) { + /* This task is not about input validation, so + we're going to trust the input to be valid */ + puzzle := make([][]string, len(input)) + for i := 0; i < len(input); i++ { + puzzle[i] = strings.Fields(input[i]) + } + nCols := len(puzzle[0]) + nRows := len(puzzle) + list := make([]int, nRows*nCols) + board = make([][]int, nRows+2) + for i := 0; i < nRows+2; i++ { + board[i] = make([]int, nCols+2) + for j := 0; j < nCols+2; j++ { + board[i][j] = -1 + } + } + for r := 0; r < nRows; r++ { + row := puzzle[r] + for c := 0; c < nCols; c++ { + switch cell := row[c]; cell { + case "_": + board[r+1][c+1] = 0 + case ".": + break + default: + val, _ := strconv.Atoi(cell) + board[r+1][c+1] = val + list = append(list, val) + if val == 1 { + start = append(start, r+1, c+1) + } + } + } + } + sort.Ints(list) + given = make([]int, len(list)) + for i := 0; i < len(given); i++ { + given[i] = list[i] + } +} + +func solve(r, c, n, next int) bool { + if n > given[len(given)-1] { + return true + } + + back := board[r][c] + if back != 0 && back != n { + return false + } + + if back == 0 && given[next] == n { + return false + } + + if back == n { + next++ + } + + board[r][c] = n + for i := -1; i < 2; i++ { + for j := -1; j < 2; j++ { + if solve(r+i, c+j, n+1, next) { + return true + } + } + } + + board[r][c] = back + return false +} + +func printBoard() { + for _, row := range board { + for _, c := range row { + switch { + case c == -1: + fmt.Print(" . ") + case c > 0: + fmt.Printf("%2d ", c) + default: + fmt.Print("__ ") + } + } + fmt.Println() + } +} + +func main() { + input := []string{ + "_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _", + } + setup(input) + printBoard() + fmt.Println("\nFound:") + solve(start[0], start[1], 1, 0) + printBoard() +} diff --git a/Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.elixir b/Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.elixir new file mode 100644 index 0000000000..a977209d61 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.elixir @@ -0,0 +1,13 @@ +# require HLPsolver + +adjacent = [{-3, 0}, {0, -3}, {0, 3}, {3, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}] + +board = """ +. 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 . . +. . . 1 . . . +""" +HLPsolver.solve(board, adjacent) diff --git a/Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-1.go b/Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-1.go new file mode 100644 index 0000000000..2329308f93 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-1.go @@ -0,0 +1,123 @@ +package main + +import ( + "fmt" + "sort" +) + +var board = []string{ + ".00.00.", + "0000000", + "0000000", + ".00000.", + "..000..", + "...0...", +} + +var moves = [][2]int{ + {-3, 0}, {0, 3}, {3, 0}, {0, -3}, + {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, +} + +var grid [][]int + +var totalToFill = 0 + +func solve(r, c, count int) bool { + if count > totalToFill { + return true + } + nbrs := neighbors(r, c) + if len(nbrs) == 0 && count != totalToFill { + return false + } + sort.Slice(nbrs, func(i, j int) bool { + return nbrs[i][2] < nbrs[j][2] + }) + + for _, nb := range nbrs { + r = nb[0] + c = nb[1] + grid[r][c] = count + if solve(r, c, count+1) { + return true + } + grid[r][c] = 0 + } + return false +} + +func neighbors(r, c int) (nbrs [][3]int) { + for _, m := range moves { + x := m[0] + y := m[1] + if grid[r+y][c+x] == 0 { + num := countNeighbors(r+y, c+x) - 1 + nbrs = append(nbrs, [3]int{r + y, c + x, num}) + } + } + return +} + +func countNeighbors(r, c int) int { + num := 0 + for _, m := range moves { + if grid[r+m[1]][c+m[0]] == 0 { + num++ + } + } + return num +} + +func printResult() { + for _, row := range grid { + for _, i := range row { + if i == -1 { + fmt.Print(" ") + } else { + fmt.Printf("%2d ", i) + } + } + fmt.Println() + } +} + +func main() { + nRows := len(board) + 6 + nCols := len(board[0]) + 6 + grid = make([][]int, nRows) + for r := 0; r < nRows; r++ { + grid[r] = make([]int, nCols) + for c := 0; c < nCols; c++ { + grid[r][c] = -1 + } + for c := 3; c < nCols-3; c++ { + if r >= 3 && r < nRows-3 { + if board[r-3][c-3] == '0' { + grid[r][c] = 0 + totalToFill++ + } + } + } + } + pos, r, c := -1, 0, 0 + for { + for { + pos++ + r = pos / nCols + c = pos % nCols + if grid[r][c] != -1 { + break + } + } + grid[r][c] = 1 + if solve(r, c, 2) { + break + } + grid[r][c] = 0 + if pos >= nRows*nCols { + break + } + } + printResult() +} diff --git a/Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-2.go b/Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-2.go new file mode 100644 index 0000000000..8b9f27784c --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Go/solve-a-hopido-puzzle-2.go @@ -0,0 +1,98 @@ +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-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.elixir b/Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.elixir new file mode 100644 index 0000000000..a32dba3b70 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.elixir @@ -0,0 +1,29 @@ +# require HLPsolver + +adjacent = [{-1, 0}, {0, -1}, {0, 1}, {1, 0}] + +board1 = """ + 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 +""" +HLPsolver.solve(board1, adjacent) + +board2 = """ + 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 +""" +HLPsolver.solve(board2, adjacent) diff --git a/Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-1.go b/Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-1.go new file mode 100644 index 0000000000..7861f08c6b --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-1.go @@ -0,0 +1,119 @@ +package main + +import ( + "fmt" + "sort" + "strconv" + "strings" +) + +var example1 = []string{ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00", +} + +var example2 = []string{ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00", +} + +var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} + +var ( + grid [][]int + clues []int + totalToFill = 0 +) + +func solve(r, c, count, nextClue int) bool { + if count > totalToFill { + return true + } + + back := grid[r][c] + + if back != 0 && back != count { + return false + } + + if back == 0 && nextClue < len(clues) && clues[nextClue] == count { + return false + } + + if back == count { + nextClue++ + } + + grid[r][c] = count + for _, move := range moves { + if solve(r+move[1], c+move[0], count+1, nextClue) { + return true + } + } + grid[r][c] = back + return false +} + +func printResult(n int) { + fmt.Println("Solution for example", n, "\b:") + for _, row := range grid { + for _, i := range row { + if i == -1 { + continue + } + fmt.Printf("%2d ", i) + } + fmt.Println() + } +} + +func main() { + for n, board := range [2][]string{example1, example2} { + nRows := len(board) + 2 + nCols := len(strings.Split(board[0], ",")) + 2 + startRow, startCol := 0, 0 + grid = make([][]int, nRows) + totalToFill = (nRows - 2) * (nCols - 2) + var lst []int + + for r := 0; r < nRows; r++ { + grid[r] = make([]int, nCols) + for c := 0; c < nCols; c++ { + grid[r][c] = -1 + } + if r >= 1 && r < nRows-1 { + row := strings.Split(board[r-1], ",") + for c := 1; c < nCols-1; c++ { + val, _ := strconv.Atoi(row[c-1]) + if val > 0 { + lst = append(lst, val) + } + if val == 1 { + startRow, startCol = r, c + } + grid[r][c] = val + } + } + } + + sort.Ints(lst) + clues = lst + if solve(startRow, startCol, 1, 0) { + printResult(n + 1) + } + } +} diff --git a/Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-2.go b/Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-2.go new file mode 100644 index 0000000000..c2e2906849 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Go/solve-a-numbrix-puzzle-2.go @@ -0,0 +1,90 @@ +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/Perl/solve-a-numbrix-puzzle.pl b/Task/Solve-a-Numbrix-puzzle/Perl/solve-a-numbrix-puzzle.pl new file mode 100644 index 0000000000..c2063c2525 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Perl/solve-a-numbrix-puzzle.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +$_ = < [1, 2, 3, 4, 5] + +puts a +# => [5, 4, 3, 2, 1] + +a.sort! +puts a +# => [1, 2, 3, 4, 5] diff --git a/Task/Sort-an-integer-array/Forth/sort-an-integer-array.fth b/Task/Sort-an-integer-array/Forth/sort-an-integer-array-1.fth similarity index 100% rename from Task/Sort-an-integer-array/Forth/sort-an-integer-array.fth rename to Task/Sort-an-integer-array/Forth/sort-an-integer-array-1.fth diff --git a/Task/Sort-an-integer-array/Forth/sort-an-integer-array-2.fth b/Task/Sort-an-integer-array/Forth/sort-an-integer-array-2.fth new file mode 100644 index 0000000000..84e2972b11 --- /dev/null +++ b/Task/Sort-an-integer-array/Forth/sort-an-integer-array-2.fth @@ -0,0 +1,41 @@ +100000 CONSTANT SIZE + +CREATE MYARRAY SIZE CELLS ALLOT + +: [] ( n addr -- addr[n]) SWAP CELLS + ; + +: FILLIT ( -- ) ( reversed order) + SIZE 0 DO SIZE I - I MYARRAY [] ! LOOP ; + +: SEEIT ( -- ) + SIZE 0 DO I MYARRAY [] ? LOOP ; + +\ define non-standard words used by Quicksort author +1 CELLS CONSTANT CELL +CELL NEGATE CONSTANT -CELL +: CELL- CELL - ; + +: MID ( l r -- mid ) OVER - 2/ -CELL AND + ; + +: EXCH ( addr1 addr2 -- ) + OVER @ OVER @ ( read values) + SWAP ROT ! SWAP ! ; ( exchange values) + +: PARTITION ( l r -- l r r2 l2 ) + 2DUP MID @ >R ( r: pivot ) + 2DUP + BEGIN + SWAP BEGIN DUP @ R@ < WHILE CELL+ REPEAT + SWAP BEGIN R@ OVER @ < WHILE CELL- REPEAT + 2DUP <= IF 2DUP EXCH >R CELL+ R> CELL- THEN + 2DUP > + UNTIL + R> DROP ; + +: QSORT ( l r -- ) + PARTITION SWAP ROT + 2DUP < IF RECURSE ELSE 2DROP THEN + 2DUP < IF RECURSE ELSE 2DROP THEN ; + +: QUICKSORT ( array len -- ) + DUP 2 < IF 2DROP EXIT THEN 1- CELLS OVER + QSORT ; diff --git a/Task/Sort-an-integer-array/Forth/sort-an-integer-array-3.fth b/Task/Sort-an-integer-array/Forth/sort-an-integer-array-3.fth new file mode 100644 index 0000000000..500dfe6492 --- /dev/null +++ b/Task/Sort-an-integer-array/Forth/sort-an-integer-array-3.fth @@ -0,0 +1,2 @@ +FILLIT ok +MYARRAY SIZE QUICKSORT ok diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx index ac10cc29af..5218a5c9d0 100644 --- a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx @@ -1,37 +1,29 @@ -/*REXX program sorts an array (using E-sort), in this case, the array contains integers.*/ +/*REXX program sorts an array (using E─sort), in this case, the array contains integers.*/ numeric digits 30 /*enables handling larger Euler numbers*/ - @. = 0 /*the default for all Euler numbers. */ - @.1 = 1 - @.3 = -1 - @.5 = 5 - @.7 = -61 - @.9 = 1385 - @.11= -50521 - @.13= 2702765 - @.15= -199360981 - @.17= 19391512145 - @.19= -2404879675441 - @.21= 370371188237525 -size=21 /*indicate that there're 21 Euler #s.*/ -call tell 'un-sorted' /*display the array before the eSsort. */ -call eSort size /*sort the array of some Euler numbers.*/ -call tell ' sorted' /*display the array after the sort. */ + @. = 0; @.1 = 1 + @.3 = -1; @.5 = 5 + @.7 = -61; @.9 = 1385 + @.11= -50521; @.13= 2702765 + @.15= -199360981; @.17= 19391512145 + @.19= -2404879675441; @.21= 370371188237525 +#= 21 /*indicate there're 21 Euler numbers.*/ +call tell 'unsorted' /*display the array before the eSort. */ +call eSort # /*sort the array of some Euler numbers.*/ +call tell ' sorted' /*display the array after the eSort. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -eSort: procedure expose @.; parse arg N; h=N - do while h>1; h=h%2 - do i=1 for N-h; j=i; k=h+i - do while @.k<@.j - parse value @.j @.k with @.k @.j /*swap two array elements.*/ - if h>=j then leave; j=j-h; k=k-h +eSort: procedure expose @.; parse arg N; h=N /*an eXchange sort.*/ + do while h>1; h= h%2 /*define a segment.*/ + do i=1 for N-h; j=i; k= h+i /*sort top segment.*/ + do while @.k<@.j /*see if need swap.*/ + parse value @.j @.k with @.k @.j /*swap two elements*/ + if h>=j then leave; j= j-h; k= k-h /*this part sorted?*/ end /*while @.k<@.j*/ end /*i*/ - end /*while h>1*/ + end /*while h>1*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ -tell: say center(arg(1), 50, '─') - do j=1 for size - say arg(1) 'array element' right(j, length(size))'='right(@.j, 20) - end /*j*/ - say +tell: say copies('─', 65); _= left('',9); w= length(#) + do j=1 for #; say _ arg(1) 'array element' right(j, w)"="right(@.j, 20) + end /*j*/ return diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx index 105caaab3c..58790194fe 100644 --- a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx @@ -16,13 +16,13 @@ $= /*list: define as nul say ' sorted =' space($) /*display the sorted list. */ exit /*stick a fork in it, we're all done.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -eSort: procedure expose @.; parse arg N; h=N /*get item count for array. */ - do while h>1; h=h%2 /*partition the array. */ - do i=1 for N-h; j=i; k=h+i - do while @.k<@.j /*keep swapping while less. */ - parse value @.j @.k with @.k @.j /*swap two array elements. */ - if h>=j then leave; j=j-h; k=k-h - end /*while @.k<@.j*/ - end /*i*/ - end /*while h>1*/ +eSort: procedure expose @.; parse arg N; h=N /*an eXchange sort.*/ + do while h>1; h= h%2 /*define a segment.*/ + do i=1 for N-h; j=i; k= h+i /*sort top segment.*/ + do while @.k<@.j /*see if need swap.*/ + parse value @.j @.k with @.k @.j /*swap two elements*/ + if h>=j then leave; j= j-h; k= k-h /*this part sorted?*/ + end /*while @.k<@.j*/ + end /*i*/ + end /*while h>1*/ return diff --git a/Task/Sort-disjoint-sublist/Maple/sort-disjoint-sublist.maple b/Task/Sort-disjoint-sublist/Maple/sort-disjoint-sublist.maple new file mode 100644 index 0000000000..8cf60057de --- /dev/null +++ b/Task/Sort-disjoint-sublist/Maple/sort-disjoint-sublist.maple @@ -0,0 +1,10 @@ +sortDisjoint := proc(values, indices::set) + local vals,inds,i: + vals := sort([seq(values[i], i in indices)]): + inds := sort(convert(indices, Array)): + for i to numelems(vals) do + values(inds[i]) := vals[i]: + od: +end proc: +tst := Array([7,6,5,4,3,2,1,0]): +sortDisjoint(tst,{7,2,8}); diff --git a/Task/Sorting-algorithms-Bogosort/Ring/sorting-algorithms-bogosort.ring b/Task/Sorting-algorithms-Bogosort/Ring/sorting-algorithms-bogosort.ring index 57ea33469d..b33d3e60ea 100644 --- a/Task/Sorting-algorithms-Bogosort/Ring/sorting-algorithms-bogosort.ring +++ b/Task/Sorting-algorithms-Bogosort/Ring/sorting-algorithms-bogosort.ring @@ -1,7 +1,4 @@ # Project : Sorting algorithms/Bogosort -# Date : 2018/02/17 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : test = [4, 65, 2, 31, 0, 99, 2, 83, 782, 1] shuffles = 0 diff --git a/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-2.basic b/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-2.basic index 58100e2c58..9802e00630 100644 --- a/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-2.basic +++ b/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-2.basic @@ -1,14 +1,10 @@ - 10 LET S$="FIRE BURN AND CAULDRON BUBBLE" - 20 PRINT S$ - 30 LET L=LEN S$-1 - 40 LET C=0 - 50 FOR I=1 TO L - 60 IF S$(I)<=S$(I+1) THEN GOTO 120 - 70 LET T$=S$(I) - 80 LET S$(I)=S$(I+1) - 90 LET S$(I+1)=T$ -100 PRINT AT 0,I-1;S$(I TO I+1) -110 LET C=1 -120 NEXT I -130 LET L=L-1 -140 IF C THEN GOTO 40 +0 GOSUB 7 : IC = I%(0) +1 FOR HC = -1 TO 0 +2 LET IC = IC - 1 +3 FOR I = 1 TO IC +4 IF I%(I) > I%(I + 1) THEN H = I%(I) : I%(I) = I%(I + 1) : I%(I + 1) = H : HC = -2 * (IC > 1) +5 NEXT I, HC +6 GOSUB 9 : END +7 DIM I%(18000) : I%(0) = 50 +8 FOR I = 1 TO I%(0) : I%(I) = INT (RND(1) * 65535) - 32767 : NEXT +9 FOR I = 1 TO I%(0) : PRINT I%(I)" "; : NEXT I : PRINT : RETURN diff --git a/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-3.basic b/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-3.basic new file mode 100644 index 0000000000..58100e2c58 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort-3.basic @@ -0,0 +1,14 @@ + 10 LET S$="FIRE BURN AND CAULDRON BUBBLE" + 20 PRINT S$ + 30 LET L=LEN S$-1 + 40 LET C=0 + 50 FOR I=1 TO L + 60 IF S$(I)<=S$(I+1) THEN GOTO 120 + 70 LET T$=S$(I) + 80 LET S$(I)=S$(I+1) + 90 LET S$(I+1)=T$ +100 PRINT AT 0,I-1;S$(I TO I+1) +110 LET C=1 +120 NEXT I +130 LET L=L-1 +140 IF C THEN GOTO 40 diff --git a/Task/Sorting-algorithms-Cocktail-sort/Scala/sorting-algorithms-cocktail-sort.scala b/Task/Sorting-algorithms-Cocktail-sort/Scala/sorting-algorithms-cocktail-sort.scala new file mode 100644 index 0000000000..79170dfe13 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Scala/sorting-algorithms-cocktail-sort.scala @@ -0,0 +1,26 @@ +object CocktailSort extends App { + def sort(arr: Array[Int]) = { + var swapped = false + do { + def swap(i: Int) { + val temp = arr(i) + arr(i) = arr(i + 1) + arr(i + 1) = temp + swapped = true + } + + swapped = false + for (i <- 0 to (arr.length - 2)) if (arr(i) > arr(i + 1)) swap(i) + + if (swapped) { + swapped = false + for (j <- arr.length - 2 to 0 by -1) if (arr(j) > arr(j + 1)) swap(j) + //if no elements have been swapped, then the list is sorted + } + } while (swapped) + arr + } + + println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", ")) + +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Scala/sorting-algorithms-gnome-sort.scala b/Task/Sorting-algorithms-Gnome-sort/Scala/sorting-algorithms-gnome-sort.scala new file mode 100644 index 0000000000..83231d012b --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Scala/sorting-algorithms-gnome-sort.scala @@ -0,0 +1,13 @@ +object GnomeSort { + def gnomeSort(a: Array[Int]): Unit = { + var (i, j) = (1, 2) + while ( i < a.length) + if (a(i - 1) <= a(i)) { i = j; j += 1 } + else { + val tmp = a(i - 1) + a(i - 1) = a(i) + a({i -= 1; i + 1}) = tmp + i = if (i == 0) {j += 1; j - 1} else i + } + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Ring/sorting-algorithms-heapsort.ring b/Task/Sorting-algorithms-Heapsort/Ring/sorting-algorithms-heapsort.ring index ac10095210..2b40ccca26 100644 --- a/Task/Sorting-algorithms-Heapsort/Ring/sorting-algorithms-heapsort.ring +++ b/Task/Sorting-algorithms-Heapsort/Ring/sorting-algorithms-heapsort.ring @@ -1,7 +1,4 @@ # Project : Sorting algorithms/Heapsort -# Date : 2018/03/04 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : test = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] see "before sort:" + nl diff --git a/Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vb b/Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vb new file mode 100644 index 0000000000..ec90898861 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vb @@ -0,0 +1,36 @@ +Randomize +Dim n(9) 'nine is the upperbound. + 'since VBS arrays are 0-based, it will have 10 elements. +For L = 0 to 9 + n(L) = Int(Rnd * 32768) +Next + +WScript.StdOut.Write "ORIGINAL : " +For L = 0 to 9 + WScript.StdOut.Write n(L) & ";" +Next + +InsertionSort n + +WScript.StdOut.Write vbCrLf & " SORTED : " +For L = 0 to 9 + WScript.StdOut.Write n(L) & ";" +Next + +'the function +Sub InsertionSort(theList) + For insertionElementIndex = 1 To UBound(theList) + insertionElement = theList(insertionElementIndex) + j = insertionElementIndex - 1 + Do While j >= 0 + 'necessary for BASICs without short-circuit evaluation + If insertionElement < theList(j) Then + theList(j + 1) = theList(j) + j = j - 1 + Else + Exit Do + End If + Loop + theList(j + 1) = insertionElement + Next +End Sub 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 index adb54b5f04..1154970f80 100644 --- 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 @@ -1,17 +1,19 @@ -fun mergeSort(m): - if m.len <= 1: return m - let middle = floor m.len / 2 +fun mergesort(m): + if m.lenght <= 1: return m + let middle = floor m.lenght / 2 let left = merge(m[:middle]) let right = merge(m[middle-1:]); fun merge(left, right): let result = [] - while not (left.isEmpty or right.isEmpty): + while not (left.isempty or right.isempty): if left[1] <= right[1]: - result ++ left.shift() + result.push left.shift() else: - result ++ right.shift() - result ++ left ++ right + result.push right.shift() + result.push left.push right let arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] +print mergesort arr + print mergeSort arr diff --git a/Task/Sorting-algorithms-Pancake-sort/Maple/sorting-algorithms-pancake-sort.maple b/Task/Sorting-algorithms-Pancake-sort/Maple/sorting-algorithms-pancake-sort.maple new file mode 100644 index 0000000000..5631d548a6 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Maple/sorting-algorithms-pancake-sort.maple @@ -0,0 +1,30 @@ +flip := proc(arr, i) + local start, temp, icopy; + temp, start, icopy := 0,1,i: + while (start < icopy) do + arr[start], arr[icopy] := arr[icopy], arr[start]: + start:=start+1: + icopy:=icopy-1: + end do: +end proc: +findMax := proc(arr, i) + local Max, j: + Max := 1: + for j from 1 to i do + if arr[j] > arr[Max] then Max := j: end if: + end do: + return Max: +end proc: +pancakesort := proc(arr) + local len,i,Max; + len := numelems(arr): + for i from len to 2 by -1 do + print(arr): + Max := findMax(arr, i): + if (not Max = i) then + flip(arr, Max): + flip(arr, i): + end if: + end do: + print(arr); +end proc: diff --git a/Task/Sorting-algorithms-Permutation-sort/Ring/sorting-algorithms-permutation-sort.ring b/Task/Sorting-algorithms-Permutation-sort/Ring/sorting-algorithms-permutation-sort.ring index 1bcf6aa8b7..c4c8a5c7a6 100644 --- a/Task/Sorting-algorithms-Permutation-sort/Ring/sorting-algorithms-permutation-sort.ring +++ b/Task/Sorting-algorithms-Permutation-sort/Ring/sorting-algorithms-permutation-sort.ring @@ -1,7 +1,4 @@ # Project : Sorting algorithms/Permutation sort -# Date : 2018/02/20 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : a = [4, 65, 2, 31, 0, 99, 2, 83, 782] result = [] diff --git a/Task/Sorting-algorithms-Quicksort/Ring/sorting-algorithms-quicksort.ring b/Task/Sorting-algorithms-Quicksort/Ring/sorting-algorithms-quicksort.ring index 0f610cc0ca..f5c3092469 100644 --- a/Task/Sorting-algorithms-Quicksort/Ring/sorting-algorithms-quicksort.ring +++ b/Task/Sorting-algorithms-Quicksort/Ring/sorting-algorithms-quicksort.ring @@ -1,7 +1,4 @@ # Project : Sorting algorithms/Quicksort -# Date : 2018/03/04 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : test = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] see "before sort:" + nl diff --git a/Task/Sorting-algorithms-Radix-sort/Scala/sorting-algorithms-radix-sort.scala b/Task/Sorting-algorithms-Radix-sort/Scala/sorting-algorithms-radix-sort.scala new file mode 100644 index 0000000000..e744e0f82d --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Scala/sorting-algorithms-radix-sort.scala @@ -0,0 +1,26 @@ +object RadixSort extends App { + def sort(toBeSort: Array[Int]): Array[Int] = { // Loop for every bit in the integers + var arr = toBeSort + for (shift <- Integer.SIZE - 1 until -1 by -1) { // The array to put the partially sorted array into + val tmp = new Array[Int](arr.length) + // The number of 0s + var j = 0 + // Move the 0s to the new array, and the 1s to the old one + for (i <- arr.indices) // If there is a 1 in the bit we are testing, the number will be negative + // If this is the last bit, negative numbers are actually lower + if ((shift == 0) == (arr(i) << shift >= 0)) arr(i - j) = arr(i) + else { + tmp(j) = arr(i) + j += 1 + } + // Copy over the 1s from the old array + arr.copyToArray(tmp, j, arr.length - j) + + // And now the tmp array gets switched for another round of sorting + arr = tmp + } + arr + } + + println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", ")) +} diff --git a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-3.js b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-3.js new file mode 100644 index 0000000000..dbf229f98b --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-3.js @@ -0,0 +1,13 @@ +Array.prototype.sleepSort = function(callback) { + const res = []; + for (let n of this) + setTimeout(() => { + res.push(n); + if (this.length === res.length) + callback(res); + }, n + 1); + return res; +}; + +[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].sleepSort(console.log); +// [ 1, 0, 2, 3, 4, 5, 5, 6, 7, 8, 9 ] diff --git a/Task/Sorting-algorithms-Strand-sort/Ring/sorting-algorithms-strand-sort.ring b/Task/Sorting-algorithms-Strand-sort/Ring/sorting-algorithms-strand-sort.ring index 41d162958c..c000842e25 100644 --- a/Task/Sorting-algorithms-Strand-sort/Ring/sorting-algorithms-strand-sort.ring +++ b/Task/Sorting-algorithms-Strand-sort/Ring/sorting-algorithms-strand-sort.ring @@ -1,7 +1,4 @@ # Project : Sorting algorithms/Strand sort -# Date : 2018/03/04 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : test = [-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2] results = [] diff --git a/Task/Soundex/Ring/soundex.ring b/Task/Soundex/Ring/soundex.ring index ef83eb8fe3..803c2f1304 100644 --- a/Task/Soundex/Ring/soundex.ring +++ b/Task/Soundex/Ring/soundex.ring @@ -1,7 +1,4 @@ # Project: Soundex -# Date : 2018/06/11 -# Author: Gal Zsolt [~ CalmoSoft ~] -# Email : name = ["Ashcraf", "Ashcroft", "Gauss", "Ghosh", "Hilbert", "Heilbronn", "Lee", "Lloyd", "Moses", "Pfister", "Robert", "Rupert", "Rubin","Tymczak", "Soundex", "Example"] diff --git a/Task/Sparkline-in-unicode/C/sparkline-in-unicode.c b/Task/Sparkline-in-unicode/C/sparkline-in-unicode.c index 762e4850d5..607bf70aeb 100644 --- a/Task/Sparkline-in-unicode/C/sparkline-in-unicode.c +++ b/Task/Sparkline-in-unicode/C/sparkline-in-unicode.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 5th October 2017*/ - #include #include #include diff --git a/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript b/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript index 77099c55b5..d43f68651b 100644 --- a/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript +++ b/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript @@ -1,83 +1,167 @@ --- SPIRAL MATRIX ------------------------------------------------------------- +-- spiral :: Int -> [[Int]] +on spiral(n) + script go + on |Ξ»|(rows, cols, start) + if 0 < rows then + {enumFromTo(start, start + pred(cols))} & Β¬ + map(my |reverse|, Β¬ + (transpose(|Ξ»|(cols, pred(rows), start + cols)))) + else + {{}} + end if + end |Ξ»| + end script --- spiral :: Int -> Int -> Int -> [[Int]] -on spiral(lngRows, lngCols, nStart) - if lngRows > 0 then - {enumFromTo(nStart, (nStart + lngCols) - 1)} & Β¬ - map(my |reverse|, Β¬ - transpose(spiral(lngCols, lngRows - 1, nStart + lngCols))) - else - {{}} - end if + go's |Ξ»|(n, n, 0) end spiral - --- TEST ---------------------------------------------------------------------- +-- TEST ------------------------------------------------------------------ on run - set n to 5 - set lstSpiral to spiral(n, n, 0) - -- {{0, 1, 2, 3, 4}, {15, 16, 17, 18, 5}, {14, 23, 24, 19, 6}, - -- {13, 22, 21, 20, 7}, {12, 11, 10, 9, 8}} - - wikiTable(lstSpiral, Β¬ + wikiTable(spiral(5), Β¬ false, Β¬ "text-align:center;width:12em;height:12em;table-layout:fixed;") end run - -- WIKI TABLE FORMAT --------------------------------------------------------- -- wikiTable :: [Text] -> Bool -> Text -> Text on wikiTable(lstRows, blnHdr, strStyle) script fWikiRows on |Ξ»|(lstRow, iRow) - set strDelim to cond(blnHdr and (iRow = 0), "!", "|") + set strDelim to if_(blnHdr and (iRow = 0), "!", "|") set strDbl to strDelim & strDelim linefeed & "|-" & linefeed & strDelim & space & Β¬ - intercalate(space & strDbl & space, lstRow) + intercalateS(space & strDbl & space, lstRow) end |Ξ»| end script linefeed & "{| class=\"wikitable\" " & Β¬ - cond(strStyle β‰  "", "style=\"" & strStyle & "\"", "") & Β¬ - intercalate("", Β¬ + if_(strStyle β‰  "", "style=\"" & strStyle & "\"", "") & Β¬ + intercalateS("", Β¬ map(fWikiRows, lstRows)) & linefeed & "|}" & linefeed end wikiTable +-- GENERIC ------------------------------------------------------------------ --- GENERIC FUNCTIONS --------------------------------------------------------- +-- comparing :: (a -> b) -> (a -> a -> Ordering) +on comparing(f) + script + on |Ξ»|(a, b) + tell mReturn(f) + set fa to |Ξ»|(a) + set fb to |Ξ»|(b) + if fa < fb then + -1 + else if fa > fb then + 1 + else + 0 + end if + end tell + end |Ξ»| + end script +end comparing --- cond :: Bool -> a -> a -> a -on cond(bool, x, y) +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set lng to length of xs + if 0 < lng and class of xs is string then + set acc to "" + else + set acc to {} + end if + tell mReturn(f) + repeat with i from 1 to lng + set acc to acc & |Ξ»|(item i of xs, i, xs) + end repeat + end tell + return acc +end concatMap + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m ≀ n then + set lst to {} + repeat with i from m to n + set end of lst to i + end repeat + return lst + else + return {} + end if +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 + +-- if_ :: Bool -> a -> a -> a +on if_(bool, x, y) if bool then x else y end if -end cond +end if_ --- 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 - --- 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 +-- intercalateS :: String -> [String] -> String +on intercalateS(sep, xs) + set {dlm, my text item delimiters} to {my text item delimiters, sep} + set s to xs as text set my text item delimiters to dlm - return strJoined -end intercalate + return s +end intercalateS + +-- length :: [a] -> Int +on |length|(xs) + length of xs +end |length| + +-- max :: Ord a => a -> a -> a +on max(x, y) + if x > y then + x + else + y + end if +end max + +-- 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 :: First-class m => (a -> b) -> m (a -> b) +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) @@ -91,17 +175,28 @@ on map(f, xs) 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 +-- pred :: Enum a => a -> a +on pred(x) + (-1) + x +end pred + +-- 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 + -- reverse :: [a] -> [a] on |reverse|(xs) @@ -112,19 +207,48 @@ on |reverse|(xs) end if end |reverse| +-- If some of the rows are shorter than the following rows, +-- their elements are skipped: +-- transpose({{10,11},{20},{},{30,31,32}}) -> {{10, 20, 30}, {11, 31}, {32}} -- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on |Ξ»|(_, iCol) - script row - on |Ξ»|(xs) - item iCol of xs - end |Ξ»| - end script - - map(row, xss) +on transpose(xxs) + set intMax to |length|(maximumBy(comparing(my |length|), xxs)) + set gaps to replicate(intMax, {}) + script padded + on |Ξ»|(xs) + set lng to |length|(xs) + if lng < intMax then + xs & items (lng + 1) thru -1 of gaps + else + xs + end if end |Ξ»| end script + set rows to map(padded, xxs) - map(column, item 1 of xss) + script cols + on |Ξ»|(_, iCol) + script cell + on |Ξ»|(row) + item iCol of row + end |Ξ»| + end script + concatMap(cell, rows) + end |Ξ»| + end script + map(cols, item 1 of rows) end transpose + +-- unlines :: [String] -> String +on unlines(xs) + set {dlm, my text item delimiters} to Β¬ + {my text item delimiters, linefeed} + set str to xs as text + set my text item delimiters to dlm + str +end unlines + +-- unwords :: [String] -> String +on unwords(xs) + intercalateS(space, xs) +end unwords diff --git a/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs b/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs index 8690da4a17..ac69c011c1 100644 --- a/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs +++ b/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs @@ -1,11 +1,27 @@ -import Data.List (transpose) +import Data.List (intercalate, transpose) +import Control.Monad (join) -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 [[]] +spiral :: Int -> [[Int]] +spiral n = go n n 0 + where + go rows cols start = + if 0 < rows + then [start .. start + pred cols] : + fmap reverse (transpose $ go cols (pred rows) (start + cols)) + else [[]] main :: IO () -main = mapM_ print $ spiral 5 5 0 +main = putStrLn $ wikiTable (spiral 5) + + +-- TABLE FORMATTING ---------------------------------------- + +wikiTable :: Show a => [[a]] -> String +wikiTable = + join . + ("{| class=\"wikitable\" style=\"text-align:center;" :) . + ("width:12em;height:12em;table-layout:fixed;\"\n|-\n" :) . + return . + (++ "\n|}") . + intercalate "\n|-\n" . + fmap (('|' :) . (' ' :) . intercalate " || " . fmap show) diff --git a/Task/Spiral-matrix/JavaScript/spiral-matrix-4.js b/Task/Spiral-matrix/JavaScript/spiral-matrix-4.js index ef438ea65f..c7e612f173 100644 --- a/Task/Spiral-matrix/JavaScript/spiral-matrix-4.js +++ b/Task/Spiral-matrix/JavaScript/spiral-matrix-4.js @@ -1,67 +1,122 @@ -(n => { +(() => { + 'use strict'; - // spiral :: the first row plus a smaller spiral rotated 90 degrees clockwise - // spiral :: Int -> Int -> Int -> [[Int]] - function spiral(lngRows, lngCols, nStart) { - return lngRows ? [range(nStart, (nStart + lngCols) - 1)] - .concat( - transpose( - spiral(lngCols, lngRows - 1, nStart + lngCols) + // main :: () -> String + const main = () => + unlines( + map(unwords, spiral(5)) + ); + + // spiral :: Int -> [[Int]] + const spiral = n => { + const go = (rows, cols, start) => + 0 < rows ? [ + enumFromTo(start, start + pred(cols)), + ...map( + reverse, + transpose( + go( + cols, + pred(rows), + start + cols + ) + ) ) - .map(reverse) - ) : [[]]; - } + ] : [ + [] + ]; + return go(n, n, 0); + }; - // transpose :: [[a]] -> [[a]] - function transpose(xs) { - return xs[0] - .map((_, iCol) => xs - .map((row) => row[iCol])); - } + // 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) => + 0 < xs.length ? (() => { + const unit = 'string' !== typeof xs ? ( + [] + ) : ''; + return unit.concat.apply(unit, xs.map(f)) + })() : []; + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + m <= n ? iterateUntil( + x => n <= x, + x => 1 + x, + m + ) : []; + + // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] + const iterateUntil = (p, f, x) => { + const vs = [x]; + let h = x; + while (!p(h))(h = f(h), vs.push(h)); + return vs; + }; + + // length :: [a] -> Int + const length = xs => xs.length; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // Ordering: (LT|EQ|GT): + // GT: 1 (or other positive n) + // EQ: 0 + // LT: -1 (or other negative n) + + // maximumBy :: (a -> a -> Ordering) -> [a] -> a + const maximumBy = (f, xs) => + 0 < xs.length ? ( + xs.slice(1) + .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0]) + ) : undefined; + + + // pred :: Enum a => a -> a + const pred = x => x - 1; // reverse :: [a] -> [a] - function reverse(xs) { - return xs.slice(0) - .reverse(); - } + const reverse = xs => + 'string' !== typeof xs ? ( + xs.slice(0).reverse() + ) : xs.split('').reverse().join(''); - // range(intFrom, intTo, optional intStep) - // Int -> Int -> Maybe Int -> [Int] - function range(m, n, step) { - let d = (step || 1) * (n >= m ? 1 : -1); + // replicate :: Int -> a -> [a] + const replicate = (n, x) => + Array.from({ + length: n + }, () => x); - return Array.from({ - length: Math.floor((n - m) / d) + 1 - }, (_, i) => m + (i * d)); - } + // transpose :: [[a]] -> [[a]] + const transpose = tbl => { + const + gaps = replicate( + length(maximumBy(comparing(length), tbl)), [] + ), + rows = map(xs => xs.concat(gaps.slice(xs.length)), tbl); + return map( + (_, col) => concatMap(row => [row[col]], rows), + rows[0] + ); + }; + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + // unwords :: [String] -> String + const unwords = xs => xs.join(' '); - // TESTING - - // replicate :: Int -> String -> String - function replicate(n, a) { - var v = [a], - o = ''; - - if (n < 1) return o; - while (n > 1) { - if (n & 1) o = o + v; - n >>= 1; - v = v + v; - } - return o + v; - } - - - return spiral(n, n, 0) - .map( - xs => xs.map(x => { - let s = `${x}`; - return replicate(4 - s.length, ' ') + s; - }) - .join('') - ) - .join('\n'); - -})(5); + // MAIN --- + return main(); +})(); diff --git a/Task/Spiral-matrix/Ring/spiral-matrix.ring b/Task/Spiral-matrix/Ring/spiral-matrix.ring index d9c5bf5b3c..0ae8d7851b 100644 --- a/Task/Spiral-matrix/Ring/spiral-matrix.ring +++ b/Task/Spiral-matrix/Ring/spiral-matrix.ring @@ -1,46 +1,53 @@ # Project : Spiral matrix -# Date : 2018/03/23 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : +load "guilib.ring" load "stdlib.ring" -n = 5 -result = newlist(n,n) -k = 1 -top = 1 -bottom = n -left = 1 -right = n -while (k<=n*n) - for i=left to right - result[top][i]=k - k = k + 1 - next - top = top + 1 - for i=top to bottom - result[i][right]=k - k = k + 1 - next - right = right - 1 - for i=right to left step -1 - result[bottom][i]=k - k = k + 1 - next - bottom = bottom - 1 - for i=bottom to top step -1 - result[i][left] = k - k = k + 1 - next - left = left + 1 -end -for m = 1 to n - for p = 1 to n - if m = 1 - see " " + result[m][p] - else - see "" + result[m][p] + " " - ok - next - see nl -next -see nl +new qapp + { + win1 = new qwidget() { + setwindowtitle("Spiral matrix") + setgeometry(100,100,600,400) + n = 5 + result = newlist(n,n) + spiral = newlist(n,n) + k = 1 + top = 1 + bottom = n + left = 1 + right = n + while (k <= n*n) + for i= left to right + result[top][i] = k + k = k + 1 + next + top = top + 1 + for i = top to bottom + result[i][right] = k + k = k + 1 + next + right = right - 1 + for i = right to left step -1 + result[bottom][i] = k + k = k + 1 + next + bottom = bottom - 1 + for i = bottom to top step -1 + result[i][left] = k + k = k + 1 + next + left = left + 1 + end + for m = 1 to n + for p = 1 to n + spiral[p][m] = new qpushbutton(win1) { + x = 150+m*40 + y = 30 + p*40 + setgeometry(x,y,40,40) + settext(string(result[m][p])) + } + next + next + show() + } + exec() + } diff --git a/Task/Stack/REBOL/stack.rebol b/Task/Stack/REBOL/stack.rebol index 5003141bb3..8a20e0acd2 100644 --- a/Task/Stack/REBOL/stack.rebol +++ b/Task/Stack/REBOL/stack.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Stack" - Author: oofoe - Date: 2010-10-04 URL: http://rosettacode.org/wiki/Stack ] diff --git a/Task/Stack/Ring/stack.ring b/Task/Stack/Ring/stack.ring new file mode 100644 index 0000000000..43527a0f69 --- /dev/null +++ b/Task/Stack/Ring/stack.ring @@ -0,0 +1,17 @@ +# Project : Stack + +load "stdlib.ring" +ostack = new stack +for n = 5 to 7 + see "Push: " + n + nl + ostack.push(n) +next +see "Pop:" + ostack.pop() + nl +see "Push: " + "8" + nl +ostack.push(8) +while len(ostack) > 0 + see "Pop:" + ostack.pop() + nl +end +if len(ostack) = 0 + see "Pop: stack is empty" + nl +ok diff --git a/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol b/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol index 8f60d1984b..4e4c5065c5 100644 --- a/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol +++ b/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Stair Climber" - Date: 2009-12-14 - Author: oofoe URL: http://rosettacode.org/wiki/Stair_Climbing ] diff --git a/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c b/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c index 11b4dd1027..82133df02e 100644 --- a/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c +++ b/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c @@ -1,4 +1,3 @@ -/*Abhishek Ghosh, 7th November 2013, Rotterdam*/ #include #define start main() diff --git a/Task/Statistics-Basic/R/statistics-basic.r b/Task/Statistics-Basic/R/statistics-basic.r index 3b82ef2f10..451112ed83 100644 --- a/Task/Statistics-Basic/R/statistics-basic.r +++ b/Task/Statistics-Basic/R/statistics-basic.r @@ -1,5 +1,3 @@ -#Abhishek Ghosh, 10th January 2018 - #Generate the sets a = runif(10,min=0,max=1) b = runif(100,min=0,max=1) diff --git a/Task/Statistics-Basic/Ring/statistics-basic.ring b/Task/Statistics-Basic/Ring/statistics-basic.ring index cf98f3db17..5862f1cc98 100644 --- a/Task/Statistics-Basic/Ring/statistics-basic.ring +++ b/Task/Statistics-Basic/Ring/statistics-basic.ring @@ -1,7 +1,4 @@ # Project : Statistics/Basic -# Date : 2017/11/14 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(9) sample(100) diff --git a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl index 0e1e2a7b76..450acf65ff 100644 --- a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl +++ b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl @@ -1,5 +1,3 @@ -#!/usr/bin/perl -w - my @data = sort {$a <=> $b} qw( 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 @@ -7,19 +5,8 @@ my @data = sort {$a <=> $b} qw( 12 127 28 42 39 113 42 18 44 118 44 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 ); - -# FIXME: This should count the maximum number of leaves in any one stem; -# instead it takes the total number of data items, which is usually -# a massive overestimate. my $columns = @data; -print <<"EOT"; -\\documentclass{report} -\\usepackage{fullpage} -\\begin{document} - \\begin{tabular}{ r | *{$columns}{c} } -EOT - my $laststem = undef; for my $value (@data) { @@ -29,15 +16,10 @@ for my $value (@data) { if (not defined $laststem) { $laststem = $stem - 1; } else { - print " \\\\\n"; + print " \n"; } $laststem++; - print " $laststem"; + printf "%3d |", $laststem; } - printf " & $leaf"; + print " $leaf"; } -print <<'EOT'; - - \end{tabular} -\end{document} -EOT diff --git a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl index d15135f545..0e1e2a7b76 100644 --- a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl +++ b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl @@ -1,12 +1,43 @@ -\documentclass{report} -\usepackage{fullpage} -\begin{document} - \begin{tabular}{ r | *{120}{c} } - 0 & 7 & 7 \\ - 1 & 2 & 3 & 8 & 8 \\ - 2 & 3 & 5 & 7 & 7 & 7 & 7 & 7 & 7 & 8 & 8 & 9 & 9 \\ - ... - 13 & 1 & 2 & 3 & 9 \\ - 14 & 1 +#!/usr/bin/perl -w + +my @data = sort {$a <=> $b} qw( 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 ); + +# FIXME: This should count the maximum number of leaves in any one stem; +# instead it takes the total number of data items, which is usually +# a massive overestimate. +my $columns = @data; + +print <<"EOT"; +\\documentclass{report} +\\usepackage{fullpage} +\\begin{document} + \\begin{tabular}{ r | *{$columns}{c} } +EOT + +my $laststem = undef; + +for my $value (@data) { + my $stem = int($value / 10); + my $leaf = $value % 10; + while (not defined $laststem or $stem > $laststem) { + if (not defined $laststem) { + $laststem = $stem - 1; + } else { + print " \\\\\n"; + } + $laststem++; + print " $laststem"; + } + printf " & $leaf"; +} +print <<'EOT'; + \end{tabular} \end{document} +EOT diff --git a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-3.pl b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-3.pl new file mode 100644 index 0000000000..d15135f545 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-3.pl @@ -0,0 +1,12 @@ +\documentclass{report} +\usepackage{fullpage} +\begin{document} + \begin{tabular}{ r | *{120}{c} } + 0 & 7 & 7 \\ + 1 & 2 & 3 & 8 & 8 \\ + 2 & 3 & 5 & 7 & 7 & 7 & 7 & 7 & 7 & 8 & 8 & 9 & 9 \\ + ... + 13 & 1 & 2 & 3 & 9 \\ + 14 & 1 + \end{tabular} +\end{document} diff --git a/Task/Stem-and-leaf-plot/Ring/stem-and-leaf-plot.ring b/Task/Stem-and-leaf-plot/Ring/stem-and-leaf-plot.ring index 2b0fe147ac..16983097c5 100644 --- a/Task/Stem-and-leaf-plot/Ring/stem-and-leaf-plot.ring +++ b/Task/Stem-and-leaf-plot/Ring/stem-and-leaf-plot.ring @@ -1,7 +1,4 @@ # Project : Stem-and-leaf plot -# Date : 2018/03/16 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : data = list(120) data = [12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, diff --git a/Task/Stern-Brocot-sequence/Factor/stern-brocot-sequence.factor b/Task/Stern-Brocot-sequence/Factor/stern-brocot-sequence.factor new file mode 100644 index 0000000000..7e94818905 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Factor/stern-brocot-sequence.factor @@ -0,0 +1,31 @@ +USING: formatting io kernel lists lists.lazy locals math +math.ranges prettyprint sequences ; +IN: rosetta-code.stern-brocot + +: fn ( n -- m ) + [ 1 0 ] dip + [ dup zero? ] [ + dup 1 bitand zero? + [ dupd [ + ] 2dip ] + [ [ dup ] [ + ] [ ] tri* ] if + -1 shift + ] until drop nip ; + +:: search ( n -- m ) + 1 0 lfrom [ fn n = ] lfilter ltake list>array first ; + +: first15 ( -- ) + 15 [1,b] [ fn pprint bl ] each + "are the first fifteen." print ; + +: first-appearances ( -- ) + 10 [1,b] 100 suffix + [ dup search "First %3u at Stern #%u.\n" printf ] each ; + +: gcd-test ( -- ) + 1,000 [1,b] [ dup 1 + [ fn ] bi@ gcd nip 1 = not ] filter + empty? "" " not" ? "All GCDs are%s 1.\n" printf ; + +: main ( -- ) first15 first-appearances gcd-test ; + +MAIN: main diff --git a/Task/Stern-Brocot-sequence/Ring/stern-brocot-sequence.ring b/Task/Stern-Brocot-sequence/Ring/stern-brocot-sequence.ring index a443a0aca4..d21685160b 100644 --- a/Task/Stern-Brocot-sequence/Ring/stern-brocot-sequence.ring +++ b/Task/Stern-Brocot-sequence/Ring/stern-brocot-sequence.ring @@ -1,7 +1,4 @@ # Project : Stern-Brocot sequence -# Date : 2018/02/01 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : limit = 1200 item = list(limit+1) diff --git a/Task/String-append/Forth/string-append-1.fth b/Task/String-append/Forth/string-append-1.fth index 5a1519bdce..f31937451e 100644 --- a/Task/String-append/Forth/string-append-1.fth +++ b/Task/String-append/Forth/string-append-1.fth @@ -1,4 +1,4 @@ -Strings in Forth are simply named memory locations +\ Strings in Forth are simply named memory locations create astring 256 allot \ create a "string" diff --git a/Task/String-comparison/ARM-Assembly/string-comparison.arm b/Task/String-comparison/ARM-Assembly/string-comparison.arm new file mode 100644 index 0000000000..3bd38ba629 --- /dev/null +++ b/Task/String-comparison/ARM-Assembly/string-comparison.arm @@ -0,0 +1,179 @@ +/* ARM assembly Raspberry PI */ +/* program comparString.s */ + +/* Constantes */ +.equ STDOUT, 1 @ Linux output console +.equ EXIT, 1 @ Linux syscall +.equ WRITE, 4 @ Linux syscall +/* Initialized data */ +.data +szMessStringEqu: .asciz "The strings are equals.\n" +szMessStringNotEqu: .asciz "The strings are not equals.\n" +szCarriageReturn: .asciz "\n" + +szString1: .asciz "ABCDE" +szString2: .asciz "ABCDE" +szString3: .asciz "ABCFG" +szString4: .asciz "ABC" +szString5: .asciz "abcde" + +/* UnInitialized data */ +.bss + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* saves 2 registers */ + + ldr r0,iAdrszString1 + ldr r1,iAdrszString2 + bl Comparaison + + ldr r0,iAdrszString1 + ldr r1,iAdrszString3 + bl Comparaison + + ldr r0,iAdrszString1 + ldr r1,iAdrszString4 + bl Comparaison + + @ case sensitive comparisons ABCDE et abcde + ldr r0,iAdrszString1 + ldr r1,iAdrszString5 + bl Comparaison + + @ case insensitive comparisons ABCDE et abcde + ldr r0,iAdrszString1 + ldr r1,iAdrszString5 + bl comparStringsInsensitive + cmp r0,#0 + bne 1f + ldr r0,iAdrszMessStringEqu + bl affichageMess + b 2f +1: + ldr r0,iAdrszMessStringNotEqu + bl affichageMess + +2: + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrszString1: .int szString1 +iAdrszString2: .int szString2 +iAdrszString3: .int szString3 +iAdrszString4: .int szString4 +iAdrszString5: .int szString5 +iAdrszMessStringEqu: .int szMessStringEqu +iAdrszMessStringNotEqu: .int szMessStringNotEqu +iAdrszCarriageReturn: .int szCarriageReturn +/*********************************************/ +/* comparaison */ +/*********************************************/ +/* r0 contains address String 1 */ +/* r1 contains address String 2 */ +Comparaison: + push {fp,lr} /* save registres */ + bl comparStrings + cmp r0,#0 + bne 1f + ldr r0,iAdrszMessStringEqu + bl affichageMess + b 2f +1: + ldr r0,iAdrszMessStringNotEqu + bl affichageMess + +2: + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registers */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ +/************************************/ +/* Strings case sensitive comparisons */ +/************************************/ +/* r0 et r1 contains the address of strings */ +/* return 0 in r0 if equals */ +/* return -1 if string r0 < string r1 */ +/* return 1 if string r0 > string r1 */ +comparStrings: + push {r1-r4} /* save des registres */ + mov r2,#0 /* counter */ +1: + ldrb r3,[r0,r2] /* byte string 1 */ + ldrb r4,[r1,r2] /* byte string 2 */ + cmp r3,r4 + movlt r0,#-1 /* small */ + movgt r0,#1 /* greather */ + bne 100f /* not equals */ + cmp r3,#0 /* 0 end string */ + moveq r0,#0 /* equals */ + beq 100f /* end string */ + add r2,r2,#1 /* else add 1 in counter */ + b 1b /* and loop */ +100: + pop {r1-r4} + bx lr + +/************************************/ +/* Strings case insensitive comparisons */ +/************************************/ +/* r0 et r1 contains the address of strings */ +/* return 0 in r0 if equals */ +/* return -1 if string r0 < string r1 */ +/* return 1 if string r0 > string r1 */ +comparStringsInsensitive: + push {r1-r4} /* save des registres */ + mov r2,#0 /* counter */ + +1: + ldrb r3,[r0,r2] /* byte string 1 */ + ldrb r4,[r1,r2] /* byte string 2 */ + @ majuscules --> minuscules byte 1 + cmp r3,#65 + blt 2f + cmp r3,#90 + bgt 2f + add r3,#32 +2: @ majuscules --> minuscules byte 2 + cmp r4,#65 + blt 3f + cmp r4,#90 + bgt 3f + add r4,#32 +3: + cmp r3,r4 + movlt r0,#-1 /* small */ + movgt r0,#1 /* greather */ + bne 100f /* not equals */ + cmp r3,#0 /* 0 end string */ + moveq r0,#0 /* equal */ + beq 100f /* end strings */ + add r2,r2,#1 /* else add 1 in counter */ + b 1b /* and loop */ +100: + pop {r1-r4} + bx lr /* end procedure */ diff --git a/Task/String-comparison/Astro/string-comparison.astro b/Task/String-comparison/Astro/string-comparison.astro index 783898a639..93edaa3447 100644 --- a/Task/String-comparison/Astro/string-comparison.astro +++ b/Task/String-comparison/Astro/string-comparison.astro @@ -1,5 +1,5 @@ fun compare(a, b): - print("\n$a is of type $(typeof(a)) and $b is of type $(typeof(b))") + print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}") if a < b: print("$a is strictly less than $b") if a <= b: print("$a is less than or equal to $b") if a > b: print("$a is strictly greater than $b") diff --git a/Task/String-concatenation/K/string-concatenation.k b/Task/String-concatenation/K/string-concatenation.k new file mode 100644 index 0000000000..e343a179d6 --- /dev/null +++ b/Task/String-concatenation/K/string-concatenation.k @@ -0,0 +1,3 @@ +s1: "Some " +s1, "text " +s2: s1 , "more text!" diff --git a/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp b/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp index 2a2103967d..0b7471e9ac 100644 --- a/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp +++ b/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp @@ -1,11 +1,44 @@ -#include -#include +// Variable argument template -int main( ) { - std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , - replacement ( "little" ) ; - std::string newString = original.replace( original.find( "X" ) , - toBeReplaced.length( ) , replacement ) ; - std::cout << "String after replacement: " << newString << " \n" ; - return 0 ; +#include +#include + +using std::string; +using std::vector; + +template +string interpolate( const S& orig , const Args&... args) +{ + string out(orig); + + // populate vector from argument list + auto va = {args...}; + vector v{va}; + + size_t i = 1; + + for( string s: v) + { + string is = std::to_string(i); + string t = "{" + is + "}"; // "{1}", "{2}", ... + try + { + auto pos = out.find(t); + + if ( pos != out.npos) // found token + { + out.erase(pos, t.length()); //erase token + out.insert( pos, s); // insert arg + } + + i++; // next + } + catch( std::exception& e) + { + std::cerr << e.what() << std::endl; + } + + } // for + + return out; } diff --git a/Task/String-length/K/string-length.k b/Task/String-length/K/string-length.k new file mode 100644 index 0000000000..365f810f12 --- /dev/null +++ b/Task/String-length/K/string-length.k @@ -0,0 +1,4 @@ + #"Hello, world!" +13 + #"HΓ«llo, world!" +13 diff --git a/Task/String-prepend/K/string-prepend.k b/Task/String-prepend/K/string-prepend.k new file mode 100644 index 0000000000..64ec41edf4 --- /dev/null +++ b/Task/String-prepend/K/string-prepend.k @@ -0,0 +1,4 @@ + s: "world!" +"world!" + "Hello " , s +"Hello world!" diff --git a/Task/Strip-block-comments/PHP/strip-block-comments.php b/Task/Strip-block-comments/PHP/strip-block-comments.php new file mode 100644 index 0000000000..84ad2ca172 --- /dev/null +++ b/Task/Strip-block-comments/PHP/strip-block-comments.php @@ -0,0 +1,23 @@ +function strip_block_comments( $test_string ) { + $pattern = "/^.*?(\K\/\*.*?\*\/)|^.*?(\K\/\*.*?^.*\*\/)$/mXus"; + return preg_replace( $pattern, '', $test_string ); +} + +echo "Result: '" . strip_block_comments( " +/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +" ) . "'"; diff --git a/Task/Strip-comments-from-a-string/Factor/strip-comments-from-a-string.factor b/Task/Strip-comments-from-a-string/Factor/strip-comments-from-a-string.factor new file mode 100644 index 0000000000..8dbadf00e3 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Factor/strip-comments-from-a-string.factor @@ -0,0 +1,3 @@ +USE: sequences.extras +: strip-comments ( str -- str' ) + [ "#;" member? not ] take-while "" like ; diff --git a/Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-1.fth b/Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-1.fth new file mode 100644 index 0000000000..d556d2c9ed --- /dev/null +++ b/Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-1.fth @@ -0,0 +1,24 @@ +\ Rosetta Code Strip Comment + +: LASTCHAR ( addr len -- addr len c) 2DUP + 1- C@ ; + +: COMMENT? ( char -- ? ) S" #;" ROT SCAN NIP ; \ is char '#' or ';' + +: -COMMENT ( addr len -- addr len') \ removes # or ; comments + BEGIN + LASTCHAR COMMENT? 0= + WHILE \ while not a comment char... + 1- \ reduce length by 1 + REPEAT + 1- ; \ remove 1 more (the comment char) + +\ -TRAILING is resident in desktop Forth systems like Swift Forth +\ shown here for demonstration +: -TRAILING ( adr len -- adr len') \ remove trailing spaces + BEGIN + LASTCHAR BL = + WHILE \ while lastchar = blank char + 1- \ reduce length by 1 + REPEAT ; + +: COMMENT-STRIP ( addr len -- addr 'len) -COMMENT -TRAILING ; diff --git a/Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-2.fth b/Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-2.fth new file mode 100644 index 0000000000..5dd8573e50 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string-2.fth @@ -0,0 +1,2 @@ +S" apples, pears # and bananas" COMMENT-STRIP TYPE apples, pears ok +S" apples, pears ; and bananas" COMMENT-STRIP TYPE apples, pears ok diff --git a/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-3.js b/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-3.js new file mode 100644 index 0000000000..97eaac5f1d --- /dev/null +++ b/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-3.js @@ -0,0 +1,62 @@ +(() => { + 'use strict'; + + const main = () => { + + const src = `apples, pears # and bananas +apples, pears ; and bananas`; + + return unlines( + map(preComment(chars(';#')), + lines(src) + ) + ); + }; + + // preComment :: [Char] -> String -> String + const preComment = cs => s => + strip( + takeWhile( + curry(flip(notElem))(cs), + s + ) + ); + + // GENERIC FUNCTIONS ------------------------------ + + // chars :: String -> [Char] + const chars = s => s.split(''); + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => (a, b) => f.apply(null, [b, a]); + + // lines :: String -> [String] + const lines = s => s.split(/[\r\n]/); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // notElem :: Eq a => a -> [a] -> Bool + const notElem = (x, xs) => -1 === xs.indexOf(x); + + // strip :: String -> String + const strip = s => s.trim(); + + // takeWhile :: (a -> Bool) -> [a] -> [a] + // takeWhile :: (Char -> Bool) -> String -> String + const takeWhile = (p, xs) => { + let i = 0; + const lng = xs.length; + while ((i < lng) && p(xs[i]))(i = i + 1); + return xs.slice(0, i); + }; + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // MAIN --- + return main(); +})(); diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Phix/strip-control-codes-and-extended-characters-from-a-string.phix b/Task/Strip-control-codes-and-extended-characters-from-a-string/Phix/strip-control-codes-and-extended-characters-from-a-string.phix new file mode 100644 index 0000000000..1ff7b16e3a --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Phix/strip-control-codes-and-extended-characters-from-a-string.phix @@ -0,0 +1,20 @@ +function filter(string s, integer fromch=' ', toch=#7E, abovech=#7F) +string res = "" + for i=1 to length(s) do + integer ch = s[i] + if ch>=fromch and (ch<=toch or ch>abovech) then + res &= ch + end if + end for + return res +end function + +procedure put_line(string text, s) + printf(1,"%s \"%s\", Length:%d\n",{text,s,length(s)}) +end procedure + +string full = "\u0000 abc\u00E9def\u007F" + +put_line("The full string:", full) +put_line("No Control Chars:", filter(full)) -- default values for fromch, toch, and abovech +put_line("\" and no Extended:", filter(full, abovech:=#FF)) -- defaults for fromch and toch diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.crystal b/Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.crystal new file mode 100644 index 0000000000..d53ed6ef5b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.crystal @@ -0,0 +1,10 @@ +def strip_whitepace(s) + puts s.lstrip() + puts s.rstrip() + puts s.strip() +end + +strip_whitepace("\t hello \t") +# => hello +# => hello +# => hello diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-1.fth b/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-1.fth index 0c76b5900c..e4e502dac9 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-1.fth +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-1.fth @@ -1,8 +1,7 @@ -: -leading ( addr len -- addr' len' ) - begin over c@ bl = while 1 /string repeat ; -\ -trailing is built in - -s" test " -2dup -leading cr type -2dup -trailing cr type - -leading -trailing cr type +: -leading ( addr len -- addr' len' ) \ called "minus-leading" + begin + over c@ bl = \ fetch character at addr, test if blank (space) + while + \ cut 1 leading character by incrementing address & decrementing length + 1 /string \ "cut-string" + repeat ; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-2.fth b/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-2.fth index 435f173a54..127ea65258 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-2.fth +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail-2.fth @@ -1 +1 @@ - : trim ( addr len -- addr' len') -leading -trailing ; + : strip ( addr len -- addr' len') -leading -trailing ; diff --git a/Task/Substring-Top-and-tail/Factor/substring-top-and-tail.factor b/Task/Substring-Top-and-tail/Factor/substring-top-and-tail.factor index a91b95b34c..662a279ee0 100644 --- a/Task/Substring-Top-and-tail/Factor/substring-top-and-tail.factor +++ b/Task/Substring-Top-and-tail/Factor/substring-top-and-tail.factor @@ -1 +1,3 @@ -"Rosetta code" [ rest . ] [ but-last . ] [ rest but-last . ] tri +USING: io kernel sequences ; +"Rosetta code" [ rest ] [ but-last ] [ rest but-last ] tri +[ print ] tri@ diff --git a/Task/Substring-Top-and-tail/K/substring-top-and-tail-1.k b/Task/Substring-Top-and-tail/K/substring-top-and-tail-1.k new file mode 100644 index 0000000000..4e8cf1df4c --- /dev/null +++ b/Task/Substring-Top-and-tail/K/substring-top-and-tail-1.k @@ -0,0 +1,8 @@ + s: "1234567890" +"1234567890" + s _di 0 /Delete 1st character +"234567890" + s _di -1+#s /Delete last character +"123456789" + (s _di -1+#s) _di 0 /String with both 1st and last character removed +"23456789" diff --git a/Task/Substring-Top-and-tail/K/substring-top-and-tail-2.k b/Task/Substring-Top-and-tail/K/substring-top-and-tail-2.k new file mode 100644 index 0000000000..17edd55c4d --- /dev/null +++ b/Task/Substring-Top-and-tail/K/substring-top-and-tail-2.k @@ -0,0 +1,8 @@ + s: "1234567890" +"1234567890" + 1 _ s /Delete 1st character +"234567890" + -1 _ s /Delete last character +"123456789" + 1 - -1 _ s /Delete 1st and last character +"23456789" diff --git a/Task/Substring/REBOL/substring.rebol b/Task/Substring/REBOL/substring.rebol index 0c89332620..5b9235d3ca 100644 --- a/Task/Substring/REBOL/substring.rebol +++ b/Task/Substring/REBOL/substring.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Retrieve Substring" - Author: oofoe - Date: 2009-12-06 URL: http://rosettacode.org/wiki/Substring#REBOL ] diff --git a/Task/Sudoku/Befunge/sudoku.bf b/Task/Sudoku/Befunge/sudoku.bf new file mode 100644 index 0000000000..8fd1c81385 --- /dev/null +++ b/Task/Sudoku/Befunge/sudoku.bf @@ -0,0 +1,8 @@ +99*>1-:0>:#$"0"\# #~`#$_"0"-\::9%:9+00p3/\9/:99++10p3vv%2g\g01< +2%v|:p+9/9\%9:\p\g02\1p\g01\1:p\g00\1:+8:\p02+*93+*3/<>\20g\g#: +v<+>:0\`>v >\::9%:9+00p3/\9/:99++10p3/3*+39*+20p\:8+::00g\g2%\^ +v^+^pppp$_:|v<::<_>1-::9%\9/9+g.::9%!\3%+>>#v_>" "v..v,<<<+55<< +03!$v9:_>1v$>9%\v^|:<_v#<%<9<:<<_v#+%*93\!::<,,"|"<\/>:#^_>>>v^ +p|<$0.0^!g+:#9/9<^@ ^,>#+5<5_>#!<>#$0"------+-------+-----":#<^ +<>v$v1:::0<>"P"`!^>0g#0v#p+9/9\%9:p04:\pg03g021pg03g011pg03g001 +::>^_:#<0#!:p#-\#1:#g0<>30g010g30g020g30g040g:9%\:9/9+\01-\1+0: diff --git a/Task/Sudoku/SystemVerilog/sudoku.v b/Task/Sudoku/SystemVerilog/sudoku.v index b66ab77cf4..a5d772d6c4 100644 --- a/Task/Sudoku/SystemVerilog/sudoku.v +++ b/Task/Sudoku/SystemVerilog/sudoku.v @@ -1,7 +1,3 @@ -/// @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 /// diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.crystal new file mode 100644 index 0000000000..0218958830 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.crystal @@ -0,0 +1,3 @@ +def sum_product(a) + { a.sum(), a.product() } +end diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.crystal new file mode 100644 index 0000000000..2528be63ca --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.crystal @@ -0,0 +1,9 @@ +def sum_product_imperative(a) + sum, product = 0, 1 + a.each do |e| + sum += e + product *= e + end + + {sum, product} +end diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.crystal new file mode 100644 index 0000000000..729ddf5f79 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.crystal @@ -0,0 +1,5 @@ +require "benchmark" +Benchmark.ips do |x| + x.report("declarative") { sum_product [1, 2, 3, 4, 5] } + x.report("imperative") { sum_product_imperative [1, 2, 3, 4, 5] } +end diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-4.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-4.crystal new file mode 100644 index 0000000000..c9293d82be --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-4.crystal @@ -0,0 +1,2 @@ +declarative 8.1M (123.45ns) (Β± 2.99%) 65 B/op 1.30Γ— slower + imperative 10.57M ( 94.61ns) (Β± 2.96%) 65 B/op fastest diff --git a/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol b/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol index 39d2a3fa2a..2a5fdea1d3 100644 --- a/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol +++ b/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Sum and Product" - Date: 2010-01-04 - Author: oofoe URL: http://rosettacode.org/wiki/Sum_and_product_of_array ] diff --git a/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5.crystal b/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5.crystal new file mode 100644 index 0000000000..6803f4bcea --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5.crystal @@ -0,0 +1,8 @@ +def sum_3_5_muliples(n) + (0...n) + .select { |i| i % 3 == 0 || i % 5 == 0 } + .reduce { |acc, i| acc + i } +end + +puts sum_3_5_muliples(1000) +# => 233168 diff --git a/Task/Sum-of-squares/Crystal/sum-of-squares.crystal b/Task/Sum-of-squares/Crystal/sum-of-squares.crystal new file mode 100644 index 0000000000..b9f568d852 --- /dev/null +++ b/Task/Sum-of-squares/Crystal/sum-of-squares.crystal @@ -0,0 +1,6 @@ +def sum_squares(a) + a.map{|e| e*e}.sum() +end + +puts sum_squares([1, 2, 3]) +# => 14 diff --git a/Task/Table-creation-Postal-addresses/Phix/table-creation-postal-addresses.phix b/Task/Table-creation-Postal-addresses/Phix/table-creation-postal-addresses.phix new file mode 100644 index 0000000000..d6de6ce735 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Phix/table-creation-postal-addresses.phix @@ -0,0 +1,17 @@ +include pSQLite.e +constant sqlcode = """ +CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL)""" + +sqlite3 db = sqlite3_open("address.sqlite") +integer res = sqlite3_exec(db,sqlcode) +if res=SQLITE_OK then + sqlite3_close(db) +else + -- can show eg "sqlite3_exec error: 1 [table address already exists]" + printf(1,"sqlite3_exec error: %d [%s]\n",{res,sqlite_last_exec_err}) +end if diff --git a/Task/Table-creation-Postal-addresses/Ring/table-creation-postal-addresses.ring b/Task/Table-creation-Postal-addresses/Ring/table-creation-postal-addresses.ring index 649731bfbf..b0145adfe7 100644 --- a/Task/Table-creation-Postal-addresses/Ring/table-creation-postal-addresses.ring +++ b/Task/Table-creation-Postal-addresses/Ring/table-creation-postal-addresses.ring @@ -1,7 +1,4 @@ # Project : Table creation/Postal addresses -# Date : 2018/04/19 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" oSQLite = sqlite_init() diff --git a/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol b/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol index c5c49111cc..3de33d4b65 100644 --- a/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol +++ b/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Notes" - Author: oofoe - Date: 2010-10-04 URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line ] diff --git a/Task/Temperature-conversion/PHP/temperature-conversion.php b/Task/Temperature-conversion/PHP/temperature-conversion.php index 35253ac339..2558b8a413 100644 --- a/Task/Temperature-conversion/PHP/temperature-conversion.php +++ b/Task/Temperature-conversion/PHP/temperature-conversion.php @@ -1,8 +1,6 @@ -error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING )); - while (true) { echo "\nEnter a value in kelvin (q to quit): "; - if (($kelvin = trim(fgets(STDIN))) !== false) { + if ($kelvin = trim(fgets(STDIN))) { if ($kelvin == 'q') { echo 'quitting'; break; diff --git a/Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-1.fth b/Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-1.fth new file mode 100644 index 0000000000..4564783020 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-1.fth @@ -0,0 +1,20 @@ +( ANSI terminal control lexicon Colored Text) +DECIMAL +( support routines) + 27 CONSTANT ESC +: <##> ( n -- ) ( sends n, radix 10, no spaces) + BASE @ >R 0 <# #S #> TYPE R> BASE ! ; + +: ESC[ ( -- ) ESC EMIT ." [" ; +( Attributes ) +1 CONSTANT BOLD 2 CONSTANT DIM 3 CONSTANT ITALIC +5 CONSTANT BLINK 7 CONSTANT REV 8 CONSTANT BLANK + +( Colors ) +0 CONSTANT BLACK 1 CONSTANT RED 2 CONSTANT GREEN +3 CONSTANT YELLOW 4 CONSTANT BLUE 5 CONSTANT MAGENTA +6 CONSTANT CYAN 7 CONSTANT WHITE + +: ATTR ( attribute ) ESC[ <##> ." m" ; ( use: BOLD ATTR ) +: TEXT ( color ) 30 + ATTR ; ( use: YELLOW TEXT ) +: BACKGROUND ( color ) 40 + ATTR ; ( use: BLUE BACKGROUND ) diff --git a/Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-2.fth b/Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-2.fth new file mode 100644 index 0000000000..823363e653 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Forth/terminal-control-coloured-text-2.fth @@ -0,0 +1,3 @@ +WHITE TEXT BLUE BACKGROUND ok +BLUE TEXT BOLD ATTR ok +CYAN TEXT ok diff --git a/Task/Terminal-control-Coloured-text/Ring/terminal-control-coloured-text.ring b/Task/Terminal-control-Coloured-text/Ring/terminal-control-coloured-text.ring index e0a9befcc9..e773b042eb 100644 --- a/Task/Terminal-control-Coloured-text/Ring/terminal-control-coloured-text.ring +++ b/Task/Terminal-control-Coloured-text/Ring/terminal-control-coloured-text.ring @@ -1,7 +1,4 @@ # Project : Terminal control/Coloured text -# Date : 2018/04/19 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "consolecolors.ring" diff --git a/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c b/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c index 088820950b..fec47ecffc 100644 --- a/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c +++ b/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c @@ -1,4 +1,3 @@ -/*Abhishek Ghosh, 7th November 2013, Rotterdam*/ #include #include diff --git a/Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-1.fth b/Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-1.fth new file mode 100644 index 0000000000..574fcee13f --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-1.fth @@ -0,0 +1,24 @@ +( ANSI terminal control lexicon ) +DECIMAL + +( support routines) + 27 CONSTANT ESC +: <##> ( n -- ) ( sends n, radix 10, no spaces) + BASE @ >R 0 <# #S #> TYPE R> BASE ! ; + +: ESC[ ( -- ) ESC EMIT ." [" ; + +( ANSI terminal commands as Forth words) +: ( row --) ESC[ <##> ." A" ; +: ( row --) ESC[ <##> ." B" ; +: ( col --) ESC[ <##> ." C" ; +: ( col --) ESC[ <##> ." D" ; +: ( -- ) ESC[ <##> ." F" ; +: ( n --) ESC[ <##> ." G" ; +: ( -- ) ESC[ ." K" ; +: ( -- ) ESC[ ." 2J" ; +: ( row col -- ) SWAP ESC[ <##> ." ;" <##> ." H" ; + +( Define ANSI Forth names for these functions using our markup words) +: AT-XY ( col row -- ) SWAP ; +: PAGE ( -- ) 1 1 ; diff --git a/Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-2.fth b/Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-2.fth new file mode 100644 index 0000000000..ad20013de5 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Forth/terminal-control-cursor-movement-2.fth @@ -0,0 +1,8 @@ +( move the cursor one position to the left) 1 +( move the cursor one position to the right) 1 +( move the cursor up one line ) 1 +( move the cursor down one line) 1 +( move the cursor to the beginning of the line) 1 +( move the cursor to the end of the line ) 80 +( move the cursor to the top left corner of the screen) 1 1 +( move the cursor to the bottom right corner of the screen) 80 24 diff --git a/Task/Terminal-control-Cursor-positioning/Ring/terminal-control-cursor-positioning.ring b/Task/Terminal-control-Cursor-positioning/Ring/terminal-control-cursor-positioning.ring index 133a49f8d9..450ef1a908 100644 --- a/Task/Terminal-control-Cursor-positioning/Ring/terminal-control-cursor-positioning.ring +++ b/Task/Terminal-control-Cursor-positioning/Ring/terminal-control-cursor-positioning.ring @@ -1,7 +1,4 @@ # Project : Terminal control/Cursor positioning -# Date : 2018/04/19 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : for n = 1 to 5 see nl diff --git a/Task/Terminal-control-Display-an-extended-character/Ring/terminal-control-display-an-extended-character.ring b/Task/Terminal-control-Display-an-extended-character/Ring/terminal-control-display-an-extended-character.ring index 5100099f81..aa23b54dbf 100644 --- a/Task/Terminal-control-Display-an-extended-character/Ring/terminal-control-display-an-extended-character.ring +++ b/Task/Terminal-control-Display-an-extended-character/Ring/terminal-control-display-an-extended-character.ring @@ -1,6 +1,3 @@ # Project : Terminal control/Display an extended character -# Date : 2017/12/04 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "Β£" diff --git a/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c b/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c index 71236ef49a..570e0990e3 100644 --- a/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c +++ b/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c @@ -1,7 +1,4 @@ -/*30th August,2012 -Abhishek Ghosh - -Please note that curs_set is terminal dependent.*/ +/* Please note that curs_set is terminal dependent. */ #include #include diff --git a/Task/Terminal-control-Hiding-the-cursor/Ring/terminal-control-hiding-the-cursor.ring b/Task/Terminal-control-Hiding-the-cursor/Ring/terminal-control-hiding-the-cursor.ring new file mode 100644 index 0000000000..e6c4e734d8 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Ring/terminal-control-hiding-the-cursor.ring @@ -0,0 +1,9 @@ +# Project : Terminal control/Hiding the cursor + +load "stdlib.ring" +# Linux +? "Hide Cursor using tput utility" +system("tput civis") # Invisible +sleep(10) +? "Show Cursor using tput utility" +system("tput cnorm") # Normal diff --git a/Task/Terminal-control-Preserve-screen/Go/terminal-control-preserve-screen.go b/Task/Terminal-control-Preserve-screen/Go/terminal-control-preserve-screen.go new file mode 100644 index 0000000000..6a0d39bfce --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Go/terminal-control-preserve-screen.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + fmt.Print("\033[?1049h\033[H") + fmt.Println("Alternate screen buffer\n") + s := "s" + for i := 5; i > 0; i-- { + if i == 1 { + s = "" + } + fmt.Printf("\rgoing back in %d second%s...", i, s) + time.Sleep(time.Second) + } + fmt.Print("\033[?1049l") +} diff --git a/Task/Terminal-control-Preserve-screen/Java/terminal-control-preserve-screen.java b/Task/Terminal-control-Preserve-screen/Java/terminal-control-preserve-screen.java new file mode 100644 index 0000000000..59ab5eae7b --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Java/terminal-control-preserve-screen.java @@ -0,0 +1,13 @@ +public class PreserveScreen +{ + public static void main(String[] args) throws InterruptedException { + System.out.print("\033[?1049h\033[H"); + System.out.println("Alternate screen buffer\n"); + for (int i = 5; i > 0; i--) { + String s = (i > 1) ? "s" : ""; + System.out.printf("\rgoing back in %d second%s...", i, s); + Thread.sleep(1000); + } + System.out.print("\033[?1049l"); + } +} diff --git a/Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-1.phix b/Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-1.phix new file mode 100644 index 0000000000..5dc1da3fb2 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-1.phix @@ -0,0 +1,6 @@ +sequence s = save_text_image({1,1}, {25,80}) +clear_screen() +puts(1,"\n\n *** hello ***\n") +sleep(5) +display_text_image({1,1}, s) +sleep(3) diff --git a/Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-2.phix b/Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-2.phix new file mode 100644 index 0000000000..bb6e3aae40 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Phix/terminal-control-preserve-screen-2.phix @@ -0,0 +1,8 @@ +puts(1,"\e[?1049h\e[H") +puts(1,"Alternate buffer!\n") + +for i=5 to 0 by -1 do + printf(1,"Going back in:%d\r", i) + sleep(1) +end for +puts(1,"\e[?1049l") diff --git a/Task/Terminal-control-Preserve-screen/Ring/terminal-control-preserve-screen.ring b/Task/Terminal-control-Preserve-screen/Ring/terminal-control-preserve-screen.ring new file mode 100644 index 0000000000..3d7c78b266 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Ring/terminal-control-preserve-screen.ring @@ -0,0 +1,10 @@ +# Project : Terminal control/Preserve screen + +load "stdlib.ring" +see char(33) + "[?1049h\" + char(33) + "[H" + nl +see "Alternate screen buffer" + nl +for i = 5 to 1 step -1 + see "going back in " + i + "..." + nl + sleep(1) +next +see char(33) + "[?1049l" + nl diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Bc/terminal-control-ringing-the-terminal-bell.bc b/Task/Terminal-control-Ringing-the-terminal-bell/Bc/terminal-control-ringing-the-terminal-bell.bc new file mode 100644 index 0000000000..3fde07b32e --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Bc/terminal-control-ringing-the-terminal-bell.bc @@ -0,0 +1 @@ +print "\a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/C++/terminal-control-ringing-the-terminal-bell.cpp b/Task/Terminal-control-Ringing-the-terminal-bell/C++/terminal-control-ringing-the-terminal-bell.cpp new file mode 100644 index 0000000000..0353fffef2 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/C++/terminal-control-ringing-the-terminal-bell.cpp @@ -0,0 +1,6 @@ +#include + +int main() { + std::cout << "\a"; + return 0; +} diff --git a/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c b/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c index 9ad4084237..02142e16f1 100644 --- a/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c +++ b/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c @@ -1,6 +1,3 @@ -/*30th August, 2012 -Abhishek Ghosh*/ - #include #include diff --git a/Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-1.phix b/Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-1.phix new file mode 100644 index 0000000000..d730b12c72 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-1.phix @@ -0,0 +1,57 @@ +-- +-- builtins/unicode_console.e +-- +-- Implements unicode_console() -- initialises one, and returns true if supported +-- +-- While there is some appeal to performing (the equivalent inline assembly of) this automatically in the +-- back-end/run-time, it would probably break too much legacy code that assumes Windows-1252 or ISO-8859. +-- +include builtins\cffi.e +--set_unicode(true) +constant +--windows: +tGSH = """ +HANDLE WINAPI GetStdHandle( + _In_ DWORD nStdHandle +); +""", +tSCOCP = """ +BOOL WINAPI SetConsoleOutputCP( + _In_ UINT wCodePageID +); +""", +STD_OUTPUT_HANDLE = -11, +CP_UTF8 = 65001, +--linux: +envset = {"LANG","LC_ALL","LC_CTYPE"} + +atom k32 = NULL, + xGetStdHandle, + hConsole, + xSetConsoleOutputCP + +global function unicode_console() +-- initialises the windows console for unicode, +-- and returns true/false if unicode is supported. +bool res = false + if platform()=WINDOWS then + if k32=NULL then + puts(1,"") -- force console to exist + k32 = open_dll("kernel32.dll") + xGetStdHandle = define_cffi_func(k32,tGSH) + hConsole = c_func(xGetStdHandle,{STD_OUTPUT_HANDLE}) + xSetConsoleOutputCP = define_cffi_func(k32,tSCOCP) + end if + -- the following is equivalent to running "chcp 65001": + res = c_func(xSetConsoleOutputCP,{CP_UTF8}) + -- zero(false) means failure. + else -- LINUX + for i=1 to length(envset) do + if match("UTF",upper(getenv(envset[i])))!=0 then + res = true + exit + end if + end for + end if + return res +end function diff --git a/Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-2.phix b/Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-2.phix new file mode 100644 index 0000000000..f0332cfce3 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Phix/terminal-control-unicode-output-2.phix @@ -0,0 +1,10 @@ +include builtins\unicode_console.e + +-- pi, root, lambda, sigma, delta +constant prlsd = "\u03C0\u221A\u03BB\u03A3\u25B3" + +if unicode_console() then + puts(1,prlsd&"\n") +else + puts(1,"unicode is not supported\n") +end if diff --git a/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 b/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 index b2789b2f29..4f5b742d8d 100644 --- a/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 +++ b/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 @@ -15,12 +15,15 @@ for $*IN.lines -> $line { %licenses.push($date_time); } } - else { + elsif $license eq 'IN' { if %licenses == %licenses { %licenses[*-1] ~= " through " ~ $date_time; } %licenses--; } + else { + # Not a licence OUT or IN event, do nothing + } }; my $plural = %licenses.elems == 1 ?? '' !! 's'; diff --git a/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-1.scala b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-1.scala new file mode 100644 index 0000000000..0c7c051b93 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-1.scala @@ -0,0 +1,29 @@ +import java.io.{BufferedReader, InputStreamReader} +import java.net.URL + +object License0 extends App { + val url = new URL("https://raw.githubusercontent.com/def-/nim-unsorted/master/mlijobs.txt") + val in = new BufferedReader(new InputStreamReader(url.openStream())) + + val dates = new collection.mutable.ListBuffer[String] + var (count: Int, max: Int) = (0, Int.MinValue) + var line: String = _ + + while ( {line = in.readLine; line} != null) { + if (line.startsWith("License OUT ")) count += 1 + if (line.startsWith("License IN ")) count -= 1 // Redundant test when "OUT" + if (count > max) { // Fruitless execution when "License IN " + max = count + val date = line.split(" ")(3) + dates.clear() + dates += date + } else if (count == max) { + val date = line.split(" ")(3) + dates += date + } + } + + println("Max licenses out: " + max) + println("At time(s): " + dates.mkString(", ")) + +} diff --git a/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-2.scala b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-2.scala new file mode 100644 index 0000000000..27049943c3 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-2.scala @@ -0,0 +1,25 @@ +import scala.collection.mutable.ListBuffer + +object License1 extends App { + val src = io.Source.fromURL("https://raw.githubusercontent.com/def-/nim-unsorted/master/mlijobs.txt") + + val dates = new ListBuffer[String] + var (max, count) = (Int.MinValue, 0) + + src.getLines.foreach { line => + def date = line.split(" ")(3) + + if (line.startsWith("License OUT ")) { + count += 1 + if (count > max) { + max = count + dates.clear + } + if (count == max) dates += date + } else if (line.startsWith("License IN ")) count -= 1 + } + + println("Max licenses out: " + max) + println("At time(s): " + dates.mkString(", ")) + +} diff --git a/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-3.scala b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-3.scala new file mode 100644 index 0000000000..eb9f74559b --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-3.scala @@ -0,0 +1,47 @@ +import scala.annotation.tailrec + +object License2 extends App { + type resultTuple = (Int /*max*/, Int /*count*/, List[String] /*dates*/ ) + + val src = io.Source.fromURL( + "https://raw.githubusercontent.com/def-/nim-unsorted/master/mlijobs.txt") + val iter = src.getLines() + val (max, count, dates) = loop(Int.MinValue, 0, Nil) + + def lineToResult(tuple: (resultTuple, String)): resultTuple = { + val ((max, count, dates), line) = tuple + + def date = line.split(" ")(3) + + if (line.startsWith("License OUT ")) { + if (count + 1 > max) (count + 1, count + 1, List(date)) + else if (count + 1 == max) (max, max, dates :+ date) + else (max, count + 1, dates) + } else if (line.startsWith("License IN ")) tuple._1.copy(_2 = count - 1) + else tuple._1 + } + + @tailrec + private def loop(tuple: resultTuple): resultTuple = { + def lineToResult(tuple: (resultTuple, String)): resultTuple = { + val ((max, count, dates), line) = tuple + + def date = line.split(" ")(3) + + if (line.startsWith("License OUT ")) { + if (count + 1 > max) (count + 1, count + 1, List(date)) + else if (count + 1 == max) (max, max, dates :+ date) + else (max, count + 1, dates) + } else if (line.startsWith("License IN ")) tuple._1.copy(_2 = count - 1) + else tuple._1 + } + + if (iter.hasNext) + loop(lineToResult(tuple, iter.next())) + else tuple + } + + println("Max licenses out: " + max) + println("At time(s): " + dates.mkString(", ")) + +} diff --git a/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-4.scala b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-4.scala new file mode 100644 index 0000000000..eada53aa09 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Scala/text-processing-max-licenses-in-use-4.scala @@ -0,0 +1,26 @@ +object License3 extends App { + type resultTuple = (Int /*max*/, Int /*count*/, List[String] /*dates*/ ) + + val src = io.Source.fromURL("https://raw.githubusercontent.com/def-/nim-unsorted/master/mlijobs.txt") + + val (max, count, dates): resultTuple = + src.getLines().foldLeft(Int.MinValue, 0, Nil: List[String]) { + case ((max: Int, count: Int, dates: List[String]), line: String) + if line.startsWith("License OUT ") => + def date = line.split(" ")(3) + + if (count + 1 > max) (count + 1, count + 1, List(date)) + else if (count + 1 == max) (max, max, dates :+ date) + else (max, count + 1, dates) + + case (resultPart: resultTuple, line: String) + if line.startsWith("License IN ") => + resultPart.copy(_2 = resultPart._2 - 1) + + case (resultPart, _) => resultPart + } + + println("Max licenses out: " + max) + println("At time(s): " + dates.mkString(", ")) + +} diff --git a/Task/Text-processing-Max-licenses-in-use/Sidef/text-processing-max-licenses-in-use.sidef b/Task/Text-processing-Max-licenses-in-use/Sidef/text-processing-max-licenses-in-use.sidef index 6bcea08d90..8b912c293e 100644 --- a/Task/Text-processing-Max-licenses-in-use/Sidef/text-processing-max-licenses-in-use.sidef +++ b/Task/Text-processing-Max-licenses-in-use/Sidef/text-processing-max-licenses-in-use.sidef @@ -1,17 +1,17 @@ -var out = 0; -var max_out = -1; -var max_times = []; +var out = 0 +var max_out = -1 +var max_times = [] ARGF.each { |line| - out += (line ~~ /OUT/ ? 1 : -1); - out > max_out && ( - max_out = out; - max_times = []; - ); - out == max_out && ( - max_times << line.split(' ')[3]; - ); + out += (line ~~ /OUT/ ? 1 : -1) + if (out > max_out) { + max_out = out + max_times = [] + } + if (out == max_out) { + max_times << line.split(' ')[3] + } } -say "Maximum simultaneous license use is #{max_out} at the following times:"; -max_times.each {|t| " #{t}".say }; +say "Maximum simultaneous license use is #{max_out} at the following times:" +max_times.each {|t| say " #{t}" } diff --git a/Task/Textonyms/Perl/textonyms.pl b/Task/Textonyms/Perl/textonyms.pl index 1247f644c9..54979d1cee 100644 --- a/Task/Textonyms/Perl/textonyms.pl +++ b/Task/Textonyms/Perl/textonyms.pl @@ -1,7 +1,17 @@ -sub find { - my @m = qw/$ $ abc def ghi jkl mno pqrs tvu wxyz/; - (my $r = shift) =~ s{(\d)}{[$m[$1]]}g; - grep /^$r$/i, split ' ', `cat words.txt`; # cats don't run on windows -} +my $src = 'unixdict.txt'; -print join("\n", $_, find($_)), "\n\n" for @ARGV +# filter word-file for valid input, transform to low-case +open $fh, "<", $src; +@words = grep { /^[a-zA-Z]+$/ } <$fh>; +map { tr/A-Z/a-z/ } @words; + +# translate words to dials +map { tr/abcdefghijklmnopqrstuvwxyz/22233344455566677778889999/ } @dials = @words; + +# get unique values (modify @dials) and non-unique ones (are textonyms) +@dials = grep {!$h{$_}++} @dials; +@textonyms = grep { $h{$_} > 1 } @dials; + +print "There are @{[scalar @words]} words in '$src' which can be represented by the digit key mapping. +They require @{[scalar @dials]} digit combinations to represent them. +@{[scalar @textonyms]} digit combinations represent Textonyms."; diff --git a/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c b/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c index 38b73144eb..e96af215d1 100644 --- a/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c +++ b/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 20th March 2014, Rotterdam*/ - #include int main() diff --git a/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring b/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring index 40c056b2bf..b4b2b7c0c8 100644 --- a/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring +++ b/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring @@ -1,7 +1,4 @@ # Project : The Twelve Days of Christmas -# Date : 2017/11/14 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : gifts = "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" days = "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth" diff --git a/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math b/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math index 437d948d7f..f74f3bc91c 100644 --- a/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math +++ b/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math @@ -1 +1 @@ -Row[Riffle[StringSplit["Hello,How,Are,You,Today", ","], "."]] +StringRiffle[StringSplit["Hello,How,Are,You,Today", ","], "."] diff --git a/Task/Top-rank-per-group/Perl/top-rank-per-group.pl b/Task/Top-rank-per-group/Perl/top-rank-per-group.pl index 84b02a891c..302b8860ab 100644 --- a/Task/Top-rank-per-group/Perl/top-rank-per-group.pl +++ b/Task/Top-rank-per-group/Perl/top-rank-per-group.pl @@ -30,10 +30,9 @@ Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190 EOF -@ARGV or die "Please provide a value for N.\n"; -my $N = shift; +my $N = shift || 3; -foreach my $d (sort uniq map {$_->{dept}} @data) { +foreach my $d (uniq sort map {$_->{dept}} @data) { print "$d\n"; my @es = sort {$b->{salary} <=> $a->{salary}} diff --git a/Task/Top-rank-per-group/Ring/top-rank-per-group.ring b/Task/Top-rank-per-group/Ring/top-rank-per-group.ring index de08247055..35ca174433 100644 --- a/Task/Top-rank-per-group/Ring/top-rank-per-group.ring +++ b/Task/Top-rank-per-group/Ring/top-rank-per-group.ring @@ -1,7 +1,4 @@ # Project : Top rank per group -# Date : 2017/12/10 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" salary = "Tyler Bennett,E10297,32000,D101 diff --git a/Task/Topic-variable/Perl/topic-variable-1.pl b/Task/Topic-variable/Perl/topic-variable-1.pl index c377a70838..f2d35a86a8 100644 --- a/Task/Topic-variable/Perl/topic-variable-1.pl +++ b/Task/Topic-variable/Perl/topic-variable-1.pl @@ -1,2 +1 @@ -my $_ = 3; -print for $_**2, "\n", sqrt; +print sqrt . " " for (4, 16, 64) diff --git a/Task/Topic-variable/Perl/topic-variable-2.pl b/Task/Topic-variable/Perl/topic-variable-2.pl index bb1de1ff17..2823d0b3a1 100644 --- a/Task/Topic-variable/Perl/topic-variable-2.pl +++ b/Task/Topic-variable/Perl/topic-variable-2.pl @@ -1,17 +1,8 @@ -for ($_ = 0; $_ <= 9; $_++) { - print "Outer"; - print "$_\n"; - # The inner loop will not nest properly unless - # it is preceded by a my statement - my $_; # This is required to nest the inner loop - for ($_ = 0; $_ <= 9; $_++) { - print "Inner"; - print "$_\n"; - } - # Alternatively we can use a local keyword in the - # inner loop declaration instead of a my statement - for (local $_ = 0; $_ <= 9; $_++) { - print "Alternative"; - print "$_\n"; +for (1..2) { + print "outer $_:\n"; + local $_; + for (1..3) { + print " inner $_,"; } + print " fini\n"; } diff --git a/Task/Topswops/C++/topswops.cpp b/Task/Topswops/C++/topswops.cpp index c0a0394b07..52b922d604 100644 --- a/Task/Topswops/C++/topswops.cpp +++ b/Task/Topswops/C++/topswops.cpp @@ -1,7 +1,3 @@ -/* - Author: Kevin Bacon [haxifix (@gmail.com)] - Date: 2018-05-16 -*/ #include #include #include diff --git a/Task/Total-circles-area/Java/total-circles-area.java b/Task/Total-circles-area/Java/total-circles-area.java index d43f93d54e..7cd0cdc995 100644 --- a/Task/Total-circles-area/Java/total-circles-area.java +++ b/Task/Total-circles-area/Java/total-circles-area.java @@ -1,6 +1,6 @@ public class CirclesTotalArea { - /* Solution by ilkka.kokkarinen@gmail.com + /* * Rectangles are given as 4-element arrays [tx, ty, w, h]. * Circles are given as 3-element arrays [cx, cy, r]. */ diff --git a/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy index 09981cad2c..3b94abd471 100644 --- a/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy +++ b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy @@ -1,4 +1,4 @@ -def tail = { list, n -> def m = list.size(); list[([m - n, 0].max()).. def m = list.size(); list.subList([m - n, 0].max(),m) } final STACK = [A:[],B:[],C:[]].asImmutable() diff --git a/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol b/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol index 1af8131a8a..2909842baa 100644 --- a/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol +++ b/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Towers of Hanoi" - Author: oofoe - Date: 2009-12-08 URL: http://rosettacode.org/wiki/Towers_of_Hanoi ] diff --git a/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION b/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION index 8a21a17f6b..3a94f16f4b 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION +++ b/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION @@ -19,6 +19,6 @@ The task is to implement the algorithm: # The 'user alert' should not stop processing of other items of the sequence. # Print a prompt before accepting '''eleven''', textual, numeric inputs. # You may optionally print the item as well as its associated result, but the results must be in reverse order of input. -# The sequence S may be 'implied' and so not shown explicitly. +# The sequence   ''' ''S'' '''   may be 'implied' and so not shown explicitly. # ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).

diff --git a/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c b/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c index 208e70edb5..0d6b84598b 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c +++ b/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c @@ -1,6 +1,3 @@ -/* Abhishek Ghosh - 27th August, 2012 */ - #include #include diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs b/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs index 2963897b0d..f263b17ac4 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs +++ b/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs @@ -1,10 +1,16 @@ import Control.Monad (replicateM, mapM_) -f x = (abs x) ** 0.5 + 5 * x ** 3 +f :: Floating a => a -> a +f x = sqrt (abs x) + 5 * x ** 3 +main :: IO () main = do - putStrLn "Enter 11 numbers for evaluation" - x <- replicateM 11 $ readLn - mapM_ ((\x -> if x > 400 - then putStrLn "OVERFLOW" - else print x). f) $ reverse x + putStrLn "Enter 11 numbers for evaluation" + x <- replicateM 11 readLn + mapM_ + ((\x -> + if x > 400 + then putStrLn "OVERFLOW" + else print x) . + f) $ + reverse x diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl b/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl index 5204fc3c29..00f678c44c 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl +++ b/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl @@ -1,14 +1,11 @@ -#!/usr/bin/perl -use strict ; -use warnings ; - -my $number ; -my @sequence ; -print "Please enter 11 numbers!\n" ; -for my $i ( 0..10 ) { - $number = ; - chomp $number ; - push @sequence , $number ; +print "Enter 11 numbers:\n"; +for ( 1..11 ) { + $number = ; + chomp $number; + push @sequence, $number; +} + +for $n (reverse @sequence) { + my $result = sqrt( abs($n) ) + 5 * $n**3; + printf "f( %6.2f ) %s\n", $n, $result > 400 ? " too large!" : sprintf "= %6.2f", $result } -map { my $result = sqrt( abs ( $_ ) ) + 5 * $_** 3 ; print "f( $_ ) " ; $result > 400 ? print "too large!\n" : print ": $result\n" ; } - reverse @sequence ; diff --git a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx index 123e006856..265def851f 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx +++ b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx @@ -4,7 +4,7 @@ parse arg N .; if N=='' | N=="," then N=11 /*Not specified? Then use the maxValue= 400 /*the maximum value f(x) can have. */ wid= 20 /* Β·Β·Β· but only show this many digits.*/ frac= 5 /* Β·Β·Β· show this # of fractional digs.*/ -say ' _____ ' /* ◄───── display a vinculum.*/ +say ' _____' /* ◄─── this SAY displays a vinculum.*/ say 'function: Ζ’(x) ≑ √ β”‚xβ”‚ + (5 * x^3)' prompt= 'enter ' N " numbers for the Trabb─Pardo─Knuth algorithm: (or Quit)" diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring b/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring index 4c79e26534..b8193c4beb 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring +++ b/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring @@ -1,7 +1,4 @@ # Project : Trabb Pardo–Knuth algorithm -# Date : 2017/10/06 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(3) x = list(11) diff --git a/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol b/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol index 5206a15cd2..93b28d9321 100644 --- a/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol +++ b/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Trigonometric Functions" - Author: oofoe - Date: 2009-12-07 URL: http://rosettacode.org/wiki/Trigonometric_Functions ] diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx new file mode 100644 index 0000000000..0a393c1cd0 --- /dev/null +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx @@ -0,0 +1,81 @@ +/*REXX program demonstrates some common trig functions (30 decimal digits are shown).*/ +showdigs= 25 /*show only 25 digits of number. */ +numeric digits showdigs + 10 /*DIGITS default is 9, but use */ + /*extra digs to prevent rounding.*/ +say 'Using' showdigs 'decimal digits precision.' /*show # decimal digs being used.*/ +say + do j=-180 to +180 by 15 /*let's just do a half─Monty. */ + stuff = right(j, 4) 'degrees, rads=' show( d2r(j) ) , + ' sin=' show( sinD(j) ) , + ' cos=' show( cosD(J) ) + /*don't let TANGENT go postal. */ + if abs(j)\==90 then stuff=stuff ' tan=' show( tanD(j) ) + say stuff + end /*j*/ +say + do k=-1 to +1 by 1/2 /*keep the Arc─functions happy. */ + say right(k, 4) 'radians, degs=' show( r2d(k) ) , + ' Acos=' show( Acos(k) ) , + ' Asin=' show( Asin(k) ) , + ' Atan=' show( Atan(k) ) + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a + if a>1 then call AsinErr x /*X argument is out of range. */ + if a >= sqrt(2) * .5 then return sign(x) * acos( sqrt(1 - aa), '-ASIN') + do j=2 by 2 until p=z; p=z; o= o * aa * (j-1) / j; z= z +o / (j+1); end + return z /* [↑] compute until no noise. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr; return pi()*.5 - Asin(x) +AcosD: return r2d( Acos( arg(1) ) ) +AsinD: return r2d( Asin( arg(1) ) ) +cosD: return cos( d2r( arg(1) ) ) +sinD: return sin( d2r( d2d( arg(1) ) ) ) +tan: procedure; parse arg x; _= cos(x); if _=0 then call tanErr; return sin(x) / _ +tanD: return tan( d2r( arg(1) ) ) +d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle*/ +d2r: return r2r( d2d( 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*/ +show: return left( left('', arg(1) >= 0)format( arg(1), , showdigs) / 1, showdigs) +tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 +tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x +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 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Atan: procedure; parse arg x; if abs(x)=1 then return pi() * .25 * sign(x) + return Asin(x / sqrt(1 + x*x) ) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +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) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, max(1, digits() -3)) + if x=pi*.5 then return 1; if x==pi * 1.5 then return -1 + if abs(x)=pi | x=0 then return 0; return .sinCos(x, 1) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.sinCos: parse arg z 1 _,i; q= x*x + do k=2 by 2 until p=z; p= z; _= - _ * q / (k * (k+i) ); z= z+_; end + return z +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9; h= d+6 + numeric digits; numeric form; 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.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 + return e /*Note: the actual E subroutine returns E's accuracy that */ + /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +exp: procedure; parse arg x; ix=x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x=x - ix + z=1; _=1; w=z; do j=1; _= _*x/j; z= (z+_) / 1; if z==w then leave; w=z; end + if z\==0 then z= e()**ix * z; return z +/*──────────────────────────────────────────────────────────────────────────────────────*/ +pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 + return pi /*Note: the actual 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. */ diff --git a/Task/Truncatable-primes/Ring/truncatable-primes.ring b/Task/Truncatable-primes/Ring/truncatable-primes.ring index 48c3a7a59e..3df998e28e 100644 --- a/Task/Truncatable-primes/Ring/truncatable-primes.ring +++ b/Task/Truncatable-primes/Ring/truncatable-primes.ring @@ -1,7 +1,4 @@ # Project : Truncatable primes -# Date : 2017/10/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : for n = 1000000 to 1 step -1 flag = 1 diff --git a/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring b/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring index ab7ef60663..0e99b2ad6e 100644 --- a/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring +++ b/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring @@ -1,7 +1,4 @@ # Project : Ulam spiral (for primes) -# Date : 2018/06/11 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "guilib.ring" load "stdlib.ring" 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 92d89b2d63..eee350d7eb 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,24 +1,29 @@ require('Imager') Β  -var (n=512, start=1, file='ulam.png') = ARGV.map{.to_i}... +var (n=512, start=1, file='ulam.png') + +ARGV.getopt( + 'n=i' => \n, + 's=i' => \start, + 'f=s' => \file, +) Β  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)) + 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 = %O.new('#000000') +var white = %O.new('#FFFFFF') Β  -var img = %s'Imager'.new(xsize => n, ysize => n, channels => 1) +var img = %O.new(xsize => n, ysize => n, channels => 1) img.box(filled => 1, color => white) Β  -for y,x in (^n ~X ^n) { - var v = cell(n, x, y, start) - if (v.is_prime) { +for y=(^n), x=(^n) { + if (cell(n, x, y, start).is_prime) { img.setpixel(x => x, y => y, color => black) } } diff --git a/Task/Undefined-values/Ring/undefined-values.ring b/Task/Undefined-values/Ring/undefined-values.ring index 775f9f2103..d93b919169 100644 --- a/Task/Undefined-values/Ring/undefined-values.ring +++ b/Task/Undefined-values/Ring/undefined-values.ring @@ -1,7 +1,4 @@ # Project : Undefined values -# Date : 2018/03/27 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : test() func test diff --git a/Task/Unicode-variable-names/C/unicode-variable-names.c b/Task/Unicode-variable-names/C/unicode-variable-names.c index 0eaa9d1ac9..291c4a0223 100644 --- a/Task/Unicode-variable-names/C/unicode-variable-names.c +++ b/Task/Unicode-variable-names/C/unicode-variable-names.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 5th October 2017*/ - #include int main() { diff --git a/Task/Unicode-variable-names/Perl-6/unicode-variable-names-2.pl6 b/Task/Unicode-variable-names/Perl-6/unicode-variable-names-2.pl6 index 0f6b462b80..10b314b537 100644 --- a/Task/Unicode-variable-names/Perl-6/unicode-variable-names-2.pl6 +++ b/Task/Unicode-variable-names/Perl-6/unicode-variable-names-2.pl6 @@ -5,3 +5,5 @@ sub Ο€ { pi }; sub postfix:<Β°>($degrees) { $degrees * Ο€ / 180 }; for @ᐁ -> $ΰ² _ΰ²  { say sin $ΰ² _ΰ² Β° }; + +sub cΝ“ΝˆΜƒΝ‚Μ‹ΜˆΜ†Μ½hΜ₯ΜͺΝ•Ν£Ν›ΜŠaΝ¨Ν£ΜΝžΖ‘Μ±Ν”Μ–Ν–Μ‘Μ½Θ™Μ»Μ₯Ν¬ΜƒΜˆΝ© { 'HE COMES' } diff --git a/Task/Unicode-variable-names/Ring/unicode-variable-names.ring b/Task/Unicode-variable-names/Ring/unicode-variable-names.ring index e516a2e9c9..19a445bf0c 100644 --- a/Task/Unicode-variable-names/Ring/unicode-variable-names.ring +++ b/Task/Unicode-variable-names/Ring/unicode-variable-names.ring @@ -1,7 +1,4 @@ # Project : Unicode variable names -# Date : 2017/09/20 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : Ξ” = "Ring Programming Language" see Ξ” + nl diff --git a/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol b/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol new file mode 100644 index 0000000000..907784f8cc --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol @@ -0,0 +1,33 @@ + identification division. + program-id. Query. + + environment division. + configuration section. + special-names. + call-convention 0 is extern. + + repository. + function all intrinsic. + + data division. + working-storage section. + 01 query-result. + 05 filler value "Here I am". + + linkage section. + 01 data-reference. + 05 data-buffer pic x occurs 0 to 8192 times + depending on length-reference. + 01 length-reference usage binary-long. + + procedure division extern using data-reference length-reference. + + if length(query-result) less than or equal to length-reference + and length-reference less than 8193 then + move query-result to data-reference + move length(query-result) to length-reference + move 1 to return-code + end-if + + goback. + end program Query. diff --git a/Task/User-input-Graphical/REBOL/user-input-graphical.rebol b/Task/User-input-Graphical/REBOL/user-input-graphical.rebol index a313d37c2a..9cfa32ffd4 100644 --- a/Task/User-input-Graphical/REBOL/user-input-graphical.rebol +++ b/Task/User-input-Graphical/REBOL/user-input-graphical.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Graphical User Input" - Author: oofoe - Date: 2009-12-07 URL: http://rosettacode.org/wiki/User_Input_-_graphical ] diff --git a/Task/User-input-Text/ARM-Assembly/user-input-text.arm b/Task/User-input-Text/ARM-Assembly/user-input-text.arm new file mode 100644 index 0000000000..1fd5d88a0b --- /dev/null +++ b/Task/User-input-Text/ARM-Assembly/user-input-text.arm @@ -0,0 +1,149 @@ +/* ARM assembly Raspberry PI */ +/* program inputText.s */ + +/* Constantes */ +.equ BUFFERSIZE, 100 +.equ STDIN, 0 @ Linux input console +.equ STDOUT, 1 @ Linux output console +.equ EXIT, 1 @ Linux syscall +.equ READ, 3 @ Linux syscall +.equ WRITE, 4 @ Linux syscall +/* Initialized data */ +.data +szMessDeb: .asciz "Enter text : \n" +szMessNum: .asciz "Enter number : \n" +szCarriageReturn: .asciz "\n" + +/* UnInitialized data */ +.bss +sBuffer: .skip BUFFERSIZE + +/* code section */ +.text +.global main +main: /* entry of program */ + push {fp,lr} /* saves 2 registers */ + ldr r0,iAdrszMessDeb + bl affichageMess + mov r0,#STDIN @ Linux input console + ldr r1,iAdrsBuffer @ buffer address + mov r2,#BUFFERSIZE @ buffer size + mov r7, #READ @ request to read datas + swi 0 @ call system + ldr r1,iAdrsBuffer @ buffer address + mov r2,#0 @ end of string + strb r2,[r1,r0] @ store byte at the end of input string (r0 contains number of characters) + + ldr r0,iAdrsBuffer @ buffer address + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessNum + bl affichageMess + mov r0,#STDIN @ Linux input console + ldr r1,iAdrsBuffer @ buffer address + mov r2,#BUFFERSIZE @ buffer size + mov r7, #READ @ request to read datas + swi 0 @ call system + ldr r1,iAdrsBuffer @ buffer address + mov r2,#0 @ end of string + strb r2,[r1,r0] @ store byte at the end of input string (r0 + @ + ldr r0,iAdrsBuffer @ buffer address + bl conversionAtoD @ conversion string in number in r0 + +100: /* standard end of the program */ + mov r0, #0 @ return code + pop {fp,lr} @restaur 2 registers + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call + +iAdrszMessDeb: .int szMessDeb +iAdrszMessNum: .int szMessNum +iAdrsBuffer: .int sBuffer +iAdrszCarriageReturn: .int szCarriageReturn +/******************************************************************/ +/* display text with size calculation */ +/******************************************************************/ +/* r0 contains the address of the message */ +affichageMess: + push {fp,lr} /* save registres */ + push {r0,r1,r2,r7} /* save others registers */ + mov r2,#0 /* counter length */ +1: /* loop length calculation */ + ldrb r1,[r0,r2] /* read octet start position + index */ + cmp r1,#0 /* if 0 its over */ + addne r2,r2,#1 /* else add 1 in the length */ + bne 1b /* and loop */ + /* so here r2 contains the length of the message */ + mov r1,r0 /* address message in r1 */ + mov r0,#STDOUT /* code to write to the standard output Linux */ + mov r7, #WRITE /* code call system "write" */ + swi #0 /* call systeme */ + pop {r0,r1,r2,r7} /* restaur others registers */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* return */ + +/******************************************************************/ +/* Convert a string to a number stored in a registry */ +/******************************************************************/ +/* r0 contains the address of the area terminated by 0 or 0A */ +/* r0 returns a number */ +conversionAtoD: + push {fp,lr} @ save 2 registers + push {r1-r7} @ save others registers + mov r1,#0 + mov r2,#10 @ factor + mov r3,#0 @ counter + mov r4,r0 @ save address string -> r4 + mov r6,#0 @ positive sign by default + mov r0,#0 @ initialization to 0 +1: /* early space elimination loop */ + ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position + cmp r5,#0 @ end of string -> end routine + beq 100f + cmp r5,#0x0A @ end of string -> end routine + beq 100f + cmp r5,#' ' @ space ? + addeq r3,r3,#1 @ yes we loop by moving one byte + beq 1b + cmp r5,#'-' @ first character is - + moveq r6,#1 @ 1 -> r6 + beq 3f @ then move on to the next position +2: /* beginning of digit processing loop */ + cmp r5,#'0' @ character is not a number + blt 3f + cmp r5,#'9' @ character is not a number + bgt 3f + /* character is a number */ + sub r5,#48 + ldr r1,iMaxi @ check the overflow of the register + cmp r0,r1 + bgt 99f @ overflow error + mul r0,r2,r0 @ multiply par factor 10 + add r0,r5 @ add to r0 +3: + add r3,r3,#1 @ advance to the next position + ldrb r5,[r4,r3] @ load byte + cmp r5,#0 @ end of string -> end routine + beq 4f + cmp r5,#0x0A @ end of string -> end routine + beq 4f + b 2b @ loop +4: + cmp r6,#1 @ test r6 for sign + moveq r1,#-1 + muleq r0,r1,r0 @ if negatif, multiply par -1 + b 100f +99: /* overflow error */ + ldr r0,=szMessErrDep + bl affichageMess + mov r0,#0 @ return zero if error +100: + pop {r1-r7} @ restaur other registers + pop {fp,lr} @ restaur 2 registers + bx lr @return procedure +/* constante program */ +iMaxi: .int 1073741824 +szMessErrDep: .asciz "Too large: overflow 32 bits.\n" diff --git a/Task/User-input-Text/REBOL/user-input-text.rebol b/Task/User-input-Text/REBOL/user-input-text.rebol index 08f159e88b..89ca3777d9 100644 --- a/Task/User-input-Text/REBOL/user-input-text.rebol +++ b/Task/User-input-Text/REBOL/user-input-text.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Textual User Input" - Author: oofoe - Date: 2009-12-07 URL: http://rosettacode.org/wiki/User_Input_-_text ] diff --git a/Task/Vampire-number/C++/vampire-number.cpp b/Task/Vampire-number/C++/vampire-number.cpp index 6253d513c3..6ad4f68cb4 100644 --- a/Task/Vampire-number/C++/vampire-number.cpp +++ b/Task/Vampire-number/C++/vampire-number.cpp @@ -13,12 +13,12 @@ bool isVampireNumber( long number, std::vector > & solutio std::sort ( numberstring.begin( ) , numberstring.end( ) ) ; int fanglength = numberstring.length( ) / 2 ; long start = static_cast( std::pow( 10 , fanglength - 1 ) ) ; - long end = start * 10 ; - for ( long i = start ; i < ( end - start ) / 2 ; i++ ) { + long end = sqrt(number) ; + for ( long i = start ; i <= end ; i++ ) { if ( number % i == 0 ) { long quotient = number / i ; if ( ( i % 10 == 0 ) && ( quotient % 10 == 0 ) ) - return false ; + continue ; numberstream.str( "" ) ; //clear the number stream numberstream << i << quotient ; std::string divisorstring ( numberstream.str( ) ) ; @@ -45,11 +45,11 @@ int main( ) { long end = start * 10 ; for ( long num = start ; num < end ; num++ ) { if ( isVampireNumber( num , solutions ) ) { + vampireNumbersFound++ ; std::cout << vampireNumbersFound << " :" << num << " is a vampire number! These are the fangs:\n" ; std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; std::cout << "\n_______________" << std::endl ; - solutions.clear( ) ; - vampireNumbersFound++ ; + solutions.clear( ) ; if ( vampireNumbersFound == 25 ) break ; } @@ -58,7 +58,7 @@ int main( ) { } std::vector testnumbers ; testnumbers.push_back( 16758243290880 ) ; - testnumbers.push_back( 2495901734865 ) ; + testnumbers.push_back( 24959017348650 ) ; testnumbers.push_back( 14593825548650 ) ; for ( std::vector::const_iterator svl = testnumbers.begin( ) ; svl != testnumbers.end( ) ; svl++ ) { diff --git a/Task/Vampire-number/Ring/vampire-number.ring b/Task/Vampire-number/Ring/vampire-number.ring index 1686dca04a..42460a9992 100644 --- a/Task/Vampire-number/Ring/vampire-number.ring +++ b/Task/Vampire-number/Ring/vampire-number.ring @@ -1,7 +1,4 @@ # Project : Vampire number -# Date : 2018/02/01 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : for p = 10 to 127000 vampire(p) diff --git a/Task/Variable-size-Get/00DESCRIPTION b/Task/Variable-size-Get/00DESCRIPTION index 0888f912c1..6215b56361 100644 --- a/Task/Variable-size-Get/00DESCRIPTION +++ b/Task/Variable-size-Get/00DESCRIPTION @@ -1,7 +1,6 @@ {{omit from|AWK}} {{omit from|Clojure}} -{{omit from|E}}ruby - +{{omit from|E}} {{omit from|gnuplot}} {{omit from|Groovy}} {{omit from|GUISS|Does not have variables.}} diff --git a/Task/Variable-size-Get/Perl/variable-size-get.pl b/Task/Variable-size-Get/Perl/variable-size-get.pl index db1e6823ee..3cf3008b2d 100644 --- a/Task/Variable-size-Get/Perl/variable-size-get.pl +++ b/Task/Variable-size-Get/Perl/variable-size-get.pl @@ -1,6 +1,6 @@ -use Devel::Size; +use Devel::Size qw(size total_size); my $var = 9384752; my @arr = (1, 2, 3, 4, 5, 6); -print size($var); -print total_size(@arr); +print size($var); # 24 +print total_size(\@arr); # 256 diff --git a/Task/Variadic-function/Ring/variadic-function.ring b/Task/Variadic-function/Ring/variadic-function.ring index 8540044200..e66669ebd4 100644 --- a/Task/Variadic-function/Ring/variadic-function.ring +++ b/Task/Variadic-function/Ring/variadic-function.ring @@ -1,7 +1,4 @@ # Project : Variadic function -# Date : 2017/11/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : sum([1,2]) sum([1,2,3]) diff --git a/Task/Vector-products/Maple/vector-products.maple b/Task/Vector-products/Maple/vector-products.maple new file mode 100644 index 0000000000..8e336e1304 --- /dev/null +++ b/Task/Vector-products/Maple/vector-products.maple @@ -0,0 +1,12 @@ +with(LinearAlgebra): +A := Vector([3,4,5]): +B := Vector([4,3,5]): +C := Vector([-5,-12,-13]): +>>>A.B; +49 +>>>CrossProduct(A,B); +Vector([5, 5, -7]) +>>>A.(CrossProduct(B,C)); +6 +>>>CrossProduct(A,CrossProduct(B,C)); +Vector([-267, 204, -3]) diff --git a/Task/Vector-products/Ring/vector-products.ring b/Task/Vector-products/Ring/vector-products.ring index a7c1025b6e..e4c0b751b2 100644 --- a/Task/Vector-products/Ring/vector-products.ring +++ b/Task/Vector-products/Ring/vector-products.ring @@ -1,7 +1,4 @@ # Project : Vector products -# Date : 2017/09/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : d = list(3) e = list(3) 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 index fd1a3b0c88..ab7ad1c152 100644 --- a/Task/Verify-distribution-uniformity-Naive/Ring/verify-distribution-uniformity-naive.ring +++ b/Task/Verify-distribution-uniformity-Naive/Ring/verify-distribution-uniformity-naive.ring @@ -1,7 +1,4 @@ # Project : Verify distribution uniformity/Naive -# Date : 2017/09/21 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : maxrnd = 7 for r = 2 to 5 diff --git a/Task/Video-display-modes/Go/video-display-modes.go b/Task/Video-display-modes/Go/video-display-modes.go new file mode 100644 index 0000000000..b91dbeb0b0 --- /dev/null +++ b/Task/Video-display-modes/Go/video-display-modes.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "log" + "os/exec" + "time" +) + +func main() { + // query supported display modes + out, err := exec.Command("xrandr", "-q").Output() + if err != nil { + log.Fatal(err) + } + fmt.Println(string(out)) + time.Sleep(3 * time.Second) + + // change display mode to 1024x768 say (no text output) + err = exec.Command("xrandr", "-s", "1024x768").Run() + if err != nil { + log.Fatal(err) + } + time.Sleep(3 * time.Second) + + // change it back again to 1366x768 (or whatever is optimal for your system) + err = exec.Command("xrandr", "-s", "1366x768").Run() + if err != nil { + log.Fatal(err) + } +} diff --git a/Task/Video-display-modes/Phix/video-display-modes.phix b/Task/Video-display-modes/Phix/video-display-modes.phix new file mode 100644 index 0000000000..fe922ec8a2 --- /dev/null +++ b/Task/Video-display-modes/Phix/video-display-modes.phix @@ -0,0 +1,10 @@ +if platform()=LINUX then + {} = system_exec("xrandr -s 640x480") + sleep(3) + {} = system_exec("xrandr -s 1280x960") +else -- WINDOWS + puts(1,"") -- (ensure console exists) + system("mode CON: COLS=40 LINES=25") + sleep(3) + system("mode CON: COLS=80 LINES=25") +end if diff --git a/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl b/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl index 47d4729b28..8e79709a7c 100644 --- a/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl +++ b/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl @@ -15,10 +15,10 @@ print "Key: " . (my $key = $ARGV[ 2 ]) . "\n"; if( $cipher_decipher =~ /ENC/ ){ print "Plain-text: " . (my $plain = $ARGV[ 1 ]) . "\n"; - print "Encrypted: " . Vigenere( 1, $plain ) . "\n"; + print "Encrypted: " . Vigenere( 1, $key, $plain ) . "\n"; }elsif( $cipher_decipher =~ /DEC/ ){ print "Cipher-text: " . (my $cipher = $ARGV[ 1 ]) . "\n"; - print "Decrypted: " . Vigenere( -1, $cipher ) . "\n"; + print "Decrypted: " . Vigenere( -1, $key, $cipher ) . "\n"; } sub printHelp{ @@ -29,7 +29,7 @@ sub printHelp{ } sub Vigenere{ - my ($direction, $text) = @_; + my ($direction, $key, $text) = @_; for( my $count = 0; $count < length $text; $count ++ ){ $key_offset = $direction * ord substr( $key, $count % length $key, 1); $char_offset = ord substr( $text, $count, 1 ); diff --git a/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring b/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring index 89ddcdc5e7..64bb9bb472 100644 --- a/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring +++ b/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring @@ -1,7 +1,4 @@ # Project : VigenΓ¨re cipher -# Date : 2018/01/02 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : key = "LEMON" plaintext = "ATTACK AT DAWN" diff --git a/Task/Voronoi-diagram/Ring/voronoi-diagram.ring b/Task/Voronoi-diagram/Ring/voronoi-diagram.ring index d0cf3a65c9..78bb64699b 100644 --- a/Task/Voronoi-diagram/Ring/voronoi-diagram.ring +++ b/Task/Voronoi-diagram/Ring/voronoi-diagram.ring @@ -1,7 +1,4 @@ # Project : Voronoi diagram -# Date : 2018/03/30 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : load "guilib.ring" load "stdlib.ring" diff --git a/Task/Voronoi-diagram/Sidef/voronoi-diagram.sidef b/Task/Voronoi-diagram/Sidef/voronoi-diagram.sidef index 11941d6d51..8e840d03e7 100644 --- a/Task/Voronoi-diagram/Sidef/voronoi-diagram.sidef +++ b/Task/Voronoi-diagram/Sidef/voronoi-diagram.sidef @@ -1,10 +1,10 @@ require('Imager') func generate_voronoi_diagram(width, height, num_cells) { - var img = %s.new(xsize => width, ysize => height) + var img = %O.new(xsize => width, ysize => height) var (nx,ny,nr,ng,nb) = 5.of { [] }... - for i in ^num_cells { + for i in (^num_cells) { nx << rand(^width) ny << rand(^height) nr << rand(^256) @@ -12,16 +12,9 @@ func generate_voronoi_diagram(width, height, num_cells) { nb << rand(^256) } - for y in ^height { - for x in ^width { - var dmin = hypot(width-1, height-1) - var j = -1 - for i in ^num_cells { - var d = hypot(nx[i]-x, ny[i]-y) - if (d < dmin) { (dmin, j) = (d, i) } - } - img.setpixel(x => x, y => y, color => [nr[j], ng[j], nb[j]]) - } + for y=(^height), x=(^width) { + var j = (^num_cells -> min_by {|i| hypot(nx[i]-x, ny[i]-y) }) + img.setpixel(x => x, y => y, color => [nr[j], ng[j], nb[j]]) } return img } diff --git a/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl index 0fc4f27922..49d28e6596 100644 --- a/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl +++ b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl @@ -1,5 +1,4 @@ use 5.010; -my $pattern = qr{ \A a }xmso; # match files whose first character is 'a' -opendir my $dh, 'the_directory'; -say for grep { $pattern } readdir $dh; +opendir my $dh, '/home/foo/bar'; +say for grep { /php$/ } readdir $dh; closedir $dh; diff --git a/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-2.hs b/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-2.hs index 77e5c0865b..a50b7ef1f8 100644 --- a/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-2.hs +++ b/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-2.hs @@ -1,73 +1,24 @@ -########################### -# A sequential solution # -########################### +import System.FilePath.Posix +import System.Directory +import System.IO -procedure main() -every write(!getdirs(".")) # writes out all directories from the current directory down -end +dir_walk :: FilePath -> (FilePath -> IO ()) -> IO () +dir_walk top filefunc = do + isDirectory <- doesDirectoryExist top + if isDirectory + then + do + files <- listDirectory top + mapM_ (\file -> dir_walk (top file) filefunc) files + else + filefunc top -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 +main :: IO () +main = do + hSetEncoding stdout utf8 + hSetEncoding stdin utf8 + let worker fname = + do if (takeExtension fname == ".hs") + then putStrLn fname + else return () + dir_walk "." worker diff --git a/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-3.hs b/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-3.hs new file mode 100644 index 0000000000..77e5c0865b --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively-3.hs @@ -0,0 +1,73 @@ +########################### +# 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/Web-scraping/REBOL/web-scraping.rebol b/Task/Web-scraping/REBOL/web-scraping.rebol index c65d3dea08..0ff410d319 100644 --- a/Task/Web-scraping/REBOL/web-scraping.rebol +++ b/Task/Web-scraping/REBOL/web-scraping.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "Web Scraping" - Author: oofoe - Date: 2009-12-07 URL: http://rosettacode.org/wiki/Web_Scraping ] diff --git a/Task/Word-wrap/REXX/word-wrap-1.rexx b/Task/Word-wrap/REXX/word-wrap-1.rexx index 1ffcdbb622..78e11e6873 100644 --- a/Task/Word-wrap/REXX/word-wrap-1.rexx +++ b/Task/Word-wrap/REXX/word-wrap-1.rexx @@ -9,8 +9,8 @@ if width=='' | width=="," then width=linesize() /* " " " " " $=word(@,1) /*initialize $ with the first word. */ do k=2 for words(@)-1; x=word(@,k) /*parse until text (@) exhausted. */ _=$ x /*append it to the $ list and test. */ - if length(_)>width then do; say $ /*this word a bridge too far? > w. */ - _=x /*assign this word to the next line. */ + if length(_)>=width then do; say $ /*this word a bridge too far? > w. */ + _=x /*assign this word to the next line. */ end $=_ /*new words (on a line) are OK so far.*/ end /*m*/ diff --git a/Task/Word-wrap/REXX/word-wrap-2.rexx b/Task/Word-wrap/REXX/word-wrap-2.rexx index 327ea7e72f..e6938e6c2f 100644 --- a/Task/Word-wrap/REXX/word-wrap-2.rexx +++ b/Task/Word-wrap/REXX/word-wrap-2.rexx @@ -1,42 +1,42 @@ -/*REXX program reads a file and displays it to the screen (with word wrap). */ -parse arg iFID width justify _ . /*obtain optional arguments from the CL*/ -if iFID=='' | iFID=="," then iFID ='LAWS.TXT' /*Not specified? Then use the defaul.t*/ -if width=='' |width=="," then width=linesize() /* " " " " " " */ -if right(width, 1)=='%' then width=linesize() * translate(width, , "%") % 100 -if justify==''|justify=="," then justify='Left' /*Default? Then use the default: LEFT */ -just=left(justify, 1) /*only use first char of JUSTIFY. */ -upper just /*be able to handle mixed case. */ -if pos(just, 'BCLR')==0 then call err "JUSTIFY (3rd arg) is illegal:" justify +/*REXX program reads a file and displays it to the screen (with word wrap). */ +parse arg iFID width kind _ . /*obtain optional arguments from the CL*/ +if iFID=='' | iFID=="," then iFID = 'LAWS.TXT' /*Not specified? Then use the default.*/ +if width=='' |width=="," then width= linesize() /* " " " " " " */ +if right(width, 1) =='%' then width= linesize() * translate(width, , "%") % 100 +if kind=='' | kind=="," then kind= 'Left' /*Default? Then use the default: LEFT */ +just= left(kind, 1); upper just /*use 1st char of JUSTIFY, uppercased.*/ +if pos(just, 'BCLR')==0 then call err "KIND (3rd arg) is illegal:" kind if _\=='' then call err "too many arguments specified." _ if \datatype(width,'W') then call err "WIDTH (2nd arg) isn't an integer:" width n=0 /*the number of words in the file. */ - do j=0 while lines(iFID)\==0 /*read from the file until End-Of-File.*/ - _=linein(iFID) /*get a record (line of text). */ - do until _==''; n=n+1 /*extract some words (or maybe not). */ - parse var _ @.n _ /*obtain and assign next word in text. */ - end /*DO until*/ /*parse 'til the line of text is null. */ - end /*j*/ + do j=0 while lines(iFID)\==0 /*read from the file until End-Of-File.*/ + _=linein(iFID) /*get a record (line of text). */ + do until _==''; n= n + 1 /*extract some words (or maybe not). */ + parse var _ @.n _ /*obtain and assign next word in text. */ + end /*until*/ /*parse 'til the line of text is null. */ + end /*j*/ + if j==0 then call err 'file' iFID "not found." if n==0 then call err 'file' iFID "is empty (or has no words)" $=@.1 /*initialize $ string with first word*/ - do m=2 for n-1; x=@.m /*parse until text (@) is exhausted. */ - _=$ x /*append it to the $ string and test.*/ - if length(_)>width then call tell /*this word a bridge too far? > w */ - $=_ /*the new words are OK (so far). */ - end /*m*/ + do m=2 for n-1; x= @.m /*parse until text (@) is exhausted. */ + _= $ x /*append it to the $ string and test.*/ + if length(_)>= width then call tell /*this word a bridge too far? > w */ + $= _ /*the new words are OK (so far). */ + end /*m*/ call tell /*handle any residual words (if any). */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -err: say; say '***error***'; say; say arg(1); say; say; exit 13 +err: say; say '***error***'; say; say arg(1); say; say; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ tell: if $=='' then return /* [↓] the first word may be too long.*/ w=max(width, length($) ) /*don't truncate long words (> w). */ select when just=='L' then $= strip($) /*left ◄──────── */ - when just=='R' then $= right($,w) /*──────► right */ - when just=='B' then $=justify($,w) /*◄────both────► */ - when just=='C' then $= center($,w) /* β—„centeredβ–Ί */ + when just=='R' then $= right($, w) /*──────► right */ + when just=='B' then $=justify($, w) /*◄────both────► */ + when just=='C' then $= center($, w) /* β—„centeredβ–Ί */ end /*select*/ say $ /*display the line of words to terminal*/ - _=x /*handle any word overflow. */ + _= x /*handle any word overflow. */ return /*go back and keep truckin'. */ diff --git a/Task/Word-wrap/Ring/word-wrap.ring b/Task/Word-wrap/Ring/word-wrap.ring index 6878cae692..d89a103a07 100644 --- a/Task/Word-wrap/Ring/word-wrap.ring +++ b/Task/Word-wrap/Ring/word-wrap.ring @@ -1,7 +1,4 @@ # Project : Word wrap -# Date : 2018/01/02 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : load "stdlib.ring" diff --git a/Task/World-Cup-group-stage/Scala/world-cup-group-stage.scala b/Task/World-Cup-group-stage/Scala/world-cup-group-stage.scala new file mode 100644 index 0000000000..3714884f63 --- /dev/null +++ b/Task/World-Cup-group-stage/Scala/world-cup-group-stage.scala @@ -0,0 +1,39 @@ +object GroupStage extends App { //team left digit vs team right digit + val games = Array("12", "13", "14", "23", "24", "34") + val points = Array.ofDim[Int](4, 10) //playing 3 games, points range from 0 to 9 + var results = "000000" //start with left teams all losing + + private def nextResult: Boolean = { + if (results == "222222") false + else { + results = Integer.toString(Integer.parseInt(results, 3) + 1, 3) + while (results.length < 6) results = "0" + results //left pad with 0s + true + } + } + + do { + val records = Array(0, 0, 0, 0) + for (i <- results.indices.reverse by -1) { + results(i) match { + case '2' => records(games(i)(0) - '1') += 3 + case '1' => //draw + records(games(i)(0) - '1') += 1 + records(games(i)(1) - '1') += 1 + case '0' => records(games(i)(1) - '1') += 3 + } + } + java.util.Arrays.sort(records) //sort ascending, first place team on the right + + points(0)(records(0)) += 1 + points(1)(records(1)) += 1 + points(2)(records(2)) += 1 + points(3)(records(3)) += 1 + } while (nextResult) + + println("First place: " + points(3).mkString("[",", ","]")) + println("Second place: " + points(2).mkString("[",", ","]")) + println("Third place: " + points(1).mkString("[",", ","]")) + println("Fourth place: " + points(0).mkString("[",", ","]")) + +} diff --git a/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring b/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring index 7e12f05aac..650901373b 100644 --- a/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring +++ b/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring @@ -1,7 +1,4 @@ # Project : Write float arrays to a text file -# Date : 2018/02/15 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : decimals(13) x = [1, 2, 3, 100000000000] diff --git a/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c b/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c index 16e1bd48ae..0d0bad08d8 100644 --- a/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c +++ b/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 6th October 2017*/ - #include #include diff --git a/Task/XML-Input/REBOL/xml-input.rebol b/Task/XML-Input/REBOL/xml-input.rebol index 8654d39dae..45bd8676f1 100644 --- a/Task/XML-Input/REBOL/xml-input.rebol +++ b/Task/XML-Input/REBOL/xml-input.rebol @@ -1,7 +1,5 @@ REBOL [ Title: "XML Reading" - Author: oofoe - Date: 2009-12-08 URL: http://rosettacode.org/wiki/XML_Reading ] diff --git a/Task/XML-XPath/C/xml-xpath.c b/Task/XML-XPath/C/xml-xpath.c index be8c0b1d78..a82b244bee 100644 --- a/Task/XML-XPath/C/xml-xpath.c +++ b/Task/XML-XPath/C/xml-xpath.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 10th March 2018*/ - #include #include diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro new file mode 100644 index 0000000000..45b14d9b2f --- /dev/null +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro @@ -0,0 +1,54 @@ +:- use_module(library(clpfd)). + +zebra :- + Nation = [Englishman, Spaniard, Japanese, Ukrainian, Norwegian ], + Color = [Red, Green, White, Yellow, Blue ], + Smoke = [Oldgold, Kools, Chesterfield, Luckystrike, Parliament], + Pet = [Dog, Snails, Fox, Horse, Zebra ], + Drink = [Tea, Coffee, Milk, Orangejuice, Water ], + + % house numbers 1 to 5 + Nation ins 1..5, + Color ins 1..5, + Smoke ins 1..5, + Pet ins 1..5, + Drink ins 1..5, + + % the values in each list are exclusive + all_different(Nation), + all_different(Color), + all_different(Smoke), + all_different(Pet), + all_different(Drink), + + % actual constraints + Englishman #= Red, + Spaniard #= Dog, + Green #= Coffee, + Ukrainian #= Tea, + Green #= White + 1, + Oldgold #= Snails, + Yellow #= Kools, + Milk #= 3, + Norwegian #= 1, + (Chesterfield #= Fox - 1 #\/ Chesterfield #= Fox + 1), + (Kools #= Horse - 1 #\/ Kools #= Horse + 1), + Luckystrike #= Orangejuice, + Japanese #= Parliament, + (Norwegian #= Blue - 1 #\/ Norwegian #= Blue + 1), + + % get solution + flatten([Nation, Color, Smoke, Pet, Drink], List), label(List), + + % print the answers + sort([Englishman-englishman, Spaniard-spaniard, Japanese-japanese, Ukrainian-ukrainian, Norwegian-norwegian], NationNames), + sort([Red-red, Green-green, White-white, Yellow-yellow, Blue-bule], ColorNames), + sort([Oldgold-oldgold, Kools-kools, Chesterfield-chesterfield, Luckystrike-luckystrike, Parliament-parliament], SmokeNames), + sort([Dog-dog, Snails-snails, Fox-fox, Horse-horse, Zebra-zebra], PetNames), + sort([Tea-tea, Coffee-coffee, Milk-milk, Orangejuice-orangejuice, Water-water], DrinkNames), + Fmt = '~w~16|~w~32|~w~48|~w~64|~w~n', + format(Fmt, NationNames), + format(Fmt, ColorNames), + format(Fmt, SmokeNames), + format(Fmt, PetNames), + format(Fmt, DrinkNames). diff --git a/Task/Zebra-puzzle/Python/zebra-puzzle-4.py b/Task/Zebra-puzzle/Python/zebra-puzzle-4.py new file mode 100644 index 0000000000..98ddaee90f --- /dev/null +++ b/Task/Zebra-puzzle/Python/zebra-puzzle-4.py @@ -0,0 +1,61 @@ +from constraint import * + +problem = Problem() + +Nation = ["Englishman", "Spaniard", "Japanese", "Ukrainian", "Norwegian" ] +Color = ["Red", "Green", "White", "Yellow", "Blue" ] +Smoke = ["Oldgold", "Kools", "Chesterfield", "Luckystrike", "Parliament"] +Pet = ["Dog", "Snails", "Fox", "Horse", "Zebra" ] +Drink = ["Tea", "Coffee", "Milk", "Orangejuice", "Water" ] + +# add variables: house numbers 1 to 5 +problem.addVariables(Nation, range(1,5+1)) +problem.addVariables(Color, range(1,5+1)) +problem.addVariables(Smoke, range(1,5+1)) +problem.addVariables(Pet, range(1,5+1)) +problem.addVariables(Drink, range(1,5+1)) + +# add constraint: the values in each list are exclusive +problem.addConstraint(AllDifferentConstraint(), Nation) +problem.addConstraint(AllDifferentConstraint(), Color) +problem.addConstraint(AllDifferentConstraint(), Smoke) +problem.addConstraint(AllDifferentConstraint(), Pet) +problem.addConstraint(AllDifferentConstraint(), Drink) + +# add constraint: actual constraints +problem.addConstraint(lambda a, b: a == b, ["Englishman", "Red" ]) +problem.addConstraint(lambda a, b: a == b, ["Spaniard", "Dog" ]) +problem.addConstraint(lambda a, b: a == b, ["Green", "Coffee" ]) +problem.addConstraint(lambda a, b: a == b, ["Ukrainian", "Tea" ]) +problem.addConstraint(lambda a, b: a == b + 1, ["Green", "White" ]) +problem.addConstraint(lambda a, b: a == b, ["Oldgold", "Snails" ]) +problem.addConstraint(lambda a, b: a == b, ["Yellow", "Kools" ]) +problem.addConstraint(lambda a: a == 3, ["Milk" ]) +problem.addConstraint(lambda a: a == 1, ["Norwegian" ]) +problem.addConstraint(lambda a, b: a == b - 1 or a == b + 1, ["Chesterfield", "Fox" ]) +problem.addConstraint(lambda a, b: a == b - 1 or a == b + 1, ["Kools", "Horse" ]) +problem.addConstraint(lambda a, b: a == b, ["Luckystrike", "Orangejuice"]) +problem.addConstraint(lambda a, b: a == b, ["Japanese", "Parliament" ]) +problem.addConstraint(lambda a, b: a == b - 1 or a == b + 1, ["Norwegian", "Blue" ]) + +# get solution +sol = problem.getSolution() + +# print the answers +nation = ["Nation" if i == 0 else "" for i in range(6)] +color = ["Color" if i == 0 else "" for i in range(6)] +smoke = ["Smoke" if i == 0 else "" for i in range(6)] +pet = ["Pet" if i == 0 else "" for i in range(6)] +drink = ["Drink" if i == 0 else "" for i in range(6)] +for n in Nation: + nation[sol[n]] = n +for n in Color: + color[sol[n]] = n +for n in Smoke: + smoke[sol[n]] = n +for n in Pet: + pet[sol[n]] = n +for n in Drink: + drink[sol[n]] = n +for d in [nation, color, smoke, pet, drink]: + print("%6s: %14s%14s%14s%14s%14s" % (d[0], d[1], d[2], d[3], d[4], d[5])) diff --git a/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring b/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring index f6ddf4668c..cc0bd873ba 100644 --- a/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring +++ b/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring @@ -1,7 +1,4 @@ # Project : Zeckendorf number representation -# Date : 2017/12/13 -# Author : Gal Zsolt (~ CalmoSoft ~) -# Email : see "0 0" + nl for n = 1 to 20 diff --git a/Task/Zero-to-the-zero-power/Bc/zero-to-the-zero-power.bc b/Task/Zero-to-the-zero-power/Bc/zero-to-the-zero-power.bc new file mode 100644 index 0000000000..52d04ab8f7 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Bc/zero-to-the-zero-power.bc @@ -0,0 +1 @@ +0 ^ 0 diff --git a/Task/Zero-to-the-zero-power/Nial/zero-to-the-zero-power.nial b/Task/Zero-to-the-zero-power/Nial/zero-to-the-zero-power.nial new file mode 100644 index 0000000000..6b0961bbbf --- /dev/null +++ b/Task/Zero-to-the-zero-power/Nial/zero-to-the-zero-power.nial @@ -0,0 +1,8 @@ + 0 0.0 o outer power 0 0.0 o ++--+--+--+ +| 1|1.| 1| ++--+--+--+ +|1.|1.|1.| ++--+--+--+ +| 1|1.| 1| ++--+--+--+ diff --git a/Task/Zhang-Suen-thinning-algorithm/C++/zhang-suen-thinning-algorithm.cpp b/Task/Zhang-Suen-thinning-algorithm/C++/zhang-suen-thinning-algorithm.cpp new file mode 100644 index 0000000000..5a540994f3 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/C++/zhang-suen-thinning-algorithm.cpp @@ -0,0 +1,241 @@ +#include +#include +#include +#include +const std::string input { +"................................" +".#########.......########......." +".###...####.....####..####......" +".###....###.....###....###......" +".###...####.....###............." +".#########......###............." +".###.####.......###....###......" +".###..####..###.####..####.###.." +".###...####.###..########..###.." +"................................" +}; +const std::string input2 { +".........................................................." +".#################...................#############........" +".##################...............################........" +".###################............##################........" +".########.....#######..........###################........" +"...######.....#######.........#######.......######........" +"...######.....#######........#######......................" +"...#################.........#######......................" +"...################..........#######......................" +"...#################.........#######......................" +"...######.....#######........#######......................" +"...######.....#######........#######......................" +"...######.....#######.........#######.......######........" +".########.....#######..........###################........" +".########.....#######.######....##################.######." +".########.....#######.######......################.######." +".########.....#######.######.........#############.######." +".........................................................." +}; + +class ZhangSuen; + +class Image { +public: + friend class ZhangSuen; + using pixel_t = char; + static const pixel_t BLACK_PIX; + static const pixel_t WHITE_PIX; + + Image(unsigned width = 1, unsigned height = 1) + : width_{width}, height_{height}, data_( '\0', width_ * height_) + {} + Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_} + {} + Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)} + {} + ~Image() = default; + Image& operator=(const Image& i) { + if (this != &i) { + width_ = i.width_; + height_ = i.height_; + data_ = i.data_; + } + return *this; + } + Image& operator=(Image&& i) { + if (this != &i) { + width_ = i.width_; + height_ = i.height_; + data_ = std::move(i.data_); + } + return *this; + } + size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; } + bool operator()(unsigned x, unsigned y) { + return data_[idx(x, y)]; + } + friend std::ostream& operator<<(std::ostream& o, const Image& i) { + o << i.width_ << " x " << i.height_ << std::endl; + size_t px = 0; + for(const auto& e : i.data_) { + o << (e?Image::BLACK_PIX:Image::WHITE_PIX); + if (++px % i.width_ == 0) + o << std::endl; + } + return o << std::endl; + } + friend std::istream& operator>>(std::istream& in, Image& img) { + auto it = std::begin(img.data_); + const auto end = std::end(img.data_); + Image::pixel_t tmp; + while(in && it != end) { + in >> tmp; + if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX) + throw "Bad character found in image"; + *it = (tmp == Image::BLACK_PIX)?1:0; + ++it; + } + return in; + } + unsigned width() const noexcept { return width_; } + unsigned height() const noexcept { return height_; } + struct Neighbours { + // 9 2 3 + // 8 1 4 + // 7 6 5 + Neighbours(const Image& img, unsigned p1_x, unsigned p1_y) + : img_{img} + , p1_{img.idx(p1_x, p1_y)} + , p2_{p1_ - img.width()} + , p3_{p2_ + 1} + , p4_{p1_ + 1} + , p5_{p4_ + img.width()} + , p6_{p5_ - 1} + , p7_{p6_ - 1} + , p8_{p1_ - 1} + , p9_{p2_ - 1} + {} + const Image& img_; + const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; } + const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; } + const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; } + const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; } + const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; } + const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; } + const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; } + const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; } + const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; } + const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_; + }; + Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); } +private: + unsigned height_ { 0 }; + unsigned width_ { 0 }; + std::valarray data_; +}; + +constexpr const Image::pixel_t Image::BLACK_PIX = '#'; +constexpr const Image::pixel_t Image::WHITE_PIX = '.'; + +class ZhangSuen { +public: + + // the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2 + unsigned transitions_white_black(const Image::Neighbours& a) const { + unsigned sum = 0; + sum += (a.p9() == 0) && a.p2(); + sum += (a.p2() == 0) && a.p3(); + sum += (a.p3() == 0) && a.p4(); + sum += (a.p8() == 0) && a.p9(); + sum += (a.p4() == 0) && a.p5(); + sum += (a.p7() == 0) && a.p8(); + sum += (a.p6() == 0) && a.p7(); + sum += (a.p5() == 0) && a.p6(); + return sum; + } + + // The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) + unsigned black_pixels(const Image::Neighbours& a) const { + unsigned sum = 0; + sum += a.p9(); + sum += a.p2(); + sum += a.p3(); + sum += a.p8(); + sum += a.p4(); + sum += a.p7(); + sum += a.p6(); + sum += a.p5(); + return sum; + } + const Image& operator()(const Image& img) { + tmp_a_ = img; + size_t changed_pixels = 0; + do { + changed_pixels = 0; + // Step 1 + tmp_b_ = tmp_a_; + for(size_t y = 1; y < tmp_a_.height() - 1; ++y) { + for(size_t x = 1; x < tmp_a_.width() - 1; ++x) { + if (tmp_a_.data_[tmp_a_.idx(x, y)]) { + auto n = tmp_a_.neighbours(x, y); + auto bp = black_pixels(n); + if (bp >= 2 && bp <= 6) { + auto tr = transitions_white_black(n); + if ( tr == 1 + && (n.p2() * n.p4() * n.p6() == 0) + && (n.p4() * n.p6() * n.p8() == 0) + ) { + tmp_b_.data_[n.p1_] = 0; + ++changed_pixels; + } + } + } + } + } + // Step 2 + tmp_a_ = tmp_b_; + for(size_t y = 1; y < tmp_b_.height() - 1; ++y) { + for(size_t x = 1; x < tmp_b_.width() - 1; ++x) { + if (tmp_b_.data_[tmp_b_.idx(x, y)]) { + auto n = tmp_b_.neighbours(x, y); + auto bp = black_pixels(n); + if (bp >= 2 && bp <= 6) { + auto tr = transitions_white_black(n); + if ( tr == 1 + && (n.p2() * n.p4() * n.p8() == 0) + && (n.p2() * n.p6() * n.p8() == 0) + ) { + tmp_a_.data_[n.p1_] = 0; + ++changed_pixels; + } + } + } + } + } + } while(changed_pixels > 0); + return tmp_a_; + } +private: + Image tmp_a_; + Image tmp_b_; +}; + +int main(int argc, char const *argv[]) +{ + using namespace std; + Image img(32, 10); + istringstream iss{input}; + iss >> img; + cout << img; + cout << "ZhangSuen" << endl; + ZhangSuen zs; + Image res = std::move(zs(img)); + cout << res << endl; + + Image img2(58,18); + istringstream iss2{input2}; + iss2 >> img2; + cout << img2; + cout << "ZhangSuen with big image" << endl; + Image res2 = std::move(zs(img2)); + cout << res2 << endl; + return 0; +} diff --git a/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c b/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c index c6ae5cd13c..0a47b94baa 100644 --- a/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c +++ b/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c @@ -1,5 +1,3 @@ -/*Abhishek Ghosh, 24th September 2017*/ - #include #include diff --git a/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring b/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring index 920fdf76f1..b303b50fd4 100644 --- a/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring +++ b/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring @@ -1,56 +1,68 @@ -# Project : Zig-zag matrix -# Date : 2018/03/24 -# Author : Gal Zsolt [~ CalmoSoft ~] -# Email : +# Project Zig-zag matrix +load "guilib.ring" load "stdlib.ring" -n = 5 -a = newlist(n,n) -for j = 1 to n - for i = 1 to n - a[j][i] = 0 - next -next -i = 1 -j = 1 -k = 1 -while k < n * n - a[j][i] = k - k = k + 1 - if i = n - j = j + 1 - a[j][i] = k - k = k + 1 - di = -1 - dj = 1 - ok - if j = 1 - i = i + 1 - a[j][i] = k - k = k + 1 - di = -1 - dj = 1 - ok - if j = n - i = i + 1 - a[j][i] = k - k = k + 1 - di = 1 - dj = -1 - ok - if i = 1 - j = j + 1 - a[j][i] = k - k = k + 1 - di = 1 - dj = -1 - ok - i = i + di - j = j + dj -end -for p = 1 to n - for m = 1 to n - see "" + a[p][m] + " " - next - see nl -next +new qapp + { + win1 = new qwidget() { + setwindowtitle("Zig-zag matrix") + setgeometry(100,100,600,400) + n = 5 + a = newlist(n,n) + zigzag = newlist(n,n) + for j = 1 to n + for i = 1 to n + a[j][i] = 0 + next + next + i = 1 + j = 1 + k = 1 + while k < n * n + a[j][i] = k + k = k + 1 + if i = n + j = j + 1 + a[j][i] = k + k = k + 1 + di = -1 + dj = 1 + ok + if j = 1 + i = i + 1 + a[j][i] = k + k = k + 1 + di = -1 + dj = 1 + ok + if j = n + i = i + 1 + a[j][i] = k + k = k + 1 + di = 1 + dj = -1 + ok + if i = 1 + j = j + 1 + a[j][i] = k + k = k + 1 + di = 1 + dj = -1 + ok + i = i + di + j = j + dj + end + for p = 1 to n + for m = 1 to n + zigzag[p][m] = new qpushbutton(win1) { + x = 150+m*40 + y = 30 + p*40 + setgeometry(x,y,40,40) + settext(string(a[p][m])) + } + next + next + show() + } + exec() + }