diff --git a/Lang/ALGOL-68/00DESCRIPTION b/Lang/ALGOL-68/00DESCRIPTION index 663d797e6f..25aef9e3ca 100644 --- a/Lang/ALGOL-68/00DESCRIPTION +++ b/Lang/ALGOL-68/00DESCRIPTION @@ -29,21 +29,24 @@ The grammar for ALGOL 68 is officially in the two level, [[wp:Van Wijngaarden gr * [http://www.softwarepreservation.org/projects/ALGOL/book/Lindsey_van_der_Meulen-IItA68-Revised-SyntaxOnly.pdf/view Syntax Chart (Size 516.6 kB - File type application/pdf)] ==Resources== -* ALGOL BULLETIN - March 1959 to August 1988, in 52 issues[http://archive.computerhistory.org/resources/text/algol/algol_bulletin/] +* ALGOL BULLETIN - March 1959 to August 1988, in 52 issues[http://archive.computerhistory.org/resources/text/algol/algol_bulletin] * Algol68 mailinglist - December 2008 - algol68-user AT lists.sourceforge.net[https://lists.sourceforge.net/lists/listinfo/algol68-user] +* Algol68 group at linked: [http://www.linkedin.com/groups/Algol68-2333923] - includes various famous compiler composers. FYI: There are two online manual pages: -* [https://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/a68g-doc.pdf/download Algol 68G Manual - By Marcel van der Veer] +* [http://jmvdveer.home.xs4all.nl/algol68g.pdf Algol 68G Manual - By Marcel van der Veer] * [http://www.poenikatu.co.uk/algol68/ Programming Algol 68 Made Easy - Sian Mountbatten] Or - if you prefer a hardcopy - you can try and pick up a hard cover manual like "''Informal Introduction to Algol 68''" - by C. H. Lindsey & S. V. Vander Meulen. Be sure to get the 1977 edition: * [http://www.amazon.com/gp/offer-listing/0720405041/ref=dp_olp_used?ie=UTF8&condition=used www.amazon.com] - Aboout $119 * [http://search.barnesandnoble.com/Informal-Introduction-to-ALGOL-68/C-H-Lindsey/e/9780720407266/?itm=3&USRI=Informal+Introduction+to+Algol+68 barnesandnoble.com] - about $40 IItA68 is a beautiful book, and makes great "bedtime" reading... Highly recommended! +* '''NEW:''' [http://www.softwarepreservation.org/projects/ALGOL/book/Lindsey_van_der_Meulen-IItA68-Revised.pdf softwarepreservation.org has an on-line IItA68 PDF] ready for download. Editor modes: * [http://www.jemarch.net/a68-mode Emacs mode] for Algol 68 supporting syntax highlighting and context-sensitive indentation. -* [http://www.vim.org/scripts/script.php?script_id=1927 Vim script] providing support for syntax colouring. +* [http://www.vim.org/scripts/script.php?script_id=1927 Vim script] providing support for syntax highlighting. +* '''NEW:''' [http://qbnz.com/highlighter/demo.php GeSHi syntax highlighting] ==Status== * 20th December 1968 - '''ALGOL 68's''' Final Report was ratified by [http://en.wikipedia.org/wiki/UNESCO UNESCO's] [http://en.wikipedia.org/wiki/IFIP IFIP] working group 2.1 in Munich. diff --git a/Lang/ALGOL-68/Self-describing-numbers b/Lang/ALGOL-68/Self-describing-numbers new file mode 120000 index 0000000000..00f78a7986 --- /dev/null +++ b/Lang/ALGOL-68/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/Ada/Terminal-control-Inverse-video b/Lang/Ada/Terminal-control-Inverse-video new file mode 120000 index 0000000000..27040276cd --- /dev/null +++ b/Lang/Ada/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Ada \ No newline at end of file diff --git a/Lang/AppleScript/99-Bottles-of-Beer b/Lang/AppleScript/99-Bottles-of-Beer new file mode 120000 index 0000000000..732d2d0298 --- /dev/null +++ b/Lang/AppleScript/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Execute-Brain---- b/Lang/AppleScript/Execute-Brain---- new file mode 120000 index 0000000000..427d66782d --- /dev/null +++ b/Lang/AppleScript/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Digital-root b/Lang/Applesoft-BASIC/Digital-root new file mode 120000 index 0000000000..4c68db4997 --- /dev/null +++ b/Lang/Applesoft-BASIC/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Function-composition b/Lang/Applesoft-BASIC/Function-composition new file mode 120000 index 0000000000..49f8637b23 --- /dev/null +++ b/Lang/Applesoft-BASIC/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Named-parameters b/Lang/Applesoft-BASIC/Named-parameters new file mode 120000 index 0000000000..93ef811ac3 --- /dev/null +++ b/Lang/Applesoft-BASIC/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Variadic-function b/Lang/Applesoft-BASIC/Variadic-function new file mode 120000 index 0000000000..8eddce00ea --- /dev/null +++ b/Lang/Applesoft-BASIC/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/AutoHotkey/00DESCRIPTION b/Lang/AutoHotkey/00DESCRIPTION index 3c6c3eb60d..1651708ee5 100644 --- a/Lang/AutoHotkey/00DESCRIPTION +++ b/Lang/AutoHotkey/00DESCRIPTION @@ -3,13 +3,14 @@ |parampass=both |untyped=yes |tags=ahk, autohotkey -|site=http://www.autohotkey.com/ +|site=http://ahkscript.org/ |LCT=yes}}'''[[wp:AutoHotkey|AutoHotkey]]''' is an [[open source]] programming language for Microsoft [[Windows]]. ==Citations== -* [http://autohotkey.com/docs Documentation] -* [http://autohotkey.net/ AutoHotkey.net] - user projects and [http://www.autohotkey.net/#archives archives] -* [http://www.autohotkey.com/docs/scripts/ Script Showcase], [http://www.autohotkey.com/wiki/index.php?title=Script_Listing scripts: wiki] -* [http://www.autohotkey.com/forum/ Community forum] +* [http://ahkscript.org/docs Documentation] +* [http://ahkscript.org/archives/Download.html Download archives] +* [http://ahkscript.org/docs/scripts/ Script Showcase] +* [http://ahkscript.org/wiki AutoHotkey Wiki] +* [http://ahkscript.org/boards/ New Community forum], [http://www.autohotkey.com/forum/ Community forum] * [[wp:AutoHotkey|AutoHotkey on Wikipedia]] * [irc://irc.freenode.net/ahk #ahk] on [[Help:IRC|freenode]] ([http://webchat.freenode.net/?channels=%23ahk Web interface]) * [[:Category:AutoHotkey_Originated]] \ No newline at end of file diff --git a/Lang/AutoHotkey/Anagrams-Deranged-anagrams b/Lang/AutoHotkey/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..d4931a66dd --- /dev/null +++ b/Lang/AutoHotkey/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Animate-a-pendulum b/Lang/AutoHotkey/Animate-a-pendulum new file mode 120000 index 0000000000..a0d4a8fea4 --- /dev/null +++ b/Lang/AutoHotkey/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Atomic-updates b/Lang/AutoHotkey/Atomic-updates new file mode 120000 index 0000000000..b644569d66 --- /dev/null +++ b/Lang/AutoHotkey/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Averages-Mean-angle b/Lang/AutoHotkey/Averages-Mean-angle new file mode 120000 index 0000000000..c08c5322a0 --- /dev/null +++ b/Lang/AutoHotkey/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Averages-Mean-time-of-day b/Lang/AutoHotkey/Averages-Mean-time-of-day new file mode 120000 index 0000000000..8633b2d616 --- /dev/null +++ b/Lang/AutoHotkey/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Balanced-ternary b/Lang/AutoHotkey/Balanced-ternary new file mode 120000 index 0000000000..99f3fa9be0 --- /dev/null +++ b/Lang/AutoHotkey/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Bitwise-IO b/Lang/AutoHotkey/Bitwise-IO new file mode 120000 index 0000000000..ba731c224c --- /dev/null +++ b/Lang/AutoHotkey/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Bulls-and-cows-Player b/Lang/AutoHotkey/Bulls-and-cows-Player new file mode 120000 index 0000000000..00d5ccc67d --- /dev/null +++ b/Lang/AutoHotkey/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/CRC-32 b/Lang/AutoHotkey/CRC-32 new file mode 120000 index 0000000000..7c43bf797f --- /dev/null +++ b/Lang/AutoHotkey/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Calendar b/Lang/AutoHotkey/Calendar new file mode 120000 index 0000000000..d335097643 --- /dev/null +++ b/Lang/AutoHotkey/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Calendar---for-real-programmers b/Lang/AutoHotkey/Calendar---for-real-programmers new file mode 120000 index 0000000000..f36b0f14e6 --- /dev/null +++ b/Lang/AutoHotkey/Calendar---for-real-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-real-programmers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/DNS-query b/Lang/AutoHotkey/DNS-query new file mode 120000 index 0000000000..6252362d7e --- /dev/null +++ b/Lang/AutoHotkey/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Deal-cards-for-FreeCell b/Lang/AutoHotkey/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..7b338e0b50 --- /dev/null +++ b/Lang/AutoHotkey/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Death-Star b/Lang/AutoHotkey/Death-Star new file mode 120000 index 0000000000..de5a3e91ea --- /dev/null +++ b/Lang/AutoHotkey/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Deepcopy b/Lang/AutoHotkey/Deepcopy new file mode 120000 index 0000000000..5bb284fa23 --- /dev/null +++ b/Lang/AutoHotkey/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Digital-root b/Lang/AutoHotkey/Digital-root new file mode 120000 index 0000000000..b4410e7fd9 --- /dev/null +++ b/Lang/AutoHotkey/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Dining-philosophers b/Lang/AutoHotkey/Dining-philosophers new file mode 120000 index 0000000000..c888e730c0 --- /dev/null +++ b/Lang/AutoHotkey/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Draw-a-cuboid b/Lang/AutoHotkey/Draw-a-cuboid new file mode 120000 index 0000000000..f8c9084dec --- /dev/null +++ b/Lang/AutoHotkey/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Draw-a-sphere b/Lang/AutoHotkey/Draw-a-sphere new file mode 120000 index 0000000000..41e61c43b8 --- /dev/null +++ b/Lang/AutoHotkey/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Dutch-national-flag-problem b/Lang/AutoHotkey/Dutch-national-flag-problem new file mode 120000 index 0000000000..1b5db78797 --- /dev/null +++ b/Lang/AutoHotkey/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Empty-directory b/Lang/AutoHotkey/Empty-directory new file mode 120000 index 0000000000..4e550697fe --- /dev/null +++ b/Lang/AutoHotkey/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Entropy b/Lang/AutoHotkey/Entropy new file mode 120000 index 0000000000..0bbce32d90 --- /dev/null +++ b/Lang/AutoHotkey/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Equilibrium-index b/Lang/AutoHotkey/Equilibrium-index new file mode 120000 index 0000000000..a972e67616 --- /dev/null +++ b/Lang/AutoHotkey/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Fibonacci-n-step-number-sequences b/Lang/AutoHotkey/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..48e467af25 --- /dev/null +++ b/Lang/AutoHotkey/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Floyds-triangle b/Lang/AutoHotkey/Floyds-triangle new file mode 120000 index 0000000000..12332f0efd --- /dev/null +++ b/Lang/AutoHotkey/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Four-bit-adder b/Lang/AutoHotkey/Four-bit-adder new file mode 120000 index 0000000000..55e8d511d3 --- /dev/null +++ b/Lang/AutoHotkey/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Fractal-tree b/Lang/AutoHotkey/Fractal-tree new file mode 120000 index 0000000000..20cb484cf2 --- /dev/null +++ b/Lang/AutoHotkey/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/GUI-Maximum-window-dimensions b/Lang/AutoHotkey/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..c153ec1669 --- /dev/null +++ b/Lang/AutoHotkey/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Handle-a-signal b/Lang/AutoHotkey/Handle-a-signal new file mode 120000 index 0000000000..58b9bffc66 --- /dev/null +++ b/Lang/AutoHotkey/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Harshad-or-Niven-series b/Lang/AutoHotkey/Harshad-or-Niven-series new file mode 120000 index 0000000000..4ebe07e7ab --- /dev/null +++ b/Lang/AutoHotkey/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Haversine-formula b/Lang/AutoHotkey/Haversine-formula new file mode 120000 index 0000000000..4e2c97ff2c --- /dev/null +++ b/Lang/AutoHotkey/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/History-variables b/Lang/AutoHotkey/History-variables new file mode 120000 index 0000000000..1e24011320 --- /dev/null +++ b/Lang/AutoHotkey/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Hofstadter-Figure-Figure-sequences b/Lang/AutoHotkey/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..0d67386dc0 --- /dev/null +++ b/Lang/AutoHotkey/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Hofstadter-Q-sequence b/Lang/AutoHotkey/Hofstadter-Q-sequence new file mode 120000 index 0000000000..6e35e3b02a --- /dev/null +++ b/Lang/AutoHotkey/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Identity-matrix b/Lang/AutoHotkey/Identity-matrix new file mode 120000 index 0000000000..21b4179865 --- /dev/null +++ b/Lang/AutoHotkey/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Joystick-position b/Lang/AutoHotkey/Joystick-position new file mode 120000 index 0000000000..784f4718d4 --- /dev/null +++ b/Lang/AutoHotkey/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Kaprekar-numbers b/Lang/AutoHotkey/Kaprekar-numbers new file mode 120000 index 0000000000..8b9e46a9ba --- /dev/null +++ b/Lang/AutoHotkey/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Keyboard-input-Keypress-check b/Lang/AutoHotkey/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..ced00e3b90 --- /dev/null +++ b/Lang/AutoHotkey/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Knights-tour b/Lang/AutoHotkey/Knights-tour new file mode 120000 index 0000000000..8f772a5db9 --- /dev/null +++ b/Lang/AutoHotkey/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Largest-int-from-concatenated-ints b/Lang/AutoHotkey/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..0c7ecedfeb --- /dev/null +++ b/Lang/AutoHotkey/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Linear-congruential-generator b/Lang/AutoHotkey/Linear-congruential-generator new file mode 120000 index 0000000000..3bdd8d19b4 --- /dev/null +++ b/Lang/AutoHotkey/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Minesweeper-game b/Lang/AutoHotkey/Minesweeper-game new file mode 120000 index 0000000000..7bbb551701 --- /dev/null +++ b/Lang/AutoHotkey/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Modular-exponentiation b/Lang/AutoHotkey/Modular-exponentiation new file mode 120000 index 0000000000..32bd11119e --- /dev/null +++ b/Lang/AutoHotkey/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Modular-inverse b/Lang/AutoHotkey/Modular-inverse new file mode 120000 index 0000000000..8261163e50 --- /dev/null +++ b/Lang/AutoHotkey/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Multifactorial b/Lang/AutoHotkey/Multifactorial new file mode 120000 index 0000000000..22f7d9a8c9 --- /dev/null +++ b/Lang/AutoHotkey/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Multisplit b/Lang/AutoHotkey/Multisplit new file mode 120000 index 0000000000..ccca8b215f --- /dev/null +++ b/Lang/AutoHotkey/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Pi b/Lang/AutoHotkey/Pi new file mode 120000 index 0000000000..545946d060 --- /dev/null +++ b/Lang/AutoHotkey/Pi @@ -0,0 +1 @@ +../../Task/Pi/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Pig-the-dice-game b/Lang/AutoHotkey/Pig-the-dice-game new file mode 120000 index 0000000000..8f54b20903 --- /dev/null +++ b/Lang/AutoHotkey/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Pig-the-dice-game-Player b/Lang/AutoHotkey/Pig-the-dice-game-Player new file mode 120000 index 0000000000..e36f93a44f --- /dev/null +++ b/Lang/AutoHotkey/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Plot-coordinate-pairs b/Lang/AutoHotkey/Plot-coordinate-pairs new file mode 120000 index 0000000000..0a02a351e2 --- /dev/null +++ b/Lang/AutoHotkey/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Priority-queue b/Lang/AutoHotkey/Priority-queue new file mode 120000 index 0000000000..fdc421d3dd --- /dev/null +++ b/Lang/AutoHotkey/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Problem-of-Apollonius b/Lang/AutoHotkey/Problem-of-Apollonius new file mode 120000 index 0000000000..704dfd38b2 --- /dev/null +++ b/Lang/AutoHotkey/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Pythagorean-triples b/Lang/AutoHotkey/Pythagorean-triples new file mode 120000 index 0000000000..228f597111 --- /dev/null +++ b/Lang/AutoHotkey/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Quaternion-type b/Lang/AutoHotkey/Quaternion-type new file mode 120000 index 0000000000..00a1a5a068 --- /dev/null +++ b/Lang/AutoHotkey/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rate-counter b/Lang/AutoHotkey/Rate-counter new file mode 120000 index 0000000000..843eb4d580 --- /dev/null +++ b/Lang/AutoHotkey/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Record-sound b/Lang/AutoHotkey/Record-sound new file mode 120000 index 0000000000..907acfd4f1 --- /dev/null +++ b/Lang/AutoHotkey/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Respond-to-an-unknown-method-call b/Lang/AutoHotkey/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..b34a5aa3ed --- /dev/null +++ b/Lang/AutoHotkey/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/S-Expressions b/Lang/AutoHotkey/S-Expressions new file mode 120000 index 0000000000..ccb024b3b2 --- /dev/null +++ b/Lang/AutoHotkey/S-Expressions @@ -0,0 +1 @@ +../../Task/S-Expressions/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Safe-addition b/Lang/AutoHotkey/Safe-addition new file mode 120000 index 0000000000..8bc6de7f02 --- /dev/null +++ b/Lang/AutoHotkey/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Semordnilap b/Lang/AutoHotkey/Semordnilap new file mode 120000 index 0000000000..673958d128 --- /dev/null +++ b/Lang/AutoHotkey/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Set b/Lang/AutoHotkey/Set new file mode 120000 index 0000000000..aaab63e893 --- /dev/null +++ b/Lang/AutoHotkey/Set @@ -0,0 +1 @@ +../../Task/Set/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Set-puzzle b/Lang/AutoHotkey/Set-puzzle new file mode 120000 index 0000000000..2fc19747b3 --- /dev/null +++ b/Lang/AutoHotkey/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sierpinski-triangle-Graphical b/Lang/AutoHotkey/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..87565fc05a --- /dev/null +++ b/Lang/AutoHotkey/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Bead-sort b/Lang/AutoHotkey/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..35f802268b --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Radix-sort b/Lang/AutoHotkey/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..d999a70155 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Strand-sort b/Lang/AutoHotkey/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..5812d12875 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Stable-marriage-problem b/Lang/AutoHotkey/Stable-marriage-problem new file mode 120000 index 0000000000..7b7c4e039e --- /dev/null +++ b/Lang/AutoHotkey/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Subtractive-generator b/Lang/AutoHotkey/Subtractive-generator new file mode 120000 index 0000000000..3c3eaefd7e --- /dev/null +++ b/Lang/AutoHotkey/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Ternary-logic b/Lang/AutoHotkey/Ternary-logic new file mode 120000 index 0000000000..8e1df0f407 --- /dev/null +++ b/Lang/AutoHotkey/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Topswops b/Lang/AutoHotkey/Topswops new file mode 120000 index 0000000000..2c8f345fc7 --- /dev/null +++ b/Lang/AutoHotkey/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Truncatable-primes b/Lang/AutoHotkey/Truncatable-primes new file mode 120000 index 0000000000..af117a5671 --- /dev/null +++ b/Lang/AutoHotkey/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Truncate-a-file b/Lang/AutoHotkey/Truncate-a-file new file mode 120000 index 0000000000..4ea3f1f532 --- /dev/null +++ b/Lang/AutoHotkey/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Twelve-statements b/Lang/AutoHotkey/Twelve-statements new file mode 120000 index 0000000000..8028a03e0e --- /dev/null +++ b/Lang/AutoHotkey/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Universal-Turing-machine b/Lang/AutoHotkey/Universal-Turing-machine new file mode 120000 index 0000000000..7165d9d482 --- /dev/null +++ b/Lang/AutoHotkey/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Vampire-number b/Lang/AutoHotkey/Vampire-number new file mode 120000 index 0000000000..ebd9bc1f5f --- /dev/null +++ b/Lang/AutoHotkey/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Van-der-Corput-sequence b/Lang/AutoHotkey/Van-der-Corput-sequence new file mode 120000 index 0000000000..16a0332f33 --- /dev/null +++ b/Lang/AutoHotkey/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Vector-products b/Lang/AutoHotkey/Vector-products new file mode 120000 index 0000000000..4be128b633 --- /dev/null +++ b/Lang/AutoHotkey/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Wireworld b/Lang/AutoHotkey/Wireworld new file mode 120000 index 0000000000..41ebbb9395 --- /dev/null +++ b/Lang/AutoHotkey/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Write-to-Windows-event-log b/Lang/AutoHotkey/Write-to-Windows-event-log new file mode 120000 index 0000000000..c1697131df --- /dev/null +++ b/Lang/AutoHotkey/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Zeckendorf-number-representation b/Lang/AutoHotkey/Zeckendorf-number-representation new file mode 120000 index 0000000000..614176c764 --- /dev/null +++ b/Lang/AutoHotkey/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoIt/Loops-N-plus-one-half b/Lang/AutoIt/Loops-N-plus-one-half new file mode 120000 index 0000000000..a254611d04 --- /dev/null +++ b/Lang/AutoIt/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Primality-by-trial-division b/Lang/AutoIt/Primality-by-trial-division new file mode 120000 index 0000000000..fa5158a37e --- /dev/null +++ b/Lang/AutoIt/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/AutoIt \ No newline at end of file diff --git a/Lang/Batch-File/Execute-a-system-command b/Lang/Batch-File/Execute-a-system-command new file mode 120000 index 0000000000..970e2793c7 --- /dev/null +++ b/Lang/Batch-File/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/Exponentiation-operator b/Lang/Befunge/Exponentiation-operator new file mode 120000 index 0000000000..14d552c6b9 --- /dev/null +++ b/Lang/Befunge/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Befunge \ No newline at end of file diff --git a/Lang/Bracmat/Call-an-object-method b/Lang/Bracmat/Call-an-object-method new file mode 120000 index 0000000000..37efce211f --- /dev/null +++ b/Lang/Bracmat/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Classes b/Lang/Bracmat/Classes new file mode 120000 index 0000000000..19f8d36738 --- /dev/null +++ b/Lang/Bracmat/Classes @@ -0,0 +1 @@ +../../Task/Classes/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Enforced-immutability b/Lang/Bracmat/Enforced-immutability new file mode 120000 index 0000000000..9770f766f8 --- /dev/null +++ b/Lang/Bracmat/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Enumerations b/Lang/Bracmat/Enumerations new file mode 120000 index 0000000000..a0ef25f328 --- /dev/null +++ b/Lang/Bracmat/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Hamming-numbers b/Lang/Bracmat/Hamming-numbers new file mode 120000 index 0000000000..b7cae5c20a --- /dev/null +++ b/Lang/Bracmat/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Logical-operations b/Lang/Bracmat/Logical-operations new file mode 120000 index 0000000000..63c3bbc1bb --- /dev/null +++ b/Lang/Bracmat/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Named-parameters b/Lang/Bracmat/Named-parameters new file mode 120000 index 0000000000..44b443c7b1 --- /dev/null +++ b/Lang/Bracmat/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Scope-modifiers b/Lang/Bracmat/Scope-modifiers new file mode 120000 index 0000000000..de9a21dcb7 --- /dev/null +++ b/Lang/Bracmat/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sorting-algorithms-Quicksort b/Lang/Bracmat/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..4621135075 --- /dev/null +++ b/Lang/Bracmat/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Strip-comments-from-a-string b/Lang/Bracmat/Strip-comments-from-a-string new file mode 120000 index 0000000000..79e1b89bcd --- /dev/null +++ b/Lang/Bracmat/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Bracmat/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..9576f0a690 --- /dev/null +++ b/Lang/Bracmat/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Terminal-control-Display-an-extended-character b/Lang/Bracmat/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..bc9c8b601b --- /dev/null +++ b/Lang/Bracmat/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Truncate-a-file b/Lang/Bracmat/Truncate-a-file new file mode 120000 index 0000000000..e4060660aa --- /dev/null +++ b/Lang/Bracmat/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Bracmat \ No newline at end of file diff --git a/Lang/Brainf---/Sorting-algorithms-Sleep-sort b/Lang/Brainf---/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..e7c8214dac --- /dev/null +++ b/Lang/Brainf---/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Brainf--- \ No newline at end of file diff --git a/Lang/Brat/Averages-Simple-moving-average b/Lang/Brat/Averages-Simple-moving-average new file mode 120000 index 0000000000..9d96b0f7eb --- /dev/null +++ b/Lang/Brat/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Brat \ No newline at end of file diff --git a/Lang/C++/00DESCRIPTION b/Lang/C++/00DESCRIPTION index a40d989057..17ed7f4c2b 100644 --- a/Lang/C++/00DESCRIPTION +++ b/Lang/C++/00DESCRIPTION @@ -12,7 +12,7 @@ |LCT=yes |bnf=http://cpp.comsci.us/syntax/statement/index.html}}{{codepad}}{{allows|Network access}}{{allows|Database access }}{{allows|Concurrency}}{{provides|Run time polymorphism}}{{provides|Compile time polymorphism}}{{allows|Windowing UI}}{{allows|Graphics}}{{allows|OpenGL}}{{allows|Dynamic linking}}{{provides|File access}}{{allows|File system access}}{{provides|Objects}}{{allows|Signal handling}}{{provides|Mutable state}} -'''C++''' is named after the [[derived from::compatible with::C]] language, from which it is derived. C++ extends C into becoming an [[object-oriented language]]. However, unlike other object-oriented languages, it doesn't try to force you into [[object-oriented programming]], but is a multi-[[:Category:Programming Paradigms|paradigm]] language. Besides conventional [[procedural programming]] and object-oriented programming, it also supports [[generic programming]]. +'''C++''' is named after the [[derived from::compatible with::C]] language, from which it is derived. C++ extends C into an [[object-oriented language]]. However, unlike other object-oriented languages, it doesn't try to force you into [[object-oriented programming]], but is a multi-[[:Category:Programming Paradigms|paradigm]] language. Besides conventional [[procedural programming]] and object-oriented programming, it also supports [[generic programming]]. The ++ in C++ is some what of an inside joke, in that C++ is C with a Post Increment operator attached, thus C++ is C + 1; however, this interpretation has the flaw that post-increment increments the value ''after'' returning the value, so the post-increment expression still evaluates to the value before the increment. diff --git a/Lang/C++/Balanced-ternary b/Lang/C++/Balanced-ternary new file mode 120000 index 0000000000..1fe4f888a0 --- /dev/null +++ b/Lang/C++/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Pig-the-dice-game b/Lang/C-sharp/Pig-the-dice-game new file mode 120000 index 0000000000..234ef64280 --- /dev/null +++ b/Lang/C-sharp/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Rock-paper-scissors b/Lang/C-sharp/Rock-paper-scissors new file mode 120000 index 0000000000..2bc2de47dd --- /dev/null +++ b/Lang/C-sharp/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/C-sharp \ No newline at end of file diff --git a/Lang/COBOL/Binary-search b/Lang/COBOL/Binary-search new file mode 120000 index 0000000000..3133d98503 --- /dev/null +++ b/Lang/COBOL/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Call-an-object-method b/Lang/COBOL/Call-an-object-method new file mode 120000 index 0000000000..6a466f10ac --- /dev/null +++ b/Lang/COBOL/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Count-in-octal b/Lang/COBOL/Count-in-octal new file mode 120000 index 0000000000..255f1251d1 --- /dev/null +++ b/Lang/COBOL/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Day-of-the-week b/Lang/COBOL/Day-of-the-week new file mode 120000 index 0000000000..f8dab226d9 --- /dev/null +++ b/Lang/COBOL/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Detect-division-by-zero b/Lang/COBOL/Detect-division-by-zero new file mode 120000 index 0000000000..29b989b1ad --- /dev/null +++ b/Lang/COBOL/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/COBOL \ No newline at end of file diff --git a/Lang/COBOL/String-comparison b/Lang/COBOL/String-comparison new file mode 120000 index 0000000000..8198369c4f --- /dev/null +++ b/Lang/COBOL/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/COBOL \ No newline at end of file diff --git a/Lang/Caml/00DESCRIPTION b/Lang/Caml/00DESCRIPTION index d94f7c82fd..c6b60fb3cf 100644 --- a/Lang/Caml/00DESCRIPTION +++ b/Lang/Caml/00DESCRIPTION @@ -1,2 +1,5 @@ -{{language|Caml}}{{stub}} +{{stub}} +{{language|Caml +|site=http://caml.inria.fr/ +}} Relative of [[Standard ML]] that took a different path from the foundational [[derived from::ML]] language. It's derived language, [[OCaml]], is more well-known. \ No newline at end of file diff --git a/Lang/Clay/00DESCRIPTION b/Lang/Clay/00DESCRIPTION index 213e3b6f94..74ee3f5b05 100644 --- a/Lang/Clay/00DESCRIPTION +++ b/Lang/Clay/00DESCRIPTION @@ -1,6 +1,6 @@ {{stub}} {{language -|site=http://tachyon.in/clay/ +|site=http://claylabs.com/clay/ }} Clay is a systems programming language with whole program type propagation designed to support Generic programming. It supports Multiple dispatch and compile time meta-programming. It does not have garbage collection diff --git a/Lang/Clean/00DESCRIPTION b/Lang/Clean/00DESCRIPTION index f8df15c3ef..71569c45c2 100644 --- a/Lang/Clean/00DESCRIPTION +++ b/Lang/Clean/00DESCRIPTION @@ -1,4 +1,5 @@ {{language|Clean +|site=http://clean.cs.ru.nl |strength=strong |express=implicit |checking=static @@ -8,5 +9,4 @@ '''Clean''' is a pure and lazy functional [[programming language]]. ==Citations== -* [http://clean.cs.ru.nl/ The Clean web site] * [[wp:Clean_%28programming_language%29|Wikipedia:Clean (programming language)]] \ No newline at end of file diff --git a/Lang/Clojure/Dinesmans-multiple-dwelling-problem b/Lang/Clojure/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..1bb40b6c2e --- /dev/null +++ b/Lang/Clojure/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Empty-directory b/Lang/Clojure/Empty-directory new file mode 120000 index 0000000000..2acf7a1b98 --- /dev/null +++ b/Lang/Clojure/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Fibonacci-n-step-number-sequences b/Lang/Clojure/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..a5193cffe5 --- /dev/null +++ b/Lang/Clojure/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Include-a-file b/Lang/Clojure/Include-a-file new file mode 120000 index 0000000000..bff391d271 --- /dev/null +++ b/Lang/Clojure/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Inverted-index b/Lang/Clojure/Inverted-index new file mode 120000 index 0000000000..36ab2f01c4 --- /dev/null +++ b/Lang/Clojure/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Modular-exponentiation b/Lang/Clojure/Modular-exponentiation new file mode 120000 index 0000000000..0ccdd9e468 --- /dev/null +++ b/Lang/Clojure/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Subtractive-generator b/Lang/Clojure/Subtractive-generator new file mode 120000 index 0000000000..71ef48677f --- /dev/null +++ b/Lang/Clojure/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Universal-Turing-machine b/Lang/Clojure/Universal-Turing-machine new file mode 120000 index 0000000000..4ccee36928 --- /dev/null +++ b/Lang/Clojure/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Zebra-puzzle b/Lang/Clojure/Zebra-puzzle new file mode 120000 index 0000000000..d0e720e194 --- /dev/null +++ b/Lang/Clojure/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Zeckendorf-number-representation b/Lang/Clojure/Zeckendorf-number-representation new file mode 120000 index 0000000000..6858862001 --- /dev/null +++ b/Lang/Clojure/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/00DESCRIPTION b/Lang/CoffeeScript/00DESCRIPTION index 40c00d3966..08d9c62010 100644 --- a/Lang/CoffeeScript/00DESCRIPTION +++ b/Lang/CoffeeScript/00DESCRIPTION @@ -1,4 +1,7 @@ -{{language}}{{wikipedia|CoffeeScript}}'''CoffeeScript''' is a programming language that compiles to [[:Category:JavaScript|JavaScript]]. The language adds syntactic sugar inspired by [[:Category:Ruby|Ruby]] and [[:Category:Python|Python]] to enhance JavaScript's brevity and readability, as well as adding more sophisticated features like array comprehension and pattern matching. +{{language| +site=http://coffeescript.org +}} +{{wikipedia|CoffeeScript}}'''CoffeeScript''' is a programming language that compiles to [[:Category:JavaScript|JavaScript]]. The language adds syntactic sugar inspired by [[:Category:Ruby|Ruby]] and [[:Category:Python|Python]] to enhance JavaScript's brevity and readability, as well as adding more sophisticated features like array comprehension and pattern matching. With 4000+ watchers and 300+ forks (as of December 2011), CoffeeScript is ranked as one of the "most interesting" projects on Github. [http://github.com/repositories] The language has a relatively large following in the Ruby community, and has been used in production by [http://thinkvitamin.com/mobile/new-rails-like-framework-from-37signals-for-html5-mobile-apps/ 37signals]. Ruby on Rails began to include CoffeeScript in its asset pipeline in Rails version 3.1 (see [http://www.rubyinside.com/rails-3-1-adopts-coffeescript-jquery-sass-and-controversy-4669.html]). @@ -48,7 +51,6 @@ The CoffeeScript compiler has been written in CoffeeScript since version 0.5, an # Ashkenas, Jeremy. "[http://github.com/jashkenas/coffee-script/issues/830 The Plan for 1.0]", Github issue tracker, Nov 4, 2010. == External links == -* [http://coffeescript.org CoffeeScript.org] - Official site] * [http://github.com/jashkenas/coffee-script/ GitHub repository] * [http://twitter.com/coffeescript @CoffeeScript] - Twitter feed * [[wp:coffeescript|Wikipedia Entry]] diff --git a/Lang/CoffeeScript/Bitmap-Bresenhams-line-algorithm b/Lang/CoffeeScript/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..5dbddaf4c6 --- /dev/null +++ b/Lang/CoffeeScript/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Entropy b/Lang/CoffeeScript/Entropy new file mode 120000 index 0000000000..dd4ba0d681 --- /dev/null +++ b/Lang/CoffeeScript/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Program-name b/Lang/CoffeeScript/Program-name new file mode 120000 index 0000000000..506230b32b --- /dev/null +++ b/Lang/CoffeeScript/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/CoffeeScript \ No newline at end of file diff --git a/Lang/Common-Lisp/Digital-root b/Lang/Common-Lisp/Digital-root new file mode 120000 index 0000000000..d101188285 --- /dev/null +++ b/Lang/Common-Lisp/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Empty-directory b/Lang/Common-Lisp/Empty-directory new file mode 120000 index 0000000000..a7323fbf67 --- /dev/null +++ b/Lang/Common-Lisp/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Include-a-file b/Lang/Common-Lisp/Include-a-file new file mode 120000 index 0000000000..a829867e3c --- /dev/null +++ b/Lang/Common-Lisp/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/MD4 b/Lang/Common-Lisp/MD4 new file mode 120000 index 0000000000..5ddb1e6700 --- /dev/null +++ b/Lang/Common-Lisp/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Parsing-RPN-calculator-algorithm b/Lang/Common-Lisp/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..b3c1629170 --- /dev/null +++ b/Lang/Common-Lisp/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/RIPEMD-160 b/Lang/Common-Lisp/RIPEMD-160 new file mode 120000 index 0000000000..47fab82ba8 --- /dev/null +++ b/Lang/Common-Lisp/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/SHA-256 b/Lang/Common-Lisp/SHA-256 new file mode 120000 index 0000000000..d6c3d1e04e --- /dev/null +++ b/Lang/Common-Lisp/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Set-consolidation b/Lang/Common-Lisp/Set-consolidation new file mode 120000 index 0000000000..64818e42f7 --- /dev/null +++ b/Lang/Common-Lisp/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Strip-comments-from-a-string b/Lang/Common-Lisp/Strip-comments-from-a-string new file mode 120000 index 0000000000..9ac29ea43b --- /dev/null +++ b/Lang/Common-Lisp/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Common-Lisp/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..aeba356cdc --- /dev/null +++ b/Lang/Common-Lisp/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Substring-Top-and-tail b/Lang/Common-Lisp/Substring-Top-and-tail new file mode 120000 index 0000000000..140209d4e6 --- /dev/null +++ b/Lang/Common-Lisp/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Common-Lisp \ No newline at end of file diff --git a/Lang/Coq/00DESCRIPTION b/Lang/Coq/00DESCRIPTION index f366dcaecc..3a03214cba 100644 --- a/Lang/Coq/00DESCRIPTION +++ b/Lang/Coq/00DESCRIPTION @@ -1,4 +1,7 @@ -{{language|Coq}}In computer science, Coq is a proof assistant application. It allows the expression of mathematical assertions, mechanically checks proofs of these assertions, helps to find formal proofs, and extracts a certified program from the constructive proof of its formal specification. Coq works within the theory of the calculus of inductive constructions, a derivative of the calculus of constructions. Coq is not an automated [[wp:Theorem_prover|theorem prover]] but includes automatic theorem proving tactics and various decision procedures. +{{language|Coq +|site=http://coq.inria.fr +}} +In computer science, Coq is a proof assistant application. It allows the expression of mathematical assertions, mechanically checks proofs of these assertions, helps to find formal proofs, and extracts a certified program from the constructive proof of its formal specification. Coq works within the theory of the calculus of inductive constructions, a derivative of the calculus of constructions. Coq is not an automated [[wp:Theorem_prover|theorem prover]] but includes automatic theorem proving tactics and various decision procedures. ==Citations== * [[wp:Coq|Coq]] diff --git a/Lang/Coq/100-doors b/Lang/Coq/100-doors new file mode 120000 index 0000000000..fd39f903ef --- /dev/null +++ b/Lang/Coq/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Coq \ No newline at end of file diff --git a/Lang/D/Bitcoin-address-validation b/Lang/D/Bitcoin-address-validation new file mode 120000 index 0000000000..688ed805c6 --- /dev/null +++ b/Lang/D/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/D \ No newline at end of file diff --git a/Lang/D/Rendezvous b/Lang/D/Rendezvous new file mode 120000 index 0000000000..7a9ac44daf --- /dev/null +++ b/Lang/D/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/D \ No newline at end of file diff --git a/Lang/D/SHA-256 b/Lang/D/SHA-256 new file mode 120000 index 0000000000..2aa4c30c6e --- /dev/null +++ b/Lang/D/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/D \ No newline at end of file diff --git a/Lang/D/Use-another-language-to-call-a-function b/Lang/D/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..4de62592fd --- /dev/null +++ b/Lang/D/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/D \ No newline at end of file diff --git a/Lang/Dart/Averages-Arithmetic-mean b/Lang/Dart/Averages-Arithmetic-mean new file mode 120000 index 0000000000..b7027bfea6 --- /dev/null +++ b/Lang/Dart/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Dart \ No newline at end of file diff --git a/Lang/Dart/Dot-product b/Lang/Dart/Dot-product new file mode 120000 index 0000000000..2cae4cd216 --- /dev/null +++ b/Lang/Dart/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Dart \ No newline at end of file diff --git a/Lang/Dart/Empty-string b/Lang/Dart/Empty-string new file mode 120000 index 0000000000..021292b420 --- /dev/null +++ b/Lang/Dart/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Dart \ No newline at end of file diff --git a/Lang/Dart/HTTP b/Lang/Dart/HTTP new file mode 120000 index 0000000000..14342e8d35 --- /dev/null +++ b/Lang/Dart/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Dart \ No newline at end of file diff --git a/Lang/Dart/Hello-world-Web-server b/Lang/Dart/Hello-world-Web-server new file mode 120000 index 0000000000..6e5f95b7bb --- /dev/null +++ b/Lang/Dart/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Dart \ No newline at end of file diff --git a/Lang/Dart/Perfect-numbers b/Lang/Dart/Perfect-numbers new file mode 120000 index 0000000000..c1ec028a78 --- /dev/null +++ b/Lang/Dart/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Dart \ No newline at end of file diff --git a/Lang/Dart/Regular-expressions b/Lang/Dart/Regular-expressions new file mode 120000 index 0000000000..0cdd9a85d0 --- /dev/null +++ b/Lang/Dart/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Dart \ No newline at end of file diff --git a/Lang/Dart/Set b/Lang/Dart/Set new file mode 120000 index 0000000000..66fc475d01 --- /dev/null +++ b/Lang/Dart/Set @@ -0,0 +1 @@ +../../Task/Set/Dart \ No newline at end of file diff --git a/Lang/Deja-Vu/Count-occurrences-of-a-substring b/Lang/Deja-Vu/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..d79b559698 --- /dev/null +++ b/Lang/Deja-Vu/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Increment-a-numerical-string b/Lang/Deja-Vu/Increment-a-numerical-string new file mode 120000 index 0000000000..7354670019 --- /dev/null +++ b/Lang/Deja-Vu/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Logical-operations b/Lang/Deja-Vu/Logical-operations new file mode 120000 index 0000000000..d6fdc9db84 --- /dev/null +++ b/Lang/Deja-Vu/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/One-dimensional-cellular-automata b/Lang/Deja-Vu/One-dimensional-cellular-automata new file mode 120000 index 0000000000..7491ced43a --- /dev/null +++ b/Lang/Deja-Vu/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Deja-Vu \ No newline at end of file diff --git a/Lang/Dylan/00DESCRIPTION b/Lang/Dylan/00DESCRIPTION index 6eb93e5d6a..959e41da01 100644 --- a/Lang/Dylan/00DESCRIPTION +++ b/Lang/Dylan/00DESCRIPTION @@ -5,7 +5,7 @@ |checking=both |gc=yes |LCT=yes -|site=http://www.opendylan.org/}} +|site=http://opendylan.org/}} {{language programming paradigm|functional}} {{language programming paradigm|procedural}} {{language programming paradigm|imperative}} diff --git a/Lang/E/00DESCRIPTION b/Lang/E/00DESCRIPTION index b614401b9f..99bab24e45 100644 --- a/Lang/E/00DESCRIPTION +++ b/Lang/E/00DESCRIPTION @@ -1,4 +1,5 @@ {{language +|site=http://www.erights.org |strength=strong |safety=safe |express=explicit @@ -11,7 +12,7 @@ }} E is a programming language designed around object-capability security and event-loop concurrency, in order to support creation of highly robust and secure programs. -Using the [[Java]] implementation of E, Java libraries can be used from E code, and its REPL (e.g. [[Creating a Window]]). +Using the [[Java]] implementation of E, Java libraries can be used from E code, and its REPL (e.g. [[Creating a Window#E|Creating a Window]]). ==Trying E== @@ -43,6 +44,4 @@ This is both the format of a transcript at an E [[REPL]], and the format employe To try out these examples for yourself, just install E and run the rune command to get the “?” prompt. Multi-line input is automatic for unbalanced brackets/parens and can be indicated in other cases by a trailing backslash. ==See Also== - -* [http://www.erights.org erights.org] — Home page of E * [http://wiki.erights.org E Wiki] \ No newline at end of file diff --git a/Lang/Elan/00DESCRIPTION b/Lang/Elan/00DESCRIPTION index 0fa3ef820b..5ec4d830b4 100644 --- a/Lang/Elan/00DESCRIPTION +++ b/Lang/Elan/00DESCRIPTION @@ -1,4 +1,2 @@ -{{language -|site=http://www.loria.fr/equipes/protheo/SOFTWARES/ELAN/elan.html -}} +{{language}} The ELAN system provides an environment for specifying and prototyping deduction systems in a language based on rules controlled by strategies. Its purpose is to support the design of theorem provers, logic programming languages, constraints solvers and decision procedures and to offer a modular framework for studying their combination. \ No newline at end of file diff --git a/Lang/Elena/00DESCRIPTION b/Lang/Elena/00DESCRIPTION index 015c207823..a1372a9eac 100644 --- a/Lang/Elena/00DESCRIPTION +++ b/Lang/Elena/00DESCRIPTION @@ -1,4 +1,5 @@ {{language|Elena +|site=http://elenalang.sourceforge.net |exec=bytecode |strength=strong |safety=safe diff --git a/Lang/Elixir/00DESCRIPTION b/Lang/Elixir/00DESCRIPTION index 4d3d27c049..dea53dfdd5 100644 --- a/Lang/Elixir/00DESCRIPTION +++ b/Lang/Elixir/00DESCRIPTION @@ -1 +1,3 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language +|site=http://elixir-lang.org}} \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Ethiopian-multiplication b/Lang/Emacs-Lisp/Ethiopian-multiplication new file mode 120000 index 0000000000..a0346f7ec2 --- /dev/null +++ b/Lang/Emacs-Lisp/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Epigram/00DESCRIPTION b/Lang/Epigram/00DESCRIPTION index eb6dcdcef9..7f4196f576 100644 --- a/Lang/Epigram/00DESCRIPTION +++ b/Lang/Epigram/00DESCRIPTION @@ -1,3 +1,2 @@ -{{stub}}{{language|Epigram -|site=http://www.e-pig.org/darcs/Pig09/web/}} +{{stub}}{{language|Epigram}} Epigram 2 is an experimental dependently typed functional programming language. \ No newline at end of file diff --git a/Lang/Erlang/00DESCRIPTION b/Lang/Erlang/00DESCRIPTION index 037fd71f00..ceb0a08b89 100644 --- a/Lang/Erlang/00DESCRIPTION +++ b/Lang/Erlang/00DESCRIPTION @@ -1,11 +1,13 @@ {{language|Erlang +|site=http://www.erlang.org |exec=bytecode |strength=strong |safety=safe |express=implicit |checking=dynamic |gc=yes -|LCT=yes}} +|LCT=yes +|tags=erlang}} {{language programming paradigm|functional}} {{language programming paradigm|concurrent}} {{language programming paradigm|distributed}} diff --git a/Lang/Erlang/Forward-difference b/Lang/Erlang/Forward-difference new file mode 120000 index 0000000000..4d80c48d11 --- /dev/null +++ b/Lang/Erlang/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Parsing-RPN-calculator-algorithm b/Lang/Erlang/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..d8fc046704 --- /dev/null +++ b/Lang/Erlang/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Euler-Math-Toolbox/00DESCRIPTION b/Lang/Euler-Math-Toolbox/00DESCRIPTION index 114c13967e..e69de29bb2 100644 --- a/Lang/Euler-Math-Toolbox/00DESCRIPTION +++ b/Lang/Euler-Math-Toolbox/00DESCRIPTION @@ -1,6 +0,0 @@ -{{language -|site=http://www.euler-math-toolbox.de/ -}} -The Euler Mathematical Toolbox is a powerful, versatile, mature software for numerical and symbolic computations written and maintained by R. Grothmann, associate professor of mathmetics at the University of Eichstätt. Euler is similar to [[MATLAB]], but has an own style, and a slightly different syntax. Symbolic mathematics is supported in Euler using the open algebra system [[Maxima]]. It contains a matrix language, a graphical notebook style interface, a plot window and can handle real, complex and interval numbers, vectors and matrices, it can produce 2D/3D plots - -[[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/F/00DESCRIPTION b/Lang/F/00DESCRIPTION index e836ff79bb..2f3dce64c7 100644 --- a/Lang/F/00DESCRIPTION +++ b/Lang/F/00DESCRIPTION @@ -1,9 +1,10 @@
Due to technical limitations, the link [[F Sharp|F#]] points to here in some articles. To correct this issue, replace [[F#]] with [[F Sharp|F#]], and {{header|F#}} with {{header|F Sharp|F#}}.
{{language +|site=http://www.fortran.com/F |hopl id=3460 -}}F is a structured, array based language created by Walter Brainerd, Richard Hendrickson, and David Epstein. +}} +F is a structured, array based language created by Walter Brainerd, Richard Hendrickson, and David Epstein. It is a subset of [[Fortran|Fortran 95]], designed to be simpler than Fortran and suitable for teaching. ==External Links== -* [http://www.fortran.com/F/ F Programming Language Homepage] * [[wp:F_programming_language|Wikipedia: F Programming Language]] \ No newline at end of file diff --git a/Lang/FALSE/00DESCRIPTION b/Lang/FALSE/00DESCRIPTION index 89f23d6d64..b2071d8d1c 100644 --- a/Lang/FALSE/00DESCRIPTION +++ b/Lang/FALSE/00DESCRIPTION @@ -1,4 +1,5 @@ -{{language|FALSE}} +{{language|FALSE +|site=http://strlen.com/false-language}} '''FALSE''' is a [[Forth]]-like esoteric programming language invented by Wouter van Oortmerssen in 1993, originally written for the Amiga to see how small one could make a compiler (1K) for a language that was still powerful enough to write applications. FALSE directly inspired the creation of [[Brainf***]] and [[Befunge]]. * [[eso:FALSE|FALSE on Esolangs]] diff --git a/Lang/Felix/00DESCRIPTION b/Lang/Felix/00DESCRIPTION index 25d8b5762b..0dd7ee6380 100644 --- a/Lang/Felix/00DESCRIPTION +++ b/Lang/Felix/00DESCRIPTION @@ -5,4 +5,4 @@ Felix is an advanced Algol like procedural programming language with a strong functional subsystem. It features ML style static typing, first class functions, pattern matching, garbage collection, polymorphism, and has built in support for high performance microthreading, regular expressions and context free parsing. ==See also== -*[[wp:Felix_(programming_language)|Wikipedia: Felix Pgramming Lguage]] \ No newline at end of file +*[[wp:Felix_(programming_language)|Felix on Wikipedia]] \ No newline at end of file diff --git a/Lang/Fexl/00DESCRIPTION b/Lang/Fexl/00DESCRIPTION index 05630421ff..51d6346397 100644 --- a/Lang/Fexl/00DESCRIPTION +++ b/Lang/Fexl/00DESCRIPTION @@ -1,4 +1,5 @@ -{{language}} +{{language +|site=http://fexl.com}} [http://fexl.com Fexl] is a [[functional programming]] language designed to be compact, efficient, and customizable in embedded environments. Its implementation aims to be the thinnest possible functional programming layer built on top of [[C]]. Fexl has no keywords, so whenever you see a symbol in a Fexl program, that symbol always refers to a function. diff --git a/Lang/Forth/Gamma-function b/Lang/Forth/Gamma-function new file mode 120000 index 0000000000..c598422753 --- /dev/null +++ b/Lang/Forth/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Forth \ No newline at end of file diff --git a/Lang/Forth/Holidays-related-to-Easter b/Lang/Forth/Holidays-related-to-Easter new file mode 120000 index 0000000000..81ad21ea3d --- /dev/null +++ b/Lang/Forth/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Forth \ No newline at end of file diff --git a/Lang/Forth/Trabb-Pardo-Knuth-algorithm b/Lang/Forth/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..727409bd85 --- /dev/null +++ b/Lang/Forth/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Forth \ No newline at end of file diff --git a/Lang/Forth/Zeckendorf-number-representation b/Lang/Forth/Zeckendorf-number-representation new file mode 120000 index 0000000000..3440a60c57 --- /dev/null +++ b/Lang/Forth/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Forth \ No newline at end of file diff --git a/Lang/Fortran/00DESCRIPTION b/Lang/Fortran/00DESCRIPTION index 31b9973756..bfe7649547 100644 --- a/Lang/Fortran/00DESCRIPTION +++ b/Lang/Fortran/00DESCRIPTION @@ -5,6 +5,7 @@ |checking=static |gc=no |LCT=yes +|tags=fortran |bnf=http://fortran.comsci.us/syntax/statement/index.html}}{{language programming paradigm|Imperative}} Fortran is the oldest programming language still in widespread use. It was given substantial rework in the Fortran 90 standard. By convention, versions before Fortran 90 are spelled with all uppercase letters (e.g. FORTRAN 66, FORTRAN 77), while starting with Fortran 90, the mixed case spelling is used (i.e. Fortran 90, Fortran 95 etc.). diff --git a/Lang/Fortran/Balanced-brackets b/Lang/Fortran/Balanced-brackets new file mode 120000 index 0000000000..c4506a1e88 --- /dev/null +++ b/Lang/Fortran/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Cholesky-decomposition b/Lang/Fortran/Cholesky-decomposition new file mode 120000 index 0000000000..f314ace313 --- /dev/null +++ b/Lang/Fortran/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Fortran \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/00DESCRIPTION b/Lang/Free-Pascal-Lazarus/00DESCRIPTION index e0ac540fa7..e69de29bb2 100644 --- a/Lang/Free-Pascal-Lazarus/00DESCRIPTION +++ b/Lang/Free-Pascal-Lazarus/00DESCRIPTION @@ -1,3 +0,0 @@ -{{language|Free Pascal / Lazarus -|site=http://wiki.lazarus.freepascal.org/ -}} \ No newline at end of file diff --git a/Lang/Frink/00DESCRIPTION b/Lang/Frink/00DESCRIPTION index 9297297384..9031493c2c 100644 --- a/Lang/Frink/00DESCRIPTION +++ b/Lang/Frink/00DESCRIPTION @@ -3,7 +3,7 @@ |gc=yes }}[[runs on vm::java virtual machine| ]] -Frink is a programming language designed and implemented by Alan Eliasen. It is designed to be a general-purpose, multi-paradigm language. +Frink is a programming language designed and implemented by Alan Eliasen. It is designed to be a general-purpose, relatively concise, multi-paradigm language. One of the most obvious differentiating features of Frink is that it tracks units of measure (feet, meters, tons, watts, etc.) through all calculations, helping ensure that physical calculations make sense. Frink understands how different units of measure interrelate, such as a length cubed is a volume, or power multiplied by time is energy. Different units of measure can be mixed in calculations, and Frink automatically ensures that the calculations lead to a result with the expected dimensions. It attempts to follow standard mathematical notation as closely as possible, and makes a strong effort to do the right thing with numeric types. @@ -11,7 +11,7 @@ Frink runs on the JVM and on Android, and is available in the Android Market. ==See Also== -*[http://futureboy.homeip.net/frinkdocs/ Frink] homepage, including full documentation. +*[http://futureboy.us/frinkdocs/ Frink] homepage, including full documentation. *[http://futureboy.us/frink/ Frink web-based interface] *[http://futureboy.us/frinkdocs/faq.html Frequently Asked Questions] *[http://futureboy.us/frinkdocs/fspdocs.html Frink Server Pages Documentation] diff --git a/Lang/Frink/100-doors b/Lang/Frink/100-doors new file mode 120000 index 0000000000..2b1366a8ec --- /dev/null +++ b/Lang/Frink/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Frink \ No newline at end of file diff --git a/Lang/Frink/A+B b/Lang/Frink/A+B new file mode 120000 index 0000000000..c6aaa2d35e --- /dev/null +++ b/Lang/Frink/A+B @@ -0,0 +1 @@ +../../Task/A+B/Frink \ No newline at end of file diff --git a/Lang/Frink/Apply-a-callback-to-an-array b/Lang/Frink/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..0961386c29 --- /dev/null +++ b/Lang/Frink/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Frink \ No newline at end of file diff --git a/Lang/Frink/Arithmetic-Complex b/Lang/Frink/Arithmetic-Complex new file mode 120000 index 0000000000..64e43cdb49 --- /dev/null +++ b/Lang/Frink/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Frink \ No newline at end of file diff --git a/Lang/Frink/Array-concatenation b/Lang/Frink/Array-concatenation new file mode 120000 index 0000000000..c9ed7d8819 --- /dev/null +++ b/Lang/Frink/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Frink \ No newline at end of file diff --git a/Lang/Frink/Arrays b/Lang/Frink/Arrays new file mode 120000 index 0000000000..d84a3a50bb --- /dev/null +++ b/Lang/Frink/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Frink \ No newline at end of file diff --git a/Lang/Frink/Averages-Arithmetic-mean b/Lang/Frink/Averages-Arithmetic-mean new file mode 120000 index 0000000000..ba4235e43c --- /dev/null +++ b/Lang/Frink/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Frink \ No newline at end of file diff --git a/Lang/Frink/Command-line-arguments b/Lang/Frink/Command-line-arguments new file mode 120000 index 0000000000..24ee0321c4 --- /dev/null +++ b/Lang/Frink/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Frink \ No newline at end of file diff --git a/Lang/Frink/Comments b/Lang/Frink/Comments new file mode 120000 index 0000000000..95b5ce342d --- /dev/null +++ b/Lang/Frink/Comments @@ -0,0 +1 @@ +../../Task/Comments/Frink \ No newline at end of file diff --git a/Lang/Frink/Create-a-two-dimensional-array-at-runtime b/Lang/Frink/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..855c2465e8 --- /dev/null +++ b/Lang/Frink/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Frink \ No newline at end of file diff --git a/Lang/Frink/Factorial b/Lang/Frink/Factorial new file mode 120000 index 0000000000..649225c6d1 --- /dev/null +++ b/Lang/Frink/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Frink \ No newline at end of file diff --git a/Lang/Frink/Fibonacci-sequence b/Lang/Frink/Fibonacci-sequence new file mode 120000 index 0000000000..df3ccb3ecb --- /dev/null +++ b/Lang/Frink/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Frink \ No newline at end of file diff --git a/Lang/Frink/File-IO b/Lang/Frink/File-IO new file mode 120000 index 0000000000..e537c87d39 --- /dev/null +++ b/Lang/Frink/File-IO @@ -0,0 +1 @@ +../../Task/File-IO/Frink \ No newline at end of file diff --git a/Lang/Frink/Filter b/Lang/Frink/Filter new file mode 120000 index 0000000000..fd3601d1f9 --- /dev/null +++ b/Lang/Frink/Filter @@ -0,0 +1 @@ +../../Task/Filter/Frink \ No newline at end of file diff --git a/Lang/Frink/HTTP b/Lang/Frink/HTTP new file mode 120000 index 0000000000..ee550035bb --- /dev/null +++ b/Lang/Frink/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Frink \ No newline at end of file diff --git a/Lang/Frink/HTTPS b/Lang/Frink/HTTPS new file mode 120000 index 0000000000..1b79a3bb25 --- /dev/null +++ b/Lang/Frink/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Frink \ No newline at end of file diff --git a/Lang/Frink/Harshad-or-Niven-series b/Lang/Frink/Harshad-or-Niven-series new file mode 120000 index 0000000000..10566fd2cc --- /dev/null +++ b/Lang/Frink/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Frink \ No newline at end of file diff --git a/Lang/Frink/Hash-from-two-arrays b/Lang/Frink/Hash-from-two-arrays new file mode 120000 index 0000000000..2c139a9936 --- /dev/null +++ b/Lang/Frink/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Frink \ No newline at end of file diff --git a/Lang/Frink/Increment-a-numerical-string b/Lang/Frink/Increment-a-numerical-string new file mode 120000 index 0000000000..069680415c --- /dev/null +++ b/Lang/Frink/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Frink \ No newline at end of file diff --git a/Lang/Frink/Integer-sequence b/Lang/Frink/Integer-sequence new file mode 120000 index 0000000000..9b53b6238e --- /dev/null +++ b/Lang/Frink/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Frink \ No newline at end of file diff --git a/Lang/Frink/Loops-Downward-for b/Lang/Frink/Loops-Downward-for new file mode 120000 index 0000000000..a0f719c5f3 --- /dev/null +++ b/Lang/Frink/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Frink \ No newline at end of file diff --git a/Lang/Frink/Loops-For b/Lang/Frink/Loops-For new file mode 120000 index 0000000000..903ec687bc --- /dev/null +++ b/Lang/Frink/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Frink \ No newline at end of file diff --git a/Lang/Frink/Loops-Foreach b/Lang/Frink/Loops-Foreach new file mode 120000 index 0000000000..52deeb86cd --- /dev/null +++ b/Lang/Frink/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Frink \ No newline at end of file diff --git a/Lang/Frink/Loops-Infinite b/Lang/Frink/Loops-Infinite new file mode 120000 index 0000000000..c89bb93396 --- /dev/null +++ b/Lang/Frink/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Frink \ No newline at end of file diff --git a/Lang/Frink/Palindrome-detection b/Lang/Frink/Palindrome-detection new file mode 120000 index 0000000000..f871791e1e --- /dev/null +++ b/Lang/Frink/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Frink \ No newline at end of file diff --git a/Lang/Frink/Quine b/Lang/Frink/Quine new file mode 120000 index 0000000000..74da7b5c41 --- /dev/null +++ b/Lang/Frink/Quine @@ -0,0 +1 @@ +../../Task/Quine/Frink \ No newline at end of file diff --git a/Lang/Frink/Real-constants-and-functions b/Lang/Frink/Real-constants-and-functions new file mode 120000 index 0000000000..0ab43cf5b5 --- /dev/null +++ b/Lang/Frink/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Frink \ No newline at end of file diff --git a/Lang/Frink/Remove-duplicate-elements b/Lang/Frink/Remove-duplicate-elements new file mode 120000 index 0000000000..c80b9d3220 --- /dev/null +++ b/Lang/Frink/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Frink \ No newline at end of file diff --git a/Lang/Frink/String-case b/Lang/Frink/String-case new file mode 120000 index 0000000000..02dced3a37 --- /dev/null +++ b/Lang/Frink/String-case @@ -0,0 +1 @@ +../../Task/String-case/Frink \ No newline at end of file diff --git a/Lang/Frink/String-concatenation b/Lang/Frink/String-concatenation new file mode 120000 index 0000000000..af96b48b1b --- /dev/null +++ b/Lang/Frink/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Frink \ No newline at end of file diff --git a/Lang/Frink/Sum-and-product-of-an-array b/Lang/Frink/Sum-and-product-of-an-array new file mode 120000 index 0000000000..675e1ee0b5 --- /dev/null +++ b/Lang/Frink/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Frink \ No newline at end of file diff --git a/Lang/Frink/Sum-of-squares b/Lang/Frink/Sum-of-squares new file mode 120000 index 0000000000..2bb81ad634 --- /dev/null +++ b/Lang/Frink/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Frink \ No newline at end of file diff --git a/Lang/Frink/Tokenize-a-string b/Lang/Frink/Tokenize-a-string new file mode 120000 index 0000000000..79dd191d86 --- /dev/null +++ b/Lang/Frink/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Frink \ No newline at end of file diff --git a/Lang/GLBasic/00DESCRIPTION b/Lang/GLBasic/00DESCRIPTION index 4d3d27c049..3efaae357f 100644 --- a/Lang/GLBasic/00DESCRIPTION +++ b/Lang/GLBasic/00DESCRIPTION @@ -1 +1,3 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language +|site=http://www.glbasic.com}} \ No newline at end of file diff --git a/Lang/Gdl/00DESCRIPTION b/Lang/Gdl/00DESCRIPTION index 4d3d27c049..e69de29bb2 100644 --- a/Lang/Gdl/00DESCRIPTION +++ b/Lang/Gdl/00DESCRIPTION @@ -1 +0,0 @@ -{{stub}}{{language}} \ No newline at end of file diff --git a/Lang/Gecho/00DESCRIPTION b/Lang/Gecho/00DESCRIPTION index 4d3d27c049..1ad0a6c8cd 100644 --- a/Lang/Gecho/00DESCRIPTION +++ b/Lang/Gecho/00DESCRIPTION @@ -1 +1,4 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language}} +From its [https://github.com/tekknolagi/gecho GitHub repo]: +
gecho is somewhat similar to FORTH. It will probably become less so as it grows.
\ No newline at end of file diff --git a/Lang/Go/Table-creation-Postal-addresses b/Lang/Go/Table-creation-Postal-addresses new file mode 120000 index 0000000000..a6709beb88 --- /dev/null +++ b/Lang/Go/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Go \ No newline at end of file diff --git a/Lang/Groovy/GUI-Maximum-window-dimensions b/Lang/Groovy/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..737789bfcb --- /dev/null +++ b/Lang/Groovy/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Groovy \ No newline at end of file diff --git a/Lang/Groovy/LZW-compression b/Lang/Groovy/LZW-compression new file mode 120000 index 0000000000..6d88bb7f7f --- /dev/null +++ b/Lang/Groovy/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Modular-exponentiation b/Lang/Groovy/Modular-exponentiation new file mode 120000 index 0000000000..dace34a9be --- /dev/null +++ b/Lang/Groovy/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Partial-function-application b/Lang/Groovy/Partial-function-application new file mode 120000 index 0000000000..e30de30686 --- /dev/null +++ b/Lang/Groovy/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Groovy \ No newline at end of file diff --git a/Lang/HLA/00DESCRIPTION b/Lang/HLA/00DESCRIPTION index dcd7d7bafe..163b52623f 100644 --- a/Lang/HLA/00DESCRIPTION +++ b/Lang/HLA/00DESCRIPTION @@ -1,5 +1,5 @@ {{language|HLA -|site=http://homepage.mac.com/randyhyde/webster.cs.ucr.edu/HighLevelAsm/index.html +|site=http://www.plantation-productions.com/Webster/HighLevelAsm/index.html |exec=machine |gc=no |parampass=value diff --git a/Lang/HQ9+/00DESCRIPTION b/Lang/HQ9+/00DESCRIPTION index 0148cdc443..59e4bc00e1 100644 --- a/Lang/HQ9+/00DESCRIPTION +++ b/Lang/HQ9+/00DESCRIPTION @@ -2,10 +2,8 @@ |tags=hq9plus |hopl=no }}[[Category:Esoteric Languages]] -External description: [http://www.cliff.biffle.org/esoterica/hq9plus.html http://www.cliff.biffle.org/esoterica/hq9plus.html] (broken?) +[http://cliffle.com/esoterica/hq9plus.html Original blog article] by the language creator Cliff L. Biffle. -External description 2: [[eso:HQ9_Plus]] +[[eso:HQ9_Plus|Description]] on esolangs.org. -This language is notable in the context of Rosetta Code in that [[RCHQ9+]] is a task for implementing it. - -{{stub}} \ No newline at end of file +This language is notable in the context of Rosetta Code in that [[RCHQ9+]] is a task for implementing it. \ No newline at end of file diff --git a/Lang/Haskell/CRC-32 b/Lang/Haskell/CRC-32 new file mode 120000 index 0000000000..96d9eeeb2e --- /dev/null +++ b/Lang/Haskell/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Haskell \ No newline at end of file diff --git a/Lang/Heron/00DESCRIPTION b/Lang/Heron/00DESCRIPTION index 75f3935fc6..ac718853cf 100644 --- a/Lang/Heron/00DESCRIPTION +++ b/Lang/Heron/00DESCRIPTION @@ -1,17 +1,14 @@ {{stub}} {{language -|site=http://www.heron-language.com/ +|site=http://code.google.com/p/heron-language/ }} Heron is a general-purpose object-oriented language, designed by Christopher Diggins, that strives to be appropriate for large scale project development (at least once it is mature). Heron borrows a number of ideas from functional languages, and offers some new twists on object-oriented programming.[[#Citation|[1]]] -Heron is influenced by the [[C++]], [[Java]] and [[Pascal]] programming languages. Heron has built-in support for object-oriented programming, generic programming, metaprogramming, aspect-oriented programming and design by contract techniques. The Heron language design goals include improving reusability of software and reduction of possibility of programmer error. Heron performance is tuned towards heavily polymorphic object-oriented designs.[[#Citation|[2]]] +Heron is influenced by the [[C++]], [[Java]] and [[Pascal]] programming languages. Heron has built-in support for object-oriented programming, generic programming, metaprogramming, aspect-oriented programming and design by contract techniques. The Heron language design goals include improving reusability of software and reduction of possibility of programmer error. Heron performance is tuned towards heavily polymorphic object-oriented designs. -Heron is effectively a combination of programming language and modeling language. It is designed to allow seamless transitioning between textual and diagrammatic representiation of executable UML (xUML) models. Heron is the first programming language designed specifically to support the model-driven architecture (MDA) paradigm.[[#Citation|[3]]] +Heron is effectively a combination of programming language and modeling language. It is designed to allow seamless transitioning between textual and diagrammatic representiation of executable UML (xUML) models. Heron is the first programming language designed specifically to support the model-driven architecture (MDA) paradigm. -Heron has a syntax which resembles [[Java]], [[C#]], [[ECMAScript]], and [[Scala]]. Heron is primarily an object-oriented language, but borrows many ideas from functional languages, and even some from array-oriented languages.[[#Citation|[4]]] +Heron has a syntax which resembles [[Java]], [[C#]], [[ECMAScript]], and [[Scala]]. Heron is primarily an object-oriented language, but borrows many ideas from functional languages, and even some from array-oriented languages. ==Citations== -# [http://www.artima.com/weblogs/viewpost.jsp?thread=284558 (Re-)Introducing the Heron Programming Language] -# [http://www.all-science-fair-projects.com/science_fair_projects_encyclopedia/Heron_programming_language Heron programming language] -# [http://www.heron-language.com/spec.html Heron Language Specification] -# [http://code.google.com/p/heron-language/ heron-language] \ No newline at end of file +# [http://www.artima.com/weblogs/viewpost.jsp?thread=284558 (Re-)Introducing the Heron Programming Language] \ No newline at end of file diff --git a/Lang/Hope/00DESCRIPTION b/Lang/Hope/00DESCRIPTION index 939b91ecd3..2dd544e6e6 100644 --- a/Lang/Hope/00DESCRIPTION +++ b/Lang/Hope/00DESCRIPTION @@ -1,4 +1,5 @@ {{language|Hope +|site=http://www.soi.city.ac.uk/~ross/Hope/ |strength=strong |safety=safe |compat=structural @@ -8,5 +9,5 @@ {{language programming paradigm|functional}} '''Hope''' is a purely [[functional programming]] language from 1970s, which predates Miranda and [[Haskell]]. It is the first language with call-by-pattern evaluation and algebraic data types, and its most used interpreter is fully [[lazy evaluation|lazy evaluated]]. -==Citations== +==See also== * [[wp:Hope_%28programming_language%29|Wikipedia:Hope (programming language)]] \ No newline at end of file diff --git a/Lang/Icon/Last-letter-first-letter b/Lang/Icon/Last-letter-first-letter new file mode 120000 index 0000000000..cec6cacdb8 --- /dev/null +++ b/Lang/Icon/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Radix-sort b/Lang/Icon/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..2ae79edbe6 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/String-comparison b/Lang/Icon/String-comparison new file mode 120000 index 0000000000..6abc95a7bc --- /dev/null +++ b/Lang/Icon/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Icon \ No newline at end of file diff --git a/Lang/J/SHA-1 b/Lang/J/SHA-1 new file mode 120000 index 0000000000..2682faced4 --- /dev/null +++ b/Lang/J/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/J \ No newline at end of file diff --git a/Lang/Jabaco/00DESCRIPTION b/Lang/Jabaco/00DESCRIPTION index 96b8bf005c..1731bc0a63 100644 --- a/Lang/Jabaco/00DESCRIPTION +++ b/Lang/Jabaco/00DESCRIPTION @@ -1 +1,3 @@ -{{language}}{{Stub}} \ No newline at end of file +{{Stub}} +{{language| +site=http://www.jabaco.org}} \ No newline at end of file diff --git a/Lang/Java/00DESCRIPTION b/Lang/Java/00DESCRIPTION index 8db85901b9..71ff53eaa0 100644 --- a/Lang/Java/00DESCRIPTION +++ b/Lang/Java/00DESCRIPTION @@ -29,7 +29,7 @@ The primary benefits of Java are: Java is used in a variety of environments including desktop applications, embedded device (PDA and wireless phone) applications, server-side web page serving applications (as [[Java Server Pages|JSP]]), and applets embedded in web pages. -There are a variety of arguments regarding Java's performance compared to other popular languages like [[C++]]. Some come to the conclusion that the programmer's choices make a bigger difference on performance in each language. Most show that each language is better than the other at specific types of operations (i.e. Java for memory allocation, C++ for numerical operations). An extensive summary of comparisons between Java and C++ can be found [[wp:Comparison of Java and C++|on Wikipedia]]. +There are a variety of arguments regarding Java's performance compared to other popular languages like [[C++]]. Some come to the conclusion that the programmer's choices make a bigger difference on performance in each language. Most show that each language is better than the other at specific types of operations (e.g. Java for memory allocation, C++ for numerical operations). An extensive summary of comparisons between Java and C++ can be found [[wp:Comparison of Java and C++|on Wikipedia]]. According to some [http://www.tiobe.com/tpci.htm sources], Java is currently one of the most popular programming languages in the world. diff --git a/Lang/Java/Deal-cards-for-FreeCell b/Lang/Java/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..94e068a838 --- /dev/null +++ b/Lang/Java/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Java \ No newline at end of file diff --git a/Lang/Java/Jensens-Device b/Lang/Java/Jensens-Device new file mode 120000 index 0000000000..92cf885295 --- /dev/null +++ b/Lang/Java/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Java \ No newline at end of file diff --git a/Lang/Java/Read-a-configuration-file b/Lang/Java/Read-a-configuration-file new file mode 120000 index 0000000000..ceea150e73 --- /dev/null +++ b/Lang/Java/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Java \ No newline at end of file diff --git a/Lang/JavaScript/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/JavaScript/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..7f12877098 --- /dev/null +++ b/Lang/JavaScript/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Quaternion-type b/Lang/JavaScript/Quaternion-type new file mode 120000 index 0000000000..e2a6535526 --- /dev/null +++ b/Lang/JavaScript/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/JavaScript \ No newline at end of file diff --git a/Lang/Joy/00DESCRIPTION b/Lang/Joy/00DESCRIPTION index e2565a3c6f..8a82f02c0a 100644 --- a/Lang/Joy/00DESCRIPTION +++ b/Lang/Joy/00DESCRIPTION @@ -2,7 +2,7 @@ |strength=strong |safety=safe |checking=dynamic -|site=http://www.latrobe.edu.au/phimvt/joy.html +|site=http://www.latrobe.edu.au/humanities/research/research-projects/past-projects/joy-programming-language |hopl id=2137 |LCT=yes}} {{language programming paradigm|concatenative}} diff --git a/Lang/JudoScript/00DESCRIPTION b/Lang/JudoScript/00DESCRIPTION index c3cf39cc64..29911f60c4 100644 --- a/Lang/JudoScript/00DESCRIPTION +++ b/Lang/JudoScript/00DESCRIPTION @@ -1,9 +1,8 @@ -{{language|JudoScript}}[[runs on vm::java virtual machine| ]] +{{language|JudoScript +|site=http://judoscript.org/judo.html}} +[[runs on vm::java virtual machine| ]] '''JudoScript''' is a scripting language based atop of [[Java]]. From the website: -:''Judo is a practical, functional scripting language. It is designed to cover the use cases of not only algorithmic/object-oriented/multi-threaded programming and Java scripting but also a number of major application domain tasks, such as scripting for JDBC, WSDL, ActiveX, OS, multiple file/data formats, etc. Despite its rich functionality, the base language is extremely simple, and domain support syntax is totally intuitive to domain experts, so that even though you have never programmed in Judo, you would have little trouble figuring out what the code does.'' - -==Citations== -* [http://www.judoscript.com/judo.html judoscript.com] \ No newline at end of file +:''Judo is a practical, functional scripting language. It is designed to cover the use cases of not only algorithmic/object-oriented/multi-threaded programming and Java scripting but also a number of major application domain tasks, such as scripting for JDBC, WSDL, ActiveX, OS, multiple file/data formats, etc. Despite its rich functionality, the base language is extremely simple, and domain support syntax is totally intuitive to domain experts, so that even though you have never programmed in Judo, you would have little trouble figuring out what the code does.'' \ No newline at end of file diff --git a/Lang/Julia/Averages-Mode b/Lang/Julia/Averages-Mode new file mode 120000 index 0000000000..bc5b729ba5 --- /dev/null +++ b/Lang/Julia/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Julia \ No newline at end of file diff --git a/Lang/Julia/Hello-world-Graphical b/Lang/Julia/Hello-world-Graphical new file mode 120000 index 0000000000..3dc071e3f0 --- /dev/null +++ b/Lang/Julia/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Julia \ No newline at end of file diff --git a/Lang/Julia/Josephus-problem b/Lang/Julia/Josephus-problem new file mode 120000 index 0000000000..1b19498380 --- /dev/null +++ b/Lang/Julia/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Leap-year b/Lang/Julia/Leap-year new file mode 120000 index 0000000000..565f2881e8 --- /dev/null +++ b/Lang/Julia/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Julia \ No newline at end of file diff --git a/Lang/Julia/Plot-coordinate-pairs b/Lang/Julia/Plot-coordinate-pairs new file mode 120000 index 0000000000..c495d01f3d --- /dev/null +++ b/Lang/Julia/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Quicksort b/Lang/Julia/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..bce8a7d2d2 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Julia \ No newline at end of file diff --git a/Lang/K3d/00DESCRIPTION b/Lang/K3d/00DESCRIPTION index bca513bbcf..e69de29bb2 100644 --- a/Lang/K3d/00DESCRIPTION +++ b/Lang/K3d/00DESCRIPTION @@ -1,2 +0,0 @@ -{{stub}}{{language}} -The k3d cad system supports the use of scripts (typically written in python) for its operation. \ No newline at end of file diff --git a/Lang/Kotlin/100-doors b/Lang/Kotlin/100-doors new file mode 120000 index 0000000000..77f5518653 --- /dev/null +++ b/Lang/Kotlin/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Array-concatenation b/Lang/Kotlin/Array-concatenation new file mode 120000 index 0000000000..e6ff60a3d1 --- /dev/null +++ b/Lang/Kotlin/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/GUI-component-interaction b/Lang/Kotlin/GUI-component-interaction new file mode 120000 index 0000000000..4c50eff4b1 --- /dev/null +++ b/Lang/Kotlin/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hailstone-sequence b/Lang/Kotlin/Hailstone-sequence new file mode 120000 index 0000000000..2565a89277 --- /dev/null +++ b/Lang/Kotlin/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hamming-numbers b/Lang/Kotlin/Hamming-numbers new file mode 120000 index 0000000000..0b6b078805 --- /dev/null +++ b/Lang/Kotlin/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Knights-tour b/Lang/Kotlin/Knights-tour new file mode 120000 index 0000000000..466d7ee7fb --- /dev/null +++ b/Lang/Kotlin/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Morse-code b/Lang/Kotlin/Morse-code new file mode 120000 index 0000000000..abeabd9dca --- /dev/null +++ b/Lang/Kotlin/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Read-a-configuration-file b/Lang/Kotlin/Read-a-configuration-file new file mode 120000 index 0000000000..9b7dfdd8bd --- /dev/null +++ b/Lang/Kotlin/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Bubble-sort b/Lang/Kotlin/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..fb7011e8dd --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Quicksort b/Lang/Kotlin/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..3c24845227 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Window-creation b/Lang/Kotlin/Window-creation new file mode 120000 index 0000000000..64ee1305a4 --- /dev/null +++ b/Lang/Kotlin/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Kotlin \ No newline at end of file diff --git a/Lang/LOLCODE/00DESCRIPTION b/Lang/LOLCODE/00DESCRIPTION index 2dd339db6b..1852f12c9d 100644 --- a/Lang/LOLCODE/00DESCRIPTION +++ b/Lang/LOLCODE/00DESCRIPTION @@ -1,2 +1,4 @@ -{{stub}}{{language|site=http://lolcode.com/}} +{{stub}} +{{language| +site=http://lolcode.org/}} [[Category:Esoteric Languages]] \ No newline at end of file diff --git a/Lang/LaTeX/00DESCRIPTION b/Lang/LaTeX/00DESCRIPTION index 80b612767b..e31cedce57 100644 --- a/Lang/LaTeX/00DESCRIPTION +++ b/Lang/LaTeX/00DESCRIPTION @@ -1,4 +1,6 @@ -{{language|LaTeX}}'''LaTeX''' is a document preparation language (markup language) written by Lamport (1985, 1994) to allow authors to create documents to be typeset using the [[TeX]] typesetting language (Knuth: 1978, 1982), without having to know the internal details of TeX. For further details please see the links below. +{{language|LaTeX +|site=http://latex-project.org/}} +'''LaTeX''' is a document preparation language (markup language) written by Lamport (1985, 1994) to allow authors to create documents to be typeset using the [[TeX]] typesetting language (Knuth: 1978, 1982), without having to know the internal details of TeX. For further details please see the links below. ==See Also== * [http://www.tug.org TeX Users Group] \ No newline at end of file diff --git a/Lang/LaTeX/FizzBuzz b/Lang/LaTeX/FizzBuzz new file mode 120000 index 0000000000..5476168fb0 --- /dev/null +++ b/Lang/LaTeX/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/LaTeX \ No newline at end of file diff --git a/Lang/Limbo/00DESCRIPTION b/Lang/Limbo/00DESCRIPTION index 2d485ae370..cd01609666 100644 --- a/Lang/Limbo/00DESCRIPTION +++ b/Lang/Limbo/00DESCRIPTION @@ -3,7 +3,7 @@ |gc=yes }} -Limbo is the application programming language for Inferno. Syntactically similar to [[C]], it has several features that make it simpler, safer and yet more powerful and better suited to the development of concurrent, distributed systems. The Limbo compiler generates architecture independent object code which is then interpreted by the Inferno Virtual Machine or compiled just before runtime to improve performance. This ensures that Limbo applications are completely portable across all Inferno platforms.[[#Citation|[1]]] +Limbo is the application programming language for Inferno. Syntactically similar to [[C]], it has several features that make it simpler, safer and yet more powerful and better suited to the development of concurrent, distributed systems. The Limbo compiler generates architecture independent object code which is then interpreted by the Dis Virtual Machine or compiled just before runtime to improve performance. This ensures that Limbo applications are completely portable across all Inferno platforms.[[#Citation|[1]]] Limbo's approach to concurrency was inspired by Hoare's Communicating Sequential Processes ([[CSP]]).[[#Citation|[2]]] diff --git a/Lang/Limbo/Gamma-function b/Lang/Limbo/Gamma-function new file mode 120000 index 0000000000..4e52212e66 --- /dev/null +++ b/Lang/Limbo/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Limbo \ No newline at end of file diff --git a/Lang/Lua/MD4 b/Lang/Lua/MD4 new file mode 120000 index 0000000000..a14a7baffb --- /dev/null +++ b/Lang/Lua/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Lua \ No newline at end of file diff --git a/Lang/Lua/RIPEMD-160 b/Lang/Lua/RIPEMD-160 new file mode 120000 index 0000000000..5a9b4f1c3d --- /dev/null +++ b/Lang/Lua/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Lua \ No newline at end of file diff --git a/Lang/Lua/SHA-1 b/Lang/Lua/SHA-1 new file mode 120000 index 0000000000..ba96d458e3 --- /dev/null +++ b/Lang/Lua/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Lua \ No newline at end of file diff --git a/Lang/Lua/SHA-256 b/Lang/Lua/SHA-256 new file mode 120000 index 0000000000..68c1c0f232 --- /dev/null +++ b/Lang/Lua/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Lua \ No newline at end of file diff --git a/Lang/Lua/Sudoku b/Lang/Lua/Sudoku new file mode 120000 index 0000000000..a31ec81a1b --- /dev/null +++ b/Lang/Lua/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Lua \ No newline at end of file diff --git a/Lang/MATLAB/Include-a-file b/Lang/MATLAB/Include-a-file new file mode 120000 index 0000000000..583c0b8732 --- /dev/null +++ b/Lang/MATLAB/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Non-decimal-radices-Convert b/Lang/MATLAB/Non-decimal-radices-Convert new file mode 120000 index 0000000000..6f360b65cd --- /dev/null +++ b/Lang/MATLAB/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Standard-deviation b/Lang/MATLAB/Standard-deviation new file mode 120000 index 0000000000..6f5d2fe983 --- /dev/null +++ b/Lang/MATLAB/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/MATLAB \ No newline at end of file diff --git a/Lang/ML-I/00DESCRIPTION b/Lang/ML-I/00DESCRIPTION index b5244bacab..c46ba37b18 100644 --- a/Lang/ML-I/00DESCRIPTION +++ b/Lang/ML-I/00DESCRIPTION @@ -1,10 +1,9 @@ -{{language|ML/I}} +{{language|ML/I +|site=http://www.ml1.org.uk}} ML/I is a general, stand alone, programmable macro processor. It is general in the sense that it can be used to process any kind of text. The text may be in any programming language or natural language, or it may be numerical data. It is stand alone in that it depends on no other program for its operation. It is programmable in that it can be programmed to carry out fairly complex operations when faced with varying kinds of input. In short, it is a very powerful tool. Historically, the most important use of ML/I has been to provide users with a simple means of adding extra statements (or other syntactic forms) to an existing programming language in order to make the language more suitable for their own field of application. This process of extension may be carried to the level where the extended language could be regarded as a new language in its own right. Other possible uses of ML/I are program parameterisation (e.g. a parameter might determine whether debugging statements are to be included in a program) and various applications in text editing or correction and in data format conversion. It has been used, for instance, to format and convert files marked up with HTML. It has also been used as part of a microprogam translator for a bit slice computer implementation. However, these are just a few applications. ML/I is very flexible, and there are many, many other uses for it. -ML/I is an exceedingly long-lived language. It was first implemented in 1966, and is still in use. - -The official ML/I web site can be found at [http://www.ml1.org.uk http://www.ml1.org.uk] \ No newline at end of file +ML/I is an exceedingly long-lived language. It was first implemented in 1966, and is still in use. \ No newline at end of file diff --git a/Lang/MPIF90/00DESCRIPTION b/Lang/MPIF90/00DESCRIPTION index 50cb6ba6d4..e69de29bb2 100644 --- a/Lang/MPIF90/00DESCRIPTION +++ b/Lang/MPIF90/00DESCRIPTION @@ -1 +0,0 @@ -{{language}}MPIf90 is the Message-passing interface for [[Fortran]] 90. See also mpif77, mpicc, etc. \ No newline at end of file diff --git a/Lang/Maple/00DESCRIPTION b/Lang/Maple/00DESCRIPTION index 36301ff907..dff6601ba1 100644 --- a/Lang/Maple/00DESCRIPTION +++ b/Lang/Maple/00DESCRIPTION @@ -1,3 +1,5 @@ -{{language}}{{stub}} +{{stub}} +{{language +|site=http://www.maplesoft.com/products/maple/}} [[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/Maple/Anagrams-Deranged-anagrams b/Lang/Maple/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..92398830aa --- /dev/null +++ b/Lang/Maple/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Maple \ No newline at end of file diff --git a/Lang/Maple/Check-that-file-exists b/Lang/Maple/Check-that-file-exists new file mode 120000 index 0000000000..9a308a89f0 --- /dev/null +++ b/Lang/Maple/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Maple \ No newline at end of file diff --git a/Lang/Maple/Comments b/Lang/Maple/Comments new file mode 120000 index 0000000000..b5e33d80bb --- /dev/null +++ b/Lang/Maple/Comments @@ -0,0 +1 @@ +../../Task/Comments/Maple \ No newline at end of file diff --git a/Lang/Maple/Conditional-structures b/Lang/Maple/Conditional-structures new file mode 120000 index 0000000000..5707e420fb --- /dev/null +++ b/Lang/Maple/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Maple \ No newline at end of file diff --git a/Lang/Maple/Count-occurrences-of-a-substring b/Lang/Maple/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..a2a5341f29 --- /dev/null +++ b/Lang/Maple/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Maple \ No newline at end of file diff --git a/Lang/Maple/Detect-division-by-zero b/Lang/Maple/Detect-division-by-zero new file mode 120000 index 0000000000..de7bf3db0a --- /dev/null +++ b/Lang/Maple/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Maple \ No newline at end of file diff --git a/Lang/Maple/Dot-product b/Lang/Maple/Dot-product new file mode 120000 index 0000000000..eea9f44d3d --- /dev/null +++ b/Lang/Maple/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Maple \ No newline at end of file diff --git a/Lang/Maple/Environment-variables b/Lang/Maple/Environment-variables new file mode 120000 index 0000000000..5f3fc0cae5 --- /dev/null +++ b/Lang/Maple/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Maple \ No newline at end of file diff --git a/Lang/Maple/Evaluate-binomial-coefficients b/Lang/Maple/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..eb14d5d53e --- /dev/null +++ b/Lang/Maple/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Maple \ No newline at end of file diff --git a/Lang/Maple/Execute-a-system-command b/Lang/Maple/Execute-a-system-command new file mode 120000 index 0000000000..13ce44e34e --- /dev/null +++ b/Lang/Maple/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Maple \ No newline at end of file diff --git a/Lang/Maple/Factors-of-an-integer b/Lang/Maple/Factors-of-an-integer new file mode 120000 index 0000000000..5288c08533 --- /dev/null +++ b/Lang/Maple/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Maple \ No newline at end of file diff --git a/Lang/Maple/Fast-Fourier-transform b/Lang/Maple/Fast-Fourier-transform new file mode 120000 index 0000000000..c66f6d7424 --- /dev/null +++ b/Lang/Maple/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Maple \ No newline at end of file diff --git a/Lang/Maple/Flatten-a-list b/Lang/Maple/Flatten-a-list new file mode 120000 index 0000000000..82837a70b0 --- /dev/null +++ b/Lang/Maple/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Maple \ No newline at end of file diff --git a/Lang/Maple/Horners-rule-for-polynomial-evaluation b/Lang/Maple/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..99e8843946 --- /dev/null +++ b/Lang/Maple/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Maple \ No newline at end of file diff --git a/Lang/Maple/Integer-sequence b/Lang/Maple/Integer-sequence new file mode 120000 index 0000000000..61b220fa27 --- /dev/null +++ b/Lang/Maple/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Maple \ No newline at end of file diff --git a/Lang/Maple/Interactive-programming b/Lang/Maple/Interactive-programming new file mode 120000 index 0000000000..a63fc97eed --- /dev/null +++ b/Lang/Maple/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/Maple \ No newline at end of file diff --git a/Lang/Maple/LU-decomposition b/Lang/Maple/LU-decomposition new file mode 120000 index 0000000000..6546dac291 --- /dev/null +++ b/Lang/Maple/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Maple \ No newline at end of file diff --git a/Lang/Maple/Logical-operations b/Lang/Maple/Logical-operations new file mode 120000 index 0000000000..2b80af257e --- /dev/null +++ b/Lang/Maple/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Maple \ No newline at end of file diff --git a/Lang/Maple/Loops-For-with-a-specified-step b/Lang/Maple/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..365e052f94 --- /dev/null +++ b/Lang/Maple/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Maple \ No newline at end of file diff --git a/Lang/Maple/Loops-Foreach b/Lang/Maple/Loops-Foreach new file mode 120000 index 0000000000..41fcf31acd --- /dev/null +++ b/Lang/Maple/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Maple \ No newline at end of file diff --git a/Lang/Maple/Loops-Nested b/Lang/Maple/Loops-Nested new file mode 120000 index 0000000000..98277b9709 --- /dev/null +++ b/Lang/Maple/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Maple \ No newline at end of file diff --git a/Lang/Maple/Matrix-arithmetic b/Lang/Maple/Matrix-arithmetic new file mode 120000 index 0000000000..ff2ce120e7 --- /dev/null +++ b/Lang/Maple/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Maple \ No newline at end of file diff --git a/Lang/Maple/Matrix-exponentiation-operator b/Lang/Maple/Matrix-exponentiation-operator new file mode 120000 index 0000000000..1b9416231f --- /dev/null +++ b/Lang/Maple/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Maple \ No newline at end of file diff --git a/Lang/Maple/Matrix-multiplication b/Lang/Maple/Matrix-multiplication new file mode 120000 index 0000000000..f605241a59 --- /dev/null +++ b/Lang/Maple/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Maple \ No newline at end of file diff --git a/Lang/Maple/Matrix-transposition b/Lang/Maple/Matrix-transposition new file mode 120000 index 0000000000..ba9650aa5a --- /dev/null +++ b/Lang/Maple/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Maple \ No newline at end of file diff --git a/Lang/Maple/Modular-inverse b/Lang/Maple/Modular-inverse new file mode 120000 index 0000000000..92f55e77d1 --- /dev/null +++ b/Lang/Maple/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Maple \ No newline at end of file diff --git a/Lang/Maple/Nth-root b/Lang/Maple/Nth-root new file mode 120000 index 0000000000..fb06275a31 --- /dev/null +++ b/Lang/Maple/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Maple \ No newline at end of file diff --git a/Lang/Maple/Palindrome-detection b/Lang/Maple/Palindrome-detection new file mode 120000 index 0000000000..17f0b198e2 --- /dev/null +++ b/Lang/Maple/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Maple \ No newline at end of file diff --git a/Lang/Maple/Power-set b/Lang/Maple/Power-set new file mode 120000 index 0000000000..47c529d1bb --- /dev/null +++ b/Lang/Maple/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Maple \ No newline at end of file diff --git a/Lang/Maple/Prime-decomposition b/Lang/Maple/Prime-decomposition new file mode 120000 index 0000000000..00cc4881d3 --- /dev/null +++ b/Lang/Maple/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Maple \ No newline at end of file diff --git a/Lang/Maple/QR-decomposition b/Lang/Maple/QR-decomposition new file mode 120000 index 0000000000..d4b8774529 --- /dev/null +++ b/Lang/Maple/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Maple \ No newline at end of file diff --git a/Lang/Maple/Reduced-row-echelon-form b/Lang/Maple/Reduced-row-echelon-form new file mode 120000 index 0000000000..4ad1595f3a --- /dev/null +++ b/Lang/Maple/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Maple \ No newline at end of file diff --git a/Lang/Maple/Roots-of-a-quadratic-function b/Lang/Maple/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..3ea529ecc2 --- /dev/null +++ b/Lang/Maple/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Maple \ No newline at end of file diff --git a/Lang/Maple/Sleep b/Lang/Maple/Sleep new file mode 120000 index 0000000000..a6b2dd8b67 --- /dev/null +++ b/Lang/Maple/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Maple \ No newline at end of file diff --git a/Lang/Maple/Sort-an-integer-array b/Lang/Maple/Sort-an-integer-array new file mode 120000 index 0000000000..e26fd8fd94 --- /dev/null +++ b/Lang/Maple/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Maple \ No newline at end of file diff --git a/Lang/Maple/Stack b/Lang/Maple/Stack new file mode 120000 index 0000000000..dabb089b84 --- /dev/null +++ b/Lang/Maple/Stack @@ -0,0 +1 @@ +../../Task/Stack/Maple \ No newline at end of file diff --git a/Lang/Maple/String-case b/Lang/Maple/String-case new file mode 120000 index 0000000000..14c481791e --- /dev/null +++ b/Lang/Maple/String-case @@ -0,0 +1 @@ +../../Task/String-case/Maple \ No newline at end of file diff --git a/Lang/Maple/String-concatenation b/Lang/Maple/String-concatenation new file mode 120000 index 0000000000..b26d6f8367 --- /dev/null +++ b/Lang/Maple/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Maple \ No newline at end of file diff --git a/Lang/Maple/Strip-a-set-of-characters-from-a-string b/Lang/Maple/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..945598e97d --- /dev/null +++ b/Lang/Maple/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Maple \ No newline at end of file diff --git a/Lang/Maple/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Maple/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..2e7d5d65e5 --- /dev/null +++ b/Lang/Maple/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Maple \ No newline at end of file diff --git a/Lang/Maple/Sum-of-squares b/Lang/Maple/Sum-of-squares new file mode 120000 index 0000000000..e72bcdea5e --- /dev/null +++ b/Lang/Maple/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Maple \ No newline at end of file diff --git a/Lang/Mathematica/00DESCRIPTION b/Lang/Mathematica/00DESCRIPTION index 604a261a34..c3b8387364 100644 --- a/Lang/Mathematica/00DESCRIPTION +++ b/Lang/Mathematica/00DESCRIPTION @@ -1,10 +1,9 @@ {{language|Mathematica +|site=https://www.wolfram.com/mathematica/ |strength=strong |checking=dynamic |gc=yes |LCT=yes}}{{implementation|Mathematica}}{{language programming paradigm|Declarative}}{{language programming paradigm|Functional}} -[[Mathematica]] is the name of Wolfram Research's mathematics analysis tool, as well as the name of the principal language used to control it. - -
+Mathematica is the name of Wolfram Research's mathematics analysis tool, as well as the name of the principal language used to control it. [[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/Maxima/00DESCRIPTION b/Lang/Maxima/00DESCRIPTION index 2085f90dad..71383750d5 100644 --- a/Lang/Maxima/00DESCRIPTION +++ b/Lang/Maxima/00DESCRIPTION @@ -1,3 +1,5 @@ -{{language|Maxima}}Maxima is the language used in the computer algebra system of the same name. See http://maxima.sourceforge.net/ +{{language|Maxima +|site=http://maxima.sourceforge.net/}} +Maxima is the language used in the computer algebra system of the same name. [[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/Maxima/Search-a-list b/Lang/Maxima/Search-a-list new file mode 120000 index 0000000000..ee11e6cdbe --- /dev/null +++ b/Lang/Maxima/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Maxima \ No newline at end of file diff --git a/Lang/Mercury/00DESCRIPTION b/Lang/Mercury/00DESCRIPTION index 46480cc7aa..a511560605 100644 --- a/Lang/Mercury/00DESCRIPTION +++ b/Lang/Mercury/00DESCRIPTION @@ -1,6 +1,7 @@ -{{stub}}{{language +{{stub}} +{{language |strength=strong -|site=http://www.mercury.csse.unimelb.edu.au/ +|site=http://mercurylang.org/ |checking=static}}[[runs on vm::java virtual machine| ]][[runs on vm::common language runtime| ]] {{language programming paradigm|Declarative}} {{language programming paradigm|functional}} diff --git a/Lang/Mercury/Create-a-file b/Lang/Mercury/Create-a-file new file mode 120000 index 0000000000..abb12ee223 --- /dev/null +++ b/Lang/Mercury/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Mercury \ No newline at end of file diff --git a/Lang/Mercury/File-IO b/Lang/Mercury/File-IO new file mode 120000 index 0000000000..c5d0f8ecdd --- /dev/null +++ b/Lang/Mercury/File-IO @@ -0,0 +1 @@ +../../Task/File-IO/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Hailstone-sequence b/Lang/Mercury/Hailstone-sequence new file mode 120000 index 0000000000..5797b63483 --- /dev/null +++ b/Lang/Mercury/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Leap-year b/Lang/Mercury/Leap-year new file mode 120000 index 0000000000..8bbfd41eab --- /dev/null +++ b/Lang/Mercury/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Parametric-polymorphism b/Lang/Mercury/Parametric-polymorphism new file mode 120000 index 0000000000..812369bba8 --- /dev/null +++ b/Lang/Mercury/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Rename-a-file b/Lang/Mercury/Rename-a-file new file mode 120000 index 0000000000..192510fc6c --- /dev/null +++ b/Lang/Mercury/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Roman-numerals-Decode b/Lang/Mercury/Roman-numerals-Decode new file mode 120000 index 0000000000..4d60af4d2d --- /dev/null +++ b/Lang/Mercury/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Take-notes-on-the-command-line b/Lang/Mercury/Take-notes-on-the-command-line new file mode 120000 index 0000000000..a7a3dac7c9 --- /dev/null +++ b/Lang/Mercury/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Mercury \ No newline at end of file diff --git a/Lang/Modula-3/00DESCRIPTION b/Lang/Modula-3/00DESCRIPTION index 2101b2d969..582f870540 100644 --- a/Lang/Modula-3/00DESCRIPTION +++ b/Lang/Modula-3/00DESCRIPTION @@ -1,4 +1,5 @@ {{language|Modula-3 +|site=http://www.modula3.org/ |exec=machine |safety=both |strength=strong @@ -20,5 +21,4 @@ Its main implementation is [[Critical Mass Modula-3]]. Modula-3 influenced a few languages such as [[C Sharp|C#]], [[Java]], [[Ocaml]] and [[Python]]. ==Links== -* [http://www.modula3.org/ Modula-3 Resource Site] * [http://en.wikipedia.org/wiki/Modula-3 Modula-3 at Wikipedia] \ No newline at end of file diff --git a/Lang/Moonscript/00DESCRIPTION b/Lang/Moonscript/00DESCRIPTION index 4d3d27c049..e69de29bb2 100644 --- a/Lang/Moonscript/00DESCRIPTION +++ b/Lang/Moonscript/00DESCRIPTION @@ -1 +0,0 @@ -{{stub}}{{language}} \ No newline at end of file diff --git a/Lang/Nemerle/00DESCRIPTION b/Lang/Nemerle/00DESCRIPTION index 0e4e42b2d5..eb1d25fc95 100644 --- a/Lang/Nemerle/00DESCRIPTION +++ b/Lang/Nemerle/00DESCRIPTION @@ -1,7 +1,6 @@ {{language|Nemerle |exec=bytecode -|site=http://nemerle.org/Main_Page -|gc=yes +|site=http://nemerle.org |express=implicit |strength=strong |compat=nominative diff --git a/Lang/NetLogo/00DESCRIPTION b/Lang/NetLogo/00DESCRIPTION index 4d3d27c049..816bff2884 100644 --- a/Lang/NetLogo/00DESCRIPTION +++ b/Lang/NetLogo/00DESCRIPTION @@ -1 +1,4 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language +|site=http://ccl.northwestern.edu/netlogo/ +}} \ No newline at end of file diff --git a/Lang/NetRexx/Harshad-or-Niven-series b/Lang/NetRexx/Harshad-or-Niven-series new file mode 120000 index 0000000000..18d5d66769 --- /dev/null +++ b/Lang/NetRexx/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Horners-rule-for-polynomial-evaluation b/Lang/NetRexx/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..edfb7ee3e0 --- /dev/null +++ b/Lang/NetRexx/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/NetRexx/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..39aa3c3749 --- /dev/null +++ b/Lang/NetRexx/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/NetRexx \ No newline at end of file diff --git a/Lang/Nimrod/100-doors b/Lang/Nimrod/100-doors new file mode 120000 index 0000000000..7babab5486 --- /dev/null +++ b/Lang/Nimrod/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Range-expansion b/Lang/Nimrod/Range-expansion new file mode 120000 index 0000000000..5fb0094a2d --- /dev/null +++ b/Lang/Nimrod/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Range-extraction b/Lang/Nimrod/Range-extraction new file mode 120000 index 0000000000..0bf5dcc076 --- /dev/null +++ b/Lang/Nimrod/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Nimrod \ No newline at end of file diff --git a/Lang/OCaml/00DESCRIPTION b/Lang/OCaml/00DESCRIPTION index e7787ed634..7af3796bbf 100644 --- a/Lang/OCaml/00DESCRIPTION +++ b/Lang/OCaml/00DESCRIPTION @@ -1,5 +1,6 @@ {{language|OCaml |strength=strong +|site=http://ocaml.org |safety=safe |compat=structural |checking=static diff --git a/Lang/OCaml/Address-of-a-variable b/Lang/OCaml/Address-of-a-variable new file mode 120000 index 0000000000..06286a5e0a --- /dev/null +++ b/Lang/OCaml/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/OCaml \ No newline at end of file diff --git a/Lang/OOC/00DESCRIPTION b/Lang/OOC/00DESCRIPTION index afefd57ab5..6ab39964dc 100644 --- a/Lang/OOC/00DESCRIPTION +++ b/Lang/OOC/00DESCRIPTION @@ -1,2 +1,2 @@ {{stub}}{{language -|site=http://www.ooc-lang.org}} \ No newline at end of file +|site=http://ooc-lang.org}} \ No newline at end of file diff --git a/Lang/OPL/00DESCRIPTION b/Lang/OPL/00DESCRIPTION index 4d3d27c049..8357c2d27a 100644 --- a/Lang/OPL/00DESCRIPTION +++ b/Lang/OPL/00DESCRIPTION @@ -1 +1,3 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language +|site=http://opl-dev.sourceforge.net/}} \ No newline at end of file diff --git a/Lang/Objeck/Case-sensitivity-of-identifiers b/Lang/Objeck/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..3ea97d65a1 --- /dev/null +++ b/Lang/Objeck/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Objeck \ No newline at end of file diff --git a/Lang/Object-Pascal/Call-an-object-method b/Lang/Object-Pascal/Call-an-object-method new file mode 120000 index 0000000000..6108c5bbb3 --- /dev/null +++ b/Lang/Object-Pascal/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Object-Pascal \ No newline at end of file diff --git a/Lang/Object-Pascal/Respond-to-an-unknown-method-call b/Lang/Object-Pascal/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..b8d8ff961c --- /dev/null +++ b/Lang/Object-Pascal/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Object-Pascal \ No newline at end of file diff --git a/Lang/Objective-C/00DESCRIPTION b/Lang/Objective-C/00DESCRIPTION index afe6edc462..55349e5be3 100644 --- a/Lang/Objective-C/00DESCRIPTION +++ b/Lang/Objective-C/00DESCRIPTION @@ -10,4 +10,8 @@ [[wp:Objective-C|Objective-C]] is an [[object-oriented]] superset of the [[derived from::compatible with::C]] language. It mostly copies the message passing system from [[derived from::Smalltalk]]. It was popularized by NeXT, and then again by [[Apple Inc]] with [[Mac OS X]] and [[iOS]] to implement the [[Cocoa]] frameworks. Its main reference implementation is within the [[gcc]] compiler, maintained mostly by Apple. As of October 2011, with the release of [http://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_4_2.html#//apple_ref/doc/uid/00200-SW1 XCode 4.2], Apple switched from [[gcc]] to [[wp:Clang|Clang]] as its default compiler. [[wp:Clang|Clang]]/[[wp:LLVM|LLVM]] offers competitive execution times, better compile times, improved error messages, and supports a simpler alternative syntax for expressing NSArray & NSDictionary literals and indexing. In the same release Apple also introduced automatic reference counting (ARC) which eliminates the need to manually release/retain memory. With ARC the compiler reports an error any time it encounters a call to release, autorelease, retain, or dealloc. + +The release of Xcode 4.4 (4.5 for iOS) added [http://clang.llvm.org/docs/ObjectiveCLiterals.html syntax to specify literals] for NSArray, NSDictionary, NSNumber, and NSString, as well as subscript syntax to access elements of NSArray and NSDictionary. + +Unless otherwise stated, Objective-C code samples will assume that they are compiled with ARC enabled, and that the compiler supports Objective-C literals and Blocks.
\ No newline at end of file diff --git a/Lang/Objective-C/Deal-cards-for-FreeCell b/Lang/Objective-C/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..a78b218f6e --- /dev/null +++ b/Lang/Objective-C/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/SHA-256 b/Lang/Objective-C/SHA-256 new file mode 120000 index 0000000000..3f9e128eef --- /dev/null +++ b/Lang/Objective-C/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sorting-algorithms-Quicksort b/Lang/Objective-C/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..173f04a34f --- /dev/null +++ b/Lang/Objective-C/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Objective-C \ No newline at end of file diff --git a/Lang/Octave/Quaternion-type b/Lang/Octave/Quaternion-type new file mode 120000 index 0000000000..6dec972e26 --- /dev/null +++ b/Lang/Octave/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Octave \ No newline at end of file diff --git a/Lang/Octave/SHA-1 b/Lang/Octave/SHA-1 new file mode 120000 index 0000000000..e4115e79c3 --- /dev/null +++ b/Lang/Octave/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Octave \ No newline at end of file diff --git a/Lang/OoRexx/00DESCRIPTION b/Lang/OoRexx/00DESCRIPTION index ef236b80eb..f97c9111ee 100644 --- a/Lang/OoRexx/00DESCRIPTION +++ b/Lang/OoRexx/00DESCRIPTION @@ -1,4 +1,8 @@ -{{DISPLAYTITLE: Category:ooREXX}}{{stub}}{{language}}{{implementation|REXX}} +{{DISPLAYTITLE: Category:ooREXX}} +{{stub}} +{{language +|site=http://www.oorexx.org/}} +{{implementation|REXX}} ooRexx (aka Open Object Rexx) is an object oriented successor of 'Classic' Rexx (another one is NetRexx). Both Open Object Rexx and NetRexx were created by IBM and are now, open sourced, maintained by the Rexx Language Association. diff --git a/Lang/Openscad/00DESCRIPTION b/Lang/Openscad/00DESCRIPTION index 6a69b7b46d..df77502458 100644 --- a/Lang/Openscad/00DESCRIPTION +++ b/Lang/Openscad/00DESCRIPTION @@ -1,4 +1,6 @@ -{{stub}}{{language}} +{{stub}} +{{language +|site=http://www.openscad.org/}} The openscad language is the scripting language used by the openscad geometry compiler. diff --git a/Lang/OxygenBasic/00DESCRIPTION b/Lang/OxygenBasic/00DESCRIPTION index 4acccc1237..2fac2da7df 100644 --- a/Lang/OxygenBasic/00DESCRIPTION +++ b/Lang/OxygenBasic/00DESCRIPTION @@ -1,4 +1,6 @@ -{{language|express=both}} +{{language +|express=both +|site=http://www.oxygenbasic.org/}} OxygenBasic is a compilable language in the [[BASIC]] genre supporting [[object-oriented programming]], and containing features of [[C]]. Its earliest origins was as a macro [[Assembly]] code language in 2009, but subsequently acquired all the features of a high-level language. The philosophy underlying OxygenBasic is to facilitate clean coding, with low syntax noise and few coding restrictions. The core language and compiler size are kept to a minimum. diff --git a/Lang/PARI-GP/00DESCRIPTION b/Lang/PARI-GP/00DESCRIPTION index bf445db178..8439a2fda6 100644 --- a/Lang/PARI-GP/00DESCRIPTION +++ b/Lang/PARI-GP/00DESCRIPTION @@ -22,13 +22,17 @@ PARI was written by Henri Cohen and others at Université Bordeaux I and is now == Using PARI/GP == PARI/GP can be downloaded at its official website's [http://pari.math.u-bordeaux.fr/download.html download page]. -For Windows users precompiled binaries are available: full-featured stable and development versions, plus a nightly build with the very latest changes. +Windows precompiled binaries are available: an installer, stand-alone stable and development versions, plus a nightly build with the very latest changes. Mac users may find it convenient to download the version from [http://pdb.finkproject.org/pdb/package.php/pari-gp Fink]. Linux users can install PARI/GP with their favorite package manager (RPM, dpkg, apt, etc.) or build it from source. [http://math.crg4.com/software.html#pari Instructions] are available for compiling. -[https://code.google.com/p/paridroid/ paridroid] is a port to Android tablets and phones. While an iPhone/iPad version has not been developed, [https://itunes.apple.com/us/app/sage-math/id496492945?mt=8 sage-math] includes PARI and GP commands can be involved with the wrapper function pari. +Android phones and tablets can use [https://code.google.com/p/paridroid/ paridroid] (also [https://github.com/FreeMonad/paridroid on github]). + +While an iPhone/iPad version has not been developed, [https://itunes.apple.com/us/app/sage-math/id496492945?mt=8 sage-math] includes PARI and GP commands can be invoked with the wrapper function pari. + +Finally, gp can be used online through [http://www.compileonline.com/execute_pari_online.php compile online] or the [https://cloud.sagemath.com/ SageMath cloud]. == Coding with PARI == The most common way to use PARI is through the gp calculator, using its own scripting language, GP. But there are other interfaces to PARI beside gp: @@ -38,7 +42,8 @@ The most common way to use PARI is through the gp calculator, using its own scri If you want to write a program rather than script a calculator, many languages are supported: * [[C]]: PARI is written in C, so it's very easy to either write your own programs or extend gp using C. -* [[C++]]: With appropriate linkage specification it is possible to use PARI directly in C++ as well. The code is intentionally written in a C++-compatible style. +** For use with the Gnu Mpc library, there is also [http://www.multiprecision.org/?prog=pari-gnump Pari-Gnump]. +* [[C++]]: PARI can be used directly in C++. The code is intentionally written in a C++-compatible style. -fpermissive is sometimes useful when compiling with g++. * [[Python]]: [http://www.sagemath.org/ SAGE] is a Python-based system that includes PARI among others; there is a [http://code.google.com/p/pari-python/ pari-python] library as well. * [[Perl]]: Use [http://search.cpan.org/dist/Math-Pari/ Math::Pari] or [https://github.com/FreeMonad/GPP GPP]. * [[Common Lisp]]: Use [http://clisp.sourceforge.net/impnotes/pari.html Pari] ([[CLISP]]). diff --git a/Lang/PARI-GP/Average-loop-length b/Lang/PARI-GP/Average-loop-length new file mode 120000 index 0000000000..8b0605cde3 --- /dev/null +++ b/Lang/PARI-GP/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Binary-strings b/Lang/PARI-GP/Binary-strings new file mode 120000 index 0000000000..3d10ecc6f7 --- /dev/null +++ b/Lang/PARI-GP/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Carmichael-3-strong-pseudoprimes b/Lang/PARI-GP/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..e2de0833c0 --- /dev/null +++ b/Lang/PARI-GP/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/PARI-GP/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..607bfd46e5 --- /dev/null +++ b/Lang/PARI-GP/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Find-the-missing-permutation b/Lang/PARI-GP/Find-the-missing-permutation new file mode 120000 index 0000000000..afb7b0bf07 --- /dev/null +++ b/Lang/PARI-GP/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Floyds-triangle b/Lang/PARI-GP/Floyds-triangle new file mode 120000 index 0000000000..16f112a2d8 --- /dev/null +++ b/Lang/PARI-GP/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Forest-fire b/Lang/PARI-GP/Forest-fire new file mode 120000 index 0000000000..9e28cdd36b --- /dev/null +++ b/Lang/PARI-GP/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/GUI-Maximum-window-dimensions b/Lang/PARI-GP/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..9e92ee8042 --- /dev/null +++ b/Lang/PARI-GP/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Partial-function-application b/Lang/PARI-GP/Partial-function-application new file mode 120000 index 0000000000..41e3368257 --- /dev/null +++ b/Lang/PARI-GP/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Show-the-epoch b/Lang/PARI-GP/Show-the-epoch new file mode 120000 index 0000000000..61d181f368 --- /dev/null +++ b/Lang/PARI-GP/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sierpinski-triangle b/Lang/PARI-GP/Sierpinski-triangle new file mode 120000 index 0000000000..41eaece7e7 --- /dev/null +++ b/Lang/PARI-GP/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Topic-variable b/Lang/PARI-GP/Topic-variable new file mode 120000 index 0000000000..85bdb23ab7 --- /dev/null +++ b/Lang/PARI-GP/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/LZW-compression b/Lang/PHP/LZW-compression new file mode 120000 index 0000000000..895928d8a6 --- /dev/null +++ b/Lang/PHP/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/PHP \ No newline at end of file diff --git a/Lang/PL-I/Carmichael-3-strong-pseudoprimes b/Lang/PL-I/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..1b709d5ff0 --- /dev/null +++ b/Lang/PL-I/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Gray-code b/Lang/PL-I/Gray-code new file mode 120000 index 0000000000..98be8ae049 --- /dev/null +++ b/Lang/PL-I/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/PL-I/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..a3c5cd38ed --- /dev/null +++ b/Lang/PL-I/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Pythagorean-triples b/Lang/PL-I/Pythagorean-triples new file mode 120000 index 0000000000..be9753aad8 --- /dev/null +++ b/Lang/PL-I/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/PL-I \ No newline at end of file diff --git a/Lang/PL-SQL/Top-rank-per-group b/Lang/PL-SQL/Top-rank-per-group new file mode 120000 index 0000000000..e1679951fd --- /dev/null +++ b/Lang/PL-SQL/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PL-SQL \ No newline at end of file diff --git a/Lang/POV-Ray/00DESCRIPTION b/Lang/POV-Ray/00DESCRIPTION index 6dee331070..45055290c2 100644 --- a/Lang/POV-Ray/00DESCRIPTION +++ b/Lang/POV-Ray/00DESCRIPTION @@ -1,8 +1,9 @@ +{{stub}} {{language |exec=interpreted |site=http://www.povray.org | -}}{{stub}} +}} '''POV-Ray''' is a raytracer where images are specified in a description language. This description language also has programming constructs, making it a full-fledged programming language. ==Citation== diff --git a/Lang/Pascal/Digital-root b/Lang/Pascal/Digital-root new file mode 120000 index 0000000000..7211db0ca2 --- /dev/null +++ b/Lang/Pascal/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Range-extraction b/Lang/Pascal/Range-extraction new file mode 120000 index 0000000000..62b5d4a193 --- /dev/null +++ b/Lang/Pascal/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Remove-lines-from-a-file b/Lang/Pascal/Remove-lines-from-a-file new file mode 120000 index 0000000000..6ca2b09310 --- /dev/null +++ b/Lang/Pascal/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Soundex b/Lang/Pascal/Soundex new file mode 120000 index 0000000000..4ea00227ca --- /dev/null +++ b/Lang/Pascal/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/I-before-E-except-after-C b/Lang/Perl-6/I-before-E-except-after-C new file mode 120000 index 0000000000..98f8a71253 --- /dev/null +++ b/Lang/Perl-6/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Memory-layout-of-a-data-structure b/Lang/Perl-6/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..6d4293e475 --- /dev/null +++ b/Lang/Perl-6/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Parsing-Shunting-yard-algorithm b/Lang/Perl-6/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..2803570bf5 --- /dev/null +++ b/Lang/Perl-6/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/XML-Input b/Lang/Perl-6/XML-Input new file mode 120000 index 0000000000..7d7e79a3c9 --- /dev/null +++ b/Lang/Perl-6/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/00DESCRIPTION b/Lang/Perl/00DESCRIPTION index 3e976e8802..15dcfd719e 100644 --- a/Lang/Perl/00DESCRIPTION +++ b/Lang/Perl/00DESCRIPTION @@ -1,4 +1,5 @@ {{language +|site=http://www.perl.org/ |exec=bytecode |strength=weak |express=implicit diff --git a/Lang/Perl/Draw-a-sphere b/Lang/Perl/Draw-a-sphere new file mode 120000 index 0000000000..676d822c9e --- /dev/null +++ b/Lang/Perl/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Perl \ No newline at end of file diff --git a/Lang/Perl/Parsing-Shunting-yard-algorithm b/Lang/Perl/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..ae9cd357d9 --- /dev/null +++ b/Lang/Perl/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Perl \ No newline at end of file diff --git a/Lang/Perl/String-comparison b/Lang/Perl/String-comparison new file mode 120000 index 0000000000..41a8fa3fb7 --- /dev/null +++ b/Lang/Perl/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Perl \ No newline at end of file diff --git a/Lang/Perl/Tic-tac-toe b/Lang/Perl/Tic-tac-toe new file mode 120000 index 0000000000..526d19c878 --- /dev/null +++ b/Lang/Perl/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Perl \ No newline at end of file diff --git a/Lang/Pike/00DESCRIPTION b/Lang/Pike/00DESCRIPTION index 6a9f781bb5..719882440c 100644 --- a/Lang/Pike/00DESCRIPTION +++ b/Lang/Pike/00DESCRIPTION @@ -1,6 +1,6 @@ {{language|Pike |exec=bytecode -|site=http://pike.ida.liu.se/ +|site=http://pike.lysator.liu.se/ |strength=strong |safety=safe |compat=structural @@ -11,7 +11,7 @@ |LCT=yes}} {{language programming paradigm|Object-oriented}} -From the official [http://pike.ida.liu.se web site], Pike is an interpreted, general-purpose, high-level, cross-platform, dynamic programming language, with a syntax similar to [[Java]] and [[C]]. +From the official [http://pike.lysator.liu.se web site], Pike is an interpreted, general-purpose, high-level, cross-platform, dynamic programming language, with a syntax similar to [[Java]] and [[C]]. ==See also== * [[wp:Pike_(programming_language)|Pike on Wikipedia]] \ No newline at end of file diff --git a/Lang/PowerShell/Digital-root b/Lang/PowerShell/Digital-root new file mode 120000 index 0000000000..49d6ada060 --- /dev/null +++ b/Lang/PowerShell/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Hailstone-sequence b/Lang/PowerShell/Hailstone-sequence new file mode 120000 index 0000000000..112121b9dd --- /dev/null +++ b/Lang/PowerShell/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/I-before-E-except-after-C b/Lang/PowerShell/I-before-E-except-after-C new file mode 120000 index 0000000000..1f9c1e376a --- /dev/null +++ b/Lang/PowerShell/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Input-loop b/Lang/PowerShell/Input-loop new file mode 120000 index 0000000000..d7ac3040fa --- /dev/null +++ b/Lang/PowerShell/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Integer-sequence b/Lang/PowerShell/Integer-sequence new file mode 120000 index 0000000000..46b16d03c6 --- /dev/null +++ b/Lang/PowerShell/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Read-a-file-line-by-line b/Lang/PowerShell/Read-a-file-line-by-line new file mode 120000 index 0000000000..ea049ab76d --- /dev/null +++ b/Lang/PowerShell/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Read-a-specific-line-from-a-file b/Lang/PowerShell/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..5083c8a341 --- /dev/null +++ b/Lang/PowerShell/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/SHA-1 b/Lang/PowerShell/SHA-1 new file mode 120000 index 0000000000..2a6d1f5629 --- /dev/null +++ b/Lang/PowerShell/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sum-digits-of-an-integer b/Lang/PowerShell/Sum-digits-of-an-integer new file mode 120000 index 0000000000..8b2c5e079f --- /dev/null +++ b/Lang/PowerShell/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PowerShell \ No newline at end of file diff --git a/Lang/Prolog/Associative-array-Iteration b/Lang/Prolog/Associative-array-Iteration new file mode 120000 index 0000000000..6f5b96f781 --- /dev/null +++ b/Lang/Prolog/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Even-or-odd b/Lang/Prolog/Even-or-odd new file mode 120000 index 0000000000..3667062c4a --- /dev/null +++ b/Lang/Prolog/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Shell-one-liner b/Lang/Prolog/Shell-one-liner new file mode 120000 index 0000000000..3e55165691 --- /dev/null +++ b/Lang/Prolog/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Variadic-function b/Lang/Prolog/Variadic-function new file mode 120000 index 0000000000..b69e370cf3 --- /dev/null +++ b/Lang/Prolog/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Prolog \ No newline at end of file diff --git a/Lang/Pure-Data/00DESCRIPTION b/Lang/Pure-Data/00DESCRIPTION index 86052767ae..684b02a343 100644 --- a/Lang/Pure-Data/00DESCRIPTION +++ b/Lang/Pure-Data/00DESCRIPTION @@ -1,5 +1,6 @@ {{stub}} -{{language -|site=http://puredata.info/ -}} -Pd (aka Pure Data) is a real-time graphical programming environment for audio, video, and graphical processing. \ No newline at end of file +{{language|Pure Data +|site=http://puredata.info}} +Pd (aka Pure Data) is a real-time graphical programming environment for audio, video, and graphical processing. + +Pure Data (aka Pd) is an open source visual programming language. Pd enables musicians, visual artists, performers, researchers, and developers to create software graphically, without writing lines of code. \ No newline at end of file diff --git a/Lang/Pure/00DESCRIPTION b/Lang/Pure/00DESCRIPTION index 9a23a85244..617d87e28a 100644 --- a/Lang/Pure/00DESCRIPTION +++ b/Lang/Pure/00DESCRIPTION @@ -1,12 +1,12 @@ {{language|Pure -|site=http://code.google.com/p/pure-lang/ +|site=http://purelang.bitbucket.org/ |compat=structural |checking=dynamic |strength=strong |gc=yes |LCT=yes}}{{language programming paradigm|Dynamic}}{{language programming paradigm|Functional}} -From the official [http://pure-lang.googlecode.com/svn/docs/pure.html Pure manual]: "Pure is a modern-style functional programming language based on term rewriting. Pure programs are basically collections of equational rules used to evaluate expressions in a symbolic fashion by reducing them to normal form." +From the official [http://puredocs.bitbucket.org/pure.html Pure manual]: "Pure is a modern-style functional programming language based on term rewriting. Pure programs are basically collections of equational rules used to evaluate expressions in a symbolic fashion by reducing them to normal form." The Pure interpreter uses LLVM to JIT-compile code; in addition, Pure programs can be compiled with LLVM to machine code as well. diff --git a/Lang/R/Knights-tour b/Lang/R/Knights-tour new file mode 120000 index 0000000000..01ae018f65 --- /dev/null +++ b/Lang/R/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/R \ No newline at end of file diff --git a/Lang/REXX/Empty-directory b/Lang/REXX/Empty-directory new file mode 120000 index 0000000000..b3c2bdb9ec --- /dev/null +++ b/Lang/REXX/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/REXX \ No newline at end of file diff --git a/Lang/REXX/Events b/Lang/REXX/Events new file mode 120000 index 0000000000..0bab154e0b --- /dev/null +++ b/Lang/REXX/Events @@ -0,0 +1 @@ +../../Task/Events/REXX \ No newline at end of file diff --git a/Lang/REXX/Plot-coordinate-pairs b/Lang/REXX/Plot-coordinate-pairs new file mode 120000 index 0000000000..e6ab9ed372 --- /dev/null +++ b/Lang/REXX/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/REXX \ No newline at end of file diff --git a/Lang/REXX/Verify-distribution-uniformity-Naive b/Lang/REXX/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..1a64089c18 --- /dev/null +++ b/Lang/REXX/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/REXX \ No newline at end of file diff --git a/Lang/REXX/Walk-a-directory-Non-recursively b/Lang/REXX/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..02983994e2 --- /dev/null +++ b/Lang/REXX/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/REXX \ No newline at end of file diff --git a/Lang/REXX/Walk-a-directory-Recursively b/Lang/REXX/Walk-a-directory-Recursively new file mode 120000 index 0000000000..f93df4f865 --- /dev/null +++ b/Lang/REXX/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/REXX \ No newline at end of file diff --git a/Lang/RTSL/00DESCRIPTION b/Lang/RTSL/00DESCRIPTION index 2e3e3d5295..9deddfa6e6 100644 --- a/Lang/RTSL/00DESCRIPTION +++ b/Lang/RTSL/00DESCRIPTION @@ -1,7 +1,5 @@ -{{language -|site=http://citeseerx.ist.psu.edu/ -}} - +{{language}} RTSL is a domain specific programming language for extending ray tracing systems. +See also: [http://www.cs.utah.edu/~boulos/papers/rtsl.pdf "RTSL: a Ray Tracing Shading Language" (Parker, Boulos, Bigler, Robison)] [[Category:Raytracing]] \ No newline at end of file diff --git a/Lang/RapidQ/00DESCRIPTION b/Lang/RapidQ/00DESCRIPTION index 2bd6564940..be9d29a8ae 100644 --- a/Lang/RapidQ/00DESCRIPTION +++ b/Lang/RapidQ/00DESCRIPTION @@ -1,4 +1,5 @@ {{language|RapidQ +|site=http://rapidq.webcindario.com/index.html |strength=strong |safety=safe |checking=static diff --git a/Lang/Raven/00DESCRIPTION b/Lang/Raven/00DESCRIPTION index a500b93e07..6e3aed39c7 100644 --- a/Lang/Raven/00DESCRIPTION +++ b/Lang/Raven/00DESCRIPTION @@ -1,4 +1,6 @@ -{{language|Raven}}Raven is an eclectic language with features derived from [[derived from::Python]], [[derived from::Forth]], and [[derived from::Perl]]. It was developed independently by [[User:Mythago|Sean Pringle]]. Raven is available from [http://aerosuidae.net aerosuidae.net] under the GNU General Public License. It is currently only available for the [[runs on::Linux]] platform. +{{language|Raven +|site=http://aerosuidae.net/raven.html}} +Raven is an eclectic language with features derived from [[derived from::Python]], [[derived from::Forth]], and [[derived from::Perl]]. It was developed independently by [[User:Mythago|Sean Pringle]]. Raven is available from [http://aerosuidae.net aerosuidae.net] under the GNU General Public License. It is currently only available for the [[runs on::Linux]] platform. ==Features== Its described feature set includes: diff --git a/Lang/Refal/00DESCRIPTION b/Lang/Refal/00DESCRIPTION index f66cf163bf..ac95bf6da2 100644 --- a/Lang/Refal/00DESCRIPTION +++ b/Lang/Refal/00DESCRIPTION @@ -1 +1,3 @@ -{{language}}{{stub}} \ No newline at end of file +{{stub}} +{{language +|site=http://www.refal.net/index_e.htm}} \ No newline at end of file diff --git a/Lang/Ruby/Averages-Mean-time-of-day b/Lang/Ruby/Averages-Mean-time-of-day new file mode 120000 index 0000000000..618c74f20f --- /dev/null +++ b/Lang/Ruby/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Element-wise-operations b/Lang/Ruby/Element-wise-operations new file mode 120000 index 0000000000..3bcda8c276 --- /dev/null +++ b/Lang/Ruby/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Permutations-by-swapping b/Lang/Ruby/Permutations-by-swapping new file mode 120000 index 0000000000..38c3533897 --- /dev/null +++ b/Lang/Ruby/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Variable-size-Get b/Lang/Ruby/Variable-size-Get new file mode 120000 index 0000000000..5b66b05e76 --- /dev/null +++ b/Lang/Ruby/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Write-language-name-in-3D-ASCII b/Lang/Ruby/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..fb2d331d26 --- /dev/null +++ b/Lang/Ruby/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Ruby \ No newline at end of file diff --git a/Lang/Rust/A+B b/Lang/Rust/A+B new file mode 120000 index 0000000000..2fb1513469 --- /dev/null +++ b/Lang/Rust/A+B @@ -0,0 +1 @@ +../../Task/A+B/Rust \ No newline at end of file diff --git a/Lang/Rust/Ackermann-function b/Lang/Rust/Ackermann-function new file mode 120000 index 0000000000..8e61ac4e80 --- /dev/null +++ b/Lang/Rust/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Rust \ No newline at end of file diff --git a/Lang/Rust/Anagrams b/Lang/Rust/Anagrams new file mode 120000 index 0000000000..e58dffb584 --- /dev/null +++ b/Lang/Rust/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Rust \ No newline at end of file diff --git a/Lang/Rust/Arithmetic-Complex b/Lang/Rust/Arithmetic-Complex new file mode 120000 index 0000000000..c777b6ff14 --- /dev/null +++ b/Lang/Rust/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Rust \ No newline at end of file diff --git a/Lang/Rust/Binary-search b/Lang/Rust/Binary-search new file mode 120000 index 0000000000..d54c2fa018 --- /dev/null +++ b/Lang/Rust/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Rust \ No newline at end of file diff --git a/Lang/Rust/Bulls-and-cows b/Lang/Rust/Bulls-and-cows new file mode 120000 index 0000000000..9a0a5c4ded --- /dev/null +++ b/Lang/Rust/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Rust \ No newline at end of file diff --git a/Lang/Rust/Combinations b/Lang/Rust/Combinations new file mode 120000 index 0000000000..09d8f29634 --- /dev/null +++ b/Lang/Rust/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Rust \ No newline at end of file diff --git a/Lang/Rust/Concurrent-computing b/Lang/Rust/Concurrent-computing new file mode 120000 index 0000000000..e57cd2e79b --- /dev/null +++ b/Lang/Rust/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Rust \ No newline at end of file diff --git a/Lang/Rust/Entropy b/Lang/Rust/Entropy new file mode 120000 index 0000000000..99a057efce --- /dev/null +++ b/Lang/Rust/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Rust \ No newline at end of file diff --git a/Lang/Rust/Enumerations b/Lang/Rust/Enumerations new file mode 120000 index 0000000000..2b0f199c28 --- /dev/null +++ b/Lang/Rust/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Rust \ No newline at end of file diff --git a/Lang/Rust/Factorial b/Lang/Rust/Factorial new file mode 120000 index 0000000000..e49f5c2e08 --- /dev/null +++ b/Lang/Rust/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Rust \ No newline at end of file diff --git a/Lang/Rust/Fibonacci-n-step-number-sequences b/Lang/Rust/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..b0f61180ce --- /dev/null +++ b/Lang/Rust/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Rust \ No newline at end of file diff --git a/Lang/Rust/File-size b/Lang/Rust/File-size new file mode 120000 index 0000000000..e0cc7dc7b3 --- /dev/null +++ b/Lang/Rust/File-size @@ -0,0 +1 @@ +../../Task/File-size/Rust \ No newline at end of file diff --git a/Lang/Rust/Gray-code b/Lang/Rust/Gray-code new file mode 120000 index 0000000000..cfe3364eea --- /dev/null +++ b/Lang/Rust/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Rust \ No newline at end of file diff --git a/Lang/Rust/Guess-the-number-With-feedback b/Lang/Rust/Guess-the-number-With-feedback new file mode 120000 index 0000000000..d160e2b24e --- /dev/null +++ b/Lang/Rust/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Break b/Lang/Rust/Loops-Break new file mode 120000 index 0000000000..d2f052fce1 --- /dev/null +++ b/Lang/Rust/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Continue b/Lang/Rust/Loops-Continue new file mode 120000 index 0000000000..ee7166cdf7 --- /dev/null +++ b/Lang/Rust/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-For-with-a-specified-step b/Lang/Rust/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..b97701fd00 --- /dev/null +++ b/Lang/Rust/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Rust \ No newline at end of file diff --git a/Lang/Rust/Mutual-recursion b/Lang/Rust/Mutual-recursion new file mode 120000 index 0000000000..efa9378565 --- /dev/null +++ b/Lang/Rust/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Rust \ No newline at end of file diff --git a/Lang/Rust/N-queens-problem b/Lang/Rust/N-queens-problem new file mode 120000 index 0000000000..a56aa76327 --- /dev/null +++ b/Lang/Rust/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Rust \ No newline at end of file diff --git a/Lang/Rust/Random-numbers b/Lang/Rust/Random-numbers new file mode 120000 index 0000000000..e261891398 --- /dev/null +++ b/Lang/Rust/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Read-entire-file b/Lang/Rust/Read-entire-file new file mode 120000 index 0000000000..27a50e670c --- /dev/null +++ b/Lang/Rust/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Roman-numerals-Decode b/Lang/Rust/Roman-numerals-Decode new file mode 120000 index 0000000000..69dccfd9f9 --- /dev/null +++ b/Lang/Rust/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Rust \ No newline at end of file diff --git a/Lang/Rust/Roman-numerals-Encode b/Lang/Rust/Roman-numerals-Encode new file mode 120000 index 0000000000..16e99f09c9 --- /dev/null +++ b/Lang/Rust/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Rust \ No newline at end of file diff --git a/Lang/Rust/Rot-13 b/Lang/Rust/Rot-13 new file mode 120000 index 0000000000..8ed87978e0 --- /dev/null +++ b/Lang/Rust/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Insertion-sort b/Lang/Rust/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..886e502049 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/String-case b/Lang/Rust/String-case new file mode 120000 index 0000000000..9874a6e2a1 --- /dev/null +++ b/Lang/Rust/String-case @@ -0,0 +1 @@ +../../Task/String-case/Rust \ No newline at end of file diff --git a/Lang/Rust/Sum-and-product-of-an-array b/Lang/Rust/Sum-and-product-of-an-array new file mode 120000 index 0000000000..79ce607e8d --- /dev/null +++ b/Lang/Rust/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Rust \ No newline at end of file diff --git a/Lang/SIMPOL/00DESCRIPTION b/Lang/SIMPOL/00DESCRIPTION index d835d3adcd..d007a14e4f 100644 --- a/Lang/SIMPOL/00DESCRIPTION +++ b/Lang/SIMPOL/00DESCRIPTION @@ -12,5 +12,4 @@ The language itself has a very small keyword set and a small set of operators. I There are some interesting quirks in the language, especially with the operators. For example, strings can be not only added (concatenated), they can be used with the the unary minus, subtraction, and multiplication operators. -Programs are developed and debugged using a Windows-based IDE and a set of RAD tools for creating databases and forms. Resulting programs are compiled to a cross-platform byte code that is executed using the SIMPOL runtime environment. -{{language}}{{stub}} \ No newline at end of file +Programs are developed and debugged using a Windows-based IDE and a set of RAD tools for creating databases and forms. Resulting programs are compiled to a cross-platform byte code that is executed using the SIMPOL runtime environment. \ No newline at end of file diff --git a/Lang/SQL/00DESCRIPTION b/Lang/SQL/00DESCRIPTION index 04c508ad95..8a74fbabbb 100644 --- a/Lang/SQL/00DESCRIPTION +++ b/Lang/SQL/00DESCRIPTION @@ -1,8 +1,12 @@ {{stub}} {{language|SQL|bnf=http://savage.net.au/SQL/sql-2003-2.bnf.html}} -{{Language programming paradigm|Query}} +{{Language programming paradigm|Declarative}} -'''[[wp:SQL|Structured Query Language]]''' (SQL) is the ''lingua franca'' for modifying and performing queries in database systems based on Dr. Edgar F. Codd's relational model. (Dr. Codd did not create the SQL language itself.) +'''[[wp:SQL|Structured Query Language]]''' (SQL) is the ''lingua franca'' for modifying and performing queries in database systems based on Dr. Edgar F. Codd's relational model. (Dr. Codd did not create the SQL language itself.) + +SQL has come a long way and it does carry its 30-year-old legacy. But with legacy comes traction and robustness, and up to date, SQL has been the unchallenged means of querying and interoperating with RDBMS. + +Some non-RDBMS have even started to adopt SQL-esque languages as their querying interfaces because of the simplicity and expressiveness of SQL. It is mostly declarative, but each database vendor has extended their dialect of SQL in various incompatible ways to give it more power or to simplify their implementation. diff --git a/Lang/SQL/Top-rank-per-group b/Lang/SQL/Top-rank-per-group new file mode 120000 index 0000000000..b9db7a52d6 --- /dev/null +++ b/Lang/SQL/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/SQL \ No newline at end of file diff --git a/Lang/Scala/00DESCRIPTION b/Lang/Scala/00DESCRIPTION index ba9ce24e3c..ff27b4ec4b 100644 --- a/Lang/Scala/00DESCRIPTION +++ b/Lang/Scala/00DESCRIPTION @@ -9,8 +9,8 @@ |bnf=http://www.scala-lang.org/docu/files/ScalaReference.pdf}} {{language programming paradigm|functional}} {{language programming paradigm|object-oriented}} -{{language programming paradigm|generic}}Scala is a hybrid [[functional programming|Functional]]/[[object-oriented|OO]] language developed by Martin Odersky and his team at [http://lamp.epfl.ch/ LAMP]. Scala compiles to [[runs on vm::Java Virtual Machine|JVM]] [[bytecode]], and can inter-operate with [[Java]] code. Running as a .Net [[Common Language Runtime]] application is also supported. +{{language programming paradigm|generic}}Scala is a hybrid [[functional programming|Functional]]/[[object-oriented|OO]] language developed by Martin Odersky and his team at [http://lamp.epfl.ch/ LAMP]. Scala compiles to [[runs on vm::Java Virtual Machine|JVM]] [[bytecode]], and can inter-operate with [[Java]] code. The language is most focused on the results of the program, therefor the [http://en.wikipedia.org/wiki/Considered_harmful considered harmful] technical computer oriented concepts like threads, semaphore, pointers, goto- and break statements to struggle with are not there. For parallel processing (that very simple can archived) these concept are present but not visible to the programmer. -Lots of RC tasks addresses technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on and are deliberate not Scala's cup of tea. \ No newline at end of file +Lots of RC tasks addresses technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on and are deliberately not Scala's cup of tea. \ No newline at end of file diff --git a/Lang/Scala/Inheritance-Multiple b/Lang/Scala/Inheritance-Multiple new file mode 120000 index 0000000000..34cda3763b --- /dev/null +++ b/Lang/Scala/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Scala \ No newline at end of file diff --git a/Lang/Scheme/Caesar-cipher b/Lang/Scheme/Caesar-cipher new file mode 120000 index 0000000000..5f8ab37830 --- /dev/null +++ b/Lang/Scheme/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Matrix-exponentiation-operator b/Lang/Scheme/Matrix-exponentiation-operator new file mode 120000 index 0000000000..420ffb158e --- /dev/null +++ b/Lang/Scheme/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Modular-exponentiation b/Lang/Scheme/Modular-exponentiation new file mode 120000 index 0000000000..0757dcca79 --- /dev/null +++ b/Lang/Scheme/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/String-comparison b/Lang/Scheme/String-comparison new file mode 120000 index 0000000000..6f57b9549b --- /dev/null +++ b/Lang/Scheme/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Scheme \ No newline at end of file diff --git a/Lang/Seed7/Permutation-test b/Lang/Seed7/Permutation-test new file mode 120000 index 0000000000..3f85a7cefc --- /dev/null +++ b/Lang/Seed7/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Cocktail-sort b/Lang/Seed7/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..13acddf6b2 --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Seed7 \ No newline at end of file diff --git a/Lang/Smalltalk/Even-or-odd b/Lang/Smalltalk/Even-or-odd new file mode 120000 index 0000000000..6c4b8a14ac --- /dev/null +++ b/Lang/Smalltalk/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Factors-of-an-integer b/Lang/Smalltalk/Factors-of-an-integer new file mode 120000 index 0000000000..feebe1938c --- /dev/null +++ b/Lang/Smalltalk/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Find-limit-of-recursion b/Lang/Smalltalk/Find-limit-of-recursion new file mode 120000 index 0000000000..5bdf139160 --- /dev/null +++ b/Lang/Smalltalk/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Fractal-tree b/Lang/Smalltalk/Fractal-tree new file mode 120000 index 0000000000..e788208f86 --- /dev/null +++ b/Lang/Smalltalk/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Smalltalk \ No newline at end of file diff --git a/Lang/Soar/00DESCRIPTION b/Lang/Soar/00DESCRIPTION index 68689371af..c389edd5aa 100644 --- a/Lang/Soar/00DESCRIPTION +++ b/Lang/Soar/00DESCRIPTION @@ -1,5 +1,6 @@ -This is the cognitive architecture created by created by John Laird, Allen Newell, and Paul Rosenbloom. +{{language +|site=http://sitemaker.umich.edu/soar/home +}} +This is the cognitive architecture created by John Laird, Allen Newell, and Paul Rosenbloom. -The primary implementation is on google code: http://code.google.com/p/soar/ - -{{language}} \ No newline at end of file +The primary implementation is on google code: http://code.google.com/p/soar/ \ No newline at end of file diff --git a/Lang/Standard-ML/Combinations-with-repetitions b/Lang/Standard-ML/Combinations-with-repetitions new file mode 120000 index 0000000000..5be383f349 --- /dev/null +++ b/Lang/Standard-ML/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Count-in-octal b/Lang/Standard-ML/Count-in-octal new file mode 120000 index 0000000000..2e3f8d7fcc --- /dev/null +++ b/Lang/Standard-ML/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Include-a-file b/Lang/Standard-ML/Include-a-file new file mode 120000 index 0000000000..76b08ccbce --- /dev/null +++ b/Lang/Standard-ML/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Luhn-test-of-credit-card-numbers b/Lang/Standard-ML/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..5aaa0c9310 --- /dev/null +++ b/Lang/Standard-ML/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Substring-Top-and-tail b/Lang/Standard-ML/Substring-Top-and-tail new file mode 120000 index 0000000000..ba9e9d2c6b --- /dev/null +++ b/Lang/Standard-ML/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Standard-ML \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Binary-search b/Lang/TI-83-BASIC/Binary-search new file mode 120000 index 0000000000..378084a2c6 --- /dev/null +++ b/Lang/TI-83-BASIC/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Hello-world-Graphical b/Lang/TI-83-BASIC/Hello-world-Graphical new file mode 120000 index 0000000000..275571cdfd --- /dev/null +++ b/Lang/TI-83-BASIC/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Loops-For b/Lang/TI-83-BASIC/Loops-For new file mode 120000 index 0000000000..06f21585d2 --- /dev/null +++ b/Lang/TI-83-BASIC/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Menu b/Lang/TI-83-BASIC/Menu new file mode 120000 index 0000000000..2035d150a9 --- /dev/null +++ b/Lang/TI-83-BASIC/Menu @@ -0,0 +1 @@ +../../Task/Menu/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Pascals-triangle b/Lang/TI-83-BASIC/Pascals-triangle new file mode 120000 index 0000000000..50b3b28731 --- /dev/null +++ b/Lang/TI-83-BASIC/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TPP/00DESCRIPTION b/Lang/TPP/00DESCRIPTION index 37a044d51b..3fced52348 100644 --- a/Lang/TPP/00DESCRIPTION +++ b/Lang/TPP/00DESCRIPTION @@ -1,4 +1,4 @@ {{stub}}{{language|tpp -|site=http://http://www.ngolde.de/tpp.html}} +|site=http://www.ngolde.de/tpp.html}} This is the markup language used by Nico Golde's text presentation program. \ No newline at end of file diff --git a/Lang/TXR/00DESCRIPTION b/Lang/TXR/00DESCRIPTION index c8b9192a97..e908b2ce73 100644 --- a/Lang/TXR/00DESCRIPTION +++ b/Lang/TXR/00DESCRIPTION @@ -1,168 +1,58 @@ -{{stub}}{{language +{{language |site=http://www.nongnu.org/txr/}} TXR is a new language implemented in [[C]], running on POSIX platforms such as [[Linux]], [[Mac OS X]] and on Windows via [[Cygwin]] as well as more natively thanks to [[MinGW]]. +The Rosetta Code TXR solutions can be viewed in color, and all on one page with a convenient navigation pane [http://www.nongnu.org/txr/rosetta-solutions.html here]. + TXR started as a language for "reversing here-documents": evaluating a template of text containing variables, plus useful pattern matching directives, against some body of text and binding pieces of the text which matches variables. The variable bindings were output in POSIX shell variable assignment syntax, allowing for shell code like eval $(txr ...) -TXR remains close to these roots: its main language is the pattern-based text extraction notation well suited for matching large regions of -entire text documents. +TXR remains close to these roots: its main language is the pattern-based text extraction notation well-suited for matching large regions of +entire text documents. That language has become powerful enough to neatly parse grammars, while the tool developed a Lisp dialect to round out the functionality and increase its power. -About the @ character: this serves as a multi-level escape in TXR. In the fundamental TXR syntax, which is literal text, this character is a signal which indicates that the object which follows is a variable or directive. Then inside a directive, the character indicates that the object which follows is a TXR Lisp expression to be evaluated as such, rather than according to the expression evaluation rules of the pattern language. (And it is possible for TXR Lisp code to give this character additional meanings, since inside TXR Lisp, the notation expands to Lisp syntax: @foo denotes (sys:var foo), and @(foo ...) denotes (sys:expr foo>). In any context which needs to separate meta-variables and meta-expressions from variables and expressions, this may come in handy.) +=== What's with all that @ stuff? === -Thus, the source of a TXR query is literal text except for directives and variables preceded by the @ character. +About the @ character: this serves as a multi-level escape in TXR. In the fundamental TXR syntax, which is literal text, this character is a signal which indicates that the object which follows is a variable or directive. Then inside a directive, the character indicates that the object which follows is a TXR Lisp expression to be evaluated as such, rather than according to the expression evaluation rules of the pattern language: -In this pattern language, computation evolves by textual pattern matching with implicit backtracking. Non-pattern matching activities are embedded into a pattern matching paradigm. For instance, the line +
This is some literal text to be matched.
+@# this is a comment in the pattern language.
+This text matches and binds @variable.
+@(bind y  ;; this is the start of a directive in the TXR pattern language
+   @(> x 42) ;; this is an expression in TXR Lisp
+)
+Back to text.
-
Four score and seven years ago,
+In TXR Lisp, the @ character has more "meta" piled on top of it: @foo denotes (sys:var foo), and @(foo ...) denotes (sys:expr foo>). In any context which needs to separate meta-variables and meta-expressions from variables and expressions, this may come in handy. It's used by the op operator for currying, for instance (op * @1 @1) returns a function of one argument which returns the square of that argument. The implementation of the operator looks for syntax like (sys:var 1) and replaces it with the arguments of the generated lambda function. The @ character also appears in quasiliteral strings, where it interpolates the values of variables and expressions as text. -is a TXR directive which matches a line of that exact text, or else fails. The following is also a directive: +TXR is somewhat unusual in that the relationship between a domain-specific language (DSL) and general-purpose host language is reversed. Typically, at least in Lisp systems, DSL's are embedded into the parent language. In TXR, the "outer shell" is the domain-specific language for extracting text, and Lisp is embedded in it as "computational appliance". It doesn't take much to reach the Lisp though: a TXR source file can just consist of a single @(do ...) directive which contains nothing but TXR Lisp forms. Also, TXR Lisp evaluation is available from program invocation via the -e and -p options. -@(bind foo "abc") +The second unusual feature in TXR Lisp is that the "tokens" in the pattern matching language are essentially themselves Lisp symbols and expressions. These "tokens" are used to create a block-structured language. This is quite odd. For instance a construct might begin with a @(collect :vars (foo)). This is a Lisp expression with interior structure, but to the parser of the pattern language, it's also basically just a token, like a giant keyword. IT begins a collect clause, and is followed by some optional material which may just be literal text, and must be terminated by the @(end) directive: another token-expression entity. -which succeeds if foo has no prior binding, or already contains "abc", but fails if foo has a binding to something other than "abc". +=== Dual Personality === -The success of a directive means that computation proceeds to the next directive (and, if this is a pattern match, the input position advances). Failure means that the enclosing query fails, triggering back-tracking behaviors and possibly failure of the entire query. +From the solutions below, it is obvious that some of them make heavy use of the pattern language and little or no TXR Lisp. Others are quite the other way around, based entirely or almost entirely on Lisp, whereas others follow strategies of mixing the approaches. -A bizarre feature of TXR is that the directives like @(collect) are independent pieces of Lisp. But, they are also de-facto "tokens" in a block-structure language. For instance @(collect) starts a block, which must be terminated by @(end). Inside @(collect) there can be additional syntax, such as @(collect :gap 0 :vars (a b c)). +=== Lisp Innovation === -==Extremely Simple Query== +Although TXR Lisp is heavily based on prior work and strongly influenced by Common Lisp (for instance, there is a real nil symbol which is a list terminator and means "false", and it's primarily Lisp-2 dialect), TXR Lisp nevertheless manages to innovate within the world of Lisp. -Extract first matching line from the password file. Of course, TXR matches are not restricted to single line! +==== Can't We All Just Get Along? ==== -$ txr -c '@(skip) -@user:@pw:@uid:@gid:@gecos:@home:@shell' /etc/passwd -
-user="root"
-pw="x"
-uid="0"
-gid="0"
-gecos="root"
-home="/root"
-shell="/bin/bash"
+One major innovation is the way in which TXR Lisp closes the ages-old gap between Lisp-1 and Lisp-2, and the associated religious sectarian division it has caused. TXR Lisp recognizes that there are advantages both in having separate function and variable namespaces, and in having a single namespace: and it provides support for both approaches. The idea is devilishly simple. A special operator called "dwim" (do what I mean) is provided such that (dwim forms ...) basically denotes (forms ...), but with Lisp-1 style evaluation: any of the forms which are symbols are resolved according to a flattened namespace that combines variable and function bindings (with conflicts resolved in favor of variables). TXR Lisp programmers do not use the dwim operator directly, but rather the square bracket notation [a b c ...] -> (dwim a b c). So for instance, [mapcar list '(1 2 3) '(a b c)] zips together two lists. Using round brackets, it would have to be (mapcar (fun list) '(1 2 3) '(a b c)). Moreover, if foo is a variable that holds a function of one argument, it has to be called using (call foo arg). But with the "dwim brackets", it is just [foo arg]. The "dwim brackets" also support various funcall-extensions, like indexing into arrays and slicing and so on. If h is a hash then [h "a" 42] looks up the string a in the hash and returns the value, or else returns 42 if the key is not found. If a is an array, list or string, then [a 2..3] extracts a slice. On the other hand, "dwim brackets" do not support operators: [let (a b c) ...] is not valid; or rather, it expects a variable or function let to exist, ignoring the let operator. Operators are strictly in the Lisp-2 domain, which is fine because Lisp-2 is a cleaner model with regard to operators anyway! -Now, pre-bind the user variable first to retrieve some other user. Now @(skip) kicks into action, skipping non-matching material: +==== Polymorphizing the Classics ==== -$ txr -Duser=sshd -c '@(skip) -@user:@pw:@uid:@gid:@gecos:@home:@shell' /etc/passwd -
user="sshd"
-pw="x"
-uid="114"
-gid="65534"
-gecos=""
-home="/var/run/sshd"
-shell="/usr/sbin/nologin"
+In TXR Lisp, classic Lisp operations like mapcar, cdr or append work exactly like they are supposed to, when they operate on lists. Right down to improper lists like (append 42) -> 42 and (append '(1) 2) -> (1 . 2). +However, most of the operations have been extended to also work with strings and vectors. So for instance, (mapcar (op + 1) "abc") nicely yields the string "bcd" where 1 has been added to every character code of the original string. (car "abc") yields #\a, a character, (cdr "abc") yields "bc", and (cdr "c") yields nil (rather than the empty string!) (Almost) everything proceeds from there. +==== Good Hackers Borrow; Great Ones Steal ==== -==Simple Query== +TXR steals ideas from libraries and languages related to Lisp. The op operator is inspired by Goo's op, and the cl-op library for Common Lisp which is also inspired by Goo's op. -Re-implement the "free" utility on Linux, showing an overview of memory use: +Array and list slices are straight out of Python, right down to the half-open ranges (not including the upper endpoint), and negative values indexing from the tail of the array. The concept is further improved upon by allowing the Lisp symbols nil and t to be used as range indexes. -#!/usr/bin/txr -f -@(next "/proc/meminfo") -@(define num (n))@\ - @(local numtok)@{numtok /[0-9]+/}@(bind n @(int-str numtok 10))@\ -@(end) -@(gather) -MemTotal: @(num TOTAL) kB -MemFree: @(num FREE) kB -Buffers: @(num BUFS) kB -Cached: @(num CACHED) kB -SwapTotal: @(num SWTOT) kB -SwapFree: @(num SWFRE) kB -@(end) -@(bind USED @(- TOTAL FREE 10)) -@(bind RUSED @(- USED BUFS CACHED)) -@(bind RFREE @(+ FREE BUFS CACHED)) -@(bind SWUSE @(- SWTOT SWFRE)) -@(output) - TOTAL USED FREE BUFFERS CACHED -Mem: @{TOTAL -12} @{USED -12} @{FREE -12} @{BUFS -12} @{CACHED -12} -+/- buffers/cache: @{RUSED -12} @{RFREE -12} -Swap: @{SWTOT -12} @{SWUSE -12} @{SWFRE -12} -@(end) +Slices, even empty ones, are assignable places in TXR Lisp: we can easily replace a possibly empty section of a string, lisp or vector, with a sequence that is of different length, also possibly empty: for instance, if x contains "abc" then (set [x 1..2] "foo") changes x to contain "afooc". -Sample run: - -
$ ./meminfo.txr
-               TOTAL         USED         FREE      BUFFERS       CACHED
-Mem:          769280       647752       121528       160108       286844
-+/- buffers/cache:         200800       568480
-Swap:        1048568        18200      1030368
-
- -== Complex Query == - -Here is a TXR query for computing the complete dependencies of a C source file (including system and compiler headers) on a typical GNU/Linux system, demonstrating features like parallel clauses, recursion and exception handling. - -@(define process_file (dir file already_visited visited_out)) -@ (local this_file next_file header_dir next_dir next_dir2 visited_out_next) -@ (bind this_file `@dir@file`) -@ (none) -@ (bind already_visited this_file) -@ (end) -@ (merge already_visited already_visited this_file) -@ (next this_file) -@ (collect) -@ (cases) -#include "@*header_dir/@next_file" -@ (bind next_dir `@dir@header_dir/`) -@ (or) -#include "@next_file" -@ (bind next_dir dir) -@ (or) -#@/ */include <@*header_dir/@next_file> -@ (bind next_dir `@sys_includes@header_dir/`) -@ (bind next_dir2 `@gcc_includes@header_dir/`) -@ (or) -#@/ */include <@next_file> -@ (bind next_dir sys_includes) -@ (bind next_dir2 gcc_includes) -@ (or) -#@/ */include_next <@*header_dir/@next_file> -@ (bind next_dir `@gcc_includes@header_dir/`) -@ (or) -#@/ */include_next <@next_file> -@ (bind next_dir gcc_includes) -@ (end) -@ (try) -@ (process_file next_dir next_file already_visited visited_out_next) -@ (merge already_visited already_visited visited_out_next) -@ (catch file_error) -@ (try) -@ (process_file next_dir2 next_file already_visited visited_out_next) -@ (merge already_visited already_visited visited_out_next) -@ (catch file_error) -@ (end) -@ (end) -@ (end) -@ (bind visited_out this_file) -@ (try) -@ (flatten visited_out_next) -@ (merge visited_out visited_out visited_out_next) -@ (catch) -@ (end) -@(end) -@(next :args) -@(cases) -@*dir/@*file.@suffix -@ (bind directory `@dir/`) -@(or) -@*file.@suffix -@ (bind directory "") -@(end) -@(next `!gcc -print-search-dirs`) -install: @gcc_install -@(bind gcc_includes `@{gcc_install}include/`) -@(bind sys_includes "/usr/include/") -@(process_file directory `@file.@suffix` nil list_out) -@(output) -@(rep) @list_out@(first)@file.o:@(end) -@(end) - -Sample run: - -
$ txr dep.txr match.c
-match.o: /usr/include/stdio.h /usr/include/features.h /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h /usr/lib/gcc/i586-redhat-linux/4.4.1/include/stddef.h /usr/include/bits/types.h /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h /usr/lib/gcc/i586-redhat-linux/4.4.1/include/stdarg.h /usr/include/bits/wchar.h /usr/include/wctype.h /usr/include/endian.h /usr/include/bits/endian.h /usr/include/bits/byteswap.h /usr/include/xlocale.h /usr/include/bits/wchar2.h /usr/include/bits/wchar-ldbl.h /usr/include/gconv.h /usr/include/bits/stdio-lock.h /usr/include/bits/libc-lock.h /usr/include/pthread.h /usr/include/sched.h /usr/include/time.h /usr/include/bits/time.h /usr/include/bits/sched.h /usr/include/signal.h /usr/include/bits/signum.h /usr/include/bits/siginfo.h /usr/include/bits/sigaction.h /usr/include/bits/sigcontext.h /usr/include/asm/sigcontext.h /usr/include/linux/types.h /usr/include/linux/posix_types.h /usr/include/linux/stddef.h /usr/include/asm/posix_types.h /usr/include/asm/types.h /usr/include/asm-generic/int-ll64.h /usr/include/bits/sigstack.h /usr/include/sys/ucontext.h /usr/include/bits/pthreadtypes.h /usr/include/bits/sigthread.h /usr/include/bits/setjmp.h /usr/include/bits/libio-ldbl.h /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h /usr/include/getopt.h /usr/include/ctype.h /usr/include/bits/stdio.h /usr/include/bits/stdio2.h /usr/include/bits/stdio-ldbl.h /usr/include/stdlib.h /usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h /usr/include/alloca.h /usr/include/bits/stdlib.h /usr/include/bits/stdlib-ldbl.h /usr/include/string.h /usr/include/bits/string.h /usr/include/bits/string2.h /usr/include/bits/string3.h /usr/include/assert.h /usr/include/errno.h /usr/include/bits/errno.h /usr/include/linux/errno.h /usr/include/asm/errno.h /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h /usr/include/dirent.h /usr/include/bits/dirent.h /usr/include/bits/posix1_lim.h /usr/include/bits/local_lim.h /usr/include/linux/limits.h /usr/include/setjmp.h config.h lib.h gc.h unwind.h regex.h /usr/include/limits.h /usr/lib/gcc/i586-redhat-linux/4.4.1/include/limits.h /usr/lib/gcc/i586-redhat-linux/4.4.1/include/syslimits.h /usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h stream.h parser.h txr.h utf8.h filter.h match.h
\ No newline at end of file +The group-by function is a straight rip-off from Ruby. \ No newline at end of file diff --git a/Lang/TXR/Ackermann-function b/Lang/TXR/Ackermann-function new file mode 120000 index 0000000000..27c6cf6e75 --- /dev/null +++ b/Lang/TXR/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/TXR \ No newline at end of file diff --git a/Lang/TXR/Combinations b/Lang/TXR/Combinations new file mode 120000 index 0000000000..b0fe0ed4e2 --- /dev/null +++ b/Lang/TXR/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/TXR \ No newline at end of file diff --git a/Lang/TXR/Evaluate-binomial-coefficients b/Lang/TXR/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..14e2db8275 --- /dev/null +++ b/Lang/TXR/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/TXR \ No newline at end of file diff --git a/Lang/TXR/Factorial b/Lang/TXR/Factorial new file mode 120000 index 0000000000..5f857ff698 --- /dev/null +++ b/Lang/TXR/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/TXR \ No newline at end of file diff --git a/Lang/TXR/Find-limit-of-recursion b/Lang/TXR/Find-limit-of-recursion new file mode 120000 index 0000000000..d8dac92486 --- /dev/null +++ b/Lang/TXR/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/TXR \ No newline at end of file diff --git a/Lang/TXR/FizzBuzz b/Lang/TXR/FizzBuzz new file mode 120000 index 0000000000..ff6d80d167 --- /dev/null +++ b/Lang/TXR/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/TXR \ No newline at end of file diff --git a/Lang/TXR/Floyds-triangle b/Lang/TXR/Floyds-triangle new file mode 120000 index 0000000000..61542aed42 --- /dev/null +++ b/Lang/TXR/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/TXR \ No newline at end of file diff --git a/Lang/TXR/Mandelbrot-set b/Lang/TXR/Mandelbrot-set new file mode 120000 index 0000000000..1ae4e514ac --- /dev/null +++ b/Lang/TXR/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/TXR \ No newline at end of file diff --git a/Lang/TXR/Maze-generation b/Lang/TXR/Maze-generation new file mode 120000 index 0000000000..4a450764fb --- /dev/null +++ b/Lang/TXR/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/TXR \ No newline at end of file diff --git a/Lang/TXR/Metaprogramming b/Lang/TXR/Metaprogramming new file mode 120000 index 0000000000..3442a1a098 --- /dev/null +++ b/Lang/TXR/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/TXR \ No newline at end of file diff --git a/Lang/TXR/Parsing-RPN-to-infix-conversion b/Lang/TXR/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..9cd8c57740 --- /dev/null +++ b/Lang/TXR/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/TXR \ No newline at end of file diff --git a/Lang/TXR/Partial-function-application b/Lang/TXR/Partial-function-application new file mode 120000 index 0000000000..07df5faf52 --- /dev/null +++ b/Lang/TXR/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/TXR \ No newline at end of file diff --git a/Lang/TXR/Rename-a-file b/Lang/TXR/Rename-a-file new file mode 120000 index 0000000000..e5a84e7a33 --- /dev/null +++ b/Lang/TXR/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/TXR \ No newline at end of file diff --git a/Lang/TXR/Runtime-evaluation-In-an-environment b/Lang/TXR/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..ee43fac6a0 --- /dev/null +++ b/Lang/TXR/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/TXR \ No newline at end of file diff --git a/Lang/TXR/Set-consolidation b/Lang/TXR/Set-consolidation new file mode 120000 index 0000000000..55d41491f9 --- /dev/null +++ b/Lang/TXR/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/TXR \ No newline at end of file diff --git a/Lang/TXR/Top-rank-per-group b/Lang/TXR/Top-rank-per-group new file mode 120000 index 0000000000..06141ce708 --- /dev/null +++ b/Lang/TXR/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/TXR \ No newline at end of file diff --git a/Lang/TXR/Twelve-statements b/Lang/TXR/Twelve-statements new file mode 120000 index 0000000000..066ff5f5d4 --- /dev/null +++ b/Lang/TXR/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/TXR \ No newline at end of file diff --git a/Lang/TXR/Y-combinator b/Lang/TXR/Y-combinator new file mode 120000 index 0000000000..e276d88fd0 --- /dev/null +++ b/Lang/TXR/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/TXR \ No newline at end of file diff --git a/Lang/True-BASIC/00DESCRIPTION b/Lang/True-BASIC/00DESCRIPTION index 4d3d27c049..5e988b9b09 100644 --- a/Lang/True-BASIC/00DESCRIPTION +++ b/Lang/True-BASIC/00DESCRIPTION @@ -1 +1,3 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language +|site=http://www.truebasic.com/}} \ No newline at end of file diff --git a/Lang/UBASIC/00DESCRIPTION b/Lang/UBASIC/00DESCRIPTION index 24309cb390..a41ca548e4 100644 --- a/Lang/UBASIC/00DESCRIPTION +++ b/Lang/UBASIC/00DESCRIPTION @@ -1,6 +1,4 @@ -{{stub}}{{language}} - -UBASIC is a freeware BASIC interpreter written by Yuji Kida at Rikkyo University in Japan, specialized for mathematical computing. +{{implementation|BASIC}}'''UBASIC''' is a freeware BASIC interpreter written by Yuji Kida at Rikkyo University in Japan, specialized for mathematical computing. More information and links can be found at its [[wp:UBASIC|Wikipedia article]]. ==Sample Program== diff --git a/Lang/Vim-Script/00DESCRIPTION b/Lang/Vim-Script/00DESCRIPTION index ab1fd757bc..28977a85b4 100644 --- a/Lang/Vim-Script/00DESCRIPTION +++ b/Lang/Vim-Script/00DESCRIPTION @@ -1,10 +1,9 @@ -Vim Script is the language for editing the popular [http://www.vim.org/ Vim text editor]. It is also sometimes called VimL. It is the 13th most popular language on [https://github.com/languages/VimL GitHub]. -{{unimpl_Page|Vim_Script}} +{{stub}} +{{language}} +Vim Script is the language for editing the popular [http://www.vim.org/ Vim text editor]. It is also sometimes called VimL. == External Links == -* [http://www.vim.org Vim.org] - Official Site] +* [http://www.vim.org vim.org] - official site * [http://www.vim.org/scripts/ Vim's script repository] -* [http://vimdoc.sourceforge.net/htmldoc/usr_41.html "Write a Vim Script", intro to Vim Script in the Vim documentation] -* [http://learnvimscriptthehardway.stevelosh.com/ Learn Vimscript the Hard Way] - an online book for learning Vim Script] - -{{stub}}{{language}} \ No newline at end of file +* [http://vimdoc.sourceforge.net/htmldoc/usr_41.html "Write a Vim Script"] - intro to Vim Script in the Vim documentation +* [http://learnvimscriptthehardway.stevelosh.com/ Learn Vimscript the Hard Way] - an online book for learning Vim Script \ No newline at end of file diff --git a/Lang/Vim-Script/Remove-duplicate-elements b/Lang/Vim-Script/Remove-duplicate-elements new file mode 120000 index 0000000000..206f655844 --- /dev/null +++ b/Lang/Vim-Script/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Vim-Script \ No newline at end of file diff --git a/Lang/Visual-Objects/00DESCRIPTION b/Lang/Visual-Objects/00DESCRIPTION index b96402f30a..a8c663e13f 100644 --- a/Lang/Visual-Objects/00DESCRIPTION +++ b/Lang/Visual-Objects/00DESCRIPTION @@ -1,8 +1,6 @@ -{{ -language|Visual Objects +{{stub}} +{{language|Visual Objects |site=http://www.cavo.com/ -LST=no }} {{Wikipedia}} -Visual Objects is an object-oriented computer programming language that is used to create software programs that operate primarily under Windows. Although it can be used as a general-purpose programming tool, it is almost exclusively used to create database programs. -{{stub}} \ No newline at end of file +Visual Objects is an object-oriented computer programming language that is used to create software programs that operate primarily under Windows. Although it can be used as a general-purpose programming tool, it is almost exclusively used to create database programs. \ No newline at end of file diff --git a/Lang/Visual-Prolog/00DESCRIPTION b/Lang/Visual-Prolog/00DESCRIPTION index e81fe26b3a..185adf11ec 100644 --- a/Lang/Visual-Prolog/00DESCRIPTION +++ b/Lang/Visual-Prolog/00DESCRIPTION @@ -1,20 +1,20 @@ +{{language +|exec=machine +|gc=yes +|parampass=value +|checking=static +|safety=safe +|strength=strong +|express=partially implicit +|site=http://www.visual-prolog.com/}} Visual Prolog is a multi-paradigm language with origin in Prolog. See also * [[wp:Visual Prolog|Visual Prolog]] in Wikipedia -* [http://www.visual-prolog.com Visual Prolog home page] * [http://wiki.visual-prolog.com Visual Prolog wiki] -[[Category:Programming Languages]] -[[Category:Execution method/Compiled/Machine code]] -[[Category:Garbage collection/Yes]] -[[Category:Parameter passing/By value]] [[Category:Programming paradigm/Functional]] [[Category:Programming paradigm/Generic]] [[Category:Programming paradigm/Imperative]] [[Category:Programming paradigm/Logic Programming]] -[[Category:Programming paradigm/Object-oriented]] -[[Category:Typing/Checking/Static]] -[[Category:Typing/Expression/Partially implicit]] -[[Category:Typing/Safe]] -[[Category:Typing/Strong]] \ No newline at end of file +[[Category:Programming paradigm/Object-oriented]] \ No newline at end of file diff --git a/Lang/Wrapl/00DESCRIPTION b/Lang/Wrapl/00DESCRIPTION index 1f5ef4cd1f..41d53f3778 100644 --- a/Lang/Wrapl/00DESCRIPTION +++ b/Lang/Wrapl/00DESCRIPTION @@ -1,5 +1,5 @@ {{language|Wrapl -site=http://wrapl.sourceforge.net/ +|site=http://wrapl.sourceforge.net/ |exec=interpreted |parampass=reference |LCT=no diff --git a/Lang/XQuery/Y-combinator b/Lang/XQuery/Y-combinator new file mode 120000 index 0000000000..34893f9e8f --- /dev/null +++ b/Lang/XQuery/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/XQuery \ No newline at end of file diff --git a/Lang/Yacas/00DESCRIPTION b/Lang/Yacas/00DESCRIPTION index aebceeee0e..026997bb17 100644 --- a/Lang/Yacas/00DESCRIPTION +++ b/Lang/Yacas/00DESCRIPTION @@ -1,10 +1,10 @@ -{{stub}}{{language|Yacas +{{stub}} +{{language|Yacas +|site=http://yacas.sourceforge.net/ |exec=interpreted |LCT=no }} - YACAS (Yet Another Computer Algebra System) is an easy to use, general purpose Computer Algebra System, a program for symbolic manipulation of mathematical expressions. It uses its own programming language designed for symbolic as well as arbitrary-precision numerical computations. The system has a library of scripts that implement many of the symbolic algebra operations; new algorithms can be easily added to the library. YACAS comes with extensive documentation (hundreds of pages) covering the scripting language, the functionality that is already implemented in the system, and the algorithms used. - == See Also == *[[wp:Yacas|Wikipedia : Yacas]] \ No newline at end of file diff --git a/Task/100-doors/6502-Assembly/100-doors-1.6502 b/Task/100-doors/6502-Assembly/100-doors-1.6502 new file mode 100644 index 0000000000..52e1ffea77 --- /dev/null +++ b/Task/100-doors/6502-Assembly/100-doors-1.6502 @@ -0,0 +1,48 @@ +; 100 DOORS in 6502 assembly language for: http://www.6502asm.com/beta/index.html +; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version. +; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC +; +; Notes: +; Doors array[1..100] is at $0201..$0264. On the specified emulator, this is in video memory, so tbe results will +; be directly shown as pixels in the display. +; $0200 (door 0) is cleared for display purposes but is not involved in the open/close loops. +; Y register holds Stride +; X register holds Index +; Zero Page address $01 used to add Stride to Index (via A) because there's no add-to-X or add-Y-to-A instruction. + + ; First, zero door array + LDA #00 + LDX #100 +Z_LOOP: + STA 200,X + DEX + BNE Z_LOOP + STA 200,X + + ; Now do doors repeated open/close + LDY #01 ; Initial value of Stride +S_LOOP: + CPY #101 + BCS S_DONE + TYA ; Initial value of Index +I_LOOP: + CMP #101 + BCS I_DONE + TAX ; Use as Door array index + INC $200,X ; Toggle bit 0 to reverse state of door + STY 01 ; Add stride (Y) to index (X, via A) + ADC 01 + BCC I_LOOP +I_DONE: + INY + BNE S_LOOP +S_DONE: + + ; Finally, format array values for output: 0 for closed, 1 for open + LDX #100 +C_LOOP: + LDA $200,X + AND #$01 + STA $200,X + DEX + BNE C_LOOP diff --git a/Task/100-doors/6502-Assembly/100-doors-2.6502 b/Task/100-doors/6502-Assembly/100-doors-2.6502 new file mode 100644 index 0000000000..a9d3f84362 --- /dev/null +++ b/Task/100-doors/6502-Assembly/100-doors-2.6502 @@ -0,0 +1,17 @@ + ;assumes memory at $02xx is initially set to 0 and stack pointer is initialized + ;the 1 to 100 door byte array will be at $0200-$0263 (decimal 512 to 611) + ;Zero-page location $01 will hold delta + ;At end, closed doors = $00, open doors = $01 + +start: ldx #0 ;initialize index - first door will be at $200 + $0 + stx $1 + inc $1 ;start out with a delta of 1 (0+1=1) +openloop: inc $200,X ;open X'th door + inc $1 ;add 2 to delta + inc $1 + txa ;add delta to X by transferring X to A, adding delta to A, then transferring back to X + clc ; clear carry before adding (6502 has no add-without-carry instruction) + adc $1 + tax + cpx #$64 ;check to see if we're at or past the 100th door (at $200 + $63) + bmi openloop ;jump back to openloop if less than 100 diff --git a/Task/100-doors/6502-Assembly/100-doors.6502 b/Task/100-doors/6502-Assembly/100-doors.6502 deleted file mode 100644 index 0a02bc7b81..0000000000 --- a/Task/100-doors/6502-Assembly/100-doors.6502 +++ /dev/null @@ -1,10 +0,0 @@ - ;assume all memory is initially set to 0 - inc $1 ;start out with a delta of 1 -openloop: inc $200,X ;open a door at X - inc $1 ;add 2 to delta - inc $1 - txa ;add delta to X - adc $1 - tax - cpx #$65 ;check to see if we're at the 100th door - bmi openloop ;jump back to openloop if less than 100 diff --git a/Task/100-doors/BASIC/100-doors-1.basic b/Task/100-doors/BASIC/100-doors-1.basic index f2179f24e0..dd92311c2f 100644 --- a/Task/100-doors/BASIC/100-doors-1.basic +++ b/Task/100-doors/BASIC/100-doors-1.basic @@ -1,16 +1,22 @@ -DIM doors(0 TO 99) -FOR pass = 0 TO 99 - FOR door = pass TO 99 STEP pass + 1 - PRINT doors(door) - PRINT NOT doors(door) - doors(door) = NOT doors(door) - NEXT door -NEXT pass -FOR i = 0 TO 99 - PRINT "Door #"; i + 1; " is "; - IF NOT doors(i) THEN - PRINT "closed" - ELSE - PRINT "open" - END IF -NEXT i +REM "100 Doors" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler. +REM Author: G. A. Tippery +REM Date: 12-Feb-2014 +REM +REM Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors + +DEFINT A-Z +CONST N = 100 +DIM door(N) + +FOR stride = 1 TO N + FOR index = stride TO N STEP stride + LET door(index) = NOT (door(index)) + NEXT index +NEXT stride + +PRINT "Open doors:" +FOR index = 1 TO N + IF door(index) THEN PRINT index +NEXT index + +END diff --git a/Task/100-doors/BASIC/100-doors-2.basic b/Task/100-doors/BASIC/100-doors-2.basic index ddaffaa2c1..f2179f24e0 100644 --- a/Task/100-doors/BASIC/100-doors-2.basic +++ b/Task/100-doors/BASIC/100-doors-2.basic @@ -1,7 +1,11 @@ DIM doors(0 TO 99) -FOR door = 0 TO 99 - IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1 -NEXT door +FOR pass = 0 TO 99 + FOR door = pass TO 99 STEP pass + 1 + PRINT doors(door) + PRINT NOT doors(door) + doors(door) = NOT doors(door) + NEXT door +NEXT pass FOR i = 0 TO 99 PRINT "Door #"; i + 1; " is "; IF NOT doors(i) THEN diff --git a/Task/100-doors/BASIC/100-doors-3.basic b/Task/100-doors/BASIC/100-doors-3.basic index 14a02c2b80..ddaffaa2c1 100644 --- a/Task/100-doors/BASIC/100-doors-3.basic +++ b/Task/100-doors/BASIC/100-doors-3.basic @@ -1,10 +1,12 @@ -'lrcvs 04.11.12 -cls -x = 1 : y = 3 : z = 0 -print x + " Open" -do -z = x + y -print z + " Open" -x = z : y = y + 2 -until z >= 100 -end +DIM doors(0 TO 99) +FOR door = 0 TO 99 + IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1 +NEXT door +FOR i = 0 TO 99 + PRINT "Door #"; i + 1; " is "; + IF NOT doors(i) THEN + PRINT "closed" + ELSE + PRINT "open" + END IF +NEXT i diff --git a/Task/100-doors/BASIC/100-doors-4.basic b/Task/100-doors/BASIC/100-doors-4.basic new file mode 100644 index 0000000000..14a02c2b80 --- /dev/null +++ b/Task/100-doors/BASIC/100-doors-4.basic @@ -0,0 +1,10 @@ +'lrcvs 04.11.12 +cls +x = 1 : y = 3 : z = 0 +print x + " Open" +do +z = x + y +print z + " Open" +x = z : y = y + 2 +until z >= 100 +end diff --git a/Task/100-doors/Coq/100-doors-1.coq b/Task/100-doors/Coq/100-doors-1.coq new file mode 100644 index 0000000000..716e97ea68 --- /dev/null +++ b/Task/100-doors/Coq/100-doors-1.coq @@ -0,0 +1,26 @@ +Require Import List. + +Fixpoint rep {A} (a : A) n := + match n with + | O => nil + | S n' => a::(rep a n') + end. + +Fixpoint flip (l : list bool) (n k : nat) : list bool := + match l with + | nil => nil + | cons h t => match k with + | O => (negb h) :: (flip t n n) + | S k' => h :: (flip t n k') + end + end. + +Definition flipeach l n := flip l n n. + +Fixpoint flipwhile l n := + match n with + | O => flipeach l 0 + | S n' => flipwhile (flipeach l (S n')) n' + end. + +Definition prison cells := flipwhile (rep false (S cells)) cells. diff --git a/Task/100-doors/Coq/100-doors-2.coq b/Task/100-doors/Coq/100-doors-2.coq new file mode 100644 index 0000000000..b22b7e0c51 --- /dev/null +++ b/Task/100-doors/Coq/100-doors-2.coq @@ -0,0 +1,13 @@ +Require Import List. + +Fixpoint prisoo' nd n k accu := + match nd with + | O => rev accu + | S nd' => let ra := match k with + | O => (true, S n, (n + n)) + | S k' => (false, n, k') + end in + prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu) + end. + +Definition prisoo n := prisoo' (S n) 1 0 nil. diff --git a/Task/100-doors/Coq/100-doors-3.coq b/Task/100-doors/Coq/100-doors-3.coq new file mode 100644 index 0000000000..56df2e7103 --- /dev/null +++ b/Task/100-doors/Coq/100-doors-3.coq @@ -0,0 +1 @@ +Goal prison 100 = prisoo 100. compute. reflexivity. Qed. diff --git a/Task/100-doors/Coq/100-doors-4.coq b/Task/100-doors/Coq/100-doors-4.coq new file mode 100644 index 0000000000..c469094c8e --- /dev/null +++ b/Task/100-doors/Coq/100-doors-4.coq @@ -0,0 +1 @@ +Goal forall n, prison n = prisoo n. Abort. diff --git a/Task/100-doors/Frink/100-doors.frink b/Task/100-doors/Frink/100-doors.frink new file mode 100644 index 0000000000..7ba4aabad2 --- /dev/null +++ b/Task/100-doors/Frink/100-doors.frink @@ -0,0 +1,9 @@ +doors = new array[[101], false] +for pass=1 to 100 + for door=pass to 100 step pass + doors@door = ! doors@door + +print["Open doors: "] +for door=1 to 100 + if doors@door + print["$door "] diff --git a/Task/100-doors/JavaScript/100-doors-1.js b/Task/100-doors/JavaScript/100-doors-1.js index 5402daccdc..0aee8648bb 100644 --- a/Task/100-doors/JavaScript/100-doors-1.js +++ b/Task/100-doors/JavaScript/100-doors-1.js @@ -1,11 +1,6 @@ -(function(){var doors = [], n = 100, i, j; - -for (i = 1; i <= n; i++) { - for (j = i; j <= n; j += i) { - doors[j] = !doors[j]; - } +for (var door = 1; door <= 100; i++) { + var sqrt = Math.sqrt(door); + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } } - -for (i = 1 ; i <= n ; i++) { - if (doors[i]) console.log("Door " + i + " is open"); -}}()) diff --git a/Task/100-doors/JavaScript/100-doors-2.js b/Task/100-doors/JavaScript/100-doors-2.js index d4d2a0027c..7a4f61260e 100644 --- a/Task/100-doors/JavaScript/100-doors-2.js +++ b/Task/100-doors/JavaScript/100-doors-2.js @@ -1,19 +1,9 @@ -var - n = 100, - doors = [n], - step, - idx; -// now, start opening and closing -for (step = 1; step <= n; step += 1) - for (idx = step; idx <= n; idx += step) - // toggle state of door - doors[idx] = !doors[idx]; +Array.apply(null, { length: 100 }) + .map(function(v, i) { return i + 1; }) + .forEach(function(door) { + var sqrt = Math.sqrt(door); -// find out which doors are open -var open = doors.reduce(function(open, val, idx) { - if (val) { - open.push(idx); - } - return open; -}, []); -document.write("These doors are open: " + open.join(', ')); + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } + }); diff --git a/Task/100-doors/JavaScript/100-doors-3.js b/Task/100-doors/JavaScript/100-doors-3.js new file mode 100644 index 0000000000..2e3d824574 --- /dev/null +++ b/Task/100-doors/JavaScript/100-doors-3.js @@ -0,0 +1,9 @@ +Array.apply(null, { length: 100 }) + .map((v, i) => i + 1) + .forEach(door => { + var sqrt = Math.sqrt(door); + + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } + }); diff --git a/Task/100-doors/JavaScript/100-doors-4.js b/Task/100-doors/JavaScript/100-doors-4.js new file mode 100644 index 0000000000..7378d4bae5 --- /dev/null +++ b/Task/100-doors/JavaScript/100-doors-4.js @@ -0,0 +1,9 @@ +// Array comprehension style +[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => { + var door = i + 1 + var sqrt = Math.sqrt(door); + + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } +}); diff --git a/Task/100-doors/Kotlin/100-doors.kotlin b/Task/100-doors/Kotlin/100-doors.kotlin new file mode 100644 index 0000000000..8055e822a6 --- /dev/null +++ b/Task/100-doors/Kotlin/100-doors.kotlin @@ -0,0 +1,11 @@ +fun oneHundredDoors(): List { + val doors = Array(100, { false }) + + for (i in 0..99) + for (j in i..99 step (i + 1)) + doors[j] = !doors[j] + + return IndexIterator(doors.iterator()).filter { it.second } + .map { it.first + 1 } + .toList() +} diff --git a/Task/100-doors/Maxima/100-doors-1.maxima b/Task/100-doors/Maxima/100-doors-1.maxima new file mode 100644 index 0000000000..a49da92e04 --- /dev/null +++ b/Task/100-doors/Maxima/100-doors-1.maxima @@ -0,0 +1,5 @@ +doors(n) := block([v], local(v), + v: makelist(true, n), + for i: 2 thru n do + for j: i step i thru n do v[j]: not v[j], + sublist_indices(v, 'identity)); diff --git a/Task/100-doors/Maxima/100-doors-2.maxima b/Task/100-doors/Maxima/100-doors-2.maxima new file mode 100644 index 0000000000..63648365e3 --- /dev/null +++ b/Task/100-doors/Maxima/100-doors-2.maxima @@ -0,0 +1,2 @@ +doors(100); +/* [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] */ diff --git a/Task/100-doors/Maxima/100-doors.maxima b/Task/100-doors/Maxima/100-doors.maxima deleted file mode 100644 index 98bad752a6..0000000000 --- a/Task/100-doors/Maxima/100-doors.maxima +++ /dev/null @@ -1,10 +0,0 @@ -doors(n) := block([v: makelist(i, i, 1, n)], - for i from 2 thru n do - for j from i step i while j <= n do v[j]: -v[j], - sublist(v, ?plusp))$ - -doors(100); -[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] - -/* Note: ?plusp is a Lisp function. Maxima has nonnegintegerp, which is equivalent, -but it needs load(linearalgebra)$ first. */ diff --git a/Task/100-doors/Nimrod/100-doors.nimrod b/Task/100-doors/Nimrod/100-doors.nimrod new file mode 100644 index 0000000000..8b914ad3d1 --- /dev/null +++ b/Task/100-doors/Nimrod/100-doors.nimrod @@ -0,0 +1,16 @@ +from strutils import format + +proc check_doors() = + const n = 100 + var is_open : array[1..n, bool] # auto-initialized to false + # pass over the doors n times + for pass in 1..n: + var i = pass + while i <= n: + is_open[i] = not is_open[i] + i += pass + # print the result + for door in 1..n: + echo format("door $1 is $2.", door, (if is_open[door]: "open" else: "closed")) + +check_doors() diff --git a/Task/100-doors/Python/100-doors-5.py b/Task/100-doors/Python/100-doors-5.py index f54fda161e..a25d125a9e 100644 --- a/Task/100-doors/Python/100-doors-5.py +++ b/Task/100-doors/Python/100-doors-5.py @@ -1,4 +1,6 @@ -for i in list(range(1, 101)): - if i**0.5 % 1: state='open' - else: state='close' - print ("Door {}:{}".format(i, state)) +for i in range(1, 101): + if i**0.5 % 1: + state='open' + else: + state='close' + print("Door {}:{}".format(i, state)) diff --git a/Task/100-doors/TXR/100-doors.txr b/Task/100-doors/TXR/100-doors.txr index e199818920..b0717473b0 100644 --- a/Task/100-doors/TXR/100-doors.txr +++ b/Task/100-doors/TXR/100-doors.txr @@ -1,9 +1,9 @@ -@(do (defun 100-doors () +@(do (defun hyaku-mai-to () (let ((doors (vector 100))) (each ((i (range 0 99))) - (for ((j i)) ((< j 100)) ((inc j (+ i 1))) + (each ((j (range i 99 (+ i 1)))) (flip [doors j]))) doors)) (each ((counter (range 1)) - (door (list-vector (100-doors)))) + (door (list-vector (hyaku-mai-to)))) (format t "door ~a is ~a\n" counter (if door "open" "closed")))) diff --git a/Task/24-game/Clojure/24-game.clj b/Task/24-game/Clojure/24-game.clj index c7f0503266..4541b581e4 100644 --- a/Task/24-game/Clojure/24-game.clj +++ b/Task/24-game/Clojure/24-game.clj @@ -1,45 +1,27 @@ (ns rosettacode.24game) -(defn gen-new-game-nums [amount] (repeatedly amount #(inc ( rand-int 9)))) +(def ^:dynamic *luser* +"You guessed wrong, or your input was not in prefix notation.") -(defn orderless-seq-eq? [seq1 seq2] (apply = (map frequencies (list seq1 seq2)))) +(def ^:private start #(println +"Your numbers are: " %1 ". Your goal is " %2 ".\n" +"Use the ops [+ - * /] in prefix notation to reach" %2 ".\n" +"q[enter] to quit.")) -(defn valid-input? - "checks whether the expression is somewhat valid prefix notation - (+ 1 2 3 4) (+ 3 (+ 4 5) 6) - this is done by making sure the only contents of the list are numbers operators and brackets - flatten gets rid of the brackets, so we just need to test for operators and integers after that" - [user-input] - (if (re-find #"^\(([\d-+/*] )+\d?\)$" (pr-str (flatten user-input))) - true - false)) +(defn play + ([] (play 24)) + ([goal] (play goal (repeatedly 4 #(inc (rand-int 9))))) + ([goal gns] + (start gns goal) + (let [input (read-string (read-line)) + flat (flatten input)] + (println + (if (and (re-find #"^\([\d\s+*/-]+\d?\)$" (pr-str flat)) + (= (set gns) (set (filter integer? flat))) + (= goal (eval input))) + "You won the game!" + *luser*)) + (when (not= input 'q) (recur goal gns))))) -(defn game-numbers-and-user-input-same? - "input form: (+ 1 2 (+ 3 4)) -tests to see if the numbers the user entered are the same as the ones given to them by the game" - [game-nums user-input] - (orderless-seq-eq? game-nums (filter integer? (flatten user-input)))) - -(defn win [] (println "you won the game!\n")) -(defn lose [] (println "you guessed wrong, or your input was not in prefix notation. eg: '(+ 1 2 3 4)'\n")) -(defn game-start [goal game-numbers] (do - (println "Your numbers are " game-numbers) - (println "Your goal is " goal) - (println "Use the numbers and +*-/ to reach your goal\n") - (println "'q' to Quit\n"))) - -(defn play-game - "typing in 'q' quits. - to play use (play-game) (play-game 24) or (play-game 24 '(1 2 3 4)" - ([] (play-game 24)) - ([goal] (play-game goal (gen-new-game-nums 4))) - ([goal game-numbers] - (game-start goal game-numbers) - (let [input (read-line) - input-as-code (read-string input)] - (if (and (valid-input? input-as-code) - (game-numbers-and-user-input-same? game-numbers input-as-code) - (try (= goal (eval input-as-code)) (catch Exception e (do (lose) (play-game goal game-numbers))))) - (win) - (when (not (= input "q")) - (do (lose) (recur goal game-numbers))))))) +; * checks prefix form, then checks to see that the numbers used +; and the numbers generated by the game are the same. diff --git a/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer.applescript b/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer.applescript new file mode 100644 index 0000000000..da179b42f5 --- /dev/null +++ b/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer.applescript @@ -0,0 +1,14 @@ +repeat with beerCount from 99 to 1 by -1 + set bottles to "bottles" + if beerCount < 99 then + if beerCount = 1 then + set bottles to "bottle" + end + log "" & beerCount & " " & bottles & " of beer on the wall" + log "" + end + log "" & beerCount & " " & bottles & " of beer on the wall" + log "" & beerCount & " " & bottles & " of beer" + log "Take one down, pass it around" +end +log "No more bottles of beer on the wall!" diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-7.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-7.cs new file mode 100644 index 0000000000..151cb4c0a5 --- /dev/null +++ b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-7.cs @@ -0,0 +1,12 @@ + public static void BottlesSong(int numberOfBottles) + { + if (numberOfBottles > 0) + { + Console.WriteLine("{0} bottles of beer on the wall", numberOfBottles); + Console.WriteLine("{0} bottles of beer ", numberOfBottles); + Console.WriteLine("Take one down, pass it around"); + Console.WriteLine("{0} bottles of beer ", numberOfBottles - 1); + Console.WriteLine(); + BottlesSong(--numberOfBottles); + } + } diff --git a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-2.c b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-2.c index 7cd63889af..d0cfc3ae74 100644 --- a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-2.c +++ b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-2.c @@ -1,5 +1,17 @@ #include -main(){_=100;while(--_)printf("%i bottle%s of beer in the wall,\n%i bottle%" -"s of beer.\nTake one down, pass it round,\n%s%s\n\n",_,_-1?"s":"",_,_-1?"s" -:"",_-1?(char[]){(_-1)/10?(_-1)/10+48:(_-1)%10+48,(_-1)/10?(_-1)%10+48:2+30, -(_-1)/10?32:0,0}:"",_-1?"bottles of beer in the wall":"No more beers");} + +int main(int argc, char *argv[]) +{ + if(argc == 99) + return 99; + if(argv[0] != NULL){ + argv[0] = NULL; + argc = 0; + } + argc = main(argc + 1, argv); + printf("%d bottle%c of beer on the wall\n", argc, argc == 1?'\0': 's'); + printf("%d bottle%c of beer\n", argc, argc == 1?'\0': 's'); + printf("Take one down, pass it around\n"); + printf("%d bottle%c of beer on the wall\n\n", argc - 1, (argc - 1) == 1?'\0': 's'); + return argc - 1; +} diff --git a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-3.c b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-3.c index d484ea9641..7cd63889af 100644 --- a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-3.c +++ b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-3.c @@ -1,30 +1,5 @@ -#include #include - -#define BOTTLE(nstr) nstr " bottles of beer" - -#define WALL(nstr) BOTTLE(nstr) " on the wall" - -#define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \ - "\nTake one down, pass it around\n" - -#define PART2(nstr) WALL(nstr) "\n\n" - -#define MIDDLE(nstr) PART2(nstr) PART1(nstr) - -#define SONG PART1("100") CD2 PART2("0") - -#define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \ - CD3("4") CD3("3") CD3("2") CD3("1") CD4("") - -#define CD3(pre) CD4(pre) MIDDLE(pre "0") - -#define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \ - MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \ - MIDDLE(pre "2") MIDDLE(pre "1") - -int main(void) -{ - (void) printf(SONG); - return EXIT_SUCCESS; -} +main(){_=100;while(--_)printf("%i bottle%s of beer in the wall,\n%i bottle%" +"s of beer.\nTake one down, pass it round,\n%s%s\n\n",_,_-1?"s":"",_,_-1?"s" +:"",_-1?(char[]){(_-1)/10?(_-1)/10+48:(_-1)%10+48,(_-1)/10?(_-1)%10+48:2+30, +(_-1)/10?32:0,0}:"",_-1?"bottles of beer in the wall":"No more beers");} diff --git a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-4.c b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-4.c index f4bde51887..d484ea9641 100644 --- a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-4.c +++ b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-4.c @@ -1,35 +1,30 @@ - int b =99,u =1; - #include - char *d[16],y[] - = "#:ottle/ of" - ":eer_ a_Goy\x20some6" - "_Take8;down4p" - "a=1rou7_17 _<" - "h;_ m?_nd_ on" - "_085wal" "l_ " - "b_e _ t_ss it" - "_?4bu_ore_9, " - "\060.""@, 9$"; - # define x c ^= - #include - #define or(t,z) else\ - if(c==t && !(c = 0) &&\ - (c =! z)); int p(char *t) -{ char *s = t; int c; for ( -d[c = 0] = y; !t && (d[c +1 -]= strchr(s = d[c], '_'));* -(d[++c]++) = 0); for(t = s? -s:t;(c= *s++); c && putchar -(c)) { if (!((( x 48)& ~0xf -) && ( x 48)) ) p(d[c]), c= -0 ; or('$', p(b - 99?".\n": -"." ) && p(b - 99? t : "")) -or ('\x40', c && p( d[!!b-- -+ 2])) or('/', c && p( b^1? -"s": "")) or ('\043', b++ ? -p("So6" + --b):!printf("%d" -, b ? --b : (b += 99))) or( -'S',!(++u % 3) * 32+ 78) or -('.', puts("."))}return c;} - int main() {return p(0);} +#include +#include + +#define BOTTLE(nstr) nstr " bottles of beer" + +#define WALL(nstr) BOTTLE(nstr) " on the wall" + +#define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \ + "\nTake one down, pass it around\n" + +#define PART2(nstr) WALL(nstr) "\n\n" + +#define MIDDLE(nstr) PART2(nstr) PART1(nstr) + +#define SONG PART1("100") CD2 PART2("0") + +#define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \ + CD3("4") CD3("3") CD3("2") CD3("1") CD4("") + +#define CD3(pre) CD4(pre) MIDDLE(pre "0") + +#define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \ + MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \ + MIDDLE(pre "2") MIDDLE(pre "1") + +int main(void) +{ + (void) printf(SONG); + return EXIT_SUCCESS; +} diff --git a/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-5.c b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-5.c new file mode 100644 index 0000000000..f4bde51887 --- /dev/null +++ b/Task/99-Bottles-of-Beer/C/99-bottles-of-beer-5.c @@ -0,0 +1,35 @@ + int b =99,u =1; + #include + char *d[16],y[] + = "#:ottle/ of" + ":eer_ a_Goy\x20some6" + "_Take8;down4p" + "a=1rou7_17 _<" + "h;_ m?_nd_ on" + "_085wal" "l_ " + "b_e _ t_ss it" + "_?4bu_ore_9, " + "\060.""@, 9$"; + # define x c ^= + #include + #define or(t,z) else\ + if(c==t && !(c = 0) &&\ + (c =! z)); int p(char *t) +{ char *s = t; int c; for ( +d[c = 0] = y; !t && (d[c +1 +]= strchr(s = d[c], '_'));* +(d[++c]++) = 0); for(t = s? +s:t;(c= *s++); c && putchar +(c)) { if (!((( x 48)& ~0xf +) && ( x 48)) ) p(d[c]), c= +0 ; or('$', p(b - 99?".\n": +"." ) && p(b - 99? t : "")) +or ('\x40', c && p( d[!!b-- ++ 2])) or('/', c && p( b^1? +"s": "")) or ('\043', b++ ? +p("So6" + --b):!printf("%d" +, b ? --b : (b += 99))) or( +'S',!(++u % 3) * 32+ 78) or +('.', puts("."))}return c;} + int main() {return p(0);} diff --git a/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer.f b/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-1.f similarity index 100% rename from Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer.f rename to Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-1.f diff --git a/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-2.f b/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-2.f new file mode 100644 index 0000000000..7037ec367a --- /dev/null +++ b/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-2.f @@ -0,0 +1,28 @@ +program bottlesMPI + + implicit none + + integer :: ierr,rank,nproc + + character(len=*), parameter :: bwall = " on the wall", & + bottles = "bottles of beer", & + bottle = "bottle of beer", & + take = "Take one down, pass it around", & + form = "(I0, ' ', A)" + + call mpi_init(ierr) + call mpi_comm_size(MPI_COMM_WORLD,nproc, ierr) + call mpi_comm_rank(MPI_COMM_WORLD,rank,ierr) + + if ( rank /= 1 ) then + write (*,form) rank, bottles // bwall + if ( rank > 0 ) write (*,form) rank, bottles + else + write (*,form) rank, bottle // bwall + write (*,form) rank, bottle + end if + if ( rank > 0 ) write (*,*) take + + call mpi_finalize(ierr) + +end program bottlesMPI diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-1.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-1.js index b877df7843..b5754a03ee 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-1.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-1.js @@ -1,10 +1,13 @@ -// Line breaks are in HTML var beer = 99; -while (beer > 0) -{ - document.write( beer + " bottles of beer on the wall
" ); - document.write( beer + " bottles of beer
" ); - document.write( "Take one down, pass it around
" ); - document.write( (beer - 1) + " bottles of beer on the wall
" ); - beer--; +while (beer > 0) { + var verse = [ + beer + " bottles of beer on the wall,", + beer + " bottles of beer!", + "Take one down, pass it around", + (beer - 1) + " bottles of beer on the wall!" + ].join("\n"); + + console.log(verse); + + beer--; } diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-2.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-2.js index 8c8b4a2fca..212664bb90 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-2.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-2.js @@ -1,2 +1,10 @@ -// Line breaks are in HTML -var beer; while ((beer = typeof beer === "undefined" ? 99 : beer) > 0) document.write( beer + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall
" + beer + " bottle" + (beer != 1 ? "s" : "") + " of beer
Take one down, pass it around
" + (--beer) + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall
" ); +let beer = 99; +while (beer > 0) { + let verse = `${beer} bottles of beer on the wall, + ${beer} bottles of beer! + Take one down, pass it around + ${beer-1} bottles of beer on the wall`; + + console.log(verse); + beer--; +} diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-3.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-3.js index 9b1ded8bdc..8c8b4a2fca 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-3.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-3.js @@ -1,21 +1,2 @@ // Line breaks are in HTML -function Bottles(count){ - this.count = (!!count)?count:99; - this.knock = function(){ - var c = document.createElement('div'); - c.id="bottle-"+this.count; - c.innerHTML = "

"+this.count+" bottles of beer on the wall

" - +"

"+this.count+" bottles of beer!

" - +"

Take one down,
Pass it around

" - +"

"+(--this.count)+" bottles of beer on the wall


"; - document.body.appendChild(c); - } - this.sing = function(){ - while (this.count>0) { this.knock(); } - } -} - -(function(){ - var bar = new Bottles(99); - bar.sing(); -})(); +var beer; while ((beer = typeof beer === "undefined" ? 99 : beer) > 0) document.write( beer + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall
" + beer + " bottle" + (beer != 1 ? "s" : "") + " of beer
Take one down, pass it around
" + (--beer) + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall
" ); diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-4.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-4.js index 036d7f4de0..f24a6c991d 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-4.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-4.js @@ -1,18 +1,25 @@ -function bottleSong(n) { - if (!isFinite(Number(n)) || n == 0) n = 100; - var a = '%% bottles of beer', - b = ' on the wall', - c = 'Take one down, pass it around', - r = '
' - p = document.createElement('p'), - s = [], - re = /%%/g; - - while(n) { - s.push((a+b+r+a+r+c+r).replace(re, n) + (a+b).replace(re, --n)); - } - p.innerHTML = s.join(r+r); - document.body.appendChild(p); +function Bottles(count) { + this.count = count || 99; } -window.onload = bottleSong; +Bottles.prototype.take = function() { + var verse = [ + this.count + " bottles of beer on the wall,", + this.count + " bottles of beer!", + "Take one down, pass it around", + (this.count - 1) + " bottles of beer on the wall!" + ].join("\n"); + + console.log(verse); + + this.count--; +}; + +Bottles.prototype.sing = function() { + while (this.count) { + this.take(); + } +}; + +var bar = new Bottles(99); +bar.sing(); diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js index 00c4e101b0..036d7f4de0 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js @@ -1,12 +1,18 @@ -(function(){var beer = 99,string=''; -while (beer > 0) -{ - string+=beer+"bottles of beer on the wall\n"+ //inline line appending shouldn't be as expensive. - beer + - "bottles of beer\nTake one down, pass it around\n"+ - (--beer)+ - " bottles of beer on the wall\n" ; +function bottleSong(n) { + if (!isFinite(Number(n)) || n == 0) n = 100; + var a = '%% bottles of beer', + b = ' on the wall', + c = 'Take one down, pass it around', + r = '
' + p = document.createElement('p'), + s = [], + re = /%%/g; + while(n) { + s.push((a+b+r+a+r+c+r).replace(re, n) + (a+b).replace(re, --n)); + } + p.innerHTML = s.join(r+r); + document.body.appendChild(p); } -console.log(string); -})() + +window.onload = bottleSong; diff --git a/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer.julia b/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-1.julia similarity index 100% rename from Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer.julia rename to Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-1.julia diff --git a/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-2.julia b/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-2.julia new file mode 100644 index 0000000000..1c57078b75 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-2.julia @@ -0,0 +1,12 @@ +bottles(n) = n==0 ? "No more bottles" : + n==1 ? "1 bottle" : + "$n bottles" + +for n = 99:-1:1 + println(""" + $(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 + """) +end diff --git a/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-3.julia b/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-3.julia new file mode 100644 index 0000000000..0b94733532 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Julia/99-bottles-of-beer-3.julia @@ -0,0 +1 @@ +bottles(n) = "$(n==0 ? "No more" : n) bottle$(n==1 ? "" : "s")" diff --git a/Task/99-Bottles-of-Beer/Maxima/99-bottles-of-beer.maxima b/Task/99-Bottles-of-Beer/Maxima/99-bottles-of-beer.maxima index 55fd2e7628..899f92f36e 100644 --- a/Task/99-Bottles-of-Beer/Maxima/99-bottles-of-beer.maxima +++ b/Task/99-Bottles-of-Beer/Maxima/99-bottles-of-beer.maxima @@ -1,13 +1,26 @@ -bottle(n) := if n = 1 then "bottle" else "bottles"$ +bottles(n) := for i from n thru 1 step -1 do ( + printf(true, "~d bottle~p of beer on the wall~%", i, i), + printf(true, "~d bottle~p of beer~%", i, i), + printf(true, "Take one down, pass it around~%"), + printf(true, "~d bottle~p of beer on the wall~%", i - 1, i - 1), + disp(""))$ -bottles(n) := block( - for i from n thru 1 step -1 do ( - printf(true, "~d ~a of beer on the wall~%", i, bottle(i)), - printf(true, "~d ~a of beer~%", i, bottle(i)), - printf(true, "Take one down, pass it around~%"), - printf(true, "~d ~a of beer on the wall~%", i - 1, bottle(i - 1)), - disp("") - ) -)$ +bottles(3); +/* -bottles(99); +3 bottles of beer on the wall +3 bottles of beer +Take one down, pass it around +2 bottles of beer on the wall + +2 bottles of beer on the wall +2 bottles of beer +Take one down, pass it around +1 bottle of beer on the wall + +1 bottle of beer on the wall +1 bottle of beer +Take one down, pass it around +0 bottles of beer on the wall + +*/ diff --git a/Task/99-Bottles-of-Beer/Objective-C/99-bottles-of-beer.m b/Task/99-Bottles-of-Beer/Objective-C/99-bottles-of-beer.m index 45536ae6b8..d65da1552e 100644 --- a/Task/99-Bottles-of-Beer/Objective-C/99-bottles-of-beer.m +++ b/Task/99-Bottles-of-Beer/Objective-C/99-bottles-of-beer.m @@ -2,16 +2,16 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - int bottles = 99; - do - { - NSLog(@"%i bottles of beer on the wall\n", bottles); - NSLog(@"%i bottles of beer\n", bottles); - NSLog(@"Take one down, pass it around\n"); - NSLog(@"%i bottles of beer on the wall\n\n", --bottles); - } while (bottles > 0); + @autoreleasepool { + int bottles = 99; + do + { + NSLog(@"%i bottles of beer on the wall\n", bottles); + NSLog(@"%i bottles of beer\n", bottles); + NSLog(@"Take one down, pass it around\n"); + NSLog(@"%i bottles of beer on the wall\n\n", --bottles); + } while (bottles > 0); - [pool drain]; + } return 0; } diff --git a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust index 74483d818b..8126b2a723 100644 --- a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust +++ b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust @@ -1,5 +1,3 @@ -// rust is changing fast, so this will probably not work in later versions - use std::iter::range_step_inclusive; fn main() { @@ -18,10 +16,9 @@ fn sing_bottles_line(num_bottles: int, on_the_wall: bool) { // check out the docs for std::fmt print!("{0, plural, =0{No bottles} =1{One bottle} other{# bottles}} of beer", num_bottles as uint); - // this is to demonstrate the select "method" - // it's probably not the best way to do it - // it needs a &str so I had to use that tmp variable to trick it - // hopefully someone else can fix it for me - let tmp: &str = on_the_wall.to_str(); - println!("{0, select, true{ on the wall} other{}}!", tmp); + if on_the_wall { + println(" on the wall!"); + } else { + println(""); + } } diff --git a/Task/A+B/Dart/a+b.dart b/Task/A+B/Dart/a+b.dart index b74744d992..4fa112d195 100644 --- a/Task/A+B/Dart/a+b.dart +++ b/Task/A+B/Dart/a+b.dart @@ -1,27 +1,27 @@ import 'dart:io'; -import 'dart:convert'; +// a little helper function that checks if the string only contains +// digits and an optional minus sign at the front bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$')); void main() { - stdin.transform(new AsciiDecoder()) - .transform(new LineSplitter()) - .listen((String str) { - var strings = str.split(new RegExp(r'[ ]+')); // split on 1 or more spaces - if(!strings.every(isAnInteger)) { - print("not an integer!"); - } else if(strings.length > 2) { - print("too many numbers!"); - } else if(strings.length < 2) { - print('not enough numbers!'); + while(true) { + String input = stdin.readLineSync(); + var chunks = input.split(new RegExp(r'[ ]+')); // split on 1 or more spaces + if(!chunks.every(isAnInteger)) { + print("not an integer!"); + } else if(chunks.length > 2) { + print("too many numbers!"); + } else if(chunks.length < 2) { + print('not enough numbers!'); + } else { + // parse the strings into integers + var nums = chunks.map((String s) => int.parse(s)); + if(nums.any((num) => num < -1000 || num > 1000)) { + print("between -1000 and 1000 please!"); } else { - // parse the strings into integers - var nums = strings.map((String s) => int.parse(s)); - if(nums.any((num) => num < -1000 || num > 1000)) { - print("between -1000 and 1000 please!"); - } else { - print(nums[0]+ nums[1]); - } + print(nums.reduce((a, b) => a + b)); } - }); + } + } } diff --git a/Task/A+B/Frink/a+b.frink b/Task/A+B/Frink/a+b.frink new file mode 100644 index 0000000000..9574babe87 --- /dev/null +++ b/Task/A+B/Frink/a+b.frink @@ -0,0 +1 @@ +sum[eval[split[%r/\s+/, input[""]]]] diff --git a/Task/A+B/JavaScript/a+b-2.js b/Task/A+B/JavaScript/a+b-2.js index 5003b51b91..94f54cceac 100644 --- a/Task/A+B/JavaScript/a+b-2.js +++ b/Task/A+B/JavaScript/a+b-2.js @@ -3,7 +3,7 @@ process.openStdin().on ( function (line) { var xs = String(line).match(/^\s*(\d+)\s+(\d+)\s*/) console.log ( - xs ? Number(xs[1]) + Number(xs[2]) : 'usage: ' + xs ? Number(xs[1]) + Number(xs[2]) : 'usage: ' ) process.exit() } diff --git a/Task/A+B/JavaScript/a+b-3.js b/Task/A+B/JavaScript/a+b-3.js new file mode 100644 index 0000000000..126e7de969 --- /dev/null +++ b/Task/A+B/JavaScript/a+b-3.js @@ -0,0 +1,5 @@ +process.stdin.on("data", buffer => { + console.log( + (buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0) + ); +}); diff --git a/Task/A+B/Rust/a+b.rust b/Task/A+B/Rust/a+b.rust new file mode 100644 index 0000000000..bf6a14d01a --- /dev/null +++ b/Task/A+B/Rust/a+b.rust @@ -0,0 +1,15 @@ +// -*- rust v0.9 -*- +use std::os; + +fn main() { + let args : ~[~str] = os::args(); + let mut values = 0; + + for i in args.iter(){ + match from_str::(i.to_str()) { + Some(valid_int) => values += valid_int, + None => () + } + } + println(values.to_str()); +} diff --git a/Task/Abstract-type/Go/abstract-type.go b/Task/Abstract-type/Go/abstract-type.go index 7c4600d45d..b551d8cad2 100644 --- a/Task/Abstract-type/Go/abstract-type.go +++ b/Task/Abstract-type/Go/abstract-type.go @@ -1,5 +1,5 @@ interface { - Method1(value float64) int + Name() string SetName(name string) - GetName() string + Method1(value float64) int } diff --git a/Task/Accumulator-factory/JavaScript/accumulator-factory-1.js b/Task/Accumulator-factory/JavaScript/accumulator-factory-1.js index cda963ad42..6485096a45 100644 --- a/Task/Accumulator-factory/JavaScript/accumulator-factory-1.js +++ b/Task/Accumulator-factory/JavaScript/accumulator-factory-1.js @@ -1,9 +1,9 @@ function accumulator(sum) { - return function(n) { - return sum += n; - } + return function(n) { + return sum += n; + } } var x = accumulator(1); x(5); -document.write(accumulator(3).toString() + '
'); -document.write(x(2.3)); +console.log(accumulator(3).toString() + '
'); +console.log(x(2.3)); diff --git a/Task/Accumulator-factory/JavaScript/accumulator-factory-2.js b/Task/Accumulator-factory/JavaScript/accumulator-factory-2.js index 59ab2114e3..b94351e94c 100644 --- a/Task/Accumulator-factory/JavaScript/accumulator-factory-2.js +++ b/Task/Accumulator-factory/JavaScript/accumulator-factory-2.js @@ -1,5 +1,5 @@ -function accumulator(sum) function(n) sum += n; -var x = accumulator(1); -x(5); -console.log(accumulator(3).toSource()); +let accumulator = sum => (n => sum += n); +let x = accumulator(1); +console.log(x(5)); +accumulator(3); console.log(x(2.3)); diff --git a/Task/Accumulator-factory/JavaScript/accumulator-factory-3.js b/Task/Accumulator-factory/JavaScript/accumulator-factory-3.js new file mode 100644 index 0000000000..59ab2114e3 --- /dev/null +++ b/Task/Accumulator-factory/JavaScript/accumulator-factory-3.js @@ -0,0 +1,5 @@ +function accumulator(sum) function(n) sum += n; +var x = accumulator(1); +x(5); +console.log(accumulator(3).toSource()); +console.log(x(2.3)); diff --git a/Task/Accumulator-factory/Objective-C/accumulator-factory.m b/Task/Accumulator-factory/Objective-C/accumulator-factory.m index e8565caff2..50e9f65fc3 100644 --- a/Task/Accumulator-factory/Objective-C/accumulator-factory.m +++ b/Task/Accumulator-factory/Objective-C/accumulator-factory.m @@ -7,17 +7,17 @@ Accumulator accumulator_factory(double initial) { Accumulator acc = ^(double n){ return sum += n; }; - return [[acc copy] autorelease]; + return acc; } int main (int argc, const char * argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - Accumulator x = accumulator_factory(1); - x(5); - accumulator_factory(3); - NSLog(@"%f", x(2.3)); + Accumulator x = accumulator_factory(1); + x(5); + accumulator_factory(3); + NSLog(@"%f", x(2.3)); - [pool drain]; + } return 0; } diff --git a/Task/Ackermann-function/D/ackermann-function-2.d b/Task/Ackermann-function/D/ackermann-function-2.d index 43e25f4710..a87e12f54a 100644 --- a/Task/Ackermann-function/D/ackermann-function-2.d +++ b/Task/Ackermann-function/D/ackermann-function-2.d @@ -3,8 +3,7 @@ import std.stdio, std.bigint, std.conv; BigInt ipow(BigInt base, BigInt exp) pure /*nothrow*/ { auto result = 1.BigInt; while (exp) { - //if (exp & 1) - if (exp % 2) + if (exp & 1) result *= base; exp >>= 1; base *= base; diff --git a/Task/Ackermann-function/Perl-6/ackermann-function-1.pl6 b/Task/Ackermann-function/Perl-6/ackermann-function-1.pl6 index e6ffcc85f3..418c24e71f 100644 --- a/Task/Ackermann-function/Perl-6/ackermann-function-1.pl6 +++ b/Task/Ackermann-function/Perl-6/ackermann-function-1.pl6 @@ -1,7 +1,5 @@ sub A(Int $m, Int $n) { - - $m == 0 ?? $n + 1 !! - $n == 0 ?? A($m - 1, 1 ) !! - A($m - 1, A($m, $n - 1)); - + if $m == 0 { $n + 1 } + elsif $n == 0 { A($m - 1, 1) } + else { A($m - 1, A($m, $n - 1)) } } diff --git a/Task/Ackermann-function/Rust/ackermann-function.rust b/Task/Ackermann-function/Rust/ackermann-function.rust new file mode 100644 index 0000000000..cea988c48a --- /dev/null +++ b/Task/Ackermann-function/Rust/ackermann-function.rust @@ -0,0 +1,15 @@ + // works for Rust 0.9 +fn main() { + let a: int = ack(3, 4); // 125 + println!("{}", a.to_str()); +} + +fn ack(m: int, n: int) -> int { + if m == 0 { + n + 1 + } else if n == 0 { + ack(m - 1, 1) + } else { + ack(m - 1, ack(m, n - 1)) + } +} diff --git a/Task/Ackermann-function/TXR/ackermann-function.txr b/Task/Ackermann-function/TXR/ackermann-function.txr new file mode 100644 index 0000000000..11fc1bf36e --- /dev/null +++ b/Task/Ackermann-function/TXR/ackermann-function.txr @@ -0,0 +1,23 @@ +@(do + (defmacro defmemofun (name (. args) . body) + (let ((hash (gensym "hash-")) + (argl (gensym "args-")) + (hent (gensym "hent-")) + (uniq (copy-str "uniq"))) + ^(let ((,hash (hash :equal-based))) + (defun ,name (,*args) + (let* ((,argl (list ,*args)) + (,hent (inhash ,hash ,argl ,uniq))) + (if (eq (cdr ,hent) ,uniq) + (set (cdr ,hent) (block ,name (progn ,*body))) + (cdr ,hent))))))) + + (defmemofun ack (m n) + (cond + ((= m 0) (+ n 1)) + ((= n 0) (ack (- m 1) 1)) + (t (ack (- m 1) (ack m (- n 1)))))) + + (each ((i (range 0 3))) + (each ((j (range 0 4))) + (format t "ack(~a, ~a) = ~a\n" i j (ack i j))))) diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m b/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m index 60994f82fe..1ab166b5b6 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m @@ -1,21 +1,20 @@ #import #import -char fooKey; +static char fooKey; int main (int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - id e = [[NSObject alloc] init]; + id e = [[NSObject alloc] init]; - // set - objc_setAssociatedObject(e, &fooKey, [NSNumber numberWithInt:1], OBJC_ASSOCIATION_RETAIN); + // set + objc_setAssociatedObject(e, &fooKey, @1, OBJC_ASSOCIATION_RETAIN); - // get - NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey); - NSLog(@"associatedObject: %@", associatedObject); + // get + NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey); + NSLog(@"associatedObject: %@", associatedObject); - [e release]; - [pool drain]; + } return 0; } diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-2.m b/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-2.m index fee7b3789e..ae89ad1419 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-2.m +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-2.m @@ -2,18 +2,17 @@ #import int main (int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - id e = [[NSObject alloc] init]; + id e = [[NSObject alloc] init]; - // set - objc_setAssociatedObject(e, @selector(foo), [NSNumber numberWithInt:1], OBJC_ASSOCIATION_RETAIN); + // set + objc_setAssociatedObject(e, @selector(foo), @1, OBJC_ASSOCIATION_RETAIN); - // get - NSNumber *associatedObject = objc_getAssociatedObject(e, @selector(foo)); - NSLog(@"associatedObject: %@", associatedObject); + // get + NSNumber *associatedObject = objc_getAssociatedObject(e, @selector(foo)); + NSLog(@"associatedObject: %@", associatedObject); - [e release]; - [pool drain]; + } return 0; } diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime.rb b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime-1.rb similarity index 100% rename from Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime.rb rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime-1.rb diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime-2.rb b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime-2.rb new file mode 100644 index 0000000000..7120ce7d32 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ruby/add-a-variable-to-a-class-instance-at-runtime-2.rb @@ -0,0 +1,10 @@ +yes_no = "Yes" + +def yes_no.not + replace( self=="Yes" ? "No": "Yes") +end + +#Demo: +p yes_no.not # => "No" +p yes_no.not # => "Yes" +p "aaa".not # => undefined method `not' for "aaa":String (NoMethodError) diff --git a/Task/Address-of-a-variable/OCaml/address-of-a-variable.ocaml b/Task/Address-of-a-variable/OCaml/address-of-a-variable.ocaml new file mode 100644 index 0000000000..d7e19cc4f5 --- /dev/null +++ b/Task/Address-of-a-variable/OCaml/address-of-a-variable.ocaml @@ -0,0 +1,13 @@ +let address_of (x:'a) : nativeint = + if Obj.is_block (Obj.repr x) then + Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *) + else + invalid_arg "Can only find address of boxed values.";; + +let () = + let a = 3.14 in + Printf.printf "%nx\n" (address_of a);; + let b = ref 42 in + Printf.printf "%nx\n" (address_of b);; + let c = 17 in + Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *) diff --git a/Task/Align-columns/AWK/align-columns.awk b/Task/Align-columns/AWK/align-columns.awk index 22cc49256c..c4a5961ec0 100644 --- a/Task/Align-columns/AWK/align-columns.awk +++ b/Task/Align-columns/AWK/align-columns.awk @@ -2,7 +2,7 @@ BEGIN { FS="$" lcounter = 1 maxfield = 0 - # justistification; pick up one + # justification; pick one #justify = "left" justify = "center" #justify = "right" diff --git a/Task/Align-columns/D/align-columns.d b/Task/Align-columns/D/align-columns.d index cc582a57c6..82e75d80c4 100644 --- a/Task/Align-columns/D/align-columns.d +++ b/Task/Align-columns/D/align-columns.d @@ -8,11 +8,11 @@ that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column." - .splitLines.map!q{ a.chomp("$").split("$") }; + .split.map!(r => r.chomp("$").split("$")); int[int] maxWidths; foreach (const line; data) - foreach (i, word; line) + foreach (immutable i, const word; line) maxWidths[i] = max(maxWidths.get(i, 0), word.length); foreach (const just; TypeTuple!(leftJustify, center, rightJustify)) diff --git a/Task/Align-columns/TXR/align-columns.txr b/Task/Align-columns/TXR/align-columns.txr index d6b5d0e906..f63a1d2a47 100644 --- a/Task/Align-columns/TXR/align-columns.txr +++ b/Task/Align-columns/TXR/align-columns.txr @@ -5,15 +5,12 @@ @; pi = padded items (data with row lengths equalized with empty strings) @; cw = vector of max column widths @; ce = center padding -@(bind nc @(apply (fun max) (mapcar (fun length) item))) -@(bind pi @(mapcar (lambda (row) - (append row (repeat '("") (- nc (length row))))) - item)) +@(bind nc @[apply max [mapcar length item]]) +@(bind pi @(mapcar (op append @1 (repeat '("") (- nc (length @1)))) item)) @(bind cw @(vector-list - (mapcar (lambda (column) - (apply (fun max) (mapcar (fun length) column))) + (mapcar (op apply max [mapcar length @1]) ;; matrix transpose trick cols become rows: - (apply (fun mapcar) (cons (fun list) pi))))) + [apply mapcar [cons list pi]]))) @(bind ns "") @(output) @ (repeat) diff --git a/Task/Anagrams-Deranged-anagrams/AutoHotkey/anagrams-deranged-anagrams.ahk b/Task/Anagrams-Deranged-anagrams/AutoHotkey/anagrams-deranged-anagrams.ahk new file mode 100644 index 0000000000..b6ee97a6ff --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/AutoHotkey/anagrams-deranged-anagrams.ahk @@ -0,0 +1,56 @@ +Time := A_TickCount +SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. +SetBatchLines -1 +Loop, Read, unixdict.txt + StrOut .= StrLen(A_LoopReadLine) - 2 . "," . A_LoopReadLine . "`n" +Sort StrOut, N R +Loop, Parse, StrOut, `n, `r +{ + StringSplit, No_Let, A_Loopfield, `, + if ( old1 = no_let1 ) + string .= old2 "`n" + if ( old1 != no_let1 ) + { + string := trim(string old2) + if ( old2 != "" ) + Loop, Parse, string, `n, `r ; Specifying `n prior to `r allows both Windows and Unix files to be Parsed. + line_number := A_Index + if ( line_number > 1 ) + { + Loop, Parse, string, `n, `r + { + StringSplit, newstr, A_Loopfield, `, ; break the string based on Comma + Loop, Parse, newstr2 + k .= A_LoopField " " + Sort k, D%A_Space% + k := RegExReplace( k, "\s", "" ) + file .= "`r`n" k . "," . newstr1 . "," . newstr2 + k = + } + Sort File + Loop, Parse, File, `n, `r + { + if ( A_Loopfield != "" ) + { + StringSplit, T_C, A_Loopfield, `, + if ( old = T_C1 ) + { + Loop, 1 + { + Loop % T_C2 + if (SubStr(T_C3, A_Index, 1) = SubStr(old3, A_Index, 1)) + break 2 + Time := (A_tickcount - Time)/1000 + MsgBox % T_C3 " " old3 " in " Time . " seconds." + ExitApp + } + } + old := T_C1, old3 := T_C3 + } + } + file = + } + string = + } + old1 := no_let1, old2 := A_Loopfield +} diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d index 7971ad0f0e..7ba3d479e7 100644 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d @@ -1,19 +1,15 @@ void main() { - import std.stdio, std.file, std.algorithm, std.string, std.range, - std.functional, std.exception; + import std.stdio, std.file, std.algorithm, std.string, std.array; - string[][const ubyte[]] anags; + string[][dstring] anags; foreach (const w; "unixdict.txt".readText.split) - anags[w.dup.representation.sort().release.assumeUnique] ~= w; + anags[w.array.sort().release.idup] ~= w; anags .byValue - .map!(words => cartesianProduct(words, words) - .filter!(ww => ww[].equal!q{ a != b }) - .array) - .filter!(not!empty) - .array - .schwartzSort!q{ a[0][0].length } - .back[0] + .map!(words => words.cartesianProduct(words) + .filter!q{ a[].equal!q{ a != b }}) + .join + .minPos!q{ a[0].length > b[0].length }[0] .writeln; } diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d index 34eed5b85d..d45b0e8fda 100644 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d @@ -1,27 +1,3 @@ -import std.stdio, std.file, std.algorithm, std.string, std.array, - std.functional, std.exception; - -string[2][] findDeranged(in string[] words) pure nothrow { - // return words.pairwise.filter!(ww => ww[].equal!q{ a != b }); - typeof(return) result; - foreach (immutable i, w1; words) - foreach (w2; words[i + 1 .. $]) - if (w1.representation.equal!q{ a != b }(w2.representation)) - result ~= [w1, w2]; - return result; -} - -void main() { - Appender!(string[])[30] wClasses; - foreach (const w; "unixdict.txt".readText.splitter) - wClasses[$ - w.length] ~= w; - - foreach (const ws; wClasses[].map!q{ a.data }.filter!(not!empty)) { - string[][const ubyte[]] anags; // Assume ASCII input. - foreach (immutable w; ws) - anags[w.dup.representation.sort().release.assumeUnique]~= w; - auto pairs = anags.byValue.map!findDeranged.joiner; - if (!pairs.empty) - return writefln("Longest deranged: %-(%s %)", pairs.front); - } -} + string[][ubyte[]] anags; + foreach (const w; "unixdict.txt".readText.split) + anags[w.dup.representation.sort().release.assumeUnique] ~= w; diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d new file mode 100644 index 0000000000..34eed5b85d --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d @@ -0,0 +1,27 @@ +import std.stdio, std.file, std.algorithm, std.string, std.array, + std.functional, std.exception; + +string[2][] findDeranged(in string[] words) pure nothrow { + // return words.pairwise.filter!(ww => ww[].equal!q{ a != b }); + typeof(return) result; + foreach (immutable i, w1; words) + foreach (w2; words[i + 1 .. $]) + if (w1.representation.equal!q{ a != b }(w2.representation)) + result ~= [w1, w2]; + return result; +} + +void main() { + Appender!(string[])[30] wClasses; + foreach (const w; "unixdict.txt".readText.splitter) + wClasses[$ - w.length] ~= w; + + foreach (const ws; wClasses[].map!q{ a.data }.filter!(not!empty)) { + string[][const ubyte[]] anags; // Assume ASCII input. + foreach (immutable w; ws) + anags[w.dup.representation.sort().release.assumeUnique]~= w; + auto pairs = anags.byValue.map!findDeranged.joiner; + if (!pairs.empty) + return writefln("Longest deranged: %-(%s %)", pairs.front); + } +} diff --git a/Task/Anagrams-Deranged-anagrams/Maple/anagrams-deranged-anagrams.maple b/Task/Anagrams-Deranged-anagrams/Maple/anagrams-deranged-anagrams.maple new file mode 100644 index 0000000000..683dcfd704 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Maple/anagrams-deranged-anagrams.maple @@ -0,0 +1,5 @@ +with(StringTools): +dict:=Split([HTTP:-Get("www.puzzlers.org/pub/wordlists/unixdict.txt")][2]): +L:=[seq(select(t->HammingDistance(t,w)=length(w),[Anagrams(w,dict)])[],w=dict)]: +len:=length(ListTools:-FindMaximalElement(L,(a,b)->length(a)length(w)=len,L)[]; diff --git a/Task/Anagrams/AutoHotkey/anagrams.ahk b/Task/Anagrams/AutoHotkey/anagrams.ahk index 58dc9fb03b..bf2826f17f 100644 --- a/Task/Anagrams/AutoHotkey/anagrams.ahk +++ b/Task/Anagrams/AutoHotkey/anagrams.ahk @@ -1,17 +1,31 @@ -MsgBox % anagrams("able") - -anagrams(word) { - Static dict - IfEqual dict,, FileRead dict, unixdict.txt ; file in the script directory - w := sort(word) - Loop Parse, dict, `n, `r - If (w = sort(A_LoopField)) - t .= A_LoopField "`n" - Return t -} - -sort(word) { - a := RegExReplace(word,".","$0`n") - Sort a - Return a +FileRead, Contents, unixdict.txt +Loop, Parse, Contents, % "`n", % "`r" +{ ; parsing each line of the file we just read + Loop, Parse, A_LoopField ; parsing each letter/character of the current word + Dummy .= "," A_LoopField + Sort, Dummy, % "D," ; sorting those letters before removing the delimiters (comma) + StringReplace, Dummy, Dummy, % ",", % "", All + List .= "`n" Dummy " " A_LoopField , Dummy := "" +} ; at this point, we have a list where each line looks like +Count := 0, Contents := "", List := SubStr(List,2) +Sort, List +Loop, Parse, List, % "`n", % "`r" +{ ; now the list is sorted, parse it counting the consecutive lines with the same set of + Max := (Count > Max) ? Count : Max + StringSplit, LinePart, A_LoopField, % " " ; (LinePart1 are the letters, LinePart2 is the word) + If ( PreviousLinePart1 = LinePart1 ) + Count++ , WordList .= "," LinePart2 + Else + var_Result .= ( Count <> Max ) ? "" ; don't append if the number of common words is too low + : "`n" Count "`t" PreviousLinePart1 "`t" SubStr(WordList,2) + , WordList := "" , Count := 0 + PreviousLinePart1 := LinePart1 } +List := "", var_Result := SubStr(var_Result,2) +Sort, var_Result, R N ; make the higher scores appear first +Loop, Parse, var_Result, % "`n", % "`r" + If ( 1 == InStr(A_LoopField,Max) ) + var_Output .= "`n" A_LoopField + Else ; output only those sets of letters that scored the maximum amount of common words + Break +MsgBox, % ClipBoard := SubStr(var_Output,2) ; the result is also copied to the clipboard diff --git a/Task/Anagrams/JavaScript/anagrams.js b/Task/Anagrams/JavaScript/anagrams.js index c05f247839..25f2b6ed2b 100644 --- a/Task/Anagrams/JavaScript/anagrams.js +++ b/Task/Anagrams/JavaScript/anagrams.js @@ -1,20 +1,20 @@ -#!/usr/bin/env js +var fs = require('fs'); var anas = {}; -var words = read('unixdict.txt').split(/\n/g); +var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n'); +var max = 0; for (var w in words) { - var key = words[w].split("").sort().join(''); + var key = words[w].split('').sort().join(''); if (!(key in anas)) { anas[key] = []; } - anas[key].push(words[w]); + var count = anas[key].push(words[w]); + max = Math.max(count, max); } for (var a in anas) { - if (anas[a].length >= 2) { - print(anas[a]); + if (anas[a].length === max) { + console.log(anas[a]); } } - -quit(); diff --git a/Task/Anagrams/PureBasic/anagrams.purebasic b/Task/Anagrams/PureBasic/anagrams.purebasic index f54fa5f679..b3d0277f16 100644 --- a/Task/Anagrams/PureBasic/anagrams.purebasic +++ b/Task/Anagrams/PureBasic/anagrams.purebasic @@ -19,6 +19,16 @@ Procedure.s sortWord(word$) ProcedureReturn word$ EndProcedure +;for a faster and more advanced alternative replace the previous procedure with this code +; Procedure.s sortWord(word$) ;returns a string with the letters of the word sorted +; Protected wordLength = Len(word$) +; Protected Dim letters.c(wordLength) +; +; PokeS(@letters(), word$) ;overwrite the array with the strings contents +; SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1) +; ProcedureReturn PeekS(@letters(), wordLength) ;return the arrays contents +; EndProcedure + tmpdir$ = GetTemporaryDirectory() filename$ = tmpdir$ + "unixdict.txt" @@ -43,15 +53,20 @@ If ReceiveHTTPFile("http://www.puzzlers.org/pub/wordlists/unixdict.txt", filenam Else ; if no anaMap(key$)\anas = word$ ; applying a new record - anaMap()\isana + 1 + anaMap()\isana = 1 + EndIf + + If anaMap()\isana > maxAnagrams ;make note of maximum anagram count + maxAnagrams = anaMap()\isana EndIf + Until Eof(1) CloseFile(1) DeleteFile(filename$) ;----- output ----- ForEach anaMap() - If anaMap()\isana >= 4 ; only emit what had 4 or more hits. + If anaMap()\isana = maxAnagrams ; only emit elements that have the most hits PrintN(anaMap()\anas) EndIf Next diff --git a/Task/Anagrams/Rust/anagrams.rust b/Task/Anagrams/Rust/anagrams.rust new file mode 100644 index 0000000000..a14b29d754 --- /dev/null +++ b/Task/Anagrams/Rust/anagrams.rust @@ -0,0 +1,39 @@ +extern crate collections; + +use std::str; +use collections::HashMap; +use std::io::File; +use std::io::BufferedReader; +use std::cmp; + +fn sort_string(string: &str) -> ~str { + let mut chars = string.chars().to_owned_vec(); + chars.sort(); + str::from_chars(chars) +} + +fn main () { + let path = Path::new("unixdict.txt"); + let mut file = BufferedReader::new(File::open(&path)); + + let mut map: HashMap<~str, ~[~str]> = HashMap::new(); + + for line in file.lines() { + let s = line.trim().to_owned(); + map.mangle(sort_string(s.clone()), s, + |_k, v| ~[v], + |_k, v, string| v.push(string) + ); + } + + let max_length = map.iter().fold(0, |s, (_k, v)| cmp::max(s, v.len())); + + for (_k, v) in map.iter() { + if v.len() == max_length { + for s in v.iter() { + print!("{} ", *s) + } + println!("") + } + } +} diff --git a/Task/Animate-a-pendulum/AutoHotkey/animate-a-pendulum.ahk b/Task/Animate-a-pendulum/AutoHotkey/animate-a-pendulum.ahk new file mode 100644 index 0000000000..68097032c1 --- /dev/null +++ b/Task/Animate-a-pendulum/AutoHotkey/animate-a-pendulum.ahk @@ -0,0 +1,39 @@ +SetBatchlines,-1 +;settings +SizeGUI:={w:650,h:400} ;Guisize +pendulum:={length:300,maxangle:90,speed:2,size:30,center:{x:Sizegui.w//2,y:10}} ;pendulum length, size, center, speed and maxangle + +pendulum.maxangle:=pendulum.maxangle*0.01745329252 +p_Token:=Gdip_Startup() +Gui,+LastFound +Gui,show,% "w" SizeGUI.w " h" SizeGUI.h +hwnd:=WinActive() +hdc:=GetDC(hwnd) +start:=A_TickCount/1000 +G:=Gdip_GraphicsFromHDC(hdc) +pBitmap:=Gdip_CreateBitmap(650, 450) +G2:=Gdip_GraphicsFromImage(pBitmap) +Gdip_SetSmoothingMode(G2, 4) +pBrush := Gdip_BrushCreateSolid(0xff0000FF) +pBrush2 := Gdip_BrushCreateSolid(0xFF777700) +pPen:=Gdip_CreatePenFromBrush(pBrush2, 10) +SetTimer,Update,10 + +Update: +Gdip_GraphicsClear(G2,0xFFFFFFFF) +time:=start-(A_TickCount/1000*pendulum.speed) +angle:=sin(time)*pendulum.maxangle +x2:=sin(angle)*pendulum.length+pendulum.center.x +y2:=cos(angle)*pendulum.length+pendulum.center.y +Gdip_DrawLine(G2,pPen,pendulum.center.x,pendulum.center.y,x2,y2) +GDIP_DrawCircle(G2,pBrush,pendulum.center.x,pendulum.center.y,15) +GDIP_DrawCircle(G2,pBrush2,x2,y2,pendulum.size) +Gdip_DrawImage(G, pBitmap) +return + +GDIP_DrawCircle(g,b,x,y,r){ + Gdip_FillEllipse(g, b, x-r//2,y-r//2 , r, r) +} + +GuiClose: +ExitApp diff --git a/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion.ahk b/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion.ahk new file mode 100644 index 0000000000..3069e0a98f --- /dev/null +++ b/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion.ahk @@ -0,0 +1,23 @@ +Fib(n) { + nold1 := 1 + nold2 := 0 + If n < 0 + { + MsgBox, Positive argument required! + Return + } + Else If n = 0 + Return nold2 + Else If n = 1 + Return nold1 + Fib_Label: + t := nold2+nold1 + If n > 2 + { + n-- + nold2:=nold1 + nold1:=t + GoSub Fib_Label + } + Return t +} diff --git a/Task/Anonymous-recursion/Axiom/anonymous-recursion-1.axiom b/Task/Anonymous-recursion/Axiom/anonymous-recursion-1.axiom index 947b80986f..3891bb5722 100644 --- a/Task/Anonymous-recursion/Axiom/anonymous-recursion-1.axiom +++ b/Task/Anonymous-recursion/Axiom/anonymous-recursion-1.axiom @@ -1,10 +1,7 @@ -)abbrev package TESTP TestPackage -Z ==> Integer -TestPackage : with - fib : Z -> Z - == add - fib x == - x <= 0 => error "argument outside of range" - f : Reference((Z,Z,Z) -> Z) := ref((n, v1, v2) +-> 0) - f() := (n, v1, v2) +-> if n<2 then v2 else f()(n-1,v2,v1+v2) - f()(x,1,1) +#include "axiom" +Z ==> Integer; +fib(x:Z):Z == { + x <= 0 => error "argument outside of range"; + f(n:Z,v1:Z,v2:Z):Z == if n<2 then v2 else f(n-1,v2,v1+v2); + f(x,1,1); +} diff --git a/Task/Anonymous-recursion/Axiom/anonymous-recursion-2.axiom b/Task/Anonymous-recursion/Axiom/anonymous-recursion-2.axiom index c12d66b649..947b80986f 100644 --- a/Task/Anonymous-recursion/Axiom/anonymous-recursion-2.axiom +++ b/Task/Anonymous-recursion/Axiom/anonymous-recursion-2.axiom @@ -1,10 +1,10 @@ -#include "aldor"; -#include "aldorio"; -import from Integer; -Z ==> Integer; -fib(x:Z):Z == { - x <= 0 => throw SyntaxException; - f(n:Z,v1:Z,v2:Z):Z == if n<2 then v2 else f(n-1,v2,v1+v2); - f(x,1,1); -} -stdout << fib(10000); +)abbrev package TESTP TestPackage +Z ==> Integer +TestPackage : with + fib : Z -> Z + == add + fib x == + x <= 0 => error "argument outside of range" + f : Reference((Z,Z,Z) -> Z) := ref((n, v1, v2) +-> 0) + f() := (n, v1, v2) +-> if n<2 then v2 else f()(n-1,v2,v1+v2) + f()(x,1,1) diff --git a/Task/Anonymous-recursion/Objective-C/anonymous-recursion-1.m b/Task/Anonymous-recursion/Objective-C/anonymous-recursion-1.m index 6baabe1cf4..36b61f9fde 100644 --- a/Task/Anonymous-recursion/Objective-C/anonymous-recursion-1.m +++ b/Task/Anonymous-recursion/Objective-C/anonymous-recursion-1.m @@ -15,19 +15,18 @@ if (i < 2) result = 1; else - result = [[self performSelector:_cmd withObject:[NSNumber numberWithInt:i-1]] intValue] - + [[self performSelector:_cmd withObject:[NSNumber numberWithInt:i-2]] intValue]; - return [NSNumber numberWithInt:result]; + result = [[self performSelector:_cmd withObject:@(i-1)] intValue] + + [[self performSelector:_cmd withObject:@(i-2)] intValue]; + return @(result); } @end int main (int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - AnonymousRecursion *dummy = [[AnonymousRecursion alloc] init]; - NSLog(@"%@", [dummy fibonacci:[NSNumber numberWithInt:8]]); - [dummy release]; + AnonymousRecursion *dummy = [[AnonymousRecursion alloc] init]; + NSLog(@"%@", [dummy fibonacci:@8]); - [pool release]; + } return 0; } diff --git a/Task/Anonymous-recursion/Objective-C/anonymous-recursion-2.m b/Task/Anonymous-recursion/Objective-C/anonymous-recursion-2.m index bfb0d63868..28eff7953a 100644 --- a/Task/Anonymous-recursion/Objective-C/anonymous-recursion-2.m +++ b/Task/Anonymous-recursion/Objective-C/anonymous-recursion-2.m @@ -5,21 +5,22 @@ int fib(int n) { @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"fib: no negative numbers" userInfo:nil]; - __block int (^f)(int); - f = ^(int n) { + int (^f)(int); + __block __weak int (^weak_f)(int); // block cannot capture strong reference to itself + weak_f = f = ^(int n) { if (n < 2) return 1; else - return f(n-1) + f(n-2); + return weak_f(n-1) + weak_f(n-2); }; return f(n); } int main (int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSLog(@"%d", fib(8)); + NSLog(@"%d", fib(8)); - [pool release]; + } return 0; } diff --git a/Task/Anonymous-recursion/Objective-C/anonymous-recursion-3.m b/Task/Anonymous-recursion/Objective-C/anonymous-recursion-3.m new file mode 100644 index 0000000000..0c93446668 --- /dev/null +++ b/Task/Anonymous-recursion/Objective-C/anonymous-recursion-3.m @@ -0,0 +1,25 @@ +#import + +int fib(int n) { + if (n < 0) + @throw [NSException exceptionWithName:NSInvalidArgumentException + reason:@"fib: no negative numbers" + userInfo:nil]; + __block int (^f)(int); + f = ^(int n) { + if (n < 2) + return 1; + else + return f(n-1) + f(n-2); + }; + return f(n); +} + +int main (int argc, const char *argv[]) { + @autoreleasepool { + + NSLog(@"%d", fib(8)); + + } + return 0; +} diff --git a/Task/Anonymous-recursion/Python/anonymous-recursion-4.py b/Task/Anonymous-recursion/Python/anonymous-recursion-4.py new file mode 100644 index 0000000000..e68e5b55df --- /dev/null +++ b/Task/Anonymous-recursion/Python/anonymous-recursion-4.py @@ -0,0 +1,9 @@ +>>> from inspect import currentframe +>>> from types import FunctionType +>>> def myself (*args, **kw): +... caller_frame = currentframe(1) +... code = caller_frame.f_code +... return FunctionType(code, caller_frame.f_globals)(*args, **kw) +... +>>> print "factorial(5) =", +>>> print (lambda n:1 if n<=1 else n*myself(n-1)) ( 5 ) diff --git a/Task/Apply-a-callback-to-an-array/Frink/apply-a-callback-to-an-array.frink b/Task/Apply-a-callback-to-an-array/Frink/apply-a-callback-to-an-array.frink new file mode 100644 index 0000000000..bca620156e --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Frink/apply-a-callback-to-an-array.frink @@ -0,0 +1,3 @@ +f = {|x| x^2} // Anonymous function to square input +a = [1,2,3,5,7] +println[map[f, a]] diff --git a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-1.js b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-1.js index c6717bfa0a..6dc60144f3 100644 --- a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-1.js +++ b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-1.js @@ -1,7 +1,9 @@ function map(a, func) { - for (var i in a) - a[i] = func(a[i]); + var ret = []; + for (var i = 0; i < a.length; i++) { + ret[i] = func(a[i]); + } + return ret; } -var a = [1, 2, 3, 4, 5]; -map(a, function(v) { return v * v; }); +map([1, 2, 3, 4, 5], function(v) { return v * v; }); diff --git a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-2.js b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-2.js index 883198c3b9..1ede80680c 100644 --- a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-2.js +++ b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-2.js @@ -1 +1 @@ -var a = (1).to(10).collect(Math.pow.curry(undefined,2)); +[1, 2, 3, 4, 5].map(function(v) { return v * v; }); diff --git a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-3.js b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-3.js index 2f638315d0..f1b331181f 100644 --- a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-3.js +++ b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-3.js @@ -1,15 +1 @@ -function cube(num) { - return Math.pow(num, 3); -} - -var numbers = [1, 2, 3, 4, 5]; - -// get results of calling cube on every element -var cubes1 = numbers.map(cube); - -// display each result in a separate dialog -cubes1.forEach(alert); - -// array comprehension -var cubes2 = [cube(n) for each (n in numbers)]; -var cubes3 = [n * n * n for each (n in numbers)]; +[1, 2, 3, 4, 5].map(v => v * v); diff --git a/Task/Apply-a-callback-to-an-array/TXR/apply-a-callback-to-an-array.txr b/Task/Apply-a-callback-to-an-array/TXR/apply-a-callback-to-an-array.txr index e30a7db78d..c19196658d 100644 --- a/Task/Apply-a-callback-to-an-array/TXR/apply-a-callback-to-an-array.txr +++ b/Task/Apply-a-callback-to-an-array/TXR/apply-a-callback-to-an-array.txr @@ -1,7 +1,11 @@ -@(do - (defun mapvec (vec fun) - (each ((i (range 0 (- (length vec) 1)))) - [fun [vec i]])) - - (mapvec #(1 2 3 4 5 6 7 8 9 10) - (lambda (x) (format t "~a\n" x)))) +$ txr -e '[mapcar prinl #(1 2 3 4 5 6 7 8 9 10)]' +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 diff --git a/Task/Arbitrary-precision-integers--included-/00DESCRIPTION b/Task/Arbitrary-precision-integers--included-/00DESCRIPTION index 917612b3f6..0da06c6ecb 100644 --- a/Task/Arbitrary-precision-integers--included-/00DESCRIPTION +++ b/Task/Arbitrary-precision-integers--included-/00DESCRIPTION @@ -9,3 +9,6 @@ C.F. [[Long multiplication]] Note:
  • Do not submit an ''implementation'' of [[wp:arbitrary precision arithmetic|arbitrary precision arithmetic]]. The intention is to show the capabilities of the language as supplied. If a language has a [[Talk:Arbitrary-precision integers (included)#Use of external libraries|single, overwhelming, library]] of varied modules that is endorsed by its home site – such as [[CPAN]] for Perl or [[Boost]] for C++ – then that ''may'' be used instead.
  • Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the '''only''' recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
+ +;See also: +* [[Exponentiation order]] diff --git a/Task/Arithmetic-Complex/COBOL/arithmetic-complex-1.cobol b/Task/Arithmetic-Complex/COBOL/arithmetic-complex-1.cobol new file mode 100644 index 0000000000..10cd47189a --- /dev/null +++ b/Task/Arithmetic-Complex/COBOL/arithmetic-complex-1.cobol @@ -0,0 +1,14 @@ + $SET SOURCEFORMAT "FREE" +$SET ILUSING "System" +$SET ILUSING "System.Numerics" +class-id Prog. +method-id. Main static. +procedure division. + declare num as type Complex = type Complex::ImaginaryOne() + declare results as type Complex occurs any + set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num)) + perform varying result as type Complex thru results + display result + end-perform +end method. +end class. diff --git a/Task/Arithmetic-Complex/COBOL/arithmetic-complex.cobol b/Task/Arithmetic-Complex/COBOL/arithmetic-complex-2.cobol similarity index 100% rename from Task/Arithmetic-Complex/COBOL/arithmetic-complex.cobol rename to Task/Arithmetic-Complex/COBOL/arithmetic-complex-2.cobol diff --git a/Task/Arithmetic-Complex/Frink/arithmetic-complex.frink b/Task/Arithmetic-Complex/Frink/arithmetic-complex.frink new file mode 100644 index 0000000000..e3967e36d3 --- /dev/null +++ b/Task/Arithmetic-Complex/Frink/arithmetic-complex.frink @@ -0,0 +1,13 @@ +add[x,y] := x + y +multiply[x,y] := x * y +negate[x] := -x +invert[x] := 1/x // Could also use inv[x] or recip[x] +conjugate[x] := Re[x] - Im[x] i + +a = 3 + 2.5i +b = 7.3 - 10i +println["$a + $b = " + add[a,b]] +println["$a * $b = " + multiply[a,b]] +println["-$a = " + negate[a]] +println["1/$a = " + invert[a]] +println["conjugate[$a] = " + conjugate[a]] diff --git a/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust b/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust new file mode 100644 index 0000000000..dffc2ea40f --- /dev/null +++ b/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust @@ -0,0 +1,16 @@ +extern crate num; + +use num::complex::Cmplx; + +fn main() { + let a = Cmplx::new(-4.0, 5.0); + let b = Cmplx::new(1.0, 1.0); + + println!("a = {}", a); + println!("b = {}", b); + println!("a + b = {}", a + b); + println!("a * b = {}", a * b); + println!("1 / a = {}", Cmplx::new(1.0, 0.0) / a); + println!("-a = {}", -a); + println!("conj a = {}", a.conj()); +} diff --git a/Task/Arithmetic-Rational/D/arithmetic-rational.d b/Task/Arithmetic-Rational/D/arithmetic-rational.d index 4f4087ca31..6c4858d11b 100644 --- a/Task/Arithmetic-Rational/D/arithmetic-rational.d +++ b/Task/Arithmetic-Rational/D/arithmetic-rational.d @@ -9,7 +9,7 @@ T lcm(T)(in T a, in T b) pure /*nothrow*/ { return a / gcd(a, b) * b; } -struct RationalT(T) { +struct RationalT(T) if (!isUnsigned!T) { private T num, den; // Numerator & denominator. private enum Type { NegINF = -2, @@ -54,7 +54,7 @@ struct RationalT(T) { return result; } - T nomerator() const pure nothrow @property { + T numerator() const pure nothrow @property { return num; } @@ -73,9 +73,9 @@ struct RationalT(T) { real toReal() pure const /*nothrow*/ { static if (is(T == BigInt)) - return num.toLong / cast(real)den.toLong; + return num.toLong / real(den.toLong); else - return num / cast(real)den; + return num / real(den); } RationalT opBinary(string op)(in RationalT r) @@ -126,14 +126,14 @@ struct RationalT(T) { return num != 0; } - int opEquals(U)(in U r) const pure nothrow { + bool opEquals(U)(in U r) const pure nothrow { RationalT rhs = RationalT(r); if (type() == Type.NaRAT || rhs.type() == Type.NaRAT) return false; return num == rhs.num && den == rhs.den; } - int opCmp(U)(in U r) const pure nothrow { + int opCmp(U)(in U r) const pure { auto rhs = RationalT(r); if (type() == Type.NaRAT || rhs.type() == Type.NaRAT) throw new Exception("Compare involve a NaRAT."); @@ -154,6 +154,15 @@ struct RationalT(T) { } } +RationalT!U rational(U)(in U n) pure /*nothrow*/ { + return typeof(return)(n); +} + +RationalT!(CommonType!(U1, U2)) +rational(U1, U2)(in U1 n, in U2 d) pure /*nothrow*/ { + return typeof(return)(n, d); +} + alias Rational = RationalT!BigInt; version (arithmetic_rational_main) { // Test. @@ -163,7 +172,7 @@ version (arithmetic_rational_main) { // Test. foreach (immutable p; 2 .. 2 ^^ 19) { auto sum = RatL(1, p); - immutable limit = 1 + cast(uint)sqrt(cast(real)p); + immutable limit = 1 + cast(uint)real(p).sqrt; foreach (immutable factor; 2 .. limit) if (p % factor == 0) sum += RatL(1, factor) + RatL(factor, p); diff --git a/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-1.py b/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-1.py index 11a8d47d54..54edcea4b3 100644 --- a/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-1.py +++ b/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-1.py @@ -8,9 +8,9 @@ def agm(a0, g0, tolerance=1e-10): value of the arithmetic-geometric mean (default value = 1e-10) """ - [an, gn] = [(a0 + g0) / 2.0, sqrt(a0 * g0)] + an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0) while abs(an - gn) > tolerance: - [an, gn] = [(an + gn) / 2.0, sqrt(an * gn)] + an, gn = (an + gn) / 2.0, sqrt(an * gn) return an print agm(1, 1 / sqrt(2)) diff --git a/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-2.py b/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-2.py index 8bbc04e1b8..fe52e42e27 100644 --- a/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-2.py +++ b/Task/Arithmetic-geometric-mean/Python/arithmetic-geometric-mean-2.py @@ -2,7 +2,7 @@ from decimal import Decimal, getcontext def agm(a, g, tolerance=Decimal("1e-65")): while True: - a, g = ((a + g) / 2, (a * g).sqrt()) + a, g = (a + g) / 2, (a * g).sqrt() if abs(a - g) < tolerance: return a diff --git a/Task/Array-concatenation/Frink/array-concatenation.frink b/Task/Array-concatenation/Frink/array-concatenation.frink new file mode 100644 index 0000000000..e81efa6211 --- /dev/null +++ b/Task/Array-concatenation/Frink/array-concatenation.frink @@ -0,0 +1,3 @@ +a = [1,2] +b = [3,4] +a.pushAll[b] diff --git a/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin b/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin new file mode 100644 index 0000000000..11765a0be6 --- /dev/null +++ b/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin @@ -0,0 +1,3 @@ +val a : Array = // initialise a +val b : Array = // initialise b +val c = (a.toList() + b.toList()).copyToArray() diff --git a/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin b/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin new file mode 100644 index 0000000000..db0f06a642 --- /dev/null +++ b/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin @@ -0,0 +1,2 @@ +fun arrayConcat(a : Array, b : Array) + = Array(a.size + b.size, {if (it in a.indices) a[it] else b[it - a.size]}) diff --git a/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin b/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin new file mode 100644 index 0000000000..95abc6a59b --- /dev/null +++ b/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin @@ -0,0 +1,3 @@ +val a : Collection // initialise a +val b : Collection = // initialise b +val c : Collection = a + b diff --git a/Task/Array-concatenation/Objective-C/array-concatenation-1.m b/Task/Array-concatenation/Objective-C/array-concatenation-1.m index 0ad02bc3ea..a715e72c10 100644 --- a/Task/Array-concatenation/Objective-C/array-concatenation-1.m +++ b/Task/Array-concatenation/Objective-C/array-concatenation-1.m @@ -1,7 +1,3 @@ -NSArray *arr1 = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], - [NSNumber numberWithInt:2], - [NSNumber numberWithInt:3], nil]; -NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithInt:4], - [NSNumber numberWithInt:5], - [NSNumber numberWithInt:6], nil]; +NSArray *arr1 = @[@1, @2, @3]; +NSArray *arr2 = @[@4, @5, @6]; NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2]; diff --git a/Task/Array-concatenation/Objective-C/array-concatenation-2.m b/Task/Array-concatenation/Objective-C/array-concatenation-2.m index 5598a036c7..e6ea8aaf4a 100644 --- a/Task/Array-concatenation/Objective-C/array-concatenation-2.m +++ b/Task/Array-concatenation/Objective-C/array-concatenation-2.m @@ -1,8 +1,4 @@ -NSArray *arr1 = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], - [NSNumber numberWithInt:2], - [NSNumber numberWithInt:3], nil]; -NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithInt:4], - [NSNumber numberWithInt:5], - [NSNumber numberWithInt:6], nil]; +NSArray *arr1 = @[@1, @2, @3]; +NSArray *arr2 = @[@4, @5, @6]; NSMutableArray *arr3 = [NSMutableArray arrayWithArray:arr1]; [arr3 addObjectsFromArray:arr2]; diff --git a/Task/Arrays/Frink/arrays.frink b/Task/Arrays/Frink/arrays.frink new file mode 100644 index 0000000000..f9b0b9d445 --- /dev/null +++ b/Task/Arrays/Frink/arrays.frink @@ -0,0 +1,6 @@ +a = new array +a@0 = 10 +a@1 = 20 +println[a@1] + +b = [1, 2, 3] diff --git a/Task/Assertions/Perl-6/assertions.pl6 b/Task/Assertions/Perl-6/assertions.pl6 index 0c831822fe..cf505f0515 100644 --- a/Task/Assertions/Perl-6/assertions.pl6 +++ b/Task/Assertions/Perl-6/assertions.pl6 @@ -5,4 +5,4 @@ macro assert ($x) { "$x or die 'assertion failed: $x'" } assert('$a == 42'); # but usually we just say -$a == 42 or die "$x ain't 42"; +$a == 42 or die '$a ain\'t 42'; diff --git a/Task/Associative-array-Creation/AutoHotkey/associative-array-creation-1.ahk b/Task/Associative-array-Creation/AutoHotkey/associative-array-creation-1.ahk index b3ab03a6b0..64420286a4 100644 --- a/Task/Associative-array-Creation/AutoHotkey/associative-array-creation-1.ahk +++ b/Task/Associative-array-Creation/AutoHotkey/associative-array-creation-1.ahk @@ -1,3 +1,3 @@ associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23} -MsgBox % associative_array["key1"] -. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"] +MsgBox % associative_array.key1 + . "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"] diff --git a/Task/Associative-array-Creation/Scheme/associative-array-creation-3.ss b/Task/Associative-array-Creation/Scheme/associative-array-creation-3.ss new file mode 100644 index 0000000000..d462b73e99 --- /dev/null +++ b/Task/Associative-array-Creation/Scheme/associative-array-creation-3.ss @@ -0,0 +1,9 @@ +#!r6rs + +(import (rnrs base) + (rnrs hashtables (6))) + +(define my-hash (make-hashtable equal-hash equal?)) +(hashtable-set! my-hash 'a 'b) +(hashtable-set! my-hash 1 'hello) +(hashtable-set! my-hash "c" '(a b c)) diff --git a/Task/Associative-array-Iteration/Prolog/associative-array-iteration-1.pro b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-1.pro new file mode 100644 index 0000000000..94eec4f4bd --- /dev/null +++ b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-1.pro @@ -0,0 +1,2 @@ +assert( mymap(key1,value1) ). +assert( mymap(key2,value1) ). diff --git a/Task/Associative-array-Iteration/Prolog/associative-array-iteration-2.pro b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-2.pro new file mode 100644 index 0000000000..9baa7da403 --- /dev/null +++ b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-2.pro @@ -0,0 +1,4 @@ +?- forall( mymap(Key,Value), writeln( [Key,Value]) ). + +[key1,value1] +[key2,value1] diff --git a/Task/Associative-array-Iteration/Prolog/associative-array-iteration-3.pro b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-3.pro new file mode 100644 index 0000000000..d252d8f30c --- /dev/null +++ b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-3.pro @@ -0,0 +1,6 @@ +?- mymap(key1, Y). +Y = value1. + +?- mymap(X, value1). +X = key1 ; +X = key2. diff --git a/Task/Associative-array-Iteration/Prolog/associative-array-iteration-4.pro b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-4.pro new file mode 100644 index 0000000000..cb15ab15b8 --- /dev/null +++ b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-4.pro @@ -0,0 +1,2 @@ +?- findall( X, mymap(X,value1), Xs). +Xs = [key1, key2]. diff --git a/Task/Associative-array-Iteration/Prolog/associative-array-iteration-5.pro b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-5.pro new file mode 100644 index 0000000000..eab0b8f2f3 --- /dev/null +++ b/Task/Associative-array-Iteration/Prolog/associative-array-iteration-5.pro @@ -0,0 +1,2 @@ +?- findall( Y, mymap(key1,Y), Ys). +Ys = [value1]. diff --git a/Task/Atomic-updates/AutoHotkey/atomic-updates.ahk b/Task/Atomic-updates/AutoHotkey/atomic-updates.ahk new file mode 100644 index 0000000000..c7af78537e --- /dev/null +++ b/Task/Atomic-updates/AutoHotkey/atomic-updates.ahk @@ -0,0 +1,41 @@ +Bucket := [], Buckets := 10, Originaltotal = 0 +loop, %Buckets% { + Random, rnd, 0,50 + Bucket[A_Index] := rnd, Originaltotal += rnd +} + +loop 100 +{ + total := 0 + Randomize(B1, B2, Buckets) + temp := (Bucket[B1] + Bucket[B2]) /2 + Bucket[B1] := floor(temp), Bucket[B2] := Ceil(temp) ; values closer to equal + + Randomize(B1, B2, Buckets) + temp := Bucket[B1] + Bucket[B2] + Random, value, 0, %temp% + Bucket[B1] := value, Bucket[B2] := temp-value ; redistribute values arbitrarily + + VisualTip := "Original Total = " Originaltotal "`n" + loop, %Buckets% + VisualTip .= SubStr("0" Bucket[A_Index], -1) " : " x(Bucket[A_Index]) "`n" , total += Bucket[A_Index] + + ToolTip % VisualTip "Current Total = " total + if (total <> Originaltotal) + MsgBox "Error" + Sleep, 100 +} +return + +Randomize(ByRef B1, ByRef B2, Buckets){ + Random, B1, 1, %Buckets% + Loop + Random, B2, 1, %Buckets% + until (B1<>B2) +} + +x(n){ + loop, % n + Res.= ">" + return Res +} diff --git a/Task/Average-loop-length/D/average-loop-length.d b/Task/Average-loop-length/D/average-loop-length.d index 71b88a6381..cc1773e523 100644 --- a/Task/Average-loop-length/D/average-loop-length.d +++ b/Task/Average-loop-length/D/average-loop-length.d @@ -1,17 +1,14 @@ import std.stdio, std.random, std.math, std.algorithm, std.range; -real analytical(in int n) pure nothrow { - real total = 0.0; - foreach (immutable k; 1 .. n + 1) { - immutable x = reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1)) - * k ^^ 2; - total += x / ((cast(real)n) ^^ (k + 1)); - } - return total; +real analytical(in int n) /*pure nothrow*/ { + enum aux = (int k)=> reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1)); + return iota(1, n + 1) + .map!(k => (aux(k) * k ^^ 2) / (real(n) ^^ (k + 1))) + .sum; } size_t loopLength(size_t maxN)(in int size, ref Xorshift rng) { - __gshared bool[maxN + 1] seen; + __gshared static bool[maxN + 1] seen; seen[0 .. size + 1] = false; int current = 1; size_t steps = 0; @@ -34,8 +31,8 @@ void main() { long total = 0; foreach (immutable _; 0 .. nTrials) total += loopLength!maxN(n, rng); - immutable average = total / cast(real)nTrials; - immutable an = analytical(n); + immutable average = total / real(nTrials); + immutable an = n.analytical; immutable percentError = abs(an - average) / an * 100; immutable errorS = format("%2.4f", percentError); writefln("%3d %9.5f %12.5f (%7s%%)", diff --git a/Task/Average-loop-length/PARI-GP/average-loop-length.pari b/Task/Average-loop-length/PARI-GP/average-loop-length.pari new file mode 100644 index 0000000000..d1e0cfd938 --- /dev/null +++ b/Task/Average-loop-length/PARI-GP/average-loop-length.pari @@ -0,0 +1,14 @@ +expected(n)=sum(i=1,n,n!/(n-i)!/n^i,0.); +test(n, times)={ + my(ct); + for(i=1,times, + my(x=1,bits); + while(!bitand(bits,x),ct++; bits=bitor(bits,x); x = 1< l) => l.reduce((num p, num n) => p + n) / l.length; + +void main(){ + print(mean([1,2,3,4,5,6,7])); +} diff --git a/Task/Averages-Arithmetic-mean/Frink/averages-arithmetic-mean.frink b/Task/Averages-Arithmetic-mean/Frink/averages-arithmetic-mean.frink new file mode 100644 index 0000000000..b22ccb07c1 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Frink/averages-arithmetic-mean.frink @@ -0,0 +1 @@ +mean[x] := length[x] > 0 ? sum[x] / length[x] : undef diff --git a/Task/Averages-Arithmetic-mean/Maxima/averages-arithmetic-mean.maxima b/Task/Averages-Arithmetic-mean/Maxima/averages-arithmetic-mean.maxima index 3e54624546..5ce90e2e6e 100644 --- a/Task/Averages-Arithmetic-mean/Maxima/averages-arithmetic-mean.maxima +++ b/Task/Averages-Arithmetic-mean/Maxima/averages-arithmetic-mean.maxima @@ -1 +1,2 @@ +load("descriptive"); mean([2, 7, 11, 17]); diff --git a/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk b/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk new file mode 100644 index 0000000000..fcc0bc11ad --- /dev/null +++ b/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk @@ -0,0 +1,16 @@ +Angles := [[350, 10], [90, 180, 270, 360], [10, 20, 30]] +MsgBox, % MeanAngle(Angles[1]) "`n" + . MeanAngle(Angles[2]) "`n" + . MeanAngle(Angles[3]) + +MeanAngle(a, x=0, y=0) { + c := ATan(1) / 45 + for k, v in a + x += Cos(v * c) / a.MaxIndex() + , y += Sin(v * c) / a.MaxIndex() + return atan2(x, y) / c +} + +atan2(x, y) { + return dllcall("msvcrt\atan2", "Double",y, "Double",x, "CDECL Double") +} diff --git a/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk b/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk new file mode 100644 index 0000000000..6a32497daf --- /dev/null +++ b/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk @@ -0,0 +1,20 @@ +MsgBox, % "The mean time is: " MeanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"]) + +MeanTime(t, x=0, y=0) { + c := ATan(1) / 45 + for k, v in t + n := StrSplit(v, ":") + , r := c * (n[1] * 3600 + n[2] * 60 + n[3]) / 240 + , x += Cos(r) + , y += Sin(r) + r := atan2(x, y) / c + r := (r < 0 ? r + 360 : r) / 15 + h := SubStr("00" Round(r // 1, 0), -1) + s := SubStr("00" Round(Mod(m := Mod(r, 1) * 60, 1) * 60, 0), -1) + m := SubStr("00" Round(m // 1, 0), -1) + return, h ":" m ":" s +} + +atan2(x, y) { + return dllcall("msvcrt\atan2", "Double",y, "Double",x, "CDECL Double") +} diff --git a/Task/Averages-Mean-time-of-day/Ruby/averages-mean-time-of-day.rb b/Task/Averages-Mean-time-of-day/Ruby/averages-mean-time-of-day.rb new file mode 100644 index 0000000000..500833099c --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Ruby/averages-mean-time-of-day.rb @@ -0,0 +1,19 @@ +def time2deg(t) + raise "invalid time" unless m = t.match(/^(\d\d):(\d\d):(\d\d)$/) + hh,mm,ss = m[1..3].map {|e| e.to_i} + raise "invalid time" unless (0..23).include? hh and + (0..59).include? mm and + (0..59).include? ss + (hh*3600 + mm*60 + ss) * 360 / 86400.0 +end + +def deg2time(d) + sec = (d % 360) * 86400 / 360.0 + "%02d:%02d:%02d" % [sec/3600, (sec%3600)/60, sec%60] +end + +def mean_time(times) + deg2time(mean_angle(times.map {|t| time2deg t})) +end + +puts mean_time ["23:00:17", "23:40:20", "00:12:45", "00:17:19"] diff --git a/Task/Averages-Median/00DESCRIPTION b/Task/Averages-Median/00DESCRIPTION index 16cca4928f..c4639f7b31 100644 --- a/Task/Averages-Median/00DESCRIPTION +++ b/Task/Averages-Median/00DESCRIPTION @@ -1,5 +1,5 @@ -Write a program to find the [[wp:Median|median]] value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but ''must'' handle the case where there are an even number of elements. +Write a program to find the [[wp:Median|median]] value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but ''must'' handle the case where there are an even number of elements. In that case, return the average of the two middle values. -There are several approaches to this. One is to sort the elements, and then pick the one in the middle. Sorting would take at least O(''n'' log''n''). Another would be to build a priority queue from the elements, and then extract half of the elements to get to the middle one(s). This would also take O(''n'' log''n''). The best solution is to use the [[wp:Selection algorithm|selection algorithm]] to find the median in O(''n'') time. +There are several approaches to this. One is to sort the elements, and then pick the one(s) in the middle. Sorting would take at least O(''n'' log''n''). Another would be to build a priority queue from the elements, and then extract half of the elements to get to the middle one(s). This would also take O(''n'' log''n''). The best solution is to use the [[wp:Selection algorithm|selection algorithm]] to find the median in O(''n'') time. See also: [[Mean]], [[Mode]] diff --git a/Task/Averages-Median/C/averages-median-2.c b/Task/Averages-Median/C/averages-median-2.c index 14e449a4d4..1ab573ea58 100644 --- a/Task/Averages-Median/C/averages-median-2.c +++ b/Task/Averages-Median/C/averages-median-2.c @@ -1,63 +1,79 @@ #include #include +#include -/* select the k-th smallest item in array x of length len */ -int qselect(int *x, int k, int len) +#define MAX_ELEMENTS 1000000 + +/* Return the k-th smallest item in array x of length len */ +double quick_select(int k, double *x, int len) { - inline void swap(int a, int b) { - int t = x[a]; - x[a] = x[b], x[b] = t; - } + inline void swap(int a, int b) + { + double t = x[a]; + x[a] = x[b], x[b] = t; + } - int left = 0, right = len - 1; - int pivot, pos, i; + int left = 0, right = len - 1; + int pos, i; + double pivot; - while (left < right) { - pivot = x[k]; - swap(k, right); - for (i = pos = left; i < right; i++) { - if (x[i] < pivot) { - swap(i, pos); - pos++; - } - } - swap(right, pos); - if (pos == k) break; - if (pos < k) left = pos + 1; - else right = pos - 1; - } - return x[k]; + while (left < right) + { + pivot = x[k]; + swap(k, right); + for (i = pos = left; i < right; i++) + { + if (x[i] < pivot) + { + swap(i, pos); + pos++; + } + } + swap(right, pos); + if (pos == k) break; + if (pos < k) left = pos + 1; + else right = pos - 1; + } + return x[k]; } -#define N 10000001 - -int icmp(const void *a, const void *b) +int main(void) { - return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*) b; -} - -int main() -{ - int i, med, *x = malloc(sizeof(int) * N); - - /* divide by large value to create many duplicate values */ - for (i = 0; i < N; i++) x[i] = rand()/100000; - - med = qselect(x, N/2, N); - - /* qsort for speed comparison */ - //qsort(x, N, sizeof(int), icmp); med = x[N/2]; - - printf("median is %d\n", med); - - /* just to show it is the median */ - int less = 0, more = 0, eq = 0; - for (i = 0; i < N; i++) { - if (x[i] < med) less ++; - else if (x[i] > med) more ++; - else eq ++; - } - printf("<: %d\n>: %d\n=: %d\n", less, more, eq); - - return 0; + int i, length; + double *x, median; + + /* Initialize random length double array with random doubles */ + srandom(time(0)); + length = random() % MAX_ELEMENTS; + x = malloc(sizeof(double) * length); + for (i = 0; i < length; i++) + { + // shifted by RAND_MAX for negative values + // divide by a random number for floating point + x[i] = (double)(random() - RAND_MAX / 2) / (random() + 1); // + 1 to not divide by 0 + } + + + if (length % 2 == 0) // Even number of elements, median is average of middle two + { + median = (quick_select(length / 2, x, length) + quick_select(length / 2 - 1, x, length / 2)) / 2; + } + else // select middle element + { + median = quick_select(length / 2, x, length); + } + + + /* Sanity testing of median */ + int less = 0, more = 0, eq = 0; + for (i = 0; i < length; i++) + { + if (x[i] < median) less ++; + else if (x[i] > median) more ++; + else eq ++; + } + printf("length: %d\nmedian: %lf\n<: %d\n>: %d\n=: %d\n", length, median, less, more, eq); + + free(x); + return 0; } diff --git a/Task/Averages-Median/C/averages-median-3.c b/Task/Averages-Median/C/averages-median-3.c new file mode 100644 index 0000000000..6af71d02a4 --- /dev/null +++ b/Task/Averages-Median/C/averages-median-3.c @@ -0,0 +1,5 @@ +length: 992021 +median: 0.000473 +<: 496010 +>: 496010 +=: 1 diff --git a/Task/Averages-Mode/Julia/averages-mode.julia b/Task/Averages-Mode/Julia/averages-mode.julia new file mode 100644 index 0000000000..cacb76baf7 --- /dev/null +++ b/Task/Averages-Mode/Julia/averages-mode.julia @@ -0,0 +1,29 @@ +function modes(values) + dict = Dict() # Values => Number of repetitions + modesArray = typeof(values[1])[] # Array of the modes so far + max = 0 # Max of repetitions so far + + for v in values + # Add one to the dict[v] entry (create one if none) + if v in keys(dict) + dict[v] += 1 + else + dict[v] = 1 + end + + # Update modesArray if the number of repetitions + # of v reaches or surpasses the max value + if dict[v] >= max + if dict[v] > max + empty!(modesArray) + max += 1 + end + append!(modesArray, [v]) + end + end + + return modesArray +end + +println(modes([1,3,6,6,6,6,7,7,12,12,17])) +println(modes((1,1,2,4,4))) diff --git a/Task/Averages-Mode/Objective-C/averages-mode.m b/Task/Averages-Mode/Objective-C/averages-mode.m index 0696bc925a..8a61fbf6de 100644 --- a/Task/Averages-Mode/Objective-C/averages-mode.m +++ b/Task/Averages-Mode/Objective-C/averages-mode.m @@ -9,9 +9,7 @@ NSCountedSet *seen = [NSCountedSet setWithArray:self]; int max = 0; NSMutableArray *maxElems = [NSMutableArray array]; - NSEnumerator *enm = [seen objectEnumerator]; - id obj; - while( (obj = [enm nextObject]) ) { + for ( obj in seen ) { int count = [seen countForObject:obj]; if (count > max) { max = count; diff --git a/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d b/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d index 9a7d0c3632..a69b369cf8 100644 --- a/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d +++ b/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d @@ -1,19 +1,19 @@ import std.stdio, std.algorithm, std.range, std.functional; -auto amean(T)(T data) { - return data.reduce!q{a + b}() / data.length; +auto aMean(T)(T data) { + return data.sum / data.length; } -auto gmean(T)(T data) { - return data.reduce!q{a * b}() ^^ (1.0 / data.length); +auto gMean(T)(T data) pure { + return data.reduce!q{a * b} ^^ (1.0 / data.length); } -auto hmean(T)(T data) { - return data.length / data.reduce!q{1.0/a + b}(); +auto hMean(T)(T data) pure { + return data.length / data.reduce!q{ 1.0 / a + b }; } void main() { - auto m = adjoin!(hmean, gmean, amean)(iota(1.0L, 11.0L)); - writefln("%.19f %.19f %.19f", m.tupleof); - assert([m.tupleof].isSorted()); + immutable m = [adjoin!(hMean, gMean, aMean)(iota(1.0L, 11.0L))[]]; + writefln("%(%.19f %)", m); + assert(m.isSorted); } diff --git a/Task/Averages-Root-mean-square/D/averages-root-mean-square.d b/Task/Averages-Root-mean-square/D/averages-root-mean-square.d index c3381d5279..55151ae320 100644 --- a/Task/Averages-Root-mean-square/D/averages-root-mean-square.d +++ b/Task/Averages-Root-mean-square/D/averages-root-mean-square.d @@ -1,9 +1,9 @@ import std.stdio, std.math, std.algorithm, std.range; -real rms(R)(R d) { - return sqrt(reduce!((a, b) => a + b * b)(d) / cast(real)d.length); +real rms(R)(R d) pure { + return sqrt(d.reduce!((a, b) => a + b * b) / real(d.length)); } void main() { - writefln("%.19f", rms(iota(1, 11))); + writefln("%.19f", iota(1, 11).rms); } diff --git a/Task/Averages-Root-mean-square/Maxima/averages-root-mean-square.maxima b/Task/Averages-Root-mean-square/Maxima/averages-root-mean-square.maxima index a635ce583f..ad29a9f8cf 100644 --- a/Task/Averages-Root-mean-square/Maxima/averages-root-mean-square.maxima +++ b/Task/Averages-Root-mean-square/Maxima/averages-root-mean-square.maxima @@ -1,4 +1,4 @@ -L: makelist(i, i, 1, 10)$ +L: makelist(i, i, 10)$ rms(L) := sqrt(lsum(x^2, x, L)/length(L))$ diff --git a/Task/Averages-Simple-moving-average/Brat/averages-simple-moving-average-1.brat b/Task/Averages-Simple-moving-average/Brat/averages-simple-moving-average-1.brat new file mode 100644 index 0000000000..a131835544 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Brat/averages-simple-moving-average-1.brat @@ -0,0 +1,21 @@ +SMA = object.new + +SMA.init = { period | + my.period = period + my.list = [] + my.average = 0 +} + +SMA.prototype.add = { num | + true? my.list.length >= my.period + { my.list.deq } + + my.list << num + my.average = my.list.reduce(:+) / my.list.length +} + +sma3 = SMA.new 3 +sma5 = SMA.new 5 +[1, 2, 3, 4, 5, 5, 4, 3, 2, 1].each { n | + p n, " - SMA3: ", sma3.add(n), " SMA5: ", sma5.add(n) +} diff --git a/Task/Averages-Simple-moving-average/Brat/averages-simple-moving-average-2.brat b/Task/Averages-Simple-moving-average/Brat/averages-simple-moving-average-2.brat new file mode 100644 index 0000000000..a6647a5880 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Brat/averages-simple-moving-average-2.brat @@ -0,0 +1,17 @@ +sma = { period | + list = [] + + { num | + true? list.length >= period + { list.deq } + + list << num + list.reduce(:+) / list.length + } +} + +sma3 = sma 3 +sma5 = sma 5 +[1, 2, 3, 4, 5, 5, 4, 3, 2, 1].each { n | + p n, " - SMA3: ", sma3(n), " SMA5: ", sma5(n) +} diff --git a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d index 5b2f4e374b..5381b293c6 100644 --- a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d +++ b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d @@ -1,25 +1,24 @@ import std.stdio, std.traits, std.algorithm; auto sma(T, int period)() { - T[period] data = 0; // D FP are default-initialized to NaN + T[period] data = 0; T sum = 0; - int index, nfilled; + int index, nFilled; - // return (in T v) nothrow { - return delegate (in T v) nothrow { + return (in T v) nothrow { sum += -data[index] + v; data[index] = v; index = (index + 1) % period; - nfilled = min(period, nfilled + 1); - return cast(CommonType!(T, float))sum / nfilled; + nFilled = min(period, nFilled + 1); + return CommonType!(T, float)(sum) / nFilled; }; } void main() { - auto s3 = sma!(int, 3)(); - auto s5 = sma!(double, 5)(); + immutable s3 = sma!(int, 3); + immutable s5 = sma!(double, 5); - foreach (e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) + foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e)); } diff --git a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d index 0464bcd31b..9f9e6132d8 100644 --- a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d +++ b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d @@ -3,14 +3,14 @@ import std.stdio, std.traits, std.algorithm; struct SMA(T, int period) { T[period] data = 0; T sum = 0; - int index, nfilled; + int index, nFilled; auto opCall(in T v) pure nothrow { sum += -data[index] + v; data[index] = v; index = (index + 1) % period; - nfilled = min(period, nfilled + 1); - return cast(CommonType!(T, float))sum / nfilled; + nFilled = min(period, nFilled + 1); + return CommonType!(T, float)(sum) / nFilled; } } @@ -18,7 +18,7 @@ void main() { SMA!(int, 3) s3; SMA!(double, 5) s5; - foreach (e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) + foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e)); } diff --git a/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average.m b/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average.m new file mode 100644 index 0000000000..c91ac17b9b --- /dev/null +++ b/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average.m @@ -0,0 +1,94 @@ +#import + +@interface MovingAverage : NSObject { + unsigned int period; + NSMutableArray *window; + double sum; +} +- (instancetype)initWithPeriod:(unsigned int)thePeriod; +@end + +@implementation MovingAverage + +// init with default period +- (instancetype)init { + self = [super init]; + if(self) { + period = 10; + window = [[NSMutableArray alloc] init]; + sum = 0.0; + } + return self; +} + +// init with specified period +- (instancetype)initWithPeriod:(unsigned int)thePeriod { + self = [super init]; + if(self) { + period = thePeriod; + window = [[NSMutableArray alloc] init]; + sum = 0.0; + } + return self; +} + +// add a new number to the window +- (void)add:(double)val { + sum += val; + [window addObject:@(val)]; + if([window count] > period) { + NSNumber *n = window[0]; + sum -= [n doubleValue]; + [window removeObjectAtIndex:0]; + } +} + +// get the average value +- (double)avg { + if([window count] == 0) { + return 0; // technically the average is undefined + } + return sum / [window count]; +} + +// set the period, resizes current window +- (void)setPeriod:(unsigned int)thePeriod { + // make smaller? + if(thePeriod < [window count]) { + for(int i = 0; i < thePeriod; ++i) { + NSNumber *n = window[0]; + sum -= [n doubleValue]; + [window removeObjectAtIndex:0]; + } + } + period = thePeriod; +} + +// get the period (window size) +- (unsigned int)period { + return period; +} + +// clear the window and current sum +- (void)clear { + [window removeAllObjects]; + sum = 0; +} + +@end + +int main (int argc, const char * argv[]) { + @autoreleasepool { + double testData[10] = {1,2,3,4,5,5,4,3,2,1}; + int periods[2] = {3,5}; + for(int i = 0; i < 2; ++i) { + MovingAverage *ma = [[MovingAverage alloc] initWithPeriod:periods[i]]; + for(int j = 0; j < 10; ++j) { + [ma add:testData[j]]; + NSLog(@"Next number = %f, SMA = %f", testData[j], [ma avg]); + } + NSLog(@"\n"); + } + } + return 0; +} diff --git a/Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 b/Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 index 929b726958..484870ca1e 100644 --- a/Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 +++ b/Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 @@ -1,8 +1,7 @@ -sub sma(Int $period where * > 0) returns Sub { +sub sma(Int \P where * > 0) returns Sub { sub ($x) { - state @a = 0 xx $period; - @a.push($x); - @a.shift; - $period R/ [+] @a; + state @a = 0 xx P; + @a.push($x).shift; + P R/ [+] @a; } } diff --git a/Task/Averages-Simple-moving-average/Perl/averages-simple-moving-average.pl b/Task/Averages-Simple-moving-average/Perl/averages-simple-moving-average.pl index ea33991644..441e99c0e2 100644 --- a/Task/Averages-Simple-moving-average/Perl/averages-simple-moving-average.pl +++ b/Task/Averages-Simple-moving-average/Perl/averages-simple-moving-average.pl @@ -1,7 +1,18 @@ -sub sma ($) - {my ($period, $sum, @a) = shift, 0; - return sub - {unshift @a, shift; - $sum += $a[0]; - @a > $period and $sum -= pop @a; - return $sum / @a;}} +sub sma_generator { + my $period = shift; + my (@list, $sum); + + return sub { + my $number = shift; + push @list, $number; + $sum += $number; + $sum -= shift @list if @list > $period; + return $sum / @list; + } +} + +# Usage: +my $sma = sma_generator(3); +for (1, 2, 3, 2, 7) { + printf "append $_ --> sma = %.2f (with period 3)\n", $sma->($_); +} diff --git a/Task/Balanced-brackets/Fortran/balanced-brackets.f b/Task/Balanced-brackets/Fortran/balanced-brackets.f new file mode 100644 index 0000000000..ebda34d4af --- /dev/null +++ b/Task/Balanced-brackets/Fortran/balanced-brackets.f @@ -0,0 +1,97 @@ +! $ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe +! $ ./f +! compiles syntax error +! : +! : ][ +! : ]][[ +! :[[[]]] +! : ][[][]][ +! : ][[]]][[[] +! : ]]]][]][[[[[ +! : ]]]][][]][[[[[ +! : ][[[]]]]][]][[[[ +! : [[][]]][]]][[[][[] +! : ]]][[][[[[[[[[]]]]]] +! :[[][[[][]]][]] +! :[[[][]][][[[]][]][]] + +program balanced_brackets + implicit none + integer :: N + character(len=20) :: brackets, fmt + write(6,*)'compiles syntax error' + call random_seed + do N=0, 10 + call generate(N, brackets) + if (balanced(brackets)) then + fmt = '(a,a20)' + else + fmt = '(a,21x,a20)' + end if + write(6,fmt)':',brackets + end do + + brackets = '[[][[[][]]][]]' + if (balanced(brackets)) then + fmt = '(a,a20)' + else + fmt = '(a,21x,a20)' + end if + write(6,fmt)':',brackets + + N = 10 + call generate(N, brackets) + do while (.not. balanced(brackets)) ! show a balanced set + call generate(N, brackets) + end do + fmt = '(a,a20)' + write(6,fmt)':',brackets + +contains + + logical function balanced(s) + implicit none + character(len=*), intent(in) :: s + integer :: i, a, n + n = len_trim(s) + a = 0 + balanced = .true. + do i=1, n + if (s(i:i) == '[') then + a = a+1 + else + a = a-1 + end if + balanced = balanced .and. (0 <= a) + end do + end function balanced + + subroutine generate(N, s) + implicit none + integer, intent(in) :: N + character(len=*), intent(out) :: s + integer :: L, R, i + real, dimension(2*N) :: harvest + character :: c + i = 1 + L = 0 + R = 0 + s = ' ' + call random_number(harvest) + do while ((L < N) .and. (R < N)) + if (harvest(i) < 0.5) then + L = L+1 + s(i:i) = '[' + else + R = R+1 + s(i:i) = ']' + end if + i = i+1 + end do + c = merge('[', ']', L < N) + do while (i <= 2*N) + s(i:i) = c + i = i+1 + end do + end subroutine generate +end program balanced_brackets diff --git a/Task/Balanced-brackets/Julia/balanced-brackets.julia b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia similarity index 100% rename from Task/Balanced-brackets/Julia/balanced-brackets.julia rename to Task/Balanced-brackets/Julia/balanced-brackets-1.julia diff --git a/Task/Balanced-brackets/Julia/balanced-brackets-2.julia b/Task/Balanced-brackets/Julia/balanced-brackets-2.julia new file mode 100644 index 0000000000..2beba0cc23 --- /dev/null +++ b/Task/Balanced-brackets/Julia/balanced-brackets-2.julia @@ -0,0 +1 @@ +balanced(str) = foldl((x,y)->x<0? -1: x+y, 0, [(x=='[')-(x==']') for x=str])==0 diff --git a/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 b/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 index b620a6e0ab..e5599d6aff 100644 --- a/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 +++ b/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 @@ -1,8 +1,5 @@ -grammar BalBrack { - token TOP { ^ * $ }; - token balanced { '[' * ']' } -} +grammar BalBrack { token TOP { '[' * ']' } } my $n = prompt "Number of bracket pairs: "; -my $s = (<[ ]> xx $n).pick(*).join; +my $s = ('[' xx $n, ']' xx $n).pick(*).join; say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced"; diff --git a/Task/Balanced-brackets/Perl/balanced-brackets-1.pl b/Task/Balanced-brackets/Perl/balanced-brackets-1.pl index f629496158..fbbc35be34 100644 --- a/Task/Balanced-brackets/Perl/balanced-brackets-1.pl +++ b/Task/Balanced-brackets/Perl/balanced-brackets-1.pl @@ -1,13 +1,15 @@ -use 5.10.0; # for given ... when construct -sub balanced { - my $depth = 0; - for (split //, shift) { - when('[') { ++$depth } - when(']') { return if --$depth < 0 } - } - return !$depth +sub generate { + my $n = shift; + my $str = '[' x $n; + substr($str, rand($n + $_), 0) = ']' for 1..$n; + return $str; } -for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') { - print balanced($_) ? "" : "not ", "balanced:\t'$_'\n"; +sub balanced { + shift =~ /^ (\[ (?1)* \])* $/x; +} + +for (0..8) { + my $input = generate($_); + print balanced($input) ? " ok:" : "bad:", " '$input'\n"; } diff --git a/Task/Balanced-brackets/Perl/balanced-brackets-2.pl b/Task/Balanced-brackets/Perl/balanced-brackets-2.pl index 0ee712dcc8..05ee4d6b40 100644 --- a/Task/Balanced-brackets/Perl/balanced-brackets-2.pl +++ b/Task/Balanced-brackets/Perl/balanced-brackets-2.pl @@ -1,10 +1,3 @@ -use 5.10.0; # for '++' non-backtrack behavior sub balanced { - my $_ = shift; - s/(\[(?:[^\[\]]++|(?1))*\])//g; - ! /[\[\]]/; -} - -for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') { - print balanced($_) ? "" : "not ", "balanced:\t'$_'\n"; + shift =~ /^ ( [^\[\]]++ | \[ (?1)* \] )* $/x; } diff --git a/Task/Balanced-brackets/Perl/balanced-brackets-3.pl b/Task/Balanced-brackets/Perl/balanced-brackets-3.pl new file mode 100644 index 0000000000..13224bdd8b --- /dev/null +++ b/Task/Balanced-brackets/Perl/balanced-brackets-3.pl @@ -0,0 +1,8 @@ +sub balanced { + my $depth = 0; + for (split //, shift) { + if ($_ eq '[') { ++$depth } + elsif ($_ eq ']') { return if --$depth < 0 } + } + return !$depth +} diff --git a/Task/Balanced-ternary/AutoHotkey/balanced-ternary-1.ahk b/Task/Balanced-ternary/AutoHotkey/balanced-ternary-1.ahk new file mode 100644 index 0000000000..2a86e16058 --- /dev/null +++ b/Task/Balanced-ternary/AutoHotkey/balanced-ternary-1.ahk @@ -0,0 +1,22 @@ +BalancedTernary(n){ + k = 0 + if abs(n)<2 + return n=1?"+":n=0?"0":"-" + if n<1 + negative := true, n:= -1*n + while !break { + d := Mod(n, 3**(k+1)) / 3**k + d := d=2?-1:d + n := n - (d * 3**k) + r := (d=-1?"-":d=1?"+":0) . r + k++ + if (n = 3**k) + r := "+" . r , break := true + } + if negative { + StringReplace, r, r, -,n, all + StringReplace, r, r, `+,-, all + StringReplace, r, r, n,+, all + } + return r +} diff --git a/Task/Balanced-ternary/AutoHotkey/balanced-ternary-2.ahk b/Task/Balanced-ternary/AutoHotkey/balanced-ternary-2.ahk new file mode 100644 index 0000000000..01b1c36e75 --- /dev/null +++ b/Task/Balanced-ternary/AutoHotkey/balanced-ternary-2.ahk @@ -0,0 +1,11 @@ +data = +( +523 +-436 +65 +-262023 +) +loop, Parse, data, `n + result .= A_LoopField " : " BalancedTernary(A_LoopField) "`n" +MsgBox % result +return diff --git a/Task/Balanced-ternary/C++/balanced-ternary.cpp b/Task/Balanced-ternary/C++/balanced-ternary.cpp new file mode 100644 index 0000000000..14136b34d8 --- /dev/null +++ b/Task/Balanced-ternary/C++/balanced-ternary.cpp @@ -0,0 +1,212 @@ +#include +#include +#include +using namespace std; + +class BalancedTernary { +protected: + // Store the value as a reversed string of +, 0 and - characters + string value; + + // Helper function to change a balanced ternary character to an integer + int charToInt(char c) const { + if (c == '0') + return 0; + return 44 - c; + } + + // Helper function to negate a string of ternary characters + string negate(string s) const { + for (int i = 0; i < s.length(); ++i) { + if (s[i] == '+') + s[i] = '-'; + else if (s[i] == '-') + s[i] = '+'; + } + return s; + } + +public: + // Default constructor + BalancedTernary() { + value = "0"; + } + + // Construct from a string + BalancedTernary(string s) { + value = string(s.rbegin(), s.rend()); + } + + // Construct from an integer + BalancedTernary(long long n) { + if (n == 0) { + value = "0"; + return; + } + + bool neg = n < 0; + if (neg) + n = -n; + + value = ""; + while (n != 0) { + int r = n % 3; + if (r == 0) + value += "0"; + else if (r == 1) + value += "+"; + else { + value += "-"; + ++n; + } + + n /= 3; + } + + if (neg) + value = negate(value); + } + + // Copy constructor + BalancedTernary(const BalancedTernary &n) { + value = n.value; + } + + // Addition operators + BalancedTernary operator+(BalancedTernary n) const { + n += *this; + return n; + } + + BalancedTernary& operator+=(const BalancedTernary &n) { + static char *add = "0+-0+-0"; + static char *carry = "--000++"; + + int lastNonZero = 0; + char c = '0'; + for (int i = 0; i < value.length() || i < n.value.length(); ++i) { + char a = i < value.length() ? value[i] : '0'; + char b = i < n.value.length() ? n.value[i] : '0'; + + int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; + c = carry[sum]; + + if (i < value.length()) + value[i] = add[sum]; + else + value += add[sum]; + + if (add[sum] != '0') + lastNonZero = i; + } + + if (c != '0') + value += c; + else + value = value.substr(0, lastNonZero + 1); // Chop off leading zeroes + + return *this; + } + + // Negation operator + BalancedTernary operator-() const { + BalancedTernary result; + result.value = negate(value); + return result; + } + + // Subtraction operators + BalancedTernary operator-(const BalancedTernary &n) const { + return operator+(-n); + } + + BalancedTernary& operator-=(const BalancedTernary &n) { + return operator+=(-n); + } + + // Multiplication operators + BalancedTernary operator*(BalancedTernary n) const { + n *= *this; + return n; + } + + BalancedTernary& operator*=(const BalancedTernary &n) { + BalancedTernary pos = *this; + BalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly + value = "0"; + + for (int i = 0; i < n.value.length(); ++i) { + if (n.value[i] == '+') + operator+=(pos); + else if (n.value[i] == '-') + operator+=(neg); + pos.value = '0' + pos.value; + neg.value = '0' + neg.value; + } + + return *this; + } + + // Stream output operator + friend ostream& operator<<(ostream &out, const BalancedTernary &n) { + out << n.toString(); + return out; + } + + // Convert to string + string toString() const { + return string(value.rbegin(), value.rend()); + } + + // Convert to integer + long long toInt() const { + long long result = 0; + for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) + result += pow * charToInt(value[i]); + return result; + } + + // Convert to integer if possible + bool tryInt(long long &out) const { + long long result = 0; + bool ok = true; + + for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { + if (value[i] == '+') { + ok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows + result += pow; + } else if (value[i] == '-') { + ok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows + result -= pow; + } + } + + if (ok) + out = result; + return ok; + } +}; + +int main() { + BalancedTernary a("+-0++0+"); + BalancedTernary b(-436); + BalancedTernary c("+-++-"); + + cout << "a = " << a << " = " << a.toInt() << endl; + cout << "b = " << b << " = " << b.toInt() << endl; + cout << "c = " << c << " = " << c.toInt() << endl; + + BalancedTernary d = a * (b - c); + + cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; + + BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); + + long long n; + if (e.tryInt(n)) + cout << "e = " << e << " = " << n << endl; + else + cout << "e = " << e << " is too big to fit in a long long" << endl; + + return 0; +} diff --git a/Task/Best-shuffle/D/best-shuffle-1.d b/Task/Best-shuffle/D/best-shuffle-1.d index 4df5a7338b..521da02365 100644 --- a/Task/Best-shuffle/D/best-shuffle-1.d +++ b/Task/Best-shuffle/D/best-shuffle-1.d @@ -1,40 +1,41 @@ import std.stdio, std.random, std.algorithm, std.conv, std.range, -std.traits, std.typecons; + std.traits, std.typecons; auto bestShuffle(S)(in S orig) if (isSomeString!S) { static if (isNarrowString!S) - auto o = to!dstring(orig); - else alias orig o; + immutable o = orig.dtext; + else + alias o = orig; auto s = o.dup; - randomShuffle(s); - foreach (i, ref ci; s) { + s.randomShuffle; + + foreach (immutable i, ref ci; s) { if (ci != o[i]) continue; - foreach (j, ref cj; s) + foreach (immutable j, ref cj; s) if (ci != cj && ci != o[j] && cj != o[i]) { swap(ci, cj); break; } } - return tuple(s, count!"a[0] == a[1]"(zip(s, o))); + + return tuple(s, s.zip(o).count!q{ a[0] == a[1] }); +} unittest { + assert("abracadabra".bestShuffle[1] == 0); + assert("immediately".bestShuffle[1] == 0); + assert("grrrrrr".bestShuffle[1] == 5); + assert("seesaw".bestShuffle[1] == 0); + assert("pop".bestShuffle[1] == 1); + assert("up".bestShuffle[1] == 0); + assert("a".bestShuffle[1] == 1); + assert("".bestShuffle[1] == 0); } -unittest { - assert(bestShuffle("abracadabra"d)[1] == 0); - assert(bestShuffle("immediately"d)[1] == 0); - assert(bestShuffle("grrrrrr"d)[1] == 5); - assert(bestShuffle("seesaw"d)[1] == 0); - assert(bestShuffle("pop"d)[1] == 1); - assert(bestShuffle("up"d)[1] == 0); - assert(bestShuffle("a"d)[1] == 1); - assert(bestShuffle(""d)[1] == 0); -} - -void main(string[] args) { +void main(in string[] args) { if (args.length > 1) { - string entry = join(args[1 .. $], " "); - auto res = bestShuffle(entry); - writefln("%s : %s (%s)", entry, res[0], res[1]); + immutable entry = args.dropOne.join(" "); + const res = entry.bestShuffle; + writefln("%s : %s (%d)", entry, res[]); } } diff --git a/Task/Best-shuffle/Perl/best-shuffle-1.pl b/Task/Best-shuffle/Perl/best-shuffle-1.pl new file mode 100644 index 0000000000..66a7610f47 --- /dev/null +++ b/Task/Best-shuffle/Perl/best-shuffle-1.pl @@ -0,0 +1,28 @@ +use strict; +use warnings; +use List::Util qw(shuffle); +use Algorithm::Permute; + +best_shuffle($_) for qw(abracadabra seesaw elk grrrrrr up a); + +sub best_shuffle { + my ($original_word) = @_; + my $best_word = $original_word; + my $best_score = length $best_word; + + my @shuffled = shuffle split //, $original_word; + my $iterator = Algorithm::Permute->new(\@shuffled); + + while( my @array = $iterator->next ) { + my $word = join '', @array; + # For each letter which is the same in the two words, + # there will be a \x00 in the "^" of the two words. + # The tr operator is then used to count the "\x00"s. + my $score = ($original_word ^ $word) =~ tr/\x00//; + next if $score >= $best_score; + ($best_word, $best_score) = ($word, $score); + last if $score == 0; + } + + print "$original_word, $best_word, $best_score\n"; +} diff --git a/Task/Best-shuffle/Perl/best-shuffle-2.pl b/Task/Best-shuffle/Perl/best-shuffle-2.pl new file mode 100644 index 0000000000..01b6def42a --- /dev/null +++ b/Task/Best-shuffle/Perl/best-shuffle-2.pl @@ -0,0 +1,27 @@ +use strict; +use warnings; +use List::Util qw(shuffle); + +best_shuffle($_) for qw(abracadabra seesaw elk grrrrrr up a); + +sub best_shuffle { + my ($original_word) = @_; + + my @s = split //, $original_word; + my @t = shuffle @s; + + for my $i ( 0 .. $#s ) { + for my $j ( 0 .. $#s ) { + next if $j == $i or + $t[$i] eq $s[$j] or + $t[$j] eq $s[$i]; + @t[$i,$j] = @t[$j,$i]; + last; + } + } + + my $word = join '', @t; + + my $score = ($original_word ^ $word) =~ tr/\x00//; + print "$original_word, $word, $score\n"; +} diff --git a/Task/Best-shuffle/Perl/best-shuffle.pl b/Task/Best-shuffle/Perl/best-shuffle.pl deleted file mode 100644 index d45fe26114..0000000000 --- a/Task/Best-shuffle/Perl/best-shuffle.pl +++ /dev/null @@ -1,38 +0,0 @@ -use strict; -use Algorithm::Permute; - -foreach ("abracadabra", "seesaw", "elk", "grrrrrr", "up", "a") { - best_shuffle($_); -} - -sub score { - my ($original_word,$new_word) = @_; - my $result = 0; - for (my $i = 0 ; $i < length($original_word) ; $i++) { - if (substr($original_word,$i,1) eq substr($new_word,$i,1)) { - $result++; - } - } - return $result; -} - -sub best_shuffle { - my ($original_word) = @_; - my $best_word = $original_word; - my $best_score = length($original_word); - my @array = split(//,$original_word); - - # The below was adapted from perlfaq4 - - my $p_iterator = Algorithm::Permute->new( \@array ); - - while (my @array = $p_iterator->next) { - if (score($original_word,join("",@array))<$best_score) { - $best_score = score($original_word, join("",@array)); - $best_word = join ("",@array); - } - last if ($best_score == 0); - } - - print "$original_word, $best_word, $best_score\n"; -} diff --git a/Task/Best-shuffle/Python/best-shuffle-1.py b/Task/Best-shuffle/Python/best-shuffle-1.py index 4b248965a0..564a255f91 100644 --- a/Task/Best-shuffle/Python/best-shuffle-1.py +++ b/Task/Best-shuffle/Python/best-shuffle-1.py @@ -1,4 +1,3 @@ -from collections import Counter import random def count(w1,wnew): @@ -15,6 +14,7 @@ def best_shuffle(w): for j in rangej: if i != j and wnew[j] != wnew[i] and w[i] != wnew[j] and w[j] != wnew[i]: wnew[j], wnew[i] = wnew[i], wnew[j] + break wnew = ''.join(wnew) return wnew, count(w, wnew) diff --git a/Task/Binary-digits/Maxima/binary-digits.maxima b/Task/Binary-digits/Maxima/binary-digits.maxima index 7e16fd7303..244de34055 100644 --- a/Task/Binary-digits/Maxima/binary-digits.maxima +++ b/Task/Binary-digits/Maxima/binary-digits.maxima @@ -1,15 +1,12 @@ digits([arg]) := block( [n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q], - if n = 0 then [0] else ( - while n # 0 do ( - [n, q]: divide(n, b), - v: endcons(q, v) - ), - v - ) -)$ - -binary(n) := simplode(reverse(digits(9000, 2)))$ + do ( + [n, q]: divide(n, b), + v: cons(q, v), + if n=0 then return(v)))$ +binary(n) := simplode(digits(n, 2))$ binary(9000); -"10001100101000" +/* + 10001100101000 +*/ diff --git a/Task/Binary-search/COBOL/binary-search.cobol b/Task/Binary-search/COBOL/binary-search.cobol new file mode 100644 index 0000000000..09d47c9289 --- /dev/null +++ b/Task/Binary-search/COBOL/binary-search.cobol @@ -0,0 +1,18 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. binary-search. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 nums-area VALUE "01040612184356". + 03 nums PIC 9(2) + OCCURS 7 TIMES + ASCENDING KEY nums + INDEXED BY nums-idx. +PROCEDURE DIVISION. + SEARCH ALL nums + WHEN nums (nums-idx) = 4 + DISPLAY "Found 4 at index " nums-idx + END-SEARCH + . +END PROGRAM binary-search. diff --git a/Task/Binary-search/Objective-C/binary-search-1.m b/Task/Binary-search/Objective-C/binary-search-1.m index 5a8cf26cbd..61af9ac18b 100644 --- a/Task/Binary-search/Objective-C/binary-search-1.m +++ b/Task/Binary-search/Objective-C/binary-search-1.m @@ -13,7 +13,7 @@ NSInteger hi = [self count] - 1; while (lo <= hi) { NSInteger mid = lo + (hi - lo) / 2; - id midVal = [self objectAtIndex:mid]; + id midVal = self[mid]; switch ([midVal compare:key]) { case NSOrderedAscending: lo = mid + 1; @@ -31,21 +31,11 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSArray *a = [NSArray arrayWithObjects: - [NSNumber numberWithInt: 1], - [NSNumber numberWithInt: 3], - [NSNumber numberWithInt: 4], - [NSNumber numberWithInt: 5], - [NSNumber numberWithInt: 6], - [NSNumber numberWithInt: 7], - [NSNumber numberWithInt: 8], - [NSNumber numberWithInt: 9], - [NSNumber numberWithInt: 10], - nil]; - NSLog(@"6 is at position %d", [a binarySearch:[NSNumber numberWithInt: 6]]); // prints 4 + NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10]; + NSLog(@"6 is at position %d", [a binarySearch:@6]); // prints 4 - [pool drain]; + } return 0; } diff --git a/Task/Binary-search/Objective-C/binary-search-2.m b/Task/Binary-search/Objective-C/binary-search-2.m index 6b0ad87c7d..4c2a017f81 100644 --- a/Task/Binary-search/Objective-C/binary-search-2.m +++ b/Task/Binary-search/Objective-C/binary-search-2.m @@ -12,7 +12,7 @@ if (range.length == 0) return NSNotFound; NSInteger mid = range.location + range.length / 2; - id midVal = [self objectAtIndex:mid]; + id midVal = self[mid]; switch ([midVal compare:key]) { case NSOrderedAscending: return [self binarySearch:key @@ -28,22 +28,11 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSArray *a = [NSArray arrayWithObjects: - [NSNumber numberWithInt: 1], - [NSNumber numberWithInt: 3], - [NSNumber numberWithInt: 4], - [NSNumber numberWithInt: 5], - [NSNumber numberWithInt: 6], - [NSNumber numberWithInt: 7], - [NSNumber numberWithInt: 8], - [NSNumber numberWithInt: 9], - [NSNumber numberWithInt: 10], - nil]; - NSLog(@"6 is at position %d", [a binarySearch:[NSNumber numberWithInt: 6] - inRange:NSMakeRange(0, [a count])]); // prints 4 + NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10]; + NSLog(@"6 is at position %d", [a binarySearch:@6]); // prints 4 - [pool drain]; + } return 0; } diff --git a/Task/Binary-search/Objective-C/binary-search-3.m b/Task/Binary-search/Objective-C/binary-search-3.m index adb7edb27b..5d2c3f12fa 100644 --- a/Task/Binary-search/Objective-C/binary-search-3.m +++ b/Task/Binary-search/Objective-C/binary-search-3.m @@ -2,24 +2,14 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSArray *a = [NSArray arrayWithObjects: - [NSNumber numberWithInt: 1], - [NSNumber numberWithInt: 3], - [NSNumber numberWithInt: 4], - [NSNumber numberWithInt: 5], - [NSNumber numberWithInt: 6], - [NSNumber numberWithInt: 7], - [NSNumber numberWithInt: 8], - [NSNumber numberWithInt: 9], - [NSNumber numberWithInt: 10], - nil]; - NSLog(@"6 is at position %lu", [a indexOfObject:[NSNumber numberWithInt: 6] - inSortedRange:NSMakeRange(0, [a count]) - options:0 - usingComparator:^(id x, id y){ return [x compare: y]; }]); // prints 4 + NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10]; + NSLog(@"6 is at position %lu", [a indexOfObject:@6 + inSortedRange:NSMakeRange(0, [a count]) + options:0 + usingComparator:^(id x, id y){ return [x compare: y]; }]); // prints 4 - [pool drain]; + } return 0; } diff --git a/Task/Binary-search/Objective-C/binary-search-4.m b/Task/Binary-search/Objective-C/binary-search-4.m index 06ebdd37ba..1bc157ff49 100644 --- a/Task/Binary-search/Objective-C/binary-search-4.m +++ b/Task/Binary-search/Objective-C/binary-search-4.m @@ -1,30 +1,19 @@ #import CFComparisonResult myComparator(const void *x, const void *y, void *context) { - return [(id)x compare:(id)y]; + return [(__bridge id)x compare:(__bridge id)y]; } -int main() -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; +int main(int argc, const char *argv[]) { + @autoreleasepool { - NSArray *a = [NSArray arrayWithObjects: - [NSNumber numberWithInt: 1], - [NSNumber numberWithInt: 3], - [NSNumber numberWithInt: 4], - [NSNumber numberWithInt: 5], - [NSNumber numberWithInt: 6], - [NSNumber numberWithInt: 7], - [NSNumber numberWithInt: 8], - [NSNumber numberWithInt: 9], - [NSNumber numberWithInt: 10], - nil]; - NSLog(@"6 is at position %d", CFArrayBSearchValues((CFArrayRef)a, - CFRangeMake(0, [a count]), - [NSNumber numberWithInt: 6], - myComparator, - NULL)); // prints 4 + NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10]; + NSLog(@"6 is at position %ld", CFArrayBSearchValues((__bridge CFArrayRef)a, + CFRangeMake(0, [a count]), + (__bridge const void *)@6, + myComparator, + NULL)); // prints 4 - [pool drain]; + } return 0; } diff --git a/Task/Binary-search/Perl-6/binary-search-1.pl6 b/Task/Binary-search/Perl-6/binary-search-1.pl6 index eee577e23d..5ab75526eb 100644 --- a/Task/Binary-search/Perl-6/binary-search-1.pl6 +++ b/Task/Binary-search/Perl-6/binary-search-1.pl6 @@ -1,3 +1,3 @@ -sub search (@a, Num $x --> Int) { - binary_search { $x <=> @a[$^i] }, 0, @a.end +sub search (@a, $x --> Int) { + binary_search { $x cmp @a[$^i] }, 0, @a.end } diff --git a/Task/Binary-search/Ruby/binary-search-3.rb b/Task/Binary-search/Ruby/binary-search-3.rb new file mode 100644 index 0000000000..30d12b48ef --- /dev/null +++ b/Task/Binary-search/Ruby/binary-search-3.rb @@ -0,0 +1,4 @@ +haystack = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324] +needles = [0,42,45,24324,99999] + +needles.select{|needle| haystack.bsearch{|hay| needle <=> hay} } # => [0, 45, 24324] diff --git a/Task/Binary-search/Rust/binary-search.rust b/Task/Binary-search/Rust/binary-search.rust new file mode 100644 index 0000000000..96f15fa1af --- /dev/null +++ b/Task/Binary-search/Rust/binary-search.rust @@ -0,0 +1,17 @@ +fn binary_search(haystack: ~[int], needle: int) -> int { + let mut low = 0; + let mut high = haystack.len() as int - 1; + + if high == 0 { return -1 } + + while low <= high { + // avoid overflow + let mid = low + (high - low) / 2; + + if haystack[mid] > needle { high = mid - 1 } + else if haystack[mid] < needle { low = mid + 1 } + else { return mid } + } + + return -1; +} diff --git a/Task/Binary-search/TI-83-BASIC/binary-search.ti-83 b/Task/Binary-search/TI-83-BASIC/binary-search.ti-83 new file mode 100644 index 0000000000..6265e8609f --- /dev/null +++ b/Task/Binary-search/TI-83-BASIC/binary-search.ti-83 @@ -0,0 +1,27 @@ +PROGRAM:BINSEARC +:Disp "INPUT A LIST:" +:Input L1 +:SortA(L1) +:Disp "INPUT A NUMBER:" +:Input A +:1→L +:dim(L1)→H +:int(L+(H-L)/2)→M +:While LM +:Then +:M+1→L +:Else +:M-1→H +:End +:int(L+(H-L)/2)→M +:End +:If L1(M)=A +:Then +:Disp A +:Disp "IS AT POSITION" +:Disp M +:Else +:Disp A +:Disp "IS NOT IN" +:Disp L1 diff --git a/Task/Binary-strings/PARI-GP/binary-strings.pari b/Task/Binary-strings/PARI-GP/binary-strings.pari new file mode 100644 index 0000000000..566dd4a9bd --- /dev/null +++ b/Task/Binary-strings/PARI-GP/binary-strings.pari @@ -0,0 +1,14 @@ +cmp_str(u,v)=u==v +copy_str(v)=v \\ Creates a copy, not a pointer +append_str(v,n)=concat(v,n) +replace_str(source, n, replacement)=my(v=[]);for(i=1,#source,v=concat(v,if(source[i]==n,replacement,source[i]))); v + +u=[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]; +v=[]; +cmp_str(u,v) +w=copy_str(v) +#w==0 +append_str(u,33) +u[8..12] +replace_str(u,108,[121]) +concat(v,w) diff --git a/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada b/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada index d11fb5bb8a..ff99481d0e 100644 --- a/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada +++ b/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada @@ -77,8 +77,8 @@ begin C := P - 1; for J in reverse A'Range loop C := C + Natural(A(J)) * 58; - A(J) := Stream_Element(Unsigned_32(C) and 255); -- 0x0F - C := Natural(Shift_Right(Unsigned_32(C),8) and 255); -- 0xF0 + A(J) := Stream_Element(Unsigned_32(C) and 255); -- 0x00FF + C := Natural(Shift_Right(Unsigned_32(C),8) and 255); -- 0xFF00 end loop; if C /= 0 then raise Invalid_Address_Error; diff --git a/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d b/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d new file mode 100644 index 0000000000..0e5d4cccbb --- /dev/null +++ b/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d @@ -0,0 +1,85 @@ +import std.stdio, std.algorithm, std.array, std.string, sha_256; + +struct A25 { + // Type for a 25 ubyte (not base58 encoded) bitcoin address. + ubyte[25] enc; + + ubyte bitcoinVersion() const pure nothrow { + return enc[0]; + } + + ubyte[4] embeddedChecksum() const pure nothrow { + return enc[$ - 4 .. $]; + } + + /** Computes a double sha256 hash of the first 21 bytes of + the address. Returns the full 32 ubyte sha256 hash. */ + ubyte[32] doubleSHA256() const pure nothrow { + return SHA256.digest(SHA256.digest(enc[0 .. 21])); + } + + /** Returns a four ubyte checksum computed from the first 21 + bytes of the address. */ + ubyte[4] computeChecksum() const pure nothrow { + return doubleSHA256[0 .. 4]; + } + + /** Takes a base58 encoded address and decodes it into the + receiver. Errors are returned if the argument is not valid base58 + or if the decoded value does not fit in the 25 ubyte address. + The address is not otherwise checked for validity. */ + string set58(in ubyte[] s) pure nothrow { + static immutable digits = + "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + .representation; + static assert(digits.length == 58); + + foreach (immutable char s1; s) { + immutable c = digits.countUntil(s1); + if (c < 0) + return "found a bad char in the Bitcoin address."; + + // Currently the D type system can't see c as nonegative. + uint uc = (c < 0) ? 0 : c; + + foreach_reverse (ref aj; enc) { + uc += digits.length * aj; + aj = uc % 256; + uc /= 256; + } + if (uc > 0) + return "too long Bitcoin address."; + } + + return null; + } +} + +/** Validates a base58 encoded bitcoin address. An address is valid +if it can be decoded into a 25 ubyte address, the Version number is 0, +and the checksum validates. Return value ok will be true for valid +addresses. If ok is false, the address is invalid and the error value +may indicate why. */ +string isValidA58(in ubyte[] a58) pure nothrow { + A25 a; + immutable err = a.set58(a58); + if (!err.empty) + return err; + if (a.bitcoinVersion != 0) + return "not Bitcoin version 0."; + return (a.embeddedChecksum == a.computeChecksum) ? null : + "checksums don't match."; +} + +void main() { + immutable tests = ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz"]; + + foreach (immutable test; tests) { + immutable err = test.representation.isValidA58; + writefln(`"%s": %s`, test, err.empty ? "OK." : err); + } +} diff --git a/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d b/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d index dbf3d945ee..8ede076552 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d +++ b/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d @@ -10,7 +10,7 @@ pure nothrow if (nSegments > 0) { Pt[nSegments + 1] points = void; foreach (immutable i, ref p; points) { - immutable double t = i / cast(double)nSegments, + immutable double t = i / double(nSegments), a = (1.0 - t) ^^ 3, b = 3.0 * t * (1.0 - t) ^^ 2, c = 3.0 * t ^^ 2 * (1.0 - t), diff --git a/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d b/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d index 7b29f8b9b1..a587bffe45 100644 --- a/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d +++ b/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d @@ -9,7 +9,7 @@ pure nothrow if (nSegments > 0) { Pt[nSegments + 1] points = void; foreach (immutable i, ref p; points) { - immutable double t = i / cast(double)nSegments, + immutable double t = i / double(nSegments), a = (1.0 - t) ^^ 2, b = 2.0 * t * (1.0 - t), c = t ^^ 2; diff --git a/Task/Bitmap-Bresenhams-line-algorithm/CoffeeScript/bitmap-bresenhams-line-algorithm.coffee b/Task/Bitmap-Bresenhams-line-algorithm/CoffeeScript/bitmap-bresenhams-line-algorithm.coffee new file mode 100644 index 0000000000..9b329de66f --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/CoffeeScript/bitmap-bresenhams-line-algorithm.coffee @@ -0,0 +1,18 @@ +drawBresenhamLine = (x0, y0, x1, y1) -> + dx = Math.abs(x1 - x0) + sx = if x0 < x1 then 1 else -1 + dy = Math.abs(y1 - y0) + sy = if y0 < y1 then 1 else -1 + err = (if dx>dy then dx else -dy) / 2 + + loop + setPixel(x0, y0) + break if x0 == x1 && y0 == y1 + e2 = err + if e2 > -dx + err -= dy + x0 += sx + if e2 < dy + err += dx + y0 += sy + null diff --git a/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d b/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d index 8e3130adfa..91bd7568ed 100644 --- a/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d +++ b/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d @@ -2,7 +2,7 @@ import std.array, bitmap; void floodFill(Color)(Image!Color img, in uint x, in uint y, in Color color) -/*pure nothrow*/ in { +pure nothrow in { assert (y < img.ny && x < img.nx); } body { immutable target = img[x, y]; @@ -11,21 +11,18 @@ void floodFill(Color)(Image!Color img, in uint x, in uint y, while (!stack.empty) { immutable p = stack.back; - stack.popBack(); + stack.popBack; if (p.y < img.ny && p.x < img.nx && img[p.x, p.y] == target) { img[p.x, p.y] = color; - stack.assumeSafeAppend(); // Not pure nor nothrow. - stack ~= Pos(p.x - 1, p.y); - stack ~= Pos(p.x + 1, p.y); - stack ~= Pos(p.x, p.y - 1); - stack ~= Pos(p.x, p.y + 1); + stack.assumeSafeAppend; + stack ~= [Pos(p.x, p.y + 1), Pos(p.x, p.y - 1), + Pos(p.x + 1, p.y), Pos(p.x - 1, p.y)]; } } } void main() { - auto img = new Image!RGB(); - img.loadPPM6("Unfilledcirc.ppm"); + auto img = loadPPM6(null, "unfilled_circ.ppm"); img.floodFill(200, 200, RGB(127, 0, 0)); - img.savePPM6("Unfilledcirc_flooded.ppm"); + img.savePPM6("unfilled_circ_flooded.ppm"); } diff --git a/Task/Bitmap-Flood-fill/J/bitmap-flood-fill-2.j b/Task/Bitmap-Flood-fill/J/bitmap-flood-fill-2.j index cfb69c60d0..ef1e52c933 100644 --- a/Task/Bitmap-Flood-fill/J/bitmap-flood-fill-2.j +++ b/Task/Bitmap-Flood-fill/J/bitmap-flood-fill-2.j @@ -1,9 +1,9 @@ 'white blue yellow black orange red'=: 255 255 255,0 0 255,255 255 0,0 0 0,255 165 0,:255 0 0 myimg=: white makeRGB 50 70 -lines=: (_2]\^:2) 0 0 25 0 , 25 0 25 35 , 25 35 0 35 , 0 35 0 0 +lines=: _2]\^:2 ] 0 0 25 0 , 25 0 25 35 , 25 35 0 35 , 0 35 0 0 myimg=: (lines;blue) drawLines myimg myimg=: (3 3; yellow) floodFill myimg -myimg=: ((35 25 24 ,: 35 25 10);black) drawCircles myimg +myimg=: ((25 35 24 ,: 25 35 10);black) drawCircles myimg myimg=: (5 34;orange) floodFill myimg myimg=: (5 36;red) floodFill myimg viewRGB myimg diff --git a/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 b/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 index 5c8fe02abe..f67346644c 100644 --- a/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 +++ b/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 @@ -7,7 +7,7 @@ sub MAIN ($filename = 'default.ppm') { $out.say("P6\n$width $height\n255"); for ^$height X ^$width -> $r, $g { - $out.printf("%c%c%c", $r*2, $g*2, 255-$r*2); + $out.write(Buf.new($r*2,$g*2,255-$r*2)); } $out.close; } diff --git a/Task/Bitmap/D/bitmap.d b/Task/Bitmap/D/bitmap.d index 9719ca01e3..758942d625 100644 --- a/Task/Bitmap/D/bitmap.d +++ b/Task/Bitmap/D/bitmap.d @@ -8,11 +8,8 @@ final class Image(T) { const static T black = T.black; else const static T black = T.init; - static if (is(typeof({ auto x = T.white; }))) const static T white = T.white; - else static if (is(typeof({ auto x = T.max; }))) - const static T white = T.max; T[] image; private size_t nx_, ny_; @@ -54,8 +51,8 @@ final class Image(T) { ref T opIndex(in size_t x, in size_t y) pure nothrow in { assert(x < nx_ && y < ny_); - debug assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); - debug assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); + //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); + //assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { return image[x + y * nx_]; } @@ -63,17 +60,17 @@ final class Image(T) { T opIndex(in size_t x, in size_t y) const pure nothrow in { assert(x < nx_ && y < ny_); - debug assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); - debug assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); + //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); + //assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { return image[x + y * nx_]; } - T opIndexAssign(in T color, in size_t x, in size_t y) pure /*nothrow*/ + T opIndexAssign(in T color, in size_t x, in size_t y) pure nothrow in { assert(x < nx_ && y < ny_); - debug assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); - debug assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); + //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); + //assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { return image[x + y * nx_] = color; } @@ -81,8 +78,6 @@ final class Image(T) { void opIndexUnary(string op)(in size_t x, in size_t y) pure nothrow if (op == "++" || op == "--") in { assert(x < nx_ && y < ny_); - debug assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); - debug assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { mixin("image[x + y * nx_] " ~ op ~ ";"); } @@ -93,11 +88,7 @@ final class Image(T) { /// Convert a 2D array of chars to a binary Image. static Image fromText(in string txt, - in char one='#', in char zero='.') - pure - out(result) { - assert(result.image.all!(x => x == black || x == white)); - } body { + in char one='#', in char zero='.') pure { auto M = txt .strip .split diff --git a/Task/Bitmap/Perl-6/bitmap.pl6 b/Task/Bitmap/Perl-6/bitmap.pl6 index 354af1057c..f30e367342 100644 --- a/Task/Bitmap/Perl-6/bitmap.pl6 +++ b/Task/Bitmap/Perl-6/bitmap.pl6 @@ -5,7 +5,7 @@ class Pixel { } class Bitmap { - has Pixel @.data; + has @.data; has Int $.width; has Int $.height; diff --git a/Task/Bitwise-IO/AutoHotkey/bitwise-io.ahk b/Task/Bitwise-IO/AutoHotkey/bitwise-io.ahk new file mode 100644 index 0000000000..7c48069298 --- /dev/null +++ b/Task/Bitwise-IO/AutoHotkey/bitwise-io.ahk @@ -0,0 +1,126 @@ +file = %A_WorkingDir%\z.dat +IfExist, %A_WorkingDir%\z.dat + FileDelete %file% +IfNotEqual ErrorLevel,0, MsgBox Can't delete file "%file%"`nErrorLevel = "%ErrorLevel%" + +res := BinWrite(file,"000102030405060708090a0b0c0d0e0f00") +MsgBox ErrorLevel = %ErrorLevel%`nBytes Written = %res% +res := BinRead(file,data) +MsgBox ErrorLevel = %ErrorLevel%`nBytes Read = %res%`nData = "%data%" + +res := BinWrite(file,"aa00bb",0,2) +MsgBox ErrorLevel = %ErrorLevel%`nBytes Written = %res% +res := BinRead(file,data) +MsgBox ErrorLevel = %ErrorLevel%`nBytes Read = %res%`nData = "%data%" + +res := BinRead(file,data,3,-2) +MsgBox ErrorLevel = %ErrorLevel%`nBytes Read = %res%`nData = "%data%" +ExitApp + +/* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BinWrite ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +| - Open binary file +| - (Over)Write n bytes (n = 0: all) +| - From offset (offset < 0: counted from end) +| - Close file +| data -> file[offset + 0..n-1], rest of file unchanged +| Return #bytes actually written +*/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +BinWrite(file, data, n=0, offset=0) +{ + ; Open file for WRITE (0x40..), OPEN_ALWAYS (4): creates only if it does not exists + h := DllCall("CreateFile","str",file,"Uint",0x40000000,"Uint",0,"UInt",0,"UInt",4,"Uint",0,"UInt",0) + IfEqual h,-1, SetEnv, ErrorLevel, -1 + IfNotEqual ErrorLevel,0,Return,0 ; couldn't create the file + + m = 0 ; seek to offset + IfLess offset,0, SetEnv,m,2 + r := DllCall("SetFilePointerEx","Uint",h,"Int64",offset,"UInt *",p,"Int",m) + IfEqual r,0, SetEnv, ErrorLevel, -3 + IfNotEqual ErrorLevel,0, { + t = %ErrorLevel% ; save ErrorLevel to be returned + DllCall("CloseHandle", "Uint", h) + ErrorLevel = %t% ; return seek error + Return 0 + } + + TotalWritten = 0 + m := Ceil(StrLen(data)/2) + If (n <= 0 or n > m) + n := m + Loop %n% + { + StringLeft c, data, 2 ; extract next byte + StringTrimLeft data, data, 2 ; remove used byte + c = 0x%c% ; make it number + result := DllCall("WriteFile","UInt",h,"UChar *",c,"UInt",1,"UInt *",Written,"UInt",0) + TotalWritten += Written ; count written + if (!result or Written < 1 or ErrorLevel) + break + } + + IfNotEqual ErrorLevel,0, SetEnv,t,%ErrorLevel% + + h := DllCall("CloseHandle", "Uint", h) + IfEqual h,-1, SetEnv, ErrorLevel, -2 + IfNotEqual t,,SetEnv, ErrorLevel, %t% + + Return TotalWritten +} + +/* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BinRead ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +| - Open binary file +| - Read n bytes (n = 0: all) +| - From offset (offset < 0: counted from end) +| - Close file +| data (replaced) <- file[offset + 0..n-1] +| Return #bytes actually read +*/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +BinRead(file, ByRef data, n=0, offset=0) +{ + h := DllCall("CreateFile","Str",file,"Uint",0x80000000,"Uint",3,"UInt",0,"UInt",3,"Uint",0,"UInt",0) + IfEqual h,-1, SetEnv, ErrorLevel, -1 + IfNotEqual ErrorLevel,0,Return,0 ; couldn't open the file + + m = 0 ; seek to offset + IfLess offset,0, SetEnv,m,2 + r := DllCall("SetFilePointerEx","Uint",h,"Int64",offset,"UInt *",p,"Int",m) + IfEqual r,0, SetEnv, ErrorLevel, -3 + IfNotEqual ErrorLevel,0, { + t = %ErrorLevel% ; save ErrorLevel to be returned + DllCall("CloseHandle", "Uint", h) + ErrorLevel = %t% ; return seek error + Return 0 + } + + TotalRead = 0 + data = + IfEqual n,0, SetEnv n,0xffffffff ; almost infinite + + format = %A_FormatInteger% ; save original integer format + SetFormat Integer, Hex ; for converting bytes to hex + + Loop %n% + { + result := DllCall("ReadFile","UInt",h,"UChar *",c,"UInt",1,"UInt *",Read,"UInt",0) + if (!result or Read < 1 or ErrorLevel) + break + TotalRead += Read ; count read + c += 0 ; convert to hex + StringTrimLeft c, c, 2 ; remove 0x + c = 0%c% ; pad left with 0 + StringRight c, c, 2 ; always 2 digits + data = %data%%c% ; append 2 hex digits + } + + IfNotEqual ErrorLevel,0, SetEnv,t,%ErrorLevel% + + h := DllCall("CloseHandle", "Uint", h) + IfEqual h,-1, SetEnv, ErrorLevel, -2 + IfNotEqual t,,SetEnv, ErrorLevel, %t% + + SetFormat Integer, %format% ; restore original format + Totalread += 0 ; convert to original format + Return TotalRead +} diff --git a/Task/Break-OO-privacy/Objective-C/break-oo-privacy.m b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m similarity index 54% rename from Task/Break-OO-privacy/Objective-C/break-oo-privacy.m rename to Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m index ea5c51b132..519c61fd95 100644 --- a/Task/Break-OO-privacy/Objective-C/break-oo-privacy.m +++ b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m @@ -17,27 +17,20 @@ } return self; } -- (void)dealloc { - [_name release]; - [super dealloc]; -} @end int main (int argc, const char * argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool{ - Example *foo = [[Example alloc] initWithName:@"Eric"]; + Example *foo = [[Example alloc] initWithName:@"Eric"]; - // get private field - NSLog(@"%@", foo->_name); + // get private field + NSLog(@"%@", [foo valueForKey:@"name"]); - // set private field - [foo->_name release]; - foo->_name = [@"Edith" copy]; - NSLog(@"%@", foo); + // set private field + [foo setValue:@"Edith" forKey:@"name"]; + NSLog(@"%@", foo); - [foo release]; - - [pool release]; + } return 0; } diff --git a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m new file mode 100644 index 0000000000..0feb4058e9 --- /dev/null +++ b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m @@ -0,0 +1,50 @@ +#import + +@interface Example : NSObject { +@private + NSString *_name; +} +- (id)initWithName:(NSString *)name; +@end + +@implementation Example +- (NSString *)description { + return [NSString stringWithFormat:@"Hello, I am %@", _name]; +} +- (id)initWithName:(NSString *)name { + if ((self = [super init])) { + _name = [name copy]; + } + return self; +} +@end + +@interface Example (HackName) +- (NSString *)getName; +- (void)setNameTo:(NSString *)newName; +@end + +@implementation Example (HackName) +- (NSString *)getName { + return _name; +} +- (void)setNameTo:(NSString *)newName { + _name = [newName copy]; +} +@end + +int main (int argc, const char * argv[]) { + @autoreleasepool{ + + Example *foo = [[Example alloc] initWithName:@"Eric"]; + + // get private field + NSLog(@"%@", [foo getName]); + + // set private field + [foo setNameTo:@"Edith"]; + NSLog(@"%@", foo); + + } + return 0; +} diff --git a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m new file mode 100644 index 0000000000..0e2840f7f7 --- /dev/null +++ b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m @@ -0,0 +1,38 @@ +#import +#import + +@interface Example : NSObject { +@private + NSString *_name; +} +- (id)initWithName:(NSString *)name; +@end + +@implementation Example +- (NSString *)description { + return [NSString stringWithFormat:@"Hello, I am %@", _name]; +} +- (id)initWithName:(NSString *)name { + if ((self = [super init])) { + _name = [name copy]; + } + return self; +} +@end + +int main (int argc, const char * argv[]) { + @autoreleasepool{ + + Example *foo = [[Example alloc] initWithName:@"Eric"]; + + // get private field + Ivar nameField = class_getInstanceVariable([foo class], "_name"); + NSLog(@"%@", object_getIvar(foo, nameField)); + + // set private field + object_setIvar(foo, nameField, @"Edith"); + NSLog(@"%@", foo); + + } + return 0; +} diff --git a/Task/Bulls-and-cows-Player/AutoHotkey/bulls-and-cows-player.ahk b/Task/Bulls-and-cows-Player/AutoHotkey/bulls-and-cows-player.ahk new file mode 100644 index 0000000000..1e67160d38 --- /dev/null +++ b/Task/Bulls-and-cows-Player/AutoHotkey/bulls-and-cows-player.ahk @@ -0,0 +1,107 @@ +length:=4, i:=0, S:=P(9,length) + +Gui, Add, Text, w83 vInfo, Think of a %length%-digit number with no duplicate digits. +Gui, Add, Edit, w40 vBulls +Gui, Add, Text, x+3, Bulls +Gui, Add, Edit, xm w40 vCows +Gui, Add, Text, x+3, Cows +Gui, Add, Button, xm w83 Default vDefault, Start +Gui, Add, Edit, ym w130 r8 vHistory ReadOnly +Gui, Show +Return + +ButtonStart: + If Default = Restart + Reload + Gui, Submit, NoHide + GuiControl, Focus, Bulls + If (Bulls = length) + { + GuiControl, , Info, Guessed in %i% tries! + GuiControl, , Default, Restart + Default = Restart + } + Else + { + If i = 0 + { + GuiControl, , Default, Submit + GuiControl, , History + } + Else + { + If (StrLen(Bulls) != 1 || StrLen(Cows) != 1) + Return + If Bulls is not digit + Return + If Cows is not digit + Return + GuiControl, , History, % History .= ": " Bulls " Bulls " Cows " Cows`n" + GuiControl, , Bulls + GuiControl, , Cows + + S:=Remove(S, Guess, Bulls, Cows) + } + If !S + { + GuiControl, , Info, Invalid response. + GuiControl, , Default, Restart + Default = Restart + } + Else + { + Guess := SubStr(S,1,length) + GuiControl, , History, % History . Guess + GuiControl, , Info, Enter a single digit number of bulls and cows. + i++ + } + } +Return + +GuiEscape: +GuiClose: + ExitApp + +Remove(S, Guess, Bulls, Cows) { + Loop, Parse, S, `n + If (Bulls "," Cows = Response(Guess, A_LoopField)) + S2 .= A_LoopField . "`n" + Return SubStr(S2,1,-1) +} + +; from http://rosettacode.org/wiki/Bulls and Cows#AutoHotkey +Response(Guess,Code) { + Bulls := 0, Cows := 0 + Loop, % StrLen(Code) + If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1)) + Bulls++ + Else If (InStr(Code, SubStr(Guess, A_Index, 1))) + Cows++ + Return Bulls "," Cows +} + +; from http://rosettacode.org/wiki/Permutations#Alternate_Version +P(n,k="",opt=0,delim="",str="") { + i:=0 + If !InStr(n,"`n") + If n in 2,3,4,5,6,7,8,9 + Loop, %n% + n := A_Index = 1 ? A_Index : n "`n" A_Index + Else + Loop, Parse, n, %delim% + n := A_Index = 1 ? A_LoopField : n "`n" A_LoopField + If (k = "") + RegExReplace(n,"`n","",k), k++ + If k is not Digit + Return "k must be a digit." + If opt not in 0,1,2,3 + Return "opt invalid." + If k = 0 + Return str + Else + Loop, Parse, n, `n + If (!InStr(str,A_LoopField) || opt & 1) + s .= (!i++ ? (opt & 2 ? str "`n" : "") : "`n" ) + . P(n,k-1,opt,delim,str . A_LoopField . delim) + Return s +} diff --git a/Task/Bulls-and-cows/AutoHotkey/bulls-and-cows.ahk b/Task/Bulls-and-cows/AutoHotkey/bulls-and-cows.ahk index 11d432c501..0ae640410b 100644 --- a/Task/Bulls-and-cows/AutoHotkey/bulls-and-cows.ahk +++ b/Task/Bulls-and-cows/AutoHotkey/bulls-and-cows.ahk @@ -1,28 +1,52 @@ -While StrLen(Code) < 4 { - Random, num, 1, 9 - If !InStr(Code, num) - Code .= num +length:=4, Code:="" ; settings + +While StrLen(Code) < length { + Random, num, 1, 9 + If !InStr(Code, num) + Code .= num } -Gui, Add, Edit, vGuess, Enter a guess... -Gui, Add, Button, wp Default, Submit -Gui, Add, ListBox, ym r8 vHistory +Gui, Add, Text, w83 vInfo, I'm thinking of a %length%-digit number with no duplicate digits. +Gui, Add, Edit, wp vGuess, Enter a guess... +Gui, Add, Button, wp Default vDefault, Submit +Gui, Add, Edit, ym w130 r8 vHistory ReadOnly Gui, Show Return ButtonSubmit: - Gui, Submit, NoHide - If StrLen(Guess) != 4 - Return - If Guess is not digit - Return - bulls:=0, cows:=0 - Loop, 4 - If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1)) - bulls++ - Else If InStr(Code, SubStr(Guess, A_Index, 1)) - cows++ - GuiControl,, History, % Guess ": " bulls " Bulls " cows " Cows" + If Default = Restart + Reload + Gui, Submit, NoHide + If (StrLen(Guess) != length) + GuiControl, , Info, Enter a %length%-digit number. + Else If Guess is not digit + GuiControl, , Info, Enter a %length%-digit number. + Else + { + GuiControl, , Info + GuiControl, , Guess + If (Guess = Code) + { + GuiControl, , Info, Correct! + GuiControl, , Default, Restart + Default = Restart + } + response := Response(Guess, Code) + Bulls := SubStr(response, 1, InStr(response,",")-1) + Cows := SubStr(response, InStr(response,",")+1) + GuiControl, , History, % History . Guess ": " Bulls " Bulls " Cows " Cows`n" + } Return +GuiEscape: GuiClose: - ExitApp + ExitApp + +Response(Guess,Code) { + Bulls := 0, Cows := 0 + Loop, % StrLen(Code) + If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1)) + Bulls++ + Else If (InStr(Code, SubStr(Guess, A_Index, 1))) + Cows++ + Return Bulls "," Cows +} diff --git a/Task/Bulls-and-cows/Rust/bulls-and-cows.rust b/Task/Bulls-and-cows/Rust/bulls-and-cows.rust new file mode 100644 index 0000000000..50efff0678 --- /dev/null +++ b/Task/Bulls-and-cows/Rust/bulls-and-cows.rust @@ -0,0 +1,93 @@ +use std::iter::range_inclusive; +use std::rand::{task_rng, Rng}; +use std::io; +use std::str; +use std::option::collect; +use std::io::stdio::StdReader; +use std::str::from_char; +use std::iter::FromIterator; +use std::hashmap::HashSet; + +static NUMBER_OF_DIGITS: uint = 4; +static LOWEST_DIGIT: uint = 1; +static HIGHEST_DIGIT: uint = 9; + +fn generate_digits() -> ~[uint] { + task_rng().sample(range_inclusive(LOWEST_DIGIT, HIGHEST_DIGIT), NUMBER_OF_DIGITS) +} + +fn read_input(reader: &mut StdReader) -> ~str { + let mut buf = [0u8, ..32]; + let num_bytes = reader.read(buf).unwrap(); + return str::from_utf8(buf).slice_to(num_bytes).trim().to_owned(); +} + +fn parse_guess_string(guess: &str) -> Option<~[uint]> { + let digit_chars = guess.chars(); + let digit_options = digit_chars.map(|c| from_str::(from_char(c))); + + // std::option::collect is a cool little function that goes through an iterator + // and returns a None if it hits a None. If not it will return a Some that + // contains a vector containing the unwrapped values of the iterator + let digits_maybe: Option<~[uint]> = collect(digit_options); + + match digits_maybe { + Some(ref digits) => { + if digits.len() != NUMBER_OF_DIGITS { + println!("you need to guess with {:u} digits", NUMBER_OF_DIGITS); + return None; + } + if digits.iter().any(|&digit| digit < LOWEST_DIGIT || digit > HIGHEST_DIGIT) { + println("digit out of range"); + return None; + } + let digits_set: HashSet<&uint> = FromIterator::from_iterator(&mut digits.iter()); + if digits_set.len() != NUMBER_OF_DIGITS { + println("no duplicates!"); + return None; + } + }, + None => println("non-numeric input, please try again") + } + return digits_maybe; +} + +fn calculate_score(digits: &[uint], guess: &[uint]) -> (uint, uint) { + let mut bulls = 0; + let mut cows = 0; + for i in range(0, digits.len()) { + let mut j = guess.iter(); + let pos_maybe: Option = j.position(|&a| -> bool {a == digits[i]}); + match pos_maybe { + None => (), + Some(pos) if pos == i => bulls += 1, + Some(_) => cows += 1 + } + } + return (bulls, cows); +} + +fn main() { + let mut reader = io::stdin(); + + loop { + let digits = generate_digits(); + println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS); + loop { + let guess_string = read_input(&mut reader); + let digits_maybe = parse_guess_string(guess_string); + match digits_maybe { + None => continue, + Some(guess_digits) => { + let (bulls, cows) = calculate_score(digits, guess_digits); + if bulls == NUMBER_OF_DIGITS { + println("you win!"); + break; + } else { + println!("bulls: {:u}, cows: {:u}", bulls, cows); + } + } + } + } + } +} diff --git a/Task/CRC-32/AutoHotkey/crc-32.ahk b/Task/CRC-32/AutoHotkey/crc-32.ahk new file mode 100644 index 0000000000..41bcf95d6a --- /dev/null +++ b/Task/CRC-32/AutoHotkey/crc-32.ahk @@ -0,0 +1,19 @@ +str := "The quick brown fox jumps over the lazy dog" +MsgBox, % "String:`n" (str) "`n`nCRC32:`n" CRC32(str) + + + +; CRC32 ============================================================================= +CRC32(string, encoding = "UTF-8") +{ + chrlength := (encoding = "CP1200" || encoding = "UTF-16") ? 2 : 1 + length := (StrPut(string, encoding) - 1) * chrlength + VarSetCapacity(data, length, 0) + StrPut(string, &data, floor(length / chrlength), encoding) + SetFormat, Integer, % SubStr((A_FI := A_FormatInteger) "H", 0) + CRC32 := DllCall("NTDLL\RtlComputeCrc32", "UInt", 0, "UInt", &data, "UInt", length, "UInt") + CRC := SubStr(CRC32 | 0x1000000000, -7) + DllCall("User32.dll\CharLower", "Str", CRC) + SetFormat, Integer, %A_FI% + return CRC +} diff --git a/Task/CRC-32/Common-Lisp/crc-32.lisp b/Task/CRC-32/Common-Lisp/crc-32.lisp index d658f581af..efc16d3280 100644 --- a/Task/CRC-32/Common-Lisp/crc-32.lisp +++ b/Task/CRC-32/Common-Lisp/crc-32.lisp @@ -1,13 +1,8 @@ (ql:quickload :ironclad) +(defun string-to-digest (str digest) + "Return the specified digest for the ASCII string as a hex string." + (ironclad:byte-array-to-hex-string + (ironclad:digest-sequence digest + (ironclad:ascii-string-to-byte-array str)))) - -(defun write-seq-base-16 (seq &key ((:stream *standard-output*) - *standard-output*) - &aux (*print-base* 16)) - (map nil #'write seq)) - - -(write-seq-base-16 - (crypto:digest-sequence 'ironclad:crc32 - (crypto:ascii-string-to-byte-array - "The quick brown fox jumps over the lazy dog"))) +(string-to-digest "The quick brown fox jumps over the lazy dog" :crc32) diff --git a/Task/CRC-32/Haskell/crc-32-1.hs b/Task/CRC-32/Haskell/crc-32-1.hs new file mode 100644 index 0000000000..4b915237ea --- /dev/null +++ b/Task/CRC-32/Haskell/crc-32-1.hs @@ -0,0 +1,21 @@ +import Data.Bits +import Data.Word +import Numeric + +crcTable :: Word32 -> Word32 +crcTable i = table !! (fromIntegral i) + where + table = map (\a -> iterate xf a !! 8) [0..255] + xf r = let d = shiftR r 1 in + if r .&. 1 == 1 then xor d 0xedb88320 else d + +charToWord :: Char -> Word32 +charToWord c = (fromIntegral . fromEnum) c + +calcCrc :: String -> Word32 +calcCrc text = complement ( foldl cf (complement 0) text ) + where cf crc x = xor (shiftR crc 8) (crcTable $ xor (crc .&. 0xff) (charToWord x) ) + +crc32 text = showHex ( calcCrc text ) "" + +main = putStrLn $ crc32 "The quick brown fox jumps over the lazy dog" diff --git a/Task/CRC-32/Haskell/crc-32-2.hs b/Task/CRC-32/Haskell/crc-32-2.hs new file mode 100644 index 0000000000..dd7739c45a --- /dev/null +++ b/Task/CRC-32/Haskell/crc-32-2.hs @@ -0,0 +1,13 @@ +import Data.List (genericLength) +import Numeric (showHex) +import Foreign.C + +foreign import ccall "zlib.h crc32" zlib_crc32 :: CULong -> CString -> CUInt -> CULong + +main = do + let s = "The quick brown fox jumps over the lazy dog" + ptr <- newCString s + + let r = zlib_crc32 0 ptr (genericLength s) + + putStrLn $ showHex r "" diff --git a/Task/Caesar-cipher/Scala/caesar-cipher-3.scala b/Task/Caesar-cipher/Scala/caesar-cipher-3.scala new file mode 100644 index 0000000000..45bb15b168 --- /dev/null +++ b/Task/Caesar-cipher/Scala/caesar-cipher-3.scala @@ -0,0 +1,12 @@ +class Caeser(val key: Int) { + @annotation.tailrec + private def rotate(p: Int, s: IndexedSeq[Char]): IndexedSeq[Char] = if (p < 0) rotate(s.length + p, s) else s.drop(p) ++ s.take(p) + + val uc = 'A' to 'Z' + val lc = 'a' to 'z' + val as = uc ++ lc + val bs = rotate(key, uc) ++ rotate(key, lc) + + def encode(c: Char) = if (as.contains(c)) bs(as.indexOf(c)) else c + def decode(c: Char) = if (bs.contains(c)) as(bs.indexOf(c)) else c +} diff --git a/Task/Caesar-cipher/Scala/caesar-cipher-4.scala b/Task/Caesar-cipher/Scala/caesar-cipher-4.scala new file mode 100644 index 0000000000..4373749759 --- /dev/null +++ b/Task/Caesar-cipher/Scala/caesar-cipher-4.scala @@ -0,0 +1,6 @@ +val text = "The five boxing wizards jump quickly" +val myCaeser = new Caeser(3) +val encoded = text.map(c => myCaeser.encode(c)) +println("Plaintext => " + text) +println("Ciphertext => " + encoded) +println("Decrypted => " + encoded.map(c => myCaeser.decode(c))) diff --git a/Task/Caesar-cipher/Scheme/caesar-cipher.ss b/Task/Caesar-cipher/Scheme/caesar-cipher.ss new file mode 100644 index 0000000000..47cef01ec7 --- /dev/null +++ b/Task/Caesar-cipher/Scheme/caesar-cipher.ss @@ -0,0 +1,27 @@ +; +; Works with R7RS-compatible Schemes (e.g. Chibi). +; Also current versions of Chicken, Gauche and Kawa. +; +(cond-expand + (chicken (use srfi-13)) + (gauche (use srfi-13)) + (kawa (import (srfi :13))) + (else (import (scheme base) (scheme write)))) ; R7RS + + +(define msg "The quick brown fox jumps over the lazy dog.") +(define key 13) + +(define (caesar char) + (define A (char->integer #\A)) + (define Z (char->integer #\Z)) + (define a (char->integer #\a)) + (define z (char->integer #\z)) + (define c (char->integer char)) + (integer->char + (cond ((<= A c Z) (+ A (modulo (+ key (- c A)) 26))) + ((<= a c z) (+ a (modulo (+ key (- c a)) 26))) + (else c)))) ; Return other characters verbatim. + +(display (string-map caesar msg)) +(newline) diff --git a/Task/Caesar-cipher/TXR/caesar-cipher.txr b/Task/Caesar-cipher/TXR/caesar-cipher.txr index ca71f41a12..6795dcce54 100644 --- a/Task/Caesar-cipher/TXR/caesar-cipher.txr +++ b/Task/Caesar-cipher/TXR/caesar-cipher.txr @@ -13,7 +13,7 @@ (e (tostringp (+ #\a (mod (+ i k) 26)))) (P (upcase-str p)) (E (upcase-str e))) - '(((,p ,e) (,P ,E)) + ^(((,p ,e) (,P ,E)) ((,e ,p) (,E ,P)))))) @(deffilter enc . @(mappend (fun first) enc-dec)) @(deffilter dec . @(mappend (fun second) enc-dec)) diff --git a/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk b/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk new file mode 100644 index 0000000000..cd89d0cb9e --- /dev/null +++ b/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk @@ -0,0 +1,39 @@ +CALENDAR(YR){ + LASTDAY := [], DAY := [] + TITLES = + (LTRIM + ______JANUARY_________________FEBRUARY_________________MARCH_______ + _______APRIL____________________MAY____________________JUNE________ + ________JULY___________________AUGUST_________________SEPTEMBER_____ + ______OCTOBER_________________NOVEMBER________________DECEMBER______ + ) + STRINGSPLIT, TITLE, TITLES, % CHR(10) + RES := "________________________________" YR CHR(13) CHR(10) + + LOOP 4 { ; 4 VERTICAL SECTIONS + DAY[1]:=YR SUBSTR("0" A_INDEX*3 -2, -1) 01 + DAY[2]:=YR SUBSTR("0" A_INDEX*3 -1, -1) 01 + DAY[3]:=YR SUBSTR("0" A_INDEX*3 , -1) 01 + RES .= CHR(13) CHR(10) TITLE%A_INDEX% CHR(13) CHR(10) "SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA" + LOOP , 6 { ; 6 WEEKS MAX PER MONTH + WEEK := A_INDEX, RES .= CHR(13) CHR(10) + LOOP, 21 { ; 3 WEEKS TIMES 7 DAYS + MON := CEIL(A_INDEX/7), THISWD := MOD(A_INDEX-1,7)+1 + FORMATTIME, WD, % DAY[MON], WDAY + ;~ MSGBOX % WD + FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) + IF (WD>THISWD) { + RES .= "__ " + CONTINUE + } + DD := ((WEEK>3) && DD <10) ? "__" : DD, RES .= DD " ", LASTDAY[MON] := DAY[MON], DAY[MON] +=1, D + RES .= ((WD=7) && A_INDEX < 21) ? "___" : "" + FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) + } + } + RES .= CHR(13) CHR(10) + } + STRINGREPLACE, RES, RES,_,%A_SPACE%, ALL + STRINGREPLACE, RES, RES,%A_SPACE%0,%A_SPACE%%A_SPACE%, ALL + RETURN RES +} diff --git a/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk b/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk new file mode 100644 index 0000000000..b366deaeac --- /dev/null +++ b/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk @@ -0,0 +1,16 @@ +EXAMPLES: +GUI, FONT,S8, COURIER +GUI, ADD, EDIT, VYR W40 R1 LIMIT4 NUMBER, 1969 +GUI, ADD, EDIT, VEDIT2 W580 R38 +GUI, ADD, BUTTON, DEFAULT HIDDEN GSUBMIT +GUI, SHOW + +SUBMIT: +GUI, SUBMIT, NOHIDE +GUICONTROL,, EDIT2, % CALENDAR(YR) +RETURN + +GUIESCAPE: +GUICLOSE: +EXITAPP +RETURN diff --git a/Task/Calendar/AutoHotkey/calendar-1.ahk b/Task/Calendar/AutoHotkey/calendar-1.ahk new file mode 100644 index 0000000000..6817c91783 --- /dev/null +++ b/Task/Calendar/AutoHotkey/calendar-1.ahk @@ -0,0 +1,38 @@ +Calendar(Yr){ + LastDay := [], Day := [] + Titles = + (ltrim + ______January_________________February_________________March_______ + _______April____________________May____________________June________ + ________July___________________August_________________September_____ + ______October_________________November________________December______ + ) + StringSplit, title, titles, `n + Res := "________________________________" Yr "`r`n" + + loop 4 { ; 4 Vertical Sections + Day[1]:=Yr SubStr("0" A_Index*3 -2, -1) 01 + Day[2]:=Yr SubStr("0" A_Index*3 -1, -1) 01 + Day[3]:=Yr SubStr("0" A_Index*3 , -1) 01 + Res .= "`r`n" title%A_Index% "`r`nSu Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa" + loop , 6 { ; 6 Weeks max per month + Week := A_Index, Res .= "`r`n" + loop, 21 { ; 3 weeks times 7 days + Mon := Ceil(A_Index/7), ThisWD := Mod(A_Index-1,7)+1 + FormatTime, WD, % Day[Mon], WDay + FormatTime, dd, % Day[Mon], dd + if (WD>ThisWD) { + Res .= "__ " + continue + } + dd := ((Week>3) && dd <10) ? "__" : dd, Res .= dd " ", LastDay[Mon] := Day[Mon], Day[Mon] +=1, Days + Res .= ((wd=7) && A_Index < 21) ? "___" : "" + FormatTime, dd, % Day[Mon], dd + } + } + Res .= "`r`n" + } + StringReplace, Res, Res,_,%A_Space%, all + Res:=RegExReplace(Res,"`am)(^|\s)\K0", " ") + return res +} diff --git a/Task/Calendar/AutoHotkey/calendar-2.ahk b/Task/Calendar/AutoHotkey/calendar-2.ahk new file mode 100644 index 0000000000..110539d3f5 --- /dev/null +++ b/Task/Calendar/AutoHotkey/calendar-2.ahk @@ -0,0 +1,15 @@ +Gui, font,s8, COURIER +Gui, add, edit, vYr w40 r1 Limit4 Number, 1969 +Gui, add, edit, vEdit2 w580 r38 +Gui, Add, Button, Default Hidden gSubmit +Gui, show + +Submit: +Gui, Submit, NoHide +GuiControl,, Edit2, % Calendar(Yr) +return + +GuiEscape: +GuiClose: +ExitApp +return diff --git a/Task/Calendar/Perl/calendar.pl b/Task/Calendar/Perl/calendar.pl index 52f47bdced..206c4b2444 100644 --- a/Task/Calendar/Perl/calendar.pl +++ b/Task/Calendar/Perl/calendar.pl @@ -1 +1,37 @@ -$_=$ARGV[0]//1969;`cal $_ >&2` +#!/usr/bin/perl +use strict; +use warnings; +use Time::Local; + +my @names = qw/ JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC/; + +my $year = shift ||'2007'; + +for my $month (0..11) { + print " $names[$month] $year\n"; + print calendar($year, $month), "\n\n"; +} + +sub calendar { + my ($year, $month) = @_; + my @mon_days = qw/31 28 31 30 31 30 31 31 30 31 30 31/; + ++$mon_days[1] if $year % 4 == 0 && ($year % 400 == 0 || $year % 1 ++00 != 0); + + my $cal = " Sun Mon Tue Wed Thu Fri Sat\n"; + + # Months are indexed beginning at 0 + my $time = timegm(0,0,0,1,$month,$year); + my $wday = (gmtime $time)[6]; + + $cal .= " " x $wday; + + my $mday = 1; + + while ($mday <= $mon_days[$month]) { + $cal .= sprintf "%4s", $mday++; + $cal .= "\n" if ($wday + $mday -1) % 7 == 0; + } + return $cal; +} +# Let's use this as a placeholder until a better solution arrives, OK? diff --git a/Task/Calendar/Pike/calendar.pike b/Task/Calendar/Pike/calendar.pike index 4ce03b863f..5cffc7390c 100644 --- a/Task/Calendar/Pike/calendar.pike +++ b/Task/Calendar/Pike/calendar.pike @@ -37,7 +37,8 @@ array make_month(object month, int field_width, void|string region) if (region) holidays = Calendar.Events.find_region(region)->scan_events(month); - array weekday_names = sprintf("%*.*s", field_width, field_width, month->week()->days()->week_day_shortname()[*]); + array weekday_names = + sprintf("%*.*s", field_width, field_width, month->week()->days()->week_day_shortname()[*]); out += ({ ({ month->month_name(), month->month_no(), month->year_name() }) }); out += ({ weekday_names }); diff --git a/Task/Call-an-object-method/Bracmat/call-an-object-method.bracmat b/Task/Call-an-object-method/Bracmat/call-an-object-method.bracmat new file mode 100644 index 0000000000..50b70a7f6c --- /dev/null +++ b/Task/Call-an-object-method/Bracmat/call-an-object-method.bracmat @@ -0,0 +1,13 @@ +( ( myClass + = (name=aClass) + ( Method + = .out$(str$("Output from " !(its.name) ": " !arg)) + ) + (new=.!arg:?(its.name)) + ) +& (myClass.Method)$"Example of calling a 'class' method" +& new$(myClass,object1):?MyObject +& (MyObject..Method)$"Example of calling an instance method" +& !MyObject:?Alias +& (Alias..Method)$"Example of calling an instance method from an alias" +); diff --git a/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol b/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol new file mode 100644 index 0000000000..e8eee82db7 --- /dev/null +++ b/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol @@ -0,0 +1,7 @@ +*> INVOKE +INVOKE FooClass "someMethod" RETURNING bar *> Factory object +INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object + +*> Inline method invocation +MOVE FooClass::"someMethod" TO bar *> Factory object +MOVE foo-instance::"anotherMethod" TO bar *> Instance object diff --git a/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol b/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol new file mode 100644 index 0000000000..a4434322d6 --- /dev/null +++ b/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol @@ -0,0 +1,3 @@ +INVOKE foo-instance "FactoryObject" RETURNING foo-factory +*> foo-factory can be treated like a normal object reference. +INVOKE foo-factory "someMethod" diff --git a/Task/Call-an-object-method/Object-Pascal/call-an-object-method.object b/Task/Call-an-object-method/Object-Pascal/call-an-object-method.object new file mode 100644 index 0000000000..ec0b5bb408 --- /dev/null +++ b/Task/Call-an-object-method/Object-Pascal/call-an-object-method.object @@ -0,0 +1,5 @@ +// Static (known in Pascal as class method) +MyClass.method(someParameter); + +// Instance +myInstance.method(someParameter); diff --git a/Task/Call-an-object-method/PL-SQL/call-an-object-method.sql b/Task/Call-an-object-method/PL-SQL/call-an-object-method.sql index b785e7d5b9..5f671f5172 100644 --- a/Task/Call-an-object-method/PL-SQL/call-an-object-method.sql +++ b/Task/Call-an-object-method/PL-SQL/call-an-object-method.sql @@ -24,5 +24,4 @@ BEGIN myInstance := myClass(null); DBMS_OUTPUT.put_line( myClass.static_method() ); DBMS_OUTPUT.put_line( myInstance.instance_method() ); -END; -/ +END;/ diff --git a/Task/Call-an-object-method/Scala/call-an-object-method.scala b/Task/Call-an-object-method/Scala/call-an-object-method.scala index 593a597102..65805fb5d5 100644 --- a/Task/Call-an-object-method/Scala/call-an-object-method.scala +++ b/Task/Call-an-object-method/Scala/call-an-object-method.scala @@ -1,10 +1,9 @@ -/** This class implicitly includes a constructor which accepts an Int and +/* This class implicitly includes a constructor which accepts an Int and * creates "val variable1: Int" with that value. */ -class MyClass(val variable1: Int) { - var variable2 = "asdf" // Another instance variable; a public var this time +class MyClass(val memberVal: Int) { // Acts like a getter, getter automatically generated. + var variable2 = "asdf" // Another instance variable; a public mutable this time def this() = this(0) // An auxilliary constructor that instantiates with a default value - def myMethod = variable1 // A getter for variable1, getter of variable1 is auto-created } object HelloObject { @@ -13,13 +12,13 @@ object HelloObject { /** Demonstrate use of our example class. */ -object Call_an_object_method extends Application { +object Call_an_object_method extends App { val s = "Hello" - val m = new MyClass() + val m = new MyClass val n = new MyClass(3) - println(HelloObject.s) // prints "Hello" by object getterHelloObject - - println(m.myMethod) // prints 0 - println(n.myMethod) // prints 3 + assert(HelloObject.s == "Hello") // "Hello" by object getterHelloObject + assert(m.memberVal == 0) + assert(n.memberVal == 3) + println("Successfully completed without error.") } diff --git a/Task/Canny-edge-detector/D/canny-edge-detector.d b/Task/Canny-edge-detector/D/canny-edge-detector.d index 83a232a644..0e3ec61fd7 100644 --- a/Task/Canny-edge-detector/D/canny-edge-detector.d +++ b/Task/Canny-edge-detector/D/canny-edge-detector.d @@ -87,7 +87,7 @@ pure nothrow in { Image!Pixel cannyEdgeDetection(in Image!Pixel inp, in int tMin, in int tMax, in float sigma) -/*pure*/ nothrow in { +pure nothrow in { assert(inp !is null); } body { immutable int nx = inp.nx; @@ -96,15 +96,15 @@ Image!Pixel cannyEdgeDetection(in Image!Pixel inp, gaussianFilter(inp.image, outp, nx, ny, sigma); - immutable float[] Gx = [-1, 0, 1, - -2, 0, 2, - -1, 0, 1]; + static immutable float[] Gx = [-1, 0, 1, + -2, 0, 2, + -1, 0, 1]; auto after_Gx = new Pixel[nx * ny]; convolution!false(outp, after_Gx, Gx, nx, ny, 3); - immutable float[] Gy = [ 1, 2, 1, - 0, 0, 0, - -1,-2,-1]; + static immutable float[] Gy = [ 1, 2, 1, + 0, 0, 0, + -1,-2,-1]; auto after_Gy = new Pixel[nx * ny]; convolution!false(outp, after_Gy, Gy, nx, ny, 3); @@ -129,11 +129,9 @@ Image!Pixel cannyEdgeDetection(in Image!Pixel inp, sw = ss + 1, se = ss - 1; - // fmod is not pure. - immutable float dir = - cast(float)(fmod(atan2(cast(double)after_Gy[c], - cast(double)after_Gx[c]) + PI, - PI) / PI) * 8; + immutable aux = atan2(double(after_Gy[c]), + double(after_Gx[c])) + PI; + immutable float dir = float((aux % PI) / PI) * 8; if (((dir <= 1 || dir > 7) && G[c] > G[ee] && G[c] > G[ww]) || // 0 deg. diff --git a/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d b/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d index b674ff462f..bdd37cc892 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d +++ b/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d @@ -1,21 +1,31 @@ -import std.stdio, sieve_of_eratosthenes3; +enum mod = (in int n, in int m) pure nothrow => ((n % m) + m) % m; -int mod(in int n, in int m) pure nothrow { - return ((n % m) + m) % m; +bool isPrime(in uint n) pure nothrow { + if (n == 2 || n == 3) + return true; + else if (n < 2 || n % 2 == 0 || n % 3 == 0) + return false; + for (uint div = 5, inc = 2; div ^^ 2 <= n; + div += inc, inc = 6 - inc) + if (n % div == 0) + return false; + return true; } void main() { + import std.stdio; + foreach (immutable p; 2 .. 62) { - if (!p.IsPrime) continue; + if (!p.isPrime) continue; foreach (immutable h3; 2 .. p) { immutable g = h3 + p; foreach (immutable d; 1 .. g) { if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3) continue; immutable q = 1 + (p - 1) * g / d; - if (!q.IsPrime) continue; + if (!q.isPrime) continue; immutable r = 1 + (p * q / h3); - if (!r.IsPrime || (q * r) % (p - 1) != 1) continue; + if (!r.isPrime || (q * r) % (p - 1) != 1) continue; writeln(p, " x ", q, " x ", r); } } diff --git a/Task/Carmichael-3-strong-pseudoprimes/PARI-GP/carmichael-3-strong-pseudoprimes.pari b/Task/Carmichael-3-strong-pseudoprimes/PARI-GP/carmichael-3-strong-pseudoprimes.pari new file mode 100644 index 0000000000..de4206ef55 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/PARI-GP/carmichael-3-strong-pseudoprimes.pari @@ -0,0 +1,12 @@ +f(p)={ + my(v=List(),q,r); + for(h=2,p-1, + for(d=1,h+p-1, + if((h+p)*(p-1)%d==0 && Mod(p,h)^2==-d && isprime(q=(p-1)*(h+p)/d+1) && isprime(r=p*q\h+1)&&q*r%(p-1)==1, + listput(v,p*q*r) + ) + ) + ); + Set(v) +}; +forprime(p=3,67,v=f(p); for(i=1,#v,print1(v[i]", "))) diff --git a/Task/Carmichael-3-strong-pseudoprimes/PL-I/carmichael-3-strong-pseudoprimes.pli b/Task/Carmichael-3-strong-pseudoprimes/PL-I/carmichael-3-strong-pseudoprimes.pli new file mode 100644 index 0000000000..9eabdb5088 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/PL-I/carmichael-3-strong-pseudoprimes.pli @@ -0,0 +1,27 @@ +Carmichael: procedure options (main, reorder); /* 24 January 2014 */ + declare (Prime1, Prime2, Prime3, h3, d) fixed binary (31); + + put ('Carmichael numbers are:'); + + do Prime1 = 1 to 61; + + do h3 = 2 to Prime1; + +d_loop: do d = 1 to h3+Prime1-1; + if (mod((h3+Prime1)*(Prime1-1), d) = 0) & + (mod(-Prime1*Prime1, h3) = mod(d, h3)) then + do; + Prime2 = (Prime1-1) * (h3+Prime1)/d; Prime2 = Prime2 + 1; + if ^is_prime(Prime2) then iterate d_loop; + Prime3 = Prime1*Prime2/h3; Prime3 = Prime3 + 1; + if ^is_prime(Prime3) then iterate d_loop; + if mod(Prime2*Prime3, Prime1-1) ^= 1 then iterate d_loop; + put skip edit (trim(Prime1), ' x ', trim(Prime2), ' x ', trim(Prime3)) (A); + end; + end; + end; + end; + + /* Uses is_prime from Rosetta Code PL/I. */ + +end Carmichael; diff --git a/Task/Case-sensitivity-of-identifiers/Objeck/case-sensitivity-of-identifiers.objeck b/Task/Case-sensitivity-of-identifiers/Objeck/case-sensitivity-of-identifiers.objeck new file mode 100644 index 0000000000..f456074439 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Objeck/case-sensitivity-of-identifiers.objeck @@ -0,0 +1,8 @@ +class Program { + function : Main(args : String[]) ~ Nil { + dog := "Benjamin"; + Dog := "Samba"; + DOG := "Bernie"; + "The three dogs are named {$dog}, {$Dog}, and {$DOG}."->PrintLine(); + } +} diff --git a/Task/Catalan-numbers/PicoLisp/catalan-numbers.l b/Task/Catalan-numbers/PicoLisp/catalan-numbers.l index 7395367737..d1dfc1a191 100644 --- a/Task/Catalan-numbers/PicoLisp/catalan-numbers.l +++ b/Task/Catalan-numbers/PicoLisp/catalan-numbers.l @@ -12,7 +12,7 @@ (de catalanRec (N) (if (=0 N) 1 - (cache '(NIL) (pack (char (hash N)) N) # Memoize + (cache '(NIL) N # Memoize (sum '((I) (* (catalanRec I) (catalanRec (- N I 1)))) (range 0 (dec N)) ) ) ) ) diff --git a/Task/Chat-server/Racket/chat-server.rkt b/Task/Chat-server/Racket/chat-server.rkt index 5400a2f994..d9be5caf7a 100644 --- a/Task/Chat-server/Racket/chat-server.rkt +++ b/Task/Chat-server/Racket/chat-server.rkt @@ -1,37 +1,21 @@ #lang racket -(define *client-outputs* (list (current-output-port))) - -(define ((tell-all who current-out) line) - (for ([out *client-outputs*] #:unless (eq? current-out out)) - (displayln (~a who ": " line) out))) - -(define (serve-client input output) - (define nick (begin - (display "Nick: " output) - (read-line input))) - (define tell (tell-all nick output)) +(define outs (list (current-output-port))) +(define ((tell-all who o) line) + (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) +(define ((client i o)) + (define nick (begin (display "Nick: " o) (read-line i))) + (define tell (tell-all nick o)) (let loop ([line "(joined)"]) - (cond [(eof-object? line) - (tell "(left)") - (set! *client-outputs* (remq output *client-outputs*)) - (close-output-port output)] - [else - (tell line) - (loop (read-line input))]))) + (if (eof-object? line) + (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) + (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) - (define-values [client-input client-output] (tcp-accept listener)) - (file-stream-buffer-mode client-input 'none) - (file-stream-buffer-mode client-output 'none) - (thread (λ () - (serve-client client-input client-output))) - (set! *client-outputs* (cons client-output *client-outputs*)) - (chat-server listener)) + (define-values [i o] (tcp-accept listener)) + (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) + (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) -(define (start-server) - (chat-server (tcp-listen 12321))) - -(void (thread start-server)) -(client (current-input-port) (current-output-port)) +(void (thread (λ() (chat-server (tcp-listen 12321))))) +((client (current-input-port) (current-output-port))) diff --git a/Task/Check-that-file-exists/Maple/check-that-file-exists.maple b/Task/Check-that-file-exists/Maple/check-that-file-exists.maple new file mode 100644 index 0000000000..72b6255f5b --- /dev/null +++ b/Task/Check-that-file-exists/Maple/check-that-file-exists.maple @@ -0,0 +1,5 @@ +with(FileTools): +Exists("input.txt"); +Exists("docs") and IsDirectory("docs"); +Exists("/input.txt"); +Exists("/docs") and IsDirectory("/docs"); diff --git a/Task/Check-that-file-exists/PARI-GP/check-that-file-exists.pari b/Task/Check-that-file-exists/PARI-GP/check-that-file-exists.pari index 5d3da4df65..d48ae24130 100644 --- a/Task/Check-that-file-exists/PARI-GP/check-that-file-exists.pari +++ b/Task/Check-that-file-exists/PARI-GP/check-that-file-exists.pari @@ -1 +1,3 @@ trap(,"does not exist",read("input.txt");"exists") +trap(,"does not exist",read("c:\\input.txt");"exists") +trap(,"does not exist",read("c:\\dirname\\nul");"exists") diff --git a/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx b/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx index dbacb1e481..67f582284a 100644 --- a/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx +++ b/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx @@ -1,20 +1,15 @@ -/********************************************************************** -* exists(filespec) -* returns 1 if filespec identifies a file with size>0 -* (a file of size 0 is deemed not to exist.) -* or a directory -* 0 otherwise -* 09.06.2013 Walter Pachl (retrieved from my toolset) -**********************************************************************/ -exists: - parse arg spec - call sysfiletree spec, 'LIST', 'BL' - if list.0\=1 then return 0 -- does not exist - parse var list.1 . . size flags . - if size>0 then return 1 -- real file - If substr(flags,2,1)='D' Then Do - Say spec 'is a directory' - Return 1 - End - If size=0 Then Say spec 'is a zero-size file' - Return 0 +/*REXX pgm creates a new empty file and directory; in curr dir and root.*/ +fn='input.txt' +dn='docs' +@.1='current directory'; @.2='root directory' /*msgs for each pass.*/ +parse upper version v; regina=pos('REGINA',v)\==0 /*Regina being used? */ + + do j=1 for 2; say /*perform these statements twice.*/ + if stream(fn,'C',"QUERY EXISTS")=='' then say 'file ' fn " doesn't exist in the" @.j + else say 'file ' fn " does exist in the" @.j + if dosisdir(dn) then say 'directory ' dn " does exist in the" @.j + else say 'directory ' dn " doesn't exist in the" @.j + if regina then call chdir '\' /*use Regina's version of CHDIR.*/ + else call doschdir '\' /*PC/REXX & Personal REXX version*/ + end /*j*/ /*now, go and perform them again.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Cholesky-decomposition/00DESCRIPTION b/Task/Cholesky-decomposition/00DESCRIPTION index 6648b11250..0e849c9368 100644 --- a/Task/Cholesky-decomposition/00DESCRIPTION +++ b/Task/Cholesky-decomposition/00DESCRIPTION @@ -16,7 +16,7 @@ A &= & = \begin{pmatrix} l_{11} & 0 & 0 \\ - l_{21} & l_{22} & 0 \\ + l_{21} & l_{22} & 0 \\f l_{31} & l_{32} & l_{33}\\ \end{pmatrix} \begin{pmatrix} diff --git a/Task/Cholesky-decomposition/Fortran/cholesky-decomposition.f b/Task/Cholesky-decomposition/Fortran/cholesky-decomposition.f new file mode 100644 index 0000000000..b8cda8d281 --- /dev/null +++ b/Task/Cholesky-decomposition/Fortran/cholesky-decomposition.f @@ -0,0 +1,70 @@ +Program Cholesky_decomp +! *************************************************! +! LBH @ ULPGC 06/03/2014 +! Compute the Cholesky decomposition for a matrix A +! after the attached +! http://rosettacode.org/wiki/Cholesky_decomposition +! note that the matrix A is complex since there might +! be values, where the sqrt has complex solutions. +! Here, only the real values are taken into account +!*************************************************! +implicit none + +INTEGER, PARAMETER :: m=3 !rows +INTEGER, PARAMETER :: n=3 !cols +COMPLEX, DIMENSION(m,n) :: A +REAL, DIMENSION(m,n) :: L +REAL :: sum1, sum2 +INTEGER i,j,k + +! Assign values to the matrix +A(1,:)=(/ 25, 15, -5 /) +A(2,:)=(/ 15, 18, 0 /) +A(3,:)=(/ -5, 0, 11 /) +! !!!!!!!!!!!another example!!!!!!! +! A(1,:) = (/ 18, 22, 54, 42 /) +! A(2,:) = (/ 22, 70, 86, 62 /) +! A(3,:) = (/ 54, 86, 174, 134 /) +! A(4,:) = (/ 42, 62, 134, 106 /) + + + + + +! Initialize values +L(1,1)=real(sqrt(A(1,1))) +L(2,1)=A(2,1)/L(1,1) +L(2,2)=real(sqrt(A(2,2)-L(2,1)*L(2,1))) +L(3,1)=A(3,1)/L(1,1) +! for greater order than m,n=3 add initial row value +! for instance if m,n=4 then add the following line +! L(4,1)=A(4,1)/L(1,1) + + + + + +do i=1,n + do k=1,i + sum1=0 + sum2=0 + do j=1,k-1 + if (i==k) then + sum1=sum1+(L(k,j)*L(k,j)) + L(k,k)=real(sqrt(A(k,k)-sum1)) + elseif (i > k) then + sum2=sum2+(L(i,j)*L(k,j)) + L(i,k)=(1/L(k,k))*(A(i,k)-sum2) + else + L(i,k)=0 + end if + end do + end do +end do + +! write output +do i=1,m + print "(3(1X,F6.1))",L(i,:) +end do + +End program Cholesky_decomp diff --git a/Task/Classes/Bracmat/classes.bracmat b/Task/Classes/Bracmat/classes.bracmat new file mode 100644 index 0000000000..e4bdbd25d0 --- /dev/null +++ b/Task/Classes/Bracmat/classes.bracmat @@ -0,0 +1,8 @@ +( ( resolution + = (x=) + (y=) + (new=.!arg:(?(its.x),?(its.y))) + ) +& new$(resolution,640,480):?VGA +& new$(resolution,1920,1080):?1080p +& out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y))); diff --git a/Task/Classes/Objective-C/classes-2.m b/Task/Classes/Objective-C/classes-2.m index e5c754559b..e49eb8e20e 100644 --- a/Task/Classes/Objective-C/classes-2.m +++ b/Task/Classes/Objective-C/classes-2.m @@ -1,7 +1,7 @@ @implementation MyClass // Was not declared because init is defined in NSObject -- init +- (id)init { if (self = [super init]) variable = 0; diff --git a/Task/Classes/Objective-C/classes-3.m b/Task/Classes/Objective-C/classes-3.m index 3af6f011c6..21b12ee89e 100644 --- a/Task/Classes/Objective-C/classes-3.m +++ b/Task/Classes/Objective-C/classes-3.m @@ -3,6 +3,3 @@ MyClass *mc = [[MyClass alloc] init]; // Sending a message [mc variable]; - -// Releasing it. When its reference count goes to zero, it will be deallocated -[mc release]; diff --git a/Task/Classes/Perl-6/classes-1.pl6 b/Task/Classes/Perl-6/classes-1.pl6 index 6bfb71feb3..5f8ff79e08 100644 --- a/Task/Classes/Perl-6/classes-1.pl6 +++ b/Task/Classes/Perl-6/classes-1.pl6 @@ -1,7 +1,7 @@ class Camel { has Int $.humps = 1; } my Camel $a .= new; -say $a.humps; # Automatically generated accessor method. +say $a.humps; # Automatically generated accessor method. my Camel $b .= new: humps => 2; say $b.humps; diff --git a/Task/Classes/Perl-6/classes-2.pl6 b/Task/Classes/Perl-6/classes-2.pl6 index 3eb0c571af..b178887605 100644 --- a/Task/Classes/Perl-6/classes-2.pl6 +++ b/Task/Classes/Perl-6/classes-2.pl6 @@ -1,5 +1,5 @@ class Butterfly { - has Int $!age; # The ! twigil makes it private. + has Int $!age; # With the ! twigil, no public accessor method is generated has Str $.name; has Str $.color; has Bool $.wings; diff --git a/Task/Classes/Scala/classes.scala b/Task/Classes/Scala/classes.scala index afbf734617..16f90495a1 100644 --- a/Task/Classes/Scala/classes.scala +++ b/Task/Classes/Scala/classes.scala @@ -1,19 +1,24 @@ -/** - * This class implicitly includes a constructor which accepts an int and - * creates "val variable1: Int" with that value. +/** This class implicitly includes a constructor which accepts an Int and + * creates "val variable1: Int" with that value. */ -class MyClass(variable1: Int) { - var variable2 = "asdf" // Another instance variable; a var this time - def this() = this(0) // An auxilliary constructor that instantiates with a default value - def myMethod = variable1 // A getter for variable1 +class MyClass(val myMethod: Int) { // Acts like a getter, getter automatically generated. + var variable2 = "asdf" // Another instance variable; a public var this time + def this() = this(0) // An auxilliary constructor that instantiates with a default value } -/** - * Demonstrate use of our example class. - */ -object Main extends Application { - val m = new MyClass() - val n = new MyClass(3) - println(m.myMethod) // prints 0 - println(n.myMethod) // prints 3 +object HelloObject { + val s = "Hello" // Not private, so getter auto-generated +} + +/** Demonstrate use of our example class. + */ +object Call_an_object_method extends App { + val s = "Hello" + val m = new MyClass() + val n = new MyClass(3) + + println(HelloObject.s) // prints "Hello" by object getterHelloObject + + println(m.myMethod) // prints 0 + println(n.myMethod) // prints 3 } diff --git a/Task/Collections/Objective-C/collections.m b/Task/Collections/Objective-C/collections.m index 90b8fde42c..691ac970a2 100644 --- a/Task/Collections/Objective-C/collections.m +++ b/Task/Collections/Objective-C/collections.m @@ -2,19 +2,12 @@ void show_collection(id coll) { - id el; - NSEnumerator *en; - if ( [coll respondsToSelector: @selector(keyEnumerator)] ) { - en = [coll keyEnumerator]; - } else { - en = [coll objectEnumerator]; - } - while( (el = [en nextObject]) != nil) + for ( id el in coll ) { - if ( [coll respondsToSelector: @selector(countForObject:)] ) { - NSLog(@"%@ appears %d times", el, [coll countForObject: el]); + if ( [coll isKindOfClass: [NSCountedSet class]] ) { + NSLog(@"%@ appears %lu times", el, [coll countForObject: el]); } else if ( [coll isKindOfClass: [NSDictionary class]] ) { - NSLog(@"%@ -> %@", el, [coll valueForKey: el]); + NSLog(@"%@ -> %@", el, coll[el]); } else { NSLog(@"%@", el); } @@ -24,37 +17,34 @@ void show_collection(id coll) int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - // create an empty set - NSMutableSet *set = [[NSMutableSet alloc] init]; - // populate it - [set addObject: @"one"]; - [set addObject: [NSNumber numberWithInt: 10]]; - [set addObjectsFromArray: [NSArray arrayWithObjects: @"one", - [NSNumber numberWithInt: 20], - [NSNumber numberWithInt: 10], - @"two", nil] ]; - // let's show it - show_collection(set); + // create an empty set + NSMutableSet *set = [[NSMutableSet alloc] init]; + // populate it + [set addObject: @"one"]; + [set addObject: @10]; + [set addObjectsFromArray: @[@"one", @20, @10, @"two"] ]; + // let's show it + show_collection(set); - // create an empty counted set (a bag) - NSCountedSet *cset = [[NSCountedSet alloc] init]; - // populate it - [cset addObject: @"one"]; - [cset addObject: @"one"]; - [cset addObject: @"two"]; - // show it - show_collection(cset); + // create an empty counted set (a bag) + NSCountedSet *cset = [[NSCountedSet alloc] init]; + // populate it + [cset addObject: @"one"]; + [cset addObject: @"one"]; + [cset addObject: @"two"]; + // show it + show_collection(cset); - // create a dictionary - NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; - // populate it - [dict setValue: [NSNumber numberWithInt: 4] forKey: @"four"]; - [dict setValue: [NSNumber numberWithInt: 8] forKey: @"eight"]; - // show it - show_collection(dict); + // create a dictionary + NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; + // populate it + dict[@"four"] = @4; + dict[@"eight"] = @8; + // show it + show_collection(dict); - [pool release]; + } return EXIT_SUCCESS; } diff --git a/Task/Color-quantization/00DESCRIPTION b/Task/Color-quantization/00DESCRIPTION index 8eb80dbbb6..28bcb4e3c8 100644 --- a/Task/Color-quantization/00DESCRIPTION +++ b/Task/Color-quantization/00DESCRIPTION @@ -1,4 +1,3 @@ -{{task}} [[file:quantum_frog.png|full color|thumb|left|192px]][[file:quantum_frog_16.png|Example: Gimp 16 color|thumb|left|192px]] [[wp:Color_quantization|Color quantization]] is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of [[wp:Cluster_analysis|cluster analysis]], if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [http://web.cs.wpi.edu/~matt/courses/cs563/talks/color_quant/CQindex.html], each with its own advantages and drawbacks. diff --git a/Task/Colour-bars-Display/PHP/colour-bars-display.php b/Task/Colour-bars-Display/PHP/colour-bars-display-1.php similarity index 100% rename from Task/Colour-bars-Display/PHP/colour-bars-display.php rename to Task/Colour-bars-Display/PHP/colour-bars-display-1.php diff --git a/Task/Colour-bars-Display/PHP/colour-bars-display-2.php b/Task/Colour-bars-Display/PHP/colour-bars-display-2.php new file mode 100644 index 0000000000..682ef1a2d2 --- /dev/null +++ b/Task/Colour-bars-Display/PHP/colour-bars-display-2.php @@ -0,0 +1,17 @@ +'; +foreach ($colors as $color) { + echo ''; +} +echo ''; diff --git a/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 b/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 index dd03d6b894..e26e3c5cb3 100644 --- a/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 +++ b/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 @@ -1,7 +1,7 @@ my $HOR = 1280; my $VERT = 720; -my @colors = map -> $r, $g, $b { Buf.new: ($r, $g, $b) xx $HOR div 8 }, +my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $HOR div 8) }, 0, 0, 0, 255, 0, 0, 0,255, 0, diff --git a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs index 4890ff2cbb..5d5e1a4945 100644 --- a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs +++ b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs @@ -1,6 +1,7 @@ -- Return the combinations, with replacement, of k items from the -- list. We ignore the case where k is greater than the length of -- the list. +combsWithRep :: Int -> [a] -> [[a]] combsWithRep 0 _ = [[]] combsWithRep _ [] = [] combsWithRep k xxs@(x:xs) = map (x:) (combsWithRep (k-1) xxs) ++ combsWithRep k xs diff --git a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs index 2c15d205d9..ea90f6e3c9 100644 --- a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs +++ b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs @@ -1,2 +1,8 @@ -[["iced","iced"],["iced","jam"],["iced","plain"],["jam","jam"],["jam","plain"],["plain","plain"]] -220 +combsWithRep :: Int -> [a] -> [[a]] +combsWithRep k xs = combsBySize xs !! k + where + combsBySize = foldr f ([[]] : repeat []) + f x next = scanl1 (\z n -> map (x:) z ++ n) next + +main = do + print $ combsWithRep 2 ["iced","jam","plain"] diff --git a/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ocaml b/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ocaml index ff7dacb731..ba52fb586f 100644 --- a/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ocaml +++ b/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ocaml @@ -1,7 +1,9 @@ -# combs_with_rep 2 ["iced"; "jam"; "plain"] ;; -- : string list list = -[["iced"; "iced"]; ["iced"; "jam"]; ["iced"; "plain"]; ["jam"; "jam"]; - ["jam"; "plain"]; ["plain"; "plain"]] - -# List.length (combs_with_rep 3 [1;2;3;4;5;6;7;8;9;10]) ;; -- : int = 220 +let combs_with_rep m xs = + let arr = Array.make (m+1) [] in + arr.(0) <- [[]]; + List.iter (fun x -> + for i = 1 to m do + arr.(i) <- arr.(i) @ List.map (fun xs -> x::xs) arr.(i-1) + done + ) xs; + arr.(m) diff --git a/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.ss b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.ss new file mode 100644 index 0000000000..47d5958f37 --- /dev/null +++ b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.ss @@ -0,0 +1,13 @@ +(define (combs-with-rep k lst) + (cond ((= k 0) '(())) + ((null? lst) '()) + (else + (append + (map + (lambda (x) + (cons (car lst) x)) + (combs-with-rep (- k 1) lst)) + (combs-with-rep k (cdr lst)))))) + +(display (combs-with-rep 2 (list "iced" "jam" "plain"))) (newline) +(display (length (combs-with-rep 3 '(1 2 3 4 5 6 7 8 9 10)))) (newline) diff --git a/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.ss b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.ss new file mode 100644 index 0000000000..ec692f21cf --- /dev/null +++ b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.ss @@ -0,0 +1,15 @@ +(define (combs-with-rep m lst) + (define arr (make-vector (+ m 1) '())) + (vector-set! arr 0 '(())) + (for-each (lambda (x) + (do ((i 1 (+ i 1))) + ((> i m)) + (vector-set! arr i (append (vector-ref arr i) + (map (lambda (xs) (cons x xs)) + (vector-ref arr (- i 1))))) + ) + ) lst) + (vector-ref arr m)) + +(display (combs-with-rep 2 (list "iced" "jam" "plain"))) (newline) +(display (length (combs-with-rep 3 '(1 2 3 4 5 6 7 8 9 10)))) (newline) diff --git a/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions.ss b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions.ss deleted file mode 100644 index 834d91c8fc..0000000000 --- a/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions.ss +++ /dev/null @@ -1,11 +0,0 @@ -(define combinations - (lambda (lst k) - (cond ((= k 0) '(())) - ((null? lst) '()) - (else - (append - (map - (lambda (x) - (cons (car lst) x)) - (combinations lst (- k 1))) - (combinations (cdr lst) k)))))) diff --git a/Task/Combinations-with-repetitions/Standard-ML/combinations-with-repetitions-1.ml b/Task/Combinations-with-repetitions/Standard-ML/combinations-with-repetitions-1.ml new file mode 100644 index 0000000000..f35f3a3c8a --- /dev/null +++ b/Task/Combinations-with-repetitions/Standard-ML/combinations-with-repetitions-1.ml @@ -0,0 +1,7 @@ +let rec combs_with_rep k xxs = + match k, xxs with + | 0, _ -> [[]] + | _, [] -> [] + | k, x::xs -> + List.map (fun ys -> x::ys) (combs_with_rep (k-1) xxs) + @ combs_with_rep k xs diff --git a/Task/Combinations-with-repetitions/Standard-ML/combinations-with-repetitions-2.ml b/Task/Combinations-with-repetitions/Standard-ML/combinations-with-repetitions-2.ml new file mode 100644 index 0000000000..58d731eec8 --- /dev/null +++ b/Task/Combinations-with-repetitions/Standard-ML/combinations-with-repetitions-2.ml @@ -0,0 +1,11 @@ +fun combs_with_rep (m, xs) = let + val arr = Array.array (m+1, []) +in + Array.update (arr, 0, [[]]); + app (fn x => + Array.modifyi (fn (i, y) => + if i = 0 then y else y @ map (fn xs => x::xs) (Array.sub (arr, i-1)) + ) arr + ) xs; + Array.sub (arr, m) +end diff --git a/Task/Combinations/Haskell/combinations-7.hs b/Task/Combinations/Haskell/combinations-7.hs new file mode 100644 index 0000000000..983f077647 --- /dev/null +++ b/Task/Combinations/Haskell/combinations-7.hs @@ -0,0 +1,5 @@ +comb :: Int -> [a] -> [[a]] +comb m xs = combsBySize xs !! m + where + combsBySize = foldr f ([[]] : repeat []) + f x next = zipWith (++) (map (map (x:)) ([]:next)) next diff --git a/Task/Combinations/OCaml/combinations.ocaml b/Task/Combinations/OCaml/combinations-1.ocaml similarity index 100% rename from Task/Combinations/OCaml/combinations.ocaml rename to Task/Combinations/OCaml/combinations-1.ocaml diff --git a/Task/Combinations/OCaml/combinations-2.ocaml b/Task/Combinations/OCaml/combinations-2.ocaml new file mode 100644 index 0000000000..3e2d015be3 --- /dev/null +++ b/Task/Combinations/OCaml/combinations-2.ocaml @@ -0,0 +1,16 @@ +let comb m xs = + let xs = Array.of_list xs in + if m > Array.length xs then + [] + else begin + let arr = Array.make (m+1) [] in + arr.(0) <- [[]]; + for j = 0 to Array.length xs - m do + for i = 1 to m do + arr.(i) <- arr.(i) @ List.map (fun ys -> xs.(j+i-1)::ys) arr.(i-1) + done + done; + arr.(m) + end +;; +comb 3 [0;1;2;3;4];; diff --git a/Task/Combinations/Perl-6/combinations-1.pl6 b/Task/Combinations/Perl-6/combinations-1.pl6 index 663b55aedb..2be33bde97 100644 --- a/Task/Combinations/Perl-6/combinations-1.pl6 +++ b/Task/Combinations/Perl-6/combinations-1.pl6 @@ -1 +1 @@ -.say for (^5).list.combinations(3).tree; +.say for combinations(5,3); diff --git a/Task/Combinations/Rust/combinations.rust b/Task/Combinations/Rust/combinations.rust new file mode 100644 index 0000000000..123220c37f --- /dev/null +++ b/Task/Combinations/Rust/combinations.rust @@ -0,0 +1,30 @@ +fn comb(arr: &[T], n: uint) { + let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false); + comb_intern(arr, n, incl_arr, 0); +} + +fn comb_intern(arr: &[T], n: uint, incl_arr: &mut [bool], index: uint) { + if (arr.len() < n + index) { return; } + if (n == 0) { + let mut it = arr.iter().zip(incl_arr.iter()).filter_map(|(val, incl)| + if (*incl) { Some(val) } else { None } + ); + for val in it { print!("{} ", *val); } + print("\n"); + return; + } + + incl_arr[index] = true; + comb_intern(arr, n-1, incl_arr, index+1); + incl_arr[index] = false; + + comb_intern(arr, n, incl_arr, index+1); +} + +fn main() { + let arr1 = ~[1, 2, 3, 4, 5]; + comb(arr1, 3); + + let arr2 = ~["A", "B", "C", "D", "E"]; + comb(arr2, 3); +} diff --git a/Task/Combinations/TXR/combinations.txr b/Task/Combinations/TXR/combinations.txr new file mode 100644 index 0000000000..5d64bce177 --- /dev/null +++ b/Task/Combinations/TXR/combinations.txr @@ -0,0 +1,5 @@ +@(do + (defun comb-n-m (n m) + (comb (range* 0 n) m)) + + (put-line `3 comb 5 = @(comb-n-m 5 3)`)) diff --git a/Task/Command-line-arguments/Frink/command-line-arguments.frink b/Task/Command-line-arguments/Frink/command-line-arguments.frink new file mode 100644 index 0000000000..7f76c5136f --- /dev/null +++ b/Task/Command-line-arguments/Frink/command-line-arguments.frink @@ -0,0 +1 @@ +println[ARGS] diff --git a/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt b/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt index bb4831edf6..d7ce86e6a8 100644 --- a/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt +++ b/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt @@ -1,2 +1,3 @@ #lang racket + (for ([arg (current-command-line-arguments)]) (displayln arg)) diff --git a/Task/Comments/00DESCRIPTION b/Task/Comments/00DESCRIPTION index 5bda1e7a05..20f1705be8 100644 --- a/Task/Comments/00DESCRIPTION +++ b/Task/Comments/00DESCRIPTION @@ -1,4 +1,6 @@ All ways to include text in a language source file that's completely ignored by the compiler or interpreter. '''See Also:'''
+* Related Task: [[Documentation]] +* [https://en.wikipedia.org/wiki/Comment_(computer_programming) Wikipedia] * [http://xkcd.com/156 xkcd] (Humor: hand gesture denoting // for "commenting out" people.) diff --git a/Task/Comments/Frink/comments.frink b/Task/Comments/Frink/comments.frink new file mode 100644 index 0000000000..0471859017 --- /dev/null +++ b/Task/Comments/Frink/comments.frink @@ -0,0 +1,6 @@ +// This is a single-line comment + +/* This is a comment + that spans multiple lines + and so on. +*/ diff --git a/Task/Comments/Maple/comments.maple b/Task/Comments/Maple/comments.maple new file mode 100644 index 0000000000..63bc4e4bd8 --- /dev/null +++ b/Task/Comments/Maple/comments.maple @@ -0,0 +1,5 @@ +x := 4: x; # Everything on this line, after this, is a comment. + +17; (* This + is + a multiline comment *) 23.4; diff --git a/Task/Concurrent-computing/Rust/concurrent-computing.rust b/Task/Concurrent-computing/Rust/concurrent-computing.rust new file mode 100644 index 0000000000..2b357f2a7f --- /dev/null +++ b/Task/Concurrent-computing/Rust/concurrent-computing.rust @@ -0,0 +1,15 @@ +use std::io::timer::sleep; +use std::rand::{rng, Rng}; + +fn main() { + let mut random = rng(); + for word in "Enjoy Rosetta Code".words() { + let local_word = word.to_owned(); + let snooze_time = random.gen_range::(0, 1000); + + spawn(proc() { + sleep(snooze_time); + println!("{}", local_word); + }); + } +} diff --git a/Task/Conditional-structures/Maple/conditional-structures-1.maple b/Task/Conditional-structures/Maple/conditional-structures-1.maple new file mode 100644 index 0000000000..e54b8022aa --- /dev/null +++ b/Task/Conditional-structures/Maple/conditional-structures-1.maple @@ -0,0 +1,5 @@ +if x > 0 then + res := x; +else + res := -x; +end if; diff --git a/Task/Conditional-structures/Maple/conditional-structures-2.maple b/Task/Conditional-structures/Maple/conditional-structures-2.maple new file mode 100644 index 0000000000..0d01a00e2f --- /dev/null +++ b/Task/Conditional-structures/Maple/conditional-structures-2.maple @@ -0,0 +1,7 @@ +if x = 0 then + res := y; +elif y = 0 then + res := x; +else + res := sqrt(x^2+y^2); +end if; diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/PARI-GP/continued-fraction-arithmetic-construct-from-rational-number.pari b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/PARI-GP/continued-fraction-arithmetic-construct-from-rational-number.pari new file mode 100644 index 0000000000..38f7402bdd --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/PARI-GP/continued-fraction-arithmetic-construct-from-rational-number.pari @@ -0,0 +1 @@ +apply(contfrac,[1/2,3,23/8,13/11,22/7,-151/77]) diff --git a/Task/Continued-fraction/D/continued-fraction.d b/Task/Continued-fraction/D/continued-fraction.d index 447a0adad3..e766353954 100644 --- a/Task/Continued-fraction/D/continued-fraction.d +++ b/Task/Continued-fraction/D/continued-fraction.d @@ -5,7 +5,7 @@ FP calc(FP, F)(in F fun, in int n) pure nothrow if (isCallable!F) { foreach_reverse (immutable ni; 1 .. n + 1) { immutable p = fun(ni); - temp = p[1] / (cast(FP)p[0] + temp); + temp = p[1] / (FP(p[0]) + temp); } return fun(0)[0] + temp; } diff --git a/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 b/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 index a50be7943b..7051b62d31 100644 --- a/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 +++ b/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 @@ -1,8 +1,9 @@ sub infix:<⚬>(&f, &g) { -> $x { &f(&g($x)) } } -sub continued-fraction(@a, @b) { +sub continued-fraction(@a, @b, $x = Inf) { + map { .($x) }, [\⚬] map { @a[$_] + @b[$_] / * }, 0 .. * } -printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10](Inf); -printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10](Inf); -printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ((1, 3, 5 ... *) X** 2))[1000](Inf); +printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10]; +printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10]; +printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ((1, 3, 5 ... *) X** 2))[100]; diff --git a/Task/Conways-Game-of-Life/00DESCRIPTION b/Task/Conways-Game-of-Life/00DESCRIPTION index 57aff5c64b..ac65efa898 100644 --- a/Task/Conways-Game-of-Life/00DESCRIPTION +++ b/Task/Conways-Game-of-Life/00DESCRIPTION @@ -15,3 +15,7 @@ Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Although you should test your implementation on more complex examples such as the [[wp:Conway%27s_Game_of_Life#Examples_of_patterns|glider]] in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid. + +;References: +* Its creator John Conway, explains [http://www.youtube.com/watch?v=E8kUJL04ELA the game of life]. Video from numberphile on youtube. +* John Conway [http://www.youtube.com/watch?v=R9Plq-D1gEk Inventing Game of Life]- Numberphile video. diff --git a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 b/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 new file mode 100644 index 0000000000..1f3b5602fe --- /dev/null +++ b/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 @@ -0,0 +1,57 @@ +class Automaton { + subset World of Str where { + .lines.pick.chars == all(.lines>>.chars) + and m/^^<[.#\n]>+$$/ + } + has Int ($.width, $.height); + has @.a; + + multi method new (World $s) { + self.new: + :width(.pick.chars), :height(.elems), + :a( .map: { [ .comb ] } ) + given $s.lines; + } + + method gist { join "\n", map { [~] @$_ }, @!a } + + method C (Int $r, Int $c --> Bool) { + @!a[$r % $!height][$c % $!width] eq '#'; + } + method N (Int $r, Int $c --> Int) { + +grep ?*, map { self.C: |@$_ }, + [ $r - 1, $c - 1], [ $r - 1, $c ], [ $r - 1, $c + 1], + [ $r , $c - 1], [ $r , $c + 1], + [ $r + 1, $c - 1], [ $r + 1, $c ], [ $r + 1, $c + 1]; + } + + method succ { + self.new: :$!width, :$!height, + :a( + gather for ^$.height -> $r { + take [ + gather for ^$.width -> $c { + take + (self.C($r, $c) == 1 && self.N($r, $c) == 2|3 ) + || (self.C($r, $c) == 0 && self.N($r, $c) == 3) + ?? '#' !! '.' + } + ] + } + ) + } +} + +my Automaton $glider .= new: '............ +............ +............ +.......###.. +.......#.... +........#... +............'; + + +for ^10 { + say $glider++; + say '--'; +} diff --git a/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 b/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 new file mode 100644 index 0000000000..0ffa9a58c8 --- /dev/null +++ b/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 @@ -0,0 +1,21 @@ +constant @primes = grep &is-prime, 2, (3, 5, 7 ... *); + +multi factors(1) { 1 } +multi factors(Int $remainder is copy) { + gather for @primes -> $factor { + + # if remainder < factor², we're done + if $factor * $factor > $remainder { + take $remainder if $remainder > 1; + last; + } + + # How many times can we divide by this prime? + while $remainder %% $factor { + take $factor; + last if ($remainder div= $factor) === 1; + } + } +} + +say "$_: ", factors($_).join(" × ") for 1..*; diff --git a/Task/Count-in-factors/Perl-6/count-in-factors-2.pl6 b/Task/Count-in-factors/Perl-6/count-in-factors-2.pl6 new file mode 100644 index 0000000000..f68a75fc72 --- /dev/null +++ b/Task/Count-in-factors/Perl-6/count-in-factors-2.pl6 @@ -0,0 +1,13 @@ +sub factor($n is copy) { + $n == 1 ?? 1 !! + gather { + $n /= take 2 while $n %% 2; + $n /= take 3 while $n %% 3; + loop (my $p = 5; $p*$p <= $n; $p+=2) { + $n /= take $p while $n %% $p; + } + take $n unless $n == 1; + } +} + +say "$_ == ", join " \x00d7 ", factor $_ for 1 .. 20; diff --git a/Task/Count-in-factors/Perl-6/count-in-factors.pl6 b/Task/Count-in-factors/Perl-6/count-in-factors.pl6 deleted file mode 100644 index bb5f77333a..0000000000 --- a/Task/Count-in-factors/Perl-6/count-in-factors.pl6 +++ /dev/null @@ -1,33 +0,0 @@ -# Define a lazy list of primes. -# Uses the ... sequence operator with a lambda that calculates -# the next available prime by using some of the existing list -# as test divisors, so we rarely divide by anything that isn't -# known to be a prime already. This is quite fast. -my @primes := 2, 3, 5, -> $p { ($p+2, $p+4 ... &prime)[*-1] } ... *; -my @isprime = False,False; # 0 and 1 are not prime by definition -sub prime($i) { @isprime[$i] //= $i %% none @primes ...^ * > sqrt $i } - -# Finds the factors of the given argument. -multi factors(1) { 1 } -multi factors(Int $remainder is copy) { - gather for @primes -> $factor { - - # if remainder < factor², we're done - if $factor * $factor > $remainder { - take $remainder if $remainder > 1; - last; - } - - # How many times can we divide by this prime? - while $remainder %% $factor { - take $factor; - last if ($remainder div= $factor) === 1; - } - } -} - -# An infinite loop, from 1 incrementing upward. -# calls factor() with each of 1, 2, 3, etc., receives an -# array containing that number's factors, and then -# formats and displays them. -say "$_: ", factors($_).join(" × ") for 1..*; diff --git a/Task/Count-in-octal/COBOL/count-in-octal.cobol b/Task/Count-in-octal/COBOL/count-in-octal.cobol new file mode 100644 index 0000000000..b024da8205 --- /dev/null +++ b/Task/Count-in-octal/COBOL/count-in-octal.cobol @@ -0,0 +1,44 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. count-in-octal. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION dec-to-oct + . +DATA DIVISION. +WORKING-STORAGE SECTION. +01 i PIC 9(18). + +PROCEDURE DIVISION. + PERFORM VARYING i FROM 1 BY 1 UNTIL i = 0 + DISPLAY FUNCTION dec-to-oct(i) + END-PERFORM + . +END PROGRAM count-in-octal. + + +IDENTIFICATION DIVISION. +FUNCTION-ID. dec-to-oct. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 rem PIC 9. + +01 dec PIC 9(18). + +LINKAGE SECTION. +01 dec-arg PIC 9(18). + +01 oct PIC 9(18). + +PROCEDURE DIVISION USING dec-arg RETURNING oct. + MOVE dec-arg TO dec *> Copy is made to avoid modifying reference arg. + PERFORM WITH TEST AFTER UNTIL dec = 0 + MOVE FUNCTION REM(dec, 8) TO rem + STRING rem, oct DELIMITED BY SPACES INTO oct + DIVIDE 8 INTO dec + END-PERFORM + . +END FUNCTION dec-to-oct. diff --git a/Task/Count-in-octal/Standard-ML/count-in-octal.ml b/Task/Count-in-octal/Standard-ML/count-in-octal.ml new file mode 100644 index 0000000000..0ff090af8a --- /dev/null +++ b/Task/Count-in-octal/Standard-ML/count-in-octal.ml @@ -0,0 +1,5 @@ +local + fun count n = (print (Int.fmt StringCvt.OCT n ^ "\n"); count (n+1)) +in + val _ = count 0 +end diff --git a/Task/Count-occurrences-of-a-substring/Deja-Vu/count-occurrences-of-a-substring.djv b/Task/Count-occurrences-of-a-substring/Deja-Vu/count-occurrences-of-a-substring.djv new file mode 100644 index 0000000000..b28e8e6334 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Deja-Vu/count-occurrences-of-a-substring.djv @@ -0,0 +1,2 @@ +!. count "the three truths" "th" +!. count "ababababab" "abab" diff --git a/Task/Count-occurrences-of-a-substring/Maple/count-occurrences-of-a-substring.maple b/Task/Count-occurrences-of-a-substring/Maple/count-occurrences-of-a-substring.maple new file mode 100644 index 0000000000..c8243177c7 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Maple/count-occurrences-of-a-substring.maple @@ -0,0 +1,9 @@ +f:=proc(s::string,c::string,count::nonnegint) local n; + n:=StringTools:-Search(c,s); + if n>0 then 1+procname(s[n+length(c)..],c,count); + else 0; end if; +end proc: + +f("the three truths","th",0); + +f("ababababab","abab",0); diff --git a/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-1.m b/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-1.m index 125a5593c0..50c74cb4c1 100644 --- a/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-1.m +++ b/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-1.m @@ -9,12 +9,12 @@ @end int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]); - NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]); - NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]); + NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]); + NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]); + NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]); - [pool release]; + } return 0; } diff --git a/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-2.m b/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-2.m index cdef2bd73a..599cff9f56 100644 --- a/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-2.m +++ b/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-2.m @@ -9,12 +9,12 @@ @end int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]); - NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]); - NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]); + NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]); + NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]); + NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]); - [pool release]; + } return 0; } diff --git a/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-3.m b/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-3.m index 731a56ed12..2c9c076577 100644 --- a/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-3.m +++ b/Task/Count-occurrences-of-a-substring/Objective-C/count-occurrences-of-a-substring-3.m @@ -15,12 +15,12 @@ @end int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]); - NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]); - NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]); + NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]); + NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]); + NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]); - [pool release]; + } return 0; } diff --git a/Task/Count-the-coins/D/count-the-coins-3.d b/Task/Count-the-coins/D/count-the-coins-3.d index e167a2d4e9..77ce234d9c 100644 --- a/Task/Count-the-coins/D/count-the-coins-3.d +++ b/Task/Count-the-coins/D/count-the-coins-3.d @@ -1,7 +1,5 @@ import std.stdio, std.bigint, std.algorithm, std.conv, std.functional; -alias sum = curry!(reduce!q{ a + b }, 0); - struct Ucent { /// Simplified 128-bit integer (like ucent). ulong hi, lo; static immutable one = Ucent(0, 1); diff --git a/Task/Create-a-file/Mercury/create-a-file.mercury b/Task/Create-a-file/Mercury/create-a-file.mercury new file mode 100644 index 0000000000..761687c56b --- /dev/null +++ b/Task/Create-a-file/Mercury/create-a-file.mercury @@ -0,0 +1,46 @@ +:- module create_file. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module dir. + +main(!IO) :- + create_file("output.txt", !IO), + create_file("/output.txt", !IO), + create_dir("docs", !IO), + create_dir("/docs", !IO). + +:- pred create_file(string::in, io::di, io::uo) is det. + +create_file(FileName, !IO) :- + io.open_output(FileName, Result, !IO), + ( + Result = ok(File), + io.close_output(File, !IO) + ; + Result = error(Error), + print_io_error(Error, !IO) + ). + +:- pred create_dir(string::in, io::di, io::uo) is det. + +create_dir(DirName, !IO) :- + dir.make_single_directory(DirName, Result, !IO), + ( + Result = ok + ; + Result = error(Error), + print_io_error(Error, !IO) + ). + +:- pred print_io_error(io.error::in, io::di, io::uo) is det. + +print_io_error(Error, !IO) :- + io.stderr_stream(Stderr, !IO), + io.write_string(Stderr, io.error_message(Error), !IO), + io.nl(Stderr, !IO), + io.set_exit_status(1, !IO). diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Frink/create-a-two-dimensional-array-at-runtime.frink b/Task/Create-a-two-dimensional-array-at-runtime/Frink/create-a-two-dimensional-array-at-runtime.frink new file mode 100644 index 0000000000..5ec5597509 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Frink/create-a-two-dimensional-array-at-runtime.frink @@ -0,0 +1,4 @@ +[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]] +a = new array[dims, 0] // Create and initialize to 0 +a@(rows-1)@(cols-1) = 10 +println[a@(rows-1)@(cols-1)] diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Objective-C/create-a-two-dimensional-array-at-runtime.m b/Task/Create-a-two-dimensional-array-at-runtime/Objective-C/create-a-two-dimensional-array-at-runtime.m index 022b18c387..5b9cc46fae 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Objective-C/create-a-two-dimensional-array-at-runtime.m +++ b/Task/Create-a-two-dimensional-array-at-runtime/Objective-C/create-a-two-dimensional-array-at-runtime.m @@ -2,27 +2,25 @@ int main() { - int num1, num2, i, j; - NSMutableArray *arr; + @autoreleasepool { + int num1, num2; + scanf("%d %d", &num1, &num2); - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - scanf("%d %d", &num1, &num2); + NSLog(@"%d %d", num1, num2); - NSLog(@"%d %d", num1, num2); + NSMutableArray *arr = [NSMutableArray arrayWithCapacity: (num1*num2)]; + // initialize it with 0s + for(int i=0; i < (num1*num2); i++) [arr addObject: @0]; - arr = [NSMutableArray arrayWithCapacity: (num1*num2)]; - // initialize it with 0s - for(i=0; i < (num1*num2); i++) [arr addObject: [NSNumber numberWithInt: 0]]; - - // replace 0s with something more interesting - for(i=0; i < num1; i++) { - for(j=0; j < num2; j++) { - [arr replaceObjectAtIndex: (i*num2+j) withObject: [NSNumber numberWithInt: (i*j)]]; + // replace 0s with something more interesting + for(int i=0; i < num1; i++) { + for(int j=0; j < num2; j++) { + arr[i*num2+j] = @(i*j); + } } - } - // access a value: i*num2+j, where i,j are the indexes for the bidimensional array - NSLog(@"%@", [arr objectAtIndex: (1*num2+3)]); - [pool release]; + // access a value: i*num2+j, where i,j are the indexes for the bidimensional array + NSLog(@"%@", arr[1*num2+3]); + } return 0; } diff --git a/Task/Create-an-HTML-table/AWK/create-an-html-table-1.awk b/Task/Create-an-HTML-table/AWK/create-an-html-table-1.awk new file mode 100644 index 0000000000..6cb7bdde87 --- /dev/null +++ b/Task/Create-an-HTML-table/AWK/create-an-html-table-1.awk @@ -0,0 +1,9 @@ +#!/usr/bin/awk -f +BEGIN { + print "\n " + printf " \n \n \n" + for (i=1; i<=10; i++) { + printf " \n",i, 10*i, 100*i, 1000*i-1 + } + print " \n
XYZ
%2i%5i%5i%5i
\n" +} diff --git a/Task/Create-an-HTML-table/AWK/create-an-html-table-2.awk b/Task/Create-an-HTML-table/AWK/create-an-html-table-2.awk new file mode 100644 index 0000000000..6c70b9b6f7 --- /dev/null +++ b/Task/Create-an-HTML-table/AWK/create-an-html-table-2.awk @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + +
XYZ
1 10 100 999
2 20 200 1999
3 30 300 2999
4 40 400 3999
5 50 500 4999
6 60 600 5999
7 70 700 6999
8 80 800 7999
9 90 900 8999
10 100 1000 9999
diff --git a/Task/Create-an-HTML-table/AWK/create-an-html-table.awk b/Task/Create-an-HTML-table/AWK/create-an-html-table.awk deleted file mode 100644 index 5bcd4dec3a..0000000000 --- a/Task/Create-an-HTML-table/AWK/create-an-html-table.awk +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/awk -f -BEGIN { - print "\n "; - printf " \n \n \n"; -}; - -{ - printf " \n",NR,$1,$2,$3; -}; - -END { - print " \n
XYZ
%2i%5i%5i%5i
\n"; -}; diff --git a/Task/Create-an-HTML-table/C-sharp/create-an-html-table.cs b/Task/Create-an-HTML-table/C-sharp/create-an-html-table-1.cs similarity index 100% rename from Task/Create-an-HTML-table/C-sharp/create-an-html-table.cs rename to Task/Create-an-HTML-table/C-sharp/create-an-html-table-1.cs diff --git a/Task/Create-an-HTML-table/C-sharp/create-an-html-table-2.cs b/Task/Create-an-HTML-table/C-sharp/create-an-html-table-2.cs new file mode 100644 index 0000000000..ac8bcc9bd5 --- /dev/null +++ b/Task/Create-an-HTML-table/C-sharp/create-an-html-table-2.cs @@ -0,0 +1,58 @@ +using System; +using System.Text; +using System.Xml; + +namespace N +{ + public class T + { + public static void Main() + { + var headerNames = new [] { "", "X", "Y", "Z" }; + + var headerColumns = headerNames.Select(name => + new XElement + ( + "th", + name, + new XAttribute("text-align", "center") + ) + ); + + var rows = Enumerable.Range(0, 4) + .Select + ( + rowIndex => + new XElement + ( + "tr", + new XElement("td", rowIndex), + Enumerable.Range(0, 4) + .Select + ( + colIndex => + new XElement + ( + "td", + colIndex, + new XAttribute("text-align", "center") + ) + ) + ) + ); + + var xml = new XElement + ( + "table", + new XElement + ( + "thead", + new XElement("tr", headerColumns), + new XElement("tbody", rows) + ) + ); + + Console.WriteLine(xml.ToString()); + } + } +} diff --git a/Task/DNS-query/AutoHotkey/dns-query.ahk b/Task/DNS-query/AutoHotkey/dns-query.ahk new file mode 100644 index 0000000000..c338007c86 --- /dev/null +++ b/Task/DNS-query/AutoHotkey/dns-query.ahk @@ -0,0 +1,6 @@ +Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" +Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide +FileRead, Contents, %LogFile% +FileDelete, %LogFile% +RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) +MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])") diff --git a/Task/DNS-query/Groovy/dns-query-3.groovy b/Task/DNS-query/Groovy/dns-query-3.groovy index 78757db877..0915009f2c 100644 --- a/Task/DNS-query/Groovy/dns-query-3.groovy +++ b/Task/DNS-query/Groovy/dns-query-3.groovy @@ -1,21 +1,4 @@ -import java.net.InetAddress; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.UnknownHostException; - -class DnsQuery { - public static void main(String[] args) { - try { - InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); - for(int i=0; i < ipAddr.length ; i++) { - if (ipAddr[i] instanceof Inet4Address) { - System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); - } else if (ipAddr[i] instanceof Inet6Address) { - System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); - } - } - } catch (UnknownHostException uhe) { - System.err.println("unknown host"); - } - } -} +procedure main(A) + host := gethost( A[1] | "www.kame.net") | stop("can't translate") + write(host.name, ": ", host.addresses) +end diff --git a/Task/DNS-query/Groovy/dns-query-4.groovy b/Task/DNS-query/Groovy/dns-query-4.groovy new file mode 100644 index 0000000000..78757db877 --- /dev/null +++ b/Task/DNS-query/Groovy/dns-query-4.groovy @@ -0,0 +1,21 @@ +import java.net.InetAddress; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.UnknownHostException; + +class DnsQuery { + public static void main(String[] args) { + try { + InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); + for(int i=0; i < ipAddr.length ; i++) { + if (ipAddr[i] instanceof Inet4Address) { + System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); + } else if (ipAddr[i] instanceof Inet6Address) { + System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); + } + } + } catch (UnknownHostException uhe) { + System.err.println("unknown host"); + } + } +} diff --git a/Task/Date-format/Objective-C/date-format-2.m b/Task/Date-format/Objective-C/date-format-2.m index b135bb74df..536e6f0dc6 100644 --- a/Task/Date-format/Objective-C/date-format-2.m +++ b/Task/Date-format/Objective-C/date-format-2.m @@ -4,4 +4,3 @@ NSDateFormatter *dateFormatter = [[NSDateFormat alloc] init]; NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]); [dateFormatter setDateFormat:@"EEEE, MMMM d, yyyy"]; NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]); -[dateFormatter release]; diff --git a/Task/Day-of-the-week/COBOL/day-of-the-week.cobol b/Task/Day-of-the-week/COBOL/day-of-the-week.cobol new file mode 100644 index 0000000000..b02dc59752 --- /dev/null +++ b/Task/Day-of-the-week/COBOL/day-of-the-week.cobol @@ -0,0 +1,68 @@ + identification division. + program-id. dowtest. + data division. + working-storage section. + 01 ws-inp-date pic x(08). + 01 filler redefines ws-inp-date. + 03 ws-inp-year pic 9(04). + 01 ws-dow pic 9(05). + procedure division. + move '00001225' to ws-inp-date + perform test before + varying ws-inp-year from 2008 by +1 + until ws-inp-year > 2121 + call "todow" using + by reference ws-inp-date + by reference ws-dow + if ws-dow = 1 then + display 'year=' ws-inp-year + end-if + end-perform + stop run. + + end program dowtest. + + identification division. + program-id. todow. + environment division. + input-output section. + file-control. + data division. + file section. + working-storage section. + 01 tally pic 9(05). + 01 wms-work-area. + 03 wms-year pic 9(04). + 03 wms-month pic 9(02). + 03 wms-csys pic 9(01) value 1. + 03 wms-sum pic 9(05). + linkage section. + 01 lkip-date. + 03 lkip-date-year pic 9(04). + 03 lkip-date-month pic 9(02). + 03 lkip-date-day pic 9(02). + 01 lkop-dow pic 9(05). + 88 lkop-sunday value 1. + procedure division using + by reference lkip-date + by reference lkop-dow + . + + if lkip-date-month < 3 + compute wms-month = lkip-date-month + 12 + compute wms-year = lkip-date-year - 1 + else + compute wms-month = lkip-date-month + compute wms-year = lkip-date-year + end-if + + compute wms-sum = + ( lkip-date-day + 2 * wms-month + wms-year + + function integer (6 * (wms-month + 1) / 10) + + function integer ( wms-year / 4 ) + - function integer ( wms-year / 100 ) + + function integer ( wms-year / 400 ) + + wms-csys ) + compute lkop-dow = function mod (wms-sum, 7) + 1 + . + end program todow. diff --git a/Task/Day-of-the-week/Objective-C/day-of-the-week.m b/Task/Day-of-the-week/Objective-C/day-of-the-week.m index 0d9ed52f52..5e146d0753 100644 --- a/Task/Day-of-the-week/Objective-C/day-of-the-week.m +++ b/Task/Day-of-the-week/Objective-C/day-of-the-week.m @@ -2,24 +2,21 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSUInteger i; - - for(i=2008; i<2121; i++) - { - NSCalendarDate *d = [[NSCalendarDate alloc] - initWithYear: i - month: 12 - day: 25 - hour: 0 minute: 0 second:0 - timeZone: [NSTimeZone timeZoneWithAbbreviation:@"CET"] ]; - if ( [d dayOfWeek] == 0 ) + @autoreleasepool { + for(NSUInteger i=2008; i<2121; i++) { - printf("25 Dec %u is Sunday\n", i); + NSCalendarDate *d = [[NSCalendarDate alloc] + initWithYear: i + month: 12 + day: 25 + hour: 0 minute: 0 second:0 + timeZone: [NSTimeZone timeZoneWithAbbreviation:@"CET"] ]; + if ( [d dayOfWeek] == 0 ) + { + printf("25 Dec %u is Sunday\n", i); + } } - [d release]; - } - [pool release]; + } return 0; } diff --git a/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk b/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk new file mode 100644 index 0000000000..2759a7a4a9 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk @@ -0,0 +1,24 @@ +FreeCell(num){ + cards := "A23456789TJQK", suits := "♣♦♥♠", card := [], Counter := 0 + loop, parse, cards + { + ThisCard := A_LoopField + loop, parse, suits + Card[Counter++] := ThisCard . A_LoopField + } + loop, 52 + { + a := MS(num) + num:=a[1] + MyCardNo := mod(a[2],53-A_Index) + MyCard := Card[MyCardNo] + Card[MyCardNo] := Card[52-A_Index] + Card.Remove(52-A_Index) + Res .= MyCard (Mod(A_Index,8)?" ":"`n") + } + return Res +} +MS(Seed) { + Seed := Mod(214013 * Seed + 2531011, 2147483648) + return, [Seed, Seed // 65536] +} diff --git a/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-2.ahk b/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-2.ahk new file mode 100644 index 0000000000..7c851c1200 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-2.ahk @@ -0,0 +1,9 @@ +Gui, font, s12, Courier +Gui, add, edit, w320 r17 -VScroll, % "Game# 1`n" FreeCell(1) "`n`nGame#617`n" FreeCell(617) +Gui, show +return + +GuiClose: +GuiEscape: +ExitApp +return diff --git a/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java b/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java new file mode 100644 index 0000000000..f9e7f1100b --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java @@ -0,0 +1,62 @@ +import java.util.Arrays; + +public class Shuffler { + + private int seed; + + private String[] deck = { + "AC", "AD", "AH", "AS", + "2C", "2D", "2H", "AS", + "3C", "3D", "3H", "3S", + "4C", "4D", "4H", "4S", + "5C", "5D", "5H", "5S", + "6C", "6D", "6H", "6S", + "7C", "7D", "7H", "7S", + "8C", "8D", "8H", "8S", + "9C", "9D", "9H", "9S", + "TC", "TD", "TH", "TS", + "JC", "JD", "JH", "JS", + "QC", "QD", "QH", "QS", + "KC", "KD", "KH", "KS", + }; + + private int random() { + seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; + return seed >> 16; + } + + //shuffled cards go to the end + private String[] getShuffledDeck() { + String[] deck = Arrays.copyOf(this.deck, this.deck.length); + for(int i = deck.length - 1; i > 0; i--) { + int r = random() % (i + 1); + String card = deck[r]; + deck[r] = deck[i]; + deck[i] = card; + } + return deck; + } + + //deal from end first + public void dealGame(int seed) { + this.seed = seed; + String[] shuffledDeck = getShuffledDeck(); + for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { + System.out.print(shuffledDeck[i]); + if(count % 8 == 0) { + System.out.println(); + } else { + System.out.print(" "); + } + } + System.out.println(); + } + + public static void main(String[] args) { + Shuffler s = new Shuffler(); + s.dealGame(1); + System.out.println(); + s.dealGame(617); + } + +} diff --git a/Task/Deal-cards-for-FreeCell/Objective-C/deal-cards-for-freecell.m b/Task/Deal-cards-for-FreeCell/Objective-C/deal-cards-for-freecell.m new file mode 100644 index 0000000000..06073a0327 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Objective-C/deal-cards-for-freecell.m @@ -0,0 +1,89 @@ +#define RMAX32 ((1U << 31) - 1) + +//-------------------------------------------------------------------- + +@interface Rand : NSObject +-(instancetype) initWithSeed: (int)seed; +-(int) next; +@property (nonatomic) long seed; +@end + +@implementation Rand +-(instancetype) initWithSeed: (int)seed { + if ((self = [super init])) { + self.seed = seed; + } + return self; +} +-(int) next { + return (int) ((_seed = (_seed * 214013 + 2531011) & RMAX32) >> 16); +} +@end + +//-------------------------------------------------------------------- + +@interface Card : NSObject +-(instancetype) initWithSequence: (int)n; +-(instancetype) initWithValue: (int)v suit: (int)s; +@property (nonatomic) int value; +@property (nonatomic) int suit; +@end + +@implementation Card +-(instancetype) initWithSequence: (int)n { + return [self initWithValue:n/4 suit:n%4]; +} +-(instancetype) initWithValue: (int)v suit: (int)s { + if ((self = [super init])) { + _value = v; _suit = s; + } + return self; +} +-(NSString *) description { + static NSString * const kSuits = @"♣♦♥♠"; + static NSString * const kValues = @"A23456789TJQK"; + return [NSString stringWithFormat:@"%C%C", + [kValues characterAtIndex:_value], + [kSuits characterAtIndex:_suit]]; +} +@end + +//-------------------------------------------------------------------- + +@interface Deck : NSObject +-(instancetype) initWithSeed: (int)seed; +@property (nonatomic, strong) NSMutableArray *cards; +@end + +@implementation Deck +-(instancetype) initWithSeed: (int)seed { + if ((self = [super init])) { + Rand *r = [[Rand alloc] initWithSeed:seed]; + _cards = [NSMutableArray array]; + for (int i = 0; i < 52; i++) + [_cards addObject:[[Card alloc] initWithSequence:51 - i]]; + for (int i = 0; i < 51; i++) + [_cards exchangeObjectAtIndex:i withObjectAtIndex:51 - [r next] % (52 - i)]; + } + return self; +} +-(NSString *) description { + NSMutableString *s = [NSMutableString string]; + for (int i = 0; i < [_cards count]; i++) { + [s appendString:[_cards[i] description]]; + [s appendString:i%8==7 ? @"\n" : @" "]; + } + return s; +} +@end + +//-------------------------------------------------------------------- + +int main(int argc, const char * argv[]) +{ + @autoreleasepool { + NSLog(@"Deck 1\n%@\n", [[Deck alloc] initWithSeed:1]); + NSLog(@"Deck 617\n%@\n", [[Deck alloc] initWithSeed:617]); + } + return 0; +} diff --git a/Task/Death-Star/AutoHotkey/death-star.ahk b/Task/Death-Star/AutoHotkey/death-star.ahk new file mode 100644 index 0000000000..742901fd77 --- /dev/null +++ b/Task/Death-Star/AutoHotkey/death-star.ahk @@ -0,0 +1,80 @@ +#NoEnv +SetBatchLines, -1 +#SingleInstance, Force + +; Uncomment if Gdip.ahk is not in your standard library +#Include, Gdip.ahk + +; Settings +X := 200, Y := 200, Width := 200, Height := 200 ; Location and size of sphere +rotation := 60 ; degrees +ARGB := 0xFFFF0000 ; Color=Solid Red + +If !pToken := Gdip_Startup() ; Start gdi+ +{ + MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system + ExitApp +} +OnExit, Exit + +Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs ; Create GUI +Gui, Show, NA ; Show GUI +hwnd1 := WinExist() ; Get a handle to this window we have created in order to update it later +hbm := CreateDIBSection(A_ScreenWidth, A_ScreenHeight) ; Create a gdi bitmap drawing area +hdc := CreateCompatibleDC() ; Get a device context compatible with the screen +obm := SelectObject(hdc, hbm) ; Select the bitmap into the device context +pGraphics := Gdip_GraphicsFromHDC(hdc) ; Get a pointer to the graphics of the bitmap, for use with drawing functions +Gdip_SetSmoothingMode(pGraphics, 4) ; Set the smoothing mode to antialias = 4 to make shapes appear smother + +Gdip_TranslateWorldTransform(pGraphics, X, Y) +Gdip_RotateWorldTransform(pGraphics, rotation) + +; Base ellipse +pBrush := Gdip_CreateLineBrushFromRect(0, 0, Width, Height, ARGB, 0xFF000000) +Gdip_FillEllipse(pGraphics, pBrush, 0, 0, Width, Height) + +; First highlight ellipse +pBrush := Gdip_CreateLineBrushFromRect(Width*0.1, Height*0.01, Width*0.8, Height*0.6, 0x33FFFFFF, 0x00FFFFFF) +Gdip_FillEllipse(pGraphics, pBrush, Width*0.1, Height*0.01, Width*0.8, Height*0.6) + +; Second highlight ellipse +pBrush := Gdip_CreateLineBrushFromRect(Width*0.3, Height*0.02, Width*0.3, Height*0.2, 0xBBFFFFFF, 0x00FFFFFF) +Gdip_FillEllipse(pGraphics, pBrush, Width*0.3, Height*0.02, Width*0.3, Height*0.2) + + +; Reset variables for smaller subtracted sphere +X-=150 +Y-=10 +Width*=0.5 +Height*=0.4 +rotation-=180 + +Gdip_TranslateWorldTransform(pGraphics, X, Y) +Gdip_RotateWorldTransform(pGraphics, rotation) + +; Base ellipse +pBrush := Gdip_CreateLineBrushFromRect(0, 0, Width, Height, ARGB, 0xFF000000) +Gdip_FillEllipse(pGraphics, pBrush, 0, 0, Width, Height) + +; First highlight ellipse +pBrush := Gdip_CreateLineBrushFromRect(Width*0.1, Height*0.01, Width*0.8, Height*0.6, 0x33FFFFFF, 0x00FFFFFF) +Gdip_FillEllipse(pGraphics, pBrush, Width*0.1, Height*0.01, Width*0.8, Height*0.6) + +; Second highlight ellipse +pBrush := Gdip_CreateLineBrushFromRect(Width*0.3, Height*0.02, Width*0.3, Height*0.2, 0xBBFFFFFF, 0x00FFFFFF) +Gdip_FillEllipse(pGraphics, pBrush, Width*0.3, Height*0.02, Width*0.3, Height*0.2) + + +UpdateLayeredWindow(hwnd1, hdc, 0, 0, A_ScreenWidth, A_ScreenHeight) +SelectObject(hdc, obm) ; Select the object back into the hdc +Gdip_DeletePath(Path) +Gdip_DeleteBrush(pBrush) +DeleteObject(hbm) ; Now the bitmap may be deleted +DeleteDC(hdc) ; Also the device context related to the bitmap may be deleted +Gdip_DeleteGraphics(G) ; The graphics may now be deleted +Return + +Exit: +; gdi+ may now be shutdown on exiting the program +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Deepcopy/AutoHotkey/deepcopy.ahk b/Task/Deepcopy/AutoHotkey/deepcopy.ahk new file mode 100644 index 0000000000..d54938768c --- /dev/null +++ b/Task/Deepcopy/AutoHotkey/deepcopy.ahk @@ -0,0 +1,13 @@ +DeepCopy(Array, Objs=0) +{ + If !Objs + Objs := Object() + Obj := Array.Clone() ; produces a shallow copy in that any sub-objects are not cloned + Objs[&Array] := Obj ; Save this new array - & returns the address of Array in memory + For Key, Val in Obj + If (IsObject(Val)) ; If it is a subarray + Obj[Key] := Objs[&Val] ; If we already know of a reference to this array + ? Objs[&Val] ; Then point it to the new array (to prevent infinite recursion on self-references + : DeepCopy(Val,Objs) ; Otherwise, clone this sub-array + Return Obj +} diff --git a/Task/Detect-division-by-zero/COBOL/detect-division-by-zero.cobol b/Task/Detect-division-by-zero/COBOL/detect-division-by-zero.cobol new file mode 100644 index 0000000000..faa7ed3c1c --- /dev/null +++ b/Task/Detect-division-by-zero/COBOL/detect-division-by-zero.cobol @@ -0,0 +1,4 @@ +DIVIDE foo BY bar GIVING foobar + ON SIZE ERROR + DISPLAY "Division by zero detected!" +END-DIVIDE diff --git a/Task/Detect-division-by-zero/D/detect-division-by-zero.d b/Task/Detect-division-by-zero/D/detect-division-by-zero.d index 6695289148..b3ff3e961e 100644 --- a/Task/Detect-division-by-zero/D/detect-division-by-zero.d +++ b/Task/Detect-division-by-zero/D/detect-division-by-zero.d @@ -28,14 +28,13 @@ if (isIntegral!T || isFloatingPoint!T) { } } - return format("%5s %s", format("%1.1g", cast(real)result), msg); + return format("%5s %s", format("%1.1g", real(result)), msg); } void main() { writeln("Division with check:"); writefln("int 1/ 0: %s", divCheck(1, 0)); - writefln("ubyte 1/ 0: %s", - divCheck(cast(ubyte)1, cast(ubyte)0)); + writefln("ubyte 1/ 0: %s", divCheck(ubyte(1), ubyte(0))); writefln("real 1/ 0: %s", divCheck(1.0L, 0.0L)); writefln("real -1/ 0: %s", divCheck(-1.0L, 0.0L)); writefln("real 0/ 0: %s", divCheck(0.0L, 0.0L)); diff --git a/Task/Detect-division-by-zero/Maple/detect-division-by-zero-1.maple b/Task/Detect-division-by-zero/Maple/detect-division-by-zero-1.maple new file mode 100644 index 0000000000..7d92807d13 --- /dev/null +++ b/Task/Detect-division-by-zero/Maple/detect-division-by-zero-1.maple @@ -0,0 +1 @@ +1/0; # Here is the default behavior. diff --git a/Task/Detect-division-by-zero/Maple/detect-division-by-zero-2.maple b/Task/Detect-division-by-zero/Maple/detect-division-by-zero-2.maple new file mode 100644 index 0000000000..b4576d15e2 --- /dev/null +++ b/Task/Detect-division-by-zero/Maple/detect-division-by-zero-2.maple @@ -0,0 +1,6 @@ +NumericEventHandler( ':-division_by_zero' + = proc() infinity; end proc ): + +1/0; + +NumericStatus(':-division_by_zero'); # We may check the status flag diff --git a/Task/Detect-division-by-zero/Maple/detect-division-by-zero-3.maple b/Task/Detect-division-by-zero/Maple/detect-division-by-zero-3.maple new file mode 100644 index 0000000000..5d68033540 --- /dev/null +++ b/Task/Detect-division-by-zero/Maple/detect-division-by-zero-3.maple @@ -0,0 +1,10 @@ +NumericEventHandler( ':-division_by_zero' + = proc() + WARNING("division by zero"); + NumericStatus(':-division_by_zero'=false): + infinity; + end proc ): + +1/0; + +NumericStatus(':-division_by_zero'); diff --git a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol index 95173a49b7..9484dc8ea4 100644 --- a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol +++ b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol @@ -1,54 +1,10 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. Is-Numeric. - - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 Numeric-Chars PIC X(10) VALUE "0123456789". - - 01 Success CONSTANT 0. - 01 Failure CONSTANT 128. - - LOCAL-STORAGE SECTION. - 01 I PIC 99. - - 01 Num-Decimal-Points PIC 99. - 01 Num-Valid-Chars PIC 99. - - LINKAGE SECTION. - 01 Str PIC X(30). - - PROCEDURE DIVISION USING Str. - IF Str = SPACES - MOVE Failure TO Return-Code - GOBACK - END-IF - - MOVE FUNCTION TRIM(Str) TO Str - - INSPECT Str TALLYING Num-Decimal-Points FOR ALL "." - IF Num-Decimal-Points > 1 - MOVE Failure TO Return-Code - GOBACK - ELSE - ADD Num-Decimal-Points TO Num-Valid-Chars - END-IF - - IF Str (1:1) = "-" OR "+" - ADD 1 TO Num-Valid-Chars - END-IF - - PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10 - INSPECT Str TALLYING Num-Valid-Chars - FOR ALL Numeric-Chars (I:1) BEFORE SPACE - END-PERFORM - - INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES - - IF Num-Valid-Chars = FUNCTION LENGTH(Str) - MOVE Success TO Return-Code - ELSE - MOVE Failure TO Return-Code - END-IF - - GOBACK - . + program-id. is-numeric. + procedure division. + display function test-numval-f("abc") end-display + display function test-numval-f("-123.01E+3") end-display + if function test-numval-f("+123.123") equal zero then + display "is numeric" end-display + else + display "failed numval-f test" end-display + end-if + goback. diff --git a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol index 9484dc8ea4..95173a49b7 100644 --- a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol +++ b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol @@ -1,10 +1,54 @@ - program-id. is-numeric. - procedure division. - display function test-numval-f("abc") end-display - display function test-numval-f("-123.01E+3") end-display - if function test-numval-f("+123.123") equal zero then - display "is numeric" end-display - else - display "failed numval-f test" end-display - end-if - goback. + IDENTIFICATION DIVISION. + PROGRAM-ID. Is-Numeric. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Numeric-Chars PIC X(10) VALUE "0123456789". + + 01 Success CONSTANT 0. + 01 Failure CONSTANT 128. + + LOCAL-STORAGE SECTION. + 01 I PIC 99. + + 01 Num-Decimal-Points PIC 99. + 01 Num-Valid-Chars PIC 99. + + LINKAGE SECTION. + 01 Str PIC X(30). + + PROCEDURE DIVISION USING Str. + IF Str = SPACES + MOVE Failure TO Return-Code + GOBACK + END-IF + + MOVE FUNCTION TRIM(Str) TO Str + + INSPECT Str TALLYING Num-Decimal-Points FOR ALL "." + IF Num-Decimal-Points > 1 + MOVE Failure TO Return-Code + GOBACK + ELSE + ADD Num-Decimal-Points TO Num-Valid-Chars + END-IF + + IF Str (1:1) = "-" OR "+" + ADD 1 TO Num-Valid-Chars + END-IF + + PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10 + INSPECT Str TALLYING Num-Valid-Chars + FOR ALL Numeric-Chars (I:1) BEFORE SPACE + END-PERFORM + + INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES + + IF Num-Valid-Chars = FUNCTION LENGTH(Str) + MOVE Success TO Return-Code + ELSE + MOVE Failure TO Return-Code + END-IF + + GOBACK + . diff --git a/Task/Digital-root/Applesoft-BASIC/digital-root.applesoft b/Task/Digital-root/Applesoft-BASIC/digital-root.applesoft new file mode 100644 index 0000000000..3e472174e3 --- /dev/null +++ b/Task/Digital-root/Applesoft-BASIC/digital-root.applesoft @@ -0,0 +1,87 @@ +1 GOSUB 430"BASE SETUP +2 FOR E = 0 TO 1 STEP 0 +3 GOSUB 7"READ +4 ON E + 1 GOSUB 50, 10 +5 NEXT E +6 END + +7 READ N$ +8 E = N$ = "" +9 RETURN + +10 GOSUB 7"READ BASE +20 IF E THEN RETURN +30 BASE = VAL(N$) +40 READ N$ + +50 GOSUB 100"DIGITAL ROOT +60 GOSUB 420: PRINT " HAS AD"; +70 PRINT "DITIVE PERSISTENCE"; +80 PRINT " "P" AND DIGITAL R"; +90 PRINT "OOT "X$";" : RETURN + +REM DIGITAL ROOT OF N$, RETURNS X$ AND P + +100 P = 0 : L = LEN(N$) +110 X$ = MID$(N$, 2, L - 1) +120 N = LEFT$(X$, 1) = "-" +130 IF NOT N THEN X$ = N$ +140 FOR P = 0 TO 1E38 +150 L = LEN(X$) +160 IF L < 2 THEN RETURN +170 GOSUB 200"DIGIT SUM +180 X$ = S$ +190 NEXT P : STOP + +REM DIGIT SUM OF X$, RETURNS S$ + +200 S$ = "0" +210 R$ = X$ +220 L = LEN(R$) +230 FOR L = L TO 1 STEP -1 +240 E$ = "" : V$ = RIGHT$(R$, 1) +250 GOSUB 400 : S = LEN(S$) +260 ON R$ <> "0" GOSUB 300 +270 R$ = MID$(R$, 1, L - 1) +280 NEXT L +290 RETURN + +REM ADD V TO S$ + +300 FOR C = V TO 0 STEP 0 +310 V$ = RIGHT$(S$, 1) +320 GOSUB 400 : S = S - 1 +330 S$ = MID$(S$, 1, S) +340 V = V + C : C = V >= BASE +350 IF C THEN V = V - BASE +360 GOSUB 410 : E$ = V$ + E$ +370 IF S THEN NEXT C +380 IF C THEN S$ = "1" +390 S$ = S$ + E$ : RETURN + +REM BASE VAL +400 V = V(ASC(V$)) : RETURN + +REM BASE STR$ +410 V$ = V$(V) : RETURN + +REM BASE DISPLAY +420 PRINT N$; +421 IF BASE = 10 THEN RETURN +422 PRINT "("BASE")"; +423 RETURN + +REM BASE SETUP +430 IF BASE = 0 THEN BASE = 10 +440 DIM V(127), V$(35) +450 FOR I = 0 TO 35 +460 V = 55 + I - (I < 10) * 7 +470 V$(I) = CHR$(V) +480 V(V) = I +490 NEXT I : RETURN + +500 DATA627615,39390,588225 +510 DATA393900588225 +1000 DATA,30 +1010 DATADIGITALROOT +63999DATA, diff --git a/Task/Digital-root/AutoHotkey/digital-root.ahk b/Task/Digital-root/AutoHotkey/digital-root.ahk new file mode 100644 index 0000000000..b526665395 --- /dev/null +++ b/Task/Digital-root/AutoHotkey/digital-root.ahk @@ -0,0 +1,18 @@ +p := {} +for key, val in [30,1597,381947,92524902,448944221089] +{ + n := val + while n > 9 + { + m := 0 + Loop, Parse, n + m += A_LoopField + n := m, i := A_Index + } + p[A_Index] := [val, n, i] +} + +for key, val in p + Output .= val[1] ": Digital Root = " val[2] ", Additive Persistence = " val[3] "`n" + +MsgBox, 524288, , % Output diff --git a/Task/Digital-root/Common-Lisp/digital-root.lisp b/Task/Digital-root/Common-Lisp/digital-root.lisp new file mode 100644 index 0000000000..bfad344d7e --- /dev/null +++ b/Task/Digital-root/Common-Lisp/digital-root.lisp @@ -0,0 +1,11 @@ +(defun digital-root (number &optional (base 10)) + (loop for n = number then s + for ap = 1 then (1+ ap) + for s = (sum-digits n base) + when (< s base) + return (values s ap))) + +(loop for (nr base) in '((627615 10) (393900588225 10) (#X14e344 16) (#36Rdg9r 36)) + do (multiple-value-bind (dr ap) (digital-root nr base) + (format T "~vR (base ~a): additive persistence = ~a, digital root = ~vR~%" + base nr base ap base dr))) diff --git a/Task/Digital-root/Pascal/digital-root.pascal b/Task/Digital-root/Pascal/digital-root.pascal new file mode 100644 index 0000000000..bfc026ef29 --- /dev/null +++ b/Task/Digital-root/Pascal/digital-root.pascal @@ -0,0 +1,70 @@ +program DigitalRoot; + +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + SysUtils, StrUtils; + +// FPC has no Big mumbers implementation, Int64 will suffice. + +procedure GetDigitalRoot(Value: Int64; Base: Byte; var DRoot, Pers: Integer); +var + i: Integer; + DigitSum: Int64; +begin + Pers := 0; + repeat + Inc(Pers); + DigitSum := 0; + while Value > 0 do + begin + Inc(DigitSum, Value mod Base); + Value := Value div Base; + end; + Value := DigitSum; + until Value < Base; + DRoot := Value; +End; + +function IntToStrBase(Value: Int64; Base: Byte):String; +const + // usable up to 36-Base + DigitSymbols = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXY'; +begin + Result := ''; + while Value > 0 do + begin + Result := DigitSymbols[Value mod Base+1] + Result; + Value := Value div Base; + End; + +End; + +procedure Display(const Value: Int64; Base: Byte = 10); +var + DRoot, Pers: Integer; + StrValue: string; +begin + GetDigitalRoot(Value, Base, DRoot, Pers); + WriteLn(Format('%s(%d) has additive persistence %d and digital root %d.', + [IntToStrBase(Value, Base), Base, Pers, DRoot])); +End; + +begin + WriteLn('--- Examples in 10-Base ---'); + Display(627615); + Display(39390); + Display(588225); + Display(393900588225); + + WriteLn('--- Examples in 16-Base ---'); + Display(627615, 16); + Display(39390, 16); + Display(588225, 16); + Display(393900588225, 16); + + ReadLn; +End. diff --git a/Task/Digital-root/PowerShell/digital-root.psh b/Task/Digital-root/PowerShell/digital-root.psh new file mode 100644 index 0000000000..cedb531cd1 --- /dev/null +++ b/Task/Digital-root/PowerShell/digital-root.psh @@ -0,0 +1,19 @@ +function Get-DigitalRoot ($n) +{ + function Get-Digitalsum ($n) + { + if ($n -lt 10) {$n} + else { + ($n % 10) + (Get-DigitalSum ([math]::Floor($n / 10))) + } + } + + $ap = 0 + do {$n = Get-DigitalSum $n; $ap++} + until ($n -lt 10) + $DigitalRoot = [pscustomobject]@{ + 'Sum' = $n + 'Additive Persistence' = $ap + } + $DigitalRoot +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Clojure/dinesmans-multiple-dwelling-problem.clj b/Task/Dinesmans-multiple-dwelling-problem/Clojure/dinesmans-multiple-dwelling-problem.clj new file mode 100644 index 0000000000..6bcccaeaab --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Clojure/dinesmans-multiple-dwelling-problem.clj @@ -0,0 +1,37 @@ +(ns rosettacode.dinesman + (:use [clojure.core.logic] + [clojure.tools.macro :as macro])) + +; whether x is immediately above (left of) y in list s; uses pattern matching on s +(defne aboveo [x y s] + ([_ _ (x y . ?rest)]) + ([_ _ [_ . ?rest]] (aboveo x y ?rest))) + +; whether x is on a higher floor than y +(defne highero [x y s] + ([_ _ (x . ?rest)] (membero y ?rest)) + ([_ _ (_ . ?rest)] (highero x y ?rest))) + +; whether x and y are on nonadjacent floors +(defn nonadjacento [x y s] + (conda + ((aboveo x y s) fail) + ((aboveo y x s) fail) + (succeed))) + +(defn dinesmano [rs] + (macro/symbol-macrolet [_ (lvar)] + (all + (permuteo ['Baker 'Cooper 'Fletcher 'Miller 'Smith] rs) + (aboveo _ 'Baker rs) ;someone lives above Baker + (aboveo 'Cooper _ rs) ;Cooper lives above someone + (aboveo 'Fletcher _ rs) + (aboveo _ 'Fletcher rs) + (highero 'Miller 'Cooper rs) + (nonadjacento 'Smith 'Fletcher rs) + (nonadjacento 'Fletcher 'Cooper rs)))) + +(let [solns (run* [q] (dinesmano q))] + (println "solution count:" (count solns)) + (println "solution(s) highest to lowest floor:") + (doseq [soln solns] (println " " soln))) diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb index 9a36a41e8b..5aa5ee22fa 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb +++ b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb @@ -3,7 +3,7 @@ def solve( problem ) names = lines.first.scan( /[A-Z]\w*/ ) re_names = Regexp.union( names ) # Later on, search for these keywords (the word "not" is handled separately). - words = %w(first second third fourth fifth sixth seventh eighth nineth tenth + words = %w(first second third fourth fifth sixth seventh eighth ninth tenth bottom top higher lower adjacent) re_keywords = Regexp.union( words ) diff --git a/Task/Dining-philosophers/AutoHotkey/dining-philosophers.ahk b/Task/Dining-philosophers/AutoHotkey/dining-philosophers.ahk new file mode 100644 index 0000000000..aa007113a5 --- /dev/null +++ b/Task/Dining-philosophers/AutoHotkey/dining-philosophers.ahk @@ -0,0 +1,142 @@ +#Persistent +SetWorkingDir, %A_ScriptDir% +FileDelete, output.txt +EnoughForks := 2 ; required forks to begin eating +Fork1 := Fork2 := Fork3 := Fork4 := Fork5 := 1 ; fork supply per philosopher +SetTimer, AristotleWaitForLeftFork +SetTimer, KantWaitForLeftFork +SetTimer, SpinozaWaitForLeftFork +SetTimer, MarxWaitForLeftFork +SetTimer, RussellWaitForLeftFork +Return ;--------------------------------------------------------------- + +AristotleWaitForLeftFork: + WaitForFork("Aristotle", "left", Fork1, Fork2, AristotleLeftForkCount, AristotleRightForkCount, AristotleWaitCount, EnoughForks) +Return +AristotleWaitForRightFork: + WaitForFork("Aristotle", "right", Fork2, Fork1, AristotleRightForkCount, AristotleLeftForkCount, AristotleWaitCount, EnoughForks) +Return +AristotleFinishEating: + ReturnForks("Aristotle", Fork1, Fork2, AristotleLeftForkCount, AristotleRightForkCount, EnoughForks) +Return + +KantWaitForLeftFork: + WaitForFork("Kant", "left", Fork2, Fork3, KantLeftForkCount, KantRightForkCount, KantWaitCount, EnoughForks) +Return +KantWaitForRightFork: + WaitForFork("Kant", "right", Fork3, Fork2, KantRightForkCount, KantLeftForkCount, KantWaitCount, EnoughForks) +Return +KantFinishEating: + ReturnForks("Kant", Fork2, Fork3, KantLeftForkCount, KantRightForkCount, EnoughForks) +Return + +SpinozaWaitForLeftFork: + WaitForFork("Spinoza", "left", Fork3, Fork4, SpinozaLeftForkCount, SpinozaRightForkCount, SpinozaWaitCount, EnoughForks) +Return +SpinozaWaitForRightFork: + WaitForFork("Spinoza", "right", Fork4, Fork3, SpinozaRightForkCount, SpinozaLeftForkCount, SpinozaWaitCount, EnoughForks) +Return +SpinozaFinishEating: + ReturnForks("Spinoza", Fork3, Fork4, SpinozaLeftForkCount, SpinozaRightForkCount, EnoughForks) +Return + +MarxWaitForLeftFork: + WaitForFork("Marx", "left", Fork4, Fork5, MarxLeftForkCount, MarxRightForkCount, MarxWaitCount, EnoughForks) +Return +MarxWaitForRightFork: + WaitForFork("Marx", "right", Fork5, Fork4, MarxRightForkCount, MarxLeftForkCount, MarxWaitCount, EnoughForks) +Return +MarxFinishEating: + ReturnForks("Marx", Fork4, Fork5, MarxLeftForkCount, MarxRightForkCount, EnoughForks) +Return + +RussellWaitForLeftFork: + WaitForFork("Russell", "left", Fork5, Fork1, RussellLeftForkCount, RussellRightForkCount, RussellWaitCount, EnoughForks) +Return +RussellWaitForRightFork: + WaitForFork("Russell", "right", Fork1, Fork5, RussellRightForkCount, RussellLeftForkCount, RussellWaitCount, EnoughForks) +Return +RussellFinishEating: + ReturnForks("Russell", Fork5, Fork1, RussellLeftForkCount, RussellRightForkCount, EnoughForks) +Return + +ReturnForks(Philosopher, ByRef ThisFork, ByRef OtherFork, ByRef CurrentThisForkCount, ByRef CurrentOtherForkCount, EnoughForks) { + OutputDebug, %Philosopher% finishes eating. + FileAppend, %Philosopher% finishes eating.`n,output.txt + ThisFork += CurrentThisForkCount ; return this fork + OtherFork += CurrentOtherForkCount ; return other fork + CurrentThisForkCount := 0 ; release this fork + CurrentOtherForkCount := 0 ; release other fork + OutputDebug, %Philosopher% returns all forks. + FileAppend, %Philosopher% returns all forks.`n,output.txt + + ; do something while resting + + Random, Rand, 0, 1 + Rand := Rand ? "Left" : "Right" + SetTimer, %Philosopher%WaitFor%Rand%Fork +} + +WaitForFork(Philosopher, This, ByRef ThisFork, ByRef OtherFork, ByRef CurrentThisForkCount, ByRef CurrentOtherForkCount, ByRef CurrentWaitCount, EnoughForks) { + If This not in Left,Right + Return Error + Other := (This="right") ? "left" : "right" + OutputDebug, %Philosopher% is hungry. + FileAppend, %Philosopher% is hungry.`n,output.txt + If (ThisFork) ; if this fork available + { + SetTimer, %Philosopher%WaitFor%This%Fork, Off + CurrentWaitCount := 0 + ThisFork-- ; take this fork + CurrentThisForkCount++ ; receive this fork + OutputDebug, %Philosopher% grabs %This% fork. + FileAppend, %Philosopher% grabs %This% fork.`n,output.txt + If (CurrentThisForkCount + CurrentOtherForkCount = EnoughForks) ; if philosopher has enough forks + { + OutputDebug, %Philosopher% starts eating. + FileAppend, %Philosopher% starts eating.`n,output.txt + + ; do something while eating + + SetTimer, %Philosopher%FinishEating, -250 + } + Else If (EnoughForks=2) + { + SetTimer, %Philosopher%WaitFor%Other%Fork + } + Else + { + Random, Rand, 0, 1 + Rand := Rand ? "Left" : "Right" + SetTimer, %Philosopher%WaitFor%Rand%Fork + } + } + Else If (CurrentOtherForkCount and CurrentWaitCount > 5) ; if we've been holding other fork too long + { + SetTimer, %Philosopher%WaitFor%This%Fork, Off + CurrentWaitCount := 0 + OtherFork++ ; return other fork + CurrentOtherForkCount-- ; release other fork + OutputDebug, %Philosopher% drops %Other% fork. + FileAppend, %Philosopher% drops %Other% fork.`n,output.txt + Random, Rand, 0, 1 + Rand := Rand ? "Left" : "Right" + SetTimer, %Philosopher%WaitFor%Rand%Fork + } + Else If (CurrentThisForkCount and CurrentWaitCount > 5) ; if we've been holding one of this fork too long + { + SetTimer, %Philosopher%WaitFor%This%Fork, Off + CurrentWaitCount := 0 + ThisFork++ ; return other fork + CurrentThisForkCount-- ; release other fork + OutputDebug, %Philosopher% drops %This% fork. + FileAppend, %Philosopher% drops %This% fork.`n,output.txt + Random, Rand, 0, 1 + Rand := Rand ? "Left" : "Right" + SetTimer, %Philosopher%WaitFor%Rand%Fork + } + Else + { + CurrentWaitCount++ + } +} diff --git a/Task/Distributed-programming/Objective-C/distributed-programming-4.m b/Task/Distributed-programming/Objective-C/distributed-programming-4.m index feba6c858e..ab6392e63e 100644 --- a/Task/Distributed-programming/Objective-C/distributed-programming-4.m +++ b/Task/Distributed-programming/Objective-C/distributed-programming-4.m @@ -3,38 +3,33 @@ int main (void) { - NSAutoreleasePool *pool; - ActionObject *action; - NSConnection *connect; - NSSocketPort *port; + @autoreleasepool { - pool = [[NSAutoreleasePool alloc] init]; + ActionObject *action = [[ActionObject alloc] init]; - action = [[ActionObject alloc] init]; + NSSocketPort *port = (NSSocketPort *)[NSSocketPort port]; + // initWithTCPPort: 1234 and other methods are not supported yet + // by GNUstep + NSConnection *connect = [NSConnection + connectionWithReceivePort: port + sendPort: port]; // or sendPort: nil - port = (NSSocketPort *)[NSSocketPort port]; - // initWithTCPPort: 1234 and other methods are not supported yet - // by GNUstep - connect = [NSConnection - connectionWithReceivePort: port - sendPort: port]; // or sendPort: nil + [connect setRootObject: action]; - [connect setRootObject: action]; + /* "vend" the object ActionObject as DistributedAction; on GNUstep + the Name Server that allows the resolution of the registered name + is bound to port 538 */ + if (![connect registerName:@"DistributedAction" + withNameServer: [NSSocketPortNameServer sharedInstance] ]) + { + NSLog(@"can't register the server DistributedAction"); + exit(EXIT_FAILURE); + } + + NSLog(@"waiting for messages..."); + + [[NSRunLoop currentRunLoop] run]; - /* "vend" the object ActionObject as DistributedAction; on GNUstep - the Name Server that allows the resolution of the registered name - is bound to port 538 */ - if ([connect registerName:@"DistributedAction" - withNameServer: [NSSocketPortNameServer sharedInstance] ] == NO) - { - NSLog(@"can't register the server DistributedAction"); - exit(EXIT_FAILURE); } - - NSLog(@"waiting for messages..."); - - [[NSRunLoop currentRunLoop] run]; - - [pool release]; return 0; } diff --git a/Task/Distributed-programming/Objective-C/distributed-programming-5.m b/Task/Distributed-programming/Objective-C/distributed-programming-5.m index 1a4de04c32..f3d0828863 100644 --- a/Task/Distributed-programming/Objective-C/distributed-programming-5.m +++ b/Task/Distributed-programming/Objective-C/distributed-programming-5.m @@ -3,41 +3,36 @@ int main(void) { - NSAutoreleasePool *pool; - NSArray *args; - id action; - NSString *msg, *backmsg; + @autoreleasepool { - pool = [[NSAutoreleasePool alloc] init]; + id action = (id ) + [NSConnection + rootProxyForConnectionWithRegisteredName: @"DistributedAction" + host: @"localhost" + usingNameServer: [NSSocketPortNameServer sharedInstance] ]; - action = (id ) - [NSConnection - rootProxyForConnectionWithRegisteredName: @"DistributedAction" - host: @"localhost" - usingNameServer: [NSSocketPortNameServer sharedInstance] ]; + if (action == nil) + { + NSLog(@"can't connect to the server"); + exit(EXIT_FAILURE); + } + + NSArray *args = [[NSProcessInfo processInfo] arguments]; + + if ([args count] == 1) + { + NSLog(@"specify a message"); + exit(EXIT_FAILURE); + } + + NSString *msg = args[1]; + + // "send" (call the selector "sendMessage:" of the (remote) object + // action) the first argument's text as msg, store the message "sent + // back" and then show it in the log + NSString *backmsg = [action sendMessage: msg]; + NSLog("%@", backmsg); - if (action == nil) - { - NSLog(@"can't connect to the server"); - exit(EXIT_FAILURE); } - - args = [[NSProcessInfo processInfo] arguments]; - - if ([args count] == 1) - { - NSLog(@"specify a message"); - exit(EXIT_FAILURE); - } - - msg = [args objectAtIndex: 1]; - - // "send" (call the selector "sendMessage:" of the (remote) object - // action) the first argument's text as msg, store the message "sent - // back" and then show it in the log - backmsg = [action sendMessage: msg]; - NSLog("%@", backmsg); - - [pool release]; return 0; } diff --git a/Task/Documentation/00DESCRIPTION b/Task/Documentation/00DESCRIPTION index 662af89c57..56b2fc280b 100644 --- a/Task/Documentation/00DESCRIPTION +++ b/Task/Documentation/00DESCRIPTION @@ -1 +1,4 @@ Show how to insert documentation for classes, functions, and/or variables in your language. If this documentation is built-in to the language, note it. If this documentation requires external tools, note them. + +'''See Also:'''
+* Related Task: [[Comments]] diff --git a/Task/Dot-product/D/dot-product-2.d b/Task/Dot-product/D/dot-product-2.d index 79f464aa57..575fbd067c 100644 --- a/Task/Dot-product/D/dot-product-2.d +++ b/Task/Dot-product/D/dot-product-2.d @@ -1,9 +1,8 @@ void main() { - import std.stdio, std.range, std.algorithm; + import std.stdio, std.algorithm; double[3] a = [1.0, 3.0, -5.0]; double[3] b = [4.0, -2.0, -1.0]; - double[3] c; - c[] = a[] * b[]; - c.reduce!q{a + b}.writeln; + double[3] c = a[] * b[]; + c[].sum.writeln; } diff --git a/Task/Dot-product/Dart/dot-product.dart b/Task/Dot-product/Dart/dot-product.dart new file mode 100644 index 0000000000..6a627fbe87 --- /dev/null +++ b/Task/Dot-product/Dart/dot-product.dart @@ -0,0 +1,16 @@ +num dot(List A, List B){ + if (A.length != B.length){ + throw new Exception('Vectors must be of equal size'); + } + num result = 0; + for (int i = 0; i < A.length; i++){ + result += A[i] * B[i]; + } + return result; +} + +void main(){ + var l = [1,3,-5]; + var k = [4,-2,-1]; + print(dot(l,k)); +} diff --git a/Task/Dot-product/Maple/dot-product-1.maple b/Task/Dot-product/Maple/dot-product-1.maple new file mode 100644 index 0000000000..d733c11251 --- /dev/null +++ b/Task/Dot-product/Maple/dot-product-1.maple @@ -0,0 +1 @@ +<1,2,3> . <4,5,6> diff --git a/Task/Dot-product/Maple/dot-product-2.maple b/Task/Dot-product/Maple/dot-product-2.maple new file mode 100644 index 0000000000..9ff9294a44 --- /dev/null +++ b/Task/Dot-product/Maple/dot-product-2.maple @@ -0,0 +1 @@ +Array([1,2,3]) . Array([4,5,6]) diff --git a/Task/Dot-product/Maple/dot-product-3.maple b/Task/Dot-product/Maple/dot-product-3.maple new file mode 100644 index 0000000000..d287135cf1 --- /dev/null +++ b/Task/Dot-product/Maple/dot-product-3.maple @@ -0,0 +1 @@ +LinearAlgebra( <1,2,3>, <4,5,6> ) diff --git a/Task/Dot-product/Maple/dot-product-4.maple b/Task/Dot-product/Maple/dot-product-4.maple new file mode 100644 index 0000000000..8a670a7088 --- /dev/null +++ b/Task/Dot-product/Maple/dot-product-4.maple @@ -0,0 +1 @@ +LinearAlgebra( Array([1,2,3]), Array([4,5,6]) ) diff --git a/Task/Dot-product/Maple/dot-product-5.maple b/Task/Dot-product/Maple/dot-product-5.maple new file mode 100644 index 0000000000..0f5a14926f --- /dev/null +++ b/Task/Dot-product/Maple/dot-product-5.maple @@ -0,0 +1 @@ +LinearAlgebra([1,2,3], [4,5,6] ) diff --git a/Task/Dot-product/Objective-C/dot-product.m b/Task/Dot-product/Objective-C/dot-product.m index da76a7781f..04e28911a0 100644 --- a/Task/Dot-product/Objective-C/dot-product.m +++ b/Task/Dot-product/Objective-C/dot-product.m @@ -2,34 +2,34 @@ #import #import #import -#import +#import // this class exists to return a result between two // vectors: if vectors have different "size", valid // must be NO -@interface VResult : Object +@interface VResult : NSObject { @private double value; BOOL valid; } -+(id)new: (double)v isValid: (BOOL)y; --(id)init: (double)v isValid: (BOOL)y; ++(instancetype)new: (double)v isValid: (BOOL)y; +-(instancetype)init: (double)v isValid: (BOOL)y; -(BOOL)isValid; -(double)value; @end @implementation VResult -+(id)new: (double)v isValid: (BOOL)y ++(instancetype)new: (double)v isValid: (BOOL)y { - id s = [super new]; - [s init: v isValid: y]; - return s; + return [[self alloc] init: v isValid: y]; } --(id)init: (double)v isValid: (BOOL)y +-(instancetype)init: (double)v isValid: (BOOL)y { - value = v; - valid = y; + if ((self == [super init])) { + value = v; + valid = y; + } return self; } -(BOOL)isValid { return valid; } @@ -37,14 +37,14 @@ @end -@interface RCVector : Object +@interface RCVector : NSObject { @private double *vec; uint32_t size; } -+(id)newWithArray: (double *)v ofLength: (uint32_t)l; --(id)initWithArray: (double *)v ofLength: (uint32_t)l; ++(instancetype)newWithArray: (double *)v ofLength: (uint32_t)l; +-(instancetype)initWithArray: (double *)v ofLength: (uint32_t)l; -(VResult *)dotProductWith: (RCVector *)v; -(uint32_t)size; -(double *)array; @@ -52,27 +52,24 @@ @end @implementation RCVector -+(id)newWithArray: (double *)v ofLength: (uint32_t)l ++(instancetype)newWithArray: (double *)v ofLength: (uint32_t)l { - id s = [super new]; - [s initWithArray: v ofLength: l]; - return s; + return [[self alloc] initWithArray: v ofLength: l]; } --(id)initWithArray: (double *)v ofLength: (uint32_t)l +-(instancetype)initWithArray: (double *)v ofLength: (uint32_t)l { - size = l; - vec = malloc(sizeof(double) * l); - if ( vec != NULL ) { + if ((self = [super init])) { + size = l; + vec = malloc(sizeof(double) * l); + if ( vec == NULL ) + return nil; memcpy(vec, v, sizeof(double)*l); - return self; } - [super free]; - return nil; + return self; } --(void)free +-(void)dealloc { free(vec); - [super free]; } -(uint32_t)size { return size; } -(double *)array { return vec; } @@ -96,13 +93,15 @@ double val2[] = { 4,-2, -1 }; int main() { - RCVector *v1 = [RCVector newWithArray: val1 ofLength: sizeof(val1)/sizeof(double)]; - RCVector *v2 = [RCVector newWithArray: val2 ofLength: sizeof(val1)/sizeof(double)]; - VResult *r = [v1 dotProductWith: v2]; - if ( [r isValid] ) { - printf("%lf\n", [r value]); - } else { - fprintf(stderr, "length of vectors differ\n"); + @autoreleasepool { + RCVector *v1 = [RCVector newWithArray: val1 ofLength: sizeof(val1)/sizeof(double)]; + RCVector *v2 = [RCVector newWithArray: val2 ofLength: sizeof(val1)/sizeof(double)]; + VResult *r = [v1 dotProductWith: v2]; + if ( [r isValid] ) { + printf("%lf\n", [r value]); + } else { + fprintf(stderr, "length of vectors differ\n"); + } } return 0; } diff --git a/Task/Dot-product/Scala/dot-product.scala b/Task/Dot-product/Scala/dot-product.scala index 28723cc556..7b0ea63e33 100644 --- a/Task/Dot-product/Scala/dot-product.scala +++ b/Task/Dot-product/Scala/dot-product.scala @@ -1,12 +1,18 @@ +import scala.language.postfixOps +import scala.language.implicitConversions + class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) { - import n._ + import n._ // import * operator def dot(v2: Seq[T]) = { - require(v1.length == v2.length) - v1 zip v2 map Function.tupled(_*_) sum + require(v1.size == v2.size) + v1 zip v2 map Function.tupled(_ * _) sum } } -implicit def toDot[T : Numeric](v1: Seq[T]) = new Dot(v1) -val v1 = List(1, 3, -5) -val v2 = List(4, -2, -1) -println(v1 dot v2) +object Main extends App { + implicit def toDot[T: Numeric](v1: Seq[T]) = new Dot(v1) + + val v1 = List(1, 3, -5) + val v2 = List(4, -2, -1) + println(v1 dot v2) +} diff --git a/Task/Dragon-curve/ALGOL-68/dragon-curve-1.alg b/Task/Dragon-curve/ALGOL-68/dragon-curve-1.alg new file mode 100644 index 0000000000..f7cc9026e8 --- /dev/null +++ b/Task/Dragon-curve/ALGOL-68/dragon-curve-1.alg @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- # + +STRUCT (REAL x, y, heading, BOOL pen down) turtle; + +PROC turtle init = VOID: ( + draw erase (window); + turtle := (0.5, 0.5, 0, TRUE); + draw move (window, x OF turtle, y OF turtle); + draw colour name(window, "white") +); + +PROC turtle left = (REAL left turn)VOID: + heading OF turtle +:= left turn; + +PROC turtle right = (REAL right turn)VOID: + heading OF turtle -:= right turn; + +PROC turtle forward = (REAL distance)VOID:( + x OF turtle +:= distance * cos(heading OF turtle) / width * height; + y OF turtle +:= distance * sin(heading OF turtle); + IF pen down OF turtle THEN + draw line + ELSE + draw move + FI (window, x OF turtle, y OF turtle) +); + +SKIP diff --git a/Task/Dragon-curve/ALGOL-68/dragon-curve-2.alg b/Task/Dragon-curve/ALGOL-68/dragon-curve-2.alg new file mode 100644 index 0000000000..7a98cd826c --- /dev/null +++ b/Task/Dragon-curve/ALGOL-68/dragon-curve-2.alg @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- # + +COMMENT + REQUIRES : + MODE EXCEPTOBJ = UNION(VOID, MODEA, MODEB, MODEC ...); + OP FIRMSTR = (EXCEPTOBJ obj)STRING: ~ +END COMMENT + +MODE EXCEPTOBJS = [0]EXCEPTOBJ; + +OP STR = (EXCEPTOBJS obj)STRING: ( + STRING out := "(", fs := ""; + FOR this FROM LWB obj TO UPB obj DO out +:= fs+FIRMSTR obj[this]; fs:=", " OD; + out +")" +); + +MODE EXCEPTMEND = PROC(EXCEPTOBJS #obj#,STRING #msg#)BOOL; + +PROC super mend = (EXCEPTOBJS obj,STRING sub exception, msg)BOOL: + ( put(stand error, ("exception/",sub exception,": ", msg," - ", STR obj, new line)); break; TRUE); + +PROC super break mend = (EXCEPTOBJS obj,STRING sub exception, msg)BOOL: ( super mend(obj, sub exception, msg); break; TRUE); +PROC super stop mend = (EXCEPTOBJS obj,STRING sub exception, msg)BOOL: ( super mend(obj, sub exception, msg); stop; FALSE); +PROC super ignore mend = (EXCEPTOBJS obj,STRING sub exception, msg)BOOL: ( #super mend(obj, sub exception, msg);# TRUE); + +EXCEPTMEND on undefined mend := super break mend(,"undefined",); +PROC on undefined = (EXCEPTMEND undefined mend)VOID: on undefined mend := undefined mend; +PROC raise undefined = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on undefined mend(obj, msg) THEN stop FI; + +EXCEPTMEND on value error mend := super break mend(,"value error",); +PROC on value error = (EXCEPTMEND value error mend)VOID: on value error mend := value error mend; +PROC raise value error = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on value error mend(obj, msg) THEN stop FI; + +EXCEPTMEND on bounds error mend := super break mend(,"bounds error",); +PROC on bounds error = (EXCEPTMEND bounds error mend)VOID: on bounds error mend := bounds error mend; +PROC raise bounds error = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on bounds error mend(obj, msg) THEN stop FI; + +EXCEPTMEND on tagged union error mend := super break mend(,"tagged union error",); +PROC on tagged union error = (EXCEPTMEND tagged union error mend)VOID: on tagged union error mend := tagged union error mend; +PROC raise tagged union error = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on tagged union error mend(obj, msg) THEN stop FI; + +EXCEPTMEND on untested mend := super break mend(,"untested",); +PROC on untested = (EXCEPTMEND untested mend)VOID: on untested mend := untested mend; +PROC raise untested = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on untested mend(obj, msg) THEN stop FI; + +EXCEPTMEND on unimplemented mend := super break mend(,"unimplemented",); +PROC on unimplemented = (EXCEPTMEND unimplemented mend)VOID: on unimplemented mend := unimplemented mend; +PROC raise unimplemented = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on unimplemented mend(obj, msg) THEN stop FI; + +SKIP diff --git a/Task/Dragon-curve/ALGOL-68/dragon-curve.alg b/Task/Dragon-curve/ALGOL-68/dragon-curve-3.alg similarity index 66% rename from Task/Dragon-curve/ALGOL-68/dragon-curve.alg rename to Task/Dragon-curve/ALGOL-68/dragon-curve-3.alg index f1aabda413..1eefa3ef10 100644 --- a/Task/Dragon-curve/ALGOL-68/dragon-curve.alg +++ b/Task/Dragon-curve/ALGOL-68/dragon-curve-3.alg @@ -1,34 +1,13 @@ -REAL sqrt 2 = sqrt(2), degrees = pi/180, width = 800-15, height = 600-15; +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # -PROC raise exception = ([]STRING args)VOID: ( - putf(stand error, ($gx$, args, $l$)); - stop -); +PR read "prelude/turtle_draw.a68" PR; +MODE EXCEPTOBJ = FILE; +OP FIRMSTR = (EXCEPTOBJ obj)STRING: "FILE"; -STRUCT (REAL x, y, heading, BOOL pen down) turtle; +PR read "prelude/exception.a68" PR; -PROC turtle init = VOID: ( - draw erase (window); - turtle := (0.5, 0.5, 0, TRUE); - draw move (window, x OF turtle, y OF turtle); - draw colour name(window, "white") -); - -PROC turtle left = (REAL left turn)VOID: - heading OF turtle +:= left turn; - -PROC turtle right = (REAL right turn)VOID: - heading OF turtle -:= right turn; - -PROC turtle forward = (REAL distance)VOID:( - x OF turtle +:= distance * cos(heading OF turtle) / width * height; - y OF turtle +:= distance * sin(heading OF turtle); - IF pen down OF turtle THEN - draw line - ELSE - draw move - FI (window, x OF turtle, y OF turtle) -); +REAL sqrt 2 = sqrt(2), degrees = pi/180; STRUCT ( INT count, depth, current shade, upb lines, upb colours ) morph; @@ -82,12 +61,18 @@ PROC dragon = (REAL in step, in length, PROC(REAL)VOID zig, zag)VOID: ( PROC window init = VOID: ( STRING aspect; FILE f; associate(f, aspect); putf(f, ($g(-4)"x"g(-3)$, width, height)); +CO # depricated # IF NOT draw device (window, "X", aspect)THEN - raise exception("cannot initialise X draw device") FI; - IF open (window, "Dragon Curve", stand draw channel) /= 0 THEN - raise exception("cannot open Dragon Curve window") FI + raise undefined(window, "cannot initialise X draw device") FI; +END CO + IF open (window, "Dragon Curve", stand draw channel) = 0 THEN + raise undefined(window, "cannot open Dragon Curve window") FI; + IF NOT make device (window, "X", aspect) THEN + raise undefined(window, "cannot make device X draw device") FI ); +INT width = 800-15, height = 600-15; + FILE window; window init; INT cycle length = 18; FOR snap shot TO cycle length DO diff --git a/Task/Draw-a-cuboid/AutoHotkey/draw-a-cuboid.ahk b/Task/Draw-a-cuboid/AutoHotkey/draw-a-cuboid.ahk new file mode 100644 index 0000000000..1b74938852 --- /dev/null +++ b/Task/Draw-a-cuboid/AutoHotkey/draw-a-cuboid.ahk @@ -0,0 +1,48 @@ +Angle := 45 +C := 0.01745329252 +W := 200 +H := 300 +L := 400 +LX := L * Cos(Angle * C), LY := L * Sin(Angle * C) + +If !pToken := Gdip_Startup() +{ + MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system + ExitApp +} +OnExit, Exit + +A := 50, B := 650, WinWidth := 700, WinHeight := 700 +TopX := (A_ScreenWidth - WinWidth) //2, TopY := (A_ScreenHeight - WinHeight) //2 + +Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, 1: Show, NA +hwnd1 := WinExist(), hbm := CreateDIBSection(WinWidth, WinHeight), hdc := CreateCompatibleDC() + , obm := SelectObject(hdc, hbm), G := Gdip_GraphicsFromHDC(hdc), Gdip_SetSmoothingMode(G, 4) + +Points := A "," B "|" A+W "," B "|" A+W "," B-H "|" A "," B-H + , DrawFace(Points, 0xff0066ff, G) + +Points := A+W "," B "|" A+W+LX "," B-LY "|" A+W+LX "," B-LY-H "|" A+W "," B-H + , DrawFace(Points, 0xff00d400, G) + +Points := A "," B-H "|" A+W "," B-H "|" A+W+LX "," B-LY-H "|" A+LX "," B-LY-H + , DrawFace(Points, 0xffd40055, G) + +UpdateLayeredWindow(hwnd1, hdc, TopX, TopY, WinWidth, WinHeight) + +SelectObject(hdc, obm), DeleteObject(hbm), DeleteDC(hdc) + , Gdip_DeleteGraphics(G) +return + +DrawFace(Points, Color, G) { + pBrush := Gdip_BrushCreateSolid(Color) + , Gdip_FillPolygon(G, pBrush, Points, 1) + , Gdip_DeleteBrush(pBrush) + return +} + +Esc:: +Exit: +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Draw-a-sphere/Ada/draw-a-sphere.ada b/Task/Draw-a-sphere/Ada/draw-a-sphere-1.ada similarity index 100% rename from Task/Draw-a-sphere/Ada/draw-a-sphere.ada rename to Task/Draw-a-sphere/Ada/draw-a-sphere-1.ada diff --git a/Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada b/Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada new file mode 100644 index 0000000000..4e66981156 --- /dev/null +++ b/Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada @@ -0,0 +1,12 @@ +with Display; use Display; +with Display.Basic; use Display.Basic; + +procedure Main is + Ball : Shape_Id := New_Circle + (X => 0.0, + Y => 0.0, + Radius => 20.0, + Color => Blue); +begin + null; +end Main; diff --git a/Task/Draw-a-sphere/AutoHotkey/draw-a-sphere.ahk b/Task/Draw-a-sphere/AutoHotkey/draw-a-sphere.ahk new file mode 100644 index 0000000000..5800b31898 --- /dev/null +++ b/Task/Draw-a-sphere/AutoHotkey/draw-a-sphere.ahk @@ -0,0 +1,57 @@ +#NoEnv +SetBatchLines, -1 +#SingleInstance, Force + +; Uncomment if Gdip.ahk is not in your standard library +#Include, Gdip.ahk + +; Settings +X := 200, Y := 200, Width := 200, Height := 200 ; Location and size of sphere +rotation := -30 ; degrees +ARGB := 0xFFFF0000 ; Color=Solid Red + +If !pToken := Gdip_Startup() ; Start gdi+ +{ + MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system + ExitApp +} +OnExit, Exit + +Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs ; Create GUI +Gui, Show, NA ; Show GUI +hwnd1 := WinExist() ; Get a handle to this window we have created in order to update it later +hbm := CreateDIBSection(A_ScreenWidth, A_ScreenHeight) ; Create a gdi bitmap drawing area +hdc := CreateCompatibleDC() ; Get a device context compatible with the screen +obm := SelectObject(hdc, hbm) ; Select the bitmap into the device context +pGraphics := Gdip_GraphicsFromHDC(hdc) ; Get a pointer to the graphics of the bitmap, for use with drawing functions +Gdip_SetSmoothingMode(pGraphics, 4) ; Set the smoothing mode to antialias = 4 to make shapes appear smother + +Gdip_TranslateWorldTransform(pGraphics, X, Y) +Gdip_RotateWorldTransform(pGraphics, rotation) + +; Base ellipse +pBrush := Gdip_CreateLineBrushFromRect(0, 0, Width, Height, ARGB, 0xFF000000) +Gdip_FillEllipse(pGraphics, pBrush, 0, 0, Width, Height) + +; First highlight ellipse +pBrush := Gdip_CreateLineBrushFromRect(Width*0.1, Height*0.01, Width*0.8, Height*0.6, 0x33FFFFFF, 0x00FFFFFF) +Gdip_FillEllipse(pGraphics, pBrush, Width*0.1, Height*0.01, Width*0.8, Height*0.6) + +; Second highlight ellipse +pBrush := Gdip_CreateLineBrushFromRect(Width*0.3, Height*0.02, Width*0.3, Height*0.2, 0xBBFFFFFF, 0x00FFFFFF) +Gdip_FillEllipse(pGraphics, pBrush, Width*0.3, Height*0.02, Width*0.3, Height*0.2) + + +UpdateLayeredWindow(hwnd1, hdc, 0, 0, A_ScreenWidth, A_ScreenHeight) +SelectObject(hdc, obm) ; Select the object back into the hdc +Gdip_DeletePath(Path) +Gdip_DeleteBrush(pBrush) +DeleteObject(hbm) ; Now the bitmap may be deleted +DeleteDC(hdc) ; Also the device context related to the bitmap may be deleted +Gdip_DeleteGraphics(G) ; The graphics may now be deleted +Return + +Exit: +; gdi+ may now be shutdown on exiting the program +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Draw-a-sphere/Perl/draw-a-sphere.pl b/Task/Draw-a-sphere/Perl/draw-a-sphere.pl new file mode 100644 index 0000000000..74a0f57285 --- /dev/null +++ b/Task/Draw-a-sphere/Perl/draw-a-sphere.pl @@ -0,0 +1,51 @@ +use strict; +use warnings; + +my $x = my $y = 255; +$x |= 1; # must be odd +my $depth = 255; + +my $light = Vector->new(rand, rand, rand)->normalized; + +print "P2\n$x $y\n$depth\n"; + +my ($r, $ambient) = (($x - 1)/2, 0); +my ($r2) = $r ** 2; +{ + for my $x (-$r .. $r) { + my $x2 = $x**2; + for my $y (-$r .. $r) { + my $y2 = $y**2; + my $pixel = 0; + if ($x2 + $y2 < $r2) { + my $v = Vector->new($x, $y, sqrt($r2 - $x2 - $y2))->normalized; + my $I = $light . $v + $ambient; + $I = $I < 0 ? 0 : $I > 1 ? 1 : $I; + $pixel = int($I * $depth); + } + print $pixel; + print $y == $r ? "\n" : " "; + } + } +} + +package Vector { + sub new { + my $class = shift; + bless ref($_[0]) eq 'Array' ? $_[0] : [ @_ ], $class; + } + sub normalized { + my $this = shift; + my $norm = sqrt($this . $this); + ref($this)->new( map $_/$norm, @$this ); + } + use overload q{.} => sub { + my ($a, $b) = @_; + my $sum = 0; + for (0 .. @$a - 1) { + $sum += $a->[$_] * $b->[$_] + } + return $sum; + }, + q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} }; +} diff --git a/Task/Dutch-national-flag-problem/AutoHotkey/dutch-national-flag-problem.ahk b/Task/Dutch-national-flag-problem/AutoHotkey/dutch-national-flag-problem.ahk new file mode 100644 index 0000000000..4b547af891 --- /dev/null +++ b/Task/Dutch-national-flag-problem/AutoHotkey/dutch-national-flag-problem.ahk @@ -0,0 +1,14 @@ +RandGen(MaxBalls){ +Random,k,3,MaxBalls +Loop,% k{ + Random,k,1,3 + o.=k +}return o +} +While((!InStr(o,1)||!InStr(o,2)||!InStr(o,3))||!RegExReplace(o,"\b1+2+3+\b")) + o:=RandGen(3) +Loop,% StrLen(o) + F.=SubStr(o,A_Index,1) "," +F:=RTrim(F,",") +Sort,F,N D`, +MsgBox,% F:=RegExReplace(RegExReplace(RegExReplace(F,"(1)","Red"),"(2)","White"),"(3)","Blue") diff --git a/Task/Echo-server/Go/echo-server.go b/Task/Echo-server/Go/echo-server.go index cf38848568..f19c65727a 100644 --- a/Task/Echo-server/Go/echo-server.go +++ b/Task/Echo-server/Go/echo-server.go @@ -7,6 +7,8 @@ import ( ) func echo(s net.Conn, i int) { + defer s.Close(); + fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr()) b := bufio.NewReader(s) for { diff --git a/Task/Element-wise-operations/Go/element-wise-operations-1.go b/Task/Element-wise-operations/Go/element-wise-operations-1.go index 08ff2b32f6..527160cc4d 100644 --- a/Task/Element-wise-operations/Go/element-wise-operations-1.go +++ b/Task/Element-wise-operations/Go/element-wise-operations-1.go @@ -1,39 +1,52 @@ -package main +package element import ( "fmt" "math" ) -type matrix [][]float64 -type binaryFunc64 func(float64, float64) float64 - -func like(m matrix) matrix { - cols := len(m[0]) - r := make([][]float64, len(m)) - all := make([]float64, len(m)*cols) - for i := range r { - r[i] = all[i*cols : (i+1)*cols] - } - return r +type Matrix struct { + ele []float64 + stride int } -func elementWiseMM(m1, m2 matrix, f binaryFunc64) matrix { +func MatrixFromRows(rows [][]float64) Matrix { + if len(rows) == 0 { + return Matrix{nil, 0} + } + m := Matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} + for rx, row := range rows { + copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) + } + return m +} + +func like(m Matrix) Matrix { + return Matrix{make([]float64, len(m.ele)), m.stride} +} + +func (m Matrix) String() string { + s := "" + for e := 0; e < len(m.ele); e += m.stride { + s += fmt.Sprintf("%6.3f \n", m.ele[e:e+m.stride]) + } + return s +} + +type binaryFunc64 func(float64, float64) float64 + +func elementWiseMM(m1, m2 Matrix, f binaryFunc64) Matrix { z := like(m1) - for rx, row := range m1 { - for cx, ele := range row { - z[rx][cx] = f(ele, m2[rx][cx]) - } + for i, m1e := range m1.ele { + z.ele[i] = f(m1e, m2.ele[i]) } return z } -func elementWiseMS(m matrix, s float64, f binaryFunc64) matrix { +func elementWiseMS(m Matrix, s float64, f binaryFunc64) Matrix { z := like(m) - for rx, row := range m { - for cx, ele := range row { - z[rx][cx] = f(ele, s) - } + for i, e := range m.ele { + z.ele[i] = f(e, s) } return z } @@ -44,55 +57,14 @@ func mul(a, b float64) float64 { return a * b } func div(a, b float64) float64 { return a / b } func exp(a, b float64) float64 { return math.Pow(a, b) } -func ewmmAdd(m1, m2 matrix) matrix { return elementWiseMM(m1, m2, add) } -func ewmmSub(m1, m2 matrix) matrix { return elementWiseMM(m1, m2, sub) } -func ewmmMul(m1, m2 matrix) matrix { return elementWiseMM(m1, m2, mul) } -func ewmmDiv(m1, m2 matrix) matrix { return elementWiseMM(m1, m2, div) } -func ewmmExp(m1, m2 matrix) matrix { return elementWiseMM(m1, m2, exp) } +func AddMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, add) } +func SubMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, sub) } +func MulMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, mul) } +func DivMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, div) } +func ExpMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, exp) } -func ewmsAdd(m matrix, s float64) matrix { return elementWiseMS(m, s, add) } -func ewmsSub(m matrix, s float64) matrix { return elementWiseMS(m, s, sub) } -func ewmsMul(m matrix, s float64) matrix { return elementWiseMS(m, s, mul) } -func ewmsDiv(m matrix, s float64) matrix { return elementWiseMS(m, s, div) } -func ewmsExp(m matrix, s float64) matrix { return elementWiseMS(m, s, exp) } - -func main() { - m1 := matrix{{3, 1, 4}, {1, 5, 9}} - m2 := matrix{{2, 7, 1}, {8, 2, 8}} - fmt.Println("m1:") - m1.print() - fmt.Println("m2:") - m2.print() - fmt.Println("m1 + m2:") - ewmmAdd(m1, m2).print() - fmt.Println("m1 - m2:") - ewmmSub(m1, m2).print() - fmt.Println("m1 * m2:") - ewmmMul(m1, m2).print() - fmt.Println("m1 / m2:") - ewmmDiv(m1, m2).print() - fmt.Println("m1 ^ m2:") - ewmmExp(m1, m2).print() - s := .5 - fmt.Println("s:", s) - fmt.Println("m1 + s") - ewmsAdd(m1, s).print() - fmt.Println("m1 - s:") - ewmsSub(m1, s).print() - fmt.Println("m1 * s:") - ewmsMul(m1, s).print() - fmt.Println("m1 / s:") - ewmsDiv(m1, s).print() - fmt.Println("m1 ^ s:") - ewmsExp(m1, s).print() -} - -func (m matrix) print() { - const f = "%6.3f " - for _, r := range m { - for _, e := range r { - fmt.Printf(f, e) - } - fmt.Println() - } -} +func AddScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, add) } +func SubScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, sub) } +func MulScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, mul) } +func DivScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, div) } +func ExpScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, exp) } diff --git a/Task/Element-wise-operations/Go/element-wise-operations-2.go b/Task/Element-wise-operations/Go/element-wise-operations-2.go index 670c898926..45511482bb 100644 --- a/Task/Element-wise-operations/Go/element-wise-operations-2.go +++ b/Task/Element-wise-operations/Go/element-wise-operations-2.go @@ -2,90 +2,32 @@ package main import ( "fmt" - "math" + + "element" ) -type matrix struct { - ele []float64 - stride int +func h(heading string, m element.Matrix) { + fmt.Println(heading) + fmt.Print(m) } -func matrixFromRows(rows [][]float64) *matrix { - if len(rows) == 0 { - return &matrix{nil, 0} - } - m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} - for rx, row := range rows { - copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) - } - return m -} - -func like(m *matrix) *matrix { - return &matrix{make([]float64, len(m.ele)), m.stride} -} - -func (m *matrix) print(heading string) { - if heading > "" { - fmt.Print("\n", heading, "\n") - } - for e := 0; e < len(m.ele); e += m.stride { - fmt.Printf("%6.3f ", m.ele[e:e+m.stride]) - fmt.Println() - } -} - -type binaryFunc64 func(float64, float64) float64 - -func elementWiseMM(m1, m2 *matrix, f binaryFunc64) *matrix { - z := like(m1) - for i, m1e := range m1.ele { - z.ele[i] = f(m1e, m2.ele[i]) - } - return z -} - -func elementWiseMS(m *matrix, s float64, f binaryFunc64) *matrix { - z := like(m) - for i, e := range m.ele { - z.ele[i] = f(e, s) - } - return z -} - -func add(a, b float64) float64 { return a + b } -func sub(a, b float64) float64 { return a - b } -func mul(a, b float64) float64 { return a * b } -func div(a, b float64) float64 { return a / b } -func exp(a, b float64) float64 { return math.Pow(a, b) } - -func ewmmAdd(m1, m2 *matrix) *matrix { return elementWiseMM(m1, m2, add) } -func ewmmSub(m1, m2 *matrix) *matrix { return elementWiseMM(m1, m2, sub) } -func ewmmMul(m1, m2 *matrix) *matrix { return elementWiseMM(m1, m2, mul) } -func ewmmDiv(m1, m2 *matrix) *matrix { return elementWiseMM(m1, m2, div) } -func ewmmExp(m1, m2 *matrix) *matrix { return elementWiseMM(m1, m2, exp) } - -func ewmsAdd(m *matrix, s float64) *matrix { return elementWiseMS(m, s, add) } -func ewmsSub(m *matrix, s float64) *matrix { return elementWiseMS(m, s, sub) } -func ewmsMul(m *matrix, s float64) *matrix { return elementWiseMS(m, s, mul) } -func ewmsDiv(m *matrix, s float64) *matrix { return elementWiseMS(m, s, div) } -func ewmsExp(m *matrix, s float64) *matrix { return elementWiseMS(m, s, exp) } - func main() { - m1 := matrixFromRows([][]float64{{3, 1, 4}, {1, 5, 9}}) - m2 := matrixFromRows([][]float64{{2, 7, 1}, {8, 2, 8}}) - m1.print("m1:") - m2.print("m2:") - ewmmAdd(m1, m2).print("m1 + m2:") - ewmmSub(m1, m2).print("m1 - m2:") - ewmmMul(m1, m2).print("m1 * m2:") - ewmmDiv(m1, m2).print("m1 / m2:") - ewmmExp(m1, m2).print("m1 ^ m2:") + m1 := element.MatrixFromRows([][]float64{{3, 1, 4}, {1, 5, 9}}) + m2 := element.MatrixFromRows([][]float64{{2, 7, 1}, {8, 2, 8}}) + h("m1:", m1) + h("m2:", m2) + fmt.Println() + h("m1 + m2:", element.AddMatrix(m1, m2)) + h("m1 - m2:", element.SubMatrix(m1, m2)) + h("m1 * m2:", element.MulMatrix(m1, m2)) + h("m1 / m2:", element.DivMatrix(m1, m2)) + h("m1 ^ m2:", element.ExpMatrix(m1, m2)) + fmt.Println() s := .5 - fmt.Println("\ns:", s) - ewmsAdd(m1, s).print("m1 + s:") - ewmsSub(m1, s).print("m1 - s:") - ewmsMul(m1, s).print("m1 * s:") - ewmsDiv(m1, s).print("m1 / s:") - ewmsExp(m1, s).print("m1 ^ s:") + fmt.Println("s:", s) + h("m1 + s:", element.AddScalar(m1, s)) + h("m1 - s:", element.SubScalar(m1, s)) + h("m1 * s:", element.MulScalar(m1, s)) + h("m1 / s:", element.DivScalar(m1, s)) + h("m1 ^ s:", element.ExpScalar(m1, s)) } diff --git a/Task/Element-wise-operations/Ruby/element-wise-operations.rb b/Task/Element-wise-operations/Ruby/element-wise-operations.rb new file mode 100644 index 0000000000..f89f037eb0 --- /dev/null +++ b/Task/Element-wise-operations/Ruby/element-wise-operations.rb @@ -0,0 +1,16 @@ +require 'matrix' + +class Matrix + def element_wise( operator, other ) + Matrix.build(row_size, column_size) do |row, col| + self[row, col].send(operator, other[row, col]) + end + end +end + +m1, m2 = Matrix[[3,1,4],[1,5,9]], Matrix[[2,7,1],[8,2,2]] +puts "m1: #{m1}\nm2: #{m2}\n\n" + +[:+, :-, :*, :/, :fdiv, :**, :%].each do |op| + puts "m1 %-4s m2 = %s" % [op, m1.element_wise(op, m2)] +end diff --git a/Task/Empty-directory/AutoHotkey/empty-directory.ahk b/Task/Empty-directory/AutoHotkey/empty-directory.ahk new file mode 100644 index 0000000000..3f4f887bdf --- /dev/null +++ b/Task/Empty-directory/AutoHotkey/empty-directory.ahk @@ -0,0 +1,7 @@ +MsgBox % isDir_empty(A_ScriptDir)?"true":"false" + +isDir_empty(p) { + Loop, %p%\* , 1 + return 0 + return 1 +} diff --git a/Task/Empty-directory/Clojure/empty-directory.clj b/Task/Empty-directory/Clojure/empty-directory.clj new file mode 100644 index 0000000000..44ea8cf087 --- /dev/null +++ b/Task/Empty-directory/Clojure/empty-directory.clj @@ -0,0 +1,6 @@ +(require '[clojure.java.io :as io]) +(defn empty-dir? [path] + (let [file (io/file path)] + (assert (.exists file)) + (assert (.isDirectory file)) + (-> file .list empty?))) ; .list ignores "." and ".." diff --git a/Task/Empty-directory/Common-Lisp/empty-directory.lisp b/Task/Empty-directory/Common-Lisp/empty-directory.lisp new file mode 100644 index 0000000000..0a40655479 --- /dev/null +++ b/Task/Empty-directory/Common-Lisp/empty-directory.lisp @@ -0,0 +1,3 @@ +(defun empty-directory-p (path) + (and (null (directory (concatenate 'string path "/*"))) + (null (directory (concatenate 'string path "/*/"))))) diff --git a/Task/Empty-directory/REXX/empty-directory.rexx b/Task/Empty-directory/REXX/empty-directory.rexx new file mode 100644 index 0000000000..c5589fa796 --- /dev/null +++ b/Task/Empty-directory/REXX/empty-directory.rexx @@ -0,0 +1,14 @@ +/*REXX pgm checks to see if a directory is empty; if not, lists entries.*/ +parse arg xdir; if xdir='' then xdir='\someDir' /*Any DIR? Use default.*/ +@.=0 /*default in case ADDRESS fails. */ +trace off /*suppress REXX err msg for fails*/ +address system 'DIR' xdir '/b' with output stem @. /*issue the DIR cmd.*/ +if rc\==0 then do /*an error happened?*/ + say '***error!*** from DIR' xDIR /*indicate que pasa.*/ + say 'return code=' rc /*show the ret Code.*/ + exit rc /*exit with the RC.*/ + end /* [↑] bad address.*/ +#=@.rc /*number of entries.*/ +if #==0 then #=' no ' /*use a word, ¬zero.*/ +say center('directory ' xdir " has " # ' entries.',79,'─') +exit @.0+rc /*stick a fork in it, we're done.*/ diff --git a/Task/Empty-program/Objective-C/empty-program-2.m b/Task/Empty-program/Objective-C/empty-program-2.m index a874b81c9f..4231952797 100644 --- a/Task/Empty-program/Objective-C/empty-program-2.m +++ b/Task/Empty-program/Objective-C/empty-program-2.m @@ -2,11 +2,8 @@ int main( int argc, const char *argv[] ) { - NSAutoreleasePool *pool; - - pool = [[NSAutoreleasePool alloc] init]; - NSApp = [NSApplication sharedApplication]; - - [pool release]; + @autoreleasepool { + [NSApplication sharedApplication]; + } return 0; } diff --git a/Task/Empty-string/Dart/empty-string.dart b/Task/Empty-string/Dart/empty-string.dart new file mode 100644 index 0000000000..47c749e5c8 --- /dev/null +++ b/Task/Empty-string/Dart/empty-string.dart @@ -0,0 +1,11 @@ +main() { + var empty = ''; + + if (empty.isEmpty) { + print('it is empty'); + } + + if (empty.isNotEmpty) { + print('it is not empty'); + } +} diff --git a/Task/Enforced-immutability/Bracmat/enforced-immutability.bracmat b/Task/Enforced-immutability/Bracmat/enforced-immutability.bracmat new file mode 100644 index 0000000000..437e2bf070 --- /dev/null +++ b/Task/Enforced-immutability/Bracmat/enforced-immutability.bracmat @@ -0,0 +1,3 @@ +myVar=immutable (m=mutable) immutable; +changed:?(myVar.m); +lst$myVar diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol index 9d54d7c7a0..fc1dc90b52 100644 --- a/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol @@ -1 +1,4 @@ -01 Foo CONSTANT AS "Foo". +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +SPECIAL-NAMES. + SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9. diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol index dc51eeb505..9d54d7c7a0 100644 --- a/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol @@ -1 +1 @@ -78 Foo VALUE "Foo". +01 Foo CONSTANT AS "Foo". diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol index 321ecd9787..dc51eeb505 100644 --- a/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol @@ -1,2 +1 @@ -CONSTANT SECTION. -01 Foo VALUE "Foo". +78 Foo VALUE "Foo". diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-4.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-4.cobol new file mode 100644 index 0000000000..321ecd9787 --- /dev/null +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-4.cobol @@ -0,0 +1,2 @@ +CONSTANT SECTION. +01 Foo VALUE "Foo". diff --git a/Task/Entropy/AutoHotkey/entropy.ahk b/Task/Entropy/AutoHotkey/entropy.ahk new file mode 100644 index 0000000000..220c7c7db2 --- /dev/null +++ b/Task/Entropy/AutoHotkey/entropy.ahk @@ -0,0 +1,18 @@ +MsgBox, % Entropy(1223334444) + +Entropy(n) +{ + a := [], len := StrLen(n), m := n + while StrLen(m) + { + s := SubStr(m, 1, 1) + m := RegExReplace(m, s, "", c) + a[s] := c + } + for key, val in a + { + m := Log(p := val / len) + e -= p * m / Log(2) + } + return, e +} diff --git a/Task/Entropy/CoffeeScript/entropy.coffee b/Task/Entropy/CoffeeScript/entropy.coffee new file mode 100644 index 0000000000..0f6855ac61 --- /dev/null +++ b/Task/Entropy/CoffeeScript/entropy.coffee @@ -0,0 +1,13 @@ +entropy = (s) -> + freq = (s) -> + result = {} + for ch in s.split "" + result[ch] ?= 0 + result[ch]++ + return result + + frq = freq s + n = s.length + ((frq[f]/n for f of frq).reduce ((e, p) -> e - p * Math.log(p)), 0) * Math.LOG2E + +console.log "The entropy of the string '1223334444' is #{entropy '1223334444'}" diff --git a/Task/Entropy/D/entropy.d b/Task/Entropy/D/entropy.d index b65b725195..1caad78b15 100644 --- a/Task/Entropy/D/entropy.d +++ b/Task/Entropy/D/entropy.d @@ -1,13 +1,13 @@ import std.stdio, std.algorithm, std.math; double entropy(T)(T[] s) -/*pure nothrow*/ if (__traits(compiles, sort(s))) { +/*pure nothrow*/ if (__traits(compiles, s.sort())) { return s .sort() .group - .map!(g => g[1] / cast(double)s.length) - .map!(p => -p * log2(p)) - .reduce!q{a + b}; + .map!(g => g[1] / double(s.length)) + .map!(p => -p * p.log2) + .sum; } void main() { diff --git a/Task/Entropy/Rust/entropy.rust b/Task/Entropy/Rust/entropy.rust new file mode 100644 index 0000000000..ecca6a0bf1 --- /dev/null +++ b/Task/Entropy/Rust/entropy.rust @@ -0,0 +1,16 @@ +// works for Rust 0.9 +fn entropy(s: &str) -> f32 { + let mut entropy: f32 = 0.0; + let mut histogram = [0, ..256]; + let len = s.len(); + + for i in range(0, len) { histogram[s[i]] += 1; } + for i in range(0, 256) { + if histogram[i] > 0 { + let ratio = (histogram[i] as f32 / len as f32) as f32; + entropy -= (ratio * log2(ratio)) as f32; + } + } + + entropy +} diff --git a/Task/Enumerations/Bracmat/enumerations.bracmat b/Task/Enumerations/Bracmat/enumerations.bracmat new file mode 100644 index 0000000000..11975acd04 --- /dev/null +++ b/Task/Enumerations/Bracmat/enumerations.bracmat @@ -0,0 +1 @@ +fruits=apple+banana+cherry; diff --git a/Task/Enumerations/D/enumerations.d b/Task/Enumerations/D/enumerations.d index 934b8914d7..6b9d4e9bfb 100644 --- a/Task/Enumerations/D/enumerations.d +++ b/Task/Enumerations/D/enumerations.d @@ -1,17 +1,17 @@ -// Anonymous -enum { APPLE, BANANA, CHERRY } - -// Named (commonlu used enum in D) (uint) +// Named (commonly used enum in D) (int). enum Fruits1 { apple, banana, cherry } -// Named with specified values (uint) +// Anonymous, as in C. +enum { APPLE, BANANA, CHERRY } + +// Named with specified values (int). enum Fruits2 { apple = 0, banana = 10, cherry = 20 } -// Named, typed and with specified values +// Named, typed and with specified values. enum Fruits3 : ubyte { apple = 0, banana = 100, cherry = 200 } void main() { static assert(CHERRY == 2); - int f1 = Fruits2.banana; // No error - // Fruits2 f2 = 1; // Compilation error + int f1 = Fruits2.banana; // No error. + // Fruits2 f2 = 1; // Error: cannot implicitly convert. } diff --git a/Task/Enumerations/JavaScript/enumerations.js b/Task/Enumerations/JavaScript/enumerations.js index d647e1d8c0..493039a3ed 100644 --- a/Task/Enumerations/JavaScript/enumerations.js +++ b/Task/Enumerations/JavaScript/enumerations.js @@ -1 +1,2 @@ -var fruits = { apple : 0, banana : 1, cherry : 2 }; +var fruits = { APPLE : 0, BANANA : 1, CHERRY : 2 }; +Object.freeze(fruits); diff --git a/Task/Enumerations/Rust/enumerations.rust b/Task/Enumerations/Rust/enumerations.rust new file mode 100644 index 0000000000..f086eb674d --- /dev/null +++ b/Task/Enumerations/Rust/enumerations.rust @@ -0,0 +1,5 @@ +enum Fruits { + Apple, + Banana, + Cherry +} diff --git a/Task/Environment-variables/Maple/environment-variables.maple b/Task/Environment-variables/Maple/environment-variables.maple new file mode 100644 index 0000000000..e887f2bce6 --- /dev/null +++ b/Task/Environment-variables/Maple/environment-variables.maple @@ -0,0 +1 @@ +getenv("PATH"); diff --git a/Task/Environment-variables/TXR/environment-variables-4.txr b/Task/Environment-variables/TXR/environment-variables-4.txr new file mode 100644 index 0000000000..0618137df2 --- /dev/null +++ b/Task/Environment-variables/TXR/environment-variables-4.txr @@ -0,0 +1,2 @@ +$ ./txr -p "(mapcar (env-hash) '(\"HOME\" \"USER\" \"PATH\"))" +("/home/kaz" "kaz" "/home/kaz/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/kaz/bin" diff --git a/Task/Equilibrium-index/AutoHotkey/equilibrium-index-1.ahk b/Task/Equilibrium-index/AutoHotkey/equilibrium-index-1.ahk new file mode 100644 index 0000000000..f10d6ddcc4 --- /dev/null +++ b/Task/Equilibrium-index/AutoHotkey/equilibrium-index-1.ahk @@ -0,0 +1,14 @@ +Equilibrium_index(list, BaseIndex=0){ + StringSplit, A, list, `, + Loop % A0 { + i := A_Index , Pre := Post := 0 + loop, % A0 + if (A_Index < i) + Pre += A%A_Index% + else if (A_Index > i) + Post += A%A_Index% + if (Pre = Post) + Res .= (Res?", ":"") i - (BaseIndex?0:1) + } + return Res +} diff --git a/Task/Equilibrium-index/AutoHotkey/equilibrium-index-2.ahk b/Task/Equilibrium-index/AutoHotkey/equilibrium-index-2.ahk new file mode 100644 index 0000000000..6acf7c1fa1 --- /dev/null +++ b/Task/Equilibrium-index/AutoHotkey/equilibrium-index-2.ahk @@ -0,0 +1,2 @@ +list = -7, 1, 5, 2, -4, 3, 0 +MsgBox % Equilibrium_index(list) diff --git a/Task/Equilibrium-index/D/equilibrium-index-1.d b/Task/Equilibrium-index/D/equilibrium-index-1.d index edbcc1112a..4040d82b1d 100644 --- a/Task/Equilibrium-index/D/equilibrium-index-1.d +++ b/Task/Equilibrium-index/D/equilibrium-index-1.d @@ -1,9 +1,7 @@ import std.stdio, std.algorithm, std.range, std.functional; -alias S = curry!(reduce!q{a + b}, 0); // Sum. - auto equilibrium(Range)(Range r) pure nothrow { - return r.length.iota.filter!(i => r[0 .. i].S == r[i + 1 .. $].S); + return r.length.iota.filter!(i => r[0..i].sum == r[i+1 .. $].sum); } void main() { diff --git a/Task/Equilibrium-index/D/equilibrium-index-2.d b/Task/Equilibrium-index/D/equilibrium-index-2.d index a6d675f215..07794ffa69 100644 --- a/Task/Equilibrium-index/D/equilibrium-index-2.d +++ b/Task/Equilibrium-index/D/equilibrium-index-2.d @@ -2,7 +2,7 @@ import std.stdio, std.algorithm; size_t[] equilibrium(T)(in T[] items) @safe pure nothrow { size_t[] result; - T left = 0, right = reduce!q{a + b}(cast(T)0, items); + T left = 0, right = items.sum; foreach (immutable i, e; items) { right -= e; diff --git a/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d b/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d index 9a5b80af63..cb1311edf2 100644 --- a/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d +++ b/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d @@ -1,12 +1,10 @@ -import std.stdio; - int ethiopian(int n1, int n2) pure nothrow in { - assert(n1 >= 0, "muliplier cannot be negative"); + assert(n1 >= 0, "Multiplier can't be negative"); } body { - static int doubleNum(in int n) pure nothrow { return n * 2; } - static int halveNum(in int n) pure nothrow { return n / 2; } - static bool isEven(in int n) pure nothrow { return !(n & 1); } + static enum doubleNum = (in int n) pure nothrow => n * 2; + static enum halveNum = (in int n) pure nothrow => n / 2; + static enum isEven = (in int n) pure nothrow => !(n & 1); int result; while (n1 >= 1) { @@ -17,14 +15,14 @@ in { } return result; -} - -unittest { +} unittest { assert(ethiopian(77, 54) == 77 * 54); assert(ethiopian(8, 923) == 8 * 923); assert(ethiopian(64, -4) == 64 * -4); } void main() { + import std.stdio; + writeln("17 ethiopian 34 is ", ethiopian(17, 34)); } diff --git a/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l b/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l new file mode 100644 index 0000000000..28a704958f --- /dev/null +++ b/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l @@ -0,0 +1,14 @@ +(defun even-p (n) + (= (mod n 2) 0)) +(defun halve (n) + (floor n 2)) +(defun double (n) + (* n 2)) +(defun ethiopian-multiplication (l r) + (setq sum 0) + (while (>= l 1) + (unless (even-p l) + (setq sum (+ r sum))) + (setq l (halve l)) + (setq r (double r))) + (print sum)) diff --git a/Task/Ethiopian-multiplication/Objective-C/ethiopian-multiplication.m b/Task/Ethiopian-multiplication/Objective-C/ethiopian-multiplication.m index 6a28086a2d..d6b78d73ea 100644 --- a/Task/Ethiopian-multiplication/Objective-C/ethiopian-multiplication.m +++ b/Task/Ethiopian-multiplication/Objective-C/ethiopian-multiplication.m @@ -1,12 +1,11 @@ #import -#import BOOL iseven(int x) { return (x&1) == 0; } -@interface EthiopicMult : Object +@interface EthiopicMult : NSObject + (int)mult: (int)plier by: (int)plicand; + (int)halve: (int)a; + (int)double: (int)a; @@ -37,6 +36,8 @@ BOOL iseven(int x) int main() { - printf("%d\n", [EthiopicMult mult: 17 by: 34]); + @autoreleasepool { + printf("%d\n", [EthiopicMult mult: 17 by: 34]); + } return 0; } diff --git a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-1.pl6 b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-1.pl6 index feeb3bb370..1fb06da87d 100644 --- a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-1.pl6 +++ b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-1.pl6 @@ -2,7 +2,7 @@ sub halve (Int $n is rw) { $n div= 2 } sub double (Int $n is rw) { $n *= 2 } sub even (Int $n --> Bool) { $n %% 2 } -sub ethiopicmult (Int $a is copy, Int $b is copy --> Int) { +sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) { my Int $r = 0; while $a { even $a or $r += $b; @@ -11,3 +11,5 @@ sub ethiopicmult (Int $a is copy, Int $b is copy --> Int) { } return $r; } + +say ethiopic-mult(17,34); diff --git a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-2.pl6 b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-2.pl6 index ab03be1f6d..c33ddd03d4 100644 --- a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-2.pl6 +++ b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-2.pl6 @@ -1,4 +1,4 @@ -sub ethiopicmult { +sub ethiopic-mult { my &halve = * div= 2; my &double = * *= 2; my &even = * %% 2; @@ -11,3 +11,5 @@ sub ethiopicmult { double $b; } } + +say ethiopic-mult(17,34); diff --git a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 index efc8d0987d..930bfadeba 100644 --- a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 +++ b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 @@ -2,8 +2,10 @@ sub halve { $^n div 2 } sub double { $^n * 2 } sub even { $^n %% 2 } -sub ethiopicmult ($a, $b) { - [+] - map { $^column_2 if !even $^column_1 }, - zip($a, &halve ... 0; $b, &double ... *); +sub ethiopic-mult ($a, $b) { + [+] ($b, &double ... *) + Z* + ($a, &halve ... 0).map: { not even $^n } } + +say ethiopic-mult(17,34); diff --git a/Task/Evaluate-binomial-coefficients/Maple/evaluate-binomial-coefficients.maple b/Task/Evaluate-binomial-coefficients/Maple/evaluate-binomial-coefficients.maple new file mode 100644 index 0000000000..ce14305276 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Maple/evaluate-binomial-coefficients.maple @@ -0,0 +1,3 @@ +convert(binomial(n,k),factorial); + +binomial(5,3); diff --git a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl index 05b018bf4d..821299185f 100644 --- a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl +++ b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl @@ -1,7 +1,7 @@ sub binomial { use bigint; my ($r, $n, $k) = (1, @_); - for (1 .. $k) { $r *= $n + 1 - $_, $r /= $_ } + for (1 .. $k) { $r *= $n + 1 - $_; $r /= $_ } $r; } diff --git a/Task/Evaluate-binomial-coefficients/TXR/evaluate-binomial-coefficients-1.txr b/Task/Evaluate-binomial-coefficients/TXR/evaluate-binomial-coefficients-1.txr new file mode 100644 index 0000000000..0a1d9d05d2 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/TXR/evaluate-binomial-coefficients-1.txr @@ -0,0 +1,2 @@ +$ txr -p '(n-choose-k 20 15)' +15504 diff --git a/Task/Evaluate-binomial-coefficients/TXR/evaluate-binomial-coefficients-2.txr b/Task/Evaluate-binomial-coefficients/TXR/evaluate-binomial-coefficients-2.txr new file mode 100644 index 0000000000..65582427f6 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/TXR/evaluate-binomial-coefficients-2.txr @@ -0,0 +1,2 @@ +$ txr -p '(n-perm-k 20 15)' +20274183401472000 diff --git a/Task/Even-or-odd/BBC-BASIC/even-or-odd.bbc b/Task/Even-or-odd/BBC-BASIC/even-or-odd.bbc index c46727f99a..b477b0fc66 100644 --- a/Task/Even-or-odd/BBC-BASIC/even-or-odd.bbc +++ b/Task/Even-or-odd/BBC-BASIC/even-or-odd.bbc @@ -1,6 +1,4 @@ -=={{header|BBC BASIC}}== -{{works with|BBC BASIC for Windows}} - IF FNisodd%(14) PRINT "14 is odd" ELSE PRINT "14 is even" + IF FNisodd%(14) PRINT "14 is odd" ELSE PRINT "14 is even" IF FNisodd%(15) PRINT "15 is odd" ELSE PRINT "15 is even" IF FNisodd#(9876543210#) PRINT "9876543210 is odd" ELSE PRINT "9876543210 is even" IF FNisodd#(9876543211#) PRINT "9876543211 is odd" ELSE PRINT "9876543211 is even" diff --git a/Task/Even-or-odd/Prolog/even-or-odd-1.pro b/Task/Even-or-odd/Prolog/even-or-odd-1.pro new file mode 100644 index 0000000000..94c872c67d --- /dev/null +++ b/Task/Even-or-odd/Prolog/even-or-odd-1.pro @@ -0,0 +1,3 @@ + even(N) :- + (between(0, inf, N); integer(N) ), + 0 is N mod 2. diff --git a/Task/Even-or-odd/Prolog/even-or-odd-2.pro b/Task/Even-or-odd/Prolog/even-or-odd-2.pro new file mode 100644 index 0000000000..e30c96d66a --- /dev/null +++ b/Task/Even-or-odd/Prolog/even-or-odd-2.pro @@ -0,0 +1 @@ + odd(N) :- N = 0 -> false; 0 is lsb(abs(N)). diff --git a/Task/Even-or-odd/Smalltalk/even-or-odd-1.st b/Task/Even-or-odd/Smalltalk/even-or-odd-1.st new file mode 100644 index 0000000000..a7dede846c --- /dev/null +++ b/Task/Even-or-odd/Smalltalk/even-or-odd-1.st @@ -0,0 +1,2 @@ +5 even +5 odd diff --git a/Task/Even-or-odd/Smalltalk/even-or-odd-2.st b/Task/Even-or-odd/Smalltalk/even-or-odd-2.st new file mode 100644 index 0000000000..fe1a1379d6 --- /dev/null +++ b/Task/Even-or-odd/Smalltalk/even-or-odd-2.st @@ -0,0 +1,2 @@ +Number>>even + ^((self digitAt: 1) bitAnd: 1) = 0 diff --git a/Task/Events/REXX/events.rexx b/Task/Events/REXX/events.rexx new file mode 100644 index 0000000000..beb0a9d19e --- /dev/null +++ b/Task/Events/REXX/events.rexx @@ -0,0 +1,16 @@ +/*REXX program shows a method of handling events (this is time-driven). */ +signal on halt /*allow the user to HALT the pgm.*/ +parse arg timeEvent /*allow "event" to be specified. */ +if timeEvent='' then timeEvent=5 /*if not specified, use default. */ + +event?: do forever /*determine if an event occurred.*/ + theEvent=right(time(),1) /*maybe it's an event, maybe not.*/ + if pos(theEvent,timeEvent)\==0 then signal happening + end /*forever*/ + +say 'Control should never get here!' /*This is a logic no-no occurance*/ +halt: say 'program halted.'; exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────HAPPENING processing───────────────*/ +happening: say 'an event occurred at' time()", the event is:" theEvent + do while theEvent==right(time(),1); /*process the event here.*/ nop;end +signal event? /*see if another event happened. */ diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Objective-C/exceptions-catch-an-exception-thrown-in-a-nested-call.m b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Objective-C/exceptions-catch-an-exception-thrown-in-a-nested-call.m index e5cbeb531b..9d55e94fa2 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Objective-C/exceptions-catch-an-exception-thrown-in-a-nested-call.m +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Objective-C/exceptions-catch-an-exception-thrown-in-a-nested-call.m @@ -27,17 +27,17 @@ void bar(int i) { void baz(int i) { if (i == 0) - @throw [[U0 new] autorelease]; + @throw [U0 new]; else - @throw [[U1 new] autorelease]; + @throw [U1 new]; } int main (int argc, const char * argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - foo(); + foo(); - [pool drain]; + } return 0; } diff --git a/Task/Exceptions/ALGOL-68/exceptions-1.alg b/Task/Exceptions/ALGOL-68/exceptions-1.alg index 05ec0d08bf..6a9593a778 100644 --- a/Task/Exceptions/ALGOL-68/exceptions-1.alg +++ b/Task/Exceptions/ALGOL-68/exceptions-1.alg @@ -1,6 +1,9 @@ # a user defined object # -MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... ); +MODE FOO = STRUCT ( ... ) + FOOOBJECTNEW = STRUCT (FOOMEND foo exception x mended, FOO instance), + FOOOBJECT = REF FOOOBJECTNEW, + FOOMEND = PROC (FOOOBJECT)BOOL; -PROC on foo event = (REF OBJECTFOO foo, PROC (REF OBJECTFOO)BOOL foo event)VOID: ( - foo event mended OF foo := foo event +PROC on foo exception x = (FOOOBJECT foo, PROC (FOOOBJECT)BOOL foo exception x mend)VOID: ( + foo exception x mended OF foo := foo exception x mend ); diff --git a/Task/Exceptions/ALGOL-68/exceptions-2.alg b/Task/Exceptions/ALGOL-68/exceptions-2.alg index 79bb2f0a40..db1870bcc2 100644 --- a/Task/Exceptions/ALGOL-68/exceptions-2.alg +++ b/Task/Exceptions/ALGOL-68/exceptions-2.alg @@ -1,8 +1,4 @@ -OBJECTFOO foo proxy := foo base; # event routines are specific to an foo # - -on foo event(foo proxy, raise foo event); - -WHILE TRUE DO - # now raise example foo event # - IF NOT (foo event mended OF foo proxy)(foo proxy) THEN undefined # trace back # FI -OD; +PROC raise foo exception x = (FOOOBJECT foo)BOOL: + IF NOT (foo exception x mended OF foo instance)(foo instance) THEN + except foo exception x + FI diff --git a/Task/Exceptions/ALGOL-68/exceptions-3.alg b/Task/Exceptions/ALGOL-68/exceptions-3.alg index 95130a1305..ede38d00f4 100644 --- a/Task/Exceptions/ALGOL-68/exceptions-3.alg +++ b/Task/Exceptions/ALGOL-68/exceptions-3.alg @@ -1,5 +1,9 @@ -... -except foo event: - IF ... THEN # Alas, cannot handle it here continue propagation of # - IF NOT (foo event mended OF foo base)(foo base) THEN undefined # trace back # FI - FI +FOOOBJECTNEW foo instance := foo base; # exception x routines are specific to a foo # + +FOOMEND prior foo exception x mend = foo exception x mended OF foo; +on foo exception x(foo instance, raise foo exception x); + +WHILE TRUE DO + # now manually raise example "foo exception x" # + raise foo exception x(foo instance) +OD; diff --git a/Task/Exceptions/ALGOL-68/exceptions-4.alg b/Task/Exceptions/ALGOL-68/exceptions-4.alg index adf1f894e3..c23e6dca0f 100644 --- a/Task/Exceptions/ALGOL-68/exceptions-4.alg +++ b/Task/Exceptions/ALGOL-68/exceptions-4.alg @@ -1,7 +1,8 @@ -PROC raise foo event(REF OBJECTFOO foo)BOOL: - IF mend foo(foo) THEN - TRUE # continue # - ELSE - except foo event - FALSE # OR fall back to default event routine # - FI + on foo exception x(foo instance, prior foo exception x mend); +... EXIT +except foo exception x: + SKIP # exception x caught code here ... # +# to continue to propagate an exception x is a bit more problematic...# +# and requires nesting/restoring prior "raise foo exception x"# + on foo exception x(foo instance, prior foo exception x mend); + raise foo exception x(foo instance) diff --git a/Task/Execute-Brain----/AWK/execute-brain----.awk b/Task/Execute-Brain----/AWK/execute-brain----.awk index 1efc5b4c0d..f13b6b217b 100644 --- a/Task/Execute-Brain----/AWK/execute-brain----.awk +++ b/Task/Execute-Brain----/AWK/execute-brain----.awk @@ -1,5 +1,6 @@ BEGIN { - compile(ARGV[1]) + bf=ARGV[1]; ARGV[1] = "" + compile(bf) execute() } @@ -48,10 +49,30 @@ function execute( pc,p,i) { else if(i == ".") printf("%c", arena[p]) else if(i == ",") { - "dd bs=1 count=1 2>/dev/null | xd -1d" | getline - sub(/^0*/, "", $2) - arena[p] = 0 + $2 - close("dd bs=1 count=1 2>/dev/null | xd -1d") + while(1) { + if (goteof) break + if (!gotline) { + gotline = getline + if(!gotline) goteof = 1 + if (goteof) break + line = $0 + } + if (line == "") { + gotline=0 + m[p]=10 + break + } + if (!genord) { + for(i=1; i<256; i++) + ord[sprintf("%c",i)] = i + genord=1 + } + c = substr(line, 1, 1) + line=substr(line, 2) + arena[p] = ord[c] + break + } + } else if((i == "[" && arena[p] == 0) || (i == "]" && arena[p] != 0)) pc = jump[pc] diff --git a/Task/Execute-Brain----/AppleScript/execute-brain----.applescript b/Task/Execute-Brain----/AppleScript/execute-brain----.applescript new file mode 100644 index 0000000000..2027e8673b --- /dev/null +++ b/Task/Execute-Brain----/AppleScript/execute-brain----.applescript @@ -0,0 +1,125 @@ +set codeString to text returned of (display dialog "Enter BF code:" buttons "OK" default answer "") +set inputString to text returned of (display dialog "Enter input string" buttons "OK" default answer "") +set codePointer to 1 +set loopPosns to {} +set tape to {} +set tapePointer to 1 +set output to {} +set inputPointer to 1 +set step to 0 + +set thePath to (path to desktop as Unicode text) & "log.txt" +set debug to (open for access file thePath with write permission) + +write (step as string) & " (" & ((codePointer - 1) as string) & "): (The program contains " & ((length of codeString) as string) & " instructions.) +" to debug + +set step to 1 + +on betterMod(x, y) -- so -2 mod 256 is 254 instead of -2 + local x + local y + try + return -y * (round (x / y) rounding down) + x + on error eMsg number eNum + error "Can't call betterMod() on " & eMsg number eNum + end try +end betterMod + +repeat while codePointer ≤ length of codeString + set theChar to (get character codePointer of codeString) + + if (theChar = "+") then + repeat while (length of tape < tapePointer) + set tape to tape & 0 + end repeat + set item tapePointer of tape to betterMod(((get item tapePointer of tape) + 1), 256) + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | a[" & ((tapePointer - 1) as string) & "]= " & ((item tapePointer of tape) as string) & " +" to debug + else if (theChar = "-") then + repeat while (length of tape < tapePointer) + set tape to tape & 0 + end repeat + set item tapePointer of tape to betterMod(((get item tapePointer of tape) - 1), 256) + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | a[" & ((tapePointer - 1) as string) & "]= " & ((item tapePointer of tape) as string) & " +" to debug + else if (theChar = "<") then + set tapePointer to tapePointer - 1 + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | array pos. now " & ((tapePointer - 1) as string) & " +" to debug + + else if (theChar = ">") then + set tapePointer to tapePointer + 1 + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | array pos. now " & ((tapePointer - 1) as string) & " +" to debug + + else if (theChar = "[") then + repeat while (length of tape < tapePointer) + set tape to tape & 0 + end repeat + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | Array[" & ((tapePointer - 1) as string) & "] is '" & ((item tapePointer of tape) as string) & "'" to debug + if (item tapePointer of tape ≠ 0) then + set loopPosns to loopPosns & codePointer + write " ** Loop nesting level: " & (((length of loopPosns) - 1) as string) & ". +" to debug + else + write " +" & (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | Not entering a loop but skipping to instruction number " to debug + set matchLoops to 1 + repeat while matchLoops ≠ 0 + set codePointer to codePointer + 1 + if (item codePointer of codeString = "[") then + set matchLoops to matchLoops + 1 + else if (item codePointer of codeString = "]") then + set matchLoops to matchLoops - 1 + end if + end repeat + write ((codePointer - 1) as string) & " +" to debug + end if + + else if (theChar = "]") then + repeat while (length of tape < tapePointer) + set tape to tape & 0 + end repeat + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | Array[" & ((tapePointer - 1) as string) & "] is '" & ((item tapePointer of tape) as string) & "' +" to debug + if (item tapePointer of tape ≠ 0) then + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | looping back to " & (((item (length of loopPosns) of loopPosns) - 1) as string) & " +" to debug + set codePointer to (item (length of loopPosns) of loopPosns) - 1 + end if + if (length of loopPosns > 1) then + set loopPosns to items 1 thru ((length of loopPosns) - 1) of loopPosns + else + set loopPosns to {} + end if + + else if (theChar = ".") then + repeat while (length of tape < tapePointer) + set tape to tape & 0 + end repeat + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | output '" & ((item tapePointer of tape) as string) & "' " & string id (item tapePointer of tape) & " +" to debug + set output to output & item tapePointer of tape + + else if (theChar = ",") then + repeat while (length of tape < tapePointer) + set tape to tape & 0 + end repeat + if (inputPointer > length of inputString) then + set inputPointer to 1 + end if + set item tapePointer of tape to id of item inputPointer of inputString + set inputPointer to inputPointer + 1 + write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | read in " & string id (item tapePointer of tape) & " (" & ((item tapePointer of tape) as string) & ") +" to debug + end if + + set codePointer to codePointer + 1 + set step to step + 1 +end repeat + +set strout to string id output +display dialog strout +close access debug diff --git a/Task/Execute-Brain----/PHP/execute-brain----.php b/Task/Execute-Brain----/PHP/execute-brain----.php index 6babdd9bcc..596ecfbffa 100644 --- a/Task/Execute-Brain----/PHP/execute-brain----.php +++ b/Task/Execute-Brain----/PHP/execute-brain----.php @@ -43,4 +43,10 @@ function brainfuck($source, $input='') { $output); return $output; } -?> + +$code = " + >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> + >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. +"; +$inp = '123'; +print brainfuck( $code, $inp ); diff --git a/Task/Execute-Brain----/Seed7/execute-brain----.seed7 b/Task/Execute-Brain----/Seed7/execute-brain----.seed7 index 2c8d1a1531..c83f429a19 100644 --- a/Task/Execute-Brain----/Seed7/execute-brain----.seed7 +++ b/Task/Execute-Brain----/Seed7/execute-brain----.seed7 @@ -2,7 +2,7 @@ $ include "seed7_05.s7i"; const proc: brainF (in string: source, inout file: input, inout file: output) is func local - var array char: memory is 100000 times '\0\'; + var array char: memory is 100000 times '\0;'; var integer: dataPointer is 50000; var integer: instructionPointer is 1; var integer: nestingLevel is 0; @@ -16,7 +16,7 @@ const proc: brainF (in string: source, inout file: input, inout file: output) is when {'.'}: write(output, memory[dataPointer]); when {','}: memory[dataPointer] := getc(input); when {'['}: # Forward if zero at dataPointer - if memory[dataPointer] = '\0\' then + if memory[dataPointer] = '\0;' then nestingLevel := 1; repeat incr(instructionPointer); @@ -27,7 +27,7 @@ const proc: brainF (in string: source, inout file: input, inout file: output) is until nestingLevel = 0; end if; when {']'}: # Backward if non-zero at dataPointer - if memory[dataPointer] <> '\0\' then + if memory[dataPointer] <> '\0;' then nestingLevel := 1; repeat decr(instructionPointer); diff --git a/Task/Execute-SNUSP/Seed7/execute-snusp.seed7 b/Task/Execute-SNUSP/Seed7/execute-snusp.seed7 index 583d6faeb6..33b273eedb 100644 --- a/Task/Execute-SNUSP/Seed7/execute-snusp.seed7 +++ b/Task/Execute-SNUSP/Seed7/execute-snusp.seed7 @@ -13,7 +13,7 @@ const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input var integer: row is 0; begin instructions := split(sourceCode, "\n"); - memory := memSize times '\0\'; + memory := memSize times '\0;'; for key row range instructions do if pos(instructions[row], '$') <> 0 then @@ -39,7 +39,7 @@ const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input columnDir := helpDir; when {'!'}: instrPtrRow +:= rowDir; instrPtrColumn +:= columnDir; - when {'?'}: if memory[dataPointer] = '\0\' then + when {'?'}: if memory[dataPointer] = '\0;' then instrPtrRow +:= rowDir; instrPtrColumn +:= columnDir; end if; diff --git a/Task/Execute-a-system-command/Batch-File/execute-a-system-command.bat b/Task/Execute-a-system-command/Batch-File/execute-a-system-command.bat new file mode 100644 index 0000000000..0d2ecd7fd0 --- /dev/null +++ b/Task/Execute-a-system-command/Batch-File/execute-a-system-command.bat @@ -0,0 +1 @@ +dir diff --git a/Task/Execute-a-system-command/Maple/execute-a-system-command.maple b/Task/Execute-a-system-command/Maple/execute-a-system-command.maple new file mode 100644 index 0000000000..d48e541db0 --- /dev/null +++ b/Task/Execute-a-system-command/Maple/execute-a-system-command.maple @@ -0,0 +1 @@ +ssystem("dir"); diff --git a/Task/Execute-a-system-command/Objective-C/execute-a-system-command-1.m b/Task/Execute-a-system-command/Objective-C/execute-a-system-command-1.m index 36e0ca033e..f649fe42c8 100644 --- a/Task/Execute-a-system-command/Objective-C/execute-a-system-command-1.m +++ b/Task/Execute-a-system-command/Objective-C/execute-a-system-command-1.m @@ -1,5 +1,5 @@ void runls() { [[NSTask launchedTaskWithLaunchPath:@"/bin/ls" - arguments:[NSArray array]] waitUntilExit]; + arguments:@[]] waitUntilExit]; } diff --git a/Task/Execute-a-system-command/Objective-C/execute-a-system-command-2.m b/Task/Execute-a-system-command/Objective-C/execute-a-system-command-2.m index c015d92bbd..755a4447b1 100644 --- a/Task/Execute-a-system-command/Objective-C/execute-a-system-command-2.m +++ b/Task/Execute-a-system-command/Objective-C/execute-a-system-command-2.m @@ -1,6 +1,6 @@ void runSystemCommand(NSString *cmd) { [[NSTask launchedTaskWithLaunchPath:@"/bin/sh" - arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]] + arguments:@[@"-c", cmd]] waitUntilExit]; } diff --git a/Task/Execute-a-system-command/Objective-C/execute-a-system-command-3.m b/Task/Execute-a-system-command/Objective-C/execute-a-system-command-3.m index 96dd051aae..e5d1068b13 100644 --- a/Task/Execute-a-system-command/Objective-C/execute-a-system-command-3.m +++ b/Task/Execute-a-system-command/Objective-C/execute-a-system-command-3.m @@ -3,17 +3,15 @@ void runSystemCommand(NSString *cmd) { [[NSTask launchedTaskWithLaunchPath:@"/bin/sh" - arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]] + arguments:@[@"-c", cmd]] waitUntilExit]; } int main(int argc, const char **argv) { - NSAutoreleasePool *pool; + @autoreleasepool { - pool = [NSAutoreleasePool new]; - - runSystemCommand(@"ls"); - [pool release]; + runSystemCommand(@"ls"); + } return 0; } diff --git a/Task/Exponentiation-operator/Befunge/exponentiation-operator.bf b/Task/Exponentiation-operator/Befunge/exponentiation-operator.bf new file mode 100644 index 0000000000..0cfaeb2a73 --- /dev/null +++ b/Task/Exponentiation-operator/Befunge/exponentiation-operator.bf @@ -0,0 +1,5 @@ +v v \< +>&:32p&1-\>32g*\1-:| + $ + . + @ diff --git a/Task/Exponentiation-operator/Retro/exponentiation-operator-3.retro b/Task/Exponentiation-operator/Retro/exponentiation-operator-3.retro new file mode 100644 index 0000000000..8892cf2cf6 --- /dev/null +++ b/Task/Exponentiation-operator/Retro/exponentiation-operator-3.retro @@ -0,0 +1,7 @@ +: pow ( n m -- n^m ) +1 2rot +[ dup 1 and 0 <> + [ [ tuck * swap ] dip ] ifTrue + [ dup * ] dip 1 >> dup 0 <> +] while +drop drop ; diff --git a/Task/Extreme-floating-point-values/D/extreme-floating-point-values-1.d b/Task/Extreme-floating-point-values/D/extreme-floating-point-values-1.d index ea6e5fc545..0df8bab317 100644 --- a/Task/Extreme-floating-point-values/D/extreme-floating-point-values-1.d +++ b/Task/Extreme-floating-point-values/D/extreme-floating-point-values-1.d @@ -7,9 +7,9 @@ import std.math: NaN, getNaNPayload; void show(T)() { static string toHex(T x) { string result; - ubyte* ptr = cast(ubyte*)&x; - foreach (i; 0 .. T.sizeof) - result = format("%02x", ptr[i]) ~ result; + auto ptr = cast(ubyte*)&x; + foreach_reverse (immutable i; 0 .. T.sizeof) + result ~= format("%02x", ptr[i]); return result; } @@ -17,16 +17,16 @@ void show(T)() { writeln("Computed extreme ", name, " values:"); T zero = 0.0; - T pos_inf = (cast(T)1.0) / zero; + T pos_inf = T(1.0) / zero; writeln(" ", name, " +oo = ", pos_inf); T neg_inf = -pos_inf; writeln(" ", name, " -oo = ", neg_inf); - T pos_zero = (cast(T)1.0) / pos_inf; + T pos_zero = T(1.0) / pos_inf; writeln(" ", name, " +0 (pos_zero) = ", pos_zero); - T neg_zero = (cast(T)1.0) / neg_inf; + T neg_zero = T(1.0) / neg_inf; writeln(" ", name, " -0 = ", neg_zero); T nan = zero / pos_zero; @@ -36,8 +36,8 @@ void show(T)() { writeln("Some ", T.stringof, " properties and literals:"); writeln(" ", name, " +oo = ", T.infinity); writeln(" ", name, " -oo = ", -T.infinity); - writeln(" ", name, " +0 = ", (cast(T)0.0)); - writeln(" ", name, " -0 = ", (cast(T)-0.0)); + writeln(" ", name, " +0 = ", T(0.0)); + writeln(" ", name, " -0 = ", T(-0.0)); writefln(" " ~ name ~ " nan = %f %s", T.nan, toHex(T.nan)); writefln(" " ~ name ~ " init = %f %s", T.init, toHex(T.init)); writeln(" ", name, " epsilon = ", T.epsilon); @@ -48,17 +48,17 @@ void show(T)() { } void main() { - show!float(); - show!double(); - show!real(); + show!float; + show!double; + show!real; writeln("Largest possible payload for float, double and real NaNs:"); - float f1 = NaN(0x3F_FFFF); + immutable float f1 = NaN(0x3F_FFFF); writeln(getNaNPayload(f1)); - double f2 = NaN(0x3_FFFF_FFFF_FFFF); + immutable double f2 = NaN(0x3_FFFF_FFFF_FFFF); writeln(getNaNPayload(f2)); - real f3 = NaN(0x3FFF_FFFF_FFFF_FFFF); + immutable real f3 = NaN(0x3FFF_FFFF_FFFF_FFFF); writeln(getNaNPayload(f3)); } diff --git a/Task/Factorial/D/factorial-1.d b/Task/Factorial/D/factorial-1.d new file mode 100644 index 0000000000..f0f9610c22 --- /dev/null +++ b/Task/Factorial/D/factorial-1.d @@ -0,0 +1,19 @@ +uint factorial(in uint n) pure nothrow +in { + assert(n <= 12); +} body { + uint result = 1; + foreach (immutable i; 1 .. n + 1) + result *= i; + return result; +} + +// Computed and printed at compile-time. +pragma(msg, 12.factorial); + +void main() { + import std.stdio; + + // Computed and printed at run-time. + 12.factorial.writeln; +} diff --git a/Task/Factorial/D/factorial-2.d b/Task/Factorial/D/factorial-2.d new file mode 100644 index 0000000000..7e74d3753f --- /dev/null +++ b/Task/Factorial/D/factorial-2.d @@ -0,0 +1,19 @@ +uint factorial(in uint n) pure nothrow +in { + assert(n <= 12); +} body { + if (n == 0) + return 1; + else + return n * factorial(n - 1); +} + +// Computed and printed at compile-time. +pragma(msg, 12.factorial); + +void main() { + import std.stdio; + + // Computed and printed at run-time. + 12.factorial.writeln; +} diff --git a/Task/Factorial/D/factorial-3.d b/Task/Factorial/D/factorial-3.d new file mode 100644 index 0000000000..727b101df2 --- /dev/null +++ b/Task/Factorial/D/factorial-3.d @@ -0,0 +1,16 @@ +import std.stdio, std.algorithm, std.range; + +uint factorial(in uint n) pure nothrow +in { + assert(n <= 12); +} body { + return reduce!q{a * b}(1u, iota(1, n + 1)); +} + +// Computed and printed at compile-time. +pragma(msg, 12.factorial); + +void main() { + // Computed and printed at run-time. + 12.factorial.writeln; +} diff --git a/Task/Factorial/D/factorial-4.d b/Task/Factorial/D/factorial-4.d new file mode 100644 index 0000000000..3acddea41a --- /dev/null +++ b/Task/Factorial/D/factorial-4.d @@ -0,0 +1,22 @@ +uint factorial(in uint n) pure nothrow +in { + assert(n <= 12); +} body { + static uint inner(uint n, uint acc) pure nothrow { + if (n < 1) + return acc; + else + return inner(n - 1, acc * n); + } + return inner(n, 1); +} + +// Computed and printed at compile-time. +pragma(msg, 12.factorial); + +void main() { + import std.stdio; + + // Computed and printed at run-time. + 12.factorial.writeln; +} diff --git a/Task/Factorial/D/factorial.d b/Task/Factorial/D/factorial.d deleted file mode 100644 index 2344074c7b..0000000000 --- a/Task/Factorial/D/factorial.d +++ /dev/null @@ -1,47 +0,0 @@ -import std.stdio, std.algorithm, std.range; - -/// Iterative. -int factorial(in int n) { - int result = 1; - foreach (i; 1 .. n + 1) - result *= i; - return result; -} - -/// Recursive. -int recFactorial(in int n) { - if (n == 0) - return 1; - else - return n * recFactorial(n - 1); -} - -/// Functional-style. -int fact(in int n) { - return iota(1, n + 1).reduce!q{a * b}; -} - -/// Tail recursive (at run-time, with DMD). -int tfactorial(in int n) { - static int facAux(int n, int acc) { - if (n < 1) - return acc; - else - return facAux(n - 1, acc * n); - } - return facAux(n, 1); -} - -// Computed and printed at compile-time. -pragma(msg, 15.factorial); -pragma(msg, 15.recFactorial); -pragma(msg, 15.fact); -pragma(msg, 15.tfactorial); - -void main() { - // Computed and printed at run-time. - 15.factorial.writeln; - 15.recFactorial.writeln; - 15.fact.writeln; - 15.tfactorial.writeln; -} diff --git a/Task/Factorial/Frink/factorial-1.frink b/Task/Factorial/Frink/factorial-1.frink new file mode 100644 index 0000000000..01b86df06e --- /dev/null +++ b/Task/Factorial/Frink/factorial-1.frink @@ -0,0 +1 @@ +factorial[x] := x! diff --git a/Task/Factorial/Frink/factorial-2.frink b/Task/Factorial/Frink/factorial-2.frink new file mode 100644 index 0000000000..a8fa509e5d --- /dev/null +++ b/Task/Factorial/Frink/factorial-2.frink @@ -0,0 +1 @@ +factorial2[x] := product[1 to x] diff --git a/Task/Factorial/Rust/factorial.rust b/Task/Factorial/Rust/factorial.rust new file mode 100644 index 0000000000..35f7ae7c37 --- /dev/null +++ b/Task/Factorial/Rust/factorial.rust @@ -0,0 +1,19 @@ +fn factorial_recursive (n: uint) -> uint { + match n { + 0 => 1, + _ => n * factorial_recursive(n-1) + } +} + +fn factorial_iterative(n: uint) -> uint { + range(1u, n+1).fold(1, |p, t| p * t) +} + +fn main () { + for i in range(1u, 10u) { + println!("{}", factorial_recursive(i)) + } + for i in range(1u, 10u) { + println!("{}", factorial_iterative(i)) + } +} diff --git a/Task/Factorial/TXR/factorial-1.txr b/Task/Factorial/TXR/factorial-1.txr new file mode 100644 index 0000000000..5af151f8a5 --- /dev/null +++ b/Task/Factorial/TXR/factorial-1.txr @@ -0,0 +1,2 @@ +$ txr -p '(n-perm-k 10 10)' +3628800 diff --git a/Task/Factorial/TXR/factorial-2.txr b/Task/Factorial/TXR/factorial-2.txr new file mode 100644 index 0000000000..316fa08fbc --- /dev/null +++ b/Task/Factorial/TXR/factorial-2.txr @@ -0,0 +1,2 @@ +$ txr -p '[reduce-left * (range 1 10) 1]' +3628800 diff --git a/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d b/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d index 2846eeea76..0a6cca326c 100644 --- a/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d +++ b/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d @@ -10,7 +10,7 @@ ulong mersenneFactor(in ulong p) pure nothrow { return true; } - static long modPow(in long cb,in long ce,in long m) pure nothrow { + static long modPow(in long cb, in long ce,in long m) pure nothrow { long b = cb; long result = 1; for (long e = ce; e > 0; e >>= 1) { @@ -21,7 +21,7 @@ ulong mersenneFactor(in ulong p) pure nothrow { return result; } - immutable ulong limit = cast(ulong)sqrt(cast(real)(2 ^^ p - 1)); + immutable ulong limit = cast(ulong)real(2 ^^ p - 1).sqrt; for (ulong k = 1; (2 * p * k - 1) < limit; k++) { immutable ulong q = 2 * p * k + 1; if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && @@ -32,5 +32,5 @@ ulong mersenneFactor(in ulong p) pure nothrow { } void main() { - writefln("Factor of M929: %s", mersenneFactor(929)); + writefln("Factor of M929: %s", 929.mersenneFactor); } diff --git a/Task/Factors-of-an-integer/00DESCRIPTION b/Task/Factors-of-an-integer/00DESCRIPTION index cd69d7c6bc..b402dcfc33 100644 --- a/Task/Factors-of-an-integer/00DESCRIPTION +++ b/Task/Factors-of-an-integer/00DESCRIPTION @@ -1,7 +1,7 @@ {{basic data operation}} [[Category:Arithmetic operations]] [[Category:Mathematical_operations]] -Compute the [[wp:Divisor|factors]] of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result (though the concepts function correctly for zero and negative integers, the set of factors of zero is has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases). Note that even prime numbers will have at least two factors; ‘1’ and themselves. +Compute the [[wp:Divisor|factors]] of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result (though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases). Note that even prime numbers will have at least two factors; ‘1’ and themselves. See also: * [[Prime decomposition]] diff --git a/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d b/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d index 716c32c1e8..c4c52105e6 100644 --- a/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d +++ b/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d @@ -1,10 +1,11 @@ import std.stdio, std.math, std.algorithm; T[] factors(T)(in T n) /*pure nothrow*/ { - if (n == 1) return [n]; + if (n == 1) + return [n]; T[] res = [1, n]; - T limit = cast(T)sqrt(cast(real)n) + 1; + T limit = cast(T)real(n).sqrt + 1; for (T i = 2; i < limit; i++) { if (n % i == 0) { res ~= i; @@ -18,6 +19,5 @@ T[] factors(T)(in T n) /*pure nothrow*/ { } void main() { - foreach (immutable i; [45, 53, 64, 1111111]) - i.factors.writeln; + writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors); } diff --git a/Task/Factors-of-an-integer/Maple/factors-of-an-integer.maple b/Task/Factors-of-an-integer/Maple/factors-of-an-integer.maple new file mode 100644 index 0000000000..3051750a2e --- /dev/null +++ b/Task/Factors-of-an-integer/Maple/factors-of-an-integer.maple @@ -0,0 +1 @@ +numtheory:-divisors(n); diff --git a/Task/Factors-of-an-integer/Smalltalk/factors-of-an-integer-1.st b/Task/Factors-of-an-integer/Smalltalk/factors-of-an-integer-1.st new file mode 100644 index 0000000000..17f370b051 --- /dev/null +++ b/Task/Factors-of-an-integer/Smalltalk/factors-of-an-integer-1.st @@ -0,0 +1,7 @@ +Integer>>factors + | a | + a := OrderedCollection new. + 1 to: (self / 2) do: [ :i | + ((self \\ i) = 0) ifTrue: [ a add: i ] ]. + a add: self. + ^a diff --git a/Task/Factors-of-an-integer/Smalltalk/factors-of-an-integer-2.st b/Task/Factors-of-an-integer/Smalltalk/factors-of-an-integer-2.st new file mode 100644 index 0000000000..af6e81723b --- /dev/null +++ b/Task/Factors-of-an-integer/Smalltalk/factors-of-an-integer-2.st @@ -0,0 +1,2 @@ +59 factors -> an OrderedCollection(1 59) +120 factors -> an OrderedCollection(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120) diff --git a/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-1.maple b/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-1.maple new file mode 100644 index 0000000000..c4a2c7fc25 --- /dev/null +++ b/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-1.maple @@ -0,0 +1,3 @@ +with( DiscreteTransforms ): + +FourierTransform( <1,1,1,1,0,0,0,0>, normalization=none ); diff --git a/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-2.maple b/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-2.maple new file mode 100644 index 0000000000..46dd5a1d84 --- /dev/null +++ b/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-2.maple @@ -0,0 +1,5 @@ +v := Vector( [1,1,1,1,0,0,0,0], datatype=complex[8] ): + +FourierTransform( v, normalization=none, inplace ): + +v; diff --git a/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-3.maple b/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-3.maple new file mode 100644 index 0000000000..7b0948eb56 --- /dev/null +++ b/Task/Fast-Fourier-transform/Maple/fast-fourier-transform-3.maple @@ -0,0 +1,3 @@ +InverseFourierTransform( v, normalization=full, inplace ): + +v; diff --git a/Task/Fibonacci-n-step-number-sequences/AutoHotkey/fibonacci-n-step-number-sequences.ahk b/Task/Fibonacci-n-step-number-sequences/AutoHotkey/fibonacci-n-step-number-sequences.ahk new file mode 100644 index 0000000000..8ac00a2cd8 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/AutoHotkey/fibonacci-n-step-number-sequences.ahk @@ -0,0 +1,17 @@ +for i, seq in ["nacci", "lucas"] + Loop, 9 { + Out .= seq "(" A_Index + 1 "): " + for key, val in NStepSequence(i, 1, A_Index + 1, 15) + Out .= val (A_Index = 15 ? "`n" : "`, ") + } +MsgBox, % Out + +NStepSequence(v1, v2, n, k) { + a := [v1, v2] + Loop, % k - 2 { + a[j := A_Index + 2] := 0 + Loop, % j < n + 2 ? j - 1 : n + a[j] += a[j - A_Index] + } + return, a +} diff --git a/Task/Fibonacci-n-step-number-sequences/Clojure/fibonacci-n-step-number-sequences.clj b/Task/Fibonacci-n-step-number-sequences/Clojure/fibonacci-n-step-number-sequences.clj new file mode 100644 index 0000000000..a63b660ac9 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Clojure/fibonacci-n-step-number-sequences.clj @@ -0,0 +1,9 @@ +(defn nacci [init] + (letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))] + (s))) + +(let [show (fn [name init] (println "first 20" name (take 20 (nacci init))))] + (show "Fibonacci" [1 1]) + (show "Tribonacci" [1 1 2]) + (show "Tetranacci" [1 1 2 4]) + (show "Lucas" [2 1])) diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d index cc32b84217..3ff57095b5 100644 --- a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d @@ -1,7 +1,7 @@ -import std.stdio, std.algorithm, std.range, std.conv; - void main() { - int[] memo; + import std.stdio, std.algorithm, std.range, std.conv; + + const(int)[] memo; size_t addNum; void setHead(int[] head) nothrow { @@ -9,21 +9,22 @@ void main() { addNum = head.length; } - int fibber(in size_t n) /*nothrow*/ { + int fibber(in size_t n) nothrow { if (n >= memo.length) - memo ~= iota(n - addNum, n).map!fibber().reduce!q{a + b}(); + memo ~= iota(n - addNum, n).map!fibber.sum; return memo[n]; } setHead([1, 1]); - iota(10).map!fibber().writeln(); + 10.iota.map!fibber.writeln; setHead([2, 1]); - iota(10).map!fibber().writeln(); + 10.iota.map!fibber.writeln; - auto prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; - foreach (n, name; zip(iota(2, 11), prefixes.split())) { - setHead(1 ~ iota(n - 1).map!q{2 ^^ a}().array()); - auto items = iota(15).map!(i => text(fibber(i)))().join(" "); - writefln("n=%2d, %5snacci -> %s ...", n, name, items); + const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; + //foreach (immutable n, const name; prefixes.split.enumerate(2)) { + foreach (immutable n, name; iota(2, 11).zip(prefixes.split)) { + setHead(1 ~ iota(n - 1).map!q{2 ^^ a}.array); + writefln("n=%2d, %5snacci -> %(%d %) ...", n, name, + 15.iota.map!fibber); } } diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d index e500b0f2a9..a353bc2e94 100644 --- a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d @@ -1,7 +1,7 @@ import std.stdio, std.algorithm, std.range, std.conv; struct fiblike(T) { - T[] memo; + const(T)[] memo; immutable size_t addNum; this(in T[] start) /*nothrow*/ { @@ -12,23 +12,25 @@ struct fiblike(T) { T opCall(in size_t n) /*nothrow*/ { if (n >= memo.length) memo ~= iota(n - addNum, n) - .map!(i => opCall(i))() - .reduce!q{a + b}(); + .map!(i => opCall(i)) + .sum + .to!int; return memo[n]; } } void main() { auto fibo = fiblike!int([1, 1]); - iota(10).map!fibo().writeln(); + iota(10).map!fibo.writeln; auto lucas = fiblike!int([2, 1]); - iota(10).map!lucas().writeln(); + iota(10).map!lucas.writeln; const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; - foreach (n, name; zip(iota(2, 11), prefixes.split())) { - auto fib = fiblike!int(1 ~ iota(n - 1).map!q{2 ^^ a}().array()); + //foreach (immutable n, const name; prefixes.split.enumerate(2)) { + foreach (immutable n, name; iota(2, 11).zip(prefixes.split)) { + auto fib = fiblike!int(1 ~ iota(n - 1).map!q{2 ^^ a}.array); writefln("n=%2d, %5snacci -> %(%d %) ...", - n, name, iota(15).map!fib()); + n, name, 15.iota.map!fib); } } diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d index 7cee5cf0f8..eb519cb273 100644 --- a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d @@ -3,39 +3,43 @@ import std.stdio, std.algorithm, std.range, std.traits; struct Fiblike(T) { T[] tail; - int opApply(int delegate(ref T) dg) { + int opApply(int delegate(immutable ref T) dg) { int result, pos; - foreach (x; tail) { + foreach (immutable x; tail) { result = dg(x); - if (result) return result; + if (result) + return result; } - foreach (i; cycle(iota(tail.length))) { - auto x = tail.reduce!q{a + b}(); + foreach (immutable i; tail.length.iota.cycle) { + immutable x = cast(int)tail.sum; result = dg(x); - if (result) break; + if (result) + break; tail[i] = x; } return result; } } -// std.range.take doesn't work with opApply -ForeachType!It[] takeApply(It)(It iterable, size_t n) { +// std.range.take doesn't work with opApply. +ForeachType!It[] takeApply(It)(It iterable, in size_t n) { typeof(return) result; - foreach (x; iterable) { + foreach (immutable x; iterable) { result ~= x; - if (result.length == n) break; + if (result.length == n) + break; } return result; } void main() { - Fiblike!int([1, 1]).takeApply(10).writeln(); - Fiblike!int([2, 1]).takeApply(10).writeln(); + Fiblike!int([1, 1]).takeApply(10).writeln; + Fiblike!int([2, 1]).takeApply(10).writeln; - auto prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; - foreach (n, name; zip(iota(2, 11), prefixes.split())) { - auto fib = Fiblike!int(1 ~ iota(n-1).map!q{2 ^^ a}().array()); + const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; + //foreach (immutable n, const name; prefixes.split.enumerate(2)) { + foreach (const n, name; iota(2, 11).zip(prefixes.split)) { + auto fib = Fiblike!int(1 ~ iota(n - 1).map!q{2 ^^ a}.array); writefln("n=%2d, %5snacci -> %s", n, name, fib.takeApply(15)); } } diff --git a/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust new file mode 100644 index 0000000000..0497fda1aa --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust @@ -0,0 +1,21 @@ + // Works with 0.9 +fn fibonacci(max: uint, mut list: ~[int]) -> ~[int] { + if list.len() == 0 { + list = ~[0,1]; // If the list is empty, give it 0 and 1 as first to items + } else if list.len() == max { + return list; + } + + // Get the last two items on the list + let n1 = list.len() - 1; // Last item + let n2 = list.len() - 2; // Second-to-last item + + let f1 = *list.iter().nth(n1).unwrap(); // Get the (n-1)th item + let f2 = *list.iter().nth(n2).unwrap(); // get the (n-2)th item + + // Add them together and push the sum onto the list! + list.push(f1 + f2); + + // Get the next number with the new list + return fibonacci(max, list) +} diff --git a/Task/Fibonacci-sequence/C/fibonacci-sequence-2.c b/Task/Fibonacci-sequence/C/fibonacci-sequence-2.c index 5a4ae177cf..b189581954 100644 --- a/Task/Fibonacci-sequence/C/fibonacci-sequence-2.c +++ b/Task/Fibonacci-sequence/C/fibonacci-sequence-2.c @@ -5,5 +5,5 @@ long long int fibb(int n) { fnow = fnext; fnext = tempf; } - return fnow; + return fnext; } diff --git a/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c b/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c new file mode 100644 index 0000000000..13ecb81d98 --- /dev/null +++ b/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c @@ -0,0 +1,74 @@ +#include +#include +#include + +typedef struct node node; +struct node { + int n; + mpz_t v; + node *next; +}; + +#define CSIZE 37 +node *cache[CSIZE]; + +// very primitive linked hash table +node * find_cache(int n) +{ + int idx = n % CSIZE; + node *p; + + for (p = cache[idx]; p && p->n != n; p = p->next); + if (p) return p; + + p = malloc(sizeof(node)); + p->next = cache[idx]; + cache[idx] = p; + + if (n < 2) { + p->n = n; + mpz_init_set_ui(p->v, 1); + } else { + p->n = -1; // -1: value not computed yet + mpz_init(p->v); + } + return p; +} + +mpz_t tmp1, tmp2; +mpz_t *fib(int n) +{ + int x; + node *p = find_cache(n); + + if (p->n < 0) { + p->n = n; + x = n / 2; + + mpz_mul(tmp1, *fib(x-1), *fib(n - x - 1)); + mpz_mul(tmp2, *fib(x), *fib(n - x)); + mpz_add(p->v, tmp1, tmp2); + } + return &p->v; +} + +int main(int argc, char **argv) +{ + int i, n; + if (argc < 2) return 1; + + mpz_init(tmp1); + mpz_init(tmp2); + + for (i = 1; i < argc; i++) { + n = atoi(argv[i]); + if (n < 0) { + printf("bad input: %s\n", argv[i]); + continue; + } + + // about 75% of time is spent in printing + gmp_printf("%Zd\n", *fib(n)); + } + return 0; +} diff --git a/Task/Fibonacci-sequence/D/fibonacci-sequence-2.d b/Task/Fibonacci-sequence/D/fibonacci-sequence-2.d index acd5fb1d0f..09c0a55b87 100644 --- a/Task/Fibonacci-sequence/D/fibonacci-sequence-2.d +++ b/Task/Fibonacci-sequence/D/fibonacci-sequence-2.d @@ -1,4 +1,4 @@ -import std.stdio, std.bigint; +import std.bigint; T fibonacciMatrix(T=BigInt)(size_t n) { int[size_t.sizeof * 8] binDigits; @@ -26,5 +26,5 @@ T fibonacciMatrix(T=BigInt)(size_t n) { } void main() { - writeln(fibonacciMatrix(1_000_000)); + 10_000_000.fibonacciMatrix; } diff --git a/Task/Fibonacci-sequence/D/fibonacci-sequence-3.d b/Task/Fibonacci-sequence/D/fibonacci-sequence-3.d new file mode 100644 index 0000000000..1ae27d9f3c --- /dev/null +++ b/Task/Fibonacci-sequence/D/fibonacci-sequence-3.d @@ -0,0 +1,44 @@ +import std.bigint, std.math; + +// Algorithm from: Takahashi, Daisuke, +// "A fast algorithm for computing large Fibonacci numbers". +// Information Processing Letters 75.6 (30 November 2000): 243-246. +// Implementation from: +// pythonista.wordpress.com/2008/07/03/pure-python-fibonacci-numbers +BigInt fibonacci(in ulong n) +in { + assert(n > 0, "fibonacci(n): n must be > 0."); +} body { + if (n <= 2) + return 1.BigInt; + BigInt F = 1; + BigInt L = 1; + int sign = -1; + immutable uint n2 = cast(uint)n.log2.floor; + auto mask = 2.BigInt ^^ (n2 - 1); + foreach (immutable i; 1 .. n2) { + auto temp = F ^^ 2; + F = (F + L) / 2; + F = 2 * F ^^ 2 - 3 * temp - 2 * sign; + L = 5 * temp + 2 * sign; + sign = 1; + if (n & mask) { + temp = F; + F = (F + L) / 2; + L = F + 2 * temp; + sign = -1; + } + mask /= 2; + } + if ((n & mask) == 0) { + F *= L; + } else { + F = (F + L) / 2; + F = F * L - sign; + } + return F; +} + +void main() { + 10_000_000.fibonacci; +} diff --git a/Task/Fibonacci-sequence/Frink/fibonacci-sequence.frink b/Task/Fibonacci-sequence/Frink/fibonacci-sequence.frink new file mode 100644 index 0000000000..0f4ef20b6d --- /dev/null +++ b/Task/Fibonacci-sequence/Frink/fibonacci-sequence.frink @@ -0,0 +1,12 @@ +fibonacciN[n] := +{ + a = 0 + b = 1 + count = 0 + while count < n + { + [a,b] = [b, a + b] + count = count + 1 + } + return a +} diff --git a/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-2.l b/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-2.l index 6474309a65..8661b5eaa7 100644 --- a/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-2.l +++ b/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-2.l @@ -1,5 +1,5 @@ (de fibo (N) - (cache '(NIL) (pack (char (hash N)) N) # Use a cache to accelerate + (cache '(NIL) N # Use a cache to accelerate (if (>= 2 N) N (+ (fibo (dec N)) (fibo (- N 2))) ) ) ) diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py new file mode 100644 index 0000000000..c3bd4903b0 --- /dev/null +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py @@ -0,0 +1,7 @@ +def fib(n, c={0:1, 1:1}): + if n not in c: + x = n // 2 + c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x) + return c[n] + +fib(10000000) # calculating it takes a few seconds, printing it takes eons diff --git a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-2.scala b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-2.scala index 2f1e32bd9b..168b559c0f 100644 --- a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-2.scala +++ b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-2.scala @@ -1,9 +1 @@ -//syntactic sugar for Stream.cons, this is unnecessary but makes the definition prettier -//Stream.cons(head,stream) becomes head::stream -//I think 2.8 will have #:: -class PrettyStream[A](str: =>Stream[A]) { - def ::(hd: A) = Stream.cons(hd, str) -} -implicit def streamToPrettyStream[A](str: =>Stream[A]) = new PrettyStream(str) - -def fib: Stream[Int] = 0 :: 1 :: fib.zip(fib.tail).map{case (a,b) => a + b} +lazy val fib: Stream[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map{case (a,b) => a + b} diff --git a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala index 9980920fe8..e0a65a61e1 100644 --- a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala +++ b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala @@ -1 +1,4 @@ -def fib: Stream[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map{case (a,b) => a + b} +def fib(i:Int, a:Int=1, b:Int=0):Int = i match{ + case 1 => b + case _ => fib(i-1, b, a+b) +} diff --git a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-4.scala b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-4.scala index 74eb11bfd9..1dab8f56f0 100644 --- a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-4.scala +++ b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-4.scala @@ -1,7 +1,13 @@ -def fib(i:Int):Int = { - def fib2(i:Int, a:Int, b:Int):Int = i match{ - case 1 => b - case _ => fib2(i-1, b, a+b) - } - fib2(i,1,0) +// Fibonacci using BigInt with Stream.foldLeft optimized for GC (Scala v2.9 and above) +// Does not run out of memory for very large Fibonacci numbers +def fib(n:Int) = { + + def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j) + + series(1,0).take(n).foldLeft(BigInt("0"))(_+_) } + +// Small test +(0 to 13) foreach {n => print(fib(n).toString + " ")} + +// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 diff --git a/Task/File-IO/Frink/file-io.frink b/Task/File-IO/Frink/file-io.frink new file mode 100644 index 0000000000..edd3d43f99 --- /dev/null +++ b/Task/File-IO/Frink/file-io.frink @@ -0,0 +1,4 @@ +contents = read["file:input.txt"] +w = new Writer["output.txt"] +w.print[contents] +w.close[] diff --git a/Task/File-IO/Mercury/file-io.mercury b/Task/File-IO/Mercury/file-io.mercury new file mode 100644 index 0000000000..2c6dd8e859 --- /dev/null +++ b/Task/File-IO/Mercury/file-io.mercury @@ -0,0 +1,40 @@ +:- module file_io. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. + +main(!IO) :- + io.open_input("input.txt", InputRes, !IO), + ( + InputRes = ok(Input), + io.read_file_as_string(Input, ReadRes, !IO), + ( + ReadRes = ok(Contents), + io.close_input(Input, !IO), + io.open_output("output.txt", OutputRes, !IO), + ( + OutputRes = ok(Output), + io.write_string(Output, Contents, !IO), + io.close_output(Output, !IO) + ; + OutputRes = error(OutputError), + print_io_error(OutputError, !IO) + ) + ; + ReadRes = error(_, ReadError), + print_io_error(ReadError, !IO) + ) + ; + InputRes = error(InputError), + print_io_error(InputError, !IO) + ). + +:- pred print_io_error(io.error::in, io::di, io::uo) is det. + +print_io_error(Error, !IO) :- + io.stderr_stream(Stderr, !IO), + io.write_string(Stderr, io.error_message(Error), !IO), + io.set_exit_status(1, !IO). diff --git a/Task/File-size/Rust/file-size.rust b/Task/File-size/Rust/file-size.rust new file mode 100644 index 0000000000..b3ab788445 --- /dev/null +++ b/Task/File-size/Rust/file-size.rust @@ -0,0 +1,7 @@ +fn main() { + let path_wd = Path::new("input.txt"); + println!("{}", path_wd.stat().size); + + let path_root = Path::new("/input.txt"); + println!("{}", path_root.stat().size); +} diff --git a/Task/Filter/Frink/filter.frink b/Task/Filter/Frink/filter.frink new file mode 100644 index 0000000000..53d4f382b5 --- /dev/null +++ b/Task/Filter/Frink/filter.frink @@ -0,0 +1,2 @@ +b = array[1 to 100] +c = select[b, {|x| x mod 2 == 0}] diff --git a/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-1.st b/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-1.st new file mode 100644 index 0000000000..34869f63b8 --- /dev/null +++ b/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-1.st @@ -0,0 +1,5 @@ +Object subclass: #RecursionTest + instanceVariableNames: '' + classVariableNames: '' + poolDictionaries: '' + category: 'RosettaCode' diff --git a/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-2.st b/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-2.st new file mode 100644 index 0000000000..1af41a74d9 --- /dev/null +++ b/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-2.st @@ -0,0 +1,2 @@ +counter: aNumber + ^self counter: aNumber + 1 diff --git a/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-3.st b/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-3.st new file mode 100644 index 0000000000..7c739dd32d --- /dev/null +++ b/Task/Find-limit-of-recursion/Smalltalk/find-limit-of-recursion-3.st @@ -0,0 +1,2 @@ +r := RecursionTest new. +r counter: 1. diff --git a/Task/Find-limit-of-recursion/TXR/find-limit-of-recursion.txr b/Task/Find-limit-of-recursion/TXR/find-limit-of-recursion.txr new file mode 100644 index 0000000000..7d01c5a3f9 --- /dev/null +++ b/Task/Find-limit-of-recursion/TXR/find-limit-of-recursion.txr @@ -0,0 +1,12 @@ +@(do + (set-sig-handler sig-segv + (lambda (signal async-p) (throw 'out))) + + (defvar *count* 0) + + (defun recurse () + (inc *count*) + (recurse)) + + (catch (recurse) + (out () (put-line `caught segfault!\nreached depth: @{*count*}`)))) diff --git a/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d b/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d index e82f26a372..d153561138 100644 --- a/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d +++ b/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d @@ -1,8 +1,6 @@ -import std.stdio, std.string, std.algorithm, std.range; - -alias sum = reduce!q{a + b}; - void main() { + import std.stdio, std.string, std.algorithm, std.range, std.conv; + const perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB".split; @@ -25,12 +23,10 @@ void main() { // Version 3 : Sum ASCII values. immutable rowSum = perms[0].sum; - foreach (immutable i; 0 .. len) { - immutable sumCols = sum(0, perms.transversal(i)); - // See how much it falls short. - write(cast(char)(rowSum - sumCols % rowSum)); - } - writeln; + len + .iota + .map!(i => to!char(rowSum - perms.transversal(i).sum % rowSum)) + .writeln; // Version 4: some sort of checksum, Java translation. // maxCode will be 36. diff --git a/Task/Find-the-missing-permutation/J/find-the-missing-permutation-6.j b/Task/Find-the-missing-permutation/J/find-the-missing-permutation-6.j new file mode 100644 index 0000000000..f91217c7ba --- /dev/null +++ b/Task/Find-the-missing-permutation/J/find-the-missing-permutation-6.j @@ -0,0 +1,2 @@ + 'ABCD'{~,I.@(= <./)@(#/.~)@('ABCD' , ])"1 |:perms +DBAC diff --git a/Task/Find-the-missing-permutation/PARI-GP/find-the-missing-permutation.pari b/Task/Find-the-missing-permutation/PARI-GP/find-the-missing-permutation.pari new file mode 100644 index 0000000000..0f018c4253 --- /dev/null +++ b/Task/Find-the-missing-permutation/PARI-GP/find-the-missing-permutation.pari @@ -0,0 +1,4 @@ +v=["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]; +v=apply(u->permtonum(apply(n->n-64,Vec(Vecsmall(u)))),v); +t=numtoperm(4, binomial(4!,2)-sum(i=1,#v,v[i])); +Strchr(apply(n->n+64,t)) diff --git a/Task/First-class-functions/D/first-class-functions-1.d b/Task/First-class-functions/D/first-class-functions-1.d index acb3a7699d..3de30a7a0f 100644 --- a/Task/First-class-functions/D/first-class-functions-1.d +++ b/Task/First-class-functions/D/first-class-functions-1.d @@ -1,16 +1,9 @@ -import std.stdio, std.math, std.typetuple, std.functional; - -enum sin = (in real x) => std.math.sin(x), - asin = (in real x) => std.math.asin(x), - cos = (in real x) => std.math.cos(x), - acos = (in real x) => std.math.acos(x), - cube = (in real x) => x ^^ 3, - cbrt = (in real x) => std.math.cbrt(x); - void main() { - alias TypeTuple!(sin, cos, cube) dir; - alias TypeTuple!(asin, acos, cbrt) inv; - foreach (i, f; dir) { + import std.stdio, std.math, std.typetuple, std.functional; + + alias dir = TypeTuple!(sin, cos, x => x ^^ 3); + alias inv = TypeTuple!(asin, acos, cbrt); + // foreach (f, g; staticZip!(dir, inv)) + foreach (immutable i, f; dir) writefln("%6.3f", compose!(f, inv[i])(0.5)); - } } diff --git a/Task/First-class-functions/D/first-class-functions-2.d b/Task/First-class-functions/D/first-class-functions-2.d index dee453b91b..19f22f3195 100644 --- a/Task/First-class-functions/D/first-class-functions-2.d +++ b/Task/First-class-functions/D/first-class-functions-2.d @@ -1,18 +1,18 @@ -T delegate(S) compose(T, U, S)(in T function(in U) f, - in U function(in S) g) { - return s => f(g(s)); -} - void main() { import std.stdio, std.math, std.range; - immutable sin = (in real x) => sin(x), - asin = (in real x) => asin(x), - cos = (in real x) => cos(x), - acos = (in real x) => acos(x), - cube = (in real x) => x ^^ 3, - cbrt = (in real x) => cbrt(x); + static T delegate(S) compose(T, U, S)(in T function(in U) f, + in U function(in S) g) { + return s => f(g(s)); + } - foreach (f, g; zip([sin, cos, cube], [asin, acos, cbrt])) + immutable sin = (in real x) pure nothrow => x.sin, + asin = (in real x) pure nothrow => x.asin, + cos = (in real x) pure nothrow => x.cos, + acos = (in real x) pure nothrow => x.acos, + cube = (in real x) pure nothrow => x ^^ 3, + cbrt = (in real x) /*pure*/ nothrow => x.cbrt; + + foreach (f, g; [sin, cos, cube].zip([asin, acos, cbrt])) writefln("%6.3f", compose(f, g)(0.5)); } diff --git a/Task/First-class-functions/Dart/first-class-functions.dart b/Task/First-class-functions/Dart/first-class-functions.dart index ea2458a5c1..fc08633dd7 100644 --- a/Task/First-class-functions/Dart/first-class-functions.dart +++ b/Task/First-class-functions/Dart/first-class-functions.dart @@ -1,13 +1,11 @@ -cube(x) { return x * x * x; } -inv_cube(x) { return Math.pow(x, 1/3); } - -compo(f1, f2) { - return func(x) { return f1(f2(x));}; -} - -main() { - var funcs = [Math.sin, Math.exp, cube]; - var invs = [Math.asin, Math.log, inv_cube]; - for (int i = 0; i < 3; i++) - print(compo(funcs[i], invs[i])(1)); +import 'dart:math' as Math; +cube(x) => x*x*x; +cuberoot(x) => Math.pow(x, 1/3); +compose(f,g) => ((x)=>f(g(x))); +main(){ + var functions = [Math.sin, Math.exp, cube]; + var inverses = [Math.asin, Math.log, cuberoot]; + for (int i = 0; i < 3; i++){ + print(compose(functions[i], inverses[i])(0.5)); + } } diff --git a/Task/First-class-functions/JavaScript/first-class-functions.js b/Task/First-class-functions/JavaScript/first-class-functions-1.js similarity index 82% rename from Task/First-class-functions/JavaScript/first-class-functions.js rename to Task/First-class-functions/JavaScript/first-class-functions-1.js index 8f8f858412..5b794d55d9 100644 --- a/Task/First-class-functions/JavaScript/first-class-functions.js +++ b/Task/First-class-functions/JavaScript/first-class-functions-1.js @@ -1,9 +1,9 @@ // Functions as values of a variable -var cube = function(x) { +var cube = function (x) { return Math.pow(x, 3); }; -var cuberoot = function(x) { - return Math.pow(x, 1/3); +var cuberoot = function (x) { + return Math.pow(x, 1 / 3); }; // Higher order function diff --git a/Task/First-class-functions/JavaScript/first-class-functions-2.js b/Task/First-class-functions/JavaScript/first-class-functions-2.js new file mode 100644 index 0000000000..fad07b9a59 --- /dev/null +++ b/Task/First-class-functions/JavaScript/first-class-functions-2.js @@ -0,0 +1,17 @@ +// Functions as values of a variable +var cube = x => Math.pow(x, 3); + +var cuberoot = x => Math.pow(x, 1 / 3); + + +// Higher order function +var compose = (f, g) => (x => f(g(x))); + +// Storing functions in a array +var fun = [ Math.sin, Math.cos, cube ]; +var inv = [ Math.asin, Math.acos, cuberoot ]; + +for (var i = 0; i < 3; i++) { + // Applying the composition to 0.5 + console.log(compose(inv[i], fun[i])(0.5)); +} diff --git a/Task/First-class-functions/Perl-6/first-class-functions.pl6 b/Task/First-class-functions/Perl-6/first-class-functions.pl6 index b2ce56f54f..df923bf8b3 100644 --- a/Task/First-class-functions/Perl-6/first-class-functions.pl6 +++ b/Task/First-class-functions/Perl-6/first-class-functions.pl6 @@ -1,6 +1,6 @@ -sub infix:<⚬> (�, �) { -> \x { #56404; #56403; x } } +sub infix:<∘> (&𝑔, &𝑓) { -> \x { 𝑔 𝑓 x } } -my \#56372; = &sin, &cos, { $_ ** <3/1> } -my \#56373; = &asin, &acos, { $_ ** <1/3> } +my \𝐴 = &sin, &cos, { $_ ** <3/1> } +my \𝐵 = &asin, &acos, { $_ ** <1/3> } -say .(.5) for #56372; Z⚬ #56373; +say .(.5) for 𝐴 Z∘ 𝐵 diff --git a/Task/FizzBuzz/Batch-File/fizzbuzz-1.bat b/Task/FizzBuzz/Batch-File/fizzbuzz-1.bat index 8df0f500ce..eaace8acdd 100644 --- a/Task/FizzBuzz/Batch-File/fizzbuzz-1.bat +++ b/Task/FizzBuzz/Batch-File/fizzbuzz-1.bat @@ -3,22 +3,22 @@ for /L %%i in (1,1,100) do call :tester %%i goto :eof :tester -set /a test = %1 %% 15 -if %test% NEQ 0 goto :NotFizzBuzz -echo FizzBuzz -goto :eof + set /a test = %1 %% 15 + if %test% NEQ 0 goto :NotFizzBuzz + echo FizzBuzz + goto :eof :NotFizzBuzz -set /a test = %1 %% 5 -if %test% NEQ 0 goto :NotBuzz -echo Buzz -goto :eof + set /a test = %1 %% 5 + if %test% NEQ 0 goto :NotBuzz + echo Buzz + goto :eof :NotBuzz -set /a test = %1 %% 3 -if %test% NEQ 0 goto :NotFizz -echo Fizz -goto :eof + set /a test = %1 %% 3 + if %test% NEQ 0 goto :NotFizz + echo Fizz + goto :eof :NotFizz -echo %1 + echo %1 diff --git a/Task/FizzBuzz/Batch-File/fizzbuzz-2.bat b/Task/FizzBuzz/Batch-File/fizzbuzz-2.bat index f70a3296a4..05ff498a8b 100644 --- a/Task/FizzBuzz/Batch-File/fizzbuzz-2.bat +++ b/Task/FizzBuzz/Batch-File/fizzbuzz-2.bat @@ -1,28 +1,29 @@ @echo off set n=1 + :loop -call :tester %n% -set /a n += 1 -if %n% LSS 101 goto loop -goto :eof + call :tester %n% + set /a n += 1 + if %n% LSS 101 goto loop + goto :eof :tester -set /a test = %1 %% 15 -if %test% NEQ 0 goto :NotFizzBuzz -echo FizzBuzz -goto :eof + set /a test = %1 %% 15 + if %test% NEQ 0 goto :NotFizzBuzz + echo FizzBuzz + goto :eof :NotFizzBuzz -set /a test = %1 %% 5 -if %test% NEQ 0 goto :NotBuzz -echo Buzz -goto :eof + set /a test = %1 %% 5 + if %test% NEQ 0 goto :NotBuzz + echo Buzz + goto :eof :NotBuzz -set /a test = %1 %% 3 -if %test% NEQ 0 goto :NotFizz -echo Fizz -goto :eof + set /a test = %1 %% 3 + if %test% NEQ 0 goto :NotFizz + echo Fizz + goto :eof :NotFizz -echo %1 + echo %1 diff --git a/Task/FizzBuzz/Batch-File/fizzbuzz-3.bat b/Task/FizzBuzz/Batch-File/fizzbuzz-3.bat new file mode 100644 index 0000000000..1aa2fecd7b --- /dev/null +++ b/Task/FizzBuzz/Batch-File/fizzbuzz-3.bat @@ -0,0 +1,10 @@ +@echo off & setlocal enabledelayedexpansion +for /l %%i in (1,1,100) do ( + set /a m5=%%i %% 5 + set /a m3=%%i %% 3 + set s= + if !m5! equ 0 set s=!s!Fizz + if !m3! equ 0 set s=!s!Buzz + if "!s!"=="" set s=%%i + echo !s! +) diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-1.js b/Task/FizzBuzz/JavaScript/fizzbuzz-1.js index be188cff9c..d7a25fd9ad 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-1.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-1.js @@ -10,23 +10,12 @@ for (var i = 1; i <= 100; i++) { } } -// ------------------ -// functional version -// ------------------ -(function (n) { - var r = []; - - while (n--) { - r.push(n + 1); - } - - return r.reverse(); - })(100).map(function (n) { - return !(n % 15) ? - 'FizzBuzz' : - !(n % 3) ? - 'Fizz' : - !(n % 5) ? - 'Buzz' : - n; - }).join('\r\n'); +Array.apply(null, { length: 100 }).map(function(n, i) { + ++i; + return !(i % 15) ? + "FizzBuzz" : + !(i % 3) ? + "Fizz" : + !(i % 5) ? + "Buzz" : i; +}).join("\r\n"); diff --git a/Task/FizzBuzz/Julia/fizzbuzz-3.julia b/Task/FizzBuzz/Julia/fizzbuzz-3.julia new file mode 100644 index 0000000000..4f2dd5f65c --- /dev/null +++ b/Task/FizzBuzz/Julia/fizzbuzz-3.julia @@ -0,0 +1,4 @@ +fb(i::Int) = "Fizz" ^ (i%3==0) * + "Buzz" ^ (i%5==0) * + string(i) ^ (i%3!=0 && i%5!=0) +[println(fb(i)) for i = 1:100]; diff --git a/Task/FizzBuzz/LaTeX/fizzbuzz.tex b/Task/FizzBuzz/LaTeX/fizzbuzz.tex new file mode 100644 index 0000000000..811ff72fa5 --- /dev/null +++ b/Task/FizzBuzz/LaTeX/fizzbuzz.tex @@ -0,0 +1,22 @@ +\documentclass{minimal} +\usepackage{ifthen} +\usepackage{intcalc} + +\newcounter{mycount} +\newboolean{fizzOrBuzz} + +\newcommand\fizzBuzz[1]{% +\setcounter{mycount}{1}\whiledo{\value{mycount}<#1} + { + \setboolean{fizzOrBuzz}{false} + \ifthenelse{\equal{\intcalcMod{\themycount}{3}}{0}}{\setboolean{fizzOrBuzz}{true}Fizz}{} + \ifthenelse{\equal{\intcalcMod{\themycount}{5}}{0}}{\setboolean{fizzOrBuzz}{true}Buzz}{} + \ifthenelse{\boolean{fizzOrBuzz}}{}{\themycount} + \stepcounter{mycount} + \\ + } +} + +\begin{document} + \fizzBuzz{101} +\end{document} diff --git a/Task/FizzBuzz/Perl/fizzbuzz-1.pl b/Task/FizzBuzz/Perl/fizzbuzz-1.pl index 3765b7e368..ca6035eeaa 100644 --- a/Task/FizzBuzz/Perl/fizzbuzz-1.pl +++ b/Task/FizzBuzz/Perl/fizzbuzz-1.pl @@ -1,14 +1,10 @@ -#!/usr/bin/perl - use strict; use warnings; +use feature qw(say); -use feature qw/say/; - -foreach my $i (1 .. 100) { - say + (0 == $i % 15) ? "FizzBuzz" - : (0 == $i % 3) ? "Fizz" - : (0 == $i % 5) ? "Buzz" - : $i - ; +for my $i (1..100) { + say $i % 15 == 0 ? "FizzBuzz" + : $i % 3 == 0 ? "Fizz" + : $i % 5 == 0 ? "Buzz" + : $i; } diff --git a/Task/FizzBuzz/Perl/fizzbuzz-5.pl b/Task/FizzBuzz/Perl/fizzbuzz-5.pl new file mode 100644 index 0000000000..95a8f8477c --- /dev/null +++ b/Task/FizzBuzz/Perl/fizzbuzz-5.pl @@ -0,0 +1,5 @@ +use feature "say"; + +@a = ("FizzBuzz", 0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz"); + +say $a[$_ % 15] || $_ for 1..100; diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-3.rb b/Task/FizzBuzz/Ruby/fizzbuzz-3.rb index dd398a91cf..a62b4110fe 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-3.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-3.rb @@ -1,4 +1,92 @@ -(1..100).each do |n| - v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}" - puts v.empty? ? n : v +class Enumerator::Lazy + def filter_map + Lazy.new(self) do |holder, *values| + result = yield *values + holder << result if result + end + end +end + +class Fizz + def initialize(head, tail) + @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 3 == 0}.first(tail) + end + + def fizz?(num) + search = @list + search.include?(num) + end + + def drop(num) + list = @list + list.delete(num) + end + + def to_a + @list.to_a + end +end + +class Buzz + def initialize(head, tail) + @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 5 == 0}.first(tail) + end + + def buzz?(num) + search = @list + search.include?(num) + end + + def drop(num) + list = @list + list.delete(num) + end + + def to_a + @list.to_a + end +end + +class FizzBuzz + def initialize(head, tail) + @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 15 == 0}.first(tail) + end + + def fizzbuzz?(num) + search = @list + search.include?(num) + end + + def to_a + @list.to_a + end + + def drop(num) + list = @list + list.delete(num) + end +end +stopper = 100 +@fizz = Fizz.new(1,100) +@buzz = Buzz.new(1,100) +@fizzbuzz = FizzBuzz.new(1,100) +def min(v, n) + if v == 1 + puts "Fizz: #{n}" + @fizz::drop(n) + elsif v == 2 + puts "Buzz: #{n}" + @buzz::drop(n) + else + puts "FizzBuzz: #{n}" + @fizzbuzz::drop(n) + end +end +(@fizz.to_a & @fizzbuzz.to_a).map{|d| @fizz::drop(d)} +(@buzz.to_a & @fizzbuzz.to_a).map{|d| @buzz::drop(d)} +while @fizz.to_a.min < stopper or @buzz.to_a.min < stopper or @fizzbuzz.to_a.min < stopper + f, b, fb = @fizz.to_a.min, @buzz.to_a.min, @fizzbuzz.to_a.min + min(1,f) if f < fb and f < b + min(2,b) if b < f and b < fb + min(0,fb) if fb < b and fb < f end diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-4.rb b/Task/FizzBuzz/Ruby/fizzbuzz-4.rb index 08c5db805d..dd398a91cf 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-4.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-4.rb @@ -1 +1,4 @@ -1.upto(100) { |n| puts "#{'Fizz' if n % 3 == 0}#{'Buzz' if n % 5 == 0}#{n if n % 3 != 0 && n % 5 != 0}" } +(1..100).each do |n| + v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}" + puts v.empty? ? n : v +end diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-5.rb b/Task/FizzBuzz/Ruby/fizzbuzz-5.rb index d87121444e..08c5db805d 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-5.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-5.rb @@ -1,7 +1 @@ -1.upto 100 do |n| - r = '' - r << 'Fizz' if n % 3 == 0 - r << 'Buzz' if n % 5 == 0 - r << n.to_s if r.empty? - puts r -end +1.upto(100) { |n| puts "#{'Fizz' if n % 3 == 0}#{'Buzz' if n % 5 == 0}#{n if n % 3 != 0 && n % 5 != 0}" } diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-6.rb b/Task/FizzBuzz/Ruby/fizzbuzz-6.rb index d0d167d009..d87121444e 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-6.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-6.rb @@ -1 +1,7 @@ -1.upto(100) { |i| p "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/m] || i } +1.upto 100 do |n| + r = '' + r << 'Fizz' if n % 3 == 0 + r << 'Buzz' if n % 5 == 0 + r << n.to_s if r.empty? + puts r +end diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-7.rb b/Task/FizzBuzz/Ruby/fizzbuzz-7.rb index 18ccc56ae3..d0d167d009 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-7.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-7.rb @@ -1,8 +1 @@ -class Integer - def fizzbuzz - v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" - v.empty? ? self : v - end -end - -puts *(1..100).map(&:fizzbuzz) +1.upto(100) { |i| p "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/m] || i } diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-8.rb b/Task/FizzBuzz/Ruby/fizzbuzz-8.rb index 3a6a18d553..18ccc56ae3 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-8.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-8.rb @@ -1,8 +1,8 @@ -fizzbuzz = ->(i) do - (i%15).zero? and next "FizzBuzz" - (i%3).zero? and next "Fizz" - (i%5).zero? and next "Buzz" - i +class Integer + def fizzbuzz + v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" + v.empty? ? self : v + end end -puts (1..100).map(&fizzbuzz).join("\n") +puts *(1..100).map(&:fizzbuzz) diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-9.rb b/Task/FizzBuzz/Ruby/fizzbuzz-9.rb new file mode 100644 index 0000000000..3a6a18d553 --- /dev/null +++ b/Task/FizzBuzz/Ruby/fizzbuzz-9.rb @@ -0,0 +1,8 @@ +fizzbuzz = ->(i) do + (i%15).zero? and next "FizzBuzz" + (i%3).zero? and next "Fizz" + (i%5).zero? and next "Buzz" + i +end + +puts (1..100).map(&fizzbuzz).join("\n") diff --git a/Task/FizzBuzz/Sed/fizzbuzz.sed b/Task/FizzBuzz/Sed/fizzbuzz-1.sed similarity index 100% rename from Task/FizzBuzz/Sed/fizzbuzz.sed rename to Task/FizzBuzz/Sed/fizzbuzz-1.sed diff --git a/Task/FizzBuzz/Sed/fizzbuzz-2.sed b/Task/FizzBuzz/Sed/fizzbuzz-2.sed new file mode 100644 index 0000000000..70ff66685e --- /dev/null +++ b/Task/FizzBuzz/Sed/fizzbuzz-2.sed @@ -0,0 +1 @@ +seq 1 100 | sed -r '3~3 s/[0-9]*/Fizz/; 5~5 s/[0-9]*$/Buzz/' diff --git a/Task/FizzBuzz/TXR/fizzbuzz.txr b/Task/FizzBuzz/TXR/fizzbuzz.txr new file mode 100644 index 0000000000..aa98519617 --- /dev/null +++ b/Task/FizzBuzz/TXR/fizzbuzz.txr @@ -0,0 +1 @@ +$ txr -p "(mapcar (op if @1 @1 @2) (repeat '(nil nil fizz nil buzz fizz nil nil fizz buzz nil fizz nil nil fizzbuzz)) (range 1 100))" diff --git a/Task/FizzBuzz/Tcl/fizzbuzz-3.tcl b/Task/FizzBuzz/Tcl/fizzbuzz-3.tcl new file mode 100644 index 0000000000..9bf7d7a88f --- /dev/null +++ b/Task/FizzBuzz/Tcl/fizzbuzz-3.tcl @@ -0,0 +1,5 @@ +set f [lrepeat 5 "Fizz" {$i} {$i}] +foreach i {5 10} {lset f $i "Buzz"};lset f 0 "FizzBuzz" +for {set i 1} {$i <= 100} {incr i} { + puts [subst [lindex [set f [list {*}[lassign $f ff] $ff]] 0]] +} diff --git a/Task/Flatten-a-list/JavaScript/flatten-a-list-1.js b/Task/Flatten-a-list/JavaScript/flatten-a-list-1.js new file mode 100644 index 0000000000..fae507a6ac --- /dev/null +++ b/Task/Flatten-a-list/JavaScript/flatten-a-list-1.js @@ -0,0 +1,5 @@ +function flatten(list) { + return list.reduce(function (acc, val) { + return acc.concat(val.constructor === Array ? flatten(val) : val); + }, []); +} diff --git a/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js b/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js new file mode 100644 index 0000000000..7a7c9a3bd3 --- /dev/null +++ b/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js @@ -0,0 +1,5 @@ +let flatten = list => { + return list.reduce( + (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] + ); +} diff --git a/Task/Flatten-a-list/JavaScript/flatten-a-list.js b/Task/Flatten-a-list/JavaScript/flatten-a-list.js deleted file mode 100644 index f8702dcc52..0000000000 --- a/Task/Flatten-a-list/JavaScript/flatten-a-list.js +++ /dev/null @@ -1,5 +0,0 @@ -function flatten(arr){ - return arr.reduce(function(acc, val){ - return acc.concat(val.constructor === Array ? flatten(val) : val); - },[]); -} diff --git a/Task/Flatten-a-list/Maple/flatten-a-list-1.maple b/Task/Flatten-a-list/Maple/flatten-a-list-1.maple new file mode 100644 index 0000000000..bfb172be58 --- /dev/null +++ b/Task/Flatten-a-list/Maple/flatten-a-list-1.maple @@ -0,0 +1,5 @@ +L := [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]: + +with(ListTools): + +Flatten(L); diff --git a/Task/Flatten-a-list/Maple/flatten-a-list-2.maple b/Task/Flatten-a-list/Maple/flatten-a-list-2.maple new file mode 100644 index 0000000000..4969daf50c --- /dev/null +++ b/Task/Flatten-a-list/Maple/flatten-a-list-2.maple @@ -0,0 +1,7 @@ +flatten := proc(x) + `if`(type(x,'list'),seq(procname(i),i = x),x); +end proc: + +L := [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]: + +[flatten(L)]; diff --git a/Task/Flatten-a-list/Objective-C/flatten-a-list.m b/Task/Flatten-a-list/Objective-C/flatten-a-list.m new file mode 100644 index 0000000000..a64f75b858 --- /dev/null +++ b/Task/Flatten-a-list/Objective-C/flatten-a-list.m @@ -0,0 +1,40 @@ +#import + +@interface NSArray (FlattenExt) +@property (nonatomic, readonly) NSArray *flattened; +@end + +@implementation NSArray (FlattenExt) +-(NSArray *) flattened { + NSMutableArray *flattened = [[NSMutableArray alloc] initWithCapacity:self.count]; + + for (id object in self) { + if ([object isKindOfClass:[NSArray class]]) + [flattened addObjectsFromArray:((NSArray *)object).flattened]; + else + [flattened addObject:object]; + } + + return [flattened autorelease]; +} +@end + +int main() { + @autoreleasepool { + NSArray *p = @[ + @[ @1 ], + @2, + @[ @[@3, @4], @5], + @[ @[ @[ ] ] ], + @[ @[ @[ @6 ] ] ], + @7, + @8, + @[ ] ]; + + for (id object in unflattened.flattened) + NSLog(@"%@", object); + + } + + return 0; +} diff --git a/Task/Flatten-a-list/PL-I/flatten-a-list.pli b/Task/Flatten-a-list/PL-I/flatten-a-list.pli index 8e93e25d6d..e69d65be09 100644 --- a/Task/Flatten-a-list/PL-I/flatten-a-list.pli +++ b/Task/Flatten-a-list/PL-I/flatten-a-list.pli @@ -1,6 +1,8 @@ list = translate (list, ' ', '[]' ); list = '[' || list || ']'; + + /* the above will erroneously return: [ 1 , 2, 3,4 , 5 , , 6 , 7, 8, ] diff --git a/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx b/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx index fe0e2764e7..8fbb184b59 100644 --- a/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx +++ b/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx @@ -1,6 +1,6 @@ -/*REXX program demonstrates how to flatten a list. */ +/*REXX pgm demonstrates how to flatten a list (it need not be numeric).*/ y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]' -z = '['changestr(' ', space( translate(y, , '[,]')), ", ")']' +z = '['changestr(" ", space( translate(y, , '[,]')), ", ")']' say ' input =' y say 'output =' z /*stick a fork in it, we're done.*/ diff --git a/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx b/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx index 45d8ee7f05..9641e67941 100644 --- a/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx +++ b/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx @@ -1,11 +1,12 @@ -/*REXX program demonstrates how to flatten a list. */ +/*REXX pgm demonstrates how to flatten a list (it need not be numeric).*/ y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]' z = translate( y, ,'[,]' ) /*change brackets&commas──►blanks*/ z = space(z) /*remove extraneous blanks. */ z = changestr( ' ', z, ", " ) /*change blanks to "comma blank".*/ z = '[' || z || "]" /*add brackets via concatenation.*/ - + /*another version of above: */ + z = '['z"]" say ' input =' y say 'output =' z /*stick a fork in it, we're done.*/ diff --git a/Task/Floyds-triangle/AutoHotkey/floyds-triangle-1.ahk b/Task/Floyds-triangle/AutoHotkey/floyds-triangle-1.ahk new file mode 100644 index 0000000000..b9cbcb27ce --- /dev/null +++ b/Task/Floyds-triangle/AutoHotkey/floyds-triangle-1.ahk @@ -0,0 +1,22 @@ +Floyds_triangle(row){ + i = 0 + loop %row% + { + n := A_Index + loop, %n% + { + m := n, j := i, i++ + while (m 0; $i--) { - for ($j = $i; $j < $n + 1; $j++) { - printf("%4s", $count); - $count++; + for($r = 1, $i = 1, $c = 0; $r <= $n; $i++) { + $cols = ceil(log10($n*($n-1)/2 + $c + 2)); + printf("%".$cols."d ", $i); + if(++$c == $r) { + echo "\r\n"; + $r++; + $c = 0; } - echo "\r\n"; } ?> diff --git a/Task/Floyds-triangle/TXR/floyds-triangle.txr b/Task/Floyds-triangle/TXR/floyds-triangle.txr new file mode 100644 index 0000000000..41a543bda8 --- /dev/null +++ b/Task/Floyds-triangle/TXR/floyds-triangle.txr @@ -0,0 +1,20 @@ +@(do + (defun flotri (n) + (let* ((last (trunc (* n (+ n 1)) 2)) + (colw (mapcar [chain tostring length] + (range (- last n -1) last))) + (x 0)) + (each ((r (range* 0 n))) + (each ((c (range 0 r))) + (format t " ~*a" [colw c] (inc x))) + (put-line)))) + + (defun usage (msg) + (put-line `error: @msg`) + (put-line `usage:\n@(ldiff *full-args* *args*) `) + (exit 1)) + + (tree-case *args* + ((num blah . etc) (usage "too many arguments")) + ((num) (flotri (int-str num))) + (() (usage "need an argument")))) diff --git a/Task/Forest-fire/PARI-GP/forest-fire.pari b/Task/Forest-fire/PARI-GP/forest-fire.pari new file mode 100644 index 0000000000..ec5594aef8 --- /dev/null +++ b/Task/Forest-fire/PARI-GP/forest-fire.pari @@ -0,0 +1,25 @@ +step(M,p,f)={ + my(m=matsize(M)[1],n=matsize(M)[2]); + matrix(m,n,i,j, + if(M[i,j]=="*", + " " + , + if(M[i,j]=="t", + my(nbr="t"); + for(x=max(1,i-1),min(m,i+1), + for(y=max(1,j-1),min(n,j+1), + if(M[x,y]=="*",nbr="*";break(2)) + ) + ); + if(random(1.) + {Result,_} = lists:mapfoldl(fun (N_2,N_1) -> {N_2 - N_1, N_2} end, X, Xs), + Result. + +difference([],_) -> []; +difference(List,0) -> List; +difference(List,Order) -> difference(difference(List),Order-1). + +task() -> + io:format("Initial: ~p~n",[?TEST_DATA]), + [io:format("~3b: ~p~n",[N,difference(?TEST_DATA,N)]) || N <- lists:seq(0,length(?TEST_DATA))], + ok. diff --git a/Task/Four-bit-adder/AutoHotkey/four-bit-adder.ahk b/Task/Four-bit-adder/AutoHotkey/four-bit-adder.ahk new file mode 100644 index 0000000000..3935dcf82e --- /dev/null +++ b/Task/Four-bit-adder/AutoHotkey/four-bit-adder.ahk @@ -0,0 +1,42 @@ +A := 13 +B := 9 +N := FourBitAdd(A, B) +MsgBox, % A " + " B ":`n" + . GetBin4(A) " + " GetBin4(B) " = " N.S " (Carry = " N.C ")" +return + +Xor(A, B) { + return (~A & B) | (A & ~B) +} + +HalfAdd(A, B) { + return {"S": Xor(A, B), "C": A & B} +} + +FullAdd(A, B, C=0) { + X := HalfAdd(A, C) + Y := HalfAdd(B, X.S) + return {"S": Y.S, "C": X.C | Y.C} +} + +FourBitAdd(A, B, C=0) { + A := GetFourBits(A) + B := GetFourBits(B) + X := FullAdd(A[4], B[4], C) + Y := FullAdd(A[3], B[3], X.C) + W := FullAdd(A[2], B[2], Y.C) + Z := FullAdd(A[1], B[1], W.C) + return {"S": Z.S W.S Y.S X.S, "C": Z.C} +} + +GetFourBits(N) { + if (N < 0 || N > 15) + return -1 + return StrSplit(GetBin4(N)) +} + +GetBin4(N) { + Loop 4 + Res := Mod(N, 2) Res, N := N >> 1 + return, Res +} diff --git a/Task/Fractal-tree/AutoHotkey/fractal-tree.ahk b/Task/Fractal-tree/AutoHotkey/fractal-tree.ahk new file mode 100644 index 0000000000..b7e34ed398 --- /dev/null +++ b/Task/Fractal-tree/AutoHotkey/fractal-tree.ahk @@ -0,0 +1,66 @@ +#SingleInstance, Force +#NoEnv +SetBatchLines, -1 + +; Uncomment if Gdip.ahk is not in your standard library +; #Include, Gdip.ahk + +FileOut := A_Desktop "\MyNewFile.png" +TreeColor := 0xff0066ff ; ARGB +TrunkWidth := 10 ; Pixels +TrunkLength := 80 ; Pixels +Angle := 60 ; Degrees +ImageWidth := 670 ; Pixels +ImageHeight := 450 ; Pixels +Branches := 13 +Decrease := 0.81 + +Angle := (Angle * 0.01745329252) / 2 + , Points := {} + , Points[1, "Angle"] := 0 + , Points[1, "X"] := ImageWidth // 2 + , Points[1, "Y"] := ImageHeight - TrunkLength + +if (!pToken := Gdip_Startup()) { + MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. + ExitApp +} +OnExit, Exit + +pBitmap := Gdip_CreateBitmap(ImageWidth, ImageHeight) + , G := Gdip_GraphicsFromImage(pBitmap) + , Gdip_SetSmoothingMode(G, 4) + , pBrush := Gdip_BrushCreateSolid(0xff000000) + , Gdip_FillRectangle(G, pBrush, -5, -5, ImageWidth + 10, ImageHeight + 10) + , Gdip_DeleteBrush(pBrush) + , pPen := Gdip_CreatePen(TreeColor, TrunkWidth/Decrease) + , Gdip_DrawLine(G, pPen, Points.1.X, Points.1.Y, Points.1.X, ImageHeight) + , Gdip_DeletePen(pPen) + +Loop, % Branches { + NewPoints := {} + pPen := Gdip_CreatePen(TreeColor, TrunkWidth) + for Each, Point in Points { + N1 := A_Index * 2 + , N2 := (A_Index * 2) + 1 + , NewPoints[N1, "X"] := Point.X + (TrunkLength * Sin(NewPoints[N1, "Angle"] := Point.Angle - Angle)) + , NewPoints[N1, "Y"] := Point.Y - (TrunkLength * Cos(NewPoints[N1].Angle)) + , NewPoints[N2, "X"] := Point.X + (TrunkLength * Sin(NewPoints[N2, "Angle"] := Point.Angle + Angle)) + , NewPoints[N2, "Y"] := Point.Y - (TrunkLength * Cos(NewPoints[N2].Angle)) + , Gdip_DrawLine(G, pPen, Point.X, Point.Y, NewPoints[N1].X, NewPoints[N1].Y) + , Gdip_DrawLine(G, pPen, Point.X, Point.Y, NewPoints[N2].X, NewPoints[N2].Y) + } + TrunkWidth *= Decrease + , TrunkLength *= Decrease + , Points := NewPoints + , Gdip_DeletePen(pPen) +} + +Gdip_SaveBitmapToFile(pBitmap, FileOut) + , Gdip_DisposeImage(pBitmap) + , Gdip_DeleteGraphics(G) +Run, % FileOut + +Exit: +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Fractal-tree/Smalltalk/fractal-tree-1.st b/Task/Fractal-tree/Smalltalk/fractal-tree-1.st new file mode 100644 index 0000000000..e116130169 --- /dev/null +++ b/Task/Fractal-tree/Smalltalk/fractal-tree-1.st @@ -0,0 +1,5 @@ +Object subclass: #FractalTree + instanceVariableNames: '' + classVariableNames: '' + poolDictionaries: '' + category: 'RosettaCode' diff --git a/Task/Fractal-tree/Smalltalk/fractal-tree-2.st b/Task/Fractal-tree/Smalltalk/fractal-tree-2.st new file mode 100644 index 0000000000..dce2053009 --- /dev/null +++ b/Task/Fractal-tree/Smalltalk/fractal-tree-2.st @@ -0,0 +1,25 @@ +tree: aPoint length: aLength angle: anAngle + | p a | + + (aLength > 10) ifTrue: [ + p := Pen new. + p up. + p goto: aPoint. + p turn: anAngle. + p down. + 5 timesRepeat: [ + p go: aLength / 5. + p turn: 5. + ]. + a := anAngle - 30. + 3 timesRepeat: [ + self tree: p location length: aLength * 0.7 angle: a. + a := a + 30. + ] + ]. + +draw + Display restoreAfter: [ + Display fillWhite. + self tree: 700@700 length: 200 angle: 0. + ] diff --git a/Task/Fractal-tree/Smalltalk/fractal-tree-3.st b/Task/Fractal-tree/Smalltalk/fractal-tree-3.st new file mode 100644 index 0000000000..75e8a8742d --- /dev/null +++ b/Task/Fractal-tree/Smalltalk/fractal-tree-3.st @@ -0,0 +1 @@ +FractalTree new draw. diff --git a/Task/Function-composition/Applesoft-BASIC/function-composition.applesoft b/Task/Function-composition/Applesoft-BASIC/function-composition.applesoft new file mode 100644 index 0000000000..b3dbdfb5a1 --- /dev/null +++ b/Task/Function-composition/Applesoft-BASIC/function-composition.applesoft @@ -0,0 +1,18 @@ +10 F$ = "SIN" +20 DEF FN A(P) = ATN(P/SQR(-P*P+1)) +30 G$ = "FN A" +40 GOSUB 100"COMPOSE +50 SA$ = E$ + +60 X = .5 : E$ = SA$ +70 GOSUB 200"EXEC +80 PRINT R +90 END + +100 E$ = F$ + "(" + G$ + "(X))" : RETURN : REMCOMPOSE F$ G$ + +200 D$ = CHR$(4) : FI$ = "TEMPORARY.EX" : M$ = CHR$(13) +210 PRINT D$"OPEN"FI$M$D$"CLOSE"FI$M$D$"DELETE"FI$ +220 PRINT D$"OPEN"FI$M$D$"WRITE"FI$ +230 PRINT "CALL-998:CALL-958:R="E$":CONT" +240 PRINT D$"CLOSE"FI$M$D$"EXEC"FI$:CALL-998:END:RETURN diff --git a/Task/Function-composition/Objective-C/function-composition.m b/Task/Function-composition/Objective-C/function-composition.m new file mode 100644 index 0000000000..e61ca4c4e9 --- /dev/null +++ b/Task/Function-composition/Objective-C/function-composition.m @@ -0,0 +1,42 @@ +#include + +typedef id (^Function)(id); + +// a commodity for "encapsulating" double f(double) +typedef double (*func_t)(double); +Function encapsulate(func_t f) { + return ^(id x) { return @(f([x doubleValue])); }; +} + +Function compose(Function a, Function b) { + return ^(id x) { return a(b(x)); }; +} + +// functions outside... +double my_f(double x) +{ + return x+1.0; +} + +double my_g(double x) +{ + return x*x; +} + + +int main() +{ + @autoreleasepool { + + Function f = encapsulate(my_f); + Function g = encapsulate(my_g); + + Function composed = compose(f, g); + + printf("g(2.0) = %lf\n", [g(@2.0) doubleValue]); + printf("f(2.0) = %lf\n", [f(@2.0) doubleValue]); + printf("f(g(2.0)) = %lf\n", [composed(@2.0) doubleValue]); + + } + return 0; +} diff --git a/Task/Function-composition/Perl-6/function-composition-1.pl6 b/Task/Function-composition/Perl-6/function-composition-1.pl6 index ef83bff83d..a66e2270c3 100644 --- a/Task/Function-composition/Perl-6/function-composition-1.pl6 +++ b/Task/Function-composition/Perl-6/function-composition-1.pl6 @@ -1,3 +1,3 @@ sub infix:<∘> (&f, &g --> Block) { - -> $args { f g |$args } + -> |args { f g |args } } diff --git a/Task/Function-definition/JavaScript/function-definition-1.js b/Task/Function-definition/JavaScript/function-definition-1.js index 857d0eafeb..e35507636b 100644 --- a/Task/Function-definition/JavaScript/function-definition-1.js +++ b/Task/Function-definition/JavaScript/function-definition-1.js @@ -1 +1,3 @@ -function multiply(a,b) { return a*b } +function multiply(a, b) { + return a*b; +} diff --git a/Task/Function-definition/JavaScript/function-definition-2.js b/Task/Function-definition/JavaScript/function-definition-2.js index d2f1f34400..627c6a91cf 100644 --- a/Task/Function-definition/JavaScript/function-definition-2.js +++ b/Task/Function-definition/JavaScript/function-definition-2.js @@ -1,3 +1,3 @@ -var multiply = function (a, b) { +var multiply = function(a, b) { return a * b; }; diff --git a/Task/Function-definition/JavaScript/function-definition-3.js b/Task/Function-definition/JavaScript/function-definition-3.js new file mode 100644 index 0000000000..2202ad9e3d --- /dev/null +++ b/Task/Function-definition/JavaScript/function-definition-3.js @@ -0,0 +1,3 @@ +var multiply = function multiply(a, b) { + return a * b; +}; diff --git a/Task/Function-definition/JavaScript/function-definition-4.js b/Task/Function-definition/JavaScript/function-definition-4.js new file mode 100644 index 0000000000..72baaf9c81 --- /dev/null +++ b/Task/Function-definition/JavaScript/function-definition-4.js @@ -0,0 +1,5 @@ +var o = { + multiply: function(a, b) { + return a * b; + } +}; diff --git a/Task/Function-definition/JavaScript/function-definition-5.js b/Task/Function-definition/JavaScript/function-definition-5.js new file mode 100644 index 0000000000..b0f2b7ff62 --- /dev/null +++ b/Task/Function-definition/JavaScript/function-definition-5.js @@ -0,0 +1,8 @@ +var o = { + get foo() { + return 1; + }, + set bar(value) { + // do things with value + } +}; diff --git a/Task/Function-definition/JavaScript/function-definition-6.js b/Task/Function-definition/JavaScript/function-definition-6.js new file mode 100644 index 0000000000..60d2fdb755 --- /dev/null +++ b/Task/Function-definition/JavaScript/function-definition-6.js @@ -0,0 +1,2 @@ +var multiply = (a, b) => a * b; +var multiply = (a, b) => { return a * b }; diff --git a/Task/Function-definition/JavaScript/function-definition-7.js b/Task/Function-definition/JavaScript/function-definition-7.js new file mode 100644 index 0000000000..135aa6939e --- /dev/null +++ b/Task/Function-definition/JavaScript/function-definition-7.js @@ -0,0 +1,5 @@ +var o = { + multiply(a, b) { + return a * b; + } +}; diff --git a/Task/Function-definition/JavaScript/function-definition-8.js b/Task/Function-definition/JavaScript/function-definition-8.js new file mode 100644 index 0000000000..956931a60f --- /dev/null +++ b/Task/Function-definition/JavaScript/function-definition-8.js @@ -0,0 +1,3 @@ +function * generator() { + yield 1; +} diff --git a/Task/Function-prototype/JavaScript/function-prototype-1.js b/Task/Function-prototype/JavaScript/function-prototype-1.js new file mode 100644 index 0000000000..5e9ffd61af --- /dev/null +++ b/Task/Function-prototype/JavaScript/function-prototype-1.js @@ -0,0 +1,36 @@ +// A prototype declaration for a function that does not require arguments +function List() {} + +List.prototype.push = function() { + return [].push.apply(this, arguments); +}; + +List.prototype.pop = function() { + return [].pop.call(this); +}; + +var l = new List(); +l.push(5); +l.length; // 1 +l[0]; 5 +l.pop(); // 5 +l.length; // 0 + +// A prototype declaration for a function that utilizes varargs +function List() { + this.push.apply(this, arguments); +} + +List.prototype.push = function() { + return [].push.apply(this, arguments); +}; + +List.prototype.pop = function() { + return [].pop.call(this); +}; + +var l = new List(5, 10, 15); +l.length; // 3 +l[0]; 5 +l.pop(); // 15 +l.length; // 2 diff --git a/Task/Function-prototype/JavaScript/function-prototype-2.js b/Task/Function-prototype/JavaScript/function-prototype-2.js new file mode 100644 index 0000000000..67d921f057 --- /dev/null +++ b/Task/Function-prototype/JavaScript/function-prototype-2.js @@ -0,0 +1,37 @@ +// A prototype declaration for a function that does not require arguments +class List { + push() { + return [].push.apply(this, arguments); + } + pop() { + return [].pop.call(this); + } +} + +var l = new List(); +l.push(5); +l.length; // 1 +l[0]; 5 +l.pop(); // 5 +l.length; // 0 + + + +// A prototype declaration for a function that utilizes varargs +class List { + constructor(...args) { + this.push(...args); + } + push() { + return [].push.apply(this, arguments); + } + pop() { + return [].pop.call(this); + } +} + +var l = new List(5, 10, 15); +l.length; // 3 +l[0]; 5 +l.pop(); // 15 +l.length; // 2 diff --git a/Task/Function-prototype/JavaScript/function-prototype.js b/Task/Function-prototype/JavaScript/function-prototype.js deleted file mode 100644 index cac1e81cfe..0000000000 --- a/Task/Function-prototype/JavaScript/function-prototype.js +++ /dev/null @@ -1,4 +0,0 @@ -var randomFunction=function(a){this.someNumber=a;}; //Doesn't matter when the function uses parameters, named arguments, no arguments, or if it doesn't return nothing at all. -randomFunction.prototype.getSomeNumber=function(){return this.someNumber;} -randomFunction.prototype.setSomeNumber=function(a){return this.someNumber=a;}//editing prototype explicitly -(new randomFunction(7)).getSomeNumber();//7 diff --git a/Task/GUI-Maximum-window-dimensions/AutoHotkey/gui-maximum-window-dimensions.ahk b/Task/GUI-Maximum-window-dimensions/AutoHotkey/gui-maximum-window-dimensions.ahk new file mode 100644 index 0000000000..4b1ee90d49 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/AutoHotkey/gui-maximum-window-dimensions.ahk @@ -0,0 +1,15 @@ +SysGet, MonitorCount, MonitorCount +SysGet, MonitorPrimary, MonitorPrimary +MsgBox, Monitor Count:`t%MonitorCount%`nPrimary Monitor:`t%MonitorPrimary% +Loop, %MonitorCount% +{ + SysGet, MonitorName, MonitorName, %A_Index% + SysGet, Monitor, Monitor, %A_Index% + SysGet, MonitorWorkArea, MonitorWorkArea, %A_Index% + MsgBox, % "Monitor:`t#" A_Index + . "`nName:`t" MonitorName + . "`nLeft:`t" MonitorLeft "(" MonitorWorkAreaLeft " work)" + . "`nTop:`t" MonitorTop " (" MonitorWorkAreaTop " work)" + . "`nRight:`t" MonitorRight " (" MonitorWorkAreaRight " work)" + . "`nBottom:`t" MonitorBottom " (" MonitorWorkAreaBottom " work)" +} diff --git a/Task/GUI-Maximum-window-dimensions/Groovy/gui-maximum-window-dimensions.groovy b/Task/GUI-Maximum-window-dimensions/Groovy/gui-maximum-window-dimensions.groovy new file mode 100644 index 0000000000..d43740dba8 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Groovy/gui-maximum-window-dimensions.groovy @@ -0,0 +1,3 @@ +def window = java.awt.GraphicsEnvironment.localGraphicsEnvironment.maximumWindowBounds + +println "width: $window.width, height: $window.height" diff --git a/Task/GUI-Maximum-window-dimensions/PARI-GP/gui-maximum-window-dimensions.pari b/Task/GUI-Maximum-window-dimensions/PARI-GP/gui-maximum-window-dimensions.pari new file mode 100644 index 0000000000..4012b9b304 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/PARI-GP/gui-maximum-window-dimensions.pari @@ -0,0 +1 @@ +plothsizes()[1..2] diff --git a/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin b/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin new file mode 100644 index 0000000000..c9844ec7fe --- /dev/null +++ b/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin @@ -0,0 +1,58 @@ +import java.awt.GridLayout +import java.awt.event.ActionEvent +import java.awt.event.ActionListener +import java.awt.event.KeyEvent +import java.awt.event.KeyListener + +import java.lang.Long // jet.Long doesn't suit our needs here +import javax.swing.JButton +import javax.swing.JFrame +import javax.swing.JOptionPane +import javax.swing.JPanel +import javax.swing.JTextField + +class Interact : JFrame() { + val numberField = JTextField() + val incButton = JButton("Increment") + val randButton = JButton("Random") + val buttonPanel = JPanel(); + + { + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) + numberField setText "0" + + numberField addKeyListener(object : KeyListener { + public override fun keyTyped(e : KeyEvent) : Unit = + if(!Character.isDigit(e.getKeyChar())) e.consume() + public override fun keyReleased(e : KeyEvent?) {} + public override fun keyPressed(e : KeyEvent) {} + }); + + incButton addActionListener(object : ActionListener { + public override fun actionPerformed(e : ActionEvent) { + val num = Long.parseLong(numberField.getText() ?: "") + numberField setText (num + 1).toString() + } + }); + + randButton addActionListener(object : ActionListener { + fun proceedOrNot() = JOptionPane.showConfirmDialog(randButton, "Are you sure?") + public override fun actionPerformed(e : ActionEvent) { + if(proceedOrNot() == JOptionPane.YES_OPTION) + numberField setText Long.toString((Math.random() * Long.MAX_VALUE).toLong()) + } + }); + + setLayout(GridLayout(2, 1)) + buttonPanel setLayout GridLayout(1, 2) + buttonPanel add incButton + buttonPanel add randButton + add(numberField) + add(buttonPanel) + pack() + } +} + +fun main(args : Array) { + Interact() setVisible(true) +} diff --git a/Task/Gamma-function/D/gamma-function.d b/Task/Gamma-function/D/gamma-function.d index 5648911d59..6311cf822c 100644 --- a/Task/Gamma-function/D/gamma-function.d +++ b/Task/Gamma-function/D/gamma-function.d @@ -1,17 +1,22 @@ -import std.stdio, std.mathspecial; +import std.stdio, std.math, std.mathspecial; -real myGamma(in real x) pure nothrow { +real taylorGamma(in real x) pure nothrow { static immutable real[30] table = [ - 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, --0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675, --0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511, --0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824, --0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776, - 0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049, - 0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562, - 0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812, - 0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119, - 0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002]; + 0x1p+0, 0x1.2788cfc6fb618f4cp-1, + -0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5, + 0x1.5512320b43fbe5dep-3, -0x1.59af103c340927bep-5, + -0x1.3b4af28483e214e4p-7, 0x1.d919c527f60b195ap-8, + -0x1.317112ce3a2a7bd2p-10, -0x1.c364fe6f1563ce9cp-13, + 0x1.0c8a78cd9f9d1a78p-13, -0x1.51ce8af47eabdfdcp-16, + -0x1.4fad41fc34fbb2p-20, 0x1.302509dbc0de2c82p-20, + -0x1.b9986666c225d1d4p-23, 0x1.a44b7ba22d628acap-28, + 0x1.57bc3fc384333fb2p-28, -0x1.44b4cedca388f7c6p-30, + 0x1.cae7675c18606c6p-34, 0x1.11d065bfaf06745ap-37, + -0x1.0423bac8ca3faaa4p-38, 0x1.1f20151323cd0392p-41, + -0x1.72cb88ea5ae6e778p-46, -0x1.815f72a05f16f348p-48, + 0x1.6198491a83bccbep-50, -0x1.10613dde57a88bd6p-53, + 0x1.5e3fee81de0e9c84p-60, 0x1.a0dc770fb8a499b6p-60, + -0x1.0f635344a29e9f8ep-62, 0x1.43d79a4b90ce8044p-66]; immutable real y = x - 1.0L; real sm = table[$ - 1]; @@ -20,9 +25,38 @@ real myGamma(in real x) pure nothrow { return 1.0L / sm; } +real lanczosGamma(real z) pure nothrow { + // Coefficients used by the GNU Scientific Library. + // http://en.wikipedia.org/wiki/Lanczos_approximation + enum g = 7; + static immutable real[9] table = + [ 0.99999_99999_99809_93, + 676.52036_81218_851, + -1259.13921_67224_028, + 771.32342_87776_5313, + -176.61502_91621_4059, + 12.50734_32786_86905, + -0.13857_10952_65720_12, + 9.98436_95780_19571_6e-6, + 1.50563_27351_49311_6e-7]; + + // Reflection formula. + if (z < 0.5L) { + return PI / (sin(PI * z) * lanczosGamma(1 - z)); + } else { + z -= 1; + real x = table[0]; + foreach (immutable i; 1 .. g + 2) + x += table[i] / (z + i); + immutable real t = z + g + 0.5L; + return sqrt(2 * PI) * t ^^ (z + 0.5L) * exp(-t) * x; + } +} + void main() { foreach (immutable i; 1 .. 11) { immutable real x = i / 3.0L; - writefln("%f: %20.19e %20.19e", x, myGamma(x), gamma(x)); + writefln("%f: %20.19e %20.19e %20.19e", x, + x.taylorGamma, x.lanczosGamma, x.gamma); } } diff --git a/Task/Gamma-function/Forth/gamma-function.fth b/Task/Gamma-function/Forth/gamma-function.fth new file mode 100644 index 0000000000..757a5221d8 --- /dev/null +++ b/Task/Gamma-function/Forth/gamma-function.fth @@ -0,0 +1,15 @@ +8 constant (gamma-shift) + +: (mortici) ( f1 -- f2) + -1 s>f f+ 1 s>f + fover 271828183e-8 f* 12 s>f f* f/ + fover 271828183e-8 f/ f+ + fover f** fswap + 628318530e-8 f* fsqrt f* \ 2*pi +; + +: gamma ( f1 -- f2) + fdup f0< >r fdup f0= r> or abort" Gamma less or equal to zero" + fdup (gamma-shift) s>f f+ (mortici) fswap + 1 s>f (gamma-shift) 0 do fover i s>f f+ f* loop fswap fdrop f/ +; diff --git a/Task/Gamma-function/Limbo/gamma-function.limbo b/Task/Gamma-function/Limbo/gamma-function.limbo new file mode 100644 index 0000000000..8e1b4ee362 --- /dev/null +++ b/Task/Gamma-function/Limbo/gamma-function.limbo @@ -0,0 +1,44 @@ +implement Lanczos7; + +include "sys.m"; sys: Sys; +include "draw.m"; +include "math.m"; math: Math; + lgamma, exp, pow, sqrt: import math; + +Lanczos7: module { + init: fn(nil: ref Draw->Context, nil: list of string); +}; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + math = load Math Math->PATH; + # We ignore some floating point exceptions: + math->FPcontrol(0, Math->OVFL|Math->UNFL); + ns : list of real = -0.5 :: 0.1 :: 0.5 :: 1.0 :: 1.5 :: 2.0 :: 3.0 :: 10.0 :: 140.0 :: 170.0 :: nil; + + sys->print("%5s %24s %24s\n", "x", "math->lgamma", "lanczos7"); + while(ns != nil) { + x := hd ns; + ns = tl ns; + # math->lgamma returns a tuple. + (i, r) := lgamma(x); + g := real i * exp(r); + sys->print("%5.1f %24.16g %24.16g\n", x, g, lanczos7(x)); + } +} + +lanczos7(z: real): real +{ + t := z + 6.5; + x := 0.99999999999980993 + + 676.5203681218851/z - + 1259.1392167224028/(z+1.0) + + 771.32342877765313/(z+2.0) - + 176.61502916214059/(z+3.0) + + 12.507343278686905/(z+4.0) - + 0.13857109526572012/(z+5.0) + + 9.9843695780195716e-6/(z+6.0) + + 1.5056327351493116e-7/(z+7.0); + return sqrt(2.0) * sqrt(Math->Pi) * pow(t, z - 0.5) * exp(-t) * x; +} diff --git a/Task/Gamma-function/Perl-6/gamma-function.pl6 b/Task/Gamma-function/Perl-6/gamma-function.pl6 index a3de210984..aa0f5ac7dc 100644 --- a/Task/Gamma-function/Perl-6/gamma-function.pl6 +++ b/Task/Gamma-function/Perl-6/gamma-function.pl6 @@ -1,18 +1,51 @@ -sub Γ($x) { - 1 / < - 0.00000_00000_00000_00002 -0.00000_00000_00000_00023 0.00000_00000_00000_00141 - 0.00000_00000_00000_00119 -0.00000_00000_00000_11813 0.00000_00000_00001_22678 - -0.00000_00000_00005_34812 -0.00000_00000_00020_58326 0.00000_00000_00510_03703 - -0.00000_00000_03696_80562 0.00000_00000_07782_26344 0.00000_00001_04342_67117 - -0.00000_00011_81274_57049 0.00000_00050_02007_64447 0.00000_00061_16095_10448 - -0.00000_02056_33841_69776 0.00000_11330_27231_98170 -0.00000_12504_93482_14267 - -0.00002_01348_54780_78824 0.00012_80502_82388_11619 -0.00021_52416_74114_95097 - -0.00116_51675_91859_06511 0.00721_89432_46663_09954 -0.00962_19715_27876_97356 - -0.04219_77345_55544_33675 0.16653_86113_82291_48950 -0.04200_26350_34095_23553 - -0.65587_80715_20253_88108 0.57721_56649_01532_86061 1.00000_00000_00000_00000 - >.reduce: * *($x-1) + * +sub Γ(\z, :$method = 'lanczos') { + given $method { + when 'lanczos' { + constant g = 9; + z < .5 ?? pi/ sin(pi * z) / Γ(1 - z, :$method) !! + sqrt(2*pi) * + (z + g - 1/2)**(z - 1/2) * + exp(-(z + g - 1/2)) * + [+] < + 1.000000000000000174663 + 5716.400188274341379136 + -14815.30426768413909044 + 14291.49277657478554025 + -6348.160217641458813289 + 1301.608286058321874105 + -108.1767053514369634679 + 2.605696505611755827729 + -0.7423452510201416151527e-2 + 0.5384136432509564062961e-7 + -0.4023533141268236372067e-8 + > Z* 1, map 1/(z + *), 0..* + } + when 'stirling' { + z < 10 ?? Γ(z + 1, :$method) / z !! + sqrt(2*pi*z)*(z/e + 1/(12*z*e))**z / z + } + when 'taylor' { + z > 3/2 ?? (z - 1)*Γ(z - 1, :$method) !! + z < 1/2 ?? Γ(z + 1, :$method)/z !! + 1 / < + 0.00000_00000_00000_00002 -0.00000_00000_00000_00023 0.00000_00000_00000_00141 + 0.00000_00000_00000_00119 -0.00000_00000_00000_11813 0.00000_00000_00001_22678 + -0.00000_00000_00005_34812 -0.00000_00000_00020_58326 0.00000_00000_00510_03703 + -0.00000_00000_03696_80562 0.00000_00000_07782_26344 0.00000_00001_04342_67117 + -0.00000_00011_81274_57049 0.00000_00050_02007_64447 0.00000_00061_16095_10448 + -0.00000_02056_33841_69776 0.00000_11330_27231_98170 -0.00000_12504_93482_14267 + -0.00002_01348_54780_78824 0.00012_80502_82388_11619 -0.00021_52416_74114_95097 + -0.00116_51675_91859_06511 0.00721_89432_46663_09954 -0.00962_19715_27876_97356 + -0.04219_77345_55544_33675 0.16653_86113_82291_48950 -0.04200_26350_34095_23553 + -0.65587_80715_20253_88108 0.57721_56649_01532_86061 1.00000_00000_00000_00000 + >.reduce: * *(z-1) + * + } + default { die "unknow method '$method'" } + } } -  -for 1/3, 2/3 ... 10/3 { - printf "Γ(%.5f) ≈ %.14f\n", $_, Γ($_); + +for -> $method { + # a bug in fmt forces us to round numbers before displaying them + say "{$method.fmt("%10s")}: ", + map { Γ($_, :$method).round(1e-12).fmt("%.12f") }, (1/3, 2/3 ... 10/3); } diff --git a/Task/Gamma-function/Perl/gamma-function.pl b/Task/Gamma-function/Perl/gamma-function.pl index 9760ce5ad3..4c57070b88 100644 --- a/Task/Gamma-function/Perl/gamma-function.pl +++ b/Task/Gamma-function/Perl/gamma-function.pl @@ -1,44 +1,61 @@ -my @coeff = reverse ; +use strict; +use warnings; +use constant pi => 4*atan2(1, 1); +use constant e => exp(1); + sub Gamma { - my $x = shift; - my $s; - $s = $s*($x-1) + $_ for @coeff; - return 1 / $s; + my $z = shift; + my $method = shift // 'lanczos'; + if ($method eq 'lanczos') { + use constant g => 9; + $z < .5 ? pi / sin(pi * $z) / Gamma(1 - $z, $method) : + sqrt(2* pi) * + ($z + g - .5)**($z - .5) * + exp(-($z + g - .5)) * + do { + my @coeff = qw{ + 1.000000000000000174663 + 5716.400188274341379136 + -14815.30426768413909044 + 14291.49277657478554025 + -6348.160217641458813289 + 1301.608286058321874105 + -108.1767053514369634679 + 2.605696505611755827729 + -0.7423452510201416151527e-2 + 0.5384136432509564062961e-7 + -0.4023533141268236372067e-8 + }; + my ($sum, $i) = (shift(@coeff), 0); + $sum += $_ / ($z + $i++) for @coeff; + $sum; + } + } elsif ($method eq 'taylor') { + $z < .5 ? Gamma($z+1, $method)/$z : + $z > 1.5 ? ($z-1)*Gamma($z-1, $method) : + do { + my $s = 0; ($s *= $z-1) += $_ for qw{ + 0.00000000000000000002 -0.00000000000000000023 0.00000000000000000141 + 0.00000000000000000119 -0.00000000000000011813 0.00000000000000122678 + -0.00000000000000534812 -0.00000000000002058326 0.00000000000051003703 + -0.00000000000369680562 0.00000000000778226344 0.00000000010434267117 + -0.00000000118127457049 0.00000000500200764447 0.00000000611609510448 + -0.00000020563384169776 0.00000113302723198170 -0.00000125049348214267 + -0.00002013485478078824 0.00012805028238811619 -0.00021524167411495097 + -0.00116516759185906511 0.00721894324666309954 -0.00962197152787697356 + -0.04219773455554433675 0.16653861138229148950 -0.04200263503409523553 + -0.65587807152025388108 0.57721566490153286061 1.00000000000000000000 + }; 1/$s; + } + } elsif ($method eq 'stirling') { + no warnings qw(recursion); + $z < 100 ? Gamma($z + 1, $method)/$z : + sqrt(2*pi*$z)*($z/e + 1/(12*e*$z))**$z / $z; + } else { die "unknown method '$method'" } } -for (1 .. 10) { - $_ /= 3; - printf "Gamma(%.5f) ≈ %.14e\n", $_, Gamma($_); +for my $method (qw(lanczos taylor stirling)) { + printf "%10s: ", $method; + print join(' ', map { sprintf "%.12f", Gamma($_/3, $method) } 1 .. 10); + print "\n"; } - -__DATA__ -1.00000000000000000000 -0.57721566490153286061 --0.65587807152025388108 --0.04200263503409523553 -0.16653861138229148950 --0.04219773455554433675 --0.00962197152787697356 -0.00721894324666309954 --0.00116516759185906511 --0.00021524167411495097 -0.00012805028238811619 --0.00002013485478078824 --0.00000125049348214267 -0.00000113302723198170 --0.00000020563384169776 -0.00000000611609510448 -0.00000000500200764447 --0.00000000118127457049 -0.00000000010434267117 -0.00000000000778226344 --0.00000000000369680562 -0.00000000000051003703 --0.00000000000002058326 --0.00000000000000534812 -0.00000000000000122678 --0.00000000000000011813 -0.00000000000000000119 -0.00000000000000000141 --0.00000000000000000023 -0.00000000000000000002 diff --git a/Task/Gamma-function/REXX/gamma-function.rexx b/Task/Gamma-function/REXX/gamma-function.rexx index 37abdfca58..d94e1abc60 100644 --- a/Task/Gamma-function/REXX/gamma-function.rexx +++ b/Task/Gamma-function/REXX/gamma-function.rexx @@ -1,70 +1,68 @@ /*REXX pgm calculates GAMMA using Taylor series coefficients, ≈80 digits*/ - /*The GAMMA function symbol is the Greek cap letter: Γ */ -numeric digits 82 /*able to use extended precision.*/ -parse arg y . /*allow specification of Γ arg.*/ - /*either show a range or a */ - do j=word(y 1,1) to word(y 9,1) /* single gamma value(s). */ - say 'gamma('j") =" gamma(j) /*compute gamma of J and display.*/ - end /*j*/ -exit /*stick a fork in it, we're done.*/ - + /*The GAMMA function symbol is the Greek capital letter: Γ */ +numeric digits 84 /*able to use extended precision.*/ +parse arg y z . /*allow specification of Γ arg.*/ + /*either show a range or a ··· */ + do j=word(y 1,1) to word(z y 9,1) /* ··· single gamma value(s). */ + say 'gamma('j") =" gamma(j) /*compute gamma of J and display.*/ + end /*j*/ exit /*stick a fork in it, we're done.*/ /*───────────────────────────────────GAMMA subroutine=──────────────────*/ gamma: procedure; parse arg x; xm=x-1; sum=0 - #.1= 1 /*#.2 is the Euler-Mascheroni constant.*/ - /*coefficients thanks to: Arne Fransén and Staffan Wrigge.*/ - #.2= 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 - #.3=-0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 - #.4=-0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 - #.5= 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 - #.6=-0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 - #.7=-0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 - #.8= 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 - #.9=-0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 -#.10=-0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 -#.11= 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 -#.12=-0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 -#.13=-0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 -#.14= 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 -#.15=-0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 -#.16= 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 -#.17= 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 -#.18=-0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 -#.19= 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 -#.20= 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 -#.21=-0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 -#.22= 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 -#.23=-0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 -#.24=-0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 -#.25= 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 -#.26=-0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 -#.27= 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 -#.28= 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 -#.29=-0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 -#.30= 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 -#.31= 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 -#.32=-0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 -#.33= 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 -#.34=-0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 -#.35=-0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 -#.36= 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 -#.37=-0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 -#.38= 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 -#.39= 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 -#.40=-0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 -#.41= 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 -#.42=-0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 -#.43= 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 -#.44= 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 -#.45=-0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 -#.46= 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 -#.47=-0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 -#.48=-0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 -#.49= 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 -#.50=-0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 -#.51= 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 -#.52= 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 + /*coefficients thanks to: Arne Fransén and Staffan Wrigge.*/ + #.1 = 1 /* [↓] #.2 is the Euler-Mascheroni constant.*/ + #.2 = 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 + #.3 = -0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 + #.4 = -0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 + #.5 = 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 + #.6 = -0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 + #.7 = -0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 + #.8 = 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 + #.9 = -0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 +#.10 = -0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 +#.11 = 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 +#.12 = -0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 +#.13 = -0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 +#.14 = 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 +#.15 = -0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 +#.16 = 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 +#.17 = 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 +#.18 = -0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 +#.19 = 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 +#.20 = 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 +#.21 = -0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 +#.22 = 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 +#.23 = -0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 +#.24 = -0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 +#.25 = 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 +#.26 = -0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 +#.27 = 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 +#.28 = 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 +#.29 = -0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 +#.30 = 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 +#.31 = 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 +#.32 = -0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 +#.33 = 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 +#.34 = -0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 +#.35 = -0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 +#.36 = 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 +#.37 = -0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 +#.38 = 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 +#.39 = 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 +#.40 = -0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 +#.41 = 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 +#.42 = -0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 +#.43 = 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 +#.44 = 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 +#.45 = -0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 +#.46 = 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 +#.47 = -0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 +#.48 = -0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 +#.49 = 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 +#.50 = -0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 +#.51 = 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 +#.52 = 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 do j=52 by -1 to 1 sum = sum * xm + #.j - end /*j*/ + end /*j*/ return 1/sum diff --git a/Task/Generic-swap/REXX/generic-swap-1.rexx b/Task/Generic-swap/REXX/generic-swap-1.rexx index 45adc1d8e1..284f85ee14 100644 --- a/Task/Generic-swap/REXX/generic-swap-1.rexx +++ b/Task/Generic-swap/REXX/generic-swap-1.rexx @@ -1,6 +1,6 @@ -a = 'some value' -b = 6 +a = 'I see you.' +b = -6 -_temp_ = a - a = b - b = _temp_ +_temp_ = a /*swap ··· */ + a = b /* A ··· */ + b = _temp_ /* and B */ diff --git a/Task/Generic-swap/REXX/generic-swap-2.rexx b/Task/Generic-swap/REXX/generic-swap-2.rexx index 9d42c5887f..40ca18685e 100644 --- a/Task/Generic-swap/REXX/generic-swap-2.rexx +++ b/Task/Generic-swap/REXX/generic-swap-2.rexx @@ -1,4 +1,4 @@ -a = -199e-12 -b = 12. +a = "bull feathers" +b = 10 -parse value a b with b a /*swaps A and B */ +a=value('b', a) /*swap A and B */ diff --git a/Task/Generic-swap/REXX/generic-swap-3.rexx b/Task/Generic-swap/REXX/generic-swap-3.rexx new file mode 100644 index 0000000000..9afeed6887 --- /dev/null +++ b/Task/Generic-swap/REXX/generic-swap-3.rexx @@ -0,0 +1,4 @@ +a = -199e-12 +b = 12. + +parse value a b with b a /*swap A and B */ diff --git a/Task/Generic-swap/Tcl/generic-swap-3.tcl b/Task/Generic-swap/Tcl/generic-swap-3.tcl index 73ca47a2b2..9556136415 100644 --- a/Task/Generic-swap/Tcl/generic-swap-3.tcl +++ b/Task/Generic-swap/Tcl/generic-swap-3.tcl @@ -1,5 +1,4 @@ -set a 1 -set b 2 -puts "before\ta=$a\tb=$b" -swap a b -puts "after\ta=$a\tb=$b" +proc swap {aName bName} { + upvar 1 $aName a $bName b + set a $b[set b $a; list] +} diff --git a/Task/Generic-swap/Tcl/generic-swap-4.tcl b/Task/Generic-swap/Tcl/generic-swap-4.tcl new file mode 100644 index 0000000000..73ca47a2b2 --- /dev/null +++ b/Task/Generic-swap/Tcl/generic-swap-4.tcl @@ -0,0 +1,5 @@ +set a 1 +set b 2 +puts "before\ta=$a\tb=$b" +swap a b +puts "after\ta=$a\tb=$b" diff --git a/Task/Gray-code/PHP/gray-code.php b/Task/Gray-code/PHP/gray-code.php new file mode 100644 index 0000000000..9ce3e0152d --- /dev/null +++ b/Task/Gray-code/PHP/gray-code.php @@ -0,0 +1,28 @@ +> 1); +} + +/** + * @param int $gray + * @return int + */ +function gray_decode($gray){ + $binary = $gray; + while($gray >>= 1) $binary ^= $gray; + return $binary; +} + +for($i=0;$i<32;$i++){ + $gray_encoded = gray_encode($i); + printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); +} diff --git a/Task/Gray-code/PL-I/gray-code.pli b/Task/Gray-code/PL-I/gray-code.pli new file mode 100644 index 0000000000..220e2f5522 --- /dev/null +++ b/Task/Gray-code/PL-I/gray-code.pli @@ -0,0 +1,31 @@ +(stringrange, stringsize): +Gray_code: procedure options (main); /* 15 November 2013 */ + declare (bin(0:31), g(0:31), b2(0:31)) bit (5); + declare (c, carry) bit (1); + declare (i, j) fixed binary (7); + + bin(0) = '00000'b; + do i = 0 to 31; + if i > 0 then + do; + carry = '1'b; + bin(i) = bin(i-1); + do j = 5 to 1 by -1; + c = substr(bin(i), j, 1) & carry; + substr(bin(i), j, 1) = substr(bin(i), j, 1) ^ carry; + carry = c; + end; + end; + g(i) = bin(i) ^ '0'b || substr(bin(i), 1, 4); + end; + do i = 0 to 31; + substr(b2(i), 1, 1) = substr(g(i), 1, 1); + do j = 2 to 5; + substr(b2(i), j, 1) = substr(g(i), j, 1) ^ substr(bin(i), j-1, 1); + end; + end; + + do i = 0 to 31; + put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b)); + end; +end Gray_code; diff --git a/Task/Gray-code/Rust/gray-code.rust b/Task/Gray-code/Rust/gray-code.rust new file mode 100644 index 0000000000..7274ae6580 --- /dev/null +++ b/Task/Gray-code/Rust/gray-code.rust @@ -0,0 +1,19 @@ +fn gray_encode(integer: uint) -> uint { + (integer >> 1) ^ integer +} + +fn gray_decode(integer: uint) -> uint { + match integer { + 0 => 0, + _ => integer ^ gray_decode(integer >> 1) + } +} + + +fn main() { + for i in range(0u,32u) { + println!("{:2} {:0>5t} {:0>5t} {:2}", i, i, gray_encode(i), + gray_decode(i)); + } + +} diff --git a/Task/Grayscale-image/Perl-6/grayscale-image.pl6 b/Task/Grayscale-image/Perl-6/grayscale-image.pl6 index c9ea0975da..4f149b2e6f 100644 --- a/Task/Grayscale-image/Perl-6/grayscale-image.pl6 +++ b/Task/Grayscale-image/Perl-6/grayscale-image.pl6 @@ -1,11 +1,11 @@ sub MAIN ($filename = 'default.ppm') { - my $in = open( $filename, :r , :bin ) or die "$!\n"; + my $in = open($filename, :r, :enc); my ($type, $dim, $depth) = $in.lines[^3]; my $outfile = $filename.subst('.ppm', '.pgm'); - my $out = open( $outfile, :w, :bin ) or die "$!\n"; + my $out = open($outfile, :w, :enc); $out.say("P5\n$dim\n$depth"); diff --git a/Task/Greatest-common-divisor/Alore/greatest-common-divisor.alore b/Task/Greatest-common-divisor/Alore/greatest-common-divisor.alore new file mode 100644 index 0000000000..4d1ae8100d --- /dev/null +++ b/Task/Greatest-common-divisor/Alore/greatest-common-divisor.alore @@ -0,0 +1,6 @@ +def gcd(a as Int, b as Int) as Int + while b != 0 + a,b = b, a mod b + end + return Abs(a) +end diff --git a/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor.ahk b/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-1.ahk similarity index 100% rename from Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor.ahk rename to Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-1.ahk diff --git a/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-2.ahk b/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-2.ahk new file mode 100644 index 0000000000..df30e5ad45 --- /dev/null +++ b/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-2.ahk @@ -0,0 +1,5 @@ +gcd(a, b) { + while b + t := b, b := Mod(a, b), a := t + return, a +} diff --git a/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-3.ahk b/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-3.ahk new file mode 100644 index 0000000000..4c247b32a5 --- /dev/null +++ b/Task/Greatest-common-divisor/AutoHotkey/greatest-common-divisor-3.ahk @@ -0,0 +1,14 @@ +_GCD(18, 12) +_GCD(1071, 1029) +_GCD(3528, 3780) + +Func _GCD($ia, $ib) + Local $ret = "GCD of " & $ia & " : " & $ib & " = " + Local $imod + While True + $imod = Mod($ia, $ib) + If $imod = 0 Then Return ConsoleWrite($ret & $ib & @CRLF) + $ia = $ib + $ib = $imod + WEnd +EndFunc ;==>_GCD diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-1.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-1.js new file mode 100644 index 0000000000..2292c82106 --- /dev/null +++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-1.js @@ -0,0 +1 @@ +Math.max.apply(null, [ 0, 1, 2, 5, 4 ]); // 5 diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js new file mode 100644 index 0000000000..28b6b9b7ba --- /dev/null +++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js @@ -0,0 +1 @@ +Math.max(...[ 0, 1, 2, 5, 4 ]); // 5 diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list.js deleted file mode 100644 index 1d847ca14c..0000000000 --- a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list.js +++ /dev/null @@ -1,8 +0,0 @@ -function max(arr) -{ - return Math.max.apply(null, arr); -} - -// Test it -a = [0,1,2,5,4]; -alert(max(a)); diff --git a/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-1.m b/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-1.m index 0c54f5fd0e..d945772a3d 100644 --- a/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-1.m +++ b/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-1.m @@ -8,10 +8,8 @@ - (id)maximumValue { if ( [self count] == 0 ) return nil; - id maybeMax = [self objectAtIndex: 0]; - NSEnumerator *en = [self objectEnumerator]; - id el; - while ( (el=[en nextObject]) != nil ) { + id maybeMax = self[0]; + for ( id el in self ) { if ( [maybeMax respondsToSelector: @selector(compare:)] && [el respondsToSelector: @selector(compare:)] && [el isKindOfClass: [NSNumber class]] && diff --git a/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-2.m b/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-2.m index 0fe15a007e..8489fbced0 100644 --- a/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-2.m +++ b/Task/Greatest-element-of-a-list/Objective-C/greatest-element-of-a-list-2.m @@ -1,14 +1,9 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSArray *collection = [NSArray arrayWithObjects: - [NSNumber numberWithInt: 1], - [NSNumber numberWithInt: 2], - [NSNumber numberWithInt: 10], - [NSNumber numberWithInt: 5], - [NSNumber numberWithDouble: 10.5], nil]; + @autoreleasepool { + NSArray *collection = @[@1, @2, @10, @5, @10.5]; - NSLog(@"%@", [collection maximumValue]); - [pool release]; + NSLog(@"%@", [collection maximumValue]); + } return 0; } diff --git a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 index 59f4e440e8..6aa2560bca 100644 --- a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 +++ b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 @@ -1 +1,2 @@ say max 10, 4, 5, -2, 11; +say max ; diff --git a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d index e44042a301..e99daa0a79 100644 --- a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d +++ b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d @@ -30,7 +30,7 @@ T[] maxSubseq(T)(T[] seq) pure nothrow { .tails .map!inits .join - .map!q{ tuple(reduce!q{a + b}(0, a), a) } + .map!q{ tuple(a.sum, a) } )[1]; } diff --git a/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player-.rb b/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player--1.rb similarity index 100% rename from Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player-.rb rename to Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player--1.rb diff --git a/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player--2.rb b/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player--2.rb new file mode 100644 index 0000000000..d4e0ee1346 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player--2.rb @@ -0,0 +1,12 @@ +r = (1..100) +secret = rand(r) +turns = 0 + +puts "Guess a number between #{r.min} and #{r.max}" +r.bsearch do |guess| # bsearch works on ranges + print "Guessing #{guess} \t" + turns += 1 + low_high = secret <=> guess # -1, 0, or 1 + puts ["found the number in #{turns} turns", "too low", "too high"][low_high] + low_high +end diff --git a/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust b/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust new file mode 100644 index 0000000000..c63b9939ab --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust @@ -0,0 +1,42 @@ +use std::io::stdio::stdin; +use std::str; +use std::rand::{task_rng, Rng}; + +static LOWEST: int = 0; +static HIGHEST: int = 100; + +fn main() { + let mut rng = task_rng(); + let mut stdin = stdin(); + let mut num_guesses = 0; + + loop { + + let number = rng.gen_range(LOWEST, HIGHEST); + + println!("I have chosen my number between {:d} and {:d}. You know what to do", LOWEST, HIGHEST); + + loop { + + let buf: &mut [u8] = [0u8, ..64]; + let num_bytes = stdin.read(buf).unwrap(); + let guess_str = str::from_utf8(buf).slice_to(num_bytes).trim(); + + match from_str::(guess_str) { + None => println("not a number! please try again"), + Some(guess) => { + num_guesses += 1; + if guess == number { + println!("you got it in {:d} tries!", num_guesses); + num_guesses = 0; + break; + } else if guess < number { + println("too low!"); + } else { + println("too high!"); + } + } + } + } + } +} diff --git a/Task/Guess-the-number/Ruby/guess-the-number.rb b/Task/Guess-the-number/Ruby/guess-the-number.rb index c6eeb6940e..cd34764d45 100644 --- a/Task/Guess-the-number/Ruby/guess-the-number.rb +++ b/Task/Guess-the-number/Ruby/guess-the-number.rb @@ -1,4 +1,4 @@ -n = rand( 10 ) + 1 +n = rand(1..10) puts 'Guess the number: ' puts 'Wrong! Guess again: ' until gets.to_i == n puts 'Well guessed!' diff --git a/Task/HTTP/Dart/http.dart b/Task/HTTP/Dart/http.dart new file mode 100644 index 0000000000..8ccb380057 --- /dev/null +++ b/Task/HTTP/Dart/http.dart @@ -0,0 +1,8 @@ +import 'dart:io'; +void main(){ + String url = 'http://rosettacode.org'; + HttpClient client = new HttpClient(); + client.getUrl(Uri.parse(url)) + .then((HttpClientRequest request) => request.close()) + .then((HttpClientResponse response) => response.pipe(stdout)); +} diff --git a/Task/HTTP/Frink/http.frink b/Task/HTTP/Frink/http.frink new file mode 100644 index 0000000000..bd2862cd94 --- /dev/null +++ b/Task/HTTP/Frink/http.frink @@ -0,0 +1 @@ +print[read["http://futureboy.us/frinkdocs/"]] diff --git a/Task/HTTP/GML/http-1.gml b/Task/HTTP/GML/http-1.gml index e6223488d7..35ea7d0dde 100644 --- a/Task/HTTP/GML/http-1.gml +++ b/Task/HTTP/GML/http-1.gml @@ -1,2 +1 @@ -var get; get = http_get("http://www.rosettacode.org/"); diff --git a/Task/HTTP/Objective-C/http.m b/Task/HTTP/Objective-C/http.m index f1a2e04974..3f34287b1c 100644 --- a/Task/HTTP/Objective-C/http.m +++ b/Task/HTTP/Objective-C/http.m @@ -1,17 +1,17 @@ #import int main (int argc, const char * argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSError *error; - NSURLResponse *response; - NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://rosettacode.org"]] - returningResponse:&response - error:&error]; + NSError *error; + NSURLResponse *response; + NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://rosettacode.org"]] + returningResponse:&response + error:&error]; - NSLog(@"%@", [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]); + NSLog(@"%@", [[NSString alloc] initWithData:data + encoding:NSUTF8StringEncoding]); - [pool drain]; + } return 0; } diff --git a/Task/HTTPS/Frink/https.frink b/Task/HTTPS/Frink/https.frink new file mode 100644 index 0000000000..006504ec8d --- /dev/null +++ b/Task/HTTPS/Frink/https.frink @@ -0,0 +1 @@ +print[read["https://sourceforge.net/"] diff --git a/Task/Hailstone-sequence/Clojure/hailstone-sequence.clj b/Task/Hailstone-sequence/Clojure/hailstone-sequence.clj index d4e57820e6..415f531f3c 100644 --- a/Task/Hailstone-sequence/Clojure/hailstone-sequence.clj +++ b/Task/Hailstone-sequence/Clojure/hailstone-sequence.clj @@ -1,14 +1,14 @@ (defn hailstone-seq [n] - (:pre [(pos? n)]) + {:pre [(pos? n)]} (lazy-seq (cond (= n 1) '(1) (even? n) (cons n (hailstone-seq (/ n 2))) :else (cons n (hailstone-seq (+ (* n 3) 1)))))) -(def hseq27 (hailstone-seq 27)) -(assert (= (count hseq27) 112)) -(assert (= (take 4 hseq27) [27 82 41 124])) -(assert (= (drop 108 hseq27) [8 4 2 1])) +(let [hseq (hailstone-seq 27)] + (-> hseq count (= 112) assert) + (->> hseq (take 4) (= [27 82 41 124]) assert) + (->> hseq (drop 108) (= [8 4 2 1]) assert)) (let [{max-i :num, max-len :len} (reduce #(max-key :len %1 %2) diff --git a/Task/Hailstone-sequence/Kotlin/hailstone-sequence.kotlin b/Task/Hailstone-sequence/Kotlin/hailstone-sequence.kotlin new file mode 100644 index 0000000000..776e8278aa --- /dev/null +++ b/Task/Hailstone-sequence/Kotlin/hailstone-sequence.kotlin @@ -0,0 +1,29 @@ +import java.util.ArrayDeque + +fun hailstone(n : Int) : ArrayDeque { + val hails = when { + n == 1 -> ArrayDeque() + n % 2 == 0 -> hailstone(n / 2) + else -> hailstone(3 * n + 1) + } + hails addFirst(n) + return hails +} + +fun main(args : Array) { + val hail27 = hailstone(27) + fun showSeq(s : List) = s map {it.toString()} reduce {a, b -> a + ", " + b} + System.out.println( + "Hailstone sequence for 27 is " + + showSeq(hail27 take(3)) + " ... " + showSeq(hail27 drop(hail27.size - 3)) + + " with length ${hail27.size}." + ) + + var longestHail = hailstone(1) + for (x in 1 .. 99999) + longestHail = array(hailstone(x), longestHail) maxBy {it.size} ?: longestHail + System.out.println( + "${longestHail.getFirst()} is the number less than 100000 with " + + "the longest sequence, having length ${longestHail.size}." + ) +} diff --git a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-1.math b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-1.math index c44375870d..42848f35f8 100644 --- a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-1.math +++ b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-1.math @@ -1 +1 @@ -HailstoneFP[n_] := Drop[FixedPointList[If[# != 1, Which[Mod[#, 2] == 0, #/2, True, ( 3*# + 1) ], 1] &, n], -1] +HailstoneFP[n_Integer] := Most[FixedPointList[Which[# == 1, 1, EvenQ[#] , #/2, OddQ[#], (3*# + 1)] &, n]] diff --git a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-3.math b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-3.math index 008b44e926..e23afcd595 100644 --- a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-3.math +++ b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-3.math @@ -1,12 +1,4 @@ -Hailstone[n_] := - NestWhileList[Which[Mod[#, 2] == 0, #/2, True, ( 3*# + 1) ] &, n, # != 1 &]; -c27 = Hailstone@27; -Print["Hailstone sequence for n = 27: [", c27[[;; 4]], "...", c27[[-4 ;;]], "]"] -Print["Length Hailstone[27] = ", Length@c27] - -longest = -1; comp = 0; -Do[temp = Length@Hailstone@i; - If[comp < temp, comp = temp; longest = i], - {i, 100000} - ] -Print["Longest Hailstone sequence at n = ", longest, "\nwith length = ", comp]; +hailstone[n_Integer] := Block[{sequence = {}, c = n}, + While[c > 1, c = If[EvenQ[c], c/2, 3 c + 1]; + AppendTo[sequence, c]]; + sequence] diff --git a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-4.math b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-4.math new file mode 100644 index 0000000000..008b44e926 --- /dev/null +++ b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-4.math @@ -0,0 +1,12 @@ +Hailstone[n_] := + NestWhileList[Which[Mod[#, 2] == 0, #/2, True, ( 3*# + 1) ] &, n, # != 1 &]; +c27 = Hailstone@27; +Print["Hailstone sequence for n = 27: [", c27[[;; 4]], "...", c27[[-4 ;;]], "]"] +Print["Length Hailstone[27] = ", Length@c27] + +longest = -1; comp = 0; +Do[temp = Length@Hailstone@i; + If[comp < temp, comp = temp; longest = i], + {i, 100000} + ] +Print["Longest Hailstone sequence at n = ", longest, "\nwith length = ", comp]; diff --git a/Task/Hailstone-sequence/Mercury/hailstone-sequence-1.mercury b/Task/Hailstone-sequence/Mercury/hailstone-sequence-1.mercury new file mode 100644 index 0000000000..1bcc68c48e --- /dev/null +++ b/Task/Hailstone-sequence/Mercury/hailstone-sequence-1.mercury @@ -0,0 +1,19 @@ +:- module hailstone. + +:- interface. + +:- import_module int, list. + +:- func hailstone(int) = list(int). +:- pred hailstone(int::in, list(int)::out) is det. + +:- implementation. + +hailstone(N) = S :- hailstone(N, S). + +hailstone(N, [N|S]) :- + ( N = 1 -> S = [] + ; N mod 2 = 0 -> hailstone(N/2, S) + ; hailstone(3 * N + 1, S) ). + +:- end_module hailstone. diff --git a/Task/Hailstone-sequence/Mercury/hailstone-sequence-2.mercury b/Task/Hailstone-sequence/Mercury/hailstone-sequence-2.mercury new file mode 100644 index 0000000000..feea15ca41 --- /dev/null +++ b/Task/Hailstone-sequence/Mercury/hailstone-sequence-2.mercury @@ -0,0 +1,36 @@ +:- module test_hailstone. + +:- interface. + +:- import_module io. + +:- pred main(io.state::di, io.state::uo) is det. + +:- implementation. + +:- import_module int, list. +:- import_module hailstone. + +:- pred longest(int::in, int::out, int::out) is det. +:- pred longest(int::in, int::in, int::in, int::out, int::out) is det. + +longest(M, N, L) :- longest(M, 0, 0, N, L). + +longest(N, CN, CL, MN, ML) :- + ( N > 1 -> + L = list.length(hailstone(N)), + ( L > CL -> longest(N - 1, N, L, MN, ML) + ; longest(N - 1, CN, CL, MN, ML) ) + ; MN = CN, ML = CL ). + + +main(!IO) :- + S = hailstone(27), + ( list.length(S) = 112, + list.append([27, 82, 41, 124], _, S), + list.remove_suffix(S, [8, 4, 2, 1], _), + longest(100000, 77031, 351) -> + io.write_string("All tests succeeded.\n", !IO) + ; io.write_string("At least one test failed.\n", !IO) ). + +:- end_module test_hailstone. diff --git a/Task/Hailstone-sequence/Mercury/hailstone-sequence-3.mercury b/Task/Hailstone-sequence/Mercury/hailstone-sequence-3.mercury new file mode 100644 index 0000000000..a4271db0ab --- /dev/null +++ b/Task/Hailstone-sequence/Mercury/hailstone-sequence-3.mercury @@ -0,0 +1 @@ +:- pred longest(int::in, int::out, int::out) is det. diff --git a/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh new file mode 100644 index 0000000000..52183708a3 --- /dev/null +++ b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh @@ -0,0 +1,26 @@ +# Author M. McNabb +function Get-HailStoneBelowLimit { +param($UpperLimit) + begin { + function Get-HailStone { + param($n) + switch($n) { + 1 {$n;return} + {$n % 2 -eq 0} {$n; return Get-Hailstone ($n = $n / 2)} + {$n % 2 -ne 0} {$n; return Get-Hailstone ($n = ($n * 3) +1)} + } + } + $Counts = @() + } + + process { + for ($i = 1; $i -lt $UpperLimit; $i++) { + $Object = [pscustomobject]@{ + 'Number' = $i + 'Count' = (Get-HailStone $i).count + } + $Counts += $Object + } + } + end {$Counts} +} diff --git a/Task/Hamming-numbers/00DESCRIPTION b/Task/Hamming-numbers/00DESCRIPTION index 59143ab062..151dc1940e 100644 --- a/Task/Hamming-numbers/00DESCRIPTION +++ b/Task/Hamming-numbers/00DESCRIPTION @@ -1,4 +1,4 @@ -[[wp:Hamming_numbers#Algorithms|Hamming numbers]] are numbers of the form +'''[[wp:Hamming numbers|Hamming numbers]]''' are numbers of the form : H = 2^i \cdot 3^j \cdot 5^k, \; \mathrm{where} \; i, j, k \geq 0. ''Hamming numbers'' are also known as ''ugly numbers'' and also ''5-smooth numbers''   (numbers whose prime divisors are less or equal to 5). @@ -7,6 +7,6 @@ Generate the sequence of Hamming numbers, ''in increasing order''. In particular # Show the 1691st Hamming number (the last one below 2^{31}). # Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). '''References''' -# [[wp:Hamming_numbers]] -# [[wp:Smooth_number]] +# [[wp:Hamming numbers|Hamming numbers]] +# [[wp:Smooth number|Smooth number]] # [http://dobbscodetalk.com/index.php?option=com_content&task=view&id=913&Itemid=85 Hamming problem] from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread [http://drdobbs.com/blogs/architecture-and-design/228700538 here] and [http://www.jsoftware.com/jwiki/Essays/Hamming%20Number here]). diff --git a/Task/Hamming-numbers/Bracmat/hamming-numbers.bracmat b/Task/Hamming-numbers/Bracmat/hamming-numbers.bracmat new file mode 100644 index 0000000000..f6e5f995ef --- /dev/null +++ b/Task/Hamming-numbers/Bracmat/hamming-numbers.bracmat @@ -0,0 +1,35 @@ +( ( hamming + = x2 x3 x5 n i j k min + . tbl$(h,!arg) { This creates an array. Arrays are always global in Bracmat. } + & 1:?(0$h) + & 2:?x2 + & 3:?x3 + & 5:?x5 + & 0:?n:?i:?j:?k + & whl + ' ( !n+1:20:?I&put$(hamming$!I " ")) +& out$ +& out$(hamming$1691) +& out$(hamming$1000000) +); diff --git a/Task/Hamming-numbers/Forth/hamming-numbers.fth b/Task/Hamming-numbers/Forth/hamming-numbers-1.fth similarity index 100% rename from Task/Hamming-numbers/Forth/hamming-numbers.fth rename to Task/Hamming-numbers/Forth/hamming-numbers-1.fth diff --git a/Task/Hamming-numbers/Forth/hamming-numbers-2.fth b/Task/Hamming-numbers/Forth/hamming-numbers-2.fth new file mode 100644 index 0000000000..4ec448597d --- /dev/null +++ b/Task/Hamming-numbers/Forth/hamming-numbers-2.fth @@ -0,0 +1,25 @@ +2000 cells constant /hamming +create hamming /hamming allot + ( n1 n2 n3 n4 n5 n6 n7 -- n3 n4 n5 n6 n1 n2 n8) +: min? >r dup r> min >r 2rot r> ; + +: hit? ( n1 n2 n3 n4 n5 n6 n7 n8 -- n3 n4 n9 n10 n1 n2 n7) + >r 2dup = \ compare number with found minimum + if -rot drop 1+ hamming over cells + @ r@ * rot then + r> drop >r 2rot r> +; \ if so, increment and rotate + +: hamming# ( n1 -- n2) + 1 hamming ! >r \ set first cell and initialize parms + 0 5 over 3 over 2 + r@ 1 ?do \ determine minimum and set cell + dup min? min? min? dup hamming i cells + ! + 2 hit? 5 hit? 3 hit? drop + loop \ find if minimum equals value + 2drop 2drop 2drop hamming r> 1- cells + @ +; \ clean up stack and fetch hamming number + +: test + cr 21 1 ?do i . i hamming# . cr loop + 1691 hamming# . cr +; diff --git a/Task/Hamming-numbers/Java/hamming-numbers.java b/Task/Hamming-numbers/Java/hamming-numbers-1.java similarity index 100% rename from Task/Hamming-numbers/Java/hamming-numbers.java rename to Task/Hamming-numbers/Java/hamming-numbers-1.java diff --git a/Task/Hamming-numbers/Java/hamming-numbers-2.java b/Task/Hamming-numbers/Java/hamming-numbers-2.java new file mode 100644 index 0000000000..fbb7745824 --- /dev/null +++ b/Task/Hamming-numbers/Java/hamming-numbers-2.java @@ -0,0 +1,111 @@ +import java.math.BigInteger; +import java.util.*; + +// ilkka.kokkarinen@gmail.com + +public class HammingTriple implements Comparable { + + // Precompute a couple of constants that we need all the time + private static final BigInteger two = BigInteger.valueOf(2); + private static final BigInteger three = BigInteger.valueOf(3); + private static final BigInteger five = BigInteger.valueOf(5); + private static final double logOf2 = Math.log(2); + private static final double logOf3 = Math.log(3); + private static final double logOf5 = Math.log(5); + + // The powers of this triple + private int a, b, c; + + public HammingTriple(int a, int b, int c) { + this.a = a; this.b = b; this.c = c; + } + + public String toString() { + return "[" + a + ", " + b + ", " + c + "]"; + } + + public BigInteger getValue() { + return two.pow(a).multiply(three.pow(b)).multiply(five.pow(c)); + } + + public boolean equals(Object other) { + if(other instanceof HammingTriple) { + HammingTriple h = (HammingTriple) other; + return this.a == h.a && this.b == h.b && this.c == h.c; + } + else { return false; } + } + + // Return 0 if this == other, +1 if this > other, and -1 if this < other + public int compareTo(HammingTriple other) { + // equality + if(this.a == other.a && this.b == other.b && this.c == other.c) { + return 0; + } + // this dominates + if(this.a >= other.a && this.b >= other.b && this.c >= other.c) { + return +1; + } + // other dominates + if(this.a <= other.a && this.b <= other.b && this.c <= other.c) { + return -1; + } + + // take the logarithms for comparison + double log1 = this.a * logOf2 + this.b * logOf3 + this.c * logOf5; + double log2 = other.a * logOf2 + other.b * logOf3 + other.c * logOf5; + + // are these different enough to be reliable? + if(Math.abs(log1 - log2) > 0.0000001) { + return (log1 < log2) ? -1: +1; + } + + // oh well, looks like we have to do this the hard way + return this.getValue().compareTo(other.getValue()); + // (getting this far should be pretty rare, though) + } + + public static BigInteger computeHamming(int n, boolean verbose) { + if(verbose) { + System.out.println("Hamming number #" + n); + } + long startTime = System.currentTimeMillis(); + + // The elements of the search frontier + PriorityQueue frontierQ = new PriorityQueue(); + int maxFrontierSize = 1; + + // Initialize the frontier + frontierQ.offer(new HammingTriple(0, 0, 0)); // 1 + + while(true) { + if(frontierQ.size() > maxFrontierSize) { + maxFrontierSize = frontierQ.size(); + } + // Pop out the next Hamming number from the frontier + HammingTriple curr = frontierQ.poll(); + + if(--n == 0) { + if(verbose) { + System.out.println("Time: " + (System.currentTimeMillis() - startTime) + " ms"); + System.out.println("Frontier max size: " + maxFrontierSize); + System.out.println("As powers: " + curr.toString()); + System.out.println("As value: " + curr.getValue()); + } + return curr.getValue(); + } + + // Current times five, if at origin in (a,b) plane + if(curr.a == 0 && curr.b == 0) { + frontierQ.offer(new HammingTriple(curr.a, curr.b, curr.c + 1)); + } + // Current times three, if at line a == 0 + if(curr.a == 0) { + frontierQ.offer(new HammingTriple(curr.a, curr.b + 1, curr.c)); + } + // Current times two, unconditionally + curr.a++; + frontierQ.offer(curr); // reuse the current HammingTriple object + } + } +} diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers.kotlin new file mode 100644 index 0000000000..f2717f3046 --- /dev/null +++ b/Task/Hamming-numbers/Kotlin/hamming-numbers.kotlin @@ -0,0 +1,32 @@ +import java.math.BigInteger; +import java.util.PriorityQueue; + +val Three = BigInteger.valueOf(3) +val Five = BigInteger.valueOf(5) + +fun updateFrontier(x : BigInteger, pq : PriorityQueue) { + pq add(x shiftLeft(1)) + pq add(x multiply(Three)) + pq add(x multiply(Five)) +} + +fun hamming(n : Int) : BigInteger { + val frontier = PriorityQueue() + updateFrontier(BigInteger.ONE, frontier) + var lowest = BigInteger.ONE + for (i in 1 .. n-1) { + lowest = frontier.poll() ?: lowest + while (frontier.peek() equals(lowest)) + frontier.poll() + updateFrontier(lowest, frontier) + } + return lowest +} + +fun main(args : Array) { + System.out print("Hamming(1 .. 20) =") + for (i in 1 .. 20) + System.out print(" ${hamming(i)}") + System.out println("\nHamming(1691) = ${hamming(1691)}") + System.out println("Hamming(1000000) = ${hamming(1000000)}") +} diff --git a/Task/Handle-a-signal/AutoHotkey/handle-a-signal.ahk b/Task/Handle-a-signal/AutoHotkey/handle-a-signal.ahk new file mode 100644 index 0000000000..75191eac4a --- /dev/null +++ b/Task/Handle-a-signal/AutoHotkey/handle-a-signal.ahk @@ -0,0 +1,15 @@ +Start:=A_TickCount +counter=0 +SetTimer, timer, 500 +return + +timer: +Send % ++Counter "`n" +return + +^c:: +SetTimer, timer, off +SetFormat, float, 0.3 +Send, % "Task took " (A_TickCount-Start)/1000 " Seconds" +ExitApp +return diff --git a/Task/Happy-numbers/AutoHotkey/happy-numbers.ahk b/Task/Happy-numbers/AutoHotkey/happy-numbers-1.ahk similarity index 100% rename from Task/Happy-numbers/AutoHotkey/happy-numbers.ahk rename to Task/Happy-numbers/AutoHotkey/happy-numbers-1.ahk diff --git a/Task/Happy-numbers/AutoHotkey/happy-numbers-2.ahk b/Task/Happy-numbers/AutoHotkey/happy-numbers-2.ahk new file mode 100644 index 0000000000..491e86ddc0 --- /dev/null +++ b/Task/Happy-numbers/AutoHotkey/happy-numbers-2.ahk @@ -0,0 +1,18 @@ +while h < 8 + if (Happy(A_Index)) { + Out .= A_Index A_Space + h++ + } +MsgBox, % Out + +Happy(n) { + Loop, { + Loop, Parse, n + t += A_LoopField ** 2 + if (t = 89) + return, 0 + if (t = 1) + return, 1 + n := t, t := 0 + } +} diff --git a/Task/Happy-numbers/D/happy-numbers-2.d b/Task/Happy-numbers/D/happy-numbers-2.d index d0f7e47213..b208f11c9e 100644 --- a/Task/Happy-numbers/D/happy-numbers-2.d +++ b/Task/Happy-numbers/D/happy-numbers-2.d @@ -4,7 +4,7 @@ bool isHappy(int n) pure /*nothrow*/ { int[int] seen; while (true) { - immutable t = n.text.map!q{(a - '0') ^^ 2}.reduce!q{a + b}; + immutable t = n.text.map!q{(a - '0') ^^ 2}.sum; if (t == 1) return true; if (t in seen) diff --git a/Task/Happy-numbers/Python/happy-numbers.py b/Task/Happy-numbers/Python/happy-numbers.py index 75f7e26f5e..4679ae56e8 100644 --- a/Task/Happy-numbers/Python/happy-numbers.py +++ b/Task/Happy-numbers/Python/happy-numbers.py @@ -1,6 +1,6 @@ >>> def happy(n): past = set() - while n <> 1: + while n != 1: n = sum(int(i)**2 for i in str(n)) if n in past: return False diff --git a/Task/Happy-numbers/REXX/happy-numbers-2.rexx b/Task/Happy-numbers/REXX/happy-numbers-2.rexx index 77305a86a9..cdd3ab39ff 100644 --- a/Task/Happy-numbers/REXX/happy-numbers-2.rexx +++ b/Task/Happy-numbers/REXX/happy-numbers-2.rexx @@ -16,7 +16,7 @@ haps=0 /*count of happy numbers so far. */ s=s+#._ /*add the square of a digit. */ end /*j*/ - if @.s then do; q=1; iterate; end /*we have found a happy number.*/ + if @.s then leave /*we have found a happy number.*/ if !.s then iterate n /*Sum unhappy? Then Q is unhappy*/ if a.s then do /*If already summed? Q is unhappy*/ !.q=1; !.s=1 /*mark Q & S as unhappy numbers*/ diff --git a/Task/Happy-numbers/REXX/happy-numbers-3.rexx b/Task/Happy-numbers/REXX/happy-numbers-3.rexx index 3ccc619914..4bb9ee8a89 100644 --- a/Task/Happy-numbers/REXX/happy-numbers-3.rexx +++ b/Task/Happy-numbers/REXX/happy-numbers-3.rexx @@ -18,7 +18,7 @@ sw=linesize() /*obtain the linesize of term scr*/ s=s+#._ /*add the square of a digit. */ end /*j*/ - if @.s then do; q=1; iterate; end /*we have found a happy number.*/ + if @.s then leave /*we have found a happy number.*/ if !.s then iterate n /*Sum unhappy? Then Q is unhappy*/ if a.s then do /*If already summed? Q is unhappy*/ !.q=1; !.s=1 /*mark Q & S as unhappy numbers*/ diff --git a/Task/Harshad-or-Niven-series/AutoHotkey/harshad-or-niven-series.ahk b/Task/Harshad-or-Niven-series/AutoHotkey/harshad-or-niven-series.ahk new file mode 100644 index 0000000000..2c708eedbe --- /dev/null +++ b/Task/Harshad-or-Niven-series/AutoHotkey/harshad-or-niven-series.ahk @@ -0,0 +1,21 @@ +H := [] +n := 1 + +Loop + n := (H[A_Index] := NextHarshad(n)) + 1 +until H[H.MaxIndex()] > 1000 + +Loop, 20 + Out .= H[A_Index] ", " + +MsgBox, % Out ". . . " H[H.MaxIndex()] + +NextHarshad(n) { + Loop, { + Loop, Parse, n + sum += A_LoopField + if (!Mod(n, sum)) + return n + n++, sum := "" + } +} diff --git a/Task/Harshad-or-Niven-series/D/harshad-or-niven-series.d b/Task/Harshad-or-Niven-series/D/harshad-or-niven-series.d index 642b3c9a9b..9f01a2d215 100644 --- a/Task/Harshad-or-Niven-series/D/harshad-or-niven-series.d +++ b/Task/Harshad-or-Niven-series/D/harshad-or-niven-series.d @@ -1,9 +1,9 @@ -import std.stdio, std.algorithm, std.range, std.conv; - void main() { - auto digsum = (int n) => n.text.map!q{a - '0'}.reduce!q{a + b}; - auto harshads = iota(1, int.max).filter!(n => n % digsum(n) == 0); + import std.stdio, std.algorithm, std.range, std.conv; + + enum digSum = (int n) => n.text.map!(d => d - '0').sum; + enum harshads = iota(1, int.max).filter!(n => n % digSum(n) == 0); harshads.take(20).writeln; - harshads.filter!q{ a > 1000 }.front.writeln; + harshads.filter!(h => h > 1000).front.writeln; } diff --git a/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink b/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink new file mode 100644 index 0000000000..35414a455d --- /dev/null +++ b/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink @@ -0,0 +1,22 @@ +isHarshad[n] := n mod sum[parseInt[charList[toString[n]]]] == 0 + +c = 0 +i = 1 +while c<20 +{ + if isHarshad[i] + { + c = c + 1 + println[i] + } + i = i + 1 +} + +println[] +i = 1000 + +do + i = i + 1 +while ! isHarshad[i] + +println[i] diff --git a/Task/Harshad-or-Niven-series/NetRexx/harshad-or-niven-series.netrexx b/Task/Harshad-or-Niven-series/NetRexx/harshad-or-niven-series.netrexx new file mode 100644 index 0000000000..9830593995 --- /dev/null +++ b/Task/Harshad-or-Niven-series/NetRexx/harshad-or-niven-series.netrexx @@ -0,0 +1,35 @@ +/* NetRexx ------------------------------------------------------------ +* 21.01.2014 Walter Pachl translated from ooRexx (from REXX version 1) +*--------------------------------------------------------------------*/ + +options replace format comments java crossref symbols nobinary + + Parse Arg x y . /* get optional arguments: X Y */ + If x='' Then x=20 /* Not specified? Use default */ + If y='' Then y=1000 /* " " " " */ + n=0 /* Niven count */ + nl='' /* Niven list. */ + + Loop j=1 By 1 Until n=x /* let's go Niven number hunting.*/ + If j//sumdigs(j)=0 Then Do /* j is a Niven number */ + n=n+1 /* bump Niven count */ + nl=nl j /* add to list. */ + End + End + + Say 'first' n 'Niven numbers:'nl + + Loop j=y+1 By 1 /* start with first candidate */ + If j//sumdigs(j)=0 Then /* j is a Niven number */ + Leave + End + + Say 'first Niven number >' y 'is:' j + Exit + +method sumdigs(n) public static returns Rexx + sum=n.left(1) + Loop k=2 To n.length() + sum=sum+n.substr(k,1) + End + Return sum diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx index 5eb8c536ac..87c9149a59 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx @@ -1,7 +1,7 @@ /*REXX program finds first X Niven numbers; also first Niven number > Y.*/ parse arg X Y . /*get optional arguments: X Y */ if X=='' then X=20 /*Not specified? Then use default*/ -if Y=='' then Y=1000 /*Not specified? Then use default*/ +if Y=='' then Y=1000 /* " " " " " */ #=0; $= /*Niven# count; Niven# list. */ do j=1 until #==X /*let's go Niven number hunting. */ @@ -11,7 +11,7 @@ if Y=='' then Y=1000 /*Not specified? Then use default*/ say 'first' X 'Niven numbers:' $ - do t=1 /*let's go Niven number searching*/ + do t=Y+1 /*let's go Niven number searching*/ if t//sumDigs(t)\==0 then iterate /*Not a Niven number? Then skip.*/ if t>Y then leave /*if greater than Y, go & show it*/ end /*t*/ diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx index 0d11f039bd..72bc3413b1 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx @@ -1,7 +1,7 @@ /*REXX program finds first X Niven numbers; also first Niven number > Y.*/ parse arg X Y . /*get optional arguments: X Y */ if X=='' then X=20 /*Not specified? Then use default*/ -if Y=='' then Y=1000 /*Not specified? Then use default*/ +if Y=='' then Y=1000 /* " " " " " */ #=0; $= /*Niven# count; Niven# list. */ do j=1 until #==X /*let's go Niven number hunting. */ @@ -11,7 +11,7 @@ if Y=='' then Y=1000 /*Not specified? Then use default*/ say 'first' X 'Niven numbers:' $ - do t=1 /*let's go Niven number searching*/ + do t=Y+1 /*let's go Niven number searching*/ if isNiven(t) & t>y then leave /*is a Niven # AND > Y, show it*/ end /*t*/ diff --git a/Task/Hash-from-two-arrays/Frink/hash-from-two-arrays.frink b/Task/Hash-from-two-arrays/Frink/hash-from-two-arrays.frink new file mode 100644 index 0000000000..968a4d583c --- /dev/null +++ b/Task/Hash-from-two-arrays/Frink/hash-from-two-arrays.frink @@ -0,0 +1 @@ +a = new dict[["a", "b", "c"], [1, 2, 3]] diff --git a/Task/Hash-from-two-arrays/Objective-C/hash-from-two-arrays.m b/Task/Hash-from-two-arrays/Objective-C/hash-from-two-arrays.m index fc91bfa13e..5843de4c2d 100644 --- a/Task/Hash-from-two-arrays/Objective-C/hash-from-two-arrays.m +++ b/Task/Hash-from-two-arrays/Objective-C/hash-from-two-arrays.m @@ -1,5 +1,3 @@ -NSArray *keys = [NSArray arrayWithObjects:@"a", @"b", @"c", nil]; -NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], - [NSNumber numberWithInt:2], - [NSNumber numberWithInt:3], nil]; +NSArray *keys = @[@"a", @"b", @"c"]; +NSArray *values = @[@1, @2, @3]; NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys]; diff --git a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-5.pl6 b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-5.pl6 new file mode 100644 index 0000000000..92213b65e4 --- /dev/null +++ b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-5.pl6 @@ -0,0 +1 @@ +{ @keys »=>« @values } diff --git a/Task/Haversine-formula/AutoHotkey/haversine-formula.ahk b/Task/Haversine-formula/AutoHotkey/haversine-formula.ahk new file mode 100644 index 0000000000..da0c822d75 --- /dev/null +++ b/Task/Haversine-formula/AutoHotkey/haversine-formula.ahk @@ -0,0 +1,13 @@ +MsgBox, % GreatCircleDist(36.12, 33.94, -86.67, -118.40, 6372.8, "km") + +GreatCircleDist(La1, La2, Lo1, Lo2, R, U) { + return, 2 * R * ASin(Sqrt(Hs(Rad(La2 - La1)) + Cos(Rad(La1)) * Cos(Rad(La2)) * Hs(Rad(Lo2 - Lo1)))) A_Space U +} + +Hs(n) { + return, (1 - Cos(n)) / 2 +} + +Rad(Deg) { + return, Deg * 4 * ATan(1) / 180 +} diff --git a/Task/Haversine-formula/Python/haversine-formula.py b/Task/Haversine-formula/Python/haversine-formula.py index d2931713e5..29516ad46a 100644 --- a/Task/Haversine-formula/Python/haversine-formula.py +++ b/Task/Haversine-formula/Python/haversine-formula.py @@ -1,14 +1,19 @@ ->>> import math ->>> def haversine(lat1, lon1, lat2, lon2): - R = 6372.8 - # In kilometers - dLat = math.radians(lat2 - lat1) - dLon = math.radians(lon2 - lon1) - lat1 = math.radians(lat1) - lat2 = math.radians(lat2) +from math import radians, sin, cos, sqrt, atan2 + +def haversine(lat1, lon1, lat2, lon2): + + R = 6372.8 + +# In kilometers + + dLat = radians(lat2 - lat1) + dLon = radians(lon2 - lon1) + lat1 = radians(lat1) + lat2 = radians(lat2) + + a = sin(dLat/2.)*sin(dLat/2.) + sin(dLon/2.)*sin(dLon/2.)*cos(lat1)*cos(lat2) + c = 2.*atan2(sqrt(a),sqrt(1-a)) - a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.sin(dLon / 2) * math.sin(dLon / 2) * math.cos(lat1) * math.cos(lat2) - c = 2 * math.asin(math.sqrt(a)) return R * c >>> haversine(36.12, -86.67, 33.94, -118.40) diff --git a/Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical.lisp b/Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical-1.lisp similarity index 100% rename from Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical.lisp rename to Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical-1.lisp diff --git a/Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical-2.lisp b/Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical-2.lisp new file mode 100644 index 0000000000..c94551c88d --- /dev/null +++ b/Task/Hello-world-Graphical/Common-Lisp/hello-world-graphical-2.lisp @@ -0,0 +1,28 @@ +((in-package :clim-user) + +(defclass hello-world-pane + (clim-stream-pane) ()) + +(define-application-frame hello-world () + ((greeting :initform "Hello World" + :accessor greeting)) + (:pane (make-pane 'hello-world-pane))) + +;;; Behaviour defined by the Handle Repaint Protocol +(defmethod handle-repaint ((pane hello-world-pane) region) + (let ((w (bounding-rectangle-width pane)) + (h (bounding-rectangle-height pane))) + ;; Blank the pane out + (draw-rectangle* pane 0 0 w h + :filled t + :ink (pane-background pane)) + ;; Draw greeting in center of pane + (draw-text* pane + (greeting *application-frame*) + (floor w 2) (floor h 2) + :align-x :center + :align-y :center))) + +(run-frame-top-level + (make-application-frame 'hello-world + :width 200 :height 200)) diff --git a/Task/Hello-world-Graphical/Frink/hello-world-graphical.frink b/Task/Hello-world-Graphical/Frink/hello-world-graphical.frink index ff673a1464..3358b9e337 100644 --- a/Task/Hello-world-Graphical/Frink/hello-world-graphical.frink +++ b/Task/Hello-world-Graphical/Frink/hello-world-graphical.frink @@ -1,7 +1,7 @@ g = new graphics g.font["SansSerif", 10] -g.text["Hello World!", 0, 0] +g.text["Goodbye, World!", 0, 0, 10 degrees] g.show[] g.print[] // Optional: render to printer -g.write["HelloWorld.png", 400, 300] // Optional: write to graphics file +g.write["GoodbyeWorld.png", 400, 300] // Optional: write to graphics file diff --git a/Task/Hello-world-Graphical/Julia/hello-world-graphical.julia b/Task/Hello-world-Graphical/Julia/hello-world-graphical.julia new file mode 100644 index 0000000000..071b496d88 --- /dev/null +++ b/Task/Hello-world-Graphical/Julia/hello-world-graphical.julia @@ -0,0 +1,14 @@ +using Tk + +window = Toplevel("Hello World", 200, 100, false) +pack_stop_propagate(window) + +fr = Frame(window) +pack(fr, expand=true, fill="both") + +txt = Label(fr, "Hello World") +pack(txt, expand=true) + +set_visible(window, true) + +# sleep(7) diff --git a/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-1.m b/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-1.m index 8d67d9ad14..be4087c210 100644 --- a/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-1.m +++ b/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-1.m @@ -1,3 +1,3 @@ -NSAlert *alert = [[[NSAlert alloc] init] autorelease]; +NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Goodbye, World!"]; [alert runModal]; diff --git a/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-2.m b/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-2.m index 854917fd56..379d3f2e12 100644 --- a/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-2.m +++ b/Task/Hello-world-Graphical/Objective-C/hello-world-graphical-2.m @@ -1,2 +1,2 @@ -UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Goodbye, World!" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; +UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Goodbye, World!" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; diff --git a/Task/Hello-world-Graphical/TI-83-BASIC/hello-world-graphical.ti-83 b/Task/Hello-world-Graphical/TI-83-BASIC/hello-world-graphical.ti-83 new file mode 100644 index 0000000000..db5a7527c7 --- /dev/null +++ b/Task/Hello-world-Graphical/TI-83-BASIC/hello-world-graphical.ti-83 @@ -0,0 +1,2 @@ +PROGRAM:GUIHELLO +:Text(0,0,"GOODBYE, WORLD!") diff --git a/Task/Hello-world-Text/PowerShell/hello-world-text.psh b/Task/Hello-world-Text/PowerShell/hello-world-text.psh index c5bec9c185..6d5a22616d 100644 --- a/Task/Hello-world-Text/PowerShell/hello-world-text.psh +++ b/Task/Hello-world-Text/PowerShell/hello-world-text.psh @@ -1,4 +1,7 @@ -Write-Host "Goodbye, World!" +'Goodbye, World!' + +#It's considered good practice to use Write-Host, although it works just fine without too +Write-Host 'Goodbye, World!' # For extra flair, you can specify colored output -Write-Host "Goodbye, World!" -foregroundcolor red +Write-Host 'Goodbye, World!' -foregroundcolor red diff --git a/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart b/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart new file mode 100644 index 0000000000..475b8131e8 --- /dev/null +++ b/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart @@ -0,0 +1,9 @@ +import 'dart:io'; + +void main(){ + HttpServer.bind('localhost', 8080) + .then((HttpServer server) => + server.listen((HttpRequest request) => + request..response.write('Hello, world') + ..response.close())); +} diff --git a/Task/Here-document/REXX/here-document.rexx b/Task/Here-document/REXX/here-document.rexx index 77db27e4e7..f4bd897aa3 100644 --- a/Task/Here-document/REXX/here-document.rexx +++ b/Task/Here-document/REXX/here-document.rexx @@ -31,7 +31,7 @@ binary data interchange. │ 12◄─secondary carrier detect [SCD] │ (common return) │ 21◄─signal quality detector [SQD] DCE │ │ 8◄─carrier detect [CD] DCE │ 22◄─ring indicator [RI] DCE │ │ 9◄─positive voltage [-] │ 23◄─data rate select [DRS] DCE/DTE │ -│10◄─negative voltate [-] │ 24◄─external clock [XTC] DTE │ +│10◄─negative voltage [-] │ 24◄─external clock [XTC] DTE │ │11◄─unassigned │ 25◄─unassigned │ └─────────────────────────────────┴───────────────────────────────────────────┘ ◄◄. diff --git a/Task/History-variables/AutoHotkey/history-variables.ahk b/Task/History-variables/AutoHotkey/history-variables.ahk new file mode 100644 index 0000000000..cde8b8aae1 --- /dev/null +++ b/Task/History-variables/AutoHotkey/history-variables.ahk @@ -0,0 +1,15 @@ +HV := new HistoryVariable +HV.var := 1 +HV.var := 2 +HV.var := "Latest value" +Msgbox % HV.var "`n" HV[2] "`n" HV[3] + +class HistoryVariable { + __Set(aName, aValue) { + this.Insert(1,aValue) + Return aValue + } + __Get(aName) { + Return this[1] + } +} diff --git a/Task/Hofstadter-Conway-$10,000-sequence/PicoLisp/hofstadter-conway-$10,000-sequence.l b/Task/Hofstadter-Conway-$10,000-sequence/PicoLisp/hofstadter-conway-$10,000-sequence.l index ba70ba4f3b..977cb1276b 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/PicoLisp/hofstadter-conway-$10,000-sequence.l +++ b/Task/Hofstadter-Conway-$10,000-sequence/PicoLisp/hofstadter-conway-$10,000-sequence.l @@ -1,5 +1,5 @@ (de hofcon (N) - (cache '(NIL) (pack (char (hash N)) N) + (cache '(NIL) N (if (>= 2 N) 1 (+ diff --git a/Task/Hofstadter-Figure-Figure-sequences/AutoHotkey/hofstadter-figure-figure-sequences-1.ahk b/Task/Hofstadter-Figure-Figure-sequences/AutoHotkey/hofstadter-figure-figure-sequences-1.ahk new file mode 100644 index 0000000000..5b8e84eb4a --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/AutoHotkey/hofstadter-figure-figure-sequences-1.ahk @@ -0,0 +1,19 @@ +R(n){ + if n=1 + return 1 + return R(n-1) + S(n-1) +} + +S(n){ + static ObjR:=[] + if n=1 + return 2 + ObjS:=[] + loop, % n + ObjR[R(A_Index)] := true + loop, % n-1 + ObjS[S(A_Index)] := true + Loop + if !(ObjR[A_Index]||ObjS[A_Index]) + return A_index +} diff --git a/Task/Hofstadter-Figure-Figure-sequences/AutoHotkey/hofstadter-figure-figure-sequences-2.ahk b/Task/Hofstadter-Figure-Figure-sequences/AutoHotkey/hofstadter-figure-figure-sequences-2.ahk new file mode 100644 index 0000000000..697a25ecea --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/AutoHotkey/hofstadter-figure-figure-sequences-2.ahk @@ -0,0 +1,2 @@ +Loop + MsgBox, 262144, , % "R(" A_Index ") = " R(A_Index) "`nS(" A_Index ") = " S(A_Index) diff --git a/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d b/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d index f66e7dbbbb..57b50654d6 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d +++ b/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d @@ -3,7 +3,7 @@ import std.stdio, std.array, std.range, std.algorithm; struct ffr { static r = [int.min, 1]; - static int opCall(in int n) /*nothrow*/ { + static int opCall(in int n) nothrow { assert(n > 0); if (n < r.length) { return r[n]; @@ -29,12 +29,12 @@ struct ffr { struct ffs { static s = [int.min, 2]; - static int opCall(in int n) /*nothrow*/ { + static int opCall(in int n) nothrow { assert(n > 0); if (n < s.length) { return s[n]; } else { - foreach (immutable i; ffr.r.length .. n+2) { + foreach (immutable i; ffr.r.length .. n + 2) { ffr(i); if (s.length > n) return s[n]; @@ -45,7 +45,7 @@ struct ffs { } void main() { - map!ffr(iota(1, 11)).writeln; + iota(1, 11).map!ffr.writeln; auto t = iota(1, 41).map!ffr.chain(iota(1, 961).map!ffs); - t.array().sort().equal(iota(1, 1001)).writeln; + t.array.sort().equal(iota(1, 1001)).writeln; } diff --git a/Task/Hofstadter-Figure-Figure-sequences/PicoLisp/hofstadter-figure-figure-sequences-1.l b/Task/Hofstadter-Figure-Figure-sequences/PicoLisp/hofstadter-figure-figure-sequences-1.l index 8945e337f7..eb8bb24b8c 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/PicoLisp/hofstadter-figure-figure-sequences-1.l +++ b/Task/Hofstadter-Figure-Figure-sequences/PicoLisp/hofstadter-figure-figure-sequences-1.l @@ -1,13 +1,13 @@ (setq *RNext 2) (de ffr (N) - (cache '(NIL) (pack (char (hash N)) N) + (cache '(NIL) N (if (= 1 N) 1 (+ (ffr (dec N)) (ffs (dec N))) ) ) ) (de ffs (N) - (cache '(NIL) (pack (char (hash N)) N) + (cache '(NIL) N (if (= 1 N) 2 (let S (inc (ffs (dec N))) diff --git a/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx b/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx index 5aef0c69fe..e160bdf48e 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx +++ b/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx @@ -1,18 +1,19 @@ /*REXX pgm calculates & verifies the Hofstadter Figure-Figure sequences.*/ -parse arg x highV . /*obtain any C.L. specifications.*/ +parse arg x highV bot . /*obtain any C.L. specifications.*/ if x=='' then x=10; if highV=='' then highV=1000 /*use the defaults?*/ +if bot=='' then bot=40 /* " " " */ low=1; if x<0 then low=abs(x) /*only show a single │X│ value.*/ -r.=0; r.1=1; rr.=r.; rr.1=1 /*initialize the R and RR arrays.*/ -s.=0; s.1=2; ss.=s.; ss.2=1 /* " " S " SS " */ +r.=0; r.1=1; rr.=r.; rr.1=1 /*initialize the R & RR arrays.*/ +s.=0; s.1=2 /* " " S array. */ errs=0; both.=0 do i=low to abs(x) /*show first X values of R & S */ say right('R('i") =",20) right(ffr(i),7), /*show nice*/ right('S('i") =",20) right(ffs(i),7) /* R & S */ end /*i*/ if x<1 then exit /*if x ≤ 0, then we're all done.*/ - do m=1 for 40; r=ffr(m); both.r=1 /*calculate 1st 40 R values.*/ + do m=1 for bot; r=ffr(m); both.r=1 /*calculate 1st 40 R values.*/ end /*m*/ /* [↑] build first 40 R values.*/ - do n=1 for 960; s=ffs(n) /*calculate 1st 960 S values.*/ + do n=1 for highV-bot; s=ffs(n) /*calculate 1st 960 S values.*/ if both.s then call sayErr 'duplicate number in R and S lists:' s both.s=1 /*indicate it's is in both array.*/ end /*n*/ /* [↑] build firstt 960 S values.*/ @@ -24,17 +25,17 @@ if errs==0 then say 'verification completed for all numbers from 1 ──►' else say 'verification failed with' errs "errors." exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────FFR subroutine──────────────────────*/ -ffr: procedure expose r. s. rr. ss.; parse arg n +ffr: procedure expose r. s. rr.; parse arg n if r.n\==0 then return r.n /*Defined? Then return the value.*/ _=ffr(n-1) + ffs(n-1) /*calculate the FFR value. */ r.n=_; rr._=1; return _ /*assign value to R & RR; return.*/ /*──────────────────────────────────FFS subroutine──────────────────────*/ -ffs: procedure expose r. s. rr. ss.; parse arg n +ffs: procedure expose r. s. rr.; parse arg n do k=1 for n while s.n==0 /*search for ¬null R │ S number*/ if s.k\==0 then if ffr(k)\==0 then iterate /*short circuit*/ - km=k-1; _=s.km+1 /*the next SS number, possibly.*/ - _=_+rr._; ss._=1; s.k=_ /*define couple of FFS numbers.*/ + km=k-1; _=s.km+1 /*the next SS number, possibly.*/ + _=_+rr._; s.k=_ /*define an element of S array.*/ end /*k*/ return s.n /*return the value to the invoker*/ /*──────────────────────────────────SAYERR subroutine───────────────────*/ -sayErr: errs=errs+1; say; say '***error***!'; say; say arg(1); say; return +sayErr: errs=errs+1; say '***error***!' arg(1); return diff --git a/Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences.rb b/Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences-1.rb similarity index 100% rename from Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences.rb rename to Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences-1.rb diff --git a/Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences-2.rb b/Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences-2.rb new file mode 100644 index 0000000000..24599de731 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Ruby/hofstadter-figure-figure-sequences-2.rb @@ -0,0 +1,19 @@ +R = Enumerator.new do |y| + y << n = 1 + S.each{|s_val| y << n += s_val} +end + +S = Enumerator.new do |y| + y << 2 + y << 4 + u = 5 + R.each do |r_val| + next if u > r_val + (u...r_val).each{|r| y << r} + u = r_val+1 + end +end + +p R.take(10) +p S.take(10) +p (R.take(40)+ S.take(960)).sort == (1..1000).to_a diff --git a/Task/Hofstadter-Q-sequence/AutoHotkey/hofstadter-q-sequence.ahk b/Task/Hofstadter-Q-sequence/AutoHotkey/hofstadter-q-sequence.ahk new file mode 100644 index 0000000000..e58691087c --- /dev/null +++ b/Task/Hofstadter-Q-sequence/AutoHotkey/hofstadter-q-sequence.ahk @@ -0,0 +1,20 @@ +SetBatchLines, -1 +Q := HofsQSeq(100000) + +Loop, 10 + Out .= Q[A_Index] ", " + +MsgBox, % "First ten:`t" Out "`n" + . "1000th:`t`t" Q[1000] "`n" + . "Flips:`t`t" Q.flips + +HofsQSeq(n) { + Q := {1: 1, 2: 1, "flips": 0} + Loop, % n - 2 { + i := A_Index + 2 + , Q[i] := Q[i - Q[i - 1]] + Q[i - Q[A_Index]] + if (Q[i] < Q[i - 1]) + Q.flips++ + } + return Q +} diff --git a/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d b/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d index 6db968e689..76dea1e9ce 100644 --- a/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d +++ b/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d @@ -3,11 +3,11 @@ import std.stdio, std.algorithm, std.range, std.array; struct Q { __gshared static Appender!(uint[]) s; - /*nothrow*/ static this() { + nothrow static this() { s ~= [0, 1, 1]; } - static uint opCall(in int n) /*nothrow*/ + static uint opCall(in int n) nothrow in { assert(n > 0); } body { diff --git a/Task/Hofstadter-Q-sequence/PicoLisp/hofstadter-q-sequence-1.l b/Task/Hofstadter-Q-sequence/PicoLisp/hofstadter-q-sequence-1.l index b37d0a3385..559e120544 100644 --- a/Task/Hofstadter-Q-sequence/PicoLisp/hofstadter-q-sequence-1.l +++ b/Task/Hofstadter-Q-sequence/PicoLisp/hofstadter-q-sequence-1.l @@ -1,5 +1,5 @@ (de q (N) - (cache '(NIL) (pack (char (hash N)) N) + (cache '(NIL) N (if (>= 2 N) 1 (+ diff --git a/Task/Holidays-related-to-Easter/Forth/holidays-related-to-easter.fth b/Task/Holidays-related-to-Easter/Forth/holidays-related-to-easter.fth new file mode 100644 index 0000000000..92980419ab --- /dev/null +++ b/Task/Holidays-related-to-Easter/Forth/holidays-related-to-easter.fth @@ -0,0 +1,49 @@ +variable year + +: ea_a year @ 19 mod ; +: ea_b year @ 100 / ; +: ea_c year @ 100 mod ; +: ea_d ea_b 4 / ; +: ea_e ea_b 4 mod ; +: ea_f ea_b 8 + 25 / ; +: ea_g ea_b ea_f - 1 + 3 / ; +: ea_h 19 ea_a * ea_b + ea_d - ea_g - 15 + 30 mod ; +: ea_i ea_c 4 / ; +: ea_k ea_c 4 mod ; +: ea_l 32 2 ea_e * + 2 ea_i * + ea_h - ea_k - 7 mod ; +: ea_m ea_a 11 ea_h * + 22 ea_i * + 451 / ; +: ea_numerator ea_h ea_l + 7 ea_m * - 114 + ; +: ea_month ea_numerator 31 / ; +: ea_day ea_numerator 31 mod 1 + ; +: bs ( -- backspace ) + 8 emit ; + +: monthname ( monthnum -- name ) + case + 1 of ." Jan" endof + 2 of ." Feb" endof + 3 of ." Mar" endof + 4 of ." Apr" endof + 5 of ." May" endof + 6 of ." Jun" endof + 7 of ." Jul" endof + 8 of ." Aug" endof + 9 of ." Sep" endof + 10 of ." Oct" endof + 11 of ." Nov" endof + 12 of ." Dec" endof + dup . ." wrong input" + endcase +; + +: eastern ( year -- ) + dup year ! . bs ." :" space ea_day . bs space ea_month monthname ; + +: main + cr .\" year: eastern" cr 2200 400 + DO i eastern cr 100 + +LOOP + cr 2021 2010 + DO i eastern cr + LOOP + ; diff --git a/Task/Horners-rule-for-polynomial-evaluation/Maple/horners-rule-for-polynomial-evaluation.maple b/Task/Horners-rule-for-polynomial-evaluation/Maple/horners-rule-for-polynomial-evaluation.maple new file mode 100644 index 0000000000..a8c2d72b94 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Maple/horners-rule-for-polynomial-evaluation.maple @@ -0,0 +1,5 @@ +applyhorner:=(L::list,x)->foldl((s,t)->s*x+t,op(ListTools:-Reverse(L))): + +applyhorner([-19,7,-4,6],x); + +applyhorner([-19,7,-4,6],3); diff --git a/Task/Horners-rule-for-polynomial-evaluation/NetRexx/horners-rule-for-polynomial-evaluation.netrexx b/Task/Horners-rule-for-polynomial-evaluation/NetRexx/horners-rule-for-polynomial-evaluation.netrexx new file mode 100644 index 0000000000..2d28b70181 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/NetRexx/horners-rule-for-polynomial-evaluation.netrexx @@ -0,0 +1,12 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols nobinary + +c = [-19, 7, -4, 6] -- # list coefficients of all x^0..x^n in order +n=3 +x=3 +r=0 +loop i=n to 0 by -1 + r=r*x+c[i] + End +Say r +Say 6*x**3-4*x**2+7*x-19 diff --git a/Task/Horners-rule-for-polynomial-evaluation/Objective-C/horners-rule-for-polynomial-evaluation.m b/Task/Horners-rule-for-polynomial-evaluation/Objective-C/horners-rule-for-polynomial-evaluation.m index ded684de5d..4ffa7def6c 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Objective-C/horners-rule-for-polynomial-evaluation.m +++ b/Task/Horners-rule-for-polynomial-evaluation/Objective-C/horners-rule-for-polynomial-evaluation.m @@ -32,16 +32,11 @@ typedef double (^mfunc)(double, double); int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSArray *coeff = [NSArray - arrayWithObjects: - [NSNumber numberWithDouble: -19.0], - [NSNumber numberWithDouble: 7.0], - [NSNumber numberWithDouble: -4.0], - [NSNumber numberWithDouble: 6.0], nil]; - printf("%f\n", [coeff horner: 3.0]); + NSArray *coeff = @[@-19.0, @7.0, @-4.0, @6.0]; + printf("%f\n", [coeff horner: 3.0]); - [pool release]; + } return 0; } diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation.pl6 b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-1.pl6 similarity index 100% rename from Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation.pl6 rename to Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-1.pl6 diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 new file mode 100644 index 0000000000..01f0b18d27 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 @@ -0,0 +1,6 @@ +multi horner(Numeric $c, $) { $c } +multi horner(Pair $c, $x) { + $c.key + $x * horner( $c.value, $x ) +} + +print horner( [=>](-19, 7, -4, 6 ), 3 ); diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 new file mode 100644 index 0000000000..bfd0fb9455 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 @@ -0,0 +1,12 @@ +sub infix:(&f, &g) { -> $x { &f(&g($x)) } } + +sub horner ( @c, $x ) { + [\o] map { -> $u { $_ + $x * $u } }, @c; +} + +say map { .(0) }, horner( [ -19, 7, -4, 6 ], 3 ); + +# compute progressive approximations of exp(2) +my @c := 1 X/ 1, [\*] 1 ... *; + +say .(0) for horner( @c, 2 ); diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl/horners-rule-for-polynomial-evaluation-3.pl b/Task/Horners-rule-for-polynomial-evaluation/Perl/horners-rule-for-polynomial-evaluation-3.pl new file mode 100644 index 0000000000..91e2c33ed1 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Perl/horners-rule-for-polynomial-evaluation-3.pl @@ -0,0 +1,7 @@ +sub horner { + my ($coeff, $x) = @_; + @$coeff and + $$coeff[0] + $x * horner( [@$coeff[1 .. $#$coeff]], $x ) +} + +print horner( [ -19, 7, -4, 6 ], 3 ); diff --git a/Task/Huffman-coding/Objective-C/huffman-coding.m b/Task/Huffman-coding/Objective-C/huffman-coding.m index 499949e3e1..9912d7bf4e 100644 --- a/Task/Huffman-coding/Objective-C/huffman-coding.m +++ b/Task/Huffman-coding/Objective-C/huffman-coding.m @@ -5,7 +5,7 @@ int freq; } -(id)initWithFreq:(int)f; -@property (readonly) int freq; +@property (nonatomic, readonly) int freq; @end @implementation HuffmanTree @@ -20,14 +20,14 @@ const void *HuffmanRetain(CFAllocatorRef allocator, const void *ptr) { - return [(id)ptr retain]; + return (__bridge_retained const void *)(__bridge id)ptr; } void HuffmanRelease(CFAllocatorRef allocator, const void *ptr) { - [(id)ptr release]; + (void)(__bridge_transfer id)ptr; } CFComparisonResult HuffmanCompare(const void *ptr1, const void *ptr2, void *unused) { - int f1 = ((HuffmanTree *)ptr1).freq; - int f2 = ((HuffmanTree *)ptr2).freq; + int f1 = ((__bridge HuffmanTree *)ptr1).freq; + int f2 = ((__bridge HuffmanTree *)ptr2).freq; if (f1 == f2) return kCFCompareEqualTo; else if (f1 > f2) @@ -66,16 +66,11 @@ CFComparisonResult HuffmanCompare(const void *ptr1, const void *ptr2, void *unus @synthesize left, right; -(id)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r { if (self = [super initWithFreq:l.freq+r.freq]) { - left = [l retain]; - right = [r retain]; + left = l; + right = r; } return self; } --(void)dealloc { - [left release]; - [right release]; - [super dealloc]; -} @end @@ -89,24 +84,24 @@ HuffmanTree *buildTree(NSCountedSet *chars) { for (NSNumber *ch in chars) { int freq = [chars countForObject:ch]; if (freq > 0) - CFBinaryHeapAddValue(trees, [[[HuffmanLeaf alloc] initWithFreq:freq character:(char)[ch intValue]] autorelease]); + CFBinaryHeapAddValue(trees, (__bridge const void *)[[HuffmanLeaf alloc] initWithFreq:freq character:(char)[ch intValue]]); } NSCAssert(CFBinaryHeapGetCount(trees) > 0, @"String must have at least one character"); // loop until there is only one tree left while (CFBinaryHeapGetCount(trees) > 1) { // two trees with least frequency - HuffmanTree *a = (HuffmanTree *)CFBinaryHeapGetMinimum(trees); + HuffmanTree *a = (__bridge HuffmanTree *)CFBinaryHeapGetMinimum(trees); CFBinaryHeapRemoveMinimumValue(trees); - HuffmanTree *b = (HuffmanTree *)CFBinaryHeapGetMinimum(trees); + HuffmanTree *b = (__bridge HuffmanTree *)CFBinaryHeapGetMinimum(trees); CFBinaryHeapRemoveMinimumValue(trees); // put into new node and re-insert into queue - CFBinaryHeapAddValue(trees, [[[HuffmanNode alloc] initWithLeft:a right:b] autorelease]); + CFBinaryHeapAddValue(trees, (__bridge const void *)[[HuffmanNode alloc] initWithLeft:a right:b]); } - HuffmanTree *result = [(HuffmanTree *)CFBinaryHeapGetMinimum(trees) retain]; + HuffmanTree *result = (__bridge HuffmanTree *)CFBinaryHeapGetMinimum(trees); CFRelease(trees); - return [result autorelease]; + return result; } void printCodes(HuffmanTree *tree, NSMutableString *prefix) { @@ -133,7 +128,7 @@ void printCodes(HuffmanTree *tree, NSMutableString *prefix) { } int main(int argc, const char * argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { NSString *test = @"this is an example for huffman encoding"; @@ -141,16 +136,15 @@ int main(int argc, const char * argv[]) { NSCountedSet *chars = [[NSCountedSet alloc] init]; int n = [test length]; for (int i = 0; i < n; i++) - [chars addObject:[NSNumber numberWithInt:[test characterAtIndex:i]]]; + [chars addObject:@([test characterAtIndex:i])]; // build tree HuffmanTree *tree = buildTree(chars); - [chars release]; // print out results NSLog(@"SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, [NSMutableString string]); - [pool drain]; + } return 0; } diff --git a/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-1.pl6 b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-1.pl6 new file mode 100644 index 0000000000..9709d8672d --- /dev/null +++ b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-1.pl6 @@ -0,0 +1,68 @@ +grammar CollectWords { + token TOP { + [^^ $$ \n?]+ + } + + token word { + [ | | \N ]+ + } + + token with_c { + c + } + + token no_c { + + } + + token ie_part { + ie | ei | eie # a couple words in the list have "eie" + } +} + +class CollectWords::Actions { + method TOP($/) { + make $».ast.Bag; + } + + method word($/) { + if $ + $ { + make ($».ast, $».ast); + } else { + make (); + } + } + + method with_c($/) { + make "c" X~ $.ast; + } + + method no_c($/) { + make "!c" X~ $.ast; + } + + method ie_part($/) { + if ~$/ eq 'eie' { + make ('ei', 'ie'); + } else { + make ~$/; + } + } +} + +sub plausible($good, $bad, $msg) { + if $good > 2*$bad { + say "$msg: PLAUSIBLE ($good ✔ vs. $bad ✘)"; + return True; + } else { + say "$msg: NOT PLAUSIBLE ($good ✔ vs. $bad ✘)"; + return False; + } +} + +my $results = CollectWords.parsefile("unixdict.txt", :actions(CollectWords::Actions)).ast; + +my $phrasetest = [&] plausible($results, $results, "I before E when not preceded by C"), + plausible($results, $results, "E before I when preceded by C"); + +say "I before E except after C: ", $phrasetest ?? "PLAUSIBLE" !! "NOT PLAUSIBLE"; diff --git a/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 new file mode 100644 index 0000000000..c6ea5a84b6 --- /dev/null +++ b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 @@ -0,0 +1,66 @@ +grammar CollectWords { + token TOP { + ^^ \t Word \t PoS \t Freq $$ \n + [^^ $$ \n?]+ + } + + token word { + \t+ + [ | | \T ]+ \t+ + \T+ \t+ # PoS doesn't matter to us, so ignore it + $=[<.digit>+] \h* + } + + token with_c { + c + } + + token no_c { + + } + + token ie_part { + ie | ei + } +} + +class CollectWords::Actions { + method TOP($/) { + make $».ast».flat.Bag; + } + + method word($/) { + if $ + $ { + make ($».ast xx $, $».ast xx $); + } else { + make (); + } + } + + method with_c($/) { + make "c" ~ $; + } + + method no_c($/) { + make "!c" ~ $; + } +} + +sub plausible($good, $bad, $msg) { + if $good > 2*$bad { + say "$msg: PLAUSIBLE ($good ✔ vs. $bad ✘)"; + return True; + } else { + say "$msg: NOT PLAUSIBLE ($good ✔ vs. $bad ✘)"; + return False; + } +} + +# can't use .parsefile like before due to the non-Unicode £ in this file. +my $file = slurp("1_2_all_freq.txt", :enc); +my $results = CollectWords.parse($file, :actions(CollectWords::Actions)).ast; + +my $phrasetest = [&] plausible($results, $results, "I before E when not preceded by C"), + plausible($results, $results, "E before I when preceded by C"); + +say "I before E except after C: ", $phrasetest ?? "PLAUSIBLE" !! "NOT PLAUSIBLE"; diff --git a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh new file mode 100644 index 0000000000..0a1ce05f03 --- /dev/null +++ b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh @@ -0,0 +1,29 @@ +$Web = New-Object -TypeName Net.Webclient +$Words = $web.DownloadString('http://www.puzzlers.org/pub/wordlists/unixdict.txt') + +$IE = $EI = $CIE = $CEI = @() + +$Clause1 = $Clause2 = $MainClause = $false + +foreach ($Word in $Words.split()) +{ + switch ($Word) + { + {($_ -like '*ie*') -and ($_ -notlike '*cie*')} {$IE += $Word} + {($_ -like '*ei*') -and ($_ -notlike '*cei*')} {$EI += $Word} + {$_ -like '*cei*'} {$CEI += $Word} + {$_ -like '*cie*'} {$CIE += $Word} + } +} + +if ($IE.count -gt $EI.count * 2) +{$Clause1 = $true} +"The plausibility of 'I before E when not preceded by C' is $Clause1" + +if ($CIE.count -gt $CEI.count * 2) +{$Clause2 = $true} +"The plausibility of 'II before E when preceded by C' is $Clause2" + +if ($Clause1 -and $Clause2) +{$MainClause = $True} +"The plausibility of the phrase 'I before E except after C' is $MainClause" diff --git a/Task/I-before-E-except-after-C/UNIX-Shell/i-before-e-except-after-c.sh b/Task/I-before-E-except-after-C/UNIX-Shell/i-before-e-except-after-c.sh index 94881762e0..6f4c2db991 100644 --- a/Task/I-before-E-except-after-C/UNIX-Shell/i-before-e-except-after-c.sh +++ b/Task/I-before-E-except-after-C/UNIX-Shell/i-before-e-except-after-c.sh @@ -1,14 +1,27 @@ #!/bin/sh matched() { - egrep "$1" unixdict.txt | wc -l + grep -Poe "$1" unixdict.txt | wc -l } check() { - if [ $(expr $(matched $3) \> $(expr 2 \* $(matched $2))) = '0' ]; then - echo clause $1 not plausible - exit 1 - fi + local num_for="$(matched "$3")" + local num_against="$(matched "$2")" + if [ "$num_for" -le "$(expr 2 \* "$num_against")" ]; then + echo "Clause $1 not plausible ($num_for examples; $num_against counterexamples)" + return 1 + else + echo "Clause $1 is plausible ($num_for examples; $num_against counterexamples)" + return 0 + fi } -check 1 \[^c\]ei \[^c\]ie && check 2 cie cei && echo plausible +check 1 '(? ... + END CLASS Animal. + + CLASS-ID. Dog INHERITS Animal. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Animal. + + *> ... + END CLASS Dog. + + CLASS-ID. Cat INHERITS Animal. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Animal. + + *> ... + END CLASS Cat. + + CLASS-ID. Lab INHERITS Dog. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Dog. + + *> ... + END CLASS Lab. + + CLASS-ID. Collie INHERITS Dog. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Dog. + + *> ... + END CLASS Collie. diff --git a/Task/Input-loop/PowerShell/input-loop-1.psh b/Task/Input-loop/PowerShell/input-loop-1.psh new file mode 100644 index 0000000000..bc979506ad --- /dev/null +++ b/Task/Input-loop/PowerShell/input-loop-1.psh @@ -0,0 +1,4 @@ +Get-Content c:\file.txt | + ForEach-Object { + $_ + } diff --git a/Task/Input-loop/PowerShell/input-loop-2.psh b/Task/Input-loop/PowerShell/input-loop-2.psh new file mode 100644 index 0000000000..91f2ae8fa2 --- /dev/null +++ b/Task/Input-loop/PowerShell/input-loop-2.psh @@ -0,0 +1 @@ +ForEach-Object -inputobject (get-content c:\file.txt) {$_} diff --git a/Task/Integer-sequence/Frink/integer-sequence.frink b/Task/Integer-sequence/Frink/integer-sequence.frink new file mode 100644 index 0000000000..7d91a5a735 --- /dev/null +++ b/Task/Integer-sequence/Frink/integer-sequence.frink @@ -0,0 +1,6 @@ +i=0 +while true +{ + println[i] + i = i + 1 +} diff --git a/Task/Integer-sequence/Maple/integer-sequence.maple b/Task/Integer-sequence/Maple/integer-sequence.maple new file mode 100644 index 0000000000..ddf22d07ed --- /dev/null +++ b/Task/Integer-sequence/Maple/integer-sequence.maple @@ -0,0 +1,3 @@ +for n do + print(n) +end do; diff --git a/Task/Integer-sequence/PowerShell/integer-sequence.psh b/Task/Integer-sequence/PowerShell/integer-sequence.psh new file mode 100644 index 0000000000..5c34aa0e4c --- /dev/null +++ b/Task/Integer-sequence/PowerShell/integer-sequence.psh @@ -0,0 +1,8 @@ +try +{ + for ([int]$i = 0;;$i++) + { + $i + } +} +catch {break} diff --git a/Task/Interactive-programming/Maple/interactive-programming.maple b/Task/Interactive-programming/Maple/interactive-programming.maple new file mode 100644 index 0000000000..0c7dc76f45 --- /dev/null +++ b/Task/Interactive-programming/Maple/interactive-programming.maple @@ -0,0 +1,3 @@ +f := (a,b,c)->cat(a,c,c,b): + +f("Rosetta","Code",":"); diff --git a/Task/Inverted-index/Clojure/inverted-index.clj b/Task/Inverted-index/Clojure/inverted-index.clj new file mode 100644 index 0000000000..730a727343 --- /dev/null +++ b/Task/Inverted-index/Clojure/inverted-index.clj @@ -0,0 +1,25 @@ +(ns inverted-index.core + (:require [clojure.set :as sets] + [clojure.java.io :as io])) + +(def pattern #"\w+") ; Java regex for a raw term: here a substring of alphanums +(defn normalize [match] (.toLowerCase match)) ; normalization of a raw term + +(defn term-seq [text] (map normalize (re-seq pattern text))) + +(defn set-assoc + "Produces map with v added to the set associated with key k in map m" + [m k v] (assoc m k (conj (get m k #{}) v))) + +(defn index-file [index file] + (with-open [reader (io/reader file)] + (reduce + (fn [idx term] (set-assoc idx term file)) + index + (mapcat term-seq (line-seq reader))))) + +(defn make-index [files] + (reduce index-file {} files)) + +(defn search [index query] + (apply sets/intersection (map index (term-seq query)))) diff --git a/Task/Jensens-Device/Forth/jensens-device.fth b/Task/Jensens-Device/Forth/jensens-device-1.fth similarity index 85% rename from Task/Jensens-Device/Forth/jensens-device.fth rename to Task/Jensens-Device/Forth/jensens-device-1.fth index 24d7347ce2..9ff14f52e0 100644 --- a/Task/Jensens-Device/Forth/jensens-device.fth +++ b/Task/Jensens-Device/Forth/jensens-device-1.fth @@ -1,3 +1,2 @@ -: s>f s>d d>f ; : sum 0 s>f 1+ swap ?do i over execute f+ loop drop ; :noname s>f 1 s>f fswap f/ ; 1 100 sum f. diff --git a/Task/Jensens-Device/Forth/jensens-device-2.fth b/Task/Jensens-Device/Forth/jensens-device-2.fth new file mode 100644 index 0000000000..dfa591b40d --- /dev/null +++ b/Task/Jensens-Device/Forth/jensens-device-2.fth @@ -0,0 +1,6 @@ +fvariable ii \ i is a Forth word that we need +: sum ( xt1 lo hi xt2 -- r ) + 0e swap 1+ rot ?do ( addr xt r1 ) + i s>f over execute f! dup execute f+ + loop 2drop ; +' ii 1 100 :noname 1e ii f@ f/ ; sum f. diff --git a/Task/Jensens-Device/Java/jensens-device-1.java b/Task/Jensens-Device/Java/jensens-device-1.java new file mode 100644 index 0000000000..e39635c291 --- /dev/null +++ b/Task/Jensens-Device/Java/jensens-device-1.java @@ -0,0 +1,12 @@ +import java.util.function.*; +import java.util.stream.*; + +public class Jensen { + static double sum(int lo, int hi, IntToDoubleFunction f) { + return IntStream.rangeClosed(lo, hi).mapToDouble(f).sum(); + } + + public static void main(String args[]) { + System.out.println(sum(1, 100, (i -> 1.0/i))); + } +} diff --git a/Task/Jensens-Device/Java/jensens-device-2.java b/Task/Jensens-Device/Java/jensens-device-2.java new file mode 100644 index 0000000000..c5ad6a4166 --- /dev/null +++ b/Task/Jensens-Device/Java/jensens-device-2.java @@ -0,0 +1,21 @@ +public class Jensen2 { + + interface IntToDoubleFunction { + double apply(int n); + } + + static double sum(int lo, int hi, IntToDoubleFunction f) { + double res = 0; + for (int i = lo; i <= hi; i++) + res += f.apply(i); + return res; + + } + public static void main(String args[]) { + System.out.println( + sum(1, 100, + new IntToDoubleFunction() { + public double apply(int i) { return 1.0/i;} + })); + } +} diff --git a/Task/Josephus-problem/Julia/josephus-problem-1.julia b/Task/Josephus-problem/Julia/josephus-problem-1.julia new file mode 100644 index 0000000000..f71db474ad --- /dev/null +++ b/Task/Josephus-problem/Julia/josephus-problem-1.julia @@ -0,0 +1,8 @@ + function j(n,k) + p, i, seq=[0:n-1], 0, Int[] + while !isempty(p) + i=(i+k-1)%length(p) + push!(seq,splice!(p,i+1)) + end + @sprintf("Prisoner killing order: %s.\nSurvivor: %i",replace(chomp(string(seq[1:end-1])),"\n",", "),seq[end]) +end diff --git a/Task/Josephus-problem/Julia/josephus-problem-2.julia b/Task/Josephus-problem/Julia/josephus-problem-2.julia new file mode 100644 index 0000000000..724d8ee0c9 --- /dev/null +++ b/Task/Josephus-problem/Julia/josephus-problem-2.julia @@ -0,0 +1,3 @@ +julia> print(j(41,3)) +Prisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15. +Survivor: 30 diff --git a/Task/Josephus-problem/Julia/josephus-problem-3.julia b/Task/Josephus-problem/Julia/josephus-problem-3.julia new file mode 100644 index 0000000000..44e6d362bc --- /dev/null +++ b/Task/Josephus-problem/Julia/josephus-problem-3.julia @@ -0,0 +1,9 @@ + function j2(n,k,m) + p, i, seq=[0:n-1], 0, Int[] + while length(p)>m + i=(i+k-1)%length(p) + push!(seq,splice!(p,i+1)) + end + prt_array(x)=replace(chomp(string(x)),"\n",", ") + @sprintf("Prisoner killing order: %s.\nSurvivors: %s",prt_array(seq),"["*prt_array(p)*"]") +end diff --git a/Task/Josephus-problem/Julia/josephus-problem-4.julia b/Task/Josephus-problem/Julia/josephus-problem-4.julia new file mode 100644 index 0000000000..a29b22a470 --- /dev/null +++ b/Task/Josephus-problem/Julia/josephus-problem-4.julia @@ -0,0 +1,3 @@ +julia> print(j2(41,3,3)) +Prisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3. +Survivors: [15, 30, 34] diff --git a/Task/Joystick-position/AutoHotkey/joystick-position.ahk b/Task/Joystick-position/AutoHotkey/joystick-position.ahk new file mode 100644 index 0000000000..cc0e108b26 --- /dev/null +++ b/Task/Joystick-position/AutoHotkey/joystick-position.ahk @@ -0,0 +1,219 @@ +; Uncomment if Gdip.ahk is not in your standard library +; #Include, Gdip.ahk + +; Comment for lower CPU usage +SetBatchLines, -1 + +JoystickNumber := 0 ; (1-16) or (0 = Auto-detect) +CrosshairSize := 100 +BarWidth := 50 +BarSpacing := BarWidth + 8 +Color1 := 0x99000000 +Color2 := 0x99ffffff +Color3 := 0x99ff6600 +Color4 := 0xff0066ff +Color5 := 0xffff6600 +Font := "Arial" +FontSize1 := 20 +FontSize2 := 30 +Lineweight1 := 8 +Lineweight2 := 3 +Lineweight3 := 2 +Lineweight4 := 4 +Show2ndCrosshair := true +AxisLabelHeight := 47 + +#SingleInstance, Force +#NoEnv +OnExit, Exit +SysGet, MWA, MonitorWorkArea +CrosshairOffset := CrosshairSize // 2 +, CircleOffset := CrosshairOffset - 5 +, CircleSize := CrosshairSize - 10 +, TaskBarHeight := A_ScreenHeight - MWABottom + Lineweight1 // 2 +, ScaleX := A_ScreenWidth / 100 +, ScaleY1 := (A_ScreenHeight - TaskBarHeight - AxisLabelHeight) / 100 +, ScaleY2 := A_ScreenHeight / 100 +, BarCenter := (MWABottom - AxisLabelHeight) // 2 + AxisLabelHeight +, BorderBot := MWABottom - Lineweight1 // 2 + 2 +, PieSize := 400 +, PieX := (A_ScreenWidth - PieSize) // 2 +, PieY := (A_ScreenHeight - PieSize) // 2 +, BarHeight := A_ScreenHeight - AxisLabelHeight - TaskBarHeight +, AxisTextOffset := BarWidth > 32 ? (BarWidth - 32) // 2 : 0 +, Axis_Array := {"X": "X", "Y": "Y"} +, MaxI := 2 + +; Auto-detect the joystick number if called for +if (JoystickNumber < 1) { + Loop, 16 { + GetKeyState, Joy_Name, %A_Index%JoyName + if (Joy_Name) { + JoystickNumber := A_Index + break + } + } + if (!JoystickNumber) { + MsgBox The system does not appear to have any joysticks. + ExitApp + } +} +else { + GetKeyState, Joy_Name, %JoystickNumber%JoyName + if (!Joy_Name) { + MsgBox The system does not appear to have a joystick number %JoystickNumber%. + ExitApp + } +} + +if (!pToken := Gdip_Startup()) { + MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. + ExitApp +} + +If (!Gdip_FontFamilyCreate(Font)) { + MsgBox, 48, Font error!, The font you have specified does not exist on your system. + ExitApp +} + +; Get joystick information +SetFormat, FloatFast, 03.2 +GetKeyState, Joy_Buttons, % JoystickNumber "JoyButtons" +GetKeyState, Joy_Info, % JoystickNumber "JoyInfo" +Loop, Parse, Joy_Info + if (A_LoopField != "C" && A_LoopField != "D" && A_LoopField != "P") + Axis_Array[A_LoopField] := A_LoopField + , %A_LoopField% := true + , MaxI++ + else + %A_LoopField% := true + +; Setup Gdip +Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, 1: Show, NA +hwnd1 := WinExist() +, hbm := CreateDIBSection(A_ScreenWidth, A_ScreenHeight) +, hdc := CreateCompatibleDC() +, obm := SelectObject(hdc, hbm) +, G1 := Gdip_GraphicsFromHDC(hdc) +, Gdip_SetSmoothingMode(G1, 4) +, pPen1 := Gdip_CreatePen(Color1, Lineweight1) +, pPen2 := Gdip_CreatePen(Color2, Lineweight2) +, pPen3 := Gdip_CreatePen(Color4, Lineweight3) +, pPen4 := Gdip_CreatePen(Color5, Lineweight4) +, pBrush1 := Gdip_BrushCreateSolid(Color1) +, pBrush2 := Gdip_BrushCreateSolid(Color3) + +; Crosshair 2 +if ((R || U) && Show2ndCrosshair) { + pPen5 := Gdip_CreatePen(Color5, Lineweight3) + , pPen6 := Gdip_CreatePen(Color4, Lineweight4) + , joy_r := joy_u := 50 +} + +; Bar X-offsets +for key, val in Axis_Array + %val%X := A_ScreenWidth - MaxI * BarSpacing + BarSpacing * (A_Index - 1) + 3 + +; Info box +IBH1 := 150 +, IBW1 := 450 +, IBX1 := A_ScreenWidth - MaxI * BarSpacing - IBW1 +, IBY1 := A_ScreenHeight - TaskBarHeight - IBH1 + Lineweight1 // 2 +, IBH2 := IBH1 - 8 +, IBW2 := IBW1 - 8 +, IBX2 := IBX1 + 4 +, IBY2 := IBY1 + 4 +, FontOptions1 := "x" (IBX1 + 8) " y" (IBY1 + 8) " w" IBW1 - 20 " Left c" SubStr(Color2, 3) " r4 s" FontSize1 " Bold" + +; Axis box +ABH1 := AxisLabelHeight + 4 +, ABW1 := MaxI * BarSpacing +, ABX1 := A_ScreenWidth - MaxI * BarSpacing +, ABY1 := 0 +, ABH2 := ABH1 - 16 +, ABW2 := ABW1 - 8 +, ABX2 := ABX1 + 4 +, ABY2 := ABY1 + 4 +, FontOptions2 := " y" ABY1 + AxisLabelHeight - 40 " w" ABW1 - 10 " Left c" SubStr(Color2, 3) " r4 s" FontSize2 " Bold" + +; Update graphics +Loop, { + Buttons_Down := "" + Loop, %Joy_Buttons% { + GetKeyState, joy%A_Index%, %JoystickNumber%joy%A_Index% + if (joy%A_Index% = "D") + Buttons_Down .= " " A_Index + } + + ; Info & axis boxes + InfoText := Joy_Name " (#" JoystickNumber "):`n" Axis_Info "`nButtons Down: " Buttons_Down "`n`n(Ctrl+Esc to exit)" + , Gdip_FillRoundedRectangle(G1, pBrush1, IBX1, IBY1, IBW1, IBH1, 5) + , Gdip_DrawRoundedRectangle(G1, pPen2, IBX2, IBY2, IBW2, IBH2, 5) + , Gdip_TextToGraphics(G1, InfoText, FontOptions1, Font, A_ScreenWidth, A_ScreenHeight) + , Gdip_FillRoundedRectangle(G1, pBrush1, ABX1, ABY1, ABW1, ABH1, 5) + , Gdip_DrawRoundedRectangle(G1, pPen2, ABX2, ABY2, ABW2, ABH2, 5) + + ; Axis bars + Axis_Info := "" + for key, val in Axis_Array { + GetKeyState, joy_%val%, % JoystickNumber "Joy" val + Axis_Info .= val joy_%val% " " + if (joy_%val% > 50) + %val%Y := BarCenter + , %val%h1 := (joy_%val% - 50) * ScaleY1 + else + %val%Y := AxisLabelHeight + joy_%val% * ScaleY1 ; + , Sc - (joy_%val% - 50) * ScaleY1 + , %val%h1 := BarCenter - %val%Y + Gdip_FillRoundedRectangle(G1, pBrush2, %val%X, %val%Y, BarWidth, %val%h1, 2) + , Gdip_DrawRoundedRectangle(G1, pPen1, %val%X, AxisLabelHeight, BarWidth, BarHeight, 5) + , Gdip_DrawRoundedRectangle(G1, pPen2, %val%X, AxisLabelHeight, BarWidth, BarHeight, 5) + , Gdip_TextToGraphics(G1, val, "x" (%val%X + AxisTextOffset) FontOptions2, Font, A_ScreenWidth, A_ScreenHeight) + } + + ; POV hat + If (P) { + GetKeyState, Joy_P, %JoystickNumber%JoyPOV + Axis_Info .= " POV" Joy_P + if (Joy_P > -1) { + StartAngle := (Joy_P > 33750 || Joy_P <= 2250) ? 247.5 ; up + : Joy_P > 29250 ? 202.5 ; up left + : Joy_P > 24750 ? 157.5 ; left + : Joy_P > 20250 ? 112.5 ; down left + : Joy_P > 15750 ? 67.5 ; down + : Joy_P > 11250 ? 22.5 ; down right + : Joy_P > 6750 ? 337.5 ; right + : 292.5 ; up right + , Gdip_FillPie(G1, pBrush2, PieX, PieY, PieSize, PieSize, StartAngle, 45) + , Gdip_DrawPie(G1, pPen1, PieX, PieY, PieSize, PieSize, StartAngle, 45) + , Gdip_DrawPie(G1, pPen2, PieX, PieY, PieSize, PieSize, StartAngle, 45) + } + } + + ; Crosshair 1 + CenterX := ScaleX * joy_x + , CenterY := ScaleY2 * joy_y + , Gdip_DrawLine(G1, pPen3, CenterX-CrosshairOffset, CenterY, CenterX+CrosshairOffset, CenterY) + , Gdip_DrawLine(G1, pPen3, CenterX, CenterY-CrosshairOffset, CenterX, CenterY+CrosshairOffset) + , Gdip_DrawEllipse(G1, pPen4, CenterX-CircleOffset, CenterY-CircleOffset, CircleSize, CircleSize) + , Gdip_DrawEllipse(G1, pPen4, CenterX-3, CenterY-3, 6, 6) + + ; Crosshair 2 + if ((R || U) && Show2ndCrosshair) + CenterU := ScaleX * joy_u + , CenterR := ScaleY2 * joy_r + , Gdip_DrawLine(G1, pPen5, CenterU-CrosshairOffset, CenterR, CenterU+CrosshairOffset, CenterR) + , Gdip_DrawLine(G1, pPen5, CenterU, CenterR-CrosshairOffset, CenterU, CenterR+CrosshairOffset) + , Gdip_DrawEllipse(G1, pPen6, CenterU-CircleOffset, CenterR-CircleOffset, CircleSize, CircleSize) + , Gdip_DrawEllipse(G1, pPen6, CenterU-3, CenterR-3, 6, 6) + + UpdateLayeredWindow(hwnd1, hdc, 0, 0, A_ScreenWidth, A_ScreenHeight) + , Gdip_GraphicsClear(G1) +} +return + +^Esc:: +Exit: +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/K-means++-clustering/D/k-means++-clustering.d b/Task/K-means++-clustering/D/k-means++-clustering.d index cbc6331606..0d57e9359f 100644 --- a/Task/K-means++-clustering/D/k-means++-clustering.d +++ b/Task/K-means++-clustering/D/k-means++-clustering.d @@ -1,5 +1,10 @@ import std.stdio, std.math, std.random, std.typecons, std.algorithm; +// On Windows this uses the printf from the Microsoft C runtime, +// that doesn't handle real type and some of the C99 format +// specifiers, but it's faster for blunk printing. +extern(C) nothrow int printf(const char*, ...); + struct Point { immutable double x, y; // Or float. size_t cluster; @@ -198,9 +203,9 @@ in { Color[] colors; colors.reserve(centers.length); foreach (immutable i; 0 .. centers.length) - colors ~= Color((3 * (i + 1) % k) / cast(double)k, - (7 * i % k) / cast(double)k, - (9 * i % k) / cast(double)k); + colors ~= Color((3 * (i + 1) % k) / double(k), + (7 * i % k) / double(k), + (9 * i % k) / double(k)); printf("%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d\n", W + 10, H + 10); diff --git a/Task/Kaprekar-numbers/AutoHotkey/kaprekar-numbers-1.ahk b/Task/Kaprekar-numbers/AutoHotkey/kaprekar-numbers-1.ahk new file mode 100644 index 0000000000..1a57655372 --- /dev/null +++ b/Task/Kaprekar-numbers/AutoHotkey/kaprekar-numbers-1.ahk @@ -0,0 +1,15 @@ +Kaprekar(L) { + Loop, % L + ( C := 0 ) { + S := ( N := A_Index ) ** 2 + Loop % StrLen(N) { + B := ( B := SubStr(S,1+A_Index) ) ? B : 0 + If !B & ( (A := SubStr(S,1,A_Index)) <> 1 ) + Break + If ( N == A+B ) { + R .= ", " N , C++ + Break + } + } + } + Return C " Kaprekar numbers in [1-" L "]:`n" SubStr(R,3) +} diff --git a/Task/Kaprekar-numbers/AutoHotkey/kaprekar-numbers-2.ahk b/Task/Kaprekar-numbers/AutoHotkey/kaprekar-numbers-2.ahk new file mode 100644 index 0000000000..fdf2227871 --- /dev/null +++ b/Task/Kaprekar-numbers/AutoHotkey/kaprekar-numbers-2.ahk @@ -0,0 +1 @@ +MsgBox, % Kaprekar(10000) diff --git a/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-1.ahk b/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-1.ahk new file mode 100644 index 0000000000..db7f124be8 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-1.ahk @@ -0,0 +1,2 @@ +; Input [, OutputVar, Options, EndKeys, MatchList] +Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds diff --git a/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-2.ahk b/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-2.ahk new file mode 100644 index 0000000000..722c12b689 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-2.ahk @@ -0,0 +1,2 @@ +; GetKeyState, OutputVar, KeyName [, Mode] +GetKeyState, State, RButton ; Right mouse button. diff --git a/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-3.ahk b/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-3.ahk new file mode 100644 index 0000000000..33e3bb74a0 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/AutoHotkey/keyboard-input-keypress-check-3.ahk @@ -0,0 +1,2 @@ +; KeyIsDown := GetKeyState("KeyName" [, "Mode"]) +State := GetKeyState("RButton", "P") ; Right mouse button. P = Physical state. diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/AutoHotkey/keyboard-input-obtain-a-y-or-n-response.ahk b/Task/Keyboard-input-Obtain-a-Y-or-N-response/AutoHotkey/keyboard-input-obtain-a-y-or-n-response.ahk index 4940ea7af3..caf25acceb 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/AutoHotkey/keyboard-input-obtain-a-y-or-n-response.ahk +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/AutoHotkey/keyboard-input-obtain-a-y-or-n-response.ahk @@ -1,11 +1,7 @@ -#NoEnv ; Recommended for increased performance -Input, Response,,,y,n -; Waits until they press y or n, storing all characters. -StringRight, Out, Response, 1 -; retrieves the ending character (which will be y or n) -Msgbox %out% -If (Out = "y") - Msgbox You pressed Y -If (Out = "n") - Msgbox You pressed n +Loop, { + Input, Key, L1 + if (Key = "n" || Key = "y") + break +} +MsgBox, % "The response was """ Key """." ExitApp diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response.js b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response.js new file mode 100644 index 0000000000..3801d331cf --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response.js @@ -0,0 +1,14 @@ +var keypress = require('keypress'); + +keypress(process.stdin); + +process.stdin.on('keypress', function (ch, key) { + if (key && (key.name === 'y' || key.name === 'n')) { + var reply = key.name === 'y'; + console.log('Reply:', reply); + // ...do something with 'reply'... + } +}); + +process.stdin.setRawMode(true); +process.stdin.resume(); diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/NetRexx/keyboard-input-obtain-a-y-or-n-response.netrexx b/Task/Keyboard-input-Obtain-a-Y-or-N-response/NetRexx/keyboard-input-obtain-a-y-or-n-response.netrexx new file mode 100644 index 0000000000..b97fa6102d --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/NetRexx/keyboard-input-obtain-a-y-or-n-response.netrexx @@ -0,0 +1,11 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols binary + +Say 'Please enter Y or N' +parse ask c +Select + when c='Y' Then Say 'YES' + when c='N' Then Say 'NO' + otherwise Say 'Undecided' + End diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/PL-I/keyboard-input-obtain-a-y-or-n-response.pli b/Task/Keyboard-input-Obtain-a-Y-or-N-response/PL-I/keyboard-input-obtain-a-y-or-n-response.pli new file mode 100644 index 0000000000..3d77b525a1 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/PL-I/keyboard-input-obtain-a-y-or-n-response.pli @@ -0,0 +1,15 @@ + yn: Proc Options(main): + Dcl sysin stream input; + Dcl sysprint stream output; + Dcl c Char(1); + Put Skip List('Please enter Y or N'); + Get Edit(c)(a(1)); + Select(c); + When('Y','y','J','j') + Put Skip List('YES'); + When('N','n') + Put Skip List('NO'); + Otherwise + Put Skip List('Undecided?'); + End; + End; diff --git a/Task/Knapsack-problem-0-1/PicoLisp/knapsack-problem-0-1.l b/Task/Knapsack-problem-0-1/PicoLisp/knapsack-problem-0-1.l index 13074bf08a..0846115261 100644 --- a/Task/Knapsack-problem-0-1/PicoLisp/knapsack-problem-0-1.l +++ b/Task/Knapsack-problem-0-1/PicoLisp/knapsack-problem-0-1.l @@ -14,7 +14,7 @@ # Dynamic programming solution (de knapsack (Lst W) (when Lst - (cache '*KnapCache (pack (length Lst) ":" W) + (cache '*KnapCache (cons W Lst) (let X (knapsack (cdr Lst) W) (if (ge0 (- W (cadar Lst))) (let Y (cons (car Lst) (knapsack (cdr Lst) @)) diff --git a/Task/Knapsack-problem-Bounded/PicoLisp/knapsack-problem-bounded.l b/Task/Knapsack-problem-Bounded/PicoLisp/knapsack-problem-bounded.l index 840706fd53..c82c5d276b 100644 --- a/Task/Knapsack-problem-Bounded/PicoLisp/knapsack-problem-bounded.l +++ b/Task/Knapsack-problem-Bounded/PicoLisp/knapsack-problem-bounded.l @@ -14,7 +14,7 @@ # Dynamic programming solution (de knapsack (Lst W) (when Lst - (cache '*KnapCache (pack (length Lst) ":" W) + (cache '*KnapCache (cons W Lst) (let X (knapsack (cdr Lst) W) (if (ge0 (- W (cadar Lst))) (let Y (cons (car Lst) (knapsack (cdr Lst) @)) diff --git a/Task/Knights-tour/00DESCRIPTION b/Task/Knights-tour/00DESCRIPTION index ee26b9aa6f..99dbd26420 100644 --- a/Task/Knights-tour/00DESCRIPTION +++ b/Task/Knights-tour/00DESCRIPTION @@ -1,6 +1,6 @@ [[wp:Knight%27s_tour|Problem]]: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. -Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in [http://en.wikipedia.org/wiki/Algebraic_chess_notation algebraic notation]. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered ordering to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. +Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in [http://en.wikipedia.org/wiki/Algebraic_chess_notation algebraic notation]. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square diff --git a/Task/Knights-tour/AutoHotkey/knights-tour.ahk b/Task/Knights-tour/AutoHotkey/knights-tour.ahk new file mode 100644 index 0000000000..36c4aa9c67 --- /dev/null +++ b/Task/Knights-tour/AutoHotkey/knights-tour.ahk @@ -0,0 +1,96 @@ +#SingleInstance, Force +#NoEnv +SetBatchLines, -1 +; Uncomment if Gdip.ahk is not in your standard library +;#Include, Gdip.ahk +If !pToken := Gdip_Startup(){ + MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. + ExitApp +} +; I've added a simple new function here, just to ensure if anyone is having any problems then to make sure they are using the correct library version +if (Gdip_LibraryVersion() < 1.30) +{ + MsgBox, 48, Version error!, Please download the latest version of the gdi+ library + ExitApp +} +OnExit, Exit +tour := "a1 b3 d2 c4 a5 b7 d8 e6 d4 b5 c7 a8 b6 c8 a7 c6 b8 a6 b4 d5 e3 d1 b2 a4 c5 d7 f8 h7 f6 g8 h6 f7 h8 g6 e7 f5 h4 g2 e1 d3 e5 g4 f2 h1 g3 f1 h2 f3 g1 h3 g5 e4 d6 e8 g7 h5 f4 e2 c1 a2 c3 b1 a3 c2 " +; Knight's tour with maximum symmetry by George Jelliss, http://www.mayhematics.com/t/8f.htm +; I know, I know, but I followed the task outline to the letter! Besides, this path is the prettiest. + +; Input: starting square +InputBox, start, Knight's Tour Start, Enter Knight's starting location in algebraic notation:, , , , , , , , b3 +i := InStr(tour, start) +If i=0 +{ + Msgbox Error, please try again. + Reload +} +; Output: move sequence +Msgbox % tour := SubStr(tour, i) . SubStr(tour, 1, i-1) + +; Animation +tour .= SubStr(tour, 1, 3) +, CellSize := 30 ; pixels +, Width := Height := 9*CellSize +, TopLeftX := (A_ScreenWidth - Width) // 2 +, TopLeftY := (A_ScreenHeight - Height) // 2 +Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, Show, NA ; show board (currently transparent) +hwnd1 := WinExist() ; required for Gdip +OnMessage(0x201, "WM_LBUTTONDOWN") +, hbm := CreateDIBSection(Width, Height) +, hdc := CreateCompatibleDC() +, obm := SelectObject(hdc, hbm) +, G := Gdip_GraphicsFromHDC(hdc) +, Gdip_SetSmoothingMode(G, 4) + +Loop 1 ; remove '1' and uncomment next line to loop infinitely +{ +;Gdip_GraphicsClear(G) ; uncomment to loop infinitely +cOdd := "0xFFFFCE9E" ; create brushes +, cEven := "0xFFD18B47" +, pBrushOdd := Gdip_BrushCreateSolid(cOdd) +, pBrushEven := Gdip_BrushCreateSolid(cEven) + +Loop 64 ; layout board +{ + Row := mod(A_Index-1,8)+1 + , Col := (A_Index-1)//8+1 + , Gdip_FillRectangle(G, mod(Row+Col,2) ? pBrushOdd : pBrushEven, Col * CellSize + 1, Row * CellSize + 1, CellSize - 2, CellSize - 2) +} +Gdip_DeleteBrush(pBrushOdd) ; cleanup memory +, Gdip_DeleteBrush(pBrushEven) +, UpdateLayeredWindow(hwnd1, hdc, TopLeftX, TopLeftY, Width, Height) ; update board + +, pPen := Gdip_CreatePen(0x66FF0000, CellSize/10) ; create pen +, Algebraic := SubStr(tour,1,2) ; get starting coordinates +, x := (Asc(SubStr(Algebraic, 1, 1))-96+0.5)*CellSize +, y := (9.5-SubStr(Algebraic, 2, 1))*CellSize + +Loop 64 ; trace path +{ + Sleep, 0.5*1000 + xold := x, yold := y ; a line has start and end points + , Algebraic := SubStr(tour,(A_Index)*3+1,2) ; get new coordinates + , x := (Asc(SubStr(Algebraic, 1, 1))-96+0.5)*CellSize + , y := (9.5-SubStr(Algebraic, 2, 1))*CellSize + , Gdip_DrawLine(G, pPen, xold, yold, x, y) + , UpdateLayeredWindow(hwnd1, hdc, TopLeftX, TopLeftY, Width, Height) ; update board +} +Gdip_DeletePen(pPen) +} +Return + +GuiEscape: + ExitApp + +Exit: + Gdip_Shutdown(pToken) + ExitApp + +WM_LBUTTONDOWN() +{ + If (A_Gui = 1) + PostMessage, 0xA1, 2 +} diff --git a/Task/Knights-tour/Kotlin/knights-tour.kotlin b/Task/Knights-tour/Kotlin/knights-tour.kotlin new file mode 100644 index 0000000000..a228c4793b --- /dev/null +++ b/Task/Knights-tour/Kotlin/knights-tour.kotlin @@ -0,0 +1,35 @@ +import java.util.ArrayList + +class Square(val x : Int, val y : Int) { + fun equals(s : Square) : Boolean = s.x == x && s.y == y +} + +class Pair(val a : T, val b : T) + +val board = Array(8 * 8, {Square(it / 8 + 1, it % 8 + 1)}) +val axisMoves = array(1, 2, -1, -2) + +fun allPairs(a : Array) = a flatMap {i -> a map {j -> Pair(i, j)}} + +fun knightMoves(s : Square) : List { + val moves = allPairs(axisMoves) filter {Math.abs(it.a) != Math.abs(it.b)} + fun onBoard(s : Square) = board.any {it equals s} + return moves map {Square(s.x + it.a, s.y + it.b)} filter {onBoard(it)} +} + +fun knightTour(moves : List) : List { + fun findMoves(s : Square) = knightMoves(s) filterNot {m -> moves any {it equals m}} + val newSquare = findMoves(moves.last()) minBy {findMoves(it).size} + return if (newSquare == null) moves else knightTour(moves + newSquare) +} + +fun knightTourFrom(start : Square) = knightTour(array(start).toList()) + +fun main(args : Array) { + var col = 0 + for (move in knightTourFrom(Square(1, 1))) { + System.out.print("${move.x},${move.y}") + System.out.print(if (col == 7) "\n" else " ") + col = (col + 1) % 8 + } +} diff --git a/Task/Knights-tour/Perl/knights-tour.pl b/Task/Knights-tour/Perl/knights-tour.pl index 541f892840..aa210ee9f0 100644 --- a/Task/Knights-tour/Perl/knights-tour.pl +++ b/Task/Knights-tour/Perl/knights-tour.pl @@ -19,7 +19,7 @@ my @moves = (); foreach my $move (1..64) { # Record current move push @moves, to_algebraic($i,$j); - $board[$i][$j] = $move++; + $board[$i][$j] = $move; # Get list of possible next moves my @targets = possible_moves($i,$j); diff --git a/Task/Knights-tour/R/knights-tour.r b/Task/Knights-tour/R/knights-tour.r new file mode 100644 index 0000000000..cfc1bd613e --- /dev/null +++ b/Task/Knights-tour/R/knights-tour.r @@ -0,0 +1,69 @@ +#!/usr/bin/Rscript + +# M x N Chess Board. +M = 8; N = 8; board = matrix(0, nrow = M, ncol = N) + +# Get/Set value on a board position. +getboard = function (position) { board[position[1], position[2]] } +setboard = function (position, x) { board[position[1], position[2]] <<- x } + +# (Relative) Hops of a Knight. +hops = cbind(c(-2, -1), c(-1, -2), c(+1, -2), c(+2, -1), + c(+2, +1), c(+1, +2), c(-1, +2), c(-2, +1)) + +# Validate a move. +valid = function (move) { + all(1 <= move & move <= c(M, N)) && (getboard(move) == 0) +} + +# Moves possible from a given position. +explore = function (position) { + moves = position + hops + cbind(moves[, apply(moves, 2, valid)]) +} + +# Possible moves sorted according to their Wornsdorff cost. +candidates = function (position) { + moves = explore(position) + + # No candidate moves available. + if (ncol(moves) == 0) { return(moves) } + + wcosts = apply(moves, 2, function (position) { ncol(explore(position)) }) + cbind(moves[, order(wcosts)]) +} + +# Recursive function for touring the chess board. +knightTour = function (position, moveN) { + + # Tour Complete. + if (moveN > (M * N)) { + print(board) + quit() + } + + # Available moves. + moves = candidates(position) + + # None possible. Backtrack. + if (ncol(moves) == 0) { return() } + + # Make a move, and continue the tour. + apply(moves, 2, function (position) { + setboard(position, moveN) + knightTour(position, moveN + 1) + setboard(position, 0) + }) +} + +# User Input: Starting position (in algebraic notation). +square = commandArgs(trailingOnly = TRUE) + +# Convert into board co-ordinates. +row = M + 1 - as.integer(substr(square, 2, 2)) +ascii = function (ch) { as.integer(charToRaw(ch)) } +col = 1 + ascii(substr(square, 1, 1)) - ascii('a') +position = c(row, col) + +# Begin tour. +setboard(position, 1); knightTour(position, 2) diff --git a/Task/Knuth-shuffle/D/knuth-shuffle-2.d b/Task/Knuth-shuffle/D/knuth-shuffle-2.d index 34b4ecd81c..88ae80e7cb 100644 --- a/Task/Knuth-shuffle/D/knuth-shuffle-2.d +++ b/Task/Knuth-shuffle/D/knuth-shuffle-2.d @@ -3,8 +3,8 @@ import std.stdio, std.algorithm, std.random, std.range; void knuthShuffle(Range)(Range r) if (isRandomAccessRange!Range && hasLength!Range && hasSwappableElements!Range) { - foreach_reverse (immutable i; 1 .. r.length) - r[i].swap(r[uniform(0, i + 1)]); + foreach_reverse (immutable i, ref ri; r[1 .. $ - 1]) + ri.swap(r[uniform(0, i + 1)]); } void main() { diff --git a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d index 1c911cc600..fba425f48e 100644 --- a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d +++ b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d @@ -8,7 +8,7 @@ auto sofN_creator(in int n) { i++; if (i <= n) sample ~= item; - else if (uniform(0.0, 1.0) < (cast(double)n / i)) + else if (uniform(0.0, 1.0) < (double(n) / i)) sample[uniform(0, n)] = item; return sample; }; @@ -18,12 +18,12 @@ void main() { enum nRuns = 100_000; size_t[10] bin; - foreach (trial; 0 .. nRuns) { - auto sofn = sofN_creator(3); + foreach (immutable trial; 0 .. nRuns) { + immutable sofn = sofN_creator(3); int[] sample; - foreach (item; 0 .. bin.length) + foreach (immutable item; 0 .. bin.length) sample = sofn(item); - foreach (s; sample) + foreach (immutable s; sample) bin[s]++; } writefln("Item counts for %d runs:\n%s", nRuns, bin); diff --git a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d index 1557201521..3d51ad1787 100644 --- a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d +++ b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d @@ -1,7 +1,7 @@ import std.stdio, std.random, std.algorithm; double random01(ref Xorshift rng) { - immutable r = rng.front / cast(double)rng.max; + immutable r = rng.front / double(rng.max); rng.popFront; return r; } @@ -14,7 +14,7 @@ struct SOfN(size_t n) { i++; if (i <= n) sample[i - 1] = item; - else if (rng.random01 < (cast(double)n / i)) + else if (rng.random01 < (double(n) / i)) sample[uniform(0, n, rng)] = item; return sample[0 .. min(i, $)]; } diff --git a/Task/Knuths-algorithm-S/Objective-C/knuths-algorithm-s.m b/Task/Knuths-algorithm-S/Objective-C/knuths-algorithm-s.m index 277897f238..6c7f9c5813 100644 --- a/Task/Knuths-algorithm-S/Objective-C/knuths-algorithm-s.m +++ b/Task/Knuths-algorithm-S/Objective-C/knuths-algorithm-s.m @@ -3,33 +3,32 @@ typedef NSArray *(^SOfN)(id); SOfN s_of_n_creator(int n) { - NSMutableArray *sample = [NSMutableArray arrayWithCapacity:n]; + NSMutableArray *sample = [[NSMutableArray alloc] initWithCapacity:n]; __block int i = 0; - return [[^(id item) { + return [^(id item) { i++; if (i <= n) { [sample addObject:item]; } else if (rand() % i < n) { - [sample replaceObjectAtIndex:rand() % n withObject:item]; + sample[rand() % n] = item; } return sample; - } copy] autorelease]; + } copy]; } int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { + + NSCountedSet *bin = [[NSCountedSet alloc] init]; + for (int trial = 0; trial < 100000; trial++) { + SOfN s_of_n = s_of_n_creator(3); + NSArray *sample; + for (int i = 0; i < 10; i++) + sample = s_of_n(@(i)); + [bin addObjectsFromArray:sample]; + } + NSLog(@"%@", bin); - NSCountedSet *bin = [[NSCountedSet alloc] init]; - for (int trial = 0; trial < 100000; trial++) { - SOfN s_of_n = s_of_n_creator(3); - NSArray *sample; - for (int i = 0; i < 10; i++) - sample = s_of_n([NSNumber numberWithInt:i]); - [bin addObjectsFromArray:sample]; } - NSLog(@"%@", bin); - [bin release]; - - [pool release]; return 0; } diff --git a/Task/Knuths-algorithm-S/Racket/knuths-algorithm-s.rkt b/Task/Knuths-algorithm-S/Racket/knuths-algorithm-s.rkt index b1051560b5..e43bb3627a 100644 --- a/Task/Knuths-algorithm-S/Racket/knuths-algorithm-s.rkt +++ b/Task/Knuths-algorithm-S/Racket/knuths-algorithm-s.rkt @@ -1,29 +1,29 @@ -#lang racket +#lang racket/base (define (s-of-n-creator n) - (let* ([count 0] ; 'i' in the description + (let ([count 0] ; 'i' in the description [vec (make-vector n)]) ; store the elts we've seen so far (lambda (item) (if (< count n) ; we're not full, so, kind of boring (begin (vector-set! vec count item) - (set! count (+ count 1)) - (vector-copy vec 0 count)) + (set! count (+ count 1))) ; we've already seen n elts; fun starts (begin (set! count (+ count 1)) - (when (< (random) (/ n count)) - (vector-set! vec (random n) item)) - (vector-copy vec)))))) + (when (< (random count) n) + (vector-set! vec (random n) item)))) + vec))) + +(define counts (make-vector 10)) -(define counts (make-hash '((0 . 0) (1 . 0) (2 . 0) (3 . 0) (4 . 0) (5 . 0) (6 . 0) (7 . 0) (8 . 0) (9 . 0)))) (for ([iter (in-range 0 100000)]) ; trials (let ([s-of-n (s-of-n-creator 3)]) ; set up the chooser (for ([d (in-vector ; iterate over the chosen digits (for/last ([digit (in-range 0 10)]) ; loop through the digits (s-of-n digit)))]) ; feed them in - (hash-update! counts d add1)))) ; update counts + (vector-set! counts d (add1 (vector-ref counts d)))))) ; update counts (for ([d (in-range 0 10)]) - (printf "~a ~a~n" d (hash-ref counts d))) + (printf "~a ~a~n" d (vector-ref counts d))) diff --git a/Task/LU-decomposition/Maple/lu-decomposition-1.maple b/Task/LU-decomposition/Maple/lu-decomposition-1.maple new file mode 100644 index 0000000000..c07891824b --- /dev/null +++ b/Task/LU-decomposition/Maple/lu-decomposition-1.maple @@ -0,0 +1,3 @@ +A:=<<1.0|3.0|5.0>,<2.0|4.0|7.0>,<1.0|1.0|0.0>>: + +LinearAlgebra:-LUDecomposition(A); diff --git a/Task/LU-decomposition/Maple/lu-decomposition-2.maple b/Task/LU-decomposition/Maple/lu-decomposition-2.maple new file mode 100644 index 0000000000..7154bc4021 --- /dev/null +++ b/Task/LU-decomposition/Maple/lu-decomposition-2.maple @@ -0,0 +1,6 @@ +A:=<<11.0|9.0|24.0|2.0>,<1.0|5.0|2.0|6.0>, + <3.0|17.0|18.0|1.0>,<2.0|5.0|7.0|1.0>>: + +with(LinearAlgebra): + +LUDecomposition(A); diff --git a/Task/LZW-compression/D/lzw-compression-1.d b/Task/LZW-compression/D/lzw-compression-1.d index 0d86c0126e..485f624d1b 100644 --- a/Task/LZW-compression/D/lzw-compression-1.d +++ b/Task/LZW-compression/D/lzw-compression-1.d @@ -1,31 +1,31 @@ import std.stdio, std.array; -auto compress(string original) { +auto compress(in string original) pure nothrow { int[string] dict; - foreach (b; 0 .. 256) - dict[[cast(immutable char)b]] = b; + foreach (immutable char c; char.min .. char.max + 1) + dict[[c]] = c; string w; int[] result; - foreach (ch; original) + foreach (immutable ch; original) if (w ~ ch in dict) w = w ~ ch; else { result ~= dict[w]; - dict[w ~ ch] = dict.length - 1; + dict[w ~ ch] = dict.length; w = [ch]; } return w.empty ? result : (result ~ dict[w]); } -auto decompress(int[] compressed) { - auto dict = new string[256]; - foreach (b; 0 .. 256) - dict[b] = [cast(char)b]; +auto decompress(in int[] compressed) pure nothrow { + auto dict = new string[char.max - char.min + 1]; + foreach (immutable char c; char.min .. char.max + 1) + dict[c] = [c]; auto w = dict[compressed[0]]; auto result = w; - foreach (k; compressed[1 .. $]) { + foreach (immutable k; compressed[1 .. $]) { auto entry = (k < dict.length) ? dict[k] : w ~ w[0]; result ~= entry; dict ~= w ~ entry[0]; @@ -35,6 +35,6 @@ auto decompress(int[] compressed) { } void main() { - auto comp = compress("TOBEORNOTTOBEORTOBEORNOT"); - writeln(comp, "\n", decompress(comp)); + auto comp = "TOBEORNOTTOBEORTOBEORNOT".compress; + writeln(comp, "\n", comp.decompress); } diff --git a/Task/LZW-compression/D/lzw-compression-2.d b/Task/LZW-compression/D/lzw-compression-2.d index 6529c7801a..150baa9485 100644 --- a/Task/LZW-compression/D/lzw-compression-2.d +++ b/Task/LZW-compression/D/lzw-compression-2.d @@ -10,8 +10,8 @@ struct LZW { enum int initDictSize = 256; static immutable ubyte[initDictSize] bytes; static this() { - foreach (immutable i; 0 .. initDictSize) - bytes[i] = cast(T)i; //* + foreach (immutable T i; 0 .. initDictSize) + bytes[i] = i; } static Tcomp[] compress(immutable scope T[] original) pure nothrow diff --git a/Task/LZW-compression/Groovy/lzw-compression-1.groovy b/Task/LZW-compression/Groovy/lzw-compression-1.groovy new file mode 100644 index 0000000000..e3c30788e3 --- /dev/null +++ b/Task/LZW-compression/Groovy/lzw-compression-1.groovy @@ -0,0 +1,33 @@ +def compress = { text -> + def dictionary = (1..255).inject([:]) { map, ch -> map."${(char)ch}" = ch; map } + def w = '', compressed = [] + text.each { ch -> + def wc = "$w$ch" + if (dictionary[wc]) { + w = wc + } else { + compressed << dictionary[w] + dictionary[wc] = dictionary.size() + 1 + w = "$ch" + } + } + if (w) { compressed << dictionary[w] } + compressed +} + +def decompress = { compressed -> + def dictionary = (1..255).inject([:]) { map, ch -> map[ch] = "${(char)ch}"; map } + String w = "${(char)compressed.remove(0)}" + StringBuffer result = new StringBuffer(w) + compressed.each { k -> + String entry = dictionary[k] + if (!entry) { + if (k != dictionary.size()) throw new IllegalArgumentException("Bad compressed k $k") + entry = "$w${w[0]}" + } + result << entry + dictionary[dictionary.size() + 1] = "$w${entry[0]}" + w = entry + } + result.toString() +} diff --git a/Task/LZW-compression/Groovy/lzw-compression-2.groovy b/Task/LZW-compression/Groovy/lzw-compression-2.groovy new file mode 100644 index 0000000000..89d0b10c21 --- /dev/null +++ b/Task/LZW-compression/Groovy/lzw-compression-2.groovy @@ -0,0 +1,8 @@ +def plaintext = 'TOBEORNOTTOBEORTOBEORNOT' +def compressed = compress(plaintext) +def result = decompress(compressed) + +println """\ + Plaintext: '$plaintext' + Compressed: $compressed + Uncompressed: '$result'""".stripIndent() diff --git a/Task/LZW-compression/Objective-C/lzw-compression-1.m b/Task/LZW-compression/Objective-C/lzw-compression-1.m index d0e2d56f8f..3ded72de61 100644 --- a/Task/LZW-compression/Objective-C/lzw-compression-1.m +++ b/Task/LZW-compression/Objective-C/lzw-compression-1.m @@ -9,8 +9,8 @@ NSUInteger codemark; } --(LZWCompressor *) init; --(LZWCompressor *) initWithArray: (NSMutableArray *) stream; +-(instancetype) init; +-(instancetype) initWithArray: (NSMutableArray *) stream; -(BOOL) compressData: (NSData *) string; -(void) setArray: (NSMutableArray *) stream; -(NSArray *) getArray; @@ -18,7 +18,7 @@ @implementation LZWCompressor : NSObject --(LZWCompressor *) init +-(instancetype) init { self = [super init]; if ( self ) @@ -30,7 +30,7 @@ return self; } --(LZWCompressor *) initWithArray: (NSMutableArray *) stream +-(instancetype) initWithArray: (NSMutableArray *) stream { self = [self init]; if ( self ) @@ -40,51 +40,40 @@ return self; } --(void) dealloc -{ - [dict release]; - [iostream release]; - [super dealloc]; -} - -(void) setArray: (NSMutableArray *) stream { - iostream = [stream retain]; + iostream = stream; } -(BOOL) compressData: (NSData *) string; { - NSUInteger i; - unsigned char j; - // prepare dict - for(i=0; i < 256; i++) + for(NSUInteger i=0; i < 256; i++) { - j = i; + unsigned char j = i; NSData *s = [NSData dataWithBytes: &j length: 1]; - [dict setObject: [NSNumber numberWithUnsignedInt: i] forKey: s]; + dict[s] = @(i); } - NSMutableData *w = [NSMutableData data]; - NSMutableData *wc = [NSMutableData data]; + NSData *w = [NSData data]; - for(i=0; i < [string length]; i++) + for(NSUInteger i=0; i < [string length]; i++) { - [wc setData: w]; + NSMutableData *wc = [NSMutableData dataWithData: w]; [wc appendData: [string subdataWithRange: NSMakeRange(i, 1)]]; - if ( [dict objectForKey: wc] != nil ) + if ( dict[wc] != nil ) { - [w setData: wc]; + w = wc; } else { - [iostream addObject: [dict objectForKey: w]]; - [dict setObject: [NSNumber numberWithUnsignedInt: codemark] forKey: wc]; + [iostream addObject: dict[w]]; + dict[wc] = @(codemark); codemark++; - [w setData: [string subdataWithRange: NSMakeRange(i, 1)]]; + w = [string subdataWithRange: NSMakeRange(i, 1)]; } } if ( [w length] != 0 ) { - [iostream addObject: [dict objectForKey: w]]; + [iostream addObject: dict[w]]; } return YES; } diff --git a/Task/LZW-compression/Objective-C/lzw-compression-2.m b/Task/LZW-compression/Objective-C/lzw-compression-2.m index 3021ba1408..311b2c395e 100644 --- a/Task/LZW-compression/Objective-C/lzw-compression-2.m +++ b/Task/LZW-compression/Objective-C/lzw-compression-2.m @@ -1,26 +1,21 @@ -const char *text = "TOBEORNOTTOBEORTOBEORNOT"; +NSString *text = @"TOBEORNOTTOBEORTOBEORNOT"; int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { + + NSMutableArray *array = [[NSMutableArray alloc] init]; + LZWCompressor *lzw = [[LZWCompressor alloc] + initWithArray: array ]; + if ( lzw ) + { + [lzw compressData: [text dataUsingEncoding: NSUTF8StringEncoding]]; + for ( id obj in array ) + { + printf("%u\n", [obj unsignedIntValue]); + } + } - NSMutableArray *array = [[NSMutableArray alloc] init]; - LZWCompressor *lzw = [[LZWCompressor alloc] - initWithArray: array ]; - if ( lzw ) - { - [lzw compressData: [NSData dataWithBytes: text - length: strlen(text)]]; - NSEnumerator *en = [array objectEnumerator]; - id obj; - while( (obj = [en nextObject]) ) - { - printf("%u\n", [obj unsignedIntValue]); - } - [lzw release]; } - [array release]; - - [pool release]; return EXIT_SUCCESS; } diff --git a/Task/LZW-compression/PHP/lzw-compression.php b/Task/LZW-compression/PHP/lzw-compression.php new file mode 100644 index 0000000000..78abea989d --- /dev/null +++ b/Task/LZW-compression/PHP/lzw-compression.php @@ -0,0 +1,64 @@ +class LZW +{ + function compress($unc) { + $i;$c;$wc; + $w = ""; + $dictionary = array(); + $result = array(); + $dictSize = 256; + for ($i = 0; $i < 256; $i += 1) { + $dictionary[chr($i)] = $i; + } + for ($i = 0; $i < strlen($unc); $i++) { + $c = $unc[$i]; + if (property_exists($dictionary, $w.$c)) { + $w = $w.$c; + } else { + array_push($result,$dictionary[$w]); + $dictionary[$wc] = $dictSize++; + $w = (string)$c; + } + } + if ($w !== "") { + array_push($result,$dictionary[$w]); + } + array_shift($result); + return implode(",",$result); + } + + function decompress($com) { + $com = explode(",",$com); + $i;$w;$k;$result; + $dictionary = array(); + $entry = ""; + $dictSize = 256; + for ($i = 0; $i < 256; $i++) { + $dictionary[$i] = chr($i); + } + $w = chr($com[0]); + $result = $w; + for ($i = 1; $i < count($com);$i++) { + $k = $com[$i]; + if ($dictionary[$k]) { + $entry = $dictionary[$k]; + } else { + if ($k === $dictSize) { + $entry = $w.$w[0]; + } else { + return null; + } + } + $result .= $entry; + $dictionary[$dictSize++] = $w + $entry[0]; + $w = $entry; + } + return $result; + } +} + +//How to use +$str = 'TOBEORNOTTOBEORTOBEORNOT'; +$lzw = new LZW(); +$com = $lzw->compress($str); +$dec = $lzw->decompress($com); +echo $com . "
" . $dec; diff --git a/Task/Langtons-ant/TI-83-BASIC/langtons-ant.ti-83 b/Task/Langtons-ant/TI-83-BASIC/langtons-ant.ti-83 index 9852dd6710..b85d738e72 100644 --- a/Task/Langtons-ant/TI-83-BASIC/langtons-ant.ti-83 +++ b/Task/Langtons-ant/TI-83-BASIC/langtons-ant.ti-83 @@ -1,19 +1,18 @@ PROGRAM:LANT :ClrDraw :0→N -:Pxl-On(0,0) -:47→X -:31→Y +:47→A +:31→B :90→Θ :Repeat getKey -:If pxl-Test(Y,X) +:If pxl-Test(B,A) :Then :Θ+90→Θ :Else :Θ-90→Θ :End -:Pxl-Change(Y,X) -:X+cos(Θ°)→X -:Y+sin(Θ°)→Y +:Pxl-Change(B,A) +:A+cos(Θ°)→A +:B+sin(Θ°)→B :N+1→N :End diff --git a/Task/Largest-int-from-concatenated-ints/AutoHotkey/largest-int-from-concatenated-ints-1.ahk b/Task/Largest-int-from-concatenated-ints/AutoHotkey/largest-int-from-concatenated-ints-1.ahk new file mode 100644 index 0000000000..f0484557c0 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/AutoHotkey/largest-int-from-concatenated-ints-1.ahk @@ -0,0 +1,11 @@ +LargestConcatenatedInts(var){ + StringReplace, var, A_LoopField,%A_Space%,, all + Sort, var, D`, fConcSort + StringReplace, var, var, `,,, all + return var +} + +ConcSort(a, b){ + m := a . b , n := b . a + return m < n ? 1 : m > n ? -1 : 0 +} diff --git a/Task/Largest-int-from-concatenated-ints/AutoHotkey/largest-int-from-concatenated-ints-2.ahk b/Task/Largest-int-from-concatenated-ints/AutoHotkey/largest-int-from-concatenated-ints-2.ahk new file mode 100644 index 0000000000..cae7f3446a --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/AutoHotkey/largest-int-from-concatenated-ints-2.ahk @@ -0,0 +1,8 @@ +d = +( +1, 34, 3, 98, 9, 76, 45, 4 +54, 546, 548, 60 +4 , 45, 54, 5 +) +loop, parse, d, `n + MsgBox % LargestConcatenatedInts(A_LoopField) diff --git a/Task/Largest-int-from-concatenated-ints/C/largest-int-from-concatenated-ints.c b/Task/Largest-int-from-concatenated-ints/C/largest-int-from-concatenated-ints.c index 0b289be085..56e5523616 100644 --- a/Task/Largest-int-from-concatenated-ints/C/largest-int-from-concatenated-ints.c +++ b/Task/Largest-int-from-concatenated-ints/C/largest-int-from-concatenated-ints.c @@ -5,8 +5,8 @@ int catcmp(const void *a, const void *b) { char ab[32], ba[32]; - sprintf(ab, "%d%d", *(const int*)a, *(const int*)b); - sprintf(ba, "%d%d", *(const int*)b, *(const int*)a); + sprintf(ab, "%d%d", *(int*)a, *(int*)b); + sprintf(ba, "%d%d", *(int*)b, *(int*)a); return strcmp(ba, ab); } diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d index 2265d9949b..638de2daa2 100644 --- a/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d @@ -22,7 +22,7 @@ petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle -whismur wingull yamask".split(); +whismur wingull yamask".split; string[] solution; foreach (ref name; pokemon) { diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d index fc1efe65bf..6250aa563a 100644 --- a/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d @@ -1,61 +1,32 @@ -import std.stdio, std.algorithm, std.string, std.range, std.typecons; +import std.stdio, std.algorithm, std.string, std.array, std.conv; -Tuple!(uint, string[]) findLongestChain(in string[] words) -pure /*nothrow*/ { - static struct Pair { string word; bool unused; } - uint nSolutions; - - void search(Pair[][] sequences, in size_t minHead, - in string currWord, string[] currentPath, - size_t currentPathLen, - ref string[] longestPath) /*nothrow*/ { - currentPath[currentPathLen] = currWord; - currentPathLen++; - - if (currentPathLen == longestPath.length) { - nSolutions++; - } else if (currentPathLen > longestPath.length) { - nSolutions = 1; - longestPath = currentPath[0 .. currentPathLen].dup;//Throw. +void search(immutable(char)*[] items, in int len, + ref immutable(char)*[] longest) pure { + if (len > longest.length) + longest = items[0 .. len].dup; + immutable lastChar = items[len - 1][1]; + foreach (ref item; items[len .. $]) + if (item[0] == lastChar) { + swap(items[len], item); + search(items, len + 1, longest); + swap(items[len], item); } - - // Recursive search. - immutable size_t lastCharIndex = currWord[$ - 1] - minHead; - if (lastCharIndex < sequences.length) - foreach (ref pair; sequences[lastCharIndex]) - if (pair.unused) { - pair.unused = false; - search(sequences, minHead, pair.word, currentPath, - currentPathLen, longestPath); - pair.unused = true; - } - } - - auto heads = words.map!q{ a[0] }; - //immutable {minHead, maxHead} = heads.reduce!(min, max); - immutable minHead = heads.reduce!min; - immutable maxHead = heads.reduce!max; - auto sequences = new Pair[][](maxHead - minHead + 1, 0); - foreach (word; words) - sequences[word[0] - minHead] ~= Pair(word, true); - - auto currentPath = new string[words.length]; - string[] longestPath; - - // Try each item as possible start. - foreach (seq; sequences) - foreach (ref pair; seq) { - pair.unused = false; - search(sequences, minHead, pair.word, - currentPath, 0, longestPath); - pair.unused = true; - } - - return typeof(return)(nSolutions, longestPath); } - void main() { + static immutable(char)* prep(in string s) pure { + assert(s.length > 1); + auto sd = s.dup; + swap(sd[1], sd[$ - 1]); + return sd.toStringz; + } + + static string unprep(immutable(char)* sd) pure { + auto ms = sd.to!(char[]); + swap(ms[1], ms[$ - 1]); + return ms; + } + auto pokemon = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor @@ -65,14 +36,14 @@ petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle -whismur wingull yamask".toLower.split; +whismur wingull yamask".split.map!prep.array; - // Remove duplicates. - pokemon.length -= pokemon.sort().uniq.copy(pokemon).length; + immutable(char)*[] solution; + foreach (ref name; pokemon) { + swap(pokemon[0], name); + search(pokemon, 1, solution); + swap(pokemon[0], name); + } - const sol = pokemon.findLongestChain; - writeln("Maximum path length: ", sol[1].length); - writeln("Paths of that length: ", sol[0]); - writeln("Example path of that length:"); - writefln("%( %-(%s %)\n%)", sol[1].chunks(7)); + writefln("%-(%s\n%)", solution.map!unprep); } diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-3.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-3.d new file mode 100644 index 0000000000..ad4fd470d9 --- /dev/null +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-3.d @@ -0,0 +1,24 @@ +LBB0_4: + movl (%esi), %eax + movb 19(%esp), %cl + cmpb %cl, (%eax) +jne LBB0_6 + movl (%edi,%ebx,4), %ecx + movl %eax, (%edi,%ebx,4) + movl %ecx, (%esi) + movl %edi, 8(%esp) + movl 48(%esp), %eax + movl %eax, 4(%esp) + movl 12(%esp), %eax + movl %eax, (%esp) + movl 20(%esp), %eax + calll __D25last_letter_first_letter26searchFNaAPyaxiKAPyaZv + subl $12, %esp + movl (%edi,%ebx,4), %eax + movl (%esi), %ecx + movl %ecx, (%edi,%ebx,4) + movl %eax, (%esi) +LBB0_6: + addl $4, %esi + decl %ebp + jne LBB0_4 diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d new file mode 100644 index 0000000000..a497f6ba3f --- /dev/null +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d @@ -0,0 +1,77 @@ +import std.stdio, std.algorithm, std.string, std.range, std.typecons; + +Tuple!(uint, string[]) findLongestChain(in string[] words) +pure /*nothrow*/ { + static struct Pair { string word; bool unused; } + uint nSolutions; + + void search(Pair[][] sequences, in size_t minHead, + in string currWord, string[] currentPath, + size_t currentPathLen, + ref string[] longestPath) /*nothrow*/ { + currentPath[currentPathLen] = currWord; + currentPathLen++; + + if (currentPathLen == longestPath.length) { + nSolutions++; + } else if (currentPathLen > longestPath.length) { + nSolutions = 1; + longestPath = currentPath[0 .. currentPathLen].dup;//Throw. + } + + // Recursive search. + immutable size_t lastCharIndex = currWord[$ - 1] - minHead; + if (lastCharIndex < sequences.length) + foreach (ref pair; sequences[lastCharIndex]) + if (pair.unused) { + pair.unused = false; + search(sequences, minHead, pair.word, currentPath, + currentPathLen, longestPath); + pair.unused = true; + } + } + + auto heads = words.map!q{ a[0] }; + //immutable {minHead, maxHead} = heads.reduce!(min, max); + immutable minHead = heads.reduce!min; + immutable maxHead = heads.reduce!max; + auto sequences = new Pair[][](maxHead - minHead + 1, 0); + foreach (word; words) + sequences[word[0] - minHead] ~= Pair(word, true); + + auto currentPath = new string[words.length]; + string[] longestPath; + + // Try each item as possible start. + foreach (seq; sequences) + foreach (ref pair; seq) { + pair.unused = false; + search(sequences, minHead, pair.word, + currentPath, 0, longestPath); + pair.unused = true; + } + + return typeof(return)(nSolutions, longestPath); +} + +void main() { + auto pokemon = "audino bagon baltoy banette bidoof braviary +bronzor carracosta charmeleon cresselia croagunk darmanitan deino +emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor +heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus +ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass +petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 +porygonz registeel relicanth remoraid rufflet sableye scolipede +scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly +tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle +whismur wingull yamask".toLower.split; + + // Remove duplicates. + pokemon.length -= pokemon.sort().uniq.copy(pokemon).length; + + const sol = pokemon.findLongestChain; + writeln("Maximum path length: ", sol[1].length); + writeln("Paths of that length: ", sol[0]); + writeln("Example path of that length:"); + writefln("%( %-(%s %)\n%)", sol[1].chunks(7)); +} diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d new file mode 100644 index 0000000000..39a48f1ba0 --- /dev/null +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d @@ -0,0 +1,40 @@ +import std.stdio, std.algorithm, std.array, std.typecons, + std.container, std.range; + +string[] findChain(in string[] seq) /*pure nothrow*/ { + const adj = seq + .map!(item => tuple(item, + seq + .filter!(x => x[0] == item[$-1]) + .array)) + .assocArray; + string[] res; + + foreach (immutable item; adj.byKey) { // Not nothrow. + void inner(in string item, SList!string lst) nothrow { + lst.insertFront(item); + if (lst[].walkLength > res.length) + res = lst.array; + foreach (immutable x; adj[item]) + if (!lst[].canFind(x)) + inner(x, lst); + } + inner(item, SList!string()); + } + + res.reverse(); + return res; +} + +void main() { + "audino bagon baltoy banette bidoof braviary + bronzor carracosta charmeleon cresselia croagunk darmanitan deino + emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor + heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus + ledyba loudred lumineon lunatone machamp magnezone mamoswine + nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena + porygon2 porygonz registeel relicanth remoraid rufflet sableye + scolipede scrafty seaking sealeo silcoon simisear snivy snorlax + spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix + wailord wartortle whismur wingull yamask".split.findChain.writeln; +} diff --git a/Task/Last-letter-first-letter/Icon/last-letter-first-letter.icon b/Task/Last-letter-first-letter/Icon/last-letter-first-letter.icon new file mode 100644 index 0000000000..00cc9b3b4d --- /dev/null +++ b/Task/Last-letter-first-letter/Icon/last-letter-first-letter.icon @@ -0,0 +1,24 @@ +global words + +procedure main() + words := table() + every word := genwords(&input) do { + /words[word[1]] := [] + put(words[word[1]], word) + } + bP := [] + every p := getPath(!!words,[]) do if *\p > *bP then bP := copy(p) + write("Longest: ",*bP) + every writes((!bP||" ")|"\n") +end + +procedure getPath(word, p) + if word == !p then return p + if /words[word[-1]] then suspend p <- p ||| [word] + else suspend getPath(!words[word[-1]], p <- p ||| [word]) +end + +procedure genwords(f) + while l := !f do + l ? while tab(upto(&letters)) do suspend tab(many(&letters))\1 +end diff --git a/Task/Leap-year/AutoHotkey/leap-year-1.ahk b/Task/Leap-year/AutoHotkey/leap-year-1.ahk new file mode 100644 index 0000000000..2b2e242941 --- /dev/null +++ b/Task/Leap-year/AutoHotkey/leap-year-1.ahk @@ -0,0 +1,8 @@ +leapyear(year) +{ + if (Mod(year, 100) = 0) + return (Mod(year, 400) = 0) + return (Mod(year, 4) = 0) +} + +MsgBox, % leapyear(1604) diff --git a/Task/Leap-year/AutoHotkey/leap-year-2.ahk b/Task/Leap-year/AutoHotkey/leap-year-2.ahk new file mode 100644 index 0000000000..52d9031a38 --- /dev/null +++ b/Task/Leap-year/AutoHotkey/leap-year-2.ahk @@ -0,0 +1,6 @@ +IsLeapYear(Year) +{ + return !Mod(Year, 4) && Mod(Year, 100) || !Mod(Year, 400) +} + +MsgBox % "The year 1604 was " (IsLeapYear(1604) ? "" : "not ") "a leap year" diff --git a/Task/Leap-year/AutoHotkey/leap-year.ahk b/Task/Leap-year/AutoHotkey/leap-year.ahk deleted file mode 100644 index b8819e1f51..0000000000 --- a/Task/Leap-year/AutoHotkey/leap-year.ahk +++ /dev/null @@ -1,6 +0,0 @@ -MsgBox % "The year 1600 was " . (IsLeapYear(1600) ? "" : "not ") . "a leap year" - -IsLeapYear(Year) -{ - Return, !Mod(Year, 100) && !Mod(Year, 400) && !Mod(Year, 4) -} diff --git a/Task/Leap-year/Julia/leap-year.julia b/Task/Leap-year/Julia/leap-year.julia new file mode 100644 index 0000000000..7c8e9ee071 --- /dev/null +++ b/Task/Leap-year/Julia/leap-year.julia @@ -0,0 +1,5 @@ +leap(y) = y%4==0 && (y<1582 || y%400==0 || y%100!=0) + +# some tests +@assert all([leap(yr) for yr in [2400, 2012, 2000, 1600, 1500, 1400]]) +@assert all([~leap(yr) for yr in [2100, 2014, 1900, 1800, 1700, 1499]]) diff --git a/Task/Leap-year/Mercury/leap-year-1.mercury b/Task/Leap-year/Mercury/leap-year-1.mercury new file mode 100644 index 0000000000..5592527a49 --- /dev/null +++ b/Task/Leap-year/Mercury/leap-year-1.mercury @@ -0,0 +1,4 @@ +:- pred is_leap_year(int::in) is semidet. + +is_leap_year(Year) :- + ( if Year mod 100 = 0 then Year mod 400 = 0 else Year mod 4 = 0 ). diff --git a/Task/Leap-year/Mercury/leap-year-2.mercury b/Task/Leap-year/Mercury/leap-year-2.mercury new file mode 100644 index 0000000000..8428486661 --- /dev/null +++ b/Task/Leap-year/Mercury/leap-year-2.mercury @@ -0,0 +1,18 @@ +:- module leap_year. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module int, list, string. + +main(!IO) :- + Years = [1600, 1700, 1899, 1900, 2000, 2006, 2012], + io.write_list(Years, "", write_year_kind, !IO). + +:- pred write_year_kind(int::in, io::di, io::uo) is det. + +write_year_kind(Year, !IO) :- + io.format("%d %s a leap year.\n", + [i(Year), s(if is_leap_year(Year) then "is" else "is not" )], !IO). diff --git a/Task/Leap-year/Perl/leap-year-1.pl b/Task/Leap-year/Perl/leap-year-1.pl index ab4f508f76..868a43dc3c 100644 --- a/Task/Leap-year/Perl/leap-year-1.pl +++ b/Task/Leap-year/Perl/leap-year-1.pl @@ -1,7 +1,7 @@ -sub leap { - my $yr = $_[0]; - if ($yr % 100 == 0) { - return ($yr % 400 == 0); +sub isleap { + my $year = shift; + if ($year % 100 == 0) { + return ($year % 400 == 0); } - return ($yr % 4 == 0); + return ($year % 4 == 0); } diff --git a/Task/Leap-year/Perl/leap-year-2.pl b/Task/Leap-year/Perl/leap-year-2.pl index f88ea4b2bc..3e9f0b0a45 100644 --- a/Task/Leap-year/Perl/leap-year-2.pl +++ b/Task/Leap-year/Perl/leap-year-2.pl @@ -1 +1 @@ -sub leap {!($_[0] % 100) ? !($_[0] % 400) : !($_[0] % 4)} +sub isleap { !($_[0] % 100) ? !($_[0] % 400) : !($_[0] % 4) } diff --git a/Task/Leap-year/Perl/leap-year-3.pl b/Task/Leap-year/Perl/leap-year-3.pl index fb37db7f74..330e421e4c 100644 --- a/Task/Leap-year/Perl/leap-year-3.pl +++ b/Task/Leap-year/Perl/leap-year-3.pl @@ -1,6 +1,10 @@ use Date::Manip; -Date_LeapYear($year); +print Date_LeapYear(2000); use Date::Manip::Base; my $dmb = new Date::Manip::Base; -$dmb->leapyear($year); +print $dmb->leapyear(2000); + +use DateTime; +my $date = DateTime->new(year => 2000); +print $date->is_leap_year(); diff --git a/Task/Least-common-multiple/Python/least-common-multiple-2.py b/Task/Least-common-multiple/Python/least-common-multiple-2.py index cf1e96a9f5..019c6f772a 100644 --- a/Task/Least-common-multiple/Python/least-common-multiple-2.py +++ b/Task/Least-common-multiple/Python/least-common-multiple-2.py @@ -1,7 +1,11 @@ -import operator from prime_decomposition import decompose +try: + reduce +except NameError: + from functools import reduce def lcm(a, b): + mul = int.__mul__ if a and b: da = list(decompose(abs(a))) db = list(decompose(abs(b))) @@ -9,7 +13,7 @@ def lcm(a, b): for d in da: if d in db: db.remove(d) merge += db - return reduce(operator.mul, merge, 1) + return reduce(mul, merge, 1) return 0 if __name__ == '__main__': diff --git a/Task/Letter-frequency/Objective-C/letter-frequency.m b/Task/Letter-frequency/Objective-C/letter-frequency.m index 55cb276c5f..09a36d4ee0 100644 --- a/Task/Letter-frequency/Objective-C/letter-frequency.m +++ b/Task/Letter-frequency/Objective-C/letter-frequency.m @@ -1,23 +1,21 @@ #import int main (int argc, const char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSData *data = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:argv[1]]]; - NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - NSCountedSet *countedSet = [[NSCountedSet alloc] init]; - NSUInteger len = [string length]; - for (NSUInteger i = 0; i < len; i++) { - unichar c = [string characterAtIndex:i]; - if ([[NSCharacterSet letterCharacterSet] characterIsMember:c]) - [countedSet addObject:[NSNumber numberWithInteger:c]]; - } - [string release]; - for (NSNumber *chr in countedSet) { - NSLog(@"%C => %lu", (unichar)[chr integerValue], [countedSet countForObject:chr]); - } - [countedSet release]; + NSData *data = [NSData dataWithContentsOfFile:@(argv[1])]; + NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + NSCountedSet *countedSet = [[NSCountedSet alloc] init]; + NSUInteger len = [string length]; + for (NSUInteger i = 0; i < len; i++) { + unichar c = [string characterAtIndex:i]; + if ([[NSCharacterSet letterCharacterSet] characterIsMember:c]) + [countedSet addObject:@(c)]; + } + for (NSNumber *chr in countedSet) { + NSLog(@"%C => %lu", (unichar)[chr integerValue], [countedSet countForObject:chr]); + } - [pool release]; + } return 0; } diff --git a/Task/Letter-frequency/TXR/letter-frequency-2.txr b/Task/Letter-frequency/TXR/letter-frequency-2.txr index 20f2e0d1fc..68f008558d 100644 --- a/Task/Letter-frequency/TXR/letter-frequency-2.txr +++ b/Task/Letter-frequency/TXR/letter-frequency-2.txr @@ -1,10 +1,9 @@ -@(do (defun lazy-char-stream (s) - (let (ch) (gen (set ch (get-char s)) ch))) - - (let ((h (make-hash nil nil t)) +@(do (let ((h (hash)) (s (open-file "/usr/share/dict/words" "r"))) - (each ((ch (lazy-char-stream s))) - (if (chr-isalpha ch) - (inc [h (chr-toupper ch) 0]))) - (dohash (key value h) - (format t "~a: ~a\n" key value)))) + (each ((ch (gun (get-char s)))) + (if (chr-isalpha ch) + (inc [h (chr-toupper ch) 0]))) + (let ((sorted [sort (hash-pairs h) > second])) + (each ((pair sorted)) + (tree-bind (key value) pair + (put-line `@key: @value`)))))) diff --git a/Task/Levenshtein-distance/Java/levenshtein-distance-1.java b/Task/Levenshtein-distance/Java/levenshtein-distance-1.java index b8172578f5..e81e703f51 100644 --- a/Task/Levenshtein-distance/Java/levenshtein-distance-1.java +++ b/Task/Levenshtein-distance/Java/levenshtein-distance-1.java @@ -1,40 +1,28 @@ -public class LevenshteinDistance { +public class Levenshtein { - public static int computeDistance(String s1, String s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - - int[] costs = new int[s2.length() + 1]; - for (int i = 0; i <= s1.length(); i++) { - int lastValue = i; - for (int j = 0; j <= s2.length(); j++) { - if (i == 0) - costs[j] = j; - else { - if (j > 0) { - int newValue = costs[j - 1]; - if (s1.charAt(i - 1) != s2.charAt(j - 1)) - newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; - costs[j - 1] = lastValue; - lastValue = newValue; - } + public static int distance(String a, String b) { + a = a.toLowerCase(); + b = b.toLowerCase(); + // i == 0 + int [] costs = new int [b.length() + 1]; + for (int j = 0; j < costs.length; j++) + costs[j] = j; + for (int i = 1; i <= a.length(); i++) { + // j == 0; nw = lev(i - 1, j) + costs[0] = i; + int nw = i - 1; + for (int j = 1; j <= b.length(); j++) { + int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1); + nw = costs[j]; + costs[j] = cj; + } } - } - if (i > 0) - costs[s2.length()] = lastValue; + return costs[b.length()]; } - return costs[s2.length()]; - } - public static void printDistance(String s1, String s2) { - System.out.println(s1 + "-->" + s2 + ": " + computeDistance(s1, s2)); - } - - public static void main(String[] args) { - printDistance("kitten", "sitting"); - printDistance("rosettacode", "raisethysword"); - printDistance(new StringBuilder("rosettacode").reverse().toString(), new StringBuilder("raisethysword").reverse().toString()); - for (int i = 1; i < args.length; i += 2) - printDistance(args[i - 1], args[i]); - } + public static void main(String [] args) { + String [] data = { "kitten", "sitting", "saturday", "sunday", "rosettacode", "raisethysword" }; + for (int i = 0; i < data.length; i += 2) + System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1])); + } } diff --git a/Task/Levenshtein-distance/REXX/levenshtein-distance.rexx b/Task/Levenshtein-distance/REXX/levenshtein-distance.rexx index 643097aaa2..1b53d6d3b3 100644 --- a/Task/Levenshtein-distance/REXX/levenshtein-distance.rexx +++ b/Task/Levenshtein-distance/REXX/levenshtein-distance.rexx @@ -1,24 +1,24 @@ -/*REXX program to calculate the Levenshtein distance (between 2 strings)*/ -call levenshtein 'kitten' , "sitting" -call levenshtein 'rosettacode' , "raisethysword" -call levenshtein 'Sunday' , "Saturday" -call levenshtein 'Vladimir_Levenshtein[1965]' ,"Vladimir_Levenshtein[1965]" -call levenshtein 'this_algorithm_is_similar_to' ,"Damerau-Levenshtein_distance" +/*REXX program calculates the Levenshtein distance between two strings.*/ +call levenshtein 'kitten' , "sitting" +call levenshtein 'rosettacode' , "raisethysword" +call levenshtein 'Sunday' , "Saturday" +call levenshtein 'Vladimir_Levenshtein[1965]' , "Vladimir_Levenshtein[1965]" +call levenshtein 'this_algorithm_is_similar_to', "Damerau-Levenshtein_distance" exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────Levenshtein subroutine───────────*/ -levenshtein: procedure; parse arg s,t; m=length(s); n=length(t); d.=0 - say ' 1st string =' s - say ' 2nd string =' t +/*──────────────────────────────────LEVENSHTEIN subroutine──────────────*/ +levenshtein: procedure; parse arg s,t; sL=length(s); tL=length(t) + say ' 1st string = ' s + say ' 2nd string = ' t +@.=0 + do j=1 for tL; @.0.j=j; end /*j*/ + do k=1 for sL; @.k.0=k; end /*k*/ - do i=1 for m; d.i.0=i; end /*i*/ - do j=1 for n; d.0.j=j; end /*j*/ - - do j=1 for n; tj=substr(t,j,1); jm=j-1 - do i=1 for m; si=substr(s,i,1); im=i-1 - if si==tj then d.i.j = d.im.jm - else d.i.j = min(d.im.j, d.i.jm, d.im.jm) + 1 - end /*i*/ + do j=1 for tL; j_=j-1; q=substr(t,j,1) + do k=1 for sL; k_=k-1 + if q==substr(s,k,1) then @.k.j=@.k_.j_ + else @.k.j=1 + min(@.k_.j, @.k.j_, @.k_.j_) + end /*k*/ end /*j*/ -say 'Levenshtein distance =' d.m.n; say +say 'Levenshtein distance = ' @.sL.tL; say return diff --git a/Task/Levenshtein-distance/Racket/levenshtein-distance.rkt b/Task/Levenshtein-distance/Racket/levenshtein-distance.rkt index 6f4498095d..28a712361a 100644 --- a/Task/Levenshtein-distance/Racket/levenshtein-distance.rkt +++ b/Task/Levenshtein-distance/Racket/levenshtein-distance.rkt @@ -11,7 +11,10 @@ (min (add1 (ls (sub1 a-index) b-index)) (add1 (ls a-index (sub1 b-index))) (add1 (ls (sub1 a-index) (sub1 b-index)))))])) - (define memo (make-hasheq)) + (define memo (make-hash)) (define (ls a-i b-i) (hash-ref! memo (cons a-i b-i) (λ() (ls0 a-i b-i)))) (ls (sub1 (string-length a)) (sub1 (string-length b)))) + +(levenshtein "kitten" "sitting") +(levenshtein "rosettacode" "raisethysword") diff --git a/Task/Levenshtein-distance/Ruby/levenshtein-distance.rb b/Task/Levenshtein-distance/Ruby/levenshtein-distance.rb index 9a3ea463fc..b86917fdbf 100644 --- a/Task/Levenshtein-distance/Ruby/levenshtein-distance.rb +++ b/Task/Levenshtein-distance/Ruby/levenshtein-distance.rb @@ -1,27 +1,21 @@ -def levenshtein_distance(s, t) - m = s.length - n = t.length - return m if n == 0 - return n if m == 0 - d = Array.new(m+1) {Array.new(n+1)} +module Levenshtein - (0..m).each {|i| d[i][0] = i} - (0..n).each {|j| d[0][j] = j} - (1..n).each do |j| - (1..m).each do |i| - d[i][j] = if s[i-1] == t[j-1] # adjust index into string - d[i-1][j-1] # no operation required - else - [ d[i-1][j]+1, # deletion - d[i][j-1]+1, # insertion - d[i-1][j-1]+1, # substitution - ].min - end + def self.distance(a, b) + a, b = a.downcase, b.downcase + costs = Array(0..b.length) # i == 0 + (1..a.length).each do |i| + costs[0], nw = i, i - 1 # j == 0; nw is lev(i-1, j) + (1..b.length).each do |j| + costs[j], nw = [costs[j] + 1, costs[j-1] + 1, a[i-1] == b[j-1] ? nw : nw + 1].min, costs[j] + end + end + costs[b.length] + end + + def self.test + %w{kitten sitting saturday sunday rosettacode raisethysword}.each_slice(2) do |a, b| + puts "distance(#{a}, #{b}) = #{distance(a, b)}" end end - d[m][n] -end -[ ['kitten','sitting'], ['saturday','sunday'], ["rosettacode", "raisethysword"] ].each do |s,t| - puts "levenshtein_distance('#{s}', '#{t}') = #{levenshtein_distance(s, t)}" end diff --git a/Task/Linear-congruential-generator/AutoHotkey/linear-congruential-generator.ahk b/Task/Linear-congruential-generator/AutoHotkey/linear-congruential-generator.ahk new file mode 100644 index 0000000000..841910f499 --- /dev/null +++ b/Task/Linear-congruential-generator/AutoHotkey/linear-congruential-generator.ahk @@ -0,0 +1,16 @@ +a := 0, b:= [0] +Loop, 10 + BSD .= "`t" (a := BSD(a)) "`n" +, b := MS(b[1]) +, MS .= "`t" (b[2]) "`n" + +MsgBox, % "BSD:`n" BSD "`nMS:`n" MS + +BSD(Seed) { + return, Mod(1103515245 * Seed + 12345, 2147483648) +} + +MS(Seed) { + Seed := Mod(214013 * Seed + 2531011, 2147483648) + return, [Seed, Seed // 65536] +} diff --git a/Task/Linear-congruential-generator/C++/linear-congruential-generator.cpp b/Task/Linear-congruential-generator/C++/linear-congruential-generator.cpp index 8c91a39570..7b606eb00c 100644 --- a/Task/Linear-congruential-generator/C++/linear-congruential-generator.cpp +++ b/Task/Linear-congruential-generator/C++/linear-congruential-generator.cpp @@ -1,4 +1,3 @@ -#include #include //-------------------------------------------------------------------------------------------------- diff --git a/Task/Linear-congruential-generator/J/linear-congruential-generator-1.j b/Task/Linear-congruential-generator/J/linear-congruential-generator-1.j index b91fc968c2..ac94fabd6e 100644 --- a/Task/Linear-congruential-generator/J/linear-congruential-generator-1.j +++ b/Task/Linear-congruential-generator/J/linear-congruential-generator-1.j @@ -1,7 +1,7 @@ lcg=: adverb define 0 m lcg y NB. default seed of 0 : - 'a c mod'=. m + 'a c mod'=. x: m }. (mod | c + a * ])^:( " + ( (!x&!y)&true + | false + ) + ) + ( \n + "x or y -> " + ( (!x|!y)&true + | false + ) + ) + "\nnot x -> " + (~!x&true|false) + ) + ) +& out$(Logic$(,)) +& out$(Logic$(~,)) +& out$(Logic$(,~)) +& out$(Logic$(~,~)) +); diff --git a/Task/Logical-operations/Deja-Vu/logical-operations.djv b/Task/Logical-operations/Deja-Vu/logical-operations.djv new file mode 100644 index 0000000000..1176c9285b --- /dev/null +++ b/Task/Logical-operations/Deja-Vu/logical-operations.djv @@ -0,0 +1,6 @@ +showbool a b: + !.( a b or a b and a b xor a b not a ) + +for a in [ false true ]: + for b in [ false true ]: + showbool a b diff --git a/Task/Logical-operations/Maple/logical-operations.maple b/Task/Logical-operations/Maple/logical-operations.maple new file mode 100644 index 0000000000..10fe1375bd --- /dev/null +++ b/Task/Logical-operations/Maple/logical-operations.maple @@ -0,0 +1,6 @@ +f:=proc(a,b) a and b, a or b, not a; end proc: + +f(true,true); +f(true,false); +f(false,true); +f(false,false); diff --git a/Task/Logical-operations/XSLT/logical-operations.xslt b/Task/Logical-operations/XSLT/logical-operations.xslt index 29cab6c04a..5b8aefae82 100644 --- a/Task/Logical-operations/XSLT/logical-operations.xslt +++ b/Task/Logical-operations/XSLT/logical-operations.xslt @@ -4,3 +4,4 @@ a and b = a or b = not a = + diff --git a/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d b/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d index c24732d210..248c3bb517 100644 --- a/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d +++ b/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d @@ -60,7 +60,7 @@ const(T)[] lcs(T)(in T[] xs, in T[] ys) pure /*nothrow*/ { .array; } -string lcsString(in string s1, in string s2) /*pure nothrow*/ { +string lcsString(in string s1, in string s2) pure /*nothrow*/ { //return lcs(s1.representation, s2.representation).assumeChars; return cast(string)lcs(s1.representation, s2.representation); } diff --git a/Task/Longest-common-subsequence/Racket/longest-common-subsequence.rkt b/Task/Longest-common-subsequence/Racket/longest-common-subsequence.rkt index a42b668d52..f157e0a3a8 100644 --- a/Task/Longest-common-subsequence/Racket/longest-common-subsequence.rkt +++ b/Task/Longest-common-subsequence/Racket/longest-common-subsequence.rkt @@ -10,12 +10,17 @@ (hash-set! memo (cons xs ys) r) r) -(define (lcs sx sy) +(define (lcs/list sx sy) (or (lookup sx sy) (store sx sy (match* (sx sy) [((cons x xs) (cons y ys)) (if (equal? x y) - (cons x (lcs xs ys)) - (longest (lcs sx ys) (lcs xs sy)))] + (cons x (lcs/list xs ys)) + (longest (lcs/list sx ys) (lcs/list xs sy)))] [(_ _) '()])))) + +(define (lcs sx sy) + (list->string (lcs/list (string->list sx) (string->list sy)))) + +(lcs "thisisatest" "testing123testing") diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-1.txr similarity index 100% rename from Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously.txr rename to Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-1.txr diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr new file mode 100644 index 0000000000..9e7f2543d8 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr @@ -0,0 +1,4 @@ +$ txr -e '(pprint (mappend (op list) "abc" "ABC" "123" (repeat "\n"))))' +aA1 +bB2 +cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr new file mode 100644 index 0000000000..8c2139d138 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr @@ -0,0 +1,4 @@ +$ txr -e '(each ((x "abc") (y "ABC") (z "123")) (put-line `@x@y@z`))' +aA1 +bB2 +cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-4.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-4.txr new file mode 100644 index 0000000000..ef8c6afb34 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-4.txr @@ -0,0 +1,22 @@ +@(do + ;; Scheme's vector-for-each: a one-liner in TXR + ;; that happily works over strings and lists. + (defun vector-for-each (fun . vecs) + [apply mapcar fun (range) vecs]) + + (defun display (obj : (stream *stdout*)) + (pprint obj stream)) + + (defun newline (: (stream *stdout*)) + (display #\newline stream)) + + (let ((a (vec "a" "b" "c")) + (b (vec "A" "B" "C")) + (c (vec 1 2 3))) + (vector-for-each + (lambda (current-index i1 i2 i3) + (display i1) + (display i2) + (display i3) + (newline)) + a b c))) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-5.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-5.txr new file mode 100644 index 0000000000..f61f27df1e --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-5.txr @@ -0,0 +1,17 @@ +@(do + (macro-time + (defun question-var-to-meta-num (var) + ^(sys:var ,(int-str (cdr (symbol-name var)))))) + + (defmacro map (square-fun . square-args) + (tree-bind [(fun . args)] square-fun + ^[apply mapcar (op ,fun ,*[mapcar question-var-to-meta-num args]) + (macrolet ([(. args) ^(quote ,args)]) + (list ,*square-args))])) + + (defun word (. items) + [apply format nil "~a~a~a" items]) + + (defun show (x) (pprinl x)) + + (show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]))) diff --git a/Task/Loops-Break/Rust/loops-break.rust b/Task/Loops-Break/Rust/loops-break.rust new file mode 100644 index 0000000000..c6e587c30f --- /dev/null +++ b/Task/Loops-Break/Rust/loops-break.rust @@ -0,0 +1,14 @@ +use std::rand; +use std::rand::Rng; + +fn main() { + let mut rng = rand::task_rng(); + loop { + let num = rng.gen_range(0, 20); + println!("{:d}", num); + if num == 10 { + break; + } + println!("{:d}", rng.gen_range(0, 20)); + } +} diff --git a/Task/Loops-Continue/Rust/loops-continue.rust b/Task/Loops-Continue/Rust/loops-continue.rust new file mode 100644 index 0000000000..1463e3d6fe --- /dev/null +++ b/Task/Loops-Continue/Rust/loops-continue.rust @@ -0,0 +1,12 @@ +use std::iter::range_inclusive; + +fn main() { + for i in range_inclusive(1, 10) { + print!("{:d}", i); + if i % 5 == 0 { + print("\n"); + continue; + } + print(", "); + } +} diff --git a/Task/Loops-Downward-for/Frink/loops-downward-for.frink b/Task/Loops-Downward-for/Frink/loops-downward-for.frink new file mode 100644 index 0000000000..c827d800c8 --- /dev/null +++ b/Task/Loops-Downward-for/Frink/loops-downward-for.frink @@ -0,0 +1,2 @@ +for i = 10 to 0 step -1 + println[i] diff --git a/Task/Loops-Downward-for/J/loops-downward-for-1.j b/Task/Loops-Downward-for/J/loops-downward-for-1.j new file mode 100644 index 0000000000..c8605d2f03 --- /dev/null +++ b/Task/Loops-Downward-for/J/loops-downward-for-1.j @@ -0,0 +1,5 @@ +3 : 0 ] 11 + for_i. i. - y do. + smoutput i + end. +) diff --git a/Task/Loops-Downward-for/J/loops-downward-for-2.j b/Task/Loops-Downward-for/J/loops-downward-for-2.j new file mode 100644 index 0000000000..f92fb4ccd3 --- /dev/null +++ b/Task/Loops-Downward-for/J/loops-downward-for-2.j @@ -0,0 +1 @@ +thru=: <./ + i.@(+*)@-~ diff --git a/Task/Loops-Downward-for/J/loops-downward-for-3.j b/Task/Loops-Downward-for/J/loops-downward-for-3.j new file mode 100644 index 0000000000..a4f6e74219 --- /dev/null +++ b/Task/Loops-Downward-for/J/loops-downward-for-3.j @@ -0,0 +1,2 @@ + 10 thru 0 +10 9 8 7 6 5 4 3 2 1 0 diff --git a/Task/Loops-Downward-for/J/loops-downward-for.j b/Task/Loops-Downward-for/J/loops-downward-for.j deleted file mode 100644 index 29d8875e10..0000000000 --- a/Task/Loops-Downward-for/J/loops-downward-for.j +++ /dev/null @@ -1,6 +0,0 @@ -3 : 0 ] 11 - for_i. i. - y do. - i 1!:2 ]2 - end. - i.0 0 - ) diff --git a/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-3.j b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-3.j new file mode 100644 index 0000000000..90497ee031 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-3.j @@ -0,0 +1,4 @@ + i:8 +_8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8 + i:8j8 +_8 _6 _4 _2 0 2 4 6 8 diff --git a/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple b/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple new file mode 100644 index 0000000000..bbbfe0a74b --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple @@ -0,0 +1,3 @@ +for i from 1 to 6 by 2 do + i; +end do; diff --git a/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step.rust b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step.rust new file mode 100644 index 0000000000..d5daf6a1db --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step.rust @@ -0,0 +1,8 @@ +use std::iter::range_step_inclusive; + +fn main() { + for i in range_step_inclusive(2, 8, 2) { + print!("{:d}, ", i); + } + println("who do we appreciate?!"); +} diff --git a/Task/Loops-For/Dart/loops-for.dart b/Task/Loops-For/Dart/loops-for.dart index f0a519d0dc..bf5831ccbd 100644 --- a/Task/Loops-For/Dart/loops-for.dart +++ b/Task/Loops-For/Dart/loops-for.dart @@ -1,4 +1,6 @@ main() { for (var i = 0; i < 5; i++) - print(i); + for (var j = 0; j < i + 1; j++) + print("*"); + print("\n"); } diff --git a/Task/Loops-For/Frink/loops-for.frink b/Task/Loops-For/Frink/loops-for.frink new file mode 100644 index 0000000000..44d829dc7e --- /dev/null +++ b/Task/Loops-For/Frink/loops-for.frink @@ -0,0 +1,7 @@ +for n = 1 to 5 +{ + for a = 1 to n + print["*"] + + println[] +} diff --git a/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 b/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 new file mode 100644 index 0000000000..f813f771ed --- /dev/null +++ b/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 @@ -0,0 +1,7 @@ +PROGRAM:FORLOOPS +:ClrHome +:For(I,1,5) +:For(J,1,I) +:Output(I,J,"*") +:End +:End diff --git a/Task/Loops-Foreach/Frink/loops-foreach.frink b/Task/Loops-Foreach/Frink/loops-foreach.frink new file mode 100644 index 0000000000..2de929f566 --- /dev/null +++ b/Task/Loops-Foreach/Frink/loops-foreach.frink @@ -0,0 +1,3 @@ +array = [1, 2, 3, 5, 7] +for n = array + println[n] diff --git a/Task/Loops-Foreach/Maple/loops-foreach.maple b/Task/Loops-Foreach/Maple/loops-foreach.maple new file mode 100644 index 0000000000..5ff01e2f05 --- /dev/null +++ b/Task/Loops-Foreach/Maple/loops-foreach.maple @@ -0,0 +1,3 @@ +for p in [2, 3, 5, 7] do + print(p); +end do; diff --git a/Task/Loops-Foreach/REXX/loops-foreach.rexx b/Task/Loops-Foreach/REXX/loops-foreach.rexx index f7cc2eac9a..94a25ee260 100644 --- a/Task/Loops-Foreach/REXX/loops-foreach.rexx +++ b/Task/Loops-Foreach/REXX/loops-foreach.rexx @@ -2,5 +2,4 @@ days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes' do j=1 for words(days) /*loop through days of the week. */ say word(days,j) /*display the weekday to screen. */ - end /*j*/ - lang postscript> /*stick a fork in it, we're done.*/ + end /*j*//*stick a fork in it, we're done.*/ diff --git a/Task/Loops-Infinite/Frink/loops-infinite.frink b/Task/Loops-Infinite/Frink/loops-infinite.frink new file mode 100644 index 0000000000..86ec82421b --- /dev/null +++ b/Task/Loops-Infinite/Frink/loops-infinite.frink @@ -0,0 +1,2 @@ +while true + println["SPAM"] diff --git a/Task/Loops-Infinite/Ruby/loops-infinite.rb b/Task/Loops-Infinite/Ruby/loops-infinite.rb index 8b3c44aeba..3d790c55a9 100644 --- a/Task/Loops-Infinite/Ruby/loops-infinite.rb +++ b/Task/Loops-Infinite/Ruby/loops-infinite.rb @@ -1,3 +1 @@ -loop do - puts "SPAM" -end +loop {puts "SPAM"} diff --git a/Task/Loops-N-plus-one-half/AutoIt/loops-n-plus-one-half.autoit b/Task/Loops-N-plus-one-half/AutoIt/loops-n-plus-one-half.autoit new file mode 100644 index 0000000000..674f48a335 --- /dev/null +++ b/Task/Loops-N-plus-one-half/AutoIt/loops-n-plus-one-half.autoit @@ -0,0 +1,26 @@ +#cs ---------------------------------------------------------------------------- + + AutoIt Version: 3.3.8.1 + Author: Alexander Alvonellos + + Script Function: + Output a comma separated list from 1 to 10, and on the tenth iteration of the + output loop, only perform half of the loop. + +#ce ---------------------------------------------------------------------------- + +Func doLoopIterative() + Dim $list = "" + For $i = 1 To 10 Step 1 + $list = $list & $i + If($i = 10) Then ExitLoop + $list = $list & ", " + Next + return $list & @CRLF +EndFunc + +Func main() + ConsoleWrite(doLoopIterative()) +EndFunc + +main() diff --git a/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-2.basic b/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-2.basic index e999e17332..2c24be5794 100644 --- a/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-2.basic +++ b/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-2.basic @@ -1,5 +1,3 @@ -10 FOR i=1 TO 10 -20 PRINT i; -30 IF i=10 THEN GOTO 50 -40 PRINT ", "; -50 NEXT i +10 FOR I = 1 TO 10 +20 PRINT I; +30 IF I < 10 THEN PRINT ", "; : NEXT I diff --git a/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-3.basic b/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-3.basic new file mode 100644 index 0000000000..e999e17332 --- /dev/null +++ b/Task/Loops-N-plus-one-half/BASIC/loops-n-plus-one-half-3.basic @@ -0,0 +1,5 @@ +10 FOR i=1 TO 10 +20 PRINT i; +30 IF i=10 THEN GOTO 50 +40 PRINT ", "; +50 NEXT i diff --git a/Task/Loops-Nested/Maple/loops-nested.maple b/Task/Loops-Nested/Maple/loops-nested.maple new file mode 100644 index 0000000000..ca88d58027 --- /dev/null +++ b/Task/Loops-Nested/Maple/loops-nested.maple @@ -0,0 +1,9 @@ +(m,n) := LinearAlgebra:-Dimensions(M): +for i from 1 to m do + for j from 1 to n do + print(M[i,j]); + if M[i,j] = 20 then + (i,j):=m,n; next; + end if; + end do; +end do: diff --git a/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d b/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d index a217bcfd78..4445111744 100644 --- a/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d +++ b/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d @@ -3,7 +3,7 @@ import std.stdio, std.math, std.bigint; bool isPrime(in int p) pure nothrow { if (p < 2 || p % 2 == 0) return p == 2; - foreach (immutable i; 3 .. cast(uint)(sqrt(cast(real)p)) + 1) + foreach (immutable i; 3 .. cast(uint)real(p).sqrt + 1) if (p % i == 0) return false; return true; diff --git a/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m b/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m index fad5db312c..8eddacc30e 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m +++ b/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m @@ -1,17 +1,17 @@ -- (NSMutableArray *) toCharArray { +- (NSArray *) toCharArray { NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]]; for (int i=0; i < [self length]; i++) { - NSString *ichar = [NSString stringWithFormat:@"%c", [self characterAtIndex:i]]; + NSString *ichar = [NSString stringWithFormat:@"%C", [self characterAtIndex:i]]; [characters addObject:ichar]; } - return [characters autorelease]; + return characters; } + (BOOL) luhnCheck:(NSString *)stringToTest { - NSMutableArray *stringAsChars = [stringToTest toCharArray]; + NSArray *stringAsChars = [stringToTest toCharArray]; BOOL isOdd = YES; int oddSum = 0; @@ -19,7 +19,7 @@ for (int i = [stringToTest length] - 1; i >= 0; i--) { - int digit = [(NSString *)[stringAsChars objectAtIndex:i] intValue]; + int digit = [(NSString *)stringAsChars[i] intValue]; if (isOdd) oddSum += digit; diff --git a/Task/Luhn-test-of-credit-card-numbers/Standard-ML/luhn-test-of-credit-card-numbers.ml b/Task/Luhn-test-of-credit-card-numbers/Standard-ML/luhn-test-of-credit-card-numbers.ml new file mode 100644 index 0000000000..4ce8325bca --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Standard-ML/luhn-test-of-credit-card-numbers.ml @@ -0,0 +1,22 @@ +local + fun revDigits 0 = [] + | revDigits n = (n mod 10) :: revDigits (n div 10) + + fun digitSum n = if n > 9 then digitSum (n div 10 + n mod 10) + else n + + fun luhn_sum [] = 0 + | luhn_sum [d] = d + | luhn_sum (d::d'::ds) = d + digitSum (2*d') + luhn_sum ds +in + fun luhn_test n = luhn_sum (revDigits n) mod 10 = 0 + + val res = map luhn_test [49927398716, 49927398717, 1234567812345678, 1234567812345670]; +end; + +(* +[opening file "luhn.sml"] +> val luhn_test = fn : int -> bool + val res = [true, false, false, true] : bool list +[closing file "luhn.sml"] +*) diff --git a/Task/MD4/Common-Lisp/md4.lisp b/Task/MD4/Common-Lisp/md4.lisp new file mode 100644 index 0000000000..954fc75722 --- /dev/null +++ b/Task/MD4/Common-Lisp/md4.lisp @@ -0,0 +1,7 @@ +(ql:quickload 'ironclad) +(defun md4 (str) + (ironclad:byte-array-to-hex-string + (ironclad:digest-sequence :md4 + (ironclad:ascii-string-to-byte-array str)))) + +(md4 "Rosetta Code") diff --git a/Task/MD4/Lua/md4.lua b/Task/MD4/Lua/md4.lua new file mode 100644 index 0000000000..0885d58fef --- /dev/null +++ b/Task/MD4/Lua/md4.lua @@ -0,0 +1,5 @@ +#!/usr/bin/lua + +require "crypto" + +print(crypto.digest("MD4", "Rosetta Code")) diff --git a/Task/MD5-Implementation/Seed7/md5-implementation.seed7 b/Task/MD5-Implementation/Seed7/md5-implementation.seed7 index a7ded1876d..6b8859c5c9 100644 --- a/Task/MD5-Implementation/Seed7/md5-implementation.seed7 +++ b/Task/MD5-Implementation/Seed7/md5-implementation.seed7 @@ -45,9 +45,9 @@ const func string: md5 (in var string: message) is func begin length := length(message); # Append the bit '1' to the message. - message &:= '\16#80\'; + message &:= '\16#80;'; # Append '0' bits, so that the resulting bit length is congruent to 448 (mod 512). - message &:= "\0\" mult 63 - (length + 8) mod 64; + message &:= "\0;" mult 63 - (length + 8) mod 64; # Append length of message (before pre-processing), in bits, as 64-bit little-endian integer. message &:= int64AsEightBytesLe(8 * length); @@ -55,7 +55,7 @@ const func string: md5 (in var string: message) is func for chunkIndex range 1 to length(message) step 64 do # Break chunk into sixteen 32-bit little-endian words. for index range 1 to 16 do - m[index] := bin32(bytesLe2Int(message[chunkIndex + 4 * pred(index) len 4])); + m[index] := bin32(bytes2Int(message[chunkIndex + 4 * pred(index) len 4], UNSIGNED, LE)); end for; a := bin32(a0 mod 16#100000000); @@ -74,7 +74,7 @@ const func string: md5 (in var string: message) is func f := b >< c >< d; g := (3 * index + 2) mod 16 + 1; else - f := c >< (b | (bin32(16#FFFFFFFF) >< d)); + f := c >< (b | (bin32(16#ffffffff) >< d)); g := (7 * pred(index)) mod 16 + 1; end if; diff --git a/Task/MD5/Common-Lisp/md5.lisp b/Task/MD5/Common-Lisp/md5.lisp new file mode 100644 index 0000000000..d8ed8e77a3 --- /dev/null +++ b/Task/MD5/Common-Lisp/md5.lisp @@ -0,0 +1,14 @@ +(ql:quickload 'ironclad) +(defun md5 (str) + (ironclad:byte-array-to-hex-string + (ironclad:digest-sequence :md5 + (ironclad:ascii-string-to-byte-array str)))) +(defvar *tests* '("" + "a" + "abc" + "message digest" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890")) +(dolist (msg *tests*) + (format T "~s: ~a~%" msg (md5 msg))) diff --git a/Task/Man-or-boy-test/D/man-or-boy-test-5.d b/Task/Man-or-boy-test/D/man-or-boy-test-5.d index 3c516b2a50..c64fd548c8 100644 --- a/Task/Man-or-boy-test/D/man-or-boy-test-5.d +++ b/Task/Man-or-boy-test/D/man-or-boy-test-5.d @@ -10,7 +10,7 @@ BigInt A(in int k, in int x1, in int x2, in int x3, static immutable t = [0, 0, 0, 1, 2, 3]; return t[k].BigInt; } - alias memoize!c1_ c1; + alias c1 = memoize!c1_; static BigInt c2_(in int k) { if (k > 5) @@ -18,7 +18,7 @@ BigInt A(in int k, in int x1, in int x2, in int x3, static immutable t = [0, 0, 1, 1, 1, 2]; return t[k].BigInt; } - alias memoize!c2_ c2; + alias c2 = memoize!c2_; static BigInt c3_(in int k) { if (k > 5) @@ -26,7 +26,7 @@ BigInt A(in int k, in int x1, in int x2, in int x3, static immutable t = [0, 1, 1, 0, 0, 1]; return t[k].BigInt; } - alias memoize!c3_ c3; + alias c3 = memoize!c3_; static BigInt c4_(in int k) { if (k > 5) @@ -34,7 +34,7 @@ BigInt A(in int k, in int x1, in int x2, in int x3, static immutable t = [1, 1, 0, 0, 0, 0]; return t[k].BigInt; } - alias memoize!c4_ c4; + alias c4 = memoize!c4_; static int c5(in int k) pure nothrow { return !!k; @@ -48,6 +48,7 @@ BigInt A(in int k, in int x1, in int x2, in int x3, void main() { import std.stdio, std.conv, std.range; + foreach (immutable i; 0 .. 40) writeln(i, " ", A(i, 1, -1, -1, 1, 0)); diff --git a/Task/Man-or-boy-test/Objective-C/man-or-boy-test-1.m b/Task/Man-or-boy-test/Objective-C/man-or-boy-test-1.m index 64dc9d09c4..46aa22346c 100644 --- a/Task/Man-or-boy-test/Objective-C/man-or-boy-test-1.m +++ b/Task/Man-or-boy-test/Objective-C/man-or-boy-test-1.m @@ -1,25 +1,25 @@ #import -typedef NSInteger (^IntegerBlock)(); +typedef NSInteger (^IntegerBlock)(void); NSInteger A (NSInteger kParam, IntegerBlock x1, IntegerBlock x2, IntegerBlock x3, IntegerBlock x4, IntegerBlock x5) { __block NSInteger k = kParam; - __block IntegerBlock B; // due to a GCC bug, we have to initialize on a separate line - B = ^ { - return A(--k, B, x1, x2, x3, x4); + __block __weak IntegerBlock weak_B; + IntegerBlock B; + weak_B = B = ^ { + return A(--k, weak_B, x1, x2, x3, x4); }; return k <= 0 ? x4() + x5() : B(); } IntegerBlock K (NSInteger n) { - IntegerBlock result = ^{return n;}; - return [[result copy] autorelease]; + return ^{return n;}; } int main (int argc, const char * argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSInteger result = A(10, K(1), K(-1), K(-1), K(1), K(0)); - NSLog(@"%d\n", result); - [pool drain]; + @autoreleasepool { + NSInteger result = A(10, K(1), K(-1), K(-1), K(1), K(0)); + NSLog(@"%d\n", result); + } return 0; } diff --git a/Task/Man-or-boy-test/Objective-C/man-or-boy-test-2.m b/Task/Man-or-boy-test/Objective-C/man-or-boy-test-2.m index 57df3e7f87..9f10e84756 100644 --- a/Task/Man-or-boy-test/Objective-C/man-or-boy-test-2.m +++ b/Task/Man-or-boy-test/Objective-C/man-or-boy-test-2.m @@ -1,73 +1,24 @@ -@protocol IntegerFun --(NSInteger)call; -@end +#import -NSInteger A (NSInteger kParam, id x1, id x2, id x3, id x4, id x5); +typedef NSInteger (^IntegerBlock)(void); -@interface B_Class : NSObject { - NSInteger *k; - id x1, x2, x3, x4; -} --(id)initWithK:(NSInteger *)k x1:(id)x1 x2:(id)x2 x3:(id)x3 x4:(id)x4; -@end - -@implementation B_Class --(id)initWithK:(NSInteger *)_k x1:(id)_x1 x2:(id)_x2 x3:(id)_x3 x4:(id)_x4 { - if ((self = [super init])) { - k = _k; - x1 = [_x1 retain]; - x2 = [_x2 retain]; - x3 = [_x3 retain]; - x4 = [_x4 retain]; - } - return self; -} --(void)dealloc { - [x1 release]; - [x2 release]; - [x3 release]; - [x4 release]; - [super dealloc]; -} --(NSInteger)call { - return A(--*k, self, x1, x2, x3, x4); -} -@end - -NSInteger A (NSInteger k, id x1, id x2, id x3, id x4, id x5) { - id B = [[[B_Class alloc] initWithK:&k x1:x1 x2:x2 x3:x3 x4:x4] autorelease]; - return k <= 0 ? [x4 call] + [x5 call] : [B call]; +NSInteger A (NSInteger kParam, IntegerBlock x1, IntegerBlock x2, IntegerBlock x3, IntegerBlock x4, IntegerBlock x5) { + __block NSInteger k = kParam; + __block IntegerBlock B; + B = ^ { + return A(--k, B, x1, x2, x3, x4); + }; + return k <= 0 ? x4() + x5() : B(); } -@interface K : NSObject { - NSInteger n; +IntegerBlock K (NSInteger n) { + return [[^{return n;} copy] autorelease]; } --(id)initWithN:(NSInteger)n; -@end -@implementation K --(id)initWithN:(NSInteger)_n { - if ((self = [super init])) { - n = _n; - } - return self; -} --(NSInteger)call { - return n; -} -@end - -int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - NSInteger result = A(10, - [[[K alloc] initWithN:1] autorelease], - [[[K alloc] initWithN:-1] autorelease], - [[[K alloc] initWithN:-1] autorelease], - [[[K alloc] initWithN:1] autorelease], - [[[K alloc] initWithN:0] autorelease]); - NSLog(@"%ld\n", result); - - [pool release]; - return 0; +int main (int argc, const char * argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSInteger result = A(10, K(1), K(-1), K(-1), K(1), K(0)); + NSLog(@"%d\n", result); + [pool drain]; + return 0; } diff --git a/Task/Man-or-boy-test/Objective-C/man-or-boy-test-3.m b/Task/Man-or-boy-test/Objective-C/man-or-boy-test-3.m new file mode 100644 index 0000000000..57df3e7f87 --- /dev/null +++ b/Task/Man-or-boy-test/Objective-C/man-or-boy-test-3.m @@ -0,0 +1,73 @@ +@protocol IntegerFun +-(NSInteger)call; +@end + +NSInteger A (NSInteger kParam, id x1, id x2, id x3, id x4, id x5); + +@interface B_Class : NSObject { + NSInteger *k; + id x1, x2, x3, x4; +} +-(id)initWithK:(NSInteger *)k x1:(id)x1 x2:(id)x2 x3:(id)x3 x4:(id)x4; +@end + +@implementation B_Class +-(id)initWithK:(NSInteger *)_k x1:(id)_x1 x2:(id)_x2 x3:(id)_x3 x4:(id)_x4 { + if ((self = [super init])) { + k = _k; + x1 = [_x1 retain]; + x2 = [_x2 retain]; + x3 = [_x3 retain]; + x4 = [_x4 retain]; + } + return self; +} +-(void)dealloc { + [x1 release]; + [x2 release]; + [x3 release]; + [x4 release]; + [super dealloc]; +} +-(NSInteger)call { + return A(--*k, self, x1, x2, x3, x4); +} +@end + +NSInteger A (NSInteger k, id x1, id x2, id x3, id x4, id x5) { + id B = [[[B_Class alloc] initWithK:&k x1:x1 x2:x2 x3:x3 x4:x4] autorelease]; + return k <= 0 ? [x4 call] + [x5 call] : [B call]; +} + +@interface K : NSObject { + NSInteger n; +} +-(id)initWithN:(NSInteger)n; +@end + +@implementation K +-(id)initWithN:(NSInteger)_n { + if ((self = [super init])) { + n = _n; + } + return self; +} +-(NSInteger)call { + return n; +} +@end + +int main(int argc, const char *argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSInteger result = A(10, + [[[K alloc] initWithN:1] autorelease], + [[[K alloc] initWithN:-1] autorelease], + [[[K alloc] initWithN:-1] autorelease], + [[[K alloc] initWithN:1] autorelease], + [[[K alloc] initWithN:0] autorelease]); + NSLog(@"%ld\n", result); + + [pool release]; + return 0; +} diff --git a/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 b/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 index d77622d1e6..4898cb702a 100644 --- a/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 +++ b/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 @@ -1,76 +1,45 @@ +constant MAX_ITERATIONS = 50; my $height = @*ARGS[0] // 31; $height = $height % 2 ?? +$height !! 1+$height; my $width = $height; -my $max_iterations = 50; -my $upper-right = -2 + 5/4i; -my $lower-left = 1/2 - 5/4i; +my $re = [ -2, 1/2 ]; +my $im = [-5/4, 5/4]; -my @color_map = ( - "0 0 0", "0 0 252", "64 0 252", "124 0 252", "188 0 252", - "252 0 252", "252 0 188", "252 0 124", "252 0 64", "252 0 0", - "252 64 0", "252 124 0", "252 188 0", "252 252 0", "188 252 0", - "124 252 0", "64 252 0", "0 252 0", "0 252 64", "0 252 124", - "0 252 188", "0 252 252", "0 188 252", "0 124 252", "0 64 252", - "124 124 252", "156 124 252", "188 124 252", "220 124 252", "252 124 252", - "252 124 220", "252 124 188", "252 124 156", "252 124 124", "252 156 124", - "252 188 124", "252 220 124", "252 252 124", "220 252 124", "188 252 124", - "156 252 124", "124 252 124", "124 252 156", "124 252 188", "124 252 220", - "124 252 252", "124 220 252", "124 188 252", "124 156 252", "180 180 252", - "196 180 252", "216 180 252", "232 180 252", "252 180 252", "252 180 232", - "252 180 216", "252 180 196", "252 180 180", "252 196 180", "252 216 180", - "252 232 180", "252 252 180", "232 252 180", "216 252 180", "196 252 180", - "180 252 180", "180 252 196", "180 252 216", "180 252 232", "180 252 252", - "180 232 252", "180 216 252", "180 196 252", "0 0 112", "28 0 112", - "56 0 112", "84 0 112", "112 0 112", "112 0 84", "112 0 56", - "112 0 28", "112 0 0", "112 28 0", "112 56 0", "112 84 0", - "112 112 0", "84 112 0", "56 112 0", "28 112 0", "0 112 0", - "0 112 28", "0 112 56", "0 112 84", "0 112 112", "0 84 112", - "0 56 112", "0 28 112", "56 56 112", "68 56 112", "84 56 112", - "96 56 112", "112 56 112", "112 56 96", "112 56 84", "112 56 68", - "112 56 56", "112 68 56", "112 84 56", "112 96 56", "112 112 56", - "96 112 56", "84 112 56", "68 112 56", "56 112 56", "56 112 68", - "56 112 84", "56 112 96", "56 112 112", "56 96 112", "56 84 112", - "56 68 112", "80 80 112", "88 80 112", "96 80 112", "104 80 112", - "112 80 112", "112 80 104", "112 80 96", "112 80 88", "112 80 80", - "112 88 80", "112 96 80", "112 104 80", "112 112 80", "104 112 80", - "96 112 80", "88 112 80", "80 112 80", "80 112 88", "80 112 96", - "80 112 104", "80 112 112", "80 104 112", "80 96 112", "80 88 112", - "0 0 64", "16 0 64", "32 0 64", "48 0 64", "64 0 64", "64 0 48", - "64 0 32", "64 0 16", "64 0 0", "64 16 0", "64 32 0", "64 48 0", - "64 64 0", "48 64 0", "32 64 0", "16 64 0", "0 64 0", "0 64 16", - "0 64 32", "0 64 48", "0 64 64", "0 48 64", "0 32 64", "0 16 64", - "32 32 64", "40 32 64", "48 32 64", "56 32 64", "64 32 64", - "64 32 56", "64 32 48", "64 32 40", "64 32 32", "64 40 32", - "64 48 32", "64 56 32", "64 64 32", "56 64 32", "48 64 32", - "40 64 32", "32 64 32", "32 64 40", "32 64 48", "32 64 56", - "32 64 64", "32 56 64", "32 48 64", "32 40 64", "44 44 64", - "48 44 64", "52 44 64", "60 44 64", "64 44 64", "64 44 60", - "64 44 52", "64 44 48", "64 44 44", "64 48 44", "64 52 44", - "64 60 44", "64 64 44", "60 64 44", "52 64 44", "48 64 44", - "44 64 44", "44 64 48", "44 64 52", "44 64 60", "44 64 64", - "44 60 64", "44 52 64", "44 48 64" -); +my @re = $re.min, * + ($re.max - $re.min)/($height - 1) ... $re.max; +my @im = 1i «*« ($im.min, * + ($im.max - $im.min)/($width - 1) ... 0); -sub mandel (Complex $c) { - my $z = 0i; - for ^$max_iterations -> $i { - return $i + 1 if $z.abs > 2; - $z = $z * $z + $c; - } - return 0; -} +my @color_map = map ~*.comb(/../).map({:16($_)}), < +000000 0000fc 4000fc 7c00fc bc00fc fc00fc fc00bc fc007c fc0040 fc0000 fc4000 +fc7c00 fcbc00 fcfc00 bcfc00 7cfc00 40fc00 00fc00 00fc40 00fc7c 00fcbc 00fcfc +00bcfc 007cfc 0040fc 7c7cfc 9c7cfc bc7cfc dc7cfc fc7cfc fc7cdc fc7cbc fc7c9c +fc7c7c fc9c7c fcbc7c fcdc7c fcfc7c dcfc7c bcfc7c 9cfc7c 7cfc7c 7cfc9c 7cfcbc +7cfcdc 7cfcfc 7cdcfc 7cbcfc 7c9cfc b4b4fc c4b4fc d8b4fc e8b4fc fcb4fc fcb4e8 +fcb4d8 fcb4c4 fcb4b4 fcc4b4 fcd8b4 fce8b4 fcfcb4 e8fcb4 d8fcb4 c4fcb4 b4fcb4 +b4fcc4 b4fcd8 b4fce8 b4fcfc b4e8fc b4d8fc b4c4fc 000070 1c0070 380070 540070 +700070 700054 700038 70001c 700000 701c00 703800 705400 707000 547000 387000 +1c7000 007000 00701c 007038 007054 007070 005470 003870 001c70 383870 443870 +543870 603870 703870 703860 703854 703844 703838 704438 705438 706038 707038 +607038 547038 447038 387038 387044 387054 387060 387070 386070 385470 384470 +505070 585070 605070 685070 705070 705068 705060 705058 705050 705850 706050 +706850 707050 687050 607050 587050 507050 507058 507060 507068 507070 506870 +506070 505870 000040 100040 200040 300040 400040 400030 400020 400010 400000 +401000 402000 403000 404000 304000 204000 104000 004000 004010 004020 004030 +004040 003040 002040 001040 202040 282040 302040 382040 402040 402038 402030 +402028 402020 402820 403020 403820 404020 384020 304020 284020 204020 204028 +204030 204038 204040 203840 203040 202840 2c2c40 302c40 342c40 3c2c40 402c40 +402c3c 402c34 402c30 402c2c 40302c 40342c 403c2c 40402c 3c402c 34402c 30402c +2c402c 2c4030 2c4034 2c403c 2c4040 2c3c40 2c3440 2c3040 +>; -sub subdivide($low, $high, $count) { - (^$count).map: { $low + ($_ / ($count - 1)) * ($high - $low) } -} +sub Mandel (Complex $z) { 0, * **2 + $z ... *.abs > 2 } say "P3"; say "$width $height"; say "255"; -for subdivide($upper-right.re, $lower-left.re, $height) -> $re { - my @line = subdivide($re + ($upper-right.im)i, $re + 0i, ($width + 1) / 2).map: { mandel($_) } - my $middle = @line.pop; - say ~(@line, $middle, @line.reverse).map: { @color_map[$_] } +for @re -> $re { + say @color_map[.[^.end], .reverse] given + map { +Mandel($^z)[^MAX_ITERATIONS] % MAX_ITERATIONS }, + $re «+« @im; } diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set.py b/Task/Mandelbrot-set/Python/mandelbrot-set-1.py similarity index 100% rename from Task/Mandelbrot-set/Python/mandelbrot-set.py rename to Task/Mandelbrot-set/Python/mandelbrot-set-1.py diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-2.py b/Task/Mandelbrot-set/Python/mandelbrot-set-2.py new file mode 100644 index 0000000000..2cbddcf2ec --- /dev/null +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-2.py @@ -0,0 +1,6 @@ +import math +mandelbrot = lambda z , c , n = 40 : float('nan') if abs(z) > 1000 else mandelbrot(z**2+c,c,n-1) if n > 0 else z**2+c +print("\n".join(["".join(["#" if not math.isnan(mandelbrot(0,x+1j*y).real) else " " + for x in [a*0.02 for a in xrange(-80,30)]]) + for y in [a*0.05 for a in xrange(-20,20)]]) + ) diff --git a/Task/Mandelbrot-set/TXR/mandelbrot-set.txr b/Task/Mandelbrot-set/TXR/mandelbrot-set.txr new file mode 100644 index 0000000000..fdb4eac2a6 --- /dev/null +++ b/Task/Mandelbrot-set/TXR/mandelbrot-set.txr @@ -0,0 +1,77 @@ +@(do + (defvar x-centre -0.5) + (defvar y-centre 0.0) + (defvar width 4.0) + (defvar i-max 800) + (defvar j-max 600) + (defvar n 100) + (defvar r-max 2.0) + (defvar file "mandelbrot.pgm") + (defvar colour-max 255) + (defvar pixel-size (/ width i-max)) + (defvar x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1)))) + (defvar y-offset (+ y-centre (* 0.5 pixel-size (+ j-max 1)))) + + ;; with-output-to-file macro + (defmacro with-output-to-file (name . body) + ^(let ((*stdout* (open-file ,name "w"))) + (unwind-protect (progn ,*body) (close-stream *stdout*)))) + + ;; complex number library + (defmacro cplx (x y) ^(cons ,x ,y)) + (defmacro re (c) ^(car ,c)) + (defmacro im (c) ^(cdr ,c)) + + (defsymacro c0 '(0 . 0)) + + (macro-time + (defun with-cplx-expand (specs body) + (tree-case specs + (((re im expr) . rest) + ^(tree-bind (,re . ,im) ,expr ,(with-cplx-expand rest body))) + (() (tree-case body + ((a b . rest) ^(progn ,a ,b ,*rest)) + ((a) a) + (x (error "with-cplx: invalid body ~s" body)))) + (x (error "with-cplx: bad args ~s" x))))) + + (defmacro with-cplx (specs . body) + (with-cplx-expand specs body)) + + (defun c+ (x y) + (with-cplx ((a b x) (c d y)) + (cplx (+ a c) (+ b d)))) + + (defun c* (x y) + (with-cplx ((a b x) (c d y)) + (cplx (- (* a c) (* b d)) (+ (* b c) (* a d))))) + + (defun modulus (z) + (with-cplx ((a b z)) + (sqrt (+ (* a a) (* b b))))) + + ;; Mandelbrot routines + (defun inside-p (z0 : (z c0) (n n)) + (and (< (modulus z) r-max) + (or (zerop n) + (inside-p z0 (c+ (c* z z) z0) (- n 1))))) + + (defmacro int-bool (b) + ^(if ,b colour-max 0)) + + (defun pixel (i j) + (int-bool + (inside-p + (cplx (+ x-offset (* pixel-size i)) + (- y-offset (* pixel-size j)))))) + + ;; Mandelbrot loop and output + (defun plot () + (with-output-to-file file + (format t "P2\n~s\n~s\n~s\n" i-max j-max colour-max) + (each ((j (range 1 j-max))) + (each ((i (range 1 i-max))) + (format *stdout* "~s " (pixel i j))) + (put-line "" *stdout*)))) + + (plot)) diff --git a/Task/Matrix-arithmetic/Maple/matrix-arithmetic.maple b/Task/Matrix-arithmetic/Maple/matrix-arithmetic.maple new file mode 100644 index 0000000000..d98a12ac02 --- /dev/null +++ b/Task/Matrix-arithmetic/Maple/matrix-arithmetic.maple @@ -0,0 +1,6 @@ +M:=<<2|9|4>,<7|5|3>,<6|1|8>>: + +with(LinearAlgebra): + +Determinant(M); +Permanent(M); diff --git a/Task/Matrix-exponentiation-operator/Maple/matrix-exponentiation-operator-1.maple b/Task/Matrix-exponentiation-operator/Maple/matrix-exponentiation-operator-1.maple new file mode 100644 index 0000000000..ba7886c4ad --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Maple/matrix-exponentiation-operator-1.maple @@ -0,0 +1,2 @@ +> M := <<1,2>|<3,4>>; +> M ^ 2; diff --git a/Task/Matrix-exponentiation-operator/Maple/matrix-exponentiation-operator-2.maple b/Task/Matrix-exponentiation-operator/Maple/matrix-exponentiation-operator-2.maple new file mode 100644 index 0000000000..9eb4a70303 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Maple/matrix-exponentiation-operator-2.maple @@ -0,0 +1,2 @@ +> M := <<1,2>|<3,4>>; +> M ^~ 2; diff --git a/Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.ss b/Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.ss new file mode 100644 index 0000000000..70f78f1718 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.ss @@ -0,0 +1,23 @@ +(define (dec x) + (- x 1)) + +(define (halve x) + (/ x 2)) + +(define (row*col row col) + (apply + (map * row col))) + +(define (matrix-multiply m1 m2) + (map + (lambda (row) + (apply map (lambda col (row*col row col)) + m2)) + m1)) + +(define (matrix-exp mat exp) + (cond ((= exp 1) mat) + ((even? exp) (square-matrix (matrix-exp mat (halve exp)))) + (else (matrix-multiply mat (matrix-exp mat (dec exp)))))) + +(define (square-matrix mat) + (matrix-multiply mat mat)) diff --git a/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication.ahk b/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-1.ahk similarity index 100% rename from Task/Matrix-multiplication/AutoHotkey/matrix-multiplication.ahk rename to Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-1.ahk diff --git a/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-2.ahk b/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-2.ahk new file mode 100644 index 0000000000..b509f9b4e7 --- /dev/null +++ b/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-2.ahk @@ -0,0 +1,16 @@ +Multiply_Matrix(A,B){ + if (A[1].MaxIndex() <> B.MaxIndex()) + return + RCols := A[1].MaxIndex()>B[1].MaxIndex()?A[1].MaxIndex():B[1].MaxIndex() + RRows := A.MaxIndex()>B.MaxIndex()?A.MaxIndex():B.MaxIndex(), R := [] + Loop, % RRows { + RRow:=A_Index + loop, % RCols { + RCol:=A_Index, v := 0 + loop % A[1].MaxIndex() + col := A_Index, v += A[RRow, col] * B[col,RCol] + R[RRow,RCol] := v + } + } + return R +} diff --git a/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-3.ahk b/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-3.ahk new file mode 100644 index 0000000000..43482cc4e9 --- /dev/null +++ b/Task/Matrix-multiplication/AutoHotkey/matrix-multiplication-3.ahk @@ -0,0 +1,19 @@ +A := [[1,2] + , [3,4] + , [5,6] + , [7,8]] + +B := [[1,2,3] + , [4,5,6]] + +if Res := Multiply_Matrix(A,B) + MsgBox % Print(Res) +else + MsgBox Error +return +Print(M){ + for i, row in M + for j, col in row + Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n") + return Trim(Res,"`n") +} diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-3.d b/Task/Matrix-multiplication/D/matrix-multiplication-3.d index f89ce5bff6..83cae671f6 100644 --- a/Task/Matrix-multiplication/D/matrix-multiplication-3.d +++ b/Task/Matrix-multiplication/D/matrix-multiplication-3.d @@ -3,8 +3,7 @@ import std.stdio, std.range, std.numeric, std.algorithm; T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow { immutable Bt = B[0].length.iota.map!(i=> B.transversal(i).array) .array; - return A.map!((immutable T[] a) => Bt.map!(b => a.dotProduct(b)) - .array).array; + return A.map!((in a) => Bt.map!(b => a.dotProduct(b)).array).array; } void main() { diff --git a/Task/Matrix-multiplication/Frink/matrix-multiplication.frink b/Task/Matrix-multiplication/Frink/matrix-multiplication.frink index a708b5ab52..15311e6c8c 100644 --- a/Task/Matrix-multiplication/Frink/matrix-multiplication.frink +++ b/Task/Matrix-multiplication/Frink/matrix-multiplication.frink @@ -7,14 +7,9 @@ matprod[a is array, b is array] := b_col = length[b]-1 for row = 0 to a_row - { for col = 0 to b_col - { for inc = 0 to a_col - { c@row@col = c@row@col + (a@row@inc * b@inc@col) - } - } - } + return c } diff --git a/Task/Matrix-multiplication/Maple/matrix-multiplication.maple b/Task/Matrix-multiplication/Maple/matrix-multiplication.maple new file mode 100644 index 0000000000..2d6cd06918 --- /dev/null +++ b/Task/Matrix-multiplication/Maple/matrix-multiplication.maple @@ -0,0 +1,5 @@ +A := <<1|2|3>,<4|5|6>>; + +B := <<1,2,3>|<4,5,6>|<7,8,9>|<10,11,12>>; + +A . B; diff --git a/Task/Matrix-transposition/AutoHotkey/matrix-transposition.ahk b/Task/Matrix-transposition/AutoHotkey/matrix-transposition-1.ahk similarity index 100% rename from Task/Matrix-transposition/AutoHotkey/matrix-transposition.ahk rename to Task/Matrix-transposition/AutoHotkey/matrix-transposition-1.ahk diff --git a/Task/Matrix-transposition/AutoHotkey/matrix-transposition-2.ahk b/Task/Matrix-transposition/AutoHotkey/matrix-transposition-2.ahk new file mode 100644 index 0000000000..2832002dbc --- /dev/null +++ b/Task/Matrix-transposition/AutoHotkey/matrix-transposition-2.ahk @@ -0,0 +1,7 @@ +Transpose(M){ + R := [] + for i, row in M + for j, col in row + R[j,i] := col + return R +} diff --git a/Task/Matrix-transposition/AutoHotkey/matrix-transposition-3.ahk b/Task/Matrix-transposition/AutoHotkey/matrix-transposition-3.ahk new file mode 100644 index 0000000000..6afcc1015e --- /dev/null +++ b/Task/Matrix-transposition/AutoHotkey/matrix-transposition-3.ahk @@ -0,0 +1,11 @@ +Matrix := [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] +MsgBox % "" + . "Original Matrix :`n" Print(Matrix) + . "`nTransposed Matrix :`n" Print(Transpose(Matrix)) + +Print(M){ + for i, row in M + for j, col in row + Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n") + return Trim(Res,"`n") +} diff --git a/Task/Matrix-transposition/C++/matrix-transposition-4.cpp b/Task/Matrix-transposition/C++/matrix-transposition-4.cpp new file mode 100644 index 0000000000..644eab7ee8 --- /dev/null +++ b/Task/Matrix-transposition/C++/matrix-transposition-4.cpp @@ -0,0 +1,36 @@ +#include + +int main(){ + const int l = 5; + const int w = 3; + int m1[l][w] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15}}; + int m2[w][l]; + + for(int i=0; i|<3,4>|<5,6>>; + +M^%T; + +with(LinearAlgebra): +Transpose(M); diff --git a/Task/Maze-generation/D/maze-generation.d b/Task/Maze-generation/D/maze-generation.d index 721c69a14a..cfed6e1d42 100644 --- a/Task/Maze-generation/D/maze-generation.d +++ b/Task/Maze-generation/D/maze-generation.d @@ -16,6 +16,6 @@ void main() { } } walk(uniform(0, w), uniform(0, h)); - foreach (a, b; hor.zip(ver ~ [])) + foreach (const a, const b; hor.zip(ver ~ [])) join(a ~ ["+\n"] ~ b).writeln; } diff --git a/Task/Maze-generation/TXR/maze-generation-1.txr b/Task/Maze-generation/TXR/maze-generation-1.txr new file mode 100644 index 0000000000..a53376db84 --- /dev/null +++ b/Task/Maze-generation/TXR/maze-generation-1.txr @@ -0,0 +1,61 @@ +@(bind (width height) (15 15)) +@(do + (defvar *r* (make-random-state nil)) + (defvar vi) + (defvar pa) + + (defun scramble (list) + (let ((out ())) + (each ((item list)) + (let ((r (random *r* (+ 1 (length out))))) + (set [out r..r] (list item)))) + out)) + + (defun neigh (loc) + (tree-bind (x . y) loc + (list (- x 1)..y (+ x 1)..y + x..(- y 1) x..(+ y 1)))) + + (defun make-maze-rec (cu) + (set [vi cu] t) + (each ((ne (scramble (neigh cu)))) + (cond ((not [vi ne]) + (push ne [pa cu]) + (push cu [pa ne]) + (make-maze-rec ne))))) + + (defun make-maze (w h) + (let ((vi (hash :equal-based)) + (pa (hash :equal-based))) + (each ((x (range -1 w))) + (set [vi x..-1] t) + (set [vi x..h] t)) + (each ((y (range* 0 h))) + (set [vi -1..y] t) + (set [vi w..y] t)) + (make-maze-rec 0..0) + pa)) + + (defun print-tops (pa w j) + (each ((i (range* 0 w))) + (if (memqual i..(- j 1) [pa i..j]) + (put-string "+ ") + (put-string "+----"))) + (put-line "+")) + + (defun print-sides (pa w j) + (let ((str "")) + (each ((i (range* 0 w))) + (if (memqual (- i 1)..j [pa i..j]) + (set str `@str `) + (set str `@str| `))) + (put-line `@str|\n@str|`))) + + (defun print-maze (pa w h) + (each ((j (range* 0 h))) + (print-tops pa w j) + (print-sides pa w j)) + (print-tops pa w h))) +@;; +@(bind m @(make-maze width height)) +@(do (print-maze m width height)) diff --git a/Task/Maze-generation/TXR/maze-generation-2.txr b/Task/Maze-generation/TXR/maze-generation-2.txr new file mode 100644 index 0000000000..9c3c4da2c5 --- /dev/null +++ b/Task/Maze-generation/TXR/maze-generation-2.txr @@ -0,0 +1,93 @@ +@(do + (defvar vi) ;; visited hash + (defvar pa) ;; path connectivity hash + (defvar sc) ;; count, derived from straightness fator + + (defun scramble (list) + (let ((out ())) + (each ((item list)) + (let ((r (rand (+ 1 (length out))))) + (set [out r..r] (list item)))) + out)) + + (defun rnd-pick (list) + (if list [list (rand (length list))])) + + (defmacro while (expr . body) + ^(for () (,expr) () ,*body)) + + (defun neigh (loc) + (tree-bind (x . y) loc + (list (- x 1)..y (+ x 1)..y + x..(- y 1) x..(+ y 1)))) + + (defun make-maze-impl (cu) + (let ((fr (hash :equal-based)) + (q (list cu)) + (c sc)) + (set [fr cu] t) + (while q + (let* ((cu (first q)) + (ne (rnd-pick (remove-if (orf vi fr) (neigh cu))))) + (cond (ne (set [fr ne] t) + (push ne [pa cu]) + (push cu [pa ne]) + (push ne q) + (cond ((<= (dec c) 0) + (set q (scramble q)) + (set c sc)))) + (t (set [vi cu] t) + (del [fr cu]) + (pop q))))))) + + (defun make-maze (w h sf) + (let ((vi (hash :equal-based)) + (pa (hash :equal-based)) + (sc (max 1 (trunc (* sf w h) 100)))) + (each ((x (range -1 w))) + (set [vi x..-1] t) + (set [vi x..h] t)) + (each ((y (range* 0 h))) + (set [vi -1..y] t) + (set [vi w..y] t)) + (make-maze-impl 0..0) + pa)) + + (defun print-tops (pa w j) + (each ((i (range* 0 w))) + (if (memqual i..(- j 1) [pa i..j]) + (put-string "+ ") + (put-string "+----"))) + (put-line "+")) + + (defun print-sides (pa w j) + (let ((str "")) + (each ((i (range* 0 w))) + (if (memqual (- i 1)..j [pa i..j]) + (set str `@str `) + (set str `@str| `))) + (put-line `@str|\n@str|`))) + + (defun print-maze (pa w h) + (each ((j (range* 0 h))) + (print-tops pa w j) + (print-sides pa w j)) + (print-tops pa w h)) + + (defun usage () + (let ((invocation (ldiff *full-args* *args*))) + (put-line "usage: ") + (put-line `@invocation []`) + (put-line "straightness-factor is a percentage, defaulting to 15") + (exit 1))) + + (let ((args [mapcar int-str *args*]) + (*random-state* (make-random-state nil))) + (if (memq nil args) + (usage)) + (tree-case args + ((w h s ju . nk) (usage)) + ((w h : (s 15)) (set w (max 1 w)) + (set h (max 1 h)) + (print-maze (make-maze w h s) w h)) + (else (usage))))) diff --git a/Task/Memory-layout-of-a-data-structure/Perl-6/memory-layout-of-a-data-structure-1.pl6 b/Task/Memory-layout-of-a-data-structure/Perl-6/memory-layout-of-a-data-structure-1.pl6 new file mode 100644 index 0000000000..8c711b89a1 --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Perl-6/memory-layout-of-a-data-structure-1.pl6 @@ -0,0 +1,15 @@ +enum T_RS232 < + carrier_detect + received_data + transmitted_data + data_terminal_ready + signal_ground + data_set_ready + request_to_send + clear_to_send + ring_indicator +>; + +my bit @signal[T_RS232]; + +@signal[signal_ground] = 1; diff --git a/Task/Memory-layout-of-a-data-structure/Perl-6/memory-layout-of-a-data-structure-2.pl6 b/Task/Memory-layout-of-a-data-structure/Perl-6/memory-layout-of-a-data-structure-2.pl6 new file mode 100644 index 0000000000..da0ef3ef91 --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Perl-6/memory-layout-of-a-data-structure-2.pl6 @@ -0,0 +1 @@ +$signal +|= 1 +< signal_ground; diff --git a/Task/Menu/TI-83-BASIC/menu.ti-83 b/Task/Menu/TI-83-BASIC/menu.ti-83 new file mode 100644 index 0000000000..f2d51401bb --- /dev/null +++ b/Task/Menu/TI-83-BASIC/menu.ti-83 @@ -0,0 +1,17 @@ +PROGRAM:MENU +:"FEE FIE"→Str0 +:"HUFF AND PUFF"→Str1 +:"MIRROR MIRROR"→Str2 +:"TICK TOCK"→Str3 +:Menu("CHOOSE",Str0,A,Str1,B,Str2,C,Str3,D) +:Lbl A +:Disp Str0 +:Stop +:Lbl B +:Disp Str1 +:Stop +:Lbl C +:Disp Str2 +:Stop +:Lbl D +:Disp Str3 diff --git a/Task/Metaprogramming/Common-Lisp/metaprogramming-3.lisp b/Task/Metaprogramming/Common-Lisp/metaprogramming-3.lisp index e9ce1812f4..fa3ab85a29 100644 --- a/Task/Metaprogramming/Common-Lisp/metaprogramming-3.lisp +++ b/Task/Metaprogramming/Common-Lisp/metaprogramming-3.lisp @@ -1,8 +1,29 @@ -;; The -> notation is not part of Lisp, it is used in examples indicate the output of a form. -;; -;; -(comprehend 'list-monad (cons x y) (x '(1 2 3)) (y '(A B C))) - - -> ((1 . A) (1 . B) (1 . C) - (2 . A) (2 . B) (2 . C) - (3 . A) (3 . B) (3 . C)) +(system::expand-form + '(loop for count from 1 + for x in '(1 2 3 4 5) + summing x into sum + summing (* x x) into sum-of-squares + finally + (return + (let* ((mean (/ sum count)) + (spl-var (- (* count sum-of-squares) (* sum sum))) + (spl-dev (sqrt (/ spl-var (1- count))))) + (values mean spl-var spl-dev)))))) +(BLOCK NIL + (LET ((COUNT 1)) + (LET ((#:LIST-3230 '(1 2 3 4 5))) + (LET ((X NIL)) + (LET ((SUM-OF-SQUARES 0) (SUM 0)) + (TAGBODY SYSTEM::BEGIN-LOOP + (WHEN (ENDP #:LIST-3230) (GO SYSTEM::END-LOOP)) + (SETQ X (CAR #:LIST-3230)) + (PROGN (SETQ SUM (+ SUM X)) + (SETQ SUM-OF-SQUARES (+ SUM-OF-SQUARES (* X X)))) + (PSETQ COUNT (+ COUNT 1)) (PSETQ #:LIST-3230 (CDR #:LIST-3230)) + (GO SYSTEM::BEGIN-LOOP) SYSTEM::END-LOOP + (RETURN-FROM NIL + (LET* + ((MEAN (/ SUM COUNT)) + (SPL-VAR (- (* COUNT SUM-OF-SQUARES) (* SUM SUM))) + (SPL-DEV (SQRT (/ SPL-VAR (1- COUNT))))) + (VALUES MEAN SPL-VAR SPL-DEV))))))))) diff --git a/Task/Metaprogramming/Common-Lisp/metaprogramming-4.lisp b/Task/Metaprogramming/Common-Lisp/metaprogramming-4.lisp index fbe16577b6..e9ce1812f4 100644 --- a/Task/Metaprogramming/Common-Lisp/metaprogramming-4.lisp +++ b/Task/Metaprogramming/Common-Lisp/metaprogramming-4.lisp @@ -1,2 +1,8 @@ -(identity-comp (list x y z) (x 1) (y (* 3 x)) (z (+ x y))) --> (1 3 4) +;; The -> notation is not part of Lisp, it is used in examples indicate the output of a form. +;; +;; +(comprehend 'list-monad (cons x y) (x '(1 2 3)) (y '(A B C))) + + -> ((1 . A) (1 . B) (1 . C) + (2 . A) (2 . B) (2 . C) + (3 . A) (3 . B) (3 . C)) diff --git a/Task/Metaprogramming/Common-Lisp/metaprogramming-5.lisp b/Task/Metaprogramming/Common-Lisp/metaprogramming-5.lisp index f759b2f231..fbe16577b6 100644 --- a/Task/Metaprogramming/Common-Lisp/metaprogramming-5.lisp +++ b/Task/Metaprogramming/Common-Lisp/metaprogramming-5.lisp @@ -1,99 +1,2 @@ -(defgeneric monadic-map (monad-class function)) - -(defgeneric monadic-join (monad-class container-of-containers &rest additional)) - -(defgeneric monadic-instance (monad-class-name)) - -(defmacro comprehend (monad-instance expr &rest clauses) - (let ((monad-var (gensym "CLASS-"))) - (cond - ((null clauses) `(multiple-value-call #'monadic-unit - ,monad-instance ,expr)) - ((rest clauses) `(let ((,monad-var ,monad-instance)) - (multiple-value-call #'monadic-join ,monad-var - (comprehend ,monad-var - (comprehend ,monad-var ,expr ,@(rest clauses)) - ,(first clauses))))) - (t (destructuring-bind (var &rest container-exprs) (first clauses) - (cond - ((and var (symbolp var)) - `(funcall (monadic-map ,monad-instance (lambda (,var) ,expr)) - ,(first container-exprs))) - ((and (consp var) (every #'symbolp var)) - `(multiple-value-call (monadic-map ,monad-instance - (lambda (,@var) ,expr)) - ,@container-exprs)) - (t (error "COMPREHEND: bad variable specification: ~s" vars)))))))) - -(defmacro define-monad (class-name - &key comprehension - (monad-param (gensym "MONAD-")) - bases slots initargs - ((:map ((map-param) - &body map-body))) - ((:join ((join-param - &optional - (j-rest-kw '&rest) - (j-rest (gensym "JOIN-REST-"))) - &body join-body))) - ((:unit ((unit-param - &optional - (u-rest-kw '&rest) - (u-rest (gensym "UNIT-REST-"))) - &body unit-body)))) - `(progn - (defclass ,class-name ,bases ,slots) - (defmethod monadic-instance ((monad (eql ',class-name))) - (load-time-value (make-instance ',class-name ,@initargs))) - (defmethod monadic-map ((,monad-param ,class-name) ,map-param) - (declare (ignorable ,monad-param)) - ,@map-body) - (defmethod monadic-join ((,monad-param ,class-name) - ,join-param &rest ,j-rest) - (declare (ignorable ,monad-param ,j-rest)) - ,@join-body) - (defmethod monadic-unit ((,monad-param ,class-name) - ,unit-param &rest ,u-rest) - (declare (ignorable ,monad-param ,u-rest)) - ,@unit-body) - ,@(if comprehension - `((defmacro ,comprehension (expr &rest clauses) - `(comprehend (monadic-instance ',',class-name) - ,expr ,@clauses)))))) - -(defmethod monadic-map ((monad symbol) function) - (monadic-map (monadic-instance monad) function)) - -(defmethod monadic-join ((monad symbol) container-of-containers &rest rest) - (apply #'monadic-join (monadic-instance monad) container-of-containers rest)) - -(defmethod monadic-unit ((monad symbol) element &rest rest) - (apply #'monadic-unit (monadic-instance monad) element rest)) - -(define-monad list-monad - :comprehension list-comp - :map ((function) (lambda (container) (mapcar function container))) - :join ((list-of-lists) (reduce #'append list-of-lists)) - :unit ((element) (list element))) - -(define-monad identity-monad - :comprehension identity-comp - :map ((f) f) - :join ((x &rest rest) (apply #'values x rest)) - :unit ((x &rest rest) (apply #'values x rest))) - -(define-monad state-xform-monad - :comprehension state-xform-comp - :map ((f) - (lambda (xformer) - (lambda (s) - (identity-comp (values (funcall f x) new-state) - ((x new-state) (funcall xformer s)))))) - :join ((nested-xformer) - (lambda (s) - (identity-comp (values x new-state) - ((embedded-xformer intermediate-state) - (funcall nested-xformer s)) - ((x new-state) - (funcall embedded-xformer intermediate-state))))) - :unit ((x) (lambda (s) (values x s)))) +(identity-comp (list x y z) (x 1) (y (* 3 x)) (z (+ x y))) +-> (1 3 4) diff --git a/Task/Metaprogramming/Common-Lisp/metaprogramming-6.lisp b/Task/Metaprogramming/Common-Lisp/metaprogramming-6.lisp new file mode 100644 index 0000000000..f759b2f231 --- /dev/null +++ b/Task/Metaprogramming/Common-Lisp/metaprogramming-6.lisp @@ -0,0 +1,99 @@ +(defgeneric monadic-map (monad-class function)) + +(defgeneric monadic-join (monad-class container-of-containers &rest additional)) + +(defgeneric monadic-instance (monad-class-name)) + +(defmacro comprehend (monad-instance expr &rest clauses) + (let ((monad-var (gensym "CLASS-"))) + (cond + ((null clauses) `(multiple-value-call #'monadic-unit + ,monad-instance ,expr)) + ((rest clauses) `(let ((,monad-var ,monad-instance)) + (multiple-value-call #'monadic-join ,monad-var + (comprehend ,monad-var + (comprehend ,monad-var ,expr ,@(rest clauses)) + ,(first clauses))))) + (t (destructuring-bind (var &rest container-exprs) (first clauses) + (cond + ((and var (symbolp var)) + `(funcall (monadic-map ,monad-instance (lambda (,var) ,expr)) + ,(first container-exprs))) + ((and (consp var) (every #'symbolp var)) + `(multiple-value-call (monadic-map ,monad-instance + (lambda (,@var) ,expr)) + ,@container-exprs)) + (t (error "COMPREHEND: bad variable specification: ~s" vars)))))))) + +(defmacro define-monad (class-name + &key comprehension + (monad-param (gensym "MONAD-")) + bases slots initargs + ((:map ((map-param) + &body map-body))) + ((:join ((join-param + &optional + (j-rest-kw '&rest) + (j-rest (gensym "JOIN-REST-"))) + &body join-body))) + ((:unit ((unit-param + &optional + (u-rest-kw '&rest) + (u-rest (gensym "UNIT-REST-"))) + &body unit-body)))) + `(progn + (defclass ,class-name ,bases ,slots) + (defmethod monadic-instance ((monad (eql ',class-name))) + (load-time-value (make-instance ',class-name ,@initargs))) + (defmethod monadic-map ((,monad-param ,class-name) ,map-param) + (declare (ignorable ,monad-param)) + ,@map-body) + (defmethod monadic-join ((,monad-param ,class-name) + ,join-param &rest ,j-rest) + (declare (ignorable ,monad-param ,j-rest)) + ,@join-body) + (defmethod monadic-unit ((,monad-param ,class-name) + ,unit-param &rest ,u-rest) + (declare (ignorable ,monad-param ,u-rest)) + ,@unit-body) + ,@(if comprehension + `((defmacro ,comprehension (expr &rest clauses) + `(comprehend (monadic-instance ',',class-name) + ,expr ,@clauses)))))) + +(defmethod monadic-map ((monad symbol) function) + (monadic-map (monadic-instance monad) function)) + +(defmethod monadic-join ((monad symbol) container-of-containers &rest rest) + (apply #'monadic-join (monadic-instance monad) container-of-containers rest)) + +(defmethod monadic-unit ((monad symbol) element &rest rest) + (apply #'monadic-unit (monadic-instance monad) element rest)) + +(define-monad list-monad + :comprehension list-comp + :map ((function) (lambda (container) (mapcar function container))) + :join ((list-of-lists) (reduce #'append list-of-lists)) + :unit ((element) (list element))) + +(define-monad identity-monad + :comprehension identity-comp + :map ((f) f) + :join ((x &rest rest) (apply #'values x rest)) + :unit ((x &rest rest) (apply #'values x rest))) + +(define-monad state-xform-monad + :comprehension state-xform-comp + :map ((f) + (lambda (xformer) + (lambda (s) + (identity-comp (values (funcall f x) new-state) + ((x new-state) (funcall xformer s)))))) + :join ((nested-xformer) + (lambda (s) + (identity-comp (values x new-state) + ((embedded-xformer intermediate-state) + (funcall nested-xformer s)) + ((x new-state) + (funcall embedded-xformer intermediate-state))))) + :unit ((x) (lambda (s) (values x s)))) diff --git a/Task/Metaprogramming/TXR/metaprogramming.txr b/Task/Metaprogramming/TXR/metaprogramming.txr new file mode 100644 index 0000000000..be385c6f73 --- /dev/null +++ b/Task/Metaprogramming/TXR/metaprogramming.txr @@ -0,0 +1,27 @@ +@(do + (defmacro while ((condition : result) . body) + (let ((cblk (gensym "cnt-blk-")) + (bblk (gensym "brk-blk-"))) + ^(macrolet ((break (value) ^(return-from ,',bblk ,value))) + (symacrolet ((break (return-from ,bblk)) + (continue (return-from ,cblk))) + (block ,bblk + (for () (,condition ,result) () + (block ,cblk ,*body))))))) + + (let ((i 0)) + (while ((< i 100)) + (if (< (inc i) 20) + continue) + (if (> i 30) + break) + (prinl i))) + + (prinl + (sys:expand + '(while ((< i 100)) + (if (< (inc i) 20) + continue) + (if (> i 30) + break) + (prinl i))))) diff --git a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test.erl b/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test.erl index bd30e00011..2873ce9c57 100644 --- a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test.erl +++ b/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test.erl @@ -1,78 +1,90 @@ -module(miller_rabin). --compile([export_all]). +-export([is_prime/1, power/2]). -basis(N) when N>2 -> - 1 + random:uniform(N-2). +is_prime(1) -> false; +is_prime(2) -> true; +is_prime(3) -> true; +is_prime(N) when N > 3, ((N rem 2) == 0) -> false; +is_prime(N) when ((N rem 2) ==1), N < 341550071728321 -> + is_mr_prime(N, proving_bases(N)); +is_prime(N) when ((N rem 2) == 1) -> + is_mr_prime(N, random_bases(N, 100)). -find_ds(D, S) -> - case D rem 2 == 0 of - true -> - find_ds(trunc(D/2), S+1); - false -> - {D, S} - end. - -find_ds(N) -> - find_ds(N-1, 0). - -pow_mod(B, E, M) -> - case E of - 0 -> 1; - _ -> case trunc(E) rem 2 == 0 of - true -> trunc(math:pow(pow_mod(B, trunc(E/2), M), 2)) rem M; - false -> trunc(B*pow_mod(B, E-1, M)) rem M - end - end. - -mr_series(N, A, D, S) when N rem 2 == 1 -> - Js = lists:seq(0, S), - lists:map(fun(J) -> pow_mod(A, math:pow(2, J)*D, N) end, Js). - -is_mr_prime(N, As) when N>2, N rem 2 == 1 -> - {D, S} = find_ds(N), - not lists:any(fun(A) -> - case mr_series(N, A, D, S) of - [1|_] -> false; - L -> not lists:member(N-1, L) - end - end, - As). proving_bases(N) when N < 1373653 -> - [2, 3]; + [2, 3]; +proving_bases(N) when N < 9080191 -> + [31, 73]; proving_bases(N) when N < 25326001 -> - [2, 3, 5]; -proving_bases(N) when N < 25000000000 -> - [2, 3, 5, 7]; -proving_bases(N) when N < 2152302898747-> - [2, 3, 5, 7, 11]; -proving_bases(N) when N < 341550071728321 -> + [2, 3, 5]; +proving_bases(N) when N < 3215031751 -> + [2, 3, 5, 7]; +proving_bases(N) when N < 4759123141 -> + [2, 7, 61]; +proving_bases(N) when N < 1122004669633 -> + [2, 13, 23, 1662803]; +proving_bases(N) when N < 2152302898747 -> + [2, 3, 5, 7, 11]; +proving_bases(N) when N < 3474749660383 -> [2, 3, 5, 7, 11, 13]; proving_bases(N) when N < 341550071728321 -> [2, 3, 5, 7, 11, 13, 17]. + +is_mr_prime(N, As) when N>2, N rem 2 == 1 -> + {D, S} = find_ds(N), + %% this is a test for compositeness; the two case patterns disprove + %% compositeness. + not lists:any(fun(A) -> + case mr_series(N, A, D, S) of + [1|_] -> false; % first elem of list = 1 + L -> not lists:member(N-1, L) % some elem of list = N-1 + end + end, + As). + + +find_ds(N) -> + find_ds(N-1, 0). + + +find_ds(D, S) -> + case D rem 2 == 0 of + true -> + find_ds(D div 2, S+1); + false -> + {D, S} + end. + + +mr_series(N, A, D, S) when N rem 2 == 1 -> + Js = lists:seq(0, S), + lists:map(fun(J) -> pow_mod(A, power(2, J)*D, N) end, Js). + + +pow_mod(B, E, M) -> + case E of + 0 -> 1; + _ -> case ((E rem 2) == 0) of + true -> (power(pow_mod(B, (E div 2), M), 2)) rem M; + false -> (B*pow_mod(B, E-1, M)) rem M + end + end. + + random_bases(N, K) -> [basis(N) || _ <- lists:seq(1, K)]. -is_prime(1) -> false; -is_prime(2) -> true; -is_prime(N) when N rem 2 == 0 -> false; -is_prime(N) when N < 341550071728321 -> - is_mr_prime(N, proving_bases(N)). -is_probable_prime(N) -> - is_mr_prime(N, random_bases(N, 20)). +basis(N) when N>2 -> + 1 + random:uniform(N-3). % random:uniform returns a single random number in range 1 -> N-3, to which is added 1, shifting the range to 2 -> N-2 -first_1000() -> - L = lists:seq(1,1000), - lists:map(fun(X) -> - case is_prime(X) of - true -> - io:format("~w~n", [X]); - false -> - false - end - end, - L), - ok. + +power(B, E) -> + power(B, E, 1). + +power(_, 0, Acc) -> + Acc; +power(B, E, Acc) -> + power(B, E - 1, B * Acc). diff --git a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f b/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f index 635d3aac5a..6039bca6ae 100644 --- a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f +++ b/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f @@ -1,4 +1,4 @@ -module Miller_Rabin + module Miller_Rabin use PrimeDecompose implicit none diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx index 42c663f82e..cfe4f194c6 100644 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx +++ b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx @@ -5,10 +5,10 @@ if limit=='' | limit==',' then limit=1000 /*maybe assume LIMIT default*/ if accur=='' | accur==',' then accur=10 /* " " ACCUR " */ numeric digits max(200,2*limit) /*we're dealing with some biggies*/ tell=accur<0 /*show primes if K is negative.*/ -accur=abs(accur) /*now, make K postive. */ +accur=abs(accur) /*now, make K positive. */ call suspenders /*suspenders now, belt later... */ primePi=# /*save the count of (real) primes*/ -say "They're" primePi 'primes ≤' limit /*might as well crow a wee bit. */ +say "There are" primePi 'primes ≤' limit /*might as well crow a wee bit.*/ say /*nothing wrong with whitespace. */ do a=2 to accur /*(skipping 1) do range of K's.*/ say copies('─',79) /*show separator for the eyeballs*/ @@ -48,7 +48,7 @@ s=0 do r=1 for s-1 x=(x*x) // n - if x==1 then return 0 /*it's definately not prime. */ + if x==1 then return 0 /*it's definitely not prime. */ if x==nL then leave end /*r*/ diff --git a/Task/Minesweeper-game/AutoHotkey/minesweeper-game.ahk b/Task/Minesweeper-game/AutoHotkey/minesweeper-game.ahk new file mode 100644 index 0000000000..4612697535 --- /dev/null +++ b/Task/Minesweeper-game/AutoHotkey/minesweeper-game.ahk @@ -0,0 +1,556 @@ +; Minesweeper.ahk - v1.0.6 +; (c) Dec 28, 2008 by derRaphael +; Licensed under the Terms of EUPL 1.0 +; Modded by Sobriquet and re-licenced as CeCILL v2 +; Modded (again) by Sobriquet and re-licenced as GPL v1.3 + +#NoEnv +#NoTrayIcon +SetBatchLines,-1 +#SingleInstance,Off +/* +[InGameSettings] +*/ +Level =Beginner +Width =9 +Height =9 +MineMax =10 +Marks =1 +Color =1 +Sound =0 +BestTimeBeginner =999 seconds Anonymous +BestTimeIntermediate=999 seconds Anonymous +BestTimeExpert =999 seconds Anonymous +; above settings are accessed as variables AND modified by IniWrite - be careful +BlockSize =16 +Title =Minesweeper +MineCount =0 +mColor =Blue,Green,Red,Purple,Navy,Olive,Maroon,Teal +GameOver =0 +TimePassed =0 + +; Add mines randomly +While (MineCount9 ? Width : 9))*BlockSize+24 " h" Height*BlockSize+68,%Title% +OnMessage(0x53,"WM_HELP") ; invoke Help handling for tooltips +Return ;--------------------------------------------------------; End of auto-execute section +#IfWinActive Minesweeper ahk_class AutoHotkeyGUI ; variable %title% not supported + +StartGame(x,y) { + Global + If (TimePassed) + Return + If (T_x%x%y%y%="M") ; we'll save you this time + { + T_x%x%y%y%:="" ; remove this mine + Loop,% Height + { + y:=A_Index + Loop,% Width + { + x:=A_Index + If ( T_x%x%y%y%!="M") ; add it to first available non-mine square + T_x%x%y%y%:="M" + ,break:=1 + IfEqual,break,1,Break + } + IfEqual,break,1,Break + } + } + Loop,% Height ; iterate over height + { + y:=A_Index + Loop,% Width ; iterate over width + { + x:=A_Index + Gui,Font + If (T_x%x%y%y%="M") { ; check for mine + Gui,Font,s11,WingDings + hColor:="Black" ; set color for text + } Else { + Loop,3 { ; loop over neighbors: three columns vertically + ty:=y-2+A_Index ; calculate top offset + Loop,3 { ; and three horizontally + tx:=x-2+A_Index ; calculate left offset + If (T_x%tx%y%ty%="M") ; no mine and inbound + T_x%x%y%y%++ ; update hint txt + } + } + Gui,Font,s11 Bold,Courier New Bold + If (Color) + Loop,Parse,mColor,`, ; find color + If (T_x%x%y%y% = A_Index) { ; hinttxt to color + hColor:=A_LoopField ; set color for text + Break + } + Else hColor:="Black" + } + Gui,Add,Text,% "c" hColor " Border +Center vT_x" x "y" y ; set color / variable + . " w" BlockSize " h" BlockSize " " (x = 1 ; width / height / if 1st block + ? "x" 12 " y" y*BlockSize+39 ; fix vertical position + : "yp x+0") ; otherwise align to previous box + ,% T_x%x%y%y% ; M is WingDings for mine + GuiControl,Hide,T_x%x%y%y% + } + } + GuiControl,,Timer,% "00" . TimePassed:=1 + SetTimer,UpdateTimer,1000 ; start timer + If (Sound) + SoundPlay,C:\WINDOWS\media\chord.wav +} + +GuiSize: + If (TimePassed) + SetTimer,UpdateTimer,On ; for cheat below +Return + +UpdateTimer: ; timer + GuiControl,,Timer,% (++TimePassed < 999) ? SubStr("00" TimePassed,-2) : 999 + If (Sound) + SoundPlay,C:\WINDOWS\media\chord.wav +Return + +Check(x,y){ + Global + If (GameOver || B_x%x%y%y% != "" ; the game is over / prevent click on flagged squares and already-opened squares + || x<1 || x>Width || y<1 || y>Height) ; do not check neighbor on illegal squares + Return + If (T_x%x%y%y%="") { ; empty field? + CheckNeighbor(x,y) ; uncover it and any neighbours + } Else If (T_x%x%y%y% != "M") { ; no Mine, ok? + GuiControl,Hide,B_x%x%y%y% ; hide covering button + GuiControl,Show,T_x%x%y%y% + B_x%x%y%y%:=1 ; remember we been here + UpdateChecks() + } Else { ; ewww ... it's a mine! + SetTimer,UpdateTimer,Off ; kill timer + GuiControl,,T_x%x%y%y%,N ; set to Jolly Roger=N to mark death location + GuiControl,,NewGame,L ; set Smiley Btn to Frown=L + RevealAll() + If (Sound) ; do we sound? + If (FileExist("C:\Program Files\Microsoft Office\Office12\MEDIA\Explode.wav")) + SoundPlay,C:\Program Files\Microsoft Office\Office12\MEDIA\Explode.wav + Else + SoundPlay,C:\WINDOWS\Media\notify.wav + } +} + +CheckNeighbor(x,y) { ; This function checks neighbours of the clicked + Global ; field and uncovers empty fields plus adjacent hint fields + If (GameOver || B_x%x%y%y%!="") + Return + GuiControl,Hide,B_x%x%y%y% ; uncover it + GuiControl,Show,T_x%x%y%y% + B_x%x%y%y%:=1 ; remember it + UpdateChecks() + If (T_x%x%y%y%!="") ; is neighbour an nonchecked 0 value field? + Return + If (y-1>=1) ; check upper neighbour + CheckNeighbor(x,y-1) + If (y+1<=Height) ; check lower neighbour + CheckNeighbor(x,y+1) + If (x-1>=1) ; check left neighbour + CheckNeighbor(x-1,y) + If (x+1<=Width) ; check right neighbour + CheckNeighbor(x+1,y) + If (x-1>=1 && y-1>=1) ; check corner neighbour + CheckNeighbor(x-1,y-1) + If (x-1>=1 && y+1<=Height) ; check corner neighbour + CheckNeighbor(x-1,y+1) + If (x+1<=Width && y-1>=1) ; check corner neighbour + CheckNeighbor(x+1,y-1) + If (x+1<=Width && y+1<=Height) ; check corner neighbour + CheckNeighbor(x+1,y+1) +} + +UpdateChecks() { + Global + MineCount:=MineMax, Die1:=Die2:=0 + Loop,% Height + { + y:=A_Index + Loop,% Width + { + x:=A_Index + If (B_x%x%y%y%="O") + MineCount-- + If (T_x%x%y%y%="M" && B_x%x%y%y%!="O") || (T_x%x%y%y%!="M" && B_x%x%y%y%="O") + Die1++ + If (B_x%x%y%y%="" && T_x%x%y%y%!="M") + Die2++ + } + } + GuiControl,,MineCount,% SubStr("00" MineCount,-2) + If (Die1 && Die2) + Return ; only get past here if flags+untouched squares match mines perfectly + SetTimer,UpdateTimer,Off ; game won - kill timer + GuiControl,,NewGame,J ; set Smiley Btn to Smile=J + RevealAll() + If (Sound) ; play sound + SoundPlay,C:\WINDOWS\Media\tada.wav + If (level!="Custom" && TimePassed < SubStr(BestTime%level%,1,InStr(BestTime%level%," ")-1) ) + { + InputBox,name,Congratulations!,You have the fastest time`nfor level %level%.`nPlease enter your name.`n,,,,,,,,%A_UserName% + If (name && !ErrorLevel) + { + BestTime%level%:=%TimePassed% seconds %name% + IniWrite,BestTime%level%,%A_ScriptFullPath%,InGameSettings,BestTime%level% + } + } +} + +RevealAll(){ + Global + Loop,% Height ; uncover all + { + y:=A_Index + Loop,% Width + { + x:=A_Index + If(T_x%x%y%y%="M") + { + GuiControl,Hide,B_x%x%y%y% + GuiControl,Show,T_x%x%y%y% + } + } + } + GameOver:=True ; remember the game's over to block clicks +} + +~F2::NewGame() +NewGame(){ +NewGame: + Reload + ExitApp +} + +LevelMenu: + If (A_ThisMenuItem="&Beginner") + level:="Beginner", Width:=9, Height:=9, MineMax:=10 + Else If (A_ThisMenuItem="&Intermediate") + level:="Intermediate", Width:=16, Height:=16, MineMax:=40 + Else If (A_ThisMenuItem="&Expert") + level:="Expert", Width:=30, Height:=16, MineMax:=99 + IniWrite,%level%,%A_ScriptFullPath%,InGameSettings,level + IniWrite,%Width%,%A_ScriptFullPath%,InGameSettings,Width + IniWrite,%Height%,%A_ScriptFullPath%,InGameSettings,Height + IniWrite,%MineMax%,%A_ScriptFullPath%,InGameSettings,MineMax + IniWrite,%Marks%,%A_ScriptFullPath%,InGameSettings,Marks + IniWrite,%Sound%,%A_ScriptFullPath%,InGameSettings,Sound + IniWrite,%Color%,%A_ScriptFullPath%,InGameSettings,Color + NewGame() +Return + +CustomMenu: ; label for setting window + Gui,2:+Owner1 ; make Gui#2 owned by gameWindow + Gui,2:Default ; set to default + Gui,1:+Disabled ; disable gameWindow + Gui,-MinimizeBox +E0x00000400 + Gui,Add,Text,x15 y36 w38 h16,&Height: + Gui,Add,Edit,Number x60 y33 w38 h20 vHeight HwndHwndHeight,%Height% ; use inGame settings + Gui,Add,Text,x15 y60 w38 h16,&Width: + Gui,Add,Edit,Number x60 y57 w38 h20 vWidth HwndHwndWidth,%Width% + Gui,Add,Text,x15 y85 w38 h16,&Mines: + Gui,Add,Edit,Number x60 y81 w38 h20 vMineMax HwndHwndMines,%MineMax% + Gui,Add,Button,x120 y33 w60 h26 Default HwndHwndOK,OK + Gui,Add,Button,x120 y75 w60 h26 g2GuiClose HwndHwndCancel,Cancel ; jump directly to 2GuiClose label + Gui,Show,w195 h138,Custom Field +Return + +2ButtonOK: ; label for OK button in settings window + Gui,2:Submit,NoHide + level:="Custom" + MineMax:=MineMax<10 ? 10 : MineMax>((Width-1)*(Height-1)) ? ((Width-1)*(Height-1)) : MineMax + Width:=Width<9 ? 9 : Width>30 ? 30 : Width + Height:=Height<9 ? 9 : Height>24 ? 24 : Height + GoSub,LevelMenu +Return + +2GuiClose: +2GuiEscape: + Gui,1:-Disabled ; reset GUI status and destroy setting window + Gui,1:Default + Gui,2:Destroy +Return + +ToggleMenu: + Toggle:=RegExReplace(RegExReplace(A_ThisMenuItem,"\s.*"),"&") + temp:=%Toggle% + %Toggle%:=!%Toggle% + Menu,GameMenu,ToggleCheck,%A_ThisMenuItem% + IniWrite,% %Toggle%,%A_ScriptFullPath%,InGameSettings,%Toggle% +Return + +BestTimesMenu: + Gui,3:+Owner1 + Gui,3:Default + Gui,1:+Disabled + Gui,-MinimizeBox +E0x00000400 + Gui,Add,Text,x15 y22 w250 vBestTimeBeginner HwndHwndBTB,Beginner: %BestTimeBeginner% + Gui,Add,Text,x15 y38 w250 vBestTimeIntermediate HwndHwndBTI,Intermediate: %BestTimeIntermediate% + Gui,Add,Text,x15 y54 w250 vBestTimeExpert HwndHwndBTE,Expert: %BestTimeExpert% + Gui,Add,Button,x38 y89 w75 h20 HwndHwndRS,&Reset Scores + Gui,Add,Button,x173 y89 w45 h20 Default HwndHwndOK,OK + Gui,Show,w255 h122,Fastest Mine Sweepers +Return + +3ButtonResetScores: + BestTimeBeginner =999 seconds Anonymous + BestTimeIntermediate=999 seconds Anonymous + BestTimeExpert =999 seconds Anonymous + GuiControl,,BestTimeBeginner,Beginner: %BestTimeBeginner%`nIntermediate: %BestTimeIntermediate%`nExpert: %BestTimeExpert% + GuiControl,,BestTimeIntermediate,Intermediate: %BestTimeIntermediate%`nExpert: %BestTimeExpert% + GuiControl,,BestTimeExpert,Expert: %BestTimeExpert% + IniWrite,%BestTimeBeginner%,%A_ScriptFullPath%,InGameSettings,BestTimeBeginner + IniWrite,%BestTimeIntermediate%,%A_ScriptFullPath%,InGameSettings,BestTimeIntermediate + IniWrite,%BestTimeExpert%,%A_ScriptFullPath%,InGameSettings,BestTimeExpert +3GuiEscape: ; fall through: +3GuiClose: +3ButtonOK: + Gui,1:-Disabled ; reset GUI status and destroy setting window + Gui,1:Default + Gui,3:Destroy +Return + +^q:: +GuiClose: + ExitApp + +HelpMenu: + ;Run C:\WINDOWS\Help\winmine.chm +Return + +AboutMenu: + Msgbox,64,About Minesweeper,AutoHotkey (r) Minesweeper`nVersion 1.0.6`nCopyright (c) 2014`nby derRaphael and Sobriquet +Return + +~LButton:: +~!LButton:: +~^LButton:: +~#LButton:: + Tooltip + If (GetKeyState("RButton","P")) + Return + If A_OSVersion not in WIN_2003,WIN_XP,WIN_2000,WIN_NT4,WIN_95,WIN_98,WIN_ME + If(A_PriorHotkey="~*LButton Up" && A_TimeSincePriorHotkey<100) + GoTo,*MButton Up ; invoke MButton handling for autofill on left double-click in vista+ + If (GameOver) + Return + MouseGetPos,,y + If (y>47) + GuiControl,,NewGame,m +Return + +~*LButton Up:: + If (GetKeyState("RButton","P")) + GoTo,*MButton Up + If (GameOver) + Return + GuiControl,,NewGame,K + control:=GetControlFromClassNN(), NumX:=NumY:=0 + RegExMatch(control,"Si)T_x(?P\d+)y(?P\d+)",Num) ; get Position + StartGame(NumX,NumY) ; start game if neccessary + Check(NumX,NumY) +Return + ++LButton:: +*MButton:: + Tooltip + If (GameOver) + Return + MouseGetPos,,y + If (y>47) + GuiControl,,NewGame,m +Return + ++LButton Up:: +*MButton Up:: + If (GameOver) + Return + GuiControl,,NewGame,K + StartGame(NumX,NumY) ; start game if neccessary + If (GetKeyState("Esc","P")) + { + SetTimer,UpdateTimer,Off + Return + } + control:=GetControlFromClassNN(), NumX:=NumY:=0 + RegExMatch(control,"Si)T_x(?P\d+)y(?P\d+)",Num) + If ( !NumX || !NumY || B_x%NumX%y%NumY%!=1) + Return + temp:=0 + Loop,3 { ; loop over neighbors: three columns vertically + ty:=NumY-2+A_Index ; calculate top offset + Loop,3 { ; and three horizontally + tx:=NumX-2+A_Index ; calculate left offset + If (B_x%tx%y%ty% = "O") ; count number of marked mines around position + temp++ + } + } + If (temp=T_x%NumX%y%NumY%) + Loop,3 { ; loop over neighbors: three columns vertically + ty:=NumY-2+A_Index ; calculate top offset + Loop,3 { ; and three horizontally + tx:=NumX-2+A_Index ; calculate left offset + Check(tx,ty) ; simulate user clicking on each surrounding square + } + } +Return + +~*RButton:: + If (GameOver || GetKeyState("LButton","P")) + Return + control:=GetControlFromClassNN(), NumX:=NumY:=0 + RegExMatch(control,"Si)T_x(?P\d+)y(?P\d+)",Num) ; grab 'em + If ( !NumX || !NumY || B_x%NumX%y%NumY%=1) + Return + StartGame(NumX,NumY) ; start counter if neccessary + B_x%NumX%y%NumY%:=(B_x%NumX%y%NumY%="" ? "O" : (B_x%NumX%y%NumY%="O" && Marks=1 ? "I" : "")) + GuiControl,,B_x%NumX%y%NumY%,% B_x%NumX%y%NumY% + UpdateChecks() +Return + +~*RButton Up:: + If (GetKeyState("LButton","P")) + GoTo,*MButton Up +Return + +GetControlFromClassNN(){ + Global width + MouseGetPos,,,,control + If (SubStr(control,1,6)="Button") + NumX:=mod(SubStr(control,7)-2,width)+1,NumY:=(SubStr(control,7)-2)//width+1 + Else If (SubStr(control,1,6)="Static") + NumX:=mod(SubStr(control,7)-3,width)+1,NumY:=(SubStr(control,7)-3)//width+1 + Return "T_x" NumX "y" NumY +} + +WM_HELP(_,_lphi) +{ + Global + hItemHandle:=NumGet(_lphi+0,12) + If (hItemHandle=HwndBTB || hItemHandle=HwndBTI || hItemHandle=HwndBTE) + ToolTip Displays a player's best game time`, and the player's name`, for`neach level of play: Beginner`, Intermediate`, and Expert. + Else If (hItemHandle=HwndRS) + ToolTip Click to clear the current high scores. + Else If (hItemHandle=HwndOK) + ToolTip Closes the dialog box and saves any changes you`nhave made. + Else If (hItemHandle=HwndCancel) + ToolTip Closes the dialog box without saving any changes you have`nmade. + Else If (hItemHandle=HwndHeight) + ToolTip Specifies the number of vertical squares on the`nplaying field. + Else If (hItemHandle=HwndWidth) + ToolTip Specifies the number of horizontal squares on the`nplaying field. + Else If (hItemHandle=HwndMines) + ToolTip Specifies the number of mines to be placed on the`nplaying field. +} + +:*?B0:xyzzy:: ; cheat + KeyWait,Shift,D T1 ; 1 sec grace period to press shift + If (ErrorLevel) + Return + While,GetKeyState("Shift","P") + { + control:=GetControlFromClassNN() + If (%control% = "M") + SplashImage,,B X0 Y0 W1 H1 CW000000 ; black pixel + Else + SplashImage,,B X0 Y0 W1 H1 CWFFFFFF ; white pixel + Sleep 100 + } + SplashImage,Off +Return + +/* + Version History +================= +Dec 29, 2008 +1.0.0 Initial Release +1.0.1 BugFix + - Game Restart Issues mentioned by Frankie + - Guess count fixup I + - Startbehaviour of game (time didnt start when 1st click was RMB Guess) +Dec 30, 2008 +1.0.2 BugFix + - Field Size Control vs Max MineCount / mentioned by °digit° / IsNull +1.0.3 BugFix + - Guess count fixup II mentioned by °digit° + - Corrected count when 'guessed' field uncovered +Dec 31, 2008 +1.0.4 BugFix + - Fix of Min Field & MineSettings +Mar 7, 2014 +1.0.5 AddFeatures + - Make appearance more like original + - Make first click always safe + - Re-license as CeCILL v2 +Mar 8, 2014 +1.0.6 AddFeatures + - Add cheat code + - Add middle-button shortcut + - Re-license as GPL 1.3 +*/ diff --git a/Task/Minesweeper-game/Ruby/minesweeper-game.rb b/Task/Minesweeper-game/Ruby/minesweeper-game.rb index 0d415b94c8..8736d8c05a 100644 --- a/Task/Minesweeper-game/Ruby/minesweeper-game.rb +++ b/Task/Minesweeper-game/Ruby/minesweeper-game.rb @@ -50,70 +50,53 @@ NUM_MINES = (WIDTH * HEIGHT * PCT).round def create_mines sx, sy arr = Array.new(WIDTH) { Array.new(HEIGHT, false) } - NUM_MINES.times do - loop do - x, y = rand(WIDTH), rand(HEIGHT) - - # place it if it isn't at (sx, sy) and we haven't already placed a mine - arr[x][y] = true and break if !arr[x][y] and (x != sx or y != sy) - end + x, y = rand(WIDTH), rand(HEIGHT) + # place it if it isn't at (sx, sy) and we haven't already placed a mine + redo if arr[x][y] or (x == sx and y == sy) + arr[x][y] = true end - arr end def num_marks - $screen.inject(0) { |sum, row| - sum + row.count("?") - } + $screen.inject(0) { |sum, row| sum + row.count("?") } end def show_grid revealed = false if revealed - puts $mines.transpose.map { |row| row.map { |cell| cell ? "*" : " " }.join }.join("\n") + puts $mines.transpose.map { |row| row.map { |cell| cell ? "*" : " " }.join(" ") } else puts "Grid has #{NUM_MINES} mines, #{num_marks} marked." - puts $screen.transpose.map(&:join).join("\n") + puts $screen.transpose.map{ |row| row.join(" ") } end end +SURROUND = [-1,0,1].product([-1,0,1]) - [[0,0]] # surround 8 def surrounding x, y # apply the passed block to each spot around (x, y) - (-1..1).each do |dx| - (-1..1).each do |dy| - # don't check if we're out of bounds, or at (0,0) - next if !(0...WIDTH).include?(x + dx) or !(0...HEIGHT).include?(y + dy) - next if dx == 0 and dy == 0 - - yield(dx, dy) - end + SURROUND.each do |dx, dy| + # don't check if we're out of bounds, or at (0,0) + yield(x+dx, y+dy) if (0...WIDTH).cover?(x+dx) and (0...HEIGHT).cover?(y+dy) end end def clear_space x, y return unless $screen[x][y] == "." - # check nearby spaces count = 0 - - surrounding(x, y) do |dx, dy| - count += 1 if $mines[x + dx][y + dy] - end - + surrounding(x, y) { |px, py| count += 1 if $mines[px][py] } if count == 0 $screen[x][y] = " " - surrounding(x, y) do |dx, dy| - clear_space x + dx, y + dy - end + surrounding(x, y) { |px, py| clear_space px, py } else $screen[x][y] = count.to_s end end def victory? - return false if $mines == nil # first one, don't need to check - + return false if $mines.nil? # first one, don't need to check + return false if num_marks != NUM_MINES mines_left = NUM_MINES WIDTH.times do |x| HEIGHT.times do |y| @@ -124,6 +107,11 @@ def victory? mines_left == 0 end +def check_input x, y + x, y = x.to_i - 1, y.to_i - 1 + [x, y] if (0...WIDTH).cover?(x) and (0...HEIGHT).cover?(y) +end + $mines = nil $screen = Array.new(WIDTH) { Array.new(HEIGHT, ".") } @@ -138,14 +126,15 @@ loop do when "quit", "exit", "x", "q" puts "Bye!" break - when /^m (\d) (\d)$/ + when /^m (\d+) (\d+)$/ # mark this cell - x, y = $1.to_i - 1, $2.to_i - 1 - + x, y = check_input $1, $2 + next unless x if $screen[x][y] == "." # mark it $screen[x][y] = "?" if victory? + show_grid puts "You win!" break end @@ -154,12 +143,12 @@ loop do $screen[x][y] = "." end show_grid - when /^c (\d) (\d)$/ - x, y = $1.to_i - 1, $2.to_i - 1 + when /^c (\d+) (\d+)$/ + x, y = check_input $1, $2 + next unless x $mines ||= create_mines(x, y) if $mines[x][y] puts "You hit a mine!" - $screen[x][y] = "*" show_grid true break else diff --git a/Task/Modular-exponentiation/AutoHotkey/modular-exponentiation.ahk b/Task/Modular-exponentiation/AutoHotkey/modular-exponentiation.ahk new file mode 100644 index 0000000000..37623e12ad --- /dev/null +++ b/Task/Modular-exponentiation/AutoHotkey/modular-exponentiation.ahk @@ -0,0 +1,26 @@ +#NoEnv +#SingleInstance, Force +SetBatchLines, -1 +#Include mpl.ahk + + MP_SET(base, "2988348162058574136915891421498819466320163312926952423791023078876139") +, MP_SET(exponent, "2351399303373464486466122544523690094744975233415544072992656881240319") +, MP_SET(modulus, "10000000000000000000000000000000000000000") + +, NumGet(exponent,0,"Int") = -1 ? return : "" +, MP_SET(result, "1") +, MP_SET(TWO, "2") +while !MP_IS0(exponent) + MP_DIV(q, r, exponent, TWO) + , (MP_DEC(r) = 1 + ? (MP_MUL(temp, result, base) + , MP_DIV(q, result, temp, modulus)) + : "") + , MP_DIV(q, r, exponent, TWO) + , MP_CPY(exponent, q) + , MP_CPY(base1, base) + , MP_MUL(base2, base1, base) + , MP_DIV(q, base, base2, modulus) + +msgbox % MP_DEC(result) +Return diff --git a/Task/Modular-exponentiation/Clojure/modular-exponentiation.clj b/Task/Modular-exponentiation/Clojure/modular-exponentiation.clj new file mode 100644 index 0000000000..fce0d2e59f --- /dev/null +++ b/Task/Modular-exponentiation/Clojure/modular-exponentiation.clj @@ -0,0 +1,6 @@ +(defn powerMod "modular exponentiation" [b e m] + (defn m* [p q] (mod (* p q) m)) + (loop [b b, e e, x 1] + (if (zero? e) x + (if (even? e) (recur (m* b b) (/ e 2) x) + (recur (m* b b) (quot e 2) (m* b x)))))) diff --git a/Task/Modular-exponentiation/Groovy/modular-exponentiation.groovy b/Task/Modular-exponentiation/Groovy/modular-exponentiation.groovy new file mode 100644 index 0000000000..778b5dc811 --- /dev/null +++ b/Task/Modular-exponentiation/Groovy/modular-exponentiation.groovy @@ -0,0 +1,3 @@ +println 2988348162058574136915891421498819466320163312926952423791023078876139.modPow( + 2351399303373464486466122544523690094744975233415544072992656881240319, + 10000000000000000000000000000000000000000) diff --git a/Task/Modular-exponentiation/Scheme/modular-exponentiation.ss b/Task/Modular-exponentiation/Scheme/modular-exponentiation.ss new file mode 100644 index 0000000000..43bc4ac6e2 --- /dev/null +++ b/Task/Modular-exponentiation/Scheme/modular-exponentiation.ss @@ -0,0 +1,15 @@ +(define (square n) + (* n n)) + +(define (mod-exp a n mod) + (cond ((= n 0) 1) + ((even? n) + (remainder (square (mod-exp a (/ n 2) mod)) + mod)) + (else (remainder (* a (mod-exp a (- n 1) mod)) + mod)))) + +(define result + (mod-exp 2988348162058574136915891421498819466320163312926952423791023078876139 + 2351399303373464486466122544523690094744975233415544072992656881240319 + (expt 10 40))) diff --git a/Task/Modular-exponentiation/TXR/modular-exponentiation.txr b/Task/Modular-exponentiation/TXR/modular-exponentiation.txr index 767754f98f..a643744c16 100644 --- a/Task/Modular-exponentiation/TXR/modular-exponentiation.txr +++ b/Task/Modular-exponentiation/TXR/modular-exponentiation.txr @@ -1,3 +1,4 @@ -@(bind result @(exptmod 2988348162058574136915891421498819466320163312926952423791023078876139 - 2351399303373464486466122544523690094744975233415544072992656881240319 - (expt 10 40))) +$ txr -p '(exptmod 2988348162058574136915891421498819466320163312926952423791023078876139 + 2351399303373464486466122544523690094744975233415544072992656881240319 + (expt 10 40)))' +1527229998585248450016808958343740453059 diff --git a/Task/Modular-inverse/00DESCRIPTION b/Task/Modular-inverse/00DESCRIPTION index d080923ea6..c9071c1a1a 100644 --- a/Task/Modular-inverse/00DESCRIPTION +++ b/Task/Modular-inverse/00DESCRIPTION @@ -2,7 +2,7 @@ From [http://en.wikipedia.org/wiki/Modular_multiplicative_inverse Wikipedia]: :In [[wp:modular arithmetic|modular arithmetic]], the '''modular multiplicative inverse''' of an [[integer]] ''a'' [[wp:modular arithmetic|modulo]] ''m'' is an integer ''x'' such that -::a^{-1} \equiv x \pmod{m}. +::a\,x \equiv 1 \pmod{m}. Or in other words, such that: :\exists k \in\mathbf{Z},\qquad a\, x = 1 + k\,m diff --git a/Task/Modular-inverse/AutoHotkey/modular-inverse.ahk b/Task/Modular-inverse/AutoHotkey/modular-inverse.ahk new file mode 100644 index 0000000000..a60d0e716c --- /dev/null +++ b/Task/Modular-inverse/AutoHotkey/modular-inverse.ahk @@ -0,0 +1,19 @@ +MsgBox, % ModInv(42, 2017) + +ModInv(a, b) { + if (b = 1) + return 1 + b0 := b, x0 := 0, x1 :=1 + while (a > 1) { + q := a // b + , t := b + , b := Mod(a, b) + , a := t + , t := x0 + , x0 := x1 - q * x0 + , x1 := t + } + if (x1 < 0) + x1 += b0 + return x1 +} diff --git a/Task/Modular-inverse/C/modular-inverse.c b/Task/Modular-inverse/C/modular-inverse.c index b9fb3014a0..eb2ef6b5a0 100644 --- a/Task/Modular-inverse/C/modular-inverse.c +++ b/Task/Modular-inverse/C/modular-inverse.c @@ -1,20 +1,18 @@ -#include - -int mul_inv(int a, int b) -{ - int b0 = b, t, q; - int x0 = 0, x1 = 1; - if (b == 1) return 1; - while (a > 1) { - q = a / b; - t = b, b = a % b, a = t; - t = x0, x0 = x1 - q * x0, x1 = t; - } - if (x1 < 0) x1 += b0; - return x1; +#include +int modularinverse( int a, int b){ + int c=b/a,x=0; + do{ + if((a) { + args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } +} + +fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } + .fold("") { (acc, ch) -> acc + morseCode[ch]!! } + +fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } + +fun beep(durationInMs: Int) { + val soundBuffer = ByteArray(durationInMs * 8) + for ((i, elem) in soundBuffer.withIndices()) { + soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() + } + + val audioFormat = AudioFormat(/*sampleRate*/ 8000F, + /*sampleSizeInBits*/ 8, + /*channels*/ 1, + /*signed*/ true, + /*bigEndian*/ false) + with (AudioSystem.getSourceDataLine(audioFormat)!!) { + open(audioFormat) + + start() + write(soundBuffer, 0, soundBuffer.size) + drain() + + close() + } +} diff --git a/Task/Mouse-position/Rust/mouse-position.rust b/Task/Mouse-position/Rust/mouse-position.rust index e5f8d43c2f..c14a9d6be1 100644 --- a/Task/Mouse-position/Rust/mouse-position.rust +++ b/Task/Mouse-position/Rust/mouse-position.rust @@ -1,9 +1,8 @@ -// rust 0.9-pre +// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800) -use std::libc::types::os::arch::extra::{BOOL, HANDLE}; +use std::libc::{BOOL, HANDLE, LONG}; use std::ptr::mut_null; -type LONG = i32; type HWND = HANDLE; #[deriving(Eq)] @@ -14,9 +13,9 @@ struct POINT { #[link_name = "user32"] extern "system" { - pub fn GetCursorPos(lpPoint:&mut POINT) -> BOOL; - pub fn GetForegroundWindow() -> HWND; - pub fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT); + fn GetCursorPos(lpPoint:&mut POINT) -> BOOL; + fn GetForegroundWindow() -> HWND; + fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT); } fn main() { diff --git a/Task/Multifactorial/AutoHotkey/multifactorial.ahk b/Task/Multifactorial/AutoHotkey/multifactorial.ahk new file mode 100644 index 0000000000..684d43e503 --- /dev/null +++ b/Task/Multifactorial/AutoHotkey/multifactorial.ahk @@ -0,0 +1,13 @@ +Loop, 5 { + Output .= "Degree " (i := A_Index) ": " + Loop, 10 + Output .= MultiFact(A_Index, i) (A_Index = 10 ? "`n" : ", ") +} +MsgBox, % Output + +MultiFact(n, d) { + Result := n + while 1 < n -= d + Result *= n + return, Result +} diff --git a/Task/Multiplication-tables/PicoLisp/multiplication-tables.l b/Task/Multiplication-tables/PicoLisp/multiplication-tables.l index e8af53e427..158e991b39 100644 --- a/Task/Multiplication-tables/PicoLisp/multiplication-tables.l +++ b/Task/Multiplication-tables/PicoLisp/multiplication-tables.l @@ -1,4 +1,4 @@ -(de mulTable (N) +sp>(de mulTable (N) (space 4) (for X N (prin (align 4 X)) ) diff --git a/Task/Multisplit/AutoHotkey/multisplit.ahk b/Task/Multisplit/AutoHotkey/multisplit.ahk new file mode 100644 index 0000000000..da76c2b5c7 --- /dev/null +++ b/Task/Multisplit/AutoHotkey/multisplit.ahk @@ -0,0 +1,9 @@ +Str := "a!===b=!=c" +Sep := ["==","!=", "="] +Res := StrSplit(Str, Sep) +for k, v in Res + Out .= (Out?",":"") v +MsgBox % Out +for k, v in Sep + N .= (N?"|":"") "\Q" v "\E" +MsgBox % RegExReplace(str, "(.*?)(" N ")", "$1 {$2}") diff --git a/Task/Multisplit/Perl/multisplit.pl b/Task/Multisplit/Perl/multisplit.pl index 06219de91f..9c6b76d117 100644 --- a/Task/Multisplit/Perl/multisplit.pl +++ b/Task/Multisplit/Perl/multisplit.pl @@ -1,11 +1,11 @@ -#!/usr/bin/perl -w -use strict ; sub multisplit { - my ( $string , $pattern ) = @_ ; - split( /($pattern)/, $string, -1 ) ; + my ($sep, $string, %opt) = @_ ; + $sep = join '|', map quotemeta($_), @$sep; + $sep = "($sep)" if $opt{keep_separators}; + split /$sep/, $string, -1; } -my $phrase = "a!===b=!=c" ; -my $pattern = "==|!=|=" ; -print "$_ ," foreach multisplit( $phrase , $pattern ) ; -print "\n" ; +print "'$_' " for multisplit ['==','!=','='], "a!===b=!=c"; +print "\n"; +print "'$_' " for multisplit ['==','!=','='], "a!===b=!=c", keep_separators => 1; +print "\n"; diff --git a/Task/Multisplit/TXR/multisplit.txr b/Task/Multisplit/TXR/multisplit-1.txr similarity index 100% rename from Task/Multisplit/TXR/multisplit.txr rename to Task/Multisplit/TXR/multisplit-1.txr diff --git a/Task/Multisplit/TXR/multisplit-2.txr b/Task/Multisplit/TXR/multisplit-2.txr new file mode 100644 index 0000000000..37489a4a06 --- /dev/null +++ b/Task/Multisplit/TXR/multisplit-2.txr @@ -0,0 +1,2 @@ +$ txr -p '(tok-str "a!===b=!=c" #/==|!=|=/ t)' +("a" "!=" "" "==" "b" "=" "" "!=" "c") diff --git a/Task/Mutual-recursion/Ada/mutual-recursion.ada b/Task/Mutual-recursion/Ada/mutual-recursion-1.ada similarity index 100% rename from Task/Mutual-recursion/Ada/mutual-recursion.ada rename to Task/Mutual-recursion/Ada/mutual-recursion-1.ada diff --git a/Task/Mutual-recursion/Ada/mutual-recursion-2.ada b/Task/Mutual-recursion/Ada/mutual-recursion-2.ada new file mode 100644 index 0000000000..af44bd0d84 --- /dev/null +++ b/Task/Mutual-recursion/Ada/mutual-recursion-2.ada @@ -0,0 +1,20 @@ +with Ada.Text_Io; use Ada.Text_Io; +procedure Mutual_Recursion is + function M(N: Natural) return Natural; + function F(N: Natural) return Natural; + + function M(N: Natural) return Natural is + (if N = 0 then 0 else N – F(M(N–1))); + + function F(N: Natural) return Natural is + (if N =0 then 1 else N – M(F(N–1))); +begin + for I in 0..19 loop + Put_Line(Integer'Image(F(I))); + end loop; + New_Line; + for I in 0..19 loop + Put_Line(Integer'Image(M(I))); + end loop; + +end Mutual_recursion; diff --git a/Task/Mutual-recursion/D/mutual-recursion.d b/Task/Mutual-recursion/D/mutual-recursion.d index 24ece225ef..2755b307a3 100644 --- a/Task/Mutual-recursion/D/mutual-recursion.d +++ b/Task/Mutual-recursion/D/mutual-recursion.d @@ -1,14 +1,14 @@ import std.stdio, std.algorithm, std.range; -/*auto*/ int male(in int n) pure nothrow { - return n ? (n - female(male(n - 1))) : 0; +int male(in int n) pure nothrow { + return n ? n - male(n - 1).female : 0; } -/*auto*/ int female(in int n) pure nothrow { - return n ? (n - male(female(n - 1))) : 1; +int female(in int n) pure nothrow { + return n ? n - female(n - 1).male : 1; } void main() { - iota(20).map!female().writeln(); - iota(20).map!male().writeln(); + 20.iota.map!female.writeln; + 20.iota.map!male.writeln; } diff --git a/Task/Mutual-recursion/Objective-C/mutual-recursion.m b/Task/Mutual-recursion/Objective-C/mutual-recursion.m index 6a3d30e98a..07094d116b 100644 --- a/Task/Mutual-recursion/Objective-C/mutual-recursion.m +++ b/Task/Mutual-recursion/Objective-C/mutual-recursion.m @@ -1,6 +1,6 @@ -#import +#import -@interface Hofstadter : Object +@interface Hofstadter : NSObject + (int)M: (int)n; + (int)F: (int)n; @end diff --git a/Task/Mutual-recursion/Perl/mutual-recursion.pl b/Task/Mutual-recursion/Perl/mutual-recursion.pl index 2d1ae3e383..54443cc77f 100644 --- a/Task/Mutual-recursion/Perl/mutual-recursion.pl +++ b/Task/Mutual-recursion/Perl/mutual-recursion.pl @@ -1,13 +1,7 @@ -use strict; -use warnings; +sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 } +sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 } -# For mutually recursive functions, -# predeclaring is probably a good idea. -sub M; sub F; - -sub F { my $n = shift; $n ? $n - M F $n-1 : 1 } -sub M { my $n = shift; $n ? $n - F M $n-1 : 0 } - -for my $f (\&F, \&M) { - print join(' ', map $f->($_), 0 .. 19), "\n"; +# Usage: +foreach my $sequence (\&F, \&M) { + print join(' ', map $sequence->($_), 0 .. 19), "\n"; } diff --git a/Task/Mutual-recursion/Rust/mutual-recursion.rust b/Task/Mutual-recursion/Rust/mutual-recursion.rust new file mode 100644 index 0000000000..c2dcdeed57 --- /dev/null +++ b/Task/Mutual-recursion/Rust/mutual-recursion.rust @@ -0,0 +1,25 @@ +fn f(n: int) -> int { + match n { + 0 => 1, + _ => n - m(f(n - 1)) + } +} + +fn m(n: int) -> int { + match n { + 0 => 0, + _ => n - f(m(n - 1)) + } +} + +fn main() { + for i in range(0, 20).map(f) { + print!("{} ", i); + } + println!("") + + for i in range(0, 20).map(m) { + print!("{} ", i); + } + println!("") +} diff --git a/Task/Mutual-recursion/TXR/mutual-recursion.txr b/Task/Mutual-recursion/TXR/mutual-recursion.txr index 19fd373416..9c11e45acb 100644 --- a/Task/Mutual-recursion/TXR/mutual-recursion.txr +++ b/Task/Mutual-recursion/TXR/mutual-recursion.txr @@ -1,37 +1,13 @@ -@(define f (n out)) -@ (local n1 fn1 mfn1) -@ (cases) -@ (bind n "0") -@ (bind out "1") -@ (or) -@ (next `!echo $(( @n - 1 ))`) -@ n1 -@ (f n1 fn1) -@ (m fn1 mfn1) -@ (next `!echo $(( @n - @mfn1 ))`) -@ out -@ (end) -@(end) -@(define m (n out)) -@ (local n1 mn1 fmn1) -@ (cases) -@ (bind n "0") -@ (bind out "0") -@ (or) -@ (next `!echo $(( @n - 1 ))`) -@ n1 -@ (m n1 mn1) -@ (f mn1 fmn1) -@ (next `!echo $(( @n - @fmn1 ))`) -@ out -@ (end) -@(end) -@(next `!seq 0 15`) -@(collect :vars ()) -@ n -@ (f n fn) -@ (m n mn) -@ (output) -f(@n) = @fn; m(@n) = @mn -@ (end) -@(end) +@(do + (defun f (n) + (if (>= 0 n) + 1 + (- n (m (f (- n 1)))))) + + (defun m (n) + (if (>= 0 n) + 0 + (- n (f (m (- n 1)))))) + + (each ((n (range 0 15))) + (format t "f(~s) = ~s; m(~s) = ~s\n" n (f n) n (m n)))) diff --git a/Task/N-queens-problem/D/n-queens-problem-3.d b/Task/N-queens-problem/D/n-queens-problem-3.d index 9dbd775941..c32e2ec6da 100644 --- a/Task/N-queens-problem/D/n-queens-problem-3.d +++ b/Task/N-queens-problem/D/n-queens-problem-3.d @@ -1,5 +1,3 @@ -import std.stdio, std.conv; - ulong nQueens(in uint nn) pure nothrow in { assert(nn > 0 && nn <= 27, @@ -85,6 +83,8 @@ in { } void main(in string[] args) { + import std.stdio, std.conv; + immutable uint side = (args.length >= 2) ? args[1].to!uint : 8; writefln("N-queens(%d) = %d solutions.", side, side.nQueens); } diff --git a/Task/N-queens-problem/Rust/n-queens-problem.rust b/Task/N-queens-problem/Rust/n-queens-problem.rust new file mode 100644 index 0000000000..d6d26d3bfd --- /dev/null +++ b/Task/N-queens-problem/Rust/n-queens-problem.rust @@ -0,0 +1,44 @@ +// rustc 0.10-pre, 24th Feb +static side: i8 = 8; +static queens: i8 = 8; //change side and queens to modify parameters + +fn place(mut board: [i8,..side*side], ix:i8) -> Option<[i8,..side*side]> { + if board[ix] == 0 { + return None + }; + board[ix] = -1; + let i1 = ix/side; + let j1 = ix % side; + for k in range(1,side) { + let mut loc :i8 = i1 * side + k; + board[loc] = 0; + loc = k * side + j1; + board[loc] = 0; + loc = (i1-k) * side + (j1-k); + if loc / side == i1 -k && loc % side == j1 - k && loc != ix && loc >= 0 { board[loc] = 0 }; + loc = loc + 2 * k; + if loc / side == i1 - k && loc % side == j1 + k && loc != ix && loc >= 0 { board[loc] = 0}; + loc = loc + 2 * side * k; + if loc / side == i1 + k && loc % side == j1 + k && loc != ix && loc < side*side { board[loc] = 0}; + loc = loc - 2 * k; + if loc / side == i1 + k && loc % side == j1 - k && loc != ix && loc < side*side { board[loc] = 0}; + } + Some(board) +} + +fn tryplace(b : [i8,..side*side],ix:i8, nq: i8, mut score: u32) -> u32 { + if nq == queens { return score + 1 } + for ind in range(ix, side*side) { + score = match place(b, ind) { + Some(b2) => tryplace(b2, ind+1, nq+1, score), + None() => score + }; + } + return score +} + +fn main() { + let b : [i8, ..side*side] = [1,..side*side]; + let score = tryplace(b, 0, 0, 0); + println!("{}", score) +} diff --git a/Task/Named-parameters/00DESCRIPTION b/Task/Named-parameters/00DESCRIPTION index 1956d77502..c9a4d7105b 100644 --- a/Task/Named-parameters/00DESCRIPTION +++ b/Task/Named-parameters/00DESCRIPTION @@ -1,9 +1,8 @@ -{{omit from|BBC BASIC}} Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. '''Note:''' : Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. -: For example, if f a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. +: For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. : func1 '''must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order''', for example: func1(paramname2=argument2, paramname1=argument1) which ''explicitly'' makes the same parameter/argument bindings as before. : Named parameters are often a feature of languages used in safety critical areas such as [[wp:Verilog|Verilog]] and [[wp:VHDL|VHDL]]. diff --git a/Task/Named-parameters/Applesoft-BASIC/named-parameters.applesoft b/Task/Named-parameters/Applesoft-BASIC/named-parameters.applesoft new file mode 100644 index 0000000000..f4542b11e6 --- /dev/null +++ b/Task/Named-parameters/Applesoft-BASIC/named-parameters.applesoft @@ -0,0 +1,6 @@ + 100 IF LAST$ = "" THEN PRINT "?"; + 110 IF LAST$ < > "" THEN PRINT LAST$; + 120 IF FIRST$ < > "" THEN PRINT ", "FIRST$; + 200 FIRST$ = "" + 210 LAST$ = "" + 220 RETURN diff --git a/Task/Named-parameters/Bracmat/named-parameters.bracmat b/Task/Named-parameters/Bracmat/named-parameters.bracmat new file mode 100644 index 0000000000..8ed2f4b250 --- /dev/null +++ b/Task/Named-parameters/Bracmat/named-parameters.bracmat @@ -0,0 +1,20 @@ +( ( testproc + = i x y z + . out$"Calling testproc" + & (=~):(=?i:?x:?y:?z) { initialise variables to 'failure' } + & !arg + : (? (i,?i) ?|?) { if "i" found, assign value to i. Otherwise just match with no side effect. } + : (? (x,?x) ?|?) { if "x" found, assign value to x. Otherwise just match with no side effect. } + : (? (y,?y) ?|?) { likewise } + : (? (z,?z) ?|?) { likewise } + & (~!i|put$(" i:=" !i)) { if variable doesn't fail, show its value } + & (~!x|put$(" x:=" !x)) + & (~!y|put$(" y:=" !y)) + & (~!z|put$(" z:=" !z)) + & put$\n { add new line } + ) +& testproc$((x,1) (y,2) (z,3)) +& testproc$((x,3) (y,1) (z,2)) +& testproc$((z,4) (x,2) (y,3)) { order is not important } +& testproc$((i,1) (y,2) (z,3)) +); diff --git a/Task/Named-parameters/Objective-C/named-parameters-1.m b/Task/Named-parameters/Objective-C/named-parameters-1.m index 6484c94c23..62519e41f1 100644 --- a/Task/Named-parameters/Objective-C/named-parameters-1.m +++ b/Task/Named-parameters/Objective-C/named-parameters-1.m @@ -1,4 +1,4 @@ -@interface Demo : Object { +@interface Demo : NSObject { // Omitted ... } diff --git a/Task/Non-decimal-radices-Convert/MATLAB/non-decimal-radices-convert.m b/Task/Non-decimal-radices-Convert/MATLAB/non-decimal-radices-convert.m new file mode 100644 index 0000000000..292aa9a170 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/MATLAB/non-decimal-radices-convert.m @@ -0,0 +1,2 @@ +dec2base(26,16) +base2dec('1a', 16) diff --git a/Task/Nth-root/Maple/nth-root.maple b/Task/Nth-root/Maple/nth-root.maple new file mode 100644 index 0000000000..8b4c8f0cb3 --- /dev/null +++ b/Task/Nth-root/Maple/nth-root.maple @@ -0,0 +1,5 @@ +root(1728, 3); + +root(1024, 10); + +root(2.0, 2); diff --git a/Task/Null-object/C++/null-object-3.cpp b/Task/Null-object/C++/null-object-3.cpp new file mode 100644 index 0000000000..b15507ce40 --- /dev/null +++ b/Task/Null-object/C++/null-object-3.cpp @@ -0,0 +1,5 @@ +int *p = nullptr; +... +if(p == nullptr){ + // do some thing +} diff --git a/Task/Object-serialization/Objective-C/object-serialization.m b/Task/Object-serialization/Objective-C/object-serialization.m index 679b23ad86..1d9b843433 100644 --- a/Task/Object-serialization/Objective-C/object-serialization.m +++ b/Task/Object-serialization/Objective-C/object-serialization.m @@ -6,15 +6,12 @@ NSString *animalName; int numberOfLegs; } -- (id) initWithName: (NSString*)name andLegs: (NSInteger)legs; +- (instancetype) initWithName: (NSString*)name andLegs: (NSInteger)legs; - (void) dump; -// the following allows "(de)archiving" of the object -- (void) encodeWithCoder: (NSCoder*)coder; -- (id) initWithCoder: (NSCoder*)coder; @end @implementation Animal -- (id) initWithName: (NSString*)name andLegs: (NSInteger)legs +- (instancetype) initWithName: (NSString*)name andLegs: (NSInteger)legs { if ((self = [super init])) { animalName = [name retain]; @@ -22,11 +19,6 @@ } return self; } -- (void) dealloc -{ - [animalName release]; - [super dealloc]; -} - (void) dump { NSLog(@"%@ has %d legs", animalName, numberOfLegs); @@ -52,16 +44,12 @@ BOOL hasFur; NSMutableArray *eatenList; } -- (id) initWithName: (NSString*)name hasFur: (BOOL)fur; +- (instancetype) initWithName: (NSString*)name hasFur: (BOOL)fur; - (void) addEatenThing: (NSString*)thing; -- (void) dump; -// for archiving / dearchiving: -- (void) encodeWithCoder: (NSCoder*)coder; -- (id) initWithCoder: (NSCoder*)coder; @end @implementation Mammal -- (id) init +- (instancetype) init { if ((self = [super init])) { hasFur = NO; @@ -69,7 +57,7 @@ } return self; } -- (id) initWithName: (NSString*)name hasFur: (BOOL)fur +- (instancetype) initWithName: (NSString*)name hasFur: (BOOL)fur { if ((self = [super initWithName: name andLegs: 4])) { hasFur = fur; @@ -81,21 +69,12 @@ { [eatenList addObject: thing]; } -- (void) dealloc -{ - [eatenList release]; - [super dealloc]; -} - (void) dump { [super dump]; NSLog(@"has fur? %@", (hasFur) ? @"yes" : @"no" ); - // fast enum not implemented yet in gcc 4.3, at least - // without a patch that it seems to exist... - NSEnumerator *en = [eatenList objectEnumerator]; - id element; NSLog(@"it has eaten %d things:", [eatenList count]); - while( (element = [en nextObject]) != nil ) + for ( id element in eatenList ) NSLog(@"it has eaten a %@", element); NSLog(@"end of eaten things list"); } @@ -110,7 +89,7 @@ { if ((self = [super initWithCoder: coder])) { hasFur = [coder decodeBoolForKey: @"Mammal.hasFur"]; - eatenList = [[coder decodeObjectForKey: @"Mammal.eaten"] retain]; + eatenList = [coder decodeObjectForKey: @"Mammal.eaten"]; } return self; } @@ -119,67 +98,59 @@ int main() { - Mammal *aMammal; - Animal *anAnimal; - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - // let us create a fantasy animal - anAnimal = [[Animal alloc] - initWithName: @"Eptohippos" - andLegs: 7 - ]; - // for some reason an Eptohippos is not an horse with 7 legs, - // and it is not a mammal, of course... + // let us create a fantasy animal + Animal *anAnimal = [[Animal alloc] + initWithName: @"Eptohippos" + andLegs: 7 + ]; + // for some reason an Eptohippos is not an horse with 7 legs, + // and it is not a mammal, of course... - // let us create a fantasy mammal (which is an animal too) - aMammal = [[Mammal alloc] - initWithName: @"Mammaluc" - hasFur: YES - ]; - // let us add some eaten stuff... - [aMammal addEatenThing: @"lamb"]; - [aMammal addEatenThing: @"table"]; - [aMammal addEatenThing: @"web page"]; + // let us create a fantasy mammal (which is an animal too) + Mammal *aMammal = [[Mammal alloc] + initWithName: @"Mammaluc" + hasFur: YES + ]; + // let us add some eaten stuff... + [aMammal addEatenThing: @"lamb"]; + [aMammal addEatenThing: @"table"]; + [aMammal addEatenThing: @"web page"]; - // dump anAnimal - NSLog(@"----- original Animal -----"); - [anAnimal dump]; + // dump anAnimal + NSLog(@"----- original Animal -----"); + [anAnimal dump]; - // dump aMammal... - NSLog(@"----- original Mammal -----"); - [aMammal dump]; + // dump aMammal... + NSLog(@"----- original Mammal -----"); + [aMammal dump]; - // now let us store the objects... - NSMutableData *data = [[NSMutableData alloc] init]; - NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] - initForWritingWithMutableData: data]; - [arch encodeObject: anAnimal forKey: @"Eptohippos"]; - [arch encodeObject: aMammal forKey: @"Mammaluc"]; - [anAnimal release]; - [aMammal release]; - [arch finishEncoding]; - [arch release]; - [data writeToFile: @"objects.dat" atomically: YES]; - [data release]; + // now let us store the objects... + NSMutableData *data = [[NSMutableData alloc] init]; + NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] + initForWritingWithMutableData: data]; + [arch encodeObject: anAnimal forKey: @"Eptohippos"]; + [arch encodeObject: aMammal forKey: @"Mammaluc"]; + [arch finishEncoding]; + [data writeToFile: @"objects.dat" atomically: YES]; - // now we want to retrieve the saved objects... - NSData *ldata = [[NSData alloc] - initWithContentsOfFile: @"objects.dat"]; - NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc] - initForReadingWithData: ldata]; - Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"]; - Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"]; - [darch finishDecoding]; - [ldata release]; - [darch release]; + // now we want to retrieve the saved objects... + NSData *ldata = [[NSData alloc] + initWithContentsOfFile: @"objects.dat"]; + NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc] + initForReadingWithData: ldata]; + Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"]; + Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"]; + [darch finishDecoding]; - // now let's dump/print the objects... - NSLog(@"\n"); - NSLog(@"----- the archived Animal -----"); - [archivedAnimal dump]; - NSLog(@"----- the archived Mammal -----"); - [archivedMammal dump]; + // now let's dump/print the objects... + NSLog(@"\n"); + NSLog(@"----- the archived Animal -----"); + [archivedAnimal dump]; + NSLog(@"----- the archived Mammal -----"); + [archivedMammal dump]; - [pool release]; + } return EXIT_SUCCESS; } diff --git a/Task/One-dimensional-cellular-automata/Clojure/one-dimensional-cellular-automata-3.clj b/Task/One-dimensional-cellular-automata/Clojure/one-dimensional-cellular-automata-3.clj new file mode 100644 index 0000000000..c8d0847ca3 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Clojure/one-dimensional-cellular-automata-3.clj @@ -0,0 +1,25 @@ +#!/usr/bin/env lein-exec + +(require '[clojure.string :as str]) + +(def first-genr "_###_##_#_#_#_#__#__") + +(def hospitable #{"_##" + "##_" + "#_#"}) + +(defn compute-next-genr + [genr] + (let [genr (str "_" genr "_") + groups (map str/join (partition 3 1 genr)) + next-genr (for [g groups] + (if (hospitable g) \# \_))] + (str/join next-genr))) + +;; ---------------- main ----------------- +(loop [g first-genr + i 0] + (if (not= i 10) + (do (println g) + (recur (compute-next-genr g) + (inc i))))) diff --git a/Task/One-dimensional-cellular-automata/Clojure/one-dimensional-cellular-automata-4.clj b/Task/One-dimensional-cellular-automata/Clojure/one-dimensional-cellular-automata-4.clj new file mode 100644 index 0000000000..beef9ca3d3 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Clojure/one-dimensional-cellular-automata-4.clj @@ -0,0 +1,23 @@ +(def rules + { + [0 0 0] 0 + [0 0 1] 0 + [0 1 0] 0 + [0 1 1] 1 + [1 0 0] 0 + [1 0 1] 1 + [1 1 0] 1 + [1 1 1] 0 + }) + +(defn nextgen [gen] + (concat [0] + (->> gen + (partition 3 1) + (map vec) + (map rules)) + [0])) + +; Output time! +(doseq [g (take 10 (iterate nextgen [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]))] + (println g)) diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d index f479ef84ce..a6b28d3374 100644 --- a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d +++ b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d @@ -1,19 +1,19 @@ -import std.stdio, std.algorithm; - void main() { - enum ngenerations = 10; + import std.stdio, std.algorithm; + + enum nGenerations = 10; enum initial = "0011101101010101001000"; enum table = "00010110"; char[initial.length + 2] A = '0', B = '0'; A[1 .. $-1] = initial; - foreach (_; 0 .. ngenerations) { - foreach (i; 1 .. A.length-1) { + foreach (immutable _; 0 .. nGenerations) { + foreach (immutable i; 1 .. A.length - 1) { write(A[i] == '0' ? '_' : '#'); - int val = (A[i-1]-'0' << 2) | (A[i]-'0' << 1) | (A[i+1]-'0'); + const val = (A[i-1]-'0' << 2) | (A[i]-'0' << 1) | (A[i+1]-'0'); B[i] = table[val]; } - swap(A, B); - writeln(); + A.swap(B); + writeln; } } diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d index 6db90f04da..37fa5123d5 100644 --- a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d +++ b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d @@ -1,14 +1,13 @@ -import std.stdio, std.algorithm, std.array, std.range; - void main() { + import std.stdio, std.algorithm, std.range; + auto A = "_###_##_#_#_#_#__#__".map!q{a == '#'}.array; auto B = A.dup; do { A.map!q{ "_#"[a] }.writeln; - zip(A, A.cycle.drop(1), A.cycle.drop(A.length - 1)) - //.map!(t => [t[]].sum == 2).copy(B); - .map!q{ a[0] + a[1] + a[2] == 2 }.copy(B); + A.zip(A.cycle.drop(1), A.cycle.drop(A.length - 1)) + .map!(t => [t[]].sum == 2).copy(B); A.swap(B); } while (A != B); } diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d index 0803473de1..f3c54783ce 100644 --- a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d +++ b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d @@ -1,25 +1,20 @@ -import std.stdio, std.algorithm, std.array, std.range, std.bitmanip; - -immutable initial = "__###_##_#_#_#_#__#___"; -enum numGenerations = 10; - void main() { + import std.stdio, std.algorithm, std.range, std.bitmanip; + + immutable initial = "__###_##_#_#_#_#__#___"; + enum nGenerations = 10; BitArray A, B; - A.length = initial.length; + A.init(initial.map!(c => c == '#').array); B.length = initial.length; - // auto A = BitArray(initial.map!(c => c == '#')); - foreach (immutable i, immutable c; initial) - A[i] = c == '#'; - - foreach (immutable _; 0 .. numGenerations) { - //A.map!(b => b ? '#' : '_').weiteln; + foreach (immutable _; 0 .. nGenerations) { + //A.map!(b => b ? '#' : '_').writeln; //foreach (immutable i, immutable b; A) { foreach (immutable i; 1 .. A.length - 1) { "_#"[A[i]].write; immutable val = (cast(uint)A[i - 1] << 2) | (cast(uint)A[i] << 1) | - cast(uint)A[i + 1]; + cast(uint)A[i + 1]; B[i] = val == 3 || val == 5 || val == 6; } diff --git a/Task/One-dimensional-cellular-automata/Deja-Vu/one-dimensional-cellular-automata.djv b/Task/One-dimensional-cellular-automata/Deja-Vu/one-dimensional-cellular-automata.djv new file mode 100644 index 0000000000..b1415538c6 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Deja-Vu/one-dimensional-cellular-automata.djv @@ -0,0 +1,36 @@ +new-state size: + 0 ] + repeat size: + random-range 0 2 + [ 0 + +update s1 s2: + for i range 1 - len s1 2: + s1! -- i + s1! i + s1! ++ i + + + + set-to s2 i = 2 + s2 s1 + +print-state s: + for i range 1 - len s 2: + !print\ s! i + !print "" + +same-state s1 s2: + for i range 1 - len s1 2: + if /= s1! i s2! i: + return false + true + +run size: + new-state size + new-state size + while true: + update + print-state over + if same-state over over: + return print-state drop + +run 60 diff --git a/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata-1.go b/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata-1.go new file mode 100644 index 0000000000..78a64d3026 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata-1.go @@ -0,0 +1,38 @@ +package main + +import "fmt" + +const ( + start = "_###_##_#_#_#_#__#__" + offLeft = '_' + offRight = '_' + dead = '_' +) + +func main() { + fmt.Println(start) + g := newGenerator(start, offLeft, offRight, dead) + for i := 0; i < 10; i++ { + fmt.Println(g()) + } +} + +func newGenerator(start string, offLeft, offRight, dead byte) func() string { + g0 := string(offLeft) + start + string(offRight) + g1 := []byte(g0) + last := len(g0) - 1 + return func() string { + for i := 1; i < last; i++ { + switch l := g0[i-1]; { + case l != g0[i+1]: + g1[i] = g0[i] + case g0[i] == dead: + g1[i] = l + default: + g1[i] = dead + } + } + g0 = string(g1) + return g0[1:last] + } +} diff --git a/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata-2.go b/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata-2.go new file mode 100644 index 0000000000..92e57a32f4 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata-2.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "sync" +) + +const ( + start = "_###_##_#_#_#_#__#__" + offLeft = '_' + offRight = '_' + dead = '_' +) + +func main() { + fmt.Println(start) + a := make([]byte, len(start)+2) + a[0] = offLeft + copy(a[1:], start) + a[len(a)-1] = offRight + var read, write sync.WaitGroup + read.Add(len(start) + 1) + for i := 1; i <= len(start); i++ { + go cell(a[i-1:i+2], &read, &write) + } + for i := 0; i < 10; i++ { + write.Add(len(start) + 1) + read.Done() + read.Wait() + read.Add(len(start) + 1) + write.Done() + write.Wait() + fmt.Println(string(a[1 : len(a)-1])) + } +} + +func cell(kernel []byte, read, write *sync.WaitGroup) { + var next byte + for { + l, v, r := kernel[0], kernel[1], kernel[2] + read.Done() + switch { + case l != r: + next = v + case v == dead: + next = l + default: + next = dead + } + read.Wait() + kernel[1] = next + write.Done() + write.Wait() + } +} diff --git a/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata.go b/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata.go deleted file mode 100644 index be1e4b6f1a..0000000000 --- a/Task/One-dimensional-cellular-automata/Go/one-dimensional-cellular-automata.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import "fmt" - -const start = "_###_##_#_#_#_#__#__" - -func main() { - g0 := []byte(start) - g1 := []byte(start) - fmt.Println(string(g0)) - last := len(g0) - 1 - for g := 0; g < 10; g++ { - for i := 1; i < last; i++ { - switch { - case g0[i-1] != g0[i+1]: - g1[i] = g0[i] - case g0[i] == '_': - g1[i] = g0[i-1] - default: - g1[i] = '_' - } - } - fmt.Println(string(g1)) - copy(g0, g1) - } -} diff --git a/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-1.pl6 b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-1.pl6 new file mode 100644 index 0000000000..76e167eb4d --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-1.pl6 @@ -0,0 +1,14 @@ +class Automata { + has ($.rule, @.cells); + method gist { <| |>.join: @!cells.map({$_ ?? '#' !! ' '}).join } + method code { $.rule.fmt("%08b").comb.reverse } + method succ { + self.new: :$.rule, :cells( + self.code[ + [Z+] 4 «*« @.cells.rotate(-1), + 2 «*« @.cells, + @.cells.rotate(1) + ] + ) + } +} diff --git a/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-2.pl6 b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-2.pl6 new file mode 100644 index 0000000000..0eecb411bc --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-2.pl6 @@ -0,0 +1,5 @@ +my $size = 10; +my Automata $a .= new: + :rule(104), + :cells( 0 xx $size div 2, '111011010101'.comb, 0 xx $size div 2 ); +say $a++ for ^10; diff --git a/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-3.pl6 b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-3.pl6 new file mode 100644 index 0000000000..40de91d1b0 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata-3.pl6 @@ -0,0 +1,4 @@ +my $size = 50; +my Automata $a .= new: :rule(90), :cells( 0 xx $size div 2, 1, 0 xx $size div 2 ); + +say $a++ for ^20; diff --git a/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 deleted file mode 100644 index f5e55587d7..0000000000 --- a/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 +++ /dev/null @@ -1,7 +0,0 @@ -my @c = <_ #>; -my @array = '_###_##_#_#_#_#__#__'.comb »eq» '#'; - -repeat until @array eqv my @prev { - say @c[@prev = @array].join; - @array = ((@array Z+ @array.rotate(1)) Z+ @array.rotate(-1)) X== 2; -} diff --git a/Task/One-of-n-lines-in-a-file/D/one-of-n-lines-in-a-file.d b/Task/One-of-n-lines-in-a-file/D/one-of-n-lines-in-a-file.d index c2ba2bc0df..14e40b8a91 100644 --- a/Task/One-of-n-lines-in-a-file/D/one-of-n-lines-in-a-file.d +++ b/Task/One-of-n-lines-in-a-file/D/one-of-n-lines-in-a-file.d @@ -3,7 +3,7 @@ import std.stdio, std.random, std.algorithm; // Zero-based line numbers. int oneOfN(in int n) { int choice = 0; - foreach (i; 1 .. n) + foreach (immutable i; 1 .. n) if (!uniform(0, i + 1)) choice = i; return choice; @@ -11,9 +11,9 @@ int oneOfN(in int n) { void main() { int[10] bins; - foreach (i; 0 .. 1_000_000) - bins[oneOfN(10)]++; + foreach (immutable i; 0 .. 1_000_000) + bins[10.oneOfN]++; - writeln(bins); - writeln("Total of bins: ", reduce!q{a + b}(bins[])); + bins.writeln; + writeln("Total of bins: ", bins[].sum); } diff --git a/Task/OpenGL/Go/opengl.go b/Task/OpenGL/Go/opengl.go index af8cb771e5..783b58133d 100644 --- a/Task/OpenGL/Go/opengl.go +++ b/Task/OpenGL/Go/opengl.go @@ -7,7 +7,7 @@ import ( "time" gl "github.com/chsc/gogl/gl21" - "github.com/mewmew/win" + "github.com/mewmew/glfw/win" ) // Window dimensions. diff --git a/Task/Ordered-Partitions/D/ordered-partitions.d b/Task/Ordered-Partitions/D/ordered-partitions.d index 4158d5997d..be79eddedc 100644 --- a/Task/Ordered-Partitions/D/ordered-partitions.d +++ b/Task/Ordered-Partitions/D/ordered-partitions.d @@ -1,22 +1,21 @@ import std.stdio, std.algorithm, std.range, std.array, std.conv; -// http://rosettacode.org/wiki/Combinations#D import combinations4: Comb; -alias int[] iRNG; +alias iRNG = int[]; iRNG setDiff(iRNG s, iRNG c) { - return setDifference(s, c).array(); + return setDifference(s, c).array; } iRNG[][] orderPart(iRNG blockSize...) { - iRNG sum = iota(1, 1 + blockSize.reduce!q{a + b}()).array(); + iRNG sum = iota(1, 1 + blockSize.sum).array; iRNG[][] p(iRNG s, in iRNG b) { if (b.length == 0) return [[]]; iRNG[][] res; foreach (c; Comb.On(s, b[0])) - foreach (r; p(setDiff(s, c), b[1 .. $])) + foreach (r; p(setDiff(s, c), b.dropOne)) res ~= c.dup ~ r; return res; } @@ -24,11 +23,7 @@ iRNG[][] orderPart(iRNG blockSize...) { return p(sum, blockSize); } -void main(string[] args) { - auto b = args.length > 1 ? - args[1 .. $].map!(to!int)().array() : - [2, 0, 2]; - - foreach (p; orderPart(b)) - writeln(p); +void main(in string[] args) { + auto b = args.length > 1 ? args.dropOne.to!(int[]) : [2, 0, 2]; + writefln("%(%s\n%)", b.orderPart); } diff --git a/Task/Palindrome-detection/Frink/palindrome-detection.frink b/Task/Palindrome-detection/Frink/palindrome-detection.frink new file mode 100644 index 0000000000..27534defbc --- /dev/null +++ b/Task/Palindrome-detection/Frink/palindrome-detection.frink @@ -0,0 +1 @@ +isPalindrome[x] := x == reverse[x] diff --git a/Task/Palindrome-detection/Maple/palindrome-detection.maple b/Task/Palindrome-detection/Maple/palindrome-detection.maple new file mode 100644 index 0000000000..41ae435f2d --- /dev/null +++ b/Task/Palindrome-detection/Maple/palindrome-detection.maple @@ -0,0 +1,7 @@ +with(StringTools): + +IsPalindrome("ingirumimusnocteetconsumimurigni"); + +IsPalindrome("In girum imus nocte et consumimur igni"); + +IsPalindrome(LowerCase(DeleteSpace("In girum imus nocte et consumimur igni"))); diff --git a/Task/Parallel-calculations/D/parallel-calculations-1.d b/Task/Parallel-calculations/D/parallel-calculations-1.d index a9dfdd1e5b..689495b1a9 100644 --- a/Task/Parallel-calculations/D/parallel-calculations-1.d +++ b/Task/Parallel-calculations/D/parallel-calculations-1.d @@ -1,6 +1,16 @@ -import std.stdio, std.algorithm, std.parallelism, std.typecons; +ulong[] decompose(ulong n) pure nothrow { + typeof(return) result; + for (ulong i = 2; n >= i * i; i++) + for (; n % i == 0; n /= i) + result ~= i; + if (n != 1) + result ~= n; + return result; +} void main() { + import std.stdio, std.algorithm, std.parallelism, std.typecons; + immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, @@ -8,9 +18,10 @@ void main() { 112_272_537_095_293, 1_099_726_829_285_419]; //auto factors = taskPool.amap!(n => tuple(decompose(n), n))(data); + //static enum genPair = (ulong n) pure => tuple(decompose(n), n); static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data); - auto pairs = map!(p => tuple(reduce!min(p[0]), p[1]))(factors); - writeln("N. with largest min factor: ", reduce!max(pairs)[1]); + auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); + writeln("N. with largest min factor: ", pairs.reduce!max[1]); } diff --git a/Task/Parallel-calculations/D/parallel-calculations-2.d b/Task/Parallel-calculations/D/parallel-calculations-2.d index 0ce26090c7..41cdec6617 100644 --- a/Task/Parallel-calculations/D/parallel-calculations-2.d +++ b/Task/Parallel-calculations/D/parallel-calculations-2.d @@ -25,14 +25,16 @@ final class MinFactor: Thread { } private void run() { - immutable clock_t begin = clock(); + immutable clock_t begin = clock; switch (num) { - case 0: fac = []; break; + case 0: fac = []; + break; - case 1: fac = [1]; break; + case 1: fac = [1]; + break; default: - uint limit = cast(uint)(1 + sqrt(cast(double)num)); + uint limit = cast(uint)(1 + double(num).sqrt); ulong n = num; for (ulong divi = 3; divi < limit; divi += 2) { if (n == 1) @@ -42,14 +44,14 @@ final class MinFactor: Thread { fac ~= divi; n /= divi; } - limit = cast(uint)(1 + sqrt(cast(double)n)); + limit = cast(uint)(1 + double(n).sqrt); } } if (n > 1) fac ~= n; } - minFac = reduce!min(fac); - immutable clock_t end = clock(); + minFac = fac.reduce!min; + immutable clock_t end = clock; writefln("num: %20d --> min. factor: %20d ticks(%7d -> %7d)", num, minFac, begin, end); } @@ -63,13 +65,13 @@ void main() { 112_272_537_095_293, 1_099_726_829_285_419]; auto tGroup = new ThreadGroup; - foreach (n; numbers) + foreach (const n; numbers) tGroup.add(new MinFactor(n)); writeln("Minimum factors for respective numbers are:"); foreach (t; tGroup) - t.start(); - tGroup.joinAll(); + t.start; + tGroup.joinAll; auto maxMin = tuple(0UL, [0UL], 0UL); foreach (thread; tGroup) { diff --git a/Task/Parametric-polymorphism/Mercury/parametric-polymorphism.mercury b/Task/Parametric-polymorphism/Mercury/parametric-polymorphism.mercury new file mode 100644 index 0000000000..afb49a3db2 --- /dev/null +++ b/Task/Parametric-polymorphism/Mercury/parametric-polymorphism.mercury @@ -0,0 +1,6 @@ +:- type tree(A) ---> empty ; node(A, tree(A), tree(A)). + +:- func map(func(A) = B, tree(A)) = tree(B). + +map(_, empty) = empty. +map(F, node(A, Left, Right)) = node(F(A), map(F, Left), map(F, Right)). diff --git a/Task/Parsing-RPN-calculator-algorithm/Common-Lisp/parsing-rpn-calculator-algorithm.lisp b/Task/Parsing-RPN-calculator-algorithm/Common-Lisp/parsing-rpn-calculator-algorithm.lisp new file mode 100644 index 0000000000..82f4f2a170 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Common-Lisp/parsing-rpn-calculator-algorithm.lisp @@ -0,0 +1,20 @@ +(setf (symbol-function '^) #'expt) ; Make ^ an alias for EXPT + +(defun print-stack (token stack) + (format T "~a: ~{~a ~}~%" token (reverse stack))) + +(defun rpn (tokens &key stack verbose ) + (cond + ((and (not tokens) (not stack)) 0) + ((not tokens) (car stack)) + (T + (let* ((current (car tokens)) + (next-stack (if (numberp current) + (cons current stack) + (let* ((arg2 (car stack)) + (arg1 (cadr stack)) + (fun (car tokens))) + (cons (funcall fun arg1 arg2) (cddr stack)))))) + (when verbose + (print-stack current next-stack)) + (rpn (cdr tokens) :stack next-stack :verbose verbose))))) diff --git a/Task/Parsing-RPN-calculator-algorithm/Erlang/parsing-rpn-calculator-algorithm.erl b/Task/Parsing-RPN-calculator-algorithm/Erlang/parsing-rpn-calculator-algorithm.erl new file mode 100644 index 0000000000..b450929e18 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Erlang/parsing-rpn-calculator-algorithm.erl @@ -0,0 +1,43 @@ +-module(rpn). +-export([eval/1]). + +parse(Expression) -> + parse(string:tokens(Expression," "),[]). + +parse([],Expression) -> + lists:reverse(Expression); +parse(["+"|Xs],Expression) -> + parse(Xs,[fun erlang:'+'/2|Expression]); +parse(["-"|Xs],Expression) -> + parse(Xs,[fun erlang:'-'/2|Expression]); +parse(["*"|Xs],Expression) -> + parse(Xs,[fun erlang:'*'/2|Expression]); +parse(["/"|Xs],Expression) -> + parse(Xs,[fun erlang:'/'/2|Expression]); +parse(["^"|Xs],Expression) -> + parse(Xs,[fun math:pow/2|Expression]); +parse([X|Xs],Expression) -> + {N,_} = string:to_integer(X), + parse(Xs,[N|Expression]). + +%% The expression should be entered as a string of numbers and +%% operators separated by spaces. No error handling is included if +%% another string format is used. +eval(Expression) -> + eval(parse(Expression),[]). + +eval([],[N]) -> + N; +eval([N|Exp],Stack) when is_number(N) -> + NewStack = [N|Stack], + print(NewStack), + eval(Exp,NewStack); +eval([F|Exp],[X,Y|Stack]) -> + NewStack = [F(Y,X)|Stack], + print(NewStack), + eval(Exp,NewStack). + +print(Stack) -> + lists:map(fun (X) when is_integer(X) -> io:format("~12.12b ",[X]); + (X) when is_float(X) -> io:format("~12f ",[X]) end, Stack), + io:format("~n"). diff --git a/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-3.j b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-3.j new file mode 100644 index 0000000000..08bf2c8b0f --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-3.j @@ -0,0 +1,7 @@ +rpn=: 3 :0 + queue=. |.3 :'|.3 :y 0'::]each;: y + op=. 1 :'2 (u~/@:{.,}.)S:0 ,@]' + ops=. +op`(-op)`(*op)`(%op)`(^op)`(,&;) + choose=. ((;:'+-*/^')&i.@[) + ,ops@.choose/queue +) diff --git a/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-4.j b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-4.j new file mode 100644 index 0000000000..b87c8cf61b --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-4.j @@ -0,0 +1,2 @@ + rpn '3 4 2 * 1 5 - 2 3 ^ ^ / +' +3.00012 diff --git a/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-5.j b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-5.j new file mode 100644 index 0000000000..70b95b729b --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-5.j @@ -0,0 +1,7 @@ +rpnD=: 3 :0 + queue=. |.3 :'|.3 :y 0'::]each;: y + op=. 1 :'2 (u~/@:{.,}.)S:0 ,@([smoutput)@]' + ops=. +op`(-op)`(*op)`(%op)`(^op)`(,&;) + choose=. ((;:'+-*/^')&i.@[) + ,ops@.choose/queue +) diff --git a/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-6.j b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-6.j new file mode 100644 index 0000000000..3095999c05 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/J/parsing-rpn-calculator-algorithm-6.j @@ -0,0 +1,10 @@ + rpnD '3 4 2 * 1 5 - 2 3 ^ ^ / +' +┌─────┐ +│2 4 3│ +└─────┘ +5 1 8 3 +3 2 _4 8 3 +8 _4 8 3 +65536 8 3 +0.00012207 3 +3.00012 diff --git a/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d index 5cfc56a488..37591ad73d 100644 --- a/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d +++ b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d @@ -1,10 +1,10 @@ -import std.stdio, std.typecons, std.string, std.array, std.algorithm; +import std.stdio, std.string, std.array, std.algorithm; void rpmToInfix(in string str) { - alias Exp = Tuple!(int,"p", string,"e"); + static struct Exp { int p; string e; } immutable P = (in Exp pair, in int prec) pure => pair.p < prec ? format("( %s )", pair.e) : pair.e; - immutable F = (string[] s...) pure nothrow => s.join(" "); + immutable F = (in string[] s...) pure nothrow => s.join(" "); writefln("=================\n%s", str); Exp[] stack; @@ -24,7 +24,7 @@ void rpmToInfix(in string str) { default: throw new Error("Wrong part: " ~ w); } } - stack.map!q{ a[1] }.writeln; + stack.map!q{ a.e }.writeln; } writeln("-----------------\n", stack.back.e); } diff --git a/Task/Parsing-RPN-to-infix-conversion/TXR/parsing-rpn-to-infix-conversion.txr b/Task/Parsing-RPN-to-infix-conversion/TXR/parsing-rpn-to-infix-conversion.txr new file mode 100644 index 0000000000..7fec316924 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/TXR/parsing-rpn-to-infix-conversion.txr @@ -0,0 +1,64 @@ +@(do + ;; alias for circumflex, which is reserved syntax + (defvar exp (intern "^")) + + (defvar *prec* ^((,exp . 4) (* . 3) (/ . 3) (+ . 2) (- . 2))) + + (defvar *asso* ^((,exp . :right) (* . nil) + (/ . :left) (+ . nil) (- . :left))) + + (defun debug-print (label val) + (format t "~a: ~a\n" label val) + val) + + (defun rpn-to-lisp (rpn) + (let (stack) + (each ((term rpn)) + (if (symbolp (debug-print "rpn term" term)) + (let ((right (pop stack)) + (left (pop stack))) + (push ^(,term ,left ,right) stack)) + (push term stack)) + (debug-print "stack" stack)) + (if (rest stack) + (return-from error "*excess stack elements*")) + (debug-print "lisp" (pop stack)))) + + (defun prec (term) + (or (cdr (assoc term *prec*)) 99)) + + (defun asso (term dfl) + (or (cdr (assoc term *asso*)) dfl)) + + (defun inf-term (op term left-or-right) + (if (atom term) + `@term` + (let ((pt (prec (car term))) + (po (prec op)) + (at (asso (car term) left-or-right)) + (ao (asso op left-or-right))) + (cond + ((< pt po) `(@(lisp-to-infix term))`) + ((> pt po) `@(lisp-to-infix term)`) + ((and (eq at ao) (eq left-or-right ao)) `@(lisp-to-infix term)`) + (t `(@(lisp-to-infix term))`))))) + + (defun lisp-to-infix (lisp) + (tree-case lisp + ((op left right) (let ((left-inf (inf-term op left :left)) + (right-inf (inf-term op right :right))) + `@{left-inf} @op @{right-inf}`)) + (() (return-from error "*stack underflow*")) + (else `@lisp`))) + + (defun string-to-rpn (str) + (debug-print "rpn" + (mapcar (do if (int-str @1) (int-str @1) (intern @1)) + (tok-str str #/[^ \t]+/)))) + + (debug-print "infix" + (block error + (tree-case *args* + ((a b . c) "*excess args*") + ((a) (lisp-to-infix (rpn-to-lisp (string-to-rpn a)))) + (else "*arg needed*"))))) diff --git a/Task/Parsing-Shunting-yard-algorithm/Perl-6/parsing-shunting-yard-algorithm.pl6 b/Task/Parsing-Shunting-yard-algorithm/Perl-6/parsing-shunting-yard-algorithm.pl6 new file mode 100644 index 0000000000..0f6ae573e3 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Perl-6/parsing-shunting-yard-algorithm.pl6 @@ -0,0 +1,46 @@ +my %prec = + '^' => 4, + '*' => 3, + '/' => 3, + '+' => 2, + '-' => 2, + '(' => 1; + +my %assoc = + '^' => 'right', + '*' => 'left', + '/' => 'left', + '+' => 'left', + '-' => 'left'; + +sub shunting-yard ($prog) { + my @inp = $prog.words; + my @ops; + my @res; + + sub report($op) { printf "%25s %-7s %10s %s\n", ~@res, ~@ops, $op, ~@inp } + sub shift($t) { report( "shift $t"); @ops.push: $t } + sub reduce($t) { report("reduce $t"); @res.push: $t } + + while @inp { + given @inp.shift { + when /\d/ { reduce $_ }; + when '(' { shift $_ } + when ')' { while @ops and (my $x = @ops.pop and $x ne '(') { reduce $x } } + default { + my $newprec = %prec{$_}; + while @ops { + my $oldprec = %prec{@ops[*-1]}; + last if $newprec > $oldprec; + last if $newprec == $oldprec and %assoc{$_} eq 'right'; + reduce @ops.pop; + } + shift $_; + } + } + } + reduce @ops.pop while @ops; + @res; +} + +say shunting-yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'; diff --git a/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl b/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl new file mode 100644 index 0000000000..2b67840cce --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl @@ -0,0 +1,51 @@ +use 5.010; +use strict; +use warnings; + +my %prec = ( + '^' => 4, + '*' => 3, + '/' => 3, + '+' => 2, + '-' => 2, + '(' => 1); + +my %assoc = ( + '^' => 'right', + '*' => 'left', + '/' => 'left', + '+' => 'left', + '-' => 'left'); + +sub shunting_yard { + my @inp = split ' ', $_[0]; + my @ops; + my @res; + + my $report = sub { printf "%25s %-7s %10s %s\n", "@res", "@ops", $_[0], "@inp" }; + my $shift = sub { $report->( "shift @_"); push @ops, @_ }; + my $reduce = sub { $report->("reduce @_"); push @res, @_ }; + + while( @inp ) { + given( shift @inp ) { + when ( /\d/ ) { $reduce->($_) } + when ( '(' ) { $shift->($_) } + when ( ')' ) { while( @ops and "(" ne (my $x = pop @ops) ) { $reduce->( $x ) } } + default { + my $newprec = $prec{$_}; + while( @ops ) { + my $oldprec = $prec{$ops[-1]}; + last if $newprec > $oldprec; + last if $newprec == $oldprec and $assoc{$_} eq 'right'; + $reduce->( pop @ops ); + } + $shift->( $_ ); + } + } + } + $reduce->( pop @ops ) while @ops; + @res; +} + +local $, = " "; +say shunting_yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' ; diff --git a/Task/Partial-function-application/Groovy/partial-function-application-1.groovy b/Task/Partial-function-application/Groovy/partial-function-application-1.groovy new file mode 100644 index 0000000000..aa0bab7095 --- /dev/null +++ b/Task/Partial-function-application/Groovy/partial-function-application-1.groovy @@ -0,0 +1,5 @@ +def fs = { fn, values -> values.collect { fn(it) } } +def f1 = { v -> v * 2 } +def f2 = { v -> v ** 2 } +def fsf1 = fs.curry(f1) +def fsf2 = fs.curry(f2) diff --git a/Task/Partial-function-application/Groovy/partial-function-application-2.groovy b/Task/Partial-function-application/Groovy/partial-function-application-2.groovy new file mode 100644 index 0000000000..f2b39b9152 --- /dev/null +++ b/Task/Partial-function-application/Groovy/partial-function-application-2.groovy @@ -0,0 +1,4 @@ +[(0..3), (2..8).step(2)].each { seq -> + println "fsf1$seq = ${fsf1(seq)}" + println "fsf2$seq = ${fsf2(seq)}" +} diff --git a/Task/Partial-function-application/Haskell/partial-function-application.hs b/Task/Partial-function-application/Haskell/partial-function-application.hs index 86750e6cf1..c8e4fb9ad5 100644 --- a/Task/Partial-function-application/Haskell/partial-function-application.hs +++ b/Task/Partial-function-application/Haskell/partial-function-application.hs @@ -1,6 +1,6 @@ -fs f s = map f s -f1 value = value * 2 -f2 value = value ^ 2 +fs = map +f1 = (* 2) +f2 = (^ 2) fsf1 = fs f1 fsf2 = fs f2 diff --git a/Task/Partial-function-application/PARI-GP/partial-function-application.pari b/Task/Partial-function-application/PARI-GP/partial-function-application.pari new file mode 100644 index 0000000000..fbe251c701 --- /dev/null +++ b/Task/Partial-function-application/PARI-GP/partial-function-application.pari @@ -0,0 +1,9 @@ +fs=apply; +f1(x)=2*x; +f2(x)=x^2; +fsf1=any->=fs(f1,any); +fsf2=any->=fs(f2,any); +fsf1([0..3]) +fsf1(2([1..4]) +fsf2([0..3]) +fsf2(2([1..4]) diff --git a/Task/Partial-function-application/TXR/partial-function-application-1.txr b/Task/Partial-function-application/TXR/partial-function-application-1.txr new file mode 100644 index 0000000000..7b28261383 --- /dev/null +++ b/Task/Partial-function-application/TXR/partial-function-application-1.txr @@ -0,0 +1,5 @@ +$ txr -p "(mapcar (op mapcar (op * 2)) (list (range 0 3) (range 2 8 2)))" +((0 2 4 6) (4 8 12 16)) + +$ txr -p "(mapcar (op mapcar (op * @1 @1)) (list (range 0 3) (range 2 8 2)))" +((0 1 4 9) (4 16 36 64)) diff --git a/Task/Partial-function-application/TXR/partial-function-application-2.txr b/Task/Partial-function-application/TXR/partial-function-application-2.txr new file mode 100644 index 0000000000..06229885b4 --- /dev/null +++ b/Task/Partial-function-application/TXR/partial-function-application-2.txr @@ -0,0 +1,11 @@ +$ txr -e "(progn + (defun fs (fun seq) (mapcar fun seq)) + (defun f1 (num) (* 2 num)) + (defun f2 (num) (* num num)) + (defvar fsf1 (op fs f1)) ;; pointless: can just be (defun fsf1 (seq) (fs f1 seq)) !!! + (defvar fsf2 (op fs f2)) + + (print [fs fsf1 '((0 1 2 3) (2 4 6 8))]) (put-line \"\") + (print [fs fsf2 '((0 1 2 3) (2 4 6 8))]) (put-line \"\"))" +((0 2 4 6) (4 8 12 16)) +((0 1 4 9) (4 16 36 64)) diff --git a/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d b/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d index a8accd613c..c3b4c1bd5e 100644 --- a/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d +++ b/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d @@ -1,12 +1,13 @@ import std.stdio, std.algorithm; -void iterate(bool doPrint=true)(double[] v, double[] diff) { +void iterate(bool doPrint=true)(double[] v, double[] diff) +/*pure nothrow*/ { static ref T E(T)(T[] x, in size_t row, in size_t col) pure nothrow { return x[row * (row + 1) / 2 + col]; } - double sum = 0.0; + double tot = 0.0; do { // enforce boundary conditions E(v, 0, 0) = 151; @@ -15,8 +16,8 @@ void iterate(bool doPrint=true)(double[] v, double[] diff) { E(v, 4, 3) = 4; // calculate difference from equilibrium - foreach (i; 1 .. 5) { - foreach (j; 0 .. i + 1) { + foreach (immutable i; 1 .. 5) { + foreach (immutable j; 0 .. i + 1) { E(diff, i, j) = 0; if (j < i) E(diff, i, j) += E(v, i - 1, j) - @@ -29,8 +30,8 @@ void iterate(bool doPrint=true)(double[] v, double[] diff) { } } - foreach (i; 1 .. 4) - foreach (j; 0 .. i) + foreach (immutable i; 1 .. 4) + foreach (immutable j; 0 .. i) E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j); @@ -40,22 +41,22 @@ void iterate(bool doPrint=true)(double[] v, double[] diff) { // do feedback, check if we are close enough // 4: scale down the feedback to avoid oscillations v[] += diff[] / 4; - sum = reduce!q{a + b ^^ 2}(0.0, diff); + tot = diff.map!q{ a ^^ 2 }.sum; static if (doPrint) - writeln("dev: ", sum); + writeln("dev: ", tot); - // sum(dx^2) < 0.1 means each cell is no more than 0.5 away + // tot(dx^2) < 0.1 means each cell is no more than 0.5 away // from equilibrium. It takes about 50 iterations. After - // 700 iterations sum is < 1e-25, but that's overkill. - } while (sum >= 0.1); + // 700 iterations tot is < 1e-25, but that's overkill. + } while (tot >= 0.1); } void main() { - static void show(in double[] x) { + static void show(in double[] x) nothrow { int idx; - foreach (i; 0 .. 5) - foreach (j; 0 .. i+1) { + foreach (immutable i; 0 .. 5) + foreach (immutable j; 0 .. i+1) { printf("%4d%c", cast(int)(0.5 + x[idx]), j < i ? ' ' : '\n'); idx++; diff --git a/Task/Pascals-triangle/AutoHotkey/pascals-triangle.ahk b/Task/Pascals-triangle/AutoHotkey/pascals-triangle-1.ahk similarity index 100% rename from Task/Pascals-triangle/AutoHotkey/pascals-triangle.ahk rename to Task/Pascals-triangle/AutoHotkey/pascals-triangle-1.ahk diff --git a/Task/Pascals-triangle/AutoHotkey/pascals-triangle-2.ahk b/Task/Pascals-triangle/AutoHotkey/pascals-triangle-2.ahk new file mode 100644 index 0000000000..191785ece3 --- /dev/null +++ b/Task/Pascals-triangle/AutoHotkey/pascals-triangle-2.ahk @@ -0,0 +1,25 @@ +Msgbox % format(pascalstriangle()) +Return + +format(o) ; converts object to string +{ + For k, v in o + s .= IsObject(v) ? format(v) "`n" : v " " + Return s +} +pascalstriangle(n=7) ; n rows of Pascal's triangle +{ + p := Object(), z:=Object() + Loop, % n + Loop, % row := A_Index + col := A_Index + , p[row, col] := row = 1 and col = 1 + ? 1 + : (p[row-1, col-1] = "" ; math operations on blanks return blanks; I want to assume zero + ? 0 + : p[row-1, col-1]) + + (p[row-1, col] = "" + ? 0 + : p[row-1, col]) + Return p +} diff --git a/Task/Pascals-triangle/TI-83-BASIC/pascals-triangle-1.ti-83 b/Task/Pascals-triangle/TI-83-BASIC/pascals-triangle-1.ti-83 new file mode 100644 index 0000000000..8eb8f36c16 --- /dev/null +++ b/Task/Pascals-triangle/TI-83-BASIC/pascals-triangle-1.ti-83 @@ -0,0 +1,17 @@ +PROGRAM:PASCALTR +:Lbl IN +:ClrHome +:Disp "NUMBER OF ROWS" +:Input N +:If N < 1:Goto IN +:{N,N}→dim([A]) +:"CHEATING TO MAKE IT FASTER" +:For(I,1,N) +:1→[A](1,1) +:End +:For(I,2,N) +:For(J,2,I) +:[A](I-1,J-1)+[A](I-1,J)→[A](I,J) +:End +:End +:[A] diff --git a/Task/Pascals-triangle/TI-83-BASIC/pascals-triangle-2.ti-83 b/Task/Pascals-triangle/TI-83-BASIC/pascals-triangle-2.ti-83 new file mode 100644 index 0000000000..60a2d3944d --- /dev/null +++ b/Task/Pascals-triangle/TI-83-BASIC/pascals-triangle-2.ti-83 @@ -0,0 +1,13 @@ +PROGRAM:PASCALTR +:Lbl IN +:ClrHome +:Disp "NUMBER OF ROWS" +:Input N +:If N < 1:Goto IN +:{N,N}→dim([A]) +:For(I,2,N) +:For(J,2,I) +:(I-1) nCr (J-1)→[A](I,J) +:End +:End +:[A] diff --git a/Task/Perfect-numbers/D/perfect-numbers-1.d b/Task/Perfect-numbers/D/perfect-numbers-1.d index 07dbfe3564..fc9d03723b 100644 --- a/Task/Perfect-numbers/D/perfect-numbers-1.d +++ b/Task/Perfect-numbers/D/perfect-numbers-1.d @@ -1,21 +1,12 @@ -import std.stdio, std.math, std.range, std.algorithm; +import std.stdio, std.algorithm, std.range; -bool isPerfectNumber(in int n) pure nothrow { - if (n < 2) - return false; - - int sum = 1; - foreach (immutable i; 2 .. cast(int)sqrt(cast(real)n) + 1) - if (n % i == 0) { - immutable int q = n / i; - sum += i; - if (q > i) - sum += q; - } - - return sum == n; +bool isPerfectNumber1(in uint n) pure nothrow +in { + assert(n > 0); +} body { + return n == iota(1, n - 1).filter!(i => n % i == 0).sum; } void main() { - 10_000.iota.filter!isPerfectNumber.writeln; + iota(1, 10_000).filter!isPerfectNumber1.writeln; } diff --git a/Task/Perfect-numbers/D/perfect-numbers-2.d b/Task/Perfect-numbers/D/perfect-numbers-2.d index 91ac976953..f7c9a113be 100644 --- a/Task/Perfect-numbers/D/perfect-numbers-2.d +++ b/Task/Perfect-numbers/D/perfect-numbers-2.d @@ -1,12 +1,21 @@ -import std.stdio, std.algorithm, std.range; +import std.stdio, std.math, std.range, std.algorithm; -bool isPerfect(in uint n) pure nothrow -in { - assert(n > 0); -} body { - return n == reduce!((s, i) => n % i ? s : s + i)(0, iota(1, n-1)); +bool isPerfectNumber2(in int n) pure nothrow { + if (n < 2) + return false; + + int total = 1; + foreach (immutable i; 2 .. cast(int)real(n).sqrt + 1) + if (n % i == 0) { + immutable int q = n / i; + total += i; + if (q > i) + total += q; + } + + return total == n; } void main() { - iota(1, 10_000).filter!isPerfect.writeln; + 10_000.iota.filter!isPerfectNumber2.writeln; } diff --git a/Task/Perfect-numbers/Dart/perfect-numbers-1.dart b/Task/Perfect-numbers/Dart/perfect-numbers-1.dart new file mode 100644 index 0000000000..175896da0f --- /dev/null +++ b/Task/Perfect-numbers/Dart/perfect-numbers-1.dart @@ -0,0 +1,23 @@ +/* + * Function to test if a number is a perfect number + * A number is a perfect number if it is equal to the sum of all its divisors + * Input: Positive integer n + * Output: true if n is a perfect number, false otherwise + */ +bool isPerfect(int n){ + //Generate a list of integers in the range 1 to n-1 : [1, 2, ..., n-1] + List range = new List.generate(n-1, (int i) => i+1); + + //Create a list that filters the divisors of n from range + List divisors = new List.from(range.where((i) => n%i == 0)); + + //Sum the all the divisors + int sumOfDivisors = 0; + for (int i = 0; i < divisors.length; i++){ + sumOfDivisors = sumOfDivisors + divisors[i]; + } + + // A number is a perfect number if it is equal to the sum of its divisors + // We return the test if n is equal to sumOfDivisors + return n == sumOfDivisors; +} diff --git a/Task/Perfect-numbers/Dart/perfect-numbers-2.dart b/Task/Perfect-numbers/Dart/perfect-numbers-2.dart new file mode 100644 index 0000000000..c5c09220a4 --- /dev/null +++ b/Task/Perfect-numbers/Dart/perfect-numbers-2.dart @@ -0,0 +1,2 @@ +isPerfect(n) => + n == new List.generate(n-1, (i) => n%(i+1) == 0 ? i+1 : 0).fold(0, (p,n)=>p+n); diff --git a/Task/Perfect-numbers/Dart/perfect-numbers-3.dart b/Task/Perfect-numbers/Dart/perfect-numbers-3.dart new file mode 100644 index 0000000000..1985656bed --- /dev/null +++ b/Task/Perfect-numbers/Dart/perfect-numbers-3.dart @@ -0,0 +1,2 @@ +main() => + new List.generate(1000,(i)=>i+1).where(isPerfect).forEach(print); diff --git a/Task/Perfect-numbers/Haskell/perfect-numbers-1.hs b/Task/Perfect-numbers/Haskell/perfect-numbers-1.hs index b98d7d3c99..df4ad4d0bf 100644 --- a/Task/Perfect-numbers/Haskell/perfect-numbers-1.hs +++ b/Task/Perfect-numbers/Haskell/perfect-numbers-1.hs @@ -1 +1,2 @@ -perf n = n == sum [i | i <- [1..n-1], n `mod` i == 0] +perfect n = + n == sum [i | i <- [1..n-1], n `mod` i == 0] diff --git a/Task/Perfect-numbers/Ruby/perfect-numbers-1.rb b/Task/Perfect-numbers/Ruby/perfect-numbers-1.rb index 9b1621e2dd..9a16f3c742 100644 --- a/Task/Perfect-numbers/Ruby/perfect-numbers-1.rb +++ b/Task/Perfect-numbers/Ruby/perfect-numbers-1.rb @@ -1,9 +1,7 @@ def perf(n) - sum = 0 - for i in 1...n - if n % i == 0 - sum += i - end - end - return sum == n + sum = 0 + for i in 1...n + sum += i if n % i == 0 + end + sum == n end diff --git a/Task/Perfect-numbers/Ruby/perfect-numbers-2.rb b/Task/Perfect-numbers/Ruby/perfect-numbers-2.rb index c82de6f678..eeba4c9852 100644 --- a/Task/Perfect-numbers/Ruby/perfect-numbers-2.rb +++ b/Task/Perfect-numbers/Ruby/perfect-numbers-2.rb @@ -1,3 +1,3 @@ def perf(n) - n == (1...n).select {|i| n % i == 0}.inject(:+) + n == (1...n).select {|i| n % i == 0}.inject(:+) end diff --git a/Task/Perfect-numbers/Ruby/perfect-numbers-3.rb b/Task/Perfect-numbers/Ruby/perfect-numbers-3.rb new file mode 100644 index 0000000000..8b8d0e5a1d --- /dev/null +++ b/Task/Perfect-numbers/Ruby/perfect-numbers-3.rb @@ -0,0 +1,7 @@ +def perf(n) + divisors = [] + for i in 1..Math.sqrt(n) + divisors << i << n/i if n % i == 0 + end + divisors.uniq.inject(:+) == 2*n +end diff --git a/Task/Perfect-numbers/Ruby/perfect-numbers-4.rb b/Task/Perfect-numbers/Ruby/perfect-numbers-4.rb new file mode 100644 index 0000000000..f35a5a3a0b --- /dev/null +++ b/Task/Perfect-numbers/Ruby/perfect-numbers-4.rb @@ -0,0 +1,3 @@ +for n in 1..10000 + puts n if perf(n) +end diff --git a/Task/Permutation-test/D/permutation-test-1.d b/Task/Permutation-test/D/permutation-test-1.d index a164c38353..c50aed753e 100644 --- a/Task/Permutation-test/D/permutation-test-1.d +++ b/Task/Permutation-test/D/permutation-test-1.d @@ -1,7 +1,5 @@ import std.stdio, std.algorithm, std.array, combinations3; -alias sum = reduce!q{a + b}; - auto permutationTest(T)(in T[] a, in T[] b) /*pure nothrow*/ { immutable tObs = a.sum; //auto combs = combinations!false(a ~ b, a.length); // Not a Range. diff --git a/Task/Permutation-test/D/permutation-test-2.d b/Task/Permutation-test/D/permutation-test-2.d index ac8ee0a984..cd2ba69e52 100644 --- a/Task/Permutation-test/D/permutation-test-2.d +++ b/Task/Permutation-test/D/permutation-test-2.d @@ -4,7 +4,7 @@ void main() { immutable treatment = [85, 88, 75, 66, 25, 29, 83, 39, 97]; immutable control = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; immutable both = treatment ~ control; - immutable sTreat = treatment.reduce!q{a + b}; + immutable sTreat = treatment.sum; T pick(T)(in size_t at, in size_t remain, in T accu) pure nothrow { if (remain == 0) diff --git a/Task/Permutation-test/Seed7/permutation-test.seed7 b/Task/Permutation-test/Seed7/permutation-test.seed7 new file mode 100644 index 0000000000..4f23ec4f5e --- /dev/null +++ b/Task/Permutation-test/Seed7/permutation-test.seed7 @@ -0,0 +1,39 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const array integer: treatmentGroup is [] (85, 88, 75, 66, 25, 29, 83, 39, 97); +const array integer: controlGroup is [] (68, 41, 10, 49, 16, 65, 32, 92, 28, 98); +const array integer: both is treatmentGroup & controlGroup; + +const func integer: pick (in integer: at, in integer: remain, in integer: accu, in integer: treat) is func + result + var integer: picked is 0; + begin + if remain = 0 then + picked := ord(accu > treat); + else + picked := pick(at - 1, remain - 1, accu + both[at], treat); + if at > remain then + picked +:= pick(at - 1, remain, accu, treat); + end if; + end if; + end func; + +const proc: main is func + local + var integer: experimentalResult is 0; + var integer: treat is 0; + var integer: total is 1; + var integer: le is 0; + var integer: gt is 0; + var integer: i is 0; + begin + for experimentalResult range treatmentGroup do + treat +:= experimentalResult; + end for; + total := 19 ! 10; # Binomial coefficient + gt := pick(19, 9, 0, treat); + le := total - gt; + writeln("<= : " <& 100.0 * flt(le) / flt(total) digits 6 <& "% " <& le); + writeln(" > : " <& 100.0 * flt(gt) / flt(total) digits 6 <& "% " <& gt); + end func; diff --git a/Task/Permutations-by-swapping/Ruby/permutations-by-swapping.rb b/Task/Permutations-by-swapping/Ruby/permutations-by-swapping.rb new file mode 100644 index 0000000000..f17542bf1c --- /dev/null +++ b/Task/Permutations-by-swapping/Ruby/permutations-by-swapping.rb @@ -0,0 +1,26 @@ +def perms(n) + p = Array.new(n+1){|i| -i} + s = 1 + loop do + yield p[1..-1].map(&:abs), s + k = 0 + for i in 2..n + k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs + end + for i in 1...n + k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs + end + break if k.zero? + for i in 1..n + p[i] *= -1 if p[i].abs > p[k].abs + end + i = k + (p[k] <=> 0) + p[k], p[i] = p[i], p[k] + s = -s + end +end + +for i in 3..4 + perms(i){|perm, sign| puts "Perm: #{perm} Sign: #{sign}"} + puts +end diff --git a/Task/Permutations/AutoHotkey/permutations.ahk b/Task/Permutations/AutoHotkey/permutations-1.ahk similarity index 100% rename from Task/Permutations/AutoHotkey/permutations.ahk rename to Task/Permutations/AutoHotkey/permutations-1.ahk diff --git a/Task/Permutations/AutoHotkey/permutations-2.ahk b/Task/Permutations/AutoHotkey/permutations-2.ahk new file mode 100644 index 0000000000..fb3138e0e7 --- /dev/null +++ b/Task/Permutations/AutoHotkey/permutations-2.ahk @@ -0,0 +1,33 @@ +P(n,k="",opt=0,delim="",str="") { ; generate all n choose k permutations lexicographically + ;1..n = range, or delimited list, or string to parse + ; to process with a different min index, pass a delimited list, e.g. "0`n1`n2" + ;k = length of result + ;opt 0 = no repetitions + ;opt 1 = with repetitions + ;opt 2 = run for 1..k + ;opt 3 = run for 1..k with repetitions + ;str = string to prepend (used internally) + ;returns delimited string, error message, or (if k > n) a blank string + i:=0 + If !InStr(n,"`n") + If n in 2,3,4,5,6,7,8,9 + Loop, %n% + n := A_Index = 1 ? A_Index : n "`n" A_Index + Else + Loop, Parse, n, %delim% + n := A_Index = 1 ? A_LoopField : n "`n" A_LoopField + If (k = "") + RegExReplace(n,"`n","",k), k++ + If k is not Digit + Return "k must be a digit." + If opt not in 0,1,2,3 + Return "opt invalid." + If k = 0 + Return str + Else + Loop, Parse, n, `n + If (!InStr(str,A_LoopField) || opt & 1) + s .= (!i++ ? (opt & 2 ? str "`n" : "") : "`n" ) + . P(n,k-1,opt,delim,str . A_LoopField . delim) + Return s +} diff --git a/Task/Permutations/AutoHotkey/permutations-3.ahk b/Task/Permutations/AutoHotkey/permutations-3.ahk new file mode 100644 index 0000000000..d9e6b72dfb --- /dev/null +++ b/Task/Permutations/AutoHotkey/permutations-3.ahk @@ -0,0 +1 @@ +MsgBox % P(3) diff --git a/Task/Permutations/AutoHotkey/permutations-4.ahk b/Task/Permutations/AutoHotkey/permutations-4.ahk new file mode 100644 index 0000000000..7319c73047 --- /dev/null +++ b/Task/Permutations/AutoHotkey/permutations-4.ahk @@ -0,0 +1 @@ +MsgBox % P("Hello",3) diff --git a/Task/Permutations/AutoHotkey/permutations-5.ahk b/Task/Permutations/AutoHotkey/permutations-5.ahk new file mode 100644 index 0000000000..2936a3d384 --- /dev/null +++ b/Task/Permutations/AutoHotkey/permutations-5.ahk @@ -0,0 +1 @@ +MsgBox % P("2`n3`n4`n5",2,3) diff --git a/Task/Permutations/AutoHotkey/permutations-6.ahk b/Task/Permutations/AutoHotkey/permutations-6.ahk new file mode 100644 index 0000000000..198f6d6fcd --- /dev/null +++ b/Task/Permutations/AutoHotkey/permutations-6.ahk @@ -0,0 +1 @@ +MsgBox % P("11 a text ] u+z",3,0," ") diff --git a/Task/Permutations/Perl-6/permutations-1.pl6 b/Task/Permutations/Perl-6/permutations-1.pl6 index 656677f74d..da76672c5b 100644 --- a/Task/Permutations/Perl-6/permutations-1.pl6 +++ b/Task/Permutations/Perl-6/permutations-1.pl6 @@ -1,8 +1 @@ -sub postfix:(@a) { - @a == 1 ?? [@a] !! - gather for @a -> $a { - take [ $a, @$_ ] for @a.grep(none $a)! - } -} - -.say for ! +.say for .permutations diff --git a/Task/Permutations/Perl-6/permutations-4.pl6 b/Task/Permutations/Perl-6/permutations-4.pl6 new file mode 100644 index 0000000000..808774164e --- /dev/null +++ b/Task/Permutations/Perl-6/permutations-4.pl6 @@ -0,0 +1 @@ +.say for permutations(3); diff --git a/Task/Pi/AutoHotkey/pi.ahk b/Task/Pi/AutoHotkey/pi.ahk new file mode 100644 index 0000000000..0ab775da0f --- /dev/null +++ b/Task/Pi/AutoHotkey/pi.ahk @@ -0,0 +1,66 @@ +#NoEnv +#SingleInstance, Force +SetBatchLines, -1 +#Include mpl.ahk +dot:=".", i:=0 +, MP_SET(q, "1") +, MP_SET(r, "0") +, MP_SET(t, "1") +, MP_SET(k, "1") +, MP_SET(n, "3") +, MP_SET(l, "3") +, MP_SET(ONE, "1") +, MP_SET(TWO, "2") +, MP_SET(THREE, "3") +, MP_SET(FOUR, "4") +, MP_SET(SEVEN, "7") +, MP_SET(TEN, "10") + +Loop +{ + MP_MUL(q4, q, FOUR) + , MP_ADD(q4r, q4, r) + , MP_SUB(q4rt, q4r, t) + , MP_MUL(tn, t, n) + If (MP_CMP(q4rt,tn) = -1) + { + s := MP_DEC(n) . dot + OutputDebug %s% + dot := "" + , i++ + , MP_MUL(tn, t, n) + , MP_SUB(rtn, r, tn) + , MP_MUL(nr, rtn, TEN) + , MP_MUL(q3, q, THREE) + , MP_ADD(q3r, q3, r) + , MP_DIV(q3rt, remainder, q3r, t) + , MP_SUB(q3rtn, q3rt, n) + , MP_MUL(n, q3rtn, TEN) + , MP_MUL(tmp, q, TEN) + , MP_CPY(q, tmp) + , MP_CPY(r, nr) + } + Else + { + MP_MUL(q2, q, TWO) + , MP_ADD(q2r, q2, r) + , MP_MUL(nr, q2r, l) + , MP_MUL(k7, k, SEVEN) + , MP_ADD(k72, k7, TWO) + , MP_MUL(qk, q, k72) + , MP_MUL(rl, r, l) + , MP_ADD(qkrl, qk, rl) + , MP_MUL(tl, t, l) + , MP_DIV(nn, remainder, qkrl, tl) + , MP_MUL(tmp, q, k) + , MP_CPY(q, tmp) + , MP_MUL(tmp, t, l) + , MP_CPY(t, tmp) + , MP_ADD(tmp, l, TWO) + , MP_CPY(l, tmp) + , MP_ADD(tmp, k, ONE) + , MP_CPY(k, tmp) + , MP_CPY(n, nn) + , MP_CPY(r, nr) + } +} diff --git a/Task/Pi/Haskell/pi.hs b/Task/Pi/Haskell/pi-1.hs similarity index 100% rename from Task/Pi/Haskell/pi.hs rename to Task/Pi/Haskell/pi-1.hs diff --git a/Task/Pi/Haskell/pi-2.hs b/Task/Pi/Haskell/pi-2.hs new file mode 100644 index 0000000000..a7784d93f1 --- /dev/null +++ b/Task/Pi/Haskell/pi-2.hs @@ -0,0 +1,18 @@ +#!/usr/bin/runhaskell + +import Control.Monad +import System.IO + +pi_ = g(1,0,1,1,3,3) where + g (q,r,t,k,n,l) = + if 4*q+r-t < n*t + then n : g (10*q, 10*(r-n*t), t, k, div (10*(3*q+r)) t - 10*n, l) + else g (q*k, (2*q+r)*l, t*l, k+1, div (q*(7*k+2)+r*l) (t*l), l+2) + +digs = insertPoint digs' + where insertPoint (x:xs) = x:'.':xs + digs' = map (head . show) pi_ + +main = do + hSetBuffering stdout $ BlockBuffering $ Just 80 + forM_ digs putChar diff --git a/Task/Pick-random-element/TXR/pick-random-element.txr b/Task/Pick-random-element/TXR/pick-random-element.txr index 69a0893ec4..d6a831ccbb 100644 --- a/Task/Pick-random-element/TXR/pick-random-element.txr +++ b/Task/Pick-random-element/TXR/pick-random-element.txr @@ -1,3 +1,3 @@ -@(do (defun randelem (vec) - (vecref vec (random nil (length vec))))) +@(do (defun randelem (seq) + [seq (random nil (length seq))])) @(bind x @(randelem #("a" "b" "c" "d"))) diff --git a/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk b/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk new file mode 100644 index 0000000000..edfc79ef74 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk @@ -0,0 +1,75 @@ +#NoEnv +SetBatchLines, -1 +#SingleInstance, Force +#Include Pig_the_dice_game_Optimal_Play.ahkl ; comment if you don't want to bother +Play:=10000 ; this is enough to give 2 digits of accuracy in win ratio +Wins0:=Wins1:=0 +Player0(TurnSum, SumMe, SumOpp) { + Return practical(TurnSum, SumMe, SumOpp) ; set first player function name +} +Player1(TurnSum, SumMe, SumOpp) { + Return optimal(TurnSum, SumMe, SumOpp) ; set second player function name +} + +Loop, % Play +{ + ;Random, FirstPlayer, 0, 1 ; to remove advantage of going first + CurrentPlayer := 0 ; set to FirstPlayer to compare same players with different N's + Sum0:=Sum1:=0 + Loop + { + OtherPlayer:=!CurrentPlayer + If (Sum%CurrentPlayer%+TurnSum < 100 + and Player%CurrentPlayer%(TurnSum, Sum%CurrentPlayer%, Sum%OtherPlayer%)) + { + ; Roll + Random, LastRoll, 1, 6 + If (LastRoll != 1) + { + TurnSum += LastRoll + Continue + } + TurnSum := 0 + } + ; Hold + Sum%CurrentPlayer% += TurnSum + TurnSum := 0 + If (Sum%CurrentPlayer% >= 100) + { + Wins%CurrentPlayer%++ + Break + } + CurrentPlayer := !CurrentPlayer + } +} +Msgbox % "Player 0 won " Round(Wins0/Play*100,0) "%`nPlayer 1 won " Round(Wins1/Play*100,0) "%" + +; Random; 1/N is ~ probablity of holding +Random(TurnSum, SumMe, SumOpp, N=9) { + Random, Roll, 0, N ; increase this last number to increase probability of rolling + Return Roll +} +; Always roll +Always(TurnSum, SumMe, SumOpp) { + Return 1 +} +; Roll N times; N=6 beats all other RollNx players +RollNx(TurnSum, SumMe, SumOpp, N=6) { + Static Roll=0 + Return Roll := TurnSum = 0 ? 1 : mod(Roll+1,N+1) +} +; Roll if TurnSum < N; N=19 beats all other RollToN players +RollToN(TurnSum, SumMe, SumOpp, N=19) { + Return Roll := TurnSum < N +} +; Roll if SumOpp > N or SumMe > N or TurnSum < 21 + (SumOpp - SumMe) / 8 +Practical(TurnSum, SumMe, SumOpp, N=72) { + Return Roll := SumOpp > N or SumMe > N or TurnSum < 21+(SumOpp-SumMe)/8 +} +; Optimal play per http://cs.gettysburg.edu/~tneller/nsf/pig/pig.pdf +; Requires additional file from [[Pig the dice game/Player/AutoHotkey]] +Optimal(TurnSum, SumMe, SumOpp) { + Global Optimal + Roll := Optimal[SumMe,TurnSum,SumOpp+1] + Return Roll = "" ? 1 : Roll +} diff --git a/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d b/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d index 7af1e74559..8659c93b77 100644 --- a/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d +++ b/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d @@ -77,15 +77,10 @@ final class PlayerAL20T: Player { } void main() { - //Player[nPlayers] players = [new PlayerRand, new PlayerQ2Win, - // new PlayerAL20, new PlayerAL20T]; - Player[nPlayers] players; - players[0] = new PlayerRand; - players[1] = new PlayerQ2Win; - players[2] = new PlayerAL20; - players[3] = new PlayerAL20T; + auto players = [new PlayerRand, new PlayerQ2Win, + new PlayerAL20, new PlayerAL20T]; - void nextTurn(ref uint p) { + void nextTurn(ref uint p) nothrow { players[p].zeroRoundScore; p = (p + 1) % nPlayers; } diff --git a/Task/Pig-the-dice-game/AutoHotkey/pig-the-dice-game.ahk b/Task/Pig-the-dice-game/AutoHotkey/pig-the-dice-game.ahk new file mode 100644 index 0000000000..dc207b8fd7 --- /dev/null +++ b/Task/Pig-the-dice-game/AutoHotkey/pig-the-dice-game.ahk @@ -0,0 +1,47 @@ +Gui, Font, s12, Verdana +Gui, Add, Text, vPlayer0, Player 0 +Gui, Add, Text, vSum0, 000 +Gui, Add, Button, Default, Roll +Gui, Add, Text, ys vLastRoll, Roll 0 +Gui, Add, Text, vTurnSum, Sum 000 +Gui, Add, Button, , Hold +Gui, Add, Text, ys vPlayer1, Player 1 +Gui, Add, Text, vSum1, 000 +Gui, Add, Button, , Reload +Gui, Show +GuiControl, Disable, Player1 + +CurrentPlayer := 0 +ButtonRoll: +Loop 10 +{ + Random, LastRoll, 1, 6 + GuiControl, , LastRoll, Roll %LastRoll% + Sleep 50 +} +If LastRoll != 1 +{ + TurnSum += LastRoll + GuiControl, , TurnSum, Sum %TurnSum% + Return +} +TurnSum := 0 +ButtonHold: +Sum%CurrentPlayer% += TurnSum +TurnSum := 0 +GuiControl, , LastRoll, Roll +GuiControl, , TurnSum, Sum %TurnSum% +GuiControl, , Sum%CurrentPlayer%, % Sum%CurrentPlayer% +If Sum%CurrentPlayer% >= 100 +{ + MsgBox Player %CurrentPlayer% Won! + GuiClose: + ExitApp +} +GuiControl, Disable, Player%CurrentPlayer% +CurrentPlayer := !CurrentPlayer +GuiControl, Enable, Player%CurrentPlayer% +Return + +ButtonReload: +Reload diff --git a/Task/Pig-the-dice-game/C-sharp/pig-the-dice-game.cs b/Task/Pig-the-dice-game/C-sharp/pig-the-dice-game.cs new file mode 100644 index 0000000000..9cbf9f70cc --- /dev/null +++ b/Task/Pig-the-dice-game/C-sharp/pig-the-dice-game.cs @@ -0,0 +1,115 @@ +using System; +using System.IO; + +namespace Pig { + + class Roll { + public int TotalScore{get;set;} + public int RollScore{get;set;} + public bool Continue{get;set;} + } + + class Player { + public String Name{get;set;} + public int Score {get;set;} + Random rand; + + public Player() { + Score = 0; + rand = new Random(); + } + + public Roll Roll(int LastScore){ + Roll roll = new Roll(); + roll.RollScore = rand.Next(6) + 1; + + if(roll.RollScore == 1){ + roll.TotalScore = 0; + roll.Continue = false; + return roll; + } + + roll.TotalScore = LastScore + roll.RollScore; + roll.Continue = true; + return roll; + } + + public void FinalizeTurn(Roll roll){ + Score = Score + roll.TotalScore; + } + } + + public class Game { + public static void Main(String[] argv){ + String input = null; + Player[] players = new Player[2]; + + // Game loop + while(true){ + Console.Write("Greetings! Would you like to play a game (y/n)?"); + while(input == null){ + input = Console.ReadLine(); + if(input.ToLowerInvariant() == "y"){ + players[0] = new Player(); + players[1] = new Player(); + Console.Write("Player One, what's your name?"); + input = Console.ReadLine(); + players[0].Name = input; + Console.Write("Player Two, what's your name?"); + input = Console.ReadLine(); + players[1].Name = input; + Console.WriteLine(players[0].Name + " and " + players[1].Name + ", prepare to do battle!"); + } else if (input.ToLowerInvariant() == "n"){ + goto Goodbye; /* Not considered harmful */ + } else { + input = null; + Console.Write("I'm sorry, I don't understand. Play a game (y/n)?"); + } + } + + // Play the game + int currentPlayer = 0; + Roll roll = null; + bool runTurn = true; + while(runTurn){ + Player p = players[currentPlayer]; + roll = p.Roll( (roll !=null) ? roll.TotalScore : 0 ); + if(roll.Continue){ + if(roll.TotalScore + p.Score > 99){ + Console.WriteLine("Congratulations, " + p.Name + "! You rolled a " + roll.RollScore + " for a final score of " + (roll.TotalScore + p.Score) + "!"); + runTurn = false; + } else { + Console.Write(p.Name + ": Roll " + roll.RollScore + "/Turn " + roll.TotalScore + "/Total " + (roll.TotalScore + p.Score) + ". Roll again (y/n)?"); + input = Console.ReadLine(); + if(input.ToLowerInvariant() == "y"){ + // Do nothing + } else if (input.ToLowerInvariant() == "n"){ + p.FinalizeTurn(roll); + currentPlayer = Math.Abs(currentPlayer - 1); + Console.WriteLine(); + Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score); + Console.WriteLine(players[currentPlayer].Name + ", your turn begins."); + roll = null; + } else { + input = null; + Console.Write("I'm sorry, I don't understand. Play a game (y/n)?"); + } + } + } else { + Console.WriteLine(p.Name + @", you rolled a 1 and lost your points for this turn. +Your current score: " + p.Score); + Console.WriteLine(); + Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score); + currentPlayer = Math.Abs(currentPlayer - 1); + } + } + + + input = null; + } + Goodbye: + Console.WriteLine("Thanks for playing, and remember: the house ALWAYS wins!"); + System.Environment.Exit(0); + } + } +} diff --git a/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx b/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx index 83cf5fa485..e1fc9c5554 100644 --- a/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx +++ b/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx @@ -1,54 +1,60 @@ -/*REXX program plays pig (the dice game) with at least one human player.*/ +/*REXX program plays pig the dice game (any # of CBLFs and/or silicons).*/ signal on syntax; signal on novalue /*handle REXX program errors. */ sw=80-1 /*the LINESIZE bif would be nicer*/ parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments.*/ + /*names with blanks should use _ */ if _\=='' then call err 'too many arguments were specified: ' _ -@nhp = 'number of human players' ; hp = scrutinize( hp, @nhp ,0, 0) -@ncp = 'number of computer players'; cp = scrutinize( cp, @ncp ,0, 0) -@sn2w = 'score needed to win' ; win = scrutinize(win, @sn2w ,1,100) -@nsid = 'number of sides in die' ; die = scrutinize(die, @nsid ,2, 6) +@nhp = 'number of human players' ; hp =scrutinize( hp,@nhp , 0, 0, 0) +@ncp = 'number of computer players'; cp =scrutinize( cp,@ncp , 0, 0, 2) +@sn2w = 'score needed to win' ; win=scrutinize(win,@sn2w, 1,1e6,60) +@nsid = 'number of sides in die' ; die=scrutinize(die,@nsid, 2,999, 6) if hp==0 & cp==0 then cp=2 /*if both counts are zero, 2 HALs*/ if hp==1 & cp==0 then cp=1 /*if one human, then use 1 HAL.*/ +name.= /*nullify all names (to a blank).*/ L=0 /*maximum length of a player name*/ do i=1 for hp+cp /*get the player's names, maybe. */ if i>hp then @='HAL_'i"_the_computer" /*use this for default.*/ else @='player_'i /* " " " " */ name.i = translate( word( strip( word(names,i)) @, 1),,'_') L=max(L, length(name.i)) /*use L for nice name formatting.*/ - end /*i*/ /*underscores are changed─�blanks*/ + end /*i*/ /*underscores are changed─►blanks*/ hpn=hp; if hpn==0 then hpn='no' /*use normal English for display.*/ cpn=cp; if cpn==0 then cpn="no" /* " " " " " */ -say 'Pig (the dice game) is being played with' +say 'Pig (the dice game) is being played with:' /*introduction to pig.*/ if cpn\==0 then say right(cpn,9) 'computer player's(cp) if hpn\==0 then say right(hpn,9) 'human player's(hp) say 'and the' @sn2w "is: " win ' (or greater).' -!.=; dieNames='ace duece trey square nickle boxcar' /*die face names.*/ +!.=; dieNames='ace deuce trey square nickle boxcar' /*die face names.*/ /*note: snake eyes is for 2 aces.*/ - do i=1 for 6; !.i=' ['word(dieNames,i)"] "; end /*i*/ +!w=0; do i=1 for die; !.i=' ['word(dieNames,i)"]" + !w=max(!w, length(!.i)) /*!w ──► maximum length die name.*/ + end /*i*/ s.=0 /*set all player's scores to zero*/ +!w=!w+length(die)+3 /*pad the die number and die name*/ @=copies('─',9) /*an eyecatcher (for prompting). */ -@jra='just rolled a '; @ati=', and the inning' /*nice literals to have.*/ +@jra='just rolled a '; @ati='and the inning' /*nice literals to have.*/ /*──────────────────────────────────────────────────let's play some pig.*/ do game=1; in.=0 /*set each inning's score to zero*/ say; say copies('█',sw) /*display a fence for da eyeballs*/ - do k=1 for hp+cp /*display the scores (as a recap)*/ - say 'The score for' left(name.k,L) "is " right(s.k,length(win))'.' - end /*k*/ + do k=1 for hp+cp /*display the scores (as a recap)*/ + say 'The score for ' left(name.k,L) " is " right(s.k,length(win))'.' + end /*k*/ say copies('█',sw) /*display a fence for da eyeballs*/ do j=1 for hp+cp /*let each player roll their dice*/ say; say copies('─',sw); /*display a fence for da eyeballs*/ - it=word('You It', 1 + (j>hp)) /*pronoun choice: You or It */ - say name.j', your total score (so far) in this pig game is:' s.j"." + it=name.j + say it', your total score (so far) in this pig game is: ' s.j"." - do until stopped /*keep prompting/rolling 'til not*/ - r=random(1,die); !=space(r !.r) /*for color, use a die-face name.*/ - in.j=in.j+r + do until stopped /*keep prompting/rolling 'til not*/ + r=random(1,die) /*get a random die face (number).*/ + !=left(space(r !.r','), !w) /*for color, use a die-face name.*/ + in.j=in.j+r /*add die-face number to inning. */ if r==1 then do; say it @jra ! || @ati "is a bust."; leave; end - say it @jra ! || @ati "total is:" in.j + say it @jra ! || @ati "total is: " in.j stopped=what2do(j) /*determine|ask to stop rolling.*/ if j>hp & stopped then say ' and' name.j "elected to stop rolling." end /*until stopped*/ @@ -63,18 +69,20 @@ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────S subroutine────────────────────────*/ s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural?*/ /*──────────────────────────────────SCRUTINIZE subroutine───────────────*/ -scrutinize: parse arg ?,what,minimum /*? is the number, or maybe not. */ -if ?=='' | ?==',' then return arg(4) +scrutinize: parse arg ?,what,min,max /*? is the number, or maybe not. */ +if ?=='' | ?==',' then return arg(5) if \datatype(?,'N') then call err what "isn't numeric: " ?; ?=?/1 if \datatype(?,'W') then call err what "isn't an integer: " ? -if ?==0 & minimum>0 then call err what "can't be zero." -if ?0 then call err what "can't be zero." +if ?0 then call err what "can't be zero." +if ?>max & max\==0 then call err what "can't be greater than" max': ' ? return ? /*──────────────────────────────────what2do subroutine──────────────────*/ what2do: parse arg who /*"who" is a human or a computer.*/ -if (j>hp & r+in.j>=win) then return 1 /*an easy choice for HAL.*/ -if (j>hp & in.j>=win%4) then return 1 /*a simple stategy for HAL.*/ -if j>hp then return 0 /*HAL says, keep truckin'! */ +if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL.*/ +if j>hp & in.j>=win%4 then return 1 /*a simple stategy for HAL.*/ +if j>hp then return 0 /*HAL says, keep truckin'! */ say @ name.who', what do you want to do? (a QUIT will stop the game),' say @ 'press ENTER to roll again, or anything else to STOP rolling.' pull action; action=space(action) /*remove any superfluous blanks. */ diff --git a/Task/Playing-cards/AutoHotkey/playing-cards.ahk b/Task/Playing-cards/AutoHotkey/playing-cards-1.ahk similarity index 97% rename from Task/Playing-cards/AutoHotkey/playing-cards.ahk rename to Task/Playing-cards/AutoHotkey/playing-cards-1.ahk index 9487e146e8..b6a33d1ddd 100644 --- a/Task/Playing-cards/AutoHotkey/playing-cards.ahk +++ b/Task/Playing-cards/AutoHotkey/playing-cards-1.ahk @@ -7,7 +7,7 @@ Loop, 52 ? "diamonds" : ((card%A_Index%) <= 24) ? "hearts" : ((card%A_Index% <= 36) ? "clubs" - : "spades"))) + : "spades")) allcards .= card%A_Index% . "`n" } currentcard = 1 diff --git a/Task/Playing-cards/AutoHotkey/playing-cards-2.ahk b/Task/Playing-cards/AutoHotkey/playing-cards-2.ahk new file mode 100644 index 0000000000..8e0f9533c4 --- /dev/null +++ b/Task/Playing-cards/AutoHotkey/playing-cards-2.ahk @@ -0,0 +1,44 @@ +Deck:=new Deck +Deck.Shuffle() +msgbox % Deck.Show() +loop, 2 + msgbox % Deck.Deal().Show() +msgbox % Deck.Show() +Return ;------------------------------------------------------------------- + +class Card +{ + __New(Pip, Suit) { + this.Pip:=Pip, this.Suit:=Suit + } + Show() { + Return this.Pip . this.Suit + } +} + +class Deck +{ + Suits:={1:"♣",2:"♦",3:"♠",4:"♥"} + Pips:={13:"A",1:"2",2:"3",3:"4",4:"5",5:"6",6:"7",7:"8",8:"9",9:"T",10:"J",11:"Q",12:"K"} + + __New() { + this.Deck:=[] + For i, Pip in this.Pips + For j, Suit in this.Suits + this.Deck.Insert(new Card(Pip,Suit)) + } + Shuffle() { ; Knuth Shuffle from http://rosettacode.org/wiki/Knuth_Shuffle#AutoHotkey + Loop % this.Deck.MaxIndex()-1 { + Random, i, A_Index, this.Deck.MaxIndex() ; swap item 1,2... with a random item to the right of it + temp := this.Deck[i], this.Deck[i] := this.Deck[A_Index], this.Deck[A_Index] := temp + } + } + Deal() { + Return this.Deck.Remove() ; to deal from bottom, use Remove(1) + } + Show() { + For i, Card in this.Deck + s .= Card.Show() " " + Return s + } +} diff --git a/Task/Plot-coordinate-pairs/AutoHotkey/plot-coordinate-pairs.ahk b/Task/Plot-coordinate-pairs/AutoHotkey/plot-coordinate-pairs.ahk new file mode 100644 index 0000000000..c19971af93 --- /dev/null +++ b/Task/Plot-coordinate-pairs/AutoHotkey/plot-coordinate-pairs.ahk @@ -0,0 +1,69 @@ +#SingleInstance, Force +#NoEnv +SetBatchLines, -1 +OnExit, Exit +FileOut := A_Desktop "\MyNewFile.png" +Font := "Arial" +x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +y := [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] +; Uncomment if Gdip.ahk is not in your standard library +; #Include, Gdip.ahk +if (!pToken := Gdip_Startup()) { + MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. + ExitApp +} +If (!Gdip_FontFamilyCreate(Font)) { + MsgBox, 48, Font error!, The font you have specified does not exist on your system. + ExitApp +} + +pBitmap := Gdip_CreateBitmap(900, 900) +, G := Gdip_GraphicsFromImage(pBitmap) +, Gdip_SetSmoothingMode(G, 4) +, pBrush := Gdip_BrushCreateSolid(0xff000000) +, Gdip_FillRectangle(G, pBrush, -3, -3, 906, 906) +, Gdip_DeleteBrush(pBrush) +, pPen1 := Gdip_CreatePen(0xffffcc00, 2) +, pPen2 := Gdip_CreatePen(0xffffffff, 2) +, pPen3 := Gdip_CreatePen(0xff447821, 1) +, pPen4 := Gdip_CreatePen(0xff0066ff, 2) +, Gdip_DrawLine(G, pPen2, 50, 50, 50, 850) +, Gdip_DrawLine(G, pPen2, 50, 850, 850, 850) +, FontOptions1 := "x0 y870 Right cbbffffff r4 s16 Bold" +, Gdip_TextToGraphics(G, 0, FontOptions1, Font, 40, 20) + +Loop, % x.MaxIndex() - 1 { + Offset1 := 50 + (x[A_Index] * 80) + , Offset2 := Offset1 + 80 + , Gdip_DrawLine(G, pPen1, Offset1, 850 - (y[A_Index] * 4), Offset1 + 80, 850 - (y[A_Index + 1] * 4)) +} + +Loop, % x.MaxIndex() { + Offset1 := 50 + ((A_Index - 1) * 80) + , Offset2 := Offset1 + 80 + , Offset3 := 45 + (x[A_Index] * 80) + , Offset4 := 845 - (y[A_Index] * 4) + , Gdip_DrawLine(G, pPen2, 45, Offset1, 55, Offset1) + , Gdip_DrawLine(G, pPen2, Offset2, 845, Offset2, 855) + , Gdip_DrawLine(G, pPen3, 50, Offset1, 850, Offset1) + , Gdip_DrawLine(G, pPen3, Offset2, 50, Offset2, 850) + , Gdip_DrawLine(G, pPen4, Offset3, Offset4, Offset3 + 10, Offset4 + 10) + , Gdip_DrawLine(G, pPen4, Offset3, Offset4 + 10, Offset3 + 10, Offset4) + , FontOptions1 := "x0 y" (Offset1 - 7) " Right cbbffffff r4 s16 Bold" + , FontOptions2 := "x" (Offset2 - 7) " y870 Left cbbffffff r4 s16 Bold" + , Gdip_TextToGraphics(G, 220 - (A_Index * 20), FontOptions1, Font, 40, 20) + , Gdip_TextToGraphics(G, A_Index, FontOptions2, Font, 40, 20) +} + +Gdip_DeletePen(pPen1) +, Gdip_DeletePen(pPen2) +, Gdip_DeletePen(pPen3) +, Gdip_DeletePen(pPen4) +, Gdip_SaveBitmapToFile(pBitmap, FileOut) +, Gdip_DisposeImage(pBitmap) +, Gdip_DeleteGraphics(G) +Run, % FileOut + +Exit: +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia b/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia new file mode 100644 index 0000000000..13d836ffa8 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia @@ -0,0 +1,6 @@ +using PyPlot + +x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] +plot(x,y, "bo") +savefig("qsort-range-10-9.png") diff --git a/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs.rexx b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs.rexx new file mode 100644 index 0000000000..7a0cc5acef --- /dev/null +++ b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs.rexx @@ -0,0 +1,9 @@ +/*REXX program plots coördinate pairs of numbers with plain characters. */ +x = 0 1 2 3 4 5 6 7 8 9 +y = 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 +$= + do j=1 for words(x) /*build a list suitable for $PLOT*/ + $=$ word(x,j)','word(y,j) + end /*j*/ /*$≡ 0,2.7 1,2.8 2,31.4 ···*/ +call '$PLOT' $ /*invoke the REXX program: $PLOT.*/ +exit rc /*stick a fork in it, we're done.*/ diff --git a/Task/Polymorphic-copy/Objective-C/polymorphic-copy.m b/Task/Polymorphic-copy/Objective-C/polymorphic-copy.m index ff31acdb69..f405ec82d3 100644 --- a/Task/Polymorphic-copy/Objective-C/polymorphic-copy.m +++ b/Task/Polymorphic-copy/Objective-C/polymorphic-copy.m @@ -1,5 +1,4 @@ @interface T : NSObject -{ } - (void)identify; @end @@ -17,7 +16,6 @@ @end @interface S : T -{ } @end @implementation S @@ -29,11 +27,12 @@ int main() { - T *original = [[S alloc] init]; - T *another = [original copy]; - [another identify]; // logs "I am an S" + @autoreleasepool { - [another release]; // like "alloc", the object returned by "copy" is "owned" by the caller, so we are responsible for releasing it - [original release]; + T *original = [[S alloc] init]; + T *another = [original copy]; + [another identify]; // logs "I am an S" + + } return 0; } diff --git a/Task/Polymorphic-copy/Racket/polymorphic-copy-2.rkt b/Task/Polymorphic-copy/Racket/polymorphic-copy-2.rkt index 10496b43f8..ef0790a394 100644 --- a/Task/Polymorphic-copy/Racket/polymorphic-copy-2.rkt +++ b/Task/Polymorphic-copy/Racket/polymorphic-copy-2.rkt @@ -1,16 +1,19 @@ -;#lang racket +#lang racket/base -(define point% - (class object% - (super-new) - (init-field x y) - (define/public (clone) (new this% [x x] [y y])) - (define/public (to-list) (list this% x y)))) +(define (copy-struct str) + (define-values (str-struct-info _) (struct-info str)) + (define str-maker (struct-type-make-constructor str-struct-info)) + (apply str-maker (cdr (vector->list (struct->vector str))))) -(define point/color% - (class point% - (super-new) - (inherit-field x y) - (init-field color) - (define/override (clone) (new this% [x x] [y y] [color color])) - (define/override (to-list) (list this% x y color)))) +(struct point (x y) #:transparent) +(struct point/color point (color) #:transparent) + +(let* ([original (point 0 0)] + [copied (copy-struct original)]) + (displayln copied) + (displayln (eq? original copied))) + +(let* ([original (point/color 0 0 'black)] + [copied (copy-struct original)]) + (displayln copied) + (displayln (eq? original copied))) diff --git a/Task/Polymorphic-copy/Racket/polymorphic-copy-3.rkt b/Task/Polymorphic-copy/Racket/polymorphic-copy-3.rkt new file mode 100644 index 0000000000..10496b43f8 --- /dev/null +++ b/Task/Polymorphic-copy/Racket/polymorphic-copy-3.rkt @@ -0,0 +1,16 @@ +;#lang racket + +(define point% + (class object% + (super-new) + (init-field x y) + (define/public (clone) (new this% [x x] [y y])) + (define/public (to-list) (list this% x y)))) + +(define point/color% + (class point% + (super-new) + (inherit-field x y) + (init-field color) + (define/override (clone) (new this% [x x] [y y] [color color])) + (define/override (to-list) (list this% x y color)))) diff --git a/Task/Polymorphism/Objective-C/polymorphism.m b/Task/Polymorphism/Objective-C/polymorphism.m index 5d3c193911..f9daac981d 100644 --- a/Task/Polymorphism/Objective-C/polymorphism.m +++ b/Task/Polymorphism/Objective-C/polymorphism.m @@ -3,71 +3,71 @@ @interface RCPoint : NSObject { int x, y; } --(id)initWithX:(int)x0; --(id)initWithX:(int)x0 andY:(int)y0; --(id)initWithPoint:(RCPoint *)p; +-(instancetype)initWithX:(int)x0; +-(instancetype)initWithX:(int)x0 andY:(int)y0; +-(instancetype)initWithPoint:(RCPoint *)p; @property (nonatomic) int x; @property (nonatomic) int y; @end @implementation RCPoint @synthesize x, y; --(id)initWithX:(int)x0 { return [self initWithX:x0 andY:0]; } --(id)initWithX:(int)x0 andY:(int)y0 { +-(instancetype)initWithX:(int)x0 { return [self initWithX:x0 andY:0]; } +-(instancetype)initWithX:(int)x0 andY:(int)y0 { if ((self = [super init])) { x = x0; y = y0; } return self; } --(id)initWithPoint:(RCPoint *)p { return [self initWithX:p.x andY:p.y]; } +-(instancetype)initWithPoint:(RCPoint *)p { return [self initWithX:p.x andY:p.y]; } -(NSString *)description { return [NSString stringWithFormat:@"", self, x, y]; } @end @interface RCCircle : RCPoint { int r; } --(id)initWithCenter:(RCPoint *)p andRadius:(int)r0; --(id)initWithX:(int)x0 andY:(int)y0 andRadius:(int)r0; --(id)initWithCircle:(RCCircle *)c; +-(instancetype)initWithCenter:(RCPoint *)p andRadius:(int)r0; +-(instancetype)initWithX:(int)x0 andY:(int)y0 andRadius:(int)r0; +-(instancetype)initWithCircle:(RCCircle *)c; @property (nonatomic) int r; @end @implementation RCCircle @synthesize r; --(id)initWithCenter:(RCPoint *)p andRadius:(int)r0 { +-(instancetype)initWithCenter:(RCPoint *)p andRadius:(int)r0 { if ((self = [super initWithPoint:p])) { r = r0; } return self; } --(id)initWithX:(int)x0 andY:(int)y0 andRadius:(int)r0 { +-(instancetype)initWithX:(int)x0 andY:(int)y0 andRadius:(int)r0 { if ((self = [super initWithX:x0 andY:y0])) { r = r0; } return self; } --(id)initWithCircle:(RCCircle *)c { return [self initWithX:c.x andY:c.y andRadius:c.r]; } +-(instancetype)initWithCircle:(RCCircle *)c { return [self initWithX:c.x andY:c.y andRadius:c.r]; } -(NSString *)description { return [NSString stringWithFormat:@"", self, x, y, r]; } @end int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSLog(@"%@", [[[RCPoint alloc] init] autorelease]); - NSLog(@"%@", [[[RCPoint alloc] initWithX:3] autorelease]); - NSLog(@"%@", [[[RCPoint alloc] initWithX:3 andY:4] autorelease]); - NSLog(@"%@", [[[RCCircle alloc] init] autorelease]); - NSLog(@"%@", [[[RCCircle alloc] initWithX:3] autorelease]); - NSLog(@"%@", [[[RCCircle alloc] initWithX:3 andY:4] autorelease]); - NSLog(@"%@", [[[RCCircle alloc] initWithX:3 andY:4 andRadius:7] autorelease]); - RCPoint *p = [[[RCPoint alloc] initWithX:1 andY:2] autorelease]; - NSLog(@"%@", [[[RCCircle alloc] initWithPoint:p] autorelease]); - NSLog(@"%@", [[[RCCircle alloc] initWithCenter:p andRadius:7] autorelease]); - NSLog(@"%d", p.x); // 1 - p.x = 8; - NSLog(@"%d", p.x); // 8 + NSLog(@"%@", [[RCPoint alloc] init]); + NSLog(@"%@", [[RCPoint alloc] initWithX:3]); + NSLog(@"%@", [[RCPoint alloc] initWithX:3 andY:4]); + NSLog(@"%@", [[RCCircle alloc] init]); + NSLog(@"%@", [[RCCircle alloc] initWithX:3]); + NSLog(@"%@", [[RCCircle alloc] initWithX:3 andY:4]); + NSLog(@"%@", [[RCCircle alloc] initWithX:3 andY:4 andRadius:7]); + RCPoint *p = [[RCPoint alloc] initWithX:1 andY:2]; + NSLog(@"%@", [[RCCircle alloc] initWithPoint:p]); + NSLog(@"%@", [[RCCircle alloc] initWithCenter:p andRadius:7]); + NSLog(@"%d", p.x); // 1 + p.x = 8; + NSLog(@"%d", p.x); // 8 - [pool release]; + } return 0; } diff --git a/Task/Power-set/C/power-set.c b/Task/Power-set/C/power-set.c new file mode 100644 index 0000000000..9c93d30475 --- /dev/null +++ b/Task/Power-set/C/power-set.c @@ -0,0 +1,31 @@ +#include + +struct node { + char *s; + struct node* prev; +}; + +void powerset(char **v, int n, struct node *up) +{ + struct node me; + + if (!n) { + putchar('['); + while (up) { + printf(" %s", up->s); + up = up->prev; + } + puts(" ]"); + } else { + me.s = *v; + me.prev = up; + powerset(v + 1, n - 1, up); + powerset(v + 1, n - 1, &me); + } +} + +int main(int argc, char **argv) +{ + powerset(argv + 1, argc - 1, 0); + return 0; +} diff --git a/Task/Power-set/Clojure/power-set.clj b/Task/Power-set/Clojure/power-set-1.clj similarity index 71% rename from Task/Power-set/Clojure/power-set.clj rename to Task/Power-set/Clojure/power-set-1.clj index 95cb24d980..1fe236f552 100644 --- a/Task/Power-set/Clojure/power-set.clj +++ b/Task/Power-set/Clojure/power-set-1.clj @@ -1,4 +1,4 @@ -(use '[clojure.contrib.combinatorics :only [subsets] ]) +(use '[clojure.math.combinatorics :only [subsets] ]) (def S #{1 2 3 4}) diff --git a/Task/Power-set/Clojure/power-set-2.clj b/Task/Power-set/Clojure/power-set-2.clj new file mode 100644 index 0000000000..3b1bdac390 --- /dev/null +++ b/Task/Power-set/Clojure/power-set-2.clj @@ -0,0 +1,7 @@ +(defn powerset + [coll] + (reduce (fn [a x] + (set (concat a (map #(set (concat #{x} %)) a)))) + #{#{}} coll)) + +(powerset #{1 2 3}) diff --git a/Task/Power-set/Clojure/power-set-3.clj b/Task/Power-set/Clojure/power-set-3.clj new file mode 100644 index 0000000000..736b7749f9 --- /dev/null +++ b/Task/Power-set/Clojure/power-set-3.clj @@ -0,0 +1 @@ +#{#{} #{1} #{2} #{1 2} #{3} #{1 3} #{2 3} #{1 2 3}} diff --git a/Task/Power-set/D/power-set-2.d b/Task/Power-set/D/power-set-2.d index 471e6e8a7a..15761ed49e 100644 --- a/Task/Power-set/D/power-set-2.d +++ b/Task/Power-set/D/power-set-2.d @@ -1,4 +1,4 @@ -auto powerSet(T)(T[] xs) { +auto powerSet(T)(T[] xs) pure nothrow { auto output = new T[xs.length]; immutable size_t len = 1U << xs.length; diff --git a/Task/Power-set/Maple/power-set.maple b/Task/Power-set/Maple/power-set.maple new file mode 100644 index 0000000000..c042354261 --- /dev/null +++ b/Task/Power-set/Maple/power-set.maple @@ -0,0 +1,3 @@ +with(combinat): + +powerset({1,2,3,4}); diff --git a/Task/Power-set/Objective-C/power-set.m b/Task/Power-set/Objective-C/power-set.m index 7fe7db7afb..69bd97e57e 100644 --- a/Task/Power-set/Objective-C/power-set.m +++ b/Task/Power-set/Objective-C/power-set.m @@ -7,11 +7,10 @@ NSMutableArray *subset = [[NSMutableArray alloc] init]; for (int itemIndex = 0; itemIndex < array.count; itemIndex++) { if((subsetIndex >> itemIndex) & 0x1) { - [subset addObject:[array objectAtIndex:itemIndex]]; + [subset addObject:array[itemIndex]]; } } [subsets addObject:subset]; - [subset release]; } return subsets; } diff --git a/Task/Power-set/Perl-6/power-set-1.pl6 b/Task/Power-set/Perl-6/power-set-1.pl6 new file mode 100644 index 0000000000..04fd04edfd --- /dev/null +++ b/Task/Power-set/Perl-6/power-set-1.pl6 @@ -0,0 +1,2 @@ +sub powerset(Set $s) { $s.combinations.map(*.Set).Set } +say powerset set ; diff --git a/Task/Power-set/Perl-6/power-set-2.pl6 b/Task/Power-set/Perl-6/power-set-2.pl6 new file mode 100644 index 0000000000..df24efe839 --- /dev/null +++ b/Task/Power-set/Perl-6/power-set-2.pl6 @@ -0,0 +1 @@ +.say for .combinations diff --git a/Task/Power-set/Perl-6/power-set.pl6 b/Task/Power-set/Perl-6/power-set.pl6 deleted file mode 100644 index 667b5c22b6..0000000000 --- a/Task/Power-set/Perl-6/power-set.pl6 +++ /dev/null @@ -1,3 +0,0 @@ -sub powerset ( *@list ) { - reduce( -> @L, $n { [ @L, @L.map({[ $_.list, $n ]}) ] }, [[]], @list ); -} diff --git a/Task/Power-set/Perl/power-set-1.pl b/Task/Power-set/Perl/power-set-1.pl index 9a1d09f9bc..9a53bbc995 100644 --- a/Task/Power-set/Perl/power-set-1.pl +++ b/Task/Power-set/Perl/power-set-1.pl @@ -1 +1,14 @@ -sub p{@_?map{$_,[$_[0],@$_]}p(@_[1..$#_]):[]} +use Set::Object qw(set); + +sub powerset { + my $p = Set::Object->new( set() ); + foreach my $i (shift->elements) { + $p->insert( map { set($_->elements, $i) } $p->elements ); + } + return $p; +} + +my $set = set(1, 2, 3); +my $powerset = powerset($set); + +print $powerset->as_string, "\n"; diff --git a/Task/Power-set/Perl/power-set-2.pl b/Task/Power-set/Perl/power-set-2.pl index fee44b1b34..14835dd1be 100644 --- a/Task/Power-set/Perl/power-set-2.pl +++ b/Task/Power-set/Perl/power-set-2.pl @@ -1,4 +1,6 @@ -use List::Util qw(reduce); -sub powerset { - @{ (reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_) } +package Set { + sub new { bless { map {$_ => undef} @_[1..$#_] }, shift; } + sub elements { sort keys %{shift()} } + sub as_string { 'Set(' . join(' ', sort keys %{shift()}) . ')' } + # ...more set methods could be defined here... } diff --git a/Task/Power-set/Perl/power-set-3.pl b/Task/Power-set/Perl/power-set-3.pl new file mode 100644 index 0000000000..fc22e29c83 --- /dev/null +++ b/Task/Power-set/Perl/power-set-3.pl @@ -0,0 +1,11 @@ +use List::Util qw(reduce); + +sub powerset { + @{( reduce { [@$a, map { Set->new($_->elements, $b) } @$a ] } + [Set->new()], shift->elements )}; +} + +my $set = Set->new(1, 2, 3); +my @subsets = powerset($set); + +print $_->as_string, "\n" for @subsets; diff --git a/Task/Power-set/Perl/power-set-4.pl b/Task/Power-set/Perl/power-set-4.pl new file mode 100644 index 0000000000..90f5ed87c2 --- /dev/null +++ b/Task/Power-set/Perl/power-set-4.pl @@ -0,0 +1,3 @@ +sub powerset { + @_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : []; +} diff --git a/Task/Power-set/Perl/power-set-5.pl b/Task/Power-set/Perl/power-set-5.pl new file mode 100644 index 0000000000..f9cea5d06c --- /dev/null +++ b/Task/Power-set/Perl/power-set-5.pl @@ -0,0 +1,5 @@ +use List::Util qw(reduce); + +sub powerset { + @{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )} +} diff --git a/Task/Power-set/Perl/power-set-6.pl b/Task/Power-set/Perl/power-set-6.pl new file mode 100644 index 0000000000..3d2864f0fb --- /dev/null +++ b/Task/Power-set/Perl/power-set-6.pl @@ -0,0 +1,8 @@ +my @set = (1, 2, 3); +my @powerset = powerset(@set); + +sub set_to_string { + "{" . join(", ", map { ref $_ ? set_to_string(@$_) : $_ } @_) . "}" +} + +print set_to_string(@powerset), "\n"; diff --git a/Task/Power-set/Prolog/power-set-1.pro b/Task/Power-set/Prolog/power-set-1.pro index 10d8d761d4..a4ceda21f5 100644 --- a/Task/Power-set/Prolog/power-set-1.pro +++ b/Task/Power-set/Prolog/power-set-1.pro @@ -1,9 +1,6 @@ -power_set(T, PS) :- - bagof(PS1, power_set(T, [], PS1), PS). +powerset(X,Y) :- bagof( S, subseq(S,X), Y). -power_set(T, PS, PS1) :- - select(E, T, T1), !, - append(PS, [E], PST), - ( PST = PS1; power_set(T1, PS, PS1); power_set(T1, PST, PS1)). - -power_set([], [], []). +subseq( [], []). +subseq( [], [_|_]). +subseq( [X|Xs], [X|Ys] ) :- subseq(Xs, Ys). +subseq( [X|Xs], [_|Ys] ) :- append(_, [X|Zs], Ys), subseq(Xs, Zs). diff --git a/Task/Power-set/Prolog/power-set-2.pro b/Task/Power-set/Prolog/power-set-2.pro index ac42e4e9c0..1cc76a16a2 100644 --- a/Task/Power-set/Prolog/power-set-2.pro +++ b/Task/Power-set/Prolog/power-set-2.pro @@ -1,18 +1,5 @@ -:- use_module(library(chr)). - -:- chr_constraint chr_power_set/2, chr_power_set/1, clean/0. - -clean @ clean \ chr_power_set(_) <=> true. -clean @ clean <=> true. - -only_one @ chr_power_set(A) \ chr_power_set(A) <=> true. - - -creation @ chr_power_set([H | T], A) <=> - append(A, [H], B), - chr_power_set(T, A), - chr_power_set(T, B), - chr_power_set(B). - - -empty_element @ chr_power_set([], _) <=> chr_power_set([]). +power_set( [], [[]]). +power_set( [X|Xs], PS) :- + power_set(Xs, PS1), + maplist( append([X]), PS1, PS2 ), % i.e. prepend X to each PS1 + append(PS1, PS2, PS). diff --git a/Task/Power-set/Prolog/power-set-3.pro b/Task/Power-set/Prolog/power-set-3.pro new file mode 100644 index 0000000000..ac42e4e9c0 --- /dev/null +++ b/Task/Power-set/Prolog/power-set-3.pro @@ -0,0 +1,18 @@ +:- use_module(library(chr)). + +:- chr_constraint chr_power_set/2, chr_power_set/1, clean/0. + +clean @ clean \ chr_power_set(_) <=> true. +clean @ clean <=> true. + +only_one @ chr_power_set(A) \ chr_power_set(A) <=> true. + + +creation @ chr_power_set([H | T], A) <=> + append(A, [H], B), + chr_power_set(T, A), + chr_power_set(T, B), + chr_power_set(B). + + +empty_element @ chr_power_set([], _) <=> chr_power_set([]). diff --git a/Task/Power-set/Python/power-set-5.py b/Task/Power-set/Python/power-set-5.py new file mode 100644 index 0000000000..b5638d9a38 --- /dev/null +++ b/Task/Power-set/Python/power-set-5.py @@ -0,0 +1,26 @@ +>>> from pprint import pprint as pp +>>> from itertools import chain, combinations +>>> +>>> def powerset(iterable): + "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) + +>>> pp(set(powerset({1,2,3,4}))) +{(), + (1,), + (1, 2), + (1, 2, 3), + (1, 2, 3, 4), + (1, 2, 4), + (1, 3), + (1, 3, 4), + (1, 4), + (2,), + (2, 3), + (2, 3, 4), + (2, 4), + (3,), + (3, 4), + (4,)} +>>> diff --git a/Task/Power-set/TXR/power-set-1.txr b/Task/Power-set/TXR/power-set-1.txr new file mode 100644 index 0000000000..57386f68b9 --- /dev/null +++ b/Task/Power-set/TXR/power-set-1.txr @@ -0,0 +1,4 @@ +(defun power-set (s) + (reduce-right + (op append (mapcar (op cons @@1) @2) @2) + s '(()))) diff --git a/Task/Power-set/TXR/power-set-2.txr b/Task/Power-set/TXR/power-set-2.txr new file mode 100644 index 0000000000..87d792ae10 --- /dev/null +++ b/Task/Power-set/TXR/power-set-2.txr @@ -0,0 +1,10 @@ +@(do (defun power-set (s) + (reduce-right + (op append (mapcar (op cons @@1) @2) @2) + s '(())))) +@(bind pset @(power-set *args*)) +@(output) +@ (repeat) +{@(rep)@pset, @(last)@pset@(empty)@(end)} +@ (end) +@(end) diff --git a/Task/Power-set/TXR/power-set-3.txr b/Task/Power-set/TXR/power-set-3.txr new file mode 100644 index 0000000000..656f0a00e1 --- /dev/null +++ b/Task/Power-set/TXR/power-set-3.txr @@ -0,0 +1,7 @@ +@(do (defun power-set (s) + (reduce-right + (op append (mapcar (op cons @@1) @2) @2) + s '(()))) + (prinl (power-set "abc")) + (prinl (power-set "")) + (prinl (power-set #(1 2 3)))) diff --git a/Task/Power-set/TXR/power-set.txr b/Task/Power-set/TXR/power-set.txr deleted file mode 100644 index c0681c0b60..0000000000 --- a/Task/Power-set/TXR/power-set.txr +++ /dev/null @@ -1,14 +0,0 @@ -@(next :args) -@(do (defun power-set (s) - (reduce-right - (lambda (item ps) - (append (mapcar (lambda (e) (cons item e)) ps) ps)) s '(()) nil))) -@(collect :vars (arg)) -@arg -@(end) -@(bind pset @(power-set arg)) -@(output) -@ (repeat) -{@(rep)@pset, @(last)@pset@(empty)@(end)} -@ (end) -@(end) diff --git a/Task/Primality-by-trial-division/00DESCRIPTION b/Task/Primality-by-trial-division/00DESCRIPTION index ff4dfbdaf7..26ee5e3b86 100644 --- a/Task/Primality-by-trial-division/00DESCRIPTION +++ b/Task/Primality-by-trial-division/00DESCRIPTION @@ -2,4 +2,4 @@ Write a boolean function that tells whether a given integer is prime. Remember t Use trial division. Even numbers over two may be eliminated right away. A loop from 3 to √n will suffice, but other loops are allowed. -* Related task: [[Sieve of Eratosthenes]], [[Prime decomposition]]. +* Related tasks: [[Sieve of Eratosthenes]], [[Prime decomposition]], [[AKS test for primes]]. diff --git a/Task/Primality-by-trial-division/AutoIt/primality-by-trial-division.autoit b/Task/Primality-by-trial-division/AutoIt/primality-by-trial-division.autoit new file mode 100644 index 0000000000..5e8df9bff5 --- /dev/null +++ b/Task/Primality-by-trial-division/AutoIt/primality-by-trial-division.autoit @@ -0,0 +1,34 @@ +#cs ---------------------------------------------------------------------------- + + AutoIt Version: 3.3.8.1 + Author: Alexander Alvonellos + + + Script Function: + Perform primality test on a given integer $number. + RETURNS: TRUE/FALSE + +#ce ---------------------------------------------------------------------------- +Func main() + ConsoleWrite("The primes up to 100 are: " & @LF) + For $i = 1 To 100 Step 1 + If(isPrime($i)) Then + If($i <> 97) Then + ConsoleWrite($i & ", ") + Else + ConsoleWrite($i) + EndIf + EndIf + Next +EndFunc + +Func isPrime($n) + If($n < 2) Then Return False + If($n = 2) Then Return True + If(BitAnd($n, 1) = 0) Then Return False + For $i = 3 To Sqrt($n) Step 2 + If(Mod($n, $i) = 0) Then Return False + Next + Return True +EndFunc +main() diff --git a/Task/Primality-by-trial-division/D/primality-by-trial-division-1.d b/Task/Primality-by-trial-division/D/primality-by-trial-division-1.d index 6f47335552..ab852bf487 100644 --- a/Task/Primality-by-trial-division/D/primality-by-trial-division-1.d +++ b/Task/Primality-by-trial-division/D/primality-by-trial-division-1.d @@ -1,15 +1,17 @@ import std.stdio, std.algorithm, std.range, std.math; -bool isPrime(in int n) pure nothrow { - if ((n & 1) == 0 || n <= 1) - return n == 2; +bool isPrime1(in int n) pure nothrow { + if (n == 2) + return true; + if (n <= 1 || (n & 1) == 0) + return false; - for(int i = 3; i <= sqrt(cast(real)n); i += 2) + for(int i = 3; i <= real(n).sqrt; i += 2) if (n % i == 0) return false; return true; } -void main() { // demo code - iota(2, 40).filter!isPrime().writeln(); +void main() { + iota(2, 40).filter!isPrime1.writeln; } diff --git a/Task/Primality-by-trial-division/D/primality-by-trial-division-2.d b/Task/Primality-by-trial-division/D/primality-by-trial-division-2.d index d1ba6bc25d..be6ac26a0a 100644 --- a/Task/Primality-by-trial-division/D/primality-by-trial-division-2.d +++ b/Task/Primality-by-trial-division/D/primality-by-trial-division-2.d @@ -1,27 +1,25 @@ -import std.stdio, std.algorithm, std.range; +bool isPrime2(It)(in It n) pure nothrow { + // Adapted from: http://www.devx.com/vb2themax/Tip/19051 + // Test 1, 2, 3 and multiples of 2 and 3: + if (n == 2 || n == 3) + return true; + else if (n < 2 || n % 2 == 0 || n % 3 == 0) + return false; + + // We can now avoid to consider multiples of 2 and 3. This + // can be done really simply by starting at 5 and + // incrementing by 2 and 4 alternatively, that is: + // 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ... + // We don't need to go higher than the square root of the n. + for (It div = 5, inc = 2; div ^^ 2 <= n; div += inc, inc = 6 - inc) + if (n % div == 0) + return false; -bool isPrime2(Integer)(in Integer number) pure nothrow { - // Adapted from: http://www.devx.com/vb2themax/Tip/19051 - // manually test 1, 2, 3 and multiples of 2 and 3 - if (number == 2 || number == 3) return true; - else if (number < 2 || number % 2 == 0 || number % 3 == 0) - return false; - - /* we can now avoid to consider multiples - * of 2 and 3. This can be done really simply - * by starting at 5 and incrementing by 2 and 4 - * alternatively, that is: - * 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ... - * we don't need to go higher than the square root of the number */ - for (Integer divisor = 5, increment = 2; divisor*divisor <= number; - divisor += increment, increment = 6 - increment) - if (number % divisor == 0) - return false; - - return true; // if we get here, the number is prime } -void main() { // demo code - iota(2, 40).filter!isPrime2().writeln(); +void main() { + import std.stdio, std.algorithm, std.range; + + iota(2, 40).filter!isPrime2.writeln; } diff --git a/Task/Primality-by-trial-division/D/primality-by-trial-division-3.d b/Task/Primality-by-trial-division/D/primality-by-trial-division-3.d index 48bca92b85..46e98cf476 100644 --- a/Task/Primality-by-trial-division/D/primality-by-trial-division-3.d +++ b/Task/Primality-by-trial-division/D/primality-by-trial-division-3.d @@ -3,13 +3,13 @@ import std.stdio, std.algorithm, std.range, std.math; bool isPrime3(T)(in T n) pure nothrow { if (n % 2 == 0 || n <= 1) return n == 2; - T head = 3, tail = (cast(T)sqrt(cast(real)n) / 2) * 2 + 1; + T head = 3, tail = (cast(T)real(n).sqrt / 2) * 2 + 1; for ( ; head <= tail ; head +=2, tail -= 2) if ((n % head) == 0 || (n % tail) == 0) return false; return true; } -void main() { // demo code - iota(2, 40).filter!isPrime3().writeln(); +void main() { + iota(2, 40).filter!isPrime3.writeln; } diff --git a/Task/Primality-by-trial-division/Prolog/primality-by-trial-division.pro b/Task/Primality-by-trial-division/Prolog/primality-by-trial-division.pro index 171979f351..7e7504c6ae 100644 --- a/Task/Primality-by-trial-division/Prolog/primality-by-trial-division.pro +++ b/Task/Primality-by-trial-division/Prolog/primality-by-trial-division.pro @@ -1,16 +1,7 @@ prime(2). -prime(N) :- integer(N), N > 1, - M is floor(sqrt(N+1)), % round-off paranoia - N mod 2 > 0, % is odd - check_by_odds(N, M, 3). - -check_by_odds(N, M, S) :- - M2 is (M-1) // 2, S2 is S // 2, - forall( between(S2,M2,X), N mod (2*X+1) > 0 ). - -/* -check_by_odds(N, M, F) :- F > M. -check_by_odds(N, M, F) :- F =< M, - N mod F > 0, - F1 is F + 2, % test by odds only - check_by_odds(N, M, F1).*/ +prime(N) :- + between(3, inf, N), + 1 is N mod 2, % odd + M is floor(sqrt(N+1)), % round-off paranoia + Max is (M-1) // 2, % integer division + forall( between(1, Max, I), N mod (2*I+1) > 0 ). diff --git a/Task/Prime-decomposition/Ada/prime-decomposition-1.ada b/Task/Prime-decomposition/Ada/prime-decomposition-1.ada new file mode 100644 index 0000000000..7ade825047 --- /dev/null +++ b/Task/Prime-decomposition/Ada/prime-decomposition-1.ada @@ -0,0 +1,13 @@ +generic + type Number is private; + Zero : Number; + One : Number; + Two : Number; + with function "+" (X, Y : Number) return Number is <>; + with function "/" (X, Y : Number) return Number is <>; + with function "mod" (X, Y : Number) return Number is <>; + with function ">=" (X, Y : Number) return Boolean is <>; +package Prime_Numbers is + type Number_List is array (Positive range <>) of Number; + function Decompose (N : Number) return Number_List; +end Prime_Numbers; diff --git a/Task/Prime-decomposition/Ada/prime-decomposition-2.ada b/Task/Prime-decomposition/Ada/prime-decomposition-2.ada new file mode 100644 index 0000000000..abac72ffac --- /dev/null +++ b/Task/Prime-decomposition/Ada/prime-decomposition-2.ada @@ -0,0 +1,30 @@ +package body Prime_Numbers is + function Decompose (N : Number) return Number_List is + Size : Natural := 0; + M : Number := N; + K : Number := Two; + begin + -- Estimation of the result length from above + while M >= Two loop + M := (M + One) / Two; + Size := Size + 1; + end loop; + M := N; + -- Filling the result with prime numbers + declare + Result : Number_List (1..Size); + Index : Positive := 1; + begin + while N >= K loop -- Divisors loop + while Zero = (M mod K) loop -- While divides + Result (Index) := K; + Index := Index + 1; + M := M / K; + end loop; + K := K + One; + end loop; + return Result (1..Index - 1); + end; + end Decompose; + +end Prime_Numbers; diff --git a/Task/Prime-decomposition/Ada/prime-decomposition-3.ada b/Task/Prime-decomposition/Ada/prime-decomposition-3.ada new file mode 100644 index 0000000000..ee9849de41 --- /dev/null +++ b/Task/Prime-decomposition/Ada/prime-decomposition-3.ada @@ -0,0 +1,18 @@ +with Prime_Numbers, Ada.Text_IO; + +procedure Test_Prime is + + package Integer_Numbers is new + Prime_Numbers (Natural, 0, 1, 2); + use Integer_Numbers; + + procedure Put (List : Number_List) is + begin + for Index in List'Range loop + Ada.Text_IO.Put (Positive'Image (List (Index))); + end loop; + end Put; + +begin + Put (Decompose (12)); +end Test_Prime; diff --git a/Task/Prime-decomposition/Ada/prime-decomposition.ada b/Task/Prime-decomposition/Ada/prime-decomposition.ada deleted file mode 100644 index a48b4b593d..0000000000 --- a/Task/Prime-decomposition/Ada/prime-decomposition.ada +++ /dev/null @@ -1,60 +0,0 @@ -with Ada.Text_IO; use Ada.Text_IO; - -procedure Test_Prime is - generic - type Number is private; - Zero : Number; - One : Number; - Two : Number; - with function Image (X : Number) return String is <>; - with function "+" (X, Y : Number) return Number is <>; - with function "/" (X, Y : Number) return Number is <>; - with function "mod" (X, Y : Number) return Number is <>; - with function ">=" (X, Y : Number) return Boolean is <>; - package Prime_Numbers is - type Number_List is array (Positive range <>) of Number; - function Decompose (N : Number) return Number_List; - procedure Put (List : Number_List); - end Prime_Numbers; - - package body Prime_Numbers is - function Decompose (N : Number) return Number_List is - Size : Natural := 0; - M : Number := N; - K : Number := Two; - begin - -- Estimation of the result length from above - while M >= Two loop - M := (M + One) / Two; - Size := Size + 1; - end loop; - M := N; - -- Filling the result with prime numbers - declare - Result : Number_List (1..Size); - Index : Positive := 1; - begin - while N >= K loop -- Divisors loop - while Zero = (M mod K) loop -- While divides - Result (Index) := K; - Index := Index + 1; - M := M / K; - end loop; - K := K + One; - end loop; - return Result (1..Index - 1); - end; - end Decompose; - - procedure Put (List : Number_List) is - begin - for Index in List'Range loop - Put (Image (List (Index))); - end loop; - end Put; - end Prime_Numbers; - package Integer_Numbers is new Prime_Numbers (Natural, 0, 1, 2, Positive'Image); - use Integer_Numbers; -begin - Put (Decompose (12)); -end Test_Prime; diff --git a/Task/Prime-decomposition/Common-Lisp/prime-decomposition.lisp b/Task/Prime-decomposition/Common-Lisp/prime-decomposition-1.lisp similarity index 100% rename from Task/Prime-decomposition/Common-Lisp/prime-decomposition.lisp rename to Task/Prime-decomposition/Common-Lisp/prime-decomposition-1.lisp diff --git a/Task/Prime-decomposition/Common-Lisp/prime-decomposition-2.lisp b/Task/Prime-decomposition/Common-Lisp/prime-decomposition-2.lisp new file mode 100644 index 0000000000..a5f4751798 --- /dev/null +++ b/Task/Prime-decomposition/Common-Lisp/prime-decomposition-2.lisp @@ -0,0 +1,11 @@ +;;; Tail-recursive version +(defun factor (n &optional (acc '())) + (when (> n 1) (loop with max-d = (isqrt n) + for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do + (cond ((> d max-d) (return (cons (list n 1) acc))) + ((zerop (rem n d)) + (return (factor (truncate n d) (if (eq d (caar acc)) + (cons + (list (caar acc) (1+ (cadar acc))) + (cdr acc)) + (cons (list d 1) acc))))))))) diff --git a/Task/Prime-decomposition/D/prime-decomposition.d b/Task/Prime-decomposition/D/prime-decomposition.d index 6c82bcf504..f4409c3fa5 100644 --- a/Task/Prime-decomposition/D/prime-decomposition.d +++ b/Task/Prime-decomposition/D/prime-decomposition.d @@ -1,23 +1,17 @@ -import std.stdio, std.bigint, std.algorithm, std.traits; +import std.stdio, std.bigint, std.algorithm, std.traits, std.range; Unqual!T[] decompose(T)(in T number) pure /*nothrow*/ in { assert(number > 1); } body { - alias UT = Unqual!T; typeof(return) result; - UT n = number; + Unqual!T n = number; - for (UT i = 2; n % i == 0;) { + for (Unqual!T i = 2; n % i == 0; n /= i) result ~= i; - n /= i; - } - for (UT i = 3; n >= i * i; i += 2) { - while (n % i == 0) { + for (Unqual!T i = 3; n >= i * i; i += 2) + for (; n % i == 0; n /= i) result ~= i; - n /= i; - } - } if (n != 1) result ~= n; @@ -25,9 +19,7 @@ in { } void main() { - foreach (immutable n; 2 .. 10) - n.decompose.writeln; - + writefln("%(%s\n%)", iota(2, 10).map!decompose); decompose(1023 * 1024).writeln; BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17).decompose.writeln; decompose(16860167264933UL.BigInt * 179951).writeln; diff --git a/Task/Prime-decomposition/Java/prime-decomposition-4.java b/Task/Prime-decomposition/Java/prime-decomposition-4.java index cdf91616f3..fd55ede1ff 100644 --- a/Task/Prime-decomposition/Java/prime-decomposition-4.java +++ b/Task/Prime-decomposition/Java/prime-decomposition-4.java @@ -1,11 +1,43 @@ -public static List primeFactorBig(BigInteger a){ - List ans = new LinkedList(); +private static final BigInteger TWO = BigInteger.valueOf(2); +private static final BigInteger THREE = BigInteger.valueOf(3); +private static final BigInteger FIVE = BigInteger.valueOf(5); - for(BigInteger divisor = BigInteger.valueOf(2); - a.compareTo(ONE) > 0; divisor = divisor.add(ONE)) - while(a.mod(divisor).equals(ZERO)){ - ans.add(divisor); - a = a.divide(divisor); +public static ArrayList primeDecomp(BigInteger n){ + if(n.compareTo(TWO) < 0) return null; + ArrayList factors = new ArrayList(); + + // handle even values + while(n.and(BigInteger.ONE).equals(BigInteger.ZERO)){ + n = n.shiftRight(1); + factors.add(TWO); + } + + // handle values divisible by three + while(n.mod(THREE).equals(BigInteger.ZERO)){ + factors.add(THREE); + n = n.divide(THREE); + } + + // handle values divisible by five + while(n.mod(FIVE).equals(BigInteger.ZERO)){ + factors.add(FIVE); + n = n.divide(FIVE); + } + + // much like how we can skip multiples of two, we can also skip + // multiples of three and multiples of five. This increment array + // helps us to accomplish that + int[] pattern = {4,2,4,2,4,6,2,6}; + int pattern_index = 0; + BigInteger current_test = BigInteger.valueOf(7); + while(!n.equals(BigInteger.ONE)){ + while(n.mod(current_test).equals(BigInteger.ZERO)){ + factors.add(current_test); + n = n.divide(current_test); } - return ans; + current_test = current_test.add(BigInteger.valueOf(pattern[pattern_index])); + pattern_index = (pattern_index + 1) & 7; + } + + return factors; } diff --git a/Task/Prime-decomposition/Java/prime-decomposition-5.java b/Task/Prime-decomposition/Java/prime-decomposition-5.java new file mode 100644 index 0000000000..cdf91616f3 --- /dev/null +++ b/Task/Prime-decomposition/Java/prime-decomposition-5.java @@ -0,0 +1,11 @@ +public static List primeFactorBig(BigInteger a){ + List ans = new LinkedList(); + + for(BigInteger divisor = BigInteger.valueOf(2); + a.compareTo(ONE) > 0; divisor = divisor.add(ONE)) + while(a.mod(divisor).equals(ZERO)){ + ans.add(divisor); + a = a.divide(divisor); + } + return ans; +} diff --git a/Task/Prime-decomposition/Maple/prime-decomposition-1.maple b/Task/Prime-decomposition/Maple/prime-decomposition-1.maple new file mode 100644 index 0000000000..ca3e2b4095 --- /dev/null +++ b/Task/Prime-decomposition/Maple/prime-decomposition-1.maple @@ -0,0 +1,2 @@ +> ifactor(1337); + (7) (191) diff --git a/Task/Prime-decomposition/Maple/prime-decomposition-2.maple b/Task/Prime-decomposition/Maple/prime-decomposition-2.maple new file mode 100644 index 0000000000..70c7307ed4 --- /dev/null +++ b/Task/Prime-decomposition/Maple/prime-decomposition-2.maple @@ -0,0 +1,2 @@ +> ifactors(1337); + [1, [[7, 1], [191, 1]]] diff --git a/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima b/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima index 6d6ab5cbae..a06835499f 100644 --- a/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima +++ b/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima @@ -1,4 +1,4 @@ -prime_dec(n) := flatten(create_list(makelist(a[1], a[2]), a, ifactors(n)))$ +prime_dec(n) := flatten(create_list(makelist(first(a), second(a)), a, ifactors(n)))$ /* or, slighlty more "functional" */ prime_dec(n) := flatten(map(lambda([a], apply(makelist, a)), ifactors(n)))$ diff --git a/Task/Prime-decomposition/Python/prime-decomposition-1.py b/Task/Prime-decomposition/Python/prime-decomposition-1.py index 35811fa0a7..f9380fbf01 100644 --- a/Task/Prime-decomposition/Python/prime-decomposition-1.py +++ b/Task/Prime-decomposition/Python/prime-decomposition-1.py @@ -1,7 +1,18 @@ +from __future__ import print_function + import sys +from itertools import islice, cycle, count + +try: + from itertools import compress +except ImportError: + def compress(data, selectors): + """compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F""" + return (d for d, s in zip(data, selectors) if s) + def is_prime(n): - return zip((True, False), decompose(n))[-1][0] + return list(zip((True, False), decompose(n)))[-1][0] class IsPrimeCached(dict): def __missing__(self, n): @@ -11,24 +22,54 @@ class IsPrimeCached(dict): is_prime_cached = IsPrimeCached() -def primes(): - yield 2 - n = 3 - while n < sys.maxint - 2: - yield n - n += 2 - while n < sys.maxint - 2 and not is_prime_cached[n]: - n += 2 +def croft(): + """Yield prime integers using the Croft Spiral sieve. + + This is a variant of wheel factorisation modulo 30. + """ + # Copied from: + # https://code.google.com/p/pyprimes/source/browse/src/pyprimes.py + # Implementation is based on erat3 from here: + # http://stackoverflow.com/q/2211990 + # and this website: + # http://www.primesdemystified.com/ + # Memory usage increases roughly linearly with the number of primes seen. + # dict ``roots`` stores an entry x:p for every prime p. + for p in (2, 3, 5): + yield p + roots = {9: 3, 25: 5} # Map d**2 -> d. + primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29)) + selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0) + for q in compress( + # Iterate over prime candidates 7, 9, 11, 13, ... + islice(count(7), 0, None, 2), + # Mask out those that can't possibly be prime. + cycle(selectors) + ): + # Using dict membership testing instead of pop gives a + # 5-10% speedup over the first three million primes. + if q in roots: + p = roots[q] + del roots[q] + x = q + 2*p + while x in roots or (x % 30) not in primeroots: + x += 2*p + roots[x] = p + else: + roots[q*q] = q + yield q +primes = croft def decompose(n): for p in primes(): if p*p > n: break while n % p == 0: yield p - n /=p + n //=p if n > 1: yield n + if __name__ == '__main__': # Example: calculate factors of Mersenne numbers to M59 # @@ -36,10 +77,10 @@ if __name__ == '__main__': for m in primes(): p = 2 ** m - 1 - print( "2**{0:d}-1 = {0:d}, with factors:".format(m, p) ) + print( "2**{0:d}-1 = {1:d}, with factors:".format(m, p) ) start = time.time() for factor in decompose(p): - print factor, + print(factor, end=' ') sys.stdout.flush() print( "=> {0:.2f}s".format( time.time()-start ) ) diff --git a/Task/Prime-decomposition/Python/prime-decomposition-2.py b/Task/Prime-decomposition/Python/prime-decomposition-2.py index fc2495b4a6..8175901839 100644 --- a/Task/Prime-decomposition/Python/prime-decomposition-2.py +++ b/Task/Prime-decomposition/Python/prime-decomposition-2.py @@ -1,21 +1,27 @@ -primelist = [2, 3] -def is_prime(n): - if n in primelist: return True - if n < primelist[-1]: return False +from math import floor, sqrt +try: + long +except NameError: + long = int - for y in primes(): - if not n % y: return False - if n < y * y: return True +def fac(n): + step = lambda x: 1 + x*4 - (x//2)*2 + maxq = long(floor(sqrt(n))) + d = 1 + q = n % 2 == 0 and 2 or 3 + while q <= maxq and n % q != 0: + q = step(d) + d += 1 + res = [] + if q <= maxq: + res.extend(fac(n//q)) + res.extend(fac(q)) + else: res=[n] + return res -def primes(): - for n in primelist: yield n - - n = primelist[-1] - while True: - n += 2 - for x in primelist: - if not n % x: break - if x * x > n: - primelist.append(n) - yield n - break +if __name__ == '__main__': + import time + start = time.time() + tocalc = 2**59-1 + print("%s = %s" % (tocalc, fac(tocalc))) + print("Needed %ss" % (time.time() - start)) diff --git a/Task/Prime-decomposition/Ruby/prime-decomposition-1.rb b/Task/Prime-decomposition/Ruby/prime-decomposition-1.rb index c36ea2bd34..df4329b2a5 100644 --- a/Task/Prime-decomposition/Ruby/prime-decomposition-1.rb +++ b/Task/Prime-decomposition/Ruby/prime-decomposition-1.rb @@ -1,4 +1,4 @@ -irb(main):001:0> require 'mathn' +irb(main):001:0> require 'prime' => true -irb(main):002:0> 2131447995319.prime_division -=> [[701, 1], [1123, 2], [2411, 1]] +irb(main):003:0> 2543821448263974486045199.prime_division +=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]] diff --git a/Task/Prime-decomposition/Ruby/prime-decomposition-2.rb b/Task/Prime-decomposition/Ruby/prime-decomposition-2.rb index df4329b2a5..ce41018e80 100644 --- a/Task/Prime-decomposition/Ruby/prime-decomposition-2.rb +++ b/Task/Prime-decomposition/Ruby/prime-decomposition-2.rb @@ -1,4 +1,13 @@ -irb(main):001:0> require 'prime' -=> true -irb(main):003:0> 2543821448263974486045199.prime_division -=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]] +# Get prime decomposition of integer _i_. +# This routine is terribly inefficient, but elegance rules. +def prime_factors(i) + v = (2..i-1).detect{|j| i % j == 0} + v ? ([v] + prime_factors(i/v)) : [i] +end + +# Example: Decompose all possible Mersenne primes up to 2**31-1. +# This may take several minutes to show that 2**31-1 is prime. +(2..31).each do |i| + factors = prime_factors(2**i-1) + puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}" +end diff --git a/Task/Prime-decomposition/Ruby/prime-decomposition-3.rb b/Task/Prime-decomposition/Ruby/prime-decomposition-3.rb index ce41018e80..d4eef1c138 100644 --- a/Task/Prime-decomposition/Ruby/prime-decomposition-3.rb +++ b/Task/Prime-decomposition/Ruby/prime-decomposition-3.rb @@ -1,13 +1,32 @@ # Get prime decomposition of integer _i_. -# This routine is terribly inefficient, but elegance rules. -def prime_factors(i) - v = (2..i-1).detect{|j| i % j == 0} - v ? ([v] + prime_factors(i/v)) : [i] +# This routine is more efficient than prime_factors, +# and quite similar to Integer#prime_division of MRI 1.9. +def prime_factors_faster(i) + factors = [] + check = proc do |p| + while(q, r = i.divmod(p) + r.zero?) + factors << p + i = q + end + end + check[2] + check[3] + p = 5 + while p * p <= i + check[p] + p += 2 + check[p] + p += 4 # skip multiples of 2 and 3 + end + factors << i if i > 1 + factors end -# Example: Decompose all possible Mersenne primes up to 2**31-1. -# This may take several minutes to show that 2**31-1 is prime. -(2..31).each do |i| - factors = prime_factors(2**i-1) +# Example: Decompose all possible Mersenne primes up to 2**70-1. +# This may take several minutes to show that 2**61-1 is prime, +# but 2**62-1 and 2**67-1 are not prime. +(2..70).each do |i| + factors = prime_factors_faster(2**i-1) puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}" end diff --git a/Task/Prime-decomposition/Ruby/prime-decomposition-4.rb b/Task/Prime-decomposition/Ruby/prime-decomposition-4.rb index d4eef1c138..edf0dedb33 100644 --- a/Task/Prime-decomposition/Ruby/prime-decomposition-4.rb +++ b/Task/Prime-decomposition/Ruby/prime-decomposition-4.rb @@ -1,32 +1,10 @@ -# Get prime decomposition of integer _i_. -# This routine is more efficient than prime_factors, -# and quite similar to Integer#prime_division of MRI 1.9. -def prime_factors_faster(i) - factors = [] - check = proc do |p| - while(q, r = i.divmod(p) - r.zero?) - factors << p - i = q - end +require 'benchmark' +require 'mathn' +Benchmark.bm(24) do |x| + [2**25 - 6, 2**35 - 7].each do |i| + puts "#{i} = #{prime_factors_faster(i).join(' * ')}" + x.report(" prime_factors") { prime_factors(i) } + x.report(" prime_factors_faster") { prime_factors_faster(i) } + x.report(" Integer#prime_division") { i.prime_division } end - check[2] - check[3] - p = 5 - while p * p <= i - check[p] - p += 2 - check[p] - p += 4 # skip multiples of 2 and 3 - end - factors << i if i > 1 - factors -end - -# Example: Decompose all possible Mersenne primes up to 2**70-1. -# This may take several minutes to show that 2**61-1 is prime, -# but 2**62-1 and 2**67-1 are not prime. -(2..70).each do |i| - factors = prime_factors_faster(2**i-1) - puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}" end diff --git a/Task/Priority-queue/AutoHotkey/priority-queue-1.ahk b/Task/Priority-queue/AutoHotkey/priority-queue-1.ahk new file mode 100644 index 0000000000..16f5fd2877 --- /dev/null +++ b/Task/Priority-queue/AutoHotkey/priority-queue-1.ahk @@ -0,0 +1,60 @@ +;----------------------------------- +PQ_TopItem(Queue,Task:=""){ ; remove and return top priority item + TopPriority := PQ_TopPriority(Queue) + for T, P in Queue + if (P = TopPriority) && ((T=Task)||!Task) + return T , Queue.Remove(T) + return 0 +} +;----------------------------------- +PQ_AddTask(Queue,Task,Priority){ ; insert and return new task + for T, P in Queue + if (T=Task) || !(Priority && Task) + return 0 + return Task, Queue[Task] := Priority +} +;----------------------------------- +PQ_DelTask(Queue, Task){ ; delete and return task + for T, P in Queue + if (T = Task) + return Task, Queue.Remove(Task) +} +;----------------------------------- +PQ_Peek(Queue){ ; peek and return top priority task(s) + TopPriority := PQ_TopPriority(Queue) + for T, P in Queue + if (P = TopPriority) + PeekList .= (PeekList?"`n":"") "`t" T + return PeekList +} +;----------------------------------- +PQ_Check(Queue,Task){ ; check task and return its priority + for T, P in Queue + if (T = Task) + return P + return 0 +} +;----------------------------------- +PQ_Edit(Queue,Task,Priority){ ; Update task priority and return its new priority + for T, P in Queue + if (T = Task) + return Priority, Queue[T]:=Priority + return 0 +} +;----------------------------------- +PQ_View(Queue){ ; view current Queue + for T, P in Queue + Res .= P " : " T "`n" + Sort, Res, FMySort + return "Priority Queue=`n" Res +} +MySort(a,b){ + RegExMatch(a,"(\d+) : (.*)", x), RegExMatch(b,"(\d+) : (.*)", y) + return x1>y1?1:x1y2?1:x2 const void *PQRetain(CFAllocatorRef allocator, const void *ptr) { - return [(id)ptr retain]; + return (__bridge_retained const void *)(__bridge id)ptr; } void PQRelease(CFAllocatorRef allocator, const void *ptr) { - [(id)ptr release]; + (void)(__bridge_transfer id)ptr; } CFComparisonResult PQCompare(const void *ptr1, const void *ptr2, void *unused) { - return [(id)ptr1 compare:(id)ptr2]; + return [(__bridge id)ptr1 compare:(__bridge id)ptr2]; } @interface Task : NSObject { @@ -26,10 +26,6 @@ CFComparisonResult PQCompare(const void *ptr1, const void *ptr2, void *unused) { } return self; } -- (void)dealloc { - [name release]; - [super dealloc]; -} - (NSString *)description { return [NSString stringWithFormat:@"%d, %@", priority, name]; } @@ -44,25 +40,25 @@ CFComparisonResult PQCompare(const void *ptr1, const void *ptr2, void *unused) { @end int main (int argc, const char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - CFBinaryHeapCallBacks callBacks = {0, PQRetain, PQRelease, NULL, PQCompare}; - CFBinaryHeapRef pq = CFBinaryHeapCreate(NULL, 0, &callBacks, NULL); + CFBinaryHeapCallBacks callBacks = {0, PQRetain, PQRelease, NULL, PQCompare}; + CFBinaryHeapRef pq = CFBinaryHeapCreate(NULL, 0, &callBacks, NULL); - CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:3 andName:@"Clear drains"] autorelease]); - CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:4 andName:@"Feed cat"] autorelease]); - CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:5 andName:@"Make tea"] autorelease]); - CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:1 andName:@"Solve RC tasks"] autorelease]); - CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:2 andName:@"Tax return"] autorelease]); + CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:3 andName:@"Clear drains"]); + CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:4 andName:@"Feed cat"]); + CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:5 andName:@"Make tea"]); + CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:1 andName:@"Solve RC tasks"]); + CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:2 andName:@"Tax return"]); + + while (CFBinaryHeapGetCount(pq) != 0) { + Task *task = (id)CFBinaryHeapGetMinimum(pq); + NSLog(@"%@", task); + CFBinaryHeapRemoveMinimumValue(pq); + } + + CFRelease(pq); - while (CFBinaryHeapGetCount(pq) != 0) { - Task *task = (id)CFBinaryHeapGetMinimum(pq); - NSLog(@"%@", task); - CFBinaryHeapRemoveMinimumValue(pq); } - - CFRelease(pq); - - [pool drain]; return 0; } diff --git a/Task/Probabilistic-choice/D/probabilistic-choice-1.d b/Task/Probabilistic-choice/D/probabilistic-choice-1.d index e5b2de6a02..4df2f17cc6 100644 --- a/Task/Probabilistic-choice/D/probabilistic-choice-1.d +++ b/Task/Probabilistic-choice/D/probabilistic-choice-1.d @@ -1,13 +1,13 @@ -import std.stdio, std.random, std.string, std.range; - void main() { + import std.stdio, std.random, std.string, std.range; + enum int nTrials = 1_000_000; - enum items = "aleph beth gimel daleth he waw zayin heth".split(); - enum pr = [1/5., 1/6., 1/7., 1/8., 1/9., 1/10., 1/11., 1759/27720.]; + const items = "aleph beth gimel daleth he waw zayin heth".split; + const pr = [1/5., 1/6., 1/7., 1/8., 1/9., 1/10., 1/11., 1759/27720.]; double[pr.length] counts = 0.0; - foreach (_; 0 .. nTrials) - counts[dice(pr)]++; + foreach (immutable _; 0 .. nTrials) + counts[pr.dice]++; writeln("Item Target prob Attained prob"); foreach (name, p, co; zip(items, pr, counts[])) diff --git a/Task/Probabilistic-choice/D/probabilistic-choice-2.d b/Task/Probabilistic-choice/D/probabilistic-choice-2.d index 5ac74ef9b7..e56c9e76e0 100644 --- a/Task/Probabilistic-choice/D/probabilistic-choice-2.d +++ b/Task/Probabilistic-choice/D/probabilistic-choice-2.d @@ -1,21 +1,21 @@ -import std.stdio, std.random, std.algorithm, std.range; - void main() { + import std.stdio, std.random, std.algorithm, std.range; + enum int nTrials = 1_000_000; - auto items = "aleph beth gimel daleth he waw zayin heth".split(); - enum pr = [1/5., 1/6., 1/7., 1/8., 1/9., 1/10., 1/11., 1759/27720.]; + const items = "aleph beth gimel daleth he waw zayin heth".split; + const pr = [1/5., 1/6., 1/7., 1/8., 1/9., 1/10., 1/11., 1759/27720.]; double[pr.length] cumulatives = pr[]; - foreach (i, ref c; cumulatives[1 .. $ - 1]) + foreach (immutable i, ref c; cumulatives[1 .. $ - 1]) c += cumulatives[i]; cumulatives[$ - 1] = 1.0; double[pr.length] counts = 0.0; - auto rnd = Xorshift(unpredictableSeed()); - foreach (_; 0 .. nTrials) { - double rnd01 = rnd.front / cast(double)rnd.max; - rnd.popFront(); - counts[cumulatives[].countUntil!(c => c >= rnd01)()]++; + auto rnd = Xorshift(unpredictableSeed); + foreach (immutable _; 0 .. nTrials) { + immutable rnd01 = rnd.front / double(rnd.max); + rnd.popFront; + counts[cumulatives[].countUntil!(c => c >= rnd01)]++; } writeln("Item Target prob Attained prob"); diff --git a/Task/Problem-of-Apollonius/AutoHotkey/problem-of-apollonius.ahk b/Task/Problem-of-Apollonius/AutoHotkey/problem-of-apollonius.ahk new file mode 100644 index 0000000000..4182f521ac --- /dev/null +++ b/Task/Problem-of-Apollonius/AutoHotkey/problem-of-apollonius.ahk @@ -0,0 +1,105 @@ +#NoEnv +#SingleInstance, Force +SetBatchLines, -1 + +; Uncomment if Gdip.ahk is not in your standard library +;#Include, Gdip.ahk + +; Start gdi+ +If !pToken := Gdip_Startup() +{ + MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system + ExitApp +} +OnExit, Exit +; I've added a simple new function here, just to ensure if anyone is having any problems then to make sure they are using the correct library version +If (Gdip_LibraryVersion() < 1.30) +{ + MsgBox, 48, version error!, Please download the latest version of the gdi+ library + ExitApp +} +x1:=300,y1:=500,r1:=50,x2:=200,y2:=200,r2:=150,x3:=600,y3:=400,r3:=100,s1:=-1,s2:=-1,s3:=-1,xs:=0,ys:=0,rs:=0 +, Apollonius(x1,y1,r1,x2,y2,r2,x3,y3,r3,s1,s2,s3,xs,ys,rs) +, Width:=max(x1+r1 "," x2+r2 "," x3+r3 "," xs+rs)*1.1 +, Height:=max(y1+r1 "," y2+r2 "," y3+r3 "," ys+rs)*1.1 + +Gui, -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, Show +hwnd1 := WinExist() +, hbm := CreateDIBSection(Width, Height) +, hdc := CreateCompatibleDC() +, obm := SelectObject(hdc, hbm) +, G := Gdip_GraphicsFromHDC(hdc) +, Gdip_SetSmoothingMode(G, 4) +, bWhite := Gdip_BrushCreateSolid(0xffffffff) +, Gdip_FillRectangle(G, bWhite, 0, 0, Width, Height) +, pRed := Gdip_CreatePen(0x88ff0000, 3) +, pGreen := Gdip_CreatePen(0x8800ff00, 3) +, pBlue := Gdip_CreatePen(0x880000ff, 3) +, pBlack := Gdip_CreatePen(0x88000000, 3) +, Gdip_DrawCircle(G, pRed, x1, y1, r1) +, Gdip_DrawCircle(G, pGreen, x2, y2, r2) +, Gdip_DrawCircle(G, pBlue, x3, y3, r3) +, Gdip_DrawCircle(G, pBlack, xs, ys, rs) +, Gdip_DeletePen(pRed) +, Gdip_DeletePen(pGreen) +, Gdip_DeletePen(pBlue) +, Gdip_DeletePen(pBlack) +, UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) +Return + +GuiEscape: +GuiClose: +Exit: + SelectObject(hdc, obm) + , DeleteObject(hbm) + , DeleteDC(hdc) + , Gdip_DeleteGraphics(G) + , Gdip_Shutdown(pToken) + ExitApp + +Apollonius(x1=300,y1=500,r1=50,x2=200,y2=200,r2=150,x3=600,y3=400,r3=100,s1=1,s2=1,s3=1,ByRef xs=0, ByRef ys=0, ByRef rs=0) { +v11 := 2*x2 - 2*x1 +v12 := 2*y2 - 2*y1 +v13 := x1**2 - x2**2 + y1**2 - y2**2 - r1**2 + r2**2 +v14 := 2*s2*r2 - 2*s1*r1 + +v21 := 2*x3 - 2*x2 +v22 := 2*y3 - 2*y2 +v23 := x2**2 - x3**2 + y2**2 - y3**2 - r2**2 + r3**2 +v24 := 2*s3*r3 - 2*s2*r2 + +w12 := v12/v11 +w13 := v13/v11 +w14 := v14/v11 + +w22 := v22/v21 - w12 +w23 := v23/v21 - w13 +w24 := v24/v21 - w14 + +p := -w23/w22 +q := w24/w22 +m := -w12*p - w13 +n := w14 - w12*q + +a := n**2 + q**2 - 1 +b := 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1 +c := x1**2 + m**2 - 2*m*x1 + p**2 + y1**2 - 2*p*y1 - r1**2 + +d := b**2 - 4*a*c +rs := (-b - d**0.5)/(2*a) +xs := m + n*rs +ys := p + q*rs +} + +; from http://rosettacode.org/wiki/Greatest_element_of_a_list#AutoHotkey +max(list) { + Loop Parse, list, `, + x := x < A_LoopField ? A_LoopField : x + Return x +} + +; Gdip helper function +Gdip_DrawCircle(G, pPen, x, y, r) { + Return Gdip_DrawEllipse(G, pPen, x-r, y-r, r*2, r*2) +} diff --git a/Task/Program-name/CoffeeScript/program-name.coffee b/Task/Program-name/CoffeeScript/program-name.coffee new file mode 100644 index 0000000000..9e9942e548 --- /dev/null +++ b/Task/Program-name/CoffeeScript/program-name.coffee @@ -0,0 +1,7 @@ +#!/usr/bin/env coffee + +main = () -> + program = __filename + console.log "Program: " + program + +if not module.parent then main() diff --git a/Task/Program-name/Objective-C/program-name-1.m b/Task/Program-name/Objective-C/program-name-1.m index 3620035b51..d4b2557cc7 100644 --- a/Task/Program-name/Objective-C/program-name-1.m +++ b/Task/Program-name/Objective-C/program-name-1.m @@ -1,16 +1,16 @@ #import int main(int argc, char **argv) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - char *program = argv[0]; - printf("Program: %s\n", program); + char *program = argv[0]; + printf("Program: %s\n", program); - // Alternatively: - NSString *program2 = [[NSProcessInfo processInfo] processName]; - NSLog(@"Program: %@\n", program2); + // Alternatively: + NSString *program2 = [[NSProcessInfo processInfo] processName]; + NSLog(@"Program: %@\n", program2); - [pool drain]; + } return 0; } diff --git a/Task/Pythagorean-triples/AutoHotkey/pythagorean-triples.ahk b/Task/Pythagorean-triples/AutoHotkey/pythagorean-triples.ahk new file mode 100644 index 0000000000..060b144b57 --- /dev/null +++ b/Task/Pythagorean-triples/AutoHotkey/pythagorean-triples.ahk @@ -0,0 +1,30 @@ +#NoEnv +SetBatchLines, -1 +#SingleInstance, Force + +; Greatest common divisor, from http://rosettacode.org/wiki/Greatest_common_divisor#AutoHotkey +gcd(a,b) { + Return b=0 ? Abs(a) : Gcd(b,mod(a,b)) +} + +count_triples(max) { + primitives := 0, triples := 0, m := 2 + while m <= (max / 2)**0.5 + { + n := mod(m, 2) + 1 + ,p := 2*m*(m + n) + , delta := 4*m + while n < m and p <= max + gcd(m, n) = 1 + ? (primitives++ + , triples += max // p) + : "" + , n += 2 + , p += delta + m++ + } + Return primitives " primitives out of " triples " triples" +} + +Loop, 8 + Msgbox % 10**A_Index ": " count_triples(10**A_Index) diff --git a/Task/Pythagorean-triples/PL-I/pythagorean-triples-1.pli b/Task/Pythagorean-triples/PL-I/pythagorean-triples-1.pli new file mode 100644 index 0000000000..04c6da0bd7 --- /dev/null +++ b/Task/Pythagorean-triples/PL-I/pythagorean-triples-1.pli @@ -0,0 +1,90 @@ +*process source attributes xref or(!); + /********************************************************************* + * REXX pgm counts number of Pythagorean triples + * that exist given a max perimeter of N, + * and also counts how many of them are primatives. + * 05.05.2013 Walter Pachl translated from REXX version 2 + *********************************************************************/ + pyt: Proc Options(main); + Dcl sysprint Print; + Dcl (addr,mod,right) Builtin; + Dcl memn Bin Fixed(31) Init(0); + Dcl mabca(300) Char(12); + Dcl 1 mabc, + 2 ma Dec fixed(7), + 2 mb Dec fixed(7), + 2 mc Dec fixed(7); + Dcl mabce Char(12) Based(addr(mabc)); + Dcl 1 abc, + 2 a Dec fixed(7), + 2 b Dec fixed(7), + 2 c Dec fixed(7); + Dcl abce Char(12) Based(addr(abc)); + Dcl (prims,trips,m,n,aa,aabb,cc,aeven,ab) Dec Fixed(7); + mabca=''; + trips=0; + prims=0; + n=100; + la: + Do a=3 To n/3; + aa=a*a; /* limit side to 1/3 of perimeter.*/ + aeven=mod(a,2)=0; + lb:Do b=a+1 By 1+aeven; /* triangle can't be isosceles. */ + ab=a+b; /* compute partial perimeter. */ + If ab>=n Then + Iterate la; /* a+b>perimeter? Try different A*/ + aabb=aa+b*b; /* compute sum of a² + b² (cheat)*/ + Do c=b+1 By 1; + cc=c*c; /* 3rd side: also compute c² */ + If aeven Then + If mod(c,2)=0 Then + Iterate; + If ab+c>n Then + Iterate la; /* a+b+c > perimeter? Try diff A.*/ + If cc>aabb Then + Iterate lb; /* c² > a²+b² ? Try different B.*/ + If cc^=aabb Then + Iterate; /* c² ¬= a²+b² ? Try different C.*/ + If mema(abce) Then + Iterate; + trips=trips+1; /* eureka. */ + prims=prims+1; /* count this primitive triple. */ + Put Edit(a,b,c,' ',right(a**2+b**2,5),right(c**2,5),a+b+c) + (Skip,f(4),2(f(5)),a,2(f(6)),f(9)); + Do m=2 By 1; + ma=a*m; + mb=b*m; + mc=c*m; /* gen non-primitives. */ + If ma+mb+mc>n Then + Leave; + /* is this multiple a triple ? */ + trips=trips+1; /* yuppers, then we found another.*/ + If mod(m,2)=1 Then /* store as even multiple. */ + call mems(mabce); + Put Edit(ma,mb,mc,' * ', + right(ma**2+mb**2,5),right(mc**2,5),ma+mb+mc) + (Skip,f(4),2(f(5)),a,2(f(6)),f(9)); + End; /* m */ + End; /* c */ + End; /* b */ + End; /* a */ + Put Edit('max perimeter = ',n, /* show a single line of output. */ + 'Pythagorean triples =',trips, + 'primitives =',prims) + (Skip,a,f(5),2(x(9),a,f(4))); + + mems: Proc(e); + Dcl e Char(12); + memn+=1; + mabca(memn)=e; + End; + + mema: Proc(e) Returns(bit(1)); + Dcl e Char(12); + Do memi=1 To memn; + If mabca(memi)=e Then Return('1'b); + End; + Return('0'b); + End; + + End; diff --git a/Task/Pythagorean-triples/PL-I/pythagorean-triples-2.pli b/Task/Pythagorean-triples/PL-I/pythagorean-triples-2.pli new file mode 100644 index 0000000000..fd0970a8d0 --- /dev/null +++ b/Task/Pythagorean-triples/PL-I/pythagorean-triples-2.pli @@ -0,0 +1,32 @@ +pythagorean: procedure options (main, reorder); /* 23 January 2014 */ + declare (a, b, c) fixed (3); + declare (asquared, bsquared) fixed; + declare (triples, primitives) fixed binary(31) initial (0); + + do a = 1 to 100; + asquared = a*a; + do b = a+1 to 100; + bsquared = b*b; + do c = b+1 to 100; + if a+b+c <= 100 then + if asquared + bsquared = c*c then + do; + triples = triples + 1; + if GCD(a,b) = 1 then primitives = primitives + 1; + end; + end; + end; + end; + put skip data (triples, primitives); + + +GCD: procedure (a, b) returns (fixed binary (31)) recursive; + declare (a, b) fixed binary (31); + + if b = 0 then return (a); + + return (GCD (b, mod(a, b)) ); + +end GCD; + +end pythagorean; diff --git a/Task/QR-decomposition/C/qr-decomposition.c b/Task/QR-decomposition/C/qr-decomposition.c index 9c212a315f..7ef333e6f7 100644 --- a/Task/QR-decomposition/C/qr-decomposition.c +++ b/Task/QR-decomposition/C/qr-decomposition.c @@ -5,7 +5,7 @@ typedef struct { int m, n; double ** v; -} mat_t, *mat; +} mat_t, mat; mat matrix_new(int m, int n) { diff --git a/Task/QR-decomposition/D/qr-decomposition.d b/Task/QR-decomposition/D/qr-decomposition.d index 7ef2feb0d4..0fbf58cb71 100644 --- a/Task/QR-decomposition/D/qr-decomposition.d +++ b/Task/QR-decomposition/D/qr-decomposition.d @@ -56,7 +56,7 @@ Unqual!T[][] transpose(T)(in T[][] m) pure nothrow { } T norm(T)(in T[][] m) pure nothrow { - return reduce!q{ a + b ^^ 2 }(cast(T)0, transversal(m, 0)).sqrt; + return transversal(m, 0).map!q{ a ^^ 2 }.sum.sqrt; } T[][] makeUnitVector(T)(in size_t dim) pure nothrow { diff --git a/Task/QR-decomposition/Maple/qr-decomposition.maple b/Task/QR-decomposition/Maple/qr-decomposition.maple new file mode 100644 index 0000000000..4535a4dda8 --- /dev/null +++ b/Task/QR-decomposition/Maple/qr-decomposition.maple @@ -0,0 +1,6 @@ +with(LinearAlgebra): + +Q,R := QRDecomposition( evalf( <<12|-51|4>,<6|167|-68>,<-4|24|-41>>) ): + +Q; +R; diff --git a/Task/Quaternion-type/AutoHotkey/quaternion-type.ahk b/Task/Quaternion-type/AutoHotkey/quaternion-type.ahk new file mode 100644 index 0000000000..8c223fa9ae --- /dev/null +++ b/Task/Quaternion-type/AutoHotkey/quaternion-type.ahk @@ -0,0 +1,72 @@ +q := [1, 2, 3, 4] +q1 := [2, 3, 4, 5] +q2 := [3, 4, 5, 6] +r := 7 + +MsgBox, % "q = " PrintQ(q) + . "`nq1 = " PrintQ(q1) + . "`nq2 = " PrintQ(q2) + . "`nr = " r + . "`nNorm(q) = " Norm(q) + . "`nNegative(q) = " PrintQ(Negative(q)) + . "`nConjugate(q) = " PrintQ(Conjugate(q)) + . "`nq + r = " PrintQ(AddR(q, r)) + . "`nq1 + q2 = " PrintQ(AddQ(q1, q2)) + . "`nq2 + q1 = " PrintQ(AddQ(q2, q1)) + . "`nqr = " PrintQ(MulR(q, r)) + . "`nq1q2 = " PrintQ(MulQ(q1, q2)) + . "`nq2q1 = " PrintQ(MulQ(q2, q1)) + +Norm(q) { + return sqrt(q[1]**2 + q[2]**2 + q[3]**2 + q[4]**2) +} + +Negative(q) { + a := [] + for k, v in q + a[A_Index] := v * -1 + return a +} + +Conjugate(q) { + a := [] + for k, v in q + a[A_Index] := v * (A_Index = 1 ? 1 : -1) + return a +} + +AddR(q, r) { + a := [] + for k, v in q + a[A_Index] := v + (A_Index = 1 ? r : 0) + return a +} + +AddQ(q1, q2) { + a := [] + for k, v in q1 + a[A_Index] := v + q2[A_Index] + return a +} + +MulR(q, r) { + a := [] + for k, v in q + a[A_Index] := v * r + return a +} + +MulQ(q, u) { + a := [] + , a[1] := q[1]*u[1] - q[2]*u[2] - q[3]*u[3] - q[4]*u[4] + , a[2] := q[1]*u[2] + q[2]*u[1] + q[3]*u[4] - q[4]*u[3] + , a[3] := q[1]*u[3] - q[2]*u[4] + q[3]*u[1] + q[4]*u[2] + , a[4] := q[1]*u[4] + q[2]*u[3] - q[3]*u[2] + q[4]*u[1] + return a +} + +PrintQ(q, b="(") { + for k, v in q + b .= v (A_Index = q.MaxIndex() ? ")" : ", ") + return b +} diff --git a/Task/Quaternion-type/JavaScript/quaternion-type-1.js b/Task/Quaternion-type/JavaScript/quaternion-type-1.js new file mode 100644 index 0000000000..7d45c327d7 --- /dev/null +++ b/Task/Quaternion-type/JavaScript/quaternion-type-1.js @@ -0,0 +1,58 @@ +var Quaternion = (function() { + // The Q() function takes an array argument and changes it + // prototype so that it becomes a Quaternion instance. This is + // scoped only for prototype member access. + function Q(a) { + a.__proto__ = proto; + return a; + } + + // Actual constructor. This constructor converts its arguments to + // an array, then that array to a Quaternion instance, then + // returns that instance. (using "new" with this constructor is + // optional) + function Quaternion() { + return Q(Array.prototype.slice.call(arguments, 0, 4)); + } + + // Prototype for all Quaternions + const proto = { + // Inherits from a 4-element Array + __proto__ : [0,0,0,0], + + // Properties -- In addition to Array[0..3] access, we + // also define matching a, b, c, and d properties + get a() this[0], + get b() this[1], + get c() this[2], + get d() this[3], + + // Methods + norm : function() Math.sqrt(this.map(function(x) x*x).reduce(function(x,y) x+y)), + negate : function() Q(this.map(function(x) -x)), + conjugate : function() Q([ this[0] ].concat(this.slice(1).map(function(x) -x))), + add : function(x) { + if ("number" === typeof x) { + return Q([ this[0] + x ].concat(this.slice(1))); + } else { + return Q(this.map(function(v,i) v+x[i])); + } + }, + mul : function(r) { + var q = this; + if ("number" === typeof r) { + return Q(q.map(function(e) e*r)); + } else { + return Q([ q[0] * r[0] - q[1] * r[1] - q[2] * r[2] - q[3] * r[3], + q[0] * r[1] + q[1] * r[0] + q[2] * r[3] - q[3] * r[2], + q[0] * r[2] - q[1] * r[3] + q[2] * r[0] + q[3] * r[1], + q[0] * r[3] + q[1] * r[2] - q[2] * r[1] + q[3] * r[0] ]); + } + }, + equals : function(q) this.every(function(v,i) v === q[i]), + toString : function() (this[0] + " + " + this[1] + "i + "+this[2] + "j + " + this[3] + "k").replace(/\+ -/g, '- ') + }; + + Quaternion.prototype = proto; + return Quaternion; +})(); diff --git a/Task/Quaternion-type/JavaScript/quaternion-type-2.js b/Task/Quaternion-type/JavaScript/quaternion-type-2.js new file mode 100644 index 0000000000..41088bc916 --- /dev/null +++ b/Task/Quaternion-type/JavaScript/quaternion-type-2.js @@ -0,0 +1,18 @@ +var q = Quaternion(1,2,3,4); +var q1 = Quaternion(2,3,4,5); +var q2 = Quaternion(3,4,5,6); +var r = 7; + +console.log("q = "+q); +console.log("q1 = "+q1); +console.log("q2 = "+q2); +console.log("r = "+r); +console.log("1. q.norm() = "+q.norm()); +console.log("2. q.negate() = "+q.negate()); +console.log("3. q.conjugate() = "+q.conjugate()); +console.log("4. q.add(r) = "+q.add(r)); +console.log("5. q1.add(q2) = "+q1.add(q2)); +console.log("6. q.mul(r) = "+q.mul(r)); +console.log("7.a. q1.mul(q2) = "+q1.mul(q2)); +console.log("7.b. q2.mul(q1) = "+q2.mul(q1)); +console.log("8. q1.mul(q2) " + (q1.mul(q2).equals(q2.mul(q1)) ? "==" : "!=") + " q2.mul(q1)"); diff --git a/Task/Quaternion-type/Octave/quaternion-type-1.octave b/Task/Quaternion-type/Octave/quaternion-type-1.octave new file mode 100644 index 0000000000..97d6510de9 --- /dev/null +++ b/Task/Quaternion-type/Octave/quaternion-type-1.octave @@ -0,0 +1 @@ +pkg install -forge quaternion diff --git a/Task/Quaternion-type/Octave/quaternion-type-2.octave b/Task/Quaternion-type/Octave/quaternion-type-2.octave new file mode 100644 index 0000000000..3d862006d1 --- /dev/null +++ b/Task/Quaternion-type/Octave/quaternion-type-2.octave @@ -0,0 +1,24 @@ +> q = quaternion (1, 2, 3, 4) +q = 1 + 2i + 3j + 4k +> q1 = quaternion (2, 3, 4, 5) +q1 = 2 + 3i + 4j + 5k +> q2 = quaternion (3, 4, 5, 6) +q2 = 3 + 4i + 5j + 6k +> r = 7 +r = 7 +> norm(q) +ans = 5.4772 +> -q +ans = -1 - 2i - 3j - 4k +> conj(q) +ans = 1 - 2i - 3j - 4k +> q + r +ans = 8 + 2i + 3j + 4k +> q1 + q2 +ans = 5 + 7i + 9j + 11k +> q * r +ans = 7 + 14i + 21j + 28k +> q1 * q2 +ans = -56 + 16i + 24j + 26k +> q1 == q2 +ans = 0 diff --git a/Task/Quine/Frink/quine.frink b/Task/Quine/Frink/quine.frink new file mode 100644 index 0000000000..3e1a2a2959 --- /dev/null +++ b/Task/Quine/Frink/quine.frink @@ -0,0 +1,2 @@ +d="633d636861725b33345d3b653d643b7072696e745b22643d2463246424635c6e222b28653d7e25732f285b612d7a302d395d7b327d292f636861725b7061727365496e745b24312c31365d5d2f6567295d" +c=char[34];e=d;print["d=$c$d$c\n"+(e=~%s/([a-z0-9]{2})/char[parseInt[$1,16]]/eg)] diff --git a/Task/Quine/Scala/quine-3.scala b/Task/Quine/Scala/quine-3.scala new file mode 100644 index 0000000000..a02ea9a574 --- /dev/null +++ b/Task/Quine/Scala/quine-3.scala @@ -0,0 +1 @@ +val x="val x=%c%s%1$c;printf(x,34,x)";printf(x,34,x) diff --git a/Task/RIPEMD-160/Common-Lisp/ripemd-160.lisp b/Task/RIPEMD-160/Common-Lisp/ripemd-160.lisp new file mode 100644 index 0000000000..62f18c6615 --- /dev/null +++ b/Task/RIPEMD-160/Common-Lisp/ripemd-160.lisp @@ -0,0 +1,8 @@ +(ql:quickload 'ironclad) +(defun string-to-ripemd-160 (str) + "Return the RIPEMD-160 digest of the given ASCII string." + (ironclad:byte-array-to-hex-string + (ironclad:digest-sequence :ripemd-160 + (ironclad:ascii-string-to-byte-array str))) + +(string-to-ripemd-160 "Rosetta Code") diff --git a/Task/RIPEMD-160/D/ripemd-160.d b/Task/RIPEMD-160/D/ripemd-160.d index 80105c3de5..451fd08245 100644 --- a/Task/RIPEMD-160/D/ripemd-160.d +++ b/Task/RIPEMD-160/D/ripemd-160.d @@ -1,6 +1,5 @@ -import std.stdio, std.digest.ripemd; - void main() { - auto txt = "Rosetta Code"; - writeln("%-(%02x%)", txt.ripemd160Of()); + import std.stdio, std.digest.ripemd; + + writefln("%(%02x%)", "Rosetta Code".ripemd160Of); } diff --git a/Task/RIPEMD-160/Lua/ripemd-160.lua b/Task/RIPEMD-160/Lua/ripemd-160.lua new file mode 100644 index 0000000000..efa0cf423e --- /dev/null +++ b/Task/RIPEMD-160/Lua/ripemd-160.lua @@ -0,0 +1,5 @@ +#!/usr/bin/lua + +require "crypto" + +print(crypto.digest("ripemd160", "Rosetta Code")) diff --git a/Task/Random-numbers/Rust/random-numbers.rust b/Task/Random-numbers/Rust/random-numbers.rust new file mode 100644 index 0000000000..13baecd5d4 --- /dev/null +++ b/Task/Random-numbers/Rust/random-numbers.rust @@ -0,0 +1,12 @@ +use std::rand; +use std::rand::distributions::{Normal, IndependentSample}; + +fn main() { + let mut rands = [0.0, ..1000]; + let normal = Normal::new(1.0, 0.5); + + for i in range(0, 1000) { + let v = normal.ind_sample(&mut rand::task_rng()); + rands[i] = v; + } +} diff --git a/Task/Range-expansion/ALGOL-68/range-expansion.alg b/Task/Range-expansion/ALGOL-68/range-expansion.alg index a188b531f9..64c01f2e61 100644 --- a/Task/Range-expansion/ALGOL-68/range-expansion.alg +++ b/Task/Range-expansion/ALGOL-68/range-expansion.alg @@ -33,7 +33,157 @@ PROC range expand = ([]RANGEINT list)[]INT: ( out ); +# test:( []RANGEINT list = (-6, RANGE(-3, -1), RANGE(3, 5), RANGE(7, 11), 14, 15, RANGE(17, 20)); print((range expand(list), new line)) ) +# + + +# converts string containing a comma-separated list of ranges and values to a []RANGEINT # +OP TORANGE = ( STRING s )[]RANGEINT: +BEGIN + + # counts the number of elements - one more than the number of commas # + # and so assumes there is always at least one element # + PROC count elements = INT: + BEGIN + + INT elements := 1; + + FOR pos FROM LWB s TO UPB s + DO + IF s[ pos ] = "," + THEN + elements +:= 1 + FI + OD; + + # RESULT # + elements + END; # count elements # + + REF[]RANGEINT result = HEAP [ 1 : count elements ]RANGEINT; + + # does the actual parsing - assumes the string is syntatically valid and doesn't check for errors # + # - in particular, a string with no elements will cause problems, as will space characters in the string # + PROC parse range string = []RANGEINT: + BEGIN + + INT element := 0; + INT str pos := 1; + + PROC next = VOID: str pos +:= 1; + PROC curr char = CHAR: IF str pos > UPB s THEN "?" ELSE s[ str pos ] FI; + PROC have minus = BOOL: curr char = "-"; + PROC have digit = BOOL: curr char >= "0" AND curr char <= "9"; + + + # parses a number out of the string # + # the number must be a sequence of digits with an optional leading minus sign # + PROC get number = INT: + BEGIN + + INT number := 0; + + INT sign multiplier = IF have minus + THEN + # negaive number # + # skip the sign # + next; + -1 + ELSE + # positive number # + 1 + FI; + + WHILE curr char >= "0" AND curr char <= "9" + DO + number *:= 10; + number +:= ( ABS curr char - ABS "0" ); + next + OD; + + # RESULT # + number * sign multiplier + END; # get number # + + + # main parsing # + WHILE str pos <= UPB s + DO + CHAR c = curr char; + + IF have minus OR have digit + THEN + # have the start of a number # + INT from value = get number; + element +:= 1; + IF NOT have minus + THEN + # not a range # + result[ element ] := from value + ELSE + # have a range # + next; + INT to value = get number; + result[ element ] := RANGE( from value, to value ) + FI + ELSE + # should be a comma # + next + FI + OD; + + # RESULT # + result + END; # parse range string # + + +# RESULT # + parse range string +END; # TORANGE # + + +# converts a []INT to a comma separated string of the elements # +OP TOSTRING = ( []INT values )STRING: +BEGIN + + # converts an integer to a string # + OP TOSTRING = ( INT value )STRING: + BEGIN + STRING result := ""; + INT n := ABS value; + + WHILE + REPR ( ( n MOD 10 ) + ABS "0" ) PLUSTO result; + n OVERAB 10; + n > 0 + DO + SKIP + OD; + + # RESULT # + IF value < 0 THEN "-" ELSE "" FI + result + END; # TOSTRING # + + + STRING result := ""; + STRING separator := ""; + + FOR pos FROM LWB values TO UPB values + DO + result +:= ( separator + TOSTRING values[ pos ] ); + separator := "," + OD; + +# RESULT # + result +END; # TOSTRING # + + + +test:( + print( ( TOSTRING range expand( TORANGE "-6,-3--1,3-5,7-11,14,15,17-20" ), newline ) ) +) diff --git a/Task/Range-expansion/J/range-expansion-1.j b/Task/Range-expansion/J/range-expansion-1.j index ffac8067e9..1450fea10b 100644 --- a/Task/Range-expansion/J/range-expansion-1.j +++ b/Task/Range-expansion/J/range-expansion-1.j @@ -1,6 +1,6 @@ require'strings' -to=: [ + i.@>:@-~ +thru=: <./ + i.@(+*)@-~ num=: _&". normaliz=: rplc&(',-';',_';'--';'-_')@,~&',' -subranges=:<@(to/)@(num;._2)@,&'-';._1 +subranges=:<@(thru/)@(num;._2)@,&'-';._1 rngexp=: ;@subranges@normaliz diff --git a/Task/Range-expansion/Nimrod/range-expansion.nimrod b/Task/Range-expansion/Nimrod/range-expansion.nimrod new file mode 100644 index 0000000000..848195129c --- /dev/null +++ b/Task/Range-expansion/Nimrod/range-expansion.nimrod @@ -0,0 +1,24 @@ +import parseutils, re, strutils + +proc expandRange(input: string): string = + var output: seq[string] = @[] + for range in input.split(','): + var sep = range.find('-', 1) + if sep > 0: # parse range + var first = -1 + if range.substr(0, sep-1).parseInt(first) == 0: + break + var last = -1 + if range.substr(sep+1).parseInt(last) == 0: + break + for i in first..last: + output.add($i) + else: # parse single number + var n = -1 + if range.parseInt(n) > 0: + output.add($n) + else: + break + return output.join(",") + +echo("-6,-3--1,3-5,7-11,14,15,17-20".expandRange) diff --git a/Task/Range-expansion/TXR/range-expansion.txr b/Task/Range-expansion/TXR/range-expansion.txr index d5bb587cd0..d18c3a7d9c 100644 --- a/Task/Range-expansion/TXR/range-expansion.txr +++ b/Task/Range-expansion/TXR/range-expansion.txr @@ -31,10 +31,8 @@ (rangeexpand (rest list)))) (t (cons (first list) (rangeexpand (rest list)))))) - (defun sortdup (list) - (let ((h (hash))) - (each ((n list)) - (set [h n] n)) + (defun sortdup (li) + (let ((h [group-by identity li])) [sort (hash-keys h) <])) (defun rangeexpand (list) diff --git a/Task/Range-extraction/Nimrod/range-extraction.nimrod b/Task/Range-extraction/Nimrod/range-extraction.nimrod new file mode 100644 index 0000000000..8f300ed0ea --- /dev/null +++ b/Task/Range-extraction/Nimrod/range-extraction.nimrod @@ -0,0 +1,30 @@ +import parseutils, re, strutils + +proc extractRange(input: string): string = + var list = input.replace(re"\s+").split(',').map(parseInt) + var ranges: seq[string] = @[] + var i = 0 + while i < list.len: + var first = list[i] # first element in the current range + var offset = i + while True: # skip ahead to the end of the current range + if i + 1 >= list.len: + # reached end of the list + break + if list[i + 1] - (i + 1) != first - offset: + # next element isn't in the current range + break + i.inc + var last = list[i] # last element in the current range + case last - first + of 0: ranges.add($first) + of 1: ranges.add("$1,$2".format([$first, $last])) + else: ranges.add("$1-$2".format([$first, $last])) + i.inc + return ranges.join(",") + +echo(""" + 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39""".extractRange) diff --git a/Task/Range-extraction/Pascal/range-extraction.pascal b/Task/Range-extraction/Pascal/range-extraction.pascal new file mode 100644 index 0000000000..2c2350390c --- /dev/null +++ b/Task/Range-extraction/Pascal/range-extraction.pascal @@ -0,0 +1,75 @@ +program RangeExtraction; + +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + SysUtils; + +function RangeExtraction(const Seq: array of integer): String; +const + SubSeqLen = 3; // minimal length of the range, can be changed. +var + i, j: Integer; + Separator: string = ''; +begin + Result := ''; + i := Low(Seq); + while i <= High(Seq) do + begin + j := i; + // All subsequent values, starting from i, up to High(Seq) possibly + while ((j < High(Seq)) and ((Seq[j+1]-Seq[j]) = 1)) do + Inc(j); + // is it a range ? + if ((j-i) >= (SubSeqLen-1)) then + begin + Result := Result + Format(Separator+'%d-%d',[Seq[i],Seq[j]]); + i := j+1; // Next value to be processed + Separator := ','; + end + else + begin + // Loop, to process the case SubSeqLen > 3 + while i<=j do + begin + Result := Result + Format(Separator+'%d',[Seq[i]]); + Inc(i); // Next value to be processed + Separator := ','; + end; + end; + end; +End; + +procedure DisplayRange(const Seq: array of integer); +var + i: Integer; +begin + Write(Format('[%d', [Seq[Low(Seq)]])); + for i := Low(Seq) + 1 to High(Seq) do + Write(Format(',%d', [Seq[i]])); + WriteLn('] => ' + RangeExtraction(Seq)); + WriteLn; +End; + +begin + DisplayRange([0]); + DisplayRange([0,1]); + DisplayRange([0,2]); + DisplayRange([0,1,2]); + DisplayRange([0,1,2,3]); + DisplayRange([0,1,2,3,4,5,6,7]); + DisplayRange([0,2,3,4,5,6,7,9]); + DisplayRange([0,2,4,6,8,10]); + DisplayRange([0,1,2,3,4,5,6,7,9]); + DisplayRange([0,1,2,3,4,6,9,10,11,12]); + + DisplayRange([ + 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]); + ReadLn; +end. diff --git a/Task/Rate-counter/AutoHotkey/rate-counter-1.ahk b/Task/Rate-counter/AutoHotkey/rate-counter-1.ahk new file mode 100644 index 0000000000..68349356f4 --- /dev/null +++ b/Task/Rate-counter/AutoHotkey/rate-counter-1.ahk @@ -0,0 +1,15 @@ +SetBatchLines, -1 +Tick := A_TickCount ; store tickcount +Loop, 1000000 { + Random, x, 1, 1000000 + Random, y, 1, 1000000 + gcd(x, y) +} +t := A_TickCount - Tick ; store ticks elapsed +MsgBox, % t / 1000 " Seconds elapsed.`n" Round(1 / (t / 1000000000), 0) " Loop iterations per second." + +gcd(a, b) { ; Euclidean GCD + while b + t := b, b := Mod(a, b), a := t + return, a +} diff --git a/Task/Rate-counter/AutoHotkey/rate-counter-2.ahk b/Task/Rate-counter/AutoHotkey/rate-counter-2.ahk new file mode 100644 index 0000000000..fe153691ad --- /dev/null +++ b/Task/Rate-counter/AutoHotkey/rate-counter-2.ahk @@ -0,0 +1,23 @@ +SetBatchLines, -1 +QPX(1) ; start timer +Loop, 1000000 { + Random, x, 1, 1000000 + Random, y, 1, 1000000 + gcd(x, y) +} +t := QPX(0) ; end timer +MsgBox, % t " Seconds elapsed.`n" Round(1 / (t / 1000000), 0) " Loop iterations per second." + +QPX( N=0 ) { ; Wrapper for QueryPerformanceCounter()by SKAN | CD: 06/Dec/2009 + Static F,A,Q,P,X ; www.autohotkey.com/forum/viewtopic.php?t=52083 | LM: 10/Dec/2009 + If ( N && !P ) + Return DllCall("QueryPerformanceFrequency",Int64P,F) + (X:=A:=0) + DllCall("QueryPerformanceCounter",Int64P,P) + DllCall("QueryPerformanceCounter",Int64P,Q), A:=A+Q-P, P:=Q, X:=X+1 + Return ( N && X=N ) ? (X:=X-1)<<64 : ( N=0 && (R:=A/X/F) ) ? ( R + (A:=P:=X:=0) ) : 1 +} + +gcd(a, b) { ; Euclidean GCD + while b + t := b, b := Mod(a, b), a := t + return, a +} diff --git a/Task/Ray-casting-algorithm/AutoHotkey/ray-casting-algorithm.ahk b/Task/Ray-casting-algorithm/AutoHotkey/ray-casting-algorithm.ahk index 296d6b9237..a5a7be0abf 100644 --- a/Task/Ray-casting-algorithm/AutoHotkey/ray-casting-algorithm.ahk +++ b/Task/Ray-casting-algorithm/AutoHotkey/ray-casting-algorithm.ahk @@ -1,11 +1,94 @@ -PiP(P,N) ; P is point, N is number of sides -{ - count := 0 - Loop %N% - If ray_intersects_segment(P,A_Index) - count++ - if mod(count,2) - return false ; P isn't in the polygon - else - return true ; P is in the polygon +Points :=[{x: 5.0, y: 5.0} + , {x: 5.0, y: 8.0} + , {x:-10.0, y: 5.0} + , {x: 0.0, y: 5.0} + , {x: 10.0, y: 5.0} + , {x: 8.0, y: 5.0} + , {x: 10.0, y:10.0}] +Square :=[{x: 0.0, y: 0.0}, {x:10.0, y: 0.0} + , {x:10.0, y: 0.0}, {x:10.0, y:10.0} + , {x:10.0, y:10.0}, {x: 0.0, y:10.0} + , {x: 0.0, y:10.0}, {x: 0.0, y: 0.0}] +Sq_Hole:=[{x: 0.0, y: 0.0}, {x:10.0, y: 0.0} + , {x:10.0, y: 0.0}, {x:10.0, y:10.0} + , {x:10.0, y:10.0}, {x: 0.0, y:10.0} + , {x: 0.0, y:10.0}, {x: 0.0, y: 0.0} + , {x: 2.5, y: 2.5}, {x: 7.5, y: 2.5} + , {x: 7.5, y: 2.5}, {x: 7.5, y: 7.5} + , {x: 7.5, y: 7.5}, {x: 2.5, y: 7.5} + , {x: 2.5, y: 7.5}, {x: 2.5, y: 2.5}] +Strange:=[{x: 0.0, y: 0.0}, {x: 2.5, y: 2.5} + , {x: 2.5, y: 2.5}, {x: 0.0, y:10.0} + , {x: 0.0, y:10.0}, {x: 2.5, y: 7.5} + , {x: 2.5, y: 7.5}, {x: 7.5, y: 7.5} + , {x: 7.5, y: 7.5}, {x:10.0, y:10.0} + , {x:10.0, y:10.0}, {x:10.0, y: 0.0} + , {x:10.0, y: 0.0}, {x: 2.5, y: 2.5}] +Exagon :=[{x: 3.0, y: 0.0}, {x: 7.0, y: 0.0} + , {x: 7.0, y: 0.0}, {x:10.0, y: 5.0} + , {x:10.0, y: 5.0}, {x: 7.0, y:10.0} + , {x: 7.0, y:10.0}, {x: 3.0, y:10.0} + , {x: 3.0, y:10.0}, {x: 0.0, y: 5.0} + , {x: 0.0, y: 5.0}, {x: 3.0, y: 0.0}] +Polygons := {"Square":Square, "Sq_Hole":Sq_Hole, "Strange":Strange, "Exagon":Exagon} +For j, Poly in Polygons + For i, Point in Points + If (point_in_polygon(Point,Poly)) + s.= j " does contain point " i "`n" + Else + s.= j " doesn't contain point " i "`n" +Msgbox %s% + +point_in_polygon(Point,Poly) { + n:=Poly.MaxIndex() + count:=0 + loop, %n% { + if (ray_intersects_segment(Point,Poly[A_Index],Poly[mod(A_Index,n)+1])) { + count++ + } + } + if (mod(count,2)) { ; true = inside, false = outside + return true ; P is in the polygon + } else { + return false ; P isn't in the polygon + } +} + +ray_intersects_segment(P,A,B) { + ;P = the point from which the ray starts + ;A = the end-point of the segment with the smallest y coordinate + ;B = the end-point of the segment with the greatest y coordinate + if (A.y > B.y) { + temp:=A + A:=B + B:=temp + } + if (P.y = A.y or P.y = B.y) { + P.y += 0.000001 + } + if (P.y < A.y or P.y > B.y) { + return false + } else if (P.x > A.x && P.x > B.x) { + return false + } else { + if (P.x < A.x && P.x < B.x) { + return true + } else { + if (A.x != B.x) { + m_red := (B.y - A.y)/(B.x - A.x) + } else { + m_red := "inf" + } + if (A.x != P.x) { + m_blue := (P.y - A.y)/(P.x - A.x) + } else { + m_blue := "inf" + } + if (m_blue >= m_red) { + return true + } else { + return false + } + } + } } diff --git a/Task/Read-a-configuration-file/Java/read-a-configuration-file.java b/Task/Read-a-configuration-file/Java/read-a-configuration-file.java new file mode 100644 index 0000000000..a536ad78dc --- /dev/null +++ b/Task/Read-a-configuration-file/Java/read-a-configuration-file.java @@ -0,0 +1,70 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ConfigReader { + private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); + private static final Map DEFAULTS = new HashMap() {{ + put( "needspeeling", false ); + put( "seedsremoved", false ); + }}; + + public static void main( final String[] args ) { + System.out.println( parseFile( args[ 0 ] ) ); + } + + public static Map parseFile( final String fileName ) { + final Map result = new HashMap( DEFAULTS ); + /*v*/ BufferedReader reader = null; + + try { + reader = new BufferedReader( new FileReader( fileName ) ); + for ( String line; null != ( line = reader.readLine() ); ) { + parseLine( line, result ); + } + } catch ( final IOException x ) { + throw new RuntimeException( "Oops: " + x, x ); + } finally { + if ( null != reader ) try { + reader.close(); + } catch ( final IOException x2 ) { + System.err.println( "Could not close " + fileName + " - " + x2 ); + } + } + + return result; + } + + private static void parseLine( final String line, final Map map ) { + if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) + return; + + final Matcher matcher = LINE_PATTERN.matcher( line ); + + if ( ! matcher.matches() ) { + System.err.println( "Bad config line: " + line ); + return; + } + + final String key = matcher.group( 1 ).trim().toLowerCase(); + final String value = matcher.group( 2 ).trim(); + + if ( "".equals( value ) ) { + map.put( key, true ); + } else if ( -1 == value.indexOf( ',' ) ) { + map.put( key, value ); + } else { + final String[] values = value.split( "," ); + + for ( int i = 0; i < values.length; i++ ) { + values[ i ] = values[ i ].trim(); + } + map.put( key, Arrays.asList( values ) ); + } + } +} diff --git a/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin b/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin new file mode 100644 index 0000000000..fae4fbc98e --- /dev/null +++ b/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin @@ -0,0 +1,38 @@ +data class Configuration(val map: Map) { + val fullName: String by Delegates.mapVal(map) + val favoriteFruit: String by Delegates.mapVal(map) + val needsPeeling: Boolean by Delegates.mapVal(map) + val otherFamily: List by Delegates.mapVal(map) +} + +fun main(args: Array) { + val configurationPath = Paths.get(args[0])!! + + val configurables = Files.readAllLines(configurationPath, StandardCharsets.UTF_8) + .map { it.trim() } + .filterNot { it.isEmpty() } + .filterNot(::commentedOut) + .map(::toKeyValuePairs) + + val configurationMap: MutableMap = hashMapOf("needsPeeling" to false) + for (configurable in configurables) { + val (key, value) = configurable + when (key) { + "FULLNAME" -> configurationMap.put("fullName", value) + "FAVOURITEFRUIT" -> configurationMap.put("favoriteFruit", value) + "NEEDSPEELING" -> configurationMap.put("needsPeeling", true) + "OTHERFAMILY" -> configurationMap.put("otherFamily", value.split(" , ").map { it.trim() }) + else -> println("Encountered unexpected key ${key}=${value}") + } + } + + val configuration = Configuration(configurationMap) +} + +private fun commentedOut(line: String): Boolean = (line.indexOf("#") == 0 || line.indexOf(";") == 0) + +private fun toKeyValuePairs(line: String): Pair { + return line.split(" ", 2).let { + Pair(it[0], if (it.size == 1) "" else it[1]) + } +} diff --git a/Task/Read-a-file-line-by-line/PowerShell/read-a-file-line-by-line.psh b/Task/Read-a-file-line-by-line/PowerShell/read-a-file-line-by-line.psh new file mode 100644 index 0000000000..9f58cff6c4 --- /dev/null +++ b/Task/Read-a-file-line-by-line/PowerShell/read-a-file-line-by-line.psh @@ -0,0 +1,10 @@ +$reader = [System.IO.File]::OpenText($mancorfile) +try { + do { + $line = $reader.ReadLine() + if ($line -eq $null) { break } + DoSomethingWithLine($line) + } while ($TRUE) +} finally { + $reader.Close() +} diff --git a/Task/Read-a-specific-line-from-a-file/PowerShell/read-a-specific-line-from-a-file.psh b/Task/Read-a-specific-line-from-a-file/PowerShell/read-a-specific-line-from-a-file.psh new file mode 100644 index 0000000000..c61e6dc963 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/PowerShell/read-a-specific-line-from-a-file.psh @@ -0,0 +1,7 @@ +$file = Get-Content c:\file.txt +if ($file.count -lt 7) +{Write-Warning "The file is too short!"} +else +{ + $file | Where Readcount -eq 7 | set-variable -name Line7 +} diff --git a/Task/Read-entire-file/Rust/read-entire-file.rust b/Task/Read-entire-file/Rust/read-entire-file.rust new file mode 100644 index 0000000000..f73017d038 --- /dev/null +++ b/Task/Read-entire-file/Rust/read-entire-file.rust @@ -0,0 +1,11 @@ +// -*- rust v0.9 -*- +use std::str; +use std::io::File; + +fn main() { + let path = Path::new("hello.txt"); + let mut file = File::open(&path); + + let contents = str::from_utf8_owned(file.read_to_end()); + println(contents); +} diff --git a/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-1.ahk b/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-1.ahk index 95ce13e7d5..ef253cdcea 100644 --- a/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-1.ahk +++ b/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-1.ahk @@ -1,7 +1,8 @@ Sqrt(Number) ; square root -Log(Number) ; returns logarithm (base 10) -Ln(Number) ; returns natural logarithm (base e) -Exp(N) ; returns e to the N power +Log(Number) ; logarithm (base 10) +Ln(Number) ; natural logarithm (base e) +Exp(N) ; e to the power N Abs(Number) ; absolute value -Floor(Number) ; floor value -Ceil(Number) ; ceiling value +Floor(Number) ; floor +Ceil(Number) ; ceiling +x**y ; x to the power y diff --git a/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-2.ahk b/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-2.ahk index 9bf922dfc5..3dd8416bf1 100644 --- a/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-2.ahk +++ b/Task/Real-constants-and-functions/AutoHotkey/real-constants-and-functions-2.ahk @@ -1,4 +1,2 @@ -x**y ; x to the y power -pi() { ; will return pi when custom function is called -return 22/7 -} +e:=exp(1) +pi:=2*asin(1) diff --git a/Task/Real-constants-and-functions/Frink/real-constants-and-functions.frink b/Task/Real-constants-and-functions/Frink/real-constants-and-functions.frink new file mode 100644 index 0000000000..6f85064682 --- /dev/null +++ b/Task/Real-constants-and-functions/Frink/real-constants-and-functions.frink @@ -0,0 +1,10 @@ +e +pi, π // Unicode can also be written in ASCII programs as \u03C0 +sqrt[x] +ln[x] // Natural log +log[x] // Log to base 10 +exp[x], e^x +abs[x] +floor[x] // Except for complex numbers where there's no good interpretation. +ceil[x] // Except for complex numbers where there's no good interpretation. +x^y diff --git a/Task/Record-sound/AutoHotkey/record-sound.ahk b/Task/Record-sound/AutoHotkey/record-sound.ahk new file mode 100644 index 0000000000..79347fc7ee --- /dev/null +++ b/Task/Record-sound/AutoHotkey/record-sound.ahk @@ -0,0 +1,36 @@ +name := "sample" +waitsec := 5 +Tooltip Recording %name%.wav +MCI_SendString("close all wait") +MCI_SendString("open new type waveaudio alias " . name) +MCI_SendString("set " . name . " time format ms wait") +;MCI_SendString("set " . name . " bitspersample 16 wait") +;MCI_SendString("set " . name . " channels 1 wait") +;MCI_SendString("set " . name . " samplespersec 16000 wait") +;MCI_SendString("set " . name . " alignment 1 wait") +;MCI_SendString("set " . name . " bytespersec 8000 wait") +MCI_SendString("record " . name) +Sleep waitsec*1000 +MCI_SendString("stop " . name . " wait") +MCI_SendString("save " . name . " """ . name . ".wav""") +Tooltip Finished ... Playing +MCI_SendString("delete " . name) +MCI_SendString("close " . name . " wait") +MCI_SendString("open """ . name . ".wav"" type waveaudio alias " . name) +MCI_SendString("play " . name . " wait") +MCI_SendString("close " . name . " wait") +Tooltip +Return + +MCI_SendString(p_lpszCommand,ByRef r_lpszReturnString="",p_hwndCallback=0) { + VarSetCapacity(r_lpszReturnString,512,0) + Return DllCall("winmm.dll\mciSendString" . (A_IsUnicode ? "W":"A") + ,"Str",p_lpszCommand ;-- lpszCommand + ,"Str",r_lpszReturnString ;-- lpszReturnString + ,"UInt",512 ;-- cchReturn + ,A_PtrSize ? "Ptr":"UInt",p_hwndCallback ;-- hwndCallback + ,"Cdecl Int") ;-- Return type +} +; For more intuitive functions, see the MCI library by jballi. +; doc: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.html +; download: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.ahk diff --git a/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit b/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit index cd02cbe02e..b93aa60ebf 100644 --- a/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit +++ b/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit @@ -38,9 +38,7 @@ Func ToReducedRowEchelonForm($matrix) Next $lead += 1 Next - ;########################################################## - ;###################CONSOLE OUTPUT######################### - ;########################################################## + ; Console Output For $i = 0 To $rowCount ConsoleWrite("[") For $k = 0 To $columnCount @@ -49,8 +47,6 @@ Func ToReducedRowEchelonForm($matrix) Next ConsoleWrite("]" & @CRLF) Next - ;########################################################## - ;########################################################## - ;########################################################## + ; End of Console Output Return $matrix EndFunc ;==>ToReducedRowEchelonForm diff --git a/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d b/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d index 95280ddafd..286d6d40b3 100644 --- a/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d +++ b/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.array, std.conv; -void toReducedRowEchelonForm(T)(T[][] M) pure /*nothrow*/ { +void toReducedRowEchelonForm(T)(T[][] M) pure nothrow { if (M.empty) return; immutable nrows = M.length; @@ -23,10 +23,11 @@ void toReducedRowEchelonForm(T)(T[][] M) pure /*nothrow*/ { } swap(M[i], M[r]); } - M[r][] /= M[r][lead]; // not nothrow + + M[r][] /= M[r][lead]; foreach (j, ref mj; M) if (j != r) - mj[] -= M[r][] * mj[lead]; // not nothrow + mj[] -= M[r][] * mj[lead]; lead++; } } @@ -35,6 +36,7 @@ void main() { auto A = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]]; - toReducedRowEchelonForm(A); + + A.toReducedRowEchelonForm; writefln("%(%(%2d %)\n%)", A); } diff --git a/Task/Reduced-row-echelon-form/Maple/reduced-row-echelon-form.maple b/Task/Reduced-row-echelon-form/Maple/reduced-row-echelon-form.maple new file mode 100644 index 0000000000..532fee6c00 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Maple/reduced-row-echelon-form.maple @@ -0,0 +1,3 @@ +with(LinearAlgebra): + +ReducedRowEchelonForm(<<1,2,-2>|<2,3,0>|<-1,-1,-3>|<-4,-11,22>>); diff --git a/Task/Regular-expressions/D/regular-expressions.d b/Task/Regular-expressions/D/regular-expressions.d index 0b46eba025..1cec6ce653 100644 --- a/Task/Regular-expressions/D/regular-expressions.d +++ b/Task/Regular-expressions/D/regular-expressions.d @@ -1,12 +1,12 @@ -import std.stdio, std.regex; - void main() { - immutable string s = "I am a string"; + import std.stdio, std.regex; - // Test: - if (!match(s, r"string$").empty) - writeln("Ends with 'string'."); + immutable s = "I am a string"; - // Substitute: - replace(s, regex(" a "), " another ").writeln(); + // Test. + if (!s.match(r"string$").empty) + "Ends with 'string'.".writeln; + + // Substitute. + s.replace(" a ".regex, " another ").writeln; } diff --git a/Task/Regular-expressions/Dart/regular-expressions.dart b/Task/Regular-expressions/Dart/regular-expressions.dart new file mode 100644 index 0000000000..58dceecfc4 --- /dev/null +++ b/Task/Regular-expressions/Dart/regular-expressions.dart @@ -0,0 +1,10 @@ +RegExp regexp = new RegExp(r'\w+\!'); + +String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}'; + +void main(){ + String hello = 'hello hello! world world!'; + String hellomodified = hello.replaceAllMapped(regexp, capitalize); + print(hello); + print(hellomodified); +} diff --git a/Task/Regular-expressions/TXR/regular-expressions-3.txr b/Task/Regular-expressions/TXR/regular-expressions-3.txr new file mode 100644 index 0000000000..6d6d517fd0 --- /dev/null +++ b/Task/Regular-expressions/TXR/regular-expressions-3.txr @@ -0,0 +1,2 @@ +$ txr -p '(regex-parse "a.*b")' +(compound #\a (0+ wild) #\b) diff --git a/Task/Regular-expressions/TXR/regular-expressions-4.txr b/Task/Regular-expressions/TXR/regular-expressions-4.txr new file mode 100644 index 0000000000..c88e762589 --- /dev/null +++ b/Task/Regular-expressions/TXR/regular-expressions-4.txr @@ -0,0 +1,2 @@ +$ txr -p "(regex-compile '(compound #\a (0+ wild) #\b))" +# diff --git a/Task/Regular-expressions/TXR/regular-expressions-5.txr b/Task/Regular-expressions/TXR/regular-expressions-5.txr new file mode 100644 index 0000000000..860bb3461e --- /dev/null +++ b/Task/Regular-expressions/TXR/regular-expressions-5.txr @@ -0,0 +1,2 @@ +$ txr -p '(regsub #/a+/ "-" "baaaaaad")' +"b-d" diff --git a/Task/Remove-duplicate-elements/Frink/remove-duplicate-elements.frink b/Task/Remove-duplicate-elements/Frink/remove-duplicate-elements.frink new file mode 100644 index 0000000000..68fb73142b --- /dev/null +++ b/Task/Remove-duplicate-elements/Frink/remove-duplicate-elements.frink @@ -0,0 +1,9 @@ +b = [1, 5, 2, 6, 6, 2, 2, 1, 9, 8, 6, 5] + +// One way, using OrderedList. An OrderedList is a type of array that keeps +// its elements in order. The items must be comparable. +a = new OrderedList +println[a.insertAllUnique[b]] + +// Another way, using the "set" datatype and back to an array. +println[toArray[toSet[b]] diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ocaml new file mode 100644 index 0000000000..c8c283c64c --- /dev/null +++ b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ocaml @@ -0,0 +1,7 @@ +let uniq lst = + let unique_set = Hashtbl.create (List.length lst) in + List.iter (fun x -> Hashtbl.replace unique_set x ()) lst; + Hashtbl.fold (fun x () xs -> x :: xs) unique_set [] + +let _ = + uniq [1;2;3;2;3;4] diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ocaml new file mode 100644 index 0000000000..14e994f317 --- /dev/null +++ b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ocaml @@ -0,0 +1,8 @@ +let uniq lst = + let seen = Hashtbl.create (List.length lst) in + List.filter (fun x -> let tmp = not (Hashtbl.mem seen x) in + Hashtbl.replace seen x (); + tmp) lst + +let _ = + uniq [1;2;3;2;3;4] diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements.ocaml deleted file mode 100644 index 781110c7a2..0000000000 --- a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements.ocaml +++ /dev/null @@ -1,7 +0,0 @@ -let uniq lst = - let unique_set = Hashtbl.create (List.length lst) in - List.iter (fun x -> Hashtbl.replace unique_set x ()) lst; - Hashtbl.fold (fun x () xs -> x :: xs) unique_set [] - -let _ = - uniq [1;2;3;2;3;4] diff --git a/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-1.pl6 b/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-1.pl6 index bef83b8f4e..b8ce167a9f 100644 --- a/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-1.pl6 +++ b/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-1.pl6 @@ -1,7 +1 @@ -sub nub (@a) { - my @b; - none(@b) eqv $_ and push @b, $_ for @a; - return @b; -} - -my @unique = nub [1, 2, 3, 5, 2, 4, 3, -3, 7, 5, 6]; +my @unique = [1, 2, 3, 5, 2, 4, 3, -3, 7, 5, 6].uniq; diff --git a/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-2.pl6 b/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-2.pl6 index b8ce167a9f..d1c8dbd473 100644 --- a/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-2.pl6 +++ b/Task/Remove-duplicate-elements/Perl-6/remove-duplicate-elements-2.pl6 @@ -1 +1 @@ -my @unique = [1, 2, 3, 5, 2, 4, 3, -3, 7, 5, 6].uniq; +set(1,2,3,5,2,4,3,-3,7,5,6).list diff --git a/Task/Remove-duplicate-elements/Vim-Script/remove-duplicate-elements.vim b/Task/Remove-duplicate-elements/Vim-Script/remove-duplicate-elements.vim new file mode 100644 index 0000000000..bd0b589bf3 --- /dev/null +++ b/Task/Remove-duplicate-elements/Vim-Script/remove-duplicate-elements.vim @@ -0,0 +1 @@ +call filter(list, 'count(list, v:val) == 1') diff --git a/Task/Remove-lines-from-a-file/Pascal/remove-lines-from-a-file.pascal b/Task/Remove-lines-from-a-file/Pascal/remove-lines-from-a-file.pascal new file mode 100644 index 0000000000..dc2b6e7ed2 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Pascal/remove-lines-from-a-file.pascal @@ -0,0 +1,109 @@ +program RemLines; + +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + Classes, SysUtils; + +type + TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines); + +function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse; +const + LineOffs = Length(LineEnding); + +var + TIn, TOut: TFileStream; + tmpFn, MemBuff, FileBuff: String; + EndingPos, CharRead, LineNumber: Integer; + + procedure WriteLine(Line: String); + begin + if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then + // First line to write, without LineEnding => Line unchanged + else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then + // No line to write + Line := '' + else + // all other cases, write Line preceded (!) by LineEnding + Line := LineEnding + Line; + // Write + if Line <> '' then + TOut.Write(Line[1], Length(Line)); + End; + +begin + if not FileExists(FileName) then + raise Exception.CreateFmt('No such file %s', [FileName]); + if From < 1 then + raise Exception.Create('First line must be >= 1'); + + tmpFn := GetTempFileName(ExtractFilePath(FileName), ''); + + TIn := TFileStream.Create(FileName, fmOpenRead); + try + TOut := TFileStream.Create(tmpFn, fmCreate); + try + FileBuff := StringOfChar(' ', 1024); // Reserve memory in a string + LineNumber := 0; + MemBuff := ''; + while True do + begin + CharRead := TIn.Read(FileBuff[1], 1024); + if (CharRead = 0) then + break; // no more char to process + MemBuff += Copy(FileBuff, 1, CharRead); // op += is FPC specific + while True do + begin + // LineEnding can contain 1 or 2 chars, depending on the OS + EndingPos := Pos(LineEnding, MemBuff); + if EndingPos = 0 then + break; // EndingLine in the next reading, maybe + Inc(LineNumber); + WriteLine(Copy(MemBuff, 1, EndingPos - 1)); + MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt); + // Loop for another line in MemBuff + end; + end; + Inc(LineNumber); + WriteLine(MemBuff); // Writes what remains + finally + TOut.Free; + end; + finally + TIn.Free; + end; + // Temp File replaces the original file. + if DeleteFile(FileName) then + RenameFile(tmpFn, FileName) + else + raise Exception.Create('Unable to process the file'); + // Response + if (LineNumber = 0) then + Result := rlrEmptyFile + else if (LineNumber < (From+Count-1)) then + Result := rlrNotEnoughLines + else + Result := rlrOk; +End; + +var + FileName: String; + +begin + FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt'; + try + case RemoveLines(FileName, 4, 3) of + rlrOk: WriteLn('Lines deleted'); + rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName])); + rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file'); + end + except + on E: Exception do + WriteLn('Error: ' + E.Message); + end; + ReadLn; +End. diff --git a/Task/Rename-a-file/Mercury/rename-a-file.mercury b/Task/Rename-a-file/Mercury/rename-a-file.mercury new file mode 100644 index 0000000000..fe91ab02a3 --- /dev/null +++ b/Task/Rename-a-file/Mercury/rename-a-file.mercury @@ -0,0 +1,34 @@ +:- module rename_file. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module dir. + +main(!IO) :- + rename_file("input.txt", "output.txt", !IO), + rename_file("docs", "mydocs", !IO), + rename_file("/input.txt", "/output.txt", !IO), + rename_file("/docs", "/mydocs", !IO). + +:- pred rename_file(string::in, string::in, io::di, io::uo) is det. + +rename_file(OldName, NewName, !IO) :- + io.rename_file(OldName, NewName, Result, !IO), + ( + Result = ok + ; + Result = error(Error), + print_io_error(Error, !IO) + ). + +:- pred print_io_error(io.error::in, io::di, io::uo) is det. + +print_io_error(Error, !IO) :- + io.stderr_stream(Stderr, !IO), + io.write_string(Stderr, io.error_message(Error), !IO), + io.nl(Stderr, !IO), + io.set_exit_status(1, !IO). diff --git a/Task/Rename-a-file/Objeck/rename-a-file.objeck b/Task/Rename-a-file/Objeck/rename-a-file.objeck index 7b4b1bc99b..7d8057825d 100644 --- a/Task/Rename-a-file/Objeck/rename-a-file.objeck +++ b/Task/Rename-a-file/Objeck/rename-a-file.objeck @@ -1,7 +1,7 @@ use IO; bundle Default { class FileExample { - function : Main(args : String[]) ~ Nil { + function : Main(args : String[]) ~ Nil { File->Rename("input.txt", "output.txt"); File->Rename("docs", "mydocs"); File->Rename("/input.txt", "/output.txt"); diff --git a/Task/Rename-a-file/TXR/rename-a-file.txr b/Task/Rename-a-file/TXR/rename-a-file.txr new file mode 100644 index 0000000000..7a2252dc8a --- /dev/null +++ b/Task/Rename-a-file/TXR/rename-a-file.txr @@ -0,0 +1,5 @@ +@(do (rename-path "input.txt" "output.txt") + ;; Windows (MinGW based port) + (rename-path "C:\\input.txt" "C:\\output.txt") + ;; Unix; Windows (Cygwin port) + (rename-path "/input.txt" "/output.txt")) diff --git a/Task/Rendezvous/D/rendezvous.d b/Task/Rendezvous/D/rendezvous.d new file mode 100644 index 0000000000..19280b9e8b --- /dev/null +++ b/Task/Rendezvous/D/rendezvous.d @@ -0,0 +1,105 @@ +import std.stdio, std.array, std.datetime, std.exception, + std.concurrency, core.thread, core.atomic; + +final class OutOfInk: Exception { + this() pure nothrow { + super("Out of ink."); + } +} + +struct Printer { + string id; + size_t ink; + + void printIt(in string line) { + enforce(ink != 0, new OutOfInk); + writefln("%s: %s", id, line); + ink--; + } +} + +/// Treats shared lvalue as if it is thread-local. +ref assumeThreadLocal(T)(ref shared T what) pure nothrow { + return *cast(T*)&what; +} + +struct RendezvousPrinter { + Printer[] printers; + + void print(const(string)[] lines) shared { + OutOfInk savedException; + + // Lightweight mutual exclusion + // using shared atomic bool. + shared static bool mutex; + + void lock() { + while (!cas(&mutex, false, true)) + Thread.sleep(1.hnsecs); + } + + void unlock() nothrow { + assert(mutex.atomicLoad!(MemoryOrder.acq)); + mutex.atomicStore!(MemoryOrder.rel)(false); + } + + while (!lines.empty) { + if (printers.empty) { + // No more printers to try. + assert(savedException !is null); + throw savedException; + } + + try { + { + lock; + scope(exit) unlock; + printers.front.assumeThreadLocal + .printIt(lines.front); + } + lines.popFront; + + // Increase the chance of interleaved output. + Thread.sleep(10.msecs); + } catch (OutOfInk exc) { + savedException = exc; + + // Switch to the next printer. + lock; + scope(exit) unlock; + printers.assumeThreadLocal.popFront; + } + } + } +} + +void humptyDumptyTask(shared ref RendezvousPrinter rendezvous) { + const humptyDumpty = [ + "Humpty Dumpty sat on a wall.", + "Humpty Dumpty had a great fall.", + "All the king's horses and all the king's men,", + "Couldn't put Humpty together again."]; + + rendezvous.print(humptyDumpty); +} + +void motherGooseTask(shared ref RendezvousPrinter rendezvous) { + const motherGoose = ["Old Mother Goose,", + "When she wanted to wander,", + "Would ride through the air,", + "On a very fine gander.", + "Jack's mother came in,", + "And caught the goose soon,", + "And mounting its back,", + "Flew up to the moon."]; + + rendezvous.print(motherGoose); +} + +void main() { + shared rendezvous = RendezvousPrinter + ([Printer("main", 5), Printer("reserve", 5)]); + + spawn(&humptyDumptyTask, rendezvous); + spawn(&motherGooseTask, rendezvous); +} diff --git a/Task/Repeat-a-string/C/repeat-a-string-1.c b/Task/Repeat-a-string/C/repeat-a-string-1.c index 48da2484d6..52e4cd2359 100644 --- a/Task/Repeat-a-string/C/repeat-a-string-1.c +++ b/Task/Repeat-a-string/C/repeat-a-string-1.c @@ -15,7 +15,7 @@ char * string_repeat( int n, const char * s ) { } int main() { - char * result = string_repeat(5, "ha") + char * result = string_repeat(5, "ha"); puts(result); free(result); return 0; diff --git a/Task/Repeat-a-string/Ruby/repeat-a-string.rb b/Task/Repeat-a-string/Ruby/repeat-a-string.rb new file mode 100644 index 0000000000..0cf142bf02 --- /dev/null +++ b/Task/Repeat-a-string/Ruby/repeat-a-string.rb @@ -0,0 +1 @@ +"ha" * 5 # ==> "hahahahaha" diff --git a/Task/Respond-to-an-unknown-method-call/AutoHotkey/respond-to-an-unknown-method-call.ahk b/Task/Respond-to-an-unknown-method-call/AutoHotkey/respond-to-an-unknown-method-call.ahk new file mode 100644 index 0000000000..60b1b359a2 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/AutoHotkey/respond-to-an-unknown-method-call.ahk @@ -0,0 +1,27 @@ +class example +{ + foo() + { + Msgbox Called example.foo() + } + + __Call(method, params*) + { + funcRef := Func(funcName := this.__class "." method) + if !IsObject(funcRef) + { + str := "Called undefined method " funcName "() with these parameters:" + for k,v in params + str .= "`n" v + Msgbox %str% + } + else + { + return funcRef.(this, params*) + } + } +} + +ex := new example +ex.foo() +ex.bar(1,2) diff --git a/Task/Respond-to-an-unknown-method-call/Object-Pascal/respond-to-an-unknown-method-call.object b/Task/Respond-to-an-unknown-method-call/Object-Pascal/respond-to-an-unknown-method-call.object new file mode 100644 index 0000000000..cfed5539f1 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Object-Pascal/respond-to-an-unknown-method-call.object @@ -0,0 +1,18 @@ +type + Tanimal = class + public + procedure bark(); virtual; abstract; + end; + +implementation + +var + animal: Tanimal; + +initialization + + animal := Tanimal.Create; + animal.bark(); // abstract method call exception at runtime here + animal.Free; + +end. diff --git a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call.m b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call.m new file mode 100644 index 0000000000..5d95b6135f --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call.m @@ -0,0 +1,62 @@ +#include + +// The methods need to be declared somewhere +@interface Dummy : NSObject +- (void)grill; +- (void)ding:(NSString *)s; +@end + +@interface Example : NSObject +- (void)foo; +- (void)bar; +@end + +@implementation Example +- (void)foo { + NSLog(@"this is foo"); +} + +- (void)bar { + NSLog(@"this is bar"); +} + +- (void)forwardInvocation:(NSInvocation *)inv { + NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); + NSUInteger n = [[inv methodSignature] numberOfArguments]; + for (NSUInteger i = 0; i < n-2; i++) { // First two arguments are the object and selector. + id __unsafe_unretained arg; // We assume that all arguments are objects. + // getArguments: is type-agnostic and does not perform memory management, + // therefore we must pass it a pointer to an unretained type + [inv getArgument:&arg atIndex:i+2]; + NSLog(@"argument #%lu: %@", i, arg); + } +} + +// forwardInvocation: does not work without methodSignatureForSelector: +// The runtime uses the signature returned here to construct the invocation. +- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { + int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; + // we assume that all arguments are objects + // The type encoding is "v@:@@@...", where "v" is the return type, void + // "@" is the receiver, object type; ":" is the selector of the current method; + // and each "@" after corresponds to an object argument + return [NSMethodSignature signatureWithObjCTypes: + [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; +} +@end + +int main() +{ + @autoreleasepool { + + id example = [[Example alloc] init]; + + [example foo]; // prints "this is foo" + [example bar]; // prints "this is bar" + [example grill]; // prints "tried to handle unknown method grill" + [example ding:@"dong"]; // prints "tried to handle unknown method ding:" + // prints "argument #0: dong" + + } + return 0; +} diff --git a/Task/Return-multiple-values/Mercury/return-multiple-values.mercury b/Task/Return-multiple-values/Mercury/return-multiple-values-1.mercury similarity index 96% rename from Task/Return-multiple-values/Mercury/return-multiple-values.mercury rename to Task/Return-multiple-values/Mercury/return-multiple-values-1.mercury index 0c9f40956a..6e54978ef5 100644 --- a/Task/Return-multiple-values/Mercury/return-multiple-values.mercury +++ b/Task/Return-multiple-values/Mercury/return-multiple-values-1.mercury @@ -24,3 +24,5 @@ main(!IO) :- addsub(X, Y, S, D) :- S = X + Y, D = X - Y. + +:- end_module addsub. diff --git a/Task/Return-multiple-values/Mercury/return-multiple-values-2.mercury b/Task/Return-multiple-values/Mercury/return-multiple-values-2.mercury new file mode 100644 index 0000000000..b22eb82956 --- /dev/null +++ b/Task/Return-multiple-values/Mercury/return-multiple-values-2.mercury @@ -0,0 +1,2 @@ +:- func addsub(int, int) = {int, int}. +addsub(X, Y) = { X + Y, X - Y }. diff --git a/Task/Return-multiple-values/Mercury/return-multiple-values-3.mercury b/Task/Return-multiple-values/Mercury/return-multiple-values-3.mercury new file mode 100644 index 0000000000..4d50c089e7 --- /dev/null +++ b/Task/Return-multiple-values/Mercury/return-multiple-values-3.mercury @@ -0,0 +1 @@ + {S, D} = addsub(X, Y), diff --git a/Task/Return-multiple-values/Mercury/return-multiple-values-4.mercury b/Task/Return-multiple-values/Mercury/return-multiple-values-4.mercury new file mode 100644 index 0000000000..3c1b83231b --- /dev/null +++ b/Task/Return-multiple-values/Mercury/return-multiple-values-4.mercury @@ -0,0 +1,28 @@ +:- module addsub. + +:- interface. +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module int, list, string. + +:- type my_result ---> twin(int, int). + +main(!IO) :- + command_line_arguments(Args, !IO), + filter_map(to_int, Args, CleanArgs), + (length(CleanArgs, 2) -> + X = det_index1(CleanArgs,1), + Y = det_index1(CleanArgs,2), + twin(S, D) = addsub(X, Y), + format("%d + %d = %d\n%d - %d = %d\n", + [i(X), i(Y), i(S), i(X), i(Y), i(D)], !IO) + ; + write_string("Please pass two integers on the command line.\n", !IO) + ). + +:- func addsub(int, int) = my_result. +addsub(X, Y) = twin(X + Y, X - Y). + +:- end_module addsub. diff --git a/Task/Reverse-a-string/D/reverse-a-string.d b/Task/Reverse-a-string/D/reverse-a-string.d index 5fbe51b474..f9e2403f83 100644 --- a/Task/Reverse-a-string/D/reverse-a-string.d +++ b/Task/Reverse-a-string/D/reverse-a-string.d @@ -1,12 +1,16 @@ void main() { - import std.stdio, std.range, std.conv; + import std.range, std.conv; - string s1 = "hello"; // UTF-8 - assert(s1.retro.text == "olleh"); + string s1 = "hello"; // UTF-8 + assert(s1.retro.text == "olleh"); - wstring s2 = "hello"w; // UTF-16 - assert(s2.retro.wtext == "olleh"); + wstring s2 = "hello"w; // UTF-16 + assert(s2.retro.wtext == "olleh"w); - dstring s3 = "hello"d; // UTF-32 - assert(s3.retro.dtext == "olleh"); + dstring s3 = "hello"d; // UTF-32 + assert(s3.retro.dtext == "olleh"d); + + // without using std.range: + dstring s4 = "hello"d; + assert(s4.dup.reverse == "olleh"d); // simple but inefficient (copies first, then reverses) } diff --git a/Task/Reverse-a-string/Objective-C/reverse-a-string-2.m b/Task/Reverse-a-string/Objective-C/reverse-a-string-2.m index 245617956c..a1029acef1 100644 --- a/Task/Reverse-a-string/Objective-C/reverse-a-string-2.m +++ b/Task/Reverse-a-string/Objective-C/reverse-a-string-2.m @@ -1,11 +1,11 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSString *test = [@"!A string to be reverted!" reverseString]; + NSString *test = [@"!A string to be reverted!" reverseString]; - NSLog(@"%@", test); + NSLog(@"%@", test); - [pool release]; + } return 0; } diff --git a/Task/Reverse-a-string/Objective-C/reverse-a-string-4.m b/Task/Reverse-a-string/Objective-C/reverse-a-string-4.m index c114a18b02..601e120baf 100644 --- a/Task/Reverse-a-string/Objective-C/reverse-a-string-4.m +++ b/Task/Reverse-a-string/Objective-C/reverse-a-string-4.m @@ -1,11 +1,11 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSString *test = [@"as⃝df̅" reverseString]; + NSString *test = [@"as⃝df̅" reverseString]; - NSLog(@"%@", test); + NSLog(@"%@", test); - [pool release]; + } return 0; } diff --git a/Task/Reverse-a-string/Rust/reverse-a-string-1.rust b/Task/Reverse-a-string/Rust/reverse-a-string-1.rust index 2a704b8bd6..26191bb3e1 100644 --- a/Task/Reverse-a-string/Rust/reverse-a-string-1.rust +++ b/Task/Reverse-a-string/Rust/reverse-a-string-1.rust @@ -1,3 +1,3 @@ -// rust 0.8 +// rust 0.9 let s = "一二三四五六七八九十"; -let reversed:~str = s.rev_iter().collect(); +let reversed:~str = s.chars_rev().collect(); diff --git a/Task/Reverse-a-string/Rust/reverse-a-string-2.rust b/Task/Reverse-a-string/Rust/reverse-a-string-2.rust index ae43daeac1..7393f0851e 100644 --- a/Task/Reverse-a-string/Rust/reverse-a-string-2.rust +++ b/Task/Reverse-a-string/Rust/reverse-a-string-2.rust @@ -1 +1 @@ -let reversed:~str = "一二三四五六七八九十".rev_iter().collect(); +let reversed:~str = "一二三四五六七八九十".chars_rev().collect(); diff --git a/Task/Rock-paper-scissors/AutoHotkey/rock-paper-scissors.ahk b/Task/Rock-paper-scissors/AutoHotkey/rock-paper-scissors.ahk index 7c170cfa7b..d0aae92e4e 100644 --- a/Task/Rock-paper-scissors/AutoHotkey/rock-paper-scissors.ahk +++ b/Task/Rock-paper-scissors/AutoHotkey/rock-paper-scissors.ahk @@ -1,4 +1,3 @@ -#Warn DllCall("AllocConsole") Write("Welcome to Rock-Paper-Scissors`nMake a choice: ") diff --git a/Task/Rock-paper-scissors/C-sharp/rock-paper-scissors.cs b/Task/Rock-paper-scissors/C-sharp/rock-paper-scissors.cs new file mode 100644 index 0000000000..d71182ca91 --- /dev/null +++ b/Task/Rock-paper-scissors/C-sharp/rock-paper-scissors.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RockPaperScissors +{ + class Program + { + static void Main(string[] args) + { + // There is no limit on the amount of weapons supported by RPSGame. Matchups are calculated depending on the order. + var rps = new RPSGame("scissors", "paper", "rock", "lizard", "spock"); + + int wins = 0, losses = 0, draws = 0; + + while (true) + { + Console.WriteLine("Make your move: " + string.Join(", ", rps.Weapons) + ", quit"); + + string weapon = Console.ReadLine().Trim().ToLower(); + + if (weapon == "quit") + break; + + if (!rps.Weapons.Contains(weapon)) + { + Console.WriteLine("Invalid weapon!"); + continue; + } + + int result = rps.Next(weapon); + + Console.WriteLine("You chose {0} and your opponent chose {1}!", weapon, rps.LastAIWeapon); + + switch (result) + { + case 1: Console.WriteLine("{0} pwns {1}. You're a winner!", weapon, rps.LastAIWeapon); + wins++; + break; + case 0: Console.WriteLine("Draw!"); + draws++; + break; + case -1: Console.WriteLine("{0} pwns {1}. You're a loser!", rps.LastAIWeapon, weapon); + losses++; + break; + } + + Console.WriteLine(); + } + + Console.WriteLine("\nPlayer Statistics\nWins: {0}\nLosses: {1}\nDraws: {2}", wins, losses, draws); + } + + class RPSGame + { + public RPSGame(params string[] weapons) + { + Weapons = weapons; + + // Creates a new AI opponent, and gives it the list of weapons. + _rpsAI = new RPSAI(weapons); + } + + // Play next turn. + public int Next(string weapon) + { + string aiWeapon = _rpsAI.NextMove(); // Gets the AI opponent's next move. + LastAIWeapon = aiWeapon; // Saves the AI opponent's move in a property so the player can see it. + + _rpsAI.AddPlayerMove(weapon); // Let the AI know which weapon the player chose, for future predictions. + return GetWinner(Weapons, weapon, aiWeapon); // Returns -1 if AI win, 0 if draw, and 1 if player win. + } + + // Returns matchup winner. + public static int GetWinner(string[] weapons, string weapon1, string weapon2) + { + if (weapon1 == weapon2) + return 0; // If weapons are the same, return 0 for draw. + + if (GetVictories(weapons, weapon1).Contains(weapon2)) + return 1; // Returns 1 for weapon1 win. + else if (GetVictories(weapons, weapon2).Contains(weapon1)) + return -1; // Returns -1 for weapon2 win. + + throw new Exception("No winner found."); + } + + /* + * Return weapons that the provided weapon beats. + * The are calculated in the following way: + * If the index of the weapon is even, then all even indices less than it, + * and all odd indices greater than it, are victories. + * One exception is if it is an odd index, and also the last index in the set, + * then the first index in the set is a victory. + */ + public static IEnumerable GetVictories(string[] weapons, string weapon) + { + // Gets index of weapon. + int index = Array.IndexOf(weapons, weapon); + + // If weapon is odd and the final index in the set, then return the first item in the set as a victory. + if (index % 2 != 0 && index == weapons.Length - 1) + yield return weapons[0]; + + for (int i = index - 2; i >= 0; i -= 2) + yield return weapons[i]; + + for (int i = index + 1; i < weapons.Length; i += 2) + yield return weapons[i]; + } + + public string LastAIWeapon + { + private set; + get; + } + + public readonly string[] Weapons; + private RPSAI _rpsAI; + + class RPSAI + { + public RPSAI(params string[] weapons) + { + _weapons = weapons; + _weaponProbability = new Dictionary(); + + // The AI sets the probability for each weapon to be chosen as 1. + foreach (string weapon in weapons) + _weaponProbability.Add(weapon, 1); + + _random = new Random(); + } + + // Increases probability of selecting each weapon that beats the provided move. + public void AddPlayerMove(string weapon) + { + int index = Array.IndexOf(_weapons, weapon); + + foreach (string winWeapon in _weapons.Except(GetVictories(_weapons, weapon))) + if (winWeapon != weapon) + _weaponProbability[winWeapon]++; + } + + // Gets the AI's next move. + public string NextMove() + { + double r = _random.NextDouble(); + + double divisor = _weaponProbability.Values.Sum(); + + var weightedWeaponRanges = new Dictionary(); + + double currentPos = 0.0; + + // Maps probabilities to ranges between 0.0 and 1.0. Returns weighted random weapon. + foreach (var weapon in _weaponProbability) + { + double weightedRange = weapon.Value / divisor; + if (r <= currentPos + (weapon.Value / divisor)) + return weapon.Key; + currentPos += weightedRange; + } + + throw new Exception("Error calculating move."); + } + + Random _random; + private readonly string[] _weapons; + private Dictionary _weaponProbability; + } + } + } +} diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d b/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d index 74b4929c8a..a8c893d253 100644 --- a/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d +++ b/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d @@ -6,7 +6,7 @@ immutable order = [EnumMembers!Choice]; uint[order.length] choiceFrequency; -Choice whatBeats(in Choice ch) pure /*nothrow*/ { +Choice whatBeats(in Choice ch) pure nothrow { return order[(order.countUntil(ch) + 1) % $]; } @@ -22,7 +22,7 @@ pure /*nothrow*/ { } Choice getRandomChoice() /*nothrow*/ { - if (choiceFrequency[].reduce!q{a + b} == 0) + if (choiceFrequency[].sum == 0) return uniform!Choice; return order[choiceFrequency.dice].whatBeats; } diff --git a/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d b/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d index dd41e94c3e..b9293e3b2b 100644 --- a/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d +++ b/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d @@ -1,9 +1,8 @@ -import std.regex, std.algorithm, std.functional; - -alias sum = curry!(reduce!q{a + b}, 0); +import std.regex, std.algorithm; immutable int[string] w2s; -nothrow static this() { + +pure nothrow static this() { w2s = ["IX": 9, "C": 100, "D": 500, "CM": 900, "I": 1, "XC": 90, "M": 1000, "L": 50, "CD": 400, "XL": 40, "V": 5, "X": 10, "IV": 4]; diff --git a/Task/Roman-numerals-Decode/Mercury/roman-numerals-decode.mercury b/Task/Roman-numerals-Decode/Mercury/roman-numerals-decode.mercury new file mode 100644 index 0000000000..44943888cf --- /dev/null +++ b/Task/Roman-numerals-Decode/Mercury/roman-numerals-decode.mercury @@ -0,0 +1,49 @@ +:- module test_roman. + +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module char. +:- import_module exception. +:- import_module int. +:- import_module list. +:- import_module string. + +:- type conversion_error ---> not_a_roman_number. + +:- func build_int(list(char), int, int) = int. +:- func from_roman(string) = int. +:- pred roman_to_int(char::in, int::out) is semidet. + +from_roman(Roman) = Decimal :- + List = reverse(to_char_list(Roman)), + Decimal = build_int(List, 0, 0). + +build_int([], LastValue, Accumulator) = LastValue + Accumulator. +build_int([Digit|Rest], LastValue, Accumulator) = Sum :- + ( roman_to_int(Digit, Value) -> + ( Value < LastValue -> + Sum = build_int(Rest, Value, Accumulator - LastValue) + ; Sum = build_int(Rest, Value, Accumulator + LastValue) ) + ; throw(not_a_roman_number) ). + +roman_to_int('I', 1). +roman_to_int('V', 5). +roman_to_int('X', 10). +roman_to_int('L', 50). +roman_to_int('C', 100). +roman_to_int('D', 500). +roman_to_int('M', 1000). + +main(!IO) :- + command_line_arguments(Args, !IO), + foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :- + format("%s => %d\n", [s(Arg), i(from_roman(Arg))], !IO)), + Args, !IO). + +:- end_module test_roman. diff --git a/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust b/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust new file mode 100644 index 0000000000..2c89fe68a8 --- /dev/null +++ b/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust @@ -0,0 +1,37 @@ +struct RomanNumeral { + symbol: &'static str, + value: uint +} + +static NUMERALS: [RomanNumeral, ..13] = [ + RomanNumeral {symbol: "M", value: 1000}, + RomanNumeral {symbol: "CM", value: 900}, + RomanNumeral {symbol: "D", value: 500}, + RomanNumeral {symbol: "CD", value: 400}, + RomanNumeral {symbol: "C", value: 100}, + RomanNumeral {symbol: "XC", value: 90}, + RomanNumeral {symbol: "L", value: 50}, + RomanNumeral {symbol: "XL", value: 40}, + RomanNumeral {symbol: "X", value: 10}, + RomanNumeral {symbol: "IX", value: 9}, + RomanNumeral {symbol: "V", value: 5}, + RomanNumeral {symbol: "IV", value: 4}, + RomanNumeral {symbol: "I", value: 1} +]; + +fn to_hindu(roman: &str) -> uint { + for numeral in NUMERALS.iter() { + if roman.starts_with(numeral.symbol) { + return numeral.value + to_hindu(roman.slice_from(numeral.symbol.len())); + } + } + + return 0; +} + +fn main() { + let roms = ["MMXIV", "MCMXCIX", "XXV", "MDCLXVI", "MMMDCCCLXXXVIII"]; + for r in roms.iter() { + println!("{:s} = {:u}", *r, to_hindu(*r)); + } +} diff --git a/Task/Roman-numerals-Encode/C/roman-numerals-encode-1.c b/Task/Roman-numerals-Encode/C/roman-numerals-encode-1.c index 4b2603f4d1..ff5ecf72f3 100644 --- a/Task/Roman-numerals-Encode/C/roman-numerals-encode-1.c +++ b/Task/Roman-numerals-Encode/C/roman-numerals-encode-1.c @@ -13,7 +13,7 @@ void roman(char *s, unsigned int n) { if (n == 0) { - fputs(stderr, "Roman numeral for zero requested."); + fputs("Roman numeral for zero requested.", stderr); exit(EXIT_FAILURE); } diff --git a/Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode.mumps b/Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode-1.mumps similarity index 100% rename from Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode.mumps rename to Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode-1.mumps diff --git a/Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode-2.mumps b/Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode-2.mumps new file mode 100644 index 0000000000..84f480417b --- /dev/null +++ b/Task/Roman-numerals-Encode/MUMPS/roman-numerals-encode-2.mumps @@ -0,0 +1,11 @@ +TOROMAN(n) + ;return empty string if input parameter 'n' is not in 1-3999 + Quit:(n'?1.4N)!(n'<4000)!'n "" + New r Set r="" + New p Set p=$Length(n) + New j,x + For j=1:1:p Do + . Set x=$Piece("~I~II~III~IV~V~VI~VII~VIII~IX","~",$Extract(n,j)+1) + . Set x=$Translate(x,"IVX",$Piece("IVX~XLC~CDM~M","~",p-j+1)) + . Set r=r_x + Quit r diff --git a/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust b/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust new file mode 100644 index 0000000000..c174b0a149 --- /dev/null +++ b/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust @@ -0,0 +1,37 @@ +struct RomanNumeral { + symbol: &'static str, + value: uint +} + +static NUMERALS: [RomanNumeral, ..13] = [ + RomanNumeral {symbol: "M", value: 1000}, + RomanNumeral {symbol: "CM", value: 900}, + RomanNumeral {symbol: "D", value: 500}, + RomanNumeral {symbol: "CD", value: 400}, + RomanNumeral {symbol: "C", value: 100}, + RomanNumeral {symbol: "XC", value: 90}, + RomanNumeral {symbol: "L", value: 50}, + RomanNumeral {symbol: "XL", value: 40}, + RomanNumeral {symbol: "X", value: 10}, + RomanNumeral {symbol: "IX", value: 9}, + RomanNumeral {symbol: "V", value: 5}, + RomanNumeral {symbol: "IV", value: 4}, + RomanNumeral {symbol: "I", value: 1} +]; + +fn to_roman(num: uint) -> ~str { + for numeral in NUMERALS.iter() { + if num >= numeral.value { + return numeral.symbol + to_roman(num - numeral.value); + } + } + + return ~""; +} + +fn main() { + let nums = [2014, 1999, 25, 1666, 3888]; + for n in nums.iter() { + println!("{:u} = {:s}", *n, to_roman(*n)); + } +} diff --git a/Task/Roots-of-a-function/D/roots-of-a-function.d b/Task/Roots-of-a-function/D/roots-of-a-function.d index 154bac805b..ac850b1ac9 100644 --- a/Task/Roots-of-a-function/D/roots-of-a-function.d +++ b/Task/Roots-of-a-function/D/roots-of-a-function.d @@ -4,12 +4,11 @@ bool nearZero(T)(in T a, in T b = T.epsilon * 4) pure nothrow { return abs(a) <= b; } -T[] findRoot(T)(immutable T function(in T) pure nothrow f, - in T start, in T end, in T step=cast(T)0.001L, - T tolerance = cast(T)1e-4L) { - if (nearZero(step)) +T[] findRoot(T)(immutable T function(in T) pure nothrow fi, + in T start, in T end, in T step=T(0.001L), + T tolerance = T(1e-4L)) { + if (step.nearZero) writefln("WARNING: step size may be too small."); - immutable fi = f; /// Search root by simple bisection. T searchRoot(T a, T b) pure nothrow { @@ -18,38 +17,40 @@ T[] findRoot(T)(immutable T function(in T) pure nothrow f, T gap = b - a; while (!nearZero(gap) && limit--) { - if (nearZero(fi(a))) return a; - if (nearZero(fi(b))) return b; + if (fi(a).nearZero) + return a; + if (fi(b).nearZero) + return b; root = (b + a) / 2.0L; - if (nearZero(fi(root))) return root; - if (fi(a) * fi(root) < 0) - b = root; - else - a = root; + if (fi(root).nearZero) + return root; + ((fi(a) * fi(root) < 0) ? b : a) = root; gap = b - a; } return root; } - immutable dir = cast(T)(end > start ? 1.0 : -1.0); + immutable dir = T(end > start ? 1.0 : -1.0); immutable step2 = (end > start) ? abs(step) : -abs(step); T[T] result; for (T x = start; (x * dir) <= (end * dir); x += step2) - if (f(x) * f(x + step2) <= 0) { + if (fi(x) * fi(x + step2) <= 0) { immutable T r = searchRoot(x, x + step2); - result[r] = f(r); + result[r] = fi(r); } - return result.keys.sort().release(); + return result.keys.sort().release; } void report(T)(in T[] r, immutable T function(in T) pure f, - in T tolerance = cast(T)1e-4L) { + in T tolerance = T(1e-4L)) { if (r.length) { writefln("Root found (tolerance = %1.4g):", tolerance); - foreach (x; r) { + + foreach (const x; r) { immutable T y = f(x); + if (nearZero(y)) writefln("... EXACTLY at %+1.20f, f(x) = %+1.4g",x,y); else if (nearZero(y, tolerance)) @@ -62,10 +63,10 @@ void report(T)(in T[] r, immutable T function(in T) pure f, writefln("No root found."); } -real f(in real x) pure nothrow { - return x ^^ 3 - (3 * x ^^ 2) + 2 * x; -} - void main() { + static real f(in real x) pure nothrow { + return x ^^ 3 - (3 * x ^^ 2) + 2 * x; + } + findRoot(&f, -1.0L, 3.0L, 0.001L).report(&f); } diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj index 19a7c263ea..972ea34d90 100644 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj @@ -1,5 +1,11 @@ -; v1.1; number of solutions -(defn quad_sol [a b c] - (def d (- (* b b) (* 4 a c)) ) - (if (< d 0) 0 - (if (> d 0) 2 1)) ) +(defn quadratic + "Compute the roots of a quadratic in the form ax^2 + bx + c = 1. + Returns any of nil, a float, or a vector." + [a b c] + (let [sq-d (Math/sqrt (- (* b b) (* 4 a c))) + f #(/ (% b sq-d) (* 2 a))] + (cond + (neg? sq-d) nil + (zero? sq-d) (f +) + (pos? sq-d) [(f +) (f -)] + :else nil))) ; maybe our number ended up as NaN diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj index 72280618c8..8ff7eb4a0b 100644 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj @@ -1,7 +1,6 @@ -; x = (b +- sqrt(b ^ 2 - 4 * a * c)) / (2 * a) -; local -(defn quad_func_sign [a b d sgn] - (/ (if (< sgn 0.0) - (- b (Math/sqrt d)) - (+ b (Math/sqrt d)) ) - (* 2.0 a) )) +user=> (quadratic 1.0 1.0 1.0) +nil +user=> (quadratic 1.0 2.0 1.0) +1.0 +user=> (quadratic 1.0 3.0 1.0) +[2.618033988749895 0.3819660112501051] diff --git a/Task/Roots-of-a-quadratic-function/Maple/roots-of-a-quadratic-function.maple b/Task/Roots-of-a-quadratic-function/Maple/roots-of-a-quadratic-function.maple new file mode 100644 index 0000000000..a7a3a1d16a --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Maple/roots-of-a-quadratic-function.maple @@ -0,0 +1,5 @@ +solve(a*x^2+b*x+c,x); + +solve(1.0*x^2-10.0^9*x+1.0,x,explicit,allsolutions); + +fsolve(x^2-10^9*x+1,x,complex); diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION index ac484bda6e..8e3b0c36aa 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION @@ -1,50 +1,50 @@ Sort most popular programming languages based in number of members in Rosetta Code categories
(from http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000) -Sample output on January 15 2014: +Sample output on March 30 2014: -
  1. 772 - Tcl
-  2. 733 - Racket
-  3. 718 - Python
-  4. 685 - C
-  5. 657 - Perl 6
-  6. 654 - J
-  7. 645 - D
-  8. 643 - Ruby
-  9. 636 - PicoLisp
- 10. 624 - Go
- 11. 610 - Perl
- 12. 579 - REXX
- 13. 578 - Ada
- 14. 567 - Mathematica
- 15. 567 - Haskell
- 16. 532 - Unicon
- 17. 526 - Java
- 18. 522 - BBC BASIC
- 19. 489 - OCaml
- 20. 487 - Icon
- 21. 477 - C++
- 22. 470 - PureBasic
- 23. 448 - Common Lisp
- 24. 439 - Erlang
- 25. 439 - C sharp
- 26. 437 - AutoHotkey
- 27. 406 - Scala
- 28. 382 - JavaScript
- 29. 375 - Clojure
- 30. 356 - Seed7
- 31. 342 - Lua
- 32. 339 - R
- 33. 337 - Groovy
- 34. 334 - PHP
- 35. 333 - F Sharp
- 36. 329 - Forth
- 37. 328 - ALGOL 68
- 38. 323 - Fortran
- 39. 312 - Pascal
+
  1. 797 - Tcl
+  2. 756 - Racket
+  3. 750 - Python
+  4. 719 - C
+  5. 692 - Perl 6
+  6. 678 - D
+  7. 677 - J
+  8. 668 - Ruby
+  9. 638 - Go
+ 10. 636 - PicoLisp
+ 11. 630 - Perl
+ 12. 615 - REXX
+ 13. 585 - Ada
+ 14. 578 - Haskell
+ 15. 567 - Mathematica
+ 16. 561 - AutoHotkey
+ 17. 541 - Unicon
+ 18. 539 - Java
+ 19. 525 - BBC BASIC
+ 20. 495 - Icon
+ 21. 492 - OCaml
+ 22. 487 - C++
+ 23. 473 - Common Lisp
+ 24. 469 - PureBasic
+ 25. 446 - C sharp
+ 26. 444 - Erlang
+ 27. 411 - Scala
+ 28. 387 - JavaScript
+ 29. 385 - Clojure
+ 30. 359 - Seed7
+ 31. 347 - Lua
+ 32. 341 - Groovy
+ 33. 340 - R
+ 34. 340 - F Sharp
+ 35. 337 - Forth
+ 36. 335 - PHP
+ 37. 329 - ALGOL 68
+ 38. 328 - Fortran
+ 39. 319 - Pascal
  40. 307 - Liberty BASIC
 ...
-A complete ranked listing of all '''505''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. +A complete ranked listing of all '''514''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. Filtering wrong results is optional. You can check against [[Special:MostLinkedCategories]] diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx b/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx index ccb563d7ef..4e3240ecf5 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx @@ -69,8 +69,9 @@ old.1='╬£C++' ; new.1= "µC++" /*Unicode ╬£C++ ──►ASCII-8: old.2='UC++' ; new.2= "µC++" /*old UC++ ──►ASCII-8: µC++ */ old.3='╨£╨Ü-' ; new.3= "MK-" /*Unicode ╨£╨Ü- ──►ASCII-8: MK- */ old.4='D├⌐j├á' ; new.4= 'Déjá' /*Unicode ├⌐j├á ──►ASCII-8: Déjá */ -old.5='Cach├⌐' ; new.5= 'Caché' /*Unicode ach├⌐ ──►ASCII-8: Caché*/ -old.6='??-61/52' ; new.6= 'MK-61/52' /*somewhere a mistranslated: MK- */ +old.5='D├⌐j├á' ; new.4= 'Dëjá' /*Unicode ├½j├á ──►ASCII-8: Dëjá */ +old.6='Cach├⌐' ; new.5= 'Caché' /*Unicode ach├⌐ ──►ASCII-8: Caché*/ +old.7='??-61/52' ; new.6= 'MK-61/52' /*somewhere a mistranslated: MK- */ do recs=0 while lines(inFID)\==0 /*read a file, 1 line at a time.*/ $=translate(linein(inFID),,'9'x) /*handle any stray tab characters*/ diff --git a/Task/Rot-13/AutoHotkey/rot-13-4.ahk b/Task/Rot-13/AutoHotkey/rot-13-4.ahk new file mode 100644 index 0000000000..3b5dbef4ee --- /dev/null +++ b/Task/Rot-13/AutoHotkey/rot-13-4.ahk @@ -0,0 +1,9 @@ +Rot13(string) { + Output := "" + Loop, Parse, string + { + a := ~Asc(A_LoopField) + Output .= Chr(~a-1//(~(a|32)//13*2-11)*13) + } + return Output +} diff --git a/Task/Rot-13/Rust/rot-13.rust b/Task/Rot-13/Rust/rot-13.rust new file mode 100644 index 0000000000..44d4dfea16 --- /dev/null +++ b/Task/Rot-13/Rust/rot-13.rust @@ -0,0 +1,17 @@ +fn rot13 (string: ~str) -> ~str { + fn rot13u8 (c: u8) -> u8 { + match c { + 97..109 => c+13, + 65..77 => c+13, + 110..122 => c-13, + 78..90 => c-13, + _ => c + } + } + std::str::from_utf8_owned(string.as_bytes().map(|c| rot13u8(*c))).unwrap() +} + +fn main () { + let a = rot13(~"abc"); + assert_eq!(a, ~"nop"); +} diff --git a/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-1.txr b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-1.txr new file mode 100644 index 0000000000..d5ab5f9f72 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-1.txr @@ -0,0 +1,5 @@ +(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0) + (- (eval ^(let ((x ,x1)) ,code-fragment)) + (eval ^(let ((x ,x0)) ,code-fragment)))) + +(eval-subtract-for-two-values-of-x 1 2) ;; yields -4.67077427047161 diff --git a/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-2.txr b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-2.txr new file mode 100644 index 0000000000..3bf3f1a531 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-2.txr @@ -0,0 +1,7 @@ +(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0) + (let ((e1 (make-env (list (cons 'x x1)))) ;; create two environments stuffed with binding for x + (e0 (make-env (list (cons 'x x0))))) + (- (eval code-fragment e1) ;; pass these environment to eval + (eval code-fragment e0)))) + +(eval-subtract-for-two-values-of-x '(exp x) 1 2) diff --git a/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-3.txr b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-3.txr new file mode 100644 index 0000000000..1e19a21c21 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-3.txr @@ -0,0 +1,9 @@ +(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0) + (let ((e1 (make-env)) + (e0 (make-env))) + (env-vbind e1 'x x1) + (env-vbind e0 'x x0) + (- (eval code-fragment e1) + (eval code-fragment e0)))) + +(eval-subtract-for-two-values-of-x '(exp x) 1 2) diff --git a/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-4.txr b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-4.txr new file mode 100644 index 0000000000..618fe32548 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/TXR/runtime-evaluation-in-an-environment-4.txr @@ -0,0 +1,7 @@ +(defvar x) + +(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0) + (- (let ((x x1)) (eval code-fragment)) + (let ((x x0)) (eval code-fragment)))) + +(eval-subtract-for-two-values-of-x '(exp x) 1 2) diff --git a/Task/S-Expressions/AutoHotkey/s-expressions-1.ahk b/Task/S-Expressions/AutoHotkey/s-expressions-1.ahk new file mode 100644 index 0000000000..7d93bd5d6a --- /dev/null +++ b/Task/S-Expressions/AutoHotkey/s-expressions-1.ahk @@ -0,0 +1,16 @@ +S_Expressions(Str){ + Str := RegExReplace(Str, "s)(? " SEDOL(A_LoopField) "`n" +Msgbox %output% + +SEDOL(code) { + Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9 + If (StrLen(code) != 6) + Return "Invalid length." + StringCaseSense On + Loop, Parse, code + If A_LoopField is Number + check_digit += A_LoopField * weight%A_Index% + Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z + check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index% + Else + Return "Invalid character." + Return code . Mod(10-Mod(check_digit,10),10) +} diff --git a/Task/SEDOLs/AutoHotkey/sedols.ahk b/Task/SEDOLs/AutoHotkey/sedols-2.ahk similarity index 66% rename from Task/SEDOLs/AutoHotkey/sedols.ahk rename to Task/SEDOLs/AutoHotkey/sedols-2.ahk index deedca1445..9c480c7496 100644 --- a/Task/SEDOLs/AutoHotkey/sedols.ahk +++ b/Task/SEDOLs/AutoHotkey/sedols-2.ahk @@ -10,8 +10,8 @@ MsgBox % SEDOL("585284") ;5852842 MsgBox % SEDOL("B0YBKT") ;B0YBKT7 SEDOL(w) { - Static w1:=1,w2:=3,w3:=1,w4:=7,w5:=3,w6:=9 - Loop Parse, w - s += ((c:=Asc(A_LoopField))>=Asc("A") ? c-Asc("A")+10 : c-Asc("0")) * w%A_Index% - Return w mod(10-mod(s,10),10) + static weights := [1,3,1,7,3,9] + loop parse, w + s += ((c := Asc(A_LoopField)) >= 65 ? c - 65 + 10 : c - 48) * weights[A_Index] + return w Mod(10 - Mod(s, 10), 10) } diff --git a/Task/SHA-1/00DESCRIPTION b/Task/SHA-1/00DESCRIPTION index ceae5f0925..371d162e9d 100644 --- a/Task/SHA-1/00DESCRIPTION +++ b/Task/SHA-1/00DESCRIPTION @@ -1,6 +1,6 @@ '''SHA-1''' or '''SHA1''' is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. -A US government standard, [http://www.itl.nist.gov/fipspubs/fip180-1.htm FIPS 180-1], defines SHA-1. +A US government standard, [[SHA-1/FIPS-180-1|FIPS 180-1]], defines SHA-1. Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. diff --git a/Task/SHA-1/J/sha-1-1.j b/Task/SHA-1/J/sha-1-1.j new file mode 100644 index 0000000000..01f71a244f --- /dev/null +++ b/Task/SHA-1/J/sha-1-1.j @@ -0,0 +1,35 @@ +pad=: ,1,(0#~512 | [: - 65 + #),(64#2)#:# + +f=:4 :0 + 'B C D'=: _32 ]\ y + if. x < 20 do. + (B*C)+.D>B + elseif. x < 40 do. + B~:C~:D + elseif. x < 60 do. + (B*C)+.(B*D)+.C*D + elseif. x < 80 do. + B~:C~:D + end. +) + +K=: ((32#2) #: 16b5a827999 16b6ed9eba1 16b8f1bbcdc 16bca62c1d6) {~ <.@%&20 + +plus=:+&.((32#2)&#.) + +process=:3 :0 + H=. #: 16b67452301 16befcdab89 16b98badcfe 16b10325476 16bc3d2e1f0 + W=. (, [: , 1 |."#. _3 _8 _14 _16 ~:/@:{ ])^:64 y ]\~ _32 + 'A B C D E'=. H + for_t. i.80 do. + TEMP=. (5|.A) plus (t f B,C,D) plus E plus (W{~t) plus K t + E=. D + D=. C + C=. 30 |. B + B=. A + A=. TEMP + end. + ,H plus A,B,C,D,:E +) + +sha1=: _512 process\ pad diff --git a/Task/SHA-1/J/sha-1-2.j b/Task/SHA-1/J/sha-1-2.j new file mode 100644 index 0000000000..8d9e939b0a --- /dev/null +++ b/Task/SHA-1/J/sha-1-2.j @@ -0,0 +1,5 @@ + text2bits=: (8#2) ,@:#: a. i. ] + bits2hex=: '0123456789abcdef' {~ _4 #.\ , + + bits2hex sha1 text2bits 'Rosetta Code' +48c98f7e5a6e736d790ab740dfc3f51a61abe2b5 diff --git a/Task/SHA-1/J/sha-1-3.j b/Task/SHA-1/J/sha-1-3.j new file mode 100644 index 0000000000..efb47272df --- /dev/null +++ b/Task/SHA-1/J/sha-1-3.j @@ -0,0 +1,42 @@ +text2bits=: (8#2) ,@:#: a. i. ] +words2bits=: ,@:((32#2)&#:) + +pad=: _32 #.\ (, 1,(0#~512 | [: - 65 + #),(64#2)#:#) +lim32=: 2^32 +rot32=: (] lim32&|@* 2 ^ [) + ] <.@% 2 ^ 32- [ +and=: 17 b. +notimplies=: 18 b. +xor=: 22 b. +or=: 23 b. + +f=:4 :0 + 'B C D'=: y + if. x < 20 do. + (B and C) or D notimplies B + elseif. x < 40 do. + B xor C xor D + elseif. x < 60 do. + (B and C) or (B and D) or C and D + elseif. x < 80 do. + B xor C xor D + end. +) + +K=: 16b5a827999 16b6ed9eba1 16b8f1bbcdc 16bca62c1d6 {~ <.@%&20 + +process=:3 :0 + H=. 16b67452301 16befcdab89 16b98badcfe 16b10325476 16bc3d2e1f0 + W=. (, [: , 1 rot32 _3 _8 _14 _16 xor/@:{ ])^:64 y + 'A B C D E'=. H + for_t. i.80 do. + TEMP=. lim32|(5 rot32 A) + (t f B,C,D) + E + (W{~t) + K t + E=. D + D=. C + C=. 30 rot32 B + B=. A + A=. TEMP + end. + ,lim32|H + A,B,C,D,E +) + +sha1=: _16 process\ pad diff --git a/Task/SHA-1/J/sha-1-4.j b/Task/SHA-1/J/sha-1-4.j new file mode 100644 index 0000000000..7d4c645a0c --- /dev/null +++ b/Task/SHA-1/J/sha-1-4.j @@ -0,0 +1,8 @@ +words2hex=: '0123456789abcdef' {~ (8#16)&#: + + words2hex sha1 text2bits 'Rosetta Code' +48c98f7e +5a6e736d +790ab740 +dfc3f51a +61abe2b5 diff --git a/Task/SHA-1/Lua/sha-1.lua b/Task/SHA-1/Lua/sha-1.lua new file mode 100644 index 0000000000..aac860983e --- /dev/null +++ b/Task/SHA-1/Lua/sha-1.lua @@ -0,0 +1,7 @@ +#!/usr/bin/lua + +local sha1 = require "sha1" + +for i, str in ipairs{"Rosetta code", "Rosetta Code"} do + print(string.format("SHA-1(%q) = %s", str, sha1(str))) +end diff --git a/Task/SHA-1/Octave/sha-1.octave b/Task/SHA-1/Octave/sha-1.octave new file mode 100644 index 0000000000..71c26d4598 --- /dev/null +++ b/Task/SHA-1/Octave/sha-1.octave @@ -0,0 +1 @@ +sprintf("%02x", SHA1(+"Rosetta Code"(:))) diff --git a/Task/SHA-1/PowerShell/sha-1.psh b/Task/SHA-1/PowerShell/sha-1.psh new file mode 100644 index 0000000000..06414aeafc --- /dev/null +++ b/Task/SHA-1/PowerShell/sha-1.psh @@ -0,0 +1,11 @@ +Function Calculate-SHA1( $String ){ + $Enc = [system.Text.Encoding]::UTF8 + $Data = $enc.GetBytes($String) + + # Create a New SHA1 Crypto Provider + $Sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider + + # Now hash and display results + $Result = $sha.ComputeHash($Data) + [System.Convert]::ToBase64String($Result) +} diff --git a/Task/SHA-256/Common-Lisp/sha-256.lisp b/Task/SHA-256/Common-Lisp/sha-256.lisp new file mode 100644 index 0000000000..168c3370ae --- /dev/null +++ b/Task/SHA-256/Common-Lisp/sha-256.lisp @@ -0,0 +1,7 @@ +(ql:quickload 'ironclad) +(defun sha-256 (str) + (ironclad:byte-array-to-hex-string + (ironclad:digest-sequence :sha256 + (ironclad:ascii-string-to-byte-array str)))) + +(sha-256 "Rosetta code") diff --git a/Task/SHA-256/D/sha-256.d b/Task/SHA-256/D/sha-256.d new file mode 100644 index 0000000000..6988d93211 --- /dev/null +++ b/Task/SHA-256/D/sha-256.d @@ -0,0 +1,350 @@ +// Copyright (C) 2005, 2006 Free Software Foundation, Inc. GNU License. +// Translated to D language. Only lightly tested, not for serious use. + +import core.stdc.string: memcpy; +import core.bitop: bswap; + +struct SHA256 { + enum uint BLOCK_SIZE = 4096; + static assert(BLOCK_SIZE % 64 == 0, "Invalid BLOCK_SIZE."); + + uint[8] state; + uint[2] total; + uint bufLen; + union { + uint[32] buffer; + ubyte[buffer.sizeof] bufferB; + } + + alias TResult = ubyte[256 / 8]; + + version(WORDS_BIGENDIAN) { + static uint bswap(in uint n) pure nothrow { return n; } + } + + // Bytes used to pad the buffer to the next 64-byte boundary. + static immutable ubyte[64] fillBuf = [0x80, 0 /* , 0, 0, ... */]; + + + /** Initialize structure containing state of computation. + Takes a pointer to a 256 bit block of data (eight 32 bit ints) and + intializes it to the start constants of the SHA256 algorithm. This + must be called before using hash in the call to sha256_hash. */ + void init() pure nothrow { + state = [0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, + 0x510e527fU, 0x9b05688cU, 0x1f83d9abU, 0x5be0cd19U]; + total[] = 0; + bufLen = 0; + } + + + /** Starting with the result of former calls of this function (or + the initialization function) update the context for the next LEN + bytes starting at BUFFER. + It is not required that LEN is a multiple of 64. */ + void processBytes(in ubyte[] inBuffer) pure nothrow { + // When we already have some bits in our internal + // buffer concatenate both inputs first. + const(ubyte)* inBufferPtr = inBuffer.ptr; + auto len = inBuffer.length; + + if (bufLen != 0) { + immutable size_t left_over = bufLen; + immutable size_t add = (128 - left_over > len) ? + len : + 128 - left_over; + + memcpy(&bufferB[left_over], inBufferPtr, add); + bufLen += add; + + if (bufLen > 64) { + processBlock(bufferB[0 .. bufLen & ~63]); + + bufLen &= 63; + // The regions in the following copy operation + // cannot overlap. + memcpy(bufferB.ptr, + &bufferB[(left_over + add) & ~63], bufLen); + } + + inBufferPtr += add; + len -= add; + } + + // Process available complete blocks. + if (len >= 64) { + processBlock(inBufferPtr[0 .. len & ~63]); + inBufferPtr += (len & ~63); + len &= 63; + } + + // Move remaining bytes in internal buffer. + if (len > 0) { + size_t left_over = bufLen; + + memcpy(&bufferB[left_over], inBufferPtr, len); + left_over += len; + if (left_over >= 64) { + processBlock(bufferB[0 .. 64]); + left_over -= 64; + memcpy(bufferB.ptr, &bufferB[64], left_over); + } + bufLen = left_over; + } + } + + + /** Starting with the result of former calls of this function + (or the initialization function) update the context ctx for + the next len bytes starting at buffer. + It is necessary that len is a multiple of 64. */ + void processBlock(in ubyte[] inBuffer) + pure nothrow in { + assert(inBuffer.length % 64 == 0); + } body { + // Round functions. + static uint F1(in uint e, in uint f, in uint g) pure nothrow { + return g ^ (e & (f ^ g)); + } + + static uint F2(in uint a, in uint b, in uint c) pure nothrow { + return (a & b) | (c & (a | b)); + } + + immutable len = inBuffer.length; + auto words = cast(uint*)inBuffer.ptr; + immutable size_t nWords = len / uint.sizeof; + const uint* endp = words + nWords; + uint[16] x = void; + auto a = state[0]; + auto b = state[1]; + auto c = state[2]; + auto d = state[3]; + auto e = state[4]; + auto f = state[5]; + auto g = state[6]; + auto h = state[7]; + + // First increment the byte count. FIPS PUB 180-2 specifies the + // possible length of the file up to 2^64 bits. Here we only + // compute the number of bytes. Do a double word increment. + total[0] += len; + if (total[0] < len) + total[1]++; + + static uint rol(in uint x, in uint n) pure nothrow { + return (x << n) | (x >> (32 - n)); } + static uint S0(in uint x) pure nothrow { + return rol(x, 25) ^ rol(x, 14) ^ (x >> 3); } + static uint S1(in uint x) pure nothrow { + return rol(x, 15) ^ rol(x, 13) ^ (x >> 10); } + static uint SS0(in uint x) pure nothrow { + return rol(x, 30) ^ rol(x,19) ^ rol(x, 10); } + static uint SS1(in uint x) pure nothrow { + return rol(x, 26) ^ rol(x, 21) ^ rol(x, 7); } + + uint M(in uint I) nothrow { + immutable uint tm = S1(x[(I - 2) & 0x0f]) + + x[(I - 7) & 0x0f] + + S0(x[(I - 15) & 0x0f]) + + x[I & 0x0f]; + x[I & 0x0f] = tm; + return tm; + } + + static void R(in uint a, in uint b, in uint c, ref uint d, + in uint e, in uint f, in uint g, ref uint h, + in uint k, in uint m) pure nothrow { + immutable t0 = SS0(a) + F2(a, b, c); + immutable t1 = h + SS1(e) + F1(e, f, g) + k + m; + d += t1; + h = t0 + t1; + } + + // SHA256 round constants. + static immutable uint[64] K = [ + 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, + 0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U, + 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, + 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, + 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, + 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, + 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, + 0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U, + 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U, + 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, + 0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U, + 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, + 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, + 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U, + 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, + 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U]; + + while (words < endp) { + foreach (ref xi; x) { + xi = bswap(*words); + words++; + } + + R(a, b, c, d, e, f, g, h, K[ 0], x[ 0]); + R(h, a, b, c, d, e, f, g, K[ 1], x[ 1]); + R(g, h, a, b, c, d, e, f, K[ 2], x[ 2]); + R(f, g, h, a, b, c, d, e, K[ 3], x[ 3]); + R(e, f, g, h, a, b, c, d, K[ 4], x[ 4]); + R(d, e, f, g, h, a, b, c, K[ 5], x[ 5]); + R(c, d, e, f, g, h, a, b, K[ 6], x[ 6]); + R(b, c, d, e, f, g, h, a, K[ 7], x[ 7]); + R(a, b, c, d, e, f, g, h, K[ 8], x[ 8]); + R(h, a, b, c, d, e, f, g, K[ 9], x[ 9]); + R(g, h, a, b, c, d, e, f, K[10], x[10]); + R(f, g, h, a, b, c, d, e, K[11], x[11]); + R(e, f, g, h, a, b, c, d, K[12], x[12]); + R(d, e, f, g, h, a, b, c, K[13], x[13]); + R(c, d, e, f, g, h, a, b, K[14], x[14]); + R(b, c, d, e, f, g, h, a, K[15], x[15]); + R(a, b, c, d, e, f, g, h, K[16], M(16)); + R(h, a, b, c, d, e, f, g, K[17], M(17)); + R(g, h, a, b, c, d, e, f, K[18], M(18)); + R(f, g, h, a, b, c, d, e, K[19], M(19)); + R(e, f, g, h, a, b, c, d, K[20], M(20)); + R(d, e, f, g, h, a, b, c, K[21], M(21)); + R(c, d, e, f, g, h, a, b, K[22], M(22)); + R(b, c, d, e, f, g, h, a, K[23], M(23)); + R(a, b, c, d, e, f, g, h, K[24], M(24)); + R(h, a, b, c, d, e, f, g, K[25], M(25)); + R(g, h, a, b, c, d, e, f, K[26], M(26)); + R(f, g, h, a, b, c, d, e, K[27], M(27)); + R(e, f, g, h, a, b, c, d, K[28], M(28)); + R(d, e, f, g, h, a, b, c, K[29], M(29)); + R(c, d, e, f, g, h, a, b, K[30], M(30)); + R(b, c, d, e, f, g, h, a, K[31], M(31)); + R(a, b, c, d, e, f, g, h, K[32], M(32)); + R(h, a, b, c, d, e, f, g, K[33], M(33)); + R(g, h, a, b, c, d, e, f, K[34], M(34)); + R(f, g, h, a, b, c, d, e, K[35], M(35)); + R(e, f, g, h, a, b, c, d, K[36], M(36)); + R(d, e, f, g, h, a, b, c, K[37], M(37)); + R(c, d, e, f, g, h, a, b, K[38], M(38)); + R(b, c, d, e, f, g, h, a, K[39], M(39)); + R(a, b, c, d, e, f, g, h, K[40], M(40)); + R(h, a, b, c, d, e, f, g, K[41], M(41)); + R(g, h, a, b, c, d, e, f, K[42], M(42)); + R(f, g, h, a, b, c, d, e, K[43], M(43)); + R(e, f, g, h, a, b, c, d, K[44], M(44)); + R(d, e, f, g, h, a, b, c, K[45], M(45)); + R(c, d, e, f, g, h, a, b, K[46], M(46)); + R(b, c, d, e, f, g, h, a, K[47], M(47)); + R(a, b, c, d, e, f, g, h, K[48], M(48)); + R(h, a, b, c, d, e, f, g, K[49], M(49)); + R(g, h, a, b, c, d, e, f, K[50], M(50)); + R(f, g, h, a, b, c, d, e, K[51], M(51)); + R(e, f, g, h, a, b, c, d, K[52], M(52)); + R(d, e, f, g, h, a, b, c, K[53], M(53)); + R(c, d, e, f, g, h, a, b, K[54], M(54)); + R(b, c, d, e, f, g, h, a, K[55], M(55)); + R(a, b, c, d, e, f, g, h, K[56], M(56)); + R(h, a, b, c, d, e, f, g, K[57], M(57)); + R(g, h, a, b, c, d, e, f, K[58], M(58)); + R(f, g, h, a, b, c, d, e, K[59], M(59)); + R(e, f, g, h, a, b, c, d, K[60], M(60)); + R(d, e, f, g, h, a, b, c, K[61], M(61)); + R(c, d, e, f, g, h, a, b, K[62], M(62)); + R(b, c, d, e, f, g, h, a, K[63], M(63)); + + a = state[0] += a; + b = state[1] += b; + c = state[2] += c; + d = state[3] += d; + e = state[4] += e; + f = state[5] += f; + g = state[6] += g; + h = state[7] += h; + } + } + + + /** Process the remaining bytes in the internal buffer and the + usual prolog according to the standard and write the result to + resBuf. + Important: On some systems it is required that resBuf is correctly + aligned for a 32-bit value. */ + void conclude() pure nothrow { + // Take yet unprocessed bytes into account. + immutable bytes = bufLen; + immutable size_t size = (bytes < 56) ? 64 / 4 : 64 * 2 / 4; + + // Now count remaining bytes. + total[0] += bytes; + if (total[0] < bytes) + total[1]++; + + // Put the 64-bit file length in *bits* at the end of + // the buffer. + buffer[size - 2] = bswap((total[1] << 3) | (total[0] >> 29)); + buffer[size - 1] = bswap(total[0] << 3); + + memcpy(&bufferB[bytes], fillBuf.ptr, (size - 2) * 4 - bytes); + + // Process last bytes. + processBlock(bufferB[0 .. size * 4]); + } + + + /** Put result from this in first 32 bytes following resBuf. The + result must be in little endian byte order. + Important: On some systems it is required that resBuf is correctly + aligned for a 32-bit value. */ + ref TResult read(ref TResult resBuf) const pure nothrow { + foreach (immutable i, immutable s; state) + (cast(uint*)resBuf.ptr)[i] = bswap(s); + return resBuf; + } + + + /** Process the remaining bytes in the buffer and put result from + CTX in first 32 (28) bytes following resBuf. The result is always + in little endian byte order, so that a byte-wise output yields to + the wanted ASCII representation of the message digest. + Important: On some systems it is required that resBuf be correctly + aligned for a 32 bits value. */ + ref TResult finish(ref TResult resBuf) pure nothrow { + conclude; + return read(resBuf); + } + + + /** Compute SHA512 message digest for LEN bytes beginning at + buffer. The result is always in little endian byte order, so that + a byte-wise output yields to the wanted ASCII representation of + the message digest. */ + static ref TResult digest(in ubyte[] inBuffer, ref TResult resBuf) + pure nothrow { + SHA256 sha = void; + + // Initialize the computation context. + sha.init; + + // Process whole buffer but last len % 64 bytes. + sha.processBytes(inBuffer); + + // Put result in desired memory area. + return sha.finish(resBuf); + } + + + /// ditto + static TResult digest(in ubyte[] inBuffer) pure nothrow { + align(4) TResult resBuf = void; + return digest(inBuffer, resBuf); + } +} + + +version (sha_256_main) { + void main() { + import std.stdio, std.string; + + immutable data = "Rosetta code".representation; + writefln("%(%02x%)", SHA256.digest(data)); + } +} diff --git a/Task/SHA-256/Lua/sha-256.lua b/Task/SHA-256/Lua/sha-256.lua new file mode 100644 index 0000000000..14863c40b3 --- /dev/null +++ b/Task/SHA-256/Lua/sha-256.lua @@ -0,0 +1,5 @@ +#!/usr/bin/lua + +require "sha2" + +print(sha2.sha256hex("Rosetta code")) diff --git a/Task/SHA-256/Objective-C/sha-256.m b/Task/SHA-256/Objective-C/sha-256.m new file mode 100644 index 0000000000..d949ec0cac --- /dev/null +++ b/Task/SHA-256/Objective-C/sha-256.m @@ -0,0 +1,21 @@ +#import + +@implementation AppDelegate + +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + NSString* key = @"secret"; + NSString* data = @"Message"; + + const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; + const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding]; + unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; + CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); + + NSMutableString* result = [NSMutableString stringWithCapacity:(CC_SHA256_DIGEST_LENGTH * 2)]; + + for(CC_LONG i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) + [result appendFormat:@"%02x", cHMAC[i]]; + + NSLog(@"Sha-256: %@", result); + +} diff --git a/Task/Safe-addition/AutoHotkey/safe-addition.ahk b/Task/Safe-addition/AutoHotkey/safe-addition.ahk new file mode 100644 index 0000000000..845e9efc70 --- /dev/null +++ b/Task/Safe-addition/AutoHotkey/safe-addition.ahk @@ -0,0 +1,14 @@ +Msgbox % IntervalAdd(1,2) ; [2.999999,3.000001] + +SetFormat, FloatFast, 0.20 +Msgbox % IntervalAdd(1,2) ; [2.99999999999999910000,3.00000000000000090000] + +;In v1.0.48+, floating point variables have about 15 digits of precision internally +;unless SetFormat Float (i.e. the slow mode) is present anywhere in the script. +;In that case, the stored precision of floating point numbers is determined by A_FormatFloat. +;As there is no way for this function to know whether this is the case or not, +;it conservatively uses A_FormatFloat in all cases. +IntervalAdd(a,b){ + err:=0.1**(SubStr(A_FormatFloat,3) > 15 ? 15 : SubStr(A_FormatFloat,3)) + Return "[" a+b-err ","a+b+err "]" +} diff --git a/Task/Same-Fringe/Clojure/same-fringe-3.clj b/Task/Same-Fringe/Clojure/same-fringe-3.clj index a65537c0d9..38be1c76e7 100644 --- a/Task/Same-Fringe/Clojure/same-fringe-3.clj +++ b/Task/Same-Fringe/Clojure/same-fringe-3.clj @@ -2,7 +2,5 @@ (cond (and (empty? s1) (empty? s2)) true (not= (empty? s1) (empty? s2)) false - :else - (if (= (first s1) (first s2)) - (recur (rest s1) (rest s2)) - false))) + (= (first s1) (first s2)) (recur (rest s1) (rest s2)) + :else false)) diff --git a/Task/Scope-modifiers/Bracmat/scope-modifiers-1.bracmat b/Task/Scope-modifiers/Bracmat/scope-modifiers-1.bracmat new file mode 100644 index 0000000000..325e790049 --- /dev/null +++ b/Task/Scope-modifiers/Bracmat/scope-modifiers-1.bracmat @@ -0,0 +1,13 @@ + 67:?x {x has global scope} +& 77:?y { y has global scope } +& ( double + = + . !y+!y { y refers to the variable declared in myFunc, which + shadows the global variable with the same name } + ) +& ( myFunc + = y,z { y and z have dynamic scope. z is never used. } + . !arg:?y { arg is dynamically scoped } + & double$ + & !x+!y + ) diff --git a/Task/Scope-modifiers/Bracmat/scope-modifiers-2.bracmat b/Task/Scope-modifiers/Bracmat/scope-modifiers-2.bracmat new file mode 100644 index 0000000000..b716b37d25 --- /dev/null +++ b/Task/Scope-modifiers/Bracmat/scope-modifiers-2.bracmat @@ -0,0 +1 @@ +/(x./(y.x$+y$)) { x and y have lexical scope } diff --git a/Task/Search-a-list/Maxima/search-a-list-1.maxima b/Task/Search-a-list/Maxima/search-a-list-1.maxima new file mode 100644 index 0000000000..8a52882fae --- /dev/null +++ b/Task/Search-a-list/Maxima/search-a-list-1.maxima @@ -0,0 +1,9 @@ +haystack: ["Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"]; +needle: "Zag"; + +findneedle(needle, haystack, [opt]):=block([idx], + idx: sublist_indices(haystack, lambda([w], w=needle)), + if emptyp(idx) then throw('notfound), + if emptyp(opt) then return(idx), + opt: first(opt), + if opt='f then first(idx) else if opt='l then last(idx) else throw('unknownmode)); diff --git a/Task/Search-a-list/Maxima/search-a-list-2.maxima b/Task/Search-a-list/Maxima/search-a-list-2.maxima new file mode 100644 index 0000000000..0c0d8e7da1 --- /dev/null +++ b/Task/Search-a-list/Maxima/search-a-list-2.maxima @@ -0,0 +1,12 @@ +(%i32) catch(findneedle("Zag", haystack, 'f)); +(%o32) 2 +(%i33) catch(findneedle("Zag", haystack, 'l)); +(%o33) 7 +(%i34) catch(findneedle("Washington", haystack)); +(%o34) notfound +(%i35) catch(findneedle("Bush", haystack, 'f)); +(%o35) 5 +(%i36) catch(findneedle("Zag", haystack)); +(%o36) [2, 7] +(%i37) catch(findneedle("Zag", haystack, 'l)); +(%o37) 7 diff --git a/Task/Search-a-list/Objective-C/search-a-list.m b/Task/Search-a-list/Objective-C/search-a-list.m new file mode 100644 index 0000000000..484545aa8b --- /dev/null +++ b/Task/Search-a-list/Objective-C/search-a-list.m @@ -0,0 +1,8 @@ +NSArray *haystack = @[@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo"]; +for (id needle in @[@"Washington",@"Bush"]) { + int index = [haystack indexOfObject:needle]; + if (index == NSNotFound) + NSLog(@"%@ is not in haystack", needle); + else + NSLog(@"%i %@", index, needle); +} diff --git a/Task/Self-describing-numbers/ALGOL-68/self-describing-numbers.alg b/Task/Self-describing-numbers/ALGOL-68/self-describing-numbers.alg new file mode 100644 index 0000000000..14de074b25 --- /dev/null +++ b/Task/Self-describing-numbers/ALGOL-68/self-describing-numbers.alg @@ -0,0 +1,46 @@ +BEGIN + + # return TRUE if number is self describing, FALSE otherwise # + OP SELFDESCRIBING = ( INT number )BOOL: + BEGIN + + [10]INT counts := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + INT n := number; + INT digits := 0; + + # count the occurances of each digit # + WHILE + n /= 0 + DO + digits +:= 1; + counts[ ( n MOD 10 ) + 1 ] +:= 1; + n OVERAB 10 + OD; + + # construct the number that the counts would describe, # + # if the number was self describing # + + INT described number := 0; + FOR i TO digits + DO + described number *:= 10; + described number +:= counts[ i ] + OD; + + # if the described number is the input number, # + # it is self describing # + ( number = described number ) + END; # SELFDESCRIBING # + +main: ( + + FOR i TO 100 000 000 + DO + IF SELFDESCRIBING i + THEN + print( ( i, " is self describing", newline ) ) + FI + OD +) + +END diff --git a/Task/Self-describing-numbers/PicoLisp/self-describing-numbers.l b/Task/Self-describing-numbers/PicoLisp/self-describing-numbers.l index 2a0f067234..770f47754d 100644 --- a/Task/Self-describing-numbers/PicoLisp/self-describing-numbers.l +++ b/Task/Self-describing-numbers/PicoLisp/self-describing-numbers.l @@ -1,5 +1,4 @@ (de selfDescribing (N) - (not - (find '((D I) (<> D (cnt = N (circ I)))) - (setq N (mapcar format (chop N))) - (range 0 (length N)) ) ) ) + (fully '((D I) (= D (cnt = N (circ I)))) + (setq N (mapcar format (chop N))) + (range 0 (length N)) ) ) diff --git a/Task/Semordnilap/00DESCRIPTION b/Task/Semordnilap/00DESCRIPTION index 822ad72410..d69ef0389d 100644 --- a/Task/Semordnilap/00DESCRIPTION +++ b/Task/Semordnilap/00DESCRIPTION @@ -1,4 +1,4 @@ -A [http://en.wikipedia.org/wiki/Semordnilap#Semordnilaps semordnilap], is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. +A '''[[wp:semordnilap|semordnilap]]''' is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: ''lager'' and ''regal'' diff --git a/Task/Semordnilap/AutoHotkey/semordnilap.ahk b/Task/Semordnilap/AutoHotkey/semordnilap.ahk new file mode 100644 index 0000000000..c0cf75c659 --- /dev/null +++ b/Task/Semordnilap/AutoHotkey/semordnilap.ahk @@ -0,0 +1,22 @@ +S := [], M := [] + +FileRead, dict, unixdict.txt +Loop, Parse, dict, `n, `r`n +{ + r := Reverse(A_LoopField) + if (S[r]) + M.Insert(r " / " A_LoopField) + else + S[A_LoopField] := 1 +} + +Loop, 5 + Out .= "`t" M[A_Index] "`n" + +MsgBox, % "5 Examples:`n" Out "`nTotal Pairs:`n`t" M.MaxIndex() + +Reverse(s) { + Loop, Parse, s + r := A_LoopField . r + return r +} diff --git a/Task/Send-an-unknown-method-call/Objective-C/send-an-unknown-method-call.m b/Task/Send-an-unknown-method-call/Objective-C/send-an-unknown-method-call.m index 60b585f8ec..f9e9c6238b 100644 --- a/Task/Send-an-unknown-method-call/Objective-C/send-an-unknown-method-call.m +++ b/Task/Send-an-unknown-method-call/Objective-C/send-an-unknown-method-call.m @@ -1,23 +1,22 @@ #import -@interface Example : NSObject { } +@interface Example : NSObject - (NSNumber *)foo; @end @implementation Example - (NSNumber *)foo { - return [NSNumber numberWithInt:42]; + return @42; } @end int main (int argc, const char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - id example = [[Example alloc] init]; - SEL selector = @selector(foo); // or = NSSelectorFromString(@"foo"); - NSLog(@"%@", [example performSelector:selector]); - [example release]; + id example = [[Example alloc] init]; + SEL selector = @selector(foo); // or = NSSelectorFromString(@"foo"); + NSLog(@"%@", [example performSelector:selector]); - [pool release]; + } return 0; } diff --git a/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d b/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d index 7d180200bd..47710f48a0 100644 --- a/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d +++ b/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d @@ -1,14 +1,14 @@ import std.stdio, std.math, std.algorithm, std.range; int nonSquare(in int n) pure nothrow { - return n + cast(int)(0.5 + sqrt(cast(real)n)); + return n + cast(int)(0.5 + real(n).sqrt); } void main() { - iota(1, 23).map!nonSquare().writeln(); + iota(1, 23).map!nonSquare.writeln; - foreach (i; 1 .. 1_000_000) { - int ns = nonSquare(i); - assert(ns != (cast(int)sqrt(cast(real)ns)) ^^ 2); + foreach (immutable i; 1 .. 1_000_000) { + immutable ns = i.nonSquare; + assert(ns != (cast(int)real(ns).sqrt) ^^ 2); } } diff --git a/Task/Set-consolidation/Common-Lisp/set-consolidation.lisp b/Task/Set-consolidation/Common-Lisp/set-consolidation.lisp new file mode 100644 index 0000000000..641cf33452 --- /dev/null +++ b/Task/Set-consolidation/Common-Lisp/set-consolidation.lisp @@ -0,0 +1,8 @@ +(defun consolidate (ss) + (labels ((comb (cs s) + (cond ((null s) cs) + ((null cs) (list s)) + ((null (intersection s (first cs))) + (cons (first cs) (comb (rest cs) s))) + ((consolidate (cons (union s (first cs)) (rest cs))))))) + (reduce #'comb ss :initial-value nil))) diff --git a/Task/Set-consolidation/TXR/set-consolidation-1.txr b/Task/Set-consolidation/TXR/set-consolidation-1.txr new file mode 100644 index 0000000000..6208b8643a --- /dev/null +++ b/Task/Set-consolidation/TXR/set-consolidation-1.txr @@ -0,0 +1,26 @@ +@(do + (defun mkset (p x) (set [p x] (or [p x] x))) + + (defun fnd (p x) (if (eq [p x] x) x (fnd p [p x]))) + + (defun uni (p x y) + (let ((xr (fnd p x)) (yr (fnd p y))) + (set [p xr] yr))) + + (defun consoli (sets) + (let ((p (hash))) + (each ((s sets)) + (each ((e s)) + (mkset p e) + (uni p e (car s)))) + (hash-values + [group-by (op fnd p) (hash-keys + [group-by identity (flatten sets)])]))) + + ;; tests + + (each ((test '(((a b) (c d)) + ((a b) (b d)) + ((a b) (c d) (d b)) + ((h i k) (a b) (c d) (d b) (f g h))))) + (format t "~s -> ~s\n" test (consoli test)))) diff --git a/Task/Set-consolidation/TXR/set-consolidation-2.txr b/Task/Set-consolidation/TXR/set-consolidation-2.txr new file mode 100644 index 0000000000..2ee935f256 --- /dev/null +++ b/Task/Set-consolidation/TXR/set-consolidation-2.txr @@ -0,0 +1,21 @@ +@(do + (defun mkset (items) [group-by identity items]) + + (defun empty-p (set) (zerop (hash-count set))) + + (defun consoli (ss) + (defun comb (cs s) + (cond ((empty-p s) cs) + ((null cs) (list s)) + ((empty-p (hash-isec s (first cs))) + (cons (first cs) (comb (rest cs) s))) + (t (consoli (cons (hash-uni s (first cs)) (rest cs)))))) + [reduce-left comb ss nil]) + + ;; tests + (each ((test '(((a b) (c d)) + ((a b) (b d)) + ((a b) (c d) (d b)) + ((h i k) (a b) (c d) (d b) (f g h))))) + (format t "~s -> ~s\n" test + [mapcar hash-keys (consoli [mapcar mkset test])]))) diff --git a/Task/Set-puzzle/AutoHotkey/set-puzzle.ahk b/Task/Set-puzzle/AutoHotkey/set-puzzle.ahk new file mode 100644 index 0000000000..6b3a18f006 --- /dev/null +++ b/Task/Set-puzzle/AutoHotkey/set-puzzle.ahk @@ -0,0 +1,104 @@ +; Generate deck; card encoding from Perl6 +Loop, 81 + deck .= ToBase(A_Index-1, 3)+1111 "," +deck := RegExReplace(deck, "3", "4") + +; Shuffle +deck := shuffle(deck) + +msgbox % clipboard := allValidSets(9, 4, deck) +msgbox % clipboard := allValidSets(12, 6, deck) + +; Render a hand (or any list) of cards +PrettyHand(hand) { + Color1:="red",Color2:="green",Color4:="purple" + ,Symbl1:="oval",Symbl2:="squiggle",Symbl4:="diamond" + ,Numbr1:="one",Numbr2:="two",Numbr4:="three" + ,Shape1:="solid",Shape2:="open",Shape4:="striped" + Loop, Parse, hand, `, + { + StringSplit, i, A_LoopField + s .= "`t" Color%i1% "`t" Symbl%i2% "`t" Numbr%i3% "`t" Shape%i4% "`n" + } + Return s +} + +; Get all unique valid sets of three cards in a hand. +allValidSets(n, m, deck) { + While j != m + { + j := 0 + ,hand := draw(n, deck) + ,s := "Dealt " n " cards:`n" . prettyhand(hand) + StringSplit, set, hand, `, + comb := comb(n,3) + Loop, Parse, comb, `n + { + StringSplit, i, A_LoopField, %A_Space% + If isValidSet(set%i1%, set%i2%, set%i3%) + s .= "`nSet " ++j ":`n" . prettyhand(set%i1% "," set%i2% "," set%i3%) + } + } + Return s +} + +; Convert n to arbitrary base using recursion +toBase(n,b) { ; n >= 0, 1 < b < StrLen(t), t = digits + Static t := "0123456789ABCDEF" + Return (n < b ? "" : ToBase(n//b,b)) . SubStr(t,mod(n,b)+1,1) +} + +; Knuth shuffle from http://rosettacode.org/wiki/Knuth_Shuffle#AutoHotkey +shuffle(list) { ; shuffle comma separated list, converted to array + StringSplit a, list, `, ; make array (length = a0) + Loop % a0-1 { + Random i, A_Index, a0 ; swap item 1,2... with a random item to the right of it + t := a%i%, a%i% := a%A_Index%, a%A_Index% := t + } + Loop % a0 ; construct string from sorted array + s .= "," . a%A_Index% + Return SubStr(s,2) ; drop leading comma +} + +; Randomly pick a hand of cards from the deck +draw(n, deck) { + Loop, % n + { + Random, i, 1, 81 + cards := deck + Loop, Parse, cards, `, + (A_Index = i) ? (hand .= A_LoopField ",") : (cards .= A_LoopField ",") + deck := cards + } + Return SubStr(hand, 1, -1) +} + +; Test if a particular group of three cards is a valid set +isValidSet(a, b, c) { + StringSplit, a, a + StringSplit, b, b + StringSplit, c, c + Return !((a1|b1|c1 ~= "[3,5,6]") + (a2|b2|c2 ~= "[3,5,6]") + (a3|b3|c3 ~= "[3,5,6]") + (a4|b4|c4 ~= "[3,5,6]")) +} + +; Get all combinations, from http://rosettacode.org/wiki/Combinations#AutoHotkey +comb(n,t) { ; Generate all n choose t combinations of 1..n, lexicographically + IfLess n,%t%, Return + Loop %t% + c%A_Index% := A_Index + i := t+1, c%i% := n+1 + + Loop { + Loop %t% + i := t+1-A_Index, c .= c%i% " " + c .= "`n" ; combinations in new lines + j := 1, i := 2 + Loop + If (c%j%+1 = c%i%) + c%j% := j, ++j, ++i + Else Break + If (j > t) + Return c + c%j% += 1 + } +} diff --git a/Task/Set-puzzle/Perl-6/set-puzzle.pl6 b/Task/Set-puzzle/Perl-6/set-puzzle.pl6 index 85bf2ea774..9681dfaeaa 100644 --- a/Task/Set-puzzle/Perl-6/set-puzzle.pl6 +++ b/Task/Set-puzzle/Perl-6/set-puzzle.pl6 @@ -6,7 +6,10 @@ enum Style (solid => 0o1, open => 0o2, striped => 0o4); my @deck := (Color.enums X Count.enums X Shape.enums X Style.enums).tree; sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) { - my @combinations = combine(3, [^$DRAW]); + sub show-cards(@c) { printf " %-6s %-5s %-8s %s\n", $_».key for @c } + + my @combinations = [^$DRAW].combinations(3); + my @draw; repeat until (my @sets) == $GOAL { @draw = @deck.pick($DRAW); @@ -15,6 +18,7 @@ sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) { take @draw[@c].item when /^ <[1247]>+ $/ given ( [+|] @bits[@c] ).base(8); } } + say "Drew $DRAW cards:"; show-cards @draw; for @sets.kv -> $i, @cards { @@ -22,5 +26,3 @@ sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) { show-cards @cards; } } - -sub show-cards(@c) { for @c -> $c { printf " %-6s %-5s %-8s %s\n", $c».key } } diff --git a/Task/Set/AutoHotkey/set-1.ahk b/Task/Set/AutoHotkey/set-1.ahk new file mode 100644 index 0000000000..e98d41e300 --- /dev/null +++ b/Task/Set/AutoHotkey/set-1.ahk @@ -0,0 +1,51 @@ +test(Set,element){ + for i, val in Set + if (val=element) + return true + return false +} + +Union(SetA,SetB){ + SetC:=[], Temp:=[] + for i, val in SetA + SetC.Insert(val), Temp[val] := true + for i, val in SetB + if !Temp[val] + SetC.Insert(val) + return SetC +} + +intersection(SetA,SetB){ + SetC:=[], Temp:=[] + for i, val in SetA + Temp[val] := true + for i, val in SetB + if Temp[val] + SetC.Insert(val) + return SetC +} + +difference(SetA,SetB){ + SetC:=[], Temp:=[] + for i, val in SetB + Temp[val] := true + for i, val in SetA + if !Temp[val] + SetC.Insert(val) + return SetC +} + +subset(SetA,SetB){ + Temp:=[], A:=B:=0 + for i, val in SetA + Temp[val] := true , A++ + for i, val in SetB + if Temp[val]{ + B++ + IfEqual, A, %B%, return 1 + } return 0 +} + +equal(SetA,SetB){ + return (SetA.MaxIndex() = SetB.MaxIndex() && subset(SetA,SetB)) ? 1: 0 +} diff --git a/Task/Set/AutoHotkey/set-2.ahk b/Task/Set/AutoHotkey/set-2.ahk new file mode 100644 index 0000000000..253e290849 --- /dev/null +++ b/Task/Set/AutoHotkey/set-2.ahk @@ -0,0 +1,42 @@ +A:= ["apple", "cherry", "elderberry", "grape"] +B:= ["banana", "cherry", "date", "elderberry", "fig"] +C:= ["apple", "cherry", "elderberry", "grape", "orange"] +D:= ["apple", "cherry", "elderberry", "grape"] +E:= ["apple", "cherry", "elderberry"] +M:= "banana" + +Res = +( +A:= ["apple", "cherry", "elderberry", "grape"] +B:= ["banana", "cherry", "date", "elderberry", "fig"] +C:= ["apple", "cherry", "elderberry", "grape", "orange"] +D:= ["apple", "cherry", "elderberry", "grape"] +E:= ["apple", "cherry", "elderberry"] +M:= "banana" + +) + +Res .= "`nM is " (test(A,M)?"":"not ") "an element of Set A" +Res .= "`nM is " (test(B,M)?"":"not ") "an element of Set B" + +Res .= "`nUnion(A,B) = " +for i, val in Union(A,B) + Res.= (A_Index=1?"`t":", ") val + +Res .= "`nintersection(A,B) = " +for i, val in intersection(A,B) + Res.= (A_Index=1?"`t":", ") val + +Res .= "`ndifference(A,B) = " +for i, val in difference(A,B) + Res.= (A_Index=1?"`t":", ") val + +Res .= "`n`nA is " (subset(A,C)?"":"not ") "a subset of Set C" +Res .= "`nA is " (subset(A,D)?"":"not ") "a subset of Set D" +Res .= "`nA is " (subset(A,E)?"":"not ") "a subset of Set E" + +Res .= "`n`nA is " (equal(A,C)?"":"not ") "a equal to Set C" +Res .= "`nA is " (equal(A,D)?"":"not ") "a equal to Set D" +Res .= "`nA is " (equal(A,E)?"":"not ") "a equal to Set E" + +MsgBox % Res diff --git a/Task/Set/Dart/set.dart b/Task/Set/Dart/set.dart new file mode 100644 index 0000000000..1d2c26a0eb --- /dev/null +++ b/Task/Set/Dart/set.dart @@ -0,0 +1,38 @@ +void main(){ + //Set Creation + Set A = new Set.from([1,2,3]); + Set B = new Set.from([1,2,3,4,5]); + Set C = new Set.from([1,2,4,5]); + + print('Set A = $A'); + print('Set B = $B'); + print('Set C = $C'); + print(''); + //Test if element is in set + int m = 3; + print('m = 5'); + print('m in A = ${A.contains(m)}'); + print('m in B = ${B.contains(m)}'); + print('m in C = ${C.contains(m)}'); + print(''); + //Union of two sets + Set AC = A.union(C); + print('Set AC = Union of A and C = $AC'); + print(''); + //Intersection of two sets + Set A_C = A.intersection(C); + print('Set A_C = Intersection of A and C = $A_C'); + print(''); + //Difference of two sets + Set A_diff_C = A.difference(C); + print('Set A_diff_C = Difference between A and C = $A_diff_C'); + print(''); + //Test if set is subset of another set + print('A is a subset of B = ${B.containsAll(A)}'); + print('C is a subset of B = ${B.containsAll(C)}'); + print('A is a subset of C = ${C.containsAll(A)}'); + print(''); + //Test if two sets are equal + print('A is equal to B = ${B.containsAll(A) && A.containsAll(B)}'); + print('B is equal to AC = ${B.containsAll(AC) && AC.containsAll(B)}'); +} diff --git a/Task/Set/Objective-C/set.m b/Task/Set/Objective-C/set.m index 23782b0168..664ab8e65d 100644 --- a/Task/Set/Objective-C/set.m +++ b/Task/Set/Objective-C/set.m @@ -1,57 +1,57 @@ #import int main (int argc, const char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSSet *s1 = [NSSet setWithObjects:@"a", @"b", @"c", @"d", @"e", nil]; - NSSet *s2 = [NSSet setWithObjects:@"b", @"c", @"d", @"e", @"f", @"h", nil]; - NSSet *s3 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; - NSSet *s4 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; - NSLog(@"s1: %@", s1); - NSLog(@"s2: %@", s2); - NSLog(@"s3: %@", s3); - NSLog(@"s4: %@", s4); + NSSet *s1 = [NSSet setWithObjects:@"a", @"b", @"c", @"d", @"e", nil]; + NSSet *s2 = [NSSet setWithObjects:@"b", @"c", @"d", @"e", @"f", @"h", nil]; + NSSet *s3 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; + NSSet *s4 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; + NSLog(@"s1: %@", s1); + NSLog(@"s2: %@", s2); + NSLog(@"s3: %@", s3); + NSLog(@"s4: %@", s4); - // Membership - NSLog(@"b in s1: %d", [s1 containsObject:@"b"]); - NSLog(@"f in s1: %d", [s1 containsObject:@"f"]); + // Membership + NSLog(@"b in s1: %d", [s1 containsObject:@"b"]); + NSLog(@"f in s1: %d", [s1 containsObject:@"f"]); - // Union - NSMutableSet *s12 = [NSMutableSet setWithSet:s1]; - [s12 unionSet:s2]; - NSLog(@"s1 union s2: %@", s12); + // Union + NSMutableSet *s12 = [NSMutableSet setWithSet:s1]; + [s12 unionSet:s2]; + NSLog(@"s1 union s2: %@", s12); - // Intersection - NSMutableSet *s1i2 = [NSMutableSet setWithSet:s1]; - [s1i2 intersectSet:s2]; - NSLog(@"s1 intersect s2: %@", s1i2); + // Intersection + NSMutableSet *s1i2 = [NSMutableSet setWithSet:s1]; + [s1i2 intersectSet:s2]; + NSLog(@"s1 intersect s2: %@", s1i2); - // Difference - NSMutableSet *s1_2 = [NSMutableSet setWithSet:s1]; - [s1_2 minusSet:s2]; - NSLog(@"s1 - s2: %@", s1_2); + // Difference + NSMutableSet *s1_2 = [NSMutableSet setWithSet:s1]; + [s1_2 minusSet:s2]; + NSLog(@"s1 - s2: %@", s1_2); - // Subset of - NSLog(@"s3 subset of s1: %d", [s3 isSubsetOfSet:s1]); + // Subset of + NSLog(@"s3 subset of s1: %d", [s3 isSubsetOfSet:s1]); - // Equality - NSLog(@"s3 = s4: %d", [s3 isEqualToSet:s4]); + // Equality + NSLog(@"s3 = s4: %d", [s3 isEqualToSet:s4]); - // Cardinality - NSLog(@"size of s1: %lu", [s1 count]); + // Cardinality + NSLog(@"size of s1: %lu", [s1 count]); - // Has intersection (not disjoint) - NSLog(@"does s1 intersect s2? %d", [s1 intersectsSet:s2]); + // Has intersection (not disjoint) + NSLog(@"does s1 intersect s2? %d", [s1 intersectsSet:s2]); - // Adding and removing elements from a mutable set - NSMutableSet *mut_s1 = [NSMutableSet setWithSet:s1]; - [mut_s1 addObject:@"g"]; - NSLog(@"mut_s1 after adding g: %@", mut_s1); - [mut_s1 addObject:@"b"]; - NSLog(@"mut_s1 after adding b again: %@", mut_s1); - [mut_s1 removeObject:@"c"]; - NSLog(@"mut_s1 after removing c: %@", mut_s1); + // Adding and removing elements from a mutable set + NSMutableSet *mut_s1 = [NSMutableSet setWithSet:s1]; + [mut_s1 addObject:@"g"]; + NSLog(@"mut_s1 after adding g: %@", mut_s1); + [mut_s1 addObject:@"b"]; + NSLog(@"mut_s1 after adding b again: %@", mut_s1); + [mut_s1 removeObject:@"c"]; + NSLog(@"mut_s1 after removing c: %@", mut_s1); - [pool release]; + } return 0; } diff --git a/Task/Shell-one-liner/Prolog/shell-one-liner-1.pro b/Task/Shell-one-liner/Prolog/shell-one-liner-1.pro new file mode 100644 index 0000000000..5dd20ae4a6 --- /dev/null +++ b/Task/Shell-one-liner/Prolog/shell-one-liner-1.pro @@ -0,0 +1,3 @@ +$ swipl -g "writeln('hello world')." -t 'halt.' +hello world +$ diff --git a/Task/Shell-one-liner/Prolog/shell-one-liner-2.pro b/Task/Shell-one-liner/Prolog/shell-one-liner-2.pro new file mode 100644 index 0000000000..0ca7d5e7d5 --- /dev/null +++ b/Task/Shell-one-liner/Prolog/shell-one-liner-2.pro @@ -0,0 +1,3 @@ +$ gprolog --init-goal "write('goodbye'),nl,halt" +goodbye +$ diff --git a/Task/Shell-one-liner/Prolog/shell-one-liner-3.pro b/Task/Shell-one-liner/Prolog/shell-one-liner-3.pro new file mode 100644 index 0000000000..6c733aedf2 --- /dev/null +++ b/Task/Shell-one-liner/Prolog/shell-one-liner-3.pro @@ -0,0 +1,2 @@ +$ yap -q -g "current_prolog_flag(dialect, D), writeln(D), halt" +yap diff --git a/Task/Shell-one-liner/Prolog/shell-one-liner-4.pro b/Task/Shell-one-liner/Prolog/shell-one-liner-4.pro new file mode 100644 index 0000000000..7b715c4e4b --- /dev/null +++ b/Task/Shell-one-liner/Prolog/shell-one-liner-4.pro @@ -0,0 +1,5 @@ +$ swipl -q <<< "current_prolog_flag(dialect,D), writeln(D), halt." +swi + +$ yap -q <<< "current_prolog_flag(dialect,D), writeln(D), halt." +yap diff --git a/Task/Shell-one-liner/Prolog/shell-one-liner-5.pro b/Task/Shell-one-liner/Prolog/shell-one-liner-5.pro new file mode 100644 index 0000000000..1175ad418d --- /dev/null +++ b/Task/Shell-one-liner/Prolog/shell-one-liner-5.pro @@ -0,0 +1,5 @@ +$ echo "current_prolog_flag(dialect,D), writeln(D), halt." | swipl -q +swi + +$ echo "current_prolog_flag(dialect,D), writeln(D), halt." | yap -q +yap diff --git a/Task/Shell-one-liner/TXR/shell-one-liner.txr b/Task/Shell-one-liner/TXR/shell-one-liner-1.txr similarity index 100% rename from Task/Shell-one-liner/TXR/shell-one-liner.txr rename to Task/Shell-one-liner/TXR/shell-one-liner-1.txr diff --git a/Task/Shell-one-liner/TXR/shell-one-liner-2.txr b/Task/Shell-one-liner/TXR/shell-one-liner-2.txr new file mode 100644 index 0000000000..ccbd00f0de --- /dev/null +++ b/Task/Shell-one-liner/TXR/shell-one-liner-2.txr @@ -0,0 +1,2 @@ +$ txr -p '(+ 2 2)' +4 diff --git a/Task/Shell-one-liner/TXR/shell-one-liner-3.txr b/Task/Shell-one-liner/TXR/shell-one-liner-3.txr new file mode 100644 index 0000000000..ee3bf8a4ac --- /dev/null +++ b/Task/Shell-one-liner/TXR/shell-one-liner-3.txr @@ -0,0 +1,3 @@ +$ txr -e '(mkdir "foo" #o777)' +$ ls -ld foo +drwxrwxr-x 2 kaz kaz 4096 Mar 4 23:36 foo diff --git a/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth b/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth index 454406fbec..c3eb188900 100644 --- a/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth +++ b/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth @@ -1,20 +1,28 @@ -\ short-circuit conditional syntax, from Wil Baden -: COND 0 ; immediate -: THENS BEGIN dup WHILE postpone THEN REPEAT DROP ; immediate -: ORIF s" ?DUP 0= IF" evaluate ; immediate -: ANDIF s" DUP IF DROP" evaluate ; immediate +\ Short-circuit evaluation definitions from Wil Baden, with minor name changes +: ENDIF postpone THEN ; immediate -: .bool IF ." true " ELSE ." false" THEN ; -: A ." A=" dup .bool ; -: B ." B=" dup .bool ; +: COND 0 ; immediate +: ENDIFS BEGIN DUP WHILE postpone ENDIF REPEAT DROP ; immediate +: ORELSE s" ?DUP 0= IF" evaluate ; immediate +: ANDIF s" DUP IF DROP" evaluate ; immediate + +: .bool IF ." true " ELSE ." false " THEN ; +: A ." A=" DUP .bool ; +: B ." B=" DUP .bool ; : test + CR 1 -1 DO 1 -1 DO - CR I A drop space J B drop space - ." : ANDIF " COND I A ANDIF drop J B IF ." (BOTH)" THENS - ." , ORIF " COND I A ORIF drop J B 0= IF ." (NEITHER)" THENS + COND I A ANDIF J B ENDIFS ." ANDIF=" .bool CR + COND I A ORELSE J B ENDIFS ." ORELSE=" .bool CR LOOP LOOP ; -\ a more typical example -: alnum? ( char -- ? ) - COND dup lower? ORIF dup upper? ORIF dup digit? THENS nip ; +\ An alternative based on explicitly short-circuiting conditionals, Dave Keenan +: END-PRIOR-IF 1 CS-ROLL postpone ENDIF ; immediate + +: test + CR + 1 -1 DO 1 -1 DO + I A IF J B IF 1 ELSE END-PRIOR-IF 0 ENDIF ." ANDIF=" .bool CR + I A 0= IF J B IF END-PRIOR-IF 1 ELSE 0 ENDIF ." ORELSE=" .bool CR + LOOP LOOP ; diff --git a/Task/Show-the-epoch/Objective-C/show-the-epoch.m b/Task/Show-the-epoch/Objective-C/show-the-epoch.m index d27fca0a74..6bfa2d63a6 100644 --- a/Task/Show-the-epoch/Objective-C/show-the-epoch.m +++ b/Task/Show-the-epoch/Objective-C/show-the-epoch.m @@ -1,14 +1,14 @@ #import int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSDate *t = [NSDate dateWithTimeIntervalSinceReferenceDate:0]; - NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; - [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; - [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"]; - NSLog(@"%@", [dateFormatter stringFromDate:t]); + NSDate *t = [NSDate dateWithTimeIntervalSinceReferenceDate:0]; + NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; + [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; + [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"]; + NSLog(@"%@", [dateFormatter stringFromDate:t]); - [pool release]; + } return 0; } diff --git a/Task/Show-the-epoch/PARI-GP/show-the-epoch.pari b/Task/Show-the-epoch/PARI-GP/show-the-epoch.pari new file mode 100644 index 0000000000..ef15bad44b --- /dev/null +++ b/Task/Show-the-epoch/PARI-GP/show-the-epoch.pari @@ -0,0 +1 @@ +system("date -ur 0") diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d index b3d51536c0..7be12d93dc 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d @@ -2,7 +2,7 @@ import std.stdio, std.algorithm, std.range, std.functional; auto nextCarpet(in string[] c) pure nothrow { /*immutable*/ const b = c.map!q{a ~ a ~ a}.array; - return b ~ c.map!q{a ~ a.replace("#", ' ') ~ a}.array ~ b; + return b ~ c.map!q{a ~ a.replace("#", " ") ~ a}.array ~ b; } void main() { diff --git a/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx b/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx index a2862f5dc2..f0437c6882 100644 --- a/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx +++ b/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx @@ -5,27 +5,19 @@ if n=='' | n==',' then n=3 /*if none specified, assume 3. */ if char=='' then char='*' /*use the default of an asterisk.*/ if length(char)==2 then char=x2c(char) /*it was specified in hexadecimal*/ if length(char)==3 then char=d2c(char) /*it was specified in decimal. */ - /*LINESIZE isn't in some REXXes. */ -/* width=linesize() */ /*maximum width of the screen. */ - width=132 - - do j=0 for 3**n; z= /* z is the line to be displayed.*/ - - do k=0 for 3**n; jj=j; kk=k; xChar=char - - do while jj\==0 & kk\==0 /*one symbol for not is \ */ - if jj//3==1 & kk//3==1 then do /* // = remainder.*/ - xChar=' ' /*use a blank. */ - leave /*leaves DO while.*/ - end +width=132 /*width of a terminal screen. */ + do j=0 for 3**n; z= /* z is the line to be displayed.*/ + do k=0 for 3**n; jj=j; kk=k; xChar=char + do while jj\==0 & kk\==0 /*one symbol for a not (¬) is \ */ + if jj//3==1 & kk//3==1 then do /* // = remainder.*/ + xChar=' ' /*use a blank. */ + leave /*leaves DO while.*/ + end jj=jj%3 kk=kk%3 /*% means it's integer division.*/ end /*while*/ - - z=z || xChar /*it's either black or white. */ - end /*k*/ - - if length(z)= Width) ? (x := i*Width/2/k, y += Height/k, i:=!i) : "" + } + UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height) + , k*=2, x:=0, y:=0, i:=1 +} + +Gdip_DeleteBrush(pBrushBlack) + +, UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height) +Sleep, 1*1000 + +; Bonus: Sierpinski triangle by random dots +Gdip_GraphicsClear(G, 0xff000000) +, pBrushBlue := Gdip_BrushCreateSolid(0xff0000ff) +, x1:=Width/2, y1:=0, x2:=0, y2:=Height, x3:=Width, y3:=Height +, x:= Width/2, y:=Height/2 ; I'm to lazy to pick a random point. +Loop, % n +{ + Loop, % 10*10**(A_Index/2) + { + Random, rand, 1, 3 + x := abs(x+x%rand%)/2 + , y := abs(y+y%rand%)/2 + , Gdip_FillEllipse(G, pBrushBlue, x, y, 1, 1) + } + UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height) + Sleep, 0.5*1000 +} +SelectObject(hdc, obm) +, DeleteObject(hbm) +, DeleteDC(hdc) +, Gdip_DeleteGraphics(G) +Return + +Exit: + Gdip_Shutdown(pToken) + ExitApp + +WM_LBUTTONDOWN() +{ + If (A_Gui = 1) + PostMessage, 0xA1, 2 +} diff --git a/Task/Sierpinski-triangle/PARI-GP/sierpinski-triangle.pari b/Task/Sierpinski-triangle/PARI-GP/sierpinski-triangle.pari new file mode 100644 index 0000000000..ccfed27522 --- /dev/null +++ b/Task/Sierpinski-triangle/PARI-GP/sierpinski-triangle.pari @@ -0,0 +1,11 @@ +Sierpinski(n)={ + my(s=2^n-1); + forstep(y=s,0,-1, + for(i=1,y,print1(" ")); + for(x=0,s-y, + print1(if(bitand(x,y)," ","*")) + ); + print() + ) +}; +Sierpinski(4) diff --git a/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 b/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 index 5fd4048634..69ad29facf 100644 --- a/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 +++ b/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 @@ -3,7 +3,7 @@ sub sierpinski ($n) { my $space = ' '; for ^$n { @down = @down.map({"$space$_$space"}), @down.map({"$_ $_"}); - $space ~= $space; + $space x= 2; } return @down; } diff --git a/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx b/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx index a91980184e..d4bb05f2bf 100644 --- a/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx +++ b/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx @@ -5,13 +5,13 @@ if mk=='' then mk='*' /*use the default of an asterisk.*/ if length(mk)==2 then mk=x2c(mk) /*MK was specified in hexadecimal*/ if length(mk)==3 then mk=d2c(mk) /*MK was specified in decimal. */ numeric digits 12000 /*this otta handle the die-hards.*/ - + /* [↓] the blood-'n-guts of pgm.*/ do j=0 for n*4; !=1; z=left('',n*4-1-j) /*indent the line. */ - do k=0 to j /*build the line with J+1 parts*/ - if !//2==0 then z=z' ' /*it's either a blank, or ... */ + do k=0 for j+1 /*build the line with J+1 parts*/ + if !//2==0 then z=z' ' /*it's either a blank, or ··· */ else z=z mk /*it's one of them thar character*/ !=!*(j-k)%(k+1) /*calculate a handy-dandy thingy.*/ - end /*k*/ + end /*k*/ /* [↑] finished building a line.*/ say z /*display a line of the triangle.*/ - end /*j*/ + end /*j*/ /* [↑] finished displaying tri. */ /*stick a fork in it, we're done.*/ diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d index 412b08937d..2d0bf669cb 100644 --- a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d @@ -21,7 +21,7 @@ size_t[] sieve(in size_t m) pure nothrow { F[offset] = F[offset] ^ mask; } - for (size_t i = 3; i <= sqrt(cast(real)n); i += 2) + for (size_t i = 3; i <= sqrt(real(n)); i += 2) if (isSet((i - 3) / 2)) for (size_t j = i * i; j <= n; j += 2 * i) resetBit((j - 3) / 2); diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d index eaacabf791..4d5d9716ea 100644 --- a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d @@ -1,39 +1,35 @@ -import std.algorithm, std.bitmanip; - /// Extensible Sieve of Eratosthenes. -struct IsPrime { - //__gshared static BitArray multiples = [true, true, false]; - __gshared static BitArray multiples; +struct Prime { + uint[] a = [2]; - /*nothrow*/ static this() { - multiples.init([true, true, false]); - } + private void grow() pure nothrow { + immutable p0 = a[$ - 1] + 1; + auto b = new bool[p0]; - static bool opCall(in size_t n) /*nothrow*/ { - if (n >= multiples.length) { - // Extend the sieve. - immutable oldLen = multiples.length; // Not nothrow. - immutable newMax = max((oldLen - 1) * 2, n); - multiples.length = newMax + 1; - foreach (immutable p; 2 .. oldLen) - if (!multiples[p]) - for (size_t i = p * ((oldLen + p) / p); - i < newMax + 1; i += p) - multiples[i] = true; - foreach (immutable i; oldLen .. newMax + 1) - if (!multiples[i]) - for (size_t j = i * 2; j < newMax + 1; j += i) - multiples[j] = true; + foreach (immutable di; a) { + immutable uint i0 = p0 / di * di; + uint i = (i0 < p0) ? i0 + di - p0 : i0 - p0; + for (; i < b.length; i += di) + b[i] = true; } - return !multiples[n]; + foreach (immutable uint i, immutable bi; b) + if (!b[i]) + a ~= p0 + i; + } + + uint opCall(in uint n) pure nothrow { + while (n >= a.length) + grow; + return a[n]; } } version (sieve_of_eratosthenes3_main) { - import std.stdio, std.range; - void main() { - 50.iota.filter!IsPrime.writeln; + import std.stdio, std.range, std.algorithm; + + Prime prime; + uint.max.iota.map!prime.until!q{a > 50}.writeln; } } diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs index 51c7d0cd11..62777bf026 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs @@ -1,9 +1,13 @@ -primesTo m = 2 : eratos [3,5..m] where - eratos (p : xs) | p*p>m = p : xs - | True = p : eratos (xs `minus` [p*p, p*p+2*p..m]) +import Data.Array.Unboxed -minus a@(x:xs) b@(y:ys) = case compare x y of - LT -> x : minus xs b - EQ -> minus xs ys - GT -> minus a ys -minus a b = a +primesSA = 2 : prs () + where + prs () = 3 : sieve 3 [] (prs ()) + sieve x fs (p:ps) = [i*2 + x | (i,True) <- assocs a] + ++ sieve (p*p) fs2 ps + where + q = (p*p-x)`div`2 + fs2 = (p,0) : [(s, rem (y-q) s) | (s,y) <- fs] + a :: UArray Int Bool + a = accumArray (\ b c -> False) True (1,q-1) + [(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs index 48431cbef8..51c7d0cd11 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs @@ -1,10 +1,9 @@ -primes = _Y $ ((2:) . minus [3..] - . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) +primesTo m = 2 : eratos [3,5..m] where + eratos (p : xs) | p*p>m = p : xs + | True = p : eratos (xs `minus` [p*p, p*p+2*p..m]) -_Y g = g (_Y g) -- non-sharing multistage fixpoint combinator --- = let x = g x in g x -- sharing two-stage fixpoint combinator - -union a@(x:xs) b@(y:ys) = case compare x y of - LT -> x : union xs b - EQ -> x : union xs ys - GT -> y : union a ys +minus a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : minus xs b + EQ -> minus xs ys + GT -> minus a ys +minus a b = a diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs index 6d00fb4d1b..48431cbef8 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs @@ -1,11 +1,10 @@ -primes :: [Integer] -primes = 2 : _Y g - where - g xs = 3 : gaps 5 (unionAll [[p*p, p*p+2*p..] | p <- xs]) +primes = _Y $ ((2:) . minus [3..] + . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) -gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- [k,k+2..]`minus`s, k<=x - | otherwise = gaps (k+2) xs -- && null(s`minus`[k,k+2..]) +_Y g = g (_Y g) -- non-sharing multistage fixpoint combinator +-- = let x = g x in g x -- sharing two-stage fixpoint combinator -unionAll ((x:xs):t) = x : (union xs . unionAll . pairs) t - where - pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t +union a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : union xs b + EQ -> x : union xs ys + GT -> y : union a ys diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs new file mode 100644 index 0000000000..ec753807e2 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs @@ -0,0 +1,9 @@ +primes :: [Int] +primes = 2 : _Y ((3 :) . gaps 5 . _U . map(\p-> [p*p, p*p+2*p..])) + +gaps k s@(x:xs) | k < x = k : gaps (k+2) s -- ~= ([k,k+2..] \\ s), when + | otherwise = gaps (k+2) xs -- k<=x && null(s \\ [k,k+2..]) + +_U ((x:xs):t) = x : (union xs . _U . pairs) t -- ~= nub . sort . concat + where + pairs (xs:ys:t) = union xs ys : pairs t diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl new file mode 100644 index 0000000000..73dff3b16f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl @@ -0,0 +1,106 @@ +use strict; +use warnings; +package Tie::SieveOfEratosthenes; + +sub TIEARRAY { + my $class = shift; + bless \$class, $class; +} + +# If set to true, produces copious output. Observing this output +# is an excellent way to gain insight into how the algorithm works. +use constant DEBUG => 0; + +# If set to true, causes the code to skip over even numbers, +# improving runtime. It does not alter the output content, only the speed. +use constant WHEEL2 => 0; + +BEGIN { + + # This is loosely based on the Python implementation of this task, + # specifically the "Infinite generator with a faster algorithm" + + my @primes = (2, 3); + my $ps = WHEEL2 ? 1 : 0; + my $p = $primes[$ps]; + my $q = $p*$p; + my $incr = WHEEL2 ? 2 : 1; + my $candidate = $primes[-1] + $incr; + my %sieve; + + print "Initial: p = $p, q = $q, candidate = $candidate\n" if DEBUG; + + sub FETCH { + my $n = pop; + return if $n < 0; + return $primes[$n] if $n <= $#primes; + OUTER: while( 1 ) { + + # each key in %sieve is a composite number between + # p and p-squared. Each value in %sieve is $incr x the prime + # which acted as a 'seed' for that key. We use the value + # to step through multiples of the seed-prime, until we find + # an empty slot in %sieve. + while( my $s = delete $sieve{$candidate} ) { + print "$candidate a multiple of ".($s/$incr).";\t\t" if DEBUG; + my $composite = $candidate + $s; + $composite += $s while exists $sieve{$composite}; + print "The next stored multiple of ".($s/$incr)." is $composite\n" if DEBUG; + $sieve{$composite} = $s; + $candidate += $incr; + } + + print "Candidate $candidate is not in sieve\n" if DEBUG; + + while( $candidate < $q ) { + print "$candidate is prime\n" if DEBUG; + push @primes, $candidate; + $candidate += $incr; + next OUTER if exists $sieve{$candidate}; + } + + die "Candidate = $candidate, p = $p, q = $q" if $candidate > $q; + print "Candidate $candidate is equal to $p squared;\t" if DEBUG; + + # Thus, it is now time to add p to the sieve, + my $step = $incr * $p; + my $composite = $q + $step; + $composite += $step while exists $sieve{$composite}; + print "The next multiple of $p is $composite\n" if DEBUG; + $sieve{$composite} = $step; + + # and fetch out a new value for p from our primes array. + $p = $primes[++$ps]; + $q = $p * $p; + + # And since $candidate was equal to some prime squared, + # it's obviously composite, and we need to increment it. + $candidate += $incr; + print "p is $p, q is $q, candidate is $candidate\n" if DEBUG; + } continue { + return $primes[$n] if $n <= $#primes; + } + } + +} + +if( !caller ) { + tie my (@prime_list), 'Tie::SieveOfEratosthenes'; + my $limit = $ARGV[0] || 100; + my $line = ""; + for( my $count = 0; $prime_list[$count] < $limit; ++$count ) { + $line .= $prime_list[$count]. ", "; + next if length($line) <= 70; + if( $line =~ tr/,// > 1 ) { + $line =~ s/^(.*,) (.*, )/$2/; + print $1, "\n"; + } else { + print $line, "\n"; + $line = ""; + } + } + $line =~ s/, \z//; + print $line, "\n" if $line; +} + +1; diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro index be0cc99ee3..85f34ef187 100644 --- a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro @@ -1,22 +1,35 @@ -sieve(N, [2|PS]) :- % PS is list of odd primes up to N - retractall(mult(_)), - sieve_O(3,N,PS). +% %sieve( +N, -Primes ) is true if Primes is the list of consecutive primes +% that are less than or equal to N +sieve( N, [2|Rest]) :- + retractall( composite(_) ), + sieve( N, 2, Rest ) -> true. % only one solution -sieve_O(I,N,PS) :- % sieve odds from I up to N to get PS - I =< N, !, I1 is I+2, - ( mult(I) -> sieve_O(I1,N,PS) - ; ( I =< N / I -> - ISq is I*I, DI is 2*I, add_mults(DI,ISq,N) - ; true - ), - PS = [I|T], - sieve_O(I1,N,T) - ). -sieve_O(I,N,[]) :- I > N. +% sieve P, find the next non-prime, and then recurse: +sieve( N, P, [I|Rest] ) :- + sieve_once(P, N), + (P = 2 -> P2 is P+1; P2 is P+2), + between(P2, N, I), + (composite(I) -> fail; sieve( N, I, Rest )). -add_mults(DI,I,N) :- - I =< N, !, - ( mult(I) -> true ; assert(mult(I)) ), - I1 is I+DI, - add_mults(DI,I1,N). -add_mults(_,I,N) :- I > N. +% It is OK if there are no more primes less than or equal to N: +sieve( N, P, [] ). + +sieve_once(P, N) :- + forall( between(P, N, P, IP), + (composite(IP) -> true ; assertz( composite(IP) )) ). + + +% To avoid division, we use the iterator +% between(+Min, +Max, +By, -I) +% where we assume that By > 0 +% This is like "for(I=Min; I <= Max; I+=By)" in C. +between(Min, Max, By, I) :- + Min =< Max, + A is Min + By, + (I = Min; between(A, Max, By, I) ). + + +% Some Prolog implementations require the dynamic predicates be +% declared: + +:- dynamic( composite/1 ). diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro index 3405beff59..20589c0335 100644 --- a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro @@ -1,26 +1,7 @@ -?- use_module(library(heaps)). +% SWI-Prolog: -prime(2). -prime(N) :- prime_heap(N, _). - -prime_heap(3, H) :- list_to_heap([9-6], H). -prime_heap(N, H) :- - prime_heap(M, H0), N0 is M + 2, - next_prime(N0, H0, N, H). - -next_prime(N0, H0, N, H) :- - \+ min_of_heap(H0, N0, _), - N = N0, Composite is N*N, Skip is N+N, - add_to_heap(H0, Composite, Skip, H). -next_prime(N0, H0, N, H) :- - min_of_heap(H0, N0, _), - adjust_heap(H0, N0, H1), N1 is N0 + 2, - next_prime(N1, H1, N, H). - -adjust_heap(H0, N, H) :- - min_of_heap(H0, N, _), - get_from_heap(H0, N, Skip, H1), - Composite is N + Skip, add_to_heap(H1, Composite, Skip, H2), - adjust_heap(H2, N, H). -adjust_heap(H, N, H) :- - \+ min_of_heap(H, N, _). +?- time( (sieve(100000,P), length(P,N), writeln(N), last(P, LP), writeln(LP) )). +% 1,323,159 inferences, 0.862 CPU in 0.921 seconds (94% CPU, 1534724 Lips) +P = [2, 3, 5, 7, 11, 13, 17, 19, 23|...], +N = 9592, +LP = 99991. diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro new file mode 100644 index 0000000000..be0cc99ee3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro @@ -0,0 +1,22 @@ +sieve(N, [2|PS]) :- % PS is list of odd primes up to N + retractall(mult(_)), + sieve_O(3,N,PS). + +sieve_O(I,N,PS) :- % sieve odds from I up to N to get PS + I =< N, !, I1 is I+2, + ( mult(I) -> sieve_O(I1,N,PS) + ; ( I =< N / I -> + ISq is I*I, DI is 2*I, add_mults(DI,ISq,N) + ; true + ), + PS = [I|T], + sieve_O(I1,N,T) + ). +sieve_O(I,N,[]) :- I > N. + +add_mults(DI,I,N) :- + I =< N, !, + ( mult(I) -> true ; assert(mult(I)) ), + I1 is I+DI, + add_mults(DI,I1,N). +add_mults(_,I,N) :- I > N. diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro new file mode 100644 index 0000000000..3405beff59 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro @@ -0,0 +1,26 @@ +?- use_module(library(heaps)). + +prime(2). +prime(N) :- prime_heap(N, _). + +prime_heap(3, H) :- list_to_heap([9-6], H). +prime_heap(N, H) :- + prime_heap(M, H0), N0 is M + 2, + next_prime(N0, H0, N, H). + +next_prime(N0, H0, N, H) :- + \+ min_of_heap(H0, N0, _), + N = N0, Composite is N*N, Skip is N+N, + add_to_heap(H0, Composite, Skip, H). +next_prime(N0, H0, N, H) :- + min_of_heap(H0, N0, _), + adjust_heap(H0, N0, H1), N1 is N0 + 2, + next_prime(N1, H1, N, H). + +adjust_heap(H0, N, H) :- + min_of_heap(H0, N, _), + get_from_heap(H0, N, Skip, H1), + Composite is N + Skip, add_to_heap(H1, Composite, Skip, H2), + adjust_heap(H2, N, H). +adjust_heap(H, N, H) :- + \+ min_of_heap(H, N, _). diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py index e5ff7b8cce..428f0fe486 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py @@ -3,7 +3,6 @@ def eratosthenes(n): for i in xrange(2, n+1): if i not in multiples: print i - for j in xrange(i*i, n+1, i): - multiples.append(j) + multiples.extend(xrange(i*i, n+1, i)) eratosthenes(100) diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx index f62971cfdc..be54767a5d 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx @@ -2,11 +2,14 @@ parse arg H .; if H=='' then H=200 /*high# can be specified on C.L. */ tell=h>0; H=abs(H); w=length(H) /*neg H suppresses prime listing.*/ if 2<=H & tell then say right(1,w+20)'st prime ───► ' right(2,w) +skip=0 /*skips top part sieve striking. */ @.=1 /*assume all numbers are prime. */ #=1 /*number of primes found so far. */ do j=3 by 2 to H /*odd integers up to H inclusive.*/ if @.j then do; #=#+1 /*Prime? Then bump prime counter*/ if tell then say right(#,w+20)th(#) 'prime ───► ' right(j,w) + if skip then iterate /*should the top part be skipped?*/ + if j*j>H then skip=1 /*indicate skipping if j > √ H. */ do m=j*j to H by j+j; @.m=0; end /*odd multiples.*/ end /*plain*/ /*[↑] strike odd multiples ¬prime*/ end /*j*/ diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx index d62b58ae9a..aa9d70aab9 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx @@ -2,11 +2,15 @@ parse arg H .; if H=='' then H=200 /*high# can be specified on C.L. */ w=length(H); prime=right('prime',20) /*W is used for formatting output*/ if 2<=H then say prime right(1,w) " ───► " right(2,w) +skip=0 /*skips top part sieve striking. */ @.=1 /*assume all numbers are prime. */ #=1 /*number of primes found so far. */ - do j=3 by 2 to H /*odd integers up to H inclusive.*/ - if @.j then do; #=#+1 /*Prime? Then bump prime counter*/ - do m=j*j to H by j+j; @.m=0; end /*odd multiples.*/ - end /*plain*/ /*[↑] strike odd multiples ¬prime*/ - end /*j*/ + do j=3 by 2 to H /*odd integers up to H inclusive.*/ + if @.j then do; #=#+1 /*Prime? Then bump prime counter*/ + say prime right(#,w) " ───► " right(j,w) /*show.*/ + if skip then iterate /*should the top part be skipped?*/ + if j*j>H then skip=1 /*indicate skipping if j > √ H. */ + do m=j*j to H by j+j; @.m=0; end /*odd multiples.*/ + end /*plain*/ /*[↑] strike odd multiples ¬prime*/ + end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala index f29caef557..ea512ca99b 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala @@ -1,10 +1,10 @@ def sieveOfEratosthenes(nTo: Int) = { - val primes = collection.mutable.BitSet.empty.par ++ (2 to nTo) + val primes = collection.mutable.BitSet.empty.par ++ (2 +: (3 to nTo by 2)) for { - candidate <- 2 until Math.sqrt(nTo).toInt + candidate <- 3 until Math.sqrt(nTo).toInt if primes contains candidate } primes --= candidate * candidate to nTo by candidate primes } -// An effect of parallel processing cause the result is shuffled. +// BitSet toList is shuffled. println(sieveOfEratosthenes(101).toList.sorted) diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala index 354793b6a6..11c3d3277c 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala @@ -2,7 +2,7 @@ import scala.language.postfixOps def sieve(nums: Stream[Int]): Stream[Int] = Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) - val primes = sieve(2 #:: Stream.from(3, 2)) + val primes = 2 #:: sieve(Stream.from(3, 2)) println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) diff --git a/Task/Simple-database/C/simple-database.c b/Task/Simple-database/C/simple-database.c index 4d2894e353..10fc933f0a 100644 --- a/Task/Simple-database/C/simple-database.c +++ b/Task/Simple-database/C/simple-database.c @@ -28,7 +28,7 @@ static time_t str2time (char *date); /* qsort callbacks */ sort_by(last_name); sort_by(title); -static sort by_date; +static int by_date(pdb_t *p1, pdb_t *p2); /* main */ int main (int argc, char **argv) { char buf[100]; @@ -76,7 +76,7 @@ usage: printf ("Usage: %s [commands]\n" case DATE: printf ("-d Print all entries sorted by date.\n"); dblist = dao (READ,f,&db,NULL); - dblist = dao (SORT,f,dblist,by_date); + dblist = dao (SORT,f,dblist,(int (*)(const void *,const void *)) by_date); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; @@ -155,7 +155,7 @@ static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) { } qsort (pdb,i,sizeof in_db,sortby); pdb[i-1]->next=NULL; - for (;i;i--) { + for (i=i-1;i;i--) { pdb[i-1]->next=pdb[i]; } rec=pdb[0]; diff --git a/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m index f7a6f90a2f..544198065c 100644 --- a/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m +++ b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m @@ -3,9 +3,9 @@ @interface ClickMe : NSWindow { - NSButton *button; - NSTextField *text; - int counter; + NSButton *_button; + NSTextField *_text; + int _counter; } - (void)applicationDidFinishLaunching: (NSNotification *)notification; - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification; diff --git a/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m index fdc6b77723..47c35efb50 100644 --- a/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m +++ b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m @@ -1,19 +1,15 @@ @implementation ClickMe : NSWindow --(id) init +-(instancetype) init { - NSRect buttonRect; - int totalWindowHeight; - - counter = 0; - button = [[NSButton alloc] init]; + NSButton *button = [[NSButton alloc] init]; [button setButtonType: NSToggleButton]; [button setTitle: @"Click Me"]; [button sizeToFit]; [button setTarget: self]; [button setAction: @selector(advanceCounter:)]; - buttonRect = [button frame]; + NSRect buttonRect = [button frame]; - text = [[NSTextField alloc] + NSTextField *text = [[NSTextField alloc] initWithFrame: NSMakeRect(buttonRect.origin.x, buttonRect.size.height, buttonRect.size.width, buttonRect.size.height)]; [text setAlignment: NSCenterTextAlignment]; @@ -25,32 +21,27 @@ [button setFrameSize: NSMakeSize( [text frame].size.width, buttonRect.size.height ) ]; - totalWindowHeight = buttonRect.size.height + [text frame].size.height; + int totalWindowHeight = buttonRect.size.height + [text frame].size.height; - [self - initWithContentRect: NSMakeRect(100, 100, + if ((self = [super initWithContentRect: NSMakeRect(100, 100, [text frame].size.width, totalWindowHeight) - styleMask: (NSTitledWindowMask | NSClosableWindowMask) - backing: NSBackingStoreBuffered - defer: NO]; + styleMask: (NSTitledWindowMask | NSClosableWindowMask) + backing: NSBackingStoreBuffered + defer: NO])) { + _counter = 0; + _button = button; + _text = text; - [[self contentView] addSubview: text]; [text release]; - [[self contentView] addSubview: button]; [button release]; - - [self setTitle: @"Click Me!"]; - [self center]; + [[self contentView] addSubview: _text]; + [[self contentView] addSubview: _button]; + [self setTitle: @"Click Me!"]; + [self center]; + } return self; } --(void) dealloc -{ - [button release]; - [text release]; - [super dealloc]; -} - - (void)applicationDidFinishLaunching: (NSNotification *)notification { [self orderFront: self]; @@ -63,24 +54,18 @@ - (void)advanceCounter: (id)sender { - counter++; - [text setStringValue: [NSString stringWithFormat: @"Clicked %d times", counter]]; + [_text setStringValue: [NSString stringWithFormat: @"Clicked %d times", ++_counter]]; } @end int main() { - ClickMe *clickme; - NSAutoreleasePool *pool; - NSApplication *app; - - pool = [[NSAutoreleasePool alloc] init]; - app = [NSApplication sharedApplication]; - clickme = [[ClickMe alloc] init]; - [app setDelegate: clickme]; - [app run]; - [clickme release]; - [pool release]; + @autoreleasepool { + NSApplication *app = [NSApplication sharedApplication]; + ClickMe *clickme = [[ClickMe alloc] init]; + [app setDelegate: clickme]; + [app run]; + } return 0; } diff --git a/Task/Singleton/Perl-6/singleton.pl6 b/Task/Singleton/Perl-6/singleton.pl6 index b14e1c13c9..939ea54eb3 100644 --- a/Task/Singleton/Perl-6/singleton.pl6 +++ b/Task/Singleton/Perl-6/singleton.pl6 @@ -1,6 +1,6 @@ class Singleton { # We create a lexical variable in the class block that holds our single instance. - my Singleton $instance = Singleton.bless(*); # You can add initialization arguments here. + my Singleton $instance = Singleton.bless; # You can add initialization arguments here. method new {!!!} # Singleton.new dies. method instance { $instance; } } diff --git a/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m b/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m index 6f6122936a..818e885922 100644 --- a/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m +++ b/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m @@ -1,11 +1,10 @@ -#import +#import -@interface RCListElement : Object +@interface RCListElement : NSObject { RCListElement *next; id datum; } -+ (RCListElement *)new; - (RCListElement *)next; - (id)datum; - (RCListElement *)setNext: (RCListElement *)nx; @@ -13,13 +12,6 @@ @end @implementation RCListElement -+ (RCListElement *)new -{ - RCListElement *m = [super new]; - [m setNext: nil]; - [m setDatum: nil]; - return m; -} - (RCListElement *)next { return next; diff --git a/Task/Sleep/Maple/sleep.maple b/Task/Sleep/Maple/sleep.maple new file mode 100644 index 0000000000..b0ca13e21f --- /dev/null +++ b/Task/Sleep/Maple/sleep.maple @@ -0,0 +1,5 @@ +sleep := proc(secs) + print("Sleeping..."); + Threads:-Sleep(secs); + print("Awake!"); + end proc: diff --git a/Task/Sleep/Objective-C/sleep.m b/Task/Sleep/Objective-C/sleep.m index b5eb337822..259b8e5f19 100644 --- a/Task/Sleep/Objective-C/sleep.m +++ b/Task/Sleep/Objective-C/sleep.m @@ -2,16 +2,16 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSTimeInterval sleeptime; + @autoreleasepool { - printf("wait time in seconds: "); - scanf("%f", &sleeptime); + NSTimeInterval sleeptime; + printf("wait time in seconds: "); + scanf("%f", &sleeptime); - NSLog(@"sleeping..."); - [NSThread sleepForTimeInterval: sleeptime]; - NSLog(@"awakening..."); + NSLog(@"sleeping..."); + [NSThread sleepForTimeInterval: sleeptime]; + NSLog(@"awakening..."); - [pool release]; + } return 0; } diff --git a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d index 0bf6486c89..a908d6971e 100644 --- a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d +++ b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d @@ -33,19 +33,19 @@ struct Hidato { cell == Hidato.unknownCell || (cell >= 1 && cell <= size)); if (cell > 0) - assert(i == known[cast(size_t)cell]); + assert(i == known[size_t(cell)]); } } body { bool[Cell] pathSeen; // A set. - /*immutable*/ const lines = input.splitLines; + immutable lines = input.splitLines; this.nRows = lines.length; this.nCols = lines[0].split.length; immutable size = nCols * nRows; - this.board = new typeof(this.board[0])[size]; + this.board.length = size; this.board[] = emptyCell; - this.known = new typeof(this.known[0])[size + 1]; - this.flood = new typeof(this.flood[0])[size]; + this.known.length = size + 1; + this.flood.length = size; auto boardMaxMutable = Cell.min; Pos i = 0; diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb index 6010baeaa0..964737282b 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb @@ -3,7 +3,6 @@ # Nigel_Galloway # May 5th., 2012. class Cell - def self.[](*args) self.new(*args) end def initialize(row=0, col=0, value=nil) @adj = [[row-1,col-1],[row,col-1],[row+1,col-1],[row-1,col],[row+1,col],[row-1,col+1],[row,col+1],[row+1,col+1]] @t = false @@ -27,3 +26,40 @@ class Cell end attr_reader :value end + +class Hidato + def initialize(board, pout=true) + $end = 0 + $zbl = [] + $board = [] + board.each_line.with_index do |line, x| + $board << line.split.each_with_index.map do |n,y| + begin + n = Integer(n) + @sx, @sy = x, y if n == 1 # start position + $end += 1 + Cell.new(x, y, n) + rescue + Cell.new # frame (Sentinel value) + end + end + end + @xmax = $board.size - 2 + @ymax = $board[1].size - 2 + printout('Problem:') if pout + end + def solve + if $board[@sx][@sy].try(1) + printout('Solution:') + else + puts "no solution" + end + end + def printout(msg=nil) + puts msg if msg + (1..@xmax).each do |x| + puts (1..@ymax).map{|y| "%3s" % $board[x][y].value}.join + end + puts + end +end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb index 3a622b83f2..675ade4603 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb @@ -1,15 +1,36 @@ -require 'benchmark' +# Which may be used as follows to solve Evil Case 1: +board1 = < $end + return false if @t + return false if @value > 0 and @value != value + return false if @value == 0 and $zbl[value] + @t = true + h = Hash.new + @adj.each_with_index do |(x,y), n| + cell = $board[x][y] + h[cell.wdof*10+n] = cell if cell.value + end + h.sort.each do |key, cell| + if (cell.try(value+1)) + @value = value + return true + end + end + @t = false + end + def wdon + (@value.nil? or @value > 0 or @t) ? 0 : 1 + end + def wdof + @adj.inject(0){|res, (x,y)| res += $board[x][y].wdon} + end + attr_reader :value +end diff --git a/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m b/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m index 30111a0286..0559eb5cb2 100644 --- a/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m +++ b/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m @@ -2,28 +2,23 @@ NSString *name; NSString *value; } -+(id)pairWithName:(NSString *)n value:(NSString *)v; --(id)initWithName:(NSString *)n value:(NSString *)v; ++(instancetype)pairWithName:(NSString *)n value:(NSString *)v; +-(instancetype)initWithName:(NSString *)n value:(NSString *)v; -(NSString *)name; -(NSString *)value; @end @implementation Pair -+(id)pairWithName:(NSString *)n value:(NSString *)v { - return [[[self alloc] initWithName:n value:v] autorelease]; ++(instancetype)pairWithName:(NSString *)n value:(NSString *)v { + return [[self alloc] initWithName:n value:v]; } --(id)initWithName:(NSString *)n value:(NSString *)v { +-(instancetype)initWithName:(NSString *)n value:(NSString *)v { if ((self = [super init])) { - name = [n retain]; - value = [v retain]; + name = n; + value = v; } return self; } --(void)dealloc { - [name release]; - [value release]; - [super dealloc]; -} -(NSString *)name { return name; } -(NSString *)value { return value; } -(NSString *)description { @@ -32,9 +27,9 @@ @end int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSArray *pairs = [NSArray arrayWithObjects: + NSArray *pairs = @[ [Pair pairWithName:@"06-07" value:@"Ducks"], [Pair pairWithName:@"00-01" value:@"Avalanche"], [Pair pairWithName:@"02-03" value:@"Devils"], @@ -44,21 +39,17 @@ int main() { [Pair pairWithName:@"05-06" value:@"Hurricanes"], [Pair pairWithName:@"99-00" value:@"Devils"], [Pair pairWithName:@"07-08" value:@"Red Wings"], - [Pair pairWithName:@"08-09" value:@"Penguins"], - nil]; + [Pair pairWithName:@"08-09" value:@"Penguins"]]; - // optional 3rd arg: you can also specify a selector to compare the keys - NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; + // optional 3rd arg: you can also specify a selector to compare the keys + NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; - // it takes an array of sort descriptors, and it will be ordered by the - // first one, then if it's a tie by the second one, etc. - NSArray *sorted = [pairs sortedArrayUsingDescriptors: - [NSArray arrayWithObject:sd]]; - NSLog(@"%@", sorted); + // it takes an array of sort descriptors, and it will be ordered by the + // first one, then if it's a tie by the second one, etc. + NSArray *sorted = [pairs sortedArrayUsingDescriptors:@[sd]]; + NSLog(@"%@", sorted); - [sd release]; - - [pool release]; + } return 0; } diff --git a/Task/Sort-an-integer-array/Maple/sort-an-integer-array.maple b/Task/Sort-an-integer-array/Maple/sort-an-integer-array.maple new file mode 100644 index 0000000000..73df928865 --- /dev/null +++ b/Task/Sort-an-integer-array/Maple/sort-an-integer-array.maple @@ -0,0 +1,2 @@ +sort([5,7,8,3,6,1]); +sort(Array([5,7,8,3,6,1])) diff --git a/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m b/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m index 4a7c636f01..5b8f2eb226 100644 --- a/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m +++ b/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m @@ -1,12 +1,2 @@ -- (void)example -{ - NSArray *nums, *sorted; - nums = [NSArray arrayWithObjects: - [NSNumber numberWithInt:2], - [NSNumber numberWithInt:4], - [NSNumber numberWithInt:3], - [NSNumber numberWithInt:1], - [NSNumber numberWithInt:2], - nil]; - sorted = [nums sortedArrayUsingSelector:@selector(compare:)]; -} +NSArray *nums = @[@2, @4, @3, @1, @2]; +NSArray *sorted = [nums sortedArrayUsingSelector:@selector(compare:)]; diff --git a/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m b/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m index 4b8dd6c7c7..8ae1602586 100644 --- a/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m +++ b/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m @@ -5,13 +5,13 @@ int *indexes; int num_indexes; } -- (id)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind; +- (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind; @end @implementation DisjointSublistView -- (id)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind { +- (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind { if ((self = [super init])) { - array = [a retain]; + array = a; num_indexes = [ind count]; indexes = malloc(num_indexes * sizeof(int)); for (NSUInteger i = [ind firstIndex], j = 0; i != NSNotFound; i = [ind indexGreaterThanIndex:i], j++) @@ -20,14 +20,11 @@ return self; } - (void)dealloc { - [array release]; free(indexes); - [super dealloc]; } - (NSUInteger)count { return num_indexes; } -- (id)objectAtIndex:(NSUInteger)i { return [array objectAtIndex:indexes[i]]; } -- (void)replaceObjectAtIndex:(NSUInteger)i withObject:(id)x { - return [array replaceObjectAtIndex:indexes[i] withObject:x]; } +- (id)objectAtIndex:(NSUInteger)i { return array[indexes[i]]; } +- (void)replaceObjectAtIndex:(NSUInteger)i withObject:(id)x { array[indexes[i]] = x; } @end @interface NSMutableArray (SortDisjoint) @@ -37,28 +34,18 @@ - (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator { DisjointSublistView *d = [[DisjointSublistView alloc] initWithArray:self andIndexes:indexes]; [d sortUsingSelector:comparator]; - [d release]; } @end int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSMutableArray *a = [NSMutableArray arrayWithObjects: - [NSNumber numberWithInt:7], - [NSNumber numberWithInt:6], - [NSNumber numberWithInt:5], - [NSNumber numberWithInt:4], - [NSNumber numberWithInt:3], - [NSNumber numberWithInt:2], - [NSNumber numberWithInt:1], - [NSNumber numberWithInt:0], - nil]; - NSMutableIndexSet *ind = [NSMutableIndexSet indexSet]; - [ind addIndex:6]; [ind addIndex:1]; [ind addIndex:7]; - [a sortDisjointSublist:ind usingSelector:@selector(compare:)]; - NSLog(@"%@", a); + NSMutableArray *a = [@[@7, @6, @5, @4, @3, @2, @1, @0] mutableCopy]; + NSMutableIndexSet *ind = [NSMutableIndexSet indexSet]; + [ind addIndex:6]; [ind addIndex:1]; [ind addIndex:7]; + [a sortDisjointSublist:ind usingSelector:@selector(compare:)]; + NSLog(@"%@", a); - [pool release]; + } return 0; } diff --git a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m index 2139172286..87cbdd7b97 100644 --- a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m +++ b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m @@ -4,25 +4,25 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSMutableArray *arr = - [NSMutableArray - arrayWithArray: [@"this is a set of strings to sort" - componentsSeparatedByString: @" "] - ]; + NSMutableArray *arr = + [NSMutableArray + arrayWithArray: [@"this is a set of strings to sort" + componentsSeparatedByString: @" "] + ]; - [arr sortUsingComparator: ^NSComparisonResult(id obj1, id obj2){ - NSComparisonResult l = esign((int)([obj1 length] - [obj2 length])); - return l ? -l // reverse the ordering - : [obj1 caseInsensitiveCompare: obj2]; - }]; + [arr sortUsingComparator: ^NSComparisonResult(id obj1, id obj2){ + NSComparisonResult l = esign((int)([obj1 length] - [obj2 length])); + return l ? -l // reverse the ordering + : [obj1 caseInsensitiveCompare: obj2]; + }]; + + for( NSString *str in arr ) + { + NSLog(@"%@", str); + } - for( NSString *str in arr ) - { - NSLog(@"%@", str); } - - [pool release]; return EXIT_SUCCESS; } diff --git a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m index 7f785c63d6..5fe3f7c30b 100644 --- a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m +++ b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m @@ -16,23 +16,21 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSMutableArray *arr = - [NSMutableArray - arrayWithArray: [@"this is a set of strings to sort" - componentsSeparatedByString: @" "] - ]; + NSMutableArray *arr = + [NSMutableArray + arrayWithArray: [@"this is a set of strings to sort" + componentsSeparatedByString: @" "] + ]; - [arr sortUsingSelector: @selector(my_compare:)]; + [arr sortUsingSelector: @selector(my_compare:)]; + + for ( NSString *str in arr ) + { + NSLog(@"%@", str); + } - NSEnumerator *iter = [arr objectEnumerator]; - NSString *str; - while( (str = [iter nextObject]) != nil ) - { - NSLog(@"%@", str); } - - [pool release]; return EXIT_SUCCESS; } diff --git a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m index 788f0774db..c3c120e68c 100644 --- a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m +++ b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m @@ -2,21 +2,17 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - NSArray *strings = [@"Here are some sample strings to be sorted" componentsSeparatedByString:@" "]; + NSArray *strings = [@"Here are some sample strings to be sorted" componentsSeparatedByString:@" "]; - NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO]; - NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"lowercaseString" ascending:YES]; + NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO]; + NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"lowercaseString" ascending:YES]; - NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil]; - [sd1 release]; - [sd2 release]; + NSArray *sorted = [strings sortedArrayUsingDescriptors:@[sd1, sd2]]; + NSLog(@"%@", sorted); - NSArray *sorted = [strings sortedArrayUsingDescriptors:sortDescriptors]; - NSLog(@"%@", sorted); - - [pool release]; + } return 0; } diff --git a/Task/Sorting-algorithms-Bead-sort/AutoHotkey/sorting-algorithms-bead-sort-1.ahk b/Task/Sorting-algorithms-Bead-sort/AutoHotkey/sorting-algorithms-bead-sort-1.ahk new file mode 100644 index 0000000000..dd0d4bd60c --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/AutoHotkey/sorting-algorithms-bead-sort-1.ahk @@ -0,0 +1,24 @@ +BeadSort(data){ + Pole:=[] , TempObj:=[], Result:=[] + for, i, v in data { + Row := i + loop, % v + MaxPole := MaxPole>A_Index?MaxPole:A_Index , Pole[A_Index, row] := 1 + } + + for i , obj in Pole { + TempVar:=0 , c := A_Index + for n, v in obj + TempVar += v + loop, % TempVar + TempObj[c, A_Index] := 1 + } + + loop, % Row { + TempVar:=0 , c := A_Index + Loop, % MaxPole + TempVar += TempObj[A_Index,c] + Result[c] := TempVar + } + return Result +} diff --git a/Task/Sorting-algorithms-Bead-sort/AutoHotkey/sorting-algorithms-bead-sort-2.ahk b/Task/Sorting-algorithms-Bead-sort/AutoHotkey/sorting-algorithms-bead-sort-2.ahk new file mode 100644 index 0000000000..32c2d278df --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/AutoHotkey/sorting-algorithms-bead-sort-2.ahk @@ -0,0 +1,3 @@ +for i, val in BeadSort([54,12,87,56,36]) + res := val (res?",":"") res +MsgBox % res diff --git a/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj b/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj index 1daa5d308f..9907626063 100644 --- a/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj +++ b/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj @@ -1,14 +1,15 @@ (defn transpose [xs] - (loop [transposed [], remaining xs] - (if (empty? remaining) - transposed - (recur - (conj transposed (map #(first %) remaining)) - (filter #(not-empty %) (map #(rest %) remaining)))) )) + (loop [ret [], remain xs] + (if (empty? remain) + ret + (recur (conj ret (map first remain)) + (filter not-empty (map rest remain)))))) (defn bead-sort [xs] - (map #(reduce + %) - (transpose - (transpose (map #(replicate % 1) xs))))) + (->> xs + (map #(repeat 1 %)) + transpose + transpose + (map #(reduce + %)))) -(println (bead-sort [5 2 4 1 3 3 9])) +(-> [5 2 4 1 3 3 9] bead-sort println) diff --git a/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin b/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin new file mode 100644 index 0000000000..7b472a63fb --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin @@ -0,0 +1,14 @@ +fun bubbleSort(a : Array, c: Comparator) { + var changed : Boolean + do { + changed = false + for (i in 0 .. a.size - 2) { + if (c.compare(a[i], a[i + 1]) > 0) { + val tmp = a[i] + a[i] = a[i + 1] + a[i + 1] = tmp + changed = true + } + } + } while (changed) +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Seed7/sorting-algorithms-cocktail-sort.seed7 b/Task/Sorting-algorithms-Cocktail-sort/Seed7/sorting-algorithms-cocktail-sort.seed7 new file mode 100644 index 0000000000..7d044c6841 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Seed7/sorting-algorithms-cocktail-sort.seed7 @@ -0,0 +1,29 @@ +const proc: cocktailSort (inout array elemType: arr) is func + local + var boolean: swapped is FALSE; + var integer: i is 0; + var elemType: help is elemType.value; + begin + repeat + swapped := FALSE; + for i range 1 to length(arr) - 1 do + if arr[i] > arr[i + 1] then + help := arr[i]; + arr[i] := arr[i + 1]; + arr[i + 1] := help; + swapped := TRUE; + end if; + end for; + if swapped then + swapped := FALSE; + for i range length(arr) - 1 downto 1 do + if arr[i] > arr[i + 1] then + help := arr[i]; + arr[i] := arr[i + 1]; + arr[i + 1] := help; + swapped := TRUE; + end if; + end for; + end if; + until not swapped; + end func; diff --git a/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb b/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb index 93a4a63f84..e3372fbd37 100644 --- a/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb +++ b/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb @@ -1,21 +1,13 @@ class Array - def counting_sort - dup.counting_sort! + def counting_sort! + replace counting_sort end - def counting_sort! + def counting_sort min, max = minmax count = Array.new(max - min + 1, 0) each {|number| count[number - min] += 1} - z = 0 - min.upto(max) do |i| - while count[i - min] > 0 - self[z] = i - z += 1 - count[i - min] -= 1 - end - end - self + (min..max).each_with_object([]) {|i, ary| count[i - min].times {ary << i}} end end diff --git a/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust b/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust new file mode 100644 index 0000000000..66a7aa1b12 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust @@ -0,0 +1,9 @@ +fn insertion_sort(arr: &mut [T]) { + for i in range(1, arr.len()) { + let mut j = i; + while (j > 0 && arr[j] < arr[j-1]) { + arr.swap(j, j-1); + j = j-1; + } + } +} diff --git a/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury b/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury index e1e40f0f7b..ef422ad1a1 100644 --- a/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury +++ b/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury @@ -1,7 +1,20 @@ +:- module merge_sort. + +:- interface. + +:- import_module list. + +:- type split_error ---> split_error. + :- func merge_sort(list(T)) = list(T). +:- pred merge_sort(list(T)::in, list(T)::out) is det. + +:- implementation. + +:- import_module int, exception. + merge_sort(U) = S :- merge_sort(U, S). -:- pred merge_sort(list(T)::in, list(T)::out) is det. merge_sort(U, S) :- merge_sort(list.length(U), U, S). :- pred merge_sort(int::in, list(T)::in, list(T)::out) is det. @@ -11,7 +24,7 @@ merge_sort(L, U, S) :- ( split(H, U, F, B) -> merge_sort(H, F, SF), merge_sort(L - H, B, SB), - merge(SF, SB, S) + merge_sort.merge(SF, SB, S) ; throw(split_error) ) ; S = U ). @@ -26,8 +39,8 @@ merge([], [], []). merge([X|Xs], [], [X|Xs]). merge([], [Y|Ys], [Y|Ys]). merge([X|Xs], [Y|Ys], M) :- - ( compare(>, A, B) -> - merge([X|Xs], Ys, M0), - C = [Y|C0] - ; merge(Xs, [Y|Ys], C0), - C = [X|C0] ). + ( compare(>, X, Y) -> + merge_sort.merge([X|Xs], Ys, M0), + M = [Y|M0] + ; merge_sort.merge(Xs, [Y|Ys], M0), + M = [X|M0] ). diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada index 20f410a28b..783d8b56ce 100644 --- a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada @@ -33,9 +33,10 @@ begin end loop; exit when Left >= Right; Swap(Item(Left), Item(Right)); - if Left < Item'Last and Right > Item'First then - Left := Index_Type'Succ(Left); - Right := Index_Type'Pred(Right); + if Pivot_Index = Left then + Pivot_Index := Right; + elsif Pivot_Index = Right then + Pivot_Index := Left; end if; end loop; if Right > Item'First then diff --git a/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort-1.ahk b/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort-1.ahk new file mode 100644 index 0000000000..d1a79b9c42 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort-1.ahk @@ -0,0 +1,29 @@ +a := [4, 65, 2, -31, 0, 99, 83, 782, 7] +for k, v in QuickSort(a) + Out .= "," v +MsgBox, % SubStr(Out, 2) +return + +QuickSort(a) +{ + if (a.MaxIndex() <= 1) + return a + Less := [], Same := [], More := [] + Pivot := a[1] + for k, v in a + { + if (v < Pivot) + less.Insert(v) + else if (v > Pivot) + more.Insert(v) + else + same.Insert(v) + } + Less := QuickSort(Less) + Out := QuickSort(More) + if (Same.MaxIndex()) + Out.Insert(1, Same*) ; insert all values of same at index 1 + if (Less.MaxIndex()) + Out.Insert(1, Less*) ; insert all values of less at index 1 + return Out +} diff --git a/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort.ahk b/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort-2.ahk similarity index 100% rename from Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort.ahk rename to Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort-2.ahk diff --git a/Task/Sorting-algorithms-Quicksort/Bracmat/sorting-algorithms-quicksort.bracmat b/Task/Sorting-algorithms-Quicksort/Bracmat/sorting-algorithms-quicksort.bracmat new file mode 100644 index 0000000000..000b8a55f3 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Bracmat/sorting-algorithms-quicksort.bracmat @@ -0,0 +1,19 @@ +( ( Q + = Less Greater Equal pivot element + . !arg:%(?pivot:?Equal) %?arg + & :?Less:?Greater + & whl + ' ( !arg:%?element ?arg + & (.!element)+(.!pivot) { BAD: 1900+90 adds to 1990, GOOD: (.1900)+(.90) is sorted to (.90)+(.1900) } + : ( (.!element)+(.!pivot) + & !element !Less:?Less + | (.!pivot)+(.!element) + & !element !Greater:?Greater + | ?&!element !Equal:?Equal + ) + ) + & Q$!Less !Equal Q$!Greater + | !arg + ) +& out$Q$(1900 optimized variants of 4001/2 Quicksort (quick,sort) are (quick,sober) features of 90 languages) +); diff --git a/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort.go b/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort-1.go similarity index 100% rename from Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort.go rename to Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort-1.go diff --git a/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort-2.go b/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort-2.go new file mode 100644 index 0000000000..1c967af75b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort-2.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "sort" + "math/rand" +) + +func partition(a sort.Interface, first int, last int, pivotIndex int) int { + a.Swap(first, pivotIndex) // move it to beginning + left := first+1 + right := last + for left <= right { + for left <= last && a.Less(left, first) { + left++ + } + for right >= first && a.Less(first, right) { + right-- + } + if left <= right { + a.Swap(left, right) + left++ + right-- + } + } + a.Swap(first, right) // swap into right place + return right +} + +func quicksortHelper(a sort.Interface, first int, last int) { + if first >= last { + return + } + pivotIndex := partition(a, first, last, rand.Intn(last - first + 1) + first) + quicksortHelper(a, first, pivotIndex-1) + quicksortHelper(a, pivotIndex+1, last) +} + +func quicksort(a sort.Interface) { + quicksortHelper(a, 0, a.Len()-1) +} + +func main() { + a := []int{1, 3, 5, 7, 9, 8, 6, 4, 2} + fmt.Printf("Unsorted: %v\n", a) + quicksort(sort.IntSlice(a)) + fmt.Printf("Sorted: %v\n", a) + b := []string{"Emil", "Peg", "Helen", "Juergen", "David", "Rick", "Barb", "Mike", "Tom"} + fmt.Printf("Unsorted: %v\n", b) + quicksort(sort.StringSlice(b)) + fmt.Printf("Sorted: %v\n", b) +} diff --git a/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia new file mode 100644 index 0000000000..cacb76baf7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia @@ -0,0 +1,29 @@ +function modes(values) + dict = Dict() # Values => Number of repetitions + modesArray = typeof(values[1])[] # Array of the modes so far + max = 0 # Max of repetitions so far + + for v in values + # Add one to the dict[v] entry (create one if none) + if v in keys(dict) + dict[v] += 1 + else + dict[v] = 1 + end + + # Update modesArray if the number of repetitions + # of v reaches or surpasses the max value + if dict[v] >= max + if dict[v] > max + empty!(modesArray) + max += 1 + end + append!(modesArray, [v]) + end + end + + return modesArray +end + +println(modes([1,3,6,6,6,6,7,7,12,12,17])) +println(modes((1,1,2,4,4))) diff --git a/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort.kotlin b/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort.kotlin new file mode 100644 index 0000000000..6dac161de6 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort.kotlin @@ -0,0 +1,13 @@ +import java.util.Comparator +import java.util.ArrayList + +fun quickSort(a : List, c : Comparator) : ArrayList { + return if (a.size == 0) ArrayList(a) + else { + val boxes = Array>(3, {ArrayList()}) + fun normalise(i : Int) = i / Math.max(1, Math.abs(i)) + a forEach {boxes[normalise(c.compare(it, a[0])) + 1] add(it)} + array(0, 2) forEach {boxes[it] = quickSort(boxes[it], c)} + boxes.flatMapTo(ArrayList()) {it} + } +} diff --git a/Task/Sorting-algorithms-Quicksort/Objective-C/sorting-algorithms-quicksort.m b/Task/Sorting-algorithms-Quicksort/Objective-C/sorting-algorithms-quicksort.m new file mode 100644 index 0000000000..5dcdfa181a --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Objective-C/sorting-algorithms-quicksort.m @@ -0,0 +1,34 @@ +void quicksortInPlace(NSMutableArray *array, NSInteger first, NSInteger last, NSComparator comparator) { + if (first >= last) return; + id pivot = array[(first + last) / 2]; + NSInteger left = first; + NSInteger right = last; + while (left <= right) { + while (comparator(array[left], pivot) == NSOrderedAscending) + left++; + while (comparator(array[right], pivot) == NSOrderedDescending) + right--; + if (left <= right) + [array exchangeObjectAtIndex:left++ withObjectAtIndex:right--]; + } + quicksortInPlace(array, first, right, comparator); + quicksortInPlace(array, left, last, comparator); +} + +NSArray* quicksort(NSArray *unsorted, NSComparator comparator) { + NSMutableArray *a = [NSMutableArray arrayWithArray:unsorted]; + quicksortInPlace(a, 0, a.count - 1, comparator); + return a; +} + +int main(int argc, const char * argv[]) { + @autoreleasepool { + NSArray *a = @[ @1, @3, @5, @7, @9, @8, @6, @4, @2 ]; + NSLog(@"Unsorted: %@", a); + NSLog(@"Sorted: %@", quicksort(a, ^(id x, id y) { return [x compare:y]; })); + NSArray *b = @[ @"Emil", @"Peg", @"Helen", @"Juergen", @"David", @"Rick", @"Barb", @"Mike", @"Tom" ]; + NSLog(@"Unsorted: %@", b); + NSLog(@"Sorted: %@", quicksort(b, ^(id x, id y) { return [x compare:y]; })); + } + return 0; +} diff --git a/Task/Sorting-algorithms-Radix-sort/AutoHotkey/sorting-algorithms-radix-sort-1.ahk b/Task/Sorting-algorithms-Radix-sort/AutoHotkey/sorting-algorithms-radix-sort-1.ahk new file mode 100644 index 0000000000..b3e3e16428 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/AutoHotkey/sorting-algorithms-radix-sort-1.ahk @@ -0,0 +1,13 @@ +Radix_Sort(data){ + loop, parse, data, `, + n := StrLen(A_LoopField)>n?StrLen(A_LoopField):n + loop % n { + bucket := [] , i := A_Index + loop, parse, data, `, + bucket[SubStr(A_LoopField,1-i)] .= (bucket[SubStr(A_LoopField,1-i)]?",":"") A_LoopField + data := "" + for i, v in bucket + data .= (data?",":"") v + } + return data +} diff --git a/Task/Sorting-algorithms-Radix-sort/AutoHotkey/sorting-algorithms-radix-sort-2.ahk b/Task/Sorting-algorithms-Radix-sort/AutoHotkey/sorting-algorithms-radix-sort-2.ahk new file mode 100644 index 0000000000..cfea5c1a75 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/AutoHotkey/sorting-algorithms-radix-sort-2.ahk @@ -0,0 +1,2 @@ +d = 170,45,75,90,802,2,24,66 +MsgBox, 262144, , % Radix_Sort(d) diff --git a/Task/Sorting-algorithms-Radix-sort/Icon/sorting-algorithms-radix-sort.icon b/Task/Sorting-algorithms-Radix-sort/Icon/sorting-algorithms-radix-sort.icon new file mode 100644 index 0000000000..5792f9a21c --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Icon/sorting-algorithms-radix-sort.icon @@ -0,0 +1,14 @@ +procedure main(A) + every writes((!rSort(A)||" ")|"\n") +end + +procedure rSort(A) + every (min := A[1]) >:= !A + every (mlen := *(A[1]-min)) <:= (!A - min) + every i := !*mlen do { + every put(b := [], |[]\12) + every a := !A do put(b[(a-min)[-i]+2|1], a) + every put(A := [],!!b) + } + return A +end diff --git a/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java new file mode 100644 index 0000000000..4d9f5b4f27 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java @@ -0,0 +1,38 @@ +public static int[] sort(int[] old) { + + for(int shift = Integer.SIZE-1; shift > -1; shift--) { //Loop for every bit in the integers + + int[] tmp = new int[old.length]; //the array to put the partially sorted array into + int j = 0; //The number of 0s + + + for(int i = 0; i < old.length; i++) { //Move the 0s to the new array, and the 1s to the old one + + boolean move = old[i] << shift >= 0; //If there is a 1 in the bit we are testing, the number will be negative + + if(shift == 0 ? !move : move) { //If this is the last bit, negative numbers are actually lower + + tmp[j] = old[i]; + j++; + + } else { //It's a 1, so stick it in the old array for now + + old[i-j] = old[i]; + + } + + } + + for(int i = j; i < tmp.length; i++) { //Copy over the 1s from the old array + + tmp[i] = old[i-j]; + + } + + old = tmp; //And now the tmp array gets switched for another round of sorting + + } + + return old; + +} diff --git a/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort.java b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-2.java similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort.java rename to Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-2.java diff --git a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb index 1f2b50944a..d1c46fdb1b 100644 --- a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb +++ b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb @@ -1,15 +1,16 @@ class Array def radix_sort(base=10) ary = dup - rounds = (Math.log(self.max.abs)/Math.log(base)).ceil + rounds = (Math.log(ary.minmax.map(&:abs).max)/Math.log(base)).ceil rounds.times do |i| - buckets = Hash.new {|h,k| h[k] = []} + buckets = Array.new(2*base){[]} + base_i = base**i ary.each do |n| - digit = (n/base**i) % base - digit = digit + base unless n<0 + digit = (n/base_i) % base + digit += base if 0<=n buckets[digit] << n end - ary = buckets.values_at(*(0..2*base)).compact.flatten + ary = buckets.flatten p [i, ary] if $DEBUG end ary diff --git a/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort-1.alg b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort-1.alg new file mode 100644 index 0000000000..dcc9fe9726 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort-1.alg @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- # + +COMMENT + REQUIRES( + MODE SORTELEMENT = mode of element of array to be sorted... + OP < = (SORTELEMENT a, b)BOOL: a < b; + ) +END COMMENT + +MODE SORTELEMENTCMP = PROC(SORTELEMENT,SORTELEMENT)BOOL; + +# create a global sort procedure for convenience # +PROC(SORTELEMENT,SORTELEMENT)BOOL sort cmp default := (SORTELEMENT a, b)BOOL: a < b; +PROC sort cmp rev = (SORTELEMENT a, b)BOOL: NOT sort cmp default(a,b); + +# Alternative gap calculations: # +# ⌊n/2**k⌋; ⌊n/2⌋; Θ(n**2) [when n=2**p]; Donald Shell 1959 # +PROC sort gap shell = (INT k, n)INT: n OVER 2; +# 2 ⌊n/2**(k+1)⌋+1; 2 ⌊n/4⌋+1, ..., 3, 1; Θ(n**(3/2)); Frank & Lazarus, 1960 # +# 2**k-1; 1, 3, 7, 15, 31, 63, ...; Θ(n**(3/2)); Hibbard, 1963 # +# 2**k+1, prefixed with 1; 1, 3, 5, 9, 17, 33, 65, ...; Θ(n**(3/2)); Papernov & Stasevich, 1965 # +# successive numbers of the form 2**p 3**q; 1, 2, 3, 4, 6, 8, 9, 12, ...; Θ(n log**2 n); Pratt 1971 # +# (3**k-1)/2, not greater than ⌈n/3⌉; 1, 4, 13, 40, 121, ...; Θ(n**(3/2)); Knuth 1973 # +# ∏a[q], where r=⌊√(2k+√(2k))⌋ and a[q]=min(n∈𝒩:n≥(5/2)**(q+1) and ∀ p:0≤ p= n | cmp(element, array[i-n]) | FALSE ) DO + array[i] := array[i-n]; + i -:= n + OD; + array[i] := element + OD; + n := sort gap(k,n) + OD; + array +); + +PROC shell sort = ([]SORTELEMENT seq)[]SORTELEMENT: + shell sort in place(LOC[LWB seq: UPB seq]SORTELEMENT:=seq, EMPTY); + +PROC shell sort rev = ([]SORTELEMENT seq)[]SORTELEMENT: + shell sort in place(LOC[LWB seq: UPB seq]SORTELEMENT:=seq, sort cmp rev); + +SKIP diff --git a/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort-2.alg b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort-2.alg new file mode 100644 index 0000000000..009cb31355 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort-2.alg @@ -0,0 +1,8 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +MODE SORTELEMENT = CHAR; +PR read "prelude/sort/shell.a68" PR; + +[]SORTELEMENT char array data = "big fjords vex quick waltz nymph"; +print((shell sort(char array data), new line)) diff --git a/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort.alg b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort.alg deleted file mode 100644 index 3247a4d4b5..0000000000 --- a/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort.alg +++ /dev/null @@ -1,24 +0,0 @@ -MODE TYPE = CHAR; - -PROC in place shell sort = (REF[]TYPE seq)REF[]TYPE:( - INT inc := ( UPB seq + LWB seq + 1 ) OVER 2; - WHILE inc NE 0 DO - FOR index FROM LWB seq TO UPB seq DO - INT i := index; - TYPE el = seq[i]; - WHILE ( i - LWB seq >= inc | seq[i - inc] > el | FALSE ) DO - seq[i] := seq[i - inc]; - i -:= inc - OD; - seq[i] := el - OD; - inc := IF inc = 2 THEN 1 ELSE ENTIER(inc * 5 / 11) FI - OD; - seq -); - -PROC shell sort = ([]TYPE seq)[]TYPE: - in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq); - -[]TYPE char array data = "big fjords vex quick waltz nymph"; -print((shell sort(char array data), new line)) diff --git a/Task/Sorting-algorithms-Sleep-sort/Brainf---/sorting-algorithms-sleep-sort.bf b/Task/Sorting-algorithms-Sleep-sort/Brainf---/sorting-algorithms-sleep-sort.bf new file mode 100644 index 0000000000..56af445ac7 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Brainf---/sorting-algorithms-sleep-sort.bf @@ -0,0 +1,8 @@ +>>>>>,----------[++++++++ +++[->+>+<<]>+>[-<<+>>]+++ ++++++[-<------>]>>+>,---- +------<<+[->>>>>+<<<<<]>> +]>>>[<<<<[<<<[->>+<<[->+> +[-]<<]]>[-<+>]>[-<<<.>>>> +->>>>>[>>>>>]<-<<<<[<<<<< +]+<]<<<<]>>>>>[>>>>>]<] diff --git a/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort.m b/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort-1.m similarity index 81% rename from Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort.m rename to Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort-1.m index c71f7186fd..c54956db8b 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort.m +++ b/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort-1.m @@ -2,7 +2,7 @@ int main(int argc, char **argv) { - NSOperationQueue *queue = [NSOperationQueue new]; + NSOperationQueue *queue = [[NSOperationQueue alloc] init]; while (--argc) { int i = atoi(argv[argc]); [queue addOperationWithBlock: ^{ diff --git a/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort-2.m b/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort-2.m new file mode 100644 index 0000000000..1cf4b3ded8 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort-2.m @@ -0,0 +1,11 @@ +#import + +int main(int argc, char **argv) +{ + while (--argc) { + int i = atoi(argv[argc]); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i * NSEC_PER_SEC), + dispatch_get_main_queue(), + ^{ NSLog(@"%d\n", i); }); + } +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust index 9747d325b4..a8242b39fb 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust +++ b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust @@ -1,4 +1,4 @@ -// rust 0.8 +// rust 0.9 fn main() { @@ -8,7 +8,7 @@ fn main() let n = from_str::(*arg).unwrap(); do std::task::spawn { - std::rt::io::timer::sleep(n); + std::io::timer::sleep(n); println!("{}", n); } } diff --git a/Task/Sorting-algorithms-Strand-sort/AutoHotkey/sorting-algorithms-strand-sort-1.ahk b/Task/Sorting-algorithms-Strand-sort/AutoHotkey/sorting-algorithms-strand-sort-1.ahk new file mode 100644 index 0000000000..7ba5778d04 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/AutoHotkey/sorting-algorithms-strand-sort-1.ahk @@ -0,0 +1,27 @@ +string = +( +-2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2 +) +string2 := string +Loop +{ + loop, parse, string, %A_space% + { + list := 1 = A_index ? A_loopfield : list + StringSplit, k, list, %A_space% + + if ( k%k0% <= A_loopfield ) && ( l != "" ) && ( A_index != 1 ) + list := list . " " . A_loopfield + + if ( k%k0% > A_loopfield ) + list := A_loopfield . " " . list , index++ + l := A_loopfield + } + if ( index = 0 ) + { + MsgBox % "unsorted:" string2 "`n Sorted:" list + exitapp + } + string := list, list = "", index := 0 + } +esc::ExitApp diff --git a/Task/Sorting-algorithms-Strand-sort/AutoHotkey/sorting-algorithms-strand-sort-2.ahk b/Task/Sorting-algorithms-Strand-sort/AutoHotkey/sorting-algorithms-strand-sort-2.ahk new file mode 100644 index 0000000000..6ac1ed14be --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/AutoHotkey/sorting-algorithms-strand-sort-2.ahk @@ -0,0 +1,2 @@ +unsorted:-2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2 + Sorted:-4 -3 -2 -2 -1 0 0 2 2 3 4 5 5 5 5 diff --git a/Task/Soundex/Pascal/soundex.pascal b/Task/Soundex/Pascal/soundex.pascal new file mode 100644 index 0000000000..deecfdd80c --- /dev/null +++ b/Task/Soundex/Pascal/soundex.pascal @@ -0,0 +1,108 @@ +program Soundex; + +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + SysUtils; + +type + TLang=(en,fr,de); + +const + Examples : array[1..16, 1..2] of string = + (('Ashcraft', 'A261') + ,('Ashcroft', 'A261') + ,('Gauss', 'G200') + ,('Ghosh', 'G200') + ,('Hilbert', 'H416') + ,('Heilbronn', 'H416') + ,('Lee', 'L000') + ,('Lloyd', 'L300') + ,('Moses', 'M220') + ,('Pfister', 'P236') + ,('Robert', 'R163') + ,('Rupert', 'R163') + ,('Rubin', 'R150') + ,('Tymczak', 'T522') + ,('Soundex', 'S532') + ,('Example', 'E251') + ); + +// For Ansi Str +function Soundex(Value: String; Lang: TLang) : String; +const + // Thx to WP. + Map: array[TLang, 0..2] of String =( + // Deals with accented, to improve + ('abcdefghijklmnopqrstuvwxyz' + ,'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + ,' 123 12- 22455 12623 1-2 2'), + ('aàâäbcçdeéèêëfghiîjklmnoöôpqrstuùûüvwxyz' // all chars with accented + ,'AAAABCCDEEEEEFGHIIJKLMNOOOPQRSTUUUUVWXYZ' // uppercased + ,' 123 97- 72455 12683 9-8 8'), // coding + ('abcdefghijklmnopqrstuvwxyz' + ,'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + ,' 123 12- 22455 12623 1-2 2') + ); +var + i: Integer; + c, cOld: Char; + + function Normalize(const s: string): string; + var + c: Char; + p: Integer; + begin + result := ''; + for c in LowerCase(s) do + begin + p := Pos(c, Map[Lang,0]); + // unmapped chars are ignored + if p > 0 then + Result := Result + Map[Lang, 1][p]; + end; + End; + + function GetCode(c: Char): Char; + begin + Result := Map[Lang, 2][Ord(c)-Ord('A')+1]; + End; + +begin + Value := Trim(Value); + if Value = '' then + begin + Result := '0000'; + exit; + end; + Value := Normalize(Value); + Result := Value[1]; + cOld := GetCode(Value[1]); + for i := 2 to length(Value) do + begin + c := GetCode(Value[i]); + if (c <> ' ') and (c <> '-') and (c <> cOld) then + Result := Result + c; + if c <> '-' then + cOld := c; + end; + Result := Copy(Result+'0000', 1, 4); +End; + +const + Status : array[boolean] of string = ('KO', 'OK'); +var + Found: String; + tab: array[1..2] of String; +begin + WriteLn('Word : Code Found Status'); + for tab in Examples do + begin + Found := Soundex(tab[1], en); + WriteLn(Format('%-20s: %s %s %s',[tab[1], tab[2], Found, Status[Found = tab[2]]])) + end; + ReadLn; +End. diff --git a/Task/Speech-synthesis/Scala/speech-synthesis.scala b/Task/Speech-synthesis/Scala/speech-synthesis.scala index 977dbe7a44..11ba1869dd 100644 --- a/Task/Speech-synthesis/Scala/speech-synthesis.scala +++ b/Task/Speech-synthesis/Scala/speech-synthesis.scala @@ -6,32 +6,26 @@ object ScalaSpeaker extends App { def speech(text: String) = { if (!text.trim.isEmpty()) { - val voiceName = "kevin16" - - System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory") - try { - Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral") - - val synth = - Central.createSynthesizer(new SynthesizerModeDesc(Locale.US)) - synth.allocate() - - val desc = synth.getEngineModeDesc() match { - case g2: SynthesizerModeDesc => g2 - case _ => throw new ClassCastException - } - - synth.getSynthesizerProperties() - .setVoice(desc.getVoices().find(_.toString() == voiceName).get) - //synth.resume() - synth.speakPlainText(text, null) - synth.waitEngineState(Synthesizer.QUEUE_EMPTY) - synth.deallocate() - } catch { - case ex: Throwable => ex.printStackTrace() - } + synth.speakPlainText(text, null) + synth.waitEngineState(Synthesizer.QUEUE_EMPTY) } } + val voiceName = "kevin16" + + System.setProperty("freetts.voices", + "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory") + + Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral") + val synth = Central.createSynthesizer(new SynthesizerModeDesc(Locale.ENGLISH)) + synth.allocate() + val desc = synth.getEngineModeDesc() match { + case g2: SynthesizerModeDesc => g2 + case _ => throw new ClassCastException + } + synth.getSynthesizerProperties() + .setVoice(desc.getVoices().find(_.toString() == voiceName).get) + speech("If it ain't Dutch, It ain't much.") + synth.deallocate() } diff --git a/Task/Stable-marriage-problem/AutoHotkey/stable-marriage-problem.ahk b/Task/Stable-marriage-problem/AutoHotkey/stable-marriage-problem.ahk new file mode 100644 index 0000000000..c232058fe5 --- /dev/null +++ b/Task/Stable-marriage-problem/AutoHotkey/stable-marriage-problem.ahk @@ -0,0 +1,89 @@ +; Given a complete list of ranked preferences, where the most liked is to the left: +abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"] +bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"] +col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"] +dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"] +ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"] +fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"] +gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"] +hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"] +ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"] +jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"] +abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"] +bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"] +cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"] +dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"] +eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"] +fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"] +gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"] +hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"] +ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"] +jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"] + +; of ten males: +males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"] + +; and ten females: +females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"] + +; and an empty set of engagements: +engagements := Object() +freemales := males.Clone() +,s := "Engagements:`n" + +; use the Gale Shapley algorithm to find a stable set of engagements: +For i, male in freemales ; i=index of male (not needed) +{ + j:=1 ; index of female + While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female])) + j++ ; each male loops through all females in order of his preference until one accepts him + If (engagements[female] != "") ; if she was previously engaged + freemales.insert(engagements[female]) ; her old male goes to the bottom of the list + ,s .= female . " dumped " . engagements[female] . "`n" + engagements[female] := male ; the new engagement is registered + ,s .= female . " accepted " . male . "`n" +} + +; summarize results: +s .= "`nCouples:`n" +For female, male in engagements + s .= female . " is engaged to " . male . "`n" +s .= Stable(engagements, females) + +; then perturb this set of engagements to form an unstable set of engagements then check this new set for stability: +s .= "`nWhat if cath and ivy swap?`n" +engagements["cath"]:="abe", engagements["ivy"]:="bob" + +; summarize results: +s .= "`nCouples:`n" +For female, male in engagements + s .= female . " is engaged to " . male . "`n" +s .= Stable(engagements, females) + +Msgbox % clipboard := s +Return + +; Functions: +Index(obj, value) { + For key, val in obj + If (val = value) + Return, key, ErrorLevel := 0 + Return, False, Errorlevel := 1 +} + +Stable(engagements, females) { + For female, male in engagements + { + For j, female2 in females ; j=index of female (not needed) + { + If (index(%male%, female) > index(%male%, female2) + and index(%female2%, male2:=engagements[female2]) > index(%female2%, male)) + s .= male . " is engaged to " . female . " but would prefer " . female2 + . " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n" + } + } + If s + Return "`nThese couples are not stable.`n" . s + Else + Return "`nThese couples are stable.`n" +} diff --git a/Task/Stack/Maple/stack.maple b/Task/Stack/Maple/stack.maple new file mode 100644 index 0000000000..edd7dbcbf6 --- /dev/null +++ b/Task/Stack/Maple/stack.maple @@ -0,0 +1,13 @@ +with(stack): # load the package, to allow use of short command names + +s := stack:-new(a, b): + +push(c, s): + +# The following statements terminate with a semicolon and print output. +top(s); +pop(s); +pop(s); +empty(s); +pop(s); +empty(s); diff --git a/Task/Standard-deviation/C/standard-deviation-1.c b/Task/Standard-deviation/C/standard-deviation-1.c index 3db6021a43..154a05b54a 100644 --- a/Task/Standard-deviation/C/standard-deviation-1.c +++ b/Task/Standard-deviation/C/standard-deviation-1.c @@ -2,7 +2,7 @@ #include #include -enum Action { STDDEV, MEAN, VAR, COUNT }; +typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action; typedef struct stat_obj_struct { double sum, sum2; @@ -12,6 +12,8 @@ typedef struct stat_obj_struct { StatObject NewStatObject( Action action ) { + StatObject so; + so = malloc(sizeof(sStatObject)); so->sum = 0.0; so->sum2 = 0.0; @@ -42,5 +44,5 @@ double stat_object_add(StatObject so, double v) so->num++; so->sum += v; so->sum2 += v*v; - return stat_obj_value(so->action); + return stat_obj_value(so, so->action); } diff --git a/Task/Standard-deviation/MATLAB/standard-deviation-1.m b/Task/Standard-deviation/MATLAB/standard-deviation-1.m new file mode 100644 index 0000000000..b5d8951025 --- /dev/null +++ b/Task/Standard-deviation/MATLAB/standard-deviation-1.m @@ -0,0 +1,7 @@ + x = [2,4,4,4,5,5,7,9]; + n = length (x); + + m = mean (x); + x2 = mean (x .* x); + dev= sqrt (x2 - m * m) + dev = 2 diff --git a/Task/Standard-deviation/MATLAB/standard-deviation-2.m b/Task/Standard-deviation/MATLAB/standard-deviation-2.m new file mode 100644 index 0000000000..0aedfc26e9 --- /dev/null +++ b/Task/Standard-deviation/MATLAB/standard-deviation-2.m @@ -0,0 +1,6 @@ + m = cumsum(x) ./ [1:n]; % running mean + x2= cumsum(x.^2) ./ [1:n]; % running squares + + dev = sqrt(x2 - m .* m) + dev = + 0.00000 1.00000 0.94281 0.86603 0.97980 1.00000 1.39971 2.00000 diff --git a/Task/Standard-deviation/Objective-C/standard-deviation-1.m b/Task/Standard-deviation/Objective-C/standard-deviation-1.m index a17d06e645..37e2c439d2 100644 --- a/Task/Standard-deviation/Objective-C/standard-deviation-1.m +++ b/Task/Standard-deviation/Objective-C/standard-deviation-1.m @@ -41,14 +41,15 @@ int main() { - double v[] = { 2,4,4,4,5,5,7,9 }; + @autoreleasepool { - SDAccum *sdacc = [SDAccum new]; + double v[] = { 2,4,4,4,5,5,7,9 }; - for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) - printf("adding %f\tstddev = %f\n", v[i], [sdacc value: v[i]]); + SDAccum *sdacc = [[SDAccum alloc] init]; - [sdacc release]; + for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) + printf("adding %f\tstddev = %f\n", v[i], [sdacc value: v[i]]); + } return 0; } diff --git a/Task/Standard-deviation/Objective-C/standard-deviation-2.m b/Task/Standard-deviation/Objective-C/standard-deviation-2.m index 7f0b192d2a..39ee4aa1d5 100644 --- a/Task/Standard-deviation/Objective-C/standard-deviation-2.m +++ b/Task/Standard-deviation/Objective-C/standard-deviation-2.m @@ -6,25 +6,25 @@ Func sdCreator() { __block int n = 0; __block double sum = 0; __block double sum2 = 0; - return [[^(double x) { + return ^(double x) { sum += x; sum2 += x*x; n++; return sqrt(sum2/n - sum*sum/n/n); - } copy] autorelease]; + }; } int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - double v[] = { 2,4,4,4,5,5,7,9 }; + double v[] = { 2,4,4,4,5,5,7,9 }; - Func sdacc = sdCreator(); + Func sdacc = sdCreator(); - for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) - printf("adding %f\tstddev = %f\n", v[i], sdacc(v[i])); + for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) + printf("adding %f\tstddev = %f\n", v[i], sdacc(v[i])); - [pool release]; + } return 0; } diff --git a/Task/String-case/Frink/string-case-1.frink b/Task/String-case/Frink/string-case-1.frink new file mode 100644 index 0000000000..cc31517d42 --- /dev/null +++ b/Task/String-case/Frink/string-case-1.frink @@ -0,0 +1,3 @@ +a = "alphaBETA" +println[lc[a]] +println[uc[a]] diff --git a/Task/String-case/Frink/string-case-2.frink b/Task/String-case/Frink/string-case-2.frink new file mode 100644 index 0000000000..d16c5cb68a --- /dev/null +++ b/Task/String-case/Frink/string-case-2.frink @@ -0,0 +1 @@ +uc["Imbiß"] // Last char is \u00df diff --git a/Task/String-case/Frink/string-case-3.frink b/Task/String-case/Frink/string-case-3.frink new file mode 100644 index 0000000000..25d1d137eb --- /dev/null +++ b/Task/String-case/Frink/string-case-3.frink @@ -0,0 +1 @@ +lc[ uc["Imbiß"] ] diff --git a/Task/String-case/Maple/string-case.maple b/Task/String-case/Maple/string-case.maple new file mode 100644 index 0000000000..e349865066 --- /dev/null +++ b/Task/String-case/Maple/string-case.maple @@ -0,0 +1,3 @@ +str := "alphaBETA"; +StringTools:-UpperCase(str); +StringTools:-LowerCase(str); diff --git a/Task/String-case/Rust/string-case.rust b/Task/String-case/Rust/string-case.rust new file mode 100644 index 0000000000..2a88159a46 --- /dev/null +++ b/Task/String-case/Rust/string-case.rust @@ -0,0 +1,5 @@ +// Rust 0.9 +use std::ascii::StrAsciiExt; + +"alphaBeta".to_ascii_upper(); +"alphaBeta".to_ascii_lower(); diff --git a/Task/String-comparison/COBOL/string-comparison-1.cobol b/Task/String-comparison/COBOL/string-comparison-1.cobol new file mode 100644 index 0000000000..e08410a5f5 --- /dev/null +++ b/Task/String-comparison/COBOL/string-comparison-1.cobol @@ -0,0 +1,3 @@ +"hello" = "hello" *> equality +"helloo" <> "hello" *> inequality +"aello" < "hello" *> lexical ordering diff --git a/Task/String-comparison/COBOL/string-comparison-2.cobol b/Task/String-comparison/COBOL/string-comparison-2.cobol new file mode 100644 index 0000000000..68a3142875 --- /dev/null +++ b/Task/String-comparison/COBOL/string-comparison-2.cobol @@ -0,0 +1,3 @@ +FUNCTION STANDARD-COMPARE("hello", "hello") *> "=" +FUNCTION STANDARD-COMPARE("aello", "hello") *> "<" +FUNCTION STANDARD-COMPARE("hello", "aello") *> ">" diff --git a/Task/String-comparison/COBOL/string-comparison-3.cobol b/Task/String-comparison/COBOL/string-comparison-3.cobol new file mode 100644 index 0000000000..ac0365dfc4 --- /dev/null +++ b/Task/String-comparison/COBOL/string-comparison-3.cobol @@ -0,0 +1,2 @@ +"hello " = "hello" *> True +X"00" > X"0000" *> True diff --git a/Task/String-comparison/Icon/string-comparison.icon b/Task/String-comparison/Icon/string-comparison.icon new file mode 100644 index 0000000000..cce1c80fcb --- /dev/null +++ b/Task/String-comparison/Icon/string-comparison.icon @@ -0,0 +1,14 @@ +procedure main(A) + s1 := A[1] | "a" + s2 := A[2] | "b" + # These first four are case-sensitive + s1 == s2 # Are they equal? + s1 ~== s2 # Are they unequal? + s1 << s2 # Does s1 come before s2? + s1 >> s2 # Does s1 come after s2? + map(s1) == map(s2) # Caseless comparison + "123" >> "12" # Lexical comparison + "123" > "12" # Numeric comparison + "123" >> 12 # Lexical comparison (12 coerced into "12") + "123" > 12 # Numeric comparison ("123" coerced into 123) +end diff --git a/Task/String-comparison/Perl/string-comparison.pl b/Task/String-comparison/Perl/string-comparison.pl new file mode 100644 index 0000000000..51d074d8b3 --- /dev/null +++ b/Task/String-comparison/Perl/string-comparison.pl @@ -0,0 +1,25 @@ +use v5.16; # ...for fc(), which does proper Unicode casefolding. + # With older Perl versions you can use lc() as a poor-man's substitute. + +sub compare { + my ($a, $b) = @_; + my $A = "'$a'"; + my $B = "'$b'"; + + print "$A and $B are lexically equal.\n" if $a eq $b; + print "$A and $B are not lexically equal.\n" if $a ne $b; + + print "$A is lexically before $B.\n" if $a lt $b; + print "$A is lexically after $B.\n" if $a gt $b; + + print "$A is not lexically before $B.\n" if $a ge $b; + print "$A is not lexically after $B.\n" if $a le $b; + + print "The lexical relationship is: ", $a cmp $b, "\n"; + print "The case-insensitive lexical relationship is: ", fc($a) cmp fc($b), "\n"; + print "\n"; +} + +compare('Hello', 'Hello'); +compare('5', '5.0'); +compare('perl', 'Perl'); diff --git a/Task/String-comparison/Scheme/string-comparison.ss b/Task/String-comparison/Scheme/string-comparison.ss new file mode 100644 index 0000000000..1e4b06b53f --- /dev/null +++ b/Task/String-comparison/Scheme/string-comparison.ss @@ -0,0 +1,14 @@ +;; Comparing two strings for exact equality +(string=? "hello" "hello") + +;; Comparing two strings for inequality +(not (string=? "hello" "Hello")) + +;; Checking if the first string is lexically ordered before the second +(string? "foo" "bar") + +;; case insensitive comparison +(string-ci=? "hello" "Hello") diff --git a/Task/String-concatenation/Frink/string-concatenation.frink b/Task/String-concatenation/Frink/string-concatenation.frink new file mode 100644 index 0000000000..a2631db36a --- /dev/null +++ b/Task/String-concatenation/Frink/string-concatenation.frink @@ -0,0 +1,3 @@ +a = "Frink" +b = a + " rules!" +println[b] diff --git a/Task/String-concatenation/Julia/string-concatenation.julia b/Task/String-concatenation/Julia/string-concatenation.julia index 7b6336c7a6..70b07135de 100644 --- a/Task/String-concatenation/Julia/string-concatenation.julia +++ b/Task/String-concatenation/Julia/string-concatenation.julia @@ -1,2 +1,2 @@ s = "hello" -println(s + " there!") +println(s * " there!") diff --git a/Task/String-concatenation/Maple/string-concatenation.maple b/Task/String-concatenation/Maple/string-concatenation.maple new file mode 100644 index 0000000000..1b4fa37924 --- /dev/null +++ b/Task/String-concatenation/Maple/string-concatenation.maple @@ -0,0 +1,4 @@ +str := "Hello": +newstr := cat(str,", world!"): +str; +newstr; diff --git a/Task/String-concatenation/Objective-C/string-concatenation.m b/Task/String-concatenation/Objective-C/string-concatenation.m index 38ebc4bf09..49396aa800 100644 --- a/Task/String-concatenation/Objective-C/string-concatenation.m +++ b/Task/String-concatenation/Objective-C/string-concatenation.m @@ -2,18 +2,19 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSString *s = @"hello"; - printf("%s%s\n", [s UTF8String], " literal"); + @autoreleasepool { - NSString *s2 = [s stringByAppendingString:@" literal"]; - // or, NSString *s2 = [NSString stringWithFormat:@"%@%@", s, @" literal"]; - puts([s2 UTF8String]); - /* or */ - NSMutableString *s3 = [NSMutableString stringWithString: s]; - [s3 appendString: @" literal"]; - puts([s3 UTF8String]); + NSString *s = @"hello"; + printf("%s%s\n", [s UTF8String], " literal"); - [pool release]; + NSString *s2 = [s stringByAppendingString:@" literal"]; + // or, NSString *s2 = [NSString stringWithFormat:@"%@%@", s, @" literal"]; + puts([s2 UTF8String]); + /* or */ + NSMutableString *s3 = [NSMutableString stringWithString: s]; + [s3 appendString: @" literal"]; + puts([s3 UTF8String]); + + } return 0; } diff --git a/Task/String-interpolation--included-/D/string-interpolation--included-.d b/Task/String-interpolation--included-/D/string-interpolation--included-.d index 6148eb3a50..f6ea7a9f80 100644 --- a/Task/String-interpolation--included-/D/string-interpolation--included-.d +++ b/Task/String-interpolation--included-/D/string-interpolation--included-.d @@ -1,9 +1,6 @@ -import std.stdio: writeln; -import std.string: format; - void main() { - auto original = "Mary had a %s lamb."; - auto extra = "little"; - auto modified = format(original, extra); - writeln(modified); + import std.stdio, std.string; + + "Mary had a %s lamb.".format("little").writeln; + "Mary had a %2$s %1$s lamb.".format("little", "white").writeln; } diff --git a/Task/Strip-a-set-of-characters-from-a-string/Maple/strip-a-set-of-characters-from-a-string.maple b/Task/Strip-a-set-of-characters-from-a-string/Maple/strip-a-set-of-characters-from-a-string.maple new file mode 100644 index 0000000000..51d229e4f2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Maple/strip-a-set-of-characters-from-a-string.maple @@ -0,0 +1,3 @@ +with(StringTools): + +Remove(c->Has("aei",c), "She was a soul stripper. She took my heart!"); diff --git a/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string-1.txr b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string-1.txr new file mode 100644 index 0000000000..dbea457ac7 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string-1.txr @@ -0,0 +1,14 @@ +@(do + (defun strip-chars (str set) + (let* ((regex-ast ^(set ,*(list-str set))) + (regex-obj (regex-compile regex-ast))) + (regsub regex-obj "" str))) + + (defun usage () + (pprinl `usage: @{(ldiff *full-args* *args*) " "} `) + (exit 1)) + + (tree-case *args* + ((str set extra) (usage)) + ((str set . junk) (pprinl (strip-chars str set))) + (else (usage)))) diff --git a/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string-2.txr b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string-2.txr new file mode 100644 index 0000000000..0c6cb53bf4 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string-2.txr @@ -0,0 +1,2 @@ +(defun strip-chars (str set) + (mappend (do if (memq @1 set) (list @1)) str)) diff --git a/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string.txr b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string.txr deleted file mode 100644 index 628f60ec21..0000000000 --- a/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string.txr +++ /dev/null @@ -1,14 +0,0 @@ -@(next :args) -@arg1 -@arg2 -@(do (defun strip-chars (str set) - (for ((pieces ()) (str-suffix str)) - ((not (zerop (length str-suffix))) (cat-str (nreverse pieces) "")) - () - (let* ((len-piece (compl-span-str str-suffix set)) - (piece (sub-str str-suffix 0 len-piece)) - (suff0 (sub-str str-suffix len-piece nil)) - (len-non-piece (span-str suff0 set))) - (push piece pieces) - (set str-suffix (sub-str suff0 len-non-piece nil)))))) -@(bind result @(strip-chars arg1 arg2)) diff --git a/Task/Strip-comments-from-a-string/Bracmat/strip-comments-from-a-string.bracmat b/Task/Strip-comments-from-a-string/Bracmat/strip-comments-from-a-string.bracmat new file mode 100644 index 0000000000..cbc25a4364 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Bracmat/strip-comments-from-a-string.bracmat @@ -0,0 +1,21 @@ +( " apples, pears # and bananas + oranges, mangos ; and a durian" + : ?text +& :?newText +& ( non-blank + = %@:~(" "|\t|\r|\n) + ) +& ( cleanUp + = + . @(!arg:?arg ("#"|";") ?) + & @(rev$!arg:? (!non-blank ?:?arg)) + & @(rev$!arg:? (!non-blank ?:?arg)) + & !arg {You could write & "[" !arg "]" to prove that the blanks are stripped.} + ) +& whl + ' ( @(!text:?line (\r|\n) ?text) + & !newText \n cleanUp$!line:?newText + ) +& !newText \n cleanUp$!text:?newText +& out$(str$!newText) +); diff --git a/Task/Strip-comments-from-a-string/Common-Lisp/strip-comments-from-a-string.lisp b/Task/Strip-comments-from-a-string/Common-Lisp/strip-comments-from-a-string.lisp new file mode 100644 index 0000000000..49d17d0f7c --- /dev/null +++ b/Task/Strip-comments-from-a-string/Common-Lisp/strip-comments-from-a-string.lisp @@ -0,0 +1,6 @@ +(defun strip-comments (s cs) + "Truncate s at the first occurrence of a character in cs." + (defun comment-char-p (c) + (some #'(lambda (x) (char= x c)) cs)) + (let ((pos (position-if #'comment-char-p s))) + (subseq s 0 pos))) diff --git a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j index 76f3434c34..4d6b0cd070 100644 --- a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j +++ b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j @@ -1 +1 @@ -strip=: #~ *./\@:-.@e.&';#' +strip=: dltb@(#~ *./\@:-.@e.&';#') diff --git a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j index 79e3998b28..39fc8601a8 100644 --- a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j +++ b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j @@ -1 +1 @@ -strip=: {.~ <./@i.&';#' +strip=: dltb@({.~ <./@i.&';#') diff --git a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j index 37e72a92f4..0be4e980a9 100644 --- a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j +++ b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j @@ -1,4 +1,4 @@ - strip 'apples, pears # and bananas' -apples, pears - strip 'apples, pears ; and bananas' -apples, pears + dquote strip ' apples, pears # and bananas' NB. quote result to show stripped whitespace +"apples, pears" + strip ' apples, pears ; and bananas' +"apples, pears" diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION b/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION index fc55d0291e..ea29f14b96 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION @@ -3,6 +3,6 @@ The task is to strip control codes and extended characters from a string. The so * a string with control codes stripped (but extended characters not stripped) * a string with control codes and extended characters stripped -In ASCII, the control codes have decimal codes 0 through to 31 and 127 and greater than 126. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ascii table. +In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ascii table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Bracmat/strip-control-codes-and-extended-characters-from-a-string.bracmat b/Task/Strip-control-codes-and-extended-characters-from-a-string/Bracmat/strip-control-codes-and-extended-characters-from-a-string.bracmat new file mode 100644 index 0000000000..b463717d2f --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Bracmat/strip-control-codes-and-extended-characters-from-a-string.bracmat @@ -0,0 +1,28 @@ +( "string of ☺☻♥♦⌂, may include control +characters and other ilk.\L\D§►↔◄ +Rødgrød med fløde" + : ?string1 + : ?string2 +& :?newString +& whl + ' ( @(!string1:?clean (%@:<" ") ?string1) + & !newString !clean:?newString + ) +& !newString !string1:?newString +& out$(str$("Control characters stripped: +" str$!newString)) +& :?newString +& whl + ' ( @(!string2:?clean (%@:(<" "|>"~")) ?string2) + & !newString !clean:?newString + ) +& !newString !string2:?newString +& out + $ ( str + $ ( " +Control characters and extended characters stripped: +" + str$!newString + ) + ) +& ); diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py index 3b2638eb0f..8ae4b5da0c 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py @@ -1,4 +1,4 @@ def stripped(x): - return "".join([i for i in x if ord(i) in range(32, 127)]) + return "".join([i for i in x if 31 < ord(i) < 127]) print stripped("\ba\x00b\n\rc\fd\xc3") diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 b/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 index 71dd31c4d3..1657a30d30 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 @@ -10,7 +10,7 @@ const func string: stripControl (in string: stri) is func var char: ch is ' '; begin for ch key index range stri do - if ch < ' ' or ch = '\127\' then + if ch < ' ' or ch = '\127;' then stripped &:= stri[old_pos .. pred(index)]; old_pos := succ(index); end if; @@ -27,7 +27,7 @@ const func string: stripControlAndExtended (in string: stri) is func var char: ch is ' '; begin for ch key index range stri do - if ch < ' ' or ch >= '\127\' then + if ch < ' ' or ch >= '\127;' then stripped &:= stri[old_pos .. pred(index)]; old_pos := succ(index); end if; @@ -36,7 +36,7 @@ const func string: stripControlAndExtended (in string: stri) is func end func; const string: src is "déjà vu\ # Unicode - \\n\0\\31\ \33\\126\\127\\128\\255\\n\ # Various boundary cases + \\n\0;\31; \33;\126;\127;\128;\255;\n\ # Various boundary cases \as⃝df̅"; # Unicode combining characters const proc: main is func diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Common-Lisp/strip-whitespace-from-a-string-top-and-tail.lisp b/Task/Strip-whitespace-from-a-string-Top-and-tail/Common-Lisp/strip-whitespace-from-a-string-top-and-tail.lisp new file mode 100644 index 0000000000..201f926a1b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Common-Lisp/strip-whitespace-from-a-string-top-and-tail.lisp @@ -0,0 +1,36 @@ +; Common whitespace characters +(defvar *whitespace* '(#\Space #\Newline #\Tab)) + +(defvar str " foo bar baz ") + +(string-trim *whitespace* str) +; -> "foo bar baz" + +(string-left-trim *whitespace* str) +; -> "foo bar baz " + +(string-right-trim *whitespace* str) +; -> " foo bar baz" + +; Whitespace characters defined by Unicode for +; implementations which support it (e.g. CLISP, SBCL). +; (see http://www.unicode.org/Public/UCD/latest/ucd/PropList.txt) +(defvar *unicode-whitespace* + '(#\u0009 #\u000a #\u000b #\u000c #\u000d + #\u0020 #\u0085 #\u00a0 #\u1680 #\u2000 + #\u2001 #\u2002 #\u2003 #\u2004 #\u2005 + #\u2006 #\u2007 #\u2008 #\u2009 #\u200a + #\u2028 #\u2029 #\u202f #\u205f #\u3000)) + +(defvar unicode-str + (format nil "~C~Cfoo~Cbar~Cbaz~C~C" + #\u2000 #\u2003 #\u0020 #\u00a0 #\u0009 #\u202f)) + +(string-trim *unicode-whitespace* unicode-str) +; -> "foo bar baz" + +(string-left-trim *unicode-whitespace* unicode-str) +; -> "foo bar baz  " + +(string-right-trim *unicode-whitespace* unicode-str) +; -> "  foo bar baz" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Maple/strip-whitespace-from-a-string-top-and-tail.maple b/Task/Strip-whitespace-from-a-string-Top-and-tail/Maple/strip-whitespace-from-a-string-top-and-tail.maple new file mode 100644 index 0000000000..0d30320941 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Maple/strip-whitespace-from-a-string-top-and-tail.maple @@ -0,0 +1,7 @@ +str := " \t \r \n String with spaces \t \r \n "; + +with(StringTools): + +TrimLeft(str); +TrimRight(str); +Trim(str); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m b/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m index 32ca79949d..3e9ff445f4 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m @@ -39,15 +39,15 @@ int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSString *s = @" this is a string "; + @autoreleasepool { - NSLog(@"'%@'", s); - NSLog(@"'%@'", [s ltrim]); - NSLog(@"'%@'", [s rtrim]); - NSLog(@"'%@'", [s trim]); + NSString *s = @" this is a string "; + NSLog(@"'%@'", s); + NSLog(@"'%@'", [s ltrim]); + NSLog(@"'%@'", [s rtrim]); + NSLog(@"'%@'", [s trim]); - [pool release]; + } return 0; } diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl-6/strip-whitespace-from-a-string-top-and-tail.pl6 b/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl-6/strip-whitespace-from-a-string-top-and-tail.pl6 index 7f00b26a0c..8db1114fe3 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl-6/strip-whitespace-from-a-string-top-and-tail.pl6 +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl-6/strip-whitespace-from-a-string-top-and-tail.pl6 @@ -1,4 +1,5 @@ -my $s = "\r\n \t\x2029 Good Stuff \x2028\n"; +my $s = "\r\n \t\x2029 Good Stuff \x202F\n"; +say $s.trim; say $s.trim.perl; say $s.trim-leading.perl; say $s.trim-trailing.perl; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl/strip-whitespace-from-a-string-top-and-tail.pl b/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl/strip-whitespace-from-a-string-top-and-tail.pl index 529e7966ed..5e6d05f71a 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl/strip-whitespace-from-a-string-top-and-tail.pl +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Perl/strip-whitespace-from-a-string-top-and-tail.pl @@ -1,27 +1,9 @@ -use strict; - -sub ltrim -{ - my $c = shift; - $c =~ s/^\s+//; - return $c; -} - -sub rtrim -{ - my $c = shift; - $c =~ s/\s+$//; - return $c; -} - -sub trim -{ - my $c = shift; - return ltrim(rtrim($c)); -} +sub ltrim { shift =~ s/^\s+//r } +sub rtrim { shift =~ s/\s+$//r } +sub trim { ltrim rtrim shift } +# Usage: my $p = " this is a string "; - print "'", $p, "'\n"; print "'", trim($p), "'\n"; print "'", ltrim($p), "'\n"; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail.txr b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-1.txr similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail.txr rename to Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-1.txr diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-2.txr b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-2.txr new file mode 100644 index 0000000000..4fcc9055ae --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-2.txr @@ -0,0 +1,2 @@ +$ txr -p '(trim-str " a b ")' +"a b" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-3.txr b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-3.txr new file mode 100644 index 0000000000..24e477525e --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-3.txr @@ -0,0 +1,2 @@ +$ txr -p '[(do progn (del [@1 0..(match-regex @1 #/\s*/)]) @1) " a b "]' +"a b " diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-4.txr b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-4.txr new file mode 100644 index 0000000000..4d6f0abebe --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail-4.txr @@ -0,0 +1,10 @@ +@(do + (defun trim-right (str) + (for () + ((and (> (length str) 0) (chr-isspace [str -1])) str) + ((del [str -1])))) + + (format t "{~a}\n" (trim-right " a a ")) + (format t "{~a}\n" (trim-right " ")) + (format t "{~a}\n" (trim-right "a ")) + (format t "{~a}\n" (trim-right ""))) diff --git a/Task/Substring-Top-and-tail/Common-Lisp/substring-top-and-tail.lisp b/Task/Substring-Top-and-tail/Common-Lisp/substring-top-and-tail.lisp new file mode 100644 index 0000000000..572a556836 --- /dev/null +++ b/Task/Substring-Top-and-tail/Common-Lisp/substring-top-and-tail.lisp @@ -0,0 +1,8 @@ +> (defvar *str* "∀Ꮺ✤Л◒") +*STR* +> (subseq *str* 1) ; remove first character +"Ꮺ✤Л◒" +> (subseq *str* 0 (1- (length *str*))) ; remove last character +"∀Ꮺ✤Л" +> (subseq *str* 1 (1- (length *str*))) ; remove first and last character +"Ꮺ✤Л" diff --git a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail.pl6 b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail.pl6 new file mode 100644 index 0000000000..99aad416fd --- /dev/null +++ b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail.pl6 @@ -0,0 +1,19 @@ +my $s = '𝄪♯♮♭𝄫'; + +print qq:to/END/; + Original: + $s + + Remove first character: + { substr($s, 1) } + { $s.substr(1) } + + Remove last character: + { substr($s, 0, *-1) } + { $s.substr( 0, *-1) } + { $s.chop } + + Remove first and last characters: + { substr($s, 1, *-1) } + { $s.substr(1, *-1) } + END diff --git a/Task/Substring-Top-and-tail/Standard-ML/substring-top-and-tail.ml b/Task/Substring-Top-and-tail/Standard-ML/substring-top-and-tail.ml new file mode 100644 index 0000000000..fc78f2828c --- /dev/null +++ b/Task/Substring-Top-and-tail/Standard-ML/substring-top-and-tail.ml @@ -0,0 +1,8 @@ +- val str = "abcde"; +val str = "abcde" : string +- String.substring(str, 1, String.size str - 1); +val it = "bcde" : string +- String.substring(str, 0, String.size str - 1); +val it = "abcd" : string +- String.substring(str, 1, String.size str - 2); +val it = "bcd" : string diff --git a/Task/Subtractive-generator/AutoHotkey/subtractive-generator.ahk b/Task/Subtractive-generator/AutoHotkey/subtractive-generator.ahk new file mode 100644 index 0000000000..2239fdc7d2 --- /dev/null +++ b/Task/Subtractive-generator/AutoHotkey/subtractive-generator.ahk @@ -0,0 +1,25 @@ +r := InitR(292929) + +Loop, 10 + Out .= (A_Index + 219) ":`t" GetRand(r) "`n" + +MsgBox, % Out + +GetRand(r) { + i := Mod(r["j"], 55) + , r[i] := Mod(r[i] - r[Mod(i + 31, 55)], r["m"]) + , r["j"] += 1 + return, (r[i] < 0 ? r[i] + r["m"] : r[i]) +} + +InitR(Seed) { + r := {"j": 0, "m": 10 ** 9}, s := {0: Seed, 1: 1} + Loop, 53 + s[A_Index + 1] := Mod(s[A_Index - 1] - s[A_Index], r["m"]) + Loop, 55 + r[A_Index - 1] := s[Mod(34 * A_Index, 55)] + Loop, 165 + i := Mod(A_Index + 54, 55) + , r[i] := Mod(r[i] - r[Mod(A_Index + 30, 55)], r["m"]) + return, r +} diff --git a/Task/Subtractive-generator/Clojure/subtractive-generator.clj b/Task/Subtractive-generator/Clojure/subtractive-generator.clj new file mode 100644 index 0000000000..12816a1a02 --- /dev/null +++ b/Task/Subtractive-generator/Clojure/subtractive-generator.clj @@ -0,0 +1,22 @@ +(defn xpat2-with-seed + "produces an xpat2 function initialized from seed" + [seed] + (let [e9 1000000000 + fs (fn [[i j]] [j (mod (- i j) e9)]) + s (->> [seed 1] (iterate fs) (map first) (take 55) vec) + rinit (map #(-> % inc (* 34) (mod 55) s) (range 55)) + r-atom (atom [54 (int-array rinit)]) + update (fn [[nprev r]] + (let [n (-> nprev inc (mod 55)) + rx #(get r (-> n (- %) (mod 55))) + rn (-> (rx 55) (- (rx 24)) (mod e9)) + _ (aset-int r n rn)] + [n r])) + xpat2 #(let [[n r] (swap! r-atom update)] + (get r n)) + _ (dotimes [_ 165] (xpat2))] + xpat2)) + +(def xpat2 (xpat2-with-seed 292929)) + +(println (xpat2) (xpat2) (xpat2)) ; prints: 467478574 512932792 539453717 diff --git a/Task/Subtractive-generator/Python/subtractive-generator.py b/Task/Subtractive-generator/Python/subtractive-generator-1.py similarity index 100% rename from Task/Subtractive-generator/Python/subtractive-generator.py rename to Task/Subtractive-generator/Python/subtractive-generator-1.py diff --git a/Task/Subtractive-generator/Python/subtractive-generator-2.py b/Task/Subtractive-generator/Python/subtractive-generator-2.py new file mode 100644 index 0000000000..bd86d49611 --- /dev/null +++ b/Task/Subtractive-generator/Python/subtractive-generator-2.py @@ -0,0 +1,23 @@ +import collections + +_ten2nine = 10**9 + +class Subtractive_generator(): + + def __init__(self, seed=292929): + self.r = collections.deque(maxlen=55) + s = collections.deque(maxlen=55) + s.extend([seed, 1]) + s.extend((s[n-2] - s[n-1]) % _ten2nine for n in range(2, 55)) + self.r.extend(s[(34 * (n+1)) % 55] for n in range(55)) + for n in range(219 - 54): + self() + + def __call__(self): + r = self.r + r.append((r[0] - r[31]) % _ten2nine) + return r[54] + +if __name__ == '__main__': + srand = Subtractive_generator() + print([srand() for i in range(5)]) diff --git a/Task/Sudoku/D/sudoku.d b/Task/Sudoku/D/sudoku.d index 468dc2abb5..67350729db 100644 --- a/Task/Sudoku/D/sudoku.d +++ b/Task/Sudoku/D/sudoku.d @@ -28,10 +28,10 @@ alias SudokuTable = Digit[sudokuSide ^^ 2]; Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem) -pure /*nothrow*/ { +pure nothrow { alias Tgrid = uint; Tgrid[SudokuTable.length] grid = void; - problem[].map!(c => c - '0').copy(grid[]); // Not pure. + problem[].map!(c => c - '0').copy(grid[]); // DMD doesn't inline this function. Performance loss. Tgrid access(in size_t x, in size_t y) nothrow { @@ -78,10 +78,9 @@ pure /*nothrow*/ { //return typeof(return)(grid[] // .map!(c => Digit(c + '0')) // .array); - Digit[] aux; - foreach (immutable c; grid) - aux ~= Digit(c + '0'); - immutable SudokuTable result = aux; + immutable SudokuTable result = grid[] + .map!(c => Digit(c + '0')) + .array; return typeof(return)(result); } else return typeof(return)(); @@ -111,17 +110,9 @@ pure nothrow out(result) { return result.replace("0", "."); } -U[] validator(U, T)(in T[] items) pure nothrow { - typeof(return) result; - foreach (immutable item; items) - result ~= U(item); - return result; -} - -//enum ValidateCells(string s) = items.map!Digit.array; -enum ValidateCells(string s) = validator!Digit(s); - void main() { + enum ValidateCells(string s) = s.map!Digit.array; + immutable SudokuTable problem = ValidateCells!(" 850002400 720000009 diff --git a/Task/Sudoku/Lua/sudoku.lua b/Task/Sudoku/Lua/sudoku.lua new file mode 100644 index 0000000000..24b9a07748 --- /dev/null +++ b/Task/Sudoku/Lua/sudoku.lua @@ -0,0 +1,183 @@ +--9x9 sudoku solver in lua +--based on a branch and bound solution +--fields are not tried in plain order +--but in a way to detect dead ends earlier +concat=table.concat +insert=table.insert +constraints = { } --contains a table with 3 constraints for every field +-- a contraint "cons" is a table containing all fields which must not have the same value +-- a field "f" is an integer from 1 to 81 +columns = { } --contains all column-constraints variable "c" +rows = { } --contains all row-constraints variable "r" +blocks = { } --contains all block-constraints variable "b" + +--initialize all constraints +for f = 1, 81 do + constraints[f] = { } +end +all_constraints = { } --union of colums, rows and blocks +for i = 1, 9 do + columns[i] = { + unknown = 9, --number of fields not yet solved + unknowns = { } --fields not yet solved + } + insert(all_constraints, columns[i]) + rows[i] = { + unknown = 9, -- see l.15 + unknowns = { } -- see l.16 + } + insert(all_constraints, rows[i]) + blocks[i] = { + unknown = 9, --see l.15 + unknowns = { } --see l.16 + } + insert(all_constraints, blocks[i]) +end +constraints_by_unknown = { } --contraints sorted by their number of unknown fields +for i = 0, 9 do + constraints_by_unknown[i] = { + count = 0 --how many contraints are in here + } +end +for r = 1, 9 do + for c = 1, 9 do + local f = (r - 1) * 9 + c + insert(rows[r], f) + insert(constraints[f], rows[r]) + insert(columns[c], f) + insert(constraints[f], columns[c]) + end +end +for i = 1, 3 do + for j = 1, 3 do + local r = (i - 1) * 3 + j + for k = 1, 3 do + for l = 1, 3 do + local c = (k - 1) * 3 + l + local f = (r - 1) * 9 + c + local b = (i - 1) * 3 + k + insert(blocks[b], f) + insert(constraints[f], blocks[b]) + end + end + end +end +working = { } --save the read values in here +function read() --read the values from stdin + local f = 1 + local l = io.read("*a") + for d in l:gmatch("(%d)") do + local n = tonumber(d) + if n > 0 then + working[f] = n + for _,cons in pairs(constraints[f]) do + cons.unknown = cons.unknown - 1 + end + else + for _,cons in pairs(constraints[f]) do + cons.unknowns[f] = f + end + end + f = f + 1 + end + assert((f == 82), "Wrong number of digits") +end +read() +function printer(t) --helper function for printing a 1-81 table + local pattern = {1,2,3,false,4,5,6,false,7,8,9} --place seperators for better readability + for _,r in pairs(pattern) do + if r then + local function p(c) + return c and t[(r - 1) * 9 + c] or "|" + end + local line={} + for k,v in pairs(pattern) do + line[k]=p(v) + end + print(concat(line)) + else + print("---+---+---") + end + end +end +order = { } --when to try a field +for _,cons in pairs(all_constraints) do --put all constraints in the corresponding constraints_by_unknown set + local level = constraints_by_unknown[cons.unknown] + level[cons] = cons + level.count = level.count + 1 +end +function first(t) --helper function to get a value from a set + for k, v in pairs(t) do + if k == v then + return k + end + end +end +function establish_order() -- determine the sequence in which the fields are to be tried + local solved = constraints_by_unknown[0].count + while solved < 27 do --there 27 constraints + --contraints with no unknown fields are considered "solved" + --keep in mind the actual solving happens in function branch + local i = 1 + while constraints_by_unknown[i].count == 0 do + i = i + 1 + -- find a unsolved contraint with the least number of unsolved fields + end + local cons = first(constraints_by_unknown[i]) + local f = first(cons.unknowns) + -- take one of its unknown fields and append it to "order" + insert(order, f) + for _,c in pairs(constraints[f]) do + --each constraint "c" of "f" is moved up one "level" + --delete "f" from the constraints unknown fields + --decrease unknown of "c" + c.unknowns[f] = nil + local level = constraints_by_unknown[c.unknown] + level[c] = nil + level.count = level.count - 1 + c.unknown = c.unknown - 1 + level = constraints_by_unknown[c.unknown] + level[c] = c + level.count = level.count + 1 + constraints_by_unknown[c.unknown][c] = c + end + solved = constraints_by_unknown[0].count + end +end +establish_order() +max = #order --how many fields are to be solved +function bound(f,i) + for _,c in pairs(constraints[f]) do + for _,x in pairs(c) do + if i == working[x] then + return false --i is already used in fs column/row/block + end + end + end + return true +end +function branch(n) + local f = order[n] --recursively iterate over fields in order + if n > max then + return working --all fields solved without collision + else + for i = 1, 9 do --check all values + if bound(f, i) then --if there is no collision + working[f] = i + local res = branch(n + 1) --try next field + if res then + return res --all fields solved without collision + else + working[f] = nil --this lead to a dead end + end + else + working[f] = nil --reset field because of a collision + end + end + return false --this is a dead end + end +end +x = branch(1) +if x then + return printer(x) +end diff --git a/Task/Sum-and-product-of-an-array/Frink/sum-and-product-of-an-array.frink b/Task/Sum-and-product-of-an-array/Frink/sum-and-product-of-an-array.frink new file mode 100644 index 0000000000..0bc8c64297 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Frink/sum-and-product-of-an-array.frink @@ -0,0 +1,3 @@ +a = [1,2,3,5,7] +sum[a] +product[a] diff --git a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx index 3c17cb2424..3d6c598499 100644 --- a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx +++ b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx @@ -1,6 +1,5 @@ /*REXX program to add and separately multiply elements of an array. */ numeric digits 30 /*allow 30-digit numbers (default is 9)*/ - m=20 /*one method of indicating array size. */ do j=1 for m /*build an array of twenty elements. */ y.j=j /*set 1st to 1, 3rd to 3, 9th to 9 ... */ @@ -14,5 +13,4 @@ prod=1 /*initialize PROD to unity. */ say ' sum of' m "elements for the Y array is: " sum say 'product of' m "elements for the Y array is: " prod - /*stick a fork in it, we're done. */ diff --git a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust new file mode 100644 index 0000000000..03dfb16a13 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust @@ -0,0 +1,16 @@ +use std::iter::{AdditiveIterator, MultiplicativeIterator}; + +fn main() { + let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + + // using fold + let sum = arr.iter().fold(0, |a, &b| a + b); + let product = arr.iter().fold(1, |a, &b| a * b); + println!("the sum is {:d} and the product is {:d}", sum, product); + + // or using sum and product from AdditiveIterator + // and MultiplicativeIterator + let sum2 = arr.iter().map(|&a| a).sum(); + let product2 = arr.iter().map(|&a| a).product(); + println!("the sum is {:d} and the product is {:d}", sum2, product2); +} diff --git a/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer.cpp b/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer-1.cpp similarity index 100% rename from Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer.cpp rename to Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer-1.cpp diff --git a/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer-2.cpp b/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer-2.cpp new file mode 100644 index 0000000000..e27cd665e2 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer-2.cpp @@ -0,0 +1,33 @@ +// Template Metaprogramming version by Martin Ettl +#include +#include + +typedef unsigned long long int T; +template void For(T &sum, T &x, const T &BASE) +{ + const double z(std::pow(BASE,i)); + const T t = x/z; + sum += t; + x -= t*z; + For(sum,x,BASE); +} +template <> void For(T &, T &, const T &){} + +template T SumDigits() + { + T sum(0); + T x(digits); + const T end(log(digits)/log(BASE)); + For(sum,x,BASE); + return x+sum; +} + +int main() +{ + std::cout << SumDigits() << ' ' + << SumDigits() << ' ' + << SumDigits() << ' ' + << SumDigits() << ' ' + << SumDigits() << std::endl; + return 0; +} diff --git a/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer.psh b/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer.psh new file mode 100644 index 0000000000..7a7a47c07b --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer.psh @@ -0,0 +1,7 @@ +function Get-DigitalSum ($n) +{ + if ($n -lt 10) {$n} + else { + ($n % 10) + (Get-DigitalSum ([math]::Floor($n / 10))) + } +} diff --git a/Task/Sum-of-a-series/D/sum-of-a-series-2.d b/Task/Sum-of-a-series/D/sum-of-a-series-2.d index b3cde6c503..9c5c1df2e2 100644 --- a/Task/Sum-of-a-series/D/sum-of-a-series-2.d +++ b/Task/Sum-of-a-series/D/sum-of-a-series-2.d @@ -1,8 +1,7 @@ import std.stdio, std.algorithm, std.range; -auto series(alias F)(in int end, in int start=1) pure { - return iota(start, end + 1).map!F.reduce!q{a + b}; -} +enum series(alias F) = (in int end, in int start=1) /*pure*/ => + iota(start, end + 1).map!F.sum; void main() { writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000)); diff --git a/Task/Sum-of-squares/Dart/sum-of-squares.dart b/Task/Sum-of-squares/Dart/sum-of-squares-1.dart similarity index 100% rename from Task/Sum-of-squares/Dart/sum-of-squares.dart rename to Task/Sum-of-squares/Dart/sum-of-squares-1.dart diff --git a/Task/Sum-of-squares/Dart/sum-of-squares-2.dart b/Task/Sum-of-squares/Dart/sum-of-squares-2.dart new file mode 100644 index 0000000000..0d67dcca7d --- /dev/null +++ b/Task/Sum-of-squares/Dart/sum-of-squares-2.dart @@ -0,0 +1,8 @@ +num sumOfSquares(List l) => l.map((num x)=>x*x) + .fold(0, (num p,num n)=> p + n); + +void main(){ + print(sumOfSquares([])); + print(sumOfSquares([1,2,3])); + print(sumOfSquares([10])); +} diff --git a/Task/Sum-of-squares/Frink/sum-of-squares.frink b/Task/Sum-of-squares/Frink/sum-of-squares.frink new file mode 100644 index 0000000000..73e3a1c712 --- /dev/null +++ b/Task/Sum-of-squares/Frink/sum-of-squares.frink @@ -0,0 +1,3 @@ +f = {|x| x^2} // Anonymous function which squares its argument +a = [1,2,3,5,7] +println[sum[map[f,a], 0]] diff --git a/Task/Sum-of-squares/Maple/sum-of-squares.maple b/Task/Sum-of-squares/Maple/sum-of-squares.maple new file mode 100644 index 0000000000..b7426bfa13 --- /dev/null +++ b/Task/Sum-of-squares/Maple/sum-of-squares.maple @@ -0,0 +1,2 @@ +F := V -> add(v^2, v in V): +F(<1,2,3,4,5>); diff --git a/Task/Sum-of-squares/Maxima/sum-of-squares.maxima b/Task/Sum-of-squares/Maxima/sum-of-squares-1.maxima similarity index 100% rename from Task/Sum-of-squares/Maxima/sum-of-squares.maxima rename to Task/Sum-of-squares/Maxima/sum-of-squares-1.maxima diff --git a/Task/Sum-of-squares/Maxima/sum-of-squares-2.maxima b/Task/Sum-of-squares/Maxima/sum-of-squares-2.maxima new file mode 100644 index 0000000000..1e270d92ad --- /dev/null +++ b/Task/Sum-of-squares/Maxima/sum-of-squares-2.maxima @@ -0,0 +1,2 @@ +nums : [3,1,4,1,5,9]; +lsum(el^2, el, nums); diff --git a/Task/Symmetric-difference/Objective-C/symmetric-difference.m b/Task/Symmetric-difference/Objective-C/symmetric-difference.m index 5ee917fbe0..41bd818182 100644 --- a/Task/Symmetric-difference/Objective-C/symmetric-difference.m +++ b/Task/Symmetric-difference/Objective-C/symmetric-difference.m @@ -1,25 +1,30 @@ -NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; +#import -NSSet* setA = [NSSet setWithObjects:@"John", @"Serena", @"Bob", @"Mary", @"Serena", nil]; -NSSet* setB = [NSSet setWithObjects:@"Jim", @"Mary", @"John", @"Jim", @"Bob", nil]; +int main(int argc, const char *argv[]) { + @autoreleasepool { -// Present our initial data set -NSLog(@"In set A: %@", setA); -NSLog(@"In set B: %@", setB); + NSSet* setA = [NSSet setWithObjects:@"John", @"Serena", @"Bob", @"Mary", @"Serena", nil]; + NSSet* setB = [NSSet setWithObjects:@"Jim", @"Mary", @"John", @"Jim", @"Bob", nil]; -// Get our individual differences. -NSMutableSet* notInSetA = [NSMutableSet setWithSet:setB]; -[notInSetA minusSet:setA]; -NSMutableSet* notInSetB = [NSMutableSet setWithSet:setA]; -[notInSetB minusSet:setB]; + // Present our initial data set + NSLog(@"In set A: %@", setA); + NSLog(@"In set B: %@", setB); -// The symmetric difference is the concatenation of the two individual differences -NSMutableSet* symmetricDifference = [NSMutableSet setWithSet:notInSetA]; -[symmetricDifference unionSet:notInSetB]; + // Get our individual differences. + NSMutableSet* notInSetA = [NSMutableSet setWithSet:setB]; + [notInSetA minusSet:setA]; + NSMutableSet* notInSetB = [NSMutableSet setWithSet:setA]; + [notInSetB minusSet:setB]; -// Present our results -NSLog(@"Not in set A: %@", notInSetA); -NSLog(@"Not in set B: %@", notInSetB); -NSLog(@"Symmetric Difference: %@", symmetricDifference); + // The symmetric difference is the concatenation of the two individual differences + NSMutableSet* symmetricDifference = [NSMutableSet setWithSet:notInSetA]; + [symmetricDifference unionSet:notInSetB]; -[pool drain]; + // Present our results + NSLog(@"Not in set A: %@", notInSetA); + NSLog(@"Not in set B: %@", notInSetB); + NSLog(@"Symmetric Difference: %@", symmetricDifference); + + } + return 0; +} diff --git a/Task/Table-creation-Postal-addresses/Go/table-creation-postal-addresses.go b/Task/Table-creation-Postal-addresses/Go/table-creation-postal-addresses.go new file mode 100644 index 0000000000..84e5195687 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Go/table-creation-postal-addresses.go @@ -0,0 +1,47 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + + _ "github.com/mattn/go-sqlite3" +) + +func main() { + // task req: show database connection + db, err := sql.Open("sqlite3", "rc.db") + if err != nil { + log.Print(err) + return + } + defer db.Close() + // task req: create table with typed fields, including a unique id + _, err = db.Exec(`create table addr ( + id int unique, + street text, + city text, + state text, + zip text + )`) + if err != nil { + log.Print(err) + return + } + // show output: query the created field names and types + rows, err := db.Query(`pragma table_info(addr)`) + if err != nil { + log.Print(err) + return + } + var field, storage string + var ignore sql.RawBytes + for rows.Next() { + err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore) + if err != nil { + log.Print(err) + return + } + fmt.Println(field, storage) + } +} diff --git a/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d b/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d index c1e903bf93..92d0c70107 100644 --- a/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d +++ b/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d @@ -1,14 +1,14 @@ -import std.stdio, std.file, std.string, std.datetime, std.range; +void main(in string[] args) { + import std.stdio, std.file, std.datetime, std.range; -void main(string[] args) { immutable filename = "NOTES.TXT"; if (args.length == 1) { - if (exists(filename) && isFile(filename)) + if (filename.exists && filename.isFile) writefln("%-(%s\n%)", filename.File.byLine); } else { auto f = File(filename, "a+"); f.writefln("%s", cast(DateTime)Clock.currTime); - f.writefln("\t%s", args.dropOne.join(" ")); + f.writefln("\t%-(%s %)", args.dropOne); } } diff --git a/Task/Take-notes-on-the-command-line/Mercury/take-notes-on-the-command-line.mercury b/Task/Take-notes-on-the-command-line/Mercury/take-notes-on-the-command-line.mercury new file mode 100644 index 0000000000..442a480d9c --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Mercury/take-notes-on-the-command-line.mercury @@ -0,0 +1,61 @@ +:- module notes. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module list, time. + +main(!IO) :- + io.command_line_arguments(Args, !IO), + ( if Args = [] then print_notes(!IO) else add_note(Args, !IO) ). + +:- pred print_notes(io::di, io::uo) is det. + +print_notes(!IO) :- + io.open_input(notes_filename, InputRes, !IO), + ( + InputRes = ok(Input), + io.input_stream_foldl_io(Input, io.write_char, WriteRes, !IO), + ( + WriteRes = ok + ; + WriteRes = error(WriteError), + print_io_error(WriteError, !IO) + ), + io.close_input(Input, !IO) + ; + InputRes = error(_InputError) + ). + +:- pred add_note(list(string)::in, io::di, io::uo) is det. + +add_note(Words, !IO) :- + io.open_append(notes_filename, OutputRes, !IO), + ( + OutputRes = ok(Output), + time(Time, !IO), + io.write_string(Output, ctime(Time), !IO), + io.write_char(Output, '\t', !IO), + io.write_list(Output, Words, " ", io.write_string, !IO), + io.nl(Output, !IO), + io.close_output(Output, !IO) + ; + OutputRes = error(OutputError), + print_io_error(OutputError, !IO) + ). + +:- pred print_io_error(io.error::in, io::di, io::uo) is det. + +print_io_error(Error, !IO) :- + io.stderr_stream(Stderr, !IO), + io.write_string(Stderr, io.error_message(Error), !IO), + io.set_exit_status(1, !IO). + +:- func notes_filename = string. + +notes_filename = "NOTES.TXT". + +:- end_module notes. diff --git a/Task/Temperature-conversion/Perl/temperature-conversion.pl b/Task/Temperature-conversion/Perl/temperature-conversion.pl index 593be6da7e..48e10c467b 100644 --- a/Task/Temperature-conversion/Perl/temperature-conversion.pl +++ b/Task/Temperature-conversion/Perl/temperature-conversion.pl @@ -1,27 +1,13 @@ -#!/usr/bin/perl -use strict ; -use warnings ; +my %scale = ( + Celcius => { factor => 1 , offset => -273.15 }, + Rankine => { factor => 1.8, offset => 0 }, + Fahrenheit => { factor => 1.8, offset => -459.67 }, +); -sub kelvin_to_other_scales { - my $kelvin = shift ; - my $celsius = $kelvin - 273.15 ; - my $rankine = 9 * $kelvin / 5 ; - my $fahrenheit = $rankine - 459.67 ; - my @scales ; - push @scales , $kelvin , $celsius , $fahrenheit , $rankine ; - return @scales ; -} +print "Enter a temperature in Kelvin: "; +chomp(my $kelvin = ); +die "No such temperature!\n" unless $kelvin > 0; -print "Enter a temperature in Kelvin: " ; -my $kelvin = ; -chomp $kelvin ; -while ( $kelvin < 0 ) { - print "Error! There are no negative kelvin degrees!\n" ; - $kelvin = ; - chomp $kelvin ; +foreach (sort keys %scale) { + printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset}; } -my @scales = kelvin_to_other_scales( $kelvin ) ; -print "K $scales[ 0 ]\n" ; -print "C $scales[ 1 ]\n" ; -print "F $scales[ 2 ]\n" ; -print "R $scales[ 3 ]\n" ; diff --git a/Task/Terminal-control-Display-an-extended-character/Bracmat/terminal-control-display-an-extended-character.bracmat b/Task/Terminal-control-Display-an-extended-character/Bracmat/terminal-control-display-an-extended-character.bracmat new file mode 100644 index 0000000000..664dd4bd65 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Bracmat/terminal-control-display-an-extended-character.bracmat @@ -0,0 +1 @@ +put$£ diff --git a/Task/Terminal-control-Inverse-video/Ada/terminal-control-inverse-video.ada b/Task/Terminal-control-Inverse-video/Ada/terminal-control-inverse-video.ada new file mode 100644 index 0000000000..d997cfc616 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Ada/terminal-control-inverse-video.ada @@ -0,0 +1,11 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Reverse_Video is + + Rev_Video : String := Ascii.ESC & "[7m"; + Norm_Video : String := Ascii.ESC & "[m"; + +begin + Put (Rev_Video & "Reversed"); + Put (Norm_Video & " Normal"); +end Reverse_Video; diff --git a/Task/Ternary-logic/AutoHotkey/ternary-logic-1.ahk b/Task/Ternary-logic/AutoHotkey/ternary-logic-1.ahk new file mode 100644 index 0000000000..1578f5b6bf --- /dev/null +++ b/Task/Ternary-logic/AutoHotkey/ternary-logic-1.ahk @@ -0,0 +1,20 @@ +Ternary_Not(a){ + SetFormat, Float, 2.1 + return Abs(a-1) +} + +Ternary_And(a,b){ + return ab?a:b +} + +Ternary_IfThen(a,b){ + return a=1?b:a=0?1:a+b>1?1:0.5 +} + +Ternary_Equiv(a,b){ + return a=b?1:a=1?b:b=1?a:0.5 +} diff --git a/Task/Ternary-logic/AutoHotkey/ternary-logic-2.ahk b/Task/Ternary-logic/AutoHotkey/ternary-logic-2.ahk new file mode 100644 index 0000000000..ace430f01c --- /dev/null +++ b/Task/Ternary-logic/AutoHotkey/ternary-logic-2.ahk @@ -0,0 +1,31 @@ +aa:=[1,0.5,0] +bb:=[1,0.5,0] + +for index, a in aa + Res .= "`tTernary_Not`t" a "`t=`t" Ternary_Not(a) "`n" +Res .= "-------------`n" + +for index, a in aa + for index, b in bb + Res .= a "`tTernary_And`t" b "`t=`t" Ternary_And(a,b) "`n" +Res .= "-------------`n" + +for index, a in aa + for index, b in bb + Res .= a "`tTernary_or`t" b "`t=`t" Ternary_Or(a,b) "`n" +Res .= "-------------`n" + +for index, a in aa + for index, b in bb + Res .= a "`tTernary_then`t" b "`t=`t" Ternary_IfThen(a,b) "`n" +Res .= "-------------`n" + +for index, a in aa + for index, b in bb + Res .= a "`tTernary_equiv`t" b "`t=`t" Ternary_Equiv(a,b) "`n" + +StringReplace, Res, Res, 1, true, all +StringReplace, Res, Res, 0.5, maybe, all +StringReplace, Res, Res, 0, false, all +MsgBox % Res +return diff --git a/Task/Text-processing-2/PicoLisp/text-processing-2.l b/Task/Text-processing-2/PicoLisp/text-processing-2.l index f95425a396..269525c59e 100644 --- a/Task/Text-processing-2/PicoLisp/text-processing-2.l +++ b/Task/Text-processing-2/PicoLisp/text-processing-2.l @@ -9,15 +9,13 @@ (and (= 49 (length Lst)) # Check total length ($dat (car Lst) "-") # Check for valid date - (not - (find # Check data format - '((L F) - (not - (if F # Alternating: - (format L 3) # Number - (>= 9 (format L) -9) ) ) ) # or flag - (cdr Lst) - '(T NIL .) ) ) ) + (fully # Check data format + '((L F) + (if F # Alternating: + (format L 3) # Number + (>= 9 (format L) -9) ) ) # or flag + (cdr Lst) + '(T NIL .) ) ) (prinl "Bad line format: " (glue " " Lst)) (bye 1) ) ) ) ) diff --git a/Task/Tic-tac-toe/Perl/tic-tac-toe.pl b/Task/Tic-tac-toe/Perl/tic-tac-toe.pl new file mode 100644 index 0000000000..48d2cf9fe8 --- /dev/null +++ b/Task/Tic-tac-toe/Perl/tic-tac-toe.pl @@ -0,0 +1,99 @@ +use warnings; +use strict; + +my $initial = join ",", qw(abc def ghi); +my %reverse = qw(X O O X); + +# In list context, returns best move, +# In scalar context, returns the score of best move. +my %cache; +sub best_move { + my ($b, $me) = @_; + if( exists $cache{$b,$me,wantarray} ) { + return $cache{$b,$me,wantarray}; + } elsif( my $s = score( $b, $me ) ) { + return $cache{$b,$me,wantarray} = (wantarray ? undef : $s); + } + my $him = $reverse{$me}; + my ($best, @best) = (-999); + for my $m (moves($b)) { + (my $with_m = $b) =~ s/$m/$me/ or die; + # The || operator supplies scalar context to best_move(...) + my $s = -(score($with_m, $him) || best_move($with_m, $him)); + if( $s > $best ) { + ($best, @best) = ($s, $m); + } elsif( $s == $best ) { + push @best, $m; + } + } + $cache{$b,$me,wantarray} = wantarray ? $best[rand @best] : $best; +} + +my $winner = q[([XOxo])(?:\1\1|...\1...\1|..\1..\1|....\1....\1)]; +sub score { + my ($b, $me) = @_; + $b =~ m/$winner/o or return 0; + return $1 eq $me ? +1 : -1; +} + +sub moves { + my ($b) = @_; + $b =~ /([^xoXO,\n])/g; +} + +sub print_board { + my ($b) = @_; + $b =~ s/\B/|/g; + $b =~ s/,/\n-+-+-\n/g; + print $b, "\n"; +} + +sub prompt { + my ($b, $color) = @_; + my @moves = moves($b); + unless( @moves ) { + return; + } + while( 1 ) { + print "Place your $color on one of [@moves]: "; + defined(my $m = <>) or return; + chomp($m); + return $m if grep $m eq $_, @moves; + } +} + +my @players = ( + { whose => "your", name => "You", + verb => "You place", get_move => \&prompt }, + { whose => "the computer's", name => "Computer", + verb => "The computer places", get_move => \&best_move }, +); +my $whose_turn = int rand 2; + +my $color = "X"; +my $b = $initial; + +while( 1 ) { + my $p = $players[$whose_turn]; + print_board($b); + print "It is $p->{whose} turn.\n"; + # The parens around $m supply list context to the right side + # or the = operator, which causes sub best_move to return the + # best move, rather than the score of the best move. + my ( $m ) = $p->{get_move}->($b, $color); + if( $m ) { + print "$p->{verb} an $color at $m\n"; + $b =~ s/$m/$color/; + my $s = score($b, $color) or next; + print_board($b); + print "$p->{name} ", $s > 0 ? "won!\n" : "lost!\n"; + } else { + print "$p->{name} cannot move.\n"; + } + print "Game over.\nNew Game...\n"; + ($b, $color, $whose_turn) = ($initial, "X", int rand 2); + redo; +} continue { + $color = $reverse{$color}; + $whose_turn = !$whose_turn; +} diff --git a/Task/Tokenize-a-string/Frink/tokenize-a-string.frink b/Task/Tokenize-a-string/Frink/tokenize-a-string.frink new file mode 100644 index 0000000000..71c8676e09 --- /dev/null +++ b/Task/Tokenize-a-string/Frink/tokenize-a-string.frink @@ -0,0 +1 @@ +println[join[".", split[",", "Hello,How,Are,You,Today"]]] diff --git a/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal b/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal index 12e4f35e85..89f9241df6 100644 --- a/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal +++ b/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal @@ -2,16 +2,24 @@ program TokenizeString; {$mode objfpc}{$H+} +uses + SysUtils, Classes; const - CHelloStr = 'Hello,How,Are,You,Today'; + TestString = 'Hello,How,Are,You,Today'; var + Tokens: TStringList; I: Integer; - VResult: string = ''; begin - for I := 1 to Length(CHelloStr) do - if CHelloStr[I] = ',' then - VResult += LineEnding - else - VResult += CHelloStr[I]; - WriteLn(VResult); + // Uses FCL facilities, "harder" algorithm not implemented + Tokens := TStringList.Create; + try + Tokens.Delimiter := ','; + Tokens.DelimitedText := TestString; + Tokens.Delimiter := '.'; // For example + // To standard Output + WriteLn(Format('Tokenize from: "%s"', [TestString])); + WriteLn(Format('to: "%s"',[Tokens.DelimitedText])); + finally + Tokens.Free; + end; end. diff --git a/Task/Top-rank-per-group/Aime/top-rank-per-group.aime b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime index 94717a9f62..c205a6d01b 100644 --- a/Task/Top-rank-per-group/Aime/top-rank-per-group.aime +++ b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime @@ -5,7 +5,6 @@ Add_Employee(record employees, text name, text id, integer salary, l_bill(r_n_list(employees, name), -1, name, id, salary, department); } - void collect(record top, record employees) { @@ -28,7 +27,6 @@ collect(record top, record employees) if (l_q_integer(l_q_list(department, i), 2) < salary) { break; } - i += 1; } @@ -44,7 +42,6 @@ collect(record top, record employees) } while (r_greater(employees, name, name)); } - void print(record top) { @@ -72,7 +69,6 @@ print(record top) } while (r_greater(top, department, department)); } - integer main(void) { diff --git a/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk b/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk index c4f929020d..cd271b4a59 100644 --- a/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk +++ b/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk @@ -16,13 +16,11 @@ Add_Employee("Tim Sampair ", "E03033", 27000, "D101") Add_Employee("Kim Arlich ", "E10001", 57000, "D190") Add_Employee("Timothy Grove ", "E16398", 29900, "D190") - ; display top 3 ranks for each department Loop, %Department_0% ; all departments MsgBox,, % "Department: " Department_%A_Index% , % TopRank(3, Department_%A_Index%) - ;--------------------------------------------------------------------------- TopRank(N, Department) { ; find the top N salaries in each department ;--------------------------------------------------------------------------- @@ -46,7 +44,6 @@ TopRank(N, Department) { ; find the top N salaries in each department Return, Msg } - ;--------------------------------------------------------------------------- Add_Employee(Name, ID, Salary, Department) { ;--------------------------------------------------------------------------- diff --git a/Task/Top-rank-per-group/E/top-rank-per-group.e b/Task/Top-rank-per-group/E/top-rank-per-group.e new file mode 100644 index 0000000000..ba2eeb2231 --- /dev/null +++ b/Task/Top-rank-per-group/E/top-rank-per-group.e @@ -0,0 +1,39 @@ +/** Turn a list of arrays into a list of maps with the given keys. */ +def addKeys(keys, rows) { + def res := [].diverge() + for row in rows { res.push(__makeMap.fromColumns(keys, row)) } + return res.snapshot() +} + +def data := addKeys( + ["name", "id", "salary", "dept"], + [["Tyler Bennett", "E10297", 32000, "D101"], + ["John Rappl", "E21437", 47000, "D050"], + ["George Woltman", "E00127", 53500, "D101"], + ["Adam Smith", "E63535", 18000, "D202"], + ["Claire Buckman", "E39876", 27800, "D202"], + ["David McClellan", "E04242", 41500, "D101"], + ["Rich Holcomb", "E01234", 49500, "D202"], + ["Nathan Adams", "E41298", 21900, "D050"], + ["Richard Potter", "E43128", 15900, "D101"], + ["David Motsinger", "E27002", 19250, "D202"], + ["Tim Sampair", "E03033", 27000, "D101"], + ["Kim Arlich", "E10001", 57000, "D190"], + ["Timothy Grove", "E16398", 29900, "D190"]]) + +def topSalaries(n, out) { + var groups := [].asMap() + for row in data { + def [=> salary, => dept] | _ := row + def top := groups.fetch(dept, fn {[]}).with([-salary, row]).sort() + groups with= (dept, top.run(0, top.size().min(n))) + } + for dept => group in groups.sortKeys() { + out.println(`Department $dept`) + out.println(`---------------`) + for [_, row] in group { + out.println(`${row["id"]} $$${row["salary"]} ${row["name"]}`) + } + out.println() + } +} diff --git a/Task/Top-rank-per-group/Lua/top-rank-per-group.lua b/Task/Top-rank-per-group/Lua/top-rank-per-group.lua index fed5a157d0..cdb6c6047c 100644 --- a/Task/Top-rank-per-group/Lua/top-rank-per-group.lua +++ b/Task/Top-rank-per-group/Lua/top-rank-per-group.lua @@ -33,4 +33,4 @@ for i, _ in pairs( dep ) do print( "", dep[i][l][1], dep[i][l][2], dep[i][l][3] ) end print "" -end +end diff --git a/Task/Top-rank-per-group/PL-SQL/top-rank-per-group.sql b/Task/Top-rank-per-group/PL-SQL/top-rank-per-group.sql new file mode 100644 index 0000000000..32fb20f110 --- /dev/null +++ b/Task/Top-rank-per-group/PL-SQL/top-rank-per-group.sql @@ -0,0 +1,108 @@ +create or replace procedure "Top rank per group"(TOP_N in pls_integer default 3) as + cursor CSR_EMP(TOP_N pls_integer) is + select case LINE + when 10 then + 'Tot.' || LPAD(POPULATION, 2) || ' Employees in ' || TIE_COUNT || + ' deps.Avg salary:' || TO_CHAR(SALARY, '99990.99') + when 30 then + '-' + when 50 then + 'Department: ' || DEPT_ID || ', pop: ' || POPULATION || + '. Avg Salary: ' || TO_CHAR(SALARY, '99990.99') + when 70 then + LPAD('Employee ID', 14) || LPAD('Employee name', 20) || + LPAD('Salary', 9) || 'Rank' + when 90 then + LPAD('+', 14, '-') || LPAD('+', 20, '-') || LPAD('+', 9, '-') || + LPAD('+', 4, '-') + else + LPAD(' ', 8) || LPAD(EMP_ID, 6) || LPAD(EMP_NAME, 20) || + TO_CHAR(SALARY, '99990.99') || + LPAD(case when TIE_COUNT = 1 then ' ' else 'T' end || RANK, 4) + end "Top rank per group" + from (select 10 LINE + ,null EMP_ID + ,null EMP_NAME + ,' ' DEPT_ID + ,avg(SALARY) SALARY + ,0 RANK + ,count(distinct DEPT_ID) TIE_COUNT + ,count(*) POPULATION + from EMP + union all + select 30 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,0 SALARY + ,0 RANK + ,0 TIE_COUNT + ,0 POPULATION + from EMP + group by DEPT_ID + union all + select 50 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,avg(SALARY) SALARY + ,0 RANK + ,0 TIE_COUNT + ,count(*) POPULATION + from EMP + group by DEPT_ID + union all + select 70 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,0 SALARY + ,0 RANK + ,0 TIE_COUNT + ,0 POPULATION + from EMP + group by DEPT_ID + union all + select 90 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,0 SALARY + ,0 RANK + ,0 TIE_COUNT + ,0 POPULATION + from EMP + group by DEPT_ID + union all + select 110 LINE + ,EMP_ID + ,EMP_NAME + ,DEPT_ID + ,SALARY + ,(select count(distinct EMP4.SALARY) + from EMP EMP4 + where EMP4.DEPT_ID = EMP3.DEPT_ID + and EMP4.SALARY >= EMP3.SALARY) RANK + ,(select count(*) + from EMP EMP2 + where EMP2.DEPT_ID = EMP3.DEPT_ID + and EMP2.SALARY = EMP3.SALARY) TIE_COUNT + ,0 POPULATION + from EMP EMP3 + where TOP_N >= -- Here is the meat, Correlated subquery + (select count(distinct EMP4.SALARY) + from EMP EMP4 + where EMP4.DEPT_ID = EMP3.DEPT_ID + and EMP4.SALARY >= EMP3.SALARY)) + order by DEPT_ID + ,LINE + ,SALARY desc + ,EMP_ID; + + V_EMP CSR_EMP%rowtype; +begin + for V_EMP in CSR_EMP(TOP_N) + loop + DBMS_OUTPUT.PUT_LINE(v_emp."Top rank per group"); + end loop; +end; diff --git a/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 b/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 index ff37df75a7..0d545119e2 100644 --- a/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 +++ b/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 @@ -1,24 +1,29 @@ -my @data = ( - [< E10297 32000 D101 Tyler_Bennett >], - [< E21437 47000 D050 John_Rappl >], - [< E00127 53500 D101 George_Woltman >], - [< E63535 18000 D202 Adam_Smith >], - [< E39876 27800 D202 Claire_Buckman >], - [< E04242 41500 D101 David_McClellan >], - [< E01234 49500 D202 Rich_Holcomb >], - [< E41298 21900 D050 Nathan_Adams >], - [< E43128 15900 D101 Richard_Potter >], - [< E27002 19250 D202 David_Motsinger >], - [< E03033 27000 D101 Tim_Sampair >], - [< E10001 57000 D190 Kim_Arlich >], - [< E16398 29900 D190 Timothy_Grove >], -).map: { item %( < id salary dept name > Z=> .list ) } +my @data = do for q:to/---/.lines -> $line { + E10297 32000 D101 Tyler Bennett + E21437 47000 D050 John Rappl + E00127 53500 D101 George Woltman + E63535 18000 D202 Adam Smith + E39876 27800 D202 Claire Buckman + E04242 41500 D101 David McClellan + E01234 49500 D202 Rich Holcomb + E41298 21900 D050 Nathan Adams + E43128 15900 D101 Richard Potter + E27002 19250 D202 David Motsinger + E03033 27000 D101 Tim Sampair + E10001 57000 D190 Kim Arlich + E16398 29900 D190 Timothy Grove + --- -sub MAIN($N as Int = 3) { - my $cont = 0; - for @data.classify({ . }).sort».value { - my @es = .sort({ -. }); - print "\n" if $cont++; - say .< dept id salary name >.Str if .so for @es[^$N]; + $%( < Id Salary Dept Name > + Z=> + $line.split(/ \t+ /) + ) +} + +sub MAIN(Int $N = 3) { + for @data.classify({ . }).sort».value { + my @es = .sort: { -. } + say '' if (state $bline)++; + say .< Dept Id Salary Name > for @es[^$N]:v; } } diff --git a/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx b/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx new file mode 100644 index 0000000000..ba33c850ed --- /dev/null +++ b/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx @@ -0,0 +1,42 @@ +/*REXX program shows top N salaries in each department (internal table).*/ +parse arg topN . /*get number for top N salaries. */ +if topN=='' then topN=1 /*if none, then assume only 1. */ +say 'Finding top' topN 'salaries in each department.'; say +@.= /*employee name, ID, salary, dept.*/ + @.1 = "Tyler Bennett,E10297,32000,D101" + @.2 = "John Rappl,E21437,47000,D050" + @.3 = "George Woltman,E00127,53500,D101" + @.4 = "Adam Smith,E63535,18000,D202" + @.5 = "Claire Buckman,E39876,27800,D202" + @.6 = "David McClellan,E04242,41500,D101" + @.7 = "Rich Holcomb,E01234,49500,D202" + @.8 = "Nathan Adams,E41298,21900,D050" + @.9 = "Richard Potter,E43128,15900,D101" + @.10 = "David Motsinger,E27002,19250,D202" + @.11 = "Tim Sampair,E03033,27000,D101" + @.12 = "Kim Arlich,E10001,57000,D190" + @.13 = "Timothy Grove,E16398,29900,D190" +depts= + do j=1 until @.j=='' /*build the database elements. */ + parse var @.j name.j ',' id.j "," sal.j ',' dept.j + if wordpos(dept.j,depts)==0 then depts=depts dept.j + end /*j*/ +employees=j-1 +#d=words(depts) +say employees 'employees,' #d "departments:" depts; say + + do dep=1 for #d; say /*process each department. */ + Xdept=word(depts,dep) /*current dept. being processed. */ + do topN; highSal=0 /*process the top N salaries. */ + h=0 /*point to the highest paid emp. */ + do e=1 for employees /*process each employee in Dept. */ + if dept.e\==Xdept | sal.e'NUM' Then /* Argument is not a number */ + Call exit 'Invalid argument ('topn'). Must be a number!' + Otherwise + Nop + End +Parse Value '0 0 0 0' with en dn esal. de. deptl + /*employee name, ID, salary, dept.*/ +Call read "Tyler Bennett,E10297,32000,D101" +Call read "George Woltman,E00127,53500,D101" +Call read "John Rappl,E21437,47000,D050" +Call read "Adam Smith,E63535,18000,D202" +Call read "Claire Buckman,E39876,27800,D202" +Call read "David McClellan,E04242,41500,D101" +Call read "Rich Holcomb,E01234,49500,D202" +Call read "Nathan Adams,E41298,21900,D050" +Call read "Richard Potter,E43128,15900,D101" +Call read "David Motsinger,E27002,19250,D202" +Call read "Tim Sampair,E03033,27000,D101" +Call read "Kim Arlich,E10001,57000,D190" +Call read "Timothy Grove,E16398,29900,D190" +Say en 'employees,' dn "departments:" deptl +Do e=1 To en + d=dept.e + Do di=1 To de.d + If esal.d.di'' + Parse Var deptl d deptl + Do i=1 To min(topn,de.d) + id=enum.d.i + Say 'department: 'd' $'esal.d.i id name.id + End + Say ' ' + End +Exit + +read: +en=en+1 +Parse Arg name ',' id.en "," sal.en ',' dept.en +If wordpos(dept.en,deptl)=0 Then Do + dn=dn+1 + deptl=deptl dept.en + End +z=id.en +name.z=name +Return + +exit: Say arg(1) +help: Say 'Syntax: rexx topsal [topn]' + Exit diff --git a/Task/Top-rank-per-group/REXX/top-rank-per-group.rexx b/Task/Top-rank-per-group/REXX/top-rank-per-group.rexx deleted file mode 100644 index 8cb6c2a316..0000000000 --- a/Task/Top-rank-per-group/REXX/top-rank-per-group.rexx +++ /dev/null @@ -1,47 +0,0 @@ -/*REXX program shows top N salaries in each department (internal table).*/ -parse arg topN . /*get number for top N salaries. */ -if topN=='' then topN=1 /*if none, then assume only 1. */ -say 'Finding top' topN 'salaries in each department.'; say -@.= - /*employee name, ID, salary, dept.*/ - @.1="Tyler Bennett,E10297,32000,D101" - @.2="John Rappl,E21437,47000,D050" - @.3="George Woltman,E00127,53500,D101" - @.4="Adam Smith,E63535,18000,D202" - @.5="Claire Buckman,E39876,27800,D202" - @.6="David McClellan,E04242,41500,D101" - @.7="Rich Holcomb,E01234,49500,D202" - @.8="Nathan Adams,E41298,21900,D050" - @.9="Richard Potter,E43128,15900,D101" -@.10="David Motsinger,E27002,19250,D202" -@.11="Tim Sampair,E03033,27000,D101" -@.12="Kim Arlich,E10001,57000,D190" -@.13="Timothy Grove,E16398,29900,D190" -depts= - do j=1 until @.j=='' /*build database elements. */ - parse var @.j name.j ',' id.j "," sal.j ',' dept.j - if wordpos(dept.j,depts)==0 then depts=depts dept.j - end /*j*/ -employees=j-1 -#d=words(depts) -say employees 'employees,' #d "departments:" depts; say - - do dep=1 for #d /*process each department. */ - Xdept=word(depts,dep) /*current dept. being processed. */ - - do topN /*process the top N salaries. */ - highsal=0 /*highest salary (so far). */ - h=0 /*point to the highest paid emp. */ - do e=1 for employees /*process each employee in Dept. */ - if dept.e\==Xdept | sal.e= EMP3.SALARY) RANK + ,(select count(*) + from EMP EMP2 + where EMP2.DEPT_ID = EMP3.DEPT_ID + and EMP2.SALARY = EMP3.SALARY) TIE_COUNT + ,0 POPULATION + from EMP EMP3 + where $topN >= -- Here is the meat, Correlated subquery + (select count(distinct EMP4.SALARY) + from EMP EMP4 + where EMP4.DEPT_ID = EMP3.DEPT_ID + and EMP4.SALARY >= EMP3.SALARY)) + order by DEPT_ID ,LINE ,SALARY desc, EMP_ID; diff --git a/Task/Top-rank-per-group/Scala/top-rank-per-group-1.scala b/Task/Top-rank-per-group/Scala/top-rank-per-group-1.scala new file mode 100644 index 0000000000..e4a76074c0 --- /dev/null +++ b/Task/Top-rank-per-group/Scala/top-rank-per-group-1.scala @@ -0,0 +1,58 @@ +import scala.io.Source +import scala.language.implicitConversions +import scala.language.reflectiveCalls +import scala.collection.immutable.TreeMap + +object TopRank extends App { + val topN = 3 + + val rawData = """Employee Name;Employee ID;Salary;Department + |Tyler Bennett;E10297;32000;D101 + |John Rappl;E21437;47000;D050 + |George Woltman;E00127;53500;D101 + |Adam Smith;E63535;18000;D202 + |Claire Buckman;E39876;27800;D202 + |David McClellan;E04242;41500;D101 + |Rich Holcomb;E01234;49500;D202 + |Nathan Adams;E41298;21900;D050 + |Richard Potter;E43128;15900;D101 + |David Motsinger;E27002;19250;D202 + |Tim Sampair;E03033;27000;D101 + |Kim Arlich;E10001;57000;D190 + |Timothy Grove;E16398;29900;D190""".stripMargin + + class Employee(name: String, id: String, + val salary: Int, + val department: String) { + override def toString = s"$id\t$salary\t$name" + } + + // A TreeMap has sorted keys + val data: TreeMap[String, Seq[TopRank.Employee]] = // TreeMap is a sorted map + TreeMap((Source.fromString(rawData) getLines ()).toSeq // Runtime parsing + .drop(1) // Drop header + .map(_.split(";")) //read fields into list of employees + .map(emp => new Employee(emp(0), emp(1), emp(2).toInt, emp(3))) + .groupBy(_.department).toSeq: _*) + + implicit def iterableWithAvg[T: Numeric](data: Iterable[T]) = new { + def average[T](ts: Iterable[T])(implicit num: Numeric[T]) = { + num.toDouble(ts.sum) / ts.size + } + def avg = average(data) + } + + val a = data.flatMap { case (_, emps) => emps.map(_.salary) }.avg + + println(s"Reporting top $topN salaries in each department.\n") + + println(s"Total of ${data.foldLeft(0)(_ + _._2.size)} employees in ${data.size} departments") + + println(f"Average salary: $a%8.2f\n") + + data.foreach { + case (dep, emps) => println(f"Department: $dep pop: ${emps.size} avg: ${emps.map(_.salary).avg}%8.2f\n" + + emps.sortBy(-_.salary).take(topN) + .map(_.toString).mkString("\t", "\n\t", "")) + } +} diff --git a/Task/Top-rank-per-group/Scala/top-rank-per-group-2.scala b/Task/Top-rank-per-group/Scala/top-rank-per-group-2.scala new file mode 100644 index 0000000000..2698f4f1ba --- /dev/null +++ b/Task/Top-rank-per-group/Scala/top-rank-per-group-2.scala @@ -0,0 +1,152 @@ +import scala.slick.driver.H2Driver.simple._ +import scala.slick.lifted.ProvenShape + +// A Employees table with 4 columns: Employee ID, Employee Name, Department, Salary +class Emp(tag: Tag) extends Table[(String, String, String, Double)](tag, "EMP") { + def id: Column[String] = column[String]("EMP_ID", O.PrimaryKey) // This is the primary key column + def name: Column[String] = column[String]("EMP_NAME", O.NotNull) + def deptId: Column[String] = column[String]("DEPT_ID", O.NotNull) + def salary: Column[Double] = column[Double]("SALARY", O.NotNull) + + // Every table needs a * projection with the same type as the table's type parameter + def * : ProvenShape[(String, String, String, Double)] = (id, name, deptId, salary) +} + +// The main application +object TopNrankSLICK extends App { + + val topN = 3 + + // The query interface for the Emp table + val employees = TableQuery[Emp] + + // Create a connection (called a "session") to an in-memory H2 database + Database.forURL("jdbc:h2:mem:hello", driver = "org.h2.Driver").withSession { + implicit session => + + // Create the schema + employees.ddl.create + + // Fill the database + val employeesInsertResult: Option[Int] = employees ++= Seq( + ("E10297", "Tyler Bennett", "D101", 32000), + ("E21437", "John Rappl", "D050", 47000), + ("E00127", "George Woltman", "D101", 53500), + ("E63535", "Adam Smith", "D202", 18000), + ("E39876", "Claire Buckman", "D202", 27800), + ("E04242", "David McClellan", "D101", 41500), + ("E01234", "Rich Holcomb", "D202", 49500), + ("E41298", "Nathan Adams", "D050", 21900), + ("E43128", "Richard Potter", "D101", 15900), + ("E27002", "David Motsinger", "D202", 19250), + ("E03033", "Tim Sampair", "D101", 27000), + ("E10001", "Kim Arlich", "D190", 57000), + ("E16398", "Timothy Grove", "D190", 29900), + ("E16399", "Timothy Grave", "D190", 29900), + ("E16400", "Timothy Grive", "D190", 29900)) + + /* Manual SQL / String Interpolation */ + // Required import for the sql interpolator + import scala.slick.jdbc.StaticQuery.interpolation + + // Construct a SQL statement manually with an interpolated value + val plainQuery = // First the bun - formatting SELECT clause + sql"""select case LINE + when 10 then + 'Tot.' || LPAD(POPULATION, 2) || ' Employees in ' || TIE_COUNT || + ' deps.Avg salary:' || TO_CHAR(SALARY, '99990.99') + when 30 then + '-' + when 50 then + 'Department: ' || DEPT_ID || ', pop: ' || POPULATION || + '. Avg Salary: ' || TO_CHAR(SALARY, '99990.99') + when 70 then + LPAD('Employee ID', 14) || LPAD('Employee name', 20) || + LPAD('Salary', 9) || 'Rank' + when 90 then + LPAD('+', 14, '-') || LPAD('+', 20, '-') || LPAD('+', 9, '-') || + LPAD('+', 4, '-') + else + LPAD(' ', 8) || LPAD(EMP_ID, 6) || LPAD(EMP_NAME, 20) || + TO_CHAR(SALARY, '99990.99') || LPAD(case when TIE_COUNT = 1 then ' ' else 'T' end || RANK, 4) + end "Top rank per group" + from (select 10 LINE + ,null EMP_ID + ,null EMP_NAME + ,' ' DEPT_ID + ,avg(SALARY) SALARY + ,0 RANK + ,count(distinct DEPT_ID) TIE_COUNT + ,count(*) POPULATION + from EMP + union all + select 30 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,0 SALARY + ,0 RANK + ,0 TIE_COUNT + ,0 POPULATION + from EMP + group by DEPT_ID + union all + select 50 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,avg(SALARY) SALARY + ,0 RANK + ,0 TIE_COUNT + ,count(*) POPULATION + from EMP + group by DEPT_ID + union all + select 70 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,0 SALARY + ,0 RANK + ,0 TIE_COUNT + ,0 POPULATION + from EMP + group by DEPT_ID + union all + select 90 LINE + ,null EMP_ID + ,null EMP_NAME + ,DEPT_ID + ,0 SALARY + ,0 RANK + ,0 TIE_COUNT + ,0 POPULATION + from EMP + group by DEPT_ID + union all + select 110 LINE + ,EMP_ID + ,EMP_NAME + ,DEPT_ID + ,SALARY + ,(select count(distinct EMP4.SALARY) + from EMP EMP4 + where EMP4.DEPT_ID = EMP3.DEPT_ID + and EMP4.SALARY >= EMP3.SALARY) RANK + ,(select count(*) + from EMP EMP2 + where EMP2.DEPT_ID = EMP3.DEPT_ID + and EMP2.SALARY = EMP3.SALARY) TIE_COUNT + ,0 POPULATION + from EMP EMP3 + where $topN >= -- Here is the meat, Correlated subquery + (select count(distinct EMP4.SALARY) + from EMP EMP4 + where EMP4.DEPT_ID = EMP3.DEPT_ID + and EMP4.SALARY >= EMP3.SALARY)) + order by DEPT_ID ,LINE ,SALARY desc, EMP_ID""".as[String] + + // Execute the query + plainQuery.foreach(println(_)) + } // session +} // TopNrankSLICK diff --git a/Task/Top-rank-per-group/Scala/top-rank-per-group.scala b/Task/Top-rank-per-group/Scala/top-rank-per-group.scala deleted file mode 100644 index 383db88067..0000000000 --- a/Task/Top-rank-per-group/Scala/top-rank-per-group.scala +++ /dev/null @@ -1,34 +0,0 @@ -import scala.io._ - -object TopRank extends App { - val data = """Employee Name,Employee ID,Salary,Department -Tyler Bennett,E10297,32000,D101 -John Rappl,E21437,47000,D050 -George Woltman,E00127,53500,D101 -Adam Smith,E63535,18000,D202 -Claire Buckman,E39876,27800,D202 -David McClellan,E04242,41500,D101 -Rich Holcomb,E01234,49500,D202 -Nathan Adams,E41298,21900,D050 -Richard Potter,E43128,15900,D101 -David Motsinger,E27002,19250,D202 -Tim Sampair,E03033,27000,D101 -Kim Arlich,E10001,57000,D190 -Timothy Grove,E16398,29900,D190""" - - class Employee(val name: String, - val id: String, - val salary: Int, - val department: String) { - override def toString = s"$id\t$salary\t$name" - } - - (for { x <- (Source.fromString(data).getLines().drop(1).map(_.split(","))) } - yield new Employee(x(0), x(1), x(2).toInt, x(3))) // read data into list of employees - .toList.sortBy(x => (x.department, -x.salary)) - .groupBy(_.department) // sort and group by - .foreach { - case (dep, emps) => println(s"Department: $dep\n" - + emps.take(3).map(_.toString).mkString("\t", "\n\t", "")) - } -} diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-1.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-1.txr new file mode 100644 index 0000000000..7e512a7fb1 --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-1.txr @@ -0,0 +1,23 @@ +@(next :args) +@{n-param} +@(next "top-rank-per-group.dat") +Employee Name,Employee ID,Salary,Department +@(collect :vars (record)) +@name,@id,@salary,@dept +@(bind record (@(int-str salary) dept name id)) +@(end) +@(bind (dept salary dept2 name id) + @(let* ((n (int-str n-param)) + (dept-hash [group-by second record :equal-based]) + (dept (hash-keys dept-hash)) + (ranked (collect-each ((rec (hash-values dept-hash))) + [apply mapcar list [[sort rec > first] 0..n]]))) + (cons dept [apply mapcar list ranked]))) +@(output) +@ (repeat) +Department: @dept +@ (repeat) + @{name 15} (@id) $@{salary -6} +@ (end) +@ (end) +@(end) diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-2.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-2.txr new file mode 100644 index 0000000000..ddf4bfc77b --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-2.txr @@ -0,0 +1 @@ +@(next :args) diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-3.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-3.txr new file mode 100644 index 0000000000..fc70872e65 --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-3.txr @@ -0,0 +1 @@ +@{n-param} diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-4.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-4.txr new file mode 100644 index 0000000000..4fec5ef49d --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-4.txr @@ -0,0 +1 @@ +@(next "top-rank-per-group.dat") diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-5.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-5.txr new file mode 100644 index 0000000000..b53d8fa79d --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-5.txr @@ -0,0 +1 @@ +Employee Name,Employee ID,Salary,Department diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-6.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-6.txr new file mode 100644 index 0000000000..3048cecef9 --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-6.txr @@ -0,0 +1,4 @@ +@(collect :vars (record)) +@name,@id,@salary,@dept +@(bind record (@(int-str salary) dept name id)) +@(end) diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-7.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-7.txr new file mode 100644 index 0000000000..20e9d0a6e6 --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-7.txr @@ -0,0 +1,7 @@ +@(bind (dept salary dept2 name id) + @(let* ((n (int-str n-param)) + (dept-hash [group-by second record :equal-based]) + (dept (hash-keys dept-hash)) + (ranked (collect-each ((rec (hash-values dept-hash))) + [apply mapcar list [[sort rec > first] 0..n]]))) + (cons dept [apply mapcar list ranked]))) diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-8.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-8.txr new file mode 100644 index 0000000000..2f77aa6862 --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-8.txr @@ -0,0 +1,8 @@ +@(output) +@ (repeat) +Department: @dept +@ (repeat) + @{name 15} (@id) $@{salary -6} +@ (end) +@ (end) +@(end) diff --git a/Task/Top-rank-per-group/TXR/top-rank-per-group-9.txr b/Task/Top-rank-per-group/TXR/top-rank-per-group-9.txr new file mode 100644 index 0000000000..f415f1f9a7 --- /dev/null +++ b/Task/Top-rank-per-group/TXR/top-rank-per-group-9.txr @@ -0,0 +1,18 @@ +@(next :args) +@{n-param} +@(next "top-rank-per-group.dat") +Employee Name,Employee ID,Salary,Department +@(collect :vars (record)) +@name,@id,@salary,@dept +@(bind record (@(int-str salary) dept name id)) +@(end) +@(do + (let* ((n (int-str n-param)) + (dept-hash [group-by second record :equal-based]) + (ranked (collect-each ((rec (hash-values dept-hash))) + [[sort rec > first] 0..n]))) + (each ((d (hash-keys dept-hash)) + (dept-recs ranked)) + (put-line `Department: @d`) + (each ((r dept-recs)) + (put-line ` @{r[2] 15} (@{r[3]}) $@{r[0] -6}`))))) diff --git a/Task/Topic-variable/PARI-GP/topic-variable.pari b/Task/Topic-variable/PARI-GP/topic-variable.pari new file mode 100644 index 0000000000..8b1f575168 --- /dev/null +++ b/Task/Topic-variable/PARI-GP/topic-variable.pari @@ -0,0 +1,2 @@ +3 +[sqrt(%),%^2] diff --git a/Task/Topswops/AutoHotkey/topswops-1.ahk b/Task/Topswops/AutoHotkey/topswops-1.ahk new file mode 100644 index 0000000000..6a13bbe623 --- /dev/null +++ b/Task/Topswops/AutoHotkey/topswops-1.ahk @@ -0,0 +1,12 @@ +Topswops(Obj, n){ + R := [] + for i, val in obj{ + if (i <=n) + res := val (A_Index=1?"":",") res + else + res .= "," val + } + Loop, Parse, res, `, + R[A_Index]:= A_LoopField + return R +} diff --git a/Task/Topswops/AutoHotkey/topswops-2.ahk b/Task/Topswops/AutoHotkey/topswops-2.ahk new file mode 100644 index 0000000000..9df3610e3d --- /dev/null +++ b/Task/Topswops/AutoHotkey/topswops-2.ahk @@ -0,0 +1,14 @@ +Cards := [2, 4, 1, 3] +Res := Print(Cards) +while (Cards[1]<>1) +{ + Cards := Topswops(Cards, Cards[1]) + Res .= "`n"Print(Cards) +} +MsgBox % Res + +Print(M){ + for i, val in M + Res .= (A_Index=1?"":"`t") val + return Trim(Res,"`n") +} diff --git a/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk b/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk index 50dd04054b..8b6c06bc58 100644 --- a/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk +++ b/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk @@ -11,3 +11,4 @@ move(n, from, to, via) ;n = # of disks, from = start pole, to = end pole, via = move(n-1, via, to, from) } } +move(64, 1, 3, 2) diff --git a/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m index 8191089970..f5c5694d11 100644 --- a/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m +++ b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m @@ -2,18 +2,19 @@ #import "TowersOfHanoi.h" int main( int argc, const char *argv[] ) { - TowersOfHanoi *tower = [[TowersOfHanoi alloc] init]; + @autoreleasepool { - int from = 1; - int to = 3; - int via = 2; - int disks = 3; + TowersOfHanoi *tower = [[TowersOfHanoi alloc] init]; - [tower setPegFrom: from andSetPegTo: to andSetPegVia: via andSetNumDisks: disks]; + int from = 1; + int to = 3; + int via = 2; + int disks = 3; - [tower movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: disks]; + [tower setPegFrom: from andSetPegTo: to andSetPegVia: via andSetNumDisks: disks]; - [tower release]; + [tower movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: disks]; + } return 0; } diff --git a/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 b/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 index e88e1702ec..3e96989e67 100644 --- a/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 +++ b/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 @@ -1,4 +1,4 @@ -subset Peg of Int where * == 1|2|3; +subset Peg of Int where 1|2|3; multi hanoi (0, Peg $a, Peg $b, Peg $c) { } multi hanoi (Int $n, Peg $a = 1, Peg $b = 2, Peg $c = 3) { diff --git a/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust b/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust index 3aa300aa82..502e9b25b2 100644 --- a/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust +++ b/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust @@ -1,7 +1,7 @@ fn move(n: int, from: int, to: int, via: int) { if (n > 0) { move(n - 1, from, via, to); - println(fmt!("Move disk from pole %d to pole %d", from, to)); + println!("Move disk from pole {:d} to pole {:d}", from, to); move(n - 1, via, to, from); } } diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Forth/trabb-pardo-knuth-algorithm.fth b/Task/Trabb-Pardo-Knuth-algorithm/Forth/trabb-pardo-knuth-algorithm.fth new file mode 100644 index 0000000000..660a775add --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Forth/trabb-pardo-knuth-algorithm.fth @@ -0,0 +1,40 @@ +: f(x) fdup fsqrt fswap 3e f** 5e f* f+ ; + +4e2 fconstant f-too-big + +11 Constant #Elements + +: float-array ( compile: n -- / run: n -- addr ) + create + floats allot + does> + swap floats + ; + +#Elements float-array vec + +: get-it ( -- ) + ." Enter " #Elements . ." numbers:" cr + #Elements 0 DO + ." > " pad 25 accept cr + pad swap >float 0= abort" Invalid Number" + i vec F! + LOOP ; + +: reverse-it ( -- ) + #Elements 2/ 0 DO + i vec F@ #Elements i - 1- vec F@ + i vec F! #Elements i - 1- vec F! + LOOP ; + +: do-it ( -- ) + #Elements 0 DO + i vec F@ fdup f. [char] : emit space + f(x) fdup f-too-big f> IF + fdrop ." too large" + ELSE + f. + THEN cr + LOOP ; + +: tpk ( -- ) + get-it reverse-it do-it ; diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m b/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m index 0e121d9450..dfcb3e1feb 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m +++ b/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m @@ -23,11 +23,11 @@ int main (int argc, const char * argv[]) double userInput = 0.0; printf("%s", "Please enter a number: "); scanf("%lf", &userInput); - [input addObject: [NSNumber numberWithDouble: (double) userInput]]; + [input addObject: @(userInput)]; } for(int i = 10; i >= 0; i--) { - double x = [[input objectAtIndex: i] doubleValue]; + double x = [input[i] doubleValue]; double y = f(x); printf("f(%.2f) \t=\t", x); if(y < 400.0) { 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 aff45b02fa..336270640c 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 @@ -1,10 +1,10 @@ -/*REXX program to implement the Trabb-Pardo-Knuth algorthm for N nums.*/ +/*REXX program to implement the Trabb-Pardo-Knuth algorithm for N nums.*/ N=11 /*N is the number of numbers. */ maxValue=400 /*the maximum value f(x) can have*/ precDigs=200 /*compute with this many digits. */ showDigs=20 /*...but only show this many digs*/ numeric digits precDigs /*the number of digits precision.*/ -prompt='enter' N "nunbers for the Trabb-Pardo-Knuth algorthm: (or Quit)" +prompt='enter' N "numbers for the Trabb-Pardo-Knuth algorithm: (or Quit)" say ' _____ ' /*vinculum.*/ say 'function: ƒ(x) ≡ √ │x│ + (5 * x^3)' /*██████████████████████████████████████████████████████████████████████*/ diff --git a/Task/Trigonometric-functions/PARI-GP/trigonometric-functions.pari b/Task/Trigonometric-functions/PARI-GP/trigonometric-functions-1.pari similarity index 100% rename from Task/Trigonometric-functions/PARI-GP/trigonometric-functions.pari rename to Task/Trigonometric-functions/PARI-GP/trigonometric-functions-1.pari diff --git a/Task/Trigonometric-functions/PARI-GP/trigonometric-functions-2.pari b/Task/Trigonometric-functions/PARI-GP/trigonometric-functions-2.pari new file mode 100644 index 0000000000..821e53a832 --- /dev/null +++ b/Task/Trigonometric-functions/PARI-GP/trigonometric-functions-2.pari @@ -0,0 +1 @@ +apply(f->f(1), [cos,sin,tan,acos,asin,atan]) diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx index 18db955584..f1a92bc988 100644 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx @@ -4,7 +4,7 @@ numeric digits showdigs+10 /*DIGITS default is 9, but use */ /*extra digs to prevent rounding.*/ say 'Using' showdigs 'decimal digits precision.'; say - do j=-180 to +180 by 15 /*let's just do a half-Monty. */ + 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)) @@ -13,7 +13,7 @@ say 'Using' showdigs 'decimal digits precision.'; say say stuff end /*j*/ -say; do k=-1 to +1 by 1/2 /*keep the Arc-functions happy. */ +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)), @@ -21,21 +21,21 @@ say; do k=-1 to +1 by 1/2 /*keep the Arc-functions happy. */ end /*k*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ -Asin: procedure; arg x; if x<-1 | x>1 then call AsinErr; s=x*x - if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z +Asin: procedure; parse arg x 1 z 1 o 1 p; if x<-1 | x>1 then call AsinErr + s=x*x; if abs(x)>=sqrt(2)*.5 then return sign(x)*Acos(sqrt(1-s)) do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end return z -Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x) - return Asin(x/sqrt(1+x**2)) +Atan: procedure; parse arg x; if abs(x)=1 then return pi()*.25*sign(x) + return Asin(x/sqrt(1+x*x)) -cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) - if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0 - if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5 +cos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) + if a=pi() then return -1; if a=pi()*.5 | a=pi()*2 then return 0 + pi3=pi()/3; if a=pi3 then return .5; if a=2*pi3 then return -.5 return .sinCos(1,1,-1) -sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) - if abs(x)=pi() then return 0; return .sinCos(x,x,1) +sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5,digits()-3) + if abs(x)=pi() then return 0; return .sinCos(x,x,1) .sinCos: parse arg z 1 p,_,i; x=x*x do k=2 by 2; _=-_*x/(k*(k+i));z=z+_;if z=p then leave;p=z;end; return z @@ -44,41 +44,42 @@ sqrt: procedure; parse arg x; if x=0 then return 0; m.=9; p=digits(); i= numeric digits 9; if x<0 then do; x=-x; i='i'; end; numeric form; m.0=p parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2; m.1=p do j=2 while p>9; m.j=p; p=p%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=.5*(g+x/g); end /*k*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ numeric digits m.0; return (g/1)i e: return, 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 - /*Note: the "real: E subroutine returns E's accuracy that */ + /*Note: the actual E subroutine returns E's accuracy that */ /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ /*If more than 1 million digits are required, be patient. */ -exp: procedure; arg x; ix=x%1; if abs(x-ix)>.5 then ix=ix+sign(x); x=x-ix +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=z*e()**ix; return z + if z\==0 then z=e()**ix*z; return z pi: return, /*a bit of overkill, but hey !! */ 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 - /*Note: the real PI subroutine returns PI's accuracy that */ + /*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. */ /*If more than 1 million digits are required, be patient. */ -Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) +Acos: procedure; parse arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) AcosD: return r2d(Acos(arg(1))) AsinD: return r2d(Asin(arg(1))) cosD: return cos(d2r(arg(1))) -sinD: return sin(d2r(arg(1))) -tan: procedure; arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ +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►1 unit circle*/ -d2r: return r2r(arg(1)*pi()/180) /*convert degrees ──► radians. */ -r2d: return d2d((arg(1)*180/pi())) /*convert radians ──► degrees. */ -r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ +d2d: return arg(1)//360 /*normalize degrees►1 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 +sqrtErr: call tellErr "sqrt(x), X can't be negative, X="||x /* ┌───────────────────────────────────────────────────────────────┐ │ Not included here are (among others): │ │ some of the usual higher-math functions normally associated │ diff --git a/Task/Truncatable-primes/AutoHotkey/truncatable-primes.ahk b/Task/Truncatable-primes/AutoHotkey/truncatable-primes.ahk new file mode 100644 index 0000000000..3b287b4371 --- /dev/null +++ b/Task/Truncatable-primes/AutoHotkey/truncatable-primes.ahk @@ -0,0 +1,56 @@ +SetBatchLines, -1 +MsgBox, % "Largest left-truncatable and right-truncatable primes less than one million:`n" + . "Left:`t" LTP(10 ** 6) "`nRight:`t" RTP(10 ** 6) + +LTP(n) { + while n { + n-- + if (!Instr(n, "0") && IsPrime(n)) { + Loop, % StrLen(n) + if (!IsPrime(SubStr(n, A_Index))) + continue, 2 + break + } + } + return, n +} + +RTP(n) { + while n { + n-- + if (!IsPrime(SubStr(n, 1, 1))) + n -= 10 ** (StrLen(n) - 1) + if (!Instr(n, "0") && IsPrime(n)) { + Loop, % StrLen(n) + if (!IsPrime(SubStr(n, 1, A_Index))) + continue, 2 + break + } + } + return, n +} + +IsPrime(n) { + if (n < 2) + return, 0 + else if (n < 4) + return, 1 + else if (!Mod(n, 2)) + return, 0 + else if (n < 9) + return 1 + else if (!Mod(n, 3)) + return, 0 + else { + r := Floor(Sqrt(n)) + f := 5 + while (f <= r) { + if (!Mod(n, f)) + return, 0 + if (!Mod(n, (f + 2))) + return, 0 + f += 6 + } + return, 1 + } +} diff --git a/Task/Truncatable-primes/D/truncatable-primes.d b/Task/Truncatable-primes/D/truncatable-primes.d index b56826eb65..3b6ec93555 100644 --- a/Task/Truncatable-primes/D/truncatable-primes.d +++ b/Task/Truncatable-primes/D/truncatable-primes.d @@ -4,7 +4,7 @@ import std.stdio, std.math, std.string, std.conv, std.algorithm, bool isPrime(in int n) pure nothrow { if (n <= 1) return false; - foreach (immutable i; 2 .. cast(int)sqrt(cast(real)n) + 1) + foreach (immutable i; 2 .. cast(int)sqrt(real(n)) + 1) if (!(n % i)) return false; return true; diff --git a/Task/Truncate-a-file/AutoHotkey/truncate-a-file.ahk b/Task/Truncate-a-file/AutoHotkey/truncate-a-file.ahk new file mode 100644 index 0000000000..0e5d94079b --- /dev/null +++ b/Task/Truncate-a-file/AutoHotkey/truncate-a-file.ahk @@ -0,0 +1,13 @@ +truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200) +return + +truncFile(file, length_bytes){ + if !FileExist(file) + msgbox, File doesn't exists. + FileGetSize, fsize, % file, B + if (length_bytes>fsize) + msgbox, New truncated size more than current file size + f := FileOpen(file, "rw") + f.length := length_bytes + f.close() +} diff --git a/Task/Truncate-a-file/Bracmat/truncate-a-file.bracmat b/Task/Truncate-a-file/Bracmat/truncate-a-file.bracmat new file mode 100644 index 0000000000..60511d853d --- /dev/null +++ b/Task/Truncate-a-file/Bracmat/truncate-a-file.bracmat @@ -0,0 +1,23 @@ +( ( trunc + = name length elif file c + . !arg:(?name,?length) + & fil$(!name,rb) + & fil$(,DEC,1) + & :?elif + & whl + ' ( !length+-1:?length:~<0 + & fil$() !elif:?elif + ) + & (fil$(,SET,-1)|) + & whl'(!elif:%?c ?elif&!c !file:?file) + & fil$(!name,wb) + & fil$(,DEC,1) + & whl'(!file:%?c ?file&fil$(,,1,!c)) + & (fil$(,SET,-1)|) + & !length:<0 + ) +& put$("I have a secret to tell you. Listen:","test.txt",NEW) +& ( trunc$("test.txt",20)&out$(get$("test.txt",STR)) + | out$"File too short" + ) +); diff --git a/Task/Twelve-statements/AutoHotkey/twelve-statements.ahk b/Task/Twelve-statements/AutoHotkey/twelve-statements.ahk new file mode 100644 index 0000000000..79639ce0a3 --- /dev/null +++ b/Task/Twelve-statements/AutoHotkey/twelve-statements.ahk @@ -0,0 +1,76 @@ +; Note: the original puzzle provides 12 statements and starts with +; "Given the following twelve statements...", so the first statement +; should ignore the F1 flag and always be true (see "( N == 1 )"). + +S := 12 ; number of statements +Output := "" +Loop, % 2**S { + ;;If !Mod(A_Index,100) ;; optional 'if' to show the loop progress + ;; ToolTip, Index: %A_Index% + SetFlags(A_Index-1), Current := "", Count := 0 + Loop, %S% + R := TestStatement(A_Index), Current .= " " R, Count += (R == F%A_Index%) + If ( Count >= S-1 ) + Output .= Count " ->" Current "`n" + If ( Count = S ) + Solution := "`nSolution = " Current +} +ToolTip +MsgBox, % Output . Solution +Return + +;------------------------------------------------------------------------------------- + +SetFlags(D) { + Local I + Loop, %S% + I := S-A_Index+1 , F%I% := (D >> (S-A_Index)) & 1 +} + +;------------------------------------------------------------------------------------- + +TestStatement(N) { + Local I, C := 0 + If ( N == 1 ) ; This is a numbered list of twelve statements. + Return ( S == 12 ) ; should always be true + If ( N == 2 ) { ; Exactly 3 of the last 6 statements are true. + Loop, 6 + I := S-A_Index+1 , C += F%I% + Return ( C == 3 ) + } + If ( N == 3 ) { ; Exactly 2 of the even-numbered statements are true. + Loop, %S% + C += ( !Mod(A_Index,2) & F%A_Index% ) + Return ( C == 2 ) + } + If ( N == 4 ) ; If statement 5 is true, then statements 6 and 7 are both true. + Return ( F5 ? F6 & F7 : 1 ) + If ( N == 5 ) { ; The 3 preceding statements are all false. + Loop, 3 + I := N-A_Index , C += F%I% + Return ( C == 0 ) + } + If ( N == 6 ) { ; Exactly 4 of the odd-numbered statements are true. + Loop, %S% + C += ( !!Mod(A_Index,2) & F%A_Index% ) + Return ( C == 4 ) + } + If ( N == 7 ) ; Either statement 2 or 3 is true, but not both. + Return ( F2 ^ F3 ) + If ( N == 8 ) ; If statement 7 is true, then 5 and 6 are both true. + Return ( F7 ? F5 & F6 : 1 ) + If ( N == 9 ) { ; Exactly 3 of the first 6 statements are true. + Loop, 6 + C += F%A_Index% + Return ( C == 3 ) + } + If ( N == 10 ) ; The next two statements are both true. + Return ( F11 & F12 ) + If ( N == 11 ) ; Exactly 1 of statements 7, 8 and 9 are true + Return ( F7+F8+F9 == 1 ) + If ( N == 12 ) { ; Exactly 4 of the preceding statements are true + Loop, % N-1 + C += F%A_Index% + Return ( C == 4 ) + } +} diff --git a/Task/Twelve-statements/D/twelve-statements.d b/Task/Twelve-statements/D/twelve-statements.d index 6b0c372b91..be7fe19c49 100644 --- a/Task/Twelve-statements/D/twelve-statements.d +++ b/Task/Twelve-statements/D/twelve-statements.d @@ -1,4 +1,4 @@ -import std.stdio, std.typecons, std.algorithm,std.range,std.functional; +import std.stdio, std.algorithm, std.range, std.functional; immutable texts = [ "this is a numbered list of twelve statements", @@ -14,50 +14,35 @@ immutable texts = [ "exactly 1 of statements 7, 8 and 9 are true", "exactly 4 of the preceding statements are true"]; -alias sumi = curry!(reduce!q{a + b}, 0); - -immutable bool function(in bool[])[] funcs = [ +immutable pure bool function(in bool[])[12] predicates = [ s => s.length == 12, - s => sumi(s[$ - 6 .. $]) == 3, - s => sumi(s[1 .. $].stride(2)) == 2, + s => s[$ - 6 .. $].sum == 3, + s => s.dropOne.stride(2).sum == 2, s => s[4] ? (s[5] && s[6]) : true, - s => sumi(s[1 .. 4]) == 0, - s => sumi(s[0 .. $].stride(2)) == 4, - s => sumi(s[1 .. 3]) == 1, + s => s[1 .. 4].sum == 0, + s => s.stride(2).sum == 4, + s => s[1 .. 3].sum == 1, s => s[6] ? (s[4] && s[5]) : true, - s => sumi(s[0 .. 6]) == 3, + s => s[0 .. 6].sum == 3, s => s[10] && s[11], - s => sumi(s[6 .. 9]) == 1, - s => sumi(s[0 .. 11]) == 4]; + s => s[6 .. 9].sum == 1, + s => s[0 .. 11].sum == 4]; void main() { - enum nStats = 12; - Tuple!(const(bool)[], const(bool)[])[] full, partial; + enum nStats = predicates.length; foreach (immutable n; 0 .. 2 ^^ nStats) { - const st = nStats.iota.map!(i => !!(n & (2 ^^ i))).array; - auto truths = funcs.map!(f => f(st)); - const matches = zip(st, truths) - .map!(s_t => s_t[0] == s_t[1]) - .array; - immutable mCount = matches.sumi; - if (mCount == nStats) - full ~= tuple(st, matches); - else if (mCount == nStats - 1) - partial ~= tuple(st, matches); - } - - foreach (sols, isPartial; zip([full, partial], [false, true])) - foreach (const stm; sols) { - if (isPartial) { - immutable pos = stm[1].countUntil(false); - writefln(`Missed by statement %d: "%s"`, - pos + 1, texts[pos]); - } else - writeln("Solution:"); - write(" "); - foreach (i, t; stm[0]) - writef("%d:%s ", i + 1, t ? "T" : "F"); - writeln; + bool[nStats] st, matches; + nStats.iota.map!(i => !!(n & (2 ^^ i))).copy(st[]); + st[].zip(predicates[].map!(f => f(st))) + .map!(s_t => s_t[0] == s_t[1]).copy(matches[]); + if (matches[].sum >= nStats - 1) { + if (matches[].all) + ">>> Solution:".writeln; + else + writefln("Missed by statement: %d", + matches[].countUntil(false) + 1); + writefln("%-(%s %)", st[].map!q{ "FT"[a] }); } + } } diff --git a/Task/Twelve-statements/Perl-6/twelve-statements.pl6 b/Task/Twelve-statements/Perl-6/twelve-statements.pl6 index 30fd0301fb..1e1f9e1f2c 100644 --- a/Task/Twelve-statements/Perl-6/twelve-statements.pl6 +++ b/Task/Twelve-statements/Perl-6/twelve-statements.pl6 @@ -1,14 +1,14 @@ -sub infix: ($protasis,$apodosis) { !$protasis or $apodosis } +sub infix:<→> ($protasis,$apodosis) { !$protasis or $apodosis } my @tests = { True }, # (there's no 0th statement) - { all(.[1..12]) === any(True, False) }, + { .end == 12 and all(.[1..12]) === any(True, False) }, { 3 == [+] .[7..12] }, { 2 == [+] .[2,4...12] }, - { .[5] ? all .[6,7] }, + { .[5] → all .[6,7] }, { none .[2,3,4] }, { 4 == [+] .[1,3...11] }, { one .[2,3] }, - { .[7] ? all .[5,6] }, + { .[7] → all .[5,6] }, { 3 == [+] .[1..6] }, { all .[11,12] }, { one .[7,8,9] }, diff --git a/Task/Twelve-statements/REXX/twelve-statements-1.rexx b/Task/Twelve-statements/REXX/twelve-statements-1.rexx index c0e4105266..34623b1143 100644 --- a/Task/Twelve-statements/REXX/twelve-statements-1.rexx +++ b/Task/Twelve-statements/REXX/twelve-statements-1.rexx @@ -1,14 +1,11 @@ -/*REXX program to solve the "Twelve Statement Puzzle". */ +/*REXX program solves the "Twelve Statement Puzzle". */ q=12; @stmt=right('statement',20) /*number of statements in puzzle.*/ -m=0 - do pass=1 for 2 /*find the maximum number trues. */ - /*statement 1 is TRUE by fiat. */ - do e=0 for 2**(q-1); n='1'right(x2b(d2x(e)), q-1, 0) - - do b=1 for q /*define the various bits. */ - @.b=substr(n,b,1) /*define a particular @ bit. */ - end /*b*/ - +m=0 /*[↓] statement 1 is TRUE by fiat*/ + do pass=1 for 2 /*find the maximum number trues. */ + do e=0 for 2**(q-1); n = '1'right(x2b(d2x(e)), q-1, 0) + do b=1 for q /*define the various bits. */ + @.b=substr(n,b,1) /*define a particular @ bit. */ + end /*b*/ if @.1 then if yeses(1,1) \==1 then iterate if @.2 then if yeses(7,12) \==3 then iterate if @.3 then if yeses(2,12,2) \==2 then iterate @@ -24,14 +21,12 @@ m=0 _=yeses(1,12) if pass==1 then do; m=max(m,_); iterate; end else if _\==m then iterate - - do j=1 for q; _=substr(n,j,1) - if _ then say @stmt right(j,2) " is " word('false true',1+_) - end /*tell*/ - end /*e*/ - end /*pass*/ + do j=1 for q; _=substr(n,j,1) + if _ then say @stmt right(j,2) " is " word('false true',1+_) + end /*tell*/ + end /*e*/ + end /*pass*/ exit /*stick a fork in it, we're done.*/ -/*----------------------------------YESES subroutine--------------------*/ -yeses: parse arg L,H,B; #=0 - do i=L to H by word(B 1,1); #=#+@.i; end /*i*/ -return # +/*──────────────────────────────────YESES subroutine────────────────────*/ +yeses: parse arg L,H,B; #=0; do i=L to H by word(B 1,1); #=#+@.i; end + return # diff --git a/Task/Twelve-statements/REXX/twelve-statements-2.rexx b/Task/Twelve-statements/REXX/twelve-statements-2.rexx index ca484e6a80..d32ccfbfc3 100644 --- a/Task/Twelve-statements/REXX/twelve-statements-2.rexx +++ b/Task/Twelve-statements/REXX/twelve-statements-2.rexx @@ -1,14 +1,11 @@ -/*REXX program to solve the "Twelve Statement Puzzle". */ +/*REXX program solves the "Twelve Statement Puzzle". */ q=12; @stmt=right('statement',20) /*number of statements in puzzle.*/ -m=0 - do pass=1 for 2 /*find the maximum number trues. */ - /*statement 1 is TRUE by fiat. */ - do e=0 for 2**(q-1); n='1'right(x2b(d2x(e)), q-1, 0) - - do b=1 for q /*define the various bits. */ - @.b=substr(n,b,1) /*define a particular @ bit. */ - end /*b*/ - +m=0 /*[↓] statement 1 is TRUE by fiat*/ + do pass=1 for 2 /*find the maximum number trues. */ + do e=0 for 2**(q-1); n = '1'right(x2b(d2x(e)), q-1, 0) + do b=1 for q /*define the various bits. */ + @.b=substr(n,b,1) /*define a particular @ bit. */ + end /*b*/ if @.1 then if \ @.1 then iterate if @.2 then if @.7+@.8+@.9+@.10+@.11+@.12 \==3 then iterate if @.3 then if @.2+@.4+@.6+@.8+@.10+@.12 \==2 then iterate @@ -25,7 +22,6 @@ m=0 _=_+@.12 if pass==1 then do; m=max(m,_); iterate; end else if _\==m then iterate - do j=1 for q if @.j then say @stmt right(j,2) " is " word('false true',1+@.j) end /*j*/ diff --git a/Task/Twelve-statements/REXX/twelve-statements-3.rexx b/Task/Twelve-statements/REXX/twelve-statements-3.rexx index aded29d9cf..f30c09c5ce 100644 --- a/Task/Twelve-statements/REXX/twelve-statements-3.rexx +++ b/Task/Twelve-statements/REXX/twelve-statements-3.rexx @@ -1,11 +1,10 @@ -/*REXX program to solve the "Twelve Statement Puzzle". */ +/*REXX program solves the "Twelve Statement Puzzle". */ q=12; @stmt=right('statement',20) /*number of statements in puzzle.*/ -m=0 - do pass=1 for 2 /*find the maximum number trues. */ - /*statement 1 is TRUE by fiat. */ - do e=0 for 2**(q-1); n='1'right(x2b(d2x(e)), q-1, 0) +m=0 /*[↓] statement 1 is TRUE by fiat*/ + do pass=1 for 2 /*find the maximum number trues. */ + do e=0 for 2**(q-1); n = '1'right(x2b(d2x(e)), q-1, 0) parse var n @1 2 @2 3 @3 4 @4 5 @5 6 @6 7 @7 8 @8 9 @9 10 @10 11 @11 12 @12 -/*¦¦¦ if @1 then if \ @1 then iterate ¦¦¦*/ +/*███ if @1 then if \ @1 then iterate ███*/ if @2 then if @7+@8+@9+@10+@11+@12 \==3 then iterate if @3 then if @2+@4+@6+@8+@10+@12 \==2 then iterate if @4 then if @5 then if \(@6 & @7) then iterate @@ -21,7 +20,6 @@ m=0 _=_+@12 if pass==1 then do; m=max(m,_); iterate; end else if _\==m then iterate - do j=1 for q; _=substr(n,j,1) if _ then say @stmt right(j,2) " is " word('false true',1+_) end /*j*/ diff --git a/Task/Twelve-statements/TXR/twelve-statements.txr b/Task/Twelve-statements/TXR/twelve-statements.txr new file mode 100644 index 0000000000..b9961ae5e8 --- /dev/null +++ b/Task/Twelve-statements/TXR/twelve-statements.txr @@ -0,0 +1,37 @@ +@(do + (defmacro defconstraints (name size-name (var) . forms) + ^(progn (defvar ,size-name ,(length forms)) + (defun ,name (,var) + (list ,*forms)))) + + (defconstraints con con-count (s) + (= (length s) con-count) ;; tautology + (= (countq t [s -6..t]) 3) + (= (countq t (mapcar (op if (evenp @1) @2) (range 1) s)) 2) + (if [s 4] (and [s 5] [s 6]) t) + (none [s 1..3]) + (= (countq t (mapcar (op if (oddp @1) @2) (range 1) s)) 4) + (and (or [s 1] [s 2]) (not (and [s 1] [s 2]))) + (if [s 6] (and [s 4] [s 5]) t) + (= (countq t [s 0..6]) 3) + (and [s 10] [s 11]) + (= (countq t [s 6..9]) 1) + (= (countq t [s 0..con-count]) 4)) + + (defun true-indices (truths) + (mappend (do if @1 ^(,@2)) truths (range 1))) + + (defvar results + (append-each ((truths (rperm '(nil t) con-count))) + (let* ((vals (con truths)) + (consist [mapcar eq truths vals]) + (wrong-count (countq nil consist)) + (pos-wrong (+ 1 (or (posq nil consist) -2)))) + (cond + ((zerop wrong-count) + ^((:----> ,*(true-indices truths)))) + ((= 1 wrong-count) + ^((:close ,*(true-indices truths) (:wrong ,pos-wrong)))))))) + + (each ((r results)) + (put-line `@r`))) diff --git a/Task/URL-decoding/AWK/url-decoding.awk b/Task/URL-decoding/AWK/url-decoding.awk index cc7efbb2ec..9affc74b17 100644 --- a/Task/URL-decoding/AWK/url-decoding.awk +++ b/Task/URL-decoding/AWK/url-decoding.awk @@ -1,12 +1,16 @@ -# syntax: GAWK -f URL_DECODING.AWK +# syntax: +awk ' BEGIN { str = "http%3A%2F%2Ffoo%20bar%2F" # "http://foo bar/" printf("%s\n",str) - while (match(str,/%/)) { - L = substr(str,1,RSTART-1) # chars to left of "%" - M = substr(str,RSTART+1,2) # 2 chars to right of "%" - R = substr(str,RSTART+3) # chars to right of "%xx" - str = sprintf("%s%c%s",L,hex2dec(M),R) + len=length(str) + for (i=1;i<=len;i++) { + if ( substr(str,i,1) == "%") { + L = substr(str,1,i-1) # chars to left of "%" + M = substr(str,i+1,2) # 2 chars to right of "%" + R = substr(str,i+3) # chars to right of "%xx" + str = sprintf("%s%c%s",L,hex2dec(M),R) + } } printf("%s\n",str) exit(0) @@ -15,4 +19,4 @@ function hex2dec(s, num) { num = index("0123456789ABCDEF",toupper(substr(s,length(s)))) - 1 sub(/.$/,"",s) return num + (length(s) ? 16*hex2dec(s) : 0) -} +} ' diff --git a/Task/URL-decoding/MATLAB/url-decoding.m b/Task/URL-decoding/MATLAB/url-decoding.m index 01ed75d8ba..4ded5d8aa0 100644 --- a/Task/URL-decoding/MATLAB/url-decoding.m +++ b/Task/URL-decoding/MATLAB/url-decoding.m @@ -2,7 +2,7 @@ function u = urldecoding(s) u = ''; k = 1; while k<=length(s) - if s(k) == '%' && k+3 <= length(s) + if s(k) == '%' && k+2 <= length(s) u = sprintf('%s%c', u, char(hex2dec(s((k+1):(k+2))))); k = k + 3; else diff --git a/Task/URL-decoding/OCaml/url-decoding-2.ocaml b/Task/URL-decoding/OCaml/url-decoding-2.ocaml index 1a603c9602..605bd4c0c8 100644 --- a/Task/URL-decoding/OCaml/url-decoding-2.ocaml +++ b/Task/URL-decoding/OCaml/url-decoding-2.ocaml @@ -1,6 +1,4 @@ /* Rexx */ - -Do X = 0 url. = '' X = X + 1; url.0 = X; url.X = 'http%3A%2F%2Ffoo%20bar%2F' @@ -13,13 +11,10 @@ Do Say End u_ - Return -End Exit -DecodeURL: -Procedure -Do +DecodeURL: Procedure + Parse Arg encoded decoded = '' PCT = '%' @@ -36,13 +31,10 @@ Do decoded = decoded || PCT tail = code || tail End - otherwise Do + otherwise Nop - End End encoded = tail End e_ Return decoded -End -Exit diff --git a/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d b/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d index e6c9fa805a..9f2bf4ddce 100644 --- a/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d +++ b/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d @@ -1,19 +1,17 @@ import std.stdio, std.random, std.algorithm, std.range, std.functional; -alias sum = curry!(reduce!q{a + b}, 0); /**/ - bool biased(in int n) /*nothrow*/ { return uniform(0.0, 1.0) < (1.0 / n); } int unbiased(in int bias) /*nothrow*/ { int a; - while ((a = biased(bias)) == biased(bias)) {} + while ((a = bias.biased) == bias.biased) {} return a; } void main() { - enum int M = 500_000; + enum M = 500_000; foreach (immutable n; 3 .. 7) writefln("%d: %2.3f%% %2.3f%%", n, M.iota.map!(_=> n.biased).sum * 100.0 / M, diff --git a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust index c8b9b6f4de..5ac0415af8 100644 --- a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust +++ b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust @@ -1,8 +1,9 @@ -// rust 0.9-pre +// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800) -fn main() -{ +#[feature(non_ascii_idents)]; + +fn main() { let mut Δ:int = 1; Δ += 1; - println(Δ.to_str()); + println!("{}", Δ); } diff --git a/Task/Universal-Turing-machine/AutoHotkey/universal-turing-machine.ahk b/Task/Universal-Turing-machine/AutoHotkey/universal-turing-machine.ahk new file mode 100644 index 0000000000..6db2c51011 --- /dev/null +++ b/Task/Universal-Turing-machine/AutoHotkey/universal-turing-machine.ahk @@ -0,0 +1,174 @@ +; By Uberi, http://www.autohotkey.com/board/topic/58599-turing-machine/ +SetBatchLines, -1 +OnExit, Exit +SaveFilePath := A_ScriptFullPath ".ini" +; Defaults are for a 2-state_3-symbol turning machine. Format: +; machine state symbol on tape, symbol on tape | tape shift (- is left, + is right, 0 is halt) | machine state +, Rule1 := "A0,1|1|B" +, Rule2 := "A1,2|-1|A" +, Rule3 := "A2,1|-1|A" +, Rule4 := "B0,2|-1|A" +, Rule5 := "B1,2|1|B" +, Rule6 := "B2,0|1|A" +; no error check is run on this input, so be sure states and symbols align with actions +IniRead, UseSaveFile, %SaveFilePath%, Global, UseSaveFile, 1 ; on exit, save state to text file so I can resume on next run +IniRead, MaxIterations, %SaveFilePath%, Global, MaxIterations, 100000 ; set as %A_Space% to run indefinitely +IniRead, Section, %SaveFilePath%, Global, Section, 2-state_3-symbol ; The name of the machine to run. Options defined: +; 2-state_3-symbol +; Simple_incrementer +; Three-state_busy_beaver +; Probable_busy_beaver_Wikipedia + +IniRead, States, %SaveFilePath%, %Section%, States, A|B ; valid states +IniRead, InitialState, %SaveFilePath%, %Section%, InitialState, A ; start state +IniRead, TerminalState, %SaveFilePath%, %Section%, TerminalState, C ; end state +IniRead, Symbols, %SaveFilePath%, %Section%, Symbols, 0,1,2 ; valid symbols +IniRead, DefaultCell, %SaveFilePath%, %Section%, DefaultCell, 0 ; the default symbol of any cell not defined on input tape +IniRead, ProgramCode, %SaveFilePath%, %Section%, ProgramCode, 10101|01010 ; start tape +Iniread, RuleCount, %SaveFilePath%, %Section%, RuleCount, 6 ; number of actions to read +Loop, %RuleCount% +{ + IniRead, Temp1, %SaveFilePath%, %Section%, Rule%A_Index%, % Rule%A_Index% + StringSplit, Temp, Temp1, `, + Action%Temp1% := Temp2 +} + +IniRead, Index, %SaveFilePath%, SavedState, Index, 0 +IniRead, IterationCount, %SaveFilePath%, SavedState, IterationCount, 0 +IniRead, State, %SaveFilePath%, SavedState, State, %InitialState% +If IterationCount > 0 + IniRead, ProgramCode, %SaveFilePath%, SavedState, ProgramCode, %ProgramCode% + +IfNotInString, ProgramCode, | + ProgramCode := "|" ProgramCode +StringSplit, Temp, ProgramCode, | +NegativeCells := Temp1, PositiveCells := Temp2 + +Loop, Parse, Symbols, | + Color%A_LoopField% := hex(mod((A_Index+1/(2**((A_Index-1)//7))-1)/7,1)*16777215) ; unlimited number of unique colors +Color%DefaultCell% := "White" + +Gui, Color, Black +Gui, +ToolWindow +AlwaysOnTop +LastFound -Caption +WindowID := WinExist() +OnMessage(0x201, "WM_LBUTTONDOWN") +Gui, Font, s6 cWhite, Arial +Loop, 61 ; display 30 cell symbols on each side of current index +{ + Temp1 := ((A_Index - 1) * 15) + 1 + Gui, Add, Progress, x%Temp1% y1 w14 h40 vCell%A_Index% BackgroundWhite + Gui, Add, Text, x%Temp1% y42 w15 h10 vLabel%A_Index% Center +} +Gui, Add, Text, x2 y54 w26 h10 vState +Gui, Add, Text, x35 y54 w50 h10 vCurrentCell +Gui, Add, Text, x350 y54 w158 h10 vActions +Gui, Add, Text, x844 y54 w33 h10, Iterations: +Gui, Add, Text, x884 y54 w29 h10 vIterations Right +Gui, Font, s4 cWhite Bold, Arial +Gui, Add, Text, x450 y1 w15 h10 Center, V +GuiControl, Move, Cell31, x451 y8 w14 h33 +Gui, Show, y20 w916 h64, Wolfram's 2-State 3-Symbol Turing Machine ;' + +;MaxIndex := ProgramOffset + StrLen(ProgramCode), MinIndex := ProgramOffset ; not implemented +While, ((MaxIterations = "") || IterationCount <= MaxIterations) ; process until limit is reached, if any +{ + Loop, 61 ; color each cell per its current symbol + { ; must run for all displayed cells because they are not directly mapped to shifting tape + TempIndex := (Index + A_Index) - 31 + GuiControl, , Label%A_Index%, %TempIndex% + CellColor := CellGet(TempIndex) + , CellColor := Color%CellColor% + GuiControl, +Background%CellColor%, Cell%A_Index% + } + CurrentCell := CellGet(Index) + GuiControl, , State, State: %State% + GuiControl, , CurrentCell, Current Cell: %CurrentCell% + GuiControl, , Iterations, %IterationCount% + If (State = TerminalState) + Break + + StringSplit, Temp, Action%State%%CurrentCell%, | + GuiControl, , Actions, % "Actions: Print " . Temp1 . ", Move " . ((Temp2 = -1) ? "left" : "right") . ", " . ((State <> Temp3) ? "Switch to state " . Temp3 : "Do not switch state") + + IterationCount++ + , CellPut(Index,Temp1) + , Index += Temp2 + , State := Temp3 + ;, (Index > MaxIndex) ? MaxIndex := Index : "" + ;, (Index < MinIndex) ? MinIndex := Index : "" + + Sleep, 0.1*1000 +} +MsgBox, 64, Complete, Completed %IterationCount% iterations of the Turing machine. +Return + + +; Hotkeys and functions: +~Pause::Pause + +GuiEscape: +GuiClose: + ExitApp + +Exit: + If UseSaveFile + { + IniWrite, %Index%, %SaveFilePath%, %Section%, Index + IniWrite, %IterationCount%, %SaveFilePath%, %Section%, IterationCount + IniWrite, %State%, %SaveFilePath%, %Section%, State + IniWrite, %NegativeCells%|%PositiveCells%, %SaveFilePath%, %Section%, ProgramCode + } + ExitApp + +CellGet(Index) +{ + global NegativeCells, PositiveCells, DefaultCell + Temp1 := (Index < 0) ? SubStr(NegativeCells,Abs(Index),1) : SubStr(PositiveCells,Index + 1,1) + Return, (Temp1 = "") ? DefaultCell : Temp1 +} + +CellPut(Index,Char) +{ + global NegativeCells, PositiveCells, DefaultCell + static StrGetFunc := "StrGet" ; workaround to hide function from AHK Basic (which does not have or require it) + CharType := A_IsUnicode ? "UShort" : "UChar" + , (Index < 0) + ? (Index := 0 - Index + , Temp1 := Index - StrLen(NegativeCells) + , (Temp1 > 0) + ? (VarSetCapacity(Pad,64) ; these three functions are quirks in AHK's memory management (not required) + , VarSetCapacity(Pad,0) + , VarSetCapacity(Pad,Temp1,Asc(DefaultCell)) + , NegativeCells .= A_IsUnicode ? %StrGetFunc%(&Pad,Temp1,"CP0") : Pad) + : "" + , NumPut(Asc(Char),NegativeCells,(Index - 1) << !!A_IsUnicode,CharType) ) + : (Temp1 := Index - StrLen(PositiveCells) + 1 + , (Temp1 > 0) + ? (VarSetCapacity(Pad,64) ; these three functions are quirks in AHK's memory management (not required) + , VarSetCapacity(Pad,0) + , VarSetCapacity(Pad,Temp1,Asc(DefaultCell)) + , PositiveCells .= A_IsUnicode ? %StrGetFunc%(&Pad,Temp1,"CP0") : Pad) + : "" + , NumPut(Asc(Char),PositiveCells,Index << !!A_IsUnicode,CharType) ) +} + +Hex(p_Integer) +{ + PtrType:=(A_PtrSize=8) ? "Ptr":"UInt" + l_Format:="`%0" . 6 . "I64X" + VarSetCapacity(l_Argument,8) + NumPut(p_Integer,l_Argument,0,"Int64") + VarSetCapacity(l_Buffer,A_IsUnicode ? 12:6,0) + DllCall(A_IsUnicode ? "msvcrt\_vsnwprintf":"msvcrt\_vsnprintf" + ,"Str",l_Buffer ;-- Storage location for output + ,"UInt",6 ;-- Maximum number of characters to write + ,"Str",l_Format ;-- Format specification + ,PtrType,&l_Argument) ;-- Argument + Return l_Buffer +} + +WM_LBUTTONDOWN() +{ + If (A_Gui = 1) + PostMessage, 0xA1, 2 +} diff --git a/Task/Universal-Turing-machine/Clojure/universal-turing-machine-1.clj b/Task/Universal-Turing-machine/Clojure/universal-turing-machine-1.clj new file mode 100644 index 0000000000..60f8df9805 --- /dev/null +++ b/Task/Universal-Turing-machine/Clojure/universal-turing-machine-1.clj @@ -0,0 +1,26 @@ +(defn tape + "Creates a new tape with given blank character and tape contents" + ([blank] (tape () blank () blank)) + ([right blank] (tape () (first right) (rest right) blank)) + ([left head right blank] [(reverse left) (or head blank) (into () right) blank])) + +; Tape operations +(defn- left [[[l & ls] _ rs b] c] [ls (or l b) (conj rs c) b]) +(defn- right [[ls _ [r & rs] b] c] [(conj ls c) (or r b) rs b]) +(defn- stay [[ls _ rs b] c] [ls c rs b]) +(defn- head [[_ c _ b]] (or c b)) +(defn- pretty [[ls c rs b]] (concat (reverse ls) [[(or c b)]] rs)) + +(defn new-machine + "Returns a function that takes a tape as input, and returns the tape + after running the machine specified in `machine`." + [machine] + (let [rules (into {} (for [[s c c' a s'] (:rules machine)] + [[s c] [c' (-> a name symbol resolve) s']])) + finished? (into #{} (:terminating machine))] + (fn [input-tape] + (loop [state (:initial machine) tape input-tape] + (if (finished? state) + (pretty tape) + (let [[out action new-state] (get rules [state (head tape)])] + (recur new-state (action tape out)))))))) diff --git a/Task/Universal-Turing-machine/Clojure/universal-turing-machine-2.clj b/Task/Universal-Turing-machine/Clojure/universal-turing-machine-2.clj new file mode 100644 index 0000000000..613eb11047 --- /dev/null +++ b/Task/Universal-Turing-machine/Clojure/universal-turing-machine-2.clj @@ -0,0 +1,40 @@ +(def simple-incrementer + (new-machine {:initial :q0 + :terminating [:qf] + :rules [[:q0 1 1 :right :q0] + [:q0 \B 1 :stay :qf]]})) +(deftest simple-incrementer-test + (is (= [1 1 1 [1]] (simple-incrementer (tape [1 1 1] \B))))) + + +(def three-state-two-symbol-busy-beaver + (new-machine {:initial :a + :terminating [:halt] + :rules [[:a 0 1 :right :b] + [:a 1 1 :left :c] + [:b 0 1 :left :a] + [:b 1 1 :right :b] + [:c 0 1 :left :b] + [:c 1 1 :stay :halt]]})) +(deftest three-state-two-symbol-busy-beaver-test + (is (= [1 1 1 [1] 1 1] (three-state-two-symbol-busy-beaver (tape 0))))) + + +(def five-state-two-symbol-busy-beaver + (new-machine {:initial :A + :terminating [:H] + :rules [[:A 0 1 :right :B] + [:A 1 1 :left :C] + [:B 0 1 :right :C] + [:B 1 1 :right :B] + [:C 0 1 :right :D] + [:C 1 0 :left :E] + [:D 0 1 :left :A] + [:D 1 1 :left :D] + [:E 0 1 :stay :H] + [:E 1 0 :left :A]]})) +(deftest five-state-two-symbol-busy-beaver-test + (let [result (flatten (five-state-two-symbol-busy-beaver (tape 0))) + freq (frequencies result)] + (is (= 4098 (get freq 1))) + (is (= 8191 (get freq 0))))) diff --git a/Task/Universal-Turing-machine/D/universal-turing-machine-2.d b/Task/Universal-Turing-machine/D/universal-turing-machine-2.d index 3d2c7d73ae..7382723d2e 100644 --- a/Task/Universal-Turing-machine/D/universal-turing-machine-2.d +++ b/Task/Universal-Turing-machine/D/universal-turing-machine-2.d @@ -1,52 +1,18 @@ -import std.stdio, std.typecons, std.array, std.algorithm, std.string; +import std.stdio, std.typecons, std.algorithm, std.string, std.array; -void turing(Sy, St)(in Sy[] symbols, in Sy blank, in St initialState, - in St[] haltStates, in St[] runningStates, - in Tuple!(Sy, string, St)[Sy][St] rules, - in Sy[] startingTape = []) { - Sy[int] tape; - foreach (i, sy; startingTape) - tape[i] = sy; - int pos = 0; - St state = initialState; - - while (!haltStates.canFind(state)) { - //auto symbol = tape.setDefault(pos, blank); - if (pos !in tape) - tape[pos] = blank; - auto symbol = tape[pos]; - tape.keys.sort() - .map!(i => format(["%s", "(%s)"][i == pos], tape[i])) - .join(" ").writeln; - //{const outsym, const action, state} = rules[state][symbol]; - const r = rules[state][symbol]; - state = r[2]; - tape[pos] = r[0]; - pos += ["left": -1, "stay": 0, "right": 1][r[1]]; - } +void turing(Sy, St)(in St state, Sy[int] tape, in int pos, + in Tuple!(Sy, int, St)[Sy][St] rules) { + if (state.empty) return; + const r = rules[state][tape[pos] = tape.get(pos, Sy.init)]; + writefln("%-(%s%)", tape.keys.sort() + .map!(i => format(i == pos ? "(%s)" : " %s ", tape[i]))); + tape[pos] = r[0]; + turing(r[2], tape, pos + r[1], rules); } void main() { - alias t = tuple; - - turing(['b', '1'], // Permitted symbols. - 'b', // Blank symbol. - "q0", // Starting state. - ["qf"], // Terminating states. - ["q0"], // Running states. - // Operating rules. - ["q0": ['1': t('1', "right", "q0"), - 'b': t('1', "stay", "qf")]], - ['1', '1', '1']); // Starting tape. - writeln; - - turing([0, 1], // Permitted symbols. - 0, // Blank symbol. - "a", // Starting state. - ["halt"], // Terminating states. - ["a", "b", "c"], // Running states. - // Operating rules. - ["a": [0: t(1, "right", "b"), 1: t(1, "left", "c")], - "b": [0: t(1, "left", "a"), 1: t(1, "right", "b")], - "c": [0: t(1, "left", "b"), 1: t(1, "stay", "halt")]]); + turing("a", null, 0, + ["a": [0: tuple(1, 1, "b"), 1: tuple(1, -1, "c")], + "b": [0: tuple(1, -1, "a"), 1: tuple(1, 1, "b")], + "c": [0: tuple(1, -1, "b"), 1: tuple(1, 0, "")]]); } diff --git a/Task/Use-another-language-to-call-a-function/D/use-another-language-to-call-a-function-1.d b/Task/Use-another-language-to-call-a-function/D/use-another-language-to-call-a-function-1.d new file mode 100644 index 0000000000..466543c9d9 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/D/use-another-language-to-call-a-function-1.d @@ -0,0 +1,14 @@ +import core.stdc.string; + +extern(C) bool query(char *data, size_t *length) pure nothrow { + immutable text = "Here am I"; + + if (*length < text.length) { + *length = 0; // Also clears length. + return false; + } else { + memcpy(data, text.ptr, text.length); + *length = text.length; + return true; + } +} diff --git a/Task/Use-another-language-to-call-a-function/D/use-another-language-to-call-a-function-2.d b/Task/Use-another-language-to-call-a-function/D/use-another-language-to-call-a-function-2.d new file mode 100644 index 0000000000..c125113ad7 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/D/use-another-language-to-call-a-function-2.d @@ -0,0 +1,16 @@ +#include +#include + +extern bool query(char *data, size_t *length); + +int main() { + char buffer[1024]; + size_t size = sizeof(buffer); + + if (query(buffer, &size)) + printf("%.*s\n", size, buffer); + else + puts("The call to query has failed."); + + return 0; +} diff --git a/Task/User-input-Text/C/user-input-text.c b/Task/User-input-Text/C/user-input-text.c index 770281896e..d36ac75fca 100644 --- a/Task/User-input-Text/C/user-input-text.c +++ b/Task/User-input-Text/C/user-input-text.c @@ -1,11 +1,22 @@ #include -int main(int argc, char* argv[]) +#include + +int main(void) { - int input; - if((scanf("%d", &input))==1) - { - printf("Read in %d\n", input); - return 1; - } - return 0; + // Get a string from stdin + char str[BUFSIZ]; + puts("Enter a string: "); + fgets(str, sizeof(str), stdin); + + // Get 75000 from stdin + long num; + char buf[BUFSIZ]; + do + { + puts("Enter 75000: "); + fgets(buf, sizeof(buf), stdin); + num = strtol(buf, NULL, 10); + } while (num != 75000); + + return EXIT_SUCCESS; } diff --git a/Task/Vampire-number/AutoHotkey/vampire-number.ahk b/Task/Vampire-number/AutoHotkey/vampire-number.ahk new file mode 100644 index 0000000000..615332ef98 --- /dev/null +++ b/Task/Vampire-number/AutoHotkey/vampire-number.ahk @@ -0,0 +1,74 @@ +SetBatchLines -1 ; used to improve performance +; (you can make it much faster by removing the informative tooltips) + +;******************** +; CONFIG +;******************** +StartingNumber := 10 +NumberLimit := 126030 +CounterLimit := 25 ; calculations stop when one of these limits is reached +AdditionalNumbers := "16758243290880,24959017348650,14593825548650" +;******************** + +CurrentCounter := 0, CurrentNumber := StartingNumber + +Loop { + if !Mod(A_Index,75) ; informative tooltip (every 75 calculations, to avoid slowing down) + ToolTip, % "Checking numbers...`nNumber: " CurrentNumber + . "/" NumberLimit "`nFound: " CurrentCounter "/" CounterLimit + if ( CurrentCounter >= CounterLimit ) || ( CurrentNumber >= NumberLimit ) + Break + if Mod(StrLen(CurrentNumber),2) + CurrentNumber *= 10 + else if ( ( CurrentResult := GetFangs(CurrentNumber) ) <> "" ) + Output .= "`n" CurrentNumber ":`t" CurrentResult, CurrentCounter++ + CurrentNumber++ +} +ToolTip ; hide informative tooltip + +MsgBox % SubStr(Output,2) ; show output (first part) + +Output := "" +Loop, Parse, AdditionalNumbers, % "," +{ + ToolTip, % "Getting fangs for " A_LoopField " ..." ; informative tooltip + Output .= "`n" A_LoopField ":`n`t" GetFangs(A_LoopField) "`n" +} +ToolTip ; hide informative tooltip + +MsgBox % SubStr(Output,2) ; show output (second part - additional numbers) +ExitApp + +;---------------------------------------------------------------------------------- + +CharSorter(Input) { ; required by GetFangs() + Loop, Parse, Input + Output .= A_LoopField "`n" + Sort, Output + StringReplace, Output, Output, % "`n",, All + Return Output +} + +;---------------------------------------------------------------------------------- + +GetFangs(CurrentNumber) { ; requires CharSorter() + ResultIndex := 1 + Length := StrLen(CurrentNumber) + Power := (Length//2)-1 + if Mod(Length,2) OR !Power + Return "" + NumberLimit := Floor(Sqrt(CurrentNumber)) + Lower := 10 ** Power + Loop, % NumberLimit - Lower { + if !Mod(CurrentNumber,Lower) { + FactorTwo := CurrentNumber//Lower + if ( !Mod(Lower,10) && !Mod(FactorTwo,10) ) + Return "" + Check := CharSorter( Lower . FactorTwo ) + if (CharSorter(CurrentNumber) = Check) && (StrLen(Lower) = StrLen(FactorTwo)) + Output .= "`n`t[" Lower "," FactorTwo "]" + } + Lower++ + } + Return SubStr(Output,3) ; 3 = 1 + length of "`n`t" +} diff --git a/Task/Vampire-number/D/vampire-number-2.d b/Task/Vampire-number/D/vampire-number-2.d index dd692d3867..16118f4fec 100644 --- a/Task/Vampire-number/D/vampire-number-2.d +++ b/Task/Vampire-number/D/vampire-number-2.d @@ -3,7 +3,7 @@ import std.stdio, std.math, std.algorithm, std.array, std.traits; T[N] pows(T, size_t N)() { typeof(return) result; result[0] = 1; - foreach (i, ref r; result[1 .. $]) + foreach (immutable i, ref r; result[1 .. $]) r = result[i] * 10; return result; } @@ -42,7 +42,7 @@ pure nothrow if (is(T == uint) || is(T == ulong)) { immutable lo = max(tenPows[nd - 1], (x + tenPows[nd] - 2) / (tenPows[nd] - 1)); - immutable hi = min(x / lo, cast(T)sqrt(cast(real)x)); + immutable hi = min(x / lo, cast(T)sqrt(real(x))); immutable t = x.dTally; size_t n = 0; diff --git a/Task/Vampire-number/Python/vampire-number-1.py b/Task/Vampire-number/Python/vampire-number-1.py index 033627cb76..1f19ec959c 100644 --- a/Task/Vampire-number/Python/vampire-number-1.py +++ b/Task/Vampire-number/Python/vampire-number-1.py @@ -1,3 +1,5 @@ +from __future__ import division + import math from operator import mul from itertools import product @@ -54,7 +56,7 @@ def divisors(n): def vampire(n): fangsets = set( frozenset([d, n//d]) for d in divisors(n) - if (len(str(d)) == len(str(n))/2 + if (len(str(d)) == len(str(n))/2. and sorted(str(d) + str(n//d)) == sorted(str(n)) and (str(d)[-1] == 0) + (str(n//d)[-1] == 0) <=1) ) return sorted(tuple(sorted(fangs)) for fangs in fangsets) diff --git a/Task/Van-der-Corput-sequence/AutoHotkey/van-der-corput-sequence.ahk b/Task/Van-der-Corput-sequence/AutoHotkey/van-der-corput-sequence.ahk new file mode 100644 index 0000000000..5cc4352119 --- /dev/null +++ b/Task/Van-der-Corput-sequence/AutoHotkey/van-der-corput-sequence.ahk @@ -0,0 +1,13 @@ +SetFormat, FloatFast, 0.5 +for i, v in [2, 3, 4, 5, 6] { + seq .= "Base " v ": " + Loop, 10 + seq .= VanDerCorput(A_Index - 1, v) (A_Index = 10 ? "`n" : ", ") +} +MsgBox, % seq + +VanDerCorput(n, b, r=0) { + while n + r += Mod(n, b) * b ** -A_Index, n := n // b + return, r +} diff --git a/Task/Variable-size-Get/REXX/variable-size-get.rexx b/Task/Variable-size-Get/REXX/variable-size-get.rexx index 3edbcfd1ca..0fd619bdf7 100644 --- a/Task/Variable-size-Get/REXX/variable-size-get.rexx +++ b/Task/Variable-size-Get/REXX/variable-size-get.rexx @@ -1,4 +1,4 @@ -/*REXX program demonstrates (see the penultimate statment) how to */ +/*REXX program demonstrates (see the penultimate statement) how to */ /* to find the size (length) of the value of a REXX variable. */ /*REXX doesn't reserve any storage for any variables, as all variables */ diff --git a/Task/Variable-size-Get/Ruby/variable-size-get.rb b/Task/Variable-size-Get/Ruby/variable-size-get.rb new file mode 100644 index 0000000000..6a41faf36b --- /dev/null +++ b/Task/Variable-size-Get/Ruby/variable-size-get.rb @@ -0,0 +1,5 @@ +require 'objspace' + +p ObjectSpace.memsize_of("a"*23) #=> 0 +p ObjectSpace.memsize_of("a"*24) #=> 25 +p ObjectSpace.memsize_of("a"*1000) #=> 1001 diff --git a/Task/Variadic-function/Applesoft-BASIC/variadic-function.applesoft b/Task/Variadic-function/Applesoft-BASIC/variadic-function.applesoft new file mode 100644 index 0000000000..7979cb38d5 --- /dev/null +++ b/Task/Variadic-function/Applesoft-BASIC/variadic-function.applesoft @@ -0,0 +1,9 @@ +10 P$(0) = STR$(5) +20 P$(1) = "MARY" +30 P$(2) = "HAD" +40 P$(3) = "A" +50 P$(4) = "LITTLE" +60 P$(5) = "LAMB" +70 GOSUB 90"VARIADIC FUNCTION +80 END +90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = "" : NEXT I : P$(0) = "" : RETURN diff --git a/Task/Variadic-function/D/variadic-function.d b/Task/Variadic-function/D/variadic-function.d index 29697711ab..6f6ef4dfd3 100644 --- a/Task/Variadic-function/D/variadic-function.d +++ b/Task/Variadic-function/D/variadic-function.d @@ -2,22 +2,22 @@ import std.stdio, std.algorithm; void printAll(TyArgs...)(TyArgs args) { foreach (el; args) - writeln(el); + el.writeln; } // Typesafe variadic function for dynamic array void showSum1(int[] items...) { - writeln(reduce!q{a + b}(0, items)); + items.sum.writeln; } // Typesafe variadic function for fixed size array void showSum2(int[4] items...) { - writeln(reduce!q{a + b}(0, items)); + items[].sum.writeln; } void main() { - printAll(4, 5.6, "Rosetta", "Code", "is", "awesome"); - writeln(); + printAll(4, 5.6, "Rosetta", "Code", "is", "awseome"); + writeln; showSum1(1, 3, 50); showSum2(1, 3, 50, 10); } diff --git a/Task/Variadic-function/Objective-C/variadic-function.m b/Task/Variadic-function/Objective-C/variadic-function.m index 171dd6315f..bb3c2b2142 100644 --- a/Task/Variadic-function/Objective-C/variadic-function.m +++ b/Task/Variadic-function/Objective-C/variadic-function.m @@ -12,6 +12,4 @@ void logObjects(id firstObject, ...) // <-- there is always at least one arg, "n // This function can be called with any number or type of objects, as long as you terminate it with "nil": logObjects(@"Rosetta", @"Code", @"Is", @"Awesome!", nil); -logObjects([NSNumber numberWithInt:4], - [NSNumber numberWithInt:3], - @"foo", nil); +logObjects(@4, @3, @"foo", nil); diff --git a/Task/Variadic-function/PARI-GP/variadic-function.pari b/Task/Variadic-function/PARI-GP/variadic-function.pari index 96e956b9b9..1bd2546b16 100644 --- a/Task/Variadic-function/PARI-GP/variadic-function.pari +++ b/Task/Variadic-function/PARI-GP/variadic-function.pari @@ -1 +1 @@ -f(a[..])=prod(i=1,#a,a[i]) +f(a[..])=for(i=1,#a,print(a[i])) diff --git a/Task/Variadic-function/Prolog/variadic-function-1.pro b/Task/Variadic-function/Prolog/variadic-function-1.pro new file mode 100644 index 0000000000..1ff4eff892 --- /dev/null +++ b/Task/Variadic-function/Prolog/variadic-function-1.pro @@ -0,0 +1 @@ +printAll( List ) :- forall( member(X,List), (write(X), nl)). diff --git a/Task/Variadic-function/Prolog/variadic-function-2.pro b/Task/Variadic-function/Prolog/variadic-function-2.pro new file mode 100644 index 0000000000..1fb18e093e --- /dev/null +++ b/Task/Variadic-function/Prolog/variadic-function-2.pro @@ -0,0 +1,3 @@ +execute( Term ) :- + Term =.. [F | Args], + forall( member(X,Args), (G =.. [F,X], G, nl) ). diff --git a/Task/Vector-products/AutoHotkey/vector-products.ahk b/Task/Vector-products/AutoHotkey/vector-products.ahk new file mode 100644 index 0000000000..c5eee5f4c3 --- /dev/null +++ b/Task/Vector-products/AutoHotkey/vector-products.ahk @@ -0,0 +1,30 @@ +V := {a: [3, 4, 5], b: [4, 3, 5], c: [-5, -12, -13]} + +for key, val in V + Out .= key " = (" val[1] ", " val[2] ", " val[3] ")`n" + +CP := CrossProduct(V.a, V.b) +VTP := VectorTripleProduct(V.a, V.b, V.c) + +MsgBox, % Out "`na • b = " DotProduct(V.a, V.b) "`n" + . "a x b = (" CP[1] ", " CP[2] ", " CP[3] ")`n" + . "a • b x c = " ScalerTripleProduct(V.a, V.b, V.c) "`n" + . "a x b x c = (" VTP[1] ", " VTP[2] ", " VTP[3] ")" + +DotProduct(v1, v2) { + return, v1[1] * v2[1] + v1[2] * v2[2] + v1[3] * v2[3] +} + +CrossProduct(v1, v2) { + return, [v1[2] * v2[3] - v1[3] * v2[2] + , v1[3] * v2[1] - v1[1] * v2[3] + , v1[1] * v2[2] - v1[2] * v2[1]] +} + +ScalerTripleProduct(v1, v2, v3) { + return, DotProduct(v1, CrossProduct(v2, v3)) +} + +VectorTripleProduct(v1, v2, v3) { + return, CrossProduct(v1, CrossProduct(v2, v3)) +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d b/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d index 7b8a8589f6..edcdc513ee 100644 --- a/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d @@ -1,7 +1,7 @@ import std.stdio, std.algorithm, std.mathspecial; real x2Dist(T)(in T[] data) pure nothrow { - immutable avg = reduce!q{a + b}(0.0L, data) / data.length; + immutable avg = data.sum / data.length; immutable sqs = reduce!((a, b) => a + (b - avg) ^^ 2)(0.0L, data); return sqs / avg; } diff --git a/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d b/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d index 33ae525986..04a6a2e20a 100644 --- a/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d +++ b/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d @@ -7,9 +7,9 @@ Bin the answers to fn() and check bin counts are within void distCheck(TF)(in TF func, in int nRepeats, in double delta) if (isCallable!TF) { int[int] counts; - foreach (i; 0 .. nRepeats) + foreach (immutable i; 0 .. nRepeats) counts[func()]++; - immutable double target = nRepeats / cast(double)counts.length; + immutable double target = nRepeats / double(counts.length); immutable int deltaCount = cast(int)(delta / 100.0 * target); foreach (k, count; counts) @@ -20,7 +20,7 @@ if (isCallable!TF) { foreach (k; counts.keys.sort()) writeln(k, " ", counts[k]); - writeln(); + writeln; } version (verify_distribution_uniformity_naive_main) { diff --git a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx new file mode 100644 index 0000000000..8e215f5a13 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx @@ -0,0 +1,33 @@ +/*REXX pgm simulates a # of trials of a random digit, show it's skew %. */ +parse arg f t d s . /*obtain arguments (options). */ +if f=='' | f==',' then f='RANDOM' /* func ¬specified? Use default.*/ +if t=='' | t==',' then t=1000000 /*times " " " */ +if d=='' | d==',' then d=1/2 /*delta% " " " */ +if s\=='' then call random ,,s /*use some seed for repeatibility*/ +highDig=9 /*use this for the highest digit.*/ +!.=0 /*zero all possible random trials*/ + do j=1 for t /* [↓] perform a lot of trials. */ + if f=='RANDOM' then ?=random(0,highDig) /*random func.*/ + else interpret '?='f"(0,"highDig')' /* user func.*/ + !.?=!.?+1 /*bump counter*/ + end /*j*/ /* [↑] trials ───► pigeonholes. */ + /* [↓] compute the dig skewness.*/ +g=t/(1+highDig) /*calculate # of each digit throw*/ +OK?='OK skewed' /*words to show skewed or if OK. */ +w=max(8,length(t)) /*maximum length of # of trials. */ +pad=left('',9) /*this is used for indentation. */ +say pad 'digit' center("hits",w) ' skew ' "skew%" 'result' /*hdr. */ +say pad '─────' center('',w,'─') '──────' "─────" '──────' /*sep. */ + /** [↑] show header & separator.*/ + do k=0 to highDig /*process each of the possible #.*/ + skew=g-!.k /*calculate the skew for the dig.*/ + skewPC=(1-(g-abs(skew))/g)*100 /* " " " percentage. */ + ok=right(word(ok?,1+(skewPC>d)),6) /*it's gotta be one or the other.*/ + say pad center(k,5) right(!.k,w) right(skew,6) format(skewPC,,3) ok + end /*k*/ + +say pad '─────' center('',w,'─') '──────' "─────" '──────' /*sep. */ +y=5+1+w+1+6+1+6+1+6 /*width*/ +say pad center(" (with " t ' trials)',y) /*info.*/ +say pad center(" (skewed when exceeds " d'%)',y) /*info.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d b/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d index a17f853d61..10a4b845e6 100644 --- a/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d +++ b/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d @@ -9,7 +9,7 @@ string[2] vigenereDecrypt(in double[] targetFreqs, in string input) { uint[nAlpha] charCounts = 0; foreach (immutable c; txt) charCounts[c - 'A']++; - return charCounts[].sort().release().dotProduct(sTargets); + return charCounts[].sort().release.dotProduct(sTargets); } static frequency(in string txt) pure nothrow { @@ -65,12 +65,12 @@ string[2] vigenereDecrypt(in double[] targetFreqs, in string input) { pieces[i % bestLength] ~= c; string key; - foreach (fr; map!frequency(pieces)) { - fr.sort!q{ a.d > b.d }(); + foreach (fr; pieces.map!frequency) { + fr.sort!q{ a.d > b.d }; size_t m; double maxCorr = 0.0; - foreach (immutable j, immutable c; std.ascii.uppercase) { + foreach (immutable j, immutable c; uppercase) { double corr = 0.0; foreach (immutable frc; fr) { immutable di = (frc.c - c + nAlpha) % nAlpha; @@ -89,10 +89,10 @@ string[2] vigenereDecrypt(in double[] targetFreqs, in string input) { return key; } - immutable cleaned = input.toUpper().removechars("^A-Z"); + immutable cleaned = input.toUpper.removechars("^A-Z"); //immutable sortedTargets = sorted(targetFreqs); - immutable sortedTargets = targetFreqs.dup.sort().release().idup; + immutable sortedTargets = targetFreqs.dup.sort().release.idup; immutable bestLength = findBestLength(cleaned, sortedTargets); if (bestLength == 0) diff --git a/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust b/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust index c17684f387..32d6736710 100644 --- a/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust +++ b/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust @@ -1,49 +1,55 @@ -fn uppercase_and_filter(in: &str) -> ~[u8] { - let mut result = ~[]; +use std::ascii::AsciiCast; +use std::str::from_utf8; - for in.each_char |c| { - if char::is_ascii(c) { - if char::is_lowercase(c) { - // We know it's ascii, so just do the math directly - result.push((c + ('A' - 'a')) as u8) - } else if char::is_uppercase(c) { - result.push(c as u8); - } - } +static A: u8 = 'A' as u8; +static a: u8 = 'a' as u8; + +fn uppercase_and_filter(input: &str) -> ~[u8] { + let mut result = ~[]; + + for b in input.bytes() { + if b.is_ascii() { + let ascii = b.to_ascii(); + if ascii.is_lower() { + // We know it's ascii, so just do the math directly + result.push((b + (A - a))) + } else if ascii.is_upper() { + result.push(b); + } } + } - return result; + return result; } fn vigenere(key: &str, text: &str, is_encoding: bool) -> ~str { - const A: u8 = 'A' as u8; - let key_bytes = uppercase_and_filter(key); - let text_bytes = uppercase_and_filter(text); + let key_bytes = uppercase_and_filter(key); + let text_bytes = uppercase_and_filter(text); - let mut result_bytes = ~[]; + let mut result_bytes = ~[]; - for text_bytes.eachi |i, &c| { - let c2 = if is_encoding { - (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A - } else { - (c - key_bytes[i % key_bytes.len()] + 26) % 26 + A - }; - result_bytes.push(c2); - } + for (i, c) in text_bytes.iter().enumerate() { + let c2 = if is_encoding { + (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A + } else { + (c - key_bytes[i % key_bytes.len()] + 26) % 26 + A + }; + result_bytes.push(c2); + } - return str::from_bytes(result_bytes); + return from_utf8(result_bytes).to_owned(); } fn main() { - let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; - let key = "VIGENERECIPHER"; + let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; + let key = "VIGENERECIPHER"; - io::println(fmt!("Text: %s", text)); - io::println(fmt!("Key: %s", key)); + println!("Text: {:s}", text); + println!("Key: {:s}", key); - let encoded = vigenere(key, text, true); - io::println(fmt!("Code: %s", encoded)); - let decoded = vigenere(key, encoded, false); - io::println(fmt!("Back: %s", decoded)); + let encoded = vigenere(key, text, true); + println!("Code: {:s}", encoded); + let decoded = vigenere(key, encoded, false); + println!("Back: {:s}", decoded); } diff --git a/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala b/Task/Vigen-re-cipher/Scala/vigen-re-cipher-1.scala similarity index 100% rename from Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala rename to Task/Vigen-re-cipher/Scala/vigen-re-cipher-1.scala diff --git a/Task/Vigen-re-cipher/Scala/vigen-re-cipher-2.scala b/Task/Vigen-re-cipher/Scala/vigen-re-cipher-2.scala new file mode 100644 index 0000000000..2efebb51e5 --- /dev/null +++ b/Task/Vigen-re-cipher/Scala/vigen-re-cipher-2.scala @@ -0,0 +1,52 @@ +class Vigenere(val key: String) { + + private def rotate(p: Int, s: IndexedSeq[Char]) = s.drop(p) ++ s.take(p) + + private val chars = 'A' to 'Z' + + private val vSquare = (chars ++ + rotate(1, chars) ++ + rotate(2, chars) ++ + rotate(3, chars) ++ + rotate(4, chars) ++ + rotate(5, chars) ++ + rotate(6, chars) ++ + rotate(7, chars) ++ + rotate(8, chars) ++ + rotate(9, chars) ++ + rotate(10, chars) ++ + rotate(11, chars) ++ + rotate(12, chars) ++ + rotate(13, chars) ++ + rotate(14, chars) ++ + rotate(15, chars) ++ + rotate(16, chars) ++ + rotate(17, chars) ++ + rotate(18, chars) ++ + rotate(19, chars) ++ + rotate(20, chars) ++ + rotate(21, chars) ++ + rotate(22, chars) ++ + rotate(23, chars) ++ + rotate(24, chars) ++ + rotate(25, chars)) + + private var encIndex = -1 + private var decIndex = -1 + + def encode(c: Char) = { + encIndex += 1 + if (encIndex == key.length) encIndex = 0 + if (chars.contains(c)) vSquare((c - 'A') * 26 + key(encIndex) - 'A') else c + } + + def decode(c: Char) = { + decIndex += 1 + if (decIndex == key.length) decIndex = 0 + if (chars.contains(c)) { + val baseIndex = (key(decIndex) - 'A') * 26 + val nextIndex = vSquare.indexOf(c, baseIndex) + chars(nextIndex - baseIndex) + } else c + } +} diff --git a/Task/Vigen-re-cipher/Scala/vigen-re-cipher-3.scala b/Task/Vigen-re-cipher/Scala/vigen-re-cipher-3.scala new file mode 100644 index 0000000000..310e4a5c50 --- /dev/null +++ b/Task/Vigen-re-cipher/Scala/vigen-re-cipher-3.scala @@ -0,0 +1,6 @@ +val text = "ATTACKATDAWN" +val myVigenere = new Vigenere("LEMON") +val encoded = text.map(c => myVigenere.encode(c)) +println("Plaintext => " + text) +println("Ciphertext => " + encoded) +println("Decrypted => " + encoded.map(c => myVigenere.decode(c))) diff --git a/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr b/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr index be41e7f79d..8dd6973e98 100644 --- a/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr +++ b/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr @@ -1,11 +1,10 @@ @(next :args) @(do - (defun letter-mod26-op (func) ;; add or subtract capital letters modulo 26 - (lambda (a b) (+ #\A (mod (call func (- a #\A) (- b #\A)) 26)))) + (defun vig-op (plus-or-minus) + (op + #\A [mod [plus-or-minus (- @1 #\A) (- @2 #\A)] 26])) + (defun vig (msg key encrypt) - (cat-str (mapcar (letter-mod26-op (if encrypt (fun +) (fun -))) - (list-str msg) - (repeat (list-str key))) ""))) + (mapcar (vig-op [if encrypt + -]) msg (repeat key)))) @(coll)@{key /[A-Za-z]/}@(end) @(coll)@{msg /[A-Za-z]/}@(end) @(cat key "") diff --git a/Task/Walk-a-directory-Non-recursively/00DESCRIPTION b/Task/Walk-a-directory-Non-recursively/00DESCRIPTION index 6b34e7c317..f3bf25ca81 100644 --- a/Task/Walk-a-directory-Non-recursively/00DESCRIPTION +++ b/Task/Walk-a-directory-Non-recursively/00DESCRIPTION @@ -1,4 +1,4 @@ -Walk a given directory and print the ''names'' of files matching a given pattern. +Walk a given directory and print the ''names'' of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) '''Note:''' This task is for non-recursive methods. These tasks should read a ''single directory'', not an entire directory tree. For code examples that read entire directory trees, see [[Walk Directory Tree]] diff --git a/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m b/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m index f6296edf3e..a21afa9750 100644 --- a/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m +++ b/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m @@ -5,8 +5,6 @@ NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir] // OS X 10.5+ NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL]; -NSEnumerator *enm = [contents objectEnumerator]; -NSString *file; -while ((file = [enm nextObject])) +for (NSString *file in contents) if ([[file pathExtension] isEqualToString:@"mp3"]) NSLog(@"%@", file); diff --git a/Task/Walk-a-directory-Non-recursively/REXX/walk-a-directory-non-recursively.rexx b/Task/Walk-a-directory-Non-recursively/REXX/walk-a-directory-non-recursively.rexx new file mode 100644 index 0000000000..013db248e4 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/REXX/walk-a-directory-non-recursively.rexx @@ -0,0 +1,17 @@ +/*REXX program shows files in directory tree that match a given criteria*/ +parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/ +@.=0 /*default in case ADDRESS fails. */ +trace off /*suppress REXX err msg for fails*/ +address system 'DIR' xdir '/b /s' with output stem @. /*issue DIR cmd.*/ +if rc\==0 then do /*an error happened?*/ + say '***error!*** from DIR' xDIR /*indicate que pasa.*/ + say 'return code=' rc /*show the Ret Code.*/ + exit rc /*exit with the RC.*/ + end /* [↑] bad address.*/ +#=@.rc /*number of entries.*/ +if #==0 then #=' no ' /*use a word, ¬zero.*/ +say center('directory ' xdir " has " # ' matching entries.',79,'─') + + do j=1 for #; say @.j; end /*show files that met criteria. */ + +exit @.0+rc /*stick a fork in it, we're done.*/ diff --git a/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m b/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m index 68d02bc973..c900bd5101 100644 --- a/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m +++ b/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m @@ -1,7 +1,6 @@ NSString *dir = NSHomeDirectory(); NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir]; -NSString *file; -while ((file = [de nextObject])) +for (NSString *file in de) if ([[file pathExtension] isEqualToString:@"mp3"]) NSLog(@"%@", file); diff --git a/Task/Walk-a-directory-Recursively/REXX/walk-a-directory-recursively.rexx b/Task/Walk-a-directory-Recursively/REXX/walk-a-directory-recursively.rexx new file mode 100644 index 0000000000..12f237fc85 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/REXX/walk-a-directory-recursively.rexx @@ -0,0 +1,17 @@ +/*REXX program shows files in a single directory that match a criteria.*/ +parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/ +@.=0 /*default in case ADDRESS fails. */ +trace off /*suppress REXX err msg for fails*/ +address system 'DIR' xdir '/b' with output stem @. /*issue the DIR cmd.*/ +if rc\==0 then do /*an error happened?*/ + say '***error!*** from DIR' xDIR /*indicate que pasa.*/ + say 'return code=' rc /*show the Ret Code.*/ + exit rc /*exit with the RC.*/ + end /* [↑] bad address.*/ +#=@.rc /*number of entries.*/ +if #==0 then #=' no ' /*use a word, ¬zero.*/ +say center('directory ' xdir " has " # ' matching entries.',79,'─') + + do j=1 for #; say @.j; end /*show files that met criteria. */ + +exit @.0+rc /*stick a fork in it, we're done.*/ diff --git a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively.scala new file mode 100644 index 0000000000..9492867880 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively.scala @@ -0,0 +1,16 @@ +import java.io.File + +object `package` { + def walkTree(file: File): Iterable[File] = { + val children = new Iterable[File] { + def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty + } + Seq(file) ++: children.flatMap(walkTree(_)) + } +} + +object Test extends App { + val dir = new File("/home/user") + for(f <- walkTree(dir)) println(f) + for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f) +} diff --git a/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl b/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl index a065327028..330eb8febb 100644 --- a/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl +++ b/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl @@ -1,11 +1,31 @@ -proc walkin {fromDir pattern} { - foreach fname [glob -nocomplain -directory $fromDir *] { - if {[file isdirectory $fname]} { - walkin $fname $pattern - } elseif {[string match $pattern [file tail $fname]]} { - puts [file normalize $fname] +package require fileutil +proc walkin {path cmd} { + set normalized [::fileutil::fullnormalize $path] + set myname [lindex [info level 0] 0] + set children [glob -nocomplain -directory $path -types hidden *] + lappend children {*}[glob -nocomplain -directory $path *] + foreach child $children[set children {}] { + if {[file tail $child] in {. ..}} { + continue } + if {[file isdirectory $child]} { + if {[file type $child] eq "link"} { + set normalizedchild [fileutil::fullnormalize $child] + if {[string first $normalized/ $normalizedchild] == 0} { + #symlink to a directory in $path. Avoid cyclic traversal. + #Don't descend. + } else { + $myname $child $cmd + } + } + } + {*}$cmd $child } } -# replace directory with something appropriate -walkin /home/user *.mp3 + +walkin /home/usr {apply {fname { + set tail [file tail $fname] + if {[string match *.mp3 $tail]} { + puts $fname + } +}}} diff --git a/Task/Web-scraping/00DESCRIPTION b/Task/Web-scraping/00DESCRIPTION index fecb7cf54d..a9b7d490f7 100644 --- a/Task/Web-scraping/00DESCRIPTION +++ b/Task/Web-scraping/00DESCRIPTION @@ -1,5 +1,7 @@ Create a program that downloads the time from this URL: [http://tycho.usno.navy.mil/cgi-bin/timer.pl http://tycho.usno.navy.mil/cgi-bin/timer.pl] and then prints the current UTC time by extracting just the UTC time from the web page's [[HTML]]. + If possible, only use libraries that come at no ''extra'' monetary cost with the programming language and that are widely available and popular such as [http://www.cpan.org/ CPAN] for Perl or [[Boost]] for C++. diff --git a/Task/Window-creation/Go/window-creation-3.go b/Task/Window-creation/Go/window-creation-3.go index 6120729a69..81e3efe449 100644 --- a/Task/Window-creation/Go/window-creation-3.go +++ b/Task/Window-creation/Go/window-creation-3.go @@ -3,24 +3,20 @@ package main import ( "code.google.com/p/x-go-binding/ui" "code.google.com/p/x-go-binding/ui/x11" - "fmt" - "os" + "log" ) func main() { win, err := x11.NewWindow() if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) + log.Fatalf("Error: %v\n", err) } defer win.Close() - evchan := win.EventChan() - for ev := range evchan { + for ev := range win.EventChan() { switch e := ev.(type) { case ui.ErrEvent: - fmt.Printf("Error: %v\n", e.Err) - os.Exit(1) + log.Fatalf("Error: %v\n", e.Err) } } } diff --git a/Task/Window-creation/Kotlin/window-creation.kotlin b/Task/Window-creation/Kotlin/window-creation.kotlin new file mode 100644 index 0000000000..9b2000ba58 --- /dev/null +++ b/Task/Window-creation/Kotlin/window-creation.kotlin @@ -0,0 +1,8 @@ +import javax.swing.JFrame + +fun main(args : Array) { + val w = JFrame("Title") + w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) + w.setSize(800, 600) + w.setVisible(true) +} diff --git a/Task/Window-creation/Objective-C/window-creation.m b/Task/Window-creation/Objective-C/window-creation.m index ca001dbd3f..765e1e6b9a 100644 --- a/Task/Window-creation/Objective-C/window-creation.m +++ b/Task/Window-creation/Objective-C/window-creation.m @@ -12,24 +12,18 @@ @implementation Win : NSWindow -(id) init { - [self + if ((self = [super initWithContentRect: NSMakeRect(0, 0, 800, 600) styleMask: (NSTitledWindowMask | NSClosableWindowMask) backing: NSBackingStoreBuffered - defer: NO]; - - [self setTitle: @"A Window"]; - [self center]; + defer: NO])) { + [self setTitle: @"A Window"]; + [self center]; + } return self; } - --(void) dealloc -{ - [super dealloc]; -} - - (void)applicationDidFinishLaunching: (NSNotification *)notification { [self orderFront: self]; @@ -43,13 +37,13 @@ int main() { - Win *mywin; - NSAutoreleasePool *pool; + @autoreleasepool { - pool = [[NSAutoreleasePool alloc] init]; - [NSApplication sharedApplication]; - mywin = [[Win alloc] init]; - [NSApp setDelegate: mywin]; - [NSApp runModalForWindow: mywin]; + [NSApplication sharedApplication]; + Win *mywin = [[Win alloc] init]; + [NSApp setDelegate: mywin]; + [NSApp runModalForWindow: mywin]; + + } return EXIT_SUCCESS; } diff --git a/Task/Wireworld/AutoHotkey/wireworld.ahk b/Task/Wireworld/AutoHotkey/wireworld.ahk new file mode 100644 index 0000000000..c670151eac --- /dev/null +++ b/Task/Wireworld/AutoHotkey/wireworld.ahk @@ -0,0 +1,107 @@ +#SingleInstance, Force +#NoEnv +SetBatchLines, -1 +File := "Wireworld.txt" +CellSize := 20 +CellSize2 := CellSize - 2 +C1 := 0xff000000 +C2 := 0xff0066ff +C3 := 0xffd40055 +C4 := 0xffffcc00 + +if (!FileExist(File)) { + MsgBox, % "File(" File ") is not present." + ExitApp +} + +; Uncomment if Gdip.ahk is not in your standard library +; #Include, Gdip.ahk +If !pToken := Gdip_Startup(){ + MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. + ExitApp +} +OnExit, Exit + +A := [], Width := 0 +Loop, Read, % File +{ + Row := A_Index + Loop, Parse, A_LoopReadLine + { + if (A_Index > Width) + Width := A_Index + if (A_LoopField = A_Space) + continue + A[Row, A_Index] := A_LoopField + } +} + +Width := Width * CellSize + 2 * CellSize +, Height := Row * CellSize + 2 * CellSize +, Row := "" +, TopLeftX := (A_ScreenWidth - Width) // 2 +, TopLeftY := (A_ScreenHeight - Height) // 2 + +Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, 1: Show, NA + +hwnd1 := WinExist() +, hbm := CreateDIBSection(Width, Height) +, hdc := CreateCompatibleDC() +, obm := SelectObject(hdc, hbm) +, G := Gdip_GraphicsFromHDC(hdc) +, Gdip_SetSmoothingMode(G, 4) + +Loop { + pBrush := Gdip_BrushCreateSolid(C1) + , Gdip_FillRectangle(G, pBrush, 0, 0, Width, Height) + , Gdip_DeleteBrush(pBrush) + + for RowNum, Row in A + for CellNum, Cell in Row + C := Cell = "H" ? C2 : Cell = "t" ? C3 : C4 + , pBrush := Gdip_BrushCreateSolid(C) + , Gdip_FillRectangle(G, pBrush, CellNum * CellSize + 1, RowNum * CellSize - 2, CellSize2, CellSize2) + , Gdip_DeleteBrush(pBrush) + + + UpdateLayeredWindow(hwnd1, hdc, TopLeftX, TopLeftY, Width, Height) + , Gdip_GraphicsClear(G) + , A := NextState(A) + Sleep, 600 +} + +NextState(A) { + B := {} + for RowNum, Row in A { + for CellNum, Cell in Row { + if (Cell = "H") + B[RowNum, CellNum] := "t" + else if (Cell = "t") + B[RowNum, CellNum] := "." + else if (Cell = ".") { + H_Count := 0 + Loop 3 { + Y := RowNum - 2 + A_Index + Loop, 3 { + X := CellNum - 2 + A_Index + if (A[Y, X] = "H") + H_Count++ + } + } + if (H_Count = 1 || H_Count = 2) + B[RowNum, CellNum] := "H" + else + B[RowNum, CellNum] := "." + } + } + } + return B +} + +p::Pause + +Esc:: +Exit: +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Write-language-name-in-3D-ASCII/Ruby/write-language-name-in-3d-ascii.rb b/Task/Write-language-name-in-3D-ASCII/Ruby/write-language-name-in-3d-ascii.rb new file mode 100644 index 0000000000..5376ecbe99 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Ruby/write-language-name-in-3d-ascii.rb @@ -0,0 +1,33 @@ +text = < + + + + + + + +'; + +say . for $xml.nodes.grep(*.name eq 'Student') diff --git a/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j b/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j index 91d3f6cf86..31c5f9d50d 100644 --- a/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j +++ b/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j @@ -1,2 +1,3 @@ - wd'pc win closeok; xywh 0 0 300 200;cc g isigraph; pas 0 0; pshow;' + wd'pc win closeok; xywh 0 0 300 200;cc g isigraph; pas 0 0; pshow;' NB. J6 or earlier + wd'pc win closeok; minwh 600 400;cc g isigraph; pas 0 0; pshow;' NB. J8 or later glpaint drawLine 10 10 590 390 diff --git a/Task/Y-combinator/Objective-C/y-combinator.m b/Task/Y-combinator/Objective-C/y-combinator.m index da491e0ed2..e24caebd03 100644 --- a/Task/Y-combinator/Objective-C/y-combinator.m +++ b/Task/Y-combinator/Objective-C/y-combinator.m @@ -16,27 +16,27 @@ Func fix (FuncFunc f) { } int main (int argc, const char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - FuncFunc almost_fac = ^Func(Func f) { - return [[^(int n) { - if (n <= 1) return 1; - return n * f(n - 1); - } copy] autorelease]; - }; + FuncFunc almost_fac = ^Func(Func f) { + return ^(int n) { + if (n <= 1) return 1; + return n * f(n - 1); + }; + }; - FuncFunc almost_fib = ^Func(Func f) { - return [[^(int n) { - if (n <= 2) return 1; - return f(n - 1) + f(n - 2); - } copy] autorelease]; - }; + FuncFunc almost_fib = ^Func(Func f) { + return ^(int n) { + if (n <= 2) return 1; + return f(n - 1) + f(n - 2); + }; + }; - Func fib = fix(almost_fib); - Func fac = fix(almost_fac); - NSLog(@"fib(10) = %d", fib(10)); - NSLog(@"fac(10) = %d", fac(10)); + Func fib = fix(almost_fib); + Func fac = fix(almost_fac); + NSLog(@"fib(10) = %d", fib(10)); + NSLog(@"fac(10) = %d", fac(10)); - [pool release]; + } return 0; } diff --git a/Task/Y-combinator/TXR/y-combinator.txr b/Task/Y-combinator/TXR/y-combinator.txr new file mode 100644 index 0000000000..e12be5ded3 --- /dev/null +++ b/Task/Y-combinator/TXR/y-combinator.txr @@ -0,0 +1,14 @@ +@(do + ;; The Y combinator: + (defun y (f) + [(op @1 @1) + (op f (op [@@1 @@1]))]) + + ;; The Y-combinator-based factorial: + (defun fac (f) + (do if (zerop @1) + 1 + (* @1 [f (- @1 1)]))) + + ;; Test: + (format t "~s\n" [[y fac] 4])) diff --git a/Task/Y-combinator/XQuery/y-combinator-1.xquery b/Task/Y-combinator/XQuery/y-combinator-1.xquery new file mode 100644 index 0000000000..2bc85bb4d6 --- /dev/null +++ b/Task/Y-combinator/XQuery/y-combinator-1.xquery @@ -0,0 +1,9 @@ +let $Y := function($f) { + (function($x) { ($x)($x) })( function($g) { $f( (function($a) { $g($g) ($a)}) ) } ) + } +let $fac := $Y(function($f) { function($n) { if($n < 2) then 1 else $n * $f($n - 1) } }) +let $fib := $Y(function($f) { function($n) { if($n <= 1) then $n else $f($n - 1) + $f($n - 2) } }) +return ( + $fac(6), + $fib(6) +) diff --git a/Task/Y-combinator/XQuery/y-combinator-2.xquery b/Task/Y-combinator/XQuery/y-combinator-2.xquery new file mode 100644 index 0000000000..a3ee25ef56 --- /dev/null +++ b/Task/Y-combinator/XQuery/y-combinator-2.xquery @@ -0,0 +1 @@ +720 8 diff --git a/Task/Zebra-puzzle/Clojure/zebra-puzzle.clj b/Task/Zebra-puzzle/Clojure/zebra-puzzle.clj new file mode 100644 index 0000000000..afcd1828f4 --- /dev/null +++ b/Task/Zebra-puzzle/Clojure/zebra-puzzle.clj @@ -0,0 +1,42 @@ +(ns zebra.core + (:refer-clojure :exclude [==]) + (:use [clojure.core.logic] + [clojure.tools.macro :as macro])) + +(defne lefto [x y l] + ([_ _ [x y . ?r]]) + ([_ _ [_ . ?r]] (lefto x y ?r))) + +(defn nexto [x y l] + (conde + ((lefto x y l)) + ((lefto y x l)))) + +(defn zebrao [hs] + (macro/symbol-macrolet [_ (lvar)] + (all + (== [_ _ _ _ _] hs) + (membero ['englishman _ _ _ 'red] hs) + (membero ['swede _ _ 'dog _] hs) + (membero ['dane _ 'tea _ _] hs) + (lefto [_ _ _ _ 'green] [_ _ _ _ 'white] hs) + (membero [_ _ 'coffee _ 'green] hs) + (membero [_ 'pallmall _ 'birds _] hs) + (membero [_ 'dunhill _ _ 'yellow] hs) + (== [_ _ [_ _ 'milk _ _] _ _ ] hs) + (firsto hs ['norwegian _ _ _ _]) + (nexto [_ 'blend _ _ _] [_ _ _ 'cats _ ] hs) + (nexto [_ _ _ 'horse _] [_ 'dunhill _ _ _] hs) + (membero [_ 'bluemaster 'beer _ _] hs) + (membero ['german 'prince _ _ _] hs) + (nexto ['norwegian _ _ _ _] [_ _ _ _ 'blue] hs) + (nexto [_ _ 'water _ _] [_ 'blend _ _ _] hs) + (membero [_ _ _ 'zebra _] hs)))) + +(let [solns (run* [q] (zebrao q)) + soln (first solns) + zebra-owner (->> soln (filter #(= 'zebra (% 3))) first (#(% 0)))] + (println "solution count:" (count solns)) + (println "zebra owner is the" zebra-owner) + (println "full solution (in house order):") + (doseq [h soln] (println " " h))) diff --git a/Task/Zeckendorf-number-representation/AutoHotkey/zeckendorf-number-representation.ahk b/Task/Zeckendorf-number-representation/AutoHotkey/zeckendorf-number-representation.ahk new file mode 100644 index 0000000000..1cb7851944 --- /dev/null +++ b/Task/Zeckendorf-number-representation/AutoHotkey/zeckendorf-number-representation.ahk @@ -0,0 +1,24 @@ +Fib := NStepSequence(1, 2, 2, 20) +Loop, 21 { + i := A_Index - 1 + , Out .= i ":`t", n := "" + Loop, % Fib.MaxIndex() { + x := Fib.MaxIndex() + 1 - A_Index + if (Fib[x] <= i) + n .= 1, i -= Fib[x] + else + n .= 0 + } + Out .= (n ? LTrim(n, "0") : 0) "`n" +} +MsgBox, % Out + +NStepSequence(v1, v2, n, k) { + a := [v1, v2] + Loop, % k - 2 { + a[j := A_Index + 2] := 0 + Loop, % j < n + 2 ? j - 1 : n + a[j] += a[j - A_Index] + } + return, a +} diff --git a/Task/Zeckendorf-number-representation/Clojure/zeckendorf-number-representation.clj b/Task/Zeckendorf-number-representation/Clojure/zeckendorf-number-representation.clj new file mode 100644 index 0000000000..7bf92947e3 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Clojure/zeckendorf-number-representation.clj @@ -0,0 +1,13 @@ +(def fibs (lazy-cat [1 1] (map + fibs (rest fibs)))) + +(defn z [n] + (if (zero? n) + "0" + (let [ps (->> fibs (take-while #(<= % n)) rest reverse) + fz (fn [[s n] p] + (if (>= n p) + [(conj s 1) (- n p)] + [(conj s 0) n]))] + (->> ps (reduce fz [[] n]) first (apply str))))) + +(doseq [n (range 0 21)] (println n (z n))) diff --git a/Task/Zeckendorf-number-representation/Forth/zeckendorf-number-representation.fth b/Task/Zeckendorf-number-representation/Forth/zeckendorf-number-representation.fth new file mode 100644 index 0000000000..3b74bf9ef4 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Forth/zeckendorf-number-representation.fth @@ -0,0 +1,15 @@ +: fib<= ( n -- n ) + >r 0 1 BEGIN dup r@ <= WHILE tuck + REPEAT drop rdrop ; + +: z. ( n -- ) + dup fib<= dup . - + BEGIN ?dup WHILE + dup fib<= dup [char] + emit space . - + REPEAT ; + +: tab 9 emit ; + +: zeckendorf ( -- ) + 21 0 DO + cr i 2 .r tab i z. + LOOP ; diff --git a/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 b/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 index 90f0b62d67..1c6f4b78f1 100644 --- a/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 +++ b/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 @@ -3,7 +3,7 @@ printf "%2d: %8s\n", $_, zeckendorf($_) for 0 .. 20; multi zeckendorf(0) { '0' } multi zeckendorf($n is copy) { constant FIBS = 1,2, *+* ... *; - join '', map { + [~] map { $n -= $_ if my $digit = $n >= $_; +$digit; }, reverse FIBS ...^ * > $n;