diff --git a/Lang/AWK/Closest-pair-problem b/Lang/AWK/Closest-pair-problem new file mode 120000 index 0000000000..53e5953314 --- /dev/null +++ b/Lang/AWK/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/AWK \ No newline at end of file diff --git a/Lang/AWK/Digital-root b/Lang/AWK/Digital-root new file mode 120000 index 0000000000..3f27d1f377 --- /dev/null +++ b/Lang/AWK/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/AWK \ No newline at end of file diff --git a/Lang/AWK/Execute-Brain---- b/Lang/AWK/Execute-Brain---- new file mode 120000 index 0000000000..f55d179614 --- /dev/null +++ b/Lang/AWK/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/AWK \ No newline at end of file diff --git a/Lang/AWK/Generic-swap b/Lang/AWK/Generic-swap new file mode 120000 index 0000000000..9030ae4ad7 --- /dev/null +++ b/Lang/AWK/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/AWK \ No newline at end of file diff --git a/Lang/AWK/Guess-the-number b/Lang/AWK/Guess-the-number new file mode 120000 index 0000000000..b8ef14a77f --- /dev/null +++ b/Lang/AWK/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/AWK \ No newline at end of file diff --git a/Lang/AWK/Guess-the-number-With-feedback b/Lang/AWK/Guess-the-number-With-feedback new file mode 120000 index 0000000000..7f205c7739 --- /dev/null +++ b/Lang/AWK/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/AWK \ No newline at end of file diff --git a/Lang/AWK/Introspection b/Lang/AWK/Introspection new file mode 120000 index 0000000000..ad2d10178e --- /dev/null +++ b/Lang/AWK/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/AWK \ No newline at end of file diff --git a/Lang/AWK/Josephus-problem b/Lang/AWK/Josephus-problem new file mode 120000 index 0000000000..117dc8c08e --- /dev/null +++ b/Lang/AWK/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/AWK \ No newline at end of file diff --git a/Lang/AWK/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/AWK/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..31a9e0114c --- /dev/null +++ b/Lang/AWK/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/AWK \ No newline at end of file diff --git a/Lang/AWK/Lucas-Lehmer-test b/Lang/AWK/Lucas-Lehmer-test new file mode 120000 index 0000000000..265b54e167 --- /dev/null +++ b/Lang/AWK/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/AWK \ No newline at end of file diff --git a/Lang/AWK/Mad-Libs b/Lang/AWK/Mad-Libs new file mode 120000 index 0000000000..a94a6ccc23 --- /dev/null +++ b/Lang/AWK/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/AWK \ No newline at end of file diff --git a/Lang/AWK/Map-range b/Lang/AWK/Map-range new file mode 120000 index 0000000000..b191a19fd4 --- /dev/null +++ b/Lang/AWK/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/AWK \ No newline at end of file diff --git a/Lang/AWK/Multisplit b/Lang/AWK/Multisplit new file mode 120000 index 0000000000..cd76bed00a --- /dev/null +++ b/Lang/AWK/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/AWK \ No newline at end of file diff --git a/Lang/AWK/Read-a-configuration-file b/Lang/AWK/Read-a-configuration-file new file mode 120000 index 0000000000..3f1d8aa995 --- /dev/null +++ b/Lang/AWK/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/AWK \ No newline at end of file diff --git a/Lang/AWK/Sort-an-integer-array b/Lang/AWK/Sort-an-integer-array new file mode 120000 index 0000000000..349857968f --- /dev/null +++ b/Lang/AWK/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/AWK \ No newline at end of file diff --git a/Lang/AWK/Sort-using-a-custom-comparator b/Lang/AWK/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..5431f320b6 --- /dev/null +++ b/Lang/AWK/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/AWK \ No newline at end of file diff --git a/Lang/AWK/Trabb-Pardo-Knuth-algorithm b/Lang/AWK/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..e87ccec943 --- /dev/null +++ b/Lang/AWK/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/AWK \ No newline at end of file diff --git a/Lang/AWK/Write-language-name-in-3D-ASCII b/Lang/AWK/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..f043db02b7 --- /dev/null +++ b/Lang/AWK/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/AWK \ No newline at end of file diff --git a/Lang/ActionScript/Bitmap b/Lang/ActionScript/Bitmap new file mode 120000 index 0000000000..612e6b87cd --- /dev/null +++ b/Lang/ActionScript/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Colour-bars-Display b/Lang/ActionScript/Colour-bars-Display new file mode 120000 index 0000000000..95ad7bacb1 --- /dev/null +++ b/Lang/ActionScript/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Colour-pinstripe-Display b/Lang/ActionScript/Colour-pinstripe-Display new file mode 120000 index 0000000000..6e4393b21d --- /dev/null +++ b/Lang/ActionScript/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Honeycombs b/Lang/ActionScript/Honeycombs new file mode 120000 index 0000000000..ebed80a6a5 --- /dev/null +++ b/Lang/ActionScript/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Mouse-position b/Lang/ActionScript/Mouse-position new file mode 120000 index 0000000000..a6d5416322 --- /dev/null +++ b/Lang/ActionScript/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Multiplication-tables b/Lang/ActionScript/Multiplication-tables new file mode 120000 index 0000000000..44a4d5313b --- /dev/null +++ b/Lang/ActionScript/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Pig-the-dice-game b/Lang/ActionScript/Pig-the-dice-game new file mode 120000 index 0000000000..f85a9625e1 --- /dev/null +++ b/Lang/ActionScript/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Pinstripe-Display b/Lang/ActionScript/Pinstripe-Display new file mode 120000 index 0000000000..2072f42a44 --- /dev/null +++ b/Lang/ActionScript/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sierpinski-triangle-Graphical b/Lang/ActionScript/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..dce009ad90 --- /dev/null +++ b/Lang/ActionScript/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Van-der-Corput-sequence b/Lang/ActionScript/Van-der-Corput-sequence new file mode 120000 index 0000000000..d3fabf0ace --- /dev/null +++ b/Lang/ActionScript/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Variable-size-Get b/Lang/ActionScript/Variable-size-Get new file mode 120000 index 0000000000..2fded41f1f --- /dev/null +++ b/Lang/ActionScript/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/ActionScript \ No newline at end of file diff --git a/Lang/Ada/Bitcoin-address-validation b/Lang/Ada/Bitcoin-address-validation new file mode 120000 index 0000000000..baa0f32023 --- /dev/null +++ b/Lang/Ada/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Ada \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/00DESCRIPTION b/Lang/Applesoft-BASIC/00DESCRIPTION index 4669b84f59..7e8548dc93 100644 --- a/Lang/Applesoft-BASIC/00DESCRIPTION +++ b/Lang/Applesoft-BASIC/00DESCRIPTION @@ -1,5 +1,4 @@ -{{stub}}{{language|Applesoft BASIC -|exec=interpreted}} +{{language|Applesoft BASIC|exec=interpreted}} {{implementation|BASIC}} '''Applesoft BASIC''' was a dialect of [[BASIC]] supplied with the [[wp:Apple II|Apple II]] series of computers. It superseded [[Integer BASIC]] and was the [[BASIC]] in ROM in all [[wp:Apple II|Apple II]] series computers after the original Apple II model. diff --git a/Lang/Applesoft-BASIC/Create-a-file-on-magnetic-tape b/Lang/Applesoft-BASIC/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..f63354a6ee --- /dev/null +++ b/Lang/Applesoft-BASIC/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Host-introspection b/Lang/Applesoft-BASIC/Host-introspection new file mode 120000 index 0000000000..9a2aad990a --- /dev/null +++ b/Lang/Applesoft-BASIC/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Joystick-position b/Lang/Applesoft-BASIC/Joystick-position new file mode 120000 index 0000000000..fb12dc82b8 --- /dev/null +++ b/Lang/Applesoft-BASIC/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Prime-decomposition b/Lang/Applesoft-BASIC/Prime-decomposition new file mode 120000 index 0000000000..ef7eab7aea --- /dev/null +++ b/Lang/Applesoft-BASIC/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/AutoHotkey/I-before-E-except-after-C b/Lang/AutoHotkey/I-before-E-except-after-C new file mode 120000 index 0000000000..67f2a4587d --- /dev/null +++ b/Lang/AutoHotkey/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/MD4 b/Lang/AutoHotkey/MD4 new file mode 120000 index 0000000000..14b95fc297 --- /dev/null +++ b/Lang/AutoHotkey/MD4 @@ -0,0 +1 @@ +../../Task/MD4/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Middle-three-digits b/Lang/AutoHotkey/Middle-three-digits new file mode 120000 index 0000000000..8ccf64ccd4 --- /dev/null +++ b/Lang/AutoHotkey/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/SHA-1 b/Lang/AutoHotkey/SHA-1 new file mode 120000 index 0000000000..90f7e2d23d --- /dev/null +++ b/Lang/AutoHotkey/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/SHA-256 b/Lang/AutoHotkey/SHA-256 new file mode 120000 index 0000000000..3a06e27af9 --- /dev/null +++ b/Lang/AutoHotkey/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Strip-block-comments b/Lang/AutoHotkey/Strip-block-comments new file mode 120000 index 0000000000..db042a1291 --- /dev/null +++ b/Lang/AutoHotkey/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sum-digits-of-an-integer b/Lang/AutoHotkey/Sum-digits-of-an-integer new file mode 120000 index 0000000000..79cfdc78e5 --- /dev/null +++ b/Lang/AutoHotkey/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Temperature-conversion b/Lang/AutoHotkey/Temperature-conversion new file mode 120000 index 0000000000..fb98bd381b --- /dev/null +++ b/Lang/AutoHotkey/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Cursor-movement b/Lang/AutoHotkey/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..78b180b136 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Unicode-output b/Lang/AutoHotkey/Terminal-control-Unicode-output new file mode 120000 index 0000000000..af9a6e3070 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Word-wrap b/Lang/AutoHotkey/Word-wrap new file mode 120000 index 0000000000..6d0f6f0009 --- /dev/null +++ b/Lang/AutoHotkey/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Write-language-name-in-3D-ASCII b/Lang/AutoHotkey/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..13052a4f1e --- /dev/null +++ b/Lang/AutoHotkey/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoIt/Align-columns b/Lang/AutoIt/Align-columns new file mode 120000 index 0000000000..103a978d8e --- /dev/null +++ b/Lang/AutoIt/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Calendar b/Lang/AutoIt/Calendar new file mode 120000 index 0000000000..7e9dd1dada --- /dev/null +++ b/Lang/AutoIt/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Conditional-structures b/Lang/AutoIt/Conditional-structures new file mode 120000 index 0000000000..61f15c64ed --- /dev/null +++ b/Lang/AutoIt/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Date-format b/Lang/AutoIt/Date-format new file mode 120000 index 0000000000..d9081e4ef3 --- /dev/null +++ b/Lang/AutoIt/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Four-bit-adder b/Lang/AutoIt/Four-bit-adder new file mode 120000 index 0000000000..1da7152d85 --- /dev/null +++ b/Lang/AutoIt/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Langtons-ant b/Lang/AutoIt/Langtons-ant new file mode 120000 index 0000000000..f8e202b4af --- /dev/null +++ b/Lang/AutoIt/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Last-Friday-of-each-month b/Lang/AutoIt/Last-Friday-of-each-month new file mode 120000 index 0000000000..fffcf049b1 --- /dev/null +++ b/Lang/AutoIt/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Least-common-multiple b/Lang/AutoIt/Least-common-multiple new file mode 120000 index 0000000000..30c0eee4bf --- /dev/null +++ b/Lang/AutoIt/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/AutoIt \ No newline at end of file diff --git a/Lang/BASIC/Colour-bars-Display b/Lang/BASIC/Colour-bars-Display new file mode 120000 index 0000000000..0b13f925a9 --- /dev/null +++ b/Lang/BASIC/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Copy-a-string b/Lang/BASIC/Copy-a-string new file mode 120000 index 0000000000..af94163039 --- /dev/null +++ b/Lang/BASIC/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Detect-division-by-zero b/Lang/BASIC/Detect-division-by-zero new file mode 120000 index 0000000000..68ae31fd93 --- /dev/null +++ b/Lang/BASIC/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Execute-Brain---- b/Lang/BASIC/Execute-Brain---- new file mode 120000 index 0000000000..449aaa6736 --- /dev/null +++ b/Lang/BASIC/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Guess-the-number-With-feedback b/Lang/BASIC/Guess-the-number-With-feedback new file mode 120000 index 0000000000..1efc208617 --- /dev/null +++ b/Lang/BASIC/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Hailstone-sequence b/Lang/BASIC/Hailstone-sequence new file mode 120000 index 0000000000..178bfab94c --- /dev/null +++ b/Lang/BASIC/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Input-loop b/Lang/BASIC/Input-loop new file mode 120000 index 0000000000..8ffe59c587 --- /dev/null +++ b/Lang/BASIC/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Least-common-multiple b/Lang/BASIC/Least-common-multiple new file mode 120000 index 0000000000..ceafb0999d --- /dev/null +++ b/Lang/BASIC/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Middle-three-digits b/Lang/BASIC/Middle-three-digits new file mode 120000 index 0000000000..b885b99145 --- /dev/null +++ b/Lang/BASIC/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Null-object b/Lang/BASIC/Null-object new file mode 120000 index 0000000000..9fc687ec7f --- /dev/null +++ b/Lang/BASIC/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Scope-modifiers b/Lang/BASIC/Scope-modifiers new file mode 120000 index 0000000000..0a5416c49d --- /dev/null +++ b/Lang/BASIC/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Write-language-name-in-3D-ASCII b/Lang/BASIC/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..b737bbc6eb --- /dev/null +++ b/Lang/BASIC/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Averages-Mean-time-of-day b/Lang/BBC-BASIC/Averages-Mean-time-of-day new file mode 120000 index 0000000000..1622f6f620 --- /dev/null +++ b/Lang/BBC-BASIC/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/BBC-BASIC \ No newline at end of file diff --git a/Lang/Batch-File/Even-or-odd b/Lang/Batch-File/Even-or-odd new file mode 120000 index 0000000000..f8167f63ed --- /dev/null +++ b/Lang/Batch-File/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/File-size b/Lang/Batch-File/File-size new file mode 120000 index 0000000000..32f43f742b --- /dev/null +++ b/Lang/Batch-File/File-size @@ -0,0 +1 @@ +../../Task/File-size/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Hello-world-Graphical b/Lang/Batch-File/Hello-world-Graphical new file mode 120000 index 0000000000..d81307b6bd --- /dev/null +++ b/Lang/Batch-File/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Include-a-file b/Lang/Batch-File/Include-a-file new file mode 120000 index 0000000000..f278def0dc --- /dev/null +++ b/Lang/Batch-File/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Input-loop b/Lang/Batch-File/Input-loop new file mode 120000 index 0000000000..a2a4a9b473 --- /dev/null +++ b/Lang/Batch-File/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Variables b/Lang/Batch-File/Variables new file mode 120000 index 0000000000..4b7cbffea1 --- /dev/null +++ b/Lang/Batch-File/Variables @@ -0,0 +1 @@ +../../Task/Variables/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Visualize-a-tree b/Lang/Batch-File/Visualize-a-tree new file mode 120000 index 0000000000..b981125eff --- /dev/null +++ b/Lang/Batch-File/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/Write-language-name-in-3D-ASCII b/Lang/Befunge/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..61a440815a --- /dev/null +++ b/Lang/Befunge/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Befunge \ No newline at end of file diff --git a/Lang/Bracmat/Arithmetic-Integer b/Lang/Bracmat/Arithmetic-Integer new file mode 120000 index 0000000000..b20cbdebf8 --- /dev/null +++ b/Lang/Bracmat/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Digital-root b/Lang/Bracmat/Digital-root new file mode 120000 index 0000000000..19979f923e --- /dev/null +++ b/Lang/Bracmat/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Flow-control-structures b/Lang/Bracmat/Flow-control-structures new file mode 120000 index 0000000000..1802b1d333 --- /dev/null +++ b/Lang/Bracmat/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Multiplication-tables b/Lang/Bracmat/Multiplication-tables new file mode 120000 index 0000000000..d36ae1867b --- /dev/null +++ b/Lang/Bracmat/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Power-set b/Lang/Bracmat/Power-set new file mode 120000 index 0000000000..8c71ebebde --- /dev/null +++ b/Lang/Bracmat/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Top-rank-per-group b/Lang/Bracmat/Top-rank-per-group new file mode 120000 index 0000000000..7ed033e081 --- /dev/null +++ b/Lang/Bracmat/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Twelve-statements b/Lang/Bracmat/Twelve-statements new file mode 120000 index 0000000000..2e63a1205e --- /dev/null +++ b/Lang/Bracmat/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Variable-length-quantity b/Lang/Bracmat/Variable-length-quantity new file mode 120000 index 0000000000..5770b51439 --- /dev/null +++ b/Lang/Bracmat/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Bracmat \ No newline at end of file diff --git a/Lang/C++/I-before-E-except-after-C b/Lang/C++/I-before-E-except-after-C new file mode 120000 index 0000000000..f05fa9fb7a --- /dev/null +++ b/Lang/C++/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Globally-replace-text-in-several-files b/Lang/C-sharp/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..af34b3da84 --- /dev/null +++ b/Lang/C-sharp/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/C-sharp \ No newline at end of file diff --git a/Lang/C/Colour-bars-Display b/Lang/C/Colour-bars-Display new file mode 120000 index 0000000000..fcb9bac6f5 --- /dev/null +++ b/Lang/C/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/C \ No newline at end of file diff --git a/Lang/C/Colour-pinstripe-Display b/Lang/C/Colour-pinstripe-Display new file mode 120000 index 0000000000..0abcfa710d --- /dev/null +++ b/Lang/C/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/C \ No newline at end of file diff --git a/Lang/C/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/C/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..1667981359 --- /dev/null +++ b/Lang/C/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C \ No newline at end of file diff --git a/Lang/C/Pinstripe-Display b/Lang/C/Pinstripe-Display new file mode 120000 index 0000000000..412805fbf0 --- /dev/null +++ b/Lang/C/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/C \ No newline at end of file diff --git a/Lang/C/Scope-Function-names-and-labels b/Lang/C/Scope-Function-names-and-labels new file mode 120000 index 0000000000..a5959d2fcb --- /dev/null +++ b/Lang/C/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/C \ No newline at end of file diff --git a/Lang/C/Start-from-a-main-routine b/Lang/C/Start-from-a-main-routine new file mode 120000 index 0000000000..dec2ae76aa --- /dev/null +++ b/Lang/C/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Cursor-movement b/Lang/C/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..4df2477a37 --- /dev/null +++ b/Lang/C/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/C \ No newline at end of file diff --git a/Lang/COBOL/00DESCRIPTION b/Lang/COBOL/00DESCRIPTION index e33b522f75..98ece1caa8 100644 --- a/Lang/COBOL/00DESCRIPTION +++ b/Lang/COBOL/00DESCRIPTION @@ -16,8 +16,8 @@ COBOL, an acronym for 'COmmon Business Oriented Language', is one of the oldest * '''ANS COBOL 1968''' is the first COBOL standard and was published by [[ANSI]]. It was created to improve compatibility between the different versions of the language. * '''COBOL 1974''' added a few more features to the language, including the ability to ACCEPT the date, day and time, and the file organization clause. * '''COBOL 1985''' added many new features to COBOL, notably including: scope terminators (END-IF, END-READ, etc.), the EVALUATE verb, the CONTINUE verb, inline PERFORM statements, the ability to pass arguments by content, and the deprecation of the infamous ALTER verb. This standard was followed by the intrinsic functions amendment and a clarifications amendment in 1989 and 1991, respectively. -* '''COBOL 2002''' is the current version of COBOL and was published by [[ISO]] as ISO/IEC 1989. It included a host of new features, most notably including object-oriented programming. However, there were also other features, including: floating-point support, portable arithmetic results, pointers, calling conventions to other languages, function prototypes, [[XML]] facilities and support for execution within framework environments. This standard has suffered from poor vendor support, due to little commercial demand for the new features.John Billman & Huib Klink, 'Thoughts on the Future of COBOL Standardization', [http://www.cobolstandard.info/j4/files/08-0034.pdf] -* '''COBOL 201X''' is the next version of the standard version of the standard and the final draft is expected to be published in 2014. It will likely include outstanding technical reports which include object finalization and a collection class library. +* '''COBOL 2002''' is the current version of COBOL and was published by [[ISO]] as ISO/IEC 1989. It included a host of new features, most notably including object-oriented programming. However, there were also other features, including: floating-point support, portable arithmetic results, pointers, calling conventions to other languages, function prototypes, [[XML]] facilities and support for execution within framework environments. This standard has suffered from poor vendor support, due to little commercial demand for the new features.John Billman & Huib Klink, 'Thoughts on the Future of COBOL Standardization', [https://www.cobolstandard.info/j4/files/08-0034.pdf] +* '''COBOL 201X''' is the next version of the standard version of the standard and is expected to be published in early 2014.ISO, 'ISO/IEC 1989', [https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=51416] It will likely include outstanding technical reports which include object finalization and a collection class library. ===References=== diff --git a/Lang/COBOL/Arithmetic-Complex b/Lang/COBOL/Arithmetic-Complex new file mode 120000 index 0000000000..6a2a3facf8 --- /dev/null +++ b/Lang/COBOL/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Caesar-cipher b/Lang/COBOL/Caesar-cipher new file mode 120000 index 0000000000..50dbbbf681 --- /dev/null +++ b/Lang/COBOL/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Fibonacci-sequence b/Lang/COBOL/Fibonacci-sequence new file mode 120000 index 0000000000..dd5904fc18 --- /dev/null +++ b/Lang/COBOL/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Input-loop b/Lang/COBOL/Input-loop new file mode 120000 index 0000000000..9f9eaa09e6 --- /dev/null +++ b/Lang/COBOL/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Pick-random-element b/Lang/COBOL/Pick-random-element new file mode 120000 index 0000000000..1087f49748 --- /dev/null +++ b/Lang/COBOL/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Run-length-encoding b/Lang/COBOL/Run-length-encoding new file mode 120000 index 0000000000..df0b1862d0 --- /dev/null +++ b/Lang/COBOL/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/COBOL \ No newline at end of file diff --git a/Lang/COBOL/SEDOLs b/Lang/COBOL/SEDOLs new file mode 120000 index 0000000000..736ac898f4 --- /dev/null +++ b/Lang/COBOL/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Stooge-sort b/Lang/COBOL/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..d6e24ec47f --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Standard-deviation b/Lang/COBOL/Standard-deviation new file mode 120000 index 0000000000..9f8fa60e84 --- /dev/null +++ b/Lang/COBOL/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/COBOL \ No newline at end of file diff --git a/Lang/COBOL/String-length b/Lang/COBOL/String-length new file mode 120000 index 0000000000..348bfbfc5a --- /dev/null +++ b/Lang/COBOL/String-length @@ -0,0 +1 @@ +../../Task/String-length/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Strip-whitespace-from-a-string-Top-and-tail b/Lang/COBOL/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..246c4bee67 --- /dev/null +++ b/Lang/COBOL/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Towers-of-Hanoi b/Lang/COBOL/Towers-of-Hanoi new file mode 120000 index 0000000000..2c4e207bc0 --- /dev/null +++ b/Lang/COBOL/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/COBOL \ No newline at end of file diff --git a/Lang/Clipper/Arithmetic-Integer b/Lang/Clipper/Arithmetic-Integer new file mode 120000 index 0000000000..c46ebcaa0b --- /dev/null +++ b/Lang/Clipper/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Include-a-file b/Lang/Clipper/Include-a-file new file mode 120000 index 0000000000..931ea9b524 --- /dev/null +++ b/Lang/Clipper/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Integer-comparison b/Lang/Clipper/Integer-comparison new file mode 120000 index 0000000000..c59c2d55f5 --- /dev/null +++ b/Lang/Clipper/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Leap-year b/Lang/Clipper/Leap-year new file mode 120000 index 0000000000..e4a206e97c --- /dev/null +++ b/Lang/Clipper/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Logical-operations b/Lang/Clipper/Logical-operations new file mode 120000 index 0000000000..441b408a1d --- /dev/null +++ b/Lang/Clipper/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Loops-Continue b/Lang/Clipper/Loops-Continue new file mode 120000 index 0000000000..d52d11e008 --- /dev/null +++ b/Lang/Clipper/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Loops-Do-while b/Lang/Clipper/Loops-Do-while new file mode 120000 index 0000000000..07625ec397 --- /dev/null +++ b/Lang/Clipper/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Loops-Downward-for b/Lang/Clipper/Loops-Downward-for new file mode 120000 index 0000000000..0f7d5d0d73 --- /dev/null +++ b/Lang/Clipper/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Clipper \ No newline at end of file diff --git a/Lang/Clipper/String-comparison b/Lang/Clipper/String-comparison new file mode 120000 index 0000000000..d7993203b2 --- /dev/null +++ b/Lang/Clipper/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Clipper \ No newline at end of file diff --git a/Lang/Clojure/Roots-of-a-quadratic-function b/Lang/Clojure/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..906b895835 --- /dev/null +++ b/Lang/Clojure/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Van-der-Corput-sequence b/Lang/Clojure/Van-der-Corput-sequence new file mode 120000 index 0000000000..a74338cbe9 --- /dev/null +++ b/Lang/Clojure/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Playing-cards b/Lang/CoffeeScript/Playing-cards new file mode 120000 index 0000000000..896912165b --- /dev/null +++ b/Lang/CoffeeScript/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/CoffeeScript \ No newline at end of file diff --git a/Lang/Common-Lisp/Pick-random-element b/Lang/Common-Lisp/Pick-random-element new file mode 120000 index 0000000000..675a882cce --- /dev/null +++ b/Lang/Common-Lisp/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Send-an-unknown-method-call b/Lang/Common-Lisp/Send-an-unknown-method-call new file mode 120000 index 0000000000..3915313273 --- /dev/null +++ b/Lang/Common-Lisp/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Common-Lisp \ No newline at end of file diff --git a/Lang/D/Calendar---for-real-programmers b/Lang/D/Calendar---for-real-programmers new file mode 120000 index 0000000000..ad4ff5ef7a --- /dev/null +++ b/Lang/D/Calendar---for-real-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-real-programmers/D \ No newline at end of file diff --git a/Lang/D/Terminal-control-Ringing-the-terminal-bell b/Lang/D/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..44d9f62c64 --- /dev/null +++ b/Lang/D/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/D \ No newline at end of file diff --git a/Lang/Dart/A+B b/Lang/Dart/A+B new file mode 120000 index 0000000000..c4b91e08fb --- /dev/null +++ b/Lang/Dart/A+B @@ -0,0 +1 @@ +../../Task/A+B/Dart \ No newline at end of file diff --git a/Lang/Dart/Accumulator-factory b/Lang/Dart/Accumulator-factory new file mode 120000 index 0000000000..b75f0d4814 --- /dev/null +++ b/Lang/Dart/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Dart \ No newline at end of file diff --git a/Lang/Dart/Arithmetic-Complex b/Lang/Dart/Arithmetic-Complex new file mode 120000 index 0000000000..097843b1e1 --- /dev/null +++ b/Lang/Dart/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Dart \ No newline at end of file diff --git a/Lang/Dart/Parametric-polymorphism b/Lang/Dart/Parametric-polymorphism new file mode 120000 index 0000000000..344f12d941 --- /dev/null +++ b/Lang/Dart/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Dart \ No newline at end of file diff --git a/Lang/Deja-Vu/100-doors b/Lang/Deja-Vu/100-doors new file mode 120000 index 0000000000..4e7ab7ee6f --- /dev/null +++ b/Lang/Deja-Vu/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/99-Bottles-of-Beer b/Lang/Deja-Vu/99-Bottles-of-Beer new file mode 120000 index 0000000000..a10211c5f7 --- /dev/null +++ b/Lang/Deja-Vu/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Apply-a-callback-to-an-array b/Lang/Deja-Vu/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..18b854df76 --- /dev/null +++ b/Lang/Deja-Vu/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Balanced-brackets b/Lang/Deja-Vu/Balanced-brackets new file mode 120000 index 0000000000..24a4e1ce98 --- /dev/null +++ b/Lang/Deja-Vu/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Binary-strings b/Lang/Deja-Vu/Binary-strings new file mode 120000 index 0000000000..1fbbf82daf --- /dev/null +++ b/Lang/Deja-Vu/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Call-a-function b/Lang/Deja-Vu/Call-a-function new file mode 120000 index 0000000000..a59f0a3f3b --- /dev/null +++ b/Lang/Deja-Vu/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Case-sensitivity-of-identifiers b/Lang/Deja-Vu/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..674e8bc728 --- /dev/null +++ b/Lang/Deja-Vu/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Comments b/Lang/Deja-Vu/Comments new file mode 120000 index 0000000000..08c54424e3 --- /dev/null +++ b/Lang/Deja-Vu/Comments @@ -0,0 +1 @@ +../../Task/Comments/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Copy-a-string b/Lang/Deja-Vu/Copy-a-string new file mode 120000 index 0000000000..384245053d --- /dev/null +++ b/Lang/Deja-Vu/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Dot-product b/Lang/Deja-Vu/Dot-product new file mode 120000 index 0000000000..3127b1267a --- /dev/null +++ b/Lang/Deja-Vu/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Dynamic-variable-names b/Lang/Deja-Vu/Dynamic-variable-names new file mode 120000 index 0000000000..58081d7ac3 --- /dev/null +++ b/Lang/Deja-Vu/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Even-or-odd b/Lang/Deja-Vu/Even-or-odd new file mode 120000 index 0000000000..570530ca3d --- /dev/null +++ b/Lang/Deja-Vu/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Exceptions b/Lang/Deja-Vu/Exceptions new file mode 120000 index 0000000000..09a5194b6e --- /dev/null +++ b/Lang/Deja-Vu/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Executable-library b/Lang/Deja-Vu/Executable-library new file mode 120000 index 0000000000..fbd2ee96d0 --- /dev/null +++ b/Lang/Deja-Vu/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Factorial b/Lang/Deja-Vu/Factorial new file mode 120000 index 0000000000..acc30eb261 --- /dev/null +++ b/Lang/Deja-Vu/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Filter b/Lang/Deja-Vu/Filter new file mode 120000 index 0000000000..7ca0902711 --- /dev/null +++ b/Lang/Deja-Vu/Filter @@ -0,0 +1 @@ +../../Task/Filter/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Find-limit-of-recursion b/Lang/Deja-Vu/Find-limit-of-recursion new file mode 120000 index 0000000000..c191f7ec8e --- /dev/null +++ b/Lang/Deja-Vu/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/FizzBuzz b/Lang/Deja-Vu/FizzBuzz new file mode 120000 index 0000000000..b0a431915b --- /dev/null +++ b/Lang/Deja-Vu/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Forest-fire b/Lang/Deja-Vu/Forest-fire new file mode 120000 index 0000000000..e5ba3669ea --- /dev/null +++ b/Lang/Deja-Vu/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Function-definition b/Lang/Deja-Vu/Function-definition new file mode 120000 index 0000000000..e7701cf5da --- /dev/null +++ b/Lang/Deja-Vu/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Greatest-element-of-a-list b/Lang/Deja-Vu/Greatest-element-of-a-list new file mode 120000 index 0000000000..5e6e669588 --- /dev/null +++ b/Lang/Deja-Vu/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Guess-the-number b/Lang/Deja-Vu/Guess-the-number new file mode 120000 index 0000000000..f4f008de49 --- /dev/null +++ b/Lang/Deja-Vu/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Happy-numbers b/Lang/Deja-Vu/Happy-numbers new file mode 120000 index 0000000000..bcb24a1a41 --- /dev/null +++ b/Lang/Deja-Vu/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Hash-from-two-arrays b/Lang/Deja-Vu/Hash-from-two-arrays new file mode 120000 index 0000000000..0eb88120b3 --- /dev/null +++ b/Lang/Deja-Vu/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Hello-world-Standard-error b/Lang/Deja-Vu/Hello-world-Standard-error new file mode 120000 index 0000000000..02afc87621 --- /dev/null +++ b/Lang/Deja-Vu/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Higher-order-functions b/Lang/Deja-Vu/Higher-order-functions new file mode 120000 index 0000000000..b5c5a31091 --- /dev/null +++ b/Lang/Deja-Vu/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Input-loop b/Lang/Deja-Vu/Input-loop new file mode 120000 index 0000000000..6d1d982bdf --- /dev/null +++ b/Lang/Deja-Vu/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Integer-sequence b/Lang/Deja-Vu/Integer-sequence new file mode 120000 index 0000000000..03902815da --- /dev/null +++ b/Lang/Deja-Vu/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Interactive-programming b/Lang/Deja-Vu/Interactive-programming new file mode 120000 index 0000000000..bbd4ae7f7f --- /dev/null +++ b/Lang/Deja-Vu/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Jump-anywhere b/Lang/Deja-Vu/Jump-anywhere new file mode 120000 index 0000000000..34c156cc63 --- /dev/null +++ b/Lang/Deja-Vu/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Literals-String b/Lang/Deja-Vu/Literals-String new file mode 120000 index 0000000000..9d52cd992e --- /dev/null +++ b/Lang/Deja-Vu/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Man-or-boy-test b/Lang/Deja-Vu/Man-or-boy-test new file mode 120000 index 0000000000..602043bbab --- /dev/null +++ b/Lang/Deja-Vu/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Null-object b/Lang/Deja-Vu/Null-object new file mode 120000 index 0000000000..ab379eee6e --- /dev/null +++ b/Lang/Deja-Vu/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Palindrome-detection b/Lang/Deja-Vu/Palindrome-detection new file mode 120000 index 0000000000..d1f230e290 --- /dev/null +++ b/Lang/Deja-Vu/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Power-set b/Lang/Deja-Vu/Power-set new file mode 120000 index 0000000000..68d7f2a91a --- /dev/null +++ b/Lang/Deja-Vu/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Program-name b/Lang/Deja-Vu/Program-name new file mode 120000 index 0000000000..08be2276d3 --- /dev/null +++ b/Lang/Deja-Vu/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Queue-Definition b/Lang/Deja-Vu/Queue-Definition new file mode 120000 index 0000000000..16c126edb3 --- /dev/null +++ b/Lang/Deja-Vu/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Queue-Usage b/Lang/Deja-Vu/Queue-Usage new file mode 120000 index 0000000000..55f253ca01 --- /dev/null +++ b/Lang/Deja-Vu/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Read-entire-file b/Lang/Deja-Vu/Read-entire-file new file mode 120000 index 0000000000..f5d99ffefc --- /dev/null +++ b/Lang/Deja-Vu/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Remove-duplicate-elements b/Lang/Deja-Vu/Remove-duplicate-elements new file mode 120000 index 0000000000..65f53cb927 --- /dev/null +++ b/Lang/Deja-Vu/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Repeat-a-string b/Lang/Deja-Vu/Repeat-a-string new file mode 120000 index 0000000000..d27f62f84d --- /dev/null +++ b/Lang/Deja-Vu/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Reverse-a-string b/Lang/Deja-Vu/Reverse-a-string new file mode 120000 index 0000000000..0f394f4ebe --- /dev/null +++ b/Lang/Deja-Vu/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Rot-13 b/Lang/Deja-Vu/Rot-13 new file mode 120000 index 0000000000..c191636f4b --- /dev/null +++ b/Lang/Deja-Vu/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Run-length-encoding b/Lang/Deja-Vu/Run-length-encoding new file mode 120000 index 0000000000..eb064469c4 --- /dev/null +++ b/Lang/Deja-Vu/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Runtime-evaluation b/Lang/Deja-Vu/Runtime-evaluation new file mode 120000 index 0000000000..876b164660 --- /dev/null +++ b/Lang/Deja-Vu/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Runtime-evaluation-In-an-environment b/Lang/Deja-Vu/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..15f763a7fe --- /dev/null +++ b/Lang/Deja-Vu/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Scope-modifiers b/Lang/Deja-Vu/Scope-modifiers new file mode 120000 index 0000000000..ef54a9bda0 --- /dev/null +++ b/Lang/Deja-Vu/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Send-an-unknown-method-call b/Lang/Deja-Vu/Send-an-unknown-method-call new file mode 120000 index 0000000000..d4a5aa1c4e --- /dev/null +++ b/Lang/Deja-Vu/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Sort-an-integer-array b/Lang/Deja-Vu/Sort-an-integer-array new file mode 120000 index 0000000000..ccfdd6665c --- /dev/null +++ b/Lang/Deja-Vu/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Special-variables b/Lang/Deja-Vu/Special-variables new file mode 120000 index 0000000000..c956f2e7ff --- /dev/null +++ b/Lang/Deja-Vu/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Stack b/Lang/Deja-Vu/Stack new file mode 120000 index 0000000000..c43568841d --- /dev/null +++ b/Lang/Deja-Vu/Stack @@ -0,0 +1 @@ +../../Task/Stack/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/String-concatenation b/Lang/Deja-Vu/String-concatenation new file mode 120000 index 0000000000..fca8fbff95 --- /dev/null +++ b/Lang/Deja-Vu/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/String-length b/Lang/Deja-Vu/String-length new file mode 120000 index 0000000000..66689cd7dc --- /dev/null +++ b/Lang/Deja-Vu/String-length @@ -0,0 +1 @@ +../../Task/String-length/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Tokenize-a-string b/Lang/Deja-Vu/Tokenize-a-string new file mode 120000 index 0000000000..c637fce61b --- /dev/null +++ b/Lang/Deja-Vu/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Undefined-values b/Lang/Deja-Vu/Undefined-values new file mode 120000 index 0000000000..dc4eef3de0 --- /dev/null +++ b/Lang/Deja-Vu/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Unicode-variable-names b/Lang/Deja-Vu/Unicode-variable-names new file mode 120000 index 0000000000..70e103f7ca --- /dev/null +++ b/Lang/Deja-Vu/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Universal-Turing-machine b/Lang/Deja-Vu/Universal-Turing-machine new file mode 120000 index 0000000000..d8122ad37b --- /dev/null +++ b/Lang/Deja-Vu/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/User-input-Text b/Lang/Deja-Vu/User-input-Text new file mode 120000 index 0000000000..872cbe50de --- /dev/null +++ b/Lang/Deja-Vu/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Variadic-function b/Lang/Deja-Vu/Variadic-function new file mode 120000 index 0000000000..231d4ad2c2 --- /dev/null +++ b/Lang/Deja-Vu/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Deja-Vu \ No newline at end of file diff --git a/Lang/Delphi/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Delphi/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..2c69152874 --- /dev/null +++ b/Lang/Delphi/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Shell-sort b/Lang/Delphi/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..4335ee1aea --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Delphi \ No newline at end of file diff --git a/Lang/Eiffel/Pascals-triangle b/Lang/Eiffel/Pascals-triangle new file mode 120000 index 0000000000..780b6da670 --- /dev/null +++ b/Lang/Eiffel/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Tree-traversal b/Lang/Eiffel/Tree-traversal new file mode 120000 index 0000000000..f966a6ea30 --- /dev/null +++ b/Lang/Eiffel/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Eiffel \ No newline at end of file diff --git a/Lang/Elena/Calendar---for-real-programmers b/Lang/Elena/Calendar---for-real-programmers new file mode 120000 index 0000000000..fdf584337b --- /dev/null +++ b/Lang/Elena/Calendar---for-real-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-real-programmers/Elena \ No newline at end of file diff --git a/Lang/Elena/Combinations b/Lang/Elena/Combinations new file mode 120000 index 0000000000..79e2d61dba --- /dev/null +++ b/Lang/Elena/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Elena \ No newline at end of file diff --git a/Lang/Elixir/Look-and-say-sequence b/Lang/Elixir/Look-and-say-sequence new file mode 120000 index 0000000000..cd8fff8724 --- /dev/null +++ b/Lang/Elixir/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Quine b/Lang/Elixir/Quine new file mode 120000 index 0000000000..cef59ed62c --- /dev/null +++ b/Lang/Elixir/Quine @@ -0,0 +1 @@ +../../Task/Quine/Elixir \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Entropy b/Lang/Emacs-Lisp/Entropy new file mode 120000 index 0000000000..02da469eaf --- /dev/null +++ b/Lang/Emacs-Lisp/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Formatted-numeric-output b/Lang/Emacs-Lisp/Formatted-numeric-output new file mode 120000 index 0000000000..9bb94053f0 --- /dev/null +++ b/Lang/Emacs-Lisp/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Literals-Integer b/Lang/Emacs-Lisp/Literals-Integer new file mode 120000 index 0000000000..b1489e6464 --- /dev/null +++ b/Lang/Emacs-Lisp/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/MD4 b/Lang/Emacs-Lisp/MD4 new file mode 120000 index 0000000000..ce462073f8 --- /dev/null +++ b/Lang/Emacs-Lisp/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/MD5 b/Lang/Emacs-Lisp/MD5 new file mode 120000 index 0000000000..7b47b3c39c --- /dev/null +++ b/Lang/Emacs-Lisp/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Binary-strings b/Lang/Erlang/Binary-strings new file mode 120000 index 0000000000..e79c740fc4 --- /dev/null +++ b/Lang/Erlang/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Bitcoin-address-validation b/Lang/Erlang/Bitcoin-address-validation new file mode 120000 index 0000000000..5788b8f639 --- /dev/null +++ b/Lang/Erlang/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Bitwise-IO b/Lang/Erlang/Bitwise-IO new file mode 120000 index 0000000000..b34360702d --- /dev/null +++ b/Lang/Erlang/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Continued-fraction b/Lang/Erlang/Continued-fraction new file mode 120000 index 0000000000..8f4decc0af --- /dev/null +++ b/Lang/Erlang/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Date-manipulation b/Lang/Erlang/Date-manipulation new file mode 120000 index 0000000000..5d31516b25 --- /dev/null +++ b/Lang/Erlang/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Digital-root b/Lang/Erlang/Digital-root new file mode 120000 index 0000000000..58360aba99 --- /dev/null +++ b/Lang/Erlang/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Dinesmans-multiple-dwelling-problem b/Lang/Erlang/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..711f8236ef --- /dev/null +++ b/Lang/Erlang/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Function-frequency b/Lang/Erlang/Function-frequency new file mode 120000 index 0000000000..f98c7d7e0e --- /dev/null +++ b/Lang/Erlang/Function-frequency @@ -0,0 +1 @@ +../../Task/Function-frequency/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Knapsack-problem-Continuous b/Lang/Erlang/Knapsack-problem-Continuous new file mode 120000 index 0000000000..d163abeb92 --- /dev/null +++ b/Lang/Erlang/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Knights-tour b/Lang/Erlang/Knights-tour new file mode 120000 index 0000000000..9ee7a6ad02 --- /dev/null +++ b/Lang/Erlang/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Erlang \ No newline at end of file diff --git a/Lang/Erlang/N-queens-problem b/Lang/Erlang/N-queens-problem new file mode 120000 index 0000000000..2c66609892 --- /dev/null +++ b/Lang/Erlang/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Parallel-calculations b/Lang/Erlang/Parallel-calculations new file mode 120000 index 0000000000..32c2ef0d3b --- /dev/null +++ b/Lang/Erlang/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Pig-the-dice-game b/Lang/Erlang/Pig-the-dice-game new file mode 120000 index 0000000000..5f80615f7e --- /dev/null +++ b/Lang/Erlang/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Pig-the-dice-game-Player b/Lang/Erlang/Pig-the-dice-game-Player new file mode 120000 index 0000000000..162fbf0932 --- /dev/null +++ b/Lang/Erlang/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Playing-cards b/Lang/Erlang/Playing-cards new file mode 120000 index 0000000000..27a1ab1b9d --- /dev/null +++ b/Lang/Erlang/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rate-counter b/Lang/Erlang/Rate-counter new file mode 120000 index 0000000000..dc97a61047 --- /dev/null +++ b/Lang/Erlang/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Set-puzzle b/Lang/Erlang/Set-puzzle new file mode 120000 index 0000000000..a81b360d47 --- /dev/null +++ b/Lang/Erlang/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Solve-a-Hidato-puzzle b/Lang/Erlang/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..310b417f82 --- /dev/null +++ b/Lang/Erlang/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Special-variables b/Lang/Erlang/Special-variables new file mode 120000 index 0000000000..500481f48a --- /dev/null +++ b/Lang/Erlang/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Standard-deviation b/Lang/Erlang/Standard-deviation new file mode 120000 index 0000000000..f18386b727 --- /dev/null +++ b/Lang/Erlang/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Strip-comments-from-a-string b/Lang/Erlang/Strip-comments-from-a-string new file mode 120000 index 0000000000..ded07b0681 --- /dev/null +++ b/Lang/Erlang/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Erlang/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..7f697867d1 --- /dev/null +++ b/Lang/Erlang/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sudoku b/Lang/Erlang/Sudoku new file mode 120000 index 0000000000..4ab755b350 --- /dev/null +++ b/Lang/Erlang/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Table-creation-Postal-addresses b/Lang/Erlang/Table-creation-Postal-addresses new file mode 120000 index 0000000000..a180b7326d --- /dev/null +++ b/Lang/Erlang/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Tic-tac-toe b/Lang/Erlang/Tic-tac-toe new file mode 120000 index 0000000000..bd58d5fdcd --- /dev/null +++ b/Lang/Erlang/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Topswops b/Lang/Erlang/Topswops new file mode 120000 index 0000000000..02249ac72c --- /dev/null +++ b/Lang/Erlang/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Trabb-Pardo-Knuth-algorithm b/Lang/Erlang/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..1fdd19eb10 --- /dev/null +++ b/Lang/Erlang/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Undefined-values b/Lang/Erlang/Undefined-values new file mode 120000 index 0000000000..400642ceb0 --- /dev/null +++ b/Lang/Erlang/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Update-a-configuration-file b/Lang/Erlang/Update-a-configuration-file new file mode 120000 index 0000000000..24ec8178a9 --- /dev/null +++ b/Lang/Erlang/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/XML-Input b/Lang/Erlang/XML-Input new file mode 120000 index 0000000000..3872dacf46 --- /dev/null +++ b/Lang/Erlang/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Erlang \ No newline at end of file diff --git a/Lang/Erlang/XML-Output b/Lang/Erlang/XML-Output new file mode 120000 index 0000000000..f184a1d37d --- /dev/null +++ b/Lang/Erlang/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Erlang \ No newline at end of file diff --git a/Lang/Euler-Math-Toolbox/Bitmap-Flood-fill b/Lang/Euler-Math-Toolbox/Bitmap-Flood-fill new file mode 120000 index 0000000000..0e61144c12 --- /dev/null +++ b/Lang/Euler-Math-Toolbox/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Euler-Math-Toolbox \ No newline at end of file diff --git a/Lang/Euler-Math-Toolbox/Grayscale-image b/Lang/Euler-Math-Toolbox/Grayscale-image new file mode 120000 index 0000000000..6cc5bde33a --- /dev/null +++ b/Lang/Euler-Math-Toolbox/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Euler-Math-Toolbox \ No newline at end of file diff --git a/Lang/FBSL/00DESCRIPTION b/Lang/FBSL/00DESCRIPTION index 84c5375c3b..f5cf6886a9 100644 --- a/Lang/FBSL/00DESCRIPTION +++ b/Lang/FBSL/00DESCRIPTION @@ -1,8 +1,3 @@ {{language |site=http://www.fbsl.net/base/preview.html}} -FBSL means “Freestyle BASIC Language Script”. -Like many modern programming languages -contains flavours of [[Visual BASIC]], [[QBasic]], [[PHP]], [[Pascal]] and [[C++]]. -It is a kind of hybrid language hence the “Freestyle”. -It is especially designed for the [[win32]] platform ([[Windows 95 SR2]] to [[Windows VISTA]]). -It is compatible with, and completely functional under, [[LINUX]] [[Wine]]. \ No newline at end of file +"FBSL" stands for “Freestyle BASIC Script Language”. FBSL is a '''multi-syntax all-in-one''' high-level language (HLL) development environment. Its interpretative layer is a vastly extended superset of traditional BASIC that targets seamless integration of FBSL applications with Windows API and third-party dynamic link libraries. Its integrated Dynamic Assembler and Dynamic C JIT compiler layers enable the user to interleave BASIC code with literatim Intel-style assembly and ANSI C, respectively. Like many modern scripting languages, it contains flavours of Visual BASIC, [[QBasic]], [[C]], [[Pascal]] and [[PHP]], hence the “Freestyle”. It is especially designed for 32-bit [[Win32]] platforms and can run on Windows 95 SR2 through Windows 8.1. It is also compatible with, and completely functional under, [[Linux]] Wine and ReactOS. \ No newline at end of file diff --git a/Lang/FBSL/CRC-32 b/Lang/FBSL/CRC-32 new file mode 120000 index 0000000000..ad1178caee --- /dev/null +++ b/Lang/FBSL/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/FBSL \ No newline at end of file diff --git a/Lang/FBSL/GUI-Maximum-window-dimensions b/Lang/FBSL/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..5a3c4ad170 --- /dev/null +++ b/Lang/FBSL/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/FBSL \ No newline at end of file diff --git a/Lang/Factor/Distributed-programming b/Lang/Factor/Distributed-programming new file mode 120000 index 0000000000..52efed6414 --- /dev/null +++ b/Lang/Factor/Distributed-programming @@ -0,0 +1 @@ +../../Task/Distributed-programming/Factor \ No newline at end of file diff --git a/Lang/Forth/Digital-root b/Lang/Forth/Digital-root new file mode 120000 index 0000000000..1bda0eec02 --- /dev/null +++ b/Lang/Forth/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Forth \ No newline at end of file diff --git a/Lang/Forth/History-variables b/Lang/Forth/History-variables new file mode 120000 index 0000000000..c34c577597 --- /dev/null +++ b/Lang/Forth/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Forth \ No newline at end of file diff --git a/Lang/Forth/Josephus-problem b/Lang/Forth/Josephus-problem new file mode 120000 index 0000000000..09eb2452b4 --- /dev/null +++ b/Lang/Forth/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Forth \ No newline at end of file diff --git a/Lang/Forth/Middle-three-digits b/Lang/Forth/Middle-three-digits new file mode 120000 index 0000000000..fd52fc5430 --- /dev/null +++ b/Lang/Forth/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Forth \ No newline at end of file diff --git a/Lang/Forth/Topic-variable b/Lang/Forth/Topic-variable new file mode 120000 index 0000000000..0262b9cd12 --- /dev/null +++ b/Lang/Forth/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Forth \ No newline at end of file diff --git a/Lang/Forth/Twelve-statements b/Lang/Forth/Twelve-statements new file mode 120000 index 0000000000..2146746b09 --- /dev/null +++ b/Lang/Forth/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Forth \ No newline at end of file diff --git a/Lang/Fortran/Continued-fraction b/Lang/Fortran/Continued-fraction new file mode 120000 index 0000000000..cee9a18465 --- /dev/null +++ b/Lang/Fortran/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Terminal-control-Clear-the-screen b/Lang/Fortran/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..01213ed73a --- /dev/null +++ b/Lang/Fortran/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Fortran \ No newline at end of file diff --git a/Lang/GAP/Combinations-with-repetitions b/Lang/GAP/Combinations-with-repetitions new file mode 120000 index 0000000000..2fd82b01dc --- /dev/null +++ b/Lang/GAP/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/GAP \ No newline at end of file diff --git a/Lang/GAP/Conditional-structures b/Lang/GAP/Conditional-structures new file mode 120000 index 0000000000..eca2b81416 --- /dev/null +++ b/Lang/GAP/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/GAP \ No newline at end of file diff --git a/Lang/GAP/Even-or-odd b/Lang/GAP/Even-or-odd new file mode 120000 index 0000000000..8d836f3374 --- /dev/null +++ b/Lang/GAP/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/GAP \ No newline at end of file diff --git a/Lang/GAP/Function-definition b/Lang/GAP/Function-definition new file mode 120000 index 0000000000..a2c7188d3f --- /dev/null +++ b/Lang/GAP/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/GAP \ No newline at end of file diff --git a/Lang/GAP/Identity-matrix b/Lang/GAP/Identity-matrix new file mode 120000 index 0000000000..48e59476f7 --- /dev/null +++ b/Lang/GAP/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/GAP \ No newline at end of file diff --git a/Lang/GAP/Literals-Floating-point b/Lang/GAP/Literals-Floating-point new file mode 120000 index 0000000000..44097949ae --- /dev/null +++ b/Lang/GAP/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/GAP \ No newline at end of file diff --git a/Lang/GAP/Literals-Integer b/Lang/GAP/Literals-Integer new file mode 120000 index 0000000000..83341b62a8 --- /dev/null +++ b/Lang/GAP/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/GAP \ No newline at end of file diff --git a/Lang/GAP/Loop-over-multiple-arrays-simultaneously b/Lang/GAP/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..6d3a3ae0d2 --- /dev/null +++ b/Lang/GAP/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-Do-while b/Lang/GAP/Loops-Do-while new file mode 120000 index 0000000000..f27f7bfc65 --- /dev/null +++ b/Lang/GAP/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-Downward-for b/Lang/GAP/Loops-Downward-for new file mode 120000 index 0000000000..c63bc01c76 --- /dev/null +++ b/Lang/GAP/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-For-with-a-specified-step b/Lang/GAP/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..1a9c523bb4 --- /dev/null +++ b/Lang/GAP/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-Foreach b/Lang/GAP/Loops-Foreach new file mode 120000 index 0000000000..46f1ecdcfc --- /dev/null +++ b/Lang/GAP/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-Infinite b/Lang/GAP/Loops-Infinite new file mode 120000 index 0000000000..5b159eba7b --- /dev/null +++ b/Lang/GAP/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-N-plus-one-half b/Lang/GAP/Loops-N-plus-one-half new file mode 120000 index 0000000000..de26d0dc37 --- /dev/null +++ b/Lang/GAP/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-Nested b/Lang/GAP/Loops-Nested new file mode 120000 index 0000000000..bbf245caff --- /dev/null +++ b/Lang/GAP/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/GAP \ No newline at end of file diff --git a/Lang/GAP/Loops-While b/Lang/GAP/Loops-While new file mode 120000 index 0000000000..4099a218da --- /dev/null +++ b/Lang/GAP/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/GAP \ No newline at end of file diff --git a/Lang/GAP/Lucas-Lehmer-test b/Lang/GAP/Lucas-Lehmer-test new file mode 120000 index 0000000000..5e2b32cb81 --- /dev/null +++ b/Lang/GAP/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/GAP \ No newline at end of file diff --git a/Lang/GAP/Modular-exponentiation b/Lang/GAP/Modular-exponentiation new file mode 120000 index 0000000000..5e2f2df9c2 --- /dev/null +++ b/Lang/GAP/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/GAP \ No newline at end of file diff --git a/Lang/GAP/Multifactorial b/Lang/GAP/Multifactorial new file mode 120000 index 0000000000..676d3cf76e --- /dev/null +++ b/Lang/GAP/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/GAP \ No newline at end of file diff --git a/Lang/GAP/N-queens-problem b/Lang/GAP/N-queens-problem new file mode 120000 index 0000000000..283b7e2f1c --- /dev/null +++ b/Lang/GAP/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/GAP \ No newline at end of file diff --git a/Lang/GAP/Pick-random-element b/Lang/GAP/Pick-random-element new file mode 120000 index 0000000000..b5fca2fffa --- /dev/null +++ b/Lang/GAP/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/GAP \ No newline at end of file diff --git a/Lang/GAP/String-case b/Lang/GAP/String-case new file mode 120000 index 0000000000..97c9aa4502 --- /dev/null +++ b/Lang/GAP/String-case @@ -0,0 +1 @@ +../../Task/String-case/GAP \ No newline at end of file diff --git a/Lang/GML/Fibonacci-sequence b/Lang/GML/Fibonacci-sequence new file mode 120000 index 0000000000..65ec21cc0e --- /dev/null +++ b/Lang/GML/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/GML \ No newline at end of file diff --git a/Lang/GML/HTTP b/Lang/GML/HTTP new file mode 120000 index 0000000000..b16c62f44d --- /dev/null +++ b/Lang/GML/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/GML \ No newline at end of file diff --git a/Lang/GML/Hello-world-Graphical b/Lang/GML/Hello-world-Graphical new file mode 120000 index 0000000000..3d47794198 --- /dev/null +++ b/Lang/GML/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/GML \ No newline at end of file diff --git a/Lang/Go/Matrix-arithmetic b/Lang/Go/Matrix-arithmetic new file mode 120000 index 0000000000..84a38a2fec --- /dev/null +++ b/Lang/Go/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Go \ No newline at end of file diff --git a/Lang/Go/Permutations-by-swapping b/Lang/Go/Permutations-by-swapping new file mode 120000 index 0000000000..23ccc4bb5a --- /dev/null +++ b/Lang/Go/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Go \ No newline at end of file diff --git a/Lang/Go/Set-puzzle b/Lang/Go/Set-puzzle new file mode 120000 index 0000000000..56707b2682 --- /dev/null +++ b/Lang/Go/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Vampire-number b/Lang/Go/Vampire-number new file mode 120000 index 0000000000..76959521e0 --- /dev/null +++ b/Lang/Go/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Go \ No newline at end of file diff --git a/Lang/Go/XML-XPath b/Lang/Go/XML-XPath new file mode 120000 index 0000000000..289ddf9507 --- /dev/null +++ b/Lang/Go/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Go \ No newline at end of file diff --git a/Lang/Groovy/Averages-Mean-time-of-day b/Lang/Groovy/Averages-Mean-time-of-day new file mode 120000 index 0000000000..dfa05248ab --- /dev/null +++ b/Lang/Groovy/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Balanced-ternary b/Lang/Groovy/Balanced-ternary new file mode 120000 index 0000000000..2fefaac13a --- /dev/null +++ b/Lang/Groovy/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Groovy \ No newline at end of file diff --git a/Lang/Groovy/CRC-32 b/Lang/Groovy/CRC-32 new file mode 120000 index 0000000000..1fe14a78a8 --- /dev/null +++ b/Lang/Groovy/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Groovy \ No newline at end of file diff --git a/Lang/Groovy/DNS-query b/Lang/Groovy/DNS-query new file mode 120000 index 0000000000..5800006928 --- /dev/null +++ b/Lang/Groovy/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Dining-philosophers b/Lang/Groovy/Dining-philosophers new file mode 120000 index 0000000000..2433f71c65 --- /dev/null +++ b/Lang/Groovy/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Entropy b/Lang/Groovy/Entropy new file mode 120000 index 0000000000..5cb83eee7e --- /dev/null +++ b/Lang/Groovy/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Execute-a-system-command b/Lang/Groovy/Execute-a-system-command new file mode 120000 index 0000000000..aab9c297e8 --- /dev/null +++ b/Lang/Groovy/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Five-weekends b/Lang/Groovy/Five-weekends new file mode 120000 index 0000000000..c33ca7ebc8 --- /dev/null +++ b/Lang/Groovy/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Jensens-Device b/Lang/Groovy/Jensens-Device new file mode 120000 index 0000000000..c3bd66b29b --- /dev/null +++ b/Lang/Groovy/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Josephus-problem b/Lang/Groovy/Josephus-problem new file mode 120000 index 0000000000..d169312f89 --- /dev/null +++ b/Lang/Groovy/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Last-Friday-of-each-month b/Lang/Groovy/Last-Friday-of-each-month new file mode 120000 index 0000000000..cd731472c8 --- /dev/null +++ b/Lang/Groovy/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Man-or-boy-test b/Lang/Groovy/Man-or-boy-test new file mode 120000 index 0000000000..220c6790b2 --- /dev/null +++ b/Lang/Groovy/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Metered-concurrency b/Lang/Groovy/Metered-concurrency new file mode 120000 index 0000000000..b6b2663d3f --- /dev/null +++ b/Lang/Groovy/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Multiple-distinct-objects b/Lang/Groovy/Multiple-distinct-objects new file mode 120000 index 0000000000..ceaf5ee4bf --- /dev/null +++ b/Lang/Groovy/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Polymorphism b/Lang/Groovy/Polymorphism new file mode 120000 index 0000000000..b94c7fb626 --- /dev/null +++ b/Lang/Groovy/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Priority-queue b/Lang/Groovy/Priority-queue new file mode 120000 index 0000000000..bafe838925 --- /dev/null +++ b/Lang/Groovy/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Read-a-configuration-file b/Lang/Groovy/Read-a-configuration-file new file mode 120000 index 0000000000..aaf5303c17 --- /dev/null +++ b/Lang/Groovy/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Rosetta-Code-Rank-languages-by-popularity b/Lang/Groovy/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..53bac431a5 --- /dev/null +++ b/Lang/Groovy/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Self-referential-sequence b/Lang/Groovy/Self-referential-sequence new file mode 120000 index 0000000000..2d96336495 --- /dev/null +++ b/Lang/Groovy/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Send-an-unknown-method-call b/Lang/Groovy/Send-an-unknown-method-call new file mode 120000 index 0000000000..db0b6687ef --- /dev/null +++ b/Lang/Groovy/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Speech-synthesis b/Lang/Groovy/Speech-synthesis new file mode 120000 index 0000000000..0932f99db4 --- /dev/null +++ b/Lang/Groovy/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Strip-comments-from-a-string b/Lang/Groovy/Strip-comments-from-a-string new file mode 120000 index 0000000000..b58cbe3fe3 --- /dev/null +++ b/Lang/Groovy/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Word-wrap b/Lang/Groovy/Word-wrap new file mode 120000 index 0000000000..82ba558f9f --- /dev/null +++ b/Lang/Groovy/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Write-language-name-in-3D-ASCII b/Lang/Groovy/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..9a2c60d4e8 --- /dev/null +++ b/Lang/Groovy/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Groovy \ No newline at end of file diff --git a/Lang/Haskell/I-before-E-except-after-C b/Lang/Haskell/I-before-E-except-after-C new file mode 120000 index 0000000000..9b43f82147 --- /dev/null +++ b/Lang/Haskell/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Parsing-RPN-to-infix-conversion b/Lang/Haskell/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..28ae41457b --- /dev/null +++ b/Lang/Haskell/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Solve-a-Hidato-puzzle b/Lang/Haskell/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..f1703a370f --- /dev/null +++ b/Lang/Haskell/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Table-creation-Postal-addresses b/Lang/Haskell/Table-creation-Postal-addresses new file mode 120000 index 0000000000..a197c19486 --- /dev/null +++ b/Lang/Haskell/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Voronoi-diagram b/Lang/Haskell/Voronoi-diagram new file mode 120000 index 0000000000..0ae9779f79 --- /dev/null +++ b/Lang/Haskell/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Haskell \ No newline at end of file diff --git a/Lang/Icon/Factors-of-a-Mersenne-number b/Lang/Icon/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..8eb9d3feb9 --- /dev/null +++ b/Lang/Icon/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Icon \ No newline at end of file diff --git a/Lang/Icon/Host-introspection b/Lang/Icon/Host-introspection new file mode 120000 index 0000000000..8d268f2907 --- /dev/null +++ b/Lang/Icon/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Icon \ No newline at end of file diff --git a/Lang/Icon/Parametric-polymorphism b/Lang/Icon/Parametric-polymorphism new file mode 120000 index 0000000000..cd837fe312 --- /dev/null +++ b/Lang/Icon/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Icon \ No newline at end of file diff --git a/Lang/Icon/Random-number-generator--device- b/Lang/Icon/Random-number-generator--device- new file mode 120000 index 0000000000..fd444dacdf --- /dev/null +++ b/Lang/Icon/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Icon \ No newline at end of file diff --git a/Lang/Icon/Read-a-configuration-file b/Lang/Icon/Read-a-configuration-file new file mode 120000 index 0000000000..05103c10c4 --- /dev/null +++ b/Lang/Icon/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Icon \ No newline at end of file diff --git a/Lang/Icon/Roots-of-a-quadratic-function b/Lang/Icon/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..6a760f88ad --- /dev/null +++ b/Lang/Icon/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Icon \ No newline at end of file diff --git a/Lang/Icon/Visualize-a-tree b/Lang/Icon/Visualize-a-tree new file mode 120000 index 0000000000..4040c04436 --- /dev/null +++ b/Lang/Icon/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Icon \ No newline at end of file diff --git a/Lang/Io/Monty-Hall-problem b/Lang/Io/Monty-Hall-problem new file mode 120000 index 0000000000..83076f0563 --- /dev/null +++ b/Lang/Io/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Io \ No newline at end of file diff --git a/Lang/Java/00DESCRIPTION b/Lang/Java/00DESCRIPTION index e04c0dcdf7..8db85901b9 100644 --- a/Lang/Java/00DESCRIPTION +++ b/Lang/Java/00DESCRIPTION @@ -18,7 +18,7 @@ {{language programming paradigm|reflective}}[[runs on vm::java virtual machine| ]] The '''Java''' programming language, developed by [[Sun Microsystems]], is a language aimed at allowing "high-performance", virtual application development. -Java source files (.java files) are typically [[Compiler|compiled]] to an intermediate [[bytecode]] language (.class files) and executed by a [[Java Virtual Machine]]. Most modern JVMs further compile the bytecode into your processor's native machine code during execution. This native code translation is done via a [[Just-In-Time|JIT]] compiler that is built in to the JVM. Some Java compilers (such as [[GCJ]]) can compile Java code to native machine code ahead-of-time rather than just-in-time. +Java source files (.java files) are typically [[Compiler|compiled]] to an intermediate [[bytecode]] (all platform) executable (.class files) and executed by a [[Java Virtual Machine]]. Most modern JVMs further compile the bytecode into your processor's native machine code during execution. This native code translation is mostly done via a [[Just-In-Time|JIT]] compiler that is built in the JVM. Some Java compilers (such as [[GCJ]]) can compile Java code to native machine code ahead-of-time rather than just-in-time. The primary benefits of Java are: * Cross-[[platform]] (Write Once, Run Anywhere (if all of the libraries are ported)) diff --git a/Lang/Java/Galton-box-animation b/Lang/Java/Galton-box-animation new file mode 120000 index 0000000000..ee1311c64f --- /dev/null +++ b/Lang/Java/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Java \ No newline at end of file diff --git a/Lang/JavaScript/Least-common-multiple b/Lang/JavaScript/Least-common-multiple new file mode 120000 index 0000000000..9c6ff4e3b5 --- /dev/null +++ b/Lang/JavaScript/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/JavaScript \ No newline at end of file diff --git a/Lang/Julia/00DESCRIPTION b/Lang/Julia/00DESCRIPTION index 359ef23da9..dbe90a1fb2 100644 --- a/Lang/Julia/00DESCRIPTION +++ b/Lang/Julia/00DESCRIPTION @@ -3,5 +3,5 @@ Julia is a high-level, high-performance dynamic programming language for technical computing, with syntax silimar to [[MATLAB]]'s. It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. -It is a functional language that uses multiple dispatch as it's primary paradigm. +It is a functional language that uses multiple dispatch as its primary paradigm. It has first-class types and homoiconic macros. \ No newline at end of file diff --git a/Lang/Julia/Address-of-a-variable b/Lang/Julia/Address-of-a-variable new file mode 120000 index 0000000000..ec29880eb9 --- /dev/null +++ b/Lang/Julia/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Julia \ No newline at end of file diff --git a/Lang/Julia/Align-columns b/Lang/Julia/Align-columns new file mode 120000 index 0000000000..38224c9ef5 --- /dev/null +++ b/Lang/Julia/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Julia \ No newline at end of file diff --git a/Lang/Julia/Anonymous-recursion b/Lang/Julia/Anonymous-recursion new file mode 120000 index 0000000000..f6aa873ec8 --- /dev/null +++ b/Lang/Julia/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Julia \ No newline at end of file diff --git a/Lang/Julia/Arithmetic-Complex b/Lang/Julia/Arithmetic-Complex new file mode 120000 index 0000000000..c55969ac91 --- /dev/null +++ b/Lang/Julia/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Julia \ No newline at end of file diff --git a/Lang/Julia/Associative-array-Iteration b/Lang/Julia/Associative-array-Iteration new file mode 120000 index 0000000000..309febba4c --- /dev/null +++ b/Lang/Julia/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Julia \ No newline at end of file diff --git a/Lang/Julia/Averages-Mean-angle b/Lang/Julia/Averages-Mean-angle new file mode 120000 index 0000000000..a85c0b040c --- /dev/null +++ b/Lang/Julia/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Julia \ No newline at end of file diff --git a/Lang/Julia/Averages-Root-mean-square b/Lang/Julia/Averages-Root-mean-square new file mode 120000 index 0000000000..f64f512533 --- /dev/null +++ b/Lang/Julia/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Julia \ No newline at end of file diff --git a/Lang/Julia/Binary-search b/Lang/Julia/Binary-search new file mode 120000 index 0000000000..1fe715746e --- /dev/null +++ b/Lang/Julia/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Julia \ No newline at end of file diff --git a/Lang/Julia/Caesar-cipher b/Lang/Julia/Caesar-cipher new file mode 120000 index 0000000000..0039376aa6 --- /dev/null +++ b/Lang/Julia/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Julia \ No newline at end of file diff --git a/Lang/Julia/Call-a-foreign-language-function b/Lang/Julia/Call-a-foreign-language-function new file mode 120000 index 0000000000..0130a0aec5 --- /dev/null +++ b/Lang/Julia/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Character-codes b/Lang/Julia/Character-codes new file mode 120000 index 0000000000..2d43f81f6f --- /dev/null +++ b/Lang/Julia/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Julia \ No newline at end of file diff --git a/Lang/Julia/Check-that-file-exists b/Lang/Julia/Check-that-file-exists new file mode 120000 index 0000000000..92628c8ccc --- /dev/null +++ b/Lang/Julia/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Julia \ No newline at end of file diff --git a/Lang/Julia/Compile-time-calculation b/Lang/Julia/Compile-time-calculation new file mode 120000 index 0000000000..a55fae4b93 --- /dev/null +++ b/Lang/Julia/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Julia \ No newline at end of file diff --git a/Lang/Julia/Environment-variables b/Lang/Julia/Environment-variables new file mode 120000 index 0000000000..bccc9eeb98 --- /dev/null +++ b/Lang/Julia/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Julia \ No newline at end of file diff --git a/Lang/Julia/Even-or-odd b/Lang/Julia/Even-or-odd new file mode 120000 index 0000000000..18586cd59d --- /dev/null +++ b/Lang/Julia/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Julia \ No newline at end of file diff --git a/Lang/Julia/Factors-of-an-integer b/Lang/Julia/Factors-of-an-integer new file mode 120000 index 0000000000..6481b8b614 --- /dev/null +++ b/Lang/Julia/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Julia \ No newline at end of file diff --git a/Lang/Julia/Fast-Fourier-transform b/Lang/Julia/Fast-Fourier-transform new file mode 120000 index 0000000000..b98759f350 --- /dev/null +++ b/Lang/Julia/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Julia \ No newline at end of file diff --git a/Lang/Julia/File-size b/Lang/Julia/File-size new file mode 120000 index 0000000000..9932cc4ebd --- /dev/null +++ b/Lang/Julia/File-size @@ -0,0 +1 @@ +../../Task/File-size/Julia \ No newline at end of file diff --git a/Lang/Julia/Forward-difference b/Lang/Julia/Forward-difference new file mode 120000 index 0000000000..bf19c627b1 --- /dev/null +++ b/Lang/Julia/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Julia \ No newline at end of file diff --git a/Lang/Julia/Function-composition b/Lang/Julia/Function-composition new file mode 120000 index 0000000000..e88c68da17 --- /dev/null +++ b/Lang/Julia/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Julia \ No newline at end of file diff --git a/Lang/Julia/Gamma-function b/Lang/Julia/Gamma-function new file mode 120000 index 0000000000..c90d969bb9 --- /dev/null +++ b/Lang/Julia/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Generic-swap b/Lang/Julia/Generic-swap new file mode 120000 index 0000000000..a2950ad362 --- /dev/null +++ b/Lang/Julia/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Julia \ No newline at end of file diff --git a/Lang/Julia/Globally-replace-text-in-several-files b/Lang/Julia/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..38f2d9d9c5 --- /dev/null +++ b/Lang/Julia/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Julia \ No newline at end of file diff --git a/Lang/Julia/Gray-code b/Lang/Julia/Gray-code new file mode 120000 index 0000000000..fd2dc475cd --- /dev/null +++ b/Lang/Julia/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Julia \ No newline at end of file diff --git a/Lang/Julia/Hash-from-two-arrays b/Lang/Julia/Hash-from-two-arrays new file mode 120000 index 0000000000..35af70499b --- /dev/null +++ b/Lang/Julia/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Julia \ No newline at end of file diff --git a/Lang/Julia/Hello-world-Newline-omission b/Lang/Julia/Hello-world-Newline-omission new file mode 120000 index 0000000000..409a9f0de1 --- /dev/null +++ b/Lang/Julia/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Julia \ No newline at end of file diff --git a/Lang/Julia/Hello-world-Standard-error b/Lang/Julia/Hello-world-Standard-error new file mode 120000 index 0000000000..35a61eaa85 --- /dev/null +++ b/Lang/Julia/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Julia \ No newline at end of file diff --git a/Lang/Julia/Here-document b/Lang/Julia/Here-document new file mode 120000 index 0000000000..dfaa541475 --- /dev/null +++ b/Lang/Julia/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Julia \ No newline at end of file diff --git a/Lang/Julia/Hofstadter-Q-sequence b/Lang/Julia/Hofstadter-Q-sequence new file mode 120000 index 0000000000..466d0d26cf --- /dev/null +++ b/Lang/Julia/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Julia \ No newline at end of file diff --git a/Lang/Julia/Include-a-file b/Lang/Julia/Include-a-file new file mode 120000 index 0000000000..c1329cb9eb --- /dev/null +++ b/Lang/Julia/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Inheritance-Single b/Lang/Julia/Inheritance-Single new file mode 120000 index 0000000000..189459d9a3 --- /dev/null +++ b/Lang/Julia/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Julia \ No newline at end of file diff --git a/Lang/Julia/Integer-sequence b/Lang/Julia/Integer-sequence new file mode 120000 index 0000000000..de89eaf363 --- /dev/null +++ b/Lang/Julia/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Julia \ No newline at end of file diff --git a/Lang/Julia/JSON b/Lang/Julia/JSON new file mode 120000 index 0000000000..fa40759156 --- /dev/null +++ b/Lang/Julia/JSON @@ -0,0 +1 @@ +../../Task/JSON/Julia \ No newline at end of file diff --git a/Lang/Julia/Least-common-multiple b/Lang/Julia/Least-common-multiple new file mode 120000 index 0000000000..7e1d39377e --- /dev/null +++ b/Lang/Julia/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Downward-for b/Lang/Julia/Loops-Downward-for new file mode 120000 index 0000000000..fbdcd857fc --- /dev/null +++ b/Lang/Julia/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-For-with-a-specified-step b/Lang/Julia/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..67ae8e3114 --- /dev/null +++ b/Lang/Julia/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Foreach b/Lang/Julia/Loops-Foreach new file mode 120000 index 0000000000..540c360520 --- /dev/null +++ b/Lang/Julia/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Julia \ No newline at end of file diff --git a/Lang/Julia/Map-range b/Lang/Julia/Map-range new file mode 120000 index 0000000000..7f8a028094 --- /dev/null +++ b/Lang/Julia/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Julia \ No newline at end of file diff --git a/Lang/Julia/Matrix-arithmetic b/Lang/Julia/Matrix-arithmetic new file mode 120000 index 0000000000..c71e12d90b --- /dev/null +++ b/Lang/Julia/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Julia \ No newline at end of file diff --git a/Lang/Julia/Miller-Rabin-primality-test b/Lang/Julia/Miller-Rabin-primality-test new file mode 120000 index 0000000000..1a7339a0d3 --- /dev/null +++ b/Lang/Julia/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Julia \ No newline at end of file diff --git a/Lang/Julia/Modular-exponentiation b/Lang/Julia/Modular-exponentiation new file mode 120000 index 0000000000..d3d2fd642a --- /dev/null +++ b/Lang/Julia/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Julia \ No newline at end of file diff --git a/Lang/Julia/Modular-inverse b/Lang/Julia/Modular-inverse new file mode 120000 index 0000000000..5805559a8c --- /dev/null +++ b/Lang/Julia/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Julia \ No newline at end of file diff --git a/Lang/Julia/Monte-Carlo-methods b/Lang/Julia/Monte-Carlo-methods new file mode 120000 index 0000000000..a235c94ac5 --- /dev/null +++ b/Lang/Julia/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Julia \ No newline at end of file diff --git a/Lang/Julia/Multiple-regression b/Lang/Julia/Multiple-regression new file mode 120000 index 0000000000..f785d03800 --- /dev/null +++ b/Lang/Julia/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Julia \ No newline at end of file diff --git a/Lang/Julia/Multiplicative-order b/Lang/Julia/Multiplicative-order new file mode 120000 index 0000000000..e276768d13 --- /dev/null +++ b/Lang/Julia/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Julia \ No newline at end of file diff --git a/Lang/Julia/Mutual-recursion b/Lang/Julia/Mutual-recursion new file mode 120000 index 0000000000..83fcdb1a23 --- /dev/null +++ b/Lang/Julia/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Julia \ No newline at end of file diff --git a/Lang/Julia/Nth-root b/Lang/Julia/Nth-root new file mode 120000 index 0000000000..a45d55009d --- /dev/null +++ b/Lang/Julia/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Julia \ No newline at end of file diff --git a/Lang/Julia/Numerical-integration b/Lang/Julia/Numerical-integration new file mode 120000 index 0000000000..e9dc897cce --- /dev/null +++ b/Lang/Julia/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Julia \ No newline at end of file diff --git a/Lang/Julia/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Julia/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..4918d9b3ea --- /dev/null +++ b/Lang/Julia/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia \ No newline at end of file diff --git a/Lang/Julia/Optional-parameters b/Lang/Julia/Optional-parameters new file mode 120000 index 0000000000..1cbdb3025e --- /dev/null +++ b/Lang/Julia/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Julia \ No newline at end of file diff --git a/Lang/Julia/Pi b/Lang/Julia/Pi new file mode 120000 index 0000000000..7c4f9867e0 --- /dev/null +++ b/Lang/Julia/Pi @@ -0,0 +1 @@ +../../Task/Pi/Julia \ No newline at end of file diff --git a/Lang/Julia/Pick-random-element b/Lang/Julia/Pick-random-element new file mode 120000 index 0000000000..78593dc2c9 --- /dev/null +++ b/Lang/Julia/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Julia \ No newline at end of file diff --git a/Lang/Julia/Polymorphism b/Lang/Julia/Polymorphism new file mode 120000 index 0000000000..28f8dde4d1 --- /dev/null +++ b/Lang/Julia/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Julia \ No newline at end of file diff --git a/Lang/Julia/Polynomial-regression b/Lang/Julia/Polynomial-regression new file mode 120000 index 0000000000..c4d2e0c820 --- /dev/null +++ b/Lang/Julia/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Julia \ No newline at end of file diff --git a/Lang/Julia/Power-set b/Lang/Julia/Power-set new file mode 120000 index 0000000000..7b65317c9a --- /dev/null +++ b/Lang/Julia/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Julia \ No newline at end of file diff --git a/Lang/Julia/Prime-decomposition b/Lang/Julia/Prime-decomposition new file mode 120000 index 0000000000..8a79c61f18 --- /dev/null +++ b/Lang/Julia/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Julia \ No newline at end of file diff --git a/Lang/Julia/QR-decomposition b/Lang/Julia/QR-decomposition new file mode 120000 index 0000000000..d7c79d58bf --- /dev/null +++ b/Lang/Julia/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Julia \ No newline at end of file diff --git a/Lang/Julia/Quaternion-type b/Lang/Julia/Quaternion-type new file mode 120000 index 0000000000..8a462d73ba --- /dev/null +++ b/Lang/Julia/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Julia \ No newline at end of file diff --git a/Lang/Julia/Random-numbers b/Lang/Julia/Random-numbers new file mode 120000 index 0000000000..7c7cf92db6 --- /dev/null +++ b/Lang/Julia/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/Real-constants-and-functions b/Lang/Julia/Real-constants-and-functions new file mode 120000 index 0000000000..090de9bbcf --- /dev/null +++ b/Lang/Julia/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Julia \ No newline at end of file diff --git a/Lang/Julia/Rename-a-file b/Lang/Julia/Rename-a-file new file mode 120000 index 0000000000..524edae806 --- /dev/null +++ b/Lang/Julia/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Resistor-mesh b/Lang/Julia/Resistor-mesh new file mode 120000 index 0000000000..c1f4b26725 --- /dev/null +++ b/Lang/Julia/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Julia \ No newline at end of file diff --git a/Lang/Julia/Roots-of-unity b/Lang/Julia/Roots-of-unity new file mode 120000 index 0000000000..b54b2059ca --- /dev/null +++ b/Lang/Julia/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Julia \ No newline at end of file diff --git a/Lang/Julia/Search-a-list b/Lang/Julia/Search-a-list new file mode 120000 index 0000000000..5d6cb1bfbc --- /dev/null +++ b/Lang/Julia/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Julia \ No newline at end of file diff --git a/Lang/Julia/Singly-linked-list-Element-definition b/Lang/Julia/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..b66eea75a5 --- /dev/null +++ b/Lang/Julia/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Julia \ No newline at end of file diff --git a/Lang/Julia/Stack b/Lang/Julia/Stack new file mode 120000 index 0000000000..749c695caa --- /dev/null +++ b/Lang/Julia/Stack @@ -0,0 +1 @@ +../../Task/Stack/Julia \ No newline at end of file diff --git a/Lang/Julia/String-case b/Lang/Julia/String-case new file mode 120000 index 0000000000..bea1445a38 --- /dev/null +++ b/Lang/Julia/String-case @@ -0,0 +1 @@ +../../Task/String-case/Julia \ No newline at end of file diff --git a/Lang/Julia/String-concatenation b/Lang/Julia/String-concatenation new file mode 120000 index 0000000000..bc48dfe824 --- /dev/null +++ b/Lang/Julia/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Julia \ No newline at end of file diff --git a/Lang/Julia/String-interpolation--included- b/Lang/Julia/String-interpolation--included- new file mode 120000 index 0000000000..86aab3ded6 --- /dev/null +++ b/Lang/Julia/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Julia \ No newline at end of file diff --git a/Lang/Julia/String-length b/Lang/Julia/String-length new file mode 120000 index 0000000000..99b93ac893 --- /dev/null +++ b/Lang/Julia/String-length @@ -0,0 +1 @@ +../../Task/String-length/Julia \ No newline at end of file diff --git a/Lang/Julia/Sum-digits-of-an-integer b/Lang/Julia/Sum-digits-of-an-integer new file mode 120000 index 0000000000..b6b5daad2e --- /dev/null +++ b/Lang/Julia/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Julia \ No newline at end of file diff --git a/Lang/Julia/Tree-traversal b/Lang/Julia/Tree-traversal new file mode 120000 index 0000000000..694af6d989 --- /dev/null +++ b/Lang/Julia/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Julia \ No newline at end of file diff --git a/Lang/LLVM/Hello-world-Text b/Lang/LLVM/Hello-world-Text new file mode 120000 index 0000000000..054b0ff949 --- /dev/null +++ b/Lang/LLVM/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/LLVM \ No newline at end of file diff --git a/Lang/LabVIEW/Include-a-file b/Lang/LabVIEW/Include-a-file new file mode 120000 index 0000000000..a0115e8161 --- /dev/null +++ b/Lang/LabVIEW/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/LabVIEW \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Arithmetic-evaluation b/Lang/Liberty-BASIC/Arithmetic-evaluation new file mode 120000 index 0000000000..4e4b91830c --- /dev/null +++ b/Lang/Liberty-BASIC/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Assertions b/Lang/Liberty-BASIC/Assertions new file mode 120000 index 0000000000..5b4ccdc8fb --- /dev/null +++ b/Lang/Liberty-BASIC/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Average-loop-length b/Lang/Liberty-BASIC/Average-loop-length new file mode 120000 index 0000000000..7d34ea69d9 --- /dev/null +++ b/Lang/Liberty-BASIC/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Averages-Mean-time-of-day b/Lang/Liberty-BASIC/Averages-Mean-time-of-day new file mode 120000 index 0000000000..629956a638 --- /dev/null +++ b/Lang/Liberty-BASIC/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Averages-Mode b/Lang/Liberty-BASIC/Averages-Mode new file mode 120000 index 0000000000..584faaf159 --- /dev/null +++ b/Lang/Liberty-BASIC/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Balanced-ternary b/Lang/Liberty-BASIC/Balanced-ternary new file mode 120000 index 0000000000..8aa8f27721 --- /dev/null +++ b/Lang/Liberty-BASIC/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Call-a-function b/Lang/Liberty-BASIC/Call-a-function new file mode 120000 index 0000000000..c05c543d40 --- /dev/null +++ b/Lang/Liberty-BASIC/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/N-queens-problem b/Lang/Liberty-BASIC/N-queens-problem new file mode 120000 index 0000000000..905931ae8d --- /dev/null +++ b/Lang/Liberty-BASIC/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Parsing-RPN-calculator-algorithm b/Lang/Liberty-BASIC/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..69c2bf874e --- /dev/null +++ b/Lang/Liberty-BASIC/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Parsing-Shunting-yard-algorithm b/Lang/Liberty-BASIC/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..ec59f3d62d --- /dev/null +++ b/Lang/Liberty-BASIC/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Permutations b/Lang/Liberty-BASIC/Permutations new file mode 120000 index 0000000000..fd954e1786 --- /dev/null +++ b/Lang/Liberty-BASIC/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Pinstripe-Display b/Lang/Liberty-BASIC/Pinstripe-Display new file mode 120000 index 0000000000..ec3827e355 --- /dev/null +++ b/Lang/Liberty-BASIC/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Limbo/Executable-library b/Lang/Limbo/Executable-library new file mode 120000 index 0000000000..a5776d583e --- /dev/null +++ b/Lang/Limbo/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Execute-Brain---- b/Lang/Limbo/Execute-Brain---- new file mode 120000 index 0000000000..65616d0500 --- /dev/null +++ b/Lang/Limbo/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Execute-a-system-command b/Lang/Limbo/Execute-a-system-command new file mode 120000 index 0000000000..f56e9ba002 --- /dev/null +++ b/Lang/Limbo/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Greatest-common-divisor b/Lang/Limbo/Greatest-common-divisor new file mode 120000 index 0000000000..80aadf3f60 --- /dev/null +++ b/Lang/Limbo/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Hailstone-sequence b/Lang/Limbo/Hailstone-sequence new file mode 120000 index 0000000000..a87c49a6d8 --- /dev/null +++ b/Lang/Limbo/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Hello-world-Newline-omission b/Lang/Limbo/Hello-world-Newline-omission new file mode 120000 index 0000000000..b7cf27fda3 --- /dev/null +++ b/Lang/Limbo/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Hostname b/Lang/Limbo/Hostname new file mode 120000 index 0000000000..c178c93836 --- /dev/null +++ b/Lang/Limbo/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Integer-sequence b/Lang/Limbo/Integer-sequence new file mode 120000 index 0000000000..d26711c37b --- /dev/null +++ b/Lang/Limbo/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Rot-13 b/Lang/Limbo/Rot-13 new file mode 120000 index 0000000000..2b476db3b0 --- /dev/null +++ b/Lang/Limbo/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Show-the-epoch b/Lang/Limbo/Show-the-epoch new file mode 120000 index 0000000000..fee6a180fc --- /dev/null +++ b/Lang/Limbo/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Limbo \ No newline at end of file diff --git a/Lang/Lua/Deal-cards-for-FreeCell b/Lang/Lua/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..954ef19414 --- /dev/null +++ b/Lang/Lua/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Lua \ No newline at end of file diff --git a/Lang/Lua/Josephus-problem b/Lang/Lua/Josephus-problem new file mode 120000 index 0000000000..6d7a6283aa --- /dev/null +++ b/Lang/Lua/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Lua \ No newline at end of file diff --git a/Lang/Lua/Pi b/Lang/Lua/Pi new file mode 120000 index 0000000000..0ccf99df0d --- /dev/null +++ b/Lang/Lua/Pi @@ -0,0 +1 @@ +../../Task/Pi/Lua \ No newline at end of file diff --git a/Lang/MATLAB/URL-decoding b/Lang/MATLAB/URL-decoding new file mode 120000 index 0000000000..8c9708493e --- /dev/null +++ b/Lang/MATLAB/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/MATLAB \ No newline at end of file diff --git a/Lang/Make/Program-name b/Lang/Make/Program-name new file mode 120000 index 0000000000..3c86287e08 --- /dev/null +++ b/Lang/Make/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Make \ No newline at end of file diff --git a/Lang/Maxima/Primality-by-trial-division b/Lang/Maxima/Primality-by-trial-division new file mode 120000 index 0000000000..5939bd82eb --- /dev/null +++ b/Lang/Maxima/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Van-der-Corput-sequence b/Lang/Maxima/Van-der-Corput-sequence new file mode 120000 index 0000000000..17dc6f906a --- /dev/null +++ b/Lang/Maxima/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Maxima \ No newline at end of file diff --git a/Lang/Mercury/Call-a-foreign-language-function b/Lang/Mercury/Call-a-foreign-language-function new file mode 120000 index 0000000000..c6afd194af --- /dev/null +++ b/Lang/Mercury/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Mercury \ No newline at end of file diff --git a/Lang/Mercury/List-comprehensions b/Lang/Mercury/List-comprehensions new file mode 120000 index 0000000000..a8b2e1c19f --- /dev/null +++ b/Lang/Mercury/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Priority-queue b/Lang/Mercury/Priority-queue new file mode 120000 index 0000000000..cc491f369e --- /dev/null +++ b/Lang/Mercury/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Mercury \ No newline at end of file diff --git a/Lang/Modula-2/00DESCRIPTION b/Lang/Modula-2/00DESCRIPTION index deca3c5fbc..854aa29a1a 100644 --- a/Lang/Modula-2/00DESCRIPTION +++ b/Lang/Modula-2/00DESCRIPTION @@ -8,10 +8,10 @@ Modula-2 was designed by Niklaus Wirth at ETH Zurich as a systems implementation [http://faq.modula2.net Modula-2 FAQ] ==Modula-2 Compilers== -[http://www.modula2.net/resources/compilers.shtml List of Modula-2 Compilers] +[http://freepages.modula2.org/compi.html List of Modula-2 Compilers] ==Modula-2 Books & Tutorials== -[http://www.modula2.net/resources/books.shtml List of Modula-2 Books & Tutorials] +[http://freepages.modula2.org/tutor.html List of Modula-2 Books & Tutorials] [http://www.modula2.org/books/index.php and] ==Modula-2 Grammars== * [http://modula2.net/resources/m2pim4.g PIM Modula-2, original version] diff --git a/Lang/Neko/00DESCRIPTION b/Lang/Neko/00DESCRIPTION index 6f806eb1aa..68f4febe69 100644 --- a/Lang/Neko/00DESCRIPTION +++ b/Lang/Neko/00DESCRIPTION @@ -1,3 +1,9 @@ -{{stub}}{{language +{{stub}} +{{language +|exec=interpreted +|gc=yes +|checking=dynamic |site=http://nekovm.org/ -}} \ No newline at end of file +}} + +'''Neko''' is a high-level [[Dynamic_programming|dynamically typed]] programming language developed by Nicolas Cannasse at [http://motion-twin.com/ Motion-Twin] as part of a R&D effort for better languages. \ No newline at end of file diff --git a/Lang/Neko/Arrays b/Lang/Neko/Arrays new file mode 120000 index 0000000000..fd5c76e459 --- /dev/null +++ b/Lang/Neko/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Neko \ No newline at end of file diff --git a/Lang/Neko/Comments b/Lang/Neko/Comments new file mode 120000 index 0000000000..493ca2984a --- /dev/null +++ b/Lang/Neko/Comments @@ -0,0 +1 @@ +../../Task/Comments/Neko \ No newline at end of file diff --git a/Lang/Neko/Hello-world-Text b/Lang/Neko/Hello-world-Text new file mode 120000 index 0000000000..910e03d38b --- /dev/null +++ b/Lang/Neko/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Neko \ No newline at end of file diff --git a/Lang/Neko/Loops-While b/Lang/Neko/Loops-While new file mode 120000 index 0000000000..a4b8c420f1 --- /dev/null +++ b/Lang/Neko/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Neko \ No newline at end of file diff --git a/Lang/NetRexx/Count-in-factors b/Lang/NetRexx/Count-in-factors new file mode 120000 index 0000000000..e57f2f7a5d --- /dev/null +++ b/Lang/NetRexx/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Filter b/Lang/NetRexx/Filter new file mode 120000 index 0000000000..48ac12b71b --- /dev/null +++ b/Lang/NetRexx/Filter @@ -0,0 +1 @@ +../../Task/Filter/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Fractal-tree b/Lang/NetRexx/Fractal-tree new file mode 120000 index 0000000000..d35632d3b6 --- /dev/null +++ b/Lang/NetRexx/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Greatest-common-divisor b/Lang/NetRexx/Greatest-common-divisor new file mode 120000 index 0000000000..206107bd32 --- /dev/null +++ b/Lang/NetRexx/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Least-common-multiple b/Lang/NetRexx/Least-common-multiple new file mode 120000 index 0000000000..feaf9294f6 --- /dev/null +++ b/Lang/NetRexx/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Terminal-control-Display-an-extended-character b/Lang/NetRexx/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..f80816da1a --- /dev/null +++ b/Lang/NetRexx/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Terminal-control-Ringing-the-terminal-bell b/Lang/NetRexx/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..ad2c680762 --- /dev/null +++ b/Lang/NetRexx/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/NetRexx \ No newline at end of file diff --git a/Lang/Nimrod/00DESCRIPTION b/Lang/Nimrod/00DESCRIPTION index 4517462187..ade96dbd09 100644 --- a/Lang/Nimrod/00DESCRIPTION +++ b/Lang/Nimrod/00DESCRIPTION @@ -6,8 +6,8 @@ |strength=strong |LCT=yes |checking=static -|site=http://nimrod-code.org}} +|site=http://nimrod-lang.org}} {{language programming paradigm|imperative}} -Nimrod is a general purpose, high-level, system programming, statically typed imperative compiled programming language that is developed by Andreas Rumpf. There is a lot of focus on portability and efficiency. The language compiles to C and supports many C compilers. Nimrod is actively being developed although it could use more developers, there is currently only one core developer. The language has excellent [http://nimrod-code.org/lib.html documentation], and a very good [http://nimrod-code.org/tut1.html tutorial]. +Nimrod is a general purpose, high-level, system programming, statically typed imperative compiled programming language that is developed by Andreas Rumpf. There is a lot of focus on portability and efficiency. The language compiles to C and supports many C compilers. Nimrod is actively being developed although it could use more developers, there is currently only one core developer. The language has excellent [http://nimrod-lang.org/lib.html documentation], and a very good [http://nimrod-lang.org/tut1.html tutorial]. You can ask for help on Freenode in the #nimrod channel. \ No newline at end of file diff --git a/Lang/Nimrod/Anagrams b/Lang/Nimrod/Anagrams new file mode 120000 index 0000000000..6821bfaabf --- /dev/null +++ b/Lang/Nimrod/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Arithmetic-Complex b/Lang/Nimrod/Arithmetic-Complex new file mode 120000 index 0000000000..c6cc45fdd3 --- /dev/null +++ b/Lang/Nimrod/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Arithmetic-Integer b/Lang/Nimrod/Arithmetic-Integer new file mode 120000 index 0000000000..d5748fc3cf --- /dev/null +++ b/Lang/Nimrod/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Arithmetic-geometric-mean b/Lang/Nimrod/Arithmetic-geometric-mean new file mode 120000 index 0000000000..98559aa412 --- /dev/null +++ b/Lang/Nimrod/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Associative-array-Creation b/Lang/Nimrod/Associative-array-Creation new file mode 120000 index 0000000000..93e293cf72 --- /dev/null +++ b/Lang/Nimrod/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Associative-array-Iteration b/Lang/Nimrod/Associative-array-Iteration new file mode 120000 index 0000000000..6677fa138d --- /dev/null +++ b/Lang/Nimrod/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Comments b/Lang/Nimrod/Comments new file mode 120000 index 0000000000..726f4bdbf9 --- /dev/null +++ b/Lang/Nimrod/Comments @@ -0,0 +1 @@ +../../Task/Comments/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Generic-swap b/Lang/Nimrod/Generic-swap new file mode 120000 index 0000000000..c2fadbeddf --- /dev/null +++ b/Lang/Nimrod/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Perfect-numbers b/Lang/Nimrod/Perfect-numbers new file mode 120000 index 0000000000..deed8bc14c --- /dev/null +++ b/Lang/Nimrod/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Repeat-a-string b/Lang/Nimrod/Repeat-a-string new file mode 120000 index 0000000000..61b3b9a2d8 --- /dev/null +++ b/Lang/Nimrod/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Stack b/Lang/Nimrod/Stack new file mode 120000 index 0000000000..31ade3675a --- /dev/null +++ b/Lang/Nimrod/Stack @@ -0,0 +1 @@ +../../Task/Stack/Nimrod \ No newline at end of file diff --git a/Lang/OPL/Power-set b/Lang/OPL/Power-set new file mode 120000 index 0000000000..e9d8b840c5 --- /dev/null +++ b/Lang/OPL/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/OPL \ No newline at end of file diff --git a/Lang/Objeck/Tree-traversal b/Lang/Objeck/Tree-traversal new file mode 120000 index 0000000000..88ab302088 --- /dev/null +++ b/Lang/Objeck/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Objeck \ No newline at end of file diff --git a/Lang/Objective-C/Guess-the-number b/Lang/Objective-C/Guess-the-number new file mode 120000 index 0000000000..15da8aa01f --- /dev/null +++ b/Lang/Objective-C/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Look-and-say-sequence b/Lang/Objective-C/Look-and-say-sequence new file mode 120000 index 0000000000..1ddda7acb6 --- /dev/null +++ b/Lang/Objective-C/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Objective-C \ No newline at end of file diff --git a/Lang/Oxygene/99-Bottles-of-Beer b/Lang/Oxygene/99-Bottles-of-Beer new file mode 120000 index 0000000000..ad2f93b607 --- /dev/null +++ b/Lang/Oxygene/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Oxygene \ No newline at end of file diff --git a/Lang/PHP/Middle-three-digits b/Lang/PHP/Middle-three-digits new file mode 120000 index 0000000000..1e9bfc7fa9 --- /dev/null +++ b/Lang/PHP/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PHP \ No newline at end of file diff --git a/Lang/PHP/Vector-products b/Lang/PHP/Vector-products new file mode 120000 index 0000000000..6d1013405a --- /dev/null +++ b/Lang/PHP/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PHP \ No newline at end of file diff --git a/Lang/PL-I/Apply-a-callback-to-an-array b/Lang/PL-I/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..4eba0bb7ab --- /dev/null +++ b/Lang/PL-I/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Averages-Mode b/Lang/PL-I/Averages-Mode new file mode 120000 index 0000000000..c6f4206e3e --- /dev/null +++ b/Lang/PL-I/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Balanced-brackets b/Lang/PL-I/Balanced-brackets new file mode 120000 index 0000000000..d4f7bd91e1 --- /dev/null +++ b/Lang/PL-I/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Calendar---for-real-programmers b/Lang/PL-I/Calendar---for-real-programmers new file mode 120000 index 0000000000..0aaf0bb2f6 --- /dev/null +++ b/Lang/PL-I/Calendar---for-real-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-real-programmers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Cholesky-decomposition b/Lang/PL-I/Cholesky-decomposition new file mode 120000 index 0000000000..3c59665e5a --- /dev/null +++ b/Lang/PL-I/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Conways-Game-of-Life b/Lang/PL-I/Conways-Game-of-Life new file mode 120000 index 0000000000..76c9c2ae40 --- /dev/null +++ b/Lang/PL-I/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Filter b/Lang/PL-I/Filter new file mode 120000 index 0000000000..26717cb1b6 --- /dev/null +++ b/Lang/PL-I/Filter @@ -0,0 +1 @@ +../../Task/Filter/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Function-prototype b/Lang/PL-I/Function-prototype new file mode 120000 index 0000000000..e5c85a48ad --- /dev/null +++ b/Lang/PL-I/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Hamming-numbers b/Lang/PL-I/Hamming-numbers new file mode 120000 index 0000000000..4f7c1bf75a --- /dev/null +++ b/Lang/PL-I/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Haversine-formula b/Lang/PL-I/Haversine-formula new file mode 120000 index 0000000000..e826c89af9 --- /dev/null +++ b/Lang/PL-I/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Holidays-related-to-Easter b/Lang/PL-I/Holidays-related-to-Easter new file mode 120000 index 0000000000..b50cf51895 --- /dev/null +++ b/Lang/PL-I/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Huffman-coding b/Lang/PL-I/Huffman-coding new file mode 120000 index 0000000000..ee8f23e5fa --- /dev/null +++ b/Lang/PL-I/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Image-noise b/Lang/PL-I/Image-noise new file mode 120000 index 0000000000..123fbee557 --- /dev/null +++ b/Lang/PL-I/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/PL-I \ No newline at end of file diff --git a/Lang/PL-I/LU-decomposition b/Lang/PL-I/LU-decomposition new file mode 120000 index 0000000000..2511a2d383 --- /dev/null +++ b/Lang/PL-I/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Mad-Libs b/Lang/PL-I/Mad-Libs new file mode 120000 index 0000000000..5ddf12ecae --- /dev/null +++ b/Lang/PL-I/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Middle-three-digits b/Lang/PL-I/Middle-three-digits new file mode 120000 index 0000000000..6f44dca087 --- /dev/null +++ b/Lang/PL-I/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Multifactorial b/Lang/PL-I/Multifactorial new file mode 120000 index 0000000000..c4c3bbd9b0 --- /dev/null +++ b/Lang/PL-I/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Nautical-bell b/Lang/PL-I/Nautical-bell new file mode 120000 index 0000000000..4a1549d3b5 --- /dev/null +++ b/Lang/PL-I/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/PL-I/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..1307ac8f03 --- /dev/null +++ b/Lang/PL-I/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Power-set b/Lang/PL-I/Power-set new file mode 120000 index 0000000000..54a1cb6d38 --- /dev/null +++ b/Lang/PL-I/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Problem-of-Apollonius b/Lang/PL-I/Problem-of-Apollonius new file mode 120000 index 0000000000..2a6e906674 --- /dev/null +++ b/Lang/PL-I/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Rock-paper-scissors b/Lang/PL-I/Rock-paper-scissors new file mode 120000 index 0000000000..6b7b4d2bbd --- /dev/null +++ b/Lang/PL-I/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Set-consolidation b/Lang/PL-I/Set-consolidation new file mode 120000 index 0000000000..e4f8940c4a --- /dev/null +++ b/Lang/PL-I/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Singly-linked-list-Element-definition b/Lang/PL-I/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..8a92f80b70 --- /dev/null +++ b/Lang/PL-I/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Singly-linked-list-Element-insertion b/Lang/PL-I/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..ab835c8f07 --- /dev/null +++ b/Lang/PL-I/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Selection-sort b/Lang/PL-I/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..8895c69847 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Special-variables b/Lang/PL-I/Special-variables new file mode 120000 index 0000000000..acfc5efb6b --- /dev/null +++ b/Lang/PL-I/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Top-rank-per-group b/Lang/PL-I/Top-rank-per-group new file mode 120000 index 0000000000..87419c0c34 --- /dev/null +++ b/Lang/PL-I/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Topswops b/Lang/PL-I/Topswops new file mode 120000 index 0000000000..2f666ab48c --- /dev/null +++ b/Lang/PL-I/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Trabb-Pardo-Knuth-algorithm b/Lang/PL-I/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..77a52245fc --- /dev/null +++ b/Lang/PL-I/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PL-I \ No newline at end of file diff --git a/Lang/Pascal/Bulls-and-cows b/Lang/Pascal/Bulls-and-cows new file mode 120000 index 0000000000..ee19a097b7 --- /dev/null +++ b/Lang/Pascal/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/00DESCRIPTION b/Lang/Perl-6/00DESCRIPTION index d0a480c788..16a7c82b3a 100644 --- a/Lang/Perl-6/00DESCRIPTION +++ b/Lang/Perl-6/00DESCRIPTION @@ -14,7 +14,7 @@ {{language programming paradigm|functional}} {{language programming paradigm|object-oriented}} {{language programming paradigm|generic}} -Perl 6 is the up-and-coming little sister to Perl 5. Though it resembles previous versions of [[Perl]] to no small degree, Perl 6 is substantially a new language; by design, it isn't backwards-compatible with Perl 5. In development since 2000, Perl 6 still lacks a complete implementation of its specification, the [http://perlcabal.org/syn/ Synopses]. However, more than one implementation is getting close to that goal. +Perl 6 is the up-and-coming little sister to Perl 5. Though it resembles previous versions of [[Perl]] to no small degree, Perl 6 is substantially a new language; by design, it isn't backwards-compatible with Perl 5. In development since 2000, Perl 6 still lacks a complete implementation of its specification, the [http://perlcabal.org/syn/ Synopses]. Damian Conway described the basic philosophy of Perl 6 as follows: @@ -22,6 +22,6 @@ Damian Conway described the basic philosophy of Perl 6 as follows: Major new features include multiple dispatch, declarative classes, grammars, formal parameters to subroutines, type constraints on variables, lazy evaluation, junctions, meta-operators, and the ability to change Perl's syntax at will with hygienic macros and user-defined operators. -There are several different implementations of Perl 6. They vary widely in design goals, degree of completeness, and current development activity. At present, the implementations closest to matching the specification are [[Pugs]], written in [[Haskell]] and primarily of historical interest, [[Rakudo]], built on the [http://www.parrot.org Parrot] virtual machine, and [[Niecza]], built on the .NET/[http://mono-project.com/ Mono] platform. +There are several different partial implementations of Perl 6. They vary widely in design goals, degree of completeness, and current development activity. At present, the implementation closest to matching the specification is [[Rakudo]].
\ No newline at end of file diff --git a/Lang/Perl-6/Dining-philosophers b/Lang/Perl-6/Dining-philosophers new file mode 120000 index 0000000000..669616543d --- /dev/null +++ b/Lang/Perl-6/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Function-frequency b/Lang/Perl-6/Function-frequency new file mode 120000 index 0000000000..5903c145c9 --- /dev/null +++ b/Lang/Perl-6/Function-frequency @@ -0,0 +1 @@ +../../Task/Function-frequency/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/History-variables b/Lang/Perl-6/History-variables new file mode 120000 index 0000000000..930d66d778 --- /dev/null +++ b/Lang/Perl-6/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Metered-concurrency b/Lang/Perl-6/Metered-concurrency new file mode 120000 index 0000000000..771a79f372 --- /dev/null +++ b/Lang/Perl-6/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Mouse-position b/Lang/Perl-6/Mouse-position new file mode 120000 index 0000000000..30f221d6ee --- /dev/null +++ b/Lang/Perl-6/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Mutex b/Lang/Perl-6/Mutex new file mode 120000 index 0000000000..151b588311 --- /dev/null +++ b/Lang/Perl-6/Mutex @@ -0,0 +1 @@ +../../Task/Mutex/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Parametrized-SQL-statement b/Lang/Perl-6/Parametrized-SQL-statement new file mode 120000 index 0000000000..8e08c19ee0 --- /dev/null +++ b/Lang/Perl-6/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Pascals-triangle-Puzzle b/Lang/Perl-6/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..c5eb2f5429 --- /dev/null +++ b/Lang/Perl-6/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Count-examples b/Lang/Perl-6/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..4bff3c0bda --- /dev/null +++ b/Lang/Perl-6/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sokoban b/Lang/Perl-6/Sokoban new file mode 120000 index 0000000000..28a809de98 --- /dev/null +++ b/Lang/Perl-6/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/Balanced-ternary b/Lang/Perl/Balanced-ternary new file mode 120000 index 0000000000..922b524817 --- /dev/null +++ b/Lang/Perl/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Perl \ No newline at end of file diff --git a/Lang/Perl/Cholesky-decomposition b/Lang/Perl/Cholesky-decomposition new file mode 120000 index 0000000000..76e0d7fd09 --- /dev/null +++ b/Lang/Perl/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Perl \ No newline at end of file diff --git a/Lang/Perl/Digital-root b/Lang/Perl/Digital-root new file mode 120000 index 0000000000..c8ac121c8f --- /dev/null +++ b/Lang/Perl/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Perl \ No newline at end of file diff --git a/Lang/Perl/Hofstadter-Figure-Figure-sequences b/Lang/Perl/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..cb18c5d048 --- /dev/null +++ b/Lang/Perl/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Perl \ No newline at end of file diff --git a/Lang/Perl/Mad-Libs b/Lang/Perl/Mad-Libs new file mode 120000 index 0000000000..7660b4016a --- /dev/null +++ b/Lang/Perl/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Perl \ No newline at end of file diff --git a/Lang/Perl/Pascals-triangle-Puzzle b/Lang/Perl/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..c99203be76 --- /dev/null +++ b/Lang/Perl/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Pattern-matching b/Lang/Perl/Pattern-matching new file mode 120000 index 0000000000..12f7889a3c --- /dev/null +++ b/Lang/Perl/Pattern-matching @@ -0,0 +1 @@ +../../Task/Pattern-matching/Perl \ No newline at end of file diff --git a/Lang/Perl/Permutation-test b/Lang/Perl/Permutation-test new file mode 120000 index 0000000000..309bd8dadf --- /dev/null +++ b/Lang/Perl/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Perl \ No newline at end of file diff --git a/Lang/Perl/Permutations-by-swapping b/Lang/Perl/Permutations-by-swapping new file mode 120000 index 0000000000..021c82119e --- /dev/null +++ b/Lang/Perl/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Perl \ No newline at end of file diff --git a/Lang/Perl/Pig-the-dice-game b/Lang/Perl/Pig-the-dice-game new file mode 120000 index 0000000000..9d005951aa --- /dev/null +++ b/Lang/Perl/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Perl \ No newline at end of file diff --git a/Lang/Perl/Pythagorean-triples b/Lang/Perl/Pythagorean-triples new file mode 120000 index 0000000000..fea717e7a5 --- /dev/null +++ b/Lang/Perl/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Perl \ No newline at end of file diff --git a/Lang/Perl/Set-puzzle b/Lang/Perl/Set-puzzle new file mode 120000 index 0000000000..df29cb145f --- /dev/null +++ b/Lang/Perl/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Seven-sided-dice-from-five-sided-dice b/Lang/Perl/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..0615f551c7 --- /dev/null +++ b/Lang/Perl/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Perl \ No newline at end of file diff --git a/Lang/Perl/Sokoban b/Lang/Perl/Sokoban new file mode 120000 index 0000000000..770f79d2e1 --- /dev/null +++ b/Lang/Perl/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Perl \ No newline at end of file diff --git a/Lang/Perl/Speech-synthesis b/Lang/Perl/Speech-synthesis new file mode 120000 index 0000000000..f7520832c0 --- /dev/null +++ b/Lang/Perl/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Perl \ No newline at end of file diff --git a/Lang/Perl/Topswops b/Lang/Perl/Topswops new file mode 120000 index 0000000000..c9e7325724 --- /dev/null +++ b/Lang/Perl/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Perl \ No newline at end of file diff --git a/Lang/Perl/Twelve-statements b/Lang/Perl/Twelve-statements new file mode 120000 index 0000000000..e793b1eddb --- /dev/null +++ b/Lang/Perl/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Perl \ No newline at end of file diff --git a/Lang/Perl/Window-management b/Lang/Perl/Window-management new file mode 120000 index 0000000000..73cb2e2ec1 --- /dev/null +++ b/Lang/Perl/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Perl \ No newline at end of file diff --git a/Lang/Perl/Xiaolin-Wus-line-algorithm b/Lang/Perl/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..4d85a3fafa --- /dev/null +++ b/Lang/Perl/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Perl \ No newline at end of file diff --git a/Lang/Perl/Zeckendorf-number-representation b/Lang/Perl/Zeckendorf-number-representation new file mode 120000 index 0000000000..d11382dcd1 --- /dev/null +++ b/Lang/Perl/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/Create-a-file-on-magnetic-tape b/Lang/PicoLisp/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..f90495fe6b --- /dev/null +++ b/Lang/PicoLisp/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Largest-int-from-concatenated-ints b/Lang/PicoLisp/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..98afdabf8f --- /dev/null +++ b/Lang/PicoLisp/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Middle-three-digits b/Lang/PicoLisp/Middle-three-digits new file mode 120000 index 0000000000..f1da15fa2a --- /dev/null +++ b/Lang/PicoLisp/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Semordnilap b/Lang/PicoLisp/Semordnilap new file mode 120000 index 0000000000..5607c424a4 --- /dev/null +++ b/Lang/PicoLisp/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Temperature-conversion b/Lang/PicoLisp/Temperature-conversion new file mode 120000 index 0000000000..a8f768f0e4 --- /dev/null +++ b/Lang/PicoLisp/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Topic-variable b/Lang/PicoLisp/Topic-variable new file mode 120000 index 0000000000..62e24159cf --- /dev/null +++ b/Lang/PicoLisp/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/PicoLisp \ No newline at end of file diff --git a/Lang/Processing/FizzBuzz b/Lang/Processing/FizzBuzz new file mode 120000 index 0000000000..0b8d28909c --- /dev/null +++ b/Lang/Processing/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Processing \ No newline at end of file diff --git a/Lang/Processing/Hello-world-Graphical b/Lang/Processing/Hello-world-Graphical new file mode 120000 index 0000000000..237edde75e --- /dev/null +++ b/Lang/Processing/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Processing \ No newline at end of file diff --git a/Lang/Prolog/Call-a-foreign-language-function b/Lang/Prolog/Call-a-foreign-language-function new file mode 120000 index 0000000000..9200a84088 --- /dev/null +++ b/Lang/Prolog/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Execute-a-Markov-algorithm b/Lang/Prolog/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..81156f00ec --- /dev/null +++ b/Lang/Prolog/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Floyds-triangle b/Lang/Prolog/Floyds-triangle new file mode 120000 index 0000000000..c9efa3cd80 --- /dev/null +++ b/Lang/Prolog/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Harshad-or-Niven-series b/Lang/Prolog/Harshad-or-Niven-series new file mode 120000 index 0000000000..b3096ef7dc --- /dev/null +++ b/Lang/Prolog/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Largest-int-from-concatenated-ints b/Lang/Prolog/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..2583f18465 --- /dev/null +++ b/Lang/Prolog/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Unicode-variable-names b/Lang/Prolog/Unicode-variable-names new file mode 120000 index 0000000000..8d4851442e --- /dev/null +++ b/Lang/Prolog/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Prolog \ No newline at end of file diff --git a/Lang/Python/Universal-Turing-machine b/Lang/Python/Universal-Turing-machine new file mode 120000 index 0000000000..3df46b0016 --- /dev/null +++ b/Lang/Python/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Python \ No newline at end of file diff --git a/Lang/R/Langtons-ant b/Lang/R/Langtons-ant new file mode 120000 index 0000000000..a60998634b --- /dev/null +++ b/Lang/R/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/R \ No newline at end of file diff --git a/Lang/REBOL/Josephus-problem b/Lang/REBOL/Josephus-problem new file mode 120000 index 0000000000..d092745290 --- /dev/null +++ b/Lang/REBOL/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/REBOL \ No newline at end of file diff --git a/Lang/REXX/00DESCRIPTION b/Lang/REXX/00DESCRIPTION index 15af1e6251..5490849be3 100644 --- a/Lang/REXX/00DESCRIPTION +++ b/Lang/REXX/00DESCRIPTION @@ -8,7 +8,7 @@ * '''[[CRX REXX]]''' (Compact REXX) is a classic REXX first written by Dr. Brian Marks. -* '''[[CTC REXX]]''' is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation, a license is required to use this product. REXX can only under PC/SPF and it's panels. +* '''[[CTC REXX]]''' is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation, a license is required to use this product. This version of REXX can only be used under PC/SPF and it's panels. * '''[[KEXX]]''' is a subset of REXX that is bundled with KEDIT and written by Mansfield Software Group, Inc., a license is required to use this product. KEXX only executes under the KEDIT licensed product. diff --git a/Lang/REXX/Check-Machin-like-formulas b/Lang/REXX/Check-Machin-like-formulas new file mode 120000 index 0000000000..ecb4d23e5f --- /dev/null +++ b/Lang/REXX/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/REXX \ No newline at end of file diff --git a/Lang/REXX/Create-a-file-on-magnetic-tape b/Lang/REXX/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..b9ead55239 --- /dev/null +++ b/Lang/REXX/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/REXX \ No newline at end of file diff --git a/Lang/REXX/DNS-query b/Lang/REXX/DNS-query new file mode 120000 index 0000000000..b5ea98f16b --- /dev/null +++ b/Lang/REXX/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/REXX \ No newline at end of file diff --git a/Lang/REXX/Delete-a-file b/Lang/REXX/Delete-a-file new file mode 120000 index 0000000000..30491fd093 --- /dev/null +++ b/Lang/REXX/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/REXX \ No newline at end of file diff --git a/Lang/REXX/Dining-philosophers b/Lang/REXX/Dining-philosophers new file mode 120000 index 0000000000..d92741248c --- /dev/null +++ b/Lang/REXX/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/REXX \ No newline at end of file diff --git a/Lang/REXX/Enforced-immutability b/Lang/REXX/Enforced-immutability new file mode 120000 index 0000000000..57973033a4 --- /dev/null +++ b/Lang/REXX/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/REXX \ No newline at end of file diff --git a/Lang/REXX/First-class-functions b/Lang/REXX/First-class-functions new file mode 120000 index 0000000000..73298fa8b5 --- /dev/null +++ b/Lang/REXX/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/REXX \ No newline at end of file diff --git a/Lang/REXX/Huffman-coding b/Lang/REXX/Huffman-coding new file mode 120000 index 0000000000..c1e6d74018 --- /dev/null +++ b/Lang/REXX/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/REXX \ No newline at end of file diff --git a/Lang/REXX/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/REXX/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..b650e9a51a --- /dev/null +++ b/Lang/REXX/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX \ No newline at end of file diff --git a/Lang/REXX/Parametric-polymorphism b/Lang/REXX/Parametric-polymorphism new file mode 120000 index 0000000000..8ccc0f73d4 --- /dev/null +++ b/Lang/REXX/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/REXX \ No newline at end of file diff --git a/Lang/REXX/Partial-function-application b/Lang/REXX/Partial-function-application new file mode 120000 index 0000000000..697809241a --- /dev/null +++ b/Lang/REXX/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/REXX \ No newline at end of file diff --git a/Lang/REXX/Permutations-by-swapping b/Lang/REXX/Permutations-by-swapping new file mode 120000 index 0000000000..2c8cf5a2dd --- /dev/null +++ b/Lang/REXX/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/REXX \ No newline at end of file diff --git a/Lang/REXX/Priority-queue b/Lang/REXX/Priority-queue new file mode 120000 index 0000000000..8b9c3757b4 --- /dev/null +++ b/Lang/REXX/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/REXX \ No newline at end of file diff --git a/Lang/REXX/Singly-linked-list-Element-insertion b/Lang/REXX/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..5f8a73959e --- /dev/null +++ b/Lang/REXX/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/REXX \ No newline at end of file diff --git a/Lang/REXX/Solve-a-Hidato-puzzle b/Lang/REXX/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..1fc20195a4 --- /dev/null +++ b/Lang/REXX/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Speech-synthesis b/Lang/REXX/Speech-synthesis new file mode 120000 index 0000000000..0b1c34b3a0 --- /dev/null +++ b/Lang/REXX/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/REXX \ No newline at end of file diff --git a/Lang/REXX/Universal-Turing-machine b/Lang/REXX/Universal-Turing-machine new file mode 120000 index 0000000000..9ff90ef3e0 --- /dev/null +++ b/Lang/REXX/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/REXX \ No newline at end of file diff --git a/Lang/RPG/00DESCRIPTION b/Lang/RPG/00DESCRIPTION index 180428a720..02f438cf73 100644 --- a/Lang/RPG/00DESCRIPTION +++ b/Lang/RPG/00DESCRIPTION @@ -1,4 +1,4 @@ {{language}} -RPG II, III, 400 and RPG IV are a family of languages created and primarily distributed by [[IBM]]. The initials initially stood for '''Report Program Generator''', though that usage is no longer in vogue. These languages were widely used for the IBM S/3, S/32, S/34, S/36, S/38 and AS/400 midrange computers. +RPG II, III, 400 and RPG IV are a family of languages created and primarily distributed by [[IBM]]. The initials initially stood for '''Report Program Generator''', though that usage is no longer in vogue. These languages were widely used for the IBM S/3, S/32, S/34, S/36, S/38, AS/400 and iSeries midrange computers. ILE RPG (RPG IV) is in wide use today on the IBM i operating system which is the successor to the above-named midrange systems of the past. The latest version of RPG ( RPG IV or RPGLE ) contains features such as prototyped functions and procedures, static and dynamic binding, access to C routine libraries, dynamic link libraries, and fully recursive and re-entrant modular code. \ No newline at end of file diff --git a/Lang/RPG/Integer-comparison b/Lang/RPG/Integer-comparison new file mode 120000 index 0000000000..8669fc24c4 --- /dev/null +++ b/Lang/RPG/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/RPG \ No newline at end of file diff --git a/Lang/Racket/Polymorphic-copy b/Lang/Racket/Polymorphic-copy new file mode 120000 index 0000000000..cb0bf460c8 --- /dev/null +++ b/Lang/Racket/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Racket \ No newline at end of file diff --git a/Lang/Racket/SQL-based-authentication b/Lang/Racket/SQL-based-authentication new file mode 120000 index 0000000000..5ed0e7633c --- /dev/null +++ b/Lang/Racket/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Racket \ No newline at end of file diff --git a/Lang/Ruby/Average-loop-length b/Lang/Ruby/Average-loop-length new file mode 120000 index 0000000000..df6c03425e --- /dev/null +++ b/Lang/Ruby/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Fast-Fourier-transform b/Lang/Ruby/Fast-Fourier-transform new file mode 120000 index 0000000000..92bf0a35a9 --- /dev/null +++ b/Lang/Ruby/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Ruby \ No newline at end of file diff --git a/Lang/Ruby/History-variables b/Lang/Ruby/History-variables new file mode 120000 index 0000000000..6d3a7cfedf --- /dev/null +++ b/Lang/Ruby/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Ruby \ No newline at end of file diff --git a/Lang/Ruby/I-before-E-except-after-C b/Lang/Ruby/I-before-E-except-after-C new file mode 120000 index 0000000000..9e0fa54cc5 --- /dev/null +++ b/Lang/Ruby/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Rate-counter b/Lang/Ruby/Rate-counter new file mode 120000 index 0000000000..e154b96cbb --- /dev/null +++ b/Lang/Ruby/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Set-consolidation b/Lang/Ruby/Set-consolidation new file mode 120000 index 0000000000..3e1ea62cd5 --- /dev/null +++ b/Lang/Ruby/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Temperature-conversion b/Lang/Ruby/Temperature-conversion new file mode 120000 index 0000000000..78f30ffa44 --- /dev/null +++ b/Lang/Ruby/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Display-an-extended-character b/Lang/Ruby/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..8bc8c4eb40 --- /dev/null +++ b/Lang/Ruby/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Hiding-the-cursor b/Lang/Ruby/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..da8066f4ac --- /dev/null +++ b/Lang/Ruby/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Unicode-output b/Lang/Ruby/Terminal-control-Unicode-output new file mode 120000 index 0000000000..459c9d95d4 --- /dev/null +++ b/Lang/Ruby/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Unicode-strings b/Lang/Ruby/Unicode-strings new file mode 120000 index 0000000000..a24dce4e87 --- /dev/null +++ b/Lang/Ruby/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Zeckendorf-number-representation b/Lang/Ruby/Zeckendorf-number-representation new file mode 120000 index 0000000000..7b05da52dc --- /dev/null +++ b/Lang/Ruby/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Read-a-configuration-file b/Lang/Run-BASIC/Read-a-configuration-file new file mode 120000 index 0000000000..f263eff321 --- /dev/null +++ b/Lang/Run-BASIC/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Read-entire-file b/Lang/Run-BASIC/Read-entire-file new file mode 120000 index 0000000000..31185a961c --- /dev/null +++ b/Lang/Run-BASIC/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/99-Bottles-of-Beer b/Lang/Rust/99-Bottles-of-Beer new file mode 120000 index 0000000000..cada6e3c83 --- /dev/null +++ b/Lang/Rust/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Rust \ No newline at end of file diff --git a/Lang/Rust/Bitmap-Write-a-PPM-file b/Lang/Rust/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..3bf01d67e7 --- /dev/null +++ b/Lang/Rust/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Bitwise-operations b/Lang/Rust/Bitwise-operations new file mode 120000 index 0000000000..02dcd4a3cb --- /dev/null +++ b/Lang/Rust/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Rust \ No newline at end of file diff --git a/Lang/Rust/Command-line-arguments b/Lang/Rust/Command-line-arguments new file mode 120000 index 0000000000..6fa24db8c2 --- /dev/null +++ b/Lang/Rust/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Rust \ No newline at end of file diff --git a/Lang/Rust/Comments b/Lang/Rust/Comments new file mode 120000 index 0000000000..f64f082325 --- /dev/null +++ b/Lang/Rust/Comments @@ -0,0 +1 @@ +../../Task/Comments/Rust \ No newline at end of file diff --git a/Lang/Rust/Count-in-octal b/Lang/Rust/Count-in-octal new file mode 120000 index 0000000000..fe23ab5e63 --- /dev/null +++ b/Lang/Rust/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Rust \ No newline at end of file diff --git a/Lang/Rust/Empty-program b/Lang/Rust/Empty-program new file mode 120000 index 0000000000..90eb062983 --- /dev/null +++ b/Lang/Rust/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Rust \ No newline at end of file diff --git a/Lang/Rust/File-IO b/Lang/Rust/File-IO new file mode 120000 index 0000000000..bf0d436165 --- /dev/null +++ b/Lang/Rust/File-IO @@ -0,0 +1 @@ +../../Task/File-IO/Rust \ No newline at end of file diff --git a/Lang/Rust/Find-limit-of-recursion b/Lang/Rust/Find-limit-of-recursion new file mode 120000 index 0000000000..7f0c3fb941 --- /dev/null +++ b/Lang/Rust/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Rust \ No newline at end of file diff --git a/Lang/Rust/Guess-the-number-With-feedback--player- b/Lang/Rust/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..28efd62375 --- /dev/null +++ b/Lang/Rust/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Rust \ No newline at end of file diff --git a/Lang/Rust/Integer-sequence b/Lang/Rust/Integer-sequence new file mode 120000 index 0000000000..9d74fc7d6a --- /dev/null +++ b/Lang/Rust/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Knuth-shuffle b/Lang/Rust/Knuth-shuffle new file mode 120000 index 0000000000..a9dbdfd57c --- /dev/null +++ b/Lang/Rust/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Rust \ No newline at end of file diff --git a/Lang/Rust/Look-and-say-sequence b/Lang/Rust/Look-and-say-sequence new file mode 120000 index 0000000000..cffba38710 --- /dev/null +++ b/Lang/Rust/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Loop-over-multiple-arrays-simultaneously b/Lang/Rust/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..0acb24326a --- /dev/null +++ b/Lang/Rust/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Downward-for b/Lang/Rust/Loops-Downward-for new file mode 120000 index 0000000000..95606d48d6 --- /dev/null +++ b/Lang/Rust/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Nested b/Lang/Rust/Loops-Nested new file mode 120000 index 0000000000..7dcbdb375d --- /dev/null +++ b/Lang/Rust/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Rust \ No newline at end of file diff --git a/Lang/Rust/Quine b/Lang/Rust/Quine new file mode 120000 index 0000000000..e3dde09404 --- /dev/null +++ b/Lang/Rust/Quine @@ -0,0 +1 @@ +../../Task/Quine/Rust \ No newline at end of file diff --git a/Lang/Rust/Sieve-of-Eratosthenes b/Lang/Rust/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..5855328323 --- /dev/null +++ b/Lang/Rust/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Rust \ No newline at end of file diff --git a/Lang/Rust/Towers-of-Hanoi b/Lang/Rust/Towers-of-Hanoi new file mode 120000 index 0000000000..8eba0d3e98 --- /dev/null +++ b/Lang/Rust/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Rust \ No newline at end of file diff --git a/Lang/SAS/Standard-deviation b/Lang/SAS/Standard-deviation new file mode 120000 index 0000000000..be23e46c07 --- /dev/null +++ b/Lang/SAS/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/SAS \ No newline at end of file diff --git a/Lang/SQL/00DESCRIPTION b/Lang/SQL/00DESCRIPTION index 13254faeef..04c508ad95 100644 --- a/Lang/SQL/00DESCRIPTION +++ b/Lang/SQL/00DESCRIPTION @@ -1,5 +1,6 @@ {{stub}} {{language|SQL|bnf=http://savage.net.au/SQL/sql-2003-2.bnf.html}} +{{Language programming paradigm|Query}} '''[[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.) diff --git a/Lang/SQL/Dutch-national-flag-problem b/Lang/SQL/Dutch-national-flag-problem new file mode 120000 index 0000000000..902904f1e5 --- /dev/null +++ b/Lang/SQL/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/SQL \ No newline at end of file diff --git a/Lang/SQL/Knapsack-problem-0-1 b/Lang/SQL/Knapsack-problem-0-1 new file mode 120000 index 0000000000..9b5e235504 --- /dev/null +++ b/Lang/SQL/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/SQL \ No newline at end of file diff --git a/Lang/Scala/00DESCRIPTION b/Lang/Scala/00DESCRIPTION index 1718b44813..ba9ce24e3c 100644 --- a/Lang/Scala/00DESCRIPTION +++ b/Lang/Scala/00DESCRIPTION @@ -13,4 +13,4 @@ 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. -The problem with rosetta.org is that lot of tasks addresses the technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on 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 deliberate not Scala's cup of tea. \ No newline at end of file diff --git a/Lang/Scala/Balanced-ternary b/Lang/Scala/Balanced-ternary new file mode 120000 index 0000000000..204dcd34d6 --- /dev/null +++ b/Lang/Scala/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Scala \ No newline at end of file diff --git a/Lang/Scala/Best-shuffle b/Lang/Scala/Best-shuffle new file mode 120000 index 0000000000..2bc6b808f6 --- /dev/null +++ b/Lang/Scala/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Scala \ No newline at end of file diff --git a/Lang/Scala/Bulls-and-cows-Player b/Lang/Scala/Bulls-and-cows-Player new file mode 120000 index 0000000000..3b2ea54558 --- /dev/null +++ b/Lang/Scala/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Scala \ No newline at end of file diff --git a/Lang/Scala/Call-an-object-method b/Lang/Scala/Call-an-object-method new file mode 120000 index 0000000000..77d9a65a51 --- /dev/null +++ b/Lang/Scala/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Scala \ No newline at end of file diff --git a/Lang/Scala/Create-a-file-on-magnetic-tape b/Lang/Scala/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..73e95f3312 --- /dev/null +++ b/Lang/Scala/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Scala \ No newline at end of file diff --git a/Lang/Scala/Delete-a-file b/Lang/Scala/Delete-a-file new file mode 120000 index 0000000000..9a37639977 --- /dev/null +++ b/Lang/Scala/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Environment-variables b/Lang/Scala/Environment-variables new file mode 120000 index 0000000000..faa0b41da4 --- /dev/null +++ b/Lang/Scala/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Scala \ No newline at end of file diff --git a/Lang/Scala/Introspection b/Lang/Scala/Introspection new file mode 120000 index 0000000000..352fa331b2 --- /dev/null +++ b/Lang/Scala/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Scala \ No newline at end of file diff --git a/Lang/Scala/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Scala/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..7b06ddc737 --- /dev/null +++ b/Lang/Scala/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Scala \ No newline at end of file diff --git a/Lang/Scala/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Scala/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..5e58c07731 --- /dev/null +++ b/Lang/Scala/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Scala \ No newline at end of file diff --git a/Lang/Scala/Maze-generation b/Lang/Scala/Maze-generation new file mode 120000 index 0000000000..dbbfd38af7 --- /dev/null +++ b/Lang/Scala/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Scala \ No newline at end of file diff --git a/Lang/Scala/Random-number-generator--included- b/Lang/Scala/Random-number-generator--included- new file mode 120000 index 0000000000..2f2630989f --- /dev/null +++ b/Lang/Scala/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/Scala \ No newline at end of file diff --git a/Lang/Scala/Read-a-configuration-file b/Lang/Scala/Read-a-configuration-file new file mode 120000 index 0000000000..5d433d0134 --- /dev/null +++ b/Lang/Scala/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Read-entire-file b/Lang/Scala/Read-entire-file new file mode 120000 index 0000000000..f389143340 --- /dev/null +++ b/Lang/Scala/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Speech-synthesis b/Lang/Scala/Speech-synthesis new file mode 120000 index 0000000000..29368fcb8f --- /dev/null +++ b/Lang/Scala/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Ringing-the-terminal-bell b/Lang/Scala/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..92b20dff8c --- /dev/null +++ b/Lang/Scala/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Scala \ No newline at end of file diff --git a/Lang/Scheme/Read-entire-file b/Lang/Scheme/Read-entire-file new file mode 120000 index 0000000000..a87cb9fc91 --- /dev/null +++ b/Lang/Scheme/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Scheme \ No newline at end of file diff --git a/Lang/Scilab/00DESCRIPTION b/Lang/Scilab/00DESCRIPTION index b8442afe01..497f740140 100644 --- a/Lang/Scilab/00DESCRIPTION +++ b/Lang/Scilab/00DESCRIPTION @@ -5,7 +5,7 @@ }} {{Wikipedia}} -Scilab is an open source, cross-platform numerical computational package and a high-level, numerically oriented programming language. It can be used for signal processing, statistical analysis, image enhancement, fluid dynamics simulations, numerical optimization, and modeling and simulation of explicit and implicit dynamical systems. [[MATLAB]] code, which is similar in syntax, can be converted to Scilab. Scilab is one of several open source alternatives to MATLAB. +[http://www.scilab.org/ Scilab] is a free and open source, cross-platform numerical computational package and a high-level, numerically oriented programming language. It can be used for signal processing, statistical analysis, image enhancement, fluid dynamics simulations, numerical optimization, and modeling and simulation of explicit and implicit dynamical systems. [[MATLAB]] code, which is similar in syntax, can be converted to Scilab. Scilab is one of several open source alternatives to MATLAB. == See Also == [[Octave]] \ No newline at end of file diff --git a/Lang/Scilab/Dot-product b/Lang/Scilab/Dot-product new file mode 120000 index 0000000000..2e0bb9e8e4 --- /dev/null +++ b/Lang/Scilab/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Factorial b/Lang/Scilab/Factorial new file mode 120000 index 0000000000..d15746153c --- /dev/null +++ b/Lang/Scilab/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Fast-Fourier-transform b/Lang/Scilab/Fast-Fourier-transform new file mode 120000 index 0000000000..b1ace19d44 --- /dev/null +++ b/Lang/Scilab/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Hello-world-Text b/Lang/Scilab/Hello-world-Text new file mode 120000 index 0000000000..fb53bc7ce4 --- /dev/null +++ b/Lang/Scilab/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Scilab \ No newline at end of file diff --git a/Lang/Seed7/Bitwise-operations b/Lang/Seed7/Bitwise-operations new file mode 120000 index 0000000000..ee84305ad0 --- /dev/null +++ b/Lang/Seed7/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/CRC-32 b/Lang/Seed7/CRC-32 new file mode 120000 index 0000000000..aa200b01e4 --- /dev/null +++ b/Lang/Seed7/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Echo-server b/Lang/Seed7/Echo-server new file mode 120000 index 0000000000..d9142c172c --- /dev/null +++ b/Lang/Seed7/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Entropy b/Lang/Seed7/Entropy new file mode 120000 index 0000000000..550c21e624 --- /dev/null +++ b/Lang/Seed7/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/HTTPS b/Lang/Seed7/HTTPS new file mode 120000 index 0000000000..c28ef6dc96 --- /dev/null +++ b/Lang/Seed7/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Host-introspection b/Lang/Seed7/Host-introspection new file mode 120000 index 0000000000..666b645f4f --- /dev/null +++ b/Lang/Seed7/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Loops-Nested b/Lang/Seed7/Loops-Nested new file mode 120000 index 0000000000..91f7d44a82 --- /dev/null +++ b/Lang/Seed7/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/MD4 b/Lang/Seed7/MD4 new file mode 120000 index 0000000000..61c045bce1 --- /dev/null +++ b/Lang/Seed7/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/MD5 b/Lang/Seed7/MD5 new file mode 120000 index 0000000000..676f65a1fe --- /dev/null +++ b/Lang/Seed7/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/MD5-Implementation b/Lang/Seed7/MD5-Implementation new file mode 120000 index 0000000000..e70a7782d6 --- /dev/null +++ b/Lang/Seed7/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Middle-three-digits b/Lang/Seed7/Middle-three-digits new file mode 120000 index 0000000000..c239466ed4 --- /dev/null +++ b/Lang/Seed7/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Multifactorial b/Lang/Seed7/Multifactorial new file mode 120000 index 0000000000..852e029bb4 --- /dev/null +++ b/Lang/Seed7/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Multiplicative-order b/Lang/Seed7/Multiplicative-order new file mode 120000 index 0000000000..81fb0cf53d --- /dev/null +++ b/Lang/Seed7/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Number-reversal-game b/Lang/Seed7/Number-reversal-game new file mode 120000 index 0000000000..e2927ead4f --- /dev/null +++ b/Lang/Seed7/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Read-entire-file b/Lang/Seed7/Read-entire-file new file mode 120000 index 0000000000..8983ba23d8 --- /dev/null +++ b/Lang/Seed7/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Rosetta-Code-Rank-languages-by-popularity b/Lang/Seed7/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..ef18e8acbd --- /dev/null +++ b/Lang/Seed7/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/SHA-1 b/Lang/Seed7/SHA-1 new file mode 120000 index 0000000000..af20d1074b --- /dev/null +++ b/Lang/Seed7/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/SHA-256 b/Lang/Seed7/SHA-256 new file mode 120000 index 0000000000..a30e0aec82 --- /dev/null +++ b/Lang/Seed7/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Write-language-name-in-3D-ASCII b/Lang/Seed7/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..24741655b9 --- /dev/null +++ b/Lang/Seed7/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Seed7 \ No newline at end of file diff --git a/Lang/Standard-ML/Gray-code b/Lang/Standard-ML/Gray-code new file mode 120000 index 0000000000..dae7fbeeb8 --- /dev/null +++ b/Lang/Standard-ML/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Standard-ML \ No newline at end of file diff --git a/Lang/TXR/00DESCRIPTION b/Lang/TXR/00DESCRIPTION index a2673a167c..c8b9192a97 100644 --- a/Lang/TXR/00DESCRIPTION +++ b/Lang/TXR/00DESCRIPTION @@ -1,11 +1,20 @@ {{stub}}{{language |site=http://www.nongnu.org/txr/}} -TXR is a new text extraction language implemented in [[C]], running on [[Linux]] and [[Cygwin]] (and possibly other [[POSIX]] platforms) as well as Windows. +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 source of a TXR query is literal text except for directives and variables preceded by the @ character. +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 -Computation evolves by textual pattern matching with implicit backtracking. Non-pattern matching activities are embedded into a pattern matching paradigm. For instance, the line +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. + +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.) + +Thus, the source of a TXR query is literal text except for directives and variables preceded by the @ character. + +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
Four score and seven years ago,
@@ -17,6 +26,8 @@ which succeeds if foo has no prior binding, or already contains @(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)). + ==Extremely Simple Query== Extract first matching line from the password file. Of course, TXR matches are not restricted to single line! @@ -82,14 +93,6 @@ Mem: 769280 647752 121528 160108 286844 Swap: 1048568 18200 1030368 -Arithmetic is not implemented in TXR as of version 035. The above example simply continues the pattern matching across invocations of echo to borrow the shell to do math. The command - -
@(next `!echo $(( @TOTAL - @FREE ))`)
-@USED
-
- -means, "Next, please switch to scanning the output of this echo command with some variables substituted in. Then capture entire first line of this command into the USED variable." - == 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. diff --git a/Lang/TXR/A+B b/Lang/TXR/A+B new file mode 120000 index 0000000000..65cb47f747 --- /dev/null +++ b/Lang/TXR/A+B @@ -0,0 +1 @@ +../../Task/A+B/TXR \ No newline at end of file diff --git a/Lang/TXR/Accumulator-factory b/Lang/TXR/Accumulator-factory new file mode 120000 index 0000000000..4d0d43e9a9 --- /dev/null +++ b/Lang/TXR/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/TXR \ No newline at end of file diff --git a/Lang/TXR/Detect-division-by-zero b/Lang/TXR/Detect-division-by-zero new file mode 120000 index 0000000000..77237581a4 --- /dev/null +++ b/Lang/TXR/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/TXR \ No newline at end of file diff --git a/Lang/TXR/Handle-a-signal b/Lang/TXR/Handle-a-signal new file mode 120000 index 0000000000..0a77b02e18 --- /dev/null +++ b/Lang/TXR/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/TXR \ No newline at end of file diff --git a/Lang/TXR/Program-name b/Lang/TXR/Program-name new file mode 120000 index 0000000000..eca8afa71d --- /dev/null +++ b/Lang/TXR/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/TXR \ No newline at end of file diff --git a/Lang/TXR/Range-expansion b/Lang/TXR/Range-expansion new file mode 120000 index 0000000000..1582ebf4a7 --- /dev/null +++ b/Lang/TXR/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/TXR \ No newline at end of file diff --git a/Lang/TXR/S-Expressions b/Lang/TXR/S-Expressions new file mode 120000 index 0000000000..f628ce9722 --- /dev/null +++ b/Lang/TXR/S-Expressions @@ -0,0 +1 @@ +../../Task/S-Expressions/TXR \ No newline at end of file diff --git a/Lang/TXR/Strip-control-codes-and-extended-characters-from-a-string b/Lang/TXR/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..aadfcd7b27 --- /dev/null +++ b/Lang/TXR/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/TXR \ No newline at end of file diff --git a/Lang/TXR/Sum-of-a-series b/Lang/TXR/Sum-of-a-series new file mode 120000 index 0000000000..52ed7a5c09 --- /dev/null +++ b/Lang/TXR/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/TXR \ No newline at end of file diff --git a/Lang/TXR/Variable-length-quantity b/Lang/TXR/Variable-length-quantity new file mode 120000 index 0000000000..df05f2260c --- /dev/null +++ b/Lang/TXR/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/TXR \ No newline at end of file diff --git a/Lang/TorqueScript/Ackermann-function b/Lang/TorqueScript/Ackermann-function new file mode 120000 index 0000000000..1bca33b440 --- /dev/null +++ b/Lang/TorqueScript/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/TorqueScript \ No newline at end of file diff --git a/Lang/TorqueScript/Sorting-algorithms-Bubble-sort b/Lang/TorqueScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..8ab7722755 --- /dev/null +++ b/Lang/TorqueScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/TorqueScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/Rock-paper-scissors b/Lang/UNIX-Shell/Rock-paper-scissors new file mode 120000 index 0000000000..c345bcedfc --- /dev/null +++ b/Lang/UNIX-Shell/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/UNIX-Shell \ No newline at end of file diff --git a/Lang/VB6/00DESCRIPTION b/Lang/VB6/00DESCRIPTION index 8c64d67b72..aa9052998e 100644 --- a/Lang/VB6/00DESCRIPTION +++ b/Lang/VB6/00DESCRIPTION @@ -1,3 +1,2 @@ #REDIRECT [[:Category:Visual_Basic]] -{{db-empty}} {{language}}{{stub}} \ No newline at end of file diff --git a/Lang/VBA/100-doors b/Lang/VBA/100-doors new file mode 120000 index 0000000000..4d89e751fe --- /dev/null +++ b/Lang/VBA/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/VBA \ No newline at end of file diff --git a/Lang/VBA/24-game b/Lang/VBA/24-game new file mode 120000 index 0000000000..157e1c8c00 --- /dev/null +++ b/Lang/VBA/24-game @@ -0,0 +1 @@ +../../Task/24-game/VBA \ No newline at end of file diff --git a/Lang/VBA/A+B b/Lang/VBA/A+B new file mode 120000 index 0000000000..2c2191ac35 --- /dev/null +++ b/Lang/VBA/A+B @@ -0,0 +1 @@ +../../Task/A+B/VBA \ No newline at end of file diff --git a/Lang/VBA/Arithmetic-Integer b/Lang/VBA/Arithmetic-Integer new file mode 120000 index 0000000000..8ae3d56288 --- /dev/null +++ b/Lang/VBA/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/VBA \ No newline at end of file diff --git a/Lang/VBA/Character-codes b/Lang/VBA/Character-codes new file mode 120000 index 0000000000..f361658cff --- /dev/null +++ b/Lang/VBA/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/VBA \ No newline at end of file diff --git a/Lang/VBA/Count-in-octal b/Lang/VBA/Count-in-octal new file mode 120000 index 0000000000..c9c372d197 --- /dev/null +++ b/Lang/VBA/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/VBA \ No newline at end of file diff --git a/Lang/VBA/Count-occurrences-of-a-substring b/Lang/VBA/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..cda8503444 --- /dev/null +++ b/Lang/VBA/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/VBA \ No newline at end of file diff --git a/Lang/VBA/Date-format b/Lang/VBA/Date-format new file mode 120000 index 0000000000..dcc26c88f7 --- /dev/null +++ b/Lang/VBA/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/VBA \ No newline at end of file diff --git a/Lang/VBA/Guess-the-number-With-feedback--player- b/Lang/VBA/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..ec1101776c --- /dev/null +++ b/Lang/VBA/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/VBA \ No newline at end of file diff --git a/Lang/VBA/Sleep b/Lang/VBA/Sleep new file mode 120000 index 0000000000..bcd107a552 --- /dev/null +++ b/Lang/VBA/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/VBA \ No newline at end of file diff --git a/Lang/VBA/String-case b/Lang/VBA/String-case new file mode 120000 index 0000000000..dffdf4fca4 --- /dev/null +++ b/Lang/VBA/String-case @@ -0,0 +1 @@ +../../Task/String-case/VBA \ No newline at end of file diff --git a/Lang/VBA/Strip-a-set-of-characters-from-a-string b/Lang/VBA/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..06136fddd1 --- /dev/null +++ b/Lang/VBA/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/VBA \ No newline at end of file diff --git a/Lang/VBA/System-time b/Lang/VBA/System-time new file mode 120000 index 0000000000..d6c202898c --- /dev/null +++ b/Lang/VBA/System-time @@ -0,0 +1 @@ +../../Task/System-time/VBA \ No newline at end of file diff --git a/Lang/VBScript/File-modification-time b/Lang/VBScript/File-modification-time new file mode 120000 index 0000000000..91a05d91ed --- /dev/null +++ b/Lang/VBScript/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/VBScript \ No newline at end of file diff --git a/Lang/VBScript/File-size b/Lang/VBScript/File-size new file mode 120000 index 0000000000..b3f7484b0b --- /dev/null +++ b/Lang/VBScript/File-size @@ -0,0 +1 @@ +../../Task/File-size/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Find-common-directory-path b/Lang/VBScript/Find-common-directory-path new file mode 120000 index 0000000000..07a276c6f5 --- /dev/null +++ b/Lang/VBScript/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Five-weekends b/Lang/VBScript/Five-weekends new file mode 120000 index 0000000000..35db737ba4 --- /dev/null +++ b/Lang/VBScript/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Floyds-triangle b/Lang/VBScript/Floyds-triangle new file mode 120000 index 0000000000..80a5ed1280 --- /dev/null +++ b/Lang/VBScript/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Formatted-numeric-output b/Lang/VBScript/Formatted-numeric-output new file mode 120000 index 0000000000..ad1328d565 --- /dev/null +++ b/Lang/VBScript/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Globally-replace-text-in-several-files b/Lang/VBScript/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..38c7ff24b9 --- /dev/null +++ b/Lang/VBScript/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Repeat-a-string b/Lang/VBScript/Repeat-a-string new file mode 120000 index 0000000000..d08291d822 --- /dev/null +++ b/Lang/VBScript/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Reverse-a-string b/Lang/VBScript/Reverse-a-string new file mode 120000 index 0000000000..db6957234b --- /dev/null +++ b/Lang/VBScript/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/VBScript \ No newline at end of file diff --git a/Lang/VHDL/Factorial b/Lang/VHDL/Factorial new file mode 120000 index 0000000000..44e2653ed8 --- /dev/null +++ b/Lang/VHDL/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/VHDL \ No newline at end of file diff --git a/Lang/Visual-Prolog/99-Bottles-of-Beer b/Lang/Visual-Prolog/99-Bottles-of-Beer new file mode 120000 index 0000000000..2538580fd2 --- /dev/null +++ b/Lang/Visual-Prolog/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Visual-Prolog \ No newline at end of file diff --git a/Lang/Visual-Prolog/Higher-order-functions b/Lang/Visual-Prolog/Higher-order-functions new file mode 120000 index 0000000000..24083cfc0d --- /dev/null +++ b/Lang/Visual-Prolog/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Visual-Prolog \ No newline at end of file diff --git a/Lang/Visual-Prolog/List-comprehensions b/Lang/Visual-Prolog/List-comprehensions new file mode 120000 index 0000000000..544da724b6 --- /dev/null +++ b/Lang/Visual-Prolog/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Visual-Prolog \ No newline at end of file diff --git a/Lang/Visual-Prolog/Parametric-polymorphism b/Lang/Visual-Prolog/Parametric-polymorphism new file mode 120000 index 0000000000..dcf5167cf7 --- /dev/null +++ b/Lang/Visual-Prolog/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Visual-Prolog \ No newline at end of file diff --git a/Lang/XSLT/Conways-Game-of-Life b/Lang/XSLT/Conways-Game-of-Life new file mode 120000 index 0000000000..77115863d6 --- /dev/null +++ b/Lang/XSLT/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/XSLT \ No newline at end of file diff --git a/Lang/Z80-Assembly/99-Bottles-of-Beer b/Lang/Z80-Assembly/99-Bottles-of-Beer new file mode 120000 index 0000000000..e13024bbe5 --- /dev/null +++ b/Lang/Z80-Assembly/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Z80-Assembly \ No newline at end of file diff --git a/Task/100-doors/C-sharp/100-doors-5.cs b/Task/100-doors/C-sharp/100-doors-5.cs new file mode 100644 index 0000000000..860050e6aa --- /dev/null +++ b/Task/100-doors/C-sharp/100-doors-5.cs @@ -0,0 +1,14 @@ + class Program + { + static void Main(string[] args) + { + bool[] doorStates = new bool[100]; + int n = 0; + int d; + while ((d = (++n * n)) <= 100) + doorStates[d - 1] = true; + for (int i = 0; i < doorStates.Length; i++) + Console.WriteLine("Door {0}: {1}", i + 1, doorStates[i] ? "Open" : "Closed"); + Console.ReadKey(true); + } + } diff --git a/Task/100-doors/C/100-doors-1.c b/Task/100-doors/C/100-doors-1.c index fcee57d070..497dfdbc12 100644 --- a/Task/100-doors/C/100-doors-1.c +++ b/Task/100-doors/C/100-doors-1.c @@ -5,12 +5,12 @@ int main() char is_open[100] = { 0 }; int pass, door; - // do the 100 passes + /* do the 100 passes */ for (pass = 0; pass < 100; ++pass) for (door = pass; door < 100; door += pass+1) is_open[door] = !is_open[door]; - // output the result + /* output the result */ for (door = 0; door < 100; ++door) printf("door #%d is %s.\n", door+1, (is_open[door]? "open" : "closed")); diff --git a/Task/100-doors/C/100-doors-2.c b/Task/100-doors/C/100-doors-2.c index fb7f7feb29..80cf7e1195 100644 --- a/Task/100-doors/C/100-doors-2.c +++ b/Task/100-doors/C/100-doors-2.c @@ -1,19 +1,22 @@ #include -int main() +#define NUM_DOORS 100 + +int main(int argc, char *argv[]) { - int square = 1, increment = 3, door; - for (door = 1; door <= 100; ++door) - { - printf("door #%d", door); - if (door == square) - { - printf(" is open.\n"); - square += increment; - increment += 2; + int is_open[NUM_DOORS] = { 0 } ; + int * doorptr, * doorlimit = is_open + NUM_DOORS ; + int pass ; + + /* do the N passes, go backwards because the order is not important */ + for ( pass= NUM_DOORS ; ( pass ) ; -- pass ) { + for ( doorptr= is_open + ( pass-1 ); ( doorptr < doorlimit ) ; doorptr += pass ) { + ( * doorptr ) ^= 1 ; } - else - printf(" is closed.\n"); } - return 0; + + /* output results */ + for ( doorptr= is_open ; ( doorptr != doorlimit ) ; ++ doorptr ) { + printf("door #%ld is %s\n", ( doorptr - is_open ) + 1, ( * doorptr ) ? "open" : "closed" ) ; + } } diff --git a/Task/100-doors/C/100-doors-3.c b/Task/100-doors/C/100-doors-3.c index a1972a382b..fb7f7feb29 100644 --- a/Task/100-doors/C/100-doors-3.c +++ b/Task/100-doors/C/100-doors-3.c @@ -2,8 +2,18 @@ int main() { - int door, square, increment; - for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2)) - printf("door #%d is %s.\n", door, (door == square? "open" : "closed")); + int square = 1, increment = 3, door; + for (door = 1; door <= 100; ++door) + { + printf("door #%d", door); + if (door == square) + { + printf(" is open.\n"); + square += increment; + increment += 2; + } + else + printf(" is closed.\n"); + } return 0; } diff --git a/Task/100-doors/C/100-doors-4.c b/Task/100-doors/C/100-doors-4.c index 4988099e36..a1972a382b 100644 --- a/Task/100-doors/C/100-doors-4.c +++ b/Task/100-doors/C/100-doors-4.c @@ -2,9 +2,8 @@ int main() { - int i; - for (i = 1; i * i <= 100; i++) - printf("door %d open\n", i * i); - - return 0; + int door, square, increment; + for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2)) + printf("door #%d is %s.\n", door, (door == square? "open" : "closed")); + return 0; } diff --git a/Task/100-doors/C/100-doors-5.c b/Task/100-doors/C/100-doors-5.c new file mode 100644 index 0000000000..4988099e36 --- /dev/null +++ b/Task/100-doors/C/100-doors-5.c @@ -0,0 +1,10 @@ +#include + +int main() +{ + int i; + for (i = 1; i * i <= 100; i++) + printf("door %d open\n", i * i); + + return 0; +} diff --git a/Task/100-doors/COBOL/100-doors.cobol b/Task/100-doors/COBOL/100-doors.cobol index 58095e4ed3..c33e3bb962 100644 --- a/Task/100-doors/COBOL/100-doors.cobol +++ b/Task/100-doors/COBOL/100-doors.cobol @@ -3,7 +3,7 @@ DATA DIVISION. WORKING-STORAGE SECTION. - 01 Current PIC 9(3). + 01 Current-n PIC 9(3). 01 StepSize PIC 9(3). 01 DoorTable. 02 Doors PIC 9(1) OCCURS 100 TIMES. @@ -12,10 +12,11 @@ PROCEDURE DIVISION. Begin. + INITIALIZE DoorTable PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100 - PERFORM VARYING Current FROM StepSize BY StepSize - UNTIL Current > 100 - SUBTRACT Doors (Current) FROM 1 GIVING Doors (Current) + PERFORM VARYING Current-n FROM StepSize BY StepSize + UNTIL Current-n > 100 + SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n) END-PERFORM END-PERFORM diff --git a/Task/100-doors/Deja-Vu/100-doors.djv b/Task/100-doors/Deja-Vu/100-doors.djv new file mode 100644 index 0000000000..31ee854952 --- /dev/null +++ b/Task/100-doors/Deja-Vu/100-doors.djv @@ -0,0 +1,12 @@ +local :open-doors [ rep 101 false ] + +for i range 1 100: + local :j i + while <= j 100: + set-to open-doors j not open-doors! j + set :j + j i + +!print\ "Open doors: " +for i range 1 100: + if open-doors! i: + !print\( to-str i " " ) diff --git a/Task/100-doors/GML/100-doors.gml b/Task/100-doors/GML/100-doors.gml index 4aec96e638..474039e887 100644 --- a/Task/100-doors/GML/100-doors.gml +++ b/Task/100-doors/GML/100-doors.gml @@ -1,28 +1,30 @@ var doors,a,i; //Sets up the array for all of the doors. -for (i=1;i<=100;i+=1) +for (i = 1; i<=100; i += 1) { - doors[i]=0; + doors[i]=0; } + //This first for loop goes through and passes the interval down to the next for loop. -for (i=1;i<=100;i+=1) +for (i = 1; i <= 100; i += 1;) { - //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..) - for (a=0;a<=100;a+=i;) - { - //Opens or closes a door. - doors[a]=!doors[a]; - } + //This for loop opens or closes the doors and uses the interval(if interval is 2 it only uses every other etc..) + for (a = 0; a <= 100; a += i;) + { + //Opens or closes a door. + doors[a] = !doors[a]; + } } -open_doors=''; +open_doors = ''; + //This for loop goes through the array and checks for open doors. //If the door is open it adds it to the string then displays the string. -for (i=1;i<=100;i+=1) +for (i = 1; i <= 100; i += 1;) { - if doors[i]=1 - { - open_doors+="Door Number "+string(i)+" is open#"; - } + if (doors[i] == 1) + { + open_doors += "Door Number "+string(i)+" is open#"; + } } show_message(open_doors); game_end(); diff --git a/Task/100-doors/Io/100-doors.io b/Task/100-doors/Io/100-doors-1.io similarity index 83% rename from Task/100-doors/Io/100-doors.io rename to Task/100-doors/Io/100-doors-1.io index 6ee0ac567f..97df941d40 100644 --- a/Task/100-doors/Io/100-doors.io +++ b/Task/100-doors/Io/100-doors-1.io @@ -1,5 +1,5 @@ doors := List clone -for(i,1,100, doors append(false)) +100 repeat(doors append(false)) for(i,1,100, for(x,i,100, i, doors atPut(x - 1, doors at(x - 1) not)) ) diff --git a/Task/100-doors/Io/100-doors-2.io b/Task/100-doors/Io/100-doors-2.io new file mode 100644 index 0000000000..06069e6232 --- /dev/null +++ b/Task/100-doors/Io/100-doors-2.io @@ -0,0 +1 @@ +(Range 1 to(10) asList) foreach(v, "Door #{v ** 2} is open." interpolate println) diff --git a/Task/100-doors/Ruby/100-doors-2.rb b/Task/100-doors/Ruby/100-doors-2.rb index c52299bd0b..6376d1cd8d 100644 --- a/Task/100-doors/Ruby/100-doors-2.rb +++ b/Task/100-doors/Ruby/100-doors-2.rb @@ -9,10 +9,10 @@ def Closed.toggle end doors = [Closed] * (n + 1) for mul in 1..n - for x in 1..n / mul - doors[mul * x] = doors[mul * x].toggle + for x in (mul..n).step(mul) + doors[x] = doors[x].toggle end end -doors.each_with_index { |b, i| +doors.each_with_index do |b, i| puts "Door #{i} is #{b}" if i > 0 -} +end diff --git a/Task/100-doors/Ruby/100-doors-4.rb b/Task/100-doors/Ruby/100-doors-4.rb index 8c1fff4de4..98bc59f7f1 100644 --- a/Task/100-doors/Ruby/100-doors-4.rb +++ b/Task/100-doors/Ruby/100-doors-4.rb @@ -4,4 +4,4 @@ doors = [false] * 100 doors[j] = !doors[j] end end -puts doors.map.with_index{|d, i| "Door #{i+1} is #{d ? 'open' : 'closed'}."} +puts doors.map.with_index(1){|d,i| "Door #{i} is #{d ? 'open' : 'closed'}."} diff --git a/Task/100-doors/VBA/100-doors.vba b/Task/100-doors/VBA/100-doors.vba new file mode 100644 index 0000000000..d8c760bf4d --- /dev/null +++ b/Task/100-doors/VBA/100-doors.vba @@ -0,0 +1,13 @@ +Sub Rosetta_100Doors() +Dim Door(100) As Boolean, i As Integer, j As Integer +For i = 1 To 100 Step 1 + For j = i To 100 Step i + Door(j) = Not Door(j) + Next j + If Door(i) = True Then + Debug.Print "Door " & i & " is Open" + Else + Debug.Print "Door " & i & " is Closed" + End If +Next i +End Sub diff --git a/Task/24-game-Solve/C/24-game-solve.c b/Task/24-game-Solve/C/24-game-solve.c index 7b7c80864b..c84ec172b8 100644 --- a/Task/24-game-Solve/C/24-game-solve.c +++ b/Task/24-game-Solve/C/24-game-solve.c @@ -7,7 +7,7 @@ #define max_digit 9 typedef struct { int num, denom; } frac_t, *frac; -typedef enum { C_NUM = 0, C_ADD, C_SUB, C_MUL, C_DIV, } op_type; +typedef enum { C_NUM = 0, C_ADD, C_SUB, C_MUL, C_DIV } op_type; typedef struct expr_t *expr; typedef struct expr_t { diff --git a/Task/24-game-Solve/PicoLisp/24-game-solve.l b/Task/24-game-Solve/PicoLisp/24-game-solve.l index dee3526918..ea449caa16 100644 --- a/Task/24-game-Solve/PicoLisp/24-game-solve.l +++ b/Task/24-game-Solve/PicoLisp/24-game-solve.l @@ -6,7 +6,7 @@ (or ((equal @Expr (@Op1 (@Op2 @A @B) (@Op3 @C @D)))) ((equal @Expr (@Op1 @A (@Op2 @B (@Op3 @C @D))))) ) - (@ = 24 (catch '("Div/0") (eval (-> @Expr)))) ) + (^ @ (= 24 (catch '("Div/0") (eval (-> @Expr))))) ) (de play24 (A B C D) # Define PicoLisp function (pilog diff --git a/Task/24-game/00DESCRIPTION b/Task/24-game/00DESCRIPTION index 3affbe40ed..5cb3d944e2 100644 --- a/Task/24-game/00DESCRIPTION +++ b/Task/24-game/00DESCRIPTION @@ -1,6 +1,6 @@ The [[wp:24 Game|24 Game]] tests one's mental arithmetic. -Write a program that [[task feature::Rosetta Code:randomness|randomly]] chooses and [[task feature::Rosetta Code:user output|displays]] four digits, each from one to nine, with repetitions allowed. The program should prompt for the player to enter an equation using ''just'' those, and ''all'' of those four digits. The program should ''check'' then [[task feature::Rosetta Code:parsing|evaluate the expression]]. The goal is for the player to [[task feature::Rosetta Code:user input|enter]] an expression that evaluates to '''24'''. +Write a program that [[task feature::Rosetta Code:randomness|randomly]] chooses and [[task feature::Rosetta Code:user output|displays]] four digits, each from one to nine, with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits. The program should ''check'' then [[task feature::Rosetta Code:parsing|evaluate the expression]]. The goal is for the player to [[task feature::Rosetta Code:user input|enter]] an expression that evaluates to '''24'''. * Only multiplication, division, addition, and subtraction operators/functions are allowed. * Division should use floating point or rational arithmetic, etc, to preserve remainders. * Brackets are allowed, if using an infix expression evaluator. diff --git a/Task/24-game/C/24-game.c b/Task/24-game/C/24-game.c index f88ca6fc0e..b1672e5f61 100644 --- a/Task/24-game/C/24-game.c +++ b/Task/24-game/C/24-game.c @@ -1,9 +1,10 @@ #include #include #include -#include +#include +#include -ucontext_t ctx; +jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; @@ -49,7 +50,7 @@ void reset() void bail(const char *s) { msg = s; - setcontext(&ctx); + longjmp(ctx, 1); } expr new_expr() @@ -256,7 +257,7 @@ int main() gen_digits(); while(1) { get_input(); - getcontext(&ctx); /* if parse error, jump back here with err msg set */ + setjmp(ctx); /* if parse error, jump back here with err msg set */ if (msg) { /* after error jump; announce, reset, redo */ printf("%s at '%.*s'\n", msg, pos, str); diff --git a/Task/24-game/Fortran/24-game.f b/Task/24-game/Fortran/24-game-1.f similarity index 100% rename from Task/24-game/Fortran/24-game.f rename to Task/24-game/Fortran/24-game-1.f diff --git a/Task/24-game/Fortran/24-game-2.f b/Task/24-game/Fortran/24-game-2.f new file mode 100644 index 0000000000..cae863449d --- /dev/null +++ b/Task/24-game/Fortran/24-game-2.f @@ -0,0 +1,210 @@ +! implement a recursive descent parser +module evaluate_algebraic_expression + + integer, parameter :: size = 124 + character, parameter :: statement_end = achar(0) + character(len=size) :: text_to_parse + integer :: position + data position/0/,text_to_parse/' '/ + +contains + + character function get_token() + ! return the current token + implicit none + if (position <= size) then + get_token = text_to_parse(position:position) + do while (get_token <= ' ') + call advance + if (size < position) exit + get_token = text_to_parse(position:position) + end do + end if + if (size < position) get_token = statement_end + end function get_token + + subroutine advance ! consume a token. Move to the next token. consume_token would have been a better name. + position = position + 1 + end subroutine advance + + logical function unfinished() + unfinished = get_token() /= statement_end + end function unfinished + + subroutine parse_error() + write(6,*)'"'//get_token()//'" unexpected in expression at',position + stop 1 + end subroutine parse_error + + function precedence3() result(a) + implicit none + real :: a + character :: token + character(len=10), parameter :: digits = '0123456789' + token = get_token() + if (verify(token,digits) /= 0) call parse_error() + a = index(digits, token) - 1 + call advance() + end function precedence3 + + recursive function precedence2() result(a) + real :: a + character :: token + token = get_token() + if (token /= '(') then + a = precedence3() + else + call advance + a = precedence0() + token = get_token() + if (token /= ')') call parse_error() + call advance + end if + end function precedence2 + + recursive function precedence1() result(a) + implicit none + real :: a + real, dimension(2) :: argument + character(len=2), parameter :: tokens = '*/' + character :: token + a = 0 + token = get_token() + argument(1) = precedence2() + token = get_token() + do while (verify(token,tokens) == 0) + call advance() + argument(2) = precedence2() + if (token == '/') argument(2) = 1 / argument(2) + argument(1) = product(argument) + token = get_token() + end do + a = argument(1) + end function precedence1 + + recursive function precedence0() result(a) + implicit none + real :: a + real, dimension(2) :: argument + character(len=2), parameter :: tokens = '+-' + character :: token + a = 0 + token = get_token() + argument(1) = precedence1() + token = get_token() + do while (verify(token,tokens) == 0) + call advance() + argument(2) = precedence1() + if (token == '-') argument = argument * (/1, -1/) + argument(1) = sum(argument) + token = get_token() + end do + a = argument(1) + end function precedence0 + + real function statement() + implicit none + if (unfinished()) then + statement = precedence0() + else !empty okay + statement = 0 + end if + if (unfinished()) call parse_error() + end function statement + + real function evaluate(expression) + implicit none + character(len=*), intent(in) :: expression + text_to_parse = expression + evaluate = statement() + end function evaluate + +end module evaluate_algebraic_expression + + +program g24 + use evaluate_algebraic_expression + implicit none + integer, dimension(4) :: digits + character(len=78) :: expression + real :: result + ! integer :: i + call random_seed!easily found internet examples exist to seed by /dev/urandom or time + call deal(digits) + ! do i=1, 9999 ! produce the data to test digit distribution + ! call deal(digits) + ! write(6,*) digits + ! end do + write(6,'(a13,4i2,a26)')'Using digits',digits,', and the algebraic dyadic' + write(6,*)'operators +-*/() enter an expression computing 24.' + expression = ' ' + read(5,'(a78)') expression + if (invalid_digits(expression, digits)) then + write(6,*)'invalid digits' + else + result = evaluate(expression) + if (nint(result) == 24) then + write(6,*) result, ' close enough' + else + write(6,*) result, ' no good' + end if + end if + +contains + + logical function invalid_digits(e,d) !verify the digits + implicit none + character(len=*), intent(in) :: e + integer, dimension(4), intent(inout) :: d + integer :: i, j, k, count + logical :: unfound + count = 0 + invalid_digits = .false. !validity assumed + !write(6,*)'expression:',e(1:len_trim(e)) + do i=1, len_trim(e) + if (verify(e(i:i),'0123456789') == 0) then + j = index('0123456789',e(i:i))-1 + unfound = .true. + do k=1, 4 + if (j == d(k)) then + unfound = .false. + exit + end if + end do + if (unfound) then + invalid_digits = .true. + !return or exit is okay here + else + d(k) = -99 + count = count + 1 + end if + end if + end do + invalid_digits = invalid_digits .or. (count /= 4) + end function invalid_digits + + subroutine deal(digits) + implicit none + integer, dimension(4), intent(out) :: digits + integer :: i + real :: harvest + call random_number(harvest) + do i=1, 4 + digits(i) = int(mod(harvest*9**i, 9.0)) + 1 + end do + ! NB. computed with executable Iverson notation, www.jsoftware.oom + ! #B NB. B are the digits from 9999 deals + ! 39996 + ! ({.,#)/.~/:~B # show the distribution of digits + ! 0 4380 + ! 1 4542 + ! 2 4348 + ! 3 4395 + ! 4 4451 + ! 5 4474 + ! 6 4467 + ! 7 4413 + ! 8 4526 + ! NB. this also shows that I forgot to add 1. Inserting now... + end subroutine deal +end program g24 diff --git a/Task/24-game/REXX/24-game-1.rexx b/Task/24-game/REXX/24-game-1.rexx index b1c8c38251..1e72c6f878 100644 --- a/Task/24-game/REXX/24-game-1.rexx +++ b/Task/24-game/REXX/24-game-1.rexx @@ -33,116 +33,105 @@ Rpar=')' /*ditto. */ show=1 /*flag used show solutions (0 = not). */ digs=123456789 /*numerals (digits) that can be used. */ - do j=1 for ops /*define a version for fast execution. */ + do j=1 for ops /*define a version for fast execution. */ o.j=substr(opers,j,1) end /*j*/ if orig\=='' then do sols=solve(start,finish) - if sols<0 then exit 13 - if sols==0 then sols='No' /*un-geek SOLS.*/ - say - say sols 'unique solution's(finds) "found for" orig /*pluralize.*/ - exit + if sols<0 then exit 13 + if sols==0 then sols='No' /*un-geek the SOLS var.*/ + say; say sols 'unique solution's(finds) "found for" orig + exit /* [↑] "S" pluralizes.*/ end show=0 /*stop SOLVE from blabbing solutions. */ - do forever + do forever rrrr=random(1111,9999) - if pos(0,rrrr)\==0 then iterate - if solve(rrrr)\==0 then leave - end + if pos(0,rrrr)\==0 then iterate + if solve(rrrr)\==0 then leave + end /*forever*/ show=1 /*enable SOLVE to show solutions. */ rrrr=sort(rrrr) /*sort four elements. */ rd.=0 - do j=1 for 9 /*digit count # for each digit in RRRR.*/ + do j=1 for 9 /*digit count # for each digit in RRRR.*/ _=substr(rrrr,j,1) rd._=countdigs(rrrr,_) end /*j*/ do guesses=1; say - say 'Using the digits', - rrrr", enter an expression that equals 24 (or QUIT):" - pull y - y=space(y,0); if y=='QUIT' then exit - _v=verify(y,digs||opers||groupsymbols) - if _v\==0 then do - call ger 'invalid character:' substr(_v,1) - iterate - end - yl=length(y) - if y='' then do - call validate y - iterate - end + say 'Using the digits' rrrr", enter an expression that equals 24 (or QUIT):" + pull y; y=space(y,0) /*get Y from CL, then remove all blanks*/ + if y=='QUIT' then exit /*Does user want to quit? If so, exit.*/ + _v=verify(y, digs || opers || groupsymbols); __=substr(y, _v, 1) + if _v\==0 then do; call ger 'invalid character:' __; iterate; end + if pos('**',y) then do; call ger 'invalid ** operator'; iterate; end + if pos('//',y) then do; call ger 'invalid // operator'; iterate; end + yL=length(y) + if y=='' then do; call validate y; iterate; end - do j=1 to yl-1 - _=substr(y,j,1) - if \datatype(_,'W') then iterate - _=substr(y,j+1,1) - if datatype(_,'W') then do - call ger 'invalid use of digit abuttal' - iterate guesses - end + do j=1 for yL-1; if \datatype(substr(y, j , 1), 'W') then iterate + if \datatype(substr(y, j+1, 1), 'W') then iterate + call ger 'invalid use of digit abuttal' + iterate guesses end /*j*/ yd=countdigs(y,digs) /*count of digits 123456789.*/ - if yd<4 then do - call ger 'not enough digits entered.' - iterate guesses - end - if yd>4 then do - call ger 'too many digits entered.' - iterate guesses - end + if yd<4 then do + call ger 'not enough digits entered.' + iterate guesses + end + if yd>4 then do + call ger 'too many digits entered.' + iterate guesses + end - do j=1 for 9; if rd.j==0 then iterate + do j=1 for 9; if rd.j==0 then iterate _d=countdigs(y,j) - if _d==rd.j then iterate - if _d /div(yyy) */ /*Enables to check for division by zero*/ origE=e /*keep old version for the display. */ - if pos('/(',e)\==0 then e=changestr('/(',e,"/div(") + if pos('/(',e)\==0 then e=changestr('/(',e,"/div(") /*The above could be replaced by: */ /* e=changestr('/(',e,"/div(") */ /*INTERPRET stresses REXX's groin, */ /*so try to avoid repeated lifting. */ - if x.e then iterate /*was the expression already used? */ + if x.e then iterate /*was the expression already used? */ x.e=1 /*mark this expression as unique. */ /*have REXX do the heavy lifting. */ interpret 'x=' e x=x/1 /*remove trailing decimal points. */ - if x\==24 then iterate /*Not correct? Try again.*/ + if x\==24 then iterate /*Not correct? Try again.*/ finds=finds+1 /*bump number of found solutions. */ - _=translate(origE,'][',")(") /*show [], not ().*/ - if show then say indent 'a solution:' _ /*show solution*/ + _=translate(origE, '][', ")(") /*show [], not ().*/ + if show then say indent 'a solution:' _ /*show solution.*/ end /*n*/ end /*m*/ end /*k*/ @@ -173,27 +162,30 @@ x.=0 /*a method to hold unique expressions. */ end /*g*/ return finds +/*───────────────────────────CHANGESTR subroutine───────────────────────*/ +changestr: procedure; parse arg o,h,n,,r; w=length(o); if w==0 then return n||h +do forever; parse var h y (o) _ +(w) h; if _=='' then return r||y; r=r||y||n; end /*───────────────────────────COUNTDIGS subroutine───────────────────────*/ countdigs: arg field,numerals /*count of digits NUMERALS.*/ return length(field)-length(space(translate(field,,numerals),0)) /*───────────────────────────DIV subroutine─────────────────────────────*/ div: procedure; parse arg q /*tests if dividing by 0 (zero). */ -if q=0 then q=1e9 /*if dividing by zero, change divisor. */ +if q=0 then q=1e9 /*if dividing by zero, change divisor. */ return q /*changing Q invalidates the expression*/ /*───────────────────────────GER subroutine─────────────────────────────*/ ger: say; say '*** error! *** for argument:' y; say arg(1); say; errCode=1; return 0 /*───────────────────────────S subroutine───────────────────────────────*/ -s: if arg(1)==1 then return ''; return 's' /*simple pluralizer.*/ +s: if arg(1)==1 then return ''; return 's' /*simple pluralizer.*/ /*───────────────────────────SORT subroutine────────────────────────────*/ sort: procedure; arg nnnn; L=length(nnnn) - do i=1 for L /*build an array of digits from NNNN.*/ + do i=1 for L /*build an array of digits from NNNN.*/ a.i=substr(nnnn,i,1) /*this enables SORT to sort an array. */ end /*i*/ - do j=1 for L; _=a.j - do k=j+1 to L - if a.k<_ then parse value a.j a.k with a.k a.j + do j=1 for L; _=a.j + do k=j+1 to L + if a.k<_ then parse value a.j a.k with a.k a.j end /*k*/ end /*j*/ return a.1 || a.2 || a.3 || a.4 diff --git a/Task/24-game/VBA/24-game.vba b/Task/24-game/VBA/24-game.vba new file mode 100644 index 0000000000..6488f4c033 --- /dev/null +++ b/Task/24-game/VBA/24-game.vba @@ -0,0 +1,122 @@ +Sub Rosetta_24game() + +Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer +Dim stUserExpression As String +Dim stFailMessage As String, stFailDigits As String +Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean +Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant + +' Generate 4 random digits +GenerateNewDigits: + For i = 1 To 4 + Digit(i) = [randbetween(1,9)] + Next i + +' Get user expression +GetUserExpression: + bValidExpression = True + stFailMessage = "" + stFailDigits = "" + stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ + Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") + +' Check each digit is included in user expression + bValidDigits = True + stFailDigits = "" + For i = 1 To 4 + If InStr(stUserExpression, Digit(i)) = 0 Then + bValidDigits = False + stFailDigits = stFailDigits & " " & Digit(i) + End If + Next i + If bValidDigits = False Then + bValidExpression = False + stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr + End If + +' Check each character of user expression is a valid character type + bValidDigits = True + stFailDigits = "" + For i = 1 To Len(stUserExpression) + If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then + bValidDigits = False + stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) + End If + Next i + If bValidDigits = False Then + bValidExpression = False + stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr + End If + +' Check no disallowed integers entered + bValidDigits = True + stFailDigits = "" + iDigitCount = 0 + For i = 1 To Len(stUserExpression) + If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then + iDigitCount = iDigitCount + 1 + If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then + bValidDigits = False + stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) + End If + End If + Next i + If iDigitCount > 4 Then + bValidExpression = False + stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr + End If + If iDigitCount < 4 Then + bValidExpression = False + stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr + End If + If bValidDigits = False Then + bValidExpression = False + stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr + End If + +' Check no double digit numbers entered + bValidDigits = True + stFailDigits = "" + For i = 11 To 99 + If Not InStr(stUserExpression, i) = 0 Then + bValidDigits = False + stFailDigits = stFailDigits & " " & i + End If + Next i + If bValidDigits = False Then + bValidExpression = False + stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr + End If + +' Check result of user expression + On Error GoTo EvalFail + vResult = Evaluate(stUserExpression) + If Not vResult = 24 Then + bValidExpression = False + stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult + End If + +' Return results + If bValidExpression = False Then + vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") + If vTryAgain = vbRetry Then + vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") + If vSameDigits = vbYes Then + GoTo GetUserExpression + Else + GoTo GenerateNewDigits + End If + End If + Else + vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ + vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") + If vTryAgain = vbRetry Then + GoTo GenerateNewDigits + End If + End If + Exit Sub +EvalFail: + bValidExpression = False + vResult = Err.Description + Resume +End Sub diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-10.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-10.basic new file mode 100644 index 0000000000..5dffeed1a5 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-10.basic @@ -0,0 +1,13 @@ +For bottles = 99 To 1 Step -1 + song$ = song$ + str$(bottles) + " bottle" + If (bottles > 1) Then song$ = song$ + "s" + song$ = song$ + " of beer on the wall, " + str$(bottles) + " bottle" + If (bottles > 1) Then song$ = song$ + "s" + song$ = song$ + " of beer," + chr$(13) + chr$(10) + "Take one down, pass it around, " + str$(bottles - 1) + " bottle" + If (bottles > 2) Or (bottles = 1) Then song$ = song$ + "s" + song$ = song$ + " of beer on the wall." + chr$(13) + chr$(10) +Next bottles +song$ = song$ + "No more bottles of beer on the wall, no more bottles of beer." _ + + chr$(13) + chr$(10) + "Go to the store and buy some more, 99 bottles of beer on the wall." + +Print song$ diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-11.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-11.basic new file mode 100644 index 0000000000..b1c205e835 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-11.basic @@ -0,0 +1,13 @@ +If OpenConsole() + Define Bottles=99 + While Bottles + PrintN(Str(Bottles)+" bottles of beer on the wall") + PrintN(Str(Bottles)+" bottles of beer") + PrintN("Take one down, pass it around") + Bottles-1 + PrintN(Str(Bottles)+" bottles of beer on the wall"+#CRLF$) + Wend + + PrintN(#CRLF$+#CRLF$+"Press ENTER to exit"):Input() + CloseConsole() +EndIf diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-12.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-12.basic new file mode 100644 index 0000000000..3e437bb017 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-12.basic @@ -0,0 +1,59 @@ +Prototype Wall_Action(*Self, Number.i) + +Structure WallClass + Inventory.i + AddBottle.Wall_Action + DrinkAndSing.Wall_Action +EndStructure + +Procedure.s _B(n, Short=#False) + Select n + Case 0 : result$="No more bottles " + Case 1 : result$=Str(n)+" bottle of beer" + Default: result$=Str(n)+" bottles of beer" + EndSelect + If Not Short: result$+" on the wall": EndIf + ProcedureReturn result$+#CRLF$ +EndProcedure + +Procedure PrintBottles(*Self.WallClass, n) + Bottles$=" bottles of beer " + Bottle$ =" bottle of beer " + txt$ = _B(*Self\Inventory) + txt$ + _B(*Self\Inventory, #True) + txt$ + "Take one down, pass it around"+#CRLF$ + *Self\AddBottle(*Self, -1) + txt$ + _B(*self\Inventory) + PrintN(txt$) + ProcedureReturn *Self\Inventory +EndProcedure + +Procedure AddBottle(*Self.WallClass, n) + i=*Self\Inventory+n + If i>=0 + *Self\Inventory=i + EndIf +EndProcedure + +Procedure InitClass() + *class.WallClass=AllocateMemory(SizeOf(WallClass)) + If *class + InitializeStructure(*class, WallClass) + With *class + \AddBottle =@AddBottle() + \DrinkAndSing =@PrintBottles() + EndWith + EndIf + ProcedureReturn *class +EndProcedure + +If OpenConsole() + *MyWall.WallClass=InitClass() + If *MyWall + *MyWall\AddBottle(*MyWall, 99) + While *MyWall\DrinkAndSing(*MyWall, #True): Wend + ; + PrintN(#CRLF$+#CRLF$+"Press ENTER to exit"):Input() + CloseConsole() + EndIf +EndIf diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-13.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-13.basic new file mode 100644 index 0000000000..97a23b973b --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-13.basic @@ -0,0 +1,8 @@ +dim bottles as Integer = 99 +While bottles > 0 + Print(str(bottles) + " bottles of beer on the wall") + Print(str(bottles) + " bottles of beer") + Print("Take one down, pass it around") + bottles = bottles - 1 + Print(str(bottles) + " bottles of beer on the wall") +Wend diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-14.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-14.basic new file mode 100644 index 0000000000..fdbfabe74e --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-14.basic @@ -0,0 +1,12 @@ +b$ = " bottles" +for bottles = 99 To 1 Step -1 + If (bottles = 1) then b$ = " bottle" + print bottles;b$;" of beer on the wall, " + print bottles ;b$;" of beer" + print "Take one down, pass it around, " + if bottles = 1 then + print "No bottles of beer on the wall" + else + print bottles - 1;b$;" of beer on the wall.";chr$(10) + end if +next bottles diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-15.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-15.basic new file mode 100644 index 0000000000..cca30e2823 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-15.basic @@ -0,0 +1,13 @@ +PROGRAM:BEER +:For(I,99,1,-1) +:Disp I +:Disp "BOTTLES OF BEER" +:Disp "ON THE WALL," +:Disp I +:Pause "BOTTLES OF BEER," +:Disp "TAKE ONE DOWN," +:Disp "PASS IT AROUND," +:Disp I-1 +:Disp "BOTTLES OF BEER" +:Disp "ON THE WALL." +:End diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-16.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-16.basic new file mode 100644 index 0000000000..be967a6f9c --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-16.basic @@ -0,0 +1,47 @@ +Prgm + Local i,plural,clockWas,t,k,wait + "s" → plural + 0 → k + isClkOn() → clockWas + + Define wait() = Prgm + EndPrgm + + ClockOn + + For i,99,0,–1 + Disp "" + Disp string(i) & " bottle" & plural & " of beer on the" + Disp "wall, " & string(i) & " bottle" & plural & " of beer." + + getTime()[3]→t + While getTime()[3] = t and k = 0 : getKey() → k : EndWhile + If k ≠ 0 Then : Exit : EndIf + + Disp "Take one down, pass it" + Disp "around." + + getTime()[3]→t + While getTime()[3] = t and k = 0 : getKey() → k : EndWhile + If k ≠ 0 Then : Exit : EndIf + + If i - 1 = 1 Then + "" → plural + EndIf + If i > 1 Then + Disp string(i-1) & " bottle" & plural & " of beer on the" + Disp "wall." + Else + Disp "No more bottles of beer on" + Disp "the wall." + EndIf + + getTime()[3]→t + While abs(getTime()[3] - t)<2 and k = 0 : getKey() → k : EndWhile + If k ≠ 0 Then : Exit : EndIf + + EndFor + If not clockWas Then + ClockOff + ENdIf +EndPrgm diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-17.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-17.basic new file mode 100644 index 0000000000..65e32dce45 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-17.basic @@ -0,0 +1,33 @@ +Sub Main() + Const bottlesofbeer As String = " bottles of beer" + Const onthewall As String = " on the wall" + Const takeonedown As String = "Take one down, pass it around" + Const onebeer As String = "1 bottle of beer" + + Dim bottles As Long + + For bottles = 99 To 3 Step -1 + Debug.Print CStr(bottles) & bottlesofbeer & onthewall + Debug.Print CStr(bottles) & bottlesofbeer + Debug.Print takeonedown + Debug.Print CStr(bottles - 1) & bottlesofbeer & onthewall + Debug.Print + Next + + Debug.Print "2" & bottlesofbeer & onthewall + Debug.Print "2" & bottlesofbeer + Debug.Print takeonedown + Debug.Print onebeer & onthewall + Debug.Print + + Debug.Print onebeer & onthewall + Debug.Print onebeer + Debug.Print takeonedown + Debug.Print "No more" & bottlesofbeer & onthewall + Debug.Print + + Debug.Print "No" & bottlesofbeer & onthewall + Debug.Print "No" & bottlesofbeer + Debug.Print "Go to the store, buy some more" + Debug.Print "99" & bottlesofbeer & onthewall +End Sub diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-18.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-18.basic new file mode 100644 index 0000000000..e1b3ae76fe --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-18.basic @@ -0,0 +1,20 @@ +Module Module1 + Sub Main() + Dim Bottles As Integer + For Bottles = 99 To 0 Step -1 + If Bottles = 0 Then + Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.") + Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.") + Console.ReadLine() + ElseIf Bottles = 1 Then + Console.WriteLine(Bottles & " bottle of beer on the wall, " & Bottles & " bottle of beer.") + Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall.") + Console.ReadLine() + Else + Console.WriteLine(Bottles & " bottles of beer on the wall, " & Bottles & " bottles of beer.") + Console.WriteLine("Take one down and pass it around, " & (Bottles - 1) & " bottles of beer on the wall.") + Console.ReadLine() + End If + Next + End Sub +End Module diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-3.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-3.basic new file mode 100644 index 0000000000..431466059b --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-3.basic @@ -0,0 +1,7 @@ +10 HOME +20 FOR B=99 TO 1 STEP -1 +30 PRINT B;" BOTTLE OF BEER ON THE WALL" +40 PRINT B;" BOTTLE OF BEER ON THE WALL" +50 PRINT "TAKE ONE DOWN, PASS IT AROUND" +60 PRINT B-1;" BOTTLE OF BEER ON THE WALL" +70 NEXT B diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-4.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-4.basic new file mode 100644 index 0000000000..795e9dcabd --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-4.basic @@ -0,0 +1,33 @@ +#length of querter and eight note in ms +n4 = 1000 * 60 / 80 / 4 +n8 = n4 / 2 + +#frequency of musical notes in hz +e = 330 +ef = 311 +b = 247 +bf = 233 +f = 349 +c = 262 +d = 294 +ds = 311 +a = 220 + +dim notes(1) +dim lengs(1) + +# redim is automatic when using a {} list to assign an array +notes = {ef, ef, ef, bf, bf, bf, ef, ef, ef, ef, f , f , f , c , c , c , f , d , d , d , d , d , d , d , bf, bf, bf, c , c , ef, ef, ef, ef, ef} +lengs = {n8, n8, n8, n8, n8, n8, n8, n8, n8, n4, n8, n8, n8, n8, n8, n8, n4, n4, n8, n8, n8, n8, n8, n4, n8, n8, n8, n8, n8, n8, n8, n8, n8, n4 } + +for x = 99 to 1 step -1 + for t = 0 to notes[?]-1 + if t = 0 then print x + " bottles of beer on the wall" + if t = 11 then print x + " bottles of beer" + if t = 18 then print "Take one down, pass it around" + if t = 25 then print(x-1) + " bottles of beer on the wall" + sound notes[t], lengs[t] + pause .002 + next t + print +next x diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-5.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-5.basic new file mode 100644 index 0000000000..f55119ce84 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-5.basic @@ -0,0 +1,32 @@ + N_Bottles = 99 + + beer$ = " of beer" + wall$ = " on the wall" + unit$ = "99 bottles" + + WHILE N_Bottles >= 0 + + IF N_Bottles=0 THEN + PRINT '"No more bottles" beer$ wall$ ", " unit$ beer$ "." + PRINT "Go to the store and buy some more, "; + ELSE + PRINT 'unit$ beer$ wall$ ", " unit$ beer$ "." + PRINT "Take one down and pass it around, "; + ENDIF + + N_Bottles -= 1 + + CASE N_Bottles OF + WHEN 0: + unit$ = "no more bottles" + WHEN 1: + unit$ = "1 bottle" + OTHERWISE: + unit$ = STR$((N_Bottles + 100) MOD 100) + " bottles" + ENDCASE + + PRINT unit$ beer$ wall$ "." + + ENDWHILE + + END diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-6.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-6.basic new file mode 100644 index 0000000000..e0e0202adf --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-6.basic @@ -0,0 +1,142 @@ +DEF Win:WINDOW +DEF Close:CHAR +DEF ScreenSizeX,ScreenSizeY:INT + +DECLARE VSpace(Number:UINT) +DECLARE CLR() + +DEF TheLine$[4],Number$,Erase:STRING +DEF TheLine,TextHeight,TextWidth:INT +DEF TextX,TextY:UINT + +TheLine$[0]="bottles" +TheLine$[1]="of beer on the wall." +TheLine$[2]="of beer." +TheLine$[3]="Take one down, pass it around." + +BottlesOfBeer=99 +TheLine=1 + +GETSCREENSIZE(ScreenSizeX,ScreenSizeY) + +WINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MINBOX|@MAXBOX|@SIZE,0,"99 Bottles Of Beer",MainHandler + +GETTEXTSIZE(Win,TheLine$[3],TextWidth,TextHeight) + +Erase$=STRING$(TextWidth," ") + +PRINT Win,"Let's sing a song." + +VSpace(2) + +'1.2 seconds. +STARTTIMER Win,1200 + +GOSUB Sing + +WAITUNTIL Close=1 + +CLOSEWINDOW Win + +END + +SUB MainHandler + + SELECT @CLASS + + CASE @IDCLOSEWINDOW + + Close=1 + + CASE @IDTIMER + + GOSUB Sing + + ENDSELECT + +RETURN + +SUB Sing + + DEF Sing:INT + + Sing=TheLine + + MOVE Win,TextX,TextY + + Number$=STR$(BottlesOfBeer) + + IF BottlesOfBeer=0 + + Number$="No more" + TheLine$[0]="bottles" + TheLine$[3]="Go to the store and buy some more." + + ENDIF + + IF BottlesOfBeer=1 + + TheLine$[0]="bottle" + TheLine$[3]="Take it down, pass it around." + + ENDIF + + IF TheLine=4 THEN Sing=1 + + IF (TheLine=1)|(TheLine=2)|(TheLine=4) + + IF BottlesOfBeer>-1 THEN PRINT Win,Number$+" "+TheLine$[0]+" "+TheLine$[Sing] ELSE GOSUB TheEnd + + ELSE + + PRINT Win,TheLine$[3] + + BottlesOfBeer=BottlesOfBeer-1 + + ENDIF + + TheLine=TheLine+1 + + VSpace(1) + + IF TheLine>4 + + TheLine=1 + + VSpace(1) + + ENDIF + +RETURN + +SUB TheEnd + + PRINT Win,"What's the problem, offishur?" + + STOPTIMER Win + + VSpace(2) + + MOVE Win,TextX,TextY:PRINT Win,"That's all." + +RETURN + +SUB VSpace(Number:UINT) + + TextY=TextY+(TextHeight*Number) + + IF TextY+(TextHeight*8)>ScreenSizeY THEN CLR() + +RETURN + +SUB CLR() + + FOR X=0 TO ScreenSizeY + + MOVE Win,0,X:PRINT Win,Erase$ + + TextY=8 + + NEXT X + +RETURN diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-7.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-7.basic new file mode 100644 index 0000000000..f0cead4e91 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-7.basic @@ -0,0 +1,111 @@ +REM Using the ESC key to exit will not work in console programs under Windows 95/98 or ME. + +DECLARE SingWallLn() +DECLARE Delay1() +DECLARE Delay2() +'To use ESC Key to exit. +DECLARE Quit() +DECLARE TheEnd() + +DEF Bottles:UINT +DEF Number$,Again$:STRING + +OPENCONSOLE + +PRINT"I'm going to sing a song.":PRINT + +Delay1() + +LABEL StartSong + +Bottles=99 + +DO + Quit() + + SingWallLn():Delay1() + + PRINT LTRIM$(STR$(Bottles))+Number$+" of beer.":Delay1() + + IF Bottles>0 THEN PRINT"Take one down, pass it around." ELSE PRINT"Take it down, pass it around.":Delay1() + + Bottles=Bottles-1 + + SingWallLn() + + Delay2() + +PRINT:PRINT + +UNTIL Bottles=0 + +Delay2() + +ClS + +LABEL Question + +INPUT"Sing it again (y or n)?",Again$ + +SELECT Again$ + + CASE("y") + CASE("Y") + + CLS + + GOTO StartSong + + CASE "n" + CASE "N" + + CLS + + PRINT"Fine, be that way.":Delay2() + + TheEnd() + +ENDSELECT + +PRINT"Sorry, I didn't understand.":PRINT + +GOTO Question + +'Keep from running into subroutines. +END + +SUB SingWallLn() + + IF Bottles=1 THEN Number$=" bottle" ELSE Number$=" bottles" + + PRINT LTRIM$(STR$(Bottles))+Number$+" of beer on the wall." + +RETURN + +SUB Delay1() + + FOR X=1 TO 7000:NEXT X + +RETURN + +SUB Delay2() + + FOR X=1 TO 1750000:NEXT X + +RETURN + +SUB Quit() + + 'Close program by pressing the ESC key. + 'Will not work in console under Windows 95/98 or ME. + IF GETKEYSTATE(0x1B) THEN TheEnd() + +RETURN + +SUB TheEnd() + + CLOSECONSOLE + + END + +RETURN diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-8.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-8.basic new file mode 100644 index 0000000000..3cefee652c --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-8.basic @@ -0,0 +1,60 @@ +#AppType Console + +Class Wall + bottles + + Sub Initialize(%n = 99) + bottles = n + End Sub + + Method Denom() + if bottles+1 > 1 then + return "one" + elseif bottles+1 = 1 then + return "it" + end if + End Method + + Method StockUp( %n = 99 ) + bottles = n + End Method + + Method TakeOneDown() + bottles = bottles - 1 + end Method + + Method Pluraliser() + if bottles > 1 then + return "s" + else + return "" + end if + end method + + Method Sing() + print bottles, " bottle", Pluraliser(), " of beer on the wall" + print bottles, " bottle", Pluraliser(), " of beer" + TakeOneDown() + print "take ", Denom(), " down and pass it round" + if bottles > 0 then + print bottles, " bottle", Pluraliser(), " of beer on the wall" + print + else + print "no more bottles of beer on the wall" + print + print "no more bottles of beer on the wall" + print "no more bottles of beer on the wall" + print "go to the store and buy some more" + StockUp(99) + print bottles, " bottle", Pluraliser(), " of beer on the wall" + print + end if + return bottles + End Method + +End Class + +Dim BeerSong as new Wall(99) + +while BeerSong.Sing() <> 99 +end while diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-9.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-9.basic new file mode 100644 index 0000000000..2e743c2ed3 --- /dev/null +++ b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-9.basic @@ -0,0 +1,28 @@ +E000G (APPLE II) +E000R (APPLE I) +10 REM ------------------------- +11 REM BEERSONG IN APPLE INTEGER +12 REM BASIC BY BARRYM 2011-8-21 +13 REM THANKS : APPLEWIN1.17.2.0 +14 REM THANKS ALSO : POM1 0.7B +15 REM ------------------------- +16 REM PRINTS THE COMPLETE UPPER +17 REM CASE LYRICS ON AN APPLE I +18 REM OR AN 'ORIGINAL' APPLE II +19 REM WITH WOZ'S INTEGER BASIC. +20 REM ------------------------- +21 REM THIS BASIC HAS AN UNUSUAL +22 REM 'THEN', WHICH EXECUTES OR +23 REM SKIPS ONE (AND ONLY ONE!) +24 REM STATEMENT. THIS CONFUSED +25 REM US KIDS REGULARLY WHEN WE +26 REM TRIED TRANSLATING INTEGER +27 REM BASIC GAMES TO APPLE$OFT! +30 REM ------------------------- +40 FOR B=99 TO 98 STEP 0: PRINT : FOR W=0 TO 2: IF W<2 THEN 70 +50 IF B THEN PRINT "TAKE ONE DOWN AND PASS IT AROUND";:B=B-1 +60 IF B+1 THEN 70:B=99: PRINT "GO TO THE STORE AND BUY SOME MORE"; +70 IF W THEN PRINT ",": IF B THEN PRINT B;: IF B=0 THEN PRINT "NO MORE"; +80 PRINT " BOTTLE";: IF B#1 THEN PRINT "S";: PRINT " OF BEER"; +90 IF W#1 THEN PRINT " ON THE WALL";: IF W THEN PRINT ".": NEXT W,B: END +RUN diff --git a/Task/99-Bottles-of-Beer/C++/99-bottles-of-beer-1.cpp b/Task/99-Bottles-of-Beer/C++/99-bottles-of-beer-1.cpp index f69026e06f..840ad12627 100644 --- a/Task/99-Bottles-of-Beer/C++/99-bottles-of-beer-1.cpp +++ b/Task/99-Bottles-of-Beer/C++/99-bottles-of-beer-1.cpp @@ -1,13 +1,12 @@ #include -using namespace std; +using std::cout; int main() { - int bottles = 99; - do { - cout << bottles << " bottles of beer on the wall" << endl; - cout << bottles << " bottles of beer" << endl; - cout << "Take one down, pass it around" << endl; - cout << --bottles << " bottles of beer on the wall\n" << endl; - } while (bottles > 0); + for(int bottles(99); bottles > 0; bottles -= 1){ + cout << bottles << " bottles of beer on the wall\n" + << bottles << " bottles of beer\n" + << "Take one down, pass it around\n" + << bottles - 1 << " bottles of beer on the wall\n\n"; + } } diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs index df76d8ce8e..47b6a7bc2d 100644 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs +++ b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs @@ -1,28 +1,39 @@ -class songs -{ - static void Main(string[] args) + class Program { - beer(5); - } + const string Vessel = "bottle"; + const string Beverage = "beer"; + const string Location = "on the wall"; - private static void beer(int bottles) - { - for (int i = bottles; i > 0; i--) + private static string DefaultAction(ref int bottles) { - if (i > 1) + bottles--; + return "take one down, pass it around,"; + } + + private static string FallbackAction(ref int bottles) + { + bottles += 99; + return "go to the store, buy some more,"; + } + + private static string Act(ref int bottles) + { + return bottles > 0 ? DefaultAction(ref bottles) : FallbackAction(ref bottles); + } + + static void Main() + { + Func plural = b => b == 1 ? "" : "s"; + Func describeCount = b => b == 0 ? "no more" : b.ToString(); + Func describeBottles = b => string.Format("{0} {1}{2} of {3}", describeCount(b), Vessel, plural(b), Beverage); + Action write = s => Console.WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s)); + int bottles = 99; + while (true) { - Console.Write("{0}\n{1}\n{2}\n{3}\n\n", - i + " bottles of beer on the wall", - i + " bottles of beer", - "Take one down, pass it around", - (i - 1) + " bottles of beer on the wall"); + write(string.Format("{0} {1}, {0},", describeBottles(bottles), Location)); + write(Act(ref bottles)); + write(string.Format("{0} {1}.", describeBottles(bottles), Location)); + write(string.Empty); } - else - Console.Write("{0}\n{1}\n{2}\n{3}\n\n", - i + " bottle of beer on the wall", - i + " bottle of beer", - "Take one down, pass it around", - (i - 1) + " bottles of beer on the wall...."); } } -} diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs index 87df3fd53e..df76d8ce8e 100644 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs +++ b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs @@ -1,21 +1,28 @@ -using System; -using System.Linq; - -class Program +class songs { - static void Main() + static void Main(string[] args) { - BeerBottles().Take(99).ToList().ForEach(Console.WriteLine); + beer(5); } - static IEnumerable BeerBottles() + private static void beer(int bottles) { - int i = 100; - String f = "{0}, {1}. Take one down, pass it around, {2}"; - Func booze = (c , b) => - String.Format("{0} bottle{1} of beer{2}", c > 0 ? c.ToString() : "no more", (c == 1 ? "" : "s"), b ? " on the wall" : ""); - - while (--i >= 1) - yield return String.Format(f, booze(i, true), booze(i, false), booze(i - 1, true)); + for (int i = bottles; i > 0; i--) + { + if (i > 1) + { + Console.Write("{0}\n{1}\n{2}\n{3}\n\n", + i + " bottles of beer on the wall", + i + " bottles of beer", + "Take one down, pass it around", + (i - 1) + " bottles of beer on the wall"); + } + else + Console.Write("{0}\n{1}\n{2}\n{3}\n\n", + i + " bottle of beer on the wall", + i + " bottle of beer", + "Take one down, pass it around", + (i - 1) + " bottles of beer on the wall...."); + } } } diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs index f087b131bd..87df3fd53e 100644 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs +++ b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs @@ -1,131 +1,21 @@ -string[] bottles = { "80 Shilling", - "Abita Amber", - "Adams Broadside Ale", - "Altenmünster Premium", - "August Schell's SnowStorm", - "Bah Humbug! Christmas Ale", - "Beck's Oktoberfest", - "Belhaven Wee Heavy", - "Bison Chocolate Stout", - "Blue Star Wheat Beer", - "Bridgeport Black Strap Stout", - "Brother Thelonius Belgian-Style Abbey Ale", - "Capital Blonde Doppelbock", - "Carta Blanca", - "Celis Raspberry Wheat", - "Christian Moerlein Select Lager", - "Corona", - "Czechvar", - "Delirium Tremens", - "Diamond Bear Southern Blonde", - "Don De Dieu", - "Eastside Dark", - "Eliot Ness", - "Flying Dog K-9 Cruiser Altitude Ale", - "Fuller's London Porter", - "Gaffel Kölsch", - "Golden Horseshoe", - "Guinness Pub Draught", - "Hacker-Pschorr Weisse", - "Hereford & Hops Black Spring Double Stout", - "Highland Oatmeal Porter", - "Ipswich Ale", - "Iron City", - "Jack Daniel's Amber Lager", - "Jamaica Sunset India Pale Ale", - "Killian's Red", - "König Ludwig Weiss", - "Kronenbourg 1664", - "Lagunitas Hairy Eyball Ale", - "Left Hand Juju Ginger", - "Locktender Lager", - "Magic Hat Blind Faith", - "Missing Elf Double Bock", - "Muskoka Cream Ale ", - "New Glarus Cherry Stout", - "Nostradamus Bruin", - "Old Devil", - "Ommegang Three Philosophers", - "Paulaner Hefe-Weizen Dunkel", - "Perla Chmielowa Pils", - "Pete's Wicked Springfest", - "Point White Biere", - "Prostel Alkoholfrei", - "Quilmes", - "Rahr's Red", - "Rebel Garnet", - "Rickard's Red", - "Rio Grande Elfego Bock", - "Rogue Brutal Bitter", - "Roswell Alien Amber Ale", - "Russian River Pliny The Elder", - "Samuel Adams Blackberry Witbier", - "Samuel Smith's Taddy Porter", - "Schlafly Pilsner", - "Sea Dog Wild Blueberry Wheat Ale", - "Sharp's", - "Shiner 99", - "Sierra Dorada", - "Skullsplitter Orkney Ale", - "Snake Chaser Irish Style Stout", - "St. Arnold Bock", - "St. Peter's Cream Stout", - "Stag", - "Stella Artois", - "Stone Russian Imperial Stout", - "Sweetwater Happy Ending Imperial Stout", - "Taiwan Gold Medal", - "Terrapin Big Hoppy Monster", - "Thomas Hooker American Pale Ale", - "Tie Die Red Ale", - "Toohey's Premium", - "Tsingtao", - "Ugly Pug Black Lager", - "Unibroue Qatre-Centieme", - "Victoria Bitter", - "Voll-Damm Doble Malta", - "Wailing Wench Ale", - "Warsteiner Dunkel", - "Wellhead Crude Oil Stout", - "Weyerbacher Blithering Idiot Barley-Wine Style Ale", - "Wild Boar Amber", - "Würzburger Oktoberfest", - "Xingu Black Beer", - "Yanjing", - "Younger's Tartan Special", - "Yuengling Black & Tan", - "Zagorka Special", - "Zig Zag River Lager", - "Zywiec" }; +using System; +using System.Linq; - -int bottlesLeft = 99; -const int FIRST_LINE_SINGULAR = 98; -const int FINAL_LINE_SINGULAR = 97; -string firstLine = ""; -string finalLine = ""; - - -for (int i = 0; i < 99; i++) +class Program { - firstLine = bottlesLeft.ToString() + " bottle"; - if (i != FIRST_LINE_SINGULAR) - firstLine += "s"; - firstLine += " of beer on the wall, " + bottlesLeft.ToString() + " bottle"; - if (i != FIRST_LINE_SINGULAR) - firstLine += "s"; - firstLine += " of beer"; + static void Main() + { + BeerBottles().Take(99).ToList().ForEach(Console.WriteLine); + } - Console.WriteLine(firstLine); - Console.WriteLine("Take the " + bottles[i] + " down, pass it around,"); - bottlesLeft--; - - finalLine = bottlesLeft.ToString() + " bottle"; - if (i != FINAL_LINE_SINGULAR) - finalLine += "s"; - finalLine += " of beer on the wall!"; - - Console.WriteLine(finalLine); - Console.WriteLine(); - Console.ReadLine(); + static IEnumerable BeerBottles() + { + int i = 100; + String f = "{0}, {1}. Take one down, pass it around, {2}"; + Func booze = (c , b) => + String.Format("{0} bottle{1} of beer{2}", c > 0 ? c.ToString() : "no more", (c == 1 ? "" : "s"), b ? " on the wall" : ""); + + while (--i >= 1) + yield return String.Format(f, booze(i, true), booze(i, false), booze(i - 1, true)); + } } diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-6.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-6.cs new file mode 100644 index 0000000000..f087b131bd --- /dev/null +++ b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-6.cs @@ -0,0 +1,131 @@ +string[] bottles = { "80 Shilling", + "Abita Amber", + "Adams Broadside Ale", + "Altenmünster Premium", + "August Schell's SnowStorm", + "Bah Humbug! Christmas Ale", + "Beck's Oktoberfest", + "Belhaven Wee Heavy", + "Bison Chocolate Stout", + "Blue Star Wheat Beer", + "Bridgeport Black Strap Stout", + "Brother Thelonius Belgian-Style Abbey Ale", + "Capital Blonde Doppelbock", + "Carta Blanca", + "Celis Raspberry Wheat", + "Christian Moerlein Select Lager", + "Corona", + "Czechvar", + "Delirium Tremens", + "Diamond Bear Southern Blonde", + "Don De Dieu", + "Eastside Dark", + "Eliot Ness", + "Flying Dog K-9 Cruiser Altitude Ale", + "Fuller's London Porter", + "Gaffel Kölsch", + "Golden Horseshoe", + "Guinness Pub Draught", + "Hacker-Pschorr Weisse", + "Hereford & Hops Black Spring Double Stout", + "Highland Oatmeal Porter", + "Ipswich Ale", + "Iron City", + "Jack Daniel's Amber Lager", + "Jamaica Sunset India Pale Ale", + "Killian's Red", + "König Ludwig Weiss", + "Kronenbourg 1664", + "Lagunitas Hairy Eyball Ale", + "Left Hand Juju Ginger", + "Locktender Lager", + "Magic Hat Blind Faith", + "Missing Elf Double Bock", + "Muskoka Cream Ale ", + "New Glarus Cherry Stout", + "Nostradamus Bruin", + "Old Devil", + "Ommegang Three Philosophers", + "Paulaner Hefe-Weizen Dunkel", + "Perla Chmielowa Pils", + "Pete's Wicked Springfest", + "Point White Biere", + "Prostel Alkoholfrei", + "Quilmes", + "Rahr's Red", + "Rebel Garnet", + "Rickard's Red", + "Rio Grande Elfego Bock", + "Rogue Brutal Bitter", + "Roswell Alien Amber Ale", + "Russian River Pliny The Elder", + "Samuel Adams Blackberry Witbier", + "Samuel Smith's Taddy Porter", + "Schlafly Pilsner", + "Sea Dog Wild Blueberry Wheat Ale", + "Sharp's", + "Shiner 99", + "Sierra Dorada", + "Skullsplitter Orkney Ale", + "Snake Chaser Irish Style Stout", + "St. Arnold Bock", + "St. Peter's Cream Stout", + "Stag", + "Stella Artois", + "Stone Russian Imperial Stout", + "Sweetwater Happy Ending Imperial Stout", + "Taiwan Gold Medal", + "Terrapin Big Hoppy Monster", + "Thomas Hooker American Pale Ale", + "Tie Die Red Ale", + "Toohey's Premium", + "Tsingtao", + "Ugly Pug Black Lager", + "Unibroue Qatre-Centieme", + "Victoria Bitter", + "Voll-Damm Doble Malta", + "Wailing Wench Ale", + "Warsteiner Dunkel", + "Wellhead Crude Oil Stout", + "Weyerbacher Blithering Idiot Barley-Wine Style Ale", + "Wild Boar Amber", + "Würzburger Oktoberfest", + "Xingu Black Beer", + "Yanjing", + "Younger's Tartan Special", + "Yuengling Black & Tan", + "Zagorka Special", + "Zig Zag River Lager", + "Zywiec" }; + + +int bottlesLeft = 99; +const int FIRST_LINE_SINGULAR = 98; +const int FINAL_LINE_SINGULAR = 97; +string firstLine = ""; +string finalLine = ""; + + +for (int i = 0; i < 99; i++) +{ + firstLine = bottlesLeft.ToString() + " bottle"; + if (i != FIRST_LINE_SINGULAR) + firstLine += "s"; + firstLine += " of beer on the wall, " + bottlesLeft.ToString() + " bottle"; + if (i != FIRST_LINE_SINGULAR) + firstLine += "s"; + firstLine += " of beer"; + + Console.WriteLine(firstLine); + Console.WriteLine("Take the " + bottles[i] + " down, pass it around,"); + bottlesLeft--; + + finalLine = bottlesLeft.ToString() + " bottle"; + if (i != FINAL_LINE_SINGULAR) + finalLine += "s"; + finalLine += " of beer on the wall!"; + + Console.WriteLine(finalLine); + Console.WriteLine(); + Console.ReadLine(); +} diff --git a/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-3.cobol b/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-3.cobol new file mode 100644 index 0000000000..6a73ccd099 --- /dev/null +++ b/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-3.cobol @@ -0,0 +1,16 @@ +program-id. ninety-nine. +data division. +working-storage section. +01 cnt pic 99. + +procedure division. + + perform varying cnt from 99 by -1 until cnt < 1 + display cnt " bottles of beer on the wall" + display cnt " bottles of beer" + display "Take one down, pass it around" + subtract 1 from cnt + display cnt " bottles of beer on the wall" + add 1 to cnt + display space + end-perform. diff --git a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-3.lisp b/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-3.lisp new file mode 100644 index 0000000000..804f496105 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-3.lisp @@ -0,0 +1,2 @@ +(format t "~{~[~^~]~:*~D bottle~:P of beer on the wall~%~:*~D bottle~:P of beer~%Take one down, pass it around~%~D bottle~:P~:* of beer on the wall~2%~}" + (loop :for n :from 99 :downto 0 :collect n)) diff --git a/Task/99-Bottles-of-Beer/D/99-bottles-of-beer.d b/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-1.d similarity index 100% rename from Task/99-Bottles-of-Beer/D/99-bottles-of-beer.d rename to Task/99-Bottles-of-Beer/D/99-bottles-of-beer-1.d diff --git a/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-2.d b/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-2.d new file mode 100644 index 0000000000..6fae6b05cb --- /dev/null +++ b/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-2.d @@ -0,0 +1,24 @@ +import std.stdio, std.conv; + +string bottles(in size_t num) pure { + static string bottlesRecurse(in size_t num) pure { + return num.text ~ " bottles of beer on the wall,\n" + ~ num.text ~ " bottles of beer!\n" + ~ "Take one down, pass it around,\n" + ~ (num - 1).text ~ " bottle" ~ ((num - 1 == 1) ? "" : "s") + ~ " of beer on the wall.\n\n" + ~ ((num > 2) + ? bottlesRecurse(num - 1) + : "1 bottle of beer on the wall,\n" + ~ "1 bottle of beer!\n" + ~ "Take one down, pass it around,\n" + ~ "No bottles of beer on the wall!\n\n"); + } + + return bottlesRecurse(num) + ~ "Go to the store and buy some more...\n" + ~ num.text ~ " bottles of beer on the wall!"; +} + +pragma(msg, 99.bottles); +void main() {} diff --git a/Task/99-Bottles-of-Beer/Deja-Vu/99-bottles-of-beer.djv b/Task/99-Bottles-of-Beer/Deja-Vu/99-bottles-of-beer.djv new file mode 100644 index 0000000000..76238d3d24 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Deja-Vu/99-bottles-of-beer.djv @@ -0,0 +1,17 @@ +plural i: + if = 1 i "" "s" + +bottles i: + local :s plural i + !print( to-str i " bottle"s" of beer on the wall, " to-str i " bottle"s" of beer," ) + !print\ "You take one down, pass it around, " + set :i -- i + if i: + set :s plural i + !print( to-str i " bottle"s" of beer on the wall." ) + bottles i + else: + !print "no more bottles of beer on the wall, no more bottles of beer." + !print "Go to the store and buy some more, 99 bottles of beer on the wall." + +bottles 99 diff --git a/Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer.haxe b/Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer-1.haxe similarity index 100% rename from Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer.haxe rename to Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer-1.haxe diff --git a/Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer-2.haxe b/Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer-2.haxe new file mode 100644 index 0000000000..7eefbfec58 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Haxe/99-bottles-of-beer-2.haxe @@ -0,0 +1,33 @@ +class Bottles { + + static public function main () : Void { + singBottlesOfBeer(100); + } + + + macro static public function singBottlesOfBeer (bottles:Int) { + var lines = []; + var s : String = 's'; + + var song : String = ''; + while( bottles >= 1 ){ + song += '$bottles bottle$s of beer on the wall,\n'; + song += '$bottles bottle$s of beer!\n'; + song += 'Take one down, pass it around,\n'; + + bottles --; + + if( bottles > 1 ){ + song += '$bottles bottles of beer on the wall!\n\n'; + }else if( bottles == 1 ){ + s = ''; + song += '$bottles bottle of beer on the wall!\n\n'; + }else{ + song += 'No more bottles of beer on the wall!\n'; + } + } + + return macro Sys.print($v{song}); + } + +} diff --git a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java index ca5c43b61a..f9d8e17684 100644 --- a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java +++ b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java @@ -1,40 +1,21 @@ -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JTextArea; -public class Beer extends JFrame implements ActionListener{ - private int x; - private JButton take; - private JTextArea text; - public static void main(String[] args){ - new Beer();//build and show the GUI - } - - public Beer(){ - x= 99; - take= new JButton("Take one down, pass it around"); - text= new JTextArea(4,30);//size the area to 4 lines, 30 chars each - text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer"); - text.setEditable(false);//so they can't change the text after it's displayed - take.addActionListener(this);//listen to the button - setLayout(new BorderLayout());//handle placement of components - add(text, BorderLayout.CENTER);//put the text area in the largest section - add(take, BorderLayout.SOUTH);//put the button underneath it - pack();//auto-size the window - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit on "X" (I hate System.exit...) - setVisible(true);//show it - } - - public void actionPerformed(ActionEvent arg0){ - if(arg0.getSource() == take){//if they clicked the button - JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");//show a popup message - text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");//change the text - } - if(x == 0){//if it's the end - dispose();//end - } - } +public class Beer +{ + public static void main(String args[]) + { + song(99); + } + + public static void song(int b) + { + if(b>=0) + { + if(b>1) + System.out.println(b+" bottles of beer on the wall\n"+b+" bottles of beer\nTake one down, pass it around\n"+(b-1)+" bottles of beer on the wall.\n"); + else if(b==1) + System.out.println(b+" bottle of beer on the wall\n"+b+" bottle of beer\nTake one down, pass it around\n"+(b-1)+" bottles of beer on the wall.\n"); + else + System.out.println(b+" bottles of beer on the wall\n"+b+" bottles of beer\nBetter go to the store and buy some more!"); + song(b-1); + } + } } diff --git a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java new file mode 100644 index 0000000000..ca5c43b61a --- /dev/null +++ b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java @@ -0,0 +1,40 @@ +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JTextArea; +public class Beer extends JFrame implements ActionListener{ + private int x; + private JButton take; + private JTextArea text; + public static void main(String[] args){ + new Beer();//build and show the GUI + } + + public Beer(){ + x= 99; + take= new JButton("Take one down, pass it around"); + text= new JTextArea(4,30);//size the area to 4 lines, 30 chars each + text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer"); + text.setEditable(false);//so they can't change the text after it's displayed + take.addActionListener(this);//listen to the button + setLayout(new BorderLayout());//handle placement of components + add(text, BorderLayout.CENTER);//put the text area in the largest section + add(take, BorderLayout.SOUTH);//put the button underneath it + pack();//auto-size the window + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit on "X" (I hate System.exit...) + setVisible(true);//show it + } + + public void actionPerformed(ActionEvent arg0){ + if(arg0.getSource() == take){//if they clicked the button + JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");//show a popup message + text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");//change the text + } + if(x == 0){//if it's the end + dispose();//end + } + } +} diff --git a/Task/99-Bottles-of-Beer/Oxygene/99-bottles-of-beer.oxy b/Task/99-Bottles-of-Beer/Oxygene/99-bottles-of-beer.oxy new file mode 100644 index 0000000000..c71d6f7573 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Oxygene/99-bottles-of-beer.oxy @@ -0,0 +1,34 @@ +namespace ConsoleApplication2; + +interface + +type + ConsoleApp = class + public + class method Main(args: array of String); + end; + +implementation + +method bottles(number: Integer): String; +begin + if (number = 1) then + Result := "bottle" + else + Result := "bottles"; +end; + +class method ConsoleApp.Main(args: array of String); +begin + for n: Integer := 99 downto 1 do + begin + Console.WriteLine("{0} {1} of beer on the wall,",n,bottles(n)); + Console.WriteLine("{0} {1} of beer,",n,bottles(n)); + Console.WriteLine("Take one down, and pass it around,"); + Console.WriteLine("{0} {1} of beer on the wall.",n-1,bottles(n-1)); + Console.WriteLine(); + end; + Console.ReadKey(); +end; + +end. diff --git a/Task/99-Bottles-of-Beer/PHP/99-bottles-of-beer-5.php b/Task/99-Bottles-of-Beer/PHP/99-bottles-of-beer-5.php new file mode 100644 index 0000000000..93b1b948f6 --- /dev/null +++ b/Task/99-Bottles-of-Beer/PHP/99-bottles-of-beer-5.php @@ -0,0 +1,16 @@ + 0) { + printf(ngettext('%d bottle', '%d bottles', $bottles) . " of beer on the wall\n", $bottles); //X bottles of beer on the wall + printf(ngettext('%d bottle', '%d bottles', $bottles) . " of beer\n", $bottles); //X bottles of beer + printf("Take one down, pass it around\n"); //Take one down, pass it around + + $bottles--; + + if ($bottles > 0) { + printf(ngettext('%d bottle', '%d bottles', $bottles) . " of beer on the wall\n\n", $bottles); //X bottles of beer on the wall + } +} +printf('No more bottles of beer on the wall'); //No more bottles of beer on the wall diff --git a/Task/99-Bottles-of-Beer/Ruby/99-bottles-of-beer-5.rb b/Task/99-Bottles-of-Beer/Ruby/99-bottles-of-beer-5.rb new file mode 100644 index 0000000000..f5d603bd3e --- /dev/null +++ b/Task/99-Bottles-of-Beer/Ruby/99-bottles-of-beer-5.rb @@ -0,0 +1,6 @@ +99.downto(1) do |bottles| + puts "#{bottles} bottle#{"s" if bottles != 1} of beer on the wall.", + "#{bottles} bottle#{"s" if bottles != 1} of beer.", + "Take one down, pass it around.", + "#{bottles - 1} bottle#{"s" if bottles - 1 != 1} of beer on the wall.\n\n" +end 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 new file mode 100644 index 0000000000..74483d818b --- /dev/null +++ b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust @@ -0,0 +1,27 @@ +// rust is changing fast, so this will probably not work in later versions + +use std::iter::range_step_inclusive; + +fn main() { + for num_bottles in range_step_inclusive(99, 1, -1) { + sing_bottles_line(num_bottles, true); + sing_bottles_line(num_bottles, false); + println("Take one down, pass it around..."); + sing_bottles_line(num_bottles - 1, true); + println("-----------------------------------"); + } +} + +fn sing_bottles_line(num_bottles: int, on_the_wall: bool) { + + // the print! macro uses a built in internationalization formatting language + // 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); +} diff --git a/Task/99-Bottles-of-Beer/Visual-Prolog/99-bottles-of-beer.pro b/Task/99-Bottles-of-Beer/Visual-Prolog/99-bottles-of-beer.pro new file mode 100644 index 0000000000..c74f83a75e --- /dev/null +++ b/Task/99-Bottles-of-Beer/Visual-Prolog/99-bottles-of-beer.pro @@ -0,0 +1,24 @@ +implement main + open core, std, console + +class predicates + bottles : (integer) -> string procedure (i). + +clauses + bottles(1) = "bottle" :- !. + bottles(_) = "bottles". + + run():- + init(), + foreach B = downTo(99,1) do + write(B," ",bottles(B), " of beer on the wall,\n"), + write(B," ",bottles(B), " of beer,\n"), + write("Take one down, pass it around,\n"), + write(B-1," ",bottles(B-1)," of beer on the wall.\n\n") + end foreach, + + succeed(). +end implement main + +goal + mainExe::run(main::run). diff --git a/Task/99-Bottles-of-Beer/Z80-Assembly/99-bottles-of-beer.z80 b/Task/99-Bottles-of-Beer/Z80-Assembly/99-bottles-of-beer.z80 new file mode 100644 index 0000000000..5ccb0feea6 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Z80-Assembly/99-bottles-of-beer.z80 @@ -0,0 +1,71 @@ +org 32768 + +start: + ld a, 2 ; Spectrum: channel 2 = "S" for screen + call $1601 ; Spectrum: Select print channel using ROM + + ld c,99 ; Number of bottles to start with + +loopstart: + call printc ; Print the number of bottles + ld hl,line1 ; Print the rest of the first line + call printline + + call printc ; Print the number of bottles + ld hl,line2_3 ; Print rest of the 2nd and 3rd lines + call printline + + dec c ; Take one bottle away + call printc ; Print the number of bottles + ld hl,line4 ; Print the rest of the fourth line + call printline + + ld a,c + cp 0 ; Out of beer bottles? + jp nz,loopstart ; If not, loop round again + ret ; Return to BASIC + +printc: ; Routine to print C register as ASCII decimal + ld a,c + call dtoa2d ; Split A register into D and E + + ld a,d ; Print first digit in D + cp '0' ; Don't bother printing leading 0 + jr z,printc2 + rst 16 ; Spectrum: Print the character in 'A' + +printc2: + ld a,e ; Print second digit in E + rst 16 ; Spectrum: Print the character in 'A' + ret + +printline: ; Routine to print out a line + ld a,(hl) ; Get character to print + cp '$' ; See if it '$' terminator + jp z,printend ; We're done if it is + rst 16 ; Spectrum: Print the character in 'A' + inc hl ; Move onto the next character + jp printline ; Loop round + +printend: + ret + +dtoa2d: ; Decimal to ASCII (2 digits only), in: A, out: DE + ld d,'0' ; Starting from ASCII '0' + dec d ; Because we are inc'ing in the loop + ld e,10 ; Want base 10 please + and a ; Clear carry flag + +dtoa2dloop: + inc d ; Increase the number of tens + sub e ; Take away one unit of ten from A + jr nc,dtoa2dloop ; If A still hasn't gone negative, do another + add a,e ; Decreased it too much, put it back + add a,'0' ; Convert to ASCII + ld e,a ; Stick remainder in E + ret + +; Data +line1: defb ' bottles of beer on the wall,',13,'$' +line2_3: defb ' bottles of beer,',13,'Take one down, pass it around,',13,'$' +line4: defb ' bottles of beer on the wall.',13,13,'$' diff --git a/Task/A+B/D/a+b-2.d b/Task/A+B/D/a+b-2.d index 734612489f..6175ac44da 100644 --- a/Task/A+B/D/a+b-2.d +++ b/Task/A+B/D/a+b-2.d @@ -1,8 +1,6 @@ -import std.stdio, std.conv, std.string; - void main() { - auto fin = File("sum_input.txt", "r"); - auto r = fin.readln().split(); - auto fout = File("sum_output.txt", "w"); - fout.writeln(to!int(r[0]) + to!int(r[1])); + import std.stdio, std.file; + + immutable ab = "sum_input.txt".slurp!(int, int)("%d %d")[0]; + "sum_output.txt".File("w").writeln(ab[0] + ab[1]); } diff --git a/Task/A+B/Dart/a+b.dart b/Task/A+B/Dart/a+b.dart new file mode 100644 index 0000000000..b74744d992 --- /dev/null +++ b/Task/A+B/Dart/a+b.dart @@ -0,0 +1,27 @@ +import 'dart:io'; +import 'dart:convert'; + +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!'); + } 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]); + } + } + }); +} diff --git a/Task/A+B/Deja-Vu/a+b.djv b/Task/A+B/Deja-Vu/a+b.djv index 4540b1d13b..48a67dad90 100644 --- a/Task/A+B/Deja-Vu/a+b.djv +++ b/Task/A+B/Deja-Vu/a+b.djv @@ -1,4 +1,4 @@ 0 -for k in split " " input: +for k in split !prompt "" " ": + to-num k -print +!print diff --git a/Task/A+B/Elena/a+b.elena b/Task/A+B/Elena/a+b.elena index 9a01ed9805..45307430a9 100644 --- a/Task/A+B/Elena/a+b.elena +++ b/Task/A+B/Elena/a+b.elena @@ -1,10 +1,11 @@ #define system. -#define extensions'io. +#define extensions. #symbol program = [ - #var A := consoleEx >> Integer new. - #var B := consoleEx >> Integer new. + #var A := Integer new. + #var B := Integer new. - consoleEx << A + B. + consoleEx readLine:A:B. + consoleEx writeLine:(A + B). ]. diff --git a/Task/A+B/GML/a+b.gml b/Task/A+B/GML/a+b.gml index 82116589e3..0e22e81a19 100644 --- a/Task/A+B/GML/a+b.gml +++ b/Task/A+B/GML/a+b.gml @@ -1,4 +1,5 @@ -add = argument0 // get the string with the numbers to add -a = real(string_copy(add, 1, string_pos(" ", add))) -b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add))) -return(a + b) +var add, a, b; +add = argument0; // get the string with the numbers to add +a = real(string_copy(add, 1, string_pos(" ", add))); +b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add))); +return(a + b); diff --git a/Task/A+B/Scala/a+b-1.scala b/Task/A+B/Scala/a+b-1.scala new file mode 100644 index 0000000000..58dde3df3e --- /dev/null +++ b/Task/A+B/Scala/a+b-1.scala @@ -0,0 +1 @@ +println(readLine().split(" ").map(_.toInt).sum) diff --git a/Task/A+B/Scala/a+b-2.scala b/Task/A+B/Scala/a+b-2.scala new file mode 100644 index 0000000000..76ca74c5c5 --- /dev/null +++ b/Task/A+B/Scala/a+b-2.scala @@ -0,0 +1,3 @@ +val s = new java.util.Scanner(System.in) +val sum = s.nextInt() + s.nextInt() +println(sum) diff --git a/Task/A+B/Scala/a+b.scala b/Task/A+B/Scala/a+b.scala deleted file mode 100644 index b089a95983..0000000000 --- a/Task/A+B/Scala/a+b.scala +++ /dev/null @@ -1 +0,0 @@ -println(readLine() split " " take 2 map (_.toInt) sum) diff --git a/Task/A+B/TXR/a+b.txr b/Task/A+B/TXR/a+b.txr new file mode 100644 index 0000000000..40b62ac240 --- /dev/null +++ b/Task/A+B/TXR/a+b.txr @@ -0,0 +1,2 @@ +@(do (let ((sum (+ (read) (read)))) + (format t "~s\n" sum))) diff --git a/Task/A+B/VBA/a+b.vba b/Task/A+B/VBA/a+b.vba new file mode 100644 index 0000000000..134b4b3284 --- /dev/null +++ b/Task/A+B/VBA/a+b.vba @@ -0,0 +1,7 @@ +Sub Rosetta_AB() +Dim stEval As String +stEval = InputBox("Enter two numbers, separated only by a space", "Rosetta Code", "2 2") +MsgBox "You entered " & stEval & vbCr & vbCr & _ + "VBA converted this input to " & Replace(stEval, " ", "+") & vbCr & vbCr & _ + "And evaluated the result as " & Evaluate(Replace(stEval, " ", "+")), vbInformation + vbOKOnly, "XLSM" +End Sub diff --git a/Task/Abstract-type/ActionScript/abstract-type.as b/Task/Abstract-type/ActionScript/abstract-type-1.as similarity index 100% rename from Task/Abstract-type/ActionScript/abstract-type.as rename to Task/Abstract-type/ActionScript/abstract-type-1.as diff --git a/Task/Abstract-type/ActionScript/abstract-type-2.as b/Task/Abstract-type/ActionScript/abstract-type-2.as new file mode 100644 index 0000000000..dfc4662938 --- /dev/null +++ b/Task/Abstract-type/ActionScript/abstract-type-2.as @@ -0,0 +1,22 @@ +package { + import flash.utils.getQualifiedClassName; + + public class AbstractClass { + + private static const FULLY_QUALIFIED_NAME:String = "AbstractClass"; + + // For classes in a package, the fully qualified name should be in the form "package.name::class_name" + // Note that a double colon and not a dot is used before the class name. This is the format returned + // by the getQualifiedClassName() function. + + public function AbstractClass() { + if ( getQualifiedClassName(this) == FULLY_QUALIFIED_NAME ) + throw new Error("Class " + FULLY_QUALIFIED_NAME + " is abstract."); + } + + public function abstractMethod(a:int, b:int):void { + throw new Error("abstractMethod is not implemented."); + } + + } +} diff --git a/Task/Abstract-type/ActionScript/abstract-type-3.as b/Task/Abstract-type/ActionScript/abstract-type-3.as new file mode 100644 index 0000000000..88e7acaa79 --- /dev/null +++ b/Task/Abstract-type/ActionScript/abstract-type-3.as @@ -0,0 +1,10 @@ +package { + + public class Example extends AbstractClass { + + override public function abstractMethod(a:int, b:int):void { + trace(a + b); + } + + } +} diff --git a/Task/Abstract-type/C/abstract-type-2.c b/Task/Abstract-type/C/abstract-type-2.c index 4354d95cec..471032a607 100644 --- a/Task/Abstract-type/C/abstract-type-2.c +++ b/Task/Abstract-type/C/abstract-type-2.c @@ -1,6 +1,6 @@ #ifndef SILLY_H #define SILLY_H -#include intefaceAbs.h +#include "intefaceAbs.h" typedef struct sillyStruct *Silly; extern Silly NewSilly( double, const char *); diff --git a/Task/Accumulator-factory/Common-Lisp/accumulator-factory-1.lisp b/Task/Accumulator-factory/Common-Lisp/accumulator-factory-1.lisp index a3762e8073..d1e78dbdc0 100644 --- a/Task/Accumulator-factory/Common-Lisp/accumulator-factory-1.lisp +++ b/Task/Accumulator-factory/Common-Lisp/accumulator-factory-1.lisp @@ -1,3 +1,3 @@ (defun accumulator (sum) (lambda (n) - (setf sum (+ sum n)))) + (incf sum n))) diff --git a/Task/Accumulator-factory/D/accumulator-factory.d b/Task/Accumulator-factory/D/accumulator-factory.d index 19678ea3b3..6bc937972a 100644 --- a/Task/Accumulator-factory/D/accumulator-factory.d +++ b/Task/Accumulator-factory/D/accumulator-factory.d @@ -1,3 +1,5 @@ +import std.stdio; + void main() { auto x = acc(1); x(5); diff --git a/Task/Accumulator-factory/Dart/accumulator-factory.dart b/Task/Accumulator-factory/Dart/accumulator-factory.dart new file mode 100644 index 0000000000..619bed1622 --- /dev/null +++ b/Task/Accumulator-factory/Dart/accumulator-factory.dart @@ -0,0 +1,9 @@ +Function accumulator(var n) => (var i) => n += i; + +void main() { + var a = accumulator(42); + print("${a(0)}, ${a(1)}, ${a(10)}, ${a(100)}"); + + var b = accumulator(4.2); + print("${b(0)}, ${b(1)}, ${b(10.0)}, ${b(100.4)}"); +} diff --git a/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv b/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv index 4b14ca2ca3..15fc62e666 100644 --- a/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv +++ b/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv @@ -6,4 +6,4 @@ accum n: local :x accum 1 drop x 5 drop accum 3 -print x 2.3 +!print x 2.3 diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index aea8c402e8..bfe4530345 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -2,9 +2,9 @@ #define system'dynamic. #symbol Function = - &&:x [ self append:x ]. + (:x) [ self append:x ]. -#symbol Accumulator = &&:anInitialValue +#symbol Accumulator = (:anInitialValue) [ Wrap(Function, Variable new:anInitialValue) ]. #symbol Program = diff --git a/Task/Accumulator-factory/TXR/accumulator-factory.txr b/Task/Accumulator-factory/TXR/accumulator-factory.txr new file mode 100644 index 0000000000..0064207bfb --- /dev/null +++ b/Task/Accumulator-factory/TXR/accumulator-factory.txr @@ -0,0 +1,12 @@ +@(do + (defun accumulate (sum) + (lambda (n) + (inc sum n))) + + ;; test + (for ((f (accumulate 0)) + num) + ((set num (read))) + ((format t "~s -> ~s\n" num [f num]))) + + (exit 0)) diff --git a/Task/Ackermann-function/C/ackermann-function-2.c b/Task/Ackermann-function/C/ackermann-function-2.c index 4046392f61..75c23fc716 100644 --- a/Task/Ackermann-function/C/ackermann-function-2.c +++ b/Task/Ackermann-function/C/ackermann-function-2.c @@ -34,7 +34,7 @@ int main() memset(cache, 0, sizeof(int) * (1 << (m_bits + n_bits))); for (m = 0; m <= 4; m++) - for (n = 0; n < 6 - m; n++) { + for (n = 0; n < 6 - m; n++) printf("A(%d, %d) = %d\n", m, n, ackermann(m, n)); return 0; diff --git a/Task/Ackermann-function/D/ackermann-function-2.d b/Task/Ackermann-function/D/ackermann-function-2.d index dc7cfc6485..43e25f4710 100644 --- a/Task/Ackermann-function/D/ackermann-function-2.d +++ b/Task/Ackermann-function/D/ackermann-function-2.d @@ -1,9 +1,8 @@ import std.stdio, std.bigint, std.conv; -/*pure nothrow*/ BigInt ipow(/*in*/ BigInt base, /*in*/ BigInt exp){ - auto result = BigInt(1); - //while (exp) { - while (exp != 0) { +BigInt ipow(BigInt base, BigInt exp) pure /*nothrow*/ { + auto result = 1.BigInt; + while (exp) { //if (exp & 1) if (exp % 2) result *= base; @@ -14,37 +13,36 @@ import std.stdio, std.bigint, std.conv; return result; } -/*pure nothrow*/ BigInt ackermann(in int m, in int n) +BigInt ackermann(in int m, in int n) pure /*nothrow*/ in { assert(m >= 0 && n >= 0); } out(result) { - //assert(result >= 0); - //assert(cast()result >= 0); + assert(result >= 0); } body { - /*pure nothrow*/ static BigInt ack(in int m, /*in*/ BigInt n) { + static BigInt ack(in int m, in BigInt n) pure /*nothrow*/ { switch (m) { case 0: return n + 1; case 1: return n + 2; case 2: return 3 + 2 * n; //case 3: return 5 + 8 * (2 ^^ n - 1); - case 3: return 5 + 8 * (ipow(BigInt(2), n) - 1); + case 3: return 5 + 8 * (ipow(2.BigInt, n) - 1); default: if (n == 0) - return ack(m - 1, BigInt(1)); + return ack(m - 1, 1.BigInt); else return ack(m - 1, ack(m, n - 1)); } } - return ack(m, BigInt(n)); + return ack(m, n.BigInt); } void main() { - foreach (m; 1 .. 4) - foreach (n; 1 .. 9) + foreach (immutable m; 1 .. 4) + foreach (immutable n; 1 .. 9) writefln("ackermann(%d, %d): %s", m, n, ackermann(m, n)); writefln("ackermann(4, 1): %s", ackermann(4, 1)); - auto a = text(ackermann(4, 2)); + immutable a = ackermann(4, 2).text; writefln("ackermann(4, 2)) (%d digits):\n%s...\n%s", - a.length, a[0 .. 94], a[$-96 .. $]); + a.length, a[0 .. 94], a[$ - 96 .. $]); } diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index fcbfed7a10..4c51a26a8c 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -2,23 +2,21 @@ // --- Ackermann function --- -#symbol ackermann = &&:m:n +#symbol ackermann = (:m:n) [ m => 0 ? [ n + 1 ] > 0 ? [ - n => 0 ? [ $self:(m - 1):1 ] - > 0 ? [ $self:(m - 1):($self:m:(n-1)) ] + n => 0 ? [ ackermann:(m - 1):1 ] + > 0 ? [ ackermann:(m - 1):(ackermann:m:(n-1)) ] ] ]. #symbol program = [ - #var n := ackermann:3:5. - - control from:0 &to:3 &do: &&:i + control from:0 &to:3 &do: i [ - control from:0 &to:5 &do: &&:j + control from:0 &to:5 &do: j [ console << "A(" << i << "," << j << ")=" << (ackermann:i:j). diff --git a/Task/Ackermann-function/TorqueScript/ackermann-function.torque b/Task/Ackermann-function/TorqueScript/ackermann-function.torque new file mode 100644 index 0000000000..6b46ef62b1 --- /dev/null +++ b/Task/Ackermann-function/TorqueScript/ackermann-function.torque @@ -0,0 +1,9 @@ +function ackermann(%m,%n) +{ + if(%m==0) + return %n+1; + if(%m>0&&%n==0) + return ackermann(%m-1,1); + if(%m>0&&%n>0) + return ackermann(%m-1,ackermann(%m,%n-1)); +} diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/D/add-a-variable-to-a-class-instance-at-runtime-1.d b/Task/Add-a-variable-to-a-class-instance-at-runtime/D/add-a-variable-to-a-class-instance-at-runtime-1.d index da09b56074..97333126eb 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/D/add-a-variable-to-a-class-instance-at-runtime-1.d +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/D/add-a-variable-to-a-class-instance-at-runtime-1.d @@ -5,7 +5,7 @@ struct Dynamic(T) { return vars[key]; } - @property void opDispatch(string key, U)(U value)/*pure*/ nothrow { + @property void opDispatch(string key, U)(U value) pure nothrow { vars[key] = value; } } diff --git a/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia b/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia new file mode 100644 index 0000000000..c9fc3dad9b --- /dev/null +++ b/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia @@ -0,0 +1,5 @@ +julia> x = 3 +julia> ptr = pointer_from_objref(x) +Ptr{Void} @0x000000010282e4a0 +julia> unsafe_pointer_to_objref(ptr) +3 diff --git a/Task/Address-of-a-variable/Julia/address-of-a-variable-2.julia b/Task/Address-of-a-variable/Julia/address-of-a-variable-2.julia new file mode 100644 index 0000000000..468f2b79e8 --- /dev/null +++ b/Task/Address-of-a-variable/Julia/address-of-a-variable-2.julia @@ -0,0 +1,24 @@ +julia> A = [1, 2.3, 4] +3-element Array{Float64,1}: + 1.0 + 2.3 + 4.0 + +julia> p = pointer(A) +Ptr{Float64} @0x0000000113f70d60 + +julia> unsafe_load(p, 3) +4.0 + +julia> unsafe_store!(p, 3.14159, 3) +julia> A +3-element Array{Float64,1}: + 1.0 + 2.3 + 3.14149 + +julia> pointer_to_array(p, (3,)) +3-element Array{Float64,1}: + 1.0 + 2.3 + 3.14149 diff --git a/Task/Address-of-a-variable/Julia/address-of-a-variable-3.julia b/Task/Address-of-a-variable/Julia/address-of-a-variable-3.julia new file mode 100644 index 0000000000..981c1f40c3 --- /dev/null +++ b/Task/Address-of-a-variable/Julia/address-of-a-variable-3.julia @@ -0,0 +1,8 @@ +julia> +julia> q = convert(Ptr{Float64}, 0x0000000113f70d68) +Ptr{Float64} @0x0000000113f70d68 + +julia> B = pointer_to_array(q, (2,)) +2-element Array{Float64,1}: + 2.3 + 3.14149 diff --git a/Task/Align-columns/AutoIt/align-columns.autoit b/Task/Align-columns/AutoIt/align-columns.autoit new file mode 100644 index 0000000000..9f63e34736 --- /dev/null +++ b/Task/Align-columns/AutoIt/align-columns.autoit @@ -0,0 +1,83 @@ +; == If the given text is in an file, it will read with: +#include +Global $aRead +_FileReadToArray($sPath, $aRead) ; == $aRead[0] includes count of lines, every line stored in one item (without linebreak) + +; == For example we get the same result with StringSplit() +Global $sText = _ +"Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & @CRLF & _ +"are$delineated$by$a$single$'dollar'$character,$write$a$program" & @CRLF & _ +"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & @CRLF & _ +"column$are$separated$by$at$least$one$space." & @CRLF & _ +"Further,$allow$for$each$word$in$a$column$to$be$either$left$" & @CRLF & _ +"justified,$right$justified,$or$center$justified$within$its$column." & @CRLF + +$aRead = StringSplit($sText, @CRLF, 1) + +; == strip leading and trailing "$" and trailing spaces, count remaining "$" to get max column number +Global $iMaxColumn = 0, $iLines = 0 +For $i = 1 To $aRead[0] + If $aRead[$i] = '' Then ContinueLoop ; skip empty lines + $iLines += 1 + $aRead[$i] = StringRegExpReplace(StringRegExpReplace(StringRegExpReplace($aRead[$i], '^\$', ''), '\$$', ''), '\s*$', '') + StringReplace($aRead[$i], '$', '$') + If @extended +1 > $iMaxColumn Then $iMaxColumn = @extended +1 +Next + +; == build array to store all fields and length of every item +Global $aFields[$iLines][$iMaxColumn +1][2] +; == and store the max. length of item in columns +Global $aColLen[$iMaxColumn] + +; == fill the array +Global $aSplitLine +$iLines = 0 +For $i = 1 To $aRead[0] + If $aRead[$i] = '' Then ContinueLoop ; skip empty lines + $iMaxColLen = 0 + $aSplitLine = StringSplit($aRead[$i], '$') + For $j = 1 To $aSplitLine[0] + $aFields[$iLines][$j-1][0] = $aSplitLine[$j] + $aFields[$iLines][$j-1][1] = StringLen($aSplitLine[$j]) + If $aFields[$iLines][$j-1][1] > $aColLen[$j-1] Then $aColLen[$j-1] = $aFields[$iLines][$j-1][1] + Next + $iLines += 1 +Next + +; == let the user select the alignment for every column +$sAlign = InputBox('Column alignment', 'There are ' & $iMaxColumn & ' columns.' & @LF & '0 = left 1 = center 2 = right' & @LF & _ + 'Input alignment for all columns without delimiters.' & @LF & 'Let it empty, to align all left.') +If $sAlign = '' Then + For $i = 1 To $iMaxColumn + $sAlign &= '0' + Next +EndIf +Global $aAlignment = StringSplit($sAlign, '', 2) + +; == output all to console +Global $sLineOut +For $i = 0 To UBound($aFields) -1 + $sLineOut = '' + For $j = 0 To $iMaxColumn -1 + If $aFields[$i][$j][0] = '' Then ContinueLoop + $sLineOut &= _GetAligned($aFields[$i][$j][0], $aFields[$i][$j][1], $aAlignment[$j], $aColLen[$j]) + Next + ConsoleWrite(StringTrimRight($sLineOut, 1) & @LF) +Next + +Func _GetAligned($_sString, $_iLen, $_iAlign, $_iMaxLen) + Local $sSpace = '' + For $i = 1 To $_iMaxLen + $sSpace &= ' ' + Next + Switch $_iAlign + Case 0 + Return $_sString & StringLeft($sSpace, $_iMaxLen - $_iLen +1) + Case 1 + Local $iLenLeft = Int(($_iMaxLen - $_iLen)/2) + Local $iLenRight = $_iMaxLen - $iLenLeft - $_iLen + Return StringLeft($sSpace, $iLenLeft) & $_sString & StringLeft($sSpace, $iLenRight) & ' ' + Case 2 + Return StringLeft($sSpace, $_iMaxLen - $_iLen) & $_sString & ' ' + EndSwitch +EndFunc ;==>_GetAligned diff --git a/Task/Align-columns/Julia/align-columns.julia b/Task/Align-columns/Julia/align-columns.julia new file mode 100644 index 0000000000..90d7248eca --- /dev/null +++ b/Task/Align-columns/Julia/align-columns.julia @@ -0,0 +1,40 @@ +txt = """Given\$a\$txt\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$ +are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program +that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$ +column\$are\$separated\$by\$at\$least\$one\$space. +Further,\$allow\$for\$each\$word\$in\$a\$column\$to\$be\$either\$left\$ +justified,\$right\$justified,\$or\$center\$justified\$within\$its\$column.""" + +# left/right/center justification of strings: +ljust(s, width) = s * " "^max(0, width - length(s)) +rjust(s, width) = " "^max(0, width - length(s)) * s +function center(s, width) + pad = width - length(s) + if pad <= 0 + return s + else + pad2 = div(pad, 2) + return " "^pad2 * s * " "^(pad - pad2) + end +end + +parts = [split(rstrip(line, '$'), '$') for line in split(txt, '\n')] + +max_widths = zeros(Int, maximum(length, parts)) +for line in parts + for (i, word) in enumerate(line) + max_widths[i] = max(max_widths[i], length(word)) + end +end +max_widths += 1 # separate cols by at least one space + +for (label, justify) in (("Left", ljust), ("Right",rjust), ("Center",center)) + println(label, " column-aligned output:") + for line in parts + for (j, word) in enumerate(line) + print(justify(word, max_widths[j])) + end + println() + end + println("-"^sum(max_widths)) +end 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 838bc0b8c1..7971ad0f0e 100644 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d @@ -3,13 +3,13 @@ void main() { std.functional, std.exception; string[][const ubyte[]] anags; - foreach (w; "unixdict.txt".readText.split) + foreach (const w; "unixdict.txt".readText.split) anags[w.dup.representation.sort().release.assumeUnique] ~= w; anags .byValue .map!(words => cartesianProduct(words, words) - .filter!(ww => ww[].zip.all!q{ a[0] != a[1] }) + .filter!(ww => ww[].equal!q{ a != b }) .array) .filter!(not!empty) .array 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 94d49b1f3c..34eed5b85d 100644 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d @@ -1,29 +1,27 @@ -import std.stdio, std.file, std.algorithm, std.string, std.range, +import std.stdio, std.file, std.algorithm, std.string, std.array, std.functional, std.exception; -string[2][] findDeranged(string[] words) pure /*nothrow*/ { - //return words.pairwise.filter!(ww=> ww[].zip.all!q{a[0] != a[1]}); +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 (zip(w1, w2).all!q{ a[0] != a[1] }) + if (w1.representation.equal!q{ a != b }(w2.representation)) result ~= [w1, w2]; return result; } void main() { Appender!(string[])[30] wClasses; - //foreach (word; "unixdict.txt".readText.splitter) - foreach (word; std.algorithm.splitter("unixdict.txt".readText)) - wClasses[$ - word.length] ~= word; + foreach (const w; "unixdict.txt".readText.splitter) + wClasses[$ - w.length] ~= w; - "Longest deranged anagrams:".writeln; - foreach (words; wClasses[].map!q{ a.data }.filter!(not!empty)) { + foreach (const ws; wClasses[].map!q{ a.data }.filter!(not!empty)) { string[][const ubyte[]] anags; // Assume ASCII input. - foreach (w; words) + foreach (immutable w; ws) anags[w.dup.representation.sort().release.assumeUnique]~= w; auto pairs = anags.byValue.map!findDeranged.joiner; if (!pairs.empty) - return writefln(" %-(%s %)", pairs.front); + return writefln("Longest deranged: %-(%s %)", pairs.front); } } diff --git a/Task/Anagrams-Deranged-anagrams/OCaml/anagrams-deranged-anagrams.ocaml b/Task/Anagrams-Deranged-anagrams/OCaml/anagrams-deranged-anagrams.ocaml index 92781c35ac..2cf0ade053 100644 --- a/Task/Anagrams-Deranged-anagrams/OCaml/anagrams-deranged-anagrams.ocaml +++ b/Task/Anagrams-Deranged-anagrams/OCaml/anagrams-deranged-anagrams.ocaml @@ -40,7 +40,7 @@ let () = try Hashtbl.find h key with Not_found -> [] in - Hashtbl.add h key (word::l); + Hashtbl.replace h key (word::l); done with End_of_file -> close_in ic; let lst = diff --git a/Task/Anagrams/Component-Pascal/anagrams-2.component b/Task/Anagrams/Component-Pascal/anagrams-2.component index 077815ca61..91e308b322 100644 --- a/Task/Anagrams/Component-Pascal/anagrams-2.component +++ b/Task/Anagrams/Component-Pascal/anagrams-2.component @@ -1,9 +1,9 @@ -import std.stdio, std.algorithm, std.range, std.string, std.exception; +import std.stdio, std.algorithm, std.string, std.exception, std.file; void main() { - string[][const ubyte[]] an; - foreach (w; "unixdict.txt".File.byLine(KeepTerminator.no)) - an[w.dup.representation.sort().release.assumeUnique] ~= w.idup; + string[][ubyte[]] an; + foreach (w; "unixdict.txt".readText.splitLines) + an[w.dup.representation.sort().release.assumeUnique] ~= w; immutable m = an.byValue.map!q{ a.length }.reduce!max; writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m)); } diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index b27b918e4d..2e7259d070 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -1,13 +1,14 @@ #define system. #define system'collections. -#define extensions'text. +#define system'routines. +#define extensions. #define extensions'text. // --- Normalized --- -#symbol Normalized = &&:aLiteral +#symbol Normalized = (:aLiteral) [ - ^ Summing new:(String new) foreach:(arrayControl sort:(stringControl toArray:aLiteral)) Literal. + ^ Summing new:(String new) foreach:(arrayControl sort:(literalControl toArray:aLiteral)) literal. ]. // --- Program --- @@ -16,20 +17,20 @@ [ #var aDictionary := Dictionary new. - textFileControl forEachLine:"unixdict.txt" &do: &&:aWord + textFileControl forEachLine:"unixdict.txt" &do: aWord [ - #var aKey := Normalized eval:aWord. - #var anItem := aDictionary @ aKey. + #var aKey := Normalized:aWord. + #var anItem := aDictionary getAt &key:aKey. nil == anItem ? [ anItem := List new. - aDictionary setAt:aKey:anItem. + aDictionary set &key:aKey &value:anItem. ]. anItem += aWord. ]. - listControl sort:aDictionary &with: &&:aFormer:aLater [ aFormer Value Count > aLater Value Count ]. + listControl sort:aDictionary &with: (:aFormer:aLater) [ aFormer value length > aLater value length ]. - listControl foreach:aDictionary &top:20 &do: &&:aPair [ console writeLine:(ListPresenter new:(aPair Value)) ]. + controlEx foreach:aDictionary &top:20 &do: aPair [ consoleEx writeLine:(aPair value) ]. ]. diff --git a/Task/Anagrams/Go/anagrams-1.go b/Task/Anagrams/Go/anagrams-1.go index e26b0ab87a..938ca53e8c 100644 --- a/Task/Anagrams/Go/anagrams-1.go +++ b/Task/Anagrams/Go/anagrams-1.go @@ -1,22 +1,30 @@ package main import ( + "bytes" "fmt" "io/ioutil" + "net/http" "sort" - "strings" ) func main() { - b, err := ioutil.ReadFile("unixdict.txt") + r, err := http.Get("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + if err != nil { + fmt.Println(err) + return + } + b, err := ioutil.ReadAll(r.Body) + r.Body.Close() if err != nil { fmt.Println(err) return } var ma int - m := make(map[string][]string) - for _, word := range strings.Split(string(b), "\n") { - bs := byteSlice(word) + var bs byteSlice + m := make(map[string][][]byte) + for _, word := range bytes.Fields(b) { + bs = append(bs[:0], byteSlice(word)...) sort.Sort(bs) k := string(bs) a := append(m[k], word) @@ -27,13 +35,13 @@ func main() { } for _, a := range m { if len(a) == ma { - fmt.Println(a) + fmt.Printf("%s\n", a) } } } type byteSlice []byte -func (b byteSlice) Len() int { return len(b) } -func (b byteSlice) Swap(i, j int) { b[i], b[j] = b[j], b[i] } +func (b byteSlice) Len() int { return len(b) } +func (b byteSlice) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byteSlice) Less(i, j int) bool { return b[i] < b[j] } diff --git a/Task/Anagrams/Nimrod/anagrams.nimrod b/Task/Anagrams/Nimrod/anagrams.nimrod new file mode 100644 index 0000000000..29650e835e --- /dev/null +++ b/Task/Anagrams/Nimrod/anagrams.nimrod @@ -0,0 +1,52 @@ +import tables + +proc sort(s: string): string = + var + i,j: int + t: char + + result = s + for i in 0 .. result.len - 1: + j = i + t = result[j] + while(j > 0) and (result[j - 1] > t): + result[j] = result[j - 1] + dec(j) + result[j] = t +# end sort + +proc maxCount(an: TTable[string,seq[string]]): int = + result = 0 + for v in an.values: + if v.len > result: + result = v.len +#end maxCount + +proc showAnagrams(s: seq[string]) = + for v in s: + write(stdout,v) + write(stdout," ") + writeln(stdout,"") +#end showAnagrams + +proc processFile: TTable[string,seq[string]] = + var + fd: TFile + sline,line: string + + result = initTable[string,seq[string]]() + if Open(fd,"unixdict.txt"): + while not EndOfFile(fd): + line = fd.readLine() + sline = sort(line) + if result.hasKey(sline): + result[sline] = result[sline] & line + else: + result[sline] = @[line] + +var + anagrams:TTable[string,seq[string]] = processFile() + max = anagrams.maxCount + +for v in anagrams.values: + if v.len == max: showAnagrams(v) diff --git a/Task/Anagrams/OCaml/anagrams.ocaml b/Task/Anagrams/OCaml/anagrams.ocaml index 7cfd4217c5..794e464044 100644 --- a/Task/Anagrams/OCaml/anagrams.ocaml +++ b/Task/Anagrams/OCaml/anagrams.ocaml @@ -23,7 +23,7 @@ let () = try Hashtbl.find h k with Not_found -> [] in - Hashtbl.add h k (w::l); + Hashtbl.replace h k (w::l); done with End_of_file -> (); let n = Hashtbl.fold (fun _ lw n -> max n (List.length lw)) h 0 in Hashtbl.iter (fun _ lw -> diff --git a/Task/Anagrams/Ruby/anagrams-2.rb b/Task/Anagrams/Ruby/anagrams-2.rb index 5157076227..9cf7089876 100644 --- a/Task/Anagrams/Ruby/anagrams-2.rb +++ b/Task/Anagrams/Ruby/anagrams-2.rb @@ -1,14 +1,4 @@ require 'open-uri' -anagram = nil - -open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| - anagram = f.read.split.group_by {|s| s.each_char.sort} -end - -count = anagram.each_value.map {|ana| ana.length}.max -anagram.each_value do |ana| - if ana.length >= count - p ana - end -end +anagrams = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt'){|f| f.read.split.group_by{|w| w.each_char.sort} } +anagrams.values.group_by(&:size).max.last.each{|group| puts group.join(", ") } diff --git a/Task/Animate-a-pendulum/Factor/animate-a-pendulum.factor b/Task/Animate-a-pendulum/Factor/animate-a-pendulum.factor index b78633bc1a..946e697175 100644 --- a/Task/Animate-a-pendulum/Factor/animate-a-pendulum.factor +++ b/Task/Animate-a-pendulum/Factor/animate-a-pendulum.factor @@ -14,8 +14,7 @@ CONSTANT: theta0 0.5 : theta ( -- theta ) current-time omega0 * cos theta0 * ; : relative-xy ( theta l -- xy ) - [ [ sin ] [ cos ] bi ] - [ [ * ] curry ] bi* bi@ 2array ; + swap [ sin * ] [ cos * ] 2bi 2array ; : theta-to-xy ( origin theta l -- xy ) relative-xy v+ ; TUPLE: pendulum-gadget < gadget alarm ; diff --git a/Task/Anonymous-recursion/00DESCRIPTION b/Task/Anonymous-recursion/00DESCRIPTION index 59f9003a1e..0a0f286b5e 100644 --- a/Task/Anonymous-recursion/00DESCRIPTION +++ b/Task/Anonymous-recursion/00DESCRIPTION @@ -1,6 +1,6 @@ While implementing a recursive function, it often happens that we must resort to a separate "helper function" to handle the actual recursion. -This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), cause unwanted side-effects, and/or the function doesn't have the right arguments and/and return values. +This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), cause unwanted side-effects, and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like "foo2" or "foo_helper". I have always found it painful to come up with a proper name, and see a quite some disadvantages: diff --git a/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-1.djv b/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-1.djv index e12c0c2c3f..2f1018abf1 100644 --- a/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-1.djv +++ b/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-1.djv @@ -15,4 +15,4 @@ Y set :fibo for j range 0 10: - print fibo j + !print fibo j diff --git a/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-2.djv b/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-2.djv index c6080a0d40..35985bc037 100644 --- a/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-2.djv +++ b/Task/Anonymous-recursion/Deja-Vu/anonymous-recursion-2.djv @@ -12,4 +12,4 @@ fibo-2 n: call for j range 0 10: - print fibo-2 j + !print fibo-2 j diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index 0774d82475..cb67970619 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -1,22 +1,24 @@ #define system. -#symbol fibo = &&:n +#symbol fibo = (:n) [ n < 0 ? [ #throw InvalidArgumentException new:"Must be non negative". ]. - ^ &&:n [ (n > 1) ? [ ($self:(n - 2)) + ($self:(n - 1)) ] ! [ n ] ] : n. + ^ { eval:n [ ^ (n > 1) ? [ ($self:(n - 2)) + ($self:(n - 1)) ] ! [ n ]. ] }:n. ]. #symbol program = [ - control from:-1 &to:10 &do: &&:i + control from:-1 &to:10 &do: i [ - console << "%fib(" << i << ")=". + console << "fib(" << i << ")=". - console writeLine:(fibo:i) | onInvalidArgumentError: &&:e + console writeLine:(fibo:i) | onInvalidArgumentError: e [ console writeLine:"invalid". ]. ]. + + console readChar. ]. diff --git a/Task/Anonymous-recursion/Forth/anonymous-recursion-3.fth b/Task/Anonymous-recursion/Forth/anonymous-recursion-3.fth new file mode 100644 index 0000000000..fe292dcd69 --- /dev/null +++ b/Task/Anonymous-recursion/Forth/anonymous-recursion-3.fth @@ -0,0 +1,3 @@ +: fib ( +n -- ) + dup 0< abort" Negative numbers don't exist" + [: dup 2 < ?exit 1- dup MYSELF swap 1- MYSELF + ;] execute . ; diff --git a/Task/Anonymous-recursion/Julia/anonymous-recursion.julia b/Task/Anonymous-recursion/Julia/anonymous-recursion.julia new file mode 100644 index 0000000000..c213154959 --- /dev/null +++ b/Task/Anonymous-recursion/Julia/anonymous-recursion.julia @@ -0,0 +1,7 @@ +function fib(n) + if n < 0 + throw(ArgumentError("negative arguments not allowed")) + end + aux(m) = m < 2 ? one(m) : aux(m-1) + aux(m-2) + aux(n) +end diff --git a/Task/Apply-a-callback-to-an-array/Deja-Vu/apply-a-callback-to-an-array.djv b/Task/Apply-a-callback-to-an-array/Deja-Vu/apply-a-callback-to-an-array.djv new file mode 100644 index 0000000000..ae28ff4f29 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Deja-Vu/apply-a-callback-to-an-array.djv @@ -0,0 +1,8 @@ +!. map @++ [ 1 4 8 ] + +#implemented roughly like this: +#map f lst: +# ] +# for i in lst: +# f i +# [ diff --git a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena index da6a6eb629..913597444c 100644 --- a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena +++ b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena @@ -1,7 +1,7 @@ #define system. #symbol PrintSecondPower = - &&:n [ console writeLine:(n * n) ]. + (:n) [ console writeLine:(n * n) ]. #symbol program = [ diff --git a/Task/Apply-a-callback-to-an-array/GAP/apply-a-callback-to-an-array.gap b/Task/Apply-a-callback-to-an-array/GAP/apply-a-callback-to-an-array.gap index 4515dd4421..aa162eec9e 100644 --- a/Task/Apply-a-callback-to-an-array/GAP/apply-a-callback-to-an-array.gap +++ b/Task/Apply-a-callback-to-an-array/GAP/apply-a-callback-to-an-array.gap @@ -7,6 +7,10 @@ a; # [ 1, 4, 9, 16 ] # Apply and don't change values +List(b, n -> n*n); +# [ 1, 4, 9, 16 ] + +# Apply and don't return anything (only side effects) Perform(b, Display); 1 2 diff --git a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia index f53b19a706..d213dbf5df 100644 --- a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia +++ b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia @@ -17,6 +17,6 @@ end squares3 = [n * n for n in numbers] # no need for a function, -squares4 = numbers .* numbers #element-wise operation +squares4 = numbers .* numbers # element-wise operation -squares4a = numbers .^ 2 #includes .+, .-, ./, comparison, and bitwise operations as well +squares4a = numbers .^ 2 # most arithmetic operations can be done element-wise diff --git a/Task/Apply-a-callback-to-an-array/PL-I/apply-a-callback-to-an-array.pli b/Task/Apply-a-callback-to-an-array/PL-I/apply-a-callback-to-an-array.pli new file mode 100644 index 0000000000..6c9085e5de --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/PL-I/apply-a-callback-to-an-array.pli @@ -0,0 +1,3 @@ + declare x(5) initial (1,3,5,7,8); + x = sqrt(x); + x = sin(x); diff --git a/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia b/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia index f88b442618..3664eeac87 100644 --- a/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia +++ b/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia @@ -1,11 +1,11 @@ -julia> @elapsed big = string(BigInt(5)^4^3^2) +julia> @elapsed bigstr = string(BigInt(5)^4^3^2) 0.017507363 -julia> length(big) +julia> length(bigstr) 183231 -julia> big[1:20] +julia> bigstr[1:20] "62060698786608744707" -julia> big[end-20:end] +julia> bigstr[end-20:end] "892256259918212890625" diff --git a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx index c708819f2c..5b4292be67 100644 --- a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx +++ b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx @@ -1,11 +1,13 @@ /*REXX program to calculate and demonstrate arbitrary precision numbers.*/ numeric digits 200000 -check = 62060698786608744707...92256259918212890625 + n = 5 ** (4 ** (3 ** 2)) /*calc. multiple exponentations. */ -sampl = left(n, 20)'...'right(n, 20) + +check = 62060698786608744707...92256259918212890625 +sampl = left(n, 20) || '...' || right(n, 20) + say ' check:' check say 'sample:' sampl -say 'digits:' length(n) say if check==sampl then say 'passed!' else say 'failed!' diff --git a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx index 4753dbe0da..658ada907e 100644 --- a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx +++ b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx @@ -1,7 +1,5 @@ /*REXX program to calculate and demonstrate arbitrary precision numbers.*/ -numeric digits 5 /*set to low precision for speed.*/ -check = 62060698786608744707...92256259918212890625 - +numeric digits 5 + 1 /*6 is needed (not 5) for ooRexx.*/ n=5** (4** (3** 2)) /*calc. multiple exponentations. */ parse var n 'E' pow . /*POW might be null, so N is OK.*/ @@ -11,7 +9,9 @@ if pow\=='' then do /*general case: POW might be < 0*/ n=5** (4** (3** 2)) /*calc. multiple exponentations. */ end +check = 62060698786608744707...92256259918212890625 sampl = left(n, 20)'...'right(n, 20) + say ' check:' check say 'sample:' sampl say 'digits:' length(n) diff --git a/Task/Arithmetic-Complex/COBOL/arithmetic-complex.cobol b/Task/Arithmetic-Complex/COBOL/arithmetic-complex.cobol new file mode 100644 index 0000000000..b64fe2ecc3 --- /dev/null +++ b/Task/Arithmetic-Complex/COBOL/arithmetic-complex.cobol @@ -0,0 +1,98 @@ + $SET SOURCEFORMAT "FREE" +class-id Prog. +method-id. Main static. +procedure division. + declare a as type Complex = new Complex(1, 1) + declare b as type Complex = new Complex(3.14159, 1.25) + + display "a = " a + display "b = " b + display space + + declare result as type Complex = a + b + display "a + b = " result + move (a - b) to result + display "a - b = " result + move (a * b) to result + display "a * b = " result + move (a / b) to result + display "a / b = " result + move (- b) to result + display "-b = " result + display space + + display "Inverse of b: " type Complex::Inverse(b) + display "Conjugate of b: " type Complex::Conjugate(b) +end method. +end class. + +class-id Complex. + +01 Real float-long property. +01 Imag float-long property. + +method-id new. + set Real, Imag to 0 +end method. + +method-id new. +procedure division using value real-val as float-long, imag-val as float-long. + set Real to real-val + set Imag to imag-val +end method. + +method-id Norm static. +procedure division using value a as type Complex returning ret as float-long. + compute ret = a::Real ** 2 + a::Imag ** 2 +end method. + +method-id Inverse static. +procedure division using value a as type Complex returning ret as type Complex. + declare norm as float-long = type Complex::Norm(a) + set ret to new Complex(a::Real / norm, (0 - a::Imag) / norm) +end method. + +method-id Conjugate static. +procedure division using value a as type Complex returning c as type Complex. + set c to new Complex(a::Real, 0 - a::Imag) +end method. + +method-id ToString override. +procedure division returning str as string. + set str to type String::Format("{0}{1:+#0;-#}i", Real, Imag) +end method. + +operator-id + . +procedure division using value a as type Complex, b as type Complex + returning c as type Complex. + set c to new Complex(a::Real + b::Real, a::Imag + b::Imag) +end operator. + +operator-id - . +procedure division using value a as type Complex, b as type Complex + returning c as type Complex. + set c to new Complex(a::Real - b::Real, a::Imag - b::Imag) +end operator. + +operator-id * . +procedure division using value a as type Complex, b as type Complex + returning c as type Complex. + set c to new Complex(a::Real * b::Real - a::Imag * b::Imag, + a::Real * b::Imag + a::Imag * b::Real) +end operator. + +operator-id / . +procedure division using value a as type Complex, b as type Complex + returning c as type Complex. + set c to new Complex() + declare b-norm as float-long = type Complex::Norm(b) + compute c::Real = (a::Real * b::Real + a::Imag * b::Imag) / b-norm + compute c::Imag = (a::Imag * b::Real - a::Real * b::Imag) / b-norm +end operator. + +operator-id - . +procedure division using value a as type Complex returning ret as type Complex. + set ret to new Complex(- a::Real, 0 - a::Imag) +end operator. + +end class. diff --git a/Task/Arithmetic-Complex/Dart/arithmetic-complex.dart b/Task/Arithmetic-Complex/Dart/arithmetic-complex.dart new file mode 100644 index 0000000000..e5d57a7091 --- /dev/null +++ b/Task/Arithmetic-Complex/Dart/arithmetic-complex.dart @@ -0,0 +1,50 @@ +class complex { + + num real=0; + num imag=0; + + complex(num r,num i){ + this.real=r; + this.imag=i; + } + + + complex add(complex b){ + return new complex(this.real + b.real, this.imag + b.imag); + } + + complex mult(complex b){ + //FOIL of (a+bi)(c+di) with i*i = -1 + return new complex(this.real * b.real - this.imag * b.imag, this.real * b.imag + this.imag * b.real); + } + + complex inv(){ + //1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable + num denom = real * real + imag * imag; + double r =real/denom; + double i= -imag/denom; + return new complex( r,-i); + } + + complex neg(){ + return new complex(-real, -imag); + } + + complex conj(){ + return new complex(real, -imag); + } + + +String toString(){ + return this.real.toString()+' + '+ this.imag.toString()+'*i'; +} +} +void main() { + var cl= new complex(1,2); + var cl2= new complex(3,-1); + print(cl.toString()); + print(cl2.toString()); + print(cl.inv().toString()); + print(cl2.mult(cl).toString()); + +} diff --git a/Task/Arithmetic-Complex/Julia/arithmetic-complex.julia b/Task/Arithmetic-Complex/Julia/arithmetic-complex.julia new file mode 100644 index 0000000000..0d52f7165e --- /dev/null +++ b/Task/Arithmetic-Complex/Julia/arithmetic-complex.julia @@ -0,0 +1,22 @@ +julia> z1 = 1.5 + 3im +julia> z2 = 1.5 + 1.5im +julia> z1 + z2 +3.0 + 4.5im +julia> z1 - z2 +0.0 + 1.5im +julia> z1 * z2 +-2.25 + 6.75im +julia> z1 / z2 +1.5 + 0.5im +julia> - z1 +-1.5 - 3.0im +julia> conj(z1), z1' # two ways to conjugate +(1.5 - 3.0im,1.5 - 3.0im) +julia> abs(z1) +3.3541019662496847 +julia> z1^z2 +-1.102482955327779 - 0.38306415117199305im +julia> real(z1) +1.5 +julia> imag(z1) +3.0 diff --git a/Task/Arithmetic-Complex/Nimrod/arithmetic-complex.nimrod b/Task/Arithmetic-Complex/Nimrod/arithmetic-complex.nimrod new file mode 100644 index 0000000000..93a744022b --- /dev/null +++ b/Task/Arithmetic-Complex/Nimrod/arithmetic-complex.nimrod @@ -0,0 +1,10 @@ +import complex +var a: TComplex = (1.0,1.0) +var b: TComplex = (3.1415,1.2) + +echo ("a : " & $a) +echo ("b : " & $b) +echo ("a + b: " & $(a + b)) +echo ("a * b: " & $(a * b)) +echo ("1/a : " & $(1/a)) +echo ("-a : " & $(-a)) diff --git a/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb b/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb index ce1c1cc161..f279509034 100644 --- a/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb +++ b/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb @@ -6,6 +6,9 @@ i = Complex::I # 2. use Complex::I b = 3.14159 + 1.25 * i c = '1/2+3/4i'.to_c # 3. Use the .to_c method from String, result ((1/2)+(3/4)*i) +#Ruby 2.1 introduced a suffix to create a complex: +c = 1.0/2+3/4i # (0.5-(3/4)*i) + # Operations: puts a + b # addition puts a * b # multiplication diff --git a/Task/Arithmetic-Integer/Bracmat/arithmetic-integer.bracmat b/Task/Arithmetic-Integer/Bracmat/arithmetic-integer.bracmat new file mode 100644 index 0000000000..22861adb31 --- /dev/null +++ b/Task/Arithmetic-Integer/Bracmat/arithmetic-integer.bracmat @@ -0,0 +1,17 @@ + ( enter + = put$"Enter two integer numbers, separated by space:" + & get':(~/#?k_~/#?m|quit:?k) + | out + $ "You must enter two integer numbers! Enter \"quit\" if you don't know how to do that." + & !enter + ) +& !enter +& !k:~quit +& out$("You entered" !k and !m ". Now look:") +& out$("Sum:" !k+!m) +& out$("Difference:" !k+-1*!m) +& out$("Product:" !k*!m) +& out$("Integer division:" div$(!k.!m)) +& out$("Remainder:" mod$(!k.!m)) +& out$("Exponentiation:" !k^!m) +& done; diff --git a/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper b/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper new file mode 100644 index 0000000000..63b9ff17a3 --- /dev/null +++ b/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper @@ -0,0 +1,11 @@ +Function( a, b ) + ? "a+b", a + b + ? "a-b", a - b + ? "a*b", a * b + // The quotient isn't integer, so we use the Int() function, which truncates it downward. + ? "a/b", Int( a / b ) + // Remainder: + ? "a%b", a % b + // Exponentiation is also a base arithmetic operation + ? "a**b", a ** b +Return Nil diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index d6b0469c42..46de656c81 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -1,6 +1,5 @@ #define system. -#define extensions'io. -#define extensions'math. +#define extensions. // --- Program --- @@ -13,5 +12,5 @@ consoleEx << a << " - " << b << " = " << a - b << "%n". consoleEx << a << " * " << b << " = " << a * b << "%n". consoleEx << a << " / " << b << " = " << a / b << "%n". // truncates towards 0 - consoleEx << a << " %% " << b << " = " << (modulus:a:b) << "%n". // matches sign of first operand + consoleEx << a << " %% " << b << " = " << (a~mathOp mod:b) << "%n". // matches sign of first operand ]. diff --git a/Task/Arithmetic-Integer/Nimrod/arithmetic-integer.nimrod b/Task/Arithmetic-Integer/Nimrod/arithmetic-integer.nimrod new file mode 100644 index 0000000000..43a6b90847 --- /dev/null +++ b/Task/Arithmetic-Integer/Nimrod/arithmetic-integer.nimrod @@ -0,0 +1,22 @@ +import parseopt,strutils + +var + opt: TOptParser = initOptParser() + str = opt.cmdLineRest.split + a: int = 0 + b: int = 0 + +try: + a = parseInt(str[0]) + b = parseInt(str[1]) +except EinvalidValue: + quit("Invalid params. Two integers are expected.") + + +echo ("a : " & $a) +echo ("b : " & $b) +echo ("a + b : " & $(a+b)) +echo ("a - b : " & $(a-b)) +echo ("a * b : " & $(a*b)) +echo ("a div b: " & $(a div b)) +echo ("a mod b: " & $(a mod b)) diff --git a/Task/Arithmetic-Integer/VBA/arithmetic-integer.vba b/Task/Arithmetic-Integer/VBA/arithmetic-integer.vba new file mode 100644 index 0000000000..f56c8ca28f --- /dev/null +++ b/Task/Arithmetic-Integer/VBA/arithmetic-integer.vba @@ -0,0 +1,17 @@ +'Arithmetic - Integer +Sub RosettaArithmeticInt() +Dim opr As Variant, a As Integer, b As Integer +On Error Resume Next + +a = CInt(InputBox("Enter first integer", "XLSM | Arithmetic")) +b = CInt(InputBox("Enter second integer", "XLSM | Arithmetic")) + +Debug.Print "a ="; a, "b="; b, vbCr +For Each opr In Split("+ - * / \ mod ^", " ") + Select Case opr + Case "mod": Debug.Print "a mod b", a; "mod"; b, a Mod b + Case "\": Debug.Print "a \ b", a; "\"; b, a \ b + Case Else: Debug.Print "a "; opr; " b", a; opr; b, Evaluate(a & opr & b) + End Select +Next opr +End Sub diff --git a/Task/Arithmetic-Rational/D/arithmetic-rational.d b/Task/Arithmetic-Rational/D/arithmetic-rational.d index 98506bb826..4f4087ca31 100644 --- a/Task/Arithmetic-Rational/D/arithmetic-rational.d +++ b/Task/Arithmetic-Rational/D/arithmetic-rational.d @@ -1,16 +1,16 @@ import std.bigint, std.traits, std.conv; -T gcd(T)(/*in*/ T a, /*in*/ T b) /*pure nothrow*/ { - // std.numeric.gcd doesn't work with BigInt. +// std.numeric.gcd doesn't work with BigInt. +T gcd(T)(in T a, in T b) pure /*nothrow*/ { return (b != 0) ? gcd(b, a % b) : (a < 0) ? -a : a; } -T lcm(T)(/*in*/ T a, /*in*/ T b) { +T lcm(T)(in T a, in T b) pure /*nothrow*/ { return a / gcd(a, b) * b; } struct RationalT(T) { - /*const*/ private T num, den; // Numerator & denominator. + private T num, den; // Numerator & denominator. private enum Type { NegINF = -2, NegDEN = -1, @@ -28,10 +28,10 @@ struct RationalT(T) { den = 1UL; } - this(U, V)(/*in*/ U n, /*in*/ V d) /*pure nothrow*/ { + this(U, V)(in U n, in V d) pure /*nothrow*/ { num = toT(n); den = toT(d); - /*const*/ T common = gcd(num, den); + const common = gcd(num, den); if (common != 0) { num /= common; den /= common; @@ -45,7 +45,7 @@ struct RationalT(T) { } } - static T toT(U)(/*in*/ ref U n) pure nothrow if (is(U == T)) { + static T toT(U)(in ref U n) pure nothrow if (is(U == T)) { return n; } @@ -54,15 +54,15 @@ struct RationalT(T) { return result; } - T nomerator() /*const*/ pure nothrow @property { + T nomerator() const pure nothrow @property { return num; } - T denominator() /*const*/ pure nothrow @property { + T denominator() const pure nothrow @property { return den; } - string toString() /*pure const*/ { + string toString() const /*pure nothrow*/ { if (den != 0) return num.text ~ (den == 1 ? "" : "/" ~ den.text); if (num == 0) @@ -71,52 +71,54 @@ struct RationalT(T) { return ((num < 0) ? "-" : "+") ~ "infRat"; } - real toReal() const { - return num.toLong / cast(real)den.toLong; + real toReal() pure const /*nothrow*/ { + static if (is(T == BigInt)) + return num.toLong / cast(real)den.toLong; + else + return num / cast(real)den; } - RationalT opBinary(string op)(/*in*/ RationalT r) - /*const pure nothrow*/ if (op == "+" || op == "-") { + RationalT opBinary(string op)(in RationalT r) + const pure /*nothrow*/ if (op == "+" || op == "-") { T common = lcm(den, r.den); T n = mixin("common / den * num" ~ op ~ "common / r.den * r.num" ); return RationalT(n, common); } - RationalT opBinary(string op)(/*in*/ RationalT r) - /*const pure nothrow*/ if (op == "*") { + RationalT opBinary(string op)(in RationalT r) + const pure /*nothrow*/ if (op == "*") { return RationalT(num * r.num, den * r.den); } - RationalT opBinary(string op)(/*in*/ RationalT r) - /*const pure nothrow*/ if (op == "/") { + RationalT opBinary(string op)(in RationalT r) + const pure /*nothrow*/ if (op == "/") { return RationalT(num * r.den, den * r.num); } RationalT opBinary(string op, U)(in U r) - /*const pure nothrow*/ if (isIntegral!U && (op == "+" || - op == "-" || op == "*" || op == "/")) { + const pure /*nothrow*/ if (isIntegral!U && (op == "+" || + op == "-" || op == "*" || op == "/")) { return opBinary!op(RationalT(r)); } RationalT opBinary(string op)(in size_t p) - /*const pure nothrow*/ if (op == "^^") { + const pure /*nothrow*/ if (op == "^^") { return RationalT(num ^^ p, den ^^ p); } RationalT opBinaryRight(string op, U)(in U l) - /*const pure nothrow*/ if (isIntegral!U) { + const pure /*nothrow*/ if (isIntegral!U) { return RationalT(l).opBinary!op(RationalT(num, den)); } - RationalT opOpAssign(string op, U)(/*in*/ U l) - /*const pure nothrow*/ { + RationalT opOpAssign(string op, U)(in U l) pure /*nothrow*/ { mixin("this = this " ~ op ~ "l;"); return this; } RationalT opUnary(string op)() - /*const pure nothrow*/ if (op == "+" || op == "-") { + const pure /*nothrow*/ if (op == "+" || op == "-") { return RationalT(mixin(op ~ "num"), den); } @@ -124,14 +126,14 @@ struct RationalT(T) { return num != 0; } - int opEquals(U)(/*in*/ U r) /*const pure nothrow*/ { + int 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 nothrow { auto rhs = RationalT(r); if (type() == Type.NaRAT || rhs.type() == Type.NaRAT) throw new Exception("Compare involve a NaRAT."); @@ -143,7 +145,7 @@ struct RationalT(T) { return (diff == 0) ? 0 : ((diff < 0) ? -1 : 1); } - Type type() /*const pure nothrow*/ { + Type type() const pure nothrow { if (den > 0) return Type.NORMAL; if (den < 0) return Type.NegDEN; if (num > 0) return Type.PosINF; diff --git a/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d b/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d index 3415266730..f1ca2ae58f 100644 --- a/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d +++ b/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d @@ -31,10 +31,11 @@ final class XP { this(string s=")", int p = -1) nothrow { str = s; pos = p; - type = Type.Num; + auto localType = Type.Num; foreach_reverse (immutable t; [EnumMembers!Type[1 .. $]]) if (opChar[t] == s) - type = t; + localType = t; + this.type = localType; } override int opCmp(Object other) pure { diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena index 477ce675b5..24f07053ce 100644 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena @@ -1,285 +1,302 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'patterns'*. -#define ext'io'*. -#define ext'convertors'*. +#define system. +#define extensions. -#subject parse_order. +// --- Token --- #class Token { #field theValue. - #initializer + #constructor new [ - theValue := String. + theValue := String new. ] - #method parse_order'get = 0. + #constructor new : aValue + [ + theValue := String new:aValue. + ] - #method += aChar + #method ParseOrder = 0. + + #method append : aChar [ theValue += aChar. ] - #method + aNode + #method add : aNode [ ^ aNode += self. ] - #method numeric = Real64Value &&literal:theValue &:erealformatter. + #method Number = convertor toReal:theValue. } +// --- Node --- #class Node { #field theLeft. #field theRight. + #field theState. - #role LeftAssigned - { - #method += aNode - [ - theRight := aNode. - - #shift. - ] - } - #role Empty - { - #method += aNode - [ - theLeft := aNode. - - #shift LeftAssigned. - ] - } - #initializer + #method setRight : aNode [ - #shift Empty. + theRight := aNode. + + theState := %appendRight. ] - #method + aNode + #method setLeft : aNode [ - #if (self parse_order > aNode parse_order)? - [ - self += aNode. - ] - | [ - aNode += self. + theLeft := aNode. - ^ aNode. - ]. + theState := %setRight. ] - #method += aNode + #constructor new [ - #if (theRight parse_order > aNode parse_order)? - [ + theState := %setLeft. + ] + + #method add : aNode + = (self ParseOrder > aNode ParseOrder) + ? [ + self += aNode. + + ^ self. + ] + ! [ + aNode += self. + + ^ aNode. + ]. + + #method appendRight : aNode + [ + (theRight ParseOrder > aNode ParseOrder) + ? [ theRight += aNode. ] - | [ + ! [ theRight := aNode += theRight. ]. ] + + #method append : anObject + = $self~theState eval:anObject. + + #method => theState. } -#class SummaryNode (Node) +// --- SummaryNode + +#class SummaryNode : Node { - #method parse_order'get = 2. + #method ParseOrder = 2. - #method numeric = theLeft numeric + theRight numeric. + #method Number = theLeft Number + theRight Number. } -#class DifferenceNode (Node) + +// --- DifferenceNode --- + +#class DifferenceNode : Node { - #method parse_order'get = 2. + #method ParseOrder = 2. - #method numeric = theLeft numeric - theRight numeric. + #method Number = theLeft Number - theRight Number. } -#class ProductNode (Node) + +// --- ProductNode --- + +#class ProductNode : Node { - #method parse_order'get = 1. + #method ParseOrder = 1. - #method numeric = theLeft numeric * theRight numeric. + #method Number = theLeft Number * theRight Number. } -#class FractionNode (Node) + +// --- FractionNode --- + +#class FractionNode : Node { - #method parse_order'get = 1. + #method ParseOrder = 1. - #method numeric = theLeft numeric / theRight numeric. + #method Number = theLeft Number / theRight Number. } + +// --- SubExpression --- + #class SubExpression { #field theParser. #field theCounter. - #role EOF - { - #method available'is [ control fail. ] - - #method += aChar [ $self fail. ] - } - - #initializer + #constructor new [ - theParser := arithmeval'Parser. - theCounter := Integer << 1. + theParser := arithmeval'Parser new. + theCounter := Integer new:1. ] - #method available'is [] + #method ParseOrder = 0. - #method parse_order'get = 0. - - #method + aNode + #method add : aNode [ ^ aNode += self. ] - #method append : aChar + #method validate [ - #if control if:(aChar == 41) - [ - theCounter -= 1. - ] - | if:(aChar == 40) - [ - theCounter += 1. - ]. + (theCounter < 0) + ? [ #throw Exception new:"Invalid expression". ]. - #if (theCounter == 0)? - [ #shift EOF. ^ $self. ]. - - theParser evaluate:aChar. + ^ (0 == theCounter). ] - #method numeric = theParser numeric. + #method append : aChar + [ + aChar => + 41 ? [ + theCounter -= 1. + ] + 40 ? [ theCounter += 1 ] + ! [ theParser evaluate:aChar ]. + ] + + #method Number + = $self validate + ? [ theParser Number ] + ! [ #throw Exception new:"Invalid expression". ]. } -#class Parser + +// ---- Parser ---- + +#class Parser : system'routines'BasePattern { #field theToken. #field theTopNode. + #field theState. - #role Brackets - { - #method evaluate : aChar - [ - theToken += aChar. + #method onBrackets : aChar + [ + theToken += aChar. - #if theToken available'is - | [ - #shift. - ]. - ] - } - #role Start - { - #method evaluate : aChar - [ - #if (40 == aChar)? - [ - theToken := SubExpression. + (theToken validate) + ? [ + theState := %onDigit. + ]. + ] + + #method onStart : aChar + [ + aChar => + 40 ? [ // ( + theToken := SubExpression new. theTopNode := theToken. - #shift Brackets. + theState := %onBrackets. ] - | [ - theToken := Token. + 45 ? [ // - + theToken := DifferenceNode new add:(Token new:"0"). + theTopNode := theToken. - theToken += aChar. + theState := %onOperator. + ] + ! [ + theToken := Token new. + theTopNode := theToken. + theState := %onDigit. - #shift. + $self appendDigit:aChar. ]. - ] - } - #role Operator - { - #method evaluate : aChar - [ - #if Control if:(48 < aChar) if:(58 > aChar) - [ - theToken := (Token += aChar). - - theTopNode += theToken. - - #shift. - ] - | if:(40 == aChar) - [ - theToken := SubExpression. - theTopNode += theToken. - - #shift Brackets. - ] - | [ $self fail. ]. - ] - } - - #initializer - [ - #shift Start. ] - #method numeric = theTopNode numeric. - - #method evaluate : aChar + #method onOperator : aChar [ - #if Control if:(48 < aChar) if:(58 > aChar) - [ + aChar => + 40 ? [ + theToken := SubExpression new. + theTopNode += theToken. + theState := %onBrackets. + ] + ! [ + theToken := Token new. + theTopNode += theToken. + theState := %onDigit. + + $self appendDigit:aChar. + ]. + ] + + #constructor new + [ + theState := %onStart. + ] + + #method Number = theTopNode Number. + + #method appendDigit : aChar + [ + (aChar >= 48) and:(aChar < 58) + ? [ theToken += aChar. ] - | if:(42 == aChar) // * - [ - theTopNode := theTopNode + ProductNode. - - #shift Operator. + ! [ + #throw Exception new:"Invalid expression". ] - | if:(47 == aChar) // / - [ - theTopNode := theTopNode + FractionNode. - #shift Operator. - ] - | if:(43 == aChar) // + - [ - theTopNode := theTopNode + SummaryNode. - - #shift Operator. - ] - | if:(45 == aChar) // - - [ - theTopNode := theTopNode + DifferenceNode. - - #shift Operator. - ] - | if:(40 == aChar) - [ - theToken := SubExpression. - theTopNode := theToken. - - #shift Brackets. - ] - | [ $self fail. ]. ] - #method start : aProcess + #method onDigit : aChar [ - aProcess run:self. + aChar => + 40 ? [ // ( + theToken := SubExpression new. + theTopNode := theToken. + theState := %onBrackets. + ] + 42 ? [ // * + theTopNode := theTopNode + ProductNode new. - ^ self numeric. + theState := %onOperator. + ] + 43 ? [ // + + theTopNode := theTopNode + SummaryNode new. + + theState := %onOperator. + ] + 45 ? [ // - + theTopNode := theTopNode + DifferenceNode new. + + theState := %onOperator. + ] + 47 ? // / + [ + theTopNode := theTopNode + FractionNode new. + + theState := %onOperator. + ] + ! [ + $self appendDigit:aChar. + ]. ] + + #method eval : aChar = $self~theState eval:aChar. } -#symbol Program = +#symbol program = [ - #var aText := String. + #var aText := String new. - #while ((Console >> aText) length > 0)? + control while:(consoleEx readLine:aText length > 0) &do: [ - #var aParser := Parser. + #var aParser := Parser new. - Console << "=" << aParser start:Scan::aText | ^^"Invalid Expression". - - Console << "%n". + consoleEx writeLine:"=" :(aParser foreach:aText Number) + | ifFailed: + [ + consoleEx writeLine:"Invalid Expression". + ]. ]. ]. diff --git a/Task/Arithmetic-evaluation/Liberty-BASIC/arithmetic-evaluation.liberty b/Task/Arithmetic-evaluation/Liberty-BASIC/arithmetic-evaluation.liberty new file mode 100644 index 0000000000..451bfdc9d4 --- /dev/null +++ b/Task/Arithmetic-evaluation/Liberty-BASIC/arithmetic-evaluation.liberty @@ -0,0 +1,235 @@ +'[RC] Arithmetic evaluation.bas +'Buld the tree (with linked nodes, in array 'cause LB has no pointers) +'applying shunting yard algorythm. +'Then evaluate tree + +global stack$ 'operator/brakets stack +stack$="" + +maxStack = 100 +dim stack(maxStack) 'nodes stack +global SP 'stack pointer +SP = 0 + +'------------------- +global maxNode,curFree +global FirstOp,SecondOp,isNumber,NodeCont +global opList$ +opList$ = "+-*/^" + +maxNode=100 +FirstOp=1 'pointers to other nodes; 0 means no pointer +SecondOp=2 +isNumber=3 'like, 1 is number, 0 is operator +NodeCont=4 'number if isNumber; or mid$("+-*/^", i, 1) for 1..5 operator + +dim node(NodeCont, maxNode) +'will be used from 1, 0 plays null pointer (no link) + +curFree=1 'first free node +'------------------- + +in$ = " 1 + 2 ^ 3 * 4 - 12 / 6 " +print "Input: " +print in$ + +'read tokens +token$ = "#" +while 1 + i=i+1 + token$ = word$(in$, i) + if token$ = "" then i=i-1: exit while + + select case + case token$ = "(" + 'If the token is a left parenthesis, then push it onto the stack. + call stack.push token$ + + case token$ = ")" + 'If the token is a right parenthesis: + 'Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. + 'Pop the left parenthesis from the stack, but not onto the output queue. + 'If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. + while stack.peek$() <> "(" + 'if stack is empty + if stack$="" then print "Error: no matching '(' for token ";i: end + 'add operator node to tree + child2=node.pop() + child1=node.pop() + call node.push addOpNode(child1,child2,stack.pop$()) + wend + discard$=stack.pop$() 'discard "(" + + case isOperator(token$) + 'If the token is an operator, o1, then: + 'while there is an operator token, o2, at the top of the stack, and + 'either o1 is left-associative and its precedence is equal to that of o2, + 'or o1 has precedence less than that of o2, + ' pop o2 off the stack, onto the output queue; + 'push o1 onto the stack + op1$=token$ + while(isOperator(stack.peek$())) + op2$=stack.peek$() + if (op2$<>"^" and precedence(op1$) = precedence(op2$)) _ + OR (precedence(op1$) < precedence(op2$)) then + '"^" is the only right-associative operator + 'add operator node to tree + child2=node.pop() + child1=node.pop() + call node.push addOpNode(child1,child2,stack.pop$()) + else + exit while + end if + wend + call stack.push op1$ + + case else 'number + 'actually, wrohg operator could end up here, like say % + 'If the token is a number, then + 'add leaf node to tree (number) + call node.push addNumNode(val(token$)) + end select + +wend + +'When there are no more tokens to read: +'While there are still operator tokens in the stack: +' If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. +' Pop the operator onto the output queue. +while stack$<>"" + if stack.peek$() = "(" then print "no matching ')'": end + 'add operator node to tree + child2=node.pop() + child1=node.pop() + call node.push addOpNode(child1,child2,stack.pop$()) +wend + +root = node.pop() +'call dumpNodes +print "Tree:" +call drawTree root, 1, 0, 3 +locate 1, 10 +print "Result: ";evaluate(root) + +end + +'------------------------------------------ +function isOperator(op$) + isOperator = instr(opList$, op$)<>0 AND len(op$)=1 +end function + +function precedence(op$) + if isOperator(op$) then + precedence = 1 _ + + (instr("+-*/^", op$)<>0) _ + + (instr("*/^", op$)<>0) _ + + (instr("^", op$)<>0) + end if +end function + +'------------------------------------------ +sub stack.push s$ + stack$=s$+"|"+stack$ +end sub + +function stack.pop$() + 'it does return empty on empty stack or queue + stack.pop$=word$(stack$,1,"|") + stack$=mid$(stack$,instr(stack$,"|")+1) +end function + +function stack.peek$() + 'it does return empty on empty stack or queue + stack.peek$=word$(stack$,1,"|") +end function + +'--------------------------------------- +sub node.push s + stack(SP)=s + SP=SP+1 +end sub + +function node.pop() + 'it does return -999999 on empty stack + if SP<1 then pop=-999999: exit function + SP=SP-1 + node.pop=stack(SP) +end function + +'======================================= +sub dumpNodes + for i = 1 to curFree-1 + print i, + for j = 1 to 4 + print node(j, i), + next + print + next + print +end sub + +function evaluate(node) + if node=0 then exit function + if node(isNumber, node) then + evaluate = node(NodeCont, node) + exit function + end if + 'else operator + op1 = evaluate(node(FirstOp, node)) + op2 = evaluate(node(SecondOp, node)) + select case node(NodeCont, node) 'opList$, "+-*/^" + case 1 + evaluate = op1+op2 + case 2 + evaluate = op1-op2 + case 3 + evaluate = op1*op2 + case 4 + evaluate = op1/op2 + case 5 + evaluate = op1^op2 + end select +end function + +sub drawTree node, level, leftRight, offsetY + if node=0 then exit sub + call drawTree node(FirstOp, node), level+1, leftRight-1/2^level, offsetY + + 'print node + 'count on 80 char maiwin + x = 40*(1+leftRight) + y = level+offsetY + locate x, y + 'print x, y,">"; + if node(isNumber, node) then + print node(NodeCont, node) + else + print mid$(opList$, node(NodeCont, node),1) + end if + + call drawTree node(SecondOp, node), level+1, leftRight+1/2^level, offsetY +end sub + +function addNumNode(num) +'returns new node + newNode=curFree + curFree=curFree+1 + node(isNumber,newNode)=1 + node(NodeCont,newNode)=num + + addNumNode = newNode +end function + +function addOpNode(firstChild, secondChild, op$) +'returns new node +'FirstOrSecond ignored if parent is 0 + newNode=curFree + curFree=curFree+1 + node(isNumber,newNode)=0 + node(NodeCont,newNode)=instr(opList$, op$) + + node(FirstOp,newNode)=firstChild + node(SecondOp,newNode)=secondChild + + addOpNode = newNode +end function diff --git a/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk b/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk index b3ed081e11..7519952e9f 100644 --- a/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk +++ b/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk @@ -1,16 +1,16 @@ #!/usr/bin/awk -f BEGIN { - printf("%.16g\n", agm(1.0,sqrt(0.5))); + printf "%.16g\n", agm(1.0,sqrt(0.5)) } function agm(a,g) { while (1) { - a0=a; - a=(a0+g)/2; - g=sqrt(a0*g); - if (abs(a0-a) < abs(a)*1e-15) break; + a0=a + a=(a0+g)/2 + g=sqrt(a0*g) + if (abs(a0-a) < abs(a)*1e-15) break } - return a; + return a } function abs(x) { - return (x<0 ? -x : x); + return (x<0 ? -x : x) } diff --git a/Task/Arithmetic-geometric-mean/Nimrod/arithmetic-geometric-mean.nimrod b/Task/Arithmetic-geometric-mean/Nimrod/arithmetic-geometric-mean.nimrod new file mode 100644 index 0000000000..dcc5f0f4ad --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Nimrod/arithmetic-geometric-mean.nimrod @@ -0,0 +1,14 @@ +import math + +proc agm(a, g: float,delta: float = 1.0e-15): float = + var + aNew: float = 0 + aOld: float = a + gOld: float = g + while (abs(aOld - gOld) > delta): + aNew = 0.5 * (aOld + gOld) + gOld = sqrt(aOld * gOld) + aOld = aNew + result = aOld + +echo ($agm(1.0,1.0/sqrt(2))) diff --git a/Task/Arithmetic-geometric-mean/PicoLisp/arithmetic-geometric-mean.l b/Task/Arithmetic-geometric-mean/PicoLisp/arithmetic-geometric-mean.l index d7520a22c2..d8303ef006 100644 --- a/Task/Arithmetic-geometric-mean/PicoLisp/arithmetic-geometric-mean.l +++ b/Task/Arithmetic-geometric-mean/PicoLisp/arithmetic-geometric-mean.l @@ -3,8 +3,8 @@ (de agm (A G) (do 7 (prog1 (/ (+ A G) 2) - (setq G (sqrt (* A G)) A @) ) ) ) + (setq G (sqrt A G) A @) ) ) ) (round - (agm 1.0 (*/ 1.0 1.0 (sqrt (* 2.0 1.0)))) + (agm 1.0 (*/ 1.0 1.0 (sqrt 2.0 1.0))) 70 ) diff --git a/Task/Array-concatenation/AWK/array-concatenation.awk b/Task/Array-concatenation/AWK/array-concatenation.awk index 72ec525c1f..fae85bec21 100644 --- a/Task/Array-concatenation/AWK/array-concatenation.awk +++ b/Task/Array-concatenation/AWK/array-concatenation.awk @@ -1,19 +1,19 @@ #!/usr/bin/awk -f BEGIN { - split("cul-de-sac",a,"-"); - split("1-2-3",b,"-"); + split("cul-de-sac",a,"-") + split("1-2-3",b,"-") concat_array(a,b,c) for (i in c) { - print i,c[i]; + print i,c[i] } } function concat_array(a,b,c) { for (i in a) { - c[++nc]=a[i]; + c[++nc]=a[i] } for (i in b) { - c[++nc]=b[i]; + c[++nc]=b[i] } } diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 60c5bae202..a013070804 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -1,9 +1,9 @@ -#define extensions'io. +#define extensions. #symbol program = [ #var a := (1,2,3). #var b := (4,5). - consoleEx write:"(" write::a write:") + (" write::b write:") = (" write::(a + b) writeLine:")". + consoleEx writeLine:"(":a:") + (":b:") = (":(a + b):")". ]. diff --git a/Task/Arrays/Deja-Vu/arrays.djv b/Task/Arrays/Deja-Vu/arrays.djv index 907e30f536..5d68c3d8e5 100644 --- a/Task/Arrays/Deja-Vu/arrays.djv +++ b/Task/Arrays/Deja-Vu/arrays.djv @@ -11,10 +11,10 @@ push-to l "Boo" local :l2 [ "Hi" "Boo" ] #this prints 2 -print len l +!print len l #this prints Hi -print get-from l 0 +!print get-from l 0 #this prints Boo -print pop-from l +!print pop-from l diff --git a/Task/Arrays/Elena/arrays-2.elena b/Task/Arrays/Elena/arrays-2.elena index bb68343048..9b96ec3462 100644 --- a/Task/Arrays/Elena/arrays-2.elena +++ b/Task/Arrays/Elena/arrays-2.elena @@ -1,4 +1,4 @@ - #var anArray := system'Array new &type'length:5. + #var anArray := system'Array new &length:5. anArray setAt:0:2. system'console writeLine:(anArray@0). diff --git a/Task/Arrays/Neko/arrays.neko b/Task/Arrays/Neko/arrays.neko new file mode 100644 index 0000000000..5d9ff6d122 --- /dev/null +++ b/Task/Arrays/Neko/arrays.neko @@ -0,0 +1,3 @@ +var myArray = $array(1); + +$print(myArray[0]); diff --git a/Task/Arrays/REXX/arrays-1.rexx b/Task/Arrays/REXX/arrays-1.rexx index b44345aaad..98beeeab34 100644 --- a/Task/Arrays/REXX/arrays-1.rexx +++ b/Task/Arrays/REXX/arrays-1.rexx @@ -1,9 +1,9 @@ -/*REXX program demonstrates array usage. */ -a.='not found' /*value for all a.xxx (so far). */ +/*REXX program demonstrates a simple array usage. */ +a.='not found' /*value for all a.xxx (so far).*/ + do j=1 to 100 /*start at 1, define 100 elements*/ + a.j=-j*100 /*define as negative J thousand. */ + end /*j*/ /*the above defines 100 elements.*/ - do j=1 to 100 /*start at 1, define 100 array elements.*/ - a.j=-j*100 /*define element as negative J thousand.*/ - end /*the above defines 100 elements. */ - -say 'element 50 is:' a.50 +say 'element 50 is:' a.50 say 'element 3000 is:' a.3000 + /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays-2.rexx b/Task/Arrays/REXX/arrays-2.rexx index f6bd2d0564..83f0292649 100644 --- a/Task/Arrays/REXX/arrays-2.rexx +++ b/Task/Arrays/REXX/arrays-2.rexx @@ -1,13 +1,11 @@ -/*REXX program demonstrates array usage with mimicry. */ +/*REXX program demonstrates array usage with mimicry. */ a. = 'not found' /*value for all a.xxx (so far). */ + do j=1 to 100 /*start at 1, define 100 elements*/ + a.j = -j * 100 /*define element as -J hundred. */ + end /*j*/ /*the above defines 100 elements.*/ - do j=1 to 100 /*start at 1, define 100 elements*/ - a.j = -j * 100 /*define element as -J thousand.*/ - end /*j*/ /*the above defines 100 elements.*/ - -say 'element 50 is:' a(50) +say 'element 50 is:' a(50) say 'element 3000 is:' a(3000) exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────A subroutine────────────────────────*/ -a: _a_ = arg(1); return a._a_ +a: _a_ = arg(1); return a._a_ diff --git a/Task/Arrays/REXX/arrays-3.rexx b/Task/Arrays/REXX/arrays-3.rexx index 2383e066f4..83f0292649 100644 --- a/Task/Arrays/REXX/arrays-3.rexx +++ b/Task/Arrays/REXX/arrays-3.rexx @@ -1,9 +1,11 @@ -/*REXX program demonstrates array usage with assigned default.*/ -a.=00 /*value for all a.xxx (so far). */ +/*REXX program demonstrates array usage with mimicry. */ +a. = 'not found' /*value for all a.xxx (so far). */ + do j=1 to 100 /*start at 1, define 100 elements*/ + a.j = -j * 100 /*define element as -J hundred. */ + end /*j*/ /*the above defines 100 elements.*/ - do j=1 to 100 /*start at 1, define 100 array elements.*/ - a.j=-j*100 /*define element as negative J thousand.*/ - end /*the above defines 100 elements. */ - -say 'element 50 is:' a.50 -say 'element 3000 is:' a.3000 +say 'element 50 is:' a(50) +say 'element 3000 is:' a(3000) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────A subroutine────────────────────────*/ +a: _a_ = arg(1); return a._a_ diff --git a/Task/Arrays/REXX/arrays-4.rexx b/Task/Arrays/REXX/arrays-4.rexx index 790ae197dd..cfbad6de11 100644 --- a/Task/Arrays/REXX/arrays-4.rexx +++ b/Task/Arrays/REXX/arrays-4.rexx @@ -1,10 +1,10 @@ -/*REXX program demonstrates array usage. */ -array.='out of range' /*for now, define ALL elements to this. */ - - do j=-3000 to 3000 /*start at -3k, going up to +3k. */ - array.j=j**2 /*define element as it's square. */ - end /*the above defines 6,001 elements. */ +/*REXX program demonstrates array usage (with elements out-of-range).*/ +array. = 'out of range' /*define ALL elements to this. */ + do j=-3000 to 3000 /*start at -3k, going up to +3k.*/ + array.j=j**2 /*define element as it's square. */ + end /*j*/ /* [↑] defines 6,001 elements. */ g=-7 -say g "squared is:" array.g -say 7000 "squared is:" array.7000 +say g "squared is:" array.g +say 7000 "squared is:" array.7000 + /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays-5.rexx b/Task/Arrays/REXX/arrays-5.rexx index b83e4c6e75..9daf6ca54b 100644 --- a/Task/Arrays/REXX/arrays-5.rexx +++ b/Task/Arrays/REXX/arrays-5.rexx @@ -1,16 +1,17 @@ -/*REXX program demonstrates disjointed array usage. */ -yr.='year not supported' /*value for all yr.xxx (so far). */ +/*REXX program demonstrates disjointed array usage. */ +yr. = 'year not supported' /*value for all yr.xxx (so far).*/ - do k=600 to 1100 /*Define a bunch of years prior to 1800.*/ - yr.k=k "AD" - end + do k=600 to 1100 /*a bunch of years prior to 1800.*/ + yr.k=k "AD" /*Kth element as the year itself.*/ + end /*k*/ /* [↑] defines 501 elements.*/ - do j=1800 to 2100 /*start at 1800, define a bunch of years*/ - yr.j=j 'AD' /*define Jth element as the year itself.*/ - end /*the above defines 301 elements. */ + do j=1800 to 2100 /*start at 1800, define a bunch. */ + yr.j=j 'AD' /*Jth element as the year itself.*/ + end /*j*/ /* [↑] defines 301 elements.*/ year=1946 say 'DOB' year "is:" yr.year year=1744 say 'DOB' year "is:" yr.year + /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays-6.rexx b/Task/Arrays/REXX/arrays-6.rexx index 1cd9e07bf0..0d2e52addd 100644 --- a/Task/Arrays/REXX/arrays-6.rexx +++ b/Task/Arrays/REXX/arrays-6.rexx @@ -1,29 +1,27 @@ -/*REXX program demonstrates array usage: sparse and disjointed. */ -yyy = -55 -a.yyy = 1e9 /*REXX must use this mechanism for neg idx.*/ +/*REXX program demonstrates array usage: sparse and disjointed. */ + yyy = -55 /*REXX must use this mechanism···*/ +a.yyy = 1e9 /*··· when assigning neg indices.*/ -a.1=1000 -a.2=2000.0001 +a.1 = 1000 +a.2 = 2000.0001 a.7 = 7000 a.2012 = 'out here in left field.' -a.cat='civet, but not a true cat --- belonging to the family Viverridae' -a.civet="A.K.A.: toddycats" - -/*------------------------------------------------------------------------ - Array elements need not be continous (nor even defined). They can hold - any nanner of numbers, or strings (which can include any characters, - including null or '00'x characters). - - Array elements need not be numeric, as the above code demonstrates. - Indeed, the element "name" can be ANYTHING, even non-displayable - characters. To illustrate: ---------------------------------------------------------------------------*/ - +a.cat = 'civet, but not a true cat ─── belonging to the family Viverridae' +a.civet = "A.K.A.: toddycats" +/*┌────────────────────────────────────────────────────────────────────┐ + │ Array elements need not be continuous (nor even defined). They │ + │ can hold any manner of numbers, or strings (which can include any │ + │ characters, including null or '00'x characters). │ + │ │ + │ Array elements need not be numeric, as the above code demonstrates.│ + │ Indeed, the element "name" can be ANYTHING, even non-displayable │ + │ characters. To illustrate [↓]: │ + └────────────────────────────────────────────────────────────────────┘*/ stuff=')g.u.t.s( or ½ of an intestine!' a.stuff=44 - -/*-------------------------------------------------------------- - where the element name has special characters, blanks, and - the glyph of one-half, as well as the symbol used in REXX to - indentify stemmed arrays (the period). -----------------------------------------------------------------*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ where the element name has special characters: blanks, and the │ + │ glyph of one-half (½), as well as the symbol used in REXX to │ + │ identify stemmed arrays (the period). │ + └────────────────────────────────────────────────────────────────────┘*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Assertions/Liberty-BASIC/assertions.liberty b/Task/Assertions/Liberty-BASIC/assertions.liberty new file mode 100644 index 0000000000..6f2d92b990 --- /dev/null +++ b/Task/Assertions/Liberty-BASIC/assertions.liberty @@ -0,0 +1,14 @@ +a=42 +call assert a=42 +print "passed" + +a=41 +call assert a=42 +print "failed (we never get here)" +end + +sub assert cond + if cond=0 then 'simulate error, mentioning "AssertionFailed" + AssertionFailed(-1)=0 + end if +end sub diff --git a/Task/Assertions/Perl/assertions-1.pl b/Task/Assertions/Perl/assertions-1.pl index e47bd1bf69..599ccc9167 100644 --- a/Task/Assertions/Perl/assertions-1.pl +++ b/Task/Assertions/Perl/assertions-1.pl @@ -1 +1,9 @@ -open my $fh, '<', 'file' or die "Cannot open file: $!\n"; # $! contains the error message from the last error +print "Give me a number: "; +chomp(my $a = <>); + +$a == 42 or die "Error message\n"; + +# Alternatives +die "Error message\n" unless $a == 42; +die "Error message\n" if not $a == 42; +die "Error message\n" if $a != 42; diff --git a/Task/Assertions/Perl/assertions-2.pl b/Task/Assertions/Perl/assertions-2.pl index 9e24ef6f41..635bbe31c2 100644 --- a/Task/Assertions/Perl/assertions-2.pl +++ b/Task/Assertions/Perl/assertions-2.pl @@ -1,2 +1,2 @@ -use autodie; -open my $fh, '<', 'file'; # automatically throws an exception on failure +open my $fh, '<', 'file' + or die "Cannot open file: $!\n"; # $! contains the error message from the last error diff --git a/Task/Assertions/Perl/assertions-3.pl b/Task/Assertions/Perl/assertions-3.pl index f509bedf3b..9e24ef6f41 100644 --- a/Task/Assertions/Perl/assertions-3.pl +++ b/Task/Assertions/Perl/assertions-3.pl @@ -1,9 +1,2 @@ -my $a = 5; -#...input or change $a here -$a == 42 or die "Error message\n"; -# or, alternatively: -die "Error message\n" unless $a == 42; -# or: -die "Error message\n" if not $a == 42; -# or just: -die "Error message\n" if $a != 42; +use autodie; +open my $fh, '<', 'file'; # automatically throws an exception on failure diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation.elena b/Task/Associative-array-Creation/Elena/associative-array-creation.elena index 03672bd504..d86acd5ebb 100644 --- a/Task/Associative-array-Creation/Elena/associative-array-creation.elena +++ b/Task/Associative-array-Creation/Elena/associative-array-creation.elena @@ -6,7 +6,8 @@ [ // 1. Create #var aMap := Dictionary new. - aMap @ "key" << "foox". - aMap @ "key" << "foo". - aMap @ "key2" << "foo2". + aMap set &key:"key" &value:"foox". + aMap set &key:"key2" &value:"foo2". + aMap set &key:"key" &value:"foo". + ]. diff --git a/Task/Associative-array-Creation/Nimrod/associative-array-creation.nimrod b/Task/Associative-array-Creation/Nimrod/associative-array-creation.nimrod new file mode 100644 index 0000000000..052b5413d5 --- /dev/null +++ b/Task/Associative-array-Creation/Nimrod/associative-array-creation.nimrod @@ -0,0 +1,23 @@ +import tables + +var t: TTable[int,string] = initTable[int,string]() + +t[1] = "one" +t[2] = "two" +t[3] = "three" +t.add(4,"four") + +echo "t has " & $t.len & " elements" + +echo "has t key 4? " & $t.hasKey(4) +echo "has t key 5? " & $t.hasKey(5) + +#iterate keys +echo "key iteration:" +for k in t.keys: + echo "at[" & $k & "]=" & t[k] + +#itetate pairs +echo "pair iteration:" +for k,v in t.pairs: + echo "at[" & $k & "]=" & v diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena index 29acfbe532..bb3a5a30ae 100644 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena @@ -7,13 +7,13 @@ [ // 1. Create #var aMap := Dictionary new. - aMap @ "key" << "foox". - aMap @ "key" << "foo". - aMap @ "key2" << "foo2". - aMap @ "key3" << "foo3". - aMap @ "key4" << "foo4". + aMap set &key:"key" &value:"foox". + aMap set &key:"key" &value:"foo". + aMap set &key:"key2" &value:"foo2". + aMap set &key:"key3" &value:"foo3". + aMap set &key:"key4" &value:"foo4". // Enumerate - control foreach:aMap &do: &&:aKeyValue - [ console write:(aKeyValue Key) write:" : " writeLine:(aKeyValue Value) ]. + control foreach:aMap &do: aKeyValue + [ console write:(aKeyValue key) write:" : " writeLine:(aKeyValue value) ]. ]. diff --git a/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia b/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia new file mode 100644 index 0000000000..5e872ae7ba --- /dev/null +++ b/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia @@ -0,0 +1,19 @@ +mydict = [ "hello"=>13, "world"=>31, "!"=>71 ] + +# applying a function to key-value pairs: + map(println, mydict); + +# iterating over key-value pairs: +for (key,value) in mydict + println("key = $key, value = $value") +end + +# iterating over keys: +for key in keys(mydict) + println("key = $key") +end + +# iterating over values: +for value in values(mydict) + println("value = $value") +end diff --git a/Task/Associative-array-Iteration/Nimrod/associative-array-iteration.nimrod b/Task/Associative-array-Iteration/Nimrod/associative-array-iteration.nimrod new file mode 100644 index 0000000000..052b5413d5 --- /dev/null +++ b/Task/Associative-array-Iteration/Nimrod/associative-array-iteration.nimrod @@ -0,0 +1,23 @@ +import tables + +var t: TTable[int,string] = initTable[int,string]() + +t[1] = "one" +t[2] = "two" +t[3] = "three" +t.add(4,"four") + +echo "t has " & $t.len & " elements" + +echo "has t key 4? " & $t.hasKey(4) +echo "has t key 5? " & $t.hasKey(5) + +#iterate keys +echo "key iteration:" +for k in t.keys: + echo "at[" & $k & "]=" & t[k] + +#itetate pairs +echo "pair iteration:" +for k,v in t.pairs: + echo "at[" & $k & "]=" & v diff --git a/Task/Average-loop-length/D/average-loop-length.d b/Task/Average-loop-length/D/average-loop-length.d index 79d608cf6b..71b88a6381 100644 --- a/Task/Average-loop-length/D/average-loop-length.d +++ b/Task/Average-loop-length/D/average-loop-length.d @@ -1,6 +1,6 @@ import std.stdio, std.random, std.math, std.algorithm, std.range; -real analytical(in int n) /*pure nothrow*/ { +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)) diff --git a/Task/Average-loop-length/Liberty-BASIC/average-loop-length.liberty b/Task/Average-loop-length/Liberty-BASIC/average-loop-length.liberty new file mode 100644 index 0000000000..2327b689af --- /dev/null +++ b/Task/Average-loop-length/Liberty-BASIC/average-loop-length.liberty @@ -0,0 +1,36 @@ +MAXN = 20 +TIMES = 10000'00 + +'t0=time$("ms") +FOR n = 1 TO MAXN + avg = FNtest(n, TIMES) + theory = FNanalytical(n) + diff = (avg / theory - 1) * 100 + PRINT n, avg, theory, using("##.####",diff); "%" +NEXT +'t1=time$("ms") +'print t1-t0; " ms" +END + +function FNanalytical(n) + FOR i = 1 TO n + s = s+ FNfactorial(n) / n^i / FNfactorial(n-i) + NEXT + FNanalytical = s +end function + +function FNtest(n, times) + FOR i = 1 TO times + x = 1 : b = 0 + WHILE (b AND x) = 0 + c = c + 1 + b = b OR x + x = 2^int(n*RND(1)) + WEND + NEXT + FNtest = c / times +end function + +function FNfactorial(n) + IF n=1 OR n=0 THEN FNfactorial=1 ELSE FNfactorial= n * FNfactorial(n-1) +end function diff --git a/Task/Average-loop-length/Ruby/average-loop-length.rb b/Task/Average-loop-length/Ruby/average-loop-length.rb new file mode 100644 index 0000000000..b8b558062c --- /dev/null +++ b/Task/Average-loop-length/Ruby/average-loop-length.rb @@ -0,0 +1,23 @@ +class Integer + def factorial + self == 0 ? 1 : (1..self).inject(:*) + end +end + +def rand_until_rep(n) + rands = {} + loop do r = rand(1..n) + return rands.size if rands[r] + rands[r] = true + end +end + +runs = 1_000_000 + +puts " n\tavg\texp.\tdiff\n_____________________________" +(1..20).each do |n| + sum_of_runs = runs.times.inject(0){|sum, _| sum += rand_until_rep(n)} + avg = sum_of_runs / runs.to_f + analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)} + puts "%2d %8.4f %8.4f %8.4f" % [n, avg, analytical, (avg/analytical - 1)*100] +end diff --git a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d index 1fd514aa78..3e3fc0bb98 100644 --- a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d +++ b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d @@ -1,13 +1,10 @@ import std.stdio, std.algorithm, std.range; -auto mean(Range)(Range r) { - auto len = r.walkLength(); - return len == 0 ? 0.0 : reduce!q{a + b}(0.0L, r) / len; +real mean(Range)(Range r) pure nothrow { + return reduce!q{a + b}(0.0L, r) / max(1.0L, r.count); } void main() { - int[] data; - writeln("mean: ", data.mean()); - data = [3, 1, 4, 1, 5, 9]; - writeln("mean: ", data.mean()); + writeln("Mean: ", (int[]).init.mean); + writeln("Mean: ", [3, 1, 4, 1, 5, 9].mean); } diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index f4ea8661ed..3c59afbe81 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -1,4 +1,5 @@ #define system. +#define system'routines. // --- Sum --- @@ -20,12 +21,12 @@ theValue += aValue. ] - #method Number = theValue / theCount. + #method number = theValue / theCount. } // --- Program --- #symbol program = [ - console writeLine:(MeanAction new foreach:(1, 2, 3, 4, 5, 6, 7, 8) Number). + console writeLine:(MeanAction new foreach:(1, 2, 3, 4, 5, 6, 7, 8) number). ]. diff --git a/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia b/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia new file mode 100644 index 0000000000..fc73f2d9d0 --- /dev/null +++ b/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia @@ -0,0 +1 @@ +meandegrees(degrees) = radians2degrees(atan2(mean(sind(degrees)), mean(cosd(degrees)))) diff --git a/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.julia b/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.julia new file mode 100644 index 0000000000..cefb410d21 --- /dev/null +++ b/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.julia @@ -0,0 +1,8 @@ +julia> meandegrees([350, 10]) +0.0 + +julia> meandegrees([90, 180, 270, 360]]) +0.0 + +julia> meandegrees([10, 20, 30]]) +19.999999999999996 diff --git a/Task/Averages-Mean-time-of-day/BBC-BASIC/averages-mean-time-of-day.bbc b/Task/Averages-Mean-time-of-day/BBC-BASIC/averages-mean-time-of-day.bbc new file mode 100644 index 0000000000..2dab7df089 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/BBC-BASIC/averages-mean-time-of-day.bbc @@ -0,0 +1,39 @@ + nTimes% = 4 + DATA 23:00:17, 23:40:20, 00:12:45, 00:17:19 + + DIM angles(nTimes%-1) + FOR N% = 0 TO nTimes%-1 + READ tim$ + angles(N%) = FNtimetoangle(tim$) + NEXT + PRINT "Mean time is " FNangletotime(FNmeanangle(angles(), nTimes%)) + END + + DEF FNtimetoangle(t$) + LOCAL A%, I% + REPEAT + A% = A% * 60 + VAL(t$) + I% = INSTR(t$, ":") + t$ = MID$(t$, I%+1) + UNTIL I% = 0 + = A% / 240 - 180 + + DEF FNangletotime(a) + LOCAL A%, I%, t$ + A% = INT((a + 180) * 240 + 0.5) + FOR I% = 1 TO 3 + t$ = RIGHT$("0" + STR$(A% MOD 60), 2) + ":" + t$ + A% DIV= 60 + NEXT + = LEFT$(t$) + + DEF FNmeanangle(angles(), N%) + LOCAL I%, addsin, addcos + FOR I% = 0 TO N%-1 + addsin += SINRADangles(I%) + addcos += COSRADangles(I%) + NEXT + = DEGFNatan2(addsin, addcos) + + DEF FNatan2(y,x) : ON ERROR LOCAL = SGN(y)*PI/2 + IF x>0 THEN = ATN(y/x) ELSE IF y>0 THEN = ATN(y/x)+PI ELSE = ATN(y/x)-PI diff --git a/Task/Averages-Mean-time-of-day/Groovy/averages-mean-time-of-day-1.groovy b/Task/Averages-Mean-time-of-day/Groovy/averages-mean-time-of-day-1.groovy new file mode 100644 index 0000000000..ec335013b3 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Groovy/averages-mean-time-of-day-1.groovy @@ -0,0 +1,11 @@ +import static java.lang.Math.* + +final format = 'HH:mm:ss', clock = PI / 12, millisPerHr = 3600*1000 +final tzOffset = new Date(0).timezoneOffset / 60 +def parseTime = { time -> (Date.parse(format, time).time / millisPerHr) - tzOffset } +def formatTime = { time -> new Date((time + tzOffset) * millisPerHr as int).format(format) } +def mean = { list, closure -> list.sum(closure)/list.size() } +def meanTime = { ... timeStrings -> + def times = timeStrings.collect(parseTime) + formatTime(atan2( mean(times) { sin(it * clock) }, mean(times) { cos(it * clock) }) / clock) +} diff --git a/Task/Averages-Mean-time-of-day/Groovy/averages-mean-time-of-day-2.groovy b/Task/Averages-Mean-time-of-day/Groovy/averages-mean-time-of-day-2.groovy new file mode 100644 index 0000000000..95d27e59d8 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Groovy/averages-mean-time-of-day-2.groovy @@ -0,0 +1 @@ +println (meanTime("23:00:17", "23:40:20", "00:12:45", "00:17:19")) diff --git a/Task/Averages-Mean-time-of-day/Liberty-BASIC/averages-mean-time-of-day.liberty b/Task/Averages-Mean-time-of-day/Liberty-BASIC/averages-mean-time-of-day.liberty new file mode 100644 index 0000000000..4c3a474f5c --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Liberty-BASIC/averages-mean-time-of-day.liberty @@ -0,0 +1,45 @@ +global pi +pi = acs(-1) + +Print "Average of:" +for i = 1 to 4 + read t$ + print t$ + a=time2angle(t$) + ss=ss+sin(a) + sc=sc+cos(a) +next +a=atan2(ss,sc) +if a<0 then a=a+2*pi +print "is ";angle2time$(a) + +end +data "23:00:17", "23:40:20", "00:12:45", "00:17:19" + +function nn$(n) + nn$=right$("0";n, 2) +end function + +function angle2time$(a) + a=int(a/2/pi*24*60*60) + ss=a mod 60 + a=int(a/60) + mm=a mod 60 + hh=int(a/60) + angle2time$=nn$(hh);":";nn$(mm);":";nn$(ss) +end function + +function time2angle(time$) + hh=val(word$(time$,1,":")) + mm=val(word$(time$,2,":")) + ss=val(word$(time$,3,":")) + time2angle=2*pi*(60*(60*hh+mm)+ss)/24/60/60 +end function + +function atan2(y, x) + On Error GoTo [DivZero] 'If y is 0 catch division by zero error + atan2 = (2 * (atn((sqr((x * x) + (y * y)) - x)/ y))) + exit function + [DivZero] + atan2 = (y=0)*(x<0)*pi +End Function diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index bd4c4ed0da..8923f97b31 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -1,27 +1,25 @@ -#define std'dictionary'*. -#define std'math'*. -#define std'routines'*. +#define system. +#define system'routines. +#define extensions. +#define extensions'math. -#symbol Sorted : anArray - = anArray clone ~esort run: aPair = (aPair former < aPair later). - -#symbol Median : anArray = +#symbol median = (:anArray) [ - #var aSorted := Sorted::anArray. + #var aSorted := arrayControl sort:(anArray~indexable array). - #var aLen := aSorted count. - #if aLen - == 0 ? [ ^ nil. ] - | [ - #var aMiddleIndex := aLen / 2. - #if aLen~eops modulus:2 - == 0 ? [ ^ aSorted@aMiddleIndex. ] - | [ ^ (aSorted@(aMiddleIndex - 1) + aSorted@aMiddleIndex) / 2. ]. - ]. + #var aLen := aSorted length. + ^ aLen => + 0 ? [ nil ] + ! [ + #var aMiddleIndex := aLen / 2. + ^ (modulus:aLen:2) => + 0 ? [ (aSorted@(aMiddleIndex - 1) + aSorted@aMiddleIndex) / 2 ] + ! [ aSorted@aMiddleIndex ]. + ]. ]. -#symbol Program = +#symbol program = [ - 'program'output << Median::(4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r) << "%n". - 'program'output << Median::(4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r) << "%n". + consoleEx writeLine:(median:(4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r)). + consoleEx writeLine:(median:(4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r)). ]. diff --git a/Task/Averages-Median/Haskell/averages-median-1.hs b/Task/Averages-Median/Haskell/averages-median-1.hs index 5337c27191..cdd2d127e4 100644 --- a/Task/Averages-Median/Haskell/averages-median-1.hs +++ b/Task/Averages-Median/Haskell/averages-median-1.hs @@ -1,8 +1,7 @@ -nth (x:xs) n - | k == n = x - | k > n = nth ys n - | otherwise = nth zs $ n - k - 1 - where (ys, zs) = partition ( [a] -> Maybe a diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index f5d43fc78a..f33d3a233d 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -1,27 +1,28 @@ #define system. +#define system'routines. #define system'collections. -#define extensions'io. +#define extensions. // Averages/Mode -#symbol mode = &&:anArray +#symbol mode = (:anArray) [ #var aCountMap := Dictionary new &default:0. - control foreach:anArray &do: &&:anItem + control foreach:anArray &do: anItem [ - aCountMap @ anItem << ((aCountMap @ anItem) + 1). + aCountMap set &key:anItem &value:(aCountMap getAt &key:anItem + 1). ]. - listControl sort:aCountMap &with: &&:p:n - [ p Value > n Value ]. + listControl sort:aCountMap &with: (:p:n) + [ p value > n value ]. #var aResult := List new. - #var aMax := aCountMap First Value. - control foreach:aCountMap &do: &&:anItem + #var aMax := aCountMap First value. + control foreach:aCountMap &do: anItem [ - aMax == anItem Value - ? [ aResult += anItem Key. ]. + aMax == anItem value + ? [ aResult += anItem key. ]. ]. ^ listControl toArray:aResult. @@ -35,6 +36,6 @@ #var aMode1 := mode:anArray1. #var aMode2 := mode:anArray2. - consoleEx write:"mode of (" write::anArray1 write:") is (" write::aMode1 writeLine:")". - consoleEx write:"mode of (" write::anArray2 write:") is (" write::aMode2 writeLine:")". + consoleEx writeLine:"mode of (":anArray1:") is (":aMode1:")". + consoleEx writeLine:"mode of (":anArray2:") is (":aMode2:")". ]. diff --git a/Task/Averages-Mode/Liberty-BASIC/averages-mode.liberty b/Task/Averages-Mode/Liberty-BASIC/averages-mode.liberty new file mode 100644 index 0000000000..40da21896e --- /dev/null +++ b/Task/Averages-Mode/Liberty-BASIC/averages-mode.liberty @@ -0,0 +1,58 @@ +a$ = "1 3 6 6 6 6 7 7 12 12 17" +b$ = "1 2 4 4 1" + +print "Modes for ";a$ +print modes$(a$) +print "Modes for ";b$ +print modes$(b$) + +function modes$(a$) +'get array size + n=0 + t$ = "*" + while t$<>"" + n=n+1 + t$=word$(a$, n) + 'print n, t$ + wend + n=n-1 + 'print "n=", n +'dim array +'read in array + redim a(n) + for i = 1 to n + a(i)=val(word$(a$, i)) + 'print i, a(i) + next +'sort + sort a(), 1, n +'get the modes + occurence = 1 + maxOccurence = 0 + oldVal = a(1) + modes$ = "" + for i = 2 to n + 'print i, a(i) + if a(i) = oldVal then + occurence = occurence + 1 + else + select case + case occurence > maxOccurence + maxOccurence = occurence + modes$ = oldVal; " " + case occurence = maxOccurence + modes$ = modes$; oldVal; " " + end select + occurence = 1 + end if + oldVal = a(i) + next + 'check after loop + select case + case occurence > maxOccurence + maxOccurence = occurence + modes$ = oldVal; " " + case occurence = maxOccurence + modes$ = modes$; oldVal; " " + end select +end function diff --git a/Task/Averages-Mode/PL-I/averages-mode.pli b/Task/Averages-Mode/PL-I/averages-mode.pli new file mode 100644 index 0000000000..9330bc07c7 --- /dev/null +++ b/Task/Averages-Mode/PL-I/averages-mode.pli @@ -0,0 +1,20 @@ +av: procedure options (main); /* 28 October 2013 */ + declare x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2); + declare f(32767) fixed binary; + declare (j, n, max, value) fixed binary; + declare i fixed; + + n = hbound(x,1); + + do i = 1 to n; + j = x(i); + f(j) = f(j) + 1; + end; + max = 0; + do i = 1 to hbound(f,1); + if max < f(i) then do; max = f(i); value = i; end; + end; + put list ('The mode value is ' || value || ' occurred ' || + max || ' times.'); + +end av; diff --git a/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square.basic b/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-1.basic similarity index 100% rename from Task/Averages-Root-mean-square/BASIC/averages-root-mean-square.basic rename to Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-1.basic diff --git a/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-2.basic b/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-2.basic new file mode 100644 index 0000000000..e6dd531a6b --- /dev/null +++ b/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-2.basic @@ -0,0 +1,6 @@ + 10 N = 10 + 20 FOR I = 1 TO N + 30 S = S + I * I + 40 NEXT + 50 X = SQR (S / N) + 60 PRINT X diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-1.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-1.julia new file mode 100644 index 0000000000..77af378a5b --- /dev/null +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-1.julia @@ -0,0 +1 @@ +sqrt(sum(A.^2.) / length(A)) diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia new file mode 100644 index 0000000000..881332dcfd --- /dev/null +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia @@ -0,0 +1 @@ +sqrt(sum(x -> x*x, A) / length(A)) diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia new file mode 100644 index 0000000000..1eeb684f14 --- /dev/null +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia @@ -0,0 +1,7 @@ +function rms(A) + s = 0.0 + for a in A + s += a*a + end + return sqrt(s / length(A)) +end diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia new file mode 100644 index 0000000000..f133058c5a --- /dev/null +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia @@ -0,0 +1 @@ +norm(A) / sqrt(length(A)) diff --git a/Task/Averages-Root-mean-square/Perl/averages-root-mean-square.pl b/Task/Averages-Root-mean-square/Perl/averages-root-mean-square.pl index 796f93c6fc..fe2f09f0c0 100644 --- a/Task/Averages-Root-mean-square/Perl/averages-root-mean-square.pl +++ b/Task/Averages-Root-mean-square/Perl/averages-root-mean-square.pl @@ -3,7 +3,7 @@ sub rms { my $r = 0; $r += $_**2 for @_; - return sqrt( $r/@_ ); + sqrt( $r/@_ ); } say rms(1..10); diff --git a/Task/Averages-Root-mean-square/R/averages-root-mean-square-1.r b/Task/Averages-Root-mean-square/R/averages-root-mean-square-1.r index 6be53be3ba..39e56f6d97 100644 --- a/Task/Averages-Root-mean-square/R/averages-root-mean-square-1.r +++ b/Task/Averages-Root-mean-square/R/averages-root-mean-square-1.r @@ -1 +1 @@ -sqrt(sum((1:10)^2/10)) +sqrt(mean((1:10)^2)) diff --git a/Task/Averages-Root-mean-square/R/averages-root-mean-square-2.r b/Task/Averages-Root-mean-square/R/averages-root-mean-square-2.r index 408cad4f72..23f47e70b9 100644 --- a/Task/Averages-Root-mean-square/R/averages-root-mean-square-2.r +++ b/Task/Averages-Root-mean-square/R/averages-root-mean-square-2.r @@ -1,2 +1,3 @@ -x<-1:10 -sqrt(sum((x)^2/length(x))) +RMS = function(x){ + sqrt(mean(x^2)) +} diff --git a/Task/Averages-Root-mean-square/R/averages-root-mean-square-3.r b/Task/Averages-Root-mean-square/R/averages-root-mean-square-3.r new file mode 100644 index 0000000000..3bb7b339de --- /dev/null +++ b/Task/Averages-Root-mean-square/R/averages-root-mean-square-3.r @@ -0,0 +1,2 @@ +> RMS(1:10) +[1] 6.204837 diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index f377becd21..502913567d 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -1,54 +1,54 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'collections'*. -#define std'patterns'*. +#define system. +#define system'routines. +#define system'collections. +#define extensions. -#class ESMARole +#class SMAExtender { #field thePeriod. - #initializer : aPeriod + #constructor new : aPeriod [ thePeriod := aPeriod. ] - #method + aNumber + #method add : aNumber [ - self += NewInt32Value::aNumber. + self += aNumber. - #if (self count > thePeriod)? - [ - self first_item'reduce. - ]. + #var aCount := self length. + ^ aCount => + 0 ? [ 0.0r ] + ! [ + (aCount > thePeriod)? + [ + self remove &index:0. + ]. - #var aCount := self count. - #if (aCount == 0)? - [ ^ 0. ]. - - #var aSum := Summing::Real::0 start:Scan::self. - - ^ aSum / aCount. + #var aSum := Summing new:(Real new:0) foreach:self. + ^ aSum / self length. + ]. ] } -#symbol SMA : aPeriod = __wrap(ESMARole::aPeriod, List). +#symbol sma = (:aPeriod) [ Extension(SMAExtender new:aPeriod, List new) ]. // --- Program --- -#symbol Program = +#symbol program = [ - #var SMA3 := SMA::3. - #var SMA5 := SMA::5. + #var SMA3 := sma:3. + #var SMA5 := sma:5. - loop &&from:1 &to:5 run: i = + control from:1 &to:5 &do: i [ - 'program'output << "sma3 + " << i << " = " << SMA3 + i. - 'program'output << ",sma5 + " << i << " = " << SMA5 + i << "%n". + consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 + i number). + consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 + i number). ]. - loop &&from:5 &to:1 &step:-1 run: i = + control from:5 &backTo:1 &do: i [ - 'program'output << "sma3 + " << i << " = " << SMA3 + i. - 'program'output << ",sma5 + " << i << " = " << SMA5 + i << "%n". + consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 + i number). + consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 + i number). ]. ]. 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 879fb63b32..929b726958 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,10 +1,8 @@ -sub sma (Int $period where (* > 0)) returns Sub { - my $sum = 0; - my @a; - return sub ($x) { - @a.push: $x; - $sum += $x; - $sum -= @a.shift if @a > $period; - return $sum / @a; - } +sub sma(Int $period where * > 0) returns Sub { + sub ($x) { + state @a = 0 xx $period; + @a.push($x); + @a.shift; + $period R/ [+] @a; + } } diff --git a/Task/Balanced-brackets/AWK/balanced-brackets.awk b/Task/Balanced-brackets/AWK/balanced-brackets.awk index e6b151f39e..5dfae28c5d 100644 --- a/Task/Balanced-brackets/AWK/balanced-brackets.awk +++ b/Task/Balanced-brackets/AWK/balanced-brackets.awk @@ -9,13 +9,13 @@ BEGIN { } function isbb(x) { - s = 0; + s = 0 for (k=1; k<=length(x); k++) { - c = substr(x,k,1); - if (c=="[") {s++;} - else { if (c=="]") s--; } + c = substr(x,k,1) + if (c=="[") {s++} + else { if (c=="]") s-- } - if (s<0) {return 0}; + if (s<0) {return 0} } - return (s==0); + return (s==0) } diff --git a/Task/Balanced-brackets/D/balanced-brackets-3.d b/Task/Balanced-brackets/D/balanced-brackets-3.d index 0f106ed6a7..fd5bfc2655 100644 --- a/Task/Balanced-brackets/D/balanced-brackets-3.d +++ b/Task/Balanced-brackets/D/balanced-brackets-3.d @@ -1,19 +1,19 @@ -import std.stdio, std.random, std.conv, std.range, std.algorithm; +import std.stdio, std.random, std.range, std.algorithm; -bool isBalanced(in string s) pure nothrow { - static bool bal(in string s, in int nb = 0) pure nothrow { - if (nb == 0 && s.empty) return true; - if (s.empty || nb < 0) return false; - if (s[0] == '[') return bal(s[1 .. $], nb + 1); - if (s[0] == ']') return bal(s[1 .. $], nb - 1); - return bal(s[1 .. $], nb); // Ignore char. +bool isBalanced(in string s, in string pars="[]") pure nothrow { + bool bal(in string t, in int nb = 0) pure nothrow { + if (!nb && t.empty) return true; + if (t.empty || nb < 0) return false; + if (t[0] == pars[0]) return bal(t.dropOne, nb + 1); + if (t[0] == pars[1]) return bal(t.dropOne, nb - 1); + return bal(t.dropOne, nb); // Ignore char. } return bal(s); } void main() { foreach (immutable i; 1 .. 9) { - immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array; + immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, $)]).array; writeln(s.isBalanced ? " OK " : "Bad ", s); } } diff --git a/Task/Balanced-brackets/Deja-Vu/balanced-brackets.djv b/Task/Balanced-brackets/Deja-Vu/balanced-brackets.djv new file mode 100644 index 0000000000..fb90652982 --- /dev/null +++ b/Task/Balanced-brackets/Deja-Vu/balanced-brackets.djv @@ -0,0 +1,19 @@ +matching?: + swap 0 + for c in chars: + if = c "]": + ++ + elseif = c "[": + if not dup: + drop + return false + -- + not + +!. matching? "" +!. matching? "[]" +!. matching? "[][]" +!. matching? "[[][]]" +!. matching? "][" +!. matching? "][][" +!. matching? "[]][[]" diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index ec721270d5..7c8b6be330 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -1,9 +1,10 @@ #define system. +#define system'routines. #define extensions. #symbol randomBrackets = &&:aLength [ - #var aBrackets := Array new &type'length:aLength &action: &&:i[ CharValue new:"[" ] + Array new &type'length:aLength &action: &&:i[ CharValue new:"]" ]. + #var aBrackets := Array new &type'length:aLength &function: &&:i[ CharValue new:91 ] + Array new &type'length:aLength &function: &&:i[ CharValue new:93 ]. randomControl randomize:(aLength * 2) &array:aBrackets. diff --git a/Task/Balanced-brackets/PL-I/balanced-brackets.pli b/Task/Balanced-brackets/PL-I/balanced-brackets.pli new file mode 100644 index 0000000000..99cce425f9 --- /dev/null +++ b/Task/Balanced-brackets/PL-I/balanced-brackets.pli @@ -0,0 +1,62 @@ +*process m or(!) s attributes source; + cb: Proc Options(main); + /* PL/I program to check for balanced brackets [] ******************** + * 07.12.2013 Walter Pachl translated from REXX Version 2 + *********************************************************************/ + Dcl v Char(20) Var; + Dcl (i,j) Bin Fixed(31); + Dcl r Bin Float(53); + + Call testbal(''); /* first some user written tests */ + Call testbal('[][][][[]]'); + Call testbal('[][][][[]]]['); + Call testbal('['); + Call testbal(']'); + Call testbal('[]'); + Call testbal(']['); + Call testbal('][]['); + Call testbal('[[]]'); + Call testbal('[[[[[[[]]]]]]]'); + Call testbal('[[[[[]]]][]'); + Call testbal('[][]'); + Call testbal('[]][[]'); + Call testbal(']]][[[[]'); + Call testbal('[[a]][b]'); + Put Edit(' ')(Skip,a); + r=random(12345); /* then some generated ones */ + Do i=1 To 10; + v=''; + Do j=1 To 10; + r=random(); + If r>0.5 Then v=v!!']'; + Else v=v!!'['; + End; + Call testbal(v); + End; + Return; + + testbal: Proc(s); /* test the given string and show result */ + Dcl s Char(*); + Dcl yesno(0:1) Char(20) Var Init('unbalanced',' balanced'); + Put Edit(yesno(checkbal(s)),''''!!s!!'''')(Skip,a,x(1),a); + End; + + checkBal: proc(s) Returns(Bin Fixed(31)); + /*check for balanced brackets [] */ + Dcl s Char(*); + Dcl nest Bin Fixed(31) Init(0); + Dcl i Bin Fixed(31); + Do i=1 To length(s); + Select(substr(s,i,1)); + When('[') nest+=1; + When(']') Do; + If nest=0 Then return(0); + nest-=1; + End; + Otherwise; + End; + End; + Return(nest=0); + End; + + End; diff --git a/Task/Balanced-brackets/PureBasic/balanced-brackets.purebasic b/Task/Balanced-brackets/PureBasic/balanced-brackets.purebasic index 2adf090a19..0880f231d6 100644 --- a/Task/Balanced-brackets/PureBasic/balanced-brackets.purebasic +++ b/Task/Balanced-brackets/PureBasic/balanced-brackets.purebasic @@ -37,8 +37,8 @@ For i=1 To 5 TestString$ = Generate(i) Print(TestString$) If Balanced(TestString$) - PrintN(" is ballanced.") + PrintN(" is balanced.") Else - PrintN(" is not ballanced") + PrintN(" is not balanced") EndIf Next diff --git a/Task/Balanced-ternary/D/balanced-ternary.d b/Task/Balanced-ternary/D/balanced-ternary.d index 51a2404d03..e5b67a83da 100644 --- a/Task/Balanced-ternary/D/balanced-ternary.d +++ b/Task/Balanced-ternary/D/balanced-ternary.d @@ -1,47 +1,47 @@ -import std.stdio, std.bigint, std.range, std.algorithm, std.array, - std.conv, std.exception; +import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { - enum Dig : byte { N=-1, Z=0, P=+1 } // Digits. - Dig[] digits; // Represented as a list of 0, 1 or -1s, // with least significant digit first. + enum Dig : byte { N=-1, Z=0, P=+1 } // Digit. + const Dig[] digits; - static string dig2str = "-0+"; + // This could also be a BalancedTernary template argument. + static immutable string dig2str = "-0+"; - const static Dig[dchar] str2dig; // = ['+': Dig.P, ...]; - static this() { + immutable static Dig[dchar] str2dig; // = ['+': Dig.P, ...]; + nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } - immutable static Dig[2][] table = + immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; - this(string inp) { - this.digits = inp.retro().map!(c => cast()str2dig[c]).array; + this(in string inp) const pure { + this.digits = inp.retro.map!(c => str2dig[c]).array; } - this(long inp) { + this(in long inp) const pure /*nothrow*/ { this.digits = _bint2ternary(inp.BigInt); } - this(BigInt inp) { + this(in BigInt inp) const pure /*nothrow*/ { this.digits = _bint2ternary(inp); } - this(BalancedTernary inp) { + this(in BalancedTernary inp) const pure nothrow { // No need to dup, they are virtually immutable. this.digits = inp.digits; } - private this(Dig[] inp) { + private this(in Dig[] inp) /*inout*/ pure nothrow { this.digits = inp; } - static Dig[] _bint2ternary(/*in*/ BigInt n) { - static py_div(T1, T2)(T1 a, T2 b) { + static Dig[] _bint2ternary(in BigInt n) pure /*nothrow*/ { + static py_div(T1, T2)(in T1 a, in T2 b) pure /*nothrow*/ { if (a < 0) { return (b < 0) ? -a / -b : @@ -54,33 +54,34 @@ struct BalancedTernary { } if (n == 0) return []; - switch (((n % 3) + 3) % 3) { // (n % 3) is the remainder. + // This final switch in D v.2.064 is fake, not enforced. + final switch (((n % 3) + 3) % 3) { // (n % 3) is the remainder. case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); - default: assert(0, "Can't happen"); } } - @property BigInt toBint() const { + @property BigInt toBint() const pure /*nothrow*/ { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } - string toString() const { + string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } - static Dig[] neg_(Dig[] digs) { - return digs.map!q{ -a }.array; + static const(Dig)[] neg_(in Dig[] digs) pure nothrow { + return digs.map!(a => -a).array; } - BalancedTernary opUnary(string op:"-")() { + BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } - static Dig[] add_(Dig[] a, Dig[] b, Dig c=Dig.Z) { - auto a_or_b = a.length ? a : b; + static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) + pure nothrow { + const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; @@ -90,7 +91,7 @@ struct BalancedTernary { // (const d, c) = table[...]; const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; - auto res = add_(a[1 .. $], b[1 .. $], dc[1]); + const res = add_(a[1 .. $], b[1 .. $], dc[1]); // Trim leading zeros. if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; @@ -99,19 +100,21 @@ struct BalancedTernary { } } - BalancedTernary opBinary(string op:"+")(BalancedTernary b) { + BalancedTernary opBinary(string op:"+")(in BalancedTernary b) + const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } - BalancedTernary opBinary(string op:"-")(BalancedTernary b) { + BalancedTernary opBinary(string op:"-")(in BalancedTernary b) + const pure nothrow { return this + (-b); } - static Dig[] mul_(in Dig[] a, /*in*/ Dig[] b) { + static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { - Dig[] y = Dig.Z ~ mul_(a[1 .. $], b); + const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); @@ -120,21 +123,22 @@ struct BalancedTernary { } } - BalancedTernary opBinary(string op:"*")(BalancedTernary b) { + BalancedTernary opBinary(string op:"*")(in BalancedTernary b) + const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { - auto a = BalancedTernary("+-0++0+"); - writeln("a: ", a.toBint, " ", a); + immutable a = BalancedTernary("+-0++0+"); + writeln("a: ", a.toBint, ' ', a); - auto b = BalancedTernary(-436); - writeln("b: ", b.toBint, " ", b); + immutable b = BalancedTernary(-436); + writeln("b: ", b.toBint, ' ', b); - auto c = BalancedTernary("+-++-"); - writeln("c: ", c.toBint, " ", c); + immutable c = BalancedTernary("+-++-"); + writeln("c: ", c.toBint, ' ', c); - auto r = a * (b - c); - writeln("a * (b - c): ", r.toBint, " ", r); + immutable r = a * (b - c); + writeln("a * (b - c): ", r.toBint, ' ', r); } diff --git a/Task/Balanced-ternary/Groovy/balanced-ternary-1.groovy b/Task/Balanced-ternary/Groovy/balanced-ternary-1.groovy new file mode 100644 index 0000000000..839ce2490b --- /dev/null +++ b/Task/Balanced-ternary/Groovy/balanced-ternary-1.groovy @@ -0,0 +1,160 @@ +enum T { + m('-', -1), z('0', 0), p('+', 1) + + final String symbol + final int value + + private T(String symbol, int value) { + this.symbol = symbol + this.value = value + } + + static T get(Object key) { + switch (key) { + case [m.value, m.symbol] : return m + case [z.value, z.symbol] : return z + case [p.value, p.symbol] : return p + default: return null + } + } + + T negative() { + T.get(-this.value) + } + + String toString() { this.symbol } +} + + +class BalancedTernaryInteger { + + static final MINUS = new BalancedTernaryInteger(T.m) + static final ZERO = new BalancedTernaryInteger(T.z) + static final PLUS = new BalancedTernaryInteger(T.p) + private static final LEADING_ZEROES = /^0+/ + + final String value + + BalancedTernaryInteger(String bt) { + assert bt && bt.toSet().every { T.get(it) } + value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); + } + + BalancedTernaryInteger(BigInteger i) { + this(i == 0 ? T.z.symbol : valueFromInt(i)); + } + + BalancedTernaryInteger(T...tArray) { + this(tArray.sum{ it.symbol }); + } + + BalancedTernaryInteger(List tList) { + this(tList.sum{ it.symbol }); + } + + private static String valueFromInt(BigInteger i) { + assert i != null + if (i < 0) return negate(valueFromInt(-i)) + if (i == 0) return '' + int bRem = (((i % 3) - 2) ?: -3) + 2 + valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) + } + + private static String negate(String bt) { + bt.collect{ T.get(it) }.inject('') { str, t -> + str + (-t) + } + } + + private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] + private static final prepValueLen = { int len, String s -> + s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } + } + private static final partCarrySum = { partialSum, carry, trit -> + [carry: carry, sum: [trit] + partialSum] + } + private static final partSum = { parts, trits -> + def carrySum = partCarrySum.curry(parts.sum) + switch ((trits + parts.carry).sort()) { + case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) //-3 + case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) //-2 + case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) //-1 + case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) //+0 + case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) //+1 + case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) //+2 + case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) //+3 + } + } + + BalancedTernaryInteger plus(BalancedTernaryInteger that) { + assert that != null + if (this == ZERO) return that + if (that == ZERO) return this + def prep = prepValueLen.curry([value.size(), that.value.size()].max()) + List values = [prep(value), prep(that.value)].transpose() + new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) + } + + BalancedTernaryInteger negative() { + !this ? this : new BalancedTernaryInteger(negate(value)) + } + + BalancedTernaryInteger minus(BalancedTernaryInteger that) { + assert that != null + this + -that + } + + private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] + private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } + + private BalancedTernaryInteger paddedValue(String pad) { + new BalancedTernaryInteger(value + pad) + } + + private BalancedTernaryInteger partialProduct(T multiplier, String pad){ + switch (multiplier) { + case T.z: return ZERO + case T.m: return -paddedValue(pad) + case T.p: default: return paddedValue(pad) + } + } + + BalancedTernaryInteger multiply(BalancedTernaryInteger that) { + assert that != null + if (that == ZERO) return ZERO + if (that == PLUS) return this + if (that == MINUS) return -this + if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { + return that.multiply(this) + } + that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> + [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] + }.sum + } + + BigInteger asBigInteger() { + value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } + } + + def asType(Class c) { + switch (c) { + case Integer: return asBigInteger() as Integer + case Long: return asBigInteger() as Long + case [BigInteger, Number]: return asBigInteger() + case Boolean: return this != ZERO + case String: return toString() + default: return super.asType(c) + } + } + + boolean equals(Object that) { + switch (that) { + case BalancedTernaryInteger: return this.value == that?.value + default: return super.equals(that) + } + } + + int hashCode() { this.value.hashCode() } + + String toString() { value } +} diff --git a/Task/Balanced-ternary/Groovy/balanced-ternary-2.groovy b/Task/Balanced-ternary/Groovy/balanced-ternary-2.groovy new file mode 100644 index 0000000000..4b97af254b --- /dev/null +++ b/Task/Balanced-ternary/Groovy/balanced-ternary-2.groovy @@ -0,0 +1,16 @@ +BalancedTernaryInteger a = new BalancedTernaryInteger('+-0++0+') +BalancedTernaryInteger b = new BalancedTernaryInteger(-436) +BalancedTernaryInteger c = new BalancedTernaryInteger(T.p, T.m, T.p, T.p, T.m) +BalancedTernaryInteger bmc = new BalancedTernaryInteger(-436 - (c as Integer)) +BalancedTernaryInteger atbmc = new BalancedTernaryInteger((a as Integer) * (-436 - (c as Integer))) + +printf ("%9s = %12s %8d\n", 'a', "${a}", a as Number) +printf ("%9s = %12s %8d\n", 'b', "${b}", b as Number) +printf ("%9s = %12s %8d\n", 'c', "${c}", c as Number) +assert (b-c) == bmc +printf ("%9s = %12s %8d\n", 'b-c', "${b-c}", (b-c) as Number) +assert (a * (b-c)) == atbmc +printf ("%9s = %12s %8d\n", 'a * (b-c)', "${a * (b-c)}", (a * (b-c)) as Number) + +println "\nDemonstrate failure:" +assert (a * (b-c)) == a diff --git a/Task/Balanced-ternary/Liberty-BASIC/balanced-ternary.liberty b/Task/Balanced-ternary/Liberty-BASIC/balanced-ternary.liberty new file mode 100644 index 0000000000..89b502073a --- /dev/null +++ b/Task/Balanced-ternary/Liberty-BASIC/balanced-ternary.liberty @@ -0,0 +1,137 @@ +global tt$ +tt$="-0+" '-1 0 1; +2 -> 1 2 3, instr + +'Test case: +'With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-": +'* write out a, b and c in decimal notation; +'* calculate a * (b - c), write out the result in both ternary and decimal notations. + +a$="+-0++0+" +a=deci(a$) +print "a",a, a$ + +b=-436 +b$=ternary$(b) +print "b",b, b$ + +c$="+-++-" +c=deci(c$) +print "c",c, c$ + +'calculate in ternary + +res$=multTernary$(a$, subTernary$(b$, c$)) +print "a * (b - c)", res$ +print "In decimal:",deci(res$) + +print "Check:" +print "a * (b - c)", a * (b - c) +end + +function deci(s$) + pow = 1 + for i = len(s$) to 1 step -1 + c$ = mid$(s$,i,1) + 'select case c$ + ' case "+":sign= 1 + ' case "-":sign=-1 + ' case "0":sign= 0 + 'end select + sign = instr(tt$,c$)-2 + deci = deci+pow*sign + pow = pow*3 + next +end function + +function ternary$(n) + while abs(n)>3^k/2 + k=k+1 + wend + k=k-1 + + pow = 3^k + for i = k to 0 step -1 + sign = (n>0) - (n<0) + sign = sign * (abs(n)>pow/2) + ternary$ = ternary$+mid$(tt$,sign+2,1) + n = n - sign*pow + pow = pow/3 + next + if ternary$ = "" then ternary$ ="0" +end function + +function multTernary$(a$, b$) + + c$ = "" + t$ = "" + shift$ = "" + for i = len(a$) to 1 step -1 + + select case mid$(a$,i,1) + case "+": t$ = b$ + case "0": t$ = "0" + case "-": t$ = negate$(b$) + end select + + c$ = addTernary$(c$, t$+shift$) + + shift$ = shift$ +"0" + 'print d, t$, c$ + next + multTernary$ = c$ +end function + +function subTernary$(a$, b$) + subTernary$ = addTernary$(a$, negate$(b$)) +end function + +function negate$(s$) + negate$="" + for i = 1 to len(s$) + 'print mid$(s$,i,1), instr(tt$, mid$(s$,i,1)), 4-instr(tt$, mid$(s$,i,1)) + negate$=negate$+mid$(tt$, 4-instr(tt$, mid$(s$,i,1)), 1) + next +end function + +function addTernary$(a$, b$) +'add a$ + b$, for now only positive + l = max(len(a$), len(b$)) + a$=pad$(a$,l) + b$=pad$(b$,l) + c$ = "" 'result + carry = 0 + for i = l to 1 step -1 + a = instr(tt$,mid$(a$,i,1))-2 + b = instr(tt$,mid$(b$,i,1))-2 '-1 0 1 + c = a+b+carry + + select case + case abs(c)<2 + carry = 0 + case c>0 + carry =1: c=c-3 + case c<0 + carry =-1: c=c+3 + end select + + 'print a, b, c + c$ = mid$(tt$,c+2,1)+c$ + next + if carry<>0 then c$ = mid$(tt$,carry+2,1) +c$ + 'print c$ + 'have to trim leading 0's + i=0 + while mid$(c$,i+1,1)="0" + i=i+1 + wend + c$=mid$(c$,i+1) + if c$="" then c$="0" + addTernary$ = c$ +end function + +function pad$(a$,n) 'pad from right with 0 to length n + pad$ = a$ + while len(pad$) [ '-', '' ], + '+0' => [ '+', '' ], + '+-' => [ '0', '' ], + '00' => [ '0', '' ], + '--' => [ '+', '-' ], + '++' => [ '-', '+' ], + ); + +sub add { + my ($b1, $b2) = @_; + return ($b1 or $b2 ) unless ($b1 and $b2); + my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; + return add( add($b1, $d->[1]), $b2 ).$d->[0]; +} + +sub unary_minus { + my $b = shift; + $b =~ tr/-+/+-/; + return $b; +} + +sub subtract { + my ($b1, $b2) = @_; + return add( $b1, unary_minus $b2 ); +} + +sub mult { + my ($b1, $b2) = @_; + my $r = '0'; + for( reverse split //, $b2 ){ + $r = add $r, $b1 if $_ eq '+'; + $r = subtract $r, $b1 if $_ eq '-'; + $b1 .= '0'; + } + $r =~ s/^0+//; + return $r; +} + +my $a = "+-0++0+"; +my $b = to_bt( -436 ); +my $c = "+-++-"; +my $d = mult( $a, subtract( $b, $c ) ); +printf " a: %14s %10d\n", $a, from_bt( $a ); +printf " b: %14s %10d\n", $b, from_bt( $b ); +printf " c: %14s %10d\n", $c, from_bt( $c ); +printf "a*(b-c): %14s %10d\n", $d, from_bt( $d ); diff --git a/Task/Balanced-ternary/Scala/balanced-ternary-1.scala b/Task/Balanced-ternary/Scala/balanced-ternary-1.scala new file mode 100644 index 0000000000..7ab1da7da0 --- /dev/null +++ b/Task/Balanced-ternary/Scala/balanced-ternary-1.scala @@ -0,0 +1,104 @@ +object TernaryBit { + val P = TernaryBit(+1) + val M = TernaryBit(-1) + val Z = TernaryBit( 0) + + implicit def asChar(t: TernaryBit): Char = t.charValue + implicit def valueOf(c: Char): TernaryBit = { + c match { + case '0' => 0 + case '+' => 1 + case '-' => -1 + case nc => throw new IllegalArgumentException("Illegal ternary symbol " + nc) + } + } + implicit def asInt(t: TernaryBit): Int = t.intValue + implicit def valueOf(i: Int): TernaryBit = TernaryBit(i) +} + +case class TernaryBit(val intValue: Int) { + + def inverse: TernaryBit = TernaryBit(-intValue) + + def charValue = intValue match { + case 0 => '0' + case 1 => '+' + case -1 => '-' + } +} + +class Ternary(val bits: List[TernaryBit]) { + + def + (b: Ternary) = { + val sumBits: List[Int] = bits.map(_.intValue).zipAll(b.bits.map(_.intValue), 0, 0).map(p => p._1 + p._2) + + // normalize + val iv: Tuple2[List[Int], Int] = (List(), 0) + val (revBits, carry) = sumBits.foldLeft(iv)((accu: Tuple2[List[Int], Int], e: Int) => { + val s = e + accu._2 + (((s + 1 + 3 * 100) % 3 - 1) :: accu._1 , (s + 1 + 3 * 100) / 3 - 100) + }) + + new Ternary(( TernaryBit(carry) :: revBits.map(TernaryBit(_))).reverse ) + } + + def - (b: Ternary) = {this + (-b)} + def <<<(a: Int): Ternary = { List.fill(a)(TernaryBit.Z) ++ bits} + def >>>(a: Int): Ternary = { bits.drop(a) } + def unary_- = { bits.map(_.inverse) } + + def ** (b: TernaryBit): Ternary = { + b match { + case TernaryBit.P => this + case TernaryBit.M => - this + case TernaryBit.Z => 0 + } + } + + def * (mul: Ternary): Ternary = { + // might be done more efficiently - perform normalize only once + mul.bits.reverse.foldLeft(new Ternary(Nil))((a: Ternary, b: TernaryBit) => (a <<< 1) + (this ** b)) + } + + def intValue = bits.foldRight(0)((c, a) => a*3 + c.intValue) + + override def toString = new String(bits.reverse.map(_.charValue).toArray) +} + +object Ternary { + + implicit def asString(t: Ternary): String = t.toString() + implicit def valueOf(s: String): Ternary = new Ternary(s.toList.reverse.map(TernaryBit.valueOf(_))) + + implicit def asBits(t: Ternary): List[TernaryBit] = t.bits + implicit def valueOf(l: List[TernaryBit]): Ternary = new Ternary(l) + + implicit def asInt(t: Ternary): BigInt = t.intValue + // XXX not tail recursive + implicit def valueOf(i: BigInt): Ternary = { + if (i < 0) -valueOf(-i) + else if (i == 0) new Ternary(List()) + else if (i % 3 == 0) TernaryBit.Z :: valueOf(i / 3) + else if (i % 3 == 1) TernaryBit.P :: valueOf(i / 3) + else /*(i % 3 == 2)*/ TernaryBit.M :: valueOf((i + 1) / 3) + } + implicit def intToTernary(i: Int): Ternary = valueOf(i) +} + + +Then these classes can be used in the following way: + +object Main { + + def main(args: Array[String]): Unit = { + val a: Ternary = "+-0++0+" + val b: Ternary = -436 + val c: Ternary = "+-++-" + println(a.toString + " " + a.intValue) + println(b.toString + " " + b.intValue) + println(c.toString + " " + c.intValue) + val res = a * (b - c) + println(res.toString + " " + res.intValue) + } + +} diff --git a/Task/Balanced-ternary/Scala/balanced-ternary-2.scala b/Task/Balanced-ternary/Scala/balanced-ternary-2.scala new file mode 100644 index 0000000000..3c884364b5 --- /dev/null +++ b/Task/Balanced-ternary/Scala/balanced-ternary-2.scala @@ -0,0 +1,15 @@ +object TernarySpecification extends Properties("Ternary") { + + property("sum") = forAll { (a: Int, b: Int) => + val at: Ternary = a + val bt: Ternary = b + (at+bt).intValue == (at.intValue + bt.intValue) + } + + property("multiply") = forAll { (a: Int, b: Int) => + val at: Ternary = a + val bt: Ternary = b + (at*bt).intValue == (at.intValue * bt.intValue) + } + +} diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index e1ba6dcc55..fe4607a0c9 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -1,16 +1,17 @@ #define system. +#define system'routines. -#symbol shuffle = &&:aLiteral +#symbol shuffle = (:aLiteral) [ - #var aLength := aLiteral Length. - #var aShuffled := stringControl toArray:aLiteral. + #var aLength := aLiteral length. + #var aShuffled := literalControl toArray:aLiteral. - control from:0 &till:aLength &do: &&:i + control from:0 &till:aLength &do: i [ #var aChar := aLiteral@i. (aChar == (aShuffled@i)) ? [ - control from:0 &till:aLength &do: &&:j + control from:0 &till:aLength &do: j [ #var anAltChar := aShuffled@j. (anAltChar != aChar)and:[ anAltChar != (aLiteral@i) ]and:[aChar != (aLiteral@j)] ? @@ -23,22 +24,22 @@ ]. ]. - ^ Summing new:(String new) foreach:aShuffled Literal. + ^ Summing new:(String new) foreach:aShuffled literal. ]. -#symbol scoreShuffle = &&:anOriginal:aShuffled +#symbol scoreShuffle = (:anOriginal:aShuffled) [ #var aScore := Integer new. - control from:0 &till:(anOriginal Length) &do: &&:i + control from:0 &till:(anOriginal length) &do: i [ (anOriginal @ i) == (aShuffled @ i) ? [ aScore += 1. ]. ]. - ^ aScore Number. + ^ aScore number. ]. #symbol program = [ - control foreach:("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") &do: &&:aWord + control foreach:("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") &do: aWord [ #var aShuffled := shuffle:aWord. diff --git a/Task/Best-shuffle/PL-I/best-shuffle.pli b/Task/Best-shuffle/PL-I/best-shuffle.pli index c4fbca48b5..2c779af93e 100644 --- a/Task/Best-shuffle/PL-I/best-shuffle.pli +++ b/Task/Best-shuffle/PL-I/best-shuffle.pli @@ -51,17 +51,3 @@ search: procedure (s, c, k) returns (fixed binary); end search; end shuffle; - -OUTPUT: - -abracadabra -baaracadrab 0 - -prrrrrr -rprrrrr 5 - -tree -eert 0 - -A -A 1 diff --git a/Task/Best-shuffle/Scala/best-shuffle-1.scala b/Task/Best-shuffle/Scala/best-shuffle-1.scala new file mode 100644 index 0000000000..89bdbd9eb4 --- /dev/null +++ b/Task/Best-shuffle/Scala/best-shuffle-1.scala @@ -0,0 +1,34 @@ + def coincidients(s1: Seq[Char], s2: Seq[Char]): Int = (s1, s2).zipped.count(p => (p._1 == p._2)) + def freqMap(s1: List[Char]) = s1.groupBy(_.toChar).mapValues(_.size) + def estimate(s1: List[Char]): Int = if (s1 == Nil) 0 else List(0, freqMap(s1).maxBy(_._2)._2 - (s1.size / 2)).max + + def bestShuffle(s: String): Pair[String, Int] = { + if (s == "") return ("", 0) else {} + val charList = s.toList + val estim = estimate(charList) + + // purely functional polynomial solution + def doStep(accu: List[Pair[Int, Int]], sourceFreqMap: Map[Int, Int], targetFreqMap: Map[Int, Int], stepsLeft: Int): List[Pair[Int, Int]] = { + if (stepsLeft == 0) accu else { + val srcChoices = sourceFreqMap.groupBy(_._2).minBy(_._1)._2 + val src = srcChoices.toList.apply(Random.nextInt(srcChoices.size))._1 + + val tgtChoices = targetFreqMap.map(p => if (charList(p._1) != charList(src)) (p._1, p._2) else (p._1, Int.MaxValue / 2)).groupBy(_._2).minBy(_._1)._2 + val tgt = tgtChoices.toList.apply(Random.nextInt(tgtChoices.size))._1 + doStep((src, tgt) :: accu, + sourceFreqMap.filterKeys(_ != src).map(p => if (charList(p._1) != charList(tgt)) (p._1, p._2 - 1) else (p._1, p._2)), + targetFreqMap.filterKeys(_ != tgt).map(p => if (charList(p._1) != charList(src)) (p._1, p._2 - 1) else (p._1, p._2)), + stepsLeft - 1) + } + } + + val leftFreqMap: Map[Int, Int] = charList.zipWithIndex.map(p => (p._2, p._1)).toMap.mapValues(x => freqMap(charList).mapValues(charList.size - _)(x)) + + val substs = doStep(List(), leftFreqMap, leftFreqMap, charList.size) + val res = substs.sortBy(_._1).map(p => charList(p._2)) + (res.mkString, coincidients(charList, res)) + + // exponential solution (inefficient) + //Random.shuffle(charList).permutations.find(coincidients(charList, _) <= estim) + + } diff --git a/Task/Best-shuffle/Scala/best-shuffle-2.scala b/Task/Best-shuffle/Scala/best-shuffle-2.scala new file mode 100644 index 0000000000..cc9e2cafb3 --- /dev/null +++ b/Task/Best-shuffle/Scala/best-shuffle-2.scala @@ -0,0 +1,10 @@ + def main(args: Array[String]): Unit = { + println(bestShuffle("abracadabra")); + println(bestShuffle("seesaw")); + println(bestShuffle("elk")); + println(bestShuffle("grrrrrr")); + println(bestShuffle("up")); + println(bestShuffle("a")); + + BestShuffleSpecification.check + } diff --git a/Task/Best-shuffle/Scala/best-shuffle-3.scala b/Task/Best-shuffle/Scala/best-shuffle-3.scala new file mode 100644 index 0000000000..807308c70b --- /dev/null +++ b/Task/Best-shuffle/Scala/best-shuffle-3.scala @@ -0,0 +1,18 @@ +object BestShuffleSpecification extends Properties("BestShuffle") { + + property("size") = forAll { (src: String) => + val s = Main.bestShuffle(src) + s._1.size == src.size + } + + property("freq") = forAll { (src: String) => + val s = Main.bestShuffle(src) + Main.freqMap(s._1.toList) == Main.freqMap(src.toList) + } + + property("estimate") = forAll { (src: String) => + val s = Main.bestShuffle(src) + Main.estimate(src.toList) == s._2 + } + +} diff --git a/Task/Binary-digits/Delphi/binary-digits.delphi b/Task/Binary-digits/Delphi/binary-digits.delphi index e993e8e9ae..561c069b5e 100644 --- a/Task/Binary-digits/Delphi/binary-digits.delphi +++ b/Task/Binary-digits/Delphi/binary-digits.delphi @@ -1,16 +1,13 @@ +function IntToBinStr(AInt : integer) : string; +begin + Result := ''; + repeat + Result := Chr(Ord('0')+(AInt and 1))+Result; + AInt := AInt div 2; + until (AInt = 0); +end; + procedure Binary_Digits; - - function IntToBinStr(AInt : integer) : string; - - begin - Result := ''; - while AInt > 0 do - begin - Result := Chr(Ord('0')+(AInt mod 2))+Result; - AInt := AInt div 2; - end; - end; - begin writeln(' 5: '+IntToBinStr(5)); writeln(' 50: '+IntToBinStr(50)); diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index d6f7d16e6f..0a7e068b3b 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -5,7 +5,7 @@ #symbol program = [ - console writeLine:(convertControl toLiteral:5 &radix:2). - console writeLine:(convertControl toLiteral:50 &radix:2). - console writeLine:(convertControl toLiteral:9000 &radix:2). + console writeLine:(convertor toLiteral:5 &base:2). + console writeLine:(convertor toLiteral:50 &base:2). + console writeLine:(convertor toLiteral:9000 &base:2). ]. diff --git a/Task/Binary-search/D/binary-search.d b/Task/Binary-search/D/binary-search.d index f2500674b1..1e1425f697 100644 --- a/Task/Binary-search/D/binary-search.d +++ b/Task/Binary-search/D/binary-search.d @@ -1,27 +1,31 @@ -import std.stdio, std.array; +import std.stdio, std.array, std.range, std.traits; -// Recursive -bool binarySearch(T)(in T[] data, in T item) pure nothrow { +/// Recursive. +bool binarySearch(R, T)(/*in*/ R data, in T x) +pure nothrow if (isRandomAccessRange!R && + is(Unqual!T == Unqual!(ElementType!R))) { if (data.empty) return false; immutable i = data.length / 2; immutable mid = data[i]; - if (mid > item) - return binarySearch(data[0 .. i], item); - if (mid < item) - return binarySearch(data[i+1 .. $], item); + if (mid > x) + return data[0 .. i].binarySearch(x); + if (mid < x) + return data[i + 1 .. $].binarySearch(x); return true; } -// Iterative -bool binarySearchIt(T)(const(T)[] data, in T item) pure nothrow { +/// Iterative. +bool binarySearchIt(R, T)(/*in*/ R data, in T x) +pure nothrow if (isRandomAccessRange!R && + is(Unqual!T == Unqual!(ElementType!R))) { while (!data.empty) { immutable i = data.length / 2; immutable mid = data[i]; - if (mid > item) + if (mid > x) data = data[0 .. i]; - else if (mid < item) - data = data[i+1 .. $]; + else if (mid < x) + data = data[i + 1 .. $]; else return true; } @@ -29,8 +33,11 @@ bool binarySearchIt(T)(const(T)[] data, in T item) pure nothrow { } void main() { - immutable items = [2, 4, 6, 8, 9]; + /*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted; foreach (x; [1, 8, 10, 9, 5, 2]) - writefln("%2d %5s %5s", x, binarySearch(items, x), - binarySearchIt(items, x)); + writefln("%2d %5s %5s %5s", x, + items.binarySearch(x), + items.binarySearchIt(x), + // Standard Binary Search: + !items.equalRange(x).empty); } diff --git a/Task/Binary-search/Julia/binary-search-1.julia b/Task/Binary-search/Julia/binary-search-1.julia new file mode 100644 index 0000000000..9b022926a6 --- /dev/null +++ b/Task/Binary-search/Julia/binary-search-1.julia @@ -0,0 +1,15 @@ +function binary_search(l, value) + low = 1 + high = length(l) + while low <= high + mid = int((low+high)/2) + if l[mid] > value + high = mid-1 + elseif l[mid] < value + low = mid+1 + else + return l[mid] + end + end + return -1 +end diff --git a/Task/Binary-search/Julia/binary-search-2.julia b/Task/Binary-search/Julia/binary-search-2.julia new file mode 100644 index 0000000000..38aaa40a12 --- /dev/null +++ b/Task/Binary-search/Julia/binary-search-2.julia @@ -0,0 +1,10 @@ +function binary_search(l, value, low = 1, high = -1) + high == -1 && (high = length(l)) + l==[] && (return -1) + low >= high && + ((low > high || l[low] != value) ? (return -1) : return low) + mid = int((low+high)/2) + l[mid] > value ? (return binary_search(l, value, low, mid-1)) : + l[mid] < value ? (return binary_search(l, value, mid+1, high)) : + return mid +end diff --git a/Task/Binary-search/Perl/binary-search-1.pl b/Task/Binary-search/Perl/binary-search-1.pl index 037b86103d..1d9f4e117d 100644 --- a/Task/Binary-search/Perl/binary-search-1.pl +++ b/Task/Binary-search/Perl/binary-search-1.pl @@ -1,7 +1,7 @@ sub binary_search { - ($array_ref, $value, $left, $right) = @_; + my ($array_ref, $value, $left, $right) = @_; while ($left <= $right) { - $middle = ($right + $left) / 2; + my $middle = int(($right + $left) / 2); if ($array_ref->[$middle] == $value) { return 1; } diff --git a/Task/Binary-search/Perl/binary-search-2.pl b/Task/Binary-search/Perl/binary-search-2.pl index 230f4bb380..aa4ecb82fc 100644 --- a/Task/Binary-search/Perl/binary-search-2.pl +++ b/Task/Binary-search/Perl/binary-search-2.pl @@ -1,9 +1,9 @@ sub binary_search { - ($array_ref, $value, $left, $right) = @_; + my ($array_ref, $value, $left, $right) = @_; if ($right < $left) { return 0; } - $middle = ($right + $left) / 2; + my $middle = int(($right + $left) / 2); if ($array_ref->[$middle] == $value) { return 1; } diff --git a/Task/Binary-search/Python/binary-search-4.py b/Task/Binary-search/Python/binary-search-4.py new file mode 100644 index 0000000000..03292b1010 --- /dev/null +++ b/Task/Binary-search/Python/binary-search-4.py @@ -0,0 +1,6 @@ +from bisect import bisect_left + +def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi + hi = hi if hi is not None else len(a) # hi defaults to len(a) + pos = bisect_left(a,x,lo,hi) # find insertion position + return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end diff --git a/Task/Binary-search/Python/binary-search-5.py b/Task/Binary-search/Python/binary-search-5.py new file mode 100644 index 0000000000..888f794825 --- /dev/null +++ b/Task/Binary-search/Python/binary-search-5.py @@ -0,0 +1,12 @@ +def binary_search(l, value): + low = 0 + high = len(l)-1 + while low + 1 < high: + mid = (low+high)//2 + if l[mid] > value: + high = mid + elif l[mid] < value: + low = mid + else: + return mid + return high if abs(l[high] - value) < abs(l[low] - value) else low diff --git a/Task/Binary-search/REXX/binary-search-1.rexx b/Task/Binary-search/REXX/binary-search-1.rexx index dde8d834d6..dca834d4d3 100644 --- a/Task/Binary-search/REXX/binary-search-1.rexx +++ b/Task/Binary-search/REXX/binary-search-1.rexx @@ -1,11 +1,9 @@ /*REXX program finds a value in a list using a recursive binary search. */ -@=' 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149', - '163 179 191 197 223 227 239 251 269 277 281 307 311 331 347', - '367 379 397 419 431 439 457 461 479 487 499 521 541 557 569', - '587 599 613 617 631 641 659 673 701 719 727 739 751 757 769', - '787 809 821 827 853 857 877 881 907 929 937 967 991 1009' - /*(above) list of strong primes.*/ - +@= 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 163 179, + 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439, + 457 461 479 487 499 521 541 557 569 587 599 613 617 631 641 659 673 701 719, + 727 739 751 757 769 787 809 821 827 853 857 877 881 907 929 937 967 991 1009 + /* [↑] a list of strong primes.*/ parse arg ? . /*get a number the user specified*/ if ?=='' then do say; say '*** error! *** no arg specified.'; say @@ -16,19 +14,19 @@ high = words(@) avg=(word(@,1)+word(@,high))/2 loc = binarySearch(low,high) -if loc==-1 then do - say ? "wasn't found in the list." - exit /*stick a fork in it, we're done.*/ - end - else say ? 'is in the list, its index is:' loc +if loc==-1 then do + say ? "wasn't found in the list." + exit /*stick a fork in it, we're done.*/ + end + else say ? 'is in the list, its index is:' loc say -say 'arithmetic mean of the' high "values=" avg +say 'arithmetic mean of the' high "values=" avg exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────BINARYSEARCH subroutine──────────*/ +/*───────────────────────────────────BINARYSEARCH subroutine────────────*/ binarySearch: procedure expose @ ?; parse arg low,high -if high? then return binarySearch(low,mid-1) - return binarySearch(mid+1,high) +if ?=y then return mid +if y>? then return binarySearch(low, mid-1) + return binarySearch(mid+1, high) diff --git a/Task/Binary-search/REXX/binary-search-2.rexx b/Task/Binary-search/REXX/binary-search-2.rexx index 0d257886d4..ae17f93d8c 100644 --- a/Task/Binary-search/REXX/binary-search-2.rexx +++ b/Task/Binary-search/REXX/binary-search-2.rexx @@ -1,31 +1,27 @@ /*REXX program finds a value in a list using an iterative binary search.*/ -@=' 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131', - '139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349', - '353 359 383 389 401 409 421 433 443 449 463 467 491 503 509 523', - '547 571 577 601 619 643 647 661 677 683 691 709 743 761 773 797', - '811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013' - /*(above) list of weak primes. */ - +@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181, + 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433, + 443 449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709, + 743 761 773 797 811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013 + /* [↑] a list of weak primes.*/ parse arg ? . /*get a number the user specified*/ - -if ?=='' then do - say; say '*** error! *** no arg specified.'; say - exit 13 - end +if ?=='' then do + say; say '*** error! *** no arg specified.'; say + exit 13 + end low = 1 high = words(@) -say 'arithmetic mean of the' high "values=" (word(@,1)+word(@,high))/2 +say 'arithmetic mean of the' high "values=" (word(@,1)+word(@,high))/2 say - do while low<=high; mid=(low+high)%2; y=word(@,mid) + do while low<=high; mid=(low+high)%2; y=word(@,mid) + if ?=y then do + say ? 'is in the list, its index is:' mid + exit /*stick a fork in it, we're done.*/ + end - if ?=y then do - say ? 'is in the list, its index is:' mid - exit /*stick a fork in it, we're done.*/ - end - - if y>? then high=mid-1 - else low=mid+1 + if y>? then high=mid-1 + else low=mid+1 end /*while*/ -say ? "wasn't found in the list." +say ? "wasn't found in the list." /*stick a fork in it, we're done.*/ diff --git a/Task/Binary-strings/BASIC/binary-strings-1.basic b/Task/Binary-strings/BASIC/binary-strings-1.basic new file mode 100644 index 0000000000..d9a31fabdf --- /dev/null +++ b/Task/Binary-strings/BASIC/binary-strings-1.basic @@ -0,0 +1,28 @@ +REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM) +A$ = "STRING" : REM CREATION +A$ = "" : REM DESTRUCTION +PRINT FRE(0) : REM GARBAGE COLLECTION + +REM STRING ASSIGNMENT +A$ = "STRING" : R$ = "DEUX" + +REM STRING COMPARISON +PRINT A$ = B$; A$ <> B$; A$ < B$; A$ > B$; A$ <= B$; A$ >= B$ + +REM STRING CLONING AND COPYING +B$ = A$ + +REM CHECK IF A STRING IS EMPTY +PRINT LEN(A$) = 0 + +REM APPEND A BYTE TO A STRING +A$ = A$ + CHR$(0) + +REM EXTRACT A SUBSTRING FROM A STRING +S$ = MID$(A$, 2, 3) + +REM REPLACE EVERY OCCURRENCE OF A BYTE (OR A STRING) IN A STRING WITH ANOTHER STRING +S = LEN(S$) : R = LEN(R$) : A = LEN(A$) : IF A > S THEN B$ = "" : FOR I = 1 TO A : F = MID$(A$, I, S) = S$ : B$ = B$ + MID$(R$, 1, R * F) + MID$(A$, I, F = 0) : NEXT I : A$ = B$ : PRINT A$ + +REM JOIN STRINGS +J$ = A$ + STR$(42) + " PUDDLES " + B$ + CHR$(255) : REM USE + diff --git a/Task/Binary-strings/BASIC/binary-strings.basic b/Task/Binary-strings/BASIC/binary-strings-2.basic similarity index 100% rename from Task/Binary-strings/BASIC/binary-strings.basic rename to Task/Binary-strings/BASIC/binary-strings-2.basic diff --git a/Task/Binary-strings/Deja-Vu/binary-strings.djv b/Task/Binary-strings/Deja-Vu/binary-strings.djv new file mode 100644 index 0000000000..e6ea3ec81d --- /dev/null +++ b/Task/Binary-strings/Deja-Vu/binary-strings.djv @@ -0,0 +1,10 @@ +local :b make-blob 10 #ten bytes of initial size +set-to b 0 255 +!. get-from b 0 #prints 255 +!. b #prints (blob:ff000000000000000000) +local :b2 make-blob 3 +set-to b2 0 97 +set-to b2 1 98 +set-to b2 2 99 +!. b #prints (blob:"abc") +!. !encode!utf-8 b #prints "abc" diff --git a/Task/Binary-strings/Erlang/binary-strings-1.erl b/Task/Binary-strings/Erlang/binary-strings-1.erl new file mode 100644 index 0000000000..2d44b5d556 --- /dev/null +++ b/Task/Binary-strings/Erlang/binary-strings-1.erl @@ -0,0 +1,49 @@ +-module(binary_string). +-compile([export_all]). + +%% Erlang has very easy handling of binary strings. Using +%% binary/bitstring syntax the various task features will be +%% demonstrated. + + +%% Erlang has GC so destruction is not shown. +test() -> + Binary = <<0,1,1,2,3,5,8,13>>, % binaries can be created directly + io:format("Creation: ~p~n",[Binary]), + Copy = binary:copy(Binary), % They can also be copied + io:format("Copy: ~p~n",[Copy]), + Compared = Binary =:= Copy, % They can be compared directly + io:format("Equal: ~p = ~p ? ~p~n",[Binary,Copy,Compared]), + Empty1 = size(Binary) =:= 0, % The empty binary would have size 0 + io:format("Empty: ~p ? ~p~n",[Binary,Empty1]), + Empty2 = size(<<>>) =:= 0, % The empty binary would have size 0 + io:format("Empty: ~p ? ~p~n",[<<>>,Empty2]), + Substring = binary:part(Binary,3,3), + io:format("Substring: ~p [~b..~b] => ~p~n",[Binary,3,5,Substring]), + Replace = binary:replace(Binary,[<<1>>],<<42>>,[global]), + io:format("Replacement: ~p~n",[Replace]), + Append = <>, + io:format("Append: ~p~n",[Append]), + Join = <>/binary>>, + io:format("Join: ~p~n",[Join]). + +%% Since the task also asks that we show how these can be reproduced +%% rather than just using BIFs, the following are some example +%% recursive functions reimplementing some of the above. + +%% Empty string +is_empty(<<>>) -> + true; +is_empty(_) -> + false. + +%% Replacement: +replace(Binary,Value,Replacement) -> + replace(Binary,Value,Replacement,<<>>). + +replace(<<>>,_,_,Acc) -> + Acc; +replace(<>,Value,Replacement,Acc) -> + replace(Rest,Value,Replacement,<< Acc/binary, Replacement >>); +replace(<>,Value,Replacement,Acc) -> + replace(Rest,Value,Replacement,<< Acc/binary, Keep >>). diff --git a/Task/Binary-strings/Erlang/binary-strings-2.erl b/Task/Binary-strings/Erlang/binary-strings-2.erl new file mode 100644 index 0000000000..5201a2b90b --- /dev/null +++ b/Task/Binary-strings/Erlang/binary-strings-2.erl @@ -0,0 +1,10 @@ +215> binary_string:test(). +Creation: <<0,1,1,2,3,5,8,13>> +Copy: <<0,1,1,2,3,5,8,13>> +Equal: <<0,1,1,2,3,5,8,13>> = <<0,1,1,2,3,5,8,13>> ? true +Empty: <<0,1,1,2,3,5,8,13>> ? false +Empty: <<>> ? true +Substring: <<0,1,1,2,3,5,8,13>> [3..5] => <<2,3,5>> +Replacement: <<0,42,42,2,3,5,8,13>> +Append: <<0,1,1,2,3,5,8,13,21>> +Join: <<0,1,1,2,3,5,8,13,21,34,55>> diff --git a/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada b/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada new file mode 100644 index 0000000000..d11fb5bb8a --- /dev/null +++ b/Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada @@ -0,0 +1,128 @@ +with Ada.Exceptions, Interfaces; +with Ada.Streams; +use Ada.Exceptions, Interfaces; +use Ada.Streams; + +package Bitcoin is + subtype BT_Raw_Addr is Stream_Element_Array(1..25); + subtype BT_Checksum is Stream_Element_Array(1..4); + subtype BT_Addr is String(1..34); + subtype Sha256String is String(1..64); + Invalid_Address_Error : Exception; + + function Double_Sha256(S : Stream_Element_Array) return BT_Checksum; + function Is_Valid(A : BT_Raw_Addr) return Boolean; + procedure Base58_Decode(S : BT_Addr; A : out BT_Raw_Addr) ; +private + Base58 : constant String := "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + function Hex_Val (C, C2 : Character) return Stream_Element; +end Bitcoin; + + +with GNAT.SHA256, Ada.Strings.Fixed; +use GNAT.SHA256, Ada.Strings.Fixed; + +package body Bitcoin is + +function Hex_Val (C, C2 : Character) return Stream_Element is + subtype Nibble is Integer range 0..15; + HEX : array (0..255) of Nibble := ( + 48=>0, 49=>1, 50=>2, 51=>3, 52=>4, 53=>5, 54=>6, 55=>7, 56=>8, 57=>9 + , 65=>10, 66=>11, 67=>12, 68 =>13, 69 =>14, 70 =>15 + , 97=>10, 98=>11, 99=>12, 100=>13, 101=>14, 102=>15 + , Others=>0 + ); +begin + return Stream_Element(HEX(Character'Pos(C)) * 16 + HEX(Character'Pos(C2))); +end Hex_Val; + +function Double_Sha256(S : Stream_Element_Array) return BT_Checksum is + Ctx : Context := Initial_Context; + D : Message_Digest; + S2 : Stream_Element_Array(1..32); + Ctx2 : Context := Initial_Context; + C : BT_Checksum; +begin + Update(Ctx, S); + D := Digest(Ctx); + for I in S2'Range loop + S2(I) := Hex_Val(D(Integer(I)*2-1), D(Integer(I)*2)); + end loop; + Update(Ctx2, S2); + D := Digest(Ctx2); + for I in C'Range loop + C(I) := Hex_Val(D(Integer(I)*2-1), D(Integer(I)*2)); + end loop; + return C; + +end Double_Sha256; + + +-------------------------------------------------------------------------------- +-- Summary of Base58: -- +-- We decode S into a 200 bit unsigned integer. -- +-- We could use a BigNum library, but choose to go without. -- +-------------------------------------------------------------------------------- +procedure Base58_Decode(S : BT_Addr; A : out BT_Raw_Addr) is +begin + A := (Others => 0); + for I in S'Range loop + declare + P : Natural := Index(Base58, String(S(I..I))); + C : Natural; + begin + if P = 0 then + raise Invalid_Address_Error; + end if; + 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 + end loop; + if C /= 0 then + raise Invalid_Address_Error; + end if; + end; + end loop; +end Base58_Decode; + + +function Is_Valid(A : BT_Raw_Addr) return Boolean is +begin + return A(1) = 0 and A(22..25) = Double_Sha256(A(1..21)); +end Is_Valid; + + +end Bitcoin; + +with Ada.Text_IO, Bitcoin; +use Ada.Text_IO, Bitcoin; + +procedure Bitcoin_Addr_Validate is +begin + declare + BTs : array (positive range <>) of BT_Addr := ( + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- VALID + , "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9" -- VALID + , "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X" -- checksum changed, original data. + , "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- data changed, original checksum. + , "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- invalid chars + ); + begin + for I in Bts'Range loop + declare + A : BT_Raw_Addr; + Valid : Boolean; + begin + Put(BTs(I) & " validity: "); + Base58_Decode(BTs(I), A); + Valid := Is_Valid(A); + Put_Line(Boolean'Image(Valid)); + exception + when E : Invalid_Address_Error => + Put_Line ("*** Error: Invalid BT address."); + end; + end loop; + end; +end Bitcoin_Addr_Validate; diff --git a/Task/Bitcoin-address-validation/Erlang/bitcoin-address-validation.erl b/Task/Bitcoin-address-validation/Erlang/bitcoin-address-validation.erl new file mode 100644 index 0000000000..06169d381c --- /dev/null +++ b/Task/Bitcoin-address-validation/Erlang/bitcoin-address-validation.erl @@ -0,0 +1,17 @@ +-module( bitcoin_address ). + +-export( [task/0, validate/1] ). + +task() -> + io:fwrite( "Validate ~p~n", ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"] ), + io:fwrite( "~p~n", [validate("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")] ), + io:fwrite( "Validate ~p~n", ["1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW622"] ), + io:fwrite( "~p~n", [validate("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW622")] ). + +validate( String ) -> + {length_25, <>} = {length_25, base58:base58_to_binary( String )}, + <> = Address, + {version_0, <<0>>} = {version_0, Version}, + <> = crypto:hash( sha256, crypto:hash(sha256, Address) ), + {checksum, Checksum} = {checksum, Four_bytes}, + ok. diff --git a/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go b/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go index 9d6c726869..a84e07fbfb 100644 --- a/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go +++ b/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go @@ -44,7 +44,7 @@ func (a *A25) doubleSHA256() []byte { func (a *A25) ComputeChecksum() (c [4]byte) { copy(c[:], a.doubleSHA256()) return -} +}/* {{header|Go}} */ // Tmpl and Set58 are adapted from the C solution. // Go has big integers but this techinique seems better. diff --git a/Task/Bitmap-B-zier-curves-Cubic/Fortran/bitmap-b-zier-curves-cubic.f b/Task/Bitmap-B-zier-curves-Cubic/Fortran/bitmap-b-zier-curves-cubic.f index 4e7e6e6471..3b5c3f9d5c 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/Fortran/bitmap-b-zier-curves-cubic.f +++ b/Task/Bitmap-B-zier-curves-Cubic/Fortran/bitmap-b-zier-curves-cubic.f @@ -9,8 +9,8 @@ subroutine cubic_bezier(img, p1, p2, p3, p4, color) do i = 0, N_SEG t = real(i) / real(N_SEG) a = (1.0 - t)**3.0 - b = 3.0 * t * (1.0 - t)**2.0 - c = 3.0 * (1.0 - t) * t**2.0 + b = 3.0 * t * (1.0 - t)**2 + c = 3.0 * (1.0 - t) * t**2 d = t**3.0 x = a * p1%x + b * p2%x + c * p3%x + d * p4%x y = a * p1%y + b * p2%y + c * p3%y + d * p4%y diff --git a/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp b/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp index 3421d234c1..b47e43dd1e 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp +++ b/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp @@ -1,44 +1,44 @@ void Line( const float x1, const float y1, const float x2, const float y2, const Color& color ) { // Bresenham's line algorithm - const bool steep = (fabs(y2 - y1) > fabs(x2 - x1)); - if(steep) - { - std::swap(x1, y1); - std::swap(x2, y2); - } + const bool steep = (fabs(y2 - y1) > fabs(x2 - x1)); + if(steep) + { + std::swap(x1, y1); + std::swap(x2, y2); + } - if(x1 > x2) - { - std::swap(x1, x2); - std::swap(y1, y2); - } + if(x1 > x2) + { + std::swap(x1, x2); + std::swap(y1, y2); + } - const float dx = x2 - x1; - const float dy = fabs(y2 - y1); - - float error = dx / 2.0f; - const int ystep = (y1 < y2) ? 1 : -1; - int y = (int)y1; + const float dx = x2 - x1; + const float dy = fabs(y2 - y1); - const int maxX = (int)x2; + float error = dx / 2.0f; + const int ystep = (y1 < y2) ? 1 : -1; + int y = (int)y1; - for(int x=(int)x1; x dist-y dist-x)] + dist-y (abs (- y1 y2)) + steep (> dist-y dist-x)] (let [[x1 y1 x2 y2] (if steep [y1 x1 y2 x2] [x1 y1 x2 y2])] (let [[x1 y1 x2 y2] (if (> x1 x2) [x2 y2 x1 y1] [x1 y1 x2 y2])] - (let [delta-x (- x2 x1) - delta-y (abs (- y1 y2)) - y-step (if (< y1 y2) 1 -1)] + (let [delta-x (- x2 x1) + delta-y (abs (- y1 y2)) + y-step (if (< y1 y2) 1 -1)] - (let [plot (if steep - #(.setRGB buffer (int %1) (int %2) pixel) - #(.setRGB buffer (int %2) (int %1) pixel))] - - (loop [x x1 y y1 error (floor delta-x 2) ] - (plot x y) - (if (< x x2) - ; Rather then rebind error, test that it is less than delta-y rather than zero - (if (< error delta-y) - (recur (inc x) (+ y y-step) (+ error (- delta-x delta-y))) - (recur (inc x) y (- error delta-y))))))))))) + (let [plot (if steep + #(.setRGB buffer (int %1) (int %2) pixel) + #(.setRGB buffer (int %2) (int %1) pixel))] + + (loop [x x1 y y1 error (floor delta-x 2) ] + (plot x y) + (if (< x x2) + ; Rather then rebind error, test that it is less than delta-y rather than zero + (if (< error delta-y) + (recur (inc x) (+ y y-step) (+ error (- delta-x delta-y))) + (recur (inc x) y (- error delta-y))))))))))) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp b/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp index 72530b0ef9..200d7b7c46 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp +++ b/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp @@ -3,26 +3,26 @@ (declare (type integer x1 y1 x2 y2)) (declare (type rgb-pixel pixel)) (let* ((dist-x (abs (- x1 x2))) - (dist-y (abs (- y1 y2))) - (steep (> dist-y dist-x))) + (dist-y (abs (- y1 y2))) + (steep (> dist-y dist-x))) (when steep (psetf x1 y1 y1 x1 - x2 y2 y2 x2)) + x2 y2 y2 x2)) (when (> x1 x2) (psetf x1 x2 x2 x1 - y1 y2 y2 y1)) + y1 y2 y2 y1)) (let* ((delta-x (- x2 x1)) - (delta-y (abs (- y1 y2))) - (error (floor delta-x 2)) - (y-step (if (< y1 y2) 1 -1)) - (y y1)) + (delta-y (abs (- y1 y2))) + (error (floor delta-x 2)) + (y-step (if (< y1 y2) 1 -1)) + (y y1)) (loop - :for x :upfrom x1 :to x2 - :do (progn (if steep - (setf (rgb-pixel buffer x y) pixel) - (setf (rgb-pixel buffer y x) pixel)) - (setf error (- error delta-y)) - (when (< error 0) - (incf y y-step) - (incf error delta-x))))) + :for x :upfrom x1 :to x2 + :do (progn (if steep + (setf (rgb-pixel buffer x y) pixel) + (setf (rgb-pixel buffer y x) pixel)) + (setf error (- error delta-y)) + (when (< error 0) + (incf y y-step) + (incf error delta-x))))) buffer)) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-1.erl b/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-1.erl index 57c6a12054..22843b6ea1 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-1.erl +++ b/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-1.erl @@ -1,45 +1,45 @@ build_path({Sx, Sy}, {Tx, Ty}) -> - if - Tx < Sx -> StepX = -1; - true -> StepX = 1 - end, - if - Ty < Sy -> StepY = -1; - true -> StepY = 1 - end, - - Dx = abs((Tx-Sx)*2), - Dy = abs((Ty-Sy)*2), - - if - Dy > Dx -> Path = through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dx*2-Dy, []); - true -> Path = through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dy*2-Dx, []) - end, - - lists:reverse(Path). + if + Tx < Sx -> StepX = -1; + true -> StepX = 1 + end, + if + Ty < Sy -> StepY = -1; + true -> StepY = 1 + end, + + Dx = abs((Tx-Sx)*2), + Dy = abs((Ty-Sy)*2), + + if + Dy > Dx -> Path = through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dx*2-Dy, []); + true -> Path = through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dy*2-Dx, []) + end, + + lists:reverse(Path). through_x({Tx, _}, {Tx, _}, _, _, _, P) -> P; through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 >= 0 -> - Ny = Sy + StepY, - F1 = F0 - Dx, - Nx = Sx + StepX, + Ny = Sy + StepY, + F1 = F0 - Dx, + Nx = Sx + StepX, F2 = F1 + Dy, - through_x({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]); + through_x({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]); through_x({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 < 0 -> - Ny = Sy, - Nx = Sx + StepX, + Ny = Sy, + Nx = Sx + StepX, F2 = F0 + Dy, - through_x({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]). + through_x({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]). through_y({_, Ty}, {_, Ty}, _, _, _, P) -> P; through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 >= 0 -> - Nx = Sx + StepX, - F1 = F0 - Dy, - Ny = Sy + StepY, + Nx = Sx + StepX, + F1 = F0 - Dy, + Ny = Sy + StepY, F2 = F1 + Dx, - through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]); + through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]); through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F0, P) when F0 < 0 -> - Nx = Sx, - Ny = Sy + StepY, + Nx = Sx, + Ny = Sy + StepY, F2 = F0 + Dx, - through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]). + through_y({Nx, Ny}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, F2, [{Nx, Ny}|P]). diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-2.erl b/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-2.erl index c725b805c8..70c7ac5964 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-2.erl +++ b/Task/Bitmap-Bresenhams-line-algorithm/Erlang/bitmap-bresenhams-line-algorithm-2.erl @@ -1,30 +1,30 @@ line({X0, Y0}, {X1, Y1}) -> - SX = step(X0, X1), - SY = step(Y0, Y1), - DX = abs(X1 - X0), - DY = abs(Y1 - Y0), - Err = DX - DY, - line({X0, Y0}, {X1, Y1}, {SX, SY}, {DX, DY}, Err, []). - + SX = step(X0, X1), + SY = step(Y0, Y1), + DX = abs(X1 - X0), + DY = abs(Y1 - Y0), + Err = DX - DY, + line({X0, Y0}, {X1, Y1}, {SX, SY}, {DX, DY}, Err, []). + line({X1, Y1}, {X1, Y1}, _, _, _, Acc) -> - lists:reverse([{X1, Y1} | Acc]); + lists:reverse([{X1, Y1} | Acc]); line({X, Y}, {X1, Y1}, {SX, SY}, {DX, DY}, Err, Acc) -> - DE = 2 * Err, - {X0, Err0} = next_x(X, SX, DY, Err, DE), - {Y0, Err1} = next_y(Y, SY, DX, Err0, DE), - line({X0, Y0}, {X1, Y1}, {SX, SY}, {DX, DY}, Err1, [{X, Y} | Acc]). - + DE = 2 * Err, + {X0, Err0} = next_x(X, SX, DY, Err, DE), + {Y0, Err1} = next_y(Y, SY, DX, Err0, DE), + line({X0, Y0}, {X1, Y1}, {SX, SY}, {DX, DY}, Err1, [{X, Y} | Acc]). + step(P0, P1) when P0 < P1 -> - 1; + 1; step(_, _) -> - -1. - + -1. + next_x(X, SX, DY, E, DE) when DE > -DY -> - {X + SX, E - DY}; + {X + SX, E - DY}; next_x(X, _SX, _DY, E, _DE) -> - {X, E}. + {X, E}. next_y(Y, SY, DX, E, DE) when DE < DX -> - {Y + SY, E + DX}; + {Y + SY, E + DX}; next_y(Y, _SY, _DX, E, _DE) -> - {Y, E}. + {Y, E}. diff --git a/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl b/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl index f0077cb883..54949fb1d0 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl +++ b/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl @@ -11,25 +11,25 @@ CENTER(ME) SHOW(ME) BEGIN EVENTS - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN: Rhombus() ' Draw - CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: Rhombus() ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT END EVENTS SUB Rhombus() - Bresenham(50, 100, 100, 190)(100, 190, 150, 100)(150, 100, 100, 10)(100, 10, 50, 100) - - SUB Bresenham(x0, y0, x1, y1) - DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) - DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) - DIM tmp, er = IIF(dx > dy, dx, -dy) / 2 - - WHILE NOT (x0 = x1 ANDALSO y0 = y1) - PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order - tmp = er - IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF - IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF - WEND - END SUB + Bresenham(50, 100, 100, 190)(100, 190, 150, 100)(150, 100, 100, 10)(100, 10, 50, 100) + + SUB Bresenham(x0, y0, x1, y1) + DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) + DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) + DIM tmp, er = IIF(dx > dy, dx, -dy) / 2 + + WHILE NOT (x0 = x1 ANDALSO y0 = y1) + PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order + tmp = er + IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF + IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF + WEND + END SUB END SUB diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Forth/bitmap-bresenhams-line-algorithm.fth b/Task/Bitmap-Bresenhams-line-algorithm/Forth/bitmap-bresenhams-line-algorithm.fth index c45f02482e..0323036d77 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Forth/bitmap-bresenhams-line-algorithm.fth +++ b/Task/Bitmap-Bresenhams-line-algorithm/Forth/bitmap-bresenhams-line-algorithm.fth @@ -7,12 +7,12 @@ defer ystep \ 1+ or 1- ( x0 x1 y0 y1 ) 2dup - abs >r 2over - abs r> < - if ['] swap \ swap use of x and y + if ['] swap \ swap use of x and y else 2swap ['] noop then is steep ( y0 y1 x0 x1 ) 2dup > - if swap 2swap swap \ ensure x1 > x0 + if swap 2swap swap \ ensure x1 > x0 else 2swap then ( x0 x1 y0 y1 ) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/MAXScript/bitmap-bresenhams-line-algorithm.max b/Task/Bitmap-Bresenhams-line-algorithm/MAXScript/bitmap-bresenhams-line-algorithm.max index 9be76aa763..cea9eb507b 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/MAXScript/bitmap-bresenhams-line-algorithm.max +++ b/Task/Bitmap-Bresenhams-line-algorithm/MAXScript/bitmap-bresenhams-line-algorithm.max @@ -10,30 +10,30 @@ fn plot img coord steep col = fn drawLine img start end col = ( local steep = (abs (end.y - start.y)) > (abs (end.x - start.x)) - + if steep then ( swap start.x start.y swap end.x end.y ) - + if start.x > end.x then ( swap start.x end.x swap start.y end.y ) - + local deltaX = end.x - start.x local deltaY = abs (end.y - start.y) local error = deltaX / 2.0 local yStep = -1 local y = start.y - + if start.y < end.y then ( yStep = 1 ) - + for x in start.x to end.x do ( plot img [x, y] steep col diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Perl/bitmap-bresenhams-line-algorithm.pl b/Task/Bitmap-Bresenhams-line-algorithm/Perl/bitmap-bresenhams-line-algorithm.pl index 488c1d918b..9f3871eae0 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Perl/bitmap-bresenhams-line-algorithm.pl +++ b/Task/Bitmap-Bresenhams-line-algorithm/Perl/bitmap-bresenhams-line-algorithm.pl @@ -8,12 +8,12 @@ sub my_draw_line my $steep = (abs($y1 - $y0) > abs($x1 - $x0)); if ( $steep ) { - ( $y0, $x0 ) = ( $x0, $y0); - ( $y1, $x1 ) = ( $x1, $y1 ); + ( $y0, $x0 ) = ( $x0, $y0); + ( $y1, $x1 ) = ( $x1, $y1 ); } if ( $x0 > $x1 ) { - ( $x1, $x0 ) = ( $x0, $x1 ); - ( $y1, $y0 ) = ( $y0, $y1 ); + ( $x1, $x0 ) = ( $x0, $x1 ); + ( $y1, $y0 ) = ( $y0, $y1 ); } my $deltax = $x1 - $x0; my $deltay = abs($y1 - $y0); @@ -23,16 +23,16 @@ sub my_draw_line my $x; $ystep = ( $y0 < $y1 ) ? 1 : -1; for( $x = $x0; $x <= $x1; $x += 1 ) { - if ( $steep ) { - $img->draw_point($y, $x); - } else { - $img->draw_point($x, $y); - } - $error -= $deltay; - if ( $error < 0 ) { - $y += $ystep; - $error += $deltax; - } + if ( $steep ) { + $img->draw_point($y, $x); + } else { + $img->draw_point($x, $y); + } + $error -= $deltay; + if ( $error < 0 ) { + $y += $ystep; + $error += $deltax; + } } } diff --git a/Task/Bitmap-Bresenhams-line-algorithm/RapidQ/bitmap-bresenhams-line-algorithm-1.rapidq b/Task/Bitmap-Bresenhams-line-algorithm/RapidQ/bitmap-bresenhams-line-algorithm-1.rapidq index 192c9651d1..4ec81ef340 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/RapidQ/bitmap-bresenhams-line-algorithm-1.rapidq +++ b/Task/Bitmap-Bresenhams-line-algorithm/RapidQ/bitmap-bresenhams-line-algorithm-1.rapidq @@ -2,34 +2,34 @@ SUB draw_line(x1, y1, x2, y2, colour) x_dist = abs(x2-x1) y_dist = abs(y2-y1) IF y2-y1 < -x_dist OR x2-x1 <= -y_dist THEN - SWAP x1, x2 ' Swap start and end points - SWAP y1, y2 + SWAP x1, x2 ' Swap start and end points + SWAP y1, y2 END IF IF x1 < x2 THEN x_step = 1 ELSE x_step = -1 IF y1 < y2 THEN y_step = 1 ELSE y_step = -1 - IF y_dist > x_dist THEN ' steep angle, step by y - error = y_dist/2 - x = x1 - FOR y = y1 TO y2 - canvas.Pset(x, y, colour) - error = error - x_dist - IF error < 0 THEN - x = x + x_step - error = error + y_dist - END IF - NEXT y - ELSE ' not steep, step by x + IF y_dist > x_dist THEN ' steep angle, step by y + error = y_dist/2 + x = x1 + FOR y = y1 TO y2 + canvas.Pset(x, y, colour) + error = error - x_dist + IF error < 0 THEN + x = x + x_step + error = error + y_dist + END IF + NEXT y + ELSE ' not steep, step by x error = x_dist/2 - y = y1 - FOR x = x1 TO x2 - canvas.Pset(x, y, colour) - error = error - y_dist - IF error < 0 THEN - y = y + y_step - error = error + x_dist - END IF - NEXT y + y = y1 + FOR x = x1 TO x2 + canvas.Pset(x, y, colour) + error = error - y_dist + IF error < 0 THEN + y = y + y_step + error = error + x_dist + END IF + NEXT y END IF END SUB diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala b/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala index d1903e7044..4896181acb 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala +++ b/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala @@ -19,6 +19,6 @@ object BitmapOps { } for((x,y) <- it) - bm.setPixel(x, y, c) + bm.setPixel(x, y, c) } } diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Vedit-macro-language/bitmap-bresenhams-line-algorithm.vedit b/Task/Bitmap-Bresenhams-line-algorithm/Vedit-macro-language/bitmap-bresenhams-line-algorithm.vedit index 617c367e9f..c976a94ee3 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Vedit-macro-language/bitmap-bresenhams-line-algorithm.vedit +++ b/Task/Bitmap-Bresenhams-line-algorithm/Vedit-macro-language/bitmap-bresenhams-line-algorithm.vedit @@ -3,36 +3,36 @@ :DRAW_LINE: Num_Push(31,35) -#31 = abs(#3-#1) // x distance -#32 = abs(#4-#2) // y distance +#31 = abs(#3-#1) // x distance +#32 = abs(#4-#2) // y distance if (#4-#2 < -#31 || #3-#1 <= -#32) { - #99=#1; #1=#3; #3=#99 // swap start and end points + #99=#1; #1=#3; #3=#99 // swap start and end points #99=#2; #2=#4; #4=#99 } -if (#1 < #3) { #34=1 } else { #34=-1 } // x step -if (#2 < #4) { #35=1 } else { #35=-1 } // y step +if (#1 < #3) { #34=1 } else { #34=-1 } // x step +if (#2 < #4) { #35=1 } else { #35=-1 } // y step -if (#32 > #31) { // steep angle, step by Y - #33 = #32 / 2 // error distance +if (#32 > #31) { // steep angle, step by Y + #33 = #32 / 2 // error distance while (#2 <= #4) { - Call("DRAW_PIXEL") - #33 -= #31 - if (#33 < 0) { - #1 += #34 // move right - #33 += #32 - } - #2++ // move up + Call("DRAW_PIXEL") + #33 -= #31 + if (#33 < 0) { + #1 += #34 // move right + #33 += #32 + } + #2++ // move up } -} else { // not steep, step by X +} else { // not steep, step by X #33 = #31 / 2 while (#1 <= #3) { - Call("DRAW_PIXEL") - #33 -= #32 - if (#33 < 0) { - #2 += #35 // move up - #33 += #31 - } - #1++ // move right + Call("DRAW_PIXEL") + #33 -= #32 + if (#33 < 0) { + #2 += #35 // move up + #33 += #31 + } + #1++ // move right } } Num_Pop(31,35) diff --git a/Task/Bitmap-Flood-fill/Euler-Math-Toolbox/bitmap-flood-fill.euler b/Task/Bitmap-Flood-fill/Euler-Math-Toolbox/bitmap-flood-fill.euler new file mode 100644 index 0000000000..245718248d --- /dev/null +++ b/Task/Bitmap-Flood-fill/Euler-Math-Toolbox/bitmap-flood-fill.euler @@ -0,0 +1,36 @@ +>file="test.png"; +>A=loadrgb(file); ... +>insrgb(A); +>function floodfill (A0,i,j,color,dist) ... +$ A=A0; +$ R=getred(A); G=getgreen(A); B=getblue(A); +$ d=sqrt((R-R[i,j])^2+(G-G[i,j])^2+(B-B[i,j])^2); +$ n=rows(A); m=cols(A); +$ V=zeros(n,m); +$ S=zeros(n*m,2); sn=0; +$ A[i,j]=color; V[i,j]=1; +$ repeat; +$ if fill(A,i+1,j,n,m,d,dist,V,S,sn,color) then i=i+1; continue; +$ elseif fill(A,i,j+1,n,m,d,dist,V,S,sn,color) then j=j+1; continue; +$ elseif fill(A,i-1,j,n,m,d,dist,V,S,sn,color) then i=i-1; continue; +$ elseif fill(A,i,j-1,n,m,d,dist,V,S,sn,color) then j=j-1; continue; +$ endif; +$ sn=sn-1; if sn==0 then break; endif; +$ i=S[sn,1]; j=S[sn,2]; +$ end; +$ return A; +$endfunction +>function fill (A,i,j,n,m,d,dist,V,S,%sn,color) ... +$ if i<1 or i>n or j<1 or j>n then return 0; endif; +$ if V[i,j] || d[i,j]>dist then A[i,j]=color; return 0; endif; +$ V[i,j]=1; +$ A[i,j]=color; +$ %sn=%sn+1; +$ S[%sn]=[i,j]; +$ return 1; +$endfunction +>B=floodfill(A,10,240,rgb(0.5,0,0),0.5); +>B=floodfill(B,10,10,rgb(0.5,0,0),0.5); +>B=floodfill(B,150,60,rgb(0,0.5,0),0.5); +>B=floodfill(B,200,200,rgb(0,0,0.5),0.5); +>insrgb(B); diff --git a/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust b/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust new file mode 100644 index 0000000000..10a6e9950f --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust @@ -0,0 +1,70 @@ +use std::vec::from_elem; +use std::path::posix::{Path}; +use std::io::File; + +pub struct RGB { + r: u8 + ,g: u8 + ,b: u8 +} + +pub struct PPM { + height: uint + ,width: uint + ,data: ~[u8] +} + +impl PPM { + pub fn new(height: uint, width: uint) -> PPM { + let size = 3 * height * width; + let buffer = from_elem(size, 0u8); + PPM{height: height, width: width, data: buffer} + } + + fn buffer_size(&self) -> uint { + 3 * self.height * self.width + } + + fn get_offset(&self, x: uint, y: uint) -> Option { + let offset = (y * self.width * 3) + (x * 3); + if(offset < self.buffer_size()){ + Some(offset) + }else{ + None + } + } + + pub fn get_pixel(&self, x: uint, y: uint) -> Option { + match self.get_offset(x, y) { + Some(offset) => { + let r = self.data[offset]; + let g = self.data[offset + 1]; + let b = self.data[offset + 2]; + Some(RGB{r, g, b}) + }, + None => None + } + } + + pub fn set_pixel(&mut self, x: uint, y: uint, color: RGB) -> bool { + match self.get_offset(x, y) { + Some(offset) => { + self.data[offset] = color.r; + self.data[offset + 1] = color.g; + self.data[offset + 2] = color.b; + true + }, + None => false + } + } + + pub fn write_file(&self, filename: &str) -> bool { + let path = Path::new(filename); + let mut file = File::create(&path); + let header = format!("P6 {} {} 255\n", self.width, self.height); + file.write(header.as_bytes()); + file.write(self.data); + true + } + +} diff --git a/Task/Bitmap/ActionScript/bitmap.as b/Task/Bitmap/ActionScript/bitmap.as new file mode 100644 index 0000000000..26741f85ea --- /dev/null +++ b/Task/Bitmap/ActionScript/bitmap.as @@ -0,0 +1,22 @@ +// To import the BitmapData class: +import flash.display.BitmapData; + +// Creates a new BitmapData object with a width of 500 pixels and a height of 300 pixels. +var bitmap:BitmapData = new BitmapData(500, 300); + +// Create a BitmapData with transparency disallowed +var opaqueBitmap:BitmapData = new BitmapData(500, 300, false); + +// Bitmap with initial fill colour, as 0xAARRGGBB (default is white) +var redFilledBitmap:BitmapData = new BitmapData(400, 300, true, 0xFFFF0000); + +// Get the colour value of the pixel at point (200, 200) +bitmap.getPixel(200, 200) // As 0xRRGGBB +bitmap.getPixel32(200, 200) // As 0xAARRGGBB + +// Set the colour value of the pixel at point (300, 200) to blue +bitmap.setPixel(300, 200, 0x0000FF); // As 0xRRGGBB +bitmap.setPixel32(300, 200, 0xFF0000FF); // As 0xAARRGGBB + +// Fill the bitmap with a given colour (as 0xAARRGGBB) after construction +bitmap.fillRect(bitmap.rect, 0xFF44FF44); diff --git a/Task/Bitmap/D/bitmap.d b/Task/Bitmap/D/bitmap.d index 4f0fe2845c..9719ca01e3 100644 --- a/Task/Bitmap/D/bitmap.d +++ b/Task/Bitmap/D/bitmap.d @@ -8,8 +8,11 @@ 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_; @@ -51,6 +54,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)); } body { return image[x + y * nx_]; } @@ -58,13 +63,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)); } 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)); } body { return image[x + y * nx_] = color; } @@ -72,6 +81,8 @@ 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 ~ ";"); } @@ -122,23 +133,23 @@ struct RGB { Image!RGB loadPPM6(Image!RGB img, in string fileName) { if (img is null) - img = new Image!RGB(); + img = new Image!RGB; auto f = File(fileName, "rb"); - enforce(f.readln().strip() == "P6"); + enforce(f.readln.strip == "P6"); string line; do { line = f.readln(); } while (line.length && line[0] == '#'); // Skip comments. - const size = line.split(); + const size = line.split; enforce(size.length == 2); - img.allocate(size[0].to!uint(), size[1].to!uint()); + img.allocate(size[0].to!uint, size[1].to!uint); enforce(f.readln().strip() == "255"); auto l = new ubyte[img.nx * 3]; size_t i = 0; foreach (immutable y; 0 .. img.ny) { f.rawRead!ubyte(l); foreach (immutable x; 0 .. img.nx) - img.image[i++] = RGB(l[x*3], l[x*3 + 1], l[x*3 + 2]); + img.image[i++] = RGB(l[x * 3], l[x * 3 + 1], l[x * 3 + 2]); } return img; } @@ -163,6 +174,6 @@ version (bitmap_main) { void main() { auto img = new Image!RGB(30, 10); img[4, 5] = RGB.white; - img.textualShow(); + img.textualShow; } } diff --git a/Task/Bitwise-IO/Erlang/bitwise-io-1.erl b/Task/Bitwise-IO/Erlang/bitwise-io-1.erl new file mode 100644 index 0000000000..0f3cddfd35 --- /dev/null +++ b/Task/Bitwise-IO/Erlang/bitwise-io-1.erl @@ -0,0 +1,53 @@ +-module(bitwise_io). +-compile([export_all]). + +%% Erlang allows for easy manipulation of bitstrings. Here I'll +%% present a function that can take a message of 8-bit ASCII +%% characters and remove the MSB, leaving the same message in 7-bits. + +compress(Message) -> + << <> || <> <= Message >>. + +%% Here we decompress the message. + +decompress(Message) -> + << <> || <> <= Message >>. + +%% Now a test to demonstrate that this conversion works: + +test_bitstring_conversion() -> + Message = <<"Hello, Rosetta Code!">>, + io:format("~p: ~B~n",[Message, bit_size(Message)]), + Compressed = compress(Message), + io:format("~p: ~B~n",[Compressed, bit_size(Compressed)]), + Decompressed = decompress(Compressed), + io:format("~p: ~B~n",[Decompressed, bit_size(Decompressed)]), + io:format("~p = ~p ? ~p~n",[Message, Decompressed, + Message =:= Decompressed]). + +%% Now to show this on file output, we'll write the compressed version +%% to a file. Now, erlang's file:write_file expects objects that are +%% multiples of 8bits. We'll add padding to allow the writing to +%% complete, and then discard the padding when reading the file back +%% in. + +test_file_io() -> + Message = <<"Hello, Rosetta Code!">>, + FileName = "bitwise_io.dat", + Compressed = compress(Message), + PaddingSize = (8 - (bit_size(Compressed) rem 8)) rem 8, + PaddedCompressed = <>, + file:write_file(FileName,PaddedCompressed), + {ok, ReadIn} = file:read_file(FileName), + UnpaddedSize = bit_size(ReadIn) - 7, + Unpadded = + case UnpaddedSize rem 7 =:= 0 of + true -> + <> = ReadIn, + T; + false -> + << <> || <> <= ReadIn >> + end, + Decompressed = decompress(Unpadded), + io:format("~p~n",[Decompressed]). diff --git a/Task/Bitwise-IO/Erlang/bitwise-io-2.erl b/Task/Bitwise-IO/Erlang/bitwise-io-2.erl new file mode 100644 index 0000000000..eb0e927609 --- /dev/null +++ b/Task/Bitwise-IO/Erlang/bitwise-io-2.erl @@ -0,0 +1,8 @@ +184> bitwise_io:test_bitstring_conversion(). +<<"Hello, Rosetta Code!">>: 160 +<<145,151,102,205,235,16,82,223,207,47,78,152,80,67,223,147,42,1:4>>: 140 +<<"Hello, Rosetta Code!">>: 160 +<<"Hello, Rosetta Code!">> = <<"Hello, Rosetta Code!">> ? true +ok +185> bitwise_io:test_file_io(). +<<"Hello, Rosetta Code!">> diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index fb5b01ca12..d4c1db44d0 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -1,20 +1,20 @@ -#define std'dictionary'*. -#define std'basic'*. +#define system. +#define extensions. -#symbol BitwiseTest &former:anA &later:aB = +#symbol bitwiseTest = (:x:y) [ - 'program'output << anA << " and " << aB << " = " << anA and:aB << "%n". - 'program'output << anA << " or " << aB << " = " << anA or:aB << "%n". - 'program'output << anA << " xor " << aB << " = " << anA xor:aB << "%n". - 'program'output << "not " << anA << " = " << anA inverted << "%n". - 'program'output << anA << " shr " << aB << " = " << anA __shift'add:aB << "%n". - 'program'output << anA << " shl " << aB << " = " << anA __shift'subtract:aB << "%n". + console write:x write:" and " write:y write:" = " writeLine:(x and:y). + console write:x write:" or " write:y write:" = " writeLine:(x or:y). + console write:x write:" xor " write:y write:" = " writeLine:(x xor:y). + console write:"not " write:x write:" = " writeLine:(x not). + console write:x write:" shr " write:y write:" = " writeLine:(x shift:y). + console write:x write:" shl " write:y write:" = " writeLine:(x shift:(y negative)). ]. -#symbol Program = +#symbol program = [ - #var a := 'program'input >> Integer. - #var b := 'program'input >> Integer. + #var a := consoleEx readLine:(Integer new). + #var b := consoleEx readLine:(Integer new). - BitwiseTest &&former:a &later:b. + bitwiseTest:a:b. ]. diff --git a/Task/Bitwise-operations/Rust/bitwise-operations.rust b/Task/Bitwise-operations/Rust/bitwise-operations.rust new file mode 100644 index 0000000000..27aed31b08 --- /dev/null +++ b/Task/Bitwise-operations/Rust/bitwise-operations.rust @@ -0,0 +1,12 @@ +fn main() { + let a: u8 = 105; + let b: u8 = 91; + println!("a = {:0>8t}", a); + println!("b = {:0>8t}", b); + println!("a | b = {:0>8t}", a | b); + println!("a & b = {:0>8t}", a & b); + println!("a ^ b = {:0>8t}", a ^ b); + println!("!a = {:0>8t}", !a); + println!("a << 3 = {:0>8t}", a >> 3); + println!("a >> 3 = {:0>8t}", a << 3); +} diff --git a/Task/Bitwise-operations/Seed7/bitwise-operations.seed7 b/Task/Bitwise-operations/Seed7/bitwise-operations.seed7 new file mode 100644 index 0000000000..2c1c086d0b --- /dev/null +++ b/Task/Bitwise-operations/Seed7/bitwise-operations.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + include "bin32.s7i"; + +const proc: bitwise (in integer: a, in integer: b) is func + begin + writeln("a: " <& a radix 2 lpad0 32); + writeln("b: " <& b radix 2 lpad0 32); + writeln("integer operations:"); + writeln("a << b: " <& a << b radix 2 lpad0 32); # left shift + writeln("a >> b: " <& a >> b radix 2 lpad0 32); # arithmetic right shift + end func; + +const proc: bitwise (in bin32: a, in bin32: b) is func + begin + writeln("bin32 operations:"); + writeln("a and b: " <& a & b radix 2 lpad0 32); + writeln("a or b: " <& a | b radix 2 lpad0 32); + writeln("a xor b: " <& a >< b radix 2 lpad0 32); + writeln("not a: " <& ~a radix 2 lpad0 32); + writeln("a << b: " <& a << ord(b) radix 2 lpad0 32); # left shift + writeln("a >> b: " <& a >> ord(b) radix 2 lpad0 32); # logical right shift + writeln("a rotL b: " <& rotLeft(a, ord(b)) radix 2 lpad0 32); # Rotate Left + writeln("a rolR b: " <& rotRight(a, ord(b)) radix 2 lpad0 32); # Rotate Right + end func; + +const proc: main is func + begin + bitwise(65076, 6); + bitwise(bin32(65076), bin32(6)); + end func; diff --git a/Task/Boolean-values/Julia/boolean-values-1.julia b/Task/Boolean-values/Julia/boolean-values-1.julia index 0777fd1564..00f280d6cf 100644 --- a/Task/Boolean-values/Julia/boolean-values-1.julia +++ b/Task/Boolean-values/Julia/boolean-values-1.julia @@ -1,8 +1,3 @@ -julia> t = true -true - -julia> typeof(t) -Bool julia> if 1 println("true") end diff --git a/Task/Boolean-values/Julia/boolean-values-2.julia b/Task/Boolean-values/Julia/boolean-values-2.julia index 43d20dbd5a..8f6a411172 100644 --- a/Task/Boolean-values/Julia/boolean-values-2.julia +++ b/Task/Boolean-values/Julia/boolean-values-2.julia @@ -1,9 +1,3 @@ -julia> bool -# methods for generic function bool -bool(x::Bool) at bool.jl:9 -bool(x::Number) at bool.jl:10 -bool(x::AbstractArray{Bool,N}) at abstractarray.jl:219 -bool(x::AbstractArray{T,N}) at abstractarray.jl:220 julia> bool(-2:2) 5-element Bool Array: true diff --git a/Task/Box-the-compass/D/box-the-compass.d b/Task/Box-the-compass/D/box-the-compass.d index 141b2cc2e4..6d45981562 100644 --- a/Task/Box-the-compass/D/box-the-compass.d +++ b/Task/Box-the-compass/D/box-the-compass.d @@ -3,7 +3,7 @@ import std.stdio, std.string, std.math, std.array; struct boxTheCompass { immutable static string[32] points; - /*pure nothrow*/ static this() { + pure nothrow static this() { immutable cardinal = ["north", "east", "south", "west"]; immutable desc = ["1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1"]; @@ -15,13 +15,13 @@ struct boxTheCompass { (s1 ~ s2) : (s2 ~ s1); foreach (immutable j; 0 .. 8) points[i * 8 + j] = desc[j].replace("1", s1). - replace("2", s2).replace("C",sc); + replace("2", s2).replace("C", sc); } } - static string opCall(in double degrees) /*pure nothrow*/ { + static string opCall(in double degrees) pure /*nothrow*/ { immutable testD = (degrees / 11.25) + 0.5; - return capitalize(points[cast(int)floor(testD % 32)]); + return points[cast(int)floor(testD % 32)].capitalize; } } diff --git a/Task/Bulls-and-cows-Player/D/bulls-and-cows-player.d b/Task/Bulls-and-cows-Player/D/bulls-and-cows-player.d index 5fcd81b5d0..24aa2809d1 100644 --- a/Task/Bulls-and-cows-Player/D/bulls-and-cows-player.d +++ b/Task/Bulls-and-cows-Player/D/bulls-and-cows-player.d @@ -1,28 +1,20 @@ -import std.stdio, std.random, std.algorithm, std.range, std.ascii; - -auto scoreCalc(in dchar[] guess, in dchar[] chosen) { - immutable bulls = guess.zip(chosen).count!q{ a[0] == a[1] }; - immutable cows = count!(p => p[0] != p[1] && chosen.canFind(p[0])) - (zip(guess, chosen)); - return [bulls, cows]; -} - void main() { + import std.stdio, std.random, std.algorithm, std.range, std.ascii; + auto d9 = "123456789"d.dup; - auto choices = cartesianProduct(d9, d9, d9, d9) - .map!(t => [t[]]) - .filter!(a => a.sort().uniq.walkLength == 4) - .array; - choices.randomShuffle; + auto choices = cartesianProduct(d9, d9, d9, d9).map!(t => [t[]]) + .filter!(a => a.sort().uniq.count == 4).array; do { - const ans = choices[0]; + const ans = choices[uniform(0, $)]; writef("My guess is %s. How many bulls and cows? ", ans); - const score = readln.filter!isDigit.map!q{ a-'0' }.array; - choices = choices.filter!(c => scoreCalc(c, ans) == score).array; - if (choices.empty) - return writeln("Nothing fits the scores you gave."); + immutable score = readln.filter!isDigit.map!q{ a - '0' }.array; + choices = choices.remove!(c => score != + [c.zip(ans).count!(p => p[0] == p[1]), + c.zip(ans).count!(p => p[0] != p[1] && ans.canFind(p[0]))]); } while (choices.length > 1); + if (choices.empty) + return "Nothing fits the scores you gave.".writeln; writeln("Solution found: ", choices[0]); } diff --git a/Task/Bulls-and-cows-Player/Scala/bulls-and-cows-player.scala b/Task/Bulls-and-cows-Player/Scala/bulls-and-cows-player.scala new file mode 100644 index 0000000000..5e97445437 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Scala/bulls-and-cows-player.scala @@ -0,0 +1,34 @@ + def allCombinations: Seq[List[Byte]] = { + (0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations) + } + + def nextGuess(possible: Seq[List[Byte]]): List[Byte] = possible match { + case Nil => throw new IllegalStateException + case List(only) => only + case _ => possible(Random.nextInt(possible.size)) + } + + def doGuess(guess: List[Byte]): Pair[Int, Int] = { + println("My guess is " + guess); + val arr = readLine().split(' ').map(Integer.valueOf(_)) + (arr(0), arr(1)) + } + + def testGuess(alt: List[Byte], guess: List[Byte]): Pair[Int, Int] = { + val bulls =alt.zip(guess).filter(p => p._1 == p._2).size + val cows = guess.filter(alt.contains(_)).size - bulls + (bulls, cows) + } + + def play(possible: Seq[List[Byte]]): List[Byte] = { + val curGuess = nextGuess(possible) + val bc = doGuess(curGuess) + if (bc._1 == 4) { println("Ye-haw!"); curGuess } + else + play(possible.filter(p => testGuess(p, curGuess) == bc)) + + } + + def main(args: Array[String]) { + play(allCombinations) + } diff --git a/Task/Bulls-and-cows/BASIC/bulls-and-cows.basic b/Task/Bulls-and-cows/BASIC/bulls-and-cows-1.basic similarity index 100% rename from Task/Bulls-and-cows/BASIC/bulls-and-cows.basic rename to Task/Bulls-and-cows/BASIC/bulls-and-cows-1.basic diff --git a/Task/Bulls-and-cows/BASIC/bulls-and-cows-2.basic b/Task/Bulls-and-cows/BASIC/bulls-and-cows-2.basic new file mode 100644 index 0000000000..b4c598e65e --- /dev/null +++ b/Task/Bulls-and-cows/BASIC/bulls-and-cows-2.basic @@ -0,0 +1,28 @@ +100 D$ = "123456789" +110 FOR I = 1 TO 4 +120 P = INT(RND(1) * LEN(D$)) + 1 +130 N$ = N$ + MID$(D$, P, 1) +140 D$ = MID$(D$, 1, P - 1) + MID$(D$, P + 1, 8) +150 NEXT +160 PRINT "A RANDOM NUMBER HAS BEEN CREATED. +170 PRINT "THE NUMBER HAS FOUR DIGITS FROM 1 TO 9, WITHOUT DUPLICATION." +200 FOR Q = 0 TO 1 STEP 0 +210 INPUT "GUESS THE NUMBER: "; G% +220 G$ = STR$(G%) +230 M = LEN(G$) <> 4 OR G% = 0 +240 IF NOT M THEN FOR I = 2 TO 4 : M = MID$(G$, I, 1) = "0" : IF NOT M THEN NEXT I +250 IF NOT M THEN FOR I = 1 TO 3 : FOR J = I + 1 TO 4 : M = MID$(G$, I, 1) = MID$(G$, J, 1) : IF NOT M THEN NEXT J, I +260 IF M THEN PRINT "THE GUESS IS MALFORMED." : NEXT Q +270 B = 0 +280 C = 0 +300 FOR I = 1 TO 4 +310 C$ = MID$(N$, I, 1) +320 BULL = MID$(G$, I, 1) = C$ +330 COW = 0 +340 IF NOT BULL THEN FOR J = 1 TO 4 : COW = MID$(G$, J, 1) = C$ : IF NOT COW THEN NEXT J +350 B = B + BULL +360 C = C + COW +370 NEXT I +380 PRINT B " BULLS, " C " COWS" +390 Q = G$ = N$ +400 NEXT Q diff --git a/Task/Bulls-and-cows/D/bulls-and-cows.d b/Task/Bulls-and-cows/D/bulls-and-cows.d index 76b9e55cfe..4aa2a16058 100644 --- a/Task/Bulls-and-cows/D/bulls-and-cows.d +++ b/Task/Bulls-and-cows/D/bulls-and-cows.d @@ -1,36 +1,19 @@ -import std.stdio, std.random, std.string, std.algorithm, - std.range, std.conv; - void main() { - enum size = 4; - immutable ddigits = "123456789"d; - //immutable chosen = ddigits.randomCover.take(size).array; - const chosen = ddigits.randomCover(rndGen).take(size).array; - writeln("Guess a number composed of ", size, - " unique digits from 1 to 9 in random order."); + import std.stdio, std.random, std.string, std.algorithm, + std.range, std.conv, std.ascii; - uint nGuesses; - while (true) { - nGuesses++; - dstring guess; + immutable hidden = "123456789"d.randomCover.take(4).array; while (true) { - writef("\nNext guess (%d): ", nGuesses); - guess = readln.strip.dtext; - if (guess.countchars(ddigits) == size && - guess.dup.sort().uniq.walkLength == size) - break; - writefln("I need %d unique digits from 1 to 9, no spaces", size); + "Next guess: ".write; + immutable d = readln.strip.dtext; + if (d.count == 4 && d.all!isDigit && + d.dup.sort().uniq.count == 4) { + immutable bulls = d.zip(hidden).count!(p => p[0] == p[1]); + if (bulls == 4) + return " You guessed it!".writeln; + immutable cows = d.count!(g => hidden.canFind(g)) - bulls; + writefln("bulls %d, cows %d", bulls, cows); + } + " Bad guess! (4 unique digits, 1-9)".writeln; } - - if (guess == chosen) { - writefln("\nYou guessed correctly in %d attempts.", nGuesses); - break; - } - - immutable bulls = zip(guess, chosen).count!q{ a[0] == a[1] }; - immutable cows = iota(size) - .count!(i => guess[i] != chosen[i] && - chosen.canFind(guess[i])); - writefln(" %d Bulls\n %d Cows", bulls, cows); - } } diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index dd78b21f4f..92f8ca6b0d 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -1,85 +1,77 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'collections'*. -#define std'patterns'*. -#define ext'utils'*. -#define std'routines'arrays'*. - -#class EDigitProp -{ - #method get - [ - ^ self numeric - 30h. - ] -} -#symbol Digits : aLiteral - = Summing &&var:List &prop:EDigitProp start:Scan::aLiteral. +#define system. +#define system'routines. +#define extensions. #class GameMaster { #field theNumbers. - #initializer + #constructor new [ // generate secret number - #var aRandomNumbers := Randomized &&base:(1,2,3,4,5,6,7,8,9) &count:9. + #var aRandomNumbers := randomControl randomize:9 &array:(1,2,3,4,5,6,7,8,9). - theNumbers := aRandomNumbers~earrayop read &from:0 &to:3 &:esubarray. + theNumbers := arrayControl Subarray:aRandomNumbers &from:0 &length:4. + ] + + #method ask + [ + #var aRow := consoleEx write:"Your Guess ?" readLine. + + ^ literalControl toArray:aRow. ] #method proceed : aGuess [ - #if (aGuess count != 4)? - [ - 'program'output << "Not a valid guess.%n". + #var aCows := Integer new:0. + #var aBulls := Integer new:0. - ^ $self. - ]. + (aGuess length != 4) + ? [ aBulls << -1. ] + ! [ + control from:0 &to:3 &do: i + [ + #var ch := aGuess@i. + #var aNumber := convertor toInt:(ch literal). - #var aCows := Integer::0. - #var aBulls := Integer::0. + // check range + (aNumber > 0)and:(aNumber < 10) + ! [ #throw InvalidArgumentException new. ]. - #if It::aGuess run: aNumber = - [ - // check range - Control if:(aNumber > 0) if:(aNumber < 10). + // check duplicates + #var duplicate := arrayControl seek:aGuess &until: x [ (x == ch)and:[ x equal &object:ch not ] ]. + nil != duplicate ? + [ + #throw InvalidArgumentException new. + ]. - // check duplicates - #if (aNumber indexer'clone index'append:1)~EIt find:aNumber - [ - control fail. + (aNumber == (theNumbers@i)) + ? [ aBulls += 1. ] + ! [ + arrayControl ifExist:aNumber &in:theNumbers + ? [ aCows += 1. ]. + ]. + ] + | ifFailed: + [ + aBulls << -1. + ]. ]. - #if Control if:(aNumber == theNumbers@aNumber index) - [ - aBulls += 1. - ] - | if:(Scan::theNumbers == aNumber) - [ - aCows += 1. - ]. - ] - | [ - 'program'output << "Not a valid guess.%n". + ^ aBulls => + -1 ? [ consoleEx writeLine:"Not a valid guess.". ^ true. ] + 4 ? [ consoleEx writeLine:"Congratulations! You have won!". ^ false. ] + ! [ + consoleEx writeLine:"Your Score is " : aBulls : " bulls and " : aCows : " cows". - ^ $self. - ]. - - #if (aBulls == 4)? - [ - 'program'output << "%nCongratulations! You have won!". - - $self fail. - ] - | [ - 'program'output << "%nYour Score is " << aBulls << " bulls and " << aCows << " cows%n". - ]. + ^ true. + ]. ] } -#symbol Program = +#symbol program = [ - #var aGameMaster := GameMaster. + #var aGameMaster := GameMaster new. - #while aGameMaster proceed:Digits::(ext'io'console << "Your Guess ?" >> String). + control while:[ aGameMaster proceed:(aGameMaster ask). ]. ]. diff --git a/Task/Bulls-and-cows/Pascal/bulls-and-cows.pascal b/Task/Bulls-and-cows/Pascal/bulls-and-cows.pascal new file mode 100644 index 0000000000..9043c91b1e --- /dev/null +++ b/Task/Bulls-and-cows/Pascal/bulls-and-cows.pascal @@ -0,0 +1,188 @@ +Program BullCow; + +{$mode objFPC} + +uses Math, SysUtils; + +type + TFourDigit = array[1..4] of integer; + +Procedure WriteFourDigit(fd: TFourDigit); +{ Write out a TFourDigit with no line break following. } +var + i: integer; +begin + for i := 1 to 4 do + begin + Write(fd[i]); + end; +end; + +Function WellFormed(Tentative: TFourDigit): Boolean; +{ Does the TFourDigit avoid repeating digits? } +var + current, check: integer; +begin + + Result := True; + + for current := 1 to 4 do + begin + for check := current + 1 to 4 do + begin + if Tentative[check] = Tentative[current] then + begin + Result := False; + end; + end; + end; + +end; + +Function MakeNumber(): TFourDigit; +{ Make a random TFourDigit, keeping trying until it is well-formed. } +var + i: integer; +begin + for i := 1 to 4 do + begin + Result[i] := RandomRange(1, 9); + end; + if not WellFormed(Result) then + begin + Result := MakeNumber(); + end; +end; + +Function StrToFourDigit(s: string): TFourDigit; +{ Convert an (input) string to a TFourDigit. } +var + i: integer; +begin + for i := 1 to Length(s) do + begin + StrToFourDigit[i] := StrToInt(s[i]); + end; +end; + +Function Wins(Num, Guess: TFourDigit): Boolean; +{ Does the guess win? } +var + i: integer; +begin + Result := True; + for i := 1 to 4 do + begin + if Num[i] <> Guess[i] then + begin + Result := False; + Exit; + end; + end; +end; + +Function GuessScore(Num, Guess: TFourDigit): string; +{ Represent the score of the current guess as a string. } +var + i, j, bulls, cows: integer; +begin + + bulls := 0; + cows := 0; + + { Count the cows and bulls. } + for i := 1 to 4 do + begin + for j := 1 to 4 do + begin + if (Num[i] = Guess[j]) then + begin + { If the indices are the same, that would be a bull. } + if (i = j) then + begin + bulls := bulls + 1; + end + else + begin + cows := cows + 1; + end; + end; + end; + end; + + { Format the result as a sentence. } + Result := IntToStr(bulls) + ' bulls, ' + IntToStr(cows) + ' cows.'; + +end; + +Function GetGuess(): TFourDigit; +{ Get a well-formed user-supplied TFourDigit guess. } +var + input: string; +begin + + WriteLn('Enter a guess:'); + ReadLn(input); + + { Must be 4 digits. } + if Length(input) = 4 then + begin + + Result := StrToFourDigit(input); + + if not WellFormed(Result) then + begin + WriteLn('Four unique digits, please.'); + Result := GetGuess(); + end; + + end + else + begin + WriteLn('Please guess a four-digit number.'); + Result := GetGuess(); + end; + +end; + +var + Num, Guess: TFourDigit; + Turns: integer; +begin + + { Initialize the randymnity. } + Randomize(); + + { Make the secred number. } + Num := MakeNumber(); + + WriteLn('I have a secret number. Guess it!'); + + Turns := 0; + + { Guess until the user gets it. } + While True do + begin + + Guess := GetGuess(); + + { Count each guess as a turn. } + Turns := Turns + 1; + + { If the user won, tell them and ditch. } + if Wins(Num, Guess) then + begin + WriteLn('You won in ' + IntToStr(Turns) + ' tries.'); + Write('The number was '); + WriteFourDigit(Num); + WriteLn('!'); + Exit; + end + else { Otherwise, score it and get a new guess. } + begin + WriteLn(GuessScore(Num, Guess)); + end; + + end; + +end. diff --git a/Task/CRC-32/FBSL/crc-32.fbsl b/Task/CRC-32/FBSL/crc-32.fbsl new file mode 100644 index 0000000000..f46c8eeb8b --- /dev/null +++ b/Task/CRC-32/FBSL/crc-32.fbsl @@ -0,0 +1,5 @@ +#APPTYPE CONSOLE + +PRINT HEX(CHECKSUM("The quick brown fox jumps over the lazy dog")) + +PAUSE diff --git a/Task/CRC-32/Groovy/crc-32-1.groovy b/Task/CRC-32/Groovy/crc-32-1.groovy new file mode 100644 index 0000000000..865d791955 --- /dev/null +++ b/Task/CRC-32/Groovy/crc-32-1.groovy @@ -0,0 +1,3 @@ +def crc32(byte[] bytes) { + new java.util.zip.CRC32().with { update bytes; value } +} diff --git a/Task/CRC-32/Groovy/crc-32-2.groovy b/Task/CRC-32/Groovy/crc-32-2.groovy new file mode 100644 index 0000000000..582dbbe6af --- /dev/null +++ b/Task/CRC-32/Groovy/crc-32-2.groovy @@ -0,0 +1 @@ +assert '414FA339' == sprintf('%04X', crc32('The quick brown fox jumps over the lazy dog'.bytes)) diff --git a/Task/CRC-32/REXX/crc-32.rexx b/Task/CRC-32/REXX/crc-32.rexx index e607ecb27c..f0ef5c2417 100644 --- a/Task/CRC-32/REXX/crc-32.rexx +++ b/Task/CRC-32/REXX/crc-32.rexx @@ -16,7 +16,7 @@ return /*──────────────────────────────────CRC_32 subroutine───────────────────*/ CRC_32: procedure; parse arg !,$ /*2nd arg is for multi-invokes. */ - do i=0 to 255; z=d2c(i) /*build the 8-bit indexed table.*/ + do i=0 for 256; z=d2c(i) /*build the 8-bit indexed table.*/ r=right(z,4,'0'x) /*insure the R is 32 bits. */ do j=0 for 8 /*handle each bit of rightmost 8.*/ rb=x2b(c2x(r)) /*convert char ──► hex ──► binary*/ diff --git a/Task/CRC-32/Seed7/crc-32.seed7 b/Task/CRC-32/Seed7/crc-32.seed7 new file mode 100644 index 0000000000..cb414ef76f --- /dev/null +++ b/Task/CRC-32/Seed7/crc-32.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "crc32.s7i"; + +const proc: main is func + begin + writeln(ord(crc32("The quick brown fox jumps over the lazy dog")) radix 16 lpad0 8); + end func; diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher.cobol b/Task/Caesar-cipher/COBOL/caesar-cipher.cobol new file mode 100644 index 0000000000..e287e5b7aa --- /dev/null +++ b/Task/Caesar-cipher/COBOL/caesar-cipher.cobol @@ -0,0 +1,86 @@ + >>SOURCE FORMAT IS FREE +PROGRAM-ID. caesar-cipher. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION encrypt + FUNCTION decrypt + . +DATA DIVISION. +WORKING-STORAGE SECTION. +01 plaintext PIC X(50). +01 offset PIC 99. + +01 encrypted-str PIC X(50). + +PROCEDURE DIVISION. + DISPLAY "Enter a message to encrypt: " NO ADVANCING + ACCEPT plaintext + DISPLAY "Enter the amount to shift by: " NO ADVANCING + ACCEPT offset + + MOVE FUNCTION encrypt(offset, plaintext) TO encrypted-str + DISPLAY "Encrypted: " encrypted-str + DISPLAY "Decrypted: " FUNCTION decrypt(offset, encrypted-str) + . +END PROGRAM caesar-cipher. + + +FUNCTION-ID. encrypt. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 i PIC 9(3). + +01 a PIC 9(3). + +LINKAGE SECTION. +01 offset PIC 99. +01 str PIC X(50). + +01 encrypted-str PIC X(50). + +PROCEDURE DIVISION USING offset, str RETURNING encrypted-str. + MOVE str TO encrypted-str + PERFORM VARYING i FROM 1 BY 1 UNTIL i > FUNCTION LENGTH(str) + IF encrypted-str (i:1) IS NOT ALPHABETIC OR encrypted-str (i:1) = SPACE + EXIT PERFORM CYCLE + END-IF + + IF encrypted-str (i:1) IS ALPHABETIC-UPPER + MOVE FUNCTION ORD("A") TO a + ELSE + MOVE FUNCTION ORD("a") TO a + END-IF + + MOVE FUNCTION CHAR(FUNCTION MOD(FUNCTION ORD(encrypted-str (i:1)) + - a + offset, 26) + a) + TO encrypted-str (i:1) + END-PERFORM + . +END FUNCTION encrypt. + + +FUNCTION-ID. decrypt. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION encrypt + . +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 decrypt-offset PIC 99. + +LINKAGE SECTION. +01 offset PIC 99. +01 str PIC X(50). + +01 decrypted-str PIC X(50). + +PROCEDURE DIVISION USING offset, str RETURNING decrypted-str. + SUBTRACT 26 FROM offset GIVING decrypt-offset + MOVE FUNCTION encrypt(decrypt-offset, str) TO decrypted-str + . +END FUNCTION decrypt. diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index 4d5ebbe974..6610015857 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -1,59 +1,74 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'patterns'*. -#define std'routines'strings'*. +#define system. +#define system'routines. +#define extensions. +#define extensions'math. -#define math'* = std'math'*. - -// --- subjects --- -#subject cipher_key. +// --- Constants --- #symbol Letters = "abcdefghijklmnopqrstuvwxyz". #symbol BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". #symbol TestText = "Pack my box with five dozen liquor jugs.". #symbol Key = 12. -#symbol EEncrypt : aKey = +// --- Encrypt / Decript --- + +#class Encrypting { - eval : aChar + #field theKey. + #field theExtendee. + + #constructor new : aKey &extending:anObject [ - #var anIndex := Letters~eliteralop first_occ'find:aChar. - #if (-1) ifless:anIndex - [ - $next eval:(Letters @ (aKey + anIndex)~math'eops math'modulus:26). - ] - | [ - anIndex := BigLetters~eliteralop first_occ'find:aChar. - #if (-1) ifless:anIndex - [ - $next eval:(BigLetters @ (aKey + anIndex)~math'eops math'modulus:26). - ] - | [ - $next eval:aChar. - ]. - ]. + theKey := aKey. + theExtendee := anObject. ] -}. -#symbol Encrypted &literal:aLiteral &cipher_key:aKey - = __group(EEncrypt::aKey, Summing::String) start:Scan::aLiteral. + #method eval : aChar + [ + #var anIndex := Letters indexOf &index:0 &char:aChar. -#symbol Decrypted &literal:aLiteral &cipher_key:aKey - = __group(EEncrypt::(26 - aKey), Summing::String) start:Scan::aLiteral. + (-1 < anIndex) + ? [ + theExtendee eval:(Letters @ (modulus:(theKey+anIndex):26)) + ] + ! [ + anIndex := BigLetters indexOf &index:0 &char:aChar. + (-1 < anIndex) + ? [ + theExtendee eval:(BigLetters @ (modulus:(theKey+anIndex):26)) + ] + ! [ + theExtendee eval:aChar. + ]. + ]. + ] -#symbol Program = + #method => theExtendee. +} + +// --- Functions --- + +#symbol encrypt = (:aText:aKey) + [ Encrypting new:aKey &extending:(Summing new:(String new)) foreach:aText literal ]. + +#symbol decrypt = (:aText:aKey) + [ Encrypting new:(26 - aKey) &extending:(Summing new:(String new)) foreach:aText literal ]. + +// --- Program --- + +#symbol program = [ #var anS := TestText. - 'program'output << "Original text :" << anS << "%n". + consoleEx writeLine:"Original text :" :anS. - anS := Encrypted &&literal:anS &cipher_key:Key. + anS := encrypt:anS:Key. - 'program'output << "Encrypted text:" << anS << "%n". + consoleEx writeLine:"Encrypted text:" :anS. - anS := Decrypted &&literal:anS &cipher_key:Key. + anS := decrypt:anS:Key. - 'program'output << "Decrypted text:" << anS << "%n". + consoleEx writeLine:"Decrypted text:" :anS. - 'program'input get. + consoleEx readChar. ]. diff --git a/Task/Caesar-cipher/Julia/caesar-cipher.julia b/Task/Caesar-cipher/Julia/caesar-cipher.julia new file mode 100644 index 0000000000..c431d87362 --- /dev/null +++ b/Task/Caesar-cipher/Julia/caesar-cipher.julia @@ -0,0 +1,18 @@ +function rot(s::String, key::Integer) + map(s) do c + if 'a' <= c <= 'z' + char( mod(c - 'a' + key, 26) + 'a') + elseif 'A' <= c <= 'Z' + char( mod(c - 'A' + key, 26) + 'A') + else + c + end + end +end + +key = 3 +txt = "The five boxing wizards jump quickly" + +println("Original: ", txt); +println("Encrypted: ", rot(txt, key)) +println("Decrypted: ", rot(rot(txt, key), 26 - key)) diff --git a/Task/Calendar---for-real-programmers/D/calendar---for-real-programmers.d b/Task/Calendar---for-real-programmers/D/calendar---for-real-programmers.d new file mode 100644 index 0000000000..811d815d86 --- /dev/null +++ b/Task/Calendar---for-real-programmers/D/calendar---for-real-programmers.d @@ -0,0 +1 @@ +import std.string;mixin(import("CALENDAR").toLower);void main(){} diff --git a/Task/Calendar---for-real-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-real-programmers/Elena/calendar---for-real-programmers.elena new file mode 100644 index 0000000000..643f5620c1 --- /dev/null +++ b/Task/Calendar---for-real-programmers/Elena/calendar---for-real-programmers.elena @@ -0,0 +1,132 @@ +#define system. +#define system'text. +#define system'routines. +#define system'calendar. +#define extensions. +#define extensions'math. +#define extensions'routines. + +#symbol MonthNames = ("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"). +#symbol DayNames = ("MO", "TU", "WE", "TH", "FR", "SA", "SU"). + +#class CalendarMonthPrinter +{ + #field theDate. + #field theLine. + #field theMonth. + #field theYear. + #field theRow. + + #constructor new &Year:aYear &Month:aMonth + [ + theMonth := aMonth. + theYear := aYear. + theLine := TextBuffer new. + theRow := Integer new. + ] + + #method firstLine : aDay + [ + theRow << 0. + theDate := Date new &Year:theYear &Month:theMonth &Day:aDay. + control foreach:DayNames &do: aName + [ theLine write:" " write:aName ]. + ] + + #method nextLine + [ + theLine clear. + + (theDate Month == theMonth) + ? [ + theLine~textOp write:" " &length:(((theDate DayOfWeek) => 0 ? [ 7 ] ! [ theDate DayOfWeek ]) - 1). + + control do: + [ + theLine~textOp write:(theDate Day) &paddingLeft:3 &with:" ". + + theDate := theDate add &Days:1. + ] + &until:[(theDate Month != theMonth)or:[theDate DayOfWeek == 1]]. + ]. + + #var aLength := theLine length. + (aLength < 21) + ? [ theLine~textOp write:" " &length:(21 - aLength). ]. + + theRow += 1. + + ^ theRow < 7. + ] + + #method enumerator = + { + set &index:anIndex [ self firstLine:(anIndex + 1) ] + + next [ ^ self nextLine. ] + + get = self. + }. + + #method printTitleTo : anOutput + [ + anOutput~textOp write:(MonthNames @(theMonth - 1)) &padding:21 &with:" ". + ] + + #method printTo : anOutput + [ + anOutput write:(theLine literal). + ] +} + +#class Calendar +{ + #field theYear. + #field theRowLength. + + #constructor new : aYear + [ + theYear := aYear int. + theRowLength := 3. + ] + + #method printTo:anOutput + [ + anOutput~textOp write:"[SNOOPY]" &padding:(theRowLength * 25) &with:" " writeLine. + anOutput~textOp write:theYear &padding:(theRowLength * 25) &with:" " writeLine writeLine. + + #var aRowCount := 12 / theRowLength. + #var Months := matrixControl new &m:aRowCount &n:theRowLength &each: (:i:j) [ CalendarMonthPrinter new &Year:theYear &Month:(i * theRowLength + j + 1) ]. + + control foreach:Months &do: aRow + [ + control foreach:aRow &do: aMonth + [ + aMonth printTitleTo:anOutput. + + anOutput write:" ". + ]. + + anOutput writeLine. + + controlEx for:(ParallelEnumerator new:aRow) &do: aLine + [ + control foreach:aLine &do: aPrinter + [ + aPrinter printTo:anOutput. + + anOutput write:" ". + ]. + + anOutput writeLine. + ]. + ]. + ] +} + +#symbol program = +[ + #var aCalender := Calendar new:1969. + + aCalender printTo:console. +]. diff --git a/Task/Calendar---for-real-programmers/PL-I/calendar---for-real-programmers.pli b/Task/Calendar---for-real-programmers/PL-I/calendar---for-real-programmers.pli new file mode 100644 index 0000000000..9e05d89236 --- /dev/null +++ b/Task/Calendar---for-real-programmers/PL-I/calendar---for-real-programmers.pli @@ -0,0 +1,52 @@ +(SUBRG, SIZE, FOFL): +CALENDAR: PROCEDURE (YEAR) OPTIONS (MAIN); + DECLARE YEAR CHARACTER (4) VARYING; + DECLARE (A, B, C) (0:5,0:6) CHARACTER (3); + DECLARE NAME_MONTH(12) STATIC CHARACTER (9) VARYING INITIAL ( + 'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', + 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'); + DECLARE I FIXED; + DECLARE (MM, MMP1, MMP2) PIC '99'; + + PUT EDIT (CENTER('CALENDAR FOR ' || YEAR, 67)) (A); + PUT SKIP (2); + + DO MM = 1 TO 12 BY 3; + MMP1 = MM + 1; MMP2 = MM + 2; + CALL PREPARE_MONTH('01' || MM || YEAR, A); + CALL PREPARE_MONTH('01' || MMP1 || YEAR, B); + CALL PREPARE_MONTH('01' || MMP2 || YEAR, C); + + PUT SKIP EDIT (CENTER(NAME_MONTH(MM), 23), + CENTER(NAME_MONTH(MMP1), 23), + CENTER(NAME_MONTH(MMP2), 23) ) (A); + PUT SKIP EDIT ((3)' M T W T F S S ') (A); + DO I = 0 TO 5; + PUT SKIP EDIT (A(I,*), B(I,*), C(I,*)) (7 A, X(2)); + END; + END; + +PREPARE_MONTH: PROCEDURE (START, MONTH); + DECLARE MONTH(0:5,0:6) CHARACTER (3); + DECLARE START CHARACTER (8); + DECLARE I PIC 'ZZ9'; + DECLARE OFFSET FIXED; + DECLARE (J, DAY) FIXED BINARY (31); + DECLARE (THIS_MONTH, NEXT_MONTH, K) FIXED BINARY; + + DAY = DAYS(START, 'DDMMYYYY'); + OFFSET = WEEKDAY(DAY) - 1; + IF OFFSET = 0 THEN OFFSET = 7; + MONTH = ''; + DO J = DAY BY 1; + THIS_MONTH = SUBSTR(DAYSTODATE(J, 'DDMMYYYY'), 3, 2); + NEXT_MONTH = SUBSTR(DAYSTODATE(J+1, 'DDMMYYYY'), 3, 2); + IF THIS_MONTH^= NEXT_MONTH THEN LEAVE; + END; + I = 1; + DO K = OFFSET-1 TO OFFSET+J-DAY-1; + MONTH(K/7, MOD(K,7)) = I; I = I + 1; + END; +END PREPARE_MONTH; + +END CALENDAR; diff --git a/Task/Calendar/AutoIt/calendar.autoit b/Task/Calendar/AutoIt/calendar.autoit new file mode 100644 index 0000000000..9cfc37d67f --- /dev/null +++ b/Task/Calendar/AutoIt/calendar.autoit @@ -0,0 +1,102 @@ +#include + +; Set the count of characters in each line, minimum is 20 - one month. +Global $iPrintSize = 132 + +; Set the count of months, you want to print side by side. With "0" it calculates automatically. +; The number will corrected, if it not allowed to print in an rectangle. +; If your print size is to small for given count, it will set back to automatically calculation. +Global $iSideBySide = 3 + +; Set the count of spaces between months. +Global $iSpace = 4 + +_CreateCalendar( 1969 ) + + +Func _CreateCalendar($_iYear) + Local $aMon[12] = [' January ', ' February ', ' March ', _ + ' April ', ' May ', ' June ', _ + ' July ', ' August ', ' September ', _ + ' October ', ' November ', ' December '] + Local $sHead = 'Mo Tu We Th Fr Sa Su' + Local $aDaysInMonth[12] = [31,28,31,30,31,30,31,31,30,31,30,31] + If _DateIsLeapYear($_iYear) Then $aDaysInMonth[1] = 29 + + ; == assign date in weekday table for the whole year + Local $aAllDaysInMonth[6][7][12] ; [ lines ][ weekdays ][ months ] + Local $iDay = 1, $iShift + For $i = 1 To 12 + $iShift = _DateToDayOfWeekISO($_iYear, $i, 1) -1 + For $j = 0 To 5 + For $k = $iShift To 6 + $aAllDaysInMonth[$j][$k][$i-1] = $iDay + $iDay += 1 + If $iDay > $aDaysInMonth[$i-1] Then ExitLoop(2) + Next + $iShift = 0 + Next + $iDay = 1 + Next + + ; == check given side by side count, calculate if needed + If $iSideBySide > 0 Then + If $iPrintSize < ($iSideBySide *(20 +$iSpace) -$iSpace) Then $iSideBySide = 0 + EndIf + Switch $iSideBySide + Case 0 + $iSideBySide = Int($iPrintSize /(20 +$iSpace)) + If $iPrintSize < 20 Then Return _PrintLine('Escape: Size Error') + If $iPrintSize < (20 +$iSpace) Then $iSideBySide = 1 + Case 5 + $iSideBySide = 4 + Case 7 To 11 + $iSideBySide = 6 + EndSwitch + + ; == create space string + Local $sSpace = '' + For $i = 1 To $iSpace + $sSpace &= ' ' + Next + + ; == print header + _PrintLine(@LF) + _PrintLine('[ here is Snoopy ]', @LF) + _PrintLine(StringRegExpReplace($_iYear, '(\d)(\d)(\d)(\d)', '$1 $2 $3 $4'), @LF) + + ; == create data for each line, in dependence to count of months in one line + Local $sLine, $iRight, $sTmp1, $sTmp2 + For $n = 0 To 12 /$iSideBySide -1 + $sTmp1 = '' + $sTmp2 = '' + For $z = 0 To $iSideBySide -1 + $sTmp1 &= $aMon[$iSideBySide *$n+$z] & $sSpace + $sTmp2 &= $sHead & $sSpace + Next + _PrintLine(StringTrimRight($sTmp1, $iSpace)) + _PrintLine(StringTrimRight($sTmp2, $iSpace)) + For $j = 0 To 5 + $sLine = '' + For $i = 1 To $iSideBySide + For $k = 0 To 6 + $iRight = 3 + If $k = 0 Then $iRight = 2 + $sLine &= StringRight(' ' & $aAllDaysInMonth[$j][$k][$iSideBySide*$n+$i-1], $iRight) + Next + If $i < $iSideBySide Then $sLine &= $sSpace + Next + _PrintLine($sLine) + Next + Next +EndFunc ;==>_CreateCalendar + +Func _PrintLine($_sLine, $_sLF='') + Local $iLen = StringLen($_sLine) + Local $sSpace = '', $sLeft = '' + For $i = 1 To $iPrintSize-1 + $sSpace &= ' ' + Next + If $iLen < $iPrintSize Then $sLeft = StringLeft($sSpace, Int(($iPrintSize-$iLen)/2)) + ConsoleWrite($sLeft & $_sLine & $_sLF & @LF) +EndFunc ;==>_PrintLine diff --git a/Task/Calendar/D/calendar.d b/Task/Calendar/D/calendar.d index 8647804dd7..0eb48091df 100644 --- a/Task/Calendar/D/calendar.d +++ b/Task/Calendar/D/calendar.d @@ -1,20 +1,21 @@ -import std.stdio, std.datetime, std.string, std.exception, std.conv; +import std.stdio, std.datetime, std.string, std.conv; -void printCalendar(in int year, in int cols) { - enforce(1 <= cols && cols <= 12); - - immutable rows = 12 / cols + (12 % cols != 0); +void printCalendar(in uint year, in uint nCols) +in { + assert(nCols > 0 && nCols <= 12); +} body { + immutable rows = 12 / nCols + (12 % nCols != 0); auto date = Date(year, 1, 1); - auto offs = cast(int)date.dayOfWeek(); - const monthNames = "January February March April May June " - "July August September October November December".split(" "); + auto offs = cast(int)date.dayOfWeek; + const months = "January February March April May June + July August September October November December".split; string[8][12] mons; - foreach (m; 0 .. 12) { - mons[m][0] = monthNames[m].center(21); + foreach (immutable m; 0 .. 12) { + mons[m][0] = months[m].center(21); mons[m][1] = " Su Mo Tu We Th Fr Sa"; - immutable dim = date.daysInMonth(); - foreach (d; 1 .. 43) { + immutable dim = date.daysInMonth; + foreach (immutable d; 1 .. 43) { immutable day = d > offs && d <= offs + dim; immutable str = day ? format(" %2s", d-offs) : " "; mons[m][2 + (d - 1) / 7] ~= str; @@ -23,16 +24,17 @@ void printCalendar(in int year, in int cols) { date.add!"months"(1); } - writeln("[Snoopy Picture]".center(cols * 24 + 4)); - writeln(text(year).center(cols * 24 + 4), "\n"); - foreach (r; 0 .. rows) { - auto s = new string[8]; - foreach (c; 0 .. cols) { - if (r * cols + c > 11) break; - foreach (i, line; mons[r * cols + c]) + "[Snoopy Picture]".center(nCols * 24 + 4).writeln; + writeln(year.text.center(nCols * 24 + 4), "\n"); + foreach (immutable r; 0 .. rows) { + string[8] s; + foreach (immutable c; 0 .. nCols) { + if (r * nCols + c > 11) + break; + foreach (immutable i, line; mons[r * nCols + c]) s[i] ~= format(" %s", line); } - writeln(s.join("\n"), "\n"); + writefln("%-(%s\n%)\n", s); } } diff --git a/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia new file mode 100644 index 0000000000..8b22d32024 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia @@ -0,0 +1,7 @@ +julia> p = ccall(:strdup, Ptr{Uint8}, (Ptr{Uint8},), "Hello world") +Ptr{Uint8} @0x000000011731bde0 + +julia> bytestring(p) # convert pointer back to a native Julia string +"Hello world" + +julia> ccall(:free, Void, (Ptr{Uint8},), p) diff --git a/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury b/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury new file mode 100644 index 0000000000..18753cc116 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury @@ -0,0 +1,23 @@ +:- module test_ffi. + +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +% The actual FFI code begins here. +:- pragma foreign_decl("C", "char *strdup(const char *s);"). + +:- func strdup(string::in) = (string::out) is det. +:- pragma foreign_proc("C", strdup(S::in) = (SD::out), + [will_not_call_mercury, not_thread_safe, promise_pure], + "SD = strdup(S);"). +% The actual FFI code ends here. + +main(!IO) :- + io.write_string(strdup("Hello, worlds!\n"), !IO). + +:- end_module test_ffi. diff --git a/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-2.mercury b/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-2.mercury new file mode 100644 index 0000000000..b8caa1809d --- /dev/null +++ b/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-2.mercury @@ -0,0 +1 @@ +:- func strdup(string) = string. diff --git a/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-1.pro b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-1.pro new file mode 100644 index 0000000000..1bb0154158 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-1.pro @@ -0,0 +1,2 @@ +:- module(plffi, [strdup/2]). +:- use_foreign_library(plffi). diff --git a/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-2.pro b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-2.pro new file mode 100644 index 0000000000..e8856a17fa --- /dev/null +++ b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-2.pro @@ -0,0 +1,20 @@ +#include +#include +#include + +static foreign_t pl_strdup(term_t string0, term_t string1) +{ + char *input_string, *output_string; + + if (PL_get_atom_chars(string0, &input_string)) + { + output_string = strdup(input_string); + return PL_unify_atom_chars(string1, output_string); + } + PL_fail; +} + +install_t install_plffi() +{ + PL_register_foreign("strdup", 2, pl_strdup, 0); +} diff --git a/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-3.pro b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-3.pro new file mode 100644 index 0000000000..37c7edb221 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-3.pro @@ -0,0 +1 @@ +$ swipl-ld -o plffi -shared plffi.c diff --git a/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-4.pro b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-4.pro new file mode 100644 index 0000000000..152bf01044 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Prolog/call-a-foreign-language-function-4.pro @@ -0,0 +1,15 @@ +?- [plffi]. +% plffi compiled into plffi 0.04 sec, 1,477 clauses +true. + +?- strdup('Booger!', X). +X = 'Booger!'. + +?- strdup(booger, X). +X = booger. + +?- strdup(booger, booger). +true. + +?- X = booger, strdup(booger, X). +X = booger. diff --git a/Task/Call-a-function/Deja-Vu/call-a-function.djv b/Task/Call-a-function/Deja-Vu/call-a-function.djv new file mode 100644 index 0000000000..1086d01a41 --- /dev/null +++ b/Task/Call-a-function/Deja-Vu/call-a-function.djv @@ -0,0 +1,32 @@ +# all functions used are from the standard library +# calling a function with no arguments: +random-int +# calling a function with a fixed number of arguments: ++ 1 2 +# calling a function with optional arguments: +# optional arguments are not really possible as such +# generally differently named functions are used: +sort [ 3 2 1 ] +sort-by @len [ "Hello" "World" "Bob" ] +# calling a function with a variable number of arguments: +# generally with a special terminator value, which one depends +# on the function called +concat( 1 2 3 ) +[ 1 2 3 ] +set{ :foo :bar :spam } +# calling a function with named arguments: not possible +# using a function in first-class context within an expression +$ @-- @len # $ is "compose", so the function returned is "one less than the length" +# obtaining the return value of a function +# return values are always pushed on the stack, so you don't need anything special +random-int +# discarding the return value of a function +drop random-int +# method call: +local :do { :nuthin @pass } +do!nuthin +!import!fooModule # same as eva!import :fooModule +# arguments are passed by object-identity, like in Python and Lua +# partial application is not possible, due to the fact that +# a function's arity is a property of its behavior and not +# of its definition diff --git a/Task/Call-a-function/Liberty-BASIC/call-a-function.liberty b/Task/Call-a-function/Liberty-BASIC/call-a-function.liberty new file mode 100644 index 0000000000..ff1c13320e --- /dev/null +++ b/Task/Call-a-function/Liberty-BASIC/call-a-function.liberty @@ -0,0 +1,42 @@ +'Call a function - Liberty BASIC + +'First, function result could not be discarded +' that is, you cannot do "f(x)" as a separate statement + +'Calling a function that requires no arguments +res = f() 'brackets required + +'Calling a function with a fixed number of arguments +res = g(x) +res = h(x,y) +'Calling a function with optional arguments + 'impossible for user-defined functions + 'Some build-in functions ex. INSTR and MID$ could be called with last argument omitted +'Calling a function with a variable number of arguments + 'impossible +'Calling a function with named arguments + 'impossible +'Using a function in statement context + 'impossible (see starting notice) +'Using a function in first-class context within an expression + 'impossible +'Obtaining the return value of a function +res = g(x) +'Distinguishing built-in functions and user-defined functions + 'I would say impossible. Though built-in functions could be EVAL'ed, + 'while user-defined would not be called (tries address array instead). + 'Still cannot distinguish user-defined function from array. +'Distinguishing subroutines and functions + 'then defined, subroutines and functions defined with words + 'SUB and FUNCTION (case incensitive) + 'Then used, function used as expression (with return value), + res = g(x) + 'while subroutines called with special keyword CALL and without brackets + call test x, y +'Stating whether arguments are passed by value or by reference + 'Variables passed as arguments into functions and subs are passed "by value" by default + 'parameters could be passed "by reference" if formal parameter in sub/function definition uses the "byref" specifier + 'Then calling a function, you can prevent pass by reference by changing variable to expression + ' like x+0, x$+"" or just (x), (x$) +'Is partial application possible and how + 'impossible 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 new file mode 100644 index 0000000000..593a597102 --- /dev/null +++ b/Task/Call-an-object-method/Scala/call-an-object-method.scala @@ -0,0 +1,25 @@ +/** 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 + 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 { + val s = "Hello" // Not private, so getter auto-generated +} + +/** Demonstrate use of our example class. + */ +object Call_an_object_method extends Application { + 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/Case-sensitivity-of-identifiers/Deja-Vu/case-sensitivity-of-identifiers.djv b/Task/Case-sensitivity-of-identifiers/Deja-Vu/case-sensitivity-of-identifiers.djv new file mode 100644 index 0000000000..b2792952f0 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Deja-Vu/case-sensitivity-of-identifiers.djv @@ -0,0 +1,5 @@ +local :dog "Benjamin" +local :Dog "Samba" +local :DOG "Bernie" + +!print( "There are three dogs named " dog ", " Dog " and " DOG "." ) diff --git a/Task/Case-sensitivity-of-identifiers/JavaScript/case-sensitivity-of-identifiers.js b/Task/Case-sensitivity-of-identifiers/JavaScript/case-sensitivity-of-identifiers.js index 312cf8a4d3..d3b19609d3 100644 --- a/Task/Case-sensitivity-of-identifiers/JavaScript/case-sensitivity-of-identifiers.js +++ b/Task/Case-sensitivity-of-identifiers/JavaScript/case-sensitivity-of-identifiers.js @@ -1,4 +1,4 @@ -var dog="Benjamin"; +var dog = "Benjamin"; var Dog = "Samba"; var DOG = "Bernie"; document.write("The three dogs are named " + dog + ", " + Dog + ", and " + DOG + "."); diff --git a/Task/Catalan-numbers/D/catalan-numbers.d b/Task/Catalan-numbers/D/catalan-numbers.d index a5e7fd5651..02a02575c3 100644 --- a/Task/Catalan-numbers/D/catalan-numbers.d +++ b/Task/Catalan-numbers/D/catalan-numbers.d @@ -1,29 +1,29 @@ import std.stdio, std.bigint, std.functional; -BigInt factorial(uint n) { - alias memoize!factorial mfact; - return n ? mfact(n - 1) * n : BigInt(1); +BigInt factorial(in uint n) { + alias mfact = memoize!factorial; + return n ? mfact(n - 1) * n : 1.BigInt; } -auto cats1(uint n) { - return factorial(2 * n) / (factorial(n + 1) * factorial(n)); +auto cats1(in uint n) { + return factorial(2 * n) / (factorial(n + 1) * n.factorial); } -BigInt cats2(uint n) { - alias memoize!cats2 mcats2; - if (n == 0) return BigInt(1); - auto sum = BigInt(0); - foreach (i; 0 .. n) +BigInt cats2(in uint n) { + alias mcats2 = memoize!cats2; + if (n == 0) return 1.BigInt; + BigInt sum = 0; + foreach (immutable i; 0 .. n) sum += mcats2(i) * mcats2(n - 1 - i); return sum; } -BigInt cats3(uint n) { - alias memoize!cats3 mcats3; - return n ? (4*n - 2) * mcats3(n - 1) / (n + 1) : BigInt(1); +BigInt cats3(in uint n) { + alias mcats3 = memoize!cats3; + return n ? (4*n - 2) * mcats3(n - 1) / (n + 1) : 1.BigInt; } void main() { - foreach (i; 0 .. 15) - writefln("%2d => %s %s %s", i, cats1(i), cats2(i), cats3(i)); + foreach (immutable i; 0 .. 15) + writefln("%2d => %s %s %s", i, i.cats1, i.cats2, i.cats3); } diff --git a/Task/Catalan-numbers/GAP/catalan-numbers.gap b/Task/Catalan-numbers/GAP/catalan-numbers.gap index 7a6b5b59ad..1f582283c5 100644 --- a/Task/Catalan-numbers/GAP/catalan-numbers.gap +++ b/Task/Catalan-numbers/GAP/catalan-numbers.gap @@ -1,30 +1,27 @@ -Catalan1 := function(n) - return Binomial(2*n, n) - Binomial(2*n, n - 1); -end; +Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1); -Catalan2 := function(n) - return Binomial(2*n, n)/(n + 1); -end; +Catalan2 := n -> Binomial(2*n, n)/(n + 1); Catalan3 := function(n) - local k, c; - c := 1; - k := 0; - while k < n do - k := k + 1; - c := 2*(2*k - 1)*c/(k + 1); - od; - return c; + local k, c; + c := 1; + k := 0; + while k < n do + k := k + 1; + c := 2*(2*k - 1)*c/(k + 1); + od; + return c; end; Catalan4_memo := [1]; Catalan4 := function(n) - if not IsBound(Catalan4_memo[n + 1]) then - Catalan4_memo[n + 1] := Sum([0 .. n - 1], i -> Catalan4(i)*Catalan4(n - 1 - i)); - fi; - return Catalan4_memo[n + 1]; + if not IsBound(Catalan4_memo[n + 1]) then + Catalan4_memo[n + 1] := Sum([0 .. n - 1], i -> Catalan4(i)*Catalan4(n - 1 - i)); + fi; + return Catalan4_memo[n + 1]; end; + # The first fifteen: 0 to 14 ! List([0 .. 14], n -> Catalan1(n)); List([0 .. 14], n -> Catalan2(n)); diff --git a/Task/Catalan-numbers/Julia/catalan-numbers.julia b/Task/Catalan-numbers/Julia/catalan-numbers.julia index 66e184e714..09b82cd1a0 100644 --- a/Task/Catalan-numbers/Julia/catalan-numbers.julia +++ b/Task/Catalan-numbers/Julia/catalan-numbers.julia @@ -1,8 +1 @@ -function catalan(bn::Integer) - if bn < 0 - throw(DomainError()) - else - n = BigInt(bn) - end - return binomial(2n, n)/(n + 1) -end +Catalan(n::Integer) = div(binomial(2n, n), n+1) diff --git a/Task/Character-codes/BASIC/character-codes-3.basic b/Task/Character-codes/BASIC/character-codes-3.basic new file mode 100644 index 0000000000..a31139d726 --- /dev/null +++ b/Task/Character-codes/BASIC/character-codes-3.basic @@ -0,0 +1 @@ +?CHR$(97)"="ASC(CHR$(97)) diff --git a/Task/Character-codes/Clojure/character-codes.clj b/Task/Character-codes/Clojure/character-codes.clj index fd93a67555..a1daa5f857 100644 --- a/Task/Character-codes/Clojure/character-codes.clj +++ b/Task/Character-codes/Clojure/character-codes.clj @@ -4,3 +4,7 @@ ; Unicode is also available, as Clojure uses the underlying java Strings & chars (print (int \π)) ; prints 960 (print (char 960)) ; prints \π + +; use String because char in Java can't represent characters outside Basic Multilingual Plane +(print (.codePointAt "𝅘𝅥𝅮" 0)) ; prints 119136 +(print (String. (int-array 1 119136) 0 1)) ; prints 𝅘𝅥𝅮 diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index ac210fa604..cda8416be0 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -1,8 +1,7 @@ -#define std'dictionary'*. -#define std'basic'*. +#define system. #symbol Program => [ - 'program'output << WideCharVar::"a" numeric. - 'program'output << WideCharVar::97. + console write:("a" getAt:0 Number). + console write:(CharValue new:97). ]. diff --git a/Task/Character-codes/GAP/character-codes.gap b/Task/Character-codes/GAP/character-codes.gap index 92d6697132..a1b966c4cc 100644 --- a/Task/Character-codes/GAP/character-codes.gap +++ b/Task/Character-codes/GAP/character-codes.gap @@ -1,5 +1,5 @@ # Code must be in 0 .. 255. -CHAR_INT(65); +CharInt(65); # 'A' -INT_CHAR('Z'); +IntChar('Z'); # 90 diff --git a/Task/Character-codes/Julia/character-codes.julia b/Task/Character-codes/Julia/character-codes.julia new file mode 100644 index 0000000000..1b59a08561 --- /dev/null +++ b/Task/Character-codes/Julia/character-codes.julia @@ -0,0 +1,2 @@ +println(int('a')) +println(char(97)) diff --git a/Task/Character-codes/VBA/character-codes.vba b/Task/Character-codes/VBA/character-codes.vba new file mode 100644 index 0000000000..33aee89dc9 --- /dev/null +++ b/Task/Character-codes/VBA/character-codes.vba @@ -0,0 +1,2 @@ +Debug.Print Chr(97) 'Prints a +Debug.Print [Code("a")] ' Prints 97 diff --git a/Task/Chat-server/00DESCRIPTION b/Task/Chat-server/00DESCRIPTION index 75d20e7776..93b5cca8da 100644 --- a/Task/Chat-server/00DESCRIPTION +++ b/Task/Chat-server/00DESCRIPTION @@ -1 +1,3 @@ Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages. + +Nov. 31st is an interesting deadline :-) --[[User:Walterpachl|Walterpachl]] ([[User talk:Walterpachl|talk]]) 10:46, 2 November 2013 (UTC) diff --git a/Task/Chat-server/Racket/chat-server.rkt b/Task/Chat-server/Racket/chat-server.rkt index d9be5caf7a..5400a2f994 100644 --- a/Task/Chat-server/Racket/chat-server.rkt +++ b/Task/Chat-server/Racket/chat-server.rkt @@ -1,21 +1,37 @@ #lang racket -(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-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 ((client i o)) - (define nick (begin (display "Nick: " o) (read-line i))) - (define tell (tell-all nick o)) (let loop ([line "(joined)"]) - (if (eof-object? line) - (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) - (begin (tell line) (loop (read-line i)))))) + (cond [(eof-object? line) + (tell "(left)") + (set! *client-outputs* (remq output *client-outputs*)) + (close-output-port output)] + [else + (tell line) + (loop (read-line input))]))) (define (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-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)) -(void (thread (λ() (chat-server (tcp-listen 12321))))) -((client (current-input-port) (current-output-port))) +(define (start-server) + (chat-server (tcp-listen 12321))) + +(void (thread start-server)) +(client (current-input-port) (current-output-port)) diff --git a/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d b/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d index ce6b4b8aed..8eb0585fc8 100644 --- a/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d +++ b/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d @@ -1,8 +1,50 @@ -import std.stdio, std.regex, std.conv, std.string, std.typecons, - std.array, std.range; -import arithmetic_rational: Rational; +import std.stdio, std.regex, std.conv, std.string, std.range, + arithmetic_rational; -immutable equationText = +struct Pair { int x; Rational r; } + +Pair[][] parseEquations(in string text) /*pure nothrow*/ { + auto r = regex(r"\s*(?P[+-])?\s*(?:(?P\d+)\s*\*)?\s*" ~ + r"arctan\((?P\d+)/(?P\d+)\)"); + Pair[][] machins; + foreach (const line; text.splitLines) { + Pair[] formula; + foreach (/*const*/ part; line.split("=")[1].matchAll(r)) { + immutable mul = part["mul"], + num = part["num"], + denom = part["denom"]; + formula ~= Pair((part["sign"] == "-" ? -1 : 1) * + (mul.empty ? 1 : mul.to!int), + Rational(num.to!int, + denom.empty ? 1 : denom.to!int)); + } + machins ~= formula; + } + return machins; +} + + +Rational tans(in Pair[] xs) pure /*nothrow*/ { + static Rational tanEval(in int coef, in Rational f) + pure /*nothrow*/ { + if (coef == 1) + return f; + if (coef < 0) + return -tanEval(-coef, f); + immutable a = tanEval(coef / 2, f), + b = tanEval(coef - coef / 2, f); + return (a + b) / (1 - a * b); + } + + if (xs.length == 1) + return tanEval(xs[0].tupleof); + immutable a = xs[0 .. $ / 2].tans, + b = xs[$ / 2 .. $].tans; + return (a + b) / (1 - a * b); +} + +void main() { + immutable equationText = "pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) @@ -21,52 +63,9 @@ pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943) pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943) pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)"; -alias Pair = Tuple!(int, Rational); - -Pair[][] parseEquations(in string text) { - auto r = regex(r"\s*(?P[+-])?\s*(?:(?P\d+)\s*\*)?\s*" ~ - r"arctan\((?P\d+)/(?P\d+)\)", "g"); - Pair[][] machins; - foreach (const line; text.splitLines()) { - Pair[] formula; - foreach (part; std.string.split(line, "=")[1].match(r)) { - immutable string mul = part["mul"]; - immutable string num = part["num"]; - immutable string denom = part["denom"]; - formula ~= Pair((part["sign"] == "-" ? -1 : 1) * - (mul.empty ? 1 : to!int(mul)), - Rational(to!int(num), - denom.empty ? 1 : to!int(denom))); - } - machins ~= formula; - } - return machins; -} - - -Rational tans(/*in*/ Pair[] xs) /*pure nothrow*/ { - static Rational tanEval(in int coef, /*in*/ Rational f) - /*pure nothrow*/ { - if (coef == 1) - return f; - if (coef < 0) - return -tanEval(-coef, f); - /*const*/ auto a = tanEval(coef / 2, f); - /*const*/ auto b = tanEval(coef - coef / 2, f); - return (a + b) / (1 - a * b); - } - - if (xs.length == 1) - return tanEval(xs[0].tupleof); - /*const*/ auto a = tans(xs[0 .. xs.length / 2]); - /*const*/ auto b = tans(xs[xs.length / 2 .. $]); - return (a + b) / (1 - a * b); -} - -void main() { - /*const*/ auto machins = parseEquations(equationText); - foreach (machin, eqn; zip(machins, equationText.splitLines())) { - /*const*/ auto ans = tans(machin); + const machins = equationText.parseEquations; + foreach (const machin, const eqn; machins.zip(equationText.splitLines)) { + immutable ans = machin.tans; writefln("%5s: %s", ans == 1 ? "OK" : "ERROR", eqn); } } diff --git a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx new file mode 100644 index 0000000000..2be4ecb356 --- /dev/null +++ b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx @@ -0,0 +1,50 @@ +/*REXX program evaluates some expressions and verifies their veracity.*/ +parse arg digs .; if digs=='' then digs=100 /*use default for digs?*/ +numeric digits digs+10; numeric fuzz 3; pi=pi(); !.= + !.1 = 'pi/4 = atan(1/2) + atan(1/3)' + !.2 = 'pi/4 = 2*atan(1/3) + atan(1/7)' + !.3 = 'pi/4 = 4*atan(1/5) - atan(1/239)' + !.4 = 'pi/4 = 5*atan(1/7) + 2*atan(3/79)' + !.5 = 'pi/4 = 5*atan(29/278) + 7*atan(3/79)' + !.6 = 'pi/4 = atan(1/2) + atan(1/5) + atan(1/8)' + !.7 = 'pi/4 = 4*atan(1/5) - atan(1/70) + atan(1/99)' + !.8 = 'pi/4 = 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443)' + !.9 = 'pi/4 = 6*atan(1/8) + 2*atan(1/57) + atan(1/239)' +!.10 = 'pi/4 = 8*atan(1/10) - atan(1/239) - 4*atan(1/515)' +!.11 = 'pi/4 = 12*atan(1/18) + 8*atan(1/57) - 5*atan(1/239)' +!.12 = 'pi/4 = 16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042)' +!.13 = 'pi/4 = 22*atan(1/28) + 2*atan(1/443) - 5*atan(1/1393) - 10*atan(1/11018)' +!.14 = 'pi/4 = 22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149)' +!.15 = 'pi/4 = 44*atan(1/57) + 7*atan(1/239) - 12*atan(1/682) + 24*atan(1/12943)' +!.16 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943)' +!.17 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944)' + + do j=1 while !.j\=='' /*evaluate each of the formulas. */ + interpret 'answer=' "(" !.j ")" /*the heavy lifting.*/ + say right(word('bad OK',answer+1),3)": " space(!.j,0) + end /*j*/ /* [↑] show OK | bad, formula. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────subroutines─────────────────────────*/ +Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr + return .5*pi()-Asin(x) + +Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x + if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z + do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end + return z + +Atan: procedure; parse arg x; if abs(x)=1 then return pi()/4*sign(x) + return Asin(x/sqrt(1+x**2)) +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*/ + numeric digits m.0; return (g/1)i +pi: return, +3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651 + +AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X='||x +AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X='||x +tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x +tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 diff --git a/Task/Check-that-file-exists/Clojure/check-that-file-exists.clj b/Task/Check-that-file-exists/Clojure/check-that-file-exists.clj index 957bc4c9db..a59187804a 100644 --- a/Task/Check-that-file-exists/Clojure/check-that-file-exists.clj +++ b/Task/Check-that-file-exists/Clojure/check-that-file-exists.clj @@ -1,17 +1 @@ -(import '(java.io File)) - -(defn kind [filename] - (let [f (File. filename)] - (cond - (.isFile f) "file" - (.isDirectory f) "directory" - (.exists f) "other" - :else "(non-existent)" ))) - -(defn look-for [filename] - (println filename ":" (kind filename))) - -(look-for "input.txt") -(look-for "/input.txt") -(look-for "docs") -(look-for "/docs") +(map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")) diff --git a/Task/Check-that-file-exists/Julia/check-that-file-exists.julia b/Task/Check-that-file-exists/Julia/check-that-file-exists.julia new file mode 100644 index 0000000000..f2cc07551d --- /dev/null +++ b/Task/Check-that-file-exists/Julia/check-that-file-exists.julia @@ -0,0 +1,4 @@ +isfile("input.txt") +isfile("/input.txt") +isdir("docs") +isdir("/docs") diff --git a/Task/Cholesky-decomposition/D/cholesky-decomposition.d b/Task/Cholesky-decomposition/D/cholesky-decomposition.d index e3d9b0c741..e8c8e0c295 100644 --- a/Task/Cholesky-decomposition/D/cholesky-decomposition.d +++ b/Task/Cholesky-decomposition/D/cholesky-decomposition.d @@ -1,12 +1,12 @@ import std.stdio, std.math, std.numeric; -T[][] cholesky(T)(in T[][] A) { +T[][] cholesky(T)(in T[][] A) pure nothrow { auto L = new T[][](A.length, A.length); - foreach (r, row; L) - row[r+1 .. $] = 0; - foreach (i; 0 .. A.length) - foreach (j; 0 .. i+1) { - T t = dotProduct(L[i][0..j], L[j][0..j]); + foreach (immutable r, row; L) + row[r + 1 .. $] = 0; + foreach (immutable i; 0 .. A.length) + foreach (immutable j; 0 .. i + 1) { + auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } @@ -23,5 +23,5 @@ void main() { [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; - writefln("%(%(%f %)\n%)\n", cholesky(m2)); + writefln("%(%(%2.3f %)\n%)\n", m2.cholesky); } diff --git a/Task/Cholesky-decomposition/PL-I/cholesky-decomposition.pli b/Task/Cholesky-decomposition/PL-I/cholesky-decomposition.pli new file mode 100644 index 0000000000..c81829621b --- /dev/null +++ b/Task/Cholesky-decomposition/PL-I/cholesky-decomposition.pli @@ -0,0 +1,47 @@ +(subscriptrange): +decompose: procedure options (main); /* 31 October 2013 */ + declare a(*,*) float controlled; + + allocate a(3,3) initial (25, 15, -5, + 15, 18, 0, + -5, 0, 11); + put skip list ('Original matrix:'); + put edit (a) (skip, 3 f(4)); + + call cholesky(a); + put skip list ('Decomposed matrix'); + put edit (a) (skip, 3 f(4)); + free a; + allocate a(4,4) initial (18, 22, 54, 42, + 22, 70, 86, 62, + 54, 86, 174, 134, + 42, 62, 134, 106); + put skip list ('Original matrix:'); + put edit (a) (skip, (hbound(a,1)) f(12) ); + call cholesky(a); + put skip list ('Decomposed matrix'); + put edit (a) (skip, (hbound(a,1)) f(12,5) ); + +cholesky: procedure(a); + declare a(*,*) float; + declare L(hbound(a,1), hbound(a,2)) float; + declare s float; + declare (i, j, k) fixed binary; + + L = 0; + do i = lbound(a,1) to hbound(a,1); + do j = lbound(a,2) to i; + s = 0; + do k = lbound(a,2) to j-1; + s = s + L(i,k) * L(j,k); + end; + if i = j then + L(i,j) = sqrt(a(i,i) - s); + else + L(i,j) = (a(i,j) - s) / L(j,j); + end; + end; + a = L; +end cholesky; + +end decompose; diff --git a/Task/Cholesky-decomposition/Perl/cholesky-decomposition.pl b/Task/Cholesky-decomposition/Perl/cholesky-decomposition.pl new file mode 100644 index 0000000000..eb059b393d --- /dev/null +++ b/Task/Cholesky-decomposition/Perl/cholesky-decomposition.pl @@ -0,0 +1,25 @@ +sub cholesky { + my $matrix = shift; + my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; + for my $row (0..@$matrix-1) { + for my $col (0..$row) { + my $x = $$matrix[$row][$col]; + $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; + $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; + } + } + return $chol; +} + +my $example1 = [ [ 25, 15, -5 ], + [ 15, 18, 0 ], + [ -5, 0, 11 ] ]; +print "Example 1:\n"; +print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 }; + +my $example2 = [ [ 18, 22, 54, 42], + [ 22, 70, 86, 62], + [ 54, 86, 174, 134], + [ 42, 62, 134, 106] ]; +print "\nExample 2:\n"; +print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 }; diff --git a/Task/Cholesky-decomposition/PicoLisp/cholesky-decomposition-1.l b/Task/Cholesky-decomposition/PicoLisp/cholesky-decomposition-1.l index 5788ed8b16..afcf677100 100644 --- a/Task/Cholesky-decomposition/PicoLisp/cholesky-decomposition-1.l +++ b/Task/Cholesky-decomposition/PicoLisp/cholesky-decomposition-1.l @@ -10,7 +10,7 @@ (dec 'S (*/ (get L I K) (get L J K) 1.0)) ) (set (nth L I J) (if (= I J) - (sqrt (* 1.0 S)) + (sqrt S 1.0) (*/ S 1.0 (get L J J)) ) ) ) ) ) (for R L (for N R (prin (align 9 (round N 5)))) diff --git a/Task/Closest-pair-problem/AWK/closest-pair-problem.awk b/Task/Closest-pair-problem/AWK/closest-pair-problem.awk new file mode 100644 index 0000000000..be99bee35f --- /dev/null +++ b/Task/Closest-pair-problem/AWK/closest-pair-problem.awk @@ -0,0 +1,26 @@ +# syntax: GAWK -f CLOSEST-PAIR_PROBLEM.AWK +BEGIN { + x[++n] = 0.654682 ; y[n] = 0.925557 + x[++n] = 0.409382 ; y[n] = 0.619391 + x[++n] = 0.891663 ; y[n] = 0.888594 + x[++n] = 0.716629 ; y[n] = 0.996200 + x[++n] = 0.477721 ; y[n] = 0.946355 + x[++n] = 0.925092 ; y[n] = 0.818220 + x[++n] = 0.624291 ; y[n] = 0.142924 + x[++n] = 0.211332 ; y[n] = 0.221507 + x[++n] = 0.293786 ; y[n] = 0.691701 + x[++n] = 0.839186 ; y[n] = 0.728260 + min = 1E20 + for (i=1; i<=n-1; i++) { + for (j=i+1; j<=n; j++) { + dsq = (x[i]-x[j])^2 + (y[i]-y[j])^2 + if (dsq < min) { + min = dsq + mini = i + minj = j + } + } + } + printf("distance between (%.6f,%.6f) and (%.6f,%.6f) is %g\n",x[mini],y[mini],x[minj],y[minj],sqrt(min)) + exit(0) +} diff --git a/Task/Closest-pair-problem/D/closest-pair-problem-1.d b/Task/Closest-pair-problem/D/closest-pair-problem-1.d index f75b27d8fc..326e8143cb 100644 --- a/Task/Closest-pair-problem/D/closest-pair-problem-1.d +++ b/Task/Closest-pair-problem/D/closest-pair-problem-1.d @@ -1,11 +1,16 @@ import std.stdio, std.typecons, std.math, std.algorithm, - std.array, std.random, std.traits; + std.random, std.traits, std.range, std.complex; + +//auto bfClosestPair(T)(in T[] points) pure nothrow { +// return pairwise(points.length.iota, points.length.iota) +// .reduce!(min!((i, j) => abs(points[i] - points[j]))); +//} auto bruteForceClosestPair(T)(in T[] points) pure nothrow { auto minD = Unqual!(typeof(T.re)).infinity; - Unqual!T minI, minJ; - foreach (i, p1; points[0 .. $-1]) - foreach (j, p2; points[i+1 .. $]) { + T minI, minJ; + foreach (immutable i, const p1; points.dropBackOne) + foreach (const p2; points[i + 1 .. $]) { immutable dist = abs(p1 - p2); if (dist < minD) { minD = dist; @@ -17,23 +22,25 @@ auto bruteForceClosestPair(T)(in T[] points) pure nothrow { } auto closestPair(T)(T[] points) /*pure nothrow*/ { - static Tuple!(typeof(T.re),T,T) inner(in T[] xP, /*in*/ T[] yP) { + static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP) + pure nothrow { if (xP.length <= 3) - return bruteForceClosestPair(xP); - const Pl = xP[0 .. xP.length/2]; - const Pr = xP[xP.length/2 .. $]; - immutable xDiv = Pl[$ - 1].re; - auto Yr = partition!(p => p.re <= xDiv)(yP); + return xP.bruteForceClosestPair; + const Pl = xP[0 .. $ / 2]; + const Pr = xP[$ / 2 .. $]; + immutable xDiv = Pl.back.re; + auto Yr = yP.partition!(p => p.re <= xDiv); immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]); immutable dr_pairr = inner(Pr, Yr); - immutable dm_pairm= dl_pairl[0] abs(p.re - xDiv) < dm)().array(); + const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array; + if (nextY.length > 1) { auto minD = typeof(T.re).infinity; size_t minI, minJ; - foreach (i; 0 .. nextY.length-1) - foreach (j; i+1 .. min(i+8, nextY.length)) { + foreach (immutable i; 0 .. nextY.length - 1) + foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) { immutable double dist = abs(nextY[i] - nextY[j]); if (dist < minD) { minD = dist; @@ -42,27 +49,29 @@ auto closestPair(T)(T[] points) /*pure nothrow*/ { } } return dm <= minD ? dm_pairm : - Tuple!(typeof(T.re),T,T)(minD,nextY[minI],nextY[minJ]); + typeof(return)(minD, nextY[minI], nextY[minJ]); } else return dm_pairm; } - sort!q{ a.re < b.re }(points); - auto xP = points.dup; - sort!q{ a.im < b.im }(points); + points.sort!q{ a.re < b.re }; + const xP = points.dup; + points.sort!q{ a.im < b.im }; return inner(xP, points); } void main() { - auto pts= [5+9i, 9+3i, 2, 8+4i, 7+4i, 9+10i, 1+9i, 8+2i, 10i, 9+6i]; - writeln(pts); - writeln("bruteForceClosestPair: ", bruteForceClosestPair(pts)); - writeln(" closestPair: ", closestPair(pts)); + alias C = complex; + auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9), + C(8,2), C(0,10), C(9,6)]; + pts.writeln; + writeln("bruteForceClosestPair: ", pts.bruteForceClosestPair); + writeln(" closestPair: ", pts.closestPair); - auto rnd = Random(1); // set seed - cdouble[10_000] points; + rndGen.seed = 1; + Complex!double[10_000] points; foreach (ref p; points) - p = uniform(0.0, 1000.0, rnd) + uniform(0.0, 1000.0, rnd) * 1i; - writeln("bruteForceClosestPair: ", bruteForceClosestPair(points)); - writeln(" closestPair: ", closestPair(points)); + p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0)); + writeln("bruteForceClosestPair: ", points.bruteForceClosestPair); + writeln(" closestPair: ", points.closestPair); } diff --git a/Task/Closest-pair-problem/D/closest-pair-problem-2.d b/Task/Closest-pair-problem/D/closest-pair-problem-2.d index 29b19f0ae8..7b0d6f5ac9 100644 --- a/Task/Closest-pair-problem/D/closest-pair-problem-2.d +++ b/Task/Closest-pair-problem/D/closest-pair-problem-2.d @@ -1,49 +1,39 @@ -import core.stdc.stdio, core.stdc.stdlib, std.math; // for Phobos -//import tango.stdc.stdio, tango.stdc.stdlib, tango.math.Math; +import std.stdio, std.random, std.math, std.typecons, std.complex, + std.traits; -int bfClosestPair2(cdouble[] points, out size_t i1, out size_t i2) { - auto minD = typeof(points[0].re).infinity; - if (points.length < 2) { - i1 = i2 = size_t.max; - return -1; - } - size_t minI, minJ; - for (int i = 0; i < points.length-1; i++) { - auto points_i_re = points[i].re; - auto points_i_im = points[i].im; - for (int j = i+1; j < points.length; j++) { - auto dre = points_i_re - points[j].re; - auto dist = dre * dre; - if (dist < minD) { - auto dim = points_i_im - points[j].im; - dist += dim * dim; - if (dist < minD) { - minD = dist; - minI = i; - minJ = j; +Nullable!(Tuple!(size_t, size_t)) +bfClosestPair2(T)(in Complex!T[] points) pure nothrow { + auto minD = Unqual!(typeof(points[0].re)).infinity; + if (points.length < 2) + return typeof(return)(); + + size_t minI, minJ; + foreach (immutable i; 0 .. points.length - 1) + foreach (immutable j; i + 1 .. points.length) { + auto dist = (points[i].re - points[j].re) ^^ 2; + if (dist < minD) { + dist += (points[i].im - points[j].im) ^^ 2; + if (dist < minD) { + minD = dist; + minI = i; + minJ = j; + } + } } - } - } - } - i1 = minI; - i2 = minJ; - return 0; + return typeof(return)(tuple(minI, minJ)); } void main() { - srand(31415); - auto pts = new cdouble[10_000]; + alias C = Complex!double; + auto rng = 31415.Xorshift; + C[10_000] pts; foreach (ref p; pts) - p = 1000.0 * (cast(double)rand() / (RAND_MAX + 1.0)) + - 1000.0i * (cast(double)rand() / (RAND_MAX + 1.0)); + p = C(uniform(0.0, 1000.0, rng), uniform(0.0, 1000.0, rng)); - size_t i, j; - int err = bfClosestPair2(pts, i, j); - if (err < 0) + immutable ij = pts.bfClosestPair2; + if (ij.isNull) return; - double d = sqrt((pts[i].re - pts[j].re) * (pts[i].re - pts[j].re) + - (pts[i].im - pts[j].im) * (pts[i].im - pts[j].im)); - printf("Closest pair: dist: %lf p1, p2: (%lf, %lf), (%lf, %lf)\n", - d, pts[i].re, pts[i].im, pts[j].re, pts[j].im); + writefln("Closest pair: Distance: %f p1, p2: %f, %f", + abs(pts[ij[0]] - pts[ij[1]]), pts[ij[0]], pts[ij[1]]); } diff --git a/Task/Colour-bars-Display/ActionScript/colour-bars-display.as b/Task/Colour-bars-Display/ActionScript/colour-bars-display.as new file mode 100644 index 0000000000..2879157c70 --- /dev/null +++ b/Task/Colour-bars-Display/ActionScript/colour-bars-display.as @@ -0,0 +1,29 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + + public class ColourBars extends Sprite { + + public function ColourBars():void { + if (stage) init(); + else addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(e:Event = null):void { + + var colours:Array = [ 0x000000, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF00FF, 0x00FFFF, 0xFFFF00, 0xFFFFFF ]; + var w:Number = stage.stageWidth / 8, h:Number = stage.stageHeight; + var x:Number = 0, i:uint, c:uint; + + for ( i = 0; i < 8; i++ ) { + c = colours[i]; + graphics.beginFill(c); + graphics.drawRect(w * i, 0, w, h); + } + + } + + } + +} diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-1.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-1.basic new file mode 100644 index 0000000000..7f1d0f8990 --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-1.basic @@ -0,0 +1,6 @@ +1 DATA1,12,6,3,14,13,15 +2 HOME : GR : FOR I = 1 TO 7 +3 READ C(I) : NEXT +4 FOR I = 0 TO 39 +5 COLOR= C(I / 5) +6 VLIN 0,39 AT I : NEXT diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-2.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-2.basic new file mode 100644 index 0000000000..41071ffd28 --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-2.basic @@ -0,0 +1,19 @@ + SW_MAXIMIZE = 3 + SYS "ShowWindow", @hwnd%, SW_MAXIMIZE + VDU 26 + + W% = @vdu%!208 / 4 + H% = @vdu%!212 * 2 + + COLOUR 1,9 + COLOUR 2,10 + COLOUR 3,12 + COLOUR 4,13 + COLOUR 5,14 + COLOUR 6,11 + COLOUR 7,15 + + FOR C% = 0 TO 7 + GCOL C% + RECTANGLE FILL C%*W%, 0, W%, H% + NEXT diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-3.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-3.basic new file mode 100644 index 0000000000..528e576b26 --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-3.basic @@ -0,0 +1,20 @@ +nomainwin +colors$="black red green blue pink cyan yellow white" +WindowWidth=DisplayWidth:WindowHeight=DisplayHeight +UpperLeftX=1:UpperLeftY=1 +barWidth=DisplayWidth/8 +graphicbox #main.g, 0,0,DisplayWidth,DisplayHeight +open "" for window_popup as #main +#main "trapclose [quit]" +#main.g "down; setfocus; when characterInput [quit]" +#main.g "when leftButtonUp [quit]" +#main.g "size ";barWidth + +for x = barWidth/2 to DisplayWidth step barWidth + i=i+1 + if i>8 then i=1 + col$=word$(colors$,i) + #main.g "color ";col$;"; line ";x;" 0 ";x;" ";DisplayHeight +next +wait +[quit] close #main:end diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-4.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-4.basic new file mode 100644 index 0000000000..22c2f0c6e0 --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-4.basic @@ -0,0 +1,7 @@ +10 MODE 0:BORDER 23 +20 FOR x=0 TO 15 +30 ORIGIN x*40,0 +40 GRAPHICS PEN x +50 FOR z=0 TO 39 STEP 4:MOVE z,0:DRAW z,400:NEXT +60 NEXT +70 CALL &bb06 ' wait for key press diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-5.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-5.basic new file mode 100644 index 0000000000..9b35d9fe22 --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-5.basic @@ -0,0 +1,31 @@ +Dim color(7) +color(0) = RGB($00, $00, $00) ;black +color(1) = RGB($FF, $00, $00) ;red +color(2) = RGB($00, $FF, $00) ;green +color(3) = RGB($00, $00, $FF) ;blue +color(4) = RGB($FF, $00, $FF) ;magenta +color(5) = RGB($00, $FF, $FF) ;cyan +color(6) = RGB($FF, $FF, $00) ;yellow +color(7) = RGB($FF, $FF, $FF) ;white + +If Not InitKeyboard(): End: EndIf ;can't init keyboard +If Not InitSprite(): End: EndIf ;can't init sprite/screen library +If Not ExamineDesktops(): End: EndIf ;can't retrieve information about desktop + +height = DesktopHeight(0) +width = DesktopWidth(0) +depth = DesktopDepth(0) +If OpenScreen(width, height, depth, "Press ENTER to exit") + StartDrawing(ScreenOutput()) + For c = 0 To 7 + Box((width * c) / 8, 0, width / 8, height, color(c)) + Next + StopDrawing() + FlipBuffers() + + Repeat + Delay(10) + ExamineKeyboard() + Until KeyboardPushed(#PB_Key_Escape) Or KeyboardPushed(#PB_Key_Return) + CloseScreen() +EndIf diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-6.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-6.basic new file mode 100644 index 0000000000..e3cde4b7fd --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-6.basic @@ -0,0 +1,24 @@ +DataSection + ;Black, Red, Green, Blue, Magenta, Cyan, Yellow, White + Data.i 0, 12, 10, 9, 13, 11, 14, 15 +EndDataSection + +Dim colors(7) +For c = 0 To 7 + Read.i colors(c) +Next + +If OpenConsole() + ;The console display is 80 columns wide by 25 rows + For r = 0 To 24 + For c = 0 To 7 + ConsoleColor(colors(c), colors(c)) + Print(Space(80 / 8)) + Next + Next + EnableGraphicalConsole(1) + ConsoleLocate(0, 0) + + ConsoleTitle("Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-7.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-7.basic new file mode 100644 index 0000000000..3e484752df --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-7.basic @@ -0,0 +1,6 @@ +colors$ = "black,red,green,blue,magenta,cyan,yellow,white" +html "" +for i = 1 to 8 + html "
" +next i +html "
" diff --git a/Task/Colour-bars-Display/BASIC/colour-bars-display-8.basic b/Task/Colour-bars-Display/BASIC/colour-bars-display-8.basic new file mode 100644 index 0000000000..3c8e3a3d25 --- /dev/null +++ b/Task/Colour-bars-Display/BASIC/colour-bars-display-8.basic @@ -0,0 +1,8 @@ +10 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces +20 FOR r=0 TO 20: REM There are 21 rows +30 FOR c=0 TO 7: REM We use the native colour sequence here +40 PAPER c: REM set the background colour for the spaces to be printed +50 PRINT " ";: REM four spaces, the semicolon prevents newline +60 NEXT c +70 REM at this point the cursor has wrapped, so we don't need a newline +80 NEXT r diff --git a/Task/Colour-bars-Display/C/colour-bars-display-1.c b/Task/Colour-bars-Display/C/colour-bars-display-1.c new file mode 100644 index 0000000000..cacdcc0fb8 --- /dev/null +++ b/Task/Colour-bars-Display/C/colour-bars-display-1.c @@ -0,0 +1,34 @@ +/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ + +#include + +#define COLOURS 8 + +int main() +{ + int colour=0,i,j,MAXROW,MAXCOL; + struct text_info tInfo; + gettextinfo(&tInfo); + MAXROW = tInfo.screenheight; + MAXCOL = tInfo.screenwidth; + textbackground(BLACK); //8 colour constants are defined + clrscr(); + + for(colour=0;colour +#include + +int main() +{ + int d=DETECT,m,maxX,maxY,maxColours,i; + initgraph(&d,&m,"c:/turboc3/bgi"); + maxX = getmaxx(); + maxY = getmaxy(); + maxColours = getmaxcolor(); + + for(i=0;i 7) ? 0 : colourIndex + 1; + colour = colours[colourIndex]; + px = 1; + } + else px++; + + data.setPixel32(x, y, colour); + + } + } + + maxy += h; + + } + + data.unlock(); + addChild(new Bitmap(data)); + } + + } + +} diff --git a/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c b/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c new file mode 100644 index 0000000000..2a1f03ca45 --- /dev/null +++ b/Task/Colour-pinstripe-Display/C/colour-pinstripe-display.c @@ -0,0 +1,30 @@ +/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ + +#include +#include + +#define sections 4 + +int main() +{ + int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1; + initgraph(&d,&m,"c:/turboc3/bgi"); + + maxX = getmaxx(); + maxY = getmaxy(); + + for(y=0;y> 1) - 1); } + this.combVal = localCombVal; } uint length() @property const pure nothrow { diff --git a/Task/Combinations-with-repetitions/GAP/combinations-with-repetitions.gap b/Task/Combinations-with-repetitions/GAP/combinations-with-repetitions.gap new file mode 100644 index 0000000000..94fac30a0d --- /dev/null +++ b/Task/Combinations-with-repetitions/GAP/combinations-with-repetitions.gap @@ -0,0 +1,2 @@ +# Built-in +UnorderedTuples(["iced", "jam", "plain"], 2); diff --git a/Task/Combinations/D/combinations-1.d b/Task/Combinations/D/combinations-1.d index c5e879768b..e2db6cacc6 100644 --- a/Task/Combinations/D/combinations-1.d +++ b/Task/Combinations/D/combinations-1.d @@ -1,15 +1,13 @@ -import std.stdio; - T[][] comb(T)(in T[] arr, in int k) pure nothrow { if (k == 0) return [[]]; typeof(return) result; - foreach (i, x; arr) + foreach (immutable i, immutable x; arr) foreach (suffix; arr[i + 1 .. $].comb(k - 1)) result ~= x ~ suffix; return result; } void main() { - //import std.stdio: writeln; - [0, 1, 2, 3].comb(2).writeln(); + import std.stdio; + [0, 1, 2, 3].comb(2).writeln; } diff --git a/Task/Combinations/D/combinations-2.d b/Task/Combinations/D/combinations-2.d index cf1448d91e..3cd4a44f4e 100644 --- a/Task/Combinations/D/combinations-2.d +++ b/Task/Combinations/D/combinations-2.d @@ -1,13 +1,12 @@ import std.stdio, std.algorithm, std.range; -T[][] comb(T)(in T[] s, in int m) /*pure nothrow*/ { +T[][] comb(T)(in T[] s, in int m) /*pure*/ nothrow { if (!m) return [[]]; if (s.empty) return []; - return s[1 .. $].comb(m - 1).map!(x => s[0] ~ x)().array() ~ + return s[1 .. $].comb(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].comb(m); } void main() { - //import std.stdio: writeln; - iota(4).array().comb(2).writeln(); + 4.iota.array.comb(2).writeln; } diff --git a/Task/Combinations/Elena/combinations.elena b/Task/Combinations/Elena/combinations.elena new file mode 100644 index 0000000000..e8d2b25a45 --- /dev/null +++ b/Task/Combinations/Elena/combinations.elena @@ -0,0 +1,25 @@ +#define system. +#define system'routines. +#define extensions. +#define extensions'routines. + +#symbol M = 3. +#symbol N = 5. + +// --- Numbers --- + +#symbol numbers = (:anN) +[ + arrayControl new &length:anN &each: anIndex [ Integer new:(anIndex + 1) ] +]. + +// --- Program --- + +#symbol program = +[ + #var aNumbers := numbers:N. + controlEx for:(Combinator new:(arrayControl new &length:M &each: i [ aNumbers ])) &do: aRow + [ + consoleEx writeLine:aRow. + ]. +]. diff --git a/Task/Combinations/Julia/combinations.julia b/Task/Combinations/Julia/combinations.julia index fa5e5688c4..3d7433b639 100644 --- a/Task/Combinations/Julia/combinations.julia +++ b/Task/Combinations/Julia/combinations.julia @@ -1,3 +1,3 @@ -for i in @task combinations(1:5,3) -println(i) +for i in combinations(1:5,3) + print(i') end diff --git a/Task/Command-line-arguments/Deja-Vu/command-line-arguments.djv b/Task/Command-line-arguments/Deja-Vu/command-line-arguments.djv index 3fe96bed43..cffbc3d8ae 100644 --- a/Task/Command-line-arguments/Deja-Vu/command-line-arguments.djv +++ b/Task/Command-line-arguments/Deja-Vu/command-line-arguments.djv @@ -1,11 +1,9 @@ -try: - set :i 1 - while true: - drop dup # some stack manipulation to force - # a stack-empty error before printing - # the next line - print( "Argument #" i " is:" ) - . - set :i ++ i -catch stack-empty: - pass #end of argument list +for i range 0 -- len !args: + print\( "Argument #" i " is " ) + . get-from !args i + +if has !opts :c: + !print "Ah, the -c option." + +if has !opts :four: + !. get-from !opts :four diff --git a/Task/Command-line-arguments/OCaml/command-line-arguments-2.ocaml b/Task/Command-line-arguments/OCaml/command-line-arguments-2.ocaml index 099ad64e19..6fee579229 100644 --- a/Task/Command-line-arguments/OCaml/command-line-arguments-2.ocaml +++ b/Task/Command-line-arguments/OCaml/command-line-arguments-2.ocaml @@ -6,9 +6,9 @@ let someint = ref 0 let usage = "usage: " ^ Sys.argv.(0) ^ " [-b] [-s string] [-d int]" let speclist = [ - ("-b", Arg.Unit (fun () -> somebool := true), ": set somebool to true"); - ("-s", Arg.String (fun s -> somestr := s), ": what follows -s sets some string"); - ("-d", Arg.Int (fun d -> someint := d), ": some int parameter"); + ("-b", Arg.Set somebool, ": set somebool to true"); + ("-s", Arg.Set_string somestr, ": what follows -s sets some string"); + ("-d", Arg.Set_int someint, ": some int parameter"); ] let () = diff --git a/Task/Command-line-arguments/Rust/command-line-arguments-1.rust b/Task/Command-line-arguments/Rust/command-line-arguments-1.rust new file mode 100644 index 0000000000..5a053037d1 --- /dev/null +++ b/Task/Command-line-arguments/Rust/command-line-arguments-1.rust @@ -0,0 +1,5 @@ +use std::os; + +fn main(){ + println!("{:?}", os::args()); +} diff --git a/Task/Command-line-arguments/Rust/command-line-arguments-2.rust b/Task/Command-line-arguments/Rust/command-line-arguments-2.rust new file mode 100644 index 0000000000..51f063e956 --- /dev/null +++ b/Task/Command-line-arguments/Rust/command-line-arguments-2.rust @@ -0,0 +1,2 @@ +./program -c "alpha beta" -h "gamma" +~[~"./args", ~"-c", ~"alpha beta", ~"-h", ~"gamma"] diff --git a/Task/Comments/Deja-Vu/comments.djv b/Task/Comments/Deja-Vu/comments.djv new file mode 100644 index 0000000000..ff9f55ccb4 --- /dev/null +++ b/Task/Comments/Deja-Vu/comments.djv @@ -0,0 +1,2 @@ +#this is a comment +!print "this is not a comment, obviously" #this is a comment as well diff --git a/Task/Comments/Neko/comments.neko b/Task/Comments/Neko/comments.neko new file mode 100644 index 0000000000..1808fcca7c --- /dev/null +++ b/Task/Comments/Neko/comments.neko @@ -0,0 +1,4 @@ +// Single line comment, of course! +/* +Multi line comment! +*/ diff --git a/Task/Comments/Nimrod/comments.nimrod b/Task/Comments/Nimrod/comments.nimrod new file mode 100644 index 0000000000..a1b99fe4cd --- /dev/null +++ b/Task/Comments/Nimrod/comments.nimrod @@ -0,0 +1,14 @@ +# Nimrod supports only single-line comments + +var x = 0 ## Documentation comments start with double hash characters. + +var y = 0 ## Comments are a proper part of the syntax and are indentation sensitive. + ## If the next line only consists of a comment piece, it must be aligned + ## either to the preceding one (documentation generator would merge these lines) +## or to the code block (starting a new comment piece). + + # any misaligned comment line (like this one) would trigger an "invalid indentation" error + +var z = 0 ## Alternatively you can end the preceding comment piece with a backslash \ + ## to reset alignment to any column you like. + ## See also http://nimrod-code.org/tut1.html#comments diff --git a/Task/Comments/Rust/comments.rust b/Task/Comments/Rust/comments.rust new file mode 100644 index 0000000000..7edf021945 --- /dev/null +++ b/Task/Comments/Rust/comments.rust @@ -0,0 +1,39 @@ +// A single line comment + +/* + This is a multi-line (aka block) comment + + /* + containing nested multi-line comment + (nesting supported since 0.9-pre https://github.com/mozilla/rust/issues/9468) + */ +*/ + + +/// Outer single line Rustdoc comments apply to the next item. + +/** + Outer multi-line Rustdoc comments. + + * Leading asterisk (*) in multi-line Rustdoc comments + * is not considered to be part of the comment text, + * blanks and tabs preceding the initial asterisk (*) are also stripped. +*/ + +fn example() { + + //! Inner single line Rustdoc comments apply to their enclosing item. + + /*! + Inner multi-line Rustdoc comments. + See also https://github.com/mozilla/rust/wiki/Doc-using-rustdoc + */ +} + +#[doc = "Unsugared outer Rustdoc comments. + (outer attributes are not terminated by a semi-colon)"] +fn example() { + #[doc = "Unsugared inner Rustdoc comments. + (inner attributes are terminated by a semi-colon) + See also https://github.com/mozilla/rust/blob/master/doc/rust.md#attributes"]; +} diff --git a/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl b/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl index 9c9a4520b4..855559b6ce 100644 --- a/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl +++ b/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl @@ -1,4 +1,4 @@ --module( compare_sorting_algorithms_performance ). +-module( compare_sorting_algorithms ). -export( [task/0] ). diff --git a/Task/Compile-time-calculation/Julia/compile-time-calculation-1.julia b/Task/Compile-time-calculation/Julia/compile-time-calculation-1.julia new file mode 100644 index 0000000000..e0817cb0c1 --- /dev/null +++ b/Task/Compile-time-calculation/Julia/compile-time-calculation-1.julia @@ -0,0 +1,3 @@ +macro fact(n) + factorial(n) +end diff --git a/Task/Compile-time-calculation/Julia/compile-time-calculation-2.julia b/Task/Compile-time-calculation/Julia/compile-time-calculation-2.julia new file mode 100644 index 0000000000..066978c47b --- /dev/null +++ b/Task/Compile-time-calculation/Julia/compile-time-calculation-2.julia @@ -0,0 +1 @@ +foo() = @fact 10 diff --git a/Task/Compound-data-type/Python/compound-data-type-4.py b/Task/Compound-data-type/Python/compound-data-type-4.py index aec9631f30..0c1de10c7b 100644 --- a/Task/Compound-data-type/Python/compound-data-type-4.py +++ b/Task/Compound-data-type/Python/compound-data-type-4.py @@ -1,27 +1 @@ ->>> from collections import namedtuple ->>> help(namedtuple) -Help on function namedtuple in module collections: - -namedtuple(typename, field_names, verbose=False) - Returns a new subclass of tuple with named fields. - - >>> Point = namedtuple('Point', 'x y') - >>> Point.__doc__ # docstring for the new class - 'Point(x, y)' - >>> p = Point(11, y=22) # instantiate with positional args or keywords - >>> p[0] + p[1] # indexable like a plain tuple - 33 - >>> x, y = p # unpack like a regular tuple - >>> x, y - (11, 22) - >>> p.x + p.y # fields also accessable by name - 33 - >>> d = p._asdict() # convert to a dictionary - >>> d['x'] - 11 - >>> Point(**d) # convert from a dictionary - Point(x=11, y=22) - >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields - Point(x=100, y=22) - ->>> +pseudo_object = {'x': 1, 'y': 2} diff --git a/Task/Compound-data-type/Python/compound-data-type-5.py b/Task/Compound-data-type/Python/compound-data-type-5.py new file mode 100644 index 0000000000..aec9631f30 --- /dev/null +++ b/Task/Compound-data-type/Python/compound-data-type-5.py @@ -0,0 +1,27 @@ +>>> from collections import namedtuple +>>> help(namedtuple) +Help on function namedtuple in module collections: + +namedtuple(typename, field_names, verbose=False) + Returns a new subclass of tuple with named fields. + + >>> Point = namedtuple('Point', 'x y') + >>> Point.__doc__ # docstring for the new class + 'Point(x, y)' + >>> p = Point(11, y=22) # instantiate with positional args or keywords + >>> p[0] + p[1] # indexable like a plain tuple + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessable by name + 33 + >>> d = p._asdict() # convert to a dictionary + >>> d['x'] + 11 + >>> Point(**d) # convert from a dictionary + Point(x=11, y=22) + >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields + Point(x=100, y=22) + +>>> diff --git a/Task/Conditional-structures/AutoIt/conditional-structures-1.autoit b/Task/Conditional-structures/AutoIt/conditional-structures-1.autoit new file mode 100644 index 0000000000..4b8cf0391f --- /dev/null +++ b/Task/Conditional-structures/AutoIt/conditional-structures-1.autoit @@ -0,0 +1,10 @@ +If Then + statements + ... +[ElseIf expression-n Then + [elseif statements ... ]] + ... +[Else + [else statements] + ... +EndIf diff --git a/Task/Conditional-structures/AutoIt/conditional-structures-2.autoit b/Task/Conditional-structures/AutoIt/conditional-structures-2.autoit new file mode 100644 index 0000000000..930b437410 --- /dev/null +++ b/Task/Conditional-structures/AutoIt/conditional-structures-2.autoit @@ -0,0 +1,11 @@ +Select + Case + statement1 + ... + [Case + statement2 + ...] + [Case Else + statementN + ...] +EndSelect diff --git a/Task/Conditional-structures/AutoIt/conditional-structures-3.autoit b/Task/Conditional-structures/AutoIt/conditional-structures-3.autoit new file mode 100644 index 0000000000..eec28addcd --- /dev/null +++ b/Task/Conditional-structures/AutoIt/conditional-structures-3.autoit @@ -0,0 +1,11 @@ +Switch + Case [To ] [, [To ] ...] + statement1 + ... + [Case [To ] [, [To ] ...] + statement2 + ...] + [Case Else + statementN + ...] +EndSwitch diff --git a/Task/Conditional-structures/GAP/conditional-structures.gap b/Task/Conditional-structures/GAP/conditional-structures.gap new file mode 100644 index 0000000000..162f421209 --- /dev/null +++ b/Task/Conditional-structures/GAP/conditional-structures.gap @@ -0,0 +1,7 @@ +if then + +elif then + +else + +fi; diff --git a/Task/Conditional-structures/SNUSP/conditional-structures.snusp b/Task/Conditional-structures/SNUSP/conditional-structures-1.snusp similarity index 100% rename from Task/Conditional-structures/SNUSP/conditional-structures.snusp rename to Task/Conditional-structures/SNUSP/conditional-structures-1.snusp diff --git a/Task/Conditional-structures/SNUSP/conditional-structures-2.snusp b/Task/Conditional-structures/SNUSP/conditional-structures-2.snusp new file mode 100644 index 0000000000..5b9f149611 --- /dev/null +++ b/Task/Conditional-structures/SNUSP/conditional-structures-2.snusp @@ -0,0 +1,4 @@ +var odd = 13; +if odd % 2 != 0 { + print("odd"); +} diff --git a/Task/Conditional-structures/SNUSP/conditional-structures-3.snusp b/Task/Conditional-structures/SNUSP/conditional-structures-3.snusp new file mode 100644 index 0000000000..577f758cbf --- /dev/null +++ b/Task/Conditional-structures/SNUSP/conditional-structures-3.snusp @@ -0,0 +1,6 @@ +var odd = 13; +if odd % 2 != 0 { + print("odd"); +} else { + print("even"); +} diff --git a/Task/Conditional-structures/SNUSP/conditional-structures-4.snusp b/Task/Conditional-structures/SNUSP/conditional-structures-4.snusp new file mode 100644 index 0000000000..79634c588f --- /dev/null +++ b/Task/Conditional-structures/SNUSP/conditional-structures-4.snusp @@ -0,0 +1,8 @@ +var nodiv3 = 13; +if nodiv3 % 3 == 0 { + print("divisible by 3"); +} else if nodiv3 % 3 == 1 { + print("gives 1 remainder"); +} else { + print("gives 2 remainder"); +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c new file mode 100644 index 0000000000..0e32ba4507 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/C/continued-fraction-arithmetic-construct-from-rational-number.c @@ -0,0 +1,72 @@ +/*Abhishek Ghosh, 8th November 2013, Rotterdam*/ + +#include + +typedef struct{ + int num,den; + }fraction; + +fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; +fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}}; +fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}}; + +int r2cf(int *numerator,int *denominator) +{ + int quotient=0,temp; + + if(denominator != 0) + { + quotient = *numerator / *denominator; + + temp = *numerator; + + *numerator = *denominator; + + *denominator = temp % *denominator; + } + + return quotient; +} + +int main() +{ + int i; + + printf("Running the examples :"); + + for(i=0;i 0 ? 2 : 1, - 1); +int[2] fSqrt2(in int n) pure nothrow { + return [n > 0 ? 2 : 1, 1]; } -Pair fnapier(in int n) pure nothrow { - return Pair(n > 0 ? n : 2, - n > 1 ? (n - 1) : 1); +int[2] fNapier(in int n) pure nothrow { + return [n > 0 ? n : 2, n > 1 ? (n - 1) : 1]; } -Pair fpi(in int n) pure nothrow { - return Pair(n > 0 ? 6 : 3, - (2 * n - 1) ^^ 2); +int[2] fPi(in int n) pure nothrow { + return [n > 0 ? 6 : 3, (2 * n - 1) ^^ 2]; } +alias print = curry!(writefln, "%.19f"); + void main() { - import std.stdio; - - writefln("%.19f", calc!real(&fsqrt2, 200)); - writefln("%.19f", calc!real(&fnapier, 200)); - writefln("%.19f", calc!real(&fpi, 200)); + calc!real(&fSqrt2, 200).print; + calc!real(&fNapier, 200).print; + calc!real(&fPi, 200).print; } diff --git a/Task/Continued-fraction/Erlang/continued-fraction-1.erl b/Task/Continued-fraction/Erlang/continued-fraction-1.erl new file mode 100644 index 0000000000..ef419c9370 --- /dev/null +++ b/Task/Continued-fraction/Erlang/continued-fraction-1.erl @@ -0,0 +1,43 @@ +-module(continued). +-compile([export_all]). + +pi_a (0) -> 3; +pi_a (_N) -> 6. + +pi_b (N) -> + (2*N-1)*(2*N-1). + +sqrt2_a (0) -> + 1; +sqrt2_a (_N) -> + 2. + +sqrt2_b (_N) -> + 1. + +nappier_a (0) -> + 2; +nappier_a (N) -> + N. + +nappier_b (1) -> + 1; +nappier_b (N) -> + N-1. + +continued_fraction(FA,_FB,0) -> FA(0); +continued_fraction(FA,FB,N) -> + continued_fraction(FA,FB,N-1,FB(N)/FA(N)). + +continued_fraction(FA,_FB,0,Acc) -> FA(0) + Acc; +continued_fraction(FA,FB,N,Acc) -> + continued_fraction(FA,FB,N-1,FB(N)/ (FA(N) + Acc)). + +test_pi (N) -> + continued_fraction(fun pi_a/1,fun pi_b/1,N). + +test_sqrt2 (N) -> + continued_fraction(fun sqrt2_a/1,fun sqrt2_b/1,N). + +test_nappier (N) -> + continued_fraction(fun nappier_a/1,fun nappier_b/1,N). diff --git a/Task/Continued-fraction/Erlang/continued-fraction-2.erl b/Task/Continued-fraction/Erlang/continued-fraction-2.erl new file mode 100644 index 0000000000..c9f47a97ee --- /dev/null +++ b/Task/Continued-fraction/Erlang/continued-fraction-2.erl @@ -0,0 +1,6 @@ +29> continued:test_pi(1000). +3.141592653340542 +30> continued:test_sqrt2(1000). +1.4142135623730951 +31> continued:test_nappier(1000). +2.7182818284590455 diff --git a/Task/Continued-fraction/Fortran/continued-fraction.f b/Task/Continued-fraction/Fortran/continued-fraction.f new file mode 100644 index 0000000000..cebf437b9f --- /dev/null +++ b/Task/Continued-fraction/Fortran/continued-fraction.f @@ -0,0 +1,99 @@ +module continued_fractions + implicit none + + integer, parameter :: long = selected_real_kind(7,99) + + type continued_fraction + integer :: a0, b1 + procedure(series), pointer, nopass :: a, b + end type + + interface + pure function series (n) + integer, intent(in) :: n + integer :: series + end function + end interface + +contains + + pure function define_cf (a0,a,b1,b) result(x) + integer, intent(in) :: a0 + procedure(series) :: a + integer, intent(in), optional :: b1 + procedure(series), optional :: b + type(continued_fraction) :: x + x%a0 = a0 + x%a => a + if ( present(b1) ) then + x%b1 = b1 + else + x%b1 = 1 + end if + if ( present(b) ) then + x%b => b + else + x%b => const_1 + end if + end function define_cf + + pure integer function const_1(n) + integer,intent(in) :: n + const_1 = 1 + end function + + pure real(kind=long) function output(x,iterations) + type(continued_fraction), intent(in) :: x + integer, intent(in) :: iterations + integer :: i + output = x%a(iterations) + do i = iterations-1,1,-1 + output = x%a(i) + (x%b(i+1) / output) + end do + output = x%a0 + (x%b1 / output) + end function output + +end module continued_fractions + + +program examples + use continued_fractions + + type(continued_fraction) :: sqr2,napier,pi + + sqr2 = define_cf(1,a_sqr2) + napier = define_cf(2,a_napier,1,b_napier) + pi = define_cf(3,a=a_pi,b=b_pi) + + write (*,*) output(sqr2,10000) + write (*,*) output(napier,10000) + write (*,*) output(pi,10000) + +contains + + pure integer function a_sqr2(n) + integer,intent(in) :: n + a_sqr2 = 2 + end function + + pure integer function a_napier(n) + integer,intent(in) :: n + a_napier = n + end function + + pure integer function b_napier(n) + integer,intent(in) :: n + b_napier = n-1 + end function + + pure integer function a_pi(n) + integer,intent(in) :: n + a_pi = 6 + end function + + pure integer function b_pi(n) + integer,intent(in) :: n + b_pi = (2*n-1)*(2*n-1) + end function + +end program examples diff --git a/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j b/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j index 31f60b3a99..0e8a5d3e72 100644 --- a/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j +++ b/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j @@ -1,4 +1,4 @@ pad=: 0,0,~0,.0,.~] life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@pad -# Note: the above could also be a one-line solution: +NB. the above could also be a one-line solution: life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~]) diff --git a/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java b/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java new file mode 100644 index 0000000000..deb39dc6bb --- /dev/null +++ b/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java @@ -0,0 +1,277 @@ +import java.awt.*; +import java.awt.event.*; +import java.net.URI; +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import javax.swing.*; + +public class ConwaysGameOfLife extends JFrame implements ActionListener { + private static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(800, 600); + private static final Dimension MINIMUM_WINDOW_SIZE = new Dimension(400, 400); + private static final int BLOCK_SIZE = 10; + private static final int SCREEN_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width; + private static final int SCREEN_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height; + private JMenuBar mb_menu; + private JMenu m_file, m_game; + private JMenuItem mi_file_options, mi_file_exit, mi_game_autofill, mi_game_play, mi_game_stop, mi_game_reset; + private int i_movesPerSecond = 3; + private GameBoard gb_gameBoard; + private Thread game; + + public static void main(String[] args) { + JFrame game = new ConwaysGameOfLife(); + game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + game.setTitle("Conway's Game of Life"); + game.setSize(DEFAULT_WINDOW_SIZE); + game.setMinimumSize(MINIMUM_WINDOW_SIZE); + game.setLocation((SCREEN_WIDTH - game.getWidth())/2, (SCREEN_HEIGHT - game.getHeight())/2); + game.setVisible(true); + } + + public ConwaysGameOfLife() { + mb_menu = new JMenuBar(); + setJMenuBar(mb_menu); + m_file = new JMenu("File"); + mb_menu.add(m_file); + m_game = new JMenu("Game"); + mb_menu.add(m_game); + mi_file_options = new JMenuItem("Options"); + mi_file_options.addActionListener(this); + mi_file_exit = new JMenuItem("Exit"); + mi_file_exit.addActionListener(this); + m_file.add(mi_file_options); + m_file.add(new JSeparator()); + m_file.add(mi_file_exit); + mi_game_autofill = new JMenuItem("Autofill"); + mi_game_autofill.addActionListener(this); + mi_game_play = new JMenuItem("Play"); + mi_game_play.addActionListener(this); + mi_game_stop = new JMenuItem("Stop"); + mi_game_stop.setEnabled(false); + mi_game_stop.addActionListener(this); + mi_game_reset = new JMenuItem("Reset"); + mi_game_reset.addActionListener(this); + m_game.add(mi_game_autofill); + m_game.add(new JSeparator()); + m_game.add(mi_game_play); + m_game.add(mi_game_stop); + m_game.add(mi_game_reset); + gb_gameBoard = new GameBoard(); + add(gb_gameBoard); + } + + public void setGameBeingPlayed(boolean isBeingPlayed) { + if (isBeingPlayed) { + mi_game_play.setEnabled(false); + mi_game_stop.setEnabled(true); + game = new Thread(gb_gameBoard); + game.start(); + } else { + mi_game_play.setEnabled(true); + mi_game_stop.setEnabled(false); + game.interrupt(); + } + } + + @Override + public void actionPerformed(ActionEvent ae) { + if (ae.getSource().equals(mi_file_exit)) { + System.exit(0); + } else if (ae.getSource().equals(mi_file_options)) { + final JFrame f_options = new JFrame(); + f_options.setTitle("Options"); + f_options.setSize(300,60); + f_options.setLocation((SCREEN_WIDTH - f_options.getWidth())/2, (SCREEN_HEIGHT - f_options.getHeight())/2); + f_options.setResizable(false); + JPanel p_options = new JPanel(); + p_options.setOpaque(false); + f_options.add(p_options); + p_options.add(new JLabel("Number of moves per second:")); + Integer[] secondOptions = {1,2,3,4,5,10,15,20}; + final JComboBox cb_seconds = new JComboBox(secondOptions); + p_options.add(cb_seconds); + cb_seconds.setSelectedItem(i_movesPerSecond); + cb_seconds.addActionListener(new ActionListener(){ + @Override + public void actionPerformed(ActionEvent ae) { + i_movesPerSecond = (Integer)cb_seconds.getSelectedItem(); + f_options.dispose(); + } + }); + f_options.setVisible(true); + } else if (ae.getSource().equals(mi_game_autofill)) { + final JFrame f_autoFill = new JFrame(); + f_autoFill.setTitle("Autofill"); + f_autoFill.setSize(360, 60); + f_autoFill.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - f_autoFill.getWidth())/2, + (Toolkit.getDefaultToolkit().getScreenSize().height - f_autoFill.getHeight())/2); + f_autoFill.setResizable(false); + JPanel p_autoFill = new JPanel(); + p_autoFill.setOpaque(false); + f_autoFill.add(p_autoFill); + p_autoFill.add(new JLabel("What percentage should be filled? ")); + Object[] percentageOptions = {"Select",5,10,15,20,25,30,40,50,60,70,80,90,95}; + final JComboBox cb_percent = new JComboBox(percentageOptions); + p_autoFill.add(cb_percent); + cb_percent.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (cb_percent.getSelectedIndex() > 0) { + gb_gameBoard.resetBoard(); + gb_gameBoard.randomlyFillBoard((Integer)cb_percent.getSelectedItem()); + f_autoFill.dispose(); + } + } + }); + f_autoFill.setVisible(true); + } else if (ae.getSource().equals(mi_game_reset)) { + gb_gameBoard.resetBoard(); + gb_gameBoard.repaint(); + } else if (ae.getSource().equals(mi_game_play)) { + setGameBeingPlayed(true); + } else if (ae.getSource().equals(mi_game_stop)) { + setGameBeingPlayed(false); + } + } + + private class GameBoard extends JPanel implements ComponentListener, MouseListener, MouseMotionListener, Runnable { + private Dimension d_gameBoardSize = null; + private ArrayList point = new ArrayList(0); + + public GameBoard() { + addComponentListener(this); + addMouseListener(this); + addMouseMotionListener(this); + } + + private void updateArraySize() { + ArrayList removeList = new ArrayList(0); + for (Point current : point) { + if ((current.x > d_gameBoardSize.width-1) || (current.y > d_gameBoardSize.height-1)) { + removeList.add(current); + } + } + point.removeAll(removeList); + repaint(); + } + + public void addPoint(int x, int y) { + if (!point.contains(new Point(x,y))) { + point.add(new Point(x,y)); + } + repaint(); + } + + public void addPoint(MouseEvent me) { + int x = me.getPoint().x/10-1; + int y = me.getPoint().y/10-1; + if ((x >= 0) && (x < d_gameBoardSize.width) && (y >= 0) && (y < d_gameBoardSize.height)) { + addPoint(x,y); + } + } + + public void removePoint(int x, int y) { + point.remove(new Point(x,y)); + } + + public void resetBoard() { + point.clear(); + } + + public void randomlyFillBoard(int percent) { + for (int i=0; i survivingCells = new ArrayList(0); + for (int i=1; i + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + _ + + + + X + diff --git a/Task/Conways-Game-of-Life/XSLT/conways-game-of-life-2.xslt b/Task/Conways-Game-of-Life/XSLT/conways-game-of-life-2.xslt new file mode 100644 index 0000000000..b634540670 --- /dev/null +++ b/Task/Conways-Game-of-Life/XSLT/conways-game-of-life-2.xslt @@ -0,0 +1,5 @@ + + + + +
_X_
_X_
_X_
diff --git a/Task/Conways-Game-of-Life/XSLT/conways-game-of-life-3.xslt b/Task/Conways-Game-of-Life/XSLT/conways-game-of-life-3.xslt new file mode 100644 index 0000000000..7a75b2b3e2 --- /dev/null +++ b/Task/Conways-Game-of-Life/XSLT/conways-game-of-life-3.xslt @@ -0,0 +1,5 @@ + + + + +
___
XXX
___
diff --git a/Task/Copy-a-string/BASIC/copy-a-string-1.basic b/Task/Copy-a-string/BASIC/copy-a-string-1.basic new file mode 100644 index 0000000000..ff6f604a0b --- /dev/null +++ b/Task/Copy-a-string/BASIC/copy-a-string-1.basic @@ -0,0 +1,4 @@ +100 DEF FN P(A) = PEEK (A) + PEEK(A + 1) * 256 : FOR I = FN P(105) TO FN P(107) - 1 STEP 7 : ON PEEK(I + 1) < 128 OR PEEK(I) > 127 GOTO 130 : ON LEFT$(P$, 1) <> CHR$(PEEK(I)) GOTO 130 +110 IF LEN(P$) > 1 THEN ON PEEK(I + 1) = 128 GOTO 130 : IF MID$(P$, 2, 1) <> CHR$(PEEK(I + 1) - 128) GOTO 130 +120 POKE I + 4, P / 256 : POKE I + 3, P - PEEK(I + 4) * 256 : RETURN +130 NEXT I : STOP diff --git a/Task/Copy-a-string/BASIC/copy-a-string-2.basic b/Task/Copy-a-string/BASIC/copy-a-string-2.basic new file mode 100644 index 0000000000..c347fbc45a --- /dev/null +++ b/Task/Copy-a-string/BASIC/copy-a-string-2.basic @@ -0,0 +1,2 @@ +S$ = "HELLO" : REM S$ IS THE ORIGINAL STRING +C$ = S$ : REM C$ IS THE COPY diff --git a/Task/Copy-a-string/BASIC/copy-a-string-3.basic b/Task/Copy-a-string/BASIC/copy-a-string-3.basic new file mode 100644 index 0000000000..876eb4100d --- /dev/null +++ b/Task/Copy-a-string/BASIC/copy-a-string-3.basic @@ -0,0 +1,3 @@ +P$ = "S" : P = 53637 : GOSUB 100"POINT STRING S AT SOMETHING ELSE +?S$ +?C$ diff --git a/Task/Copy-a-string/C++/copy-a-string.cpp b/Task/Copy-a-string/C++/copy-a-string.cpp index 18f0a2ec3a..24465c712f 100644 --- a/Task/Copy-a-string/C++/copy-a-string.cpp +++ b/Task/Copy-a-string/C++/copy-a-string.cpp @@ -1,13 +1,10 @@ #include #include -#include int main( ) { - std::string original ( "This is the original" ) ; - std::string mycopy( original.length( ) , ' ' ) ; - std::copy ( original.begin( ) , original.end( ) , mycopy.begin( ) ) ; - std::cout << "This is the copy: " << mycopy << std::endl ; - original.assign( "Now we change the original! " ) ; - std::cout << "mycopy still is " << mycopy << std::endl ; - return 0 ; + std::string original ("This is the original"); + std::string my_copy = original; + std::cout << "This is the copy: " << my_copy << std::endl; + original = "Now we change the original! "; + std::cout << "my_copy still is " << my_copy << std::endl; } diff --git a/Task/Copy-a-string/Deja-Vu/copy-a-string.djv b/Task/Copy-a-string/Deja-Vu/copy-a-string.djv new file mode 100644 index 0000000000..ab7730194c --- /dev/null +++ b/Task/Copy-a-string/Deja-Vu/copy-a-string.djv @@ -0,0 +1,3 @@ +local :orgininal "this is the original" +local :scopy concat( original "" ) +!. scopy diff --git a/Task/Copy-a-string/GML/copy-a-string.gml b/Task/Copy-a-string/GML/copy-a-string.gml index 5669d8cecc..166c9e3823 100644 --- a/Task/Copy-a-string/GML/copy-a-string.gml +++ b/Task/Copy-a-string/GML/copy-a-string.gml @@ -1,2 +1,2 @@ -src = "string" -dest = src +src = "string"; +dest = src; diff --git a/Task/Copy-a-string/REXX/copy-a-string.rexx b/Task/Copy-a-string/REXX/copy-a-string.rexx index 6d7223de5c..cb58d9bd01 100644 --- a/Task/Copy-a-string/REXX/copy-a-string.rexx +++ b/Task/Copy-a-string/REXX/copy-a-string.rexx @@ -1,2 +1,3 @@ src = "this is a string" +

Note that all REXX values (variables) are stored as character strings. dst = src diff --git a/Task/Count-in-factors/NetRexx/count-in-factors.netrexx b/Task/Count-in-factors/NetRexx/count-in-factors.netrexx new file mode 100644 index 0000000000..6ea21e8db5 --- /dev/null +++ b/Task/Count-in-factors/NetRexx/count-in-factors.netrexx @@ -0,0 +1,52 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method factor(val) public static + rv = 1 + if val > 1 then do + rv = '' + loop n_ = val until n_ = 1 + parse checkFactor(2, n_, rv) n_ rv + if n_ = 1 then leave n_ + parse checkFactor(3, n_, rv) n_ rv + if n_ = 1 then leave n_ + loop m_ = 5 to n_ by 2 until n_ = 1 + if m_ // 3 = 0 then iterate m_ + parse checkFactor(m_, n_, rv) n_ rv + end m_ + end n_ + end + return rv + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method checkFactor(mult = long, n_ = long, fac) private static binary + msym = 'x' + loop while n_ // mult = 0 + fac = fac msym mult + n_ = n_ % mult + end + fac = (fac.strip).strip('l', msym).space + return n_ fac + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + -- input is a list of pairs of numbers - no checking is done + if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' + loop while arg \= '' + parse arg lv rv arg + say + say '-'.copies(60) + say lv.right(8) 'to' rv + say '-'.copies(60) + loop fv = lv to rv + fac = factor(fv) + pv = '' + if fac.words = 1 & fac \= 1 then pv = '' + say fv.right(8) '=' fac pv + end fv + end + return diff --git a/Task/Count-in-factors/REXX/count-in-factors.rexx b/Task/Count-in-factors/REXX/count-in-factors.rexx index 0aee4957ae..ddca145f2a 100644 --- a/Task/Count-in-factors/REXX/count-in-factors.rexx +++ b/Task/Count-in-factors/REXX/count-in-factors.rexx @@ -1,20 +1,25 @@ /*REXX program lists the prime factors of a specified integer (or range)*/ +@.=left('',8); @.0='{unity} '; @.1='[prime] ' /*unity & prime tags.*/ parse arg low high . /*get the argument(s) from the CL*/ if low=='' then do;low=1;high=40;end /*No LOW&HIGH? Then use default.*/ -if high=='' then high=low /*No HIGH? Then use the LOW.*/ -w=length(high) /*get max width for pretty tell. */ +if high=='' then high=low; oHigh=high /*No HIGH? Then use the LOW.*/ +w=length(high); high=abs(high) /*get max width for pretty tell. */ numeric digits max(9,w+1) /*maybe bump precision of numbers*/ blanks=1 /*1=allow spaces around the "x".*/ +primes=0 /*number of primes detected. */ do n=low to high /*process single number | a range*/ - y=space(factr(n),blanks) /*squish (or not) the blanks. */ - say right(n,w) '=' left('',9*(words(y)\==1|n==1)) y /*factors.*/ - /* ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ indentation.*/ - end /*n*/ /*if BLANKS=0, no spaces around X*/ + y=factr(n); /*squish (or not) the blanks. */ + #=words(translate(y,,'x')) - (n==1) /*# of prime factors. */ + if #==1 then primes=primes+1 /*bump primes counter (exlude 1).*/ + if high\==oHigh then iterate /*only show facters of HIGH is >0*/ + say right(n,w) '=' @.# space(y,blanks) /*prime flag, factors.*/ + end /*n*/ /*if BLANKS=0, no spaces around X*/ +say +say right(primes,w) ' primes found.' /*display number of primes found.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────FACTR subroutine────────────────────*/ factr: procedure; parse arg x; x=abs(x); z=x /*insure X is positive.*/ if x<2 then return x /*handle a couple special cases. */ -Xtimes= 'x' /*character used for "times" (x).*/ list= /*nullify the list (empty string)*/ /* [↓] process some low primes. */ do j=2 to 5; if j\==4 then call .buildF; end /*factorize, put──►list*/ @@ -27,10 +32,10 @@ list= /*nullify the list (empty string)*/ end /*y*/ if z==1 then z= /*if residual is = 1, nullify it.*/ -return strip(strip(list Xtimes z),,Xtimes) /*elide any leading "x". */ +return strip(strip(list 'x' z),,"x") /*elide a possible leading "x". */ /*──────────────────────────────────.BUILDF subroutine──────────────────*/ .buildF: do while z//j==0 /*keep dividing until it hurts. */ - list=list Xtimes j /*add number to the list (J). */ + list=list 'x' j /*add number to the list (J). */ z=z%j /*do an integer divide. */ end /*while*/ return diff --git a/Task/Count-in-octal/BASIC/count-in-octal-3.basic b/Task/Count-in-octal/BASIC/count-in-octal-3.basic new file mode 100644 index 0000000000..21c712f499 --- /dev/null +++ b/Task/Count-in-octal/BASIC/count-in-octal-3.basic @@ -0,0 +1,13 @@ +10 N$ = "0" + +100 O$ = N$ +110 PRINT O$ +120 N$ = "" +130 C = 1 +140 FOR I = LEN(O$) TO 1 STEP -1 +150 N = VAL(MID$(O$, I, 1)) + C +160 C = N >= 8 +170 N$ = STR$(N - C * 8) + N$ +180 NEXT I +190 IF C THEN N$ = "1" + N$ +200 GOTO 100 diff --git a/Task/Count-in-octal/PL-I/count-in-octal.pli b/Task/Count-in-octal/PL-I/count-in-octal-1.pli similarity index 100% rename from Task/Count-in-octal/PL-I/count-in-octal.pli rename to Task/Count-in-octal/PL-I/count-in-octal-1.pli diff --git a/Task/Count-in-octal/PL-I/count-in-octal-2.pli b/Task/Count-in-octal/PL-I/count-in-octal-2.pli new file mode 100644 index 0000000000..3f51bc2d55 --- /dev/null +++ b/Task/Count-in-octal/PL-I/count-in-octal-2.pli @@ -0,0 +1,11 @@ +count: procedure options (main); /* 12 Jan. 2014 */ + declare (i, j) fixed binary; + + do i = 0 upthru 2147483647; + do j = 30 to 0 by -3; + put edit (iand(isrl(i, j), 7) ) (f(1)); + end; + put skip; + end; + +end count; diff --git a/Task/Count-in-octal/Rust/count-in-octal.rust b/Task/Count-in-octal/Rust/count-in-octal.rust new file mode 100644 index 0000000000..6cedd7178e --- /dev/null +++ b/Task/Count-in-octal/Rust/count-in-octal.rust @@ -0,0 +1,9 @@ +// rust 0.9-pre + +use std::uint; + +fn main() { + for i in range(uint::min_value, uint::max_value) { + println!("{:o}", i); + } +} diff --git a/Task/Count-in-octal/VBA/count-in-octal.vba b/Task/Count-in-octal/VBA/count-in-octal.vba new file mode 100644 index 0000000000..dca0b2a785 --- /dev/null +++ b/Task/Count-in-octal/VBA/count-in-octal.vba @@ -0,0 +1,11 @@ +Sub CountOctal() +Dim i As Integer +i = 0 +On Error GoTo OctEnd +Do + Debug.Print Oct(i) + i = i + 1 +Loop +OctEnd: +Debug.Print "Integer overflow - count terminated" +End Sub diff --git a/Task/Count-occurrences-of-a-substring/00DESCRIPTION b/Task/Count-occurrences-of-a-substring/00DESCRIPTION index e51d7b5483..5110419319 100644 --- a/Task/Count-occurrences-of-a-substring/00DESCRIPTION +++ b/Task/Count-occurrences-of-a-substring/00DESCRIPTION @@ -1,4 +1,4 @@ -The task is to either create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments: the first argument being the string to search and the second a substring to be search for. It should return an integer count. +The task is to either create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments: the first argument being the string to search and the second a substring to be searched for. It should return an integer count. print countSubstring("the three truths","th") 3 diff --git a/Task/Count-occurrences-of-a-substring/VBA/count-occurrences-of-a-substring.vba b/Task/Count-occurrences-of-a-substring/VBA/count-occurrences-of-a-substring.vba new file mode 100644 index 0000000000..60b556fc02 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/VBA/count-occurrences-of-a-substring.vba @@ -0,0 +1,3 @@ +Function CountStringInString(stLookIn As String, stLookFor As String) + CountStringInString = UBound(Split(stLookIn, stLookFor)) +End Function diff --git a/Task/Count-the-coins/D/count-the-coins-4.d b/Task/Count-the-coins/D/count-the-coins-4.d new file mode 100644 index 0000000000..73cb6a7fdd --- /dev/null +++ b/Task/Count-the-coins/D/count-the-coins-4.d @@ -0,0 +1,32 @@ +import std.stdio, std.conv, std.string, std.algorithm, std.range; + +void printChange(in uint tot, in uint[] coins) +in { + assert(coins.isSorted); +} body { + auto freqs = new uint[coins.length]; + + void inner(in uint curTot, in size_t start) { + if (curTot == tot) + return writefln("%-(%s %)", + zip(coins, freqs) + .filter!(cf => cf[1] != 0) + .map!(cf => format("%u:%u", cf[]))); + + foreach (immutable i; start .. coins.length) { + immutable ci = coins[i]; + for (auto v = (freqs[i] + 1) * ci; v <= tot; v += ci) + if (curTot + v <= tot) { + freqs[i] += v / ci; + inner(curTot + v, i + 1); + freqs[i] -= v / ci; + } + } + } + + inner(0, 0); +} + +void main() { + printChange(1_00, [1, 5, 10, 25]); +} diff --git a/Task/Create-a-file-on-magnetic-tape/Applesoft-BASIC/create-a-file-on-magnetic-tape.applesoft b/Task/Create-a-file-on-magnetic-tape/Applesoft-BASIC/create-a-file-on-magnetic-tape.applesoft new file mode 100644 index 0000000000..79ab64e6a4 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Applesoft-BASIC/create-a-file-on-magnetic-tape.applesoft @@ -0,0 +1 @@ +SAVE diff --git a/Task/Create-a-file-on-magnetic-tape/PicoLisp/create-a-file-on-magnetic-tape.l b/Task/Create-a-file-on-magnetic-tape/PicoLisp/create-a-file-on-magnetic-tape.l new file mode 100644 index 0000000000..f4e067460d --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/PicoLisp/create-a-file-on-magnetic-tape.l @@ -0,0 +1,2 @@ +(out "/dev/tape" + (prin "Hello World!") ) diff --git a/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx b/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx new file mode 100644 index 0000000000..1cadad83d5 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx @@ -0,0 +1,16 @@ +/*REXX pgm demonstrates writing records to an attached magnetic tape.*/ +/* The actual mounting & attaching would be performed by the appropriate*/ +/* operating system (and/or user) commands. DSNAME (below) would be */ +/* the REXX variable that is associated with a dataset that is assigned */ +/* to a magnetic tape device. The association would be different, */ +/* depending on upon the operating system being used. VM/CMS would use */ +/* a CP ATTACH command, coupled with a CMS FILEDEF command which*/ +/* associates a DSNAME (dataset name) that will be written to on the */ +/* attached (and mounted) magnetic tape device. */ + +dsName = 'TAPE.FILE' /*dsName of "file" being written.*/ + + do j=1 for 100 /*write 100 records to mag tape. */ + call lineout dsName, 'this is record' j || "." + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Create-a-file-on-magnetic-tape/Scala/create-a-file-on-magnetic-tape.scala b/Task/Create-a-file-on-magnetic-tape/Scala/create-a-file-on-magnetic-tape.scala new file mode 100644 index 0000000000..9ec14de333 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Scala/create-a-file-on-magnetic-tape.scala @@ -0,0 +1,8 @@ +object LinePrinter extends App { + import java.io.{ FileWriter, IOException } + { + val lp0 = new FileWriter("/dev/tape") + lp0.write("Hello, world!") + lp0.close() + } +} diff --git a/Task/Create-a-file-on-magnetic-tape/UNIX-Shell/create-a-file-on-magnetic-tape.sh b/Task/Create-a-file-on-magnetic-tape/UNIX-Shell/create-a-file-on-magnetic-tape.sh index 401f7cced7..28ed06e245 100644 --- a/Task/Create-a-file-on-magnetic-tape/UNIX-Shell/create-a-file-on-magnetic-tape.sh +++ b/Task/Create-a-file-on-magnetic-tape/UNIX-Shell/create-a-file-on-magnetic-tape.sh @@ -2,5 +2,5 @@ cd # Make our home directory current echo "Hello World!" > hello.jnk # Create a junk file # tape rewind # Uncomment this to rewind the tape -tar c hello.jnk # Traditonal archivers use magnetic tape by default +tar c hello.jnk # Traditional archivers use magnetic tape by default # tar c hello.jnk > /dev/tape # With newer archivers redirection is needed diff --git a/Task/Create-a-file/REXX/create-a-file.rexx b/Task/Create-a-file/REXX/create-a-file.rexx index 2424c5a38b..8869c5ac1b 100644 --- a/Task/Create-a-file/REXX/create-a-file.rexx +++ b/Task/Create-a-file/REXX/create-a-file.rexx @@ -1,4 +1,7 @@ - do 2 - 'COPY NUL>output.txt' - 'CD \' - end +/*REXX pgm creates a new empty file and directory; in curr dir and root.*/ + do 2 /*perform three statements twice.*/ + 'COPY NUL output.txt' /*copy a "null" (empty) file. */ + 'MKDIR DOCS' /*make a directory (aka: folder).*/ + 'CD \' /*change currect dir to the root.*/ + end /*2*/ /*now, go and perform them again.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/DNS-query/Go/dns-query.go b/Task/DNS-query/Go/dns-query.go new file mode 100644 index 0000000000..388858346b --- /dev/null +++ b/Task/DNS-query/Go/dns-query.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "net" +) + +func main() { + if addrs, err := net.LookupHost("www.kame.net"); err == nil { + fmt.Println(addrs) + } else { + fmt.Println(err) + } +} diff --git a/Task/DNS-query/Groovy/dns-query-1.groovy b/Task/DNS-query/Groovy/dns-query-1.groovy new file mode 100644 index 0000000000..d67b0256bd --- /dev/null +++ b/Task/DNS-query/Groovy/dns-query-1.groovy @@ -0,0 +1,3 @@ +def addresses = InetAddress.getAllByName('www.kame.net') +println "IPv4: ${addresses.find { it instanceof Inet4Address }?.hostAddress}" +println "IPv6: ${addresses.find { it instanceof Inet6Address }?.hostAddress}" diff --git a/Task/DNS-query/Groovy/dns-query-2.groovy b/Task/DNS-query/Groovy/dns-query-2.groovy new file mode 100644 index 0000000000..64baaaa7e7 --- /dev/null +++ b/Task/DNS-query/Groovy/dns-query-2.groovy @@ -0,0 +1,16 @@ +module Main where + +import Network.Socket + +getWebAddresses :: HostName -> IO [SockAddr] +getWebAddresses host = do + results <- getAddrInfo (Just defaultHints) (Just host) (Just "http") + return [ addrAddress a | a <- results, addrSocketType a == Stream ] + +showIPs :: HostName -> IO () +showIPs host = do + putStrLn $ "IP addresses for " ++ host ++ ":" + addresses <- getWebAddresses host + mapM_ (putStrLn . (" "++) . show) addresses + +main = showIPs "www.kame.net" diff --git a/Task/DNS-query/Groovy/dns-query-3.groovy b/Task/DNS-query/Groovy/dns-query-3.groovy new file mode 100644 index 0000000000..78757db877 --- /dev/null +++ b/Task/DNS-query/Groovy/dns-query-3.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/DNS-query/REXX/dns-query.rexx b/Task/DNS-query/REXX/dns-query.rexx new file mode 100644 index 0000000000..94ee61cc35 --- /dev/null +++ b/Task/DNS-query/REXX/dns-query.rexx @@ -0,0 +1,16 @@ +/*REXX pgm displays IPv4 and IPv6 addresses for a supplied domain name. */ +trace off /*don't show the PING return code*/ +parse arg dn . /*get the optional domain name. */ +if dn=='' then dn='www.kame.net' /*Not specified? Then use default*/ +tmp='\TEMP\TEMP.PING' /*define temp file to store IPv4.*/ + + do j=4 to 6 by 2 /*handle IPv4 and IPv6 addresses.*/ + 'PING' (-j) '-l 0 -n 1' dn ">" tmp /*restrict PING's output to min. */ + q=charin(tmp,1,999) /*read output file from PING cmd.*/ + parse var q '[' IPA ']' /*parse IP a ddress from output.*/ + say 'IPv'j 'for domain name ' dn " is " IPA /*IPv4 | IPv6 addr.*/ + call lineout tmp /*needed by most REXXes to force */ + end /*j*/ /* [↑] file integrity. */ + +'ERASE' tmp /*clean up the temporary file. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Date-format/AutoIt/date-format.autoit b/Task/Date-format/AutoIt/date-format.autoit new file mode 100644 index 0000000000..7f83e3d9d9 --- /dev/null +++ b/Task/Date-format/AutoIt/date-format.autoit @@ -0,0 +1,31 @@ +#include + +$iYear = 2007 +$iMonth = 11 +$iDay = 10 + +ConsoleWrite(StringFormat('%4d-%02d-%02d', $iYear, $iMonth, $iDay) & @LF) + +$iWeekDay = _DateToDayOfWeekISO($iYear, $iMonth, $iDay) +ConsoleWrite(StringFormat('%s, %s %02d, %4d', _GetLongDayLocale($iWeekDay), _GetLongMonthLocale($iMonth), $iDay, $iYear) & @LF) + + +Func _GetLongDayLocale($_iWeekDay) ; 1..7 Monday=1 + Local $aDayName[8] = [0, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30] + Return GetLocaleInfo($aDayName[$_iWeekDay]) +EndFunc + +Func _GetLongMonthLocale($_iMonth) ; 1..12 January=1 + Local $aMonthName[13] = [0, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43] + Return GetLocaleInfo($aMonthName[$_iMonth]) +EndFunc + +Func GetLocaleInfo($_LCType) + Local $ret, $LCID, $sBuffer, $iLen + $ret = DllCall('kernel32', 'long', 'GetSystemDefaultLCID') + $LCID = $ret[0] + $ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', 0) + $iLen = $ret[0] + $ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', $iLen) + Return $ret[3] +EndFunc diff --git a/Task/Date-format/PL-I/date-format-1.pli b/Task/Date-format/PL-I/date-format-1.pli new file mode 100644 index 0000000000..b414f373b8 --- /dev/null +++ b/Task/Date-format/PL-I/date-format-1.pli @@ -0,0 +1,15 @@ +df: proc Options(main); + declare day_of_week(7) character (9) varying initial( + 'Sunday','Monday','Tuesday','Wednesday', + 'Thursday','Friday','Saturday'); + declare today character (9); + + today = datetime('YYYYMMDD'); + put edit(substr(today,1,4),'-',substr(today,5,2),'-',substr(today,7)) + (A); + + today = datetime('MmmDDYYYY'); + put skip edit(day_of_week(weekday(days())),', ') (A); + put edit(substr(today,1,3),' ',substr(today,4,2),', ', + substr(today,6,4))(A); + end; diff --git a/Task/Date-format/PL-I/date-format-2.pli b/Task/Date-format/PL-I/date-format-2.pli new file mode 100644 index 0000000000..0da3a9c59f --- /dev/null +++ b/Task/Date-format/PL-I/date-format-2.pli @@ -0,0 +1,16 @@ + df: proc Options(Main); + declare day_of_week(7) character(9) varying initial( + 'Sunday','Monday','Tuesday','Wednesday', + 'Thursday','Friday','Saturday'); + declare today character(8); + declare month(12) character(10) varying initial( + 'January','February','March','April','May','June','July', + 'August','September','October','November','December'); + + Put edit(translate('abcd-ef-gh',datetime('YYYYMMDD'),'abcdefgh'))(a); + today = datetime('MMDDYYYY'); + + put skip edit(day_of_week(weekday()),', ') (A); + put edit(month(substr(today,1,2)),' ',substr(today,3,2),', ', + substr(today,5,4))(A); + End; diff --git a/Task/Date-format/PL-I/date-format.pli b/Task/Date-format/PL-I/date-format.pli deleted file mode 100644 index e36f787b18..0000000000 --- a/Task/Date-format/PL-I/date-format.pli +++ /dev/null @@ -1,12 +0,0 @@ -declare day_of_week(7) character (9) varying initial - 'Sunday', 'Monday', 'Tuesday', 'Wednesday', - 'Thursday', 'Friday', 'Saturday'); -declare today character (8); - -today = datetime('YYYYMMDD'); -put edit (substr(today, 1, 4), '-', substr(today, 5, 2), '-', substr(today, 7) ) (A); - -today = datetime('MmmDDYYYY'); - -put skip edit (day_of_week(weekday(days())), ', ') (A); -put edit (substr(today, 1, 3), ' ', substr(today, 4, 2), ',', substr(today, 6, 4) ) (A); diff --git a/Task/Date-format/VBA/date-format.vba b/Task/Date-format/VBA/date-format.vba new file mode 100644 index 0000000000..422c83b9d9 --- /dev/null +++ b/Task/Date-format/VBA/date-format.vba @@ -0,0 +1,4 @@ +Function DateFormats() + Debug.Print Format(Date, "yyyy-mm-dd") + Debug.Print Format(Date, "dddd, mmmm dd yyyy") +End Function diff --git a/Task/Date-manipulation/Erlang/date-manipulation.erl b/Task/Date-manipulation/Erlang/date-manipulation.erl new file mode 100644 index 0000000000..7b74e2931c --- /dev/null +++ b/Task/Date-manipulation/Erlang/date-manipulation.erl @@ -0,0 +1,40 @@ +-module( date_manipulation ). + +-export( [task/0] ). + +task() -> + {Date_time, TZ} = date_time_tz_from_string( "March 7 2009 7:30pm EST" ), + Seconds1 = calendar:datetime_to_gregorian_seconds( Date_time ), + Seconds2 = calendar:datetime_to_gregorian_seconds( {calendar:gregorian_days_to_date(0), {12, 0, 0}} ), + Date_time_later = calendar:gregorian_seconds_to_datetime( Seconds1 + Seconds2 ), + {Date_time_later, TZ}. + + + +date_time_tz_from_string( String ) -> + [Month, Date, Year, Time, TZ] = string:tokens( String, " " ), + [Hour, Minute] = string:tokens( Time, ":" ), + {{date_from_strings(Year, Month, Date), time_from_strings(Hour, Minute)}, TZ}. + +date_from_strings( Year, Month, Date ) -> + {erlang:list_to_integer(Year), date_from_strings_month(Month), erlang:list_to_integer(Date)}. + +date_from_strings_month( "January" ) -> 1; +date_from_strings_month( "February" ) -> 2; +date_from_strings_month( "March" ) -> 3; +date_from_strings_month( "April" ) -> 4; +date_from_strings_month( "May" ) -> 5; +date_from_strings_month( "June" ) -> 6; +date_from_strings_month( "July" ) -> 7; +date_from_strings_month( "August" ) -> 8; +date_from_strings_month( "September" ) -> 9; +date_from_strings_month( "October" ) -> 10; +date_from_strings_month( "November" ) -> 11; +date_from_strings_month( "December" ) -> 12. + +time_from_strings( Hour, Minute_12hours ) -> + {ok, [Minute], AM_PM} = io_lib:fread("~d", Minute_12hours ), + {time_from_strings_hour( Hour, string:to_lower(AM_PM) ), Minute, 0}. + +time_from_strings_hour( Hour, "am" ) -> erlang:list_to_integer( Hour ); +time_from_strings_hour( Hour, "pm" ) -> erlang:list_to_integer( Hour ) + 12. diff --git a/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx b/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx index c6974c1b83..b328c0df33 100644 --- a/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx +++ b/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx @@ -8,7 +8,7 @@ if finish=='' then finish=2121 /*None specified? Assume default*/ if dow(12,25,y)==1 then say 'December 25th,' y "falls on a Sunday." end /*y*/ exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────DOW (day of week) subroutine─────*/ +/*──────────────────────────────────DOW (day of week) subroutine────────*/ dow: procedure; arg m,d,y; if m<3 then do; m=m+12; y=y-1; end yL=left(y,2); yr=right(y,2); w=(d + (m+1)*26%10+yr+yr%4+yL%4+5*yL) // 7 if w==0 then w=7; return w /*Sunday=1, Monday=2, ... Saturday=7*/ diff --git a/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d b/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d index 433daa8f30..9b455b9d7d 100644 --- a/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d +++ b/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d @@ -12,9 +12,9 @@ struct RandomGenerator { struct Deck { int[52] cards; - void deal(in uint seed) /*pure nothrow*/ { + void deal(in uint seed) pure /*nothrow*/ { enum int nc = cards.length; // Must be signed for iota. - iota(nc - 1, -1, -1).copy(cards[]); // iota not pure nothrow. + iota(nc - 1, -1, -1).copy(cards[]); // iota isn't nothrow. auto rnd = RandomGenerator(seed); foreach (immutable i, ref c; cards) diff --git a/Task/Deal-cards-for-FreeCell/Lua/deal-cards-for-freecell.lua b/Task/Deal-cards-for-FreeCell/Lua/deal-cards-for-freecell.lua new file mode 100644 index 0000000000..bd51ea7e94 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Lua/deal-cards-for-freecell.lua @@ -0,0 +1,36 @@ +deck = {} +rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} +suit = {"C", "D", "H", "S"} +two31, state = bit32.lshift(1, 31), 0 + +function rng() + state = (214013 * state + 2531011) % two31 + return bit32.rshift(state, 16) +end + +function initdeck() + for i, r in ipairs(rank) do + for j, s in ipairs(suit) do + table.insert(deck, r .. s) + end + end +end + +function deal(num) + initdeck() + state = num + print("Game #" .. num) + repeat + choice = rng(num) % #deck + 1 + deck[choice], deck[#deck] = deck[#deck], deck[choice] + io.write(" " .. deck[#deck]) + if (#deck % 8 == 5) then + print() + end + deck[#deck] = nil + until #deck == 0 + print() +end + +deal(1) +deal(617) diff --git a/Task/Deepcopy/Deja-Vu/deepcopy.djv b/Task/Deepcopy/Deja-Vu/deepcopy.djv index fa63e5647f..4196f384c9 100644 --- a/Task/Deepcopy/Deja-Vu/deepcopy.djv +++ b/Task/Deepcopy/Deja-Vu/deepcopy.djv @@ -1,23 +1,27 @@ -local :no-copy set{ :num :str :ident :pair :frac :func } +local :(copy-action) {} + +(copy-action)!list obj cache: + local :new [] + set-to cache obj new + for i range 0 -- len obj: + push-to new (deepcopy) @obj! i cache + return new + +(copy-action)!dict obj cache: + local :new {} + set-to cache obj new + for key in keys obj: + set-to new (deepcopy) @key cache (deepcopy) @obj! @key cache + return new + +labda obj cache: + set-to cache @obj dup copy @obj +set-default (copy-action) + (deepcopy) obj cache: if has cache obj: - return get-from cache obj - if has no-copy type obj: - # this object is either immutable - # or a function object which can't be copied - return obj - if = :list type obj: - local :new [] - set-to cache obj new - for value in reversed copy obj: - push-to new (deepcopy) value cache - return new - else: - local :new {} - set-to cache obj new - for key in keys obj: - set-to new (deepcopy) key cache (deepcopy) get-from obj key cache - return new + return @cache! @obj + (copy-action)! type @obj @obj cache deepcopy obj: (deepcopy) obj {} @@ -27,30 +31,22 @@ deepcopy obj: set :A { :foo [ "bar" ] [] [ & 1 2 & 3 4 ] } set :B deepcopy A -. A -#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" ] } -. B -#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" ] } +!. A +!. B push-to get-from B :foo "HODOR" -. A -#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" ] } -. B -#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" "HODOR" ] } +!. A +!. B #it works with cycles: set :C push-through dup [] set :D deepcopy C -. C -#prints: [ [ [ [ [...] ] ] ] ] -. D -#prints: [ [ [ [ [...] ] ] ] ] +!. C +!. D push-to C 7 -. C -#prints: [ [ [ [ [...] 7 ] 7 ] 7 ] 7 ] -. D -#prints: [ [ [ [ [...] ] ] ] ] +!. C +!. D diff --git a/Task/Delete-a-file/AWK/delete-a-file.awk b/Task/Delete-a-file/AWK/delete-a-file.awk index 764f59ec15..2c55e89964 100644 --- a/Task/Delete-a-file/AWK/delete-a-file.awk +++ b/Task/Delete-a-file/AWK/delete-a-file.awk @@ -1,4 +1,4 @@ -system("rm input.txt"); -system("rm /input.txt"); -system("rm -rf docs"); -system("rm -rf /docs"); +system("rm input.txt") +system("rm /input.txt") +system("rm -rf docs") +system("rm -rf /docs") diff --git a/Task/Delete-a-file/AutoHotkey/delete-a-file.ahk b/Task/Delete-a-file/AutoHotkey/delete-a-file-1.ahk similarity index 100% rename from Task/Delete-a-file/AutoHotkey/delete-a-file.ahk rename to Task/Delete-a-file/AutoHotkey/delete-a-file-1.ahk diff --git a/Task/Delete-a-file/AutoHotkey/delete-a-file-2.ahk b/Task/Delete-a-file/AutoHotkey/delete-a-file-2.ahk new file mode 100644 index 0000000000..b7124ce366 --- /dev/null +++ b/Task/Delete-a-file/AutoHotkey/delete-a-file-2.ahk @@ -0,0 +1,6 @@ +DeleteFile(lpFileName) +{ + DllCall("Kernel32.dll\DeleteFile", "Str", lpFileName) +} + +DeleteFile("C:\Temp\TestFile.txt") diff --git a/Task/Delete-a-file/Java/delete-a-file.java b/Task/Delete-a-file/Java/delete-a-file.java index 35bbfea0ca..7e4a2f2631 100644 --- a/Task/Delete-a-file/Java/delete-a-file.java +++ b/Task/Delete-a-file/Java/delete-a-file.java @@ -1,4 +1,4 @@ -import java.util.File; +import java.io.File; public class FileDeleteTest { public static boolean deleteFile(String filename) { boolean exists = new File(filename).delete(); diff --git a/Task/Delete-a-file/REXX/delete-a-file.rexx b/Task/Delete-a-file/REXX/delete-a-file.rexx new file mode 100644 index 0000000000..18c5805b6f --- /dev/null +++ b/Task/Delete-a-file/REXX/delete-a-file.rexx @@ -0,0 +1,10 @@ +/*REXX pgm deletes a file & a folder in the current directory & the root*/ +trace off /*suppress REXX error messages. */ +aFile= 'input.txt' /*name of a file to be deleted.*/ +aDir = 'docs' /*name of a folder to be removed.*/ + do j=1 for 2 /*perform this DO loop twice. */ + 'ERASE' aFile /*erase this file in the cur dir*/ + 'RMDIR' "/s /q" aDir /*remove the folder " " " " */ + if j==1 then 'CD \' /*make current dir the root dir.*/ + end /* [↑] just do CD \ once.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Delete-a-file/Scala/delete-a-file.scala b/Task/Delete-a-file/Scala/delete-a-file.scala new file mode 100644 index 0000000000..365dbd3b45 --- /dev/null +++ b/Task/Delete-a-file/Scala/delete-a-file.scala @@ -0,0 +1,18 @@ +import java.util._ +import java.io.File + +object FileDeleteTest extends App { + + def deleteFile(filename: String) = { + new File(filename).delete(); + } + + def test(typ: String, filename: String) = { + System.out.println("The following " + typ + " called " + filename + + (if (deleteFile(filename)) " was deleted." else " could not be deleted.")) + } + test("file", "input.txt"); + test("file", File.separatorChar + "input.txt"); + test("directory", "docs"); + test("directory", File.separatorChar + "docs" + File.separatorChar); +} diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-1.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-1.basic new file mode 100644 index 0000000000..556e9b99ed --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-1.basic @@ -0,0 +1,10 @@ + 100 REM TRY + 110 ONERR GOTO 200 + 120 D = - 44 / 0 + 190 END + 200 REM CATCH + 210 E = PEEK (222) < > 133 + 220 POKE 216,0: REM ONERR OFF + 230 IF E THEN RESUME + 240 CALL - 3288: REM RECOVER + 250 PRINT "DIVISION BY ZERO" diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-2.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-2.basic new file mode 100644 index 0000000000..b4ac40401e --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-2.basic @@ -0,0 +1,19 @@ + PROCdivide(-44, 0) + PROCdivide(-44, 5) + PROCdivide(0, 5) + PROCdivide(5, 0) + END + + DEF PROCdivide(numerator, denominator) + ON ERROR LOCAL IF FALSE THEN + REM 'Try' clause: + PRINT numerator / denominator + ELSE + REM 'Catch' clause: + CASE ERR OF + WHEN 18: PRINT "Division by zero" + WHEN 20: PRINT "Number too big" + OTHERWISE RESTORE LOCAL : ERROR ERR, REPORT$ + ENDCASE + ENDIF + ENDPROC diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-3.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-3.basic new file mode 100644 index 0000000000..5b02911f51 --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-3.basic @@ -0,0 +1,12 @@ +result = DetectDividebyZero(1, 0) + + +Function DetectDividebyZero(a, b) + On Error GoTo [Error] + DetectDividebyZero= (a/ b) + Exit Function + [Error] + If Err = 11 Then '11 is the error number raised when divide by zero occurs + Notice "Divide by Zero Detected!" + End If +End Function diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-4.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-4.basic new file mode 100644 index 0000000000..27ec7e1b97 --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-4.basic @@ -0,0 +1,6 @@ +10 ON ERROR GOTO 60 +20 PRINT 2/3 +30 PRINT 3/5 +40 PRINT 4/0 +50 END +60 IF ERR=11 THEN PRINT "Division by zero in line"ERL:RESUME 50 diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-5.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-5.basic new file mode 100644 index 0000000000..663cc0755f --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-5.basic @@ -0,0 +1,13 @@ +;Set up a Procedure to handle any Error +Procedure MyErrorHandler() + Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine()) + MessageRequester("OnError test", txt$) +EndProcedure + +; Tell where to go if an Error happens +OnErrorCall(@MyErrorHandler()) + +;Now, do something very stupid so that we may see an Error... +Repeat + A=Random(100)/Random(100) +ForEver diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-6.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-6.basic new file mode 100644 index 0000000000..16b33ba475 --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-6.basic @@ -0,0 +1,2 @@ +Define.d a, b +Debug a/b diff --git a/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-7.basic b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-7.basic new file mode 100644 index 0000000000..61985e1dd3 --- /dev/null +++ b/Task/Detect-division-by-zero/BASIC/detect-division-by-zero-7.basic @@ -0,0 +1,7 @@ +on error goto [error] +a = 1 / 0 +wait + +[error] ' error 11 is division by zero err number +If err = 11 Then print "Division by Zero" +wait diff --git a/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv b/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv index 5127eb05b1..094e56cadd 100644 --- a/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv +++ b/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv @@ -6,6 +6,6 @@ divcheck x y: not if divcheck 1 0: - print "Okay" + !print "Okay" else: - print "Division by zero" + !print "Division by zero" diff --git a/Task/Detect-division-by-zero/TXR/detect-division-by-zero.txr b/Task/Detect-division-by-zero/TXR/detect-division-by-zero.txr new file mode 100644 index 0000000000..2707126ad6 --- /dev/null +++ b/Task/Detect-division-by-zero/TXR/detect-division-by-zero.txr @@ -0,0 +1,6 @@ +@(do (defun div-check (x y) + (catch (/ x y) + (numeric_error (msg) + 'div-check-failed)))) +@(bind good @(div-check 32 8)) +@(bind bad @(div-check 42 0)) 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 78d7fb024e..95173a49b7 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 @@ -6,7 +6,6 @@ 01 Numeric-Chars PIC X(10) VALUE "0123456789". 01 Success CONSTANT 0. - *> By convention, a non-zero value is used to signify failure 01 Failure CONSTANT 128. LOCAL-STORAGE SECTION. @@ -18,11 +17,9 @@ LINKAGE SECTION. 01 Str PIC X(30). - PROCEDURE DIVISION USING BY VALUE Str. - + PROCEDURE DIVISION USING Str. IF Str = SPACES MOVE Failure TO Return-Code - GOBACK END-IF @@ -31,7 +28,6 @@ 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 diff --git a/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv b/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv index 14329cb604..7dfe7ffaa0 100644 --- a/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv +++ b/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv @@ -6,4 +6,4 @@ is-numeric s: not for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]: - .( v is-numeric v ) + !.( v is-numeric v ) diff --git a/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m b/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m index d743374033..de1a1d3dee 100644 --- a/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m +++ b/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m @@ -1,20 +1,15 @@ -% Is string numeric? - -function [out] = str_isnumeric(string) - - if ~ischar(string) - error('str_isnumeric:NonCharacterArray','not a string input'); + % Is string numeric? + function out = is_str_numeric(s) + out = ~isempty(parse_float(s)); end - Nd = sum(isstrprop(string,'digit')); - Nc = length(string); - - dN = Nc - Nd; - - switch dN - case 0 - out = 1; - otherwise - out = 0; + % Returns the float (double) if true, empty array otherwise. + function f = parse_float(s) + [f_in_cell, pos] = textscan(s, '%f'); + % Make sure there are no trailing chars. textscan(..) is greedy. + if pos == length(s) + f = f_in_cell{:}; + else + f = []; + end end -end diff --git a/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx b/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx index 56e29ea45a..6f3100103e 100644 --- a/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx +++ b/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx @@ -2,30 +2,31 @@ yyy=' -123.78' /*or some such.*/ /*strings below are all numeric (REXX).*/ -zzz=' -123.78 ' +zzz=' -123.78 ' zzz='-123.78' zzz='2' zzz="2" zzz=2 zzz='000000000004' zzz='+5' -zzz=' +6 ' -zzz=' + 7 ' -zzz=' - 8 ' -zzz=' - .9' -zzz='- 19.' +zzz=' +6 ' +zzz=' + 7 ' +zzz=' - 8 ' +zzz=' - .9 ' +zzz='- 19.' zzz='.7' zzz='2e3' zzz=47e567 zzz='2e-3' zzz='1.2e1' -zzz=' .2E6' -zzz=' 2.e5 ' -zzz=' +1.2E0002 ' -zzz=' +1.2e+002 ' -zzz=' +0000001.200e+002 ' -zzz=' - 000001.200e+002 ' -zzz=' - 000008.201e-00000000000000002 ' +zzz=' .2E6' +zzz=' 2.e5 ' +zzz=' +1.2E0002 ' +zzz=' +1.2e+002 ' +zzz=' +0000001.200e+002 ' +zzz=' - 000001.200e+002 ' +zzz=' - 000008.201e-00000000000000002 ' +ifx=i /*Note: some REXX interpreters allow use of tab chars as blanks. */ @@ -44,3 +45,4 @@ if datatype(yyy)¬= 'NUM' then say 'oops, not numeric:' yyy /*note: REXX only looks at the first char for DATATYPE's 2nd arg. */ /*note: some REXX interpreters don't support the ¬ (not) character.*/ +/*note: " " " " " the / as negation. */ diff --git a/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric.scala b/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-1.scala similarity index 100% rename from Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric.scala rename to Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-1.scala diff --git a/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-2.scala b/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-2.scala new file mode 100644 index 0000000000..2d034f21d5 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-2.scala @@ -0,0 +1,3 @@ +def isNumeric2(str: String): Boolean = { + str.matches(s"""[+-]?((\d+(e\d+)?[lL]?)|(((\d+(\.\d*)?)|(\.\d+))(e\d+)?[fF]?))""") +} diff --git a/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-3.scala b/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-3.scala new file mode 100644 index 0000000000..ae99bfa3f6 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Scala/determine-if-a-string-is-numeric-3.scala @@ -0,0 +1,7 @@ +def isNumeric(str: String): Boolean = { + !throwsNumberFormatException(str.toLong) || !throwsNumberFormatException(str.toDouble) +} + +def throwsNumberFormatException(f: => Any): Boolean = { + try { f; false } catch { case e: NumberFormatException => true } +} diff --git a/Task/Digital-root/AWK/digital-root.awk b/Task/Digital-root/AWK/digital-root.awk new file mode 100644 index 0000000000..5b50450b50 --- /dev/null +++ b/Task/Digital-root/AWK/digital-root.awk @@ -0,0 +1,25 @@ +# syntax: GAWK -f DIGITAL_ROOT.AWK +BEGIN { + n = split("627615,39390,588225,393900588225,10,199",arr,",") + for (i=1; i<=n; i++) { + dr = digitalroot(arr[i],10) + printf("%12.0f has additive persistence %d and digital root of %d\n",arr[i],p,dr) + } + exit(0) +} +function digitalroot(n,b) { + p = 0 # global + while (n >= b) { + p++ + n = digitsum(n,b) + } + return(n) +} +function digitsum(n,b, q,s) { + while (n != 0) { + q = int(n / b) + s += n - q * b + n = q + } + return(s) +} diff --git a/Task/Digital-root/Bracmat/digital-root.bracmat b/Task/Digital-root/Bracmat/digital-root.bracmat new file mode 100644 index 0000000000..847c8383db --- /dev/null +++ b/Task/Digital-root/Bracmat/digital-root.bracmat @@ -0,0 +1,29 @@ + ( root + = sum persistence n d + . !arg:(~>9.?) + | !arg:(?n.?persistence) + & 0:?sum + & ( @( !n + : ? + (#%@?d&!d+!sum:?sum&~) + ? + ) + | root$(!sum.!persistence+1) + ) + ) +& ( 627615 39390 588225 393900588225 10 199 + : ? + ( #%@?N + & root$(!N.0):(?Sum.?Persistence) + & out + $ ( !N + "has additive persistence" + !Persistence + "and digital root of" + !Sum + ) + & ~ + ) + ? + | done + ); diff --git a/Task/Digital-root/D/digital-root.d b/Task/Digital-root/D/digital-root.d index a6c63a7903..ab1ed1c7cd 100644 --- a/Task/Digital-root/D/digital-root.d +++ b/Task/Digital-root/D/digital-root.d @@ -1,12 +1,13 @@ -import std.stdio, std.typecons, std.conv, std.bigint; +import std.stdio, std.typecons, std.conv, std.bigint, std.math, + std.traits; -Tuple!(int, T) digitalRoot(T)(T root, in uint base) /*pure nothrow*/ +Tuple!(uint, Unqual!T) digitalRoot(T)(in T inRoot, in uint base) +pure /*nothrow*/ in { assert(base > 1); } body { - if (root < 0) - root = -root; - int persistence = 0; + Unqual!T root = inRoot.abs; + uint persistence = 0; while (root >= base) { auto num = root; root = 0; @@ -16,22 +17,20 @@ in { } persistence++; } - return tuple(persistence, root); + return typeof(return)(persistence, root); } void main() { - // import std.stdio, std.conv, std.bigint; enum f1 = "%s(%d): additive persistance= %d, digital root= %d"; - foreach (b; [2, 3, 8, 10, 16, 36]) { - foreach (n; [5, 627615, 39390, 588225, 393900588225]) - writefln(f1, to!string(n,b), b, digitalRoot(n, b).tupleof); - writeln(); + foreach (immutable b; [2, 3, 8, 10, 16, 36]) { + foreach (immutable n; [5, 627615, 39390, 588225, 393900588225]) + writefln(f1, text(n, b), b, n.digitalRoot(b)[]); + writeln; } enum f2 = "(%d): additive persistance= %d, digital root= %d"; - foreach (b; [2, 3, 8, 10, 16, 36]) { - auto n = BigInt("58142718981673030403681039458302204471" ~ - "300738980834668522257090844071443085937"); - writefln(f2, b, digitalRoot(n, b).tupleof); // shortened output - } + immutable n = BigInt("581427189816730304036810394583022044713" ~ + "00738980834668522257090844071443085937"); + foreach (immutable b; [2, 3, 8, 10, 16, 36]) + writefln(f2, b, n.digitalRoot(b)[]); // Shortened output. } diff --git a/Task/Digital-root/Erlang/digital-root.erl b/Task/Digital-root/Erlang/digital-root.erl new file mode 100644 index 0000000000..2aaf33390e --- /dev/null +++ b/Task/Digital-root/Erlang/digital-root.erl @@ -0,0 +1,15 @@ +-module( digital_root ). + +-export( [task/0] ). + +task() -> + Ns = [N || N <- [627615, 39390, 588225, 393900588225]], + Persistances = [persistance_root(X) || X <- Ns], + [io:fwrite("~p has additive persistence ~p and digital root of ~p~n", [X, Y, Z]) || {X, {Y, Z}} <- lists:zip(Ns, Persistances)]. + + + +persistance_root( X ) -> persistance_root( sum_digits:sum_digits(X), 1 ). + +persistance_root( X, N ) when X < 10 -> {N, X}; +persistance_root( X, N ) -> persistance_root( sum_digits:sum_digits(X), N + 1 ). diff --git a/Task/Digital-root/Forth/digital-root-1.fth b/Task/Digital-root/Forth/digital-root-1.fth new file mode 100644 index 0000000000..5e61d06c89 --- /dev/null +++ b/Task/Digital-root/Forth/digital-root-1.fth @@ -0,0 +1,2 @@ +: (Sdigit) 0 swap begin base @ /mod >r + r> dup 0= until drop ; +: digiroot 0 swap begin (Sdigit) >r 1+ r> dup base @ < until ; diff --git a/Task/Digital-root/Forth/digital-root-2.fth b/Task/Digital-root/Forth/digital-root-2.fth new file mode 100644 index 0000000000..5a9b4a57aa --- /dev/null +++ b/Task/Digital-root/Forth/digital-root-2.fth @@ -0,0 +1,4 @@ +[UNDEFINED] mu/mod [IF] : mu/mod >r 0 r@ um/mod r> swap >r um/mod r> ; [THEN] + +: (Sdigit) 0. 2swap begin base @ mu/mod 2>r s>d d+ 2r> 2dup d0= until 2drop ; +: digiroot 0 -rot begin (Sdigit) 2>r 1+ 2r> 2dup base @ s>d d< until d>s ; diff --git a/Task/Digital-root/Perl/digital-root.pl b/Task/Digital-root/Perl/digital-root.pl new file mode 100644 index 0000000000..625d1d6263 --- /dev/null +++ b/Task/Digital-root/Perl/digital-root.pl @@ -0,0 +1,51 @@ +#!perl +use strict; +use warnings; +use List::Util qw(sum); + +my @digit = (0..9, 'a'..'z'); +my %digit = map { +$digit[$_], $_ } 0 .. $#digit; + +sub base { + my ($n, $b) = @_; + $b ||= 10; + die if $b > @digit; + my $result = ''; + while( $n ) { + $result .= $digit[ $n % $b ]; + $n = int( $n / $b ); + } + reverse($result) || '0'; +} + +sub digi_root { + my ($n, $b) = @_; + my $inbase = base($n, $b); + my $additive_persistance = 0; + while( length($inbase) > 1 ) { + ++$additive_persistance; + $n = sum @digit{split //, $inbase}; + $inbase = base($n, $b); + } + $additive_persistance, $n; +} + +MAIN: { + my @numbers = (5, 627615, 39390, 588225, 393900588225); + my @bases = (2, 3, 8, 10, 16, 36); + my $fmt = "%25s(%2s): persistance = %s, root = %2s\n"; + + if( eval { require Math::BigInt; 1 } ) { + push @numbers, Math::BigInt->new("5814271898167303040368". + "1039458302204471300738980834668522257090844071443085937"); + } + + for my $base (@bases) { + for my $num (@numbers) { + my $inbase = base($num, $base); + $inbase = 'BIG' if length($inbase) > 25; + printf $fmt, $inbase, $base, digi_root($num, $base); + } + print "\n"; + } +} diff --git a/Task/Digital-root/Ruby/digital-root.rb b/Task/Digital-root/Ruby/digital-root.rb index 491ff5af77..c6e3ae1044 100644 --- a/Task/Digital-root/Ruby/digital-root.rb +++ b/Task/Digital-root/Ruby/digital-root.rb @@ -1,12 +1,12 @@ class String - def digroot_persistance(base) + def digroot_persistence(base) num = self.to_i(base) - persistance = 0 + persistence = 0 until num < base do num = num.to_s(base).each_char.reduce(0){|m, c| m += c.to_i(base) } - persistance += 1 + persistence += 1 end - [num.to_s(base), persistance] + [num.to_s(base), persistence] end end @@ -16,4 +16,4 @@ end ["5", 10], ["393900588225", 10], ["50YE8N29", 36]].each{|(str, base)| puts "#{str} base #{base} has a digital root \ -of %s and a resistance of %s." % str.digroot_persistance(base) } +of %s and a persistence of %s." % str.digroot_persistence(base) } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Erlang/dinesmans-multiple-dwelling-problem.erl b/Task/Dinesmans-multiple-dwelling-problem/Erlang/dinesmans-multiple-dwelling-problem.erl new file mode 100644 index 0000000000..e5f7ec1a6e --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Erlang/dinesmans-multiple-dwelling-problem.erl @@ -0,0 +1,43 @@ +-module( dinesman_multiple_dwelling ). + +-export( [solve/2, task/0] ). + +solve( All_persons, Rules ) -> + [house(Bottom_floor, B, C, D, Top_floor) || Bottom_floor <- All_persons, B <- All_persons, C <- All_persons, D <- All_persons, Top_floor <- All_persons, + lists:all( fun (Fun) -> Fun( house(Bottom_floor, B, C, D, Top_floor) ) end, rules( Rules ))]. + +task() -> + All_persons = [baker, cooper, fletcher, miller, smith], + Rules = [all_on_different_floors, {not_lives_on_floor, 4, baker}, {not_lives_on_floor, 0, cooper}, {not_lives_on_floor, 4, fletcher}, {not_lives_on_floor, 0, fletcher}, + {on_higher_floor, miller, cooper}, {not_adjacent, smith, fletcher}, {not_adjacent, fletcher, cooper}], + [House] = solve( All_persons, Rules ), + [io:fwrite("~p lives on floor ~p~n", [lists:nth(X, House), X - 1]) || X <- lists:seq(1,5)]. + + + +house( A, B, C, D, E ) -> [A, B, C, D, E]. + +is_all_on_different_floors( [A, B, C, D, E] ) -> + A =/= B andalso A =/= C andalso A =/= D andalso A =/= E + andalso B =/= C andalso B =/= D andalso B =/= E + andalso C =/= D andalso C =/= E + andalso D =/= E. + +is_not_adjacent( Person1, Person2, House ) -> + is_not_below( Person1, Person2, House ) andalso is_not_below( Person2, Person1, House ). + +is_not_below( _Person1, _Person2, [_Person] ) -> true; +is_not_below( Person1, Person2, [Person1, Person2 | _T] ) -> false; +is_not_below( Person1, Person2, [_Person | T] ) -> is_not_below( Person1, Person2, T ). + +is_on_higher_floor( Person1, _Person2, [Person1 | _T] ) -> false; +is_on_higher_floor( _Person1, Person2, [Person2 | _T] ) -> true; +is_on_higher_floor( Person1, Person2, [_Person | T] ) -> is_on_higher_floor( Person1, Person2, T ). + +rules( Rules ) -> lists:map( fun rules_fun/1, Rules ). + +rules_fun( all_on_different_floors ) -> fun is_all_on_different_floors/1; +rules_fun( {not_lives_on_floor, N, Person} ) -> fun (House) -> Person =/= lists:nth(N + 1, House) end; +rules_fun( {on_higher_floor, Person1, Person2} ) -> fun (House) -> is_on_higher_floor( Person1, Person2, House ) end; +rules_fun( {not_below, Person1, Person2} ) -> fun (House) -> is_not_below( Person1, Person2, House ) end; +rules_fun( {not_adjacent, Person1, Person2} ) -> fun (House) -> is_not_adjacent( Person1, Person2, House ) end. 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 e1d5b9b0f4..9a36a41e8b 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 @@ -7,11 +7,10 @@ def solve( problem ) bottom top higher lower adjacent) re_keywords = Regexp.union( words ) - predicates = [] #build an array of lambda's - lines[1..-2].each do |line| + predicates = lines[1..-2].flat_map do |line| #build an array of lambda's keywords = line.scan( re_keywords ) name1, name2 = line.scan( re_names ) - keywords.each do |keyword| + keywords.map do |keyword| l = case keyword when "bottom" then ->(c){ c.first == name1 } when "top" then ->(c){ c.last == name1 } @@ -19,12 +18,10 @@ def solve( problem ) when "lower" then ->(c){ c.index( name1 ) < c.index( name2 ) } when "adjacent" then ->(c){ (c.index( name1 ) - c.index( name2 )).abs == 1 } else ->(c){ c[words.index(keyword)] == name1 } - end - line =~ /\bnot\b/ ? res = ->(c){not l.call(c) } : res = l - predicates << res + end + line =~ /\bnot\b/ ? ->(c){not l.call(c) } : l # handle "not" end end names.permutation.detect{|candidate| predicates.all?{|predicate| predicate.(candidate)}} - end diff --git a/Task/Dining-philosophers/Common-Lisp/dining-philosophers.lisp b/Task/Dining-philosophers/Common-Lisp/dining-philosophers.lisp index 2c55ef8d7f..a94d0ddd2a 100644 --- a/Task/Dining-philosophers/Common-Lisp/dining-philosophers.lisp +++ b/Task/Dining-philosophers/Common-Lisp/dining-philosophers.lisp @@ -1,3 +1,10 @@ +(in-package :common-lisp-user) + +;; +;; FLAG -- if using quicklisp, you can get bordeaux-threads loaded up +;; with: (ql:quickload :bordeaux-threads) +;; + (defvar *philosophers* '(Aristotle Kant Spinoza Marx Russell)) (defclass philosopher () @@ -7,7 +14,7 @@ (meals-left :initarg :meals-left :accessor meals-left-of))) (defclass fork () - ((lock :initform (make-lock "fork") :reader lock-of))) + ((lock :initform (bt:make-lock "fork") :reader lock-of))) (defun random-normal (&optional (mean 0.0) (sd 1.0)) (do* ((x1 #1=(1- (* 2.0d0 (random 1d0))) #1#) @@ -31,9 +38,9 @@ :right-fork (nth (mod (1+ i) count) forks) :name name :meals-left meals))) - (condition (make-condition-variable)) - (lock (make-lock "main loop")) - (output-lock (make-lock "output lock"))) + (condition (bt:make-condition-variable)) + (lock (bt:make-lock "main loop")) + (output-lock (bt:make-lock "output lock"))) (dolist (p philosophers) (labels ((think () (/me "is now thinking") @@ -41,33 +48,33 @@ (/me "is now hungry") (dine)) (dine () - (with-lock-held ((lock-of (left-fork-of p))) - (or (acquire-lock (lock-of (right-fork-of p)) nil) + (bt:with-lock-held ((lock-of (left-fork-of p))) + (or (bt:acquire-lock (lock-of (right-fork-of p)) nil) (progn (/me "couldn't get a fork and ~ returns to thinking") - (release-lock (lock-of (left-fork-of p))) + (bt:release-lock (lock-of (left-fork-of p))) (return-from dine (think)))) (/me "is eating") (sleep* (apply #'random-normal dining-time)) - (release-lock (lock-of (right-fork-of p))) + (bt:release-lock (lock-of (right-fork-of p))) (/me "is done eating (~A meals left)" (decf (meals-left-of p)))) (cond ((<= (meals-left-of p) 0) (/me "leaves the dining room") - (with-lock-held (lock) + (bt:with-lock-held (lock) (setq philosophers (delete p philosophers)) - (condition-notify condition))) + (bt:condition-notify condition))) (t (think)))) (/me (control &rest args) - (with-lock-held (output-lock) + (bt:with-lock-held (output-lock) (write-sequence (string (name-of p)) e) (write-char #\Space e) (apply #'format e (concatenate 'string control "~%") args)))) - (make-thread #'think))) - (loop (with-lock-held (lock) + (bt:make-thread #'think))) + (loop (bt:with-lock-held (lock) (when (endp philosophers) (format e "all philosophers are done dining~%") (return))) - (with-lock-held (lock) - (condition-wait condition lock))))) + (bt:with-lock-held (lock) + (bt:condition-wait condition lock))))) diff --git a/Task/Dining-philosophers/D/dining-philosophers.d b/Task/Dining-philosophers/D/dining-philosophers.d index 552cfacf9e..3a984905f7 100644 --- a/Task/Dining-philosophers/D/dining-philosophers.d +++ b/Task/Dining-philosophers/D/dining-philosophers.d @@ -1,20 +1,19 @@ import std.stdio, std.algorithm, std.string, std.parallelism, - core.sync.mutex; + core.sync.mutex; -void eat(in uint i, in string name, Mutex[] forks) { +void eat(in size_t i, in string name, Mutex[] forks) { writeln(name, " is hungry."); - immutable j = (i + 1) % forks.length; // Take forks i and j. The lower one first to prevent deadlock. auto fork1 = forks[min(i, j)]; auto fork2 = forks[max(i, j)]; - fork1.lock(); - scope(exit) fork1.unlock(); + fork1.lock; + scope(exit) fork1.unlock; - fork2.lock(); - scope(exit) fork2.unlock(); + fork2.lock; + scope(exit) fork2.unlock; writeln(name, " is eating."); writeln(name, " is full."); @@ -25,16 +24,16 @@ void think(in string name) { } void main() { - const philosophers = "Aristotle Kant Spinoza Marx Russell".split(); + const philosophers = "Aristotle Kant Spinoza Marx Russell".split; Mutex[philosophers.length] forks; foreach (ref fork; forks) - fork = new Mutex(); + fork = new Mutex; defaultPoolThreads = forks.length; foreach (i, philo; taskPool.parallel(philosophers)) { - foreach (_; 0 .. 100) { + foreach (immutable _; 0 .. 100) { eat(i, philo, forks); - think(philo); + philo.think; } } } diff --git a/Task/Dining-philosophers/Groovy/dining-philosophers.groovy b/Task/Dining-philosophers/Groovy/dining-philosophers.groovy new file mode 100644 index 0000000000..c6e03d7425 --- /dev/null +++ b/Task/Dining-philosophers/Groovy/dining-philosophers.groovy @@ -0,0 +1,56 @@ +import groovy.transform.Canonical + +import java.util.concurrent.locks.Lock +import java.util.concurrent.locks.ReentrantLock + +@Canonical +class Fork { + String name + Lock lock = new ReentrantLock() + + void pickUp(String philosopher) { + lock.lock() + println " $philosopher picked up $name" + } + + void putDown(String philosopher) { + lock.unlock() + println " $philosopher put down $name" + } +} + +@Canonical +class Philosopher extends Thread { + Fork f1 + Fork f2 + + @Override + void run() { + def random = new Random() + (1..20).each { bite -> + println "$name is hungry" + f1.pickUp name + f2.pickUp name + println "$name is eating bite $bite" + Thread.sleep random.nextInt(300) + 100 + f2.putDown name + f1.putDown name + } + } +} + +void diningPhilosophers(names) { + def forks = (1..names.size()).collect { new Fork(name: "Fork $it") } + def philosophers = [] + names.eachWithIndex{ n, i -> + def (i1, i2) = [i, (i + 1) % 5] + if (i2 < i1) (i1, i2) = [i2, i] + + def p = new Philosopher(name: n, f1: forks[i1], f2: forks[i2]) + p.start() + philosophers << p + } + philosophers.each { it.join() } +} + +diningPhilosophers(['Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell']) diff --git a/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 b/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 new file mode 100644 index 0000000000..f99a013338 --- /dev/null +++ b/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 @@ -0,0 +1,55 @@ +class Fork { + has $!lock = Lock.new; + method grab($who, $which) { + remark "$who grabbing $which fork"; + $!lock.lock; + } + method drop($who, $which) { + remark "$who dropping $which fork"; + $!lock.unlock; + } +} + +class Lollipop { + has $!channel = Channel.new; + method mine($who) { $!channel.send($who) } + method yours { $!channel.receive } +} + +my $out = Channel.new; +sub remark($msg) { $out.send($msg) } +start { loop { $out.receive.say } } + +sub dally($sec) { sleep 0.01 + rand * $sec } + +sub MAIN(*@names) { + @names ||= ; + + my @lfork = Fork.new xx @names; + my @rfork = @lfork.rotate; + + my $lollipop = Lollipop.new; + start { $lollipop.yours; } + + my @philosophers = do for @names Z @lfork Z @rfork -> $n, $l, $r { + start { + sleep 1 + rand*4; + loop { + $l.grab($n,'left'); + dally 1; # give opportunity for deadlock + $r.grab($n,'right'); + remark "$n eating"; + dally 10; + $l.drop($n,'left'); + $r.drop($n,'right'); + + $lollipop.mine($n); + sleep 1; # lick at least once + remark "$n lost lollipop to $lollipop.yours(), now digesting"; + + dally 20; + } + } + } + await @philosophers; +} diff --git a/Task/Dining-philosophers/Perl/dining-philosophers.pl b/Task/Dining-philosophers/Perl/dining-philosophers-1.pl similarity index 100% rename from Task/Dining-philosophers/Perl/dining-philosophers.pl rename to Task/Dining-philosophers/Perl/dining-philosophers-1.pl diff --git a/Task/Dining-philosophers/Perl/dining-philosophers-2.pl b/Task/Dining-philosophers/Perl/dining-philosophers-2.pl new file mode 100644 index 0000000000..44e8e41636 --- /dev/null +++ b/Task/Dining-philosophers/Perl/dining-philosophers-2.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl +use common::sense; +use Coro; +use AnyEvent; +use Coro::AnyEvent; +use EV; + +my @philosophers = qw(Aristotle Kant Spinoza Marx Russell); +my @forks = (1..@philosophers); +my @fork_sem; + +$fork_sem[$_] = new Coro::Semaphore for (0..$#philosophers); + + +for(my $i = $#philosophers; $i >= 0; $i--){ + say $philosophers[$i] . " has fork #" . $forks[$i] . " and fork #" . $forks[$i-1]; + async { + my ($name, ,$no, $forks_got) = (@_); + + $Coro::current->{desc} = $name; + Coro::AnyEvent::sleep(rand 4); + + while(1){ + say $name . " is hungry."; + $$forks_got[$no]->down(); + Coro::AnyEvent::sleep(rand 1); #Let's make deadlock! + $$forks_got[$no-1]->down(); + say $name . " is eating."; + Coro::AnyEvent::sleep(1 + rand 8); + + $$forks_got[$no]->up(); + $$forks_got[$no-1]->up(); + + say $name . " is thinking."; + Coro::AnyEvent::sleep(1 + rand 8); + } + }($philosophers[$i], $i, \@fork_sem); +} + +EV::loop; diff --git a/Task/Dining-philosophers/REXX/dining-philosophers.rexx b/Task/Dining-philosophers/REXX/dining-philosophers.rexx new file mode 100644 index 0000000000..b70116e42a --- /dev/null +++ b/Task/Dining-philosophers/REXX/dining-philosophers.rexx @@ -0,0 +1,48 @@ +/*REXX prm demonstrates a solution to solve dining philosophers problem.*/ +parse arg seed diners /*get optional arguments from CL.*/ +if seed\=='' & seed\==',' then call random ,, seed /*for repeatability*/ +if diners='' then diners='Aristotle,Kant,Spinoza,Marx,Russell' +tell=left(seed,1)\=='+' /*Leading + in SEED? No stats.*/ +diners=translate(diners,,',') /*change a commatized diners list*/ +#=words(diners); @.=0 /*the number of dining philospers*/ + eatL=15; eatH= 60 /*min & max minutes for eating. */ +thinkL=30; thinkH=180 /* " " " " " thinking.*/ +forks.=1 /*indicate all forks are on table*/ + do tic=1 /*use minutes as time advancement*/ + call grabForks /*see if anybody can grab 2 forks*/ + call passTime /*handle diners eating | thinking*/ + end /*tic*/ /* ··· and time marches on ··· */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────FORK subroutine─────────────────────*/ +fork: parse arg x 1 ox; x=abs(x); L=x-1; if L==0 then L=# /*boundry ? */ +if ox<0 then do; forks.L=1; forks.x=1; return; end /*drop forks*/ +got2=forks.L & forks.x /*did we get two forks or not? */ +if got2 then do; forks.L=0; forks.x=0; end /*got forks.*/ +return got2 /*return with success or failure.*/ +/*──────────────────────────────────GRABFORKS subroutine────────────────*/ +grabForks: do person=1 for # /*see if any person can grab two.*/ + if @.person.status\==0 then iterate /*diner ain't waiting*/ + if \fork(person) then iterate /*diner didn't grab 2*/ + @.person.status='eating' /*diner now chomps on spaghetti. */ + @.person.dur=random(eatL,eatH) /*how long will diner eat? */ + end /*person*/ +return +/*──────────────────────────────────PASSTIME subroutine─────────────────*/ +passTime: if tell then say /*show a (blank line) separator. */ + do p=1 for # /*process each diner's activity. */ + if tell then say right(tic,9,'.') right(word(diners,p),20), + right(word(@.p.status 'waiting',1+(@.p.status==0)),9) right(@.p.dur,5) + if @.p.dur==0 then iterate /*diner is waiting for two forks.*/ + @.p.dur=@.p.dur-1 /*indicate 1 timeUnit has gone by*/ + if @.p.dur\==0 then iterate /*Activity done? No, keep it up.*/ + select /*handle the activity being done.*/ + when @.p.status=='eating' then do /*now, leave the table.*/ + call fork -p /*drop the forks.*/ + @.p.status='thinking' /*status.*/ + @.p.dur=random(thinkL,thinkH) + end + when @.p.status=='thinking' then @.p.status=0 /*──► table*/ + otherwise nop /*diner must be waiting on forks.*/ + end /*select*/ + end /*p*/ +return diff --git a/Task/Distributed-programming/Factor/distributed-programming-1.factor b/Task/Distributed-programming/Factor/distributed-programming-1.factor new file mode 100644 index 0000000000..6f923548aa --- /dev/null +++ b/Task/Distributed-programming/Factor/distributed-programming-1.factor @@ -0,0 +1,5 @@ +USING: concurrency.distributed concurrency.messaging threads io.sockets io.servers ; +QUALIFIED: concurrency.messaging +: prettyprint-message ( -- ) concurrency.messaging:receive . flush prettyprint-message ; +[ prettyprint-message ] "logger" spawn dup name>> register-remote-thread +"127.0.0.1" 9000 start-server diff --git a/Task/Distributed-programming/Factor/distributed-programming-2.factor b/Task/Distributed-programming/Factor/distributed-programming-2.factor new file mode 100644 index 0000000000..801ca89d84 --- /dev/null +++ b/Task/Distributed-programming/Factor/distributed-programming-2.factor @@ -0,0 +1,4 @@ +USING: concurrency.distributed io.sockets ; +QUALIFIED: concurrency.messaging +{ "Hello Remote Factor!" H{ { "key1" "value1" } } } +"127.0.0.1" 9000 "logger" concurrency.messaging:send diff --git a/Task/Dot-product/Deja-Vu/dot-product.djv b/Task/Dot-product/Deja-Vu/dot-product.djv new file mode 100644 index 0000000000..0b4f801cb2 --- /dev/null +++ b/Task/Dot-product/Deja-Vu/dot-product.djv @@ -0,0 +1,9 @@ +dot a b: + if /= len a len b: + Raise value-error "dot product needs two vectors with the same length" + + 0 + while a: + + * pop-from a pop-from b + +!. dot [ 1 3 -5 ] [ 4 -2 -1 ] diff --git a/Task/Dot-product/REXX/dot-product.rexx b/Task/Dot-product/REXX/dot-product.rexx index 8fe6608e94..9e3513171d 100644 --- a/Task/Dot-product/REXX/dot-product.rexx +++ b/Task/Dot-product/REXX/dot-product.rexx @@ -2,31 +2,25 @@ vectorA = ' 1 3 -5 ' /*populate vectorA with numbers, */ vectorB = ' 4 -2 -1 ' /* ∙∙∙ and the same for vectorB. */ say /*display a blank line. */ -say 'vector A='vectorA /*echo the vectorA's values. */ -say 'vector B='vectorB /*echo the vectorB's values. */ +say 'vector A = ' vectorA /*echo the elements in vector A. */ +say 'vector B = ' vectorB /* " " " " " B. */ say /*display another blank line. */ p = dotProd(vectorA, vectorB) /*go and compute the dot product.*/ say 'dot product = ' p /*show and tell the dot product. */ -say /*display another a blank line. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DOTPROD subroutine──────────────────*/ dotProd: procedure; parse arg A,B /*compute the dot product. */ -sum = 0 /*initilize the sum to 0 (zero). */ -lenA = words(A) /*length of vector A in words. */ -lenB = words(B) /*length of vector B in words. */ - -if lenA\==lenB then do - say +lenA = words(A) /*number of numbers in vector A.*/ +lenB = words(B) /* " " " " " B.*/ +if lenA\==lenB then do /*are vectors unequal in size? */ say '*** error! ***' say "vectors aren't the same size:" - say 'vectorA length='lenA - say 'vectorB length='lenB - say + say ' vector A length = ' lenA + say ' vector B length = ' lenB exit 13 /*exit with return code 13. */ end - - do j=1 for lenA /*multiply each number in vectors*/ - sum = sum + word(A,j) * word(B,j) /*∙∙∙ and add the product to SUM.*/ - end /*j*/ - +sum=0 /*initialize the sum to 0 (zero).*/ + do j=1 for lenA /*multiply each number in vectors*/ + sum=sum+word(A,j)*word(B,j) /*∙∙∙ and add the product to SUM.*/ + end /*j*/ return sum /*return the SUM to the invoker. */ diff --git a/Task/Dot-product/Scilab/dot-product.scilab b/Task/Dot-product/Scilab/dot-product.scilab new file mode 100644 index 0000000000..fbaf2d42e6 --- /dev/null +++ b/Task/Dot-product/Scilab/dot-product.scilab @@ -0,0 +1,3 @@ +A = [1 3 -5] +B = [4 -2 -1] +C = sum(A.*B) diff --git a/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition.go b/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition.go index 764f2c57fc..48723ea9db 100644 --- a/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition.go +++ b/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition.go @@ -1,4 +1,4 @@ type dlNode struct { string - next, prev *dll + next, prev *dlNode } diff --git a/Task/Doubly-linked-list-Element-definition/REXX/doubly-linked-list-element-definition.rexx b/Task/Doubly-linked-list-Element-definition/REXX/doubly-linked-list-element-definition.rexx index d7744b6517..816a1b99dc 100644 --- a/Task/Doubly-linked-list-Element-definition/REXX/doubly-linked-list-element-definition.rexx +++ b/Task/Doubly-linked-list-Element-definition/REXX/doubly-linked-list-element-definition.rexx @@ -28,7 +28,7 @@ call sy 'displaying list size.' ; say 'list size='@size() call sy 'forward list' ; call @show call sy 'backward list' ; call @show ,,-1 call sy 'showing 4th item' ; call @show 4,1 -call sy 'showing 6th & 6th items' ; call @show 5,2 +call sy 'showing 5th & 6th items' ; call @show 5,2 call sy 'adding item before item 4: black' ; call @put 'black',4 call sy 'showing list' ; call @show call sy 'adding to tail: there, in the ...'; call @put 'there, in the shadows, stalking its prey (and next meal).' diff --git a/Task/Dragon-curve/00DESCRIPTION b/Task/Dragon-curve/00DESCRIPTION index e09e3ffc36..ade2ed67b8 100644 --- a/Task/Dragon-curve/00DESCRIPTION +++ b/Task/Dragon-curve/00DESCRIPTION @@ -78,6 +78,18 @@ BitAboveLowestOne = n BITAND AboveMask * Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See [[#M4|M4]] for an example of this. -: A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why is works is slightly subtle but the calculation is not difficult. (Segment check by applying an offset to move X,Y to an "even" position before dividing i+1. Vertex check by whether the segment either East or West is on the curve.) +: A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why is works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) : The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. + +* As a [[Lindenmayer system]] of expansions. The simplest is two symbols F and S both straight lines, as used by the [[#PGF|PGF]] code. + +
Axiom F, angle 90 degrees
+F -> F+S
+S -> F-S
+ +This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance [http://www.cs.unm.edu/~joel/PaperFoldingFractal/L-system-rules.html Joel Castellanos' L-system page]. + +Variations are possible if you have only a single symbol for line draw, for example the [[#Icon and Unicon|Icon and Unicon]] and [[#Xfractint|Xfractint]] code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. + +The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example [[#C by IFS Drawing|C by IFS Drawing]] code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems. diff --git a/Task/Dragon-curve/D/dragon-curve-3.d b/Task/Dragon-curve/D/dragon-curve-3.d new file mode 100644 index 0000000000..e72883194e --- /dev/null +++ b/Task/Dragon-curve/D/dragon-curve-3.d @@ -0,0 +1,22 @@ +module turtle; + +import bitmap_bresenhams_line_algorithm, grayscale_image, std.math; + +// Minimal turtle graphics. +struct Turtle { + real x = 100, y = 100, angle = -90; + + void left(in real a) pure nothrow { angle -= a; } + void right(in real a) pure nothrow { angle += a; } + + void forward(Color)(Image!Color img, in real len) pure nothrow { + immutable r = angle * (PI / 180.0); + immutable dx = r.cos * len; + immutable dy = r.sin * len; + img.drawLine(cast(uint)x, cast(uint)y, + cast(uint)(x + dx), cast(uint)(y + dy), + Color.white); + x += dx; + y += dy; + } +} diff --git a/Task/Dragon-curve/D/dragon-curve-4.d b/Task/Dragon-curve/D/dragon-curve-4.d new file mode 100644 index 0000000000..31d8603260 --- /dev/null +++ b/Task/Dragon-curve/D/dragon-curve-4.d @@ -0,0 +1,19 @@ +import grayscale_image, turtle; + +void drawDragon(Color)(Image!Color img, ref Turtle t, in uint depth, + in real dir, in uint step) { + if (depth == 0) + return t.forward(img, step); + t.right(dir); + img.drawDragon(t, depth - 1, 45.0, step); + t.left(dir * 2); + img.drawDragon(t, depth - 1, -45.0, step); + t.right(dir); +} + +void main() { + auto img = new Image!Gray(500, 700); + auto t = Turtle(180, 510, -90); + img.drawDragon(t, 14, 45.0, 3); + img.savePGM("dragon_curve.pgm"); +} diff --git a/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl b/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl index 565df2d176..5e0c7e282e 100644 --- a/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl +++ b/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl @@ -1,5 +1,17 @@ #!/usr/bin/perl -use warnings; +{{task}} +The Dutch national flag is composed of three coloured bands in the order red then white and lastly blue. The problem posed by [[wp:Edsger Dijkstra|Edsger Dijkstra]] is: +:Given a number of red, blue and white balls in random order, arrange them in the order of the colours Dutch national flag. +When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... + +;This task is to: +# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. +# Sort the balls in a way idiomatic to your language. +# Check the sorted balls ''are'' in the order of the Dutch national flag. + +;Cf. +* [[wp:Dutch national flag problem|Dutch national flag problem]] +* [https://www.google.co.uk/search?rlz=1C1DSGK_enGB472GB472use warnings; use strict; use 5.010; # // diff --git a/Task/Dutch-national-flag-problem/SQL/dutch-national-flag-problem.sql b/Task/Dutch-national-flag-problem/SQL/dutch-national-flag-problem.sql new file mode 100644 index 0000000000..a8cc5866ca --- /dev/null +++ b/Task/Dutch-national-flag-problem/SQL/dutch-national-flag-problem.sql @@ -0,0 +1,35 @@ +-- Create and populate tables +create table colours (id integer primary key, name varchar(5)); +insert into colours (id, name) values ( 1, 'red' ); +insert into colours (id, name) values ( 2, 'white'); +insert into colours (id, name) values ( 3, 'blue' ); + +create table balls ( colour integer references colours ); +insert into balls ( colour ) values ( 2 ); +insert into balls ( colour ) values ( 2 ); +insert into balls ( colour ) values ( 3 ); +insert into balls ( colour ) values ( 2 ); +insert into balls ( colour ) values ( 1 ); +insert into balls ( colour ) values ( 3 ); +insert into balls ( colour ) values ( 3 ); +insert into balls ( colour ) values ( 2 ); + +-- Show the balls are unsorted +select + colours.name +from + balls + join colours on balls.colour = colours.id; + +-- Show the balls in dutch flag order +select + colours.name +from + balls + join colours on balls.colour = colours.id +order by + colours.id; + +-- Tidy up +drop table balls; +drop table colours; diff --git a/Task/Dynamic-variable-names/Deja-Vu/dynamic-variable-names.djv b/Task/Dynamic-variable-names/Deja-Vu/dynamic-variable-names.djv new file mode 100644 index 0000000000..83cc10871d --- /dev/null +++ b/Task/Dynamic-variable-names/Deja-Vu/dynamic-variable-names.djv @@ -0,0 +1,5 @@ +local :var-name !run-blob !compile-string dup concat( ":" !prompt "Enter a variable name: " ) +local var-name 42 + +#Assuming the user types THISISWEIRD, otherwise this'll error +!. THISISWEIRD diff --git a/Task/Dynamic-variable-names/JavaScript/dynamic-variable-names.js b/Task/Dynamic-variable-names/JavaScript/dynamic-variable-names-1.js similarity index 100% rename from Task/Dynamic-variable-names/JavaScript/dynamic-variable-names.js rename to Task/Dynamic-variable-names/JavaScript/dynamic-variable-names-1.js diff --git a/Task/Dynamic-variable-names/JavaScript/dynamic-variable-names-2.js b/Task/Dynamic-variable-names/JavaScript/dynamic-variable-names-2.js new file mode 100644 index 0000000000..7ca5c1cd79 --- /dev/null +++ b/Task/Dynamic-variable-names/JavaScript/dynamic-variable-names-2.js @@ -0,0 +1,3 @@ +var varname = prompt('Variable name:'); +var value = 42; +this[varname] = value; diff --git a/Task/Echo-server/Seed7/echo-server.seed7 b/Task/Echo-server/Seed7/echo-server.seed7 new file mode 100644 index 0000000000..4b7e9cc0ad --- /dev/null +++ b/Task/Echo-server/Seed7/echo-server.seed7 @@ -0,0 +1,29 @@ +$ include "seed7_05.s7i"; + include "socket.s7i"; + include "listener.s7i"; + +const proc: main is func + local + var listener: aListener is listener.value; + var file: existingConnection is STD_NULL; + var file: newConnection is STD_NULL; + begin + aListener := openInetListener(12321); + listen(aListener, 10); + while TRUE do + waitForRequest(aListener, existingConnection, newConnection); + if existingConnection <> STD_NULL then + if eof(existingConnection) then + writeln("Close connection " <& numericAddress(address(existingConnection)) <& + " port " <& port(existingConnection)); + close(existingConnection); + else + write(existingConnection, gets(existingConnection, 1024)); + end if; + end if; + if newConnection <> STD_NULL then + writeln("New connection " <& numericAddress(address(newConnection)) <& + " port " <& port(newConnection)); + end if; + end while; + end func; diff --git a/Task/Element-wise-operations/D/element-wise-operations-2.d b/Task/Element-wise-operations/D/element-wise-operations-2.d index fe3a550091..cb561d43a2 100644 --- a/Task/Element-wise-operations/D/element-wise-operations-2.d +++ b/Task/Element-wise-operations/D/element-wise-operations-2.d @@ -3,7 +3,7 @@ import std.stdio, std.typetuple, std.traits; T[][] elementwise(string op, T, U)(in T[][] A, in U B) @safe pure nothrow if (isNumeric!U || (isArray!U && isArray!(ForeachType!U) && - isNumeric!(ForeachType!(ForeachType!U)))) { + isNumeric!(ForeachType!(ForeachType!U)))) { static if (!isNumeric!U) assert(A.length == B.length); if (!A.length) @@ -22,13 +22,13 @@ if (isNumeric!U || (isArray!U && isArray!(ForeachType!U) && } void main() { - /*immutable*/ const matrix = [[3, 5, 7], - [1, 2, 3], - [2, 4, 6]]; enum scalar = 2; enum matFormat = "[%([%(%d, %)],\n %)]]\n"; + immutable matrix = [[3, 5, 7], + [1, 2, 3], + [2, 4, 6]]; - foreach (op; TypeTuple!("+", "-", "*", "/", "^^")) { + foreach (immutable op; TypeTuple!("+", "-", "*", "/", "^^")) { writeln(op, ":"); writefln(matFormat, elementwise!op(matrix, scalar)); writefln(matFormat, elementwise!op(matrix, matrix)); diff --git a/Task/Empty-program/BASIC/empty-program-3.basic b/Task/Empty-program/BASIC/empty-program-3.basic new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/C++/empty-program.cpp b/Task/Empty-program/C++/empty-program.cpp index 705f51bc26..979a1cd784 100644 --- a/Task/Empty-program/C++/empty-program.cpp +++ b/Task/Empty-program/C++/empty-program.cpp @@ -1,11 +1 @@ -int main ( int /*argc*/, char * * /*argv*/ ) -{ - // Unused arguments should not be named - // There are variations: - // 1: main ''may'' explicitly return a value - // (other non-void-returning C++ functions ''must'' do so, - // but there's a special exception for main that falling off it - // without an explicit return is equivalent to a "return 0;" at - // the end of the main function) - // 2: The arguments may be omitted entirely -} +int main(){} diff --git a/Task/Empty-program/REXX/empty-program-1.rexx b/Task/Empty-program/REXX/empty-program-1.rexx index 40a8c178f1..a23f9fdc47 100644 --- a/Task/Empty-program/REXX/empty-program-1.rexx +++ b/Task/Empty-program/REXX/empty-program-1.rexx @@ -1 +1 @@ -/* empty */ +/*comment*/ diff --git a/Task/Empty-program/REXX/empty-program-3.rexx b/Task/Empty-program/REXX/empty-program-3.rexx index 0bc8e7f4b9..76138cf7f3 100644 --- a/Task/Empty-program/REXX/empty-program-3.rexx +++ b/Task/Empty-program/REXX/empty-program-3.rexx @@ -1 +1 @@ -/* REXX */ +/*REXX*/ diff --git a/Task/Empty-program/REXX/empty-program-4.rexx b/Task/Empty-program/REXX/empty-program-4.rexx new file mode 100644 index 0000000000..7893e47dd7 --- /dev/null +++ b/Task/Empty-program/REXX/empty-program-4.rexx @@ -0,0 +1 @@ +/*this REXX program calculates if a date is a workday for the XYZ Company.*/ diff --git a/Task/Empty-program/Rust/empty-program.rust b/Task/Empty-program/Rust/empty-program.rust new file mode 100644 index 0000000000..90278189fd --- /dev/null +++ b/Task/Empty-program/Rust/empty-program.rust @@ -0,0 +1 @@ +fn main(){} diff --git a/Task/Empty-string/Deja-Vu/empty-string.djv b/Task/Empty-string/Deja-Vu/empty-string.djv index bcfbbd4860..844633b521 100644 --- a/Task/Empty-string/Deja-Vu/empty-string.djv +++ b/Task/Empty-string/Deja-Vu/empty-string.djv @@ -1,7 +1,7 @@ local :e "" if not e: - print "an empty string" + !print "an empty string" if e: - print "not an empty string" + !print "not an empty string" diff --git a/Task/Enforced-immutability/REXX/enforced-immutability.rexx b/Task/Enforced-immutability/REXX/enforced-immutability.rexx new file mode 100644 index 0000000000..8c389d8b3c --- /dev/null +++ b/Task/Enforced-immutability/REXX/enforced-immutability.rexx @@ -0,0 +1,37 @@ +/*REXX pgm emulates immutable variables (as a post-computational check).*/ +call immutable '$=1' /* ◄─── assigns an immutable var.*/ +call immutable ' pi = 3.14159' /* ◄─── " " " " */ +call immutable 'radius= 2*pi/4 ' /* ◄─── " " " " */ +call immutable ' r=13/2 ' /* ◄─── " " " " */ +call immutable ' d=0002 * r' /* ◄─── " " " " */ +call immutable ' f.1 = 12**2 ' /* ◄─── " " " " */ + +say ' $ =' $ /*show variable, just to be sure.*/ +say ' pi =' pi /* " " " " " " */ +say ' radius =' radius /* " " " " " " */ +say ' r =' r /* " " " " " " */ +say ' d =' d /* " " " " " " */ + + do radius=10 to -10 by -1 /*perform some stuff*/ + circum=$*pi*2*radius /*some kind of calc.*/ + end /*k*/ /*that should do it.*/ +call immutable /* ◄═══ check if immutables OK. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────IMMUTABLE subroutine────────────────*/ +immutable: if symbol('immutable.0')=='LIT' then immutable.0= /*1st time*/ +if arg()==0 then do /* [↓] check all immutable vars.*/ + do __=1 for words(immutable.0); _=word(immutable.0,__) + if value(_)==value('IMMUTABLE.!'_) then iterate /*same?*/ + call ser -12, 'immutable variable ' _ " compromised." + end /*__*/ /* [↑] if an error, ERRmsg, exit*/ + return 0 /*return to invoker, indicate OK.*/ + end /* [↓] immutable var must have =*/ +if pos('=',arg(1))==0 then call ser -4, 'no equal sign in assignment:' arg(1) +parse arg _ '=' __; upper _; _=space(_) /*purify var name.*/ +if symbol('_')=='BAD' then call ser -8,_ "isn't a valid variable symbol." +immutable.0=immutable.0 _ /*add immutable var to the list. */ +interpret '__='__; call value _,__ /*assign a value to a variable. */ +call value 'IMMUTABLE.!'_,__ /*also, assign value to bkup. var*/ +return words(immutable.0) /*return the # of immutable vars.*/ +/*──────────────────────────────────SER subroutine──────────────────────*/ +ser: say; say '***error!***' arg(2); say; exit arg(1) /*ERRmsg.*/ diff --git a/Task/Entropy/00DESCRIPTION b/Task/Entropy/00DESCRIPTION index 5830ee3680..70ec8e6324 100644 --- a/Task/Entropy/00DESCRIPTION +++ b/Task/Entropy/00DESCRIPTION @@ -5,3 +5,5 @@ Entropy is the [[wp:Expected value|expected value]] of the measure of [[wp:Self- where the information content I(x) = -\log_{b} P(x). If the base of the logarithm b = 2, the result is expressed in ''bits'', a [[wp:Units of information|unit of information]]. Therefore, given a string S of length n where P(s_i) is the relative frequency of each character, the entropy of a string in bits is: :H(S) = -\sum_{i=0}^n P(s_i) \log_2 (P(s_i)) For this task, use "1223334444" as an example. The result should be around 1.84644 bits. + +Related Task: [[Fibonacci_word]] diff --git a/Task/Entropy/Emacs-Lisp/entropy-1.l b/Task/Entropy/Emacs-Lisp/entropy-1.l new file mode 100644 index 0000000000..b279c9be69 --- /dev/null +++ b/Task/Entropy/Emacs-Lisp/entropy-1.l @@ -0,0 +1,15 @@ +(defun shannon-entropy (input) + (let ((freq-table (make-hash-table)) + (entropy 0) + (length (+ (length input) 0.0))) + (mapcar (lambda (x) + (puthash x + (+ 1 (gethash x freq-table 0)) + freq-table)) + input) + (maphash (lambda (k v) + (set 'entropy (+ entropy + (* (/ v length) + (log (/ v length) 2))))) + freq-table) + (- entropy))) diff --git a/Task/Entropy/Emacs-Lisp/entropy-2.l b/Task/Entropy/Emacs-Lisp/entropy-2.l new file mode 100644 index 0000000000..bff725d9fa --- /dev/null +++ b/Task/Entropy/Emacs-Lisp/entropy-2.l @@ -0,0 +1,2 @@ +(shannon-entropy "1223334444") +1.8464393446710154 diff --git a/Task/Entropy/Groovy/entropy-1.groovy b/Task/Entropy/Groovy/entropy-1.groovy new file mode 100644 index 0000000000..ea7a92b5b3 --- /dev/null +++ b/Task/Entropy/Groovy/entropy-1.groovy @@ -0,0 +1,6 @@ +String.metaClass.getShannonEntrophy = { + -delegate.inject([:]) { map, v -> map[v] = (map[v] ?: 0) + 1; map }.values().inject(0.0) { sum, v -> + def p = (BigDecimal)v / delegate.size() + sum + p * Math.log(p) / Math.log(2) + } +} diff --git a/Task/Entropy/Groovy/entropy-2.groovy b/Task/Entropy/Groovy/entropy-2.groovy new file mode 100644 index 0000000000..f4c788e66a --- /dev/null +++ b/Task/Entropy/Groovy/entropy-2.groovy @@ -0,0 +1,11 @@ +[ '1223334444': '1.846439344671', + '1223334444555555555': '1.969811065121', + '122333': '1.459147917061', + '1227774444': '1.846439344671', + aaBBcccDDDD: '1.936260027482', + '1234567890abcdefghijklmnopqrstuvwxyz': '5.169925004424', + 'Rosetta Code': '3.084962500407' ].each { s, expected -> + + println "Checking $s has a shannon entrophy of $expected" + assert sprintf('%.12f', s.shannonEntrophy) == expected +} diff --git a/Task/Entropy/REXX/entropy-2.rexx b/Task/Entropy/REXX/entropy-2.rexx index f93af99bea..ad5b26abe2 100644 --- a/Task/Entropy/REXX/entropy-2.rexx +++ b/Task/Entropy/REXX/entropy-2.rexx @@ -6,7 +6,7 @@ * 22.05.2013 Walter Pachl (I won't analyze the minor differences) * 25.05.2013 I did now analyze and had to discover that * 'my' log routine is apparently incorrect -* Correction is yet to come +* 25.05.2013 problem identified & corrected *********************************************************************/ Call both '1223334444' Call both '1223334444555555555' diff --git a/Task/Entropy/Seed7/entropy.seed7 b/Task/Entropy/Seed7/entropy.seed7 new file mode 100644 index 0000000000..0e6215e263 --- /dev/null +++ b/Task/Entropy/Seed7/entropy.seed7 @@ -0,0 +1,29 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const func float: entropy (in string: stri) is func + result + var float: entropy is 0.0; + local + var hash [char] integer: count is (hash [char] integer).value; + var char: ch is ' '; + var float: p is 0.0; + begin + for ch range stri do + if ch in count then + incr(count[ch]); + else + count @:= [ch] 1; + end if; + end for; + for key ch range count do + p := flt(count[ch]) / flt(length(stri)); + entropy -:= p * log(p) / log(2.0); + end for; + end func ; + +const proc: main is func + begin + writeln(entropy("1223334444") digits 5); + end func; diff --git a/Task/Environment-variables/Julia/environment-variables.julia b/Task/Environment-variables/Julia/environment-variables.julia new file mode 100644 index 0000000000..0c912e901f --- /dev/null +++ b/Task/Environment-variables/Julia/environment-variables.julia @@ -0,0 +1 @@ +ENV["HOME"] diff --git a/Task/Environment-variables/Scala/environment-variables.scala b/Task/Environment-variables/Scala/environment-variables.scala new file mode 100644 index 0000000000..2cf8d75d4c --- /dev/null +++ b/Task/Environment-variables/Scala/environment-variables.scala @@ -0,0 +1,9 @@ +object Environment_variables extends App { + + val variablesToUse = List("PATH", "HOME", "HOMEPATH", "USERNAME") + println((for { + y <- sys.env + x <- variablesToUse + if y._1 == x + } yield y).sorted.toMap.mkString("\n")) +} diff --git a/Task/Equilibrium-index/D/equilibrium-index-1.d b/Task/Equilibrium-index/D/equilibrium-index-1.d index f0ebf2afda..edbcc1112a 100644 --- a/Task/Equilibrium-index/D/equilibrium-index-1.d +++ b/Task/Equilibrium-index/D/equilibrium-index-1.d @@ -2,7 +2,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*/ { +auto equilibrium(Range)(Range r) pure nothrow { return r.length.iota.filter!(i => r[0 .. i].S == r[i + 1 .. $].S); } diff --git a/Task/Equilibrium-index/Java/equilibrium-index.java b/Task/Equilibrium-index/Java/equilibrium-index.java index 8d341ec86d..49ccd2e43d 100644 --- a/Task/Equilibrium-index/Java/equilibrium-index.java +++ b/Task/Equilibrium-index/Java/equilibrium-index.java @@ -1,20 +1,23 @@ -import java.util.Arrays; - public class Equlibrium { - private static int[] sequence = {-7, 1, 5, 2, -4, 3, 0}; - public static void main(String[] args) { - System.out.println("Equilibrium indices of " + Arrays.toString(sequence)+":"); + int[] sequence = {-7, 1, 5, 2, -4, 3, 0}; + equlibrium_indices(sequence); + } + + public static void equlibrium_indices(int[] sequence){ + //find total sum + int totalSum = 0; + for (int n : sequence) { + totalSum += n; + } + //compare running sum to remaining sum to find equlibrium indices + int runningSum = 0; for (int i = 0; i < sequence.length; i++) { - int sum = 0; - for (int j = 0; j < sequence.length; j++) { - if (j < i) - sum += sequence[j]; - if (j > i) - sum -= sequence[j]; - } - if (sum == 0) + int n = sequence[i]; + if (totalSum - runningSum - n == runningSum) { System.out.println(i); + } + runningSum += n; } } } diff --git a/Task/Ethiopian-multiplication/Ruby/ethiopian-multiplication-1.rb b/Task/Ethiopian-multiplication/Ruby/ethiopian-multiplication-1.rb index 84c2352b52..ce571c003c 100644 --- a/Task/Ethiopian-multiplication/Ruby/ethiopian-multiplication-1.rb +++ b/Task/Ethiopian-multiplication/Ruby/ethiopian-multiplication-1.rb @@ -1,13 +1,12 @@ -def even(x); x.even?; end -def halve(x); x/2; end -def double(x); x*2; end +def halve(x) x/2 end +def double(x) x*2 end # iterative -def ethopian_multiply(a, b) +def ethiopian_multiply(a, b) product = 0 while a >= 1 - p [a, b, even(a) ? "STRIKE" : "KEEP"] if $DEBUG - product += b if not even(a) + p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG + product += b unless a.even? a = halve(a) b = double(b) end @@ -15,12 +14,12 @@ def ethopian_multiply(a, b) end # recursive -def rec_ethopian_multiply(a, b) +def rec_ethiopian_multiply(a, b) return 0 if a < 1 - p [a, b, even(a) ? "STRIKE" : "KEEP"] if $DEBUG - (even(a) ? 0 : b) + rec_ethopian_multiply(halve(a), double(b)) + p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG + (a.even? ? 0 : b) + rec_ethiopian_multiply(halve(a), double(b)) end $DEBUG = true # $DEBUG also set to true if "-d" option given a, b = 20, 5 -puts "#{a} * #{b} = #{ethopian_multiply(a,b)}"; puts +puts "#{a} * #{b} = #{ethiopian_multiply(a,b)}"; puts diff --git a/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d index 21a486d431..7fb8e2cb4f 100644 --- a/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d +++ b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d @@ -1,6 +1,4 @@ -import std.stdio, std.bigint; - -T binomial(T)(/*in*/ T n, T k) /*pure nothrow*/ { +T binomial(T)(in T n, T k) pure /*nothrow*/ { if (k > (n / 2)) k = n - k; T bc = 1; @@ -10,7 +8,9 @@ T binomial(T)(/*in*/ T n, T k) /*pure nothrow*/ { } void main() { + import std.stdio, std.bigint; + foreach (d; [[5, 3], [100, 2], [100, 98]]) writefln("(%3d %3d) = %s", d[0], d[1], binomial(d[0], d[1])); - writeln("(100 50) = ", binomial(BigInt(100), BigInt(50))); + writeln("(100 50) = ", binomial(100.BigInt, 50.BigInt)); } diff --git a/Task/Evaluate-binomial-coefficients/Go/evaluate-binomial-coefficients.go b/Task/Evaluate-binomial-coefficients/Go/evaluate-binomial-coefficients.go index 4d8d7c580c..682ca059c3 100644 --- a/Task/Evaluate-binomial-coefficients/Go/evaluate-binomial-coefficients.go +++ b/Task/Evaluate-binomial-coefficients/Go/evaluate-binomial-coefficients.go @@ -4,4 +4,5 @@ import "math/big" func main() { fmt.Println(new(big.Int).Binomial(5, 3)) + fmt.Println(new(big.Int).Binomial(60, 30)) } diff --git a/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 index fb38c40fef..0c0bb0da3e 100644 --- a/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 +++ b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 @@ -1,9 +1,3 @@ -multi sub postfix:(Int $a) { - [*] 1..$a; -} +sub infix:($n, $k) { ([*] $n-$k+1 .. $n) / [*] 2 .. $k } -sub binomialcoefficient($n, $k) { - $n! / (($n - $k)! * $k!); -} - -say binomialcoefficient(5, 3); +say 5 choose 3; diff --git a/Task/Even-or-odd/Batch-File/even-or-odd.bat b/Task/Even-or-odd/Batch-File/even-or-odd.bat new file mode 100644 index 0000000000..808359977b --- /dev/null +++ b/Task/Even-or-odd/Batch-File/even-or-odd.bat @@ -0,0 +1,14 @@ +@echo off +set /p i=Insert number: + +::bitwise and +set /a "test1=%i%&1" + +::divide last character by 2 +set /a test2=%i:~-1%/2 + +::modulo +set /a test3=%i% %% 2 + +set test +pause>nul diff --git a/Task/Even-or-odd/Deja-Vu/even-or-odd.djv b/Task/Even-or-odd/Deja-Vu/even-or-odd.djv new file mode 100644 index 0000000000..8a46f4e75d --- /dev/null +++ b/Task/Even-or-odd/Deja-Vu/even-or-odd.djv @@ -0,0 +1,10 @@ +even n: + = 0 % n 2 + +odd: + not even + +!. odd 0 +!. even 0 +!. odd 7 +!. even 7 diff --git a/Task/Even-or-odd/GAP/even-or-odd.gap b/Task/Even-or-odd/GAP/even-or-odd.gap new file mode 100644 index 0000000000..5a0bad373b --- /dev/null +++ b/Task/Even-or-odd/GAP/even-or-odd.gap @@ -0,0 +1,2 @@ +IsEvenInt(n); +IsOddInt(n); diff --git a/Task/Even-or-odd/Julia/even-or-odd.julia b/Task/Even-or-odd/Julia/even-or-odd.julia new file mode 100644 index 0000000000..00277145c4 --- /dev/null +++ b/Task/Even-or-odd/Julia/even-or-odd.julia @@ -0,0 +1 @@ +iseven(i), isodd(i) diff --git a/Task/Evolutionary-algorithm/Ruby/evolutionary-algorithm.rb b/Task/Evolutionary-algorithm/Ruby/evolutionary-algorithm.rb index c5f0685498..58a3d90e3b 100644 --- a/Task/Evolutionary-algorithm/Ruby/evolutionary-algorithm.rb +++ b/Task/Evolutionary-algorithm/Ruby/evolutionary-algorithm.rb @@ -1,9 +1,8 @@ @target = "METHINKS IT IS LIKE A WEASEL" -Charset = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" -Max_mutate_rate = 0.91 -C = 100 +Charset = [" ", *"A".."Z"] +COPIES = 100 -def random_char; Charset[rand Charset.length].chr; end +def random_char; Charset.sample end def fitness(candidate) sum = 0 @@ -31,10 +30,10 @@ while parent != @target iteration += 1 rate = mutation_rate(parent) if prev != parent - log iteration, rate, parent + log(iteration, rate, parent) prev = parent end - copies = [parent] + Array.new(C) {mutate(parent, rate)} + copies = [parent] + Array.new(COPIES) {mutate(parent, rate)} parent = copies.max_by {|c| fitness(c)} end -log iteration, rate, parent +log(iteration, rate, parent) diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-1.c b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-1.c index 5d2618f99b..0a6cb92611 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-1.c +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-1.c @@ -1,73 +1,119 @@ #include #include -#include -#include -#define try push_handler(); if (!exc_string) -#define catch(e) pop_handler(e); for (; exc_string; exc_string = 0) +typedef struct exception { + int extype; + char what[128]; +} exception; -ucontext_t *exc; -int exc_depth = 0; -int exc_alloc = 0; -const char * exc_string; +typedef struct exception_ctx { + exception * exs; + int size; + int pos; +} exception_ctx; -void throw(const char *str) -{ - exc_string = str; - setcontext(exc + exc_depth - 1); +exception_ctx * Create_Ex_Ctx(int length) { + const int safety = 8; // alignment precaution. + char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length); + if (! tmp) return NULL; + exception_ctx * ctx = (exception_ctx*)tmp; + ctx->size = length; + ctx->pos = -1; + ctx->exs = (exception*) (tmp + sizeof(exception_ctx)); + return ctx; } -void push_handler() -{ - exc_string = 0; - if (exc_alloc <= exc_depth) { - exc_alloc += 16; - exc = realloc(exc, sizeof(ucontext_t) * exc_alloc); +void Free_Ex_Ctx(exception_ctx * ctx) { + free(ctx); +} + +int Has_Ex(exception_ctx * ctx) { + return (ctx->pos >= 0) ? 1 : 0; +} + +int Is_Ex_Type(exception_ctx * exctx, int extype) { + return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0; +} + +void Pop_Ex(exception_ctx * ctx) { + if (ctx->pos >= 0) --ctx->pos; +} + +const char * Get_What(exception_ctx * ctx) { + if (ctx->pos >= 0) return ctx->exs[ctx->pos].what; + return NULL; +} + +int Push_Ex(exception_ctx * exctx, int extype, const char * msg) { + if (++exctx->pos == exctx->size) { + // Use last slot and report error. + --exctx->pos; + fprintf(stderr, "*** Error: Overflow in exception context.\n"); } - getcontext(exc + exc_depth++); + snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg); + exctx->exs[exctx->pos].extype = extype; + return -1; } -void pop_handler(const char *e) -{ - exc_depth --; - if (exc_string && strcmp(e, exc_string)) { - if (exc_depth > 0) - throw(exc_string); - fprintf(stderr, "Fatal: unhandled exception %s\n", exc_string); - exit(1); +////////////////////////////////////////////////////////////////////// + +exception_ctx * GLOBALEX = NULL; +enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR }; + +void baz(int n) { + if (! n) { + Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz."); + return; + } + else { + Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz."); + return; } } -/* try out the exception system */ - -void baz() { - static int count = 0; - switch (count++) { - case 0: throw("U0"); - case 1: throw("U1"); - case 2: throw("U2"); - } +void bar(int n) { + fprintf(stdout, "Bar door is open.\n"); + baz(n); + if (Has_Ex(GLOBALEX)) goto bar_cleanup; + fprintf(stdout, "Baz has been called without errors.\n"); +bar_cleanup: + fprintf(stdout, "Bar door is closed.\n"); } -void foo() -{ - printf(" foo: calling baz\n"); - try { baz(); } - catch("U0") { - printf(" foo: got exception U0; handled and dandy\n"); +void foo() { + fprintf(stdout, "Foo entering bar.\n"); + bar(0); + while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { + fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); + Pop_Ex(GLOBALEX); } - - printf(" foo: finished\n"); + if (Has_Ex(GLOBALEX)) return; + fprintf(stdout, "Foo left the bar.\n"); + fprintf(stdout, "Foo entering bar again.\n"); + bar(1); + while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { + fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); + Pop_Ex(GLOBALEX); + } + if (Has_Ex(GLOBALEX)) return; + fprintf(stdout, "Foo left the bar.\n"); } -int main() { - int i; - for (i = 0; i < 3; i++) { - printf("main: calling foo: %d\n", i); - try { foo(); } - catch("U1") { - printf("main: Someone threw U1; handled and dandy\n"); - } + +int main(int argc, char ** argv) { + exception_ctx * ctx = Create_Ex_Ctx(5); + GLOBALEX = ctx; + + foo(); + if (Has_Ex(ctx)) goto main_ex; + + fprintf(stdout, "No errors encountered.\n"); + +main_ex: + while (Has_Ex(ctx)) { + fprintf(stderr, "*** Error: %s\n", Get_What(ctx)); + Pop_Ex(ctx); } + Free_Ex_Ctx(ctx); return 0; } diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c index 6361d8dee7..087671ccf1 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c @@ -1,10 +1,9 @@ -main: calling foo: 0 - foo: calling baz - foo: got exception U0; handled and dandy - foo: finished -main: calling foo: 1 - foo: calling baz -main: Someone threw U1; handled and dandy -main: calling foo: 2 - foo: calling baz -Unhandled exception U2 +Foo entering bar. +Bar door is open. +Bar door is closed. +I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [U0 Drink Error. Insufficient drinks in bar Baz.] +Foo left the bar. +Foo entering bar again. +Bar door is open. +Bar door is closed. +*** Error: U1 Bartender Error. Bartender kicked customer out of bar Baz. diff --git a/Task/Exceptions/Deja-Vu/exceptions.djv b/Task/Exceptions/Deja-Vu/exceptions.djv new file mode 100644 index 0000000000..00d0609648 --- /dev/null +++ b/Task/Exceptions/Deja-Vu/exceptions.djv @@ -0,0 +1,7 @@ +stuff-going-wrong: + raise :value-error + +try: + stuff-going-wrong +catch value-error: + !print "Whoops!" diff --git a/Task/Executable-library/Deja-Vu/executable-library-1.djv b/Task/Executable-library/Deja-Vu/executable-library-1.djv new file mode 100644 index 0000000000..030827b6e3 --- /dev/null +++ b/Task/Executable-library/Deja-Vu/executable-library-1.djv @@ -0,0 +1,36 @@ +local hailstone: + swap [ over ] + while < 1 dup: + if % over 2: + #odd + ++ * 3 + else: + #even + / swap 2 + swap push-through rot dup + drop + +if = (name) :(main): + local :h27 hailstone 27 + !. = 112 len h27 + !. = 27 h27! 0 + !. = 82 h27! 1 + !. = 41 h27! 2 + !. = 124 h27! 3 + !. = 8 h27! 108 + !. = 4 h27! 109 + !. = 2 h27! 110 + !. = 1 h27! 111 + + local :max 0 + local :maxlen 0 + for i range 1 99999: + dup len hailstone i + if < maxlen: + set :maxlen + set :max i + else: + drop + !print( "number: " to-str max ", length: " to-str maxlen ) +else: + @hailstone diff --git a/Task/Executable-library/Deja-Vu/executable-library-2.djv b/Task/Executable-library/Deja-Vu/executable-library-2.djv new file mode 100644 index 0000000000..93d50bcba1 --- /dev/null +++ b/Task/Executable-library/Deja-Vu/executable-library-2.djv @@ -0,0 +1,12 @@ +!import!hailstone + +local :counts {} +set-default counts 0 +for i range 1 99999: + set-to counts swap ++ counts! dup len hailstone i + +local :maxlen 0 +for k in keys counts: + if < maxlen counts! k: + set :maxlen counts! k +!print( "Maximum length: " to-str maxlen ) diff --git a/Task/Executable-library/Limbo/executable-library-1.limbo b/Task/Executable-library/Limbo/executable-library-1.limbo new file mode 100644 index 0000000000..cda7ab5019 --- /dev/null +++ b/Task/Executable-library/Limbo/executable-library-1.limbo @@ -0,0 +1,53 @@ +implement Execlib; + +include "sys.m"; sys: Sys; +include "draw.m"; + +Execlib: module { + init: fn(ctxt: ref Draw->Context, args: list of string); + hailstone: fn(i: big): list of big; +}; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + + seq := hailstone(big 27); + l := len seq; + + sys->print("hailstone(27): "); + for(i := 0; i < 4; i++) { + sys->print("%bd, ", hd seq); + seq = tl seq; + } + sys->print("⋯"); + + while(len seq > 4) + seq = tl seq; + + while(seq != nil) { + sys->print(", %bd", hd seq); + seq = tl seq; + } + sys->print(" (length %d)\n", l); + + max := 1; + maxn := big 1; + for(n := big 2; n < big 100000; n++) { + cur := len hailstone(n); + if(cur > max) { + max = cur; + maxn = n; + } + } + sys->print("hailstone(%bd) has length %d\n", maxn, max); +} + +hailstone(i: big): list of big +{ + if(i == big 1) + return big 1 :: nil; + if(i % big 2 == big 0) + return i :: hailstone(i / big 2); + return i :: hailstone(big 3 * i + big 1); +} diff --git a/Task/Executable-library/Limbo/executable-library-2.limbo b/Task/Executable-library/Limbo/executable-library-2.limbo new file mode 100644 index 0000000000..9241c88ddc --- /dev/null +++ b/Task/Executable-library/Limbo/executable-library-2.limbo @@ -0,0 +1,45 @@ +implement ExecsExeclib; + +include "sys.m"; sys: Sys; +include "draw.m"; + +ExecsExeclib: module { + init: fn(ctxt: ref Draw->Context, args: list of string); +}; + +# Usually, this would be placed into something like "execlib.m", +# but it's fine here. +Execlib: module { + hailstone: fn(i: big): list of big; +}; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + # This program expects that the result of compiling Execlib is execlib.dis, + # so you'll need to adjust this line if you used a different filename. + lib := load Execlib "execlib.dis"; + if(lib == nil) + die("Couldn't load execlib.dis"); + + counts := array[352] of { * => 0 }; + for(i := 1; i < 100000; i++) { + counts[len lib->hailstone(big i)]++; + } + + max := 0; + maxi := 0; + for(i = 1; i < len counts; i++) { + if(counts[i] > max) { + max = counts[i]; + maxi = i; + } + } + sys->print("The most common sequence length is %d (encountered %d times)\n", maxi, max); +} + +die(s: string) +{ + sys->fprint(sys->fildes(2), "runls: %s: %r", s); + raise "fail:errors"; +} diff --git a/Task/Execute-Brain----/AWK/execute-brain----.awk b/Task/Execute-Brain----/AWK/execute-brain----.awk new file mode 100644 index 0000000000..1efc5b4c0d --- /dev/null +++ b/Task/Execute-Brain----/AWK/execute-brain----.awk @@ -0,0 +1,60 @@ +BEGIN { + compile(ARGV[1]) + execute() +} + +# Strips non-instructions, builds the jump table. +function compile(s, i,j,k,f) { + c = split(s, src, "") + j = 0 + for(i = 1; i <= c; i++) { + if(src[i] ~ /[\-\+\[\]\<\>,\.]/) + code[j++] = src[i] + + if(src[i] == "[") { + marks[j] = 1 + } else if(src[i] == "]") { + f = 0 + for(k = j; k > 0; k--) { + if(k in marks) { + jump[k-1] = j - 1 + jump[j-1] = k - 1 + f = 1 + delete marks[k] + break + } + } + if(!f) { + print "Unmatched ]" + exit 1 + } + } + } +} + +function execute( pc,p,i) { + pc = p = 0 + while(pc in code) { + i = code[pc] + + if(i == "+") + arena[p]++ + else if(i == "-") + arena[p]-- + else if(i == "<") + p-- + else if(i == ">") + p++ + 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") + } else if((i == "[" && arena[p] == 0) || + (i == "]" && arena[p] != 0)) + pc = jump[pc] + pc++ + } +} diff --git a/Task/Execute-Brain----/BASIC/execute-brain----.basic b/Task/Execute-Brain----/BASIC/execute-brain----.basic new file mode 100644 index 0000000000..277fcf60fd --- /dev/null +++ b/Task/Execute-Brain----/BASIC/execute-brain----.basic @@ -0,0 +1,41 @@ +0 ON NOT T GOTO 20 : FOR A = T TO L : B = PEEK(S + P) : ON C%(ASC(MID$(C$, A, T))) GOSUB 1, 2, 3, 4, 5, 8, 6, 7 : NEXT A : END +1 P = P + T : ON P < E GOTO 11 : O = 1E99 +2 P = P - T : ON P > M GOTO 11 : O = 1E99 +3 B = B + T : B = B - (B > U) * B : GOTO 9 +4 B = B - T : B = B - (B < 0) * (B - U) : GOTO 9 +5 PRINT CHR$(B); : RETURN +6 D = T : ON NOT B GOTO 10 : RETURN +7 D = M : ON NOT NOT B GOTO 10 : RETURN +8 GET B$ : B = LEN(B$) : IF B THEN B = ASC(B$) +9 POKE S + P, B : RETURN +10 FOR K = D TO 0 STEP 0 : A = A + D : K = K + D%(ASC(MID$(C$, A, T))) : NEXT K : RETURN +11 RETURN +20 HIMEM: 38401 +21 LOMEM: 8185 +22 DIM C%(14999) : CLEAR +23 POKE 105, PEEK(175) +24 POKE 106, PEEK(176) +25 POKE 107, PEEK(175) +26 POKE 108, PEEK(176) +27 POKE 109, PEEK(175) +28 POKE 110, PEEK(176) +29 HIMEM: 8192 +30 T = 1 +31 M = -1 +32 S = 8192 +33 E = 30000 +34 U = 255 +35 DIM C%(255), D%(255) +43 C%(ASC("+")) = 3 +44 C%(ASC(",")) = 6 +45 C%(ASC("-")) = 4 +46 C%(ASC(".")) = 5 +60 C%(ASC("<")) = 2 +62 C%(ASC(">")) = 1 +91 C%(ASC("[")) = 7 +92 D%(ASC("[")) = 1 +93 C%(ASC("]")) = 8 +94 D%(ASC("]")) = -1 +95 C$ = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>>---.+++++++..+++.>.<<-.>.+++.------.--------.>+.>++.+++." +98 L = LEN(C$) +99 GOTO diff --git a/Task/Execute-Brain----/Limbo/execute-brain----.limbo b/Task/Execute-Brain----/Limbo/execute-brain----.limbo new file mode 100644 index 0000000000..29f208ee29 --- /dev/null +++ b/Task/Execute-Brain----/Limbo/execute-brain----.limbo @@ -0,0 +1,102 @@ +implement Bf; + +include "sys.m"; sys: Sys; +include "draw.m"; + +Bf: module { + init: fn(nil: ref Draw->Context, args: list of string); + ARENASZ: con 1024 * 1024; + EXIT, INC, DEC, JZ, JNZ, INCP, DECP, READ, WRITE: con iota; +}; + +init(nil: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + args = tl args; + if(args == nil || len args != 1) { + sys->fprint(sys->fildes(2), "usage: bf program"); + raise "fail:usage"; + } + code := compile(hd args); + execute(code, array[ARENASZ] of { * => byte 0 }); +} + +compile(p: string): array of int +{ + marks: list of int = nil; + code := array[len p * 2 + 1] of { * => EXIT }; + pc := 0; + for(i := 0; i < len p; i++) { + case p[i] { + '-' => code[pc++] = DEC; + '+' => code[pc++] = INC; + '<' => code[pc++] = DECP; + '>' => code[pc++] = INCP; + ',' => code[pc++] = READ; + '.' => code[pc++] = WRITE; + '[' => + code[pc++] = JZ; + marks = pc++ :: marks; + ']' => + if(marks == nil) { + sys->fprint(sys->fildes(2), "bf: unmatched ']' at character %d.", pc); + raise "fail:errors"; + } + c := hd marks; + marks = tl marks; + code[pc++] = JNZ; + code[c] = pc; + code[pc++] = c; + } + } + if(marks != nil) { + sys->fprint(sys->fildes(2), "bf: unmatched '['."); + raise "fail:errors"; + } + return code; +} + +execute(code: array of int, arena: array of byte) +{ + pc := 0; + p := 0; + buf := array[1] of byte; + stopreading := 0; + for(;;) { + case code[pc] { + DEC => arena[p]--; + INC => arena[p]++; + DECP => + p--; + if(p < 0) + p = len arena - 1; + INCP => + p = (p + 1) % len arena; + READ => + if(!stopreading) { + n := sys->read(sys->fildes(0), buf, 1); + if(n < 1) { + arena[p] = byte 0; + stopreading = 1; + } else { + arena[p] = buf[0]; + } + } + WRITE => + buf[0] = arena[p]; + sys->write(sys->fildes(1), buf, 1); + JNZ => + if(arena[p] != byte 0) + pc = code[pc + 1]; + else + pc++; + JZ => + if(arena[p] == byte 0) + pc = code[pc + 1]; + else + pc++; + EXIT => return; + } + pc++; + } +} diff --git a/Task/Execute-Brain----/Mathematica/execute-brain-----1.math b/Task/Execute-Brain----/Mathematica/execute-brain-----1.math index bdcc3228a9..f279438e2a 100644 --- a/Task/Execute-Brain----/Mathematica/execute-brain-----1.math +++ b/Task/Execute-Brain----/Mathematica/execute-brain-----1.math @@ -1,6 +1,6 @@ bf[program_, input_] := Module[{p = Characters[program], pp = 0, m, mp = 0, bc = 0, - instr = StringToStream[input], + instr = StringToStream[input]}, m[_] = 0; While[pp < Length@p, pp++; @@ -9,7 +9,7 @@ bf[program_, input_] := "<", mp--, "+", m[mp]++, "-", m[mp]--, - ".", BinaryWrite[OutputStream["stdout", 1], m[mp]], + ".", BinaryWrite["stdout", m[mp]], ",", m[mp] = BinaryRead[instr], "[", If[m[mp] == 0, bc = 1; diff --git a/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv b/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv index 0024c58baf..1d63f0eab9 100644 --- a/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv +++ b/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv @@ -18,11 +18,7 @@ [ markov-parse: - ] - while dup input: - pass - [ - (markov-parse) (remove-comments) + (markov-parse) (remove-comments) split !decode!utf-8 !read!stdin "\n" (markov-tick) rules start: for rule in copy rules: @@ -44,4 +40,4 @@ markov rules: while: not (markov-tick) rules -markov markov-parse +!. markov markov-parse get-from !args 1 diff --git a/Task/Execute-a-Markov-algorithm/Prolog/execute-a-markov-algorithm-1.pro b/Task/Execute-a-Markov-algorithm/Prolog/execute-a-markov-algorithm-1.pro new file mode 100644 index 0000000000..7e6b87ed99 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Prolog/execute-a-markov-algorithm-1.pro @@ -0,0 +1,88 @@ +:- module('markov.pl', [markov/3, apply_markov/3]). + +:- use_module(library(lambda)). + +apply_markov(Rules, Sentence, Replacement) :- + maplist(\X^Y^(atom_chars(X, Ch), phrase(markov(Y), Ch, [])), Rules, TmpRules), + % comments produce empty rules + exclude(=([]), TmpRules, LstRules), + + atom_chars(Sentence, L), + apply_rules(L, LstRules, R), + atom_chars(Replacement, R). + +apply_rules(In, Rules, Out ) :- + apply_one_rule(In, Rules, Out1, Keep_On), + ( Keep_On = false + -> Out = Out1 + ; apply_rules(Out1, Rules, Out)). + + +apply_one_rule(In, [Rule | Rules], Out, Keep_On) :- + extract(Rule, In, Out1, KeepOn), + ( KeepOn = false + -> Out = Out1, Keep_On = KeepOn + ; (KeepOn = stop + -> Out = Out1, + Keep_On = true + ; apply_one_rule(Out1, Rules, Out, Keep_On))). + +apply_one_rule(In, [], In, false) . + + +extract([Pattern, Replace], In, Out, Keep_On) :- + ( Replace = [.|Rest] + -> R = Rest + ; R = Replace), + ( (append(Pattern, End, T), append(Deb, T, In)) + -> extract([Pattern, Replace], End, NewEnd, _Keep_On), + append_3(Deb, R, NewEnd, Out), + Keep_On = stop + ; Out = In, + ( R = Replace + -> Keep_On = true + ; Keep_On = false)). + + +append_3(A, B, C, D) :- + append(A, B, T), + append(T, C, D). + +% creation of the rules +markov(A) --> line(A). + +line(A) --> text(A), newline. + + +newline --> ['\n'], newline. +newline --> []. + +text([]) --> comment([]). +text(A) --> rule(A). + +comment([]) --> ['#'], anything. + +anything --> [X], {X \= '\n'}, anything. +anything --> ['\n']. +anything --> []. + +rule([A,B]) --> + pattern(A), whitespaces, ['-', '>'], whitespaces, end_rule(B). + +pattern([X | R]) --> [X], {X \= '\n'}, pattern(R). +pattern([]) --> []. + +whitespaces --> ['\t'], whitespace. +whitespaces --> [' '], whitespace. + +whitespace --> whitespaces. +whitespace --> []. + +end_rule([.| A]) --> [.], rest_of_rule(A). +end_rule(A) --> rest_of_rule(A). +end_rule([]) --> []. + +rest_of_rule(A) --> replacement(A). + +replacement([X | R]) --> [X], {X \= '\n'}, replacement(R). +replacement([]) --> []. diff --git a/Task/Execute-a-Markov-algorithm/Prolog/execute-a-markov-algorithm-2.pro b/Task/Execute-a-Markov-algorithm/Prolog/execute-a-markov-algorithm-2.pro new file mode 100644 index 0000000000..4441a9a6cf --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Prolog/execute-a-markov-algorithm-2.pro @@ -0,0 +1,117 @@ +:- use_module('markov.pl'). +:- use_module(library(lambda)). + +markov :- + maplist(\X^(call(X), nl,nl), [markov_1, markov_2, markov_3, markov_4, markov_5]). + +markov_1 :- + A = ['# This rules file is extracted from Wikipedia:', + '# http://en.wikipedia.org/wiki/Markov_Algorithm', + 'A -> apple', + 'B -> bag', + 'S -> shop', + 'T -> the', + 'the shop -> my brother', + 'a never used -> .terminating rule'], + B = 'I bought a B of As from T S.', + apply_markov(A, B, R), + writeln(B), + writeln(R). + + +markov_2 :- + A = ['# Slightly modified from the rules on Wikipedia', + 'A -> apple', + 'B -> bag', + 'S -> .shop', + 'T -> the', + 'the shop -> my brother', + 'a never used -> .terminating rule'], + + B = 'I bought a B of As from T S.', + + apply_markov(A, B, R), + writeln(B), + writeln(R). + + +markov_3 :- + A = ['# BNF Syntax testing rules', + 'A -> apple', + 'WWWW -> with', + 'Bgage -> ->.*', + 'B -> bag', + '->.* -> money', + 'W -> WW', + 'S -> .shop', + 'T -> the', + 'the shop -> my brother', + 'a never used -> .terminating rule'], + + B = 'I bought a B of As W my Bgage from T S.', + + apply_markov(A, B, R), + writeln(B), + writeln(R). + + +markov_4 :- + A = ['### Unary Multiplication Engine, for testing Markov Algorithm implementations', + '### By Donal Fellows.', + '# Unary addition engine', + '_+1 -> _1+', + '1+1 -> 11+', + '# Pass for converting from the splitting of multiplication into ordinary', + '# addition', + '1! -> !1', + ',! -> !+', + '_! -> _', + '# Unary multiplication by duplicating left side, right side times', + '1*1 -> x,@y', + '1x -> xX', + 'X, -> 1,1', + 'X1 -> 1X', + '_x -> _X', + ',x -> ,X', + 'y1 -> 1y', + 'y_ -> _', + '# Next phase of applying', + '1@1 -> x,@y', + '1@_ -> @_', + ',@_ -> !_', + '++ -> +', + '# Termination cleanup for addition', + '_1 -> 1', + '1+_ -> 1', + '_+_ -> '], + + B = '_1111*11111_', + + apply_markov(A, B, R), + writeln(B), + writeln(R). + +markov_5 :- + A = ['# Turing machine: three-state busy beaver', + '#', + '# state A, symbol 0 => write 1, move right, new state B', + 'A0 -> 1B', + '# state A, symbol 1 => write 1, move left, new state C', + '0A1 -> C01', + '1A1 -> C11', + '# state B, symbol 0 => write 1, move left, new state A', + '0B0 -> A01', + '1B0 -> A11', + '# state B, symbol 1 => write 1, move right, new state B', + 'B1 -> 1B', + '# state C, symbol 0 => write 1, move left, new state B', + '0C0 -> B01', + '1C0 -> B11', + '# state C, symbol 1 => write 1, move left, halt', + '0C1 -> H01', + '1C1 -> H11'], + + B = '000000A000000', + apply_markov(A, B, R), + writeln(B), + writeln(R). diff --git a/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm-1.rb b/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm-1.rb new file mode 100644 index 0000000000..bee781e49a --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm-1.rb @@ -0,0 +1,20 @@ +def setup(ruleset) + ruleset.each_line.inject([]) do |rules, line| + if line =~ /^\s*#/ + rules + elsif line =~ /^(.+)\s+->\s+(\.?)(.*)$/ + rules << [$1, $3, $2 != ""] + else + raise "Syntax error: #{line}" + end + end +end + +def morcov(ruleset, input_data) + rules = setup(ruleset) + while (matched = rules.find { |match, replace, term| + input_data[match] and input_data.sub!(match, replace) + }) and !matched[2] + end + input_data +end diff --git a/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm-2.rb b/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm-2.rb new file mode 100644 index 0000000000..6e5c640778 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm-2.rb @@ -0,0 +1,96 @@ +ruleset1 = < apple +B -> bag +S -> shop +T -> the +the shop -> my brother +a never used -> .terminating rule +EOS + +puts morcov(ruleset1, "I bought a B of As from T S.") + +ruleset2 = < apple +B -> bag +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule +EOS + +puts morcov(ruleset2, "I bought a B of As from T S.") + +ruleset3 = < apple +WWWW -> with +Bgage -> ->.* +B -> bag +->.* -> money +W -> WW +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule +EOS + +puts morcov(ruleset3, "I bought a B of As W my Bgage from T S.") + +ruleset4 = < _1+ +1+1 -> 11+ +# Pass for converting from the splitting of multiplication into ordinary +# addition +1! -> !1 +,! -> !+ +_! -> _ +# Unary multiplication by duplicating left side, right side times +1*1 -> x,@y +1x -> xX +X, -> 1,1 +X1 -> 1X +_x -> _X +,x -> ,X +y1 -> 1y +y_ -> _ +# Next phase of applying +1@1 -> x,@y +1@_ -> @_ +,@_ -> !_ +++ -> + +# Termination cleanup for addition +_1 -> 1 +1+_ -> 1 +_+_ -> +EOS + +puts morcov(ruleset4, "_1111*11111_") + +ruleset5 = < write 1, move right, new state B +A0 -> 1B +# state A, symbol 1 => write 1, move left, new state C +0A1 -> C01 +1A1 -> C11 +# state B, symbol 0 => write 1, move left, new state A +0B0 -> A01 +1B0 -> A11 +# state B, symbol 1 => write 1, move right, new state B +B1 -> 1B +# state C, symbol 0 => write 1, move left, new state B +0C0 -> B01 +1C0 -> B11 +# state C, symbol 1 => write 1, move left, halt +0C1 -> H01 +1C1 -> H11 +EOS + +puts morcov(ruleset5, "000000A000000") diff --git a/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm.rb b/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm.rb deleted file mode 100644 index 2d25124cda..0000000000 --- a/Task/Execute-a-Markov-algorithm/Ruby/execute-a-markov-algorithm.rb +++ /dev/null @@ -1,20 +0,0 @@ -raise "Please input an input code file, an input data file, and an output file." if ARGV.size < 3 - -rules = File.readlines(ARGV[0]).inject([]) do |rules, line| - if line =~ /^\s*#/ - rules - elsif line =~ /^(.+)\s+->\s+(\.?)(.*)$/ - rules << [$1, $3, $2 != ""] - else - raise "Syntax error: #{line}" - end -end - -File.open(ARGV[2], "w") do |file| - file.write(File.read(ARGV[1]).tap { |input_data| - while (matched = rules.find { |match, replace, term| - input_data[match] and input_data.sub!(match, replace) - }) and !matched[2] - end - }) -end diff --git a/Task/Execute-a-system-command/Groovy/execute-a-system-command.groovy b/Task/Execute-a-system-command/Groovy/execute-a-system-command.groovy new file mode 100644 index 0000000000..77dc08f9e2 --- /dev/null +++ b/Task/Execute-a-system-command/Groovy/execute-a-system-command.groovy @@ -0,0 +1 @@ +println "ls -la".execute().text diff --git a/Task/Execute-a-system-command/Limbo/execute-a-system-command.limbo b/Task/Execute-a-system-command/Limbo/execute-a-system-command.limbo new file mode 100644 index 0000000000..8c8fec4a55 --- /dev/null +++ b/Task/Execute-a-system-command/Limbo/execute-a-system-command.limbo @@ -0,0 +1,24 @@ +implement Runls; + +include "sys.m"; sys: Sys; +include "draw.m"; +include "sh.m"; + +Runls: module { + init: fn(ctxt: ref Draw->Context, args: list of string); +}; + +init(ctxt: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + ls := load Command "/dis/ls.dis"; + if(ls == nil) + die("Couldn't load /dis/ls.dis"); + ls->init(ctxt, "ls" :: tl args); +} + +die(s: string) +{ + sys->fprint(sys->fildes(2), "runls: %s: %r", s); + raise "fail:errors"; +} diff --git a/Task/Exponentiation-operator/C/exponentiation-operator.c b/Task/Exponentiation-operator/C/exponentiation-operator.c index a888838e40..04ce076199 100644 --- a/Task/Exponentiation-operator/C/exponentiation-operator.c +++ b/Task/Exponentiation-operator/C/exponentiation-operator.c @@ -36,8 +36,8 @@ double dpow(double base, int exp) int main() { - printf("2^6 = %d\n", (int)ipow(2,6)); - printf("2^-6 = %lf\n", ipow(2,-6)); + printf("2^6 = %d\n", ipow(2,6)); + printf("2^-6 = %d\n", ipow(2,-6)); printf("2.71^6 = %lf\n", dpow(2.71,6)); printf("2.71^-6 = %lf\n", dpow(2.71,-6)); } diff --git a/Task/Exponentiation-operator/Forth/exponentiation-operator-3.fth b/Task/Exponentiation-operator/Forth/exponentiation-operator-3.fth new file mode 100644 index 0000000000..ce3e5bee49 --- /dev/null +++ b/Task/Exponentiation-operator/Forth/exponentiation-operator-3.fth @@ -0,0 +1,11 @@ +: pow ( n m -- n^m ) +( written in Retro Forth ) +1 2rot +[ + dup 1 and 0 <> + [ [ tuck * swap ] dip ] ifTrue + [ dup * ] dip + 1 >> + dup 0 <> +] while +drop drop ; diff --git a/Task/Exponentiation-operator/PicoLisp/exponentiation-operator.l b/Task/Exponentiation-operator/PicoLisp/exponentiation-operator.l index 46f9b81a4c..60c0e9ff49 100644 --- a/Task/Exponentiation-operator/PicoLisp/exponentiation-operator.l +++ b/Task/Exponentiation-operator/PicoLisp/exponentiation-operator.l @@ -1,8 +1,10 @@ (de ** (X N) # N th power of X - (let Y 1 - (loop - (when (bit? 1 N) - (setq Y (* Y X)) ) - (T (=0 (setq N (>> 1 N))) - Y ) - (setq X (* X X)) ) ) ) + (if (ge0 N) + (let Y 1 + (loop + (when (bit? 1 N) + (setq Y (* Y X)) ) + (T (=0 (setq N (>> 1 N))) + Y ) + (setq X (* X X)) ) ) + 0 ) ) diff --git a/Task/Factorial/Deja-Vu/factorial-1.djv b/Task/Factorial/Deja-Vu/factorial-1.djv new file mode 100644 index 0000000000..ee56797f95 --- /dev/null +++ b/Task/Factorial/Deja-Vu/factorial-1.djv @@ -0,0 +1,6 @@ +factorial: + 1 + while over: + * over + swap -- swap + drop swap diff --git a/Task/Factorial/Deja-Vu/factorial-2.djv b/Task/Factorial/Deja-Vu/factorial-2.djv new file mode 100644 index 0000000000..89c16dbec3 --- /dev/null +++ b/Task/Factorial/Deja-Vu/factorial-2.djv @@ -0,0 +1,5 @@ +factorial: + if dup: + * factorial -- dup + else: + 1 drop diff --git a/Task/Factorial/Julia/factorial-3.julia b/Task/Factorial/Julia/factorial-3.julia index c71433c6ee..75d4cd9408 100644 --- a/Task/Factorial/Julia/factorial-3.julia +++ b/Task/Factorial/Julia/factorial-3.julia @@ -1 +1 @@ -fact(n) = prod(1:big(n)) +fact(n) = prod(one(n):n) diff --git a/Task/Factorial/Scilab/factorial.scilab b/Task/Factorial/Scilab/factorial.scilab new file mode 100644 index 0000000000..460b7231a1 --- /dev/null +++ b/Task/Factorial/Scilab/factorial.scilab @@ -0,0 +1 @@ +answer = factorial(N) diff --git a/Task/Factorial/VHDL/factorial.vhdl b/Task/Factorial/VHDL/factorial.vhdl new file mode 100644 index 0000000000..25315ccdd4 --- /dev/null +++ b/Task/Factorial/VHDL/factorial.vhdl @@ -0,0 +1,30 @@ +use std.textio.all; + +entity rc is +end entity rc; + +architecture beh of rc is +function fact(n:integer) return integer is + variable f: integer := 1; + variable i: integer; +begin + for i in 2 to n loop + f := f*i; + end loop; + return f; +end; + +begin +process + variable i: integer; + variable l: line; +begin + for i in 0 to 5 loop + write(l, i); + write(l, string'(" ")); + write(l, fact(i)); + writeline(output, l); + end loop; + wait; +end process; +end; diff --git a/Task/Factors-of-a-Mersenne-number/GAP/factors-of-a-mersenne-number.gap b/Task/Factors-of-a-Mersenne-number/GAP/factors-of-a-mersenne-number.gap index 2b479a025e..cafdde74d6 100644 --- a/Task/Factors-of-a-Mersenne-number/GAP/factors-of-a-mersenne-number.gap +++ b/Task/Factors-of-a-Mersenne-number/GAP/factors-of-a-mersenne-number.gap @@ -1,16 +1,19 @@ MersenneSmallFactor := function(n) - local k, m; - if IsPrime(n) then - for k in [1 .. 1000000] do - m := 2*k*n + 1; - if PowerModInt(2, n, m) = 1 then - return m; - fi; - od; - fi; - return fail; + local k, m, d; + if IsPrime(n) then + d := 2*n; + m := 1; + for k in [1 .. 1000000] do + m := m + d; + if PowerModInt(2, n, m) = 1 then + return m; + fi; + od; + fi; + return fail; end; + # If n is not prime, fail immediately MersenneSmallFactor(15); # fail @@ -21,7 +24,7 @@ MersenneSmallFactor(929); MersenneSmallFactor(1009); # 3454817 -# We stop at k = 1000000 in 2*k*n + 1, so it may fail if 2^n - 1 has only large factors +# We stop at k = 1000000 in 2*k*n + 1, so it may fail if 2^n - 1 has only larger factors MersenneSmallFactor(101); # fail diff --git a/Task/Factors-of-a-Mersenne-number/Icon/factors-of-a-mersenne-number.icon b/Task/Factors-of-a-Mersenne-number/Icon/factors-of-a-mersenne-number.icon new file mode 100644 index 0000000000..fbf81e4810 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Icon/factors-of-a-mersenne-number.icon @@ -0,0 +1,32 @@ +procedure main(A) + p := integer(A[1]) | 929 + write("M",p," has a factor ",mfactor(p)) +end + +procedure mfactor(p) + if isPrime(p) then { + limit := sqrt(2^p)-1 + k := 1 + while 2*p*k-1 < limit do { + q := 2*p*k+1 + if isPrime(q) & (q%8 = (1|7)) & btest(p,q) then return q + k +:= 1 + } + } +end + +procedure btest(p, q) + return (2^p % q) = 1 +end + +procedure isPrime(n) + if n%(i := 2|3) = 0 then return n = i; + d := 5 + while d*d <= n do { + if n%d = 0 then fail + d +:= 2 + if n%d = 0 then fail + d +:= 4 + } + return +end diff --git a/Task/Factors-of-a-Mersenne-number/Ruby/factors-of-a-mersenne-number.rb b/Task/Factors-of-a-Mersenne-number/Ruby/factors-of-a-mersenne-number.rb index 31af7e6248..9f41641af2 100644 --- a/Task/Factors-of-a-Mersenne-number/Ruby/factors-of-a-mersenne-number.rb +++ b/Task/Factors-of-a-Mersenne-number/Ruby/factors-of-a-mersenne-number.rb @@ -1,11 +1,11 @@ -require 'mathn' +require 'prime' def mersenne_factor(p) limit = Math.sqrt(2**p - 1) k = 1 while (2*k*p - 1) < limit q = 2*k*p + 1 - if prime?(q) and (q % 8 == 1 or q % 8 == 7) and trial_factor(2,p,q) + if q.prime? and (q % 8 == 1 or q % 8 == 7) and trial_factor(2,p,q) # q is a factor of 2**p-1 return q end @@ -14,16 +14,6 @@ def mersenne_factor(p) nil end -def prime?(value) - return false if value < 2 - png = Prime.new - for prime in png - q,r = value.divmod prime - return true if q < prime - return false if r == 0 - end -end - def trial_factor(base, exp, mod) square = 1 ("%b" % exp).each_char {|bit| square = square**2 * (bit == "1" ? base : 1) % mod} @@ -40,10 +30,5 @@ def check_mersenne(p) end end -png = Prime.new -for p in png - check_mersenne p - break if p == 53 -end -p = 929 -check_mersenne p +Prime.each(53) { |p| check_mersenne p } +check_mersenne 929 diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-1.hs similarity index 100% rename from Task/Factors-of-an-integer/Haskell/factors-of-an-integer.hs rename to Task/Factors-of-an-integer/Haskell/factors-of-an-integer-1.hs diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-2.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-2.hs new file mode 100644 index 0000000000..9c8b0dc7ea --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-2.hs @@ -0,0 +1 @@ +factors_naive n = [i | i <-[1..n], (mod n i) == 0] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-3.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-3.hs new file mode 100644 index 0000000000..4865b7dedb --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-3.hs @@ -0,0 +1,2 @@ +factors_naive 6 +[1,2,3,6] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs new file mode 100644 index 0000000000..6d8edc4c4b --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs @@ -0,0 +1,7 @@ +import Data.List +tuple_to_list lt = (fst lt) ++ (snd lt) +factors_co n = sort (tuple_to_list(unzip + [ (j, (div n j)) | j <- + [i | i <- + [1..truncate (sqrt (fromIntegral n))] + , (mod n i) == 0]] )) diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs new file mode 100644 index 0000000000..b89b91f1fd --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs @@ -0,0 +1,2 @@ +factors_co 6 +[1,2,3,6] diff --git a/Task/Factors-of-an-integer/Julia/factors-of-an-integer.julia b/Task/Factors-of-an-integer/Julia/factors-of-an-integer.julia new file mode 100644 index 0000000000..8f05b3186a --- /dev/null +++ b/Task/Factors-of-an-integer/Julia/factors-of-an-integer.julia @@ -0,0 +1,7 @@ +function factors(n) + f = [one(n)] + for (p,e) in factor(n) + f = reduce(vcat, f, [f*p^j for j in 1:e]) + end + return length(f) == 1 ? [one(n), n] : sort!(f) +end diff --git a/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia new file mode 100644 index 0000000000..8343c6d267 --- /dev/null +++ b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia @@ -0,0 +1 @@ +fft([1,1,1,1,0,0,0,0]) diff --git a/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-2.julia b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-2.julia new file mode 100644 index 0000000000..f06c3cb17c --- /dev/null +++ b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-2.julia @@ -0,0 +1,9 @@ +8-element Array{Complex{Float64},1}: + 4.0+0.0im + 1.0-2.41421im + 0.0+0.0im + 1.0-0.414214im + 0.0+0.0im + 1.0+0.414214im + 0.0+0.0im + 1.0+2.41421im diff --git a/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx b/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx index 95ec69c891..524b15aba4 100644 --- a/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx +++ b/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx @@ -1,5 +1,5 @@ /*REXX pgm does a fast Fourier transform (FFT) on a set of complex nums.*/ -numeric digits 85 +numeric digits length( pi() ) - 1 /*limited by PI function result. */ arg data; if data='' then data='1 1 1 1 0' /*no data? Then use default*/ data=translate(data, 'J', "I") /*allow use of i as well as j */ size=words(data); pad=left('',6) /*PAD: for indenting/padding SAYs*/ diff --git a/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb b/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb new file mode 100644 index 0000000000..ae7723d4c8 --- /dev/null +++ b/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb @@ -0,0 +1,10 @@ +def fft(vec) + return vec if vec.size <= 1 + evens_odds = vec.partition.with_index{|_,i| i.even?} + evens, odds = evens_odds.map{|even_odd| fft(even_odd)*2} + evens.zip(odds).map.with_index do |(even, odd),i| + even + odd * Math::E ** Complex(0, 2 * Math::PI * (-i)/ vec.size) + end +end + +fft([1,1,1,1,0,0,0,0]).each{|c| p c} diff --git a/Task/Fast-Fourier-transform/Scilab/fast-fourier-transform.scilab b/Task/Fast-Fourier-transform/Scilab/fast-fourier-transform.scilab new file mode 100644 index 0000000000..3753a02783 --- /dev/null +++ b/Task/Fast-Fourier-transform/Scilab/fast-fourier-transform.scilab @@ -0,0 +1 @@ +fft([1,1,1,1,0,0,0,0]') diff --git a/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-1.rb b/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-1.rb index 3682cbf212..3b08caa3e8 100644 --- a/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-1.rb +++ b/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-1.rb @@ -3,10 +3,25 @@ def anynacci(start_sequence, count) result = start_sequence.dup # Create a new result array with the values copied from the array that was passed by reference (n+1..count).each do # Loop for the remaining results up to count - tail = result.last(n) # Get the last n elements from result - next_num = tail.reduce(:+) # In Rails: tail.sum - result << next_num # Array append + result << result.last(n).reduce(:+) # Get the last n element from result and append its total to Array end result # Return result end + +naccis = { lucus: [2,1], + fibonacci: [1,1], + tribonacci: [1,1,2], + tetranacci: [1,1,2,4], + pentanacci: [1,1,2,4,8], + hexanacci: [1,1,2,4,8,16], + heptanacci: [1,1,2,4,8,16,32], + octonacci: [1,1,2,4,8,16,32,64], + nonanacci: [1,1,2,4,8,16,32,64,128], + decanacci: [1,1,2,4,8,16,32,64,128,256] } + +def print_nacci(naccis, count=15) + puts naccis.map {|name, seq| "%12s : %p" % [name, anynacci(seq, count)]} +end + +print_nacci(naccis) diff --git a/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-2.rb b/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-2.rb index b9cee748e2..a6c000457e 100644 --- a/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-2.rb +++ b/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-2.rb @@ -1,13 +1,10 @@ -def print_nacci - naccis = { :fibo => [1,1], - :lucas => [2,1], - :tribo => [1,1,2], - :tetra => [1,1,2,4] } - - naccis.each do |name, start_sequence| - nacci_result = anynacci(start_sequence, 10) - puts "#{name}nacci: #{nacci_result}" - end - - nil -end + lucus : [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843] + fibonacci : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] + tribonacci : [1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136] + tetranacci : [1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536] + pentanacci : [1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930] + hexanacci : [1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617] + heptanacci : [1, 1, 2, 4, 8, 16, 32, 64, 127, 253, 504, 1004, 2000, 3984, 7936] + octonacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 255, 509, 1016, 2028, 4048, 8080] + nonanacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144] + decanacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172] diff --git a/Task/Fibonacci-sequence/Burlesque/fibonacci-sequence.blq b/Task/Fibonacci-sequence/Burlesque/fibonacci-sequence-1.blq similarity index 100% rename from Task/Fibonacci-sequence/Burlesque/fibonacci-sequence.blq rename to Task/Fibonacci-sequence/Burlesque/fibonacci-sequence-1.blq diff --git a/Task/Fibonacci-sequence/Burlesque/fibonacci-sequence-2.blq b/Task/Fibonacci-sequence/Burlesque/fibonacci-sequence-2.blq new file mode 100644 index 0000000000..af22f27b6a --- /dev/null +++ b/Task/Fibonacci-sequence/Burlesque/fibonacci-sequence-2.blq @@ -0,0 +1 @@ +0 1{{.+}c!}{1000.<}w! diff --git a/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cobol b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cobol new file mode 100644 index 0000000000..4c4c1900c2 --- /dev/null +++ b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cobol @@ -0,0 +1,40 @@ +Program-ID. Fibonacci-Sequence. +Data Division. +Working-Storage Section. + 01 FIBONACCI-PROCESSING. + 05 FIBONACCI-NUMBER PIC 9(36) VALUE 0. + 05 FIB-ONE PIC 9(36) VALUE 0. + 05 FIB-TWO PIC 9(36) VALUE 1. + 01 DESIRED-COUNT PIC 9(4). + 01 FORMATTING. + 05 INTERM-RESULT PIC Z(35)9. + 05 FORMATTED-RESULT PIC X(36). + 05 FORMATTED-SPACE PIC x(35). +Procedure Division. + 000-START-PROGRAM. + Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing. + Accept DESIRED-COUNT. + If DESIRED-COUNT is less than 1 + Stop run. + If DESIRED-COUNT is less than 2 + Move FIBONACCI-NUMBER to INTERM-RESULT + Move INTERM-RESULT to FORMATTED-RESULT + Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT + Display FORMATTED-RESULT + Stop run. + Subtract 1 from DESIRED-COUNT. + Move FIBONACCI-NUMBER to INTERM-RESULT. + Move INTERM-RESULT to FORMATTED-RESULT. + Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT. + Display FORMATTED-RESULT. + Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero. + Stop run. + 100-COMPUTE-FIBONACCI. + Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO. + Move FIB-TWO to FIB-ONE. + Move FIBONACCI-NUMBER to FIB-TWO. + Subtract 1 from DESIRED-COUNT. + Move FIBONACCI-NUMBER to INTERM-RESULT. + Move INTERM-RESULT to FORMATTED-RESULT. + Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT. + Display FORMATTED-RESULT. diff --git a/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cobol b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cobol new file mode 100644 index 0000000000..05204bf137 --- /dev/null +++ b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cobol @@ -0,0 +1,45 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. fibonacci-main. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 num PIC 9(6) COMP. +01 fib-num PIC 9(6) COMP. + +PROCEDURE DIVISION. + ACCEPT num + CALL "fibonacci" USING CONTENT num RETURNING fib-num + DISPLAY fib-num + . +END PROGRAM fibonacci-main. + +IDENTIFICATION DIVISION. +PROGRAM-ID. fibonacci RECURSIVE. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 1-before PIC 9(6) COMP. +01 2-before PIC 9(6) COMP. + +LINKAGE SECTION. +01 num PIC 9(6) COMP. + +01 fib-num PIC 9(6) COMP BASED. + +PROCEDURE DIVISION USING num RETURNING fib-num. + ALLOCATE fib-num + EVALUATE num + WHEN 0 + MOVE 0 TO fib-num + WHEN 1 + MOVE 1 TO fib-num + WHEN OTHER + SUBTRACT 1 FROM num + CALL "fibonacci" USING CONTENT num RETURNING 1-before + SUBTRACT 1 FROM num + CALL "fibonacci" USING CONTENT num RETURNING 2-before + ADD 1-before TO 2-before GIVING fib-num + END-EVALUATE + . +END PROGRAM fibonacci. diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-1.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-1.lisp index 88b355bdf9..73bea2e31e 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-1.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-1.lisp @@ -1,4 +1,8 @@ -(defun fibonacci-recursive (n) - (if (< n 2) - n - (+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1))))) +(defun fibonacci-iterative (n &aux (f0 0) (f1 1)) + (case n + (0 f0) + (1 f1) + (t (loop for n from 2 to n + for a = f0 then b and b = f1 then result + for result = (+ a b) + finally (return result))))) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp index 73bea2e31e..75b857ae65 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp @@ -1,8 +1,7 @@ -(defun fibonacci-iterative (n &aux (f0 0) (f1 1)) - (case n - (0 f0) - (1 f1) - (t (loop for n from 2 to n - for a = f0 then b and b = f1 then result - for result = (+ a b) - finally (return result))))) +(defun fibonacci (n) + (let ((a 0) (b 1) (c n)) + (loop for i from 2 to n do + (setq c (+ a b) + a b + b c)) + c)) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-3.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-3.lisp index 740efb0487..3b67859ea1 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-3.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-3.lisp @@ -1,4 +1 @@ -(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1)) - (if (= n 0) - a - (fibonacci-tail-recursive (- n 1) b (+ a b)))) +(loop for x = 0 then y and y = 1 then (+ x y) do (print x)) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-4.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-4.lisp index bb4e24a4b8..88b355bdf9 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-4.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-4.lisp @@ -1,9 +1,4 @@ -(defun fib (n &optional (a 1) (b 0) (p 0) (q 1)) - (if (= n 1) (+ (* b p) (* a q)) - (fib (ash n -1) - (if (evenp n) a (+ (* b q) (* a (+ p q)))) - (if (evenp n) b (+ (* b p) (* a q))) - (+ (* p p) (* q q)) - (+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n). - -(print (fib 100000)) +(defun fibonacci-recursive (n) + (if (< n 2) + n + (+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1))))) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-5.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-5.lisp index 3b67859ea1..740efb0487 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-5.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-5.lisp @@ -1 +1,4 @@ -(loop for x = 0 then y and y = 1 then (+ x y) do (print x)) +(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1)) + (if (= n 0) + a + (fibonacci-tail-recursive (- n 1) b (+ a b)))) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-6.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-6.lisp new file mode 100644 index 0000000000..bb4e24a4b8 --- /dev/null +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-6.lisp @@ -0,0 +1,9 @@ +(defun fib (n &optional (a 1) (b 0) (p 0) (q 1)) + (if (= n 1) (+ (* b p) (* a q)) + (fib (ash n -1) + (if (evenp n) a (+ (* b q) (* a (+ p q)))) + (if (evenp n) b (+ (* b p) (* a q))) + (+ (* p p) (* q q)) + (+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n). + +(print (fib 100000)) diff --git a/Task/Fibonacci-sequence/Forth/fibonacci-sequence.fth b/Task/Fibonacci-sequence/Forth/fibonacci-sequence-1.fth similarity index 100% rename from Task/Fibonacci-sequence/Forth/fibonacci-sequence.fth rename to Task/Fibonacci-sequence/Forth/fibonacci-sequence-1.fth diff --git a/Task/Fibonacci-sequence/Forth/fibonacci-sequence-2.fth b/Task/Fibonacci-sequence/Forth/fibonacci-sequence-2.fth new file mode 100644 index 0000000000..74d9a4e6cf --- /dev/null +++ b/Task/Fibonacci-sequence/Forth/fibonacci-sequence-2.fth @@ -0,0 +1,17 @@ +: F-start, here 1 0 dup , ; +: F-next, over + swap + dup 0> IF dup , true ELSE false THEN ; + +: computed-table ( compile: 'start 'next / run: i -- x ) + create + >r execute + BEGIN r@ execute not UNTIL rdrop + does> + swap cells + @ ; + +' F-start, ' F-next, computed-table fibonacci 2drop +here swap - cell/ Constant #F/64 \ # of fibonacci numbers generated + +16 fibonacci . 987 ok +#F/64 . 93 ok +92 fibonacci . 7540113804746346429 ok \ largest number generated. diff --git a/Task/Fibonacci-sequence/GML/fibonacci-sequence.gml b/Task/Fibonacci-sequence/GML/fibonacci-sequence.gml new file mode 100644 index 0000000000..9ab80133ac --- /dev/null +++ b/Task/Fibonacci-sequence/GML/fibonacci-sequence.gml @@ -0,0 +1,25 @@ +///fibonacci(n) +//Returns the nth fibonacci number + +var n, numb; +n = argument0; + +if (n == 0) + { + numb = 0; + } +else + { + var fm2, fm1; + fm2 = 0; + fm1 = 1; + numb = 1; + repeat(n-1) + { + numb = fm2+fm1; + fm2 = fm1; + fm1 = numb; + } + } + +return numb; diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs new file mode 100644 index 0000000000..00d8c20448 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs @@ -0,0 +1 @@ +let fib x = if x < 1 then 0 else (if x < 3 then 1 else (fib(x - 1) + fib(x - 2))) diff --git a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp new file mode 100644 index 0000000000..3494dc9551 --- /dev/null +++ b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp @@ -0,0 +1,8 @@ +(define (fibonacci n) + (let (a 0 b 1 c n i 2) + (while (<= i n) + (setq c (+ a b) + a b + b c) + (++ i)) + c)) diff --git a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence.newlisp b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-2.newlisp similarity index 100% rename from Task/Fibonacci-sequence/NewLISP/fibonacci-sequence.newlisp rename to Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-2.newlisp diff --git a/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod b/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod index 8c5e772f5f..5ee44b1b2c 100644 --- a/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod +++ b/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod @@ -1,10 +1,10 @@ -proc Fibonacci(n: int): int64 = - var first: int64 = 0 - var second: int64 = 1 - var t: int64 = 0 - while n > 1: - t = first + second - first = second - second = t - dec(n) - result = second +proc Fibonacci(n: int): int = + var + first = 0 + second = 1 + + for i in 0 .. 'GMP'; + +sub fib_iter +{ + my ($n) = @_; + + my $this_fib = Math::BigInt->new(0); + my $next_fib = Math::BigInt->new(1); + + my $pos = 0; + + while ($pos < $n) + { + ($this_fib, $next_fib) = ($next_fib, $this_fib+$next_fib); + } + continue + { + $pos++; + } + + return $this_fib; } diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py new file mode 100644 index 0000000000..4bb8438a9e --- /dev/null +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py @@ -0,0 +1,30 @@ +def prevPowTwo(n): + 'Gets the power of two that is less than or equal to the given input' + if ((n & -n) == n): + return n + else: + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + n += 1 + return (n/2) + +def crazyFib(n): + 'Crazy fast fibonacci number calculation' + powTwo = prevPowTwo(n) + + q = r = i = 1 + s = 0 + + while(i < powTwo): + i *= 2 + q, r, s = q*q + r*r, r * (q + s), (r*r + s*s) + + while(i < n): + i += 1 + q, r, s = q+r, q, r + + return q diff --git a/Task/File-IO/BASIC/file-io.basic b/Task/File-IO/BASIC/file-io-1.basic similarity index 100% rename from Task/File-IO/BASIC/file-io.basic rename to Task/File-IO/BASIC/file-io-1.basic diff --git a/Task/File-IO/BASIC/file-io-2.basic b/Task/File-IO/BASIC/file-io-2.basic new file mode 100644 index 0000000000..ab05afe9b9 --- /dev/null +++ b/Task/File-IO/BASIC/file-io-2.basic @@ -0,0 +1,20 @@ +100 I$ = "INPUT.TXT" +110 O$ = "OUTPUT.TXT" +120 D$ = CHR$(4) +130 M$ = CHR$(13) +140 PRINT D$"VERIFY"I$ +150 PRINT D$"OPEN"O$M$D$"CLOSE"O$M$D$"DELETE"O$ +160 PRINT D$"OPEN"O$M$D$"OPEN"I$; + +170 PRINT M$D$"READ"I$ +180 ONERR GOTO 250 +190 GET C$ +200 POKE 216,0 +210 PRINT M$D$"WRITE"O$",B"B +220 IF C$ <> M$ THEN PRINT C$; +230 B = B + 1 +240 GOTO 170 + +250 POKE 216,0 +260 IF PEEK(222) <> 5 THEN RESUME +270 PRINT M$D$"CLOSE"I$M$D$"CLOSE"O$ diff --git a/Task/File-IO/GML/file-io.gml b/Task/File-IO/GML/file-io.gml index 0778164a48..42d83a3faa 100644 --- a/Task/File-IO/GML/file-io.gml +++ b/Task/File-IO/GML/file-io.gml @@ -1 +1,21 @@ -file_copy("input.txt","output.txt") +var file, str; +file = file_text_open_read("input.txt"); +str = ""; +while (true) + { + str += file_text_read_string(file); + if (file_text_eof(file)) + { + break; + } + else + { + str += chr(vk_enter); + file_text_readln(file); + } + } +file_text_close(file); + +file = file_text_open_write("output.txt"); +file_text_write_string(file,str); +file_text_close(file); diff --git a/Task/File-IO/Java/file-io-4.java b/Task/File-IO/Java/file-io-4.java index 6bccf168c9..3c480152da 100644 --- a/Task/File-IO/Java/file-io-4.java +++ b/Task/File-IO/Java/file-io-4.java @@ -4,7 +4,7 @@ public class Test { BufferedReader br = new BufferedReader(new FileReader("input.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); String line; - while (line = br.readLine() != null) { + while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } diff --git a/Task/File-IO/Rust/file-io.rust b/Task/File-IO/Rust/file-io.rust new file mode 100644 index 0000000000..212f6e82c3 --- /dev/null +++ b/Task/File-IO/Rust/file-io.rust @@ -0,0 +1,20 @@ +extern mod std; +use std::io; + +fn main() { + let input_file = &Path("input.txt"); + let input = io::read_whole_file_str(input_file); + match input { + Err(e) => fail!(e), + Ok(_) => {} + } + + let output_file = &Path("output.txt"); + let output = io::file_writer(output_file, [io::Create, io::Truncate]); + match output { + Err(e) => fail!(e), + Ok(_) => {} + } + + output.unwrap().write_str(input.unwrap()); +} diff --git a/Task/File-modification-time/VBScript/file-modification-time.vb b/Task/File-modification-time/VBScript/file-modification-time.vb new file mode 100644 index 0000000000..ea77a468e3 --- /dev/null +++ b/Task/File-modification-time/VBScript/file-modification-time.vb @@ -0,0 +1 @@ +WScript.Echo CreateObject("Scripting.FileSystemObject").GetFile("input.txt").DateLastModified diff --git a/Task/File-size/Batch-File/file-size.bat b/Task/File-size/Batch-File/file-size.bat new file mode 100644 index 0000000000..84c9126bea --- /dev/null +++ b/Task/File-size/Batch-File/file-size.bat @@ -0,0 +1,4 @@ +@echo off +if not exist "%~1" exit /b 1 & rem If file doesn't exist exit with error code of 1. +for /f %%i in (%~1) do echo %~zi +pause>nul diff --git a/Task/File-size/Julia/file-size.julia b/Task/File-size/Julia/file-size.julia new file mode 100644 index 0000000000..cf65365c57 --- /dev/null +++ b/Task/File-size/Julia/file-size.julia @@ -0,0 +1,2 @@ +println(filesize("input.txt")) +println(filesize("/input.txt")) diff --git a/Task/File-size/VBScript/file-size.vb b/Task/File-size/VBScript/file-size.vb new file mode 100644 index 0000000000..288b9e4a29 --- /dev/null +++ b/Task/File-size/VBScript/file-size.vb @@ -0,0 +1,4 @@ +With CreateObject("Scripting.FileSystemObject") + WScript.Echo .GetFile("input.txt").Size + WScript.Echo .GetFile("\input.txt").Size +End With diff --git a/Task/Filter/Deja-Vu/filter-1.djv b/Task/Filter/Deja-Vu/filter-1.djv new file mode 100644 index 0000000000..8b8b4f96b5 --- /dev/null +++ b/Task/Filter/Deja-Vu/filter-1.djv @@ -0,0 +1,11 @@ +filter pred lst: + ] + for value in copy lst: + if pred @value: + @value + [ + +even x: + = 0 % x 2 + +!. filter @even [ 0 1 2 3 4 5 6 7 8 9 ] diff --git a/Task/Filter/Deja-Vu/filter-2.djv b/Task/Filter/Deja-Vu/filter-2.djv new file mode 100644 index 0000000000..990bff81b7 --- /dev/null +++ b/Task/Filter/Deja-Vu/filter-2.djv @@ -0,0 +1,16 @@ +local :lst [ 0 1 2 3 4 5 6 7 8 9 ] + +filter-destructively pred lst: + local :tmp [] + while lst: + pop-from lst + if pred dup: + push-to tmp + else: + drop + while tmp: + push-to lst pop-from tmp + +filter-destructively @even lst + +!. lst diff --git a/Task/Filter/NetRexx/filter.netrexx b/Task/Filter/NetRexx/filter.netrexx new file mode 100644 index 0000000000..b0831a2ef3 --- /dev/null +++ b/Task/Filter/NetRexx/filter.netrexx @@ -0,0 +1,63 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +numeric digits 5000 + +-- ============================================================================= +class RFilter public + properties indirect + filter = RFilter.ArrayFilter + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method main(args = String[]) public static + arg = Rexx(args) + RFilter().runSample(arg) + return + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method runSample(arg) public + sd1 = Rexx[] + sd2 = Rexx[] + + say 'Test data:' + sd1 = makeSampleData(100) + display(sd1) + setFilter(RFilter.EvenNumberOnlyArrayFilter()) + say + say 'Option 1 (copy to a new array):' + sd2 = getFilter().filter(sd1) + display(sd2) + say + say 'Option 2 (replace the original array):' + sd1 = getFilter().filter(sd1) + display(sd1) + return + -- --------------------------------------------------------------------------- + method display(sd = Rexx[]) public static + say '-'.copies(80) + loop i_ = 0 to sd.length - 1 + say sd[i_] '\-' + end i_ + say + return + -- --------------------------------------------------------------------------- + method makeSampleData(size) public static returns Rexx[] + sd = Rexx[size] + loop e_ = 0 to size - 1 + sd[e_] = (e_ + 1 - size / 2) / 2 + end e_ + return sd + +-- ============================================================================= +class RFilter.ArrayFilter abstract + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method filter(array = Rexx[]) public abstract returns Rexx[] +-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = +class RFilter.EvenNumberOnlyArrayFilter extends RFilter.ArrayFilter + -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + method filter(array = Rexx[]) public returns Rexx[] + clist = ArrayList(Arrays.asList(array)) + li = clist.listIterator() + loop while li.hasNext() + e_ = Rexx li.next + if \e_.datatype('w'), e_ // 2 \= 0 then li.remove() + end + ry = Rexx[] clist.toArray(Rexx[clist.size()]) + return ry diff --git a/Task/Filter/PL-I/filter.pli b/Task/Filter/PL-I/filter.pli new file mode 100644 index 0000000000..befd3b944a --- /dev/null +++ b/Task/Filter/PL-I/filter.pli @@ -0,0 +1,28 @@ +(subscriptrange): +filter_values: procedure options (main); /* 15 November 2013 */ + declare a(20) fixed, b(*) fixed controlled; + declare (i, j, n) fixed binary; + + a = random()*99999; /* fill the array with random elements from 0-99998 */ + put list ('Unfiltered values:'); + put skip edit (a) (f(6)); + /* Loop to count the number of elements that will be filtered */ + n = 0; + do i = 1 to hbound(a); + n = n + filter(a(i)); + end; + allocate b(n); + j = 0; + do i = 1 to hbound(a); + if filter(a(i)) then do; j = j + 1; b(j) = a(i); end; + end; + put skip list ('Filtered values:'); + put skip edit (b) (f(6)); + +filter: procedure (value) returns (bit(1)); + declare value fixed; + + return (iand(abs(value), 1) = 0); +end filter; + +end filter_values; diff --git a/Task/Filter/REXX/filter-1.rexx b/Task/Filter/REXX/filter-1.rexx new file mode 100644 index 0000000000..cf7644116a --- /dev/null +++ b/Task/Filter/REXX/filter-1.rexx @@ -0,0 +1,20 @@ +/*REXX program selects all even numbers from an array ──► a new array.*/ +parse arg N seed . /*get optional parameters from CL*/ +if N=='' | N==',' then N=50 /*Not specified? Then use default*/ +if seed\=='' & seed\==',' then call random ,,seed /*for repeatability.*/ +old.= /*the OLD array, all null so far.*/ +new.= /*the NEW array, all null so far.*/ + do i=1 for N /*gen N random numbers ──► OLD*/ + old.i=random(1,99999) /*randum number 1 ──► 99999 */ + end /*i*/ +#=0 /*numb. of elements in NEW so far*/ + do j=1 for N /*process the OLD array elements.*/ + if old.j//2 \== 0 then iterate /*if element isn't even, skip it.*/ + #=#+1 /*bump the number of NEW elements*/ + new.#=old.j /*assign it to the NEW array. */ + end /*j*/ + + do k=1 for # /*display all the NEW numbers. */ + say right('new.'k, 20) "=" right(new.k,9) /*show a line*/ + end /*k*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Filter/REXX/filter-2.rexx b/Task/Filter/REXX/filter-2.rexx new file mode 100644 index 0000000000..abaf2cadd7 --- /dev/null +++ b/Task/Filter/REXX/filter-2.rexx @@ -0,0 +1 @@ + if old.j//2 \== 0 then iterate diff --git a/Task/Filter/REXX/filter-3.rexx b/Task/Filter/REXX/filter-3.rexx new file mode 100644 index 0000000000..e4739b9fc0 --- /dev/null +++ b/Task/Filter/REXX/filter-3.rexx @@ -0,0 +1 @@ + if old.j//2 then iterate diff --git a/Task/Filter/REXX/filter-4.rexx b/Task/Filter/REXX/filter-4.rexx new file mode 100644 index 0000000000..435497c537 --- /dev/null +++ b/Task/Filter/REXX/filter-4.rexx @@ -0,0 +1,18 @@ +/*REXX pgm find all even numbers from an array, marks a control array. */ +arse arg N seed . /*get optional parameters from CL*/ +f N=='' | N==',' then N=50 /*Not specified? Then use default*/ +f seed\=='' & seed\==',' then call random ,,seed /*for repeatability.*/ + + do i=1 for N /*gen N random numbers ──► OLD*/ + @.i=random(1,99999) /*randum number 1 ──► 99999 */ + end /*i*/ +.=0 /*numb. of elements in NEW so far*/ + do j=1 for N /*process the OLD array elements.*/ + if @.j//2 \==0 then !.j=1 /*mark ! array that it's ¬even.*/ + end /*j*/ + + do k=1 for N /*display all the @ even numbers.*/ + if !.k then iterate /*if it's marked ¬even, skip it.*/ + say right('array.'k, 20) "=" right(@.k,9) /*show a line*/ + end /*k*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Filter/REXX/filter-5.rexx b/Task/Filter/REXX/filter-5.rexx new file mode 100644 index 0000000000..b40d3137b4 --- /dev/null +++ b/Task/Filter/REXX/filter-5.rexx @@ -0,0 +1,18 @@ +/*REXX pgm find all even numbers from an array, marks ¬ even numbers. */ +parse arg N seed . /*get optional parameters from CL*/ +if N=='' | N==',' then N=50 /*Not specified? Then use default*/ +if seed\=='' & seed\==',' then call random ,,seed /*for repeatability.*/ + + do i=1 for N /*gen N random numbers ──► OLD*/ + @.i=random(1,99999) /*randum number 1 ──► 99999 */ + end /*i*/ + + do j=1 for N /*process the OLD array elements.*/ + if @.j//2 \==0 then @.j= /*mark @ array that it's ¬even.*/ + end /*j*/ + + do k=1 for N /*display all the @ even numbers.*/ + if @.k=='' then iterate /*if it's marked ¬even, skip it.*/ + say right('array.'k, 20) "=" right(@.k,9) /*show a line*/ + end /*k*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Filter/REXX/filter.rexx b/Task/Filter/REXX/filter.rexx deleted file mode 100644 index 2445770bc4..0000000000 --- a/Task/Filter/REXX/filter.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program selects all even numbers from an array ──► a new array. */ -numeric digits 210000 /*handle past 1m for Fibonacci.*/ -old.= /*the OLD array, all null so far.*/ -new.= /*the NEW array, all null so far.*/ - do j=-40 to 40; old.j=fib(j); end /*put 81 Fibonacci numbs ==> OLD */ -news=0 /*numb. of elements in NEW so far*/ - -/*══════════════════════════════════════════════════════════════════════*/ - do k=-40 while old.k\=='' /*process the OLD array elements.*/ - if old.k//2 \== 0 then iterate /*if element isn't even, skip it.*/ - news=news+1 /*bump the number of NEW elements*/ - new.news=old.k /*assign it to the NEW array. */ - end -/*══════════════════════════════════════════════════════════════════════*/ - - do j=1 for news /*display all the NEW numbers. */ - say 'new.'j "=" new.j - end -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────FIB subroutine (non-recursive)───*/ -fib: procedure; parse arg n; na=abs(n); if na<2 then return na /*special*/ -a=0; b=1 - do j=2 to na; s=a+b; a=b; b=s; end - -if n>0 | na//2==1 then return s /*if positive or odd negative... */ - else return -s /*return a negative Fib number. */ diff --git a/Task/Filter/UNIX-Shell/filter.sh b/Task/Filter/UNIX-Shell/filter-1.sh similarity index 77% rename from Task/Filter/UNIX-Shell/filter.sh rename to Task/Filter/UNIX-Shell/filter-1.sh index a43b83c6b0..a7287e5943 100644 --- a/Task/Filter/UNIX-Shell/filter.sh +++ b/Task/Filter/UNIX-Shell/filter-1.sh @@ -3,6 +3,3 @@ unset e[@] for ((i=0;i<${#a[@]};i++)); do [ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}" done - -echo "${a[@]}" -echo "${e[@]}" diff --git a/Task/Filter/UNIX-Shell/filter-2.sh b/Task/Filter/UNIX-Shell/filter-2.sh new file mode 100644 index 0000000000..21b9697bb0 --- /dev/null +++ b/Task/Filter/UNIX-Shell/filter-2.sh @@ -0,0 +1,2 @@ +a=(1 2 3 4 5) +read -a e -d\n < <(printf '%s\n' "${a[@]}" | grep '[02468]$') diff --git a/Task/Filter/UNIX-Shell/filter-3.sh b/Task/Filter/UNIX-Shell/filter-3.sh new file mode 100644 index 0000000000..331d11d269 --- /dev/null +++ b/Task/Filter/UNIX-Shell/filter-3.sh @@ -0,0 +1,2 @@ +echo "${a[@]}" +echo "${e[@]}" diff --git a/Task/Find-common-directory-path/D/find-common-directory-path.d b/Task/Find-common-directory-path/D/find-common-directory-path.d index 45ae459205..77d9d447e5 100644 --- a/Task/Find-common-directory-path/D/find-common-directory-path.d +++ b/Task/Find-common-directory-path/D/find-common-directory-path.d @@ -1,15 +1,14 @@ import std.stdio, std.string, std.algorithm, std.path, std.array; -string commonDirPath(in string[] paths, in string sep = "/") -/*pure nothrow*/ { +string commonDirPath(in string[] paths, in string sep = "/") pure { if (paths.empty) return null; return paths.map!(p => p.split(sep)).reduce!commonPrefix.join(sep); } void main() { - auto paths = ["/home/user1/tmp/coverage/test", - "/home/user1/tmp/covert/operator", - "/home/user1/tmp/coven/members"]; + immutable paths = ["/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members"]; writeln(`The common path is: "`, paths.commonDirPath, '"'); } diff --git a/Task/Find-common-directory-path/VBScript/find-common-directory-path.vb b/Task/Find-common-directory-path/VBScript/find-common-directory-path.vb new file mode 100644 index 0000000000..853cc31e65 --- /dev/null +++ b/Task/Find-common-directory-path/VBScript/find-common-directory-path.vb @@ -0,0 +1,31 @@ +' Read the list of paths (newline-separated) into an array... +strPaths = Split(WScript.StdIn.ReadAll, vbCrLf) + +' Split each path by the delimiter (/)... +For i = 0 To UBound(strPaths) + strPaths(i) = Split(strPaths(i), "/") +Next + +With CreateObject("Scripting.FileSystemObject") + + ' Test each path segment... + For j = 0 To UBound(strPaths(0)) + + ' Test each successive path against the first... + For i = 1 To UBound(strPaths) + If strPaths(0)(j) <> strPaths(i)(j) Then Exit For + Next + + ' If we didn't make it all the way through, exit the block... + If i <= UBound(strPaths) Then Exit For + + ' Make sure this path exists... + If Not .FolderExists(strPath & strPaths(0)(j) & "/") Then Exit For + strPath = strPath & strPaths(0)(j) & "/" + + Next + +End With + +' Remove the final "/"... +WScript.Echo Left(strPath, Len(strPath) - 1) diff --git a/Task/Find-limit-of-recursion/Deja-Vu/find-limit-of-recursion.djv b/Task/Find-limit-of-recursion/Deja-Vu/find-limit-of-recursion.djv new file mode 100644 index 0000000000..58e6236997 --- /dev/null +++ b/Task/Find-limit-of-recursion/Deja-Vu/find-limit-of-recursion.djv @@ -0,0 +1,5 @@ +rec-fun n: + !. n + rec-fun ++ n + +rec-fun 0 diff --git a/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion.rb b/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion-1.rb similarity index 51% rename from Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion.rb rename to Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion-1.rb index d2ab4ed35c..7759e39569 100644 --- a/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion.rb +++ b/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion-1.rb @@ -1,6 +1,6 @@ def recurse x - puts x - recurse(x+1) + puts x + recurse(x+1) end recurse(0) diff --git a/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion-2.rb b/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion-2.rb new file mode 100644 index 0000000000..bed12f9ef8 --- /dev/null +++ b/Task/Find-limit-of-recursion/Ruby/find-limit-of-recursion-2.rb @@ -0,0 +1,7 @@ +def recurse n + recurse(n+1) +rescue SystemStackError + n +end + +puts recurse(0) diff --git a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-1.rust b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-1.rust new file mode 100644 index 0000000000..8dead19a30 --- /dev/null +++ b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-1.rust @@ -0,0 +1,8 @@ +fn recurse(n: int) { + println(fmt!("deep: %?", n)); + recurse(n + 1); +} + +fn main() { + recurse(0); +} diff --git a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-2.rust b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-2.rust new file mode 100644 index 0000000000..dbdba9f2dd --- /dev/null +++ b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-2.rust @@ -0,0 +1,8 @@ +fn recurse(n: int) { + println!("deep: {:d}", n); + recurse(n + 1); +} + +fn main() { + recurse(0); +} diff --git a/Task/First-class-environments/REXX/first-class-environments.rexx b/Task/First-class-environments/REXX/first-class-environments.rexx index 3a934a62a7..76e65de839 100644 --- a/Task/First-class-environments/REXX/first-class-environments.rexx +++ b/Task/First-class-environments/REXX/first-class-environments.rexx @@ -1,35 +1,32 @@ /*REXX program illustrates first-class environments (using hailstone #s)*/ -parse arg #envs .; env_.=; if #envs=='' then #envs=12 +parse arg N .; if N=='' then N=12 /*Was N defined? No, use default.*/ +w=length(N) /*the width (so far) for columns.*/ +@.= + do init=1 for N; @.init=init; end /*initialize all the environments*/ -/*═════════════════════════════════════initialize (twelve) environments.*/ - do init=1 for #envs; env_.init=init; end + do forever until @.0; @.0=1 /* ◄─── process all environments.*/ + do k=1 for N; x=hailstone(k); w=max(w,length(x)) + @.k=@.k x /*where the rubber meets the road*/ + end /*k*/ + end /*forever*/ -/*═════════════════════════════════════process environments until done. */ - do forever until env_.0; env_.0=1 - do k=1 for #envs - env_.k=env_.k hailstone(k) /*where the rubber meets the road*/ - end /*k*/ - end /*forever*/ +count=0 /* [↓] show tabular results. */ + do lines=-1 until _==''; _= /*process each line for each env.*/ + do j=1 for N /*process each environment. */ + select /*choose how to process the line.*/ + when count== 1 then _=_ right(words(@.j)-1, w) + when lines==-1 then _=_ right(j, w) /*hdr.*/ + when lines== 0 then _=_ right('', w, '─') /*sep.*/ + otherwise _=_ right(word(@.j, lines), w) + end /*select*/ + end /*j*/ -/*═════════════════════════════════════show results in tabular form. */ -count=0; do lines=-1 until _==''; _= - do j=1 for #envs - select - when count== 1 then _=_ right(words(env_.j)-1,3) - when lines==-1 then _=_ right(j,3) - when lines== 0 then _=_ right('',3,'─') - otherwise _=_ right(word(env_.j,lines),3) - end /*select*/ - end /*j*/ - - if count==1 then count=2 - _=strip(_,'T') - if _=='' then count=count+1 - if count==1 then _=copies(' ═══',#envs) - if _\=='' then say substr(_,2) - end /*lines*/ + if count==1 then count=2 + _=strip(_,'T'); if _=='' then count=count+1 /*if null, bump*/ + if count==1 then _=copies(" "left('', w, "═"), N) /*foot sep*/ + if _\=='' then say substr(_,2) /*show the (foot) counts.*/ + end /*lines*/ exit /*stick a fork in it, we're done.*/ - /*─────────────────────────────────────HAILSTONE (Collatz) subroutine───*/ -hailstone: procedure expose env_.; arg n; _=word(env_.n,words(env_.n)) -if _==1 then return ''; env_.0=0; if _//2==0 then return _%2; return _*3+1 +hailstone: procedure expose @.; parse arg y; _=word(@.y, words(@.y)) +if _==1 then return '' ; @.0=0; if _//2==0 then return _%2; return _*3+1 diff --git a/Task/First-class-environments/Ruby/first-class-environments-1.rb b/Task/First-class-environments/Ruby/first-class-environments-1.rb index 3ab1a5f43a..140dd6e033 100644 --- a/Task/First-class-environments/Ruby/first-class-environments-1.rb +++ b/Task/First-class-environments/Ruby/first-class-environments-1.rb @@ -4,13 +4,13 @@ envs = (1..12).map do |n| end # Until all values are 1: -while envs.find {|e| e.instance_eval {@n} > 1} +until envs.all? {|e| e.instance_eval{@n} == 1} envs.each do |e| e.instance_eval do # Use environment _e_ printf "%4s", @n - unless 1 == @n + if @n > 1 @cnt += 1 # Increment step count - @n = if 1 & @n == 1 # Calculate next hailstone value + @n = if @n.odd? # Calculate next hailstone value @n * 3 + 1 else @n / 2 diff --git a/Task/First-class-environments/Ruby/first-class-environments-2.rb b/Task/First-class-environments/Ruby/first-class-environments-2.rb index 570de7d5b0..548e35b6a6 100644 --- a/Task/First-class-environments/Ruby/first-class-environments-2.rb +++ b/Task/First-class-environments/Ruby/first-class-environments-2.rb @@ -5,34 +5,32 @@ envs = (1..12).map do |n| # Create a new binding here. binding end - eval(<<-'eos', e).call(n) + eval(<<-EOS, e).call(n) n, cnt = nil, 0 proc {|arg| n = arg} - eos - next e + EOS + e end # Until all values are 1: -while envs.find {|e| eval('n > 1', e)} +until envs.all? {|e| eval('n == 1', e)} envs.each do |e| - eval(<<-'eos', e) # Use environment _e_ + eval(<<-EOS, e) # Use environment _e_ printf "%4s", n - unless 1 == n - cnt += 1 # Increment step count - n = if 1 & n == 1 # Calculate next hailstone value + if n > 1 + cnt += 1 # Increment step count + n = if n.odd? # Calculate next hailstone value n * 3 + 1 else n / 2 end end - eos + EOS end puts end puts '=' * 48 envs.each do |e| # For each environment _e_ - eval(<<-'eos', e) - printf "%4s", cnt # print the step count - eos + eval('printf "%4s", cnt', e) # print the step count end puts diff --git a/Task/First-class-functions/Deja-Vu/first-class-functions.djv b/Task/First-class-functions/Deja-Vu/first-class-functions.djv index 1f2a853831..6731867cbb 100644 --- a/Task/First-class-functions/Deja-Vu/first-class-functions.djv +++ b/Task/First-class-functions/Deja-Vu/first-class-functions.djv @@ -1,22 +1,18 @@ -compose f g: - labda: - f g - negate: - 0 -set :A [ @++ compose @negate @-- ] +set :A [ @++ $ @negate @-- ] -set :B [ @-- compose @++ @negate ] +set :B [ @-- $ @++ @negate ] test n: for i range 0 -- len A: - if /= n call compose get-from B i get-from A i n: + if /= n call compose @B! i @A! i n: return false true -test to-num input print\ "Enter a number: " +test to-num !prompt "Enter a number: " if: - print "f^-1(f(x)) = x" + !print "f^-1(f(x)) = x" else: - print "Something went wrong." + !print "Something went wrong." diff --git a/Task/First-class-functions/REXX/first-class-functions.rexx b/Task/First-class-functions/REXX/first-class-functions.rexx new file mode 100644 index 0000000000..1b466cdd4f --- /dev/null +++ b/Task/First-class-functions/REXX/first-class-functions.rexx @@ -0,0 +1,62 @@ +/*REXX pgm demonstrating first-class functions (as a list of functions).*/ +A = 'd2x square sin cos' /*list of functions to test. */ +B = 'x2d sqrt Asin Acos' /*inverse functions of the above.*/ +w=digits() /*W=width of numbers to be shown.*/ + + do j=1 for words(A); say /*do functions: A,B collections.*/ + say center("number",w) center('function',3*w+1) center("inverse",4*w) + say copies("─",w) copies("─",3*w+1) copies("─",4*w) + if j<2 then call test j, 20 60 500 /*x2d,d2x; integers only.*/ + else call test j, 0 0.5 1 2 /*all else, floating pt. */ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────INVOKE subroutine───────────────────*/ +invoke: parse arg fn,v; q='"'; if datatype(v,'N') then q= +_=fn||'('q||v||q')'; interpret 'func='_; return func +/*──────────────────────────────────TEST subroutine─────────────────────*/ +test: procedure expose A B w; parse arg fu,xList /*xList=bunch of #s*/ + do k=1 for words(xList); x=word(xList,k) + numeric digits digits()+5 /*higher precision.*/ + fun=word(A,fu); funV=invoke(fun,x) ; funInvoke=_ + inv=word(B,fu); invV=invoke(inv,funV); invInvoke=_ + numeric digits digits()-5 /*restore precision*/ + if datatype(funV,'N') then funV=funV/1 /*round to digits()*/ + if datatype(invV,'N') then invV=invV/1 /*round to digits()*/ + say center(x,w) right(funInvoke,2*w)'='left(funV,w), + right(invInvoke,3*w)'='left(invV,w) + end /*k*/ +return +/*──────────────────────────────────subroutines (functions)─────────────*/ +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 + do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end + return z + +cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) + if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0 + if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5 + return .sinCos(1,1,-1) + +sin: procedure; 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 + +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*/ + numeric digits m.0; return (g/1)i + +pi: return, /*a bit of overkill, but hey !! */ +3.1415926535897932384626433832795028841971693993751058209749445923078164062862 + +Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) +r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ +square: return arg(1)**2 +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 diff --git a/Task/First-class-functions/Ruby/first-class-functions.rb b/Task/First-class-functions/Ruby/first-class-functions.rb index f07b17e252..adb9034431 100644 --- a/Task/First-class-functions/Ruby/first-class-functions.rb +++ b/Task/First-class-functions/Ruby/first-class-functions.rb @@ -1,12 +1,7 @@ -irb(main):001:0> cube = proc{|x| x ** 3} -=> # -irb(main):002:0> croot = proc{|x| x ** (1.quo 3)} -=> # -irb(main):003:0> compose = proc {|f,g| proc {|x| f[g[x]]}} -=> # -irb(main):004:0> funclist = [Math.method(:sin), Math.method(:cos), cube] -=> [#, #, #] -irb(main):005:0> invlist = [Math.method(:asin), Math.method(:acos), croot] -=> [#, #, #] -irb(main):006:0> funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]} -=> [0.5, 0.4999999999999999, 0.5] +cube = proc{|x| x ** 3} +croot = proc{|x| x ** (1.quo 3)} +compose = proc {|f,g| proc {|x| f[g[x]]}} +funclist = [Math.method(:sin), Math.method(:cos), cube] +invlist = [Math.method(:asin), Math.method(:acos), croot] + +puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]} diff --git a/Task/Five-weekends/Groovy/five-weekends-1.groovy b/Task/Five-weekends/Groovy/five-weekends-1.groovy new file mode 100644 index 0000000000..791e9e3aa9 --- /dev/null +++ b/Task/Five-weekends/Groovy/five-weekends-1.groovy @@ -0,0 +1,17 @@ +enum Day { + Sun, Mon, Tue, Wed, Thu, Fri, Sat + static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } +} + +def date = Date.&parse.curry('yyyy-M-dd') +def isLongMonth = { firstDay -> (firstDay + 31).format('dd') == '01'} + +def fiveWeekends = { years -> + years.collect { year -> + (1..12).collect { month -> + date("${year}-${month}-01") + }.findAll { firstDay -> + isLongMonth(firstDay) && Day.valueOf(firstDay) == Day.Fri + } + }.flatten() +} diff --git a/Task/Five-weekends/Groovy/five-weekends-2.groovy b/Task/Five-weekends/Groovy/five-weekends-2.groovy new file mode 100644 index 0000000000..1c90badd7d --- /dev/null +++ b/Task/Five-weekends/Groovy/five-weekends-2.groovy @@ -0,0 +1,5 @@ +def ym = { it.format('yyyy-MM') } +def years = 1900..2100 +def fiveWeekendMonths = fiveWeekends(years) +println "Number of five weekend months: ${fiveWeekendMonths.size()}" +fiveWeekendMonths.each { println (ym(it)) } diff --git a/Task/Five-weekends/Groovy/five-weekends-3.groovy b/Task/Five-weekends/Groovy/five-weekends-3.groovy new file mode 100644 index 0000000000..9cd2d96d13 --- /dev/null +++ b/Task/Five-weekends/Groovy/five-weekends-3.groovy @@ -0,0 +1,4 @@ +def yearsWith = fiveWeekendMonths.collect { it.format('yyyy') as int } as Set +def yearsWithout = (years as Set) - yearsWith +println "\nNumber of years without a five weekend month: ${yearsWithout.size()}" +yearsWithout.each { println it } diff --git a/Task/Five-weekends/VBScript/five-weekends.vb b/Task/Five-weekends/VBScript/five-weekends.vb new file mode 100644 index 0000000000..6cb146e2e5 --- /dev/null +++ b/Task/Five-weekends/VBScript/five-weekends.vb @@ -0,0 +1,11 @@ +For y = 1900 To 2100 + For m = 1 To 12 + d = DateSerial(y, m + 1, 1) - 1 + If Day(d) = 31 And Weekday(d) = vbSunday Then + WScript.Echo y & ", " & MonthName(m) + i = i + 1 + End If + Next +Next + +WScript.Echo vbCrLf & "Total = " & i & " months" diff --git a/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 b/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 index e3037f0885..3dae559cde 100644 --- a/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 +++ b/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 @@ -11,58 +11,58 @@ ;------------------------------------------------------ ; Constant Section ; -FizzCt = 3 Fizz Counter (must be < 255) -BuzzCt = 5 Buzz Counter (must be < 255) -Lower = 1 Loop start value (must be 1) -Upper = 100 Loop end value (must be < 255) -CharOut = $fded Specific to the Apple II -IntOut = $ed24 Specific to ROM Applesoft +FizzCt = 3 ;Fizz Counter (must be < 255) +BuzzCt = 5 ;Buzz Counter (must be < 255) +Lower = 1 ;Loop start value (must be 1) +Upper = 100 ;Loop end value (must be < 255) +CharOut = $fded ;Specific to the Apple II +IntOut = $ed24 ;Specific to ROM Applesoft ;====================================================== .or $0f00 ;------------------------------------------------------ ; The main program ; -main ldx #Lower init LoopCt +main ldx #Lower ;init LoopCt lda #FizzCt - sta Fizz init FizzCt + sta Fizz ;init FizzCt lda #BuzzCt - sta Buzz init BuzzCt -next ldy #0 reset string pointer (y) - dec Fizz LoopCt mod FizzCt == 0? - bne noFizz yes: + sta Buzz ;init BuzzCt +next ldy #0 ;reset string pointer (y) + dec Fizz ;LoopCt mod FizzCt == 0? + bne noFizz ; yes: lda #FizzCt - sta Fizz restore FizzCt - ldy #sFizz-str point y to "Fizz" - jsr puts output "Fizz" -noFizz dec Buzz LoopCt mod BuzzCt == 0? - bne noBuzz yes: + sta Fizz ; restore FizzCt + ldy #sFizz-str ; point y to "Fizz" + jsr puts ; output "Fizz" +noFizz dec Buzz ;LoopCt mod BuzzCt == 0? + bne noBuzz ; yes: lda #BuzzCt - sta Buzz restore BuzzCt - ldy #sBuzz-str point y to "Buzz" - jsr puts output "Buzz" -noBuzz dey any output yet this cycle? - bpl noInt no: - txa save LoopCt + sta Buzz ; restore BuzzCt + ldy #sBuzz-str ; point y to "Buzz" + jsr puts ; output "Buzz" +noBuzz dey ;any output yet this cycle? + bpl noInt ; no: + txa ; save LoopCt pha - lda #0 set up regs for IntOut - jsr IntOut output itoa(LoopCt) + lda #0 ; set up regs for IntOut + jsr IntOut ; output itoa(LoopCt) pla - tax restore LoopCt + tax ; restore LoopCt noInt ldy #sNL-str - jsr puts output "\n" - inx increment LoopCt - cpx #Upper+1 LoopCt >= Upper+1? - bcc next no: loop back - rts yes: end main + jsr puts ;output "\n" + inx ;increment LoopCt + cpx #Upper+1 ;LoopCt >= Upper+1? + bcc next ; no: loop back + rts ; yes: end main ;------------------------------------------------------ ; Output zero-terminated string @ (str+y) ; (Entry point is puts, not outch) ; -outch jsr CharOut output string char - iny advance string ptr -puts lda str,y get a string char - bne outch output and loop if non-zero - rts return +outch jsr CharOut ;output string char + iny ;advance string ptr +puts lda str,y ;get a string char + bne outch ;output and loop if non-zero + rts ;return ;------------------------------------------------------ ; String literals (in '+128' ascii, Apple II style) ; diff --git a/Task/FizzBuzz/Deja-Vu/fizzbuzz.djv b/Task/FizzBuzz/Deja-Vu/fizzbuzz.djv new file mode 100644 index 0000000000..ef98e6d4f1 --- /dev/null +++ b/Task/FizzBuzz/Deja-Vu/fizzbuzz.djv @@ -0,0 +1,10 @@ +for i range 1 100: + if = 0 % i 15: + "FizzBuzz" + elseif = 0 % i 3: + "Fizz" + elseif = 0 % i 5: + "Buzz" + else: + i + !print diff --git a/Task/FizzBuzz/Icon/fizzbuzz-5.icon b/Task/FizzBuzz/Icon/fizzbuzz-5.icon index eb00ffa789..647da790da 100644 --- a/Task/FizzBuzz/Icon/fizzbuzz-5.icon +++ b/Task/FizzBuzz/Icon/fizzbuzz-5.icon @@ -1,5 +1,5 @@ # idiomatic buffer builder, 1st alternative procedure main() -    every i := 1 to 100 do -        write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i) + every i := 1 to 100 do + write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i) end diff --git a/Task/FizzBuzz/Icon/fizzbuzz-6.icon b/Task/FizzBuzz/Icon/fizzbuzz-6.icon index 360fa81834..b5caab9cd4 100644 --- a/Task/FizzBuzz/Icon/fizzbuzz-6.icon +++ b/Task/FizzBuzz/Icon/fizzbuzz-6.icon @@ -1,8 +1,8 @@ # idiomatic buffer builder, 2nd alternative procedure main() -    every i := 1 to 100 do { -        s   := if i%3 = 0 then "Fizz" else "" -        s ||:= if i%5 = 0 then "Buzz" -        write(("" ~= s) | i) -    } + every i := 1 to 100 do { + s := if i%3 = 0 then "Fizz" else "" + s ||:= if i%5 = 0 then "Buzz" + write(("" ~= s) | i) + } end diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-4.js b/Task/FizzBuzz/JavaScript/fizzbuzz-4.js index 8179b5aff3..04679acfbc 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-4.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-4.js @@ -1,8 +1 @@ -(function() { - var i; - - for (i = 1; i <= 100; i++) { - console.log([i % 3 === 0 ? 'Fizz' : void 0] + [i % 5 === 0 ? 'Buzz' : void 0] || i); - } - -}).call(this); +for(i=0;i<100;console.log(++i%15?i%5?i%3?i:f='Fizz':b='Buzz':f+b)); diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-5.js b/Task/FizzBuzz/JavaScript/fizzbuzz-5.js index 6d37d23951..8179b5aff3 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-5.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-5.js @@ -1,25 +1,8 @@ -var divs = [15, 3, 5]; -var says = ['FizzBuzz', 'Fizz', 'Buzz']; +(function() { + var i; -function fizzBuzz(first, last) { - for (var n = first; n <= last; n++) { - print(getFizzBuzz(n)); - } -} + for (i = 1; i <= 100; i++) { + console.log([i % 3 === 0 ? 'Fizz' : void 0] + [i % 5 === 0 ? 'Buzz' : void 0] || i); + } -function getFizzBuzz(n) { - var sayWhat = n; - for (var d = 0; d < divs.length; d++) { - if (isMultOf(n, divs[d])) { - sayWhat = says[d]; - break; - } - } - return sayWhat; -} - -function isMultOf(n, d) { - return n % d == 0; -} - -fizzBuzz(1, 100); +}).call(this); diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-6.js b/Task/FizzBuzz/JavaScript/fizzbuzz-6.js new file mode 100644 index 0000000000..6d37d23951 --- /dev/null +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-6.js @@ -0,0 +1,25 @@ +var divs = [15, 3, 5]; +var says = ['FizzBuzz', 'Fizz', 'Buzz']; + +function fizzBuzz(first, last) { + for (var n = first; n <= last; n++) { + print(getFizzBuzz(n)); + } +} + +function getFizzBuzz(n) { + var sayWhat = n; + for (var d = 0; d < divs.length; d++) { + if (isMultOf(n, divs[d])) { + sayWhat = says[d]; + break; + } + } + return sayWhat; +} + +function isMultOf(n, d) { + return n % d == 0; +} + +fizzBuzz(1, 100); diff --git a/Task/FizzBuzz/Processing/fizzbuzz-1 b/Task/FizzBuzz/Processing/fizzbuzz-1 new file mode 100644 index 0000000000..f72b7fc647 --- /dev/null +++ b/Task/FizzBuzz/Processing/fizzbuzz-1 @@ -0,0 +1,19 @@ +for (int i = 0; i < width; i++) { + if (i % 3 == 0 && i % 5 == 0) { + stroke(255, 255, 0); + println("FizzBuzz!"); + } + else if (i % 5 == 0) { + stroke(0, 255, 0); + println("Buzz"); + } + else if (i % 3 == 0) { + stroke(255, 0, 0); + println("Fizz"); + } + else { + stroke(0, 0, 255); + println(i); + } + line(i, 0, i, height); +} diff --git a/Task/FizzBuzz/Processing/fizzbuzz-2 b/Task/FizzBuzz/Processing/fizzbuzz-2 new file mode 100644 index 0000000000..0e81b1b605 --- /dev/null +++ b/Task/FizzBuzz/Processing/fizzbuzz-2 @@ -0,0 +1,5 @@ +for (int i = 0; i < width; i++) { + stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF); + line(i, 0, i, height); + println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i); +} diff --git a/Task/FizzBuzz/Prolog/fizzbuzz-3.pro b/Task/FizzBuzz/Prolog/fizzbuzz-3.pro new file mode 100644 index 0000000000..babd6d8486 --- /dev/null +++ b/Task/FizzBuzz/Prolog/fizzbuzz-3.pro @@ -0,0 +1,20 @@ +% N /3? /5? V +fizzbuzz(_, yes, yes, 'FizzBuzz'). +fizzbuzz(_, yes, no, 'Fizz'). +fizzbuzz(_, no, yes, 'Buzz'). +fizzbuzz(N, no, no, N). + +% Unifies V with 'yes' if D divides evenly into N, 'no' otherwise. +divisible_by(N, D, V) :- + ( 0 is N mod D -> V = yes + ; V = no). + +% Print 'Fizz', 'Buzz', 'FizzBuzz' or N as appropriate. +fizz_buzz_or_n(N) :- + divisible_by(N, 3, Fizz), + divisible_by(N, 5, Buzz), + fizzbuzz(N, Fizz, Buzz, FB), + format("~p -> ~p~n", [N, FB]). + +main :- + foreach(between(1,100, N), fizz_buzz_or_n(N)). diff --git a/Task/FizzBuzz/SQL/fizzbuzz-2.sql b/Task/FizzBuzz/SQL/fizzbuzz-2.sql index 917e8e124e..49ea56e974 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-2.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-2.sql @@ -1,11 +1,2 @@ -SELECT i, fizzbuzz - FROM - (SELECT i, - CASE - WHEN i % 15 = 0 THEN 'FizzBuzz' - WHEN i % 5 = 0 THEN 'Buzz' - WHEN i % 3 = 0 THEN 'Fizz' - ELSE NULL - END AS fizzbuzz - FROM generate_series(1,100) AS i) AS fb - WHERE fizzbuzz IS NOT NULL; +select nvl(decode(mod(n,3),0,'Fizz')||decode(mod(n,5),0,'Buzz'),n) +from (select level n from dual connect by level<=100) diff --git a/Task/FizzBuzz/SQL/fizzbuzz-3.sql b/Task/FizzBuzz/SQL/fizzbuzz-3.sql index 0848993633..917e8e124e 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-3.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-3.sql @@ -1,15 +1,11 @@ -WITH nums (n, fizzbuzz ) AS ( - SELECT 1, CONVERT(nvarchar, 1) UNION ALL - SELECT - (n + 1) as n1, - CASE - WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz' - WHEN (n + 1) % 3 = 0 THEN 'Fizz' - WHEN (n + 1) % 5 = 0 THEN 'Buzz' - ELSE CONVERT(nvarchar, (n + 1)) - END - FROM nums WHERE n < 100 -) -SELECT n, fizzbuzz FROM nums -ORDER BY n ASC -OPTION ( MAXRECURSION 100 ) +SELECT i, fizzbuzz + FROM + (SELECT i, + CASE + WHEN i % 15 = 0 THEN 'FizzBuzz' + WHEN i % 5 = 0 THEN 'Buzz' + WHEN i % 3 = 0 THEN 'Fizz' + ELSE NULL + END AS fizzbuzz + FROM generate_series(1,100) AS i) AS fb + WHERE fizzbuzz IS NOT NULL; diff --git a/Task/FizzBuzz/SQL/fizzbuzz-4.sql b/Task/FizzBuzz/SQL/fizzbuzz-4.sql index f709a0c11c..0b55ca0b98 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-4.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-4.sql @@ -1,24 +1,7 @@ --- Load some numbers -CREATE TABLE numbers(i INTEGER); -INSERT INTO numbers VALUES(1); -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; --- Define the fizzes and buzzes -CREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER); -INSERT INTO fizzbuzz VALUES('fizz', 3); -INSERT INTO fizzbuzz VALUES('buzz', 5); -INSERT INTO fizzbuzz VALUES('fizzbuzz', 15); --- Play fizzbuzz -SELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result -FROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0 -GROUP BY i -HAVING i <= 100 -ORDER BY i; --- Tidy up -DROP TABLE fizzbuzz; -DROP TABLE numbers; +SELECT COALESCE(FIZZ || BUZZ, FIZZ, BUZZ, OUTPUT) AS FIZZBUZZ FROM +(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT +FROM GENERATE_SERIES(1,100)) F LEFT JOIN +(SELECT TEXT 'Fizz' AS FIZZ, GENERATE_SERIES AS FIZZ_SERIES FROM GENERATE_SERIES(0,100,3)) FIZZ ON +FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN +(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON +BUZZ.BUZZ_SERIES = F.FULL_SERIES; diff --git a/Task/FizzBuzz/SQL/fizzbuzz-5.sql b/Task/FizzBuzz/SQL/fizzbuzz-5.sql index da150181cc..0848993633 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-5.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-5.sql @@ -1,16 +1,15 @@ -declare - v_count integer; - -begin - for v_count in 1..100 loop - if(mod(v_count, 15) = 0) then - dbms_output.put_line('Fizz Buzz'); - elsif(mod(v_count, 3) = 0) then - dbms_output.put_line('Fizz'); - elsif(mod(v_count, 5) = 0) then - dbms_output.put_line('Buzz'); - else - dbms_output.put_line(v_count); - end if; - end loop; -end; +WITH nums (n, fizzbuzz ) AS ( + SELECT 1, CONVERT(nvarchar, 1) UNION ALL + SELECT + (n + 1) as n1, + CASE + WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz' + WHEN (n + 1) % 3 = 0 THEN 'Fizz' + WHEN (n + 1) % 5 = 0 THEN 'Buzz' + ELSE CONVERT(nvarchar, (n + 1)) + END + FROM nums WHERE n < 100 +) +SELECT n, fizzbuzz FROM nums +ORDER BY n ASC +OPTION ( MAXRECURSION 100 ) diff --git a/Task/FizzBuzz/SQL/fizzbuzz-6.sql b/Task/FizzBuzz/SQL/fizzbuzz-6.sql new file mode 100644 index 0000000000..f709a0c11c --- /dev/null +++ b/Task/FizzBuzz/SQL/fizzbuzz-6.sql @@ -0,0 +1,24 @@ +-- Load some numbers +CREATE TABLE numbers(i INTEGER); +INSERT INTO numbers VALUES(1); +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +-- Define the fizzes and buzzes +CREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER); +INSERT INTO fizzbuzz VALUES('fizz', 3); +INSERT INTO fizzbuzz VALUES('buzz', 5); +INSERT INTO fizzbuzz VALUES('fizzbuzz', 15); +-- Play fizzbuzz +SELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result +FROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0 +GROUP BY i +HAVING i <= 100 +ORDER BY i; +-- Tidy up +DROP TABLE fizzbuzz; +DROP TABLE numbers; diff --git a/Task/FizzBuzz/Standard-ML/fizzbuzz-1.ml b/Task/FizzBuzz/Standard-ML/fizzbuzz-1.ml new file mode 100644 index 0000000000..a8457895ac --- /dev/null +++ b/Task/FizzBuzz/Standard-ML/fizzbuzz-1.ml @@ -0,0 +1,14 @@ +local + fun fbstr i = + case (i mod 3 = 0, i mod 5 = 0) of + (true , true ) => "FizzBuzz" + | (true , false) => "Fizz" + | (false, true ) => "Buzz" + | (false, false) => Int.toString i + + fun fizzbuzz' (n, j) = + if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1)) +in + fun fizzbuzz n = fizzbuzz' (n, 1) + val _ = fizzbuzz 100 +end diff --git a/Task/FizzBuzz/Standard-ML/fizzbuzz-2.ml b/Task/FizzBuzz/Standard-ML/fizzbuzz-2.ml new file mode 100644 index 0000000000..007a5bfe89 --- /dev/null +++ b/Task/FizzBuzz/Standard-ML/fizzbuzz-2.ml @@ -0,0 +1,8 @@ +local + fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true) + val buzz = i mod 5 = 0 andalso (print "Buzz"; true) + in fizz orelse buzz orelse (print (Int.toString i); true) end +in + fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ()) + val _ = fizzbuzz 100 +end diff --git a/Task/FizzBuzz/Standard-ML/fizzbuzz.ml b/Task/FizzBuzz/Standard-ML/fizzbuzz.ml deleted file mode 100644 index b5c3f1335c..0000000000 --- a/Task/FizzBuzz/Standard-ML/fizzbuzz.ml +++ /dev/null @@ -1,14 +0,0 @@ -fun output x = - case (x mod 3 = 0, x mod 5 = 0) of - (true , true ) => "FizzBuzz" - | (true , false) => "Fizz" - | (false, true ) => "Buzz" - | (false, false) => Int.toString x - -val () = let - fun aux i = if i <= 100 then (print (output i ^ "\n"); - aux (i+1)) - else () -in - aux 1 -end diff --git a/Task/FizzBuzz/VBScript/fizzbuzz-1.vb b/Task/FizzBuzz/VBScript/fizzbuzz-1.vb index b0019f956a..e7ec915dfe 100644 --- a/Task/FizzBuzz/VBScript/fizzbuzz-1.vb +++ b/Task/FizzBuzz/VBScript/fizzbuzz-1.vb @@ -1,26 +1,11 @@ -'using the IF/ELSEIF ladder -function fb( n ) - if n mod 15 = 0 then - fb = "FizzBuzz" - elseif n mod 5 = 0 then - fb = "Fizz" - elseif n mod 3 = 0 then - fb = "Buzz" - else - fb = n - end if -end function - -'the Mexican IF -function eef( b, p1, p2 ) - if b then - eef = p1 - else - eef = p2 - end if -end function - -'using the Mexican IF -function fb2( n ) - fb2 = eef( n mod 15 = 0, "FizzBuzz", eef( n mod 5 = 0, "Fizz", eef( n mod 3 = 0, "Buzz", n ) ) ) -end function +For i = 1 To 100 + If i Mod 15 = 0 Then + WScript.Echo "FizzBuzz" + ElseIf i Mod 5 = 0 Then + WScript.Echo "Buzz" + ElseIf i Mod 3 = 0 Then + WScript.Echo "Fizz" + Else + WScript.Echo i + End If +Next diff --git a/Task/FizzBuzz/VBScript/fizzbuzz-2.vb b/Task/FizzBuzz/VBScript/fizzbuzz-2.vb index cefadcca04..ea7023676f 100644 --- a/Task/FizzBuzz/VBScript/fizzbuzz-2.vb +++ b/Task/FizzBuzz/VBScript/fizzbuzz-2.vb @@ -1,9 +1,7 @@ -for i = 1 to 16 - wscript.stdout.write fb(i) & " " -next -wscript.echo - -for i = 1 to 16 - wscript.stdout.write fb2(i) & " " -next -wscript.echo +With WScript.StdOut + For i = 1 To 100 + If i Mod 3 = 0 Then .Write "Fizz" + If i Mod 5 = 0 Then .Write "Buzz" + If .Column = 1 Then .WriteLine i Else .WriteLine "" + Next +End With diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp index 50ed8c193d..ea887a7439 100644 --- a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp +++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp @@ -1,5 +1,5 @@ -(defun flatten-trf (x &optional stack out) - (cond ((consp x) (flatten-trf (rest x) (cons (first x) stack) out)) - (x (flatten-trf (first stack) (rest stack) (cons x out))) - (stack (flatten-trf (first stack) (rest stack) out)) +(defun flatten (x &optional stack out) + (cond ((consp x) (flatten (rest x) (cons (first x) stack) out)) + (x (flatten (first stack) (rest stack) (cons x out))) + (stack (flatten (first stack) (rest stack) out)) (t out))) diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-5.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-5.lisp new file mode 100644 index 0000000000..4288cd027f --- /dev/null +++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-5.lisp @@ -0,0 +1,8 @@ +(defun flatten (obj) + (do* ((result (list obj)) + (node result)) + ((null node) (delete nil result)) + (cond ((consp (car node)) + (when (cdar node) (push (cdar node) (cdr node))) + (setf (car node) (caar node))) + (t (setf node (cdr node)))))) diff --git a/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv b/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv index 7ca56c0383..d652c3cf36 100644 --- a/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv +++ b/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv @@ -8,4 +8,4 @@ flatten l: [ (flatten) l ] -. flatten [ [ 1 ] 2 [ [ 3 4 ] 5 ] [ [ [] ] ] [ [ [ 6 ] ] ] 7 8 [] ] +!. flatten [ [ 1 ] 2 [ [ 3 4 ] 5 ] [ [ [] ] ] [ [ [ 6 ] ] ] 7 8 [] ] diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia index 07bcd81584..6437725aa5 100644 --- a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia +++ b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia @@ -1,2 +1 @@ -flat(A) = isempty(A)? A : - [isa(first(A), Array)? flat(first(A)): first(A), flat(A[2:])] +flat(A) = [[isa(x,Array)? flat(x): x for x in A]...] diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-3.julia b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia new file mode 100644 index 0000000000..6b4f560cf9 --- /dev/null +++ b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia @@ -0,0 +1 @@ +flat(A) = mapreduce(x->isa(x,Array)? flat(x): x, vcat, A) diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-4.julia b/Task/Flatten-a-list/Julia/flatten-a-list-4.julia new file mode 100644 index 0000000000..822d2a47df --- /dev/null +++ b/Task/Flatten-a-list/Julia/flatten-a-list-4.julia @@ -0,0 +1,8 @@ +function flat(A) + result = {} + grep(a) = for x in a + isa(x,Array) ? grep(x) : push!(result,x) + end + grep(A) + result + end diff --git a/Task/Flatten-a-list/VBScript/flatten-a-list-4.vb b/Task/Flatten-a-list/VBScript/flatten-a-list-4.vb new file mode 100644 index 0000000000..527938aa5f --- /dev/null +++ b/Task/Flatten-a-list/VBScript/flatten-a-list-4.vb @@ -0,0 +1,15 @@ +' Flatten the example array... +a = FlattenArray(Array(Array(1), 2, Array(Array(3,4), 5), Array(Array(Array())), Array(Array(Array(6))), 7, 8, Array())) + +' Print the list, comma-separated... +WScript.Echo Join(a, ",") + +Function FlattenArray(a) + If IsArray(a) Then DoFlatten a, FlattenArray: FlattenArray = Split(Trim(FlattenArray)) +End Function + +Sub DoFlatten(a, s) + For i = 0 To UBound(a) + If IsArray(a(i)) Then DoFlatten a(i), s Else s = s & a(i) & " " + Next +End Sub diff --git a/Task/Flow-control-structures/Bracmat/flow-control-structures.bracmat b/Task/Flow-control-structures/Bracmat/flow-control-structures.bracmat new file mode 100644 index 0000000000..9c13012fac --- /dev/null +++ b/Task/Flow-control-structures/Bracmat/flow-control-structures.bracmat @@ -0,0 +1,6 @@ + ( LOOP + = out$"Hi again!" + & !LOOP + ) +& out$Hi! +& !LOOP diff --git a/Task/Flow-control-structures/PL-I/flow-control-structures.pli b/Task/Flow-control-structures/PL-I/flow-control-structures.pli index 5401bbbadf..5e2933bf66 100644 --- a/Task/Flow-control-structures/PL-I/flow-control-structures.pli +++ b/Task/Flow-control-structures/PL-I/flow-control-structures.pli @@ -26,3 +26,4 @@ GO TO statement. It can also be used to transfer control to any one of an array of labelled statements. (This form is superseded by SELECT, above.) + [GO TO can also be spelled as GOTO]. diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-1.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-1.rexx index 8a7bc14fe6..6dcb8db943 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-1.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-1.rexx @@ -1,3 +1,11 @@ -exit - -exit expression +call routineName /*no arguments passed to routine.*/ +call routineName 50 /*one argument (fifty) passed. */ +call routineName 50,60 /*two arguments passed. */ +call routineName 50, 60 /*(same as above) */ +call routineName 50 ,60 /*(same as above) */ +call routineName 10*5 , 8**4 - 4 /*(same as above) */ +call routineName 50 , , , 70 /*4 args passed, 2nd&3rd omitted.*/ + /*omitted args are NOT null. */ +call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */ +call date /*looks for DATE internally first*/ +call 'DATE' /* " " " BIF | externally*/ diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-10.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-10.rexx new file mode 100644 index 0000000000..96e1d12df7 --- /dev/null +++ b/Task/Flow-control-structures/REXX/flow-control-structures-10.rexx @@ -0,0 +1,22 @@ +... +prod=1 +a=7 /*or somesuch.*/ +b=3 /* likewise. */ + +op='**' /*or whatever.*/ +... + select + when op=='+' then r=a+b /*add. */ + when op=='-' then r=a-b /*subtract. */ + when op=='∙' then do; r=a*b; prod=prod*r; end /*multiply.*/ + when op=='*' then r=a*b /*multiply. */ + when op=='**' then r=a**b /*power (exponentiation) */ + when op=='/' & b\=0 then r=a/b /*divide. */ + when op=='%' & b\=0 then r=a/b /*interger divide. */ + when op=='//' & b\=0 then r=a/b /*modulus (remainder). */ + when op=='||' then r=a||b /*concatenation. */ + when op=='caw' then r=xyz(a,b) /*call the XYZ subroutine*/ + otherwise r='[n/a]' /*signify not applicable.*/ + end /*select*/ + +say 'result for' a op b "=" r diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-11.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-11.rexx new file mode 100644 index 0000000000..a0c97912a6 --- /dev/null +++ b/Task/Flow-control-structures/REXX/flow-control-structures-11.rexx @@ -0,0 +1,33 @@ +... +signal on error +signal on failure +signal on halt +signal on lostdigits /*newer REXXes.*/ +signal on notready +signal on novalue +signal on syntax + +signal off error +signal off failure +signal off halt +signal off lostdigits /*newer REXXes.*/ +signal off notready +signal off novalue +signal off syntax +... +signal on novalue +... +x=oopsay+1 /* ◄─── this is it.*/ +exit + +novalue: say +say '───────────────────────────error!─────────────────────────────────' +say 'that reference to oopsay (above) will cause control to get here.' +parse source . . fid . +say; say 'REXX raised a NOVALUE error in program:' fid +say; say 'it occurred on line' sigl +say; say 'the REXX statement is:' /*put it on separate line.*/ + say sourceline(sigl) +say; say 'which code:' condition('C') "error" +say; say 'REXX variable:' condition('D') +say; say "Moral: shouldn't do that." diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-2.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-2.rexx index 0a3389143e..8450b892cb 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-2.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-2.rexx @@ -1,3 +1,13 @@ -return - -return expression +numeric digits 1000 /*prepare for some gihugeic numbers.*/ +... +n=4 +call factorial n +say n'!=' result +exit +/*──────────────────────────────────FACTORIAL subroutine────────────────*/ +factorial: parse arg x +!=1 + do j=2 to x + !=!*j + end /*j*/ +return ! diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx index 8d005a11ab..8a7bc14fe6 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx @@ -1,32 +1,3 @@ -signal on error -signal on failure -signal on halt -signal on lostdigits -signal on notready -signal on novalue -signal on syntax +exit -signal off error -signal off failure -signal off halt -signal off lostdigits -signal off notready -signal off novalue -signal off syntax -... -signal on novalue -... -x=oopsay+1 -... -novalue: say -say '*** error! ***' -say -say 'undefined REXX variable' condition("D") -say -say 'in line' sigl -say -say 'REXX source statement is:' -say sourceline(sigl) -say -exit 13 -... +exit expression diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx index c1fcb802d7..d4aa5d4f3a 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx @@ -1,20 +1,12 @@ - do j=1 to 10 - say 'j=' j - if j>5 then leave - say 'negative j=' -j - end -say 'end of the DO loop for j.' +numeric digits 1000 /*prepare for some gihugeic numbers.*/ ... -ouch=60 -sum=0 - - do k=0 to 100 by 3 - say 'k=' k - - do m=1 to k - if m=ouch then leave k - sum=sum+m - end - - end -say 'sum=' sum +n=4 +say n'!=' factorial(n) +exit +/*──────────────────────────────────FACTORIAL subroutine────────────────*/ +factorial: parse arg x +!=1 + do j=2 to x + !=!*j + end /*j*/ +return ! diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx index cb2ae600bc..15baf217f0 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx @@ -1,22 +1,18 @@ sum=0 - - do j=1 to 1000 - if j//3==0 | j//7==0 then iterate - sum=sum+j - end + do j=1 to 1000 + if j//3==0 | j//7==0 then iterate + sum=sum+j + end /*j*/ /*shows sum of 1k numbers except those divisible by 3 or 7.*/ say 'sum='sum ... numeric digits 5000 prod=0 - - do k=1 to 2000 - - do m=1 to k - if m>99 then iterate k - prod=prod*m - end - - end + do k=1 to 2000 + do m=1 to k + if m>99 then iterate k + prod=prod*m + end /*m*/ + end /*k*/ say 'prod=' prod diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx index 2923c94f82..ac7da12a7d 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx @@ -1,16 +1,18 @@ -numeric digits 1000 /*prepare for some gihugeic numbers.*/ -... -n=4 -call factorial n -say n'!=' result -exit + do j=1 to 10 + say 'j=' j + if j>5 then leave + say 'negative j=' (-j) + end /*j*/ +say 'end of the DO loop for j.' -factorial: parse arg x -!=1 - - do j=2 to x - !=!*j - end - -return ! +ouch=60 +sum=0 + do k=0 to 100 by 3 + say 'k=' k + do m=1 to k + if m=ouch then leave k + sum=sum+m + end /*m*/ + end /*k*/ +say 'sum=' sum diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx index 70a5f4bd08..06b83ab5bc 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx @@ -1,21 +1,32 @@ ... -prod=1 -a=7 /*or somesuch.*/ -b=3 /* likewise. */ - -op='**' /*or whatever.*/ +signal on syntax ... - select - when op=='+' then r=a+b /*add. */ - when op=='-' then r=a-b /*subtract. */ - when op=='*' then do; r=a*b; prod=prod*r; end /*multiply.*/ - when op=='*' then r=a*b /*multiply. */ - when op=='/' & b\=0 then r=a/b /*divide. */ - when op=='%' & b\=0 then r=a/b /*interger divide. */ - when op=='//' & b\=0 then r=a/b /*modulus (remainder). */ - when op=='||' then r=a||b /*concatenation. */ - when op=='caw' then r=xyz(a,b) /*call the XYZ subroutine*/ - otherwise r='[n/a]' /*signify not applicable.*/ - end +y=4 - 4 +x=66 +say x/y /*divide x by y.*/ +say "yup, that's a divide by zero, by gum." +exit -say 'result for' a op b "=" r +syntax: say + +/* We can now possibly do some repair work , but most people trap */ +/* the condition, display where it happened, the REXX sourceline */ +/* (the actual REXX statement), which condition was triggered, */ +/* display any other pertinent REXX variables, which line in the */ +/* REXX program, and then (usually) exit with some kind of error */ +/* message and error code indicator. */ +/* Note: the "name" of the REXX program isn't quite accurate, */ +/* rather, it is the name that was invoked (called by), which may */ +/* be different name than the actual program being executed. */ + +say '──────────────────────error!─────────────────────────' +say 'that division (above) will cause control to get here.' +parse source . . fid . +say; say 'REXX raised a SYNTAX error in program:' fid +say; say 'it occurred on line' sigl +say; say 'the REXX statement is:' /*put it on separate line.*/ + say sourceline(sigl) +say; say 'which code:' condition('C') "error" +say; say 'error code:' condition('D') +say; say "Moral: don't do that." +exit 13 diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-8.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-8.rexx new file mode 100644 index 0000000000..967fe1c90f --- /dev/null +++ b/Task/Flow-control-structures/REXX/flow-control-structures-8.rexx @@ -0,0 +1,7 @@ +Say 'Interrupt this program after a short while' +Call on halt +Do i=1 To 10000000 + j=i**2+1 + End +halt: Say i j +Return diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-9.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-9.rexx new file mode 100644 index 0000000000..0a3389143e --- /dev/null +++ b/Task/Flow-control-structures/REXX/flow-control-structures-9.rexx @@ -0,0 +1,3 @@ +return + +return expression diff --git a/Task/Floyds-triangle/Prolog/floyds-triangle.pro b/Task/Floyds-triangle/Prolog/floyds-triangle.pro new file mode 100644 index 0000000000..7d44b6d86f --- /dev/null +++ b/Task/Floyds-triangle/Prolog/floyds-triangle.pro @@ -0,0 +1,13 @@ +floyd(N) :- + forall(between(1, N, I), + ( forall(between(1,I, J), + ( Last is N * (N-1)/2+J, + V is I * (I-1) /2 + J, + get_column(Last, C), + sformat(AR, '~~t~~w~~~w| ', [C]), + sformat(AF, AR, [V]), + writef(AF))), + nl)). + +get_column(Last, C) :- + name(Last, N1), length(N1,C). diff --git a/Task/Floyds-triangle/Ruby/floyds-triangle.rb b/Task/Floyds-triangle/Ruby/floyds-triangle.rb index eb049f210c..30e10e1116 100644 --- a/Task/Floyds-triangle/Ruby/floyds-triangle.rb +++ b/Task/Floyds-triangle/Ruby/floyds-triangle.rb @@ -1,14 +1,11 @@ -raise ArgumentError, "Usage: #{$0} ROWS" unless - ARGV.length == 1 && (rows = ARGV[0].to_i) > 0 - -max = (rows * (rows + 1)) / 2 -widths = ((max - rows + 1)..max).map {|n| n.to_s.length + 1} - -n = 0 -rows.times do |r| - (r+1).times do |i| - n += 1 - print "%#{widths[i]}d" % n +def floyd(rows) + max = (rows * (rows + 1)) / 2 + widths = ((max - rows + 1)..max).map {|n| n.to_s.length + 1} + n = 0 + rows.times do |r| + puts (0..r).map {|i| n += 1; "%#{widths[i]}d" % n}.join end - print "\n" end + +floyd(5) +floyd(14) diff --git a/Task/Floyds-triangle/VBScript/floyds-triangle.vb b/Task/Floyds-triangle/VBScript/floyds-triangle.vb new file mode 100644 index 0000000000..9512303fe0 --- /dev/null +++ b/Task/Floyds-triangle/VBScript/floyds-triangle.vb @@ -0,0 +1,15 @@ +' Read the number of rows to use.. +intRows = WScript.StdIn.ReadLine + +' Get the first number of the final row so we can calculate widths... +intLastRowStart = (intRows ^ 2 - intRows) \ 2 + 1 + +For i = 1 To intRows + intLastRow = intLastRowStart + For j = 1 To i + k = k + 1 + WScript.StdOut.Write Space(Len(intLastRow) - Len(k)) & k & " " + intLastRow = intLastRow + 1 + Next + WScript.StdOut.WriteLine "" +Next diff --git a/Task/Forest-fire/Deja-Vu/forest-fire.djv b/Task/Forest-fire/Deja-Vu/forest-fire.djv new file mode 100644 index 0000000000..83d749213f --- /dev/null +++ b/Task/Forest-fire/Deja-Vu/forest-fire.djv @@ -0,0 +1,77 @@ +#chance of empty->tree +set :p 0.004 +#chance of spontaneous tree combustion +set :f 0.001 +#chance of tree in initial state +set :s 0.5 +#height of world +set :H 10 +#width of world +set :W 20 + +has-burning-neigbour state pos: + for i range -- swap ++ dup &< pos: + for j range -- swap ++ dup &> pos: + & i j + try: + state! + catch value-error: + :empty + if = :burning: + return true + false + +evolve state pos: + state! pos + if = :tree dup: + if has-burning-neigbour state pos: + :burning drop + elseif chance f: + :burning drop + elseif = :burning: + :empty + else: + if chance p: + :tree + else: + :empty + +step state: + local :next {} + for k in keys state: + set-to next k evolve state k + next + +local :(c) { :tree "T" :burning "B" :empty "." } +print-state state: + for j range 0 H: + for i range 0 W: + !print\ (c)! state! & i j + !print "" + +init-state: + local :first {} + for j range 0 H: + for i range 0 W: + if chance s: + :tree + else: + :empty + set-to first & i j + first + +run: + init-state + while true: + print-state dup + !print "" + step + +run-slowly: + init-state + while true: + print-state dup + drop !prompt "Continue." + step + +run diff --git a/Task/Forest-fire/Perl-6/forest-fire.pl6 b/Task/Forest-fire/Perl-6/forest-fire.pl6 index 5305f09efb..b40b574046 100644 --- a/Task/Forest-fire/Perl-6/forest-fire.pl6 +++ b/Task/Forest-fire/Perl-6/forest-fire.pl6 @@ -13,7 +13,7 @@ class Forest { has $.f; method new(Int $height, Int $width, $p=0.01, $f=0.001) { - my $c = self.bless(*, :$height, :$width, :$p, :$f); + my $c = self.bless(:$height, :$width, :$p, :$f); $c!init-grid; $c!init-neighbors; return $c; diff --git a/Task/Formatted-numeric-output/Emacs-Lisp/formatted-numeric-output.l b/Task/Formatted-numeric-output/Emacs-Lisp/formatted-numeric-output.l new file mode 100644 index 0000000000..bdefbd22cd --- /dev/null +++ b/Task/Formatted-numeric-output/Emacs-Lisp/formatted-numeric-output.l @@ -0,0 +1,3 @@ +(format "%09.3f" 7.125) +=> +"00007.125" diff --git a/Task/Formatted-numeric-output/VBScript/formatted-numeric-output.vb b/Task/Formatted-numeric-output/VBScript/formatted-numeric-output.vb new file mode 100644 index 0000000000..839dfeabb3 --- /dev/null +++ b/Task/Formatted-numeric-output/VBScript/formatted-numeric-output.vb @@ -0,0 +1,13 @@ +a = 1234.5678 + +' Round to three decimal places. Groups by default. Output = "1,234.568". +WScript.Echo FormatNumber(a, 3) + +' Truncate to three decimal places. Output = "1234.567". +WScript.Echo Left(a, InStr(a, ".") + 3) + +' Round to a whole number. Grouping disabled. Output = "1235". +WScript.Echo FormatNumber(a, 0, , , False) + +' Use integer portion only and pad with zeroes to fill 8 chars. Output = "00001234". +WScript.Echo Right("00000000" & Int(a), 8) diff --git a/Task/Forward-difference/D/forward-difference-2.d b/Task/Forward-difference/D/forward-difference-2.d index 5d44301d88..4896c315d2 100644 --- a/Task/Forward-difference/D/forward-difference-2.d +++ b/Task/Forward-difference/D/forward-difference-2.d @@ -1,13 +1,13 @@ import std.stdio, std.algorithm, std.range, std.array; auto forwardDifference(Range)(Range d, in int level) { - foreach (_; 0 .. level) - d = zip(d[1 .. $], d).map!q{ a[0] - a[1] }().array(); + foreach (immutable _; 0 .. level) + d = d.zip(d.dropOne).map!(a => a[0] - a[1]).array; return d; } void main() { - auto data = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]; - foreach (level; 0 .. data.length) - writeln(forwardDifference(data, level)); + const data = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]; + foreach (immutable level; 0 .. data.length) + forwardDifference(data, level).writeln; } diff --git a/Task/Forward-difference/Julia/forward-difference-1.julia b/Task/Forward-difference/Julia/forward-difference-1.julia new file mode 100644 index 0000000000..18d19000f9 --- /dev/null +++ b/Task/Forward-difference/Julia/forward-difference-1.julia @@ -0,0 +1 @@ +ndiff(A, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1)) diff --git a/Task/Forward-difference/Julia/forward-difference-2.julia b/Task/Forward-difference/Julia/forward-difference-2.julia new file mode 100644 index 0000000000..961e8531df --- /dev/null +++ b/Task/Forward-difference/Julia/forward-difference-2.julia @@ -0,0 +1,13 @@ +julia> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] +julia> [ndiff(s, i) for i in 0:9] +10-element Array{Any,1}: + [90,47,58,29,22,32,55,5,55,73] + [-43,11,-29,-7,10,23,-50,50,18] + [54,-40,22,17,13,-73,100,-32] + [-94,62,-5,-4,-86,173,-132] + [156,-67,1,-82,259,-305] + [-223,68,-83,341,-564] + [291,-151,424,-905] + [-442,575,-1329] + [1017,-1904] + [-2921] diff --git a/Task/Four-bit-adder/AutoIt/four-bit-adder-1.autoit b/Task/Four-bit-adder/AutoIt/four-bit-adder-1.autoit new file mode 100644 index 0000000000..1be6da9764 --- /dev/null +++ b/Task/Four-bit-adder/AutoIt/four-bit-adder-1.autoit @@ -0,0 +1,40 @@ +Func _NOT($_A) + Return (Not $_A) *1 +EndFunc ;==>_NOT + +Func _AND($_A, $_B) + Return BitAND($_A, $_B) +EndFunc ;==>_AND + +Func _OR($_A, $_B) + Return BitOR($_A, $_B) +EndFunc ;==>_OR + +Func _XOR($_A, $_B) + Return _OR( _ + _AND( $_A, _NOT($_B) ), _ + _AND( _NOT($_A), $_B) ) +EndFunc ;==>_XOR + +Func _HalfAdder($_A, $_B, ByRef $_CO) + $_CO = _AND($_A, $_B) + Return _XOR($_A, $_B) +EndFunc ;==>_HalfAdder + +Func _FullAdder($_A, $_B, $_CI, ByRef $_CO) + Local $CO1, $CO2, $Q1, $Q2 + $Q1 = _HalfAdder($_A, $_B, $CO1) + $Q2 = _HalfAdder($Q1, $_CI, $CO2) + $_CO = _OR($CO2, $CO1) + Return $Q2 +EndFunc ;==>_FullAdder + +Func _4BitAdder($_A1, $_A2, $_A3, $_A4, $_B1, $_B2, $_B3, $_B4, $_CI, ByRef $_CO) + Local $CO1, $CO2, $CO3, $CO4, $Q1, $Q2, $Q3, $Q4 + $Q1 = _FullAdder($_A4, $_B4, $_CI, $CO1) + $Q2 = _FullAdder($_A3, $_B3, $CO1, $CO2) + $Q3 = _FullAdder($_A2, $_B2, $CO2, $CO3) + $Q4 = _FullAdder($_A1, $_B1, $CO3, $CO4) + $_CO = $CO4 + Return $Q4 & $Q3 & $Q2 & $Q1 +EndFunc ;==>_4BitAdder diff --git a/Task/Four-bit-adder/AutoIt/four-bit-adder-2.autoit b/Task/Four-bit-adder/AutoIt/four-bit-adder-2.autoit new file mode 100644 index 0000000000..de8ec4034f --- /dev/null +++ b/Task/Four-bit-adder/AutoIt/four-bit-adder-2.autoit @@ -0,0 +1,6 @@ +Local $CarryOut, $sResult +$sResult = _4BitAdder(0, 0, 1, 1, 0, 1, 1, 1, 0, $CarryOut) ; adds 3 + 7 +ConsoleWrite('result: ' & $sResult & ' ==> carry out: ' & $CarryOut & @LF) + +$sResult = _4BitAdder(1, 0, 1, 1, 1, 0, 0, 0, 0, $CarryOut) ; adds 11 + 8 +ConsoleWrite('result: ' & $sResult & ' ==> carry out: ' & $CarryOut & @LF) diff --git a/Task/Four-bit-adder/AutoIt/four-bit-adder-3.autoit b/Task/Four-bit-adder/AutoIt/four-bit-adder-3.autoit new file mode 100644 index 0000000000..8c9439ea15 --- /dev/null +++ b/Task/Four-bit-adder/AutoIt/four-bit-adder-3.autoit @@ -0,0 +1,2 @@ +result: 1010 ==> carry out: 0 +result: 0011 ==> carry out: 1 diff --git a/Task/Fractal-tree/D/fractal-tree-2.d b/Task/Fractal-tree/D/fractal-tree-2.d index 242b7ba011..c815b4dc2f 100644 --- a/Task/Fractal-tree/D/fractal-tree-2.d +++ b/Task/Fractal-tree/D/fractal-tree-2.d @@ -1,43 +1,20 @@ -import dfl.all; -import std.math; +import grayscale_image, turtle; -class FractalTree: Form { - - private immutable DEG_TO_RAD = PI / 180.0; - - this() { - width = 600; - height = 500; - text = "Fractal Tree"; - backColor = Color(0xFF, 0xFF, 0xFF); - startPosition = FormStartPosition.CENTER_SCREEN; - formBorderStyle = FormBorderStyle.FIXED_DIALOG; - maximizeBox = false; - } - - private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) { - if (depth == 0) return; - int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0); - int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0); - g.drawLine(p, x1, y1, x2, y2); - drawTree(g, p, x2, y2, angle - 20, depth - 1); - drawTree(g, p, x2, y2, angle + 20, depth - 1); - } - - protected override void onPaint(PaintEventArgs ea){ - super.onPaint(ea); - Pen p = new Pen(Color(0, 0xAA, 0)); - drawTree(ea.graphics, p, 300, 450, -90, 9); - } +void tree(Color)(Image!Color img, ref Turtle t, in uint depth, + in real step, in real scale, in real angle) { + if (depth == 0) return; + t.forward(img, step); + t.right(angle); + img.tree(t, depth - 1, step * scale, scale, angle); + t.left(2 * angle); + img.tree(t, depth - 1, step * scale, scale, angle); + t.right(angle); + t.forward(img, -step); } -int main() { - int result = 0; - try { - Application.run(new FractalTree); - } catch(Exception e) { - msgBox(e.msg, "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR); - result = 1; - } - return result; +void main() { + auto img = new Image!Gray(330, 300); + auto t = Turtle(165, 270, -90); + img.tree(t, 10, 80, 0.7, 30); + img.savePGM("fractal_tree.pgm"); } diff --git a/Task/Fractal-tree/D/fractal-tree-3.d b/Task/Fractal-tree/D/fractal-tree-3.d new file mode 100644 index 0000000000..242b7ba011 --- /dev/null +++ b/Task/Fractal-tree/D/fractal-tree-3.d @@ -0,0 +1,43 @@ +import dfl.all; +import std.math; + +class FractalTree: Form { + + private immutable DEG_TO_RAD = PI / 180.0; + + this() { + width = 600; + height = 500; + text = "Fractal Tree"; + backColor = Color(0xFF, 0xFF, 0xFF); + startPosition = FormStartPosition.CENTER_SCREEN; + formBorderStyle = FormBorderStyle.FIXED_DIALOG; + maximizeBox = false; + } + + private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) { + if (depth == 0) return; + int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0); + int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0); + g.drawLine(p, x1, y1, x2, y2); + drawTree(g, p, x2, y2, angle - 20, depth - 1); + drawTree(g, p, x2, y2, angle + 20, depth - 1); + } + + protected override void onPaint(PaintEventArgs ea){ + super.onPaint(ea); + Pen p = new Pen(Color(0, 0xAA, 0)); + drawTree(ea.graphics, p, 300, 450, -90, 9); + } +} + +int main() { + int result = 0; + try { + Application.run(new FractalTree); + } catch(Exception e) { + msgBox(e.msg, "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR); + result = 1; + } + return result; +} diff --git a/Task/Fractal-tree/NetRexx/fractal-tree.netrexx b/Task/Fractal-tree/NetRexx/fractal-tree.netrexx new file mode 100644 index 0000000000..387d0fc089 --- /dev/null +++ b/Task/Fractal-tree/NetRexx/fractal-tree.netrexx @@ -0,0 +1,37 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +import java.awt.Color +import java.awt.Graphics +import javax.swing.JFrame + +class RFractalTree public extends JFrame + properties constant + isTrue = (1 == 1) + isFalse = \isTrue + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method RFractalTree() public + super('Fractal Tree') + setBounds(100, 100, 800, 600) + setResizable(isFalse) + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) + return + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method drawTree(g = Graphics, x1 = int, y1 = int, angle = double, depth = int) private + if depth \= 0 then do + x2 = x1 + (int Math.cos(Math.toRadians(angle)) * depth * 10.0) + y2 = y1 + (int Math.sin(Math.toRadians(angle)) * depth * 10.0) + g.drawLine(x1, y1, x2, y2) + drawTree(g, x2, y2, angle - 20, depth - 1) + drawTree(g, x2, y2, angle + 20, depth - 1) + end + return + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method paint(g = Graphics) public + g.setColor(Color.BLACK) + drawTree(g, 400, 500, -90, 9) + return + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method main(args = String[])public static + RFractalTree().setVisible(isTrue) + return diff --git a/Task/Function-composition/Julia/function-composition.julia b/Task/Function-composition/Julia/function-composition.julia new file mode 100644 index 0000000000..56de333938 --- /dev/null +++ b/Task/Function-composition/Julia/function-composition.julia @@ -0,0 +1 @@ +compose(f::Function, g::Function) = x->f(g(x)) diff --git a/Task/Function-definition/COBOL/function-definition.cobol b/Task/Function-definition/COBOL/function-definition-1.cobol similarity index 92% rename from Task/Function-definition/COBOL/function-definition.cobol rename to Task/Function-definition/COBOL/function-definition-1.cobol index afb55fe0b5..7c00afbef6 100644 --- a/Task/Function-definition/COBOL/function-definition.cobol +++ b/Task/Function-definition/COBOL/function-definition-1.cobol @@ -1,5 +1,3 @@ - * Multiply in COBOL - IDENTIFICATION DIVISION. PROGRAM-ID. myTest. DATA DIVISION. @@ -18,7 +16,6 @@ IDENTIFICATION DIVISION. PROGRAM-ID. myMultiply. DATA DIVISION. - WORKING-STORAGE SECTION. LINKAGE SECTION. 01 x PIC 9(3). 01 y PIC 9(3). diff --git a/Task/Function-definition/COBOL/function-definition-2.cobol b/Task/Function-definition/COBOL/function-definition-2.cobol new file mode 100644 index 0000000000..6c12bbfc1a --- /dev/null +++ b/Task/Function-definition/COBOL/function-definition-2.cobol @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. myTest. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION myMultiply. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 x PIC 9(3) VALUE 3. + 01 y PIC 9(3) VALUE 2. + PROCEDURE DIVISION. + DISPLAY myMultiply(x, y). + STOP RUN. + END PROGRAM myTest. + + IDENTIFICATION DIVISION. + FUNCTION-ID. myMultiply. + DATA DIVISION. + LINKAGE SECTION. + 01 x PIC 9(3). + 01 y PIC 9(3). + 01 z pic 9(9). + PROCEDURE DIVISION USING x, y RETURNING z. + MULTIPLY x BY y GIVING z. + EXIT FUNCTION. + END FUNCTION myMultiply. diff --git a/Task/Function-definition/Deja-Vu/function-definition.djv b/Task/Function-definition/Deja-Vu/function-definition.djv new file mode 100644 index 0000000000..754f28155a --- /dev/null +++ b/Task/Function-definition/Deja-Vu/function-definition.djv @@ -0,0 +1,2 @@ +multiply a b: + * a b diff --git a/Task/Function-definition/GAP/function-definition.gap b/Task/Function-definition/GAP/function-definition.gap new file mode 100644 index 0000000000..8284da1b0d --- /dev/null +++ b/Task/Function-definition/GAP/function-definition.gap @@ -0,0 +1,3 @@ +multiply := function(a, b) + return a*b; +end; diff --git a/Task/Function-definition/Julia/function-definition-3.julia b/Task/Function-definition/Julia/function-definition-3.julia new file mode 100644 index 0000000000..01d199afcc --- /dev/null +++ b/Task/Function-definition/Julia/function-definition-3.julia @@ -0,0 +1 @@ +(a,b) -> a*b diff --git a/Task/Function-definition/Neko/function-definition.neko b/Task/Function-definition/Neko/function-definition.neko index 1a17e2e947..d91f8af0b8 100644 --- a/Task/Function-definition/Neko/function-definition.neko +++ b/Task/Function-definition/Neko/function-definition.neko @@ -1,5 +1,12 @@ -// a function definition -var multiply = function(a,b) { a*b } +// a function definition can be written either as +var multiply = function(a, b) { + a * b +} + +// or +function multiply(a, b) { + a * b +} // and calling a function -$print( multiply(2,3) + "\n"); +$print(multiply(2,3)); diff --git a/Task/Function-definition/TXR/function-definition-2.txr b/Task/Function-definition/TXR/function-definition-2.txr index e79eb6f915..5653d1d6e7 100644 --- a/Task/Function-definition/TXR/function-definition-2.txr +++ b/Task/Function-definition/TXR/function-definition-2.txr @@ -1,2 +1,2 @@ @(do (defun mult (a b) (* a b)) - (format t "3 * 4 = ~a\n" (* 3 4))) + (format t "3 * 4 = ~a\n" (* 3 4))) diff --git a/Task/Function-definition/UNIX-Shell/function-definition-1.sh b/Task/Function-definition/UNIX-Shell/function-definition-1.sh index c7a6a4d7c1..e92a498586 100644 --- a/Task/Function-definition/UNIX-Shell/function-definition-1.sh +++ b/Task/Function-definition/UNIX-Shell/function-definition-1.sh @@ -7,4 +7,4 @@ multiply() { # Call the function multiply 3 4 # The function is invoked in statement context -echo $? # The dollarhook special variable gives the return value +echo $? # The dollarhook special variable gives the return value diff --git a/Task/Function-definition/X86-Assembly/function-definition-1.x86 b/Task/Function-definition/X86-Assembly/function-definition-1.x86 index 161394db99..923ccc1151 100644 --- a/Task/Function-definition/X86-Assembly/function-definition-1.x86 +++ b/Task/Function-definition/X86-Assembly/function-definition-1.x86 @@ -2,23 +2,23 @@ section .text global _start _multiply_regs: - mul ebx - mov eax, ebx - ret + mul ebx + mov eax, ebx + ret _multiply_stack: - enter 2,0 - mov eax, [esp+4] - mov ebx, [esp+8] - mul ebx - mov eax, ebx - leave - ret + enter 2,0 + mov eax, [esp+4] + mov ebx, [esp+8] + mul ebx + mov eax, ebx + leave + ret _start: - mov ax, 6 ;The number to multiply by - mov ebx, 16 ;base number to multiply. - call _multiply_regs - push 6 - push 16 - call _multiply_stack + mov ax, 6 ;The number to multiply by + mov ebx, 16 ;base number to multiply. + call _multiply_regs + push 6 + push 16 + call _multiply_stack diff --git a/Task/Function-definition/X86-Assembly/function-definition-2.x86 b/Task/Function-definition/X86-Assembly/function-definition-2.x86 index 23fbc41fe5..3e329f32cb 100644 --- a/Task/Function-definition/X86-Assembly/function-definition-2.x86 +++ b/Task/Function-definition/X86-Assembly/function-definition-2.x86 @@ -1,7 +1,7 @@ multiply proc arg1:dword, arg2:dword - mov eax, arg1 - mov ebx, arg2 - mul ebx - mov eax, ebx - ret + mov eax, arg1 + mov ebx, arg2 + mul ebx + mov eax, ebx + ret multiply endp diff --git a/Task/Function-definition/XPL0/function-definition.xpl0 b/Task/Function-definition/XPL0/function-definition.xpl0 index 1283ac91da..54e5a79219 100644 --- a/Task/Function-definition/XPL0/function-definition.xpl0 +++ b/Task/Function-definition/XPL0/function-definition.xpl0 @@ -1,6 +1,6 @@ func Multiply(A, B); \the characters in parentheses are only a comment int A, B; \the arguments are actually declared here, as integers -return A*B; \the default (undeclared) function type is integer +return A*B; \the default (undeclared) function type is integer \no need to enclose a single statement in brackets func real FloatMul(A, B); \floating point version diff --git a/Task/Function-frequency/Erlang/function-frequency.erl b/Task/Function-frequency/Erlang/function-frequency.erl new file mode 100644 index 0000000000..4190e482e4 --- /dev/null +++ b/Task/Function-frequency/Erlang/function-frequency.erl @@ -0,0 +1,31 @@ +-module( function_frequency ). + +-export( [erlang_source/1, task/0] ). + +erlang_source( File ) -> + {ok, IO} = file:open( File, [read] ), + Forms = parse_all( IO, io:parse_erl_form(IO, ''), [] ), + Functions = lists:flatten( [erl_syntax_lib:fold(fun accumulate_functions/2, [], X) || X <- Forms] ), + dict:to_list( lists:foldl(fun count/2, dict:new(), Functions) ). + +task() -> + Function_frequencies = erlang_source( "function_frequency.erl" ), + {Top_tens, _Rest} = lists:split( 10, lists:reverse(lists:keysort(2, Function_frequencies)) ), + [io:fwrite("Function ~p called ~p times.~n", [X, Y]) || {X, Y} <- Top_tens]. + + + +accumulate_functions( Tree, Acc ) -> accumulate_functions( erlang:element(1, Tree), Tree, Acc ). + +accumulate_functions( call, Tree, Acc ) -> [accumulate_functions_name(Tree) | Acc]; +accumulate_functions( _Other, _Tree, Acc ) -> Acc. + +accumulate_functions_name( Tree ) -> accumulate_functions_name_scoop( erlang:element(3, Tree) ). + +accumulate_functions_name_scoop( {atom, _Line, Name} ) -> Name; +accumulate_functions_name_scoop( {remote, _Line, {atom, _Line, Module}, {atom, _Line, Name}} ) -> {Module, Name}. + +count( Key, Dict ) -> dict:update_counter( Key, 1, Dict ). + +parse_all( _IO, {eof, _End}, Acc ) -> Acc; +parse_all( IO, {ok, Tokens, Location}, Acc ) -> parse_all( IO, io:parse_erl_form(IO, '', Location), [Tokens | Acc] ). diff --git a/Task/Function-frequency/Perl-6/function-frequency.pl6 b/Task/Function-frequency/Perl-6/function-frequency.pl6 new file mode 100644 index 0000000000..31a8be2474 --- /dev/null +++ b/Task/Function-frequency/Perl-6/function-frequency.pl6 @@ -0,0 +1,7 @@ +my $text = qqx[perl6 --target=ast @*ARGS[]]; +my %fun; +for $text.lines { + %fun{$0}++ if / '(call &' (.*?) ')' / +} + +for %fun.invert.sort.reverse[^10] { .value.say } diff --git a/Task/Function-prototype/COBOL/function-prototype.cobol b/Task/Function-prototype/COBOL/function-prototype.cobol index 308f381c01..e483b4e7f3 100644 --- a/Task/Function-prototype/COBOL/function-prototype.cobol +++ b/Task/Function-prototype/COBOL/function-prototype.cobol @@ -2,15 +2,15 @@ PROGRAM-ID. no-args PROTOTYPE. END PROGRAM no-args. - *> A subprogram taking two 8-digit numbers as arguments (passed by - *> value), and returning an 8-digit number. + *> A subprogram taking two 8-digit numbers as arguments, and returning + *> an 8-digit number. PROGRAM-ID. two-args PROTOTYPE. DATA DIVISION. LINKAGE SECTION. 01 arg-1 PIC 9(8). 01 arg-2 PIC 9(8). 01 ret PIC 9(8). - PROCEDURE DIVISION USING BY VALUE arg-1, arg-2 RETURNING ret. + PROCEDURE DIVISION USING arg-1, arg-2 RETURNING ret. END PROGRAM two-args. *> A subprogram taking two optional arguments which are 8-digit diff --git a/Task/Function-prototype/PL-I/function-prototype.pli b/Task/Function-prototype/PL-I/function-prototype.pli new file mode 100644 index 0000000000..5792667ff3 --- /dev/null +++ b/Task/Function-prototype/PL-I/function-prototype.pli @@ -0,0 +1,7 @@ +declare s1 entry; +declare s2 entry (fixed); +declare s3 entry (fixed, float); + +declare f1 entry returns (fixed); +declare f2 entry (float) returns (float); +declare f3 entry (character(*), character(*)) returns (character (20)); diff --git a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions.egl b/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions.egl new file mode 100644 index 0000000000..bc7b40f449 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions.egl @@ -0,0 +1,5 @@ +browser Browser{}; +bvh int = browser.getViewportHeight(); +bvw int = browser.getViewportWidth(); +SysLib.writeStdout("ViewportHeight: " + bvh); +SysLib.writeStdout("ViewportWidth: " + bvw); diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-1.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-1.fbsl new file mode 100644 index 0000000000..eb54c12363 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-1.fbsl @@ -0,0 +1,4 @@ +#INCLUDE +ShowWindow(ME, SW_MAXIMIZE) +BEGIN EVENTS +END EVENTS diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-2.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-2.fbsl new file mode 100644 index 0000000000..a0b3263ddd --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-2.fbsl @@ -0,0 +1,15 @@ +#APPTYPE CONSOLE +#INCLUDE + +TYPE RECT + %Left + %Top + %Right + %Bottom +END TYPE + +DIM rc AS RECT +SystemParametersInfo(SPI_GETWORKAREA, 0, @rc, 0) +PRINT "width = ", rc.Right - rc.Left, ", height = ", rc.Bottom - rc.Top + +PAUSE diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-3.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-3.fbsl new file mode 100644 index 0000000000..8079f1ca5c --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-3.fbsl @@ -0,0 +1,2 @@ +FMain.Maximized = True +FMain.Visible = False ' The form can be invisible diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-4.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-4.fbsl new file mode 100644 index 0000000000..b9a1b98527 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-4.fbsl @@ -0,0 +1,7 @@ +PUBLIC SUB _new() + +END + +PUBLIC SUB Form_Open() + +END diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-5.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-5.fbsl new file mode 100644 index 0000000000..62c047491e --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-5.fbsl @@ -0,0 +1,3 @@ +PUBLIC SUB Form_Resize() + PRINT "The maximum window size that can be used without scrolling is "; FMain.Width; " x "; FMain.Height +END diff --git a/Task/GUI-component-interaction/Scala/gui-component-interaction.scala b/Task/GUI-component-interaction/Scala/gui-component-interaction.scala index a291043ec0..892efd9f39 100644 --- a/Task/GUI-component-interaction/Scala/gui-component-interaction.scala +++ b/Task/GUI-component-interaction/Scala/gui-component-interaction.scala @@ -36,7 +36,7 @@ object Interact extends SimpleSwingApplication { numberField.text = showOptions(buttonPanel, message = "Are you sure?", title = "Choose an option!", entries = List("Yes", "No", "Cancel"), initial = 2) match { - case Result.Yes => (Long.MaxValue * Math.random).toLong.toString + case Result.Yes => (Long.MaxValue * math.random).toLong.toString case _ => numberField.text } } diff --git a/Task/Galton-box-animation/Java/galton-box-animation.java b/Task/Galton-box-animation/Java/galton-box-animation.java new file mode 100644 index 0000000000..e41a5ee57c --- /dev/null +++ b/Task/Galton-box-animation/Java/galton-box-animation.java @@ -0,0 +1,131 @@ +import java.util.Random; +import java.util.List; +import java.util.ArrayList; + +public class GaltonBox { + public static void main( final String[] args ) { + new GaltonBox( 8, 200 ).run(); + } + + private final int m_pinRows; + private final int m_startRow; + private final Position[] m_balls; + private final Random m_random = new Random(); + + public GaltonBox( final int pinRows, final int ballCount ) { + m_pinRows = pinRows; + m_startRow = pinRows + 1; + m_balls = new Position[ ballCount ]; + + for ( int ball = 0; ball < ballCount; ball++ ) + m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); + } + + private static class Position { + int m_row; + int m_col; + char m_char; + + Position( final int row, final int col, final char ch ) { + m_row = row; + m_col = col; + m_char = ch; + } + } + + public void run() { + for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { + ballsInPlay = dropBalls(); + print(); + } + } + + private int dropBalls() { + int ballsInPlay = 0; + int ballToStart = -1; + + // Pick a ball to start dropping + for ( int ball = 0; ball < m_balls.length; ball++ ) + if ( m_balls[ ball ].m_row == m_startRow ) + ballToStart = ball; + + // Drop balls that are already in play + for ( int ball = 0; ball < m_balls.length; ball++ ) + if ( ball == ballToStart ) { + m_balls[ ball ].m_row = m_pinRows; + ballsInPlay++; + } + else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) { + m_balls[ ball ].m_row -= 1; + m_balls[ ball ].m_col += m_random.nextInt( 2 ); + if ( 0 != m_balls[ ball ].m_row ) + ballsInPlay++; + } + + return ballsInPlay; + } + + private void print() { + for ( int row = m_startRow; row --> 1; ) { + for ( int ball = 0; ball < m_balls.length; ball++ ) + if ( m_balls[ ball ].m_row == row ) + printBall( m_balls[ ball ] ); + System.out.println(); + printPins( row ); + } + printCollectors(); + System.out.println(); + } + + private static void printBall( final Position pos ) { + for ( int col = pos.m_row + 1; col --> 0; ) + System.out.print( ' ' ); + for ( int col = 0; col < pos.m_col; col++ ) + System.out.print( " " ); + System.out.print( pos.m_char ); + } + + private void printPins( final int row ) { + for ( int col = row + 1; col --> 0; ) + System.out.print( ' ' ); + for ( int col = m_startRow - row; col --> 0; ) + System.out.print( ". " ); + System.out.println(); + } + + private void printCollectors() { + final List> collectors = new ArrayList>(); + + for ( int col = 0; col < m_startRow; col++ ) { + final List collector = new ArrayList(); + + collectors.add( collector ); + for ( int ball = 0; ball < m_balls.length; ball++ ) + if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col ) + collector.add( m_balls[ ball ] ); + } + + for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) { + for ( int col = 0; col < m_startRow; col++ ) { + final List collector = collectors.get( col ); + final int pos = row + collector.size() - rows; + + System.out.print( '|' ); + if ( pos >= 0 ) + System.out.print( collector.get( pos ).m_char ); + else + System.out.print( ' ' ); + } + System.out.println( '|' ); + } + } + + private static final int longest( final List> collectors ) { + int result = 0; + + for ( final List collector : collectors ) + result = Math.max( collector.size(), result ); + + return result; + } +} diff --git a/Task/Gamma-function/Julia/gamma-function-1.julia b/Task/Gamma-function/Julia/gamma-function-1.julia new file mode 100644 index 0000000000..c4129dc643 --- /dev/null +++ b/Task/Gamma-function/Julia/gamma-function-1.julia @@ -0,0 +1 @@ +gamma(x) diff --git a/Task/Gamma-function/Julia/gamma-function-2.julia b/Task/Gamma-function/Julia/gamma-function-2.julia new file mode 100644 index 0000000000..079c39c211 --- /dev/null +++ b/Task/Gamma-function/Julia/gamma-function-2.julia @@ -0,0 +1,4 @@ +gamma_quad(t) = quadgk(x -> x^(t-1)*exp(-x), zero(t), inf(t), reltol=100*eps(t))[1] + +# generalize to handle arrays of inputs: +@vectorize_1arg Real gamma_quad diff --git a/Task/Gamma-function/Julia/gamma-function-3.julia b/Task/Gamma-function/Julia/gamma-function-3.julia new file mode 100644 index 0000000000..940d83cd64 --- /dev/null +++ b/Task/Gamma-function/Julia/gamma-function-3.julia @@ -0,0 +1,14 @@ +julia> x = rand(10)*20 +julia> (gamma_quad(x) - gamma(x)) ./ gamma(x) + +10-element Array{Any,1}: + -1.64473e-16 + 1.30036e-16 + 0.0 + -1.92627e-16 + 0.0 + 2.06808e-16 + -1.46141e-16 + 1.65947e-16 + 0.0 + 0.0 diff --git a/Task/Generic-swap/AWK/generic-swap.awk b/Task/Generic-swap/AWK/generic-swap.awk new file mode 100644 index 0000000000..1ad66b057c --- /dev/null +++ b/Task/Generic-swap/AWK/generic-swap.awk @@ -0,0 +1,25 @@ +# syntax: GAWK -f GENERIC_SWAP.AWK +BEGIN { + printf("%s version %s\n",ARGV[0],PROCINFO["version"]) + foo = 1 + bar = "a" + printf("\n%s %s\n",foo,bar) + rc = swap("foo","bar") # ok + printf("%s %s %s\n",foo,bar,rc?"ok":"ng") + printf("\n%s %s\n",foo,bar) + rc = swap("FOO","BAR") # ng + printf("%s %s %s\n",foo,bar,rc?"ok":"ng") + exit(0) +} +function swap(a1,a2, tmp) { # strings or numbers only; no arrays + if (a1 in SYMTAB && a2 in SYMTAB) { + if (isarray(SYMTAB[a1]) || isarray(SYMTAB[a2])) { + return(0) + } + tmp = SYMTAB[a1] + SYMTAB[a1] = SYMTAB[a2] + SYMTAB[a2] = tmp + return(1) + } + return(0) +} diff --git a/Task/Generic-swap/Julia/generic-swap.julia b/Task/Generic-swap/Julia/generic-swap.julia new file mode 100644 index 0000000000..053b49fb51 --- /dev/null +++ b/Task/Generic-swap/Julia/generic-swap.julia @@ -0,0 +1 @@ +a, b = b, a diff --git a/Task/Generic-swap/Nimrod/generic-swap.nimrod b/Task/Generic-swap/Nimrod/generic-swap.nimrod new file mode 100644 index 0000000000..0a57ac0104 --- /dev/null +++ b/Task/Generic-swap/Nimrod/generic-swap.nimrod @@ -0,0 +1 @@ +swap(a, b) diff --git a/Task/Globally-replace-text-in-several-files/C-sharp/globally-replace-text-in-several-files.cs b/Task/Globally-replace-text-in-several-files/C-sharp/globally-replace-text-in-several-files.cs new file mode 100644 index 0000000000..5ae2289b06 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/C-sharp/globally-replace-text-in-several-files.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.IO; + +class Program { + static void Main() { + var files = new List { + "test1.txt", + "test2.txt" + }; + foreach (string file in files) { + File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!")); + } + } +} diff --git a/Task/Globally-replace-text-in-several-files/Julia/globally-replace-text-in-several-files.julia b/Task/Globally-replace-text-in-several-files/Julia/globally-replace-text-in-several-files.julia new file mode 100644 index 0000000000..0ca690ae65 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Julia/globally-replace-text-in-several-files.julia @@ -0,0 +1,7 @@ +filenames = ["f1.txt", "f2.txt"] +for filename in filenames + txt = readall(filename) + open(filename, "w") do f + write(f, replace(txt, "Goodbye London!", "Hello New York!")) + end +end diff --git a/Task/Globally-replace-text-in-several-files/VBScript/globally-replace-text-in-several-files.vb b/Task/Globally-replace-text-in-several-files/VBScript/globally-replace-text-in-several-files.vb new file mode 100644 index 0000000000..df0dcf5bed --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/VBScript/globally-replace-text-in-several-files.vb @@ -0,0 +1,14 @@ +Const ForReading = 1 +Const ForWriting = 2 + +strFiles = Array("test1.txt", "test2.txt", "test3.txt") + +With CreateObject("Scripting.FileSystemObject") + For i = 0 To UBound(strFiles) + strText = .OpenTextFile(strFiles(i), ForReading).ReadAll() + With .OpenTextFile(strFiles(i), ForWriting) + .Write Replace(strText, "Goodbye London!", "Hello New York!") + .Close + End With + Next +End With diff --git a/Task/Gray-code/D/gray-code-1.d b/Task/Gray-code/D/gray-code-1.d index db8eb9bf63..930c6da424 100644 --- a/Task/Gray-code/D/gray-code-1.d +++ b/Task/Gray-code/D/gray-code-1.d @@ -1,23 +1,22 @@ -import std.stdio; - -T enGray(T)(in T n) pure nothrow { - return n ^ (n >>> 1); +uint grayEncode(in uint n) pure nothrow { + return n ^ (n >> 1); } -T deGray(T)(in T n) pure nothrow { - enum T MSB = (cast(T)1) << (T.sizeof * 8 - 1); - - auto res = (n & MSB) ; - foreach (bit; 1 .. T.sizeof * 8) - res += (n ^ (res >>> 1)) & (MSB >>> bit); - return res; +uint grayDecode(uint n) pure nothrow { + auto p = n; + while (n >>= 1) + p ^= n; + return p; } void main() { - writeln("num bits encoded decoded"); - foreach (i; 0 .. 32) { - immutable encoded = enGray(i); - writefln("%2d: %5b ==> %5b : %2d", - i, i, encoded, deGray(encoded)); + import std.stdio; + + " N N2 enc dec2 dec".writeln; + foreach (immutable n; 0 .. 32) { + immutable g = n.grayEncode; + immutable d = g.grayDecode; + writefln("%2d: %5b => %5b => %5b: %2d", n, n, g, d, d); + assert(d == n); } } diff --git a/Task/Gray-code/Haskell/gray-code.hs b/Task/Gray-code/Haskell/gray-code.hs index d475840cf8..f28983ffcb 100644 --- a/Task/Gray-code/Haskell/gray-code.hs +++ b/Task/Gray-code/Haskell/gray-code.hs @@ -1,28 +1,18 @@ -module Main where +import Data.Bits +import Data.Char +import Numeric +import Text.Printf -main = mapM_ (putStrLn . flip grayconvstr 5) [0..31] +-- Conversion to and from traditional binary and Gray code +grayToBin :: (Integral t, Bits t) => t -> t +grayToBin 0 = 0 +grayToBin g = g `xor` (grayToBin $ g `shiftR` 1) --- Convert number to bit list, MSB first. Second argument is minimum width. -num2bin :: (Integral t) => t -> t -> [t] -num2bin n w = num2bin' n w [] where - num2bin' n w acc | n <= 0 && w <= 0 = acc - | otherwise = num2bin' m (w-1) (b:acc) - where (m, b) = divMod n 2 +binToGray :: (Integral t, Bits t) => t -> t +binToGray b = b `xor` (b `shiftR` 1) -xor2 :: (Integral t) => t -> t -> t -xor2 x y = (x + y) `mod` 2 - -bin2gray :: (Integral t) => [t] -> [t] -bin2gray [] = [] -bin2gray (x:xs) = x : zipWith xor2 xs (x:xs) - -gray2bin :: (Integral t) => [t] -> [t] -gray2bin = scanl1 xor2 - --- Prettyprinting, since it is in the task description... -grayconvstr :: (Integral t, Show t) => t -> t -> String -grayconvstr n w = (show n) ++ ": " ++ (show b) ++ " => " ++ (show g) ++ " => " ++ (show u) - where - b = num2bin n w - g = bin2gray b - u = gray2bin g +-- Print the first 32 Gray codes alongside their decimal and binary equivalences. +main = flip mapM_ (take 32 [0,1..] :: [Int]) (\num -> do + let bin = showIntAtBase 2 intToDigit num "" + gray = showIntAtBase 2 intToDigit (binToGray num) "" + printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray) diff --git a/Task/Gray-code/Julia/gray-code.julia b/Task/Gray-code/Julia/gray-code.julia new file mode 100644 index 0000000000..5cb734a2a2 --- /dev/null +++ b/Task/Gray-code/Julia/gray-code.julia @@ -0,0 +1,9 @@ +gray_encode(n) = n $ (n >> 1) + +function gray_decode(n) + p = n + while (n >>= 1) != 0 + p $= n + end + return p +end diff --git a/Task/Gray-code/PHP/gray-code.php b/Task/Gray-code/PHP/gray-code-1.php similarity index 100% rename from Task/Gray-code/PHP/gray-code.php rename to Task/Gray-code/PHP/gray-code-1.php diff --git a/Task/Gray-code/PHP/gray-code-2.php b/Task/Gray-code/PHP/gray-code-2.php new file mode 100644 index 0000000000..220e2f5522 --- /dev/null +++ b/Task/Gray-code/PHP/gray-code-2.php @@ -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/Standard-ML/gray-code.ml b/Task/Gray-code/Standard-ML/gray-code.ml new file mode 100644 index 0000000000..7786412e43 --- /dev/null +++ b/Task/Gray-code/Standard-ML/gray-code.ml @@ -0,0 +1,25 @@ +fun gray_encode b = + Word.xorb (b, Word.>> (b, 0w1)) + +fun gray_decode n = + let + fun aux (p, n) = + if n = 0w0 then p + else aux (Word.xorb (p, n), Word.>> (n, 0w1)) + in + aux (n, Word.>> (n, 0w1)) + end; + +val s = Word.fmt StringCvt.BIN; +fun aux i = + if i = 0w32 then + () + else + let + val g = gray_encode i + val b = gray_decode g + in + print (Word.toString i ^ " :\t" ^ s i ^ " => " ^ s g ^ " => " ^ s b ^ "\t: " ^ Word.toString b ^ "\n"); + aux (i + 0w1) + end; +aux 0w0 diff --git a/Task/Grayscale-image/D/grayscale-image.d b/Task/Grayscale-image/D/grayscale-image.d index ebe9fcabd1..18b4408ed6 100644 --- a/Task/Grayscale-image/D/grayscale-image.d +++ b/Task/Grayscale-image/D/grayscale-image.d @@ -106,12 +106,12 @@ Image!RGB gray2rgbImage(in Image!Gray im) { version (grayscale_image_main) { void main() { - auto im1 = new Image!Gray(); + auto im1 = new Image!Gray; im1.loadPGM("lena.pgm"); gray2rgbImage(im1).savePPM6("lena_rgb.ppm"); - auto img2 = new Image!RGB(); + auto img2 = new Image!RGB; img2.loadPPM6("quantum_frog.ppm"); - img2.rgb2grayImage().savePGM("quantum_frog_grey.pgm"); + img2.rgb2grayImage.savePGM("quantum_frog_grey.pgm"); } } diff --git a/Task/Grayscale-image/Euler-Math-Toolbox/grayscale-image.euler b/Task/Grayscale-image/Euler-Math-Toolbox/grayscale-image.euler new file mode 100644 index 0000000000..827e6e6b6c --- /dev/null +++ b/Task/Grayscale-image/Euler-Math-Toolbox/grayscale-image.euler @@ -0,0 +1,9 @@ +>A=loadrgb("mona.jpg"); +>insrgb(A); +>function grayscale (A) ... +${r,g,b}=getrgb(A); +$c=0.2126*r+0.7152*g+0.0722*b; +$return rgb(c,c,c); +$endfunction +>insrgb(grayscale(A)); +>insrgb(A|grayscale(A)); diff --git a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js new file mode 100644 index 0000000000..0ca0d4ac1c --- /dev/null +++ b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js @@ -0,0 +1,14 @@ +function GCD(A) // A is an integer array (e.g. [57,0,-45,-18,90,447]) +{ + var n = A.length, x = A[0] < 0 ? -A[0] : A[0]; + for (var i = 1; i < n; i++) + { var y = A[i] < 0 ? -A[i] : A[i]; + while (x && y){ x > y ? x %= y : y %= x; } + x += y; + } + return x; +} + +/* For example: + GCD([57,0,-45,-18,90,447]) -> 3 +*/ diff --git a/Task/Greatest-common-divisor/Limbo/greatest-common-divisor.limbo b/Task/Greatest-common-divisor/Limbo/greatest-common-divisor.limbo new file mode 100644 index 0000000000..45e8a0cb9d --- /dev/null +++ b/Task/Greatest-common-divisor/Limbo/greatest-common-divisor.limbo @@ -0,0 +1,6 @@ +gcd(x: int, y: int): int +{ + if(y == 0) + return x; + return gcd(y, x % y); +} diff --git a/Task/Greatest-common-divisor/NetRexx/greatest-common-divisor.netrexx b/Task/Greatest-common-divisor/NetRexx/greatest-common-divisor.netrexx new file mode 100644 index 0000000000..66ea6a199e --- /dev/null +++ b/Task/Greatest-common-divisor/NetRexx/greatest-common-divisor.netrexx @@ -0,0 +1,93 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 2000 +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- Euclid's algorithm - iterative implementation +method gcdEucidI(a_, b_) public static + loop while b_ > 0 + c_ = a_ // b_ + a_ = b_ + b_ = c_ + end + return a_ + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- Euclid's algorithm - recursive implementation +method gcdEucidR(a_, b_) public static + if b_ \= 0 then a_ = gcdEucidR(b_, a_ // b_) + return a_ + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + -- pairs of numbers, each number in the pair separated by a colon, each pair separated by a comma + parse arg tests + if tests = '' then + tests = '0:0, 6:4, 7:21, 12:36, 33:77, 41:47, 99:51, 100:5, 7:23, 1989:867, 12345:9876, 40902:24140, 49865:69811, 137438691328:2305843008139952128' + + -- most of what follows is for formatting + xiterate = 0 + xrecurse = 0 + ll_ = 0 + lr_ = 0 + lgi = 0 + lgr = 0 + loop i_ = 1 until tests = '' + xiterate[0] = i_ + xrecurse[0] = i_ + parse tests pair ',' tests + parse pair l_ ':' r_ . + + -- get the GCDs + gcdi = gcdEucidI(l_, r_) + gcdr = gcdEucidR(l_, r_) + + xiterate[i_] = l_ r_ gcdi + xrecurse[i_] = l_ r_ gcdr + ll_ = ll_.max(l_.strip.length) + lr_ = lr_.max(r_.strip.length) + lgi = lgi.max(gcdi.strip.length) + lgr = lgr.max(gcdr.strip.length) + end i_ + -- save formatter sizes in stems + xiterate[-1] = ll_ lr_ lgi + xrecurse[-1] = ll_ lr_ lgr + + -- present results + showResults(xiterate, 'Euclid''s algorithm - iterative') + showResults(xrecurse, 'Euclid''s algorithm - recursive') + say + if verifyResults(xiterate, xrecurse) then + say 'Success: Results of iterative and recursive methods match' + else + say 'Error: Results of iterative and recursive methods do not match' + say + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method showResults(stem, title) public static + say + say title + parse stem[-1] ll lr lg + loop v_ = 1 to stem[0] + parse stem[v_] lv rv gcd . + say lv.right(ll)',' rv.right(lr) ':' gcd.right(lg) + end v_ + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method verifyResults(stem1, stem2) public static returns boolean + if stem1[0] \= stem2[0] then signal BadArgumentException + T = (1 == 1) + F = \T + verified = T + loop i_ = 1 to stem1[0] + if stem1[i_] \= stem2[i_] then do + verified = F + leave i_ + end + end i_ + return verified diff --git a/Task/Greatest-element-of-a-list/Deja-Vu/greatest-element-of-a-list.djv b/Task/Greatest-element-of-a-list/Deja-Vu/greatest-element-of-a-list.djv new file mode 100644 index 0000000000..06d2a813ff --- /dev/null +++ b/Task/Greatest-element-of-a-list/Deja-Vu/greatest-element-of-a-list.djv @@ -0,0 +1,7 @@ +max lst: + lst! 0 + for item in copy lst: + if > item dup: + item drop + +!. max [ 10 300 999 9 ] diff --git a/Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.julia b/Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.julia index a765d0e6ce..0854f8d2bf 100644 --- a/Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.julia +++ b/Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.julia @@ -1,11 +1,13 @@ -julia> max([1,3,3,7]) +julia> maximum([1,3,3,7]) 7 -julia> max([pi,e+2/5,cos(6)/5,sqrt(91/10)]) +julia> maximum([pi,e+2/5,cos(6)/5,sqrt(91/10)]) 3.141592653589793 -julia> max([1,6,Inf]) +julia> maximum([1,6,Inf]) Inf -julia> max(Float64[]) --Inf +julia> maximum(Float64[]) +maximum: argument is empty +at In[138]:1 + in maximum at abstractarray.jl:1591 diff --git a/Task/Greatest-element-of-a-list/Prolog/greatest-element-of-a-list-2.pro b/Task/Greatest-element-of-a-list/Prolog/greatest-element-of-a-list-2.pro index 9616cdbd77..863539d8e6 100644 --- a/Task/Greatest-element-of-a-list/Prolog/greatest-element-of-a-list-2.pro +++ b/Task/Greatest-element-of-a-list/Prolog/greatest-element-of-a-list-2.pro @@ -1,11 +1,2 @@ -max_list([H|T], Max) :- - max_list(T, H, Max). - -max_list([], Max, Max). - -max_list([H|T], Max0, Max) :- - H > Max0, !, - max_list(T, H, Max). - -max_list([_|T], Max0, Max) :- - max_list(T, Max0, Max). +max_list(L, V) :- + select(V, L, R), \+((member(X, R), X > V)). diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx index 07eedf5437..94e7944044 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx @@ -1,11 +1,11 @@ /*REXX program finds the greatest element in a list (of numbers). */ /* [↓] list of first twenty reversed primes*/ -y = '2 3 5 7 11 31 71 91 32 92 13 73 14 34 74 35 95 16 76 17' +y = 2 3 5 7 11 31 71 91 32 92 13 73 14 34 74 35 95 16 76 17 +big=word(y,1) /*choose a initial biggest number*/ + do j=2 to words(y) /*traipse through the list. */ + big=max(big, word(y,j)) /*use the MAX bif to find biggie.*/ + end /*j*/ -big = word(y,1) /*choose a initial biggest number*/ - do j=2 to words(y) /*traipse through the list. */ - big = max(big, word(y,j)) - end /*j*/ - -say 'the biggest value in a list of' words(y) "numbers is:" big +say 'the biggest value in a list of ' words(y) " numbers is: " big + /* [↓] list of first twenty reversed primes*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx index 0f5564e5ec..dbc7f6c1f1 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx @@ -1,14 +1,14 @@ /*REXX program finds the greatest element in an array (of numbers). */ +y.= /*set all array elements to null.*/ y.1 = 2; y.2 = 3; y.3 = 5; y.4 = 7; y.5 = 11 y.6 = 31; y.7 = 71; y.8 = 91; y.9 = 32; y.10 = 92 y.11 = 13; y.12 = 73; y.13 = 14; y.14 = 34; y.15 = 74 y.16 = 35; y.17 = 95; y.18 = 16; y.19 = 76; y.20 = 17 big = y.1 /*choose a initial biggest number*/ -items = 20 /*number of elements in the array*/ - do j=2 to items /*traipse through the array. */ - big = max(big, y.j) /*use a BIF for finding the max. */ + do j=2 while y.j\=='' /*traipse through the whole array*/ + big = max(big, y.j) /*use a BIF to find the biggie.*/ end /*j*/ -say 'the biggest value in an array of' items "elements is:" big +say 'the biggest value in an array of ' j-1 " elements is: " big /*stick a fork in it, we're done.*/ diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx index 371d0e3073..cc6f66c9ec 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx @@ -1,18 +1,13 @@ -/* REXX *************************************************************** -* If the list contains any character strings, the following will wotk -* Note the use of >> (instead of >) to avoid numeric comparison -* 30.07.2013 Walter Pachl -**********************************************************************/ -list='Walter Pachl living in Vienna' -Say max(list) -list='8 33 -12' -Say max(list) -Exit -max: Procedure -Parse Arg l -max=word(l,1) -Do i=2 To words(l) - If word(l,i)>>max Then - max=word(l,i) - End -Return max +/*REXX program finds the greatest element in an array (of numbers). */ +say 'Please enter a list of numbers (separated by blanks or commas):' +parse pull nums /*get a list from console (user).*/ +nums=translate(nums,,',') /*change commas (,) to blanks.*/ +items=words(nums) /*obtain the number of numbers. */ +big=word(nums,1) /*assume the biggest is the 1st #*/ + + do j=2 to items /*traipse through the list. */ + big = max(big, word(nums,j) ) /*use a BIF for finding the max. */ + end /*j*/ + +say 'the biggest value in the list of ' items " elements is: " big + /*stick a fork in it, we're done.*/ diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx new file mode 100644 index 0000000000..371d0e3073 --- /dev/null +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx @@ -0,0 +1,18 @@ +/* REXX *************************************************************** +* If the list contains any character strings, the following will wotk +* Note the use of >> (instead of >) to avoid numeric comparison +* 30.07.2013 Walter Pachl +**********************************************************************/ +list='Walter Pachl living in Vienna' +Say max(list) +list='8 33 -12' +Say max(list) +Exit +max: Procedure +Parse Arg l +max=word(l,1) +Do i=2 To words(l) + If word(l,i)>>max Then + max=word(l,i) + End +Return max diff --git a/Task/Guess-the-number-With-feedback--player-/Perl/guess-the-number-with-feedback--player-.pl b/Task/Guess-the-number-With-feedback--player-/Perl/guess-the-number-with-feedback--player-.pl index b9e0a81173..b5006859bb 100644 --- a/Task/Guess-the-number-With-feedback--player-/Perl/guess-the-number-with-feedback--player-.pl +++ b/Task/Guess-the-number-With-feedback--player-/Perl/guess-the-number-with-feedback--player-.pl @@ -2,43 +2,35 @@ my $min = 1; my $max = 99; +my $guess = int(rand $max) + $min; +my $tries = 0; print "=>> Think of a number between $min and $max and I'll guess it!\n Press when are you ready... "; ; -my $guess = int(rand $max) + $min; -my $tries = 0; +{ + do { -sub question { - my $guess = shift(); - print "\n=>> My guess is: $guess. Is your number higher, lower or equal? (h/l/e)\n> "; - ++$tries; -} - -question $guess; - -while (1) { - my $score = ; - - if (lc substr($score, 0, 1) eq 'h') { - $min = $guess + 1; - } - elsif (lc substr($score, 0, 1) eq 'l') { - $max = $guess; - } - elsif (lc substr($score, 0, 1) eq 'e') { - print "\nI knew it! It took me only $tries tries.\n"; - last; - } - else { - print "error: invalid score\n"; - } - - print "\nI gave up...\n" and last if $max <= $min; - - $guess = int(($max + $min) / 2); - - question $guess; + $tries++; + print "\n=>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e)\n> "; + + my $score = ; + + if ($max <= $min) { + print "\nI give up...\n" and last; + } elsif ($score =~ /^h/i) { + $min = $guess + 1; + } elsif ($score =~ /^l/i) { + $max = $guess; + } elsif ($score =~ /^e/i) { + print "\nI knew it! It took me only $tries tries.\n" and last; + } else { + print "error: invalid score\n"; + } + + $guess = int(($max + $min) / 2); + + } while(1); } diff --git a/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust b/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust new file mode 100644 index 0000000000..98c40c7371 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust @@ -0,0 +1,50 @@ +use std::io::stdio::stdin; +use std::str; + +fn main() { + let mut low = 1; + let mut high = 100; + let mut current_guess = calculate_guess(low, high); + let mut number_of_guesses = 1; + let mut stdin = stdin(); + + let take_a_guess = |new_low: int, new_high: int| { + low = new_low; + high = new_high; + number_of_guesses += 1; + current_guess = calculate_guess(low, high); + }; + + println!("Hello, please choose a number between {} and {} and remember it.", low, high); + println("Got it? Good. Now I shall guess it using only the power of my mind.\n"); + + loop { + println!("My guess is {:d}. Is that too [h]igh, too [l]ow or is it [e]qual to it? ", current_guess); + println("(please type h, l or e and then hit enter)"); + let buf: &mut [u8] = [0u8, ..8]; + let num_bytes = stdin.read(buf); + let answer = str::from_utf8(buf).slice_to(num_bytes.unwrap()).trim(); + match answer { + "e" | "E" => { + println!("Jolly good! I got it in only {} tries!", number_of_guesses); + break; + } + "l" | "L" => take_a_guess(current_guess, high), + "h" | "H" => take_a_guess(low, current_guess), + _ => println("sorry, I didn't quite get that") + + } + if low == high { + println!("Your number must be {}. Or maybe you forgot it? It happens!", low); + break; + } + if low > high { + println("Uh, I think something went wrong. Entirely my fault, I'm sure!"); + break; + } + } +} + +fn calculate_guess(low: int, high: int) -> int { + (low + high) / 2 +} diff --git a/Task/Guess-the-number-With-feedback--player-/VBA/guess-the-number-with-feedback--player-.vba b/Task/Guess-the-number-With-feedback--player-/VBA/guess-the-number-with-feedback--player-.vba new file mode 100644 index 0000000000..57d8f9f05c --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/VBA/guess-the-number-with-feedback--player-.vba @@ -0,0 +1,28 @@ +Sub GuessNumberPlayer() +Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer +Dim vSolved As Variant +On Error GoTo ErrHandler +MsgBox "Pick a number between 1 and 100. I will guess it!", vbInformation + vbOKOnly, "Rosetta Code | Guess the Number Player" +iCount = 0 +iLow = 1 +iHigh = 100 +Do While Not vSolved = "Y" + iGuess = Application.WorksheetFunction.RandBetween(iLow, iHigh) + iCount = iCount + 1 +CheckGuess: + vSolved = InputBox("My guess: " & iGuess & vbCr & vbCr & "Y = Yes, correct guess" & vbCr & _ + "H = your number is higher" & vbCr & "L = your number is lower" & vbCr & "X = exit game", "Rosetta Code | Guess the Number Player | Guess " & iCount) + Select Case vSolved + Case "Y", "y": GoTo CorrectGuess + Case "X", "x": Exit Sub + Case "H", "h": iLow = iGuess + 1 + Case "L", "l": iHigh = iGuess - 1 + Case Else: GoTo CheckGuess + End Select +Loop +CorrectGuess: + MsgBox "I guessed number " & iGuess & " in just " & iCount & " attempts!", vbExclamation + vbOKOnly, "Rosetta Code | Guess the Number Player" + Exit Sub +ErrHandler: + MsgBox "Not possible. Were you cheating?!", vbCritical + vbOKOnly, "Rosetta Code | Guess the Number Player | ERROR!" +End Sub diff --git a/Task/Guess-the-number-With-feedback/AWK/guess-the-number-with-feedback.awk b/Task/Guess-the-number-With-feedback/AWK/guess-the-number-with-feedback.awk new file mode 100644 index 0000000000..a918daa501 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/AWK/guess-the-number-with-feedback.awk @@ -0,0 +1,28 @@ +# syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK +BEGIN { + L = 1 + H = 100 + srand() + n = int(rand() * (H-L+1)) + 1 + printf("I am thinking of a number between %d and %d. Try to guess it.\n",L,H) + while (1) { + getline ans + if (ans !~ /^[0-9]+$/) { + print("Your input was not a number. Try again.") + continue + } + if (n == ans) { + print("Well done you.") + break + } + if (n > ans) { + print("Incorrect, your answer was too low. Try again.") + continue + } + if (n < ans) { + print("Incorrect, your answer was too high. Try again.") + continue + } + } + exit(0) +} diff --git a/Task/Guess-the-number-With-feedback/BASIC/guess-the-number-with-feedback.basic b/Task/Guess-the-number-With-feedback/BASIC/guess-the-number-with-feedback.basic new file mode 100644 index 0000000000..998d086838 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/BASIC/guess-the-number-with-feedback.basic @@ -0,0 +1,14 @@ +100 L% = 1 +110 U% = 10 +120 N% = RND(1) * (U% - L% + 1) + L% +130 PRINT "A NUMBER FROM " L%; +140 PRINT " TO " U%; +150 PRINT ", CALLED A TARGET, HAS BEEN RANDOMLY CHOSEN." +160 FOR Q = 0 TO 1 STEP 0 +170 INPUT "GUESS THE TARGET NUMBER: "; G% +180 IF G% < L% OR G% > U% THEN PRINT "THE INPUT WAS INAPPROPRIATE." +190 IF G% > N% THEN PRINT "THE GUESS WAS HIGHER THAN THE TARGET." +200 IF G% < N% THEN PRINT "THE GUESS WAS LESS THAN THE TARGET." +210 Q = G% = N% +220 NEXT +230 PRINT "THE GUESS WAS EQUAL TO THE TARGET." diff --git a/Task/Guess-the-number/AWK/guess-the-number.awk b/Task/Guess-the-number/AWK/guess-the-number.awk new file mode 100644 index 0000000000..83130fd303 --- /dev/null +++ b/Task/Guess-the-number/AWK/guess-the-number.awk @@ -0,0 +1,19 @@ +# syntax: GAWK -f GUESS_THE_NUMBER.AWK +BEGIN { + srand() + n = int(rand() * 10) + 1 + print("I am thinking of a number between 1 and 10. Try to guess it.") + while (1) { + getline ans + if (ans !~ /^[0-9]+$/) { + print("Your input was not a number. Try again.") + continue + } + if (n == ans) { + print("Well done you.") + break + } + print("Incorrect. Try again.") + } + exit(0) +} diff --git a/Task/Guess-the-number/BASIC/guess-the-number-1.basic b/Task/Guess-the-number/BASIC/guess-the-number-1.basic index 49c036043a..a3fe28b6b3 100644 --- a/Task/Guess-the-number/BASIC/guess-the-number-1.basic +++ b/Task/Guess-the-number/BASIC/guess-the-number-1.basic @@ -1,9 +1,9 @@ -10 LET n=INT (RND*10)+1 -20 PRINT "I have thought of a number." -30 PRINT "Try to guess it!" -40 INPUT "Enter your guess: ";g -50 IF g=n THEN GO TO 100 -60 PRINT "Your guess was wrong. Try again!" -70 GO TO 40 - -100 PRINT "Well done! You guessed it." +10 N% = RND(1) * 10 + 1 +20 PRINT "A NUMBER FROM 1 "; +30 PRINT "TO 10 HAS BEEN "; +40 PRINT "RANDOMLY CHOSEN." +50 FOR Q = 0 TO 1 STEP 0 +60 INPUT "ENTER A GUESS. "; G% +70 Q = G% = N% +80 NEXT +90 PRINT "WELL GUESSED!" diff --git a/Task/Guess-the-number/BASIC/guess-the-number-3.basic b/Task/Guess-the-number/BASIC/guess-the-number-3.basic new file mode 100644 index 0000000000..49c036043a --- /dev/null +++ b/Task/Guess-the-number/BASIC/guess-the-number-3.basic @@ -0,0 +1,9 @@ +10 LET n=INT (RND*10)+1 +20 PRINT "I have thought of a number." +30 PRINT "Try to guess it!" +40 INPUT "Enter your guess: ";g +50 IF g=n THEN GO TO 100 +60 PRINT "Your guess was wrong. Try again!" +70 GO TO 40 + +100 PRINT "Well done! You guessed it." diff --git a/Task/Guess-the-number/Deja-Vu/guess-the-number.djv b/Task/Guess-the-number/Deja-Vu/guess-the-number.djv new file mode 100644 index 0000000000..763ad5d8d3 --- /dev/null +++ b/Task/Guess-the-number/Deja-Vu/guess-the-number.djv @@ -0,0 +1,8 @@ +local :number random-range 1 11 + +while true: + if = number to-num !prompt "Guess my number: ": + !print "Congratulations, you've guessed it!" + return + else: + !print "Nope, try again." diff --git a/Task/Guess-the-number/GML/guess-the-number.gml b/Task/Guess-the-number/GML/guess-the-number.gml index a24bd83d07..2d3cbc83dd 100644 --- a/Task/Guess-the-number/GML/guess-the-number.gml +++ b/Task/Guess-the-number/GML/guess-the-number.gml @@ -1,7 +1,9 @@ -n = string(ceil(random(10))); +var n, g; +n = irandom_range(1,10); show_message("I'm thinking of a number from 1 to 10"); -g = get_string("Please enter guess", ""); -while(g != n){ - g=get_string("I'm sorry "+g+" is not my number, try again. Please enter guess", "");} -show_message("Correct! "+g+" was my number!"); -exit +g = get_integer("Please enter guess", 1); +while(g != n) + { + g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1); + } +show_message("Well guessed!"); diff --git a/Task/Guess-the-number/Objective-C/guess-the-number.m b/Task/Guess-the-number/Objective-C/guess-the-number.m new file mode 100644 index 0000000000..62b65ac46c --- /dev/null +++ b/Task/Guess-the-number/Objective-C/guess-the-number.m @@ -0,0 +1,39 @@ +#import + +int main(int argc, const char * argv[]) +{ + + @autoreleasepool { + + NSLog(@"I'm thinking of a number between 1 - 10. Can you guess what it is?\n"); + + int rndNumber = (arc4random() % 10) + 1; + + // Debug (Show rndNumber in console) + //NSLog(@"Random number is %i", rndNumber); + + int userInput; + + do { + + NSLog(@"Input the number below\n"); + scanf("%i", &userInput); + + if (userInput > 10) { + + NSLog(@"Please enter a number less than 10\n"); + } + + if (userInput > 10 || userInput != rndNumber) { + + NSLog(@"Your guess %i is incorrect, please try again", userInput); + + } else { + + NSLog(@"Your guess %i is correct!", userInput); + } + + } while (userInput > 10 || userInput != rndNumber); + } + return 0; +} diff --git a/Task/HTTP/GML/http-1.gml b/Task/HTTP/GML/http-1.gml new file mode 100644 index 0000000000..e6223488d7 --- /dev/null +++ b/Task/HTTP/GML/http-1.gml @@ -0,0 +1,2 @@ +var get; +get = http_get("http://www.rosettacode.org/"); diff --git a/Task/HTTP/GML/http-2.gml b/Task/HTTP/GML/http-2.gml new file mode 100644 index 0000000000..e01bef654a --- /dev/null +++ b/Task/HTTP/GML/http-2.gml @@ -0,0 +1,4 @@ +if (ds_map_find_value(async_load,"id") == get) + { + show_message_async(ds_map_find_value(async_load,"result")); + } diff --git a/Task/HTTPS/Seed7/https.seed7 b/Task/HTTPS/Seed7/https.seed7 new file mode 100644 index 0000000000..4fe57262ff --- /dev/null +++ b/Task/HTTPS/Seed7/https.seed7 @@ -0,0 +1,8 @@ +$ include "seed7_05.s7i"; + include "gethttps.s7i"; + include "utf8.s7i"; + +const proc: main is func + begin + writeln(STD_UTF8_OUT, getHttps("sourceforge.net")); + end func; diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-1.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-1.basic new file mode 100644 index 0000000000..9ad6d5e7ad --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-1.basic @@ -0,0 +1,32 @@ +10 HOME + +100 N = 27 +110 GOSUB 400"HAILSTONE +120 DEF FN L(I) = E(I + 4 * (I < 0)) +130IFL=112AND(S(0)=27ANDS(1)=82ANDS(2)=41ANDS(3)=124)AND(FNL(M-3)=8ANDFNL(M-2)=4ANDFNL(M-1)=2ANDFNL(M)=1)THENPRINT"THE HAILSTONE SEQUENCE FOR THE NUMBER 27 HAS 112 ELEMENTS STARTING WITH 27, 82, 41, 124 AND ENDING WITH 8, 4, 2, 1" +140 PRINT +150 V = PEEK(37) + 1 + +200 N = 1 +210 GOSUB 400"HAILSTONE +220 MN = 1 +230 ML = L +240 FOR I = 2 TO 99999 +250 N = I +260 GOSUB 400"HAILSTONE +270 IFL>MLTHENMN=I:ML=L:VTABV:HTAB1:PRINT "THE NUMBER " MN " HAS A HAILSTONE SEQUENCE LENGTH OF "L" WHICH IS THE LONGEST HAILSTONE SEQUENCE OF NUMBERS LESS THAN ";:Y=PEEK(37)+1:X=PEEK(36)+1 +280 IF Y THEN VTAB Y : HTAB X : PRINTI+1; +290 NEXT I + +300 END + +400 M = 0 +410 FOR L = 1 TO 1E38 +420 IF L < 5 THEN S(L-1) = N +430 M = (M + 1) * (M < 3) +440 E(M) = N +450 IF N = 1 THEN RETURN +460 EVEN = INT(N/2)=N/2 +470 IF EVEN THEN N=N/2 +480 IF NOT EVEN THEN N = (3 * N) + 1 +490 NEXT L : STOP diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-2.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-2.basic new file mode 100644 index 0000000000..cb03395d1f --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-2.basic @@ -0,0 +1,23 @@ + seqlen% = FNhailstone(27, TRUE) + PRINT '"Sequence length = "; seqlen% + maxlen% = 0 + FOR number% = 2 TO 100000 + seqlen% = FNhailstone(number%, FALSE) + IF seqlen% > maxlen% THEN + maxlen% = seqlen% + maxnum% = number% + ENDIF + NEXT + PRINT "The number with the longest hailstone sequence is " ; maxnum% + PRINT "Its sequence length is " ; maxlen% + END + + DEF FNhailstone(N%, S%) + LOCAL L% + IF S% THEN PRINT N%; + WHILE N% <> 1 + IF N% AND 1 THEN N% = 3 * N% + 1 ELSE N% DIV= 2 + IF S% THEN PRINT N%; + L% += 1 + ENDWHILE + = L% + 1 diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic new file mode 100644 index 0000000000..8f487d6014 --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic @@ -0,0 +1,52 @@ +print "Part 1: Create a routine to generate the hailstone sequence for a number." +print "" +while hailstone < 1 or hailstone <> int(hailstone) + input "Please enter a positive integer: "; hailstone +wend +print "" +print "The following is the 'Hailstone Sequence' for your number..." +print "" +print hailstone +while hailstone <> 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + print hailstone +wend +print "" +input "Hit 'Enter' to continue to part 2...";dummy$ +cls +print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." +print "" +print "No. in Seq.","Hailstone Sequence Number for 27" +print "" +c = 1: hailstone = 27 +print c, hailstone +while hailstone <> 1 + c = c + 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + print c, hailstone +wend +print "" +input "Hit 'Enter' to continue to part 3...";dummy$ +cls +print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" +print "" +print "Calculating result... Please wait... This could take a little while..." +print "" +print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far" +print "" +for cc = 1 to 99999 + hailstone = cc: c = 1 + while hailstone <> 1 + c = c + 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + wend + if c > max then max = c: largesthailstone = cc + locate 1, 7 + print " " + locate 1, 7 + print using("###.###", cc / 99999 * 100);"%", cc, c, max + scan +next cc +print "" +print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"." +end diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic new file mode 100644 index 0000000000..d8536360e3 --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic @@ -0,0 +1,37 @@ +function Hailstone(sys *n) +'========================= +if n and 1 + n=n*3+1 +else + n=n>>1 +end if +end function + +function HailstoneSequence(sys n) as sys +'======================================= +count=1 +do + Hailstone n + Count++ + if n=1 then exit do +end do +return count +end function + +'MAIN +'==== + +maxc=0 +maxn=0 +e=100000 +for n=1 to e + c=HailstoneSequence n + if c>maxc + maxc=c + maxn=n + end if +next + +print e ", " maxn ", " maxc + +'result 100000, 77031, 351 diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic new file mode 100644 index 0000000000..76de11443f --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic @@ -0,0 +1,48 @@ +NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array + +Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list + Shared Hailstones() ; Get access to the Hailstones-List + ClearList(Hailstones()) ; Remove old data + Repeat + AddElement(Hailstones()) ; Add an element to the list + Hailstones()=n ; Fill current value in the new list element + If n=1 + ProcedureReturn ListSize(Hailstones()) + ElseIf n%2=0 + n/2 + Else + n=(3*n)+1 + EndIf + ForEver +EndProcedure + +If OpenConsole() + Define i, l, maxl, maxi + l=FillHailstones(27) + Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$) + ForEach Hailstones() + If i=6 + Print(#CRLF$) + i=0 + EndIf + i+1 + Print(RSet(Str(Hailstones()),5)) + If Hailstones()<>1 + Print(", ") + EndIf + Next + + i=1 + Repeat + l=FillHailstones(i) + If l>maxl + maxl=l + maxi=i + EndIf + i+1 + Until i>=100000 + Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.") + + Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() + CloseConsole() +EndIf diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic new file mode 100644 index 0000000000..84d246dfee --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic @@ -0,0 +1,40 @@ +print "Part 1: Create a routine to generate the hailstone sequence for a number." +print "" + +while hailstone < 1 or hailstone <> int(hailstone) + input "Please enter a positive integer: "; hailstone +wend +count = doHailstone(hailstone,"Y") + +print: print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." +count = doHailstone(27,"Y") + +print: print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" +print "Calculating result... Please wait... This could take a little while..." +print "Stone Percent Count" +for i = 1 to 99999 + count = doHailstone(i,"N") + if count > maxCount then + theBigStone = i + maxCount = count + print using("#####",i);" ";using("###.#", i / 99999 * 100);"% ";using("####",count) + end if +next i +end + +'--------------------------------------------- +' pass number and print (Y/N) +FUNCTION doHailstone(hailstone,prnt$) +if prnt$ = "Y" then + print + print "The following is the 'Hailstone Sequence' for number:";hailstone +end if +while hailstone <> 1 + if (hailstone and 1) then hailstone = (hailstone * 3) + 1 else hailstone = hailstone / 2 + doHailstone = doHailstone + 1 + if prnt$ = "Y" then + print hailstone;chr$(9); + if (doHailstone mod 10) = 0 then print + end if +wend +END FUNCTION diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic new file mode 100644 index 0000000000..3cbc39d283 --- /dev/null +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic @@ -0,0 +1,42 @@ +Module HailstoneSequence + Sub Main() + ' Checking sequence of 27. + + Dim l As List(Of Long) = HailstoneSequence(27) + Console.WriteLine("27 has {0} elements in sequence:", l.Count()) + + For i As Integer = 0 To 3 : Console.Write("{0}, ", l(i)) : Next + Console.Write("... ") + For i As Integer = l.Count - 4 To l.Count - 1 : Console.Write(", {0}", l(i)) : Next + + Console.WriteLine() + + ' Finding longest sequence for numbers below 100000. + + Dim max As Integer = 0 + Dim maxCount As Integer = 0 + + For i = 1 To 99999 + l = HailstoneSequence(i) + If l.Count > maxCount Then + max = i + maxCount = l.Count + End If + Next + Console.WriteLine("Max elements in sequence for number below 100k: {0} with {1} elements.", max, maxCount) + Console.ReadLine() + End Sub + + Private Function HailstoneSequence(ByVal n As Long) As List(Of Long) + Dim valList As New List(Of Long)() + valList.Add(n) + + Do Until n = 1 + n = IIf(n Mod 2 = 0, n / 2, (3 * n) + 1) + valList.Add(n) + Loop + + Return valList + End Function + +End Module diff --git a/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv b/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv index 53687d0f38..030827b6e3 100644 --- a/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv +++ b/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv @@ -1,4 +1,4 @@ -hailstone: +local hailstone: swap [ over ] while < 1 dup: if % over 2: @@ -10,25 +10,27 @@ hailstone: swap push-through rot dup drop -local :h27 hailstone 27 -. = 112 len h27 -. = 27 h27! 0 -. = 82 h27! 1 -. = 41 h27! 2 -. = 124 h27! 3 -. = 8 h27! 108 -. = 4 h27! 109 -. = 2 h27! 110 -. = 1 h27! 111 +if = (name) :(main): + local :h27 hailstone 27 + !. = 112 len h27 + !. = 27 h27! 0 + !. = 82 h27! 1 + !. = 41 h27! 2 + !. = 124 h27! 3 + !. = 8 h27! 108 + !. = 4 h27! 109 + !. = 2 h27! 110 + !. = 1 h27! 111 -local :max 0 -local :maxlen 0 -for i range 1 99999: - dup len hailstone i - if < maxlen: - set :maxlen - set :max i - else: - drop - -print( "number: " max ", length: " maxlen ) + local :max 0 + local :maxlen 0 + for i range 1 99999: + dup len hailstone i + if < maxlen: + set :maxlen + set :max i + else: + drop + !print( "number: " to-str max ", length: " to-str maxlen ) +else: + @hailstone diff --git a/Task/Hailstone-sequence/Go/hailstone-sequence-1.go b/Task/Hailstone-sequence/Go/hailstone-sequence-1.go index 93ea3a24b2..dcd1fa54e2 100644 --- a/Task/Hailstone-sequence/Go/hailstone-sequence-1.go +++ b/Task/Hailstone-sequence/Go/hailstone-sequence-1.go @@ -2,8 +2,10 @@ package main import "fmt" -func hs(n int, seq *[]int) { - s := append((*seq)[:0], n) +// 1st arg is the number to generate the sequence for. +// 2nd arg is a slice to recycle, to reduce garbage. +func hs(n int, recycle []int) []int { + s := append(recycle[:0], n) for n > 1 { if n&1 == 0 { n = n / 2 @@ -12,21 +14,18 @@ func hs(n int, seq *[]int) { } s = append(s, n) } - *seq = s + return s } func main() { - var seq []int - - hs(27, &seq) + seq := hs(27, nil) fmt.Printf("hs(27): %d elements: [%d %d %d %d ... %d %d %d %d]\n", len(seq), seq[0], seq[1], seq[2], seq[3], seq[len(seq)-4], seq[len(seq)-3], seq[len(seq)-2], seq[len(seq)-1]) var maxN, maxLen int for n := 1; n < 100000; n++ { - // reusing seq reduces garbage - hs(n, &seq) + seq = hs(n, seq) if len(seq) > maxLen { maxN = n maxLen = len(seq) diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence.julia index 4287ea841a..e3027b0d71 100644 --- a/Task/Hailstone-sequence/Julia/hailstone-sequence.julia +++ b/Task/Hailstone-sequence/Julia/hailstone-sequence.julia @@ -1,7 +1,7 @@ function hailstone(n) seq = [n] while n>1 - n = n % 2 == 0 ? n/2 : 3n + 1 + n = n % 2 == 0 ? n >> 1 : 3n + 1 push!(seq,n) end return seq diff --git a/Task/Hailstone-sequence/Limbo/hailstone-sequence.limbo b/Task/Hailstone-sequence/Limbo/hailstone-sequence.limbo new file mode 100644 index 0000000000..84b5122b01 --- /dev/null +++ b/Task/Hailstone-sequence/Limbo/hailstone-sequence.limbo @@ -0,0 +1,52 @@ +implement Hailstone; + +include "sys.m"; sys: Sys; +include "draw.m"; + +Hailstone: module { + init: fn(ctxt: ref Draw->Context, args: list of string); +}; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + + seq := hailstone(big 27); + l := len seq; + + sys->print("hailstone(27): "); + for(i := 0; i < 4; i++) { + sys->print("%bd, ", hd seq); + seq = tl seq; + } + sys->print("⋯"); + + while(len seq > 4) + seq = tl seq; + + while(seq != nil) { + sys->print(", %bd", hd seq); + seq = tl seq; + } + sys->print(" (length %d)\n", l); + + max := 1; + maxn := big 1; + for(n := big 2; n < big 100000; n++) { + cur := len hailstone(n); + if(cur > max) { + max = cur; + maxn = n; + } + } + sys->print("hailstone(%bd) has length %d\n", maxn, max); +} + +hailstone(i: big): list of big +{ + if(i == big 1) + return big 1 :: nil; + if(i % big 2 == big 0) + return i :: hailstone(i / big 2); + return i :: hailstone((big 3 * i) + big 1); +} diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx index c5089aa462..1c821a28e6 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx @@ -26,6 +26,5 @@ hailstone: procedure expose @.; parse arg n 1 s 1 o /*N,S,O = 1st arg.*/ else n=n%2 /* " " " even, perform fast ÷ */ s=s n /*build a sequence list (append).*/ end /*forever*/ -@.o=s /*memoization for this hailstone.*/ -@.o=subword(s,2) +@.o=subword(s,2) /*memoization for this hailstone.*/ return s diff --git a/Task/Hamming-numbers/Clojure/hamming-numbers.clj b/Task/Hamming-numbers/Clojure/hamming-numbers.clj index ef1c4b259c..fad60b0c5d 100644 --- a/Task/Hamming-numbers/Clojure/hamming-numbers.clj +++ b/Task/Hamming-numbers/Clojure/hamming-numbers.clj @@ -12,7 +12,7 @@ (defn smerge3 [xs ys zs] (smerge xs (smerge ys zs))) -(defn map*n [n ks] (map #(* n %) ks)) +(defn map*n [n ks] (map #(*' n %) ks)) (def hamming (lazy-seq diff --git a/Task/Hamming-numbers/PL-I/hamming-numbers.pli b/Task/Hamming-numbers/PL-I/hamming-numbers.pli new file mode 100644 index 0000000000..663ad0ad9e --- /dev/null +++ b/Task/Hamming-numbers/PL-I/hamming-numbers.pli @@ -0,0 +1,31 @@ +(subscriptrange): +Hamming: procedure options (main); /* 14 November 2013 */ + declare (H(3000), t) fixed (15); + declare (i, j, k, m, n) fixed binary; + declare swaps bit (1); + + on underflow ; + + m = 0; n = 12; + do k = 0 to n; + do j = 0 to n; + do i = 0 to n; + m = m + 1; + H(m) = 2**i * 3**j * 5**k; + end; + end; + end; + /* sort */ + swaps = '1'b; + do while (swaps); /* Cocktail-shaker sort is adequate, because values are largely sorted */ + swaps = '0'b; + do i = 1 to m-1, i-1 to 1 by -1; + if H(i) > H(i+1) then /* swap */ + do; t = H(i); H(i) = H(i+1); H(i+1) = t; swaps = '1'b; end; + end; + end; + do i = 1 to m; + put skip data (H(i)); + end; + put skip data (H(1653)); +end Hamming; diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx index 49c07af3e1..3fb25475c1 100644 --- a/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx +++ b/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx @@ -2,8 +2,7 @@ numeric digits 100 /*ensure we have enough precision*/ call hamming 1, 20 /*show the first ──► twentieth #s*/ call hamming 1691 /*show the 1,691st Hamming number*/ -call hamming 1000000 /*show the one millionth number*/ -call hamming 10000000 /*show the 10th millionth number*/ +call hamming 1000000 /*show the one millionth number.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────HAMMING subroutine──────────────────*/ hamming: procedure; parse arg x,y; if y=='' then y=x; w=length(y) diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx index 0b9506a7ce..1063d2da23 100644 --- a/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx +++ b/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx @@ -2,7 +2,7 @@ numeric digits 100 /*ensure we have enough precision*/ call hamming 1, 20 /*show the first ──► twentieth #s*/ call hamming 1691 /*show the 1,691st Hamming number*/ -call hamming 1000000 /*show the one millionth number*/ +call hamming 1000000 /*show the one millionth number.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────HAMMING subroutine──────────────────*/ hamming: procedure; parse arg x,y; if y=='' then y=x; w=length(y) @@ -16,9 +16,9 @@ hamming: procedure; parse arg x,y; if y=='' then y=x; w=length(y) if _3 < m then m =_3 /*is this less than the minimum? */ if _5 < m then m =_5 /* " " " " " " */ @.n = m /*now, assign the next Hamming #.*/ - if _2 == m then #2 =#2 + 1 /*# already defined? Use next #.*/ - if _3 == m then #3 =#3 + 1 /*" " " " " " */ - if _5 == m then #5 =#5 + 1 /*" " " " " " */ + if _2 == m then #2 = #2 + 1 /*# already defined? Use next #.*/ + if _3 == m then #3 = #3 + 1 /*" " " " " " */ + if _5 == m then #5 = #5 + 1 /*" " " " " " */ end /*n*/ do j=x to y /*W is used to align the index. */ say 'Hamming('right(j,w)") =" @.j /*list 'em, Dano.*/ diff --git a/Task/Handle-a-signal/Go/handle-a-signal.go b/Task/Handle-a-signal/Go/handle-a-signal.go index fb594faa70..d92e2b6bf3 100644 --- a/Task/Handle-a-signal/Go/handle-a-signal.go +++ b/Task/Handle-a-signal/Go/handle-a-signal.go @@ -9,14 +9,14 @@ import ( func main() { start := time.Now() - k := time.NewTicker(time.Second / 2) + k := time.Tick(time.Second / 2) sc := make(chan os.Signal, 1) signal.Notify(sc, os.Interrupt) for n := 1; ; { // not busy waiting, this blocks until one of the two // channel operations is possible select { - case <-k.C: + case <-k: fmt.Println(n) n++ case <-sc: diff --git a/Task/Handle-a-signal/HicEst/handle-a-signal.hicest b/Task/Handle-a-signal/HicEst/handle-a-signal-1.hicest similarity index 100% rename from Task/Handle-a-signal/HicEst/handle-a-signal.hicest rename to Task/Handle-a-signal/HicEst/handle-a-signal-1.hicest diff --git a/Task/Handle-a-signal/HicEst/handle-a-signal-2.hicest b/Task/Handle-a-signal/HicEst/handle-a-signal-2.hicest new file mode 100644 index 0000000000..4901dcfcfb --- /dev/null +++ b/Task/Handle-a-signal/HicEst/handle-a-signal-2.hicest @@ -0,0 +1,11 @@ +global startTime + +procedure main() + startTime := &now + trap("SIGINT", handler) + every write(seq()) do delay(500) +end + +procedure handler(s) + stop("\n",&now-startTime," seconds") +end diff --git a/Task/Handle-a-signal/TXR/handle-a-signal.txr b/Task/Handle-a-signal/TXR/handle-a-signal.txr new file mode 100644 index 0000000000..040c2d4284 --- /dev/null +++ b/Task/Handle-a-signal/TXR/handle-a-signal.txr @@ -0,0 +1,13 @@ +@(do + (set-sig-handler sig-int + (lambda (signum async-p) + (throwf 'error "caught signal ~s" signum))) + + (let ((start-time (time))) + (catch (each ((num (range 1))) + (format t "~s\n" num) + (usleep 500000)) + (error (msg) + (let ((end-time (time))) + (format t "\n\n~a after ~s seconds of execution\n" + msg (- end-time start-time))))))) diff --git a/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-3.sh b/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-3.sh index 8aaebe2e8c..383bab04ba 100644 --- a/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-3.sh +++ b/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-3.sh @@ -1,2 +1,19 @@ -TRAPINT(){ print $n; exit } -for (( n = 0; ; n++)) sleep 1 +#!/bin/bash +trap 'echo "Run for $((s/2)) seconds"; exit' 2 +s=1 + +half_sec_sleep() +{ + local save_tty=$(stty -g) + stty -icanon time 5 min 0 + read + stty $save_tty +} + + +while true +do + echo $s + half_sec_sleep + let s++ +done diff --git a/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-4.sh b/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-4.sh new file mode 100644 index 0000000000..8aaebe2e8c --- /dev/null +++ b/Task/Handle-a-signal/UNIX-Shell/handle-a-signal-4.sh @@ -0,0 +1,2 @@ +TRAPINT(){ print $n; exit } +for (( n = 0; ; n++)) sleep 1 diff --git a/Task/Happy-numbers/Deja-Vu/happy-numbers.djv b/Task/Happy-numbers/Deja-Vu/happy-numbers.djv new file mode 100644 index 0000000000..02009497b7 --- /dev/null +++ b/Task/Happy-numbers/Deja-Vu/happy-numbers.djv @@ -0,0 +1,37 @@ +next-num: + 0 + while over: + over + * dup % swap 10 + + + swap floor / swap 10 swap + drop swap + +is-happy happies n: + if has happies n: + return happies! n + local :seq set{ n } + n + while /= 1 dup: + next-num + if has seq dup: + drop + set-to happies n false + return false + if has happies dup: + set-to happies n dup happies! + return + set-to seq over true + drop + set-to happies n true + true + +local :h {} +1 0 +while > 8 over: + if is-happy h dup: + !print( "A happy number: " over ) + swap ++ swap + ++ +drop +drop diff --git a/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia b/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia index ac376fd175..a05cdd0b41 100644 --- a/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia +++ b/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia @@ -1,6 +1,6 @@ isharshad(x) = x % sum(digits(x)) == 0 function harshads(n) - h = ref(Int) + h = Int[] i = 1 while length(h) < n isharshad(i) && push!(h,i) diff --git a/Task/Harshad-or-Niven-series/Prolog/harshad-or-niven-series.pro b/Task/Harshad-or-Niven-series/Prolog/harshad-or-niven-series.pro new file mode 100644 index 0000000000..8d8a89e4ca --- /dev/null +++ b/Task/Harshad-or-Niven-series/Prolog/harshad-or-niven-series.pro @@ -0,0 +1,41 @@ +:- use_module(library(lambda)). + +niven :- + nb_setval(go, 1), + + L = [1 | _], + print_niven(L, 1), + gen_niven(1, L). + + +print_niven([X|T], N) :- + when(ground(X), + ( ( nb_getval(go, 1) + -> ( N < 20 + -> writeln(X), + N1 is N+1, + print_niven(T, N1) + ; ( X > 1000 + -> writeln(X), + nb_setval(go, 0) + ; N1 is N+1, + print_niven(T, N1))) + ; true))). + + + +gen_niven(X, [N | T]) :- + ( nb_getval(go, 1) + -> X1 is X+1, + sum_of_digit(X, S), + ( X mod S =:= 0 + -> N = X, + gen_niven(X1, T) + ; gen_niven(X1, [N | T])) + ; true). + + +sum_of_digit(N, S) :- + number_chars(N, LC), + maplist(\X^Y^number_chars(Y, [X]), LC, LN), + sum_list(LN, S). diff --git a/Task/Hash-from-two-arrays/Deja-Vu/hash-from-two-arrays.djv b/Task/Hash-from-two-arrays/Deja-Vu/hash-from-two-arrays.djv new file mode 100644 index 0000000000..b8157b8303 --- /dev/null +++ b/Task/Hash-from-two-arrays/Deja-Vu/hash-from-two-arrays.djv @@ -0,0 +1,5 @@ +local :h_keys [ :one :two :three ] +local :h_values [ 1 2 3 ] +local :h {} +for item in h_keys: + set-to h item pop-from h_values diff --git a/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-1.groovy b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-1.groovy new file mode 100644 index 0000000000..6381e91ad6 --- /dev/null +++ b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-1.groovy @@ -0,0 +1,6 @@ +def keys = ['a','b','c'] +def vals = ['aaa', 'bbb', 'ccc'] +def hash = [:] +keys.eachWithIndex { key, i -> + hash[key] = vals[i] +} diff --git a/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-2.groovy b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-2.groovy new file mode 100644 index 0000000000..843f86643f --- /dev/null +++ b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-2.groovy @@ -0,0 +1 @@ +List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } } diff --git a/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-3.groovy b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-3.groovy new file mode 100644 index 0000000000..2cc6668760 --- /dev/null +++ b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays-3.groovy @@ -0,0 +1 @@ +assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc'] diff --git a/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays.groovy b/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays.groovy deleted file mode 100644 index 953dd5688e..0000000000 --- a/Task/Hash-from-two-arrays/Groovy/hash-from-two-arrays.groovy +++ /dev/null @@ -1,6 +0,0 @@ -keys = ['a','b','c'] -vals = ['aaa', 'bbb', 'ccc'] -hash = [:] -keys.eachWithIndex { key, i -> - hash[key] = vals[i] -} diff --git a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia new file mode 100644 index 0000000000..733230ee9b --- /dev/null +++ b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia @@ -0,0 +1,4 @@ +julia> K = ["a", "b", "c"] +julia> V = [1, 2, 3] +julia> H = [key => value for (key, value) in zip(K,V)] +{"b"=>2,"c"=>3,"a"=>1} diff --git a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia new file mode 100644 index 0000000000..44dac07a46 --- /dev/null +++ b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia @@ -0,0 +1,2 @@ +julia> H = (String=>Int)[key => value for (key, value) in zip(K,V)] +["b"=>2,"c"=>3,"a"=>1] diff --git a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia new file mode 100644 index 0000000000..a9e3040ab4 --- /dev/null +++ b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia @@ -0,0 +1,2 @@ +julia> H = Dict(K, V) +["b"=>2,"c"=>3,"a"=>1] diff --git a/Task/Haversine-formula/PL-I/haversine-formula.pli b/Task/Haversine-formula/PL-I/haversine-formula.pli new file mode 100644 index 0000000000..93dfd579e5 --- /dev/null +++ b/Task/Haversine-formula/PL-I/haversine-formula.pli @@ -0,0 +1,29 @@ +test: procedure options (main); /* 12 January 2014. Derived from Fortran version */ + declare d float; + + d = haversine(36.12, -86.67, 33.94, -118.40); /* BNA to LAX */ + put edit ( 'distance: ', d, ' km') (A, F(10,3)); /* distance: 2887.2600 km */ + + +degrees_to_radians: procedure (degree) returns (float); + declare degree float nonassignable; + declare pi float (15) initial ( (4*atan(1.0d0)) ); + + return ( degree*pi/180 ); +end degrees_to_radians; + +haversine: procedure (deglat1, deglon1, deglat2, deglon2) returns (float); + declare (deglat1, deglon1, deglat2, deglon2) float nonassignable; + declare (a, c, dlat, dlon, lat1, lat2) float; + declare radius float value (6372.8); + + dlat = degrees_to_radians(deglat2-deglat1); + dlon = degrees_to_radians(deglon2-deglon1); + lat1 = degrees_to_radians(deglat1); + lat2 = degrees_to_radians(deglat2); + a = (sin(dlat/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon/2))**2; + c = 2*atan(sqrt(a),sqrt(1-a)); + return ( radius*c ); +end haversine; + +end test; diff --git a/Task/Haversine-formula/Run-BASIC/haversine-formula.run b/Task/Haversine-formula/Run-BASIC/haversine-formula.run index 85e3f4bf56..8d85db7700 100644 --- a/Task/Haversine-formula/Run-BASIC/haversine-formula.run +++ b/Task/Haversine-formula/Run-BASIC/haversine-formula.run @@ -1,18 +1,19 @@ -Lt1=36.12: Lg1=-86.67: Lt2=33.94: Lg2=-118.4 -D2R = acs(-1)/180 + D2R = atn(1)/45 diam = 2 * 6372.8 - ph1 = (Lg1 - Lg2) * D2R - th1 = Lt1 * D2R ' degrees to rad - th2 = Lt2 * D2R - dz = sin(th1) - sin(th2) - dx = cos(ph1) * cos(th1) - cos( th2) - dy = sin(ph1) * cos(th1) +Lg1m2 = ((-86.67)-(-118.4)) * D2R +Lt1 = 36.12 * D2R ' degrees to rad +Lt2 = 33.94 * D2R + dz = sin(Lt1) - sin(Lt2) + dx = cos(Lg1m2) * cos(Lt1) - cos(Lt2) + dy = sin(Lg1m2) * cos(Lt1) hDist = asn((dx^2 + dy^2 + dz^2)^0.5 /2) * diam -print "Haversine distance: ";using("####.###########",hDist);" km" +print "Haversine distance: ";using("####.#############",hDist);" km." 'Tips: ( 36 deg 7 min 12 sec ) = print 36+(7/60)+(12/3600). Produces: 36.12 deg ' ' Put "36.12,-86.67" into http://maps.google.com (no quotes). Click map, ' satellite, center the pin "A", zoom in, and see airport. Extra: in "Get ' Directions" enter 36.12,-86.66999 and see pin "B" about one meter away. - ' (This formula says: .00089846878 km., (or 35.37 in.)) + ' (.00089846878 km., or 35.37 in.) + ' + ' This code also works in Liberty BASIC. diff --git a/Task/Hello-world-Graphical/AutoHotkey/hello-world-graphical-3.ahk b/Task/Hello-world-Graphical/AutoHotkey/hello-world-graphical-3.ahk index abe5734342..5b027e7966 100644 --- a/Task/Hello-world-Graphical/AutoHotkey/hello-world-graphical-3.ahk +++ b/Task/Hello-world-Graphical/AutoHotkey/hello-world-graphical-3.ahk @@ -1,5 +1,5 @@ Gui, Add, Text, x4 y4, To be announced: Gui, Add, Edit, xp+90 yp-3, Goodbye, World! Gui, Add, Button, xp+98 yp-1, OK -Gui, Show, w226 h22 , Rosetta Code +Gui, Show, w226 h22 , Rosetta Code Return diff --git a/Task/Hello-world-Graphical/Batch-File/hello-world-graphical.bat b/Task/Hello-world-Graphical/Batch-File/hello-world-graphical.bat new file mode 100644 index 0000000000..dd9ef8db70 --- /dev/null +++ b/Task/Hello-world-Graphical/Batch-File/hello-world-graphical.bat @@ -0,0 +1,13 @@ +@echo off + +::Output to console +echo Goodbye, World! + +::Output to message box +msg * "Goodbye, World!" + +::Output to file and open it +echo Goodbye, World!>temp.txt +start temp.txt + +pause>nul diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol index 2f46c51e30..32f523ea75 100644 --- a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol @@ -1,19 +1,19 @@ - program-id. ghello. - data division. - working-storage section. - 01 var pic x(1). - 01 lynz pic 9(3). - 01 colz pic 9(3). - 01 msg pic x(15) value "Goodbye, world!". - procedure division. - accept lynz from lines end-accept - divide lynz by 2 giving lynz. - accept colz from columns end-accept - divide colz by 2 giving colz. - subtract 7 from colz giving colz. - display msg - at line number lynz - column number colz - end-display - accept var end-accept - stop run. + program-id. ghello. + data division. + working-storage section. + 01 var pic x(1). + 01 lynz pic 9(3). + 01 colz pic 9(3). + 01 msg pic x(15) value "Goodbye, world!". + procedure division. + accept lynz from lines end-accept + divide lynz by 2 giving lynz. + accept colz from columns end-accept + divide colz by 2 giving colz. + subtract 7 from colz giving colz. + display msg + at line number lynz + column number colz + end-display + accept var end-accept + stop run. diff --git a/Task/Hello-world-Graphical/Clojure/hello-world-graphical.clj b/Task/Hello-world-Graphical/Clojure/hello-world-graphical.clj index 5d92975f65..9532fa704b 100644 --- a/Task/Hello-world-Graphical/Clojure/hello-world-graphical.clj +++ b/Task/Hello-world-Graphical/Clojure/hello-world-graphical.clj @@ -1,6 +1,6 @@ (ns experimentation.core (:import (javax.swing JOptionPane JFrame JTextArea JButton) - (java.awt FlowLayout))) + (java.awt FlowLayout))) (JOptionPane/showMessageDialog nil "Goodbye, World!") (let [button (JButton. "Goodbye, World!") diff --git a/Task/Hello-world-Graphical/Cobra/hello-world-graphical.cobra b/Task/Hello-world-Graphical/Cobra/hello-world-graphical.cobra index 910dbd29e4..e6790fc283 100644 --- a/Task/Hello-world-Graphical/Cobra/hello-world-graphical.cobra +++ b/Task/Hello-world-Graphical/Cobra/hello-world-graphical.cobra @@ -3,12 +3,12 @@ use Gtk class MainProgram - def main - Application.init - dialog = MessageDialog(nil, - DialogFlags.DestroyWithParent, - MessageType.Info, - ButtonsType.Ok, - "Goodbye, World!") - dialog.run - dialog.destroy + def main + Application.init + dialog = MessageDialog(nil, + DialogFlags.DestroyWithParent, + MessageType.Info, + ButtonsType.Ok, + "Goodbye, World!") + dialog.run + dialog.destroy diff --git a/Task/Hello-world-Graphical/EGL/hello-world-graphical.egl b/Task/Hello-world-Graphical/EGL/hello-world-graphical.egl index dff2d4398a..8a48d3002f 100644 --- a/Task/Hello-world-Graphical/EGL/hello-world-graphical.egl +++ b/Task/Hello-world-Graphical/EGL/hello-world-graphical.egl @@ -4,11 +4,11 @@ import dojo.widgets.*; handler HelloWorld type RUIhandler{initialUI =[ui]} ui Box {columns=1, children=[nameField, helloLabel, goButton]}; - + nameField DojoTextField {placeHolder = "What's your name?", text = "World"}; helloLabel TextLabel {}; goButton DojoButton {text = "Say Goodbye", onClick ::= onClick_goButton}; - + function onClick_goButton(e Event in) helloLabel.text = "Goodbye, " + nameField.text + "!"; end diff --git a/Task/Hello-world-Graphical/GML/hello-world-graphical.gml b/Task/Hello-world-Graphical/GML/hello-world-graphical.gml new file mode 100644 index 0000000000..2f7cb85074 --- /dev/null +++ b/Task/Hello-world-Graphical/GML/hello-world-graphical.gml @@ -0,0 +1 @@ +draw_text(0,0,"Goodbye World!"); diff --git a/Task/Hello-world-Graphical/Pascal/hello-world-graphical.pascal b/Task/Hello-world-Graphical/Pascal/hello-world-graphical.pascal index 52bb1def27..725ce25d3b 100644 --- a/Task/Hello-world-Graphical/Pascal/hello-world-graphical.pascal +++ b/Task/Hello-world-Graphical/Pascal/hello-world-graphical.pascal @@ -14,8 +14,8 @@ begin gtk_window_set_title (GTK_WINDOW (window), 'Goodbye, World'); g_signal_connect (G_OBJECT (window), 'delete-event', - G_CALLBACK (@gtk_main_quit), - NULL); + G_CALLBACK (@gtk_main_quit), + NULL); gtk_widget_show_all (window); gtk_main(); diff --git a/Task/Hello-world-Graphical/Processing/hello-world-graphical b/Task/Hello-world-Graphical/Processing/hello-world-graphical new file mode 100644 index 0000000000..b748402463 --- /dev/null +++ b/Task/Hello-world-Graphical/Processing/hello-world-graphical @@ -0,0 +1 @@ + text("Goodbye, World!",0,height/2); diff --git a/Task/Hello-world-Graphical/Rascal/hello-world-graphical.rascal b/Task/Hello-world-Graphical/Rascal/hello-world-graphical.rascal index 27bfa1ccb4..69061fe3bf 100644 --- a/Task/Hello-world-Graphical/Rascal/hello-world-graphical.rascal +++ b/Task/Hello-world-Graphical/Rascal/hello-world-graphical.rascal @@ -2,4 +2,4 @@ import vis::Figure; import vis::Render; public void GoodbyeWorld() = - render(box(text("Goodbye World"))); + render(box(text("Goodbye World"))); diff --git a/Task/Hello-world-Graphical/Ruby/hello-world-graphical-3.rb b/Task/Hello-world-Graphical/Ruby/hello-world-graphical-3.rb index 06e596f871..4615cbf01b 100644 --- a/Task/Hello-world-Graphical/Ruby/hello-world-graphical-3.rb +++ b/Task/Hello-world-Graphical/Ruby/hello-world-graphical-3.rb @@ -1,5 +1,5 @@ #_Note: this code MUST be executed through the Shoes GUI!! Shoes.app do - para "CHUNKY BACON!", :size => 72 + para "CHUNKY BACON!", :size => 72 end diff --git a/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission.basic b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-1.basic similarity index 100% rename from Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission.basic rename to Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-1.basic diff --git a/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic new file mode 100644 index 0000000000..6f3e0b2530 --- /dev/null +++ b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic @@ -0,0 +1 @@ +PRINT "GOODBYE, WORLD!"; diff --git a/Task/Hello-world-Newline-omission/COBOL/hello-world-newline-omission.cobol b/Task/Hello-world-Newline-omission/COBOL/hello-world-newline-omission.cobol index bdd232ef8e..65e8787697 100644 --- a/Task/Hello-world-Newline-omission/COBOL/hello-world-newline-omission.cobol +++ b/Task/Hello-world-Newline-omission/COBOL/hello-world-newline-omission.cobol @@ -3,7 +3,7 @@ PROGRAM-ID. GOODBYE-WORLD. PROCEDURE DIVISION. DISPLAY 'Goodbye, World!' - WITH NO ADVANCING + WITH NO ADVANCING END-DISPLAY . STOP RUN. diff --git a/Task/Hello-world-Newline-omission/Deja-Vu/hello-world-newline-omission.djv b/Task/Hello-world-Newline-omission/Deja-Vu/hello-world-newline-omission.djv index 886afd8d92..379523d845 100644 --- a/Task/Hello-world-Newline-omission/Deja-Vu/hello-world-newline-omission.djv +++ b/Task/Hello-world-Newline-omission/Deja-Vu/hello-world-newline-omission.djv @@ -1 +1 @@ -print\ "Goodbye, World!" +!print\ "Goodbye, World!" diff --git a/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom b/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom index f3e5dcfe41..ef17c4b16a 100644 --- a/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom +++ b/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom @@ -1,7 +1,5 @@ -class Main -{ - Void main () - { - Env.cur.out.writeChars ("Hello world") +class Main { + Void main() { + echo("Goodbye, World!") } } diff --git a/Task/Hello-world-Newline-omission/Julia/hello-world-newline-omission.julia b/Task/Hello-world-Newline-omission/Julia/hello-world-newline-omission.julia new file mode 100644 index 0000000000..b4f3181031 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Julia/hello-world-newline-omission.julia @@ -0,0 +1 @@ +print("Goodbye, World!") diff --git a/Task/Hello-world-Newline-omission/Limbo/hello-world-newline-omission.limbo b/Task/Hello-world-Newline-omission/Limbo/hello-world-newline-omission.limbo new file mode 100644 index 0000000000..c00340f58b --- /dev/null +++ b/Task/Hello-world-Newline-omission/Limbo/hello-world-newline-omission.limbo @@ -0,0 +1,14 @@ +implement HelloWorld; + +include "sys.m"; sys: Sys; +include "draw.m"; + +HelloWorld: 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; + sys->print("Goodbye, World!"); # No automatic newline. +} diff --git a/Task/Hello-world-Newline-omission/TXR/hello-world-newline-omission.txr b/Task/Hello-world-Newline-omission/TXR/hello-world-newline-omission.txr index d4a82c12a0..25ea3674e7 100644 --- a/Task/Hello-world-Newline-omission/TXR/hello-world-newline-omission.txr +++ b/Task/Hello-world-Newline-omission/TXR/hello-world-newline-omission.txr @@ -1,2 +1,2 @@ -$txr -c '@(do (format t "Hello, world!"))' -Hello, world!$ +$txr -c '@(do (format t "Goodbye, world!"))' +Goodbye, world!$ diff --git a/Task/Hello-world-Standard-error/Deja-Vu/hello-world-standard-error.djv b/Task/Hello-world-Standard-error/Deja-Vu/hello-world-standard-error.djv new file mode 100644 index 0000000000..e640ec3838 --- /dev/null +++ b/Task/Hello-world-Standard-error/Deja-Vu/hello-world-standard-error.djv @@ -0,0 +1 @@ +!write-fragment!stderr !encode!utf-8 "Goodbye, World!\n" diff --git a/Task/Hello-world-Standard-error/Julia/hello-world-standard-error.julia b/Task/Hello-world-Standard-error/Julia/hello-world-standard-error.julia new file mode 100644 index 0000000000..297cbabdab --- /dev/null +++ b/Task/Hello-world-Standard-error/Julia/hello-world-standard-error.julia @@ -0,0 +1 @@ +println(STDERR, "Goodbye, World!") diff --git a/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv b/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv index a9f594ad30..a2009a57ae 100644 --- a/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv +++ b/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv @@ -1 +1 @@ -print "Goodbye, World!" +!print "Goodbye, World!" diff --git a/Task/Hello-world-Text/Elena/hello-world-text-2.elena b/Task/Hello-world-Text/Elena/hello-world-text-2.elena index e687500bb8..491fb4dca1 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text-2.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text-2.elena @@ -1,5 +1,6 @@ -sys'vm'routines'dummy "Goodbye, World!" %write &nil 'program'output &wrapbatch[4] -%get &nil 'program'input &wrapbatch[2] -&cast[2] -&nil -^eval +[[ + #config vm_console #start; + #define start ::= "?" system'console .eval&writeLine($literal); +]] + +? "Hello World" diff --git a/Task/Hello-world-Text/Julia/hello-world-text.julia b/Task/Hello-world-Text/Julia/hello-world-text.julia index b4f3181031..d0337b0351 100644 --- a/Task/Hello-world-Text/Julia/hello-world-text.julia +++ b/Task/Hello-world-Text/Julia/hello-world-text.julia @@ -1 +1 @@ -print("Goodbye, World!") +println("Goodbye, World!") diff --git a/Task/Hello-world-Text/LLVM/hello-world-text.llvm b/Task/Hello-world-Text/LLVM/hello-world-text.llvm new file mode 100644 index 0000000000..d5b70574d8 --- /dev/null +++ b/Task/Hello-world-Text/LLVM/hello-world-text.llvm @@ -0,0 +1,7 @@ +@str = internal constant [14 x i8] c"Hello, world!\00" +declare i32 @puts(i8*) +define i32 @main() +{ + call i32 @puts( i8* getelementptr ([14 x i8]* @str, i32 0,i32 0)) + ret i32 0 +} diff --git a/Task/Hello-world-Text/Neko/hello-world-text.neko b/Task/Hello-world-Text/Neko/hello-world-text.neko new file mode 100644 index 0000000000..8ed64406d4 --- /dev/null +++ b/Task/Hello-world-Text/Neko/hello-world-text.neko @@ -0,0 +1 @@ +$print("Hello, World!"); diff --git a/Task/Hello-world-Text/Scilab/hello-world-text.scilab b/Task/Hello-world-Text/Scilab/hello-world-text.scilab new file mode 100644 index 0000000000..2a78fe60de --- /dev/null +++ b/Task/Hello-world-Text/Scilab/hello-world-text.scilab @@ -0,0 +1 @@ +disp("Goodbye, World!"); diff --git a/Task/Hello-world-Web-server/C/hello-world-web-server.c b/Task/Hello-world-Web-server/C/hello-world-web-server.c index 124a86c512..d6201c0ece 100644 --- a/Task/Hello-world-Web-server/C/hello-world-web-server.c +++ b/Task/Hello-world-Web-server/C/hello-world-web-server.c @@ -18,37 +18,37 @@ char response[] = "HTTP/1.1 200 OK\r\n" int main() { - int one = 1, client_fd; - struct sockaddr_in svr_addr, cli_addr; - socklen_t sin_len = sizeof(cli_addr); + int one = 1, client_fd; + struct sockaddr_in svr_addr, cli_addr; + socklen_t sin_len = sizeof(cli_addr); - int sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) - err(1, "can't open socket"); + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0) + err(1, "can't open socket"); - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); - int port = 8080; - svr_addr.sin_family = AF_INET; - svr_addr.sin_addr.s_addr = INADDR_ANY; - svr_addr.sin_port = htons(port); + int port = 8080; + svr_addr.sin_family = AF_INET; + svr_addr.sin_addr.s_addr = INADDR_ANY; + svr_addr.sin_port = htons(port); - if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { - close(sock); - err(1, "Can't bind"); - } + if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { + close(sock); + err(1, "Can't bind"); + } - listen(sock, 5); - while (1) { - client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); - printf("got connection\n"); + listen(sock, 5); + while (1) { + client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); + printf("got connection\n"); - if (client_fd == -1) { - perror("Can't accept"); - continue; - } + if (client_fd == -1) { + perror("Can't accept"); + continue; + } - write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/ - close(client_fd); - } + write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/ + close(client_fd); + } } diff --git a/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp b/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp index a8ab7fd8c3..35a9c51fce 100644 --- a/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp +++ b/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp @@ -19,19 +19,19 @@ (defun serve (port &optional (log-stream *standard-output*)) (let ((connections (list (socket-listen "127.0.0.1" port :reuse-address t)))) (unwind-protect - (loop (loop for ready in (wait-for-input connections :ready-only t) - do (if (typep ready 'stream-server-usocket) - (push (socket-accept ready) connections) - (let* ((stream (socket-stream ready))) - (read-all stream) - (format log-stream "Got message...~%") - (mapc (lambda (line) (ln line stream)) - (list "HTTP/1.1 200 OK" - "Content-Type: text/plain; charset=UTF-8" - "" - "Hello world!")) - (socket-close ready) - (setf connections (remove ready connections)))))) + (loop (loop for ready in (wait-for-input connections :ready-only t) + do (if (typep ready 'stream-server-usocket) + (push (socket-accept ready) connections) + (let* ((stream (socket-stream ready))) + (read-all stream) + (format log-stream "Got message...~%") + (mapc (lambda (line) (ln line stream)) + (list "HTTP/1.1 200 OK" + "Content-Type: text/plain; charset=UTF-8" + "" + "Hello world!")) + (socket-close ready) + (setf connections (remove ready connections)))))) (loop for c in connections do (loop while (socket-close c)))))) (serve 8080) diff --git a/Task/Hello-world-Web-server/D/hello-world-web-server.d b/Task/Hello-world-Web-server/D/hello-world-web-server.d index ae74051007..99590d0794 100644 --- a/Task/Hello-world-Web-server/D/hello-world-web-server.d +++ b/Task/Hello-world-Web-server/D/hello-world-web-server.d @@ -3,22 +3,22 @@ import std.socket, std.array; ushort port = 8080; void main() { - Socket listener = new TcpSocket; - listener.bind(new InternetAddress(port)); - listener.listen(10); + Socket listener = new TcpSocket; + listener.bind(new InternetAddress(port)); + listener.listen(10); - Socket currSock; + Socket currSock; - while(cast(bool)(currSock = listener.accept())) { - currSock.sendTo(replace(q"EOF + while(cast(bool)(currSock = listener.accept())) { + currSock.sendTo(replace(q"EOF HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 - Hello, world! - Hello, world! + Hello, world! + Hello, world! EOF", "\n", "\r\n")); - currSock.close(); - } + currSock.close(); + } } diff --git a/Task/Hello-world-Web-server/Erlang/hello-world-web-server.erl b/Task/Hello-world-Web-server/Erlang/hello-world-web-server.erl index cd225e6f54..a6b8772271 100644 --- a/Task/Hello-world-Web-server/Erlang/hello-world-web-server.erl +++ b/Task/Hello-world-Web-server/Erlang/hello-world-web-server.erl @@ -3,19 +3,19 @@ -export( [do/1, httpd_start/2, httpd_stop/1, task/0] ). do( _Data ) -> - {proceed, [{response,{200,"Goodbye, World!"}}]}. + {proceed, [{response,{200,"Goodbye, World!"}}]}. httpd_start( Port, Module ) -> - Arguments = [{bind_address, "localhost"}, {port, Port}, {ipfamily, inet}, - {modules, [Module]}, - {server_name,erlang:atom_to_list(Module)}, {server_root,"."}, {document_root,"."}], - {ok, Pid} = inets:start( httpd, Arguments, stand_alone ), - Pid. - + Arguments = [{bind_address, "localhost"}, {port, Port}, {ipfamily, inet}, + {modules, [Module]}, + {server_name,erlang:atom_to_list(Module)}, {server_root,"."}, {document_root,"."}], + {ok, Pid} = inets:start( httpd, Arguments, stand_alone ), + Pid. + httpd_stop( Pid ) -> - inets:stop( stand_alone, Pid ). + inets:stop( stand_alone, Pid ). task() -> - Pid = httpd_start( 8080, ?MODULE ), - timer:sleep( 30000 ), - httpd_stop( Pid ). + Pid = httpd_start( 8080, ?MODULE ), + timer:sleep( 30000 ), + httpd_stop( Pid ). diff --git a/Task/Hello-world-Web-server/Go/hello-world-web-server.go b/Task/Hello-world-Web-server/Go/hello-world-web-server.go index 60a4f40ed4..002578c77c 100644 --- a/Task/Hello-world-Web-server/Go/hello-world-web-server.go +++ b/Task/Hello-world-Web-server/Go/hello-world-web-server.go @@ -1,14 +1,14 @@ package main import ( - "fmt" - "log" - "net/http" + "fmt" + "log" + "net/http" ) func main() { - http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { - fmt.Fprintln(w, "Goodbye, World!") - }) - log.Fatal(http.ListenAndServe(":8080", nil)) + http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { + fmt.Fprintln(w, "Goodbye, World!") + }) + log.Fatal(http.ListenAndServe(":8080", nil)) } diff --git a/Task/Hello-world-Web-server/Java/hello-world-web-server.java b/Task/Hello-world-Web-server/Java/hello-world-web-server.java index f45b202e6d..aa315fc4ad 100644 --- a/Task/Hello-world-Web-server/Java/hello-world-web-server.java +++ b/Task/Hello-world-Web-server/Java/hello-world-web-server.java @@ -4,13 +4,13 @@ import java.net.ServerSocket; import java.net.Socket; public class HelloWorld{ - public static void main(String[] args) throws IOException{ - ServerSocket listener = new ServerSocket(8080); - while(true){ - Socket sock = listener.accept(); - new PrintWriter(sock.getOutputStream(), true). - println("Goodbye, World!"); - sock.close(); - } - } + public static void main(String[] args) throws IOException{ + ServerSocket listener = new ServerSocket(8080); + while(true){ + Socket sock = listener.accept(); + new PrintWriter(sock.getOutputStream(), true). + println("Goodbye, World!"); + sock.close(); + } + } } diff --git a/Task/Hello-world-Web-server/Perl/hello-world-web-server-3.pl b/Task/Hello-world-Web-server/Perl/hello-world-web-server-3.pl index 63b7847c3b..2add005951 100644 --- a/Task/Hello-world-Web-server/Perl/hello-world-web-server-3.pl +++ b/Task/Hello-world-Web-server/Perl/hello-world-web-server-3.pl @@ -1,6 +1,6 @@ while (++(our $vn)) { - open NC, "|-", qw(nc -l -p 8080 -q 1); - print NC "HTTP/1.0 200 OK\xd\xa", - "Content-type: text/plain; charset=utf-8\xd\xa\xd\xa", - "Goodbye, World! (hello, visitor No. $vn!)\xd\xa"; + open NC, "|-", qw(nc -l -p 8080 -q 1); + print NC "HTTP/1.0 200 OK\xd\xa", + "Content-type: text/plain; charset=utf-8\xd\xa\xd\xa", + "Goodbye, World! (hello, visitor No. $vn!)\xd\xa"; } diff --git a/Task/Hello-world-Web-server/Perl/hello-world-web-server-4.pl b/Task/Hello-world-Web-server/Perl/hello-world-web-server-4.pl index c29fe8fbdc..b5c53dd07d 100644 --- a/Task/Hello-world-Web-server/Perl/hello-world-web-server-4.pl +++ b/Task/Hello-world-Web-server/Perl/hello-world-web-server-4.pl @@ -1,9 +1,9 @@ use Plack::Runner; my $app = sub { return [ 200, - [ 'Content-Type' => 'text/html; charset=UTF-8' ], - [ 'Goodbye, world!Goodbye, world!' ] - ] + [ 'Content-Type' => 'text/html; charset=UTF-8' ], + [ 'Goodbye, world!Goodbye, world!' ] + ] }; my $runner = Plack::Runner->new; $runner->parse_options('--host' => 'localhost', '--port' => 8080); diff --git a/Task/Hello-world-Web-server/Prolog/hello-world-web-server.pro b/Task/Hello-world-Web-server/Prolog/hello-world-web-server.pro index a9274807fe..cb851a93ea 100644 --- a/Task/Hello-world-Web-server/Prolog/hello-world-web-server.pro +++ b/Task/Hello-world-Web-server/Prolog/hello-world-web-server.pro @@ -15,4 +15,4 @@ server :- http_server(http_dispatch, [port(8080)]). % In this case we're returning a page with the title "Howdy" and the content, % wrapped in

tags, "Goodbye, World!". say_goodbye(_Request) :- reply_html_page([title('Howdy')], - [h1('Goodbye, World!')]). + [h1('Goodbye, World!')]). diff --git a/Task/Hello-world-Web-server/PureBasic/hello-world-web-server.purebasic b/Task/Hello-world-Web-server/PureBasic/hello-world-web-server.purebasic index 21380cb76b..6d34ad0602 100644 --- a/Task/Hello-world-Web-server/PureBasic/hello-world-web-server.purebasic +++ b/Task/Hello-world-Web-server/PureBasic/hello-world-web-server.purebasic @@ -1,23 +1,23 @@ If InitNetwork() = 0 - MessageRequester("Error", "Can't initialize the network !") - End + MessageRequester("Error", "Can't initialize the network !") + End EndIf Port = 8080 If CreateNetworkServer(0, Port) - Repeat - Delay(1) - SEvent = NetworkServerEvent() - If SEvent - ClientID = EventClient() - Select SEvent - Case #PB_NetworkEvent_Data - SendNetworkData(ClientID,@"Goodbye, World!",Len("Goodbye, World!")) - CloseNetworkConnection(ClientID) - EndSelect - EndIf - ForEver + Repeat + Delay(1) + SEvent = NetworkServerEvent() + If SEvent + ClientID = EventClient() + Select SEvent + Case #PB_NetworkEvent_Data + SendNetworkData(ClientID,@"Goodbye, World!",Len("Goodbye, World!")) + CloseNetworkConnection(ClientID) + EndSelect + EndIf + ForEver Else - MessageRequester("Error", "Can't create the server (port in use ?).") + MessageRequester("Error", "Can't create the server (port in use ?).") EndIf diff --git a/Task/Here-document/Julia/here-document.julia b/Task/Here-document/Julia/here-document.julia new file mode 100644 index 0000000000..8996ab7ad4 --- /dev/null +++ b/Task/Here-document/Julia/here-document.julia @@ -0,0 +1,5 @@ +print("""\ +Usage: thingy [OPTIONS] + -h Display this usage message + -H hostname Hostname to connect to +""") diff --git a/Task/Higher-order-functions/Deja-Vu/higher-order-functions.djv b/Task/Higher-order-functions/Deja-Vu/higher-order-functions.djv new file mode 100644 index 0000000000..01f5efc46a --- /dev/null +++ b/Task/Higher-order-functions/Deja-Vu/higher-order-functions.djv @@ -0,0 +1,10 @@ +map f lst: + ] + for item in lst: + f item + [ + +twice: + * 2 + +!. map @twice [ 1 2 5 ] diff --git a/Task/Higher-order-functions/Visual-Prolog/higher-order-functions.pro b/Task/Higher-order-functions/Visual-Prolog/higher-order-functions.pro new file mode 100644 index 0000000000..caa6388e19 --- /dev/null +++ b/Task/Higher-order-functions/Visual-Prolog/higher-order-functions.pro @@ -0,0 +1,16 @@ +domains + intFunction = (integer In) -> integer Out procedure (i). + +class predicates + addone : intFunction. + doTwice : (intFunction, integer) -> integer procedure (i, i). + +clauses + doTwice(Pred,X) = Y :- Y = Pred(Pred(X)). + + addone(X) = Y := Y = X + 1. + + run():- + init(), + write(dotwice(addone,2)), + succeed(). diff --git a/Task/History-variables/Forth/history-variables.fth b/Task/History-variables/Forth/history-variables.fth new file mode 100644 index 0000000000..4eb4417c70 --- /dev/null +++ b/Task/History-variables/Forth/history-variables.fth @@ -0,0 +1,5 @@ +: history create here cell+ , 0 , -1 , ; +: h@ @ @ ; +: h! swap here >r , dup @ , r> swap ! ; +: .history @ begin dup cell+ @ -1 <> while dup ? cell+ @ repeat drop ; +: h-- dup @ cell+ @ dup -1 = if abort" End of history" then swap ! ; diff --git a/Task/History-variables/Perl-6/history-variables.pl6 b/Task/History-variables/Perl-6/history-variables.pl6 new file mode 100644 index 0000000000..86a52fbac5 --- /dev/null +++ b/Task/History-variables/Perl-6/history-variables.pl6 @@ -0,0 +1,18 @@ +class HistoryVar { + has @.history; + has $!var handles ; + method STORE($val) is rw { + push @.history, [now, $!var]; + $!var = $val; + } +} + +my $foo := HistoryVar.new; + +$foo = 1; +$foo = 2; +$foo += 3; +$foo = 42; + +.say for $foo.history; +say "Current value: $foo"; diff --git a/Task/History-variables/Ruby/history-variables.rb b/Task/History-variables/Ruby/history-variables.rb new file mode 100644 index 0000000000..54f631b63e --- /dev/null +++ b/Task/History-variables/Ruby/history-variables.rb @@ -0,0 +1,8 @@ +foo_hist = [] +trace_var(:$foo){|v| foo_hist.unshift(v)} + +$foo = "apple" +$foo = "pear" +$foo = "banana" + +p foo_hist # => ["banana", "pear", "apple"] diff --git a/Task/Hofstadter-Figure-Figure-sequences/Perl/hofstadter-figure-figure-sequences.pl b/Task/Hofstadter-Figure-Figure-sequences/Perl/hofstadter-figure-figure-sequences.pl new file mode 100644 index 0000000000..c57b8eb997 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Perl/hofstadter-figure-figure-sequences.pl @@ -0,0 +1,35 @@ +#!perl +use strict; +use warnings; + +my @r = ( undef, 1 ); +my @s = ( undef, 2 ); + +sub ffsr { + my $n = shift; + while( $#r < $n ) { + push @r, $s[$#r]+$r[-1]; + push @s, grep { $s[-1]<$_ } $s[-1]+1..$r[-1]-1, $r[-1]+1; + } + return $n; +} + +sub ffr { $r[ffsr shift] } +sub ffs { $s[ffsr shift] } + +printf " i: R(i) S(i)\n"; +printf "==============\n"; +printf "%3d: %3d %3d\n", $_, ffr($_), ffs($_) for 1..10; +printf "\nR(40)=%3d S(960)=%3d R(41)=%3d\n", ffr(40), ffs(960), ffr(41); + +my %seen; +$seen{ffr($_)}++ for 1 .. 40; +$seen{ffs($_)}++ for 1 .. 960; +if( 1000 == keys %seen and grep $seen{$_}, 1 .. 1000 ) { + print "All occured exactly once.\n"; +} else { + my @missed = grep !$seen{$_}, 1 .. 1000; + my @dupped = sort { $a <=> $b} grep $seen{$_}>1, keys %seen; + print "These were missed: @missed\n"; + print "These were duplicated: @dupped\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 b7260b3a35..5aef0c69fe 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,50 +1,40 @@ -/*REXX pgm to calculate & verify the Hofstadter Figure-Figure sequences.*/ +/*REXX pgm calculates & verifies the Hofstadter Figure-Figure sequences.*/ parse arg x highV . /*obtain any C.L. specifications.*/ if x=='' then x=10; if highV=='' then highV=1000 /*use the defaults?*/ -low=1 /*use unity as the starting point*/ -if x<0 then low=abs(x) /*only show a single │X│ value.*/ +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 " .*/ -errs=0 +s.=0; s.1=2; ss.=s.; ss.2=1 /* " " S " SS " */ +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 /*stick a fork in it, we're done.*/ -/*═══════════════════════════════════════verify 1st 1k: unique & present*/ -both.=0 /*initialize the BOTH array. */ - /*build list of 1st 40 R values.*/ - do m=1 for 40; r=ffr(m) /*calculate 1st 40 R values.*/ - both.r=1 /*build the BOTH array. */ - end /*m*/ - - do n=1 for 960; 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 /*add to the BOTH array. */ - end /*n*/ - /*verify presence and uniqueness.*/ - do v=1 for highV /*verify all 1 ≤ # ≤ 1k present.*/ - if \both.v then call sayErr 'missing R │ S:' v - end /*v*/ +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.*/ + end /*m*/ /* [↑] build first 40 R values.*/ + do n=1 for 960; 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.*/ + do v=1 for highV /*verify all 1 ≤ # ≤ 1k present.*/ + if \both.v then call sayErr 'missing R │ S:' v + end /*v*/ /* [↑] verify presence&uniqueness*/ say -@v='verification'; @i=" [inclusive]." /*shortcuts to shorten prog width*/ -if errs==0 then say @v 'completed for all numbers from 1 ──►' highV @i - else say @v 'failed with' errs "errors." +if errs==0 then say 'verification completed for all numbers from 1 ──►' highV " [inclusive]." + 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 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 /*assign the value to R and RR.*/ -return _ /*return the value to the invoker*/ +_=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 - do k=1 for n while s.n==0 /*search for not null R │ S num.*/ + 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._ /*maybe adjust for the FRR num.*/ - s.k=_; ss._=1 /*define couple of FFS numbers.*/ + _=_+rr._; ss._=1; s.k=_ /*define couple of FFS numbers.*/ end /*k*/ -return s.n /*return the value to the invoker*/ +return s.n /*return the value to the invoker*/ /*──────────────────────────────────SAYERR subroutine───────────────────*/ sayErr: errs=errs+1; say; say '***error***!'; say; say arg(1); say; return diff --git a/Task/Hofstadter-Q-sequence/AWK/hofstadter-q-sequence.awk b/Task/Hofstadter-Q-sequence/AWK/hofstadter-q-sequence.awk index 8c10fbfabe..a7f17164ef 100644 --- a/Task/Hofstadter-Q-sequence/AWK/hofstadter-q-sequence.awk +++ b/Task/Hofstadter-Q-sequence/AWK/hofstadter-q-sequence.awk @@ -1,22 +1,22 @@ #!/usr/bin/awk -f BEGIN { - N = 100000; - print "Q-sequence(1..10) : " Qsequence(10); - Qsequence(N,Q); - print "1000th number of Q sequence : " Q[1000]; + N = 100000 + print "Q-sequence(1..10) : " Qsequence(10) + Qsequence(N,Q) + print "1000th number of Q sequence : " Q[1000] for (n=2; n<=N; n++) { - if (Q[n] Q(1:10) +10-element Array{Int64,1}: + 1 + 1 + 2 + 3 + 3 + 4 + 5 + 5 + 6 + 6 + +julia> Q(1000) +502 diff --git a/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-3.julia b/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-3.julia new file mode 100644 index 0000000000..efe24b4a9d --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-3.julia @@ -0,0 +1,2 @@ +julia> sum(diff(Q(1:10^5)) .< 0) +49798 diff --git a/Task/Holidays-related-to-Easter/PL-I/holidays-related-to-easter.pli b/Task/Holidays-related-to-Easter/PL-I/holidays-related-to-easter.pli new file mode 100644 index 0000000000..9ec8b56078 --- /dev/null +++ b/Task/Holidays-related-to-Easter/PL-I/holidays-related-to-easter.pli @@ -0,0 +1,42 @@ +(subscriptrange, size, fofl): +Easter: procedure options (main); + declare months(12) character (9) varying static initial ( + 'January', 'February', 'March', 'April', 'May', 'June', + 'July', 'August', 'September', 'October', 'November', 'December'); + declare (year, month, day) fixed binary; + + do year = 2000 to 2020; + call Easter_Sunday (year, month, day); + put skip edit ('In ', year, ' Easter occurs on ', day, ' of ', months(month)) + (a, f(4), a, f(2), a, a); + end; + +/* Given the year, this procedure computes the month and day when Easter Sunday falls. */ +Easter_Sunday: procedure (year,month,day); +/* + See: + Jean Meeus, "Astronomical Formulae for Calculators", + 4th edition, Willmann-Bell, 1988, p.31 +*/ + + declare (year nonassignable, month, day) fixed binary; + declare (a, b, c, d, e, f, g, h, i, j, k, l, m, n) fixed binary; + + a = mod(year, 19); + b = year/100; + c = mod(year, 100); + d = b/4; + e = mod(b,4); + f = (b+8)/25; + g = (b-f+1)/3; + h = mod(19*a+b-d-g+15, 30); + i = c/4; + k = mod(c,4); + l = mod(32+2*e+2*i-h-k, 7); + m = (a+11*h+22*l)/451; + n = h+l-7*m+114; + month = n/31; + day = mod(n, 31)+1; +end Easter_Sunday; + +end Easter; diff --git a/Task/Honeycombs/ActionScript/honeycombs-1.as b/Task/Honeycombs/ActionScript/honeycombs-1.as new file mode 100644 index 0000000000..9bdcd9c1a2 --- /dev/null +++ b/Task/Honeycombs/ActionScript/honeycombs-1.as @@ -0,0 +1,214 @@ +package { + + import flash.display.GraphicsPathCommand; + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + + /** + * A honeycomb. + */ + public class Honeycomb extends Sprite { + + /** + * The sine of 60 degrees. + * + * @private + */ + private static const SIN_60:Number = Math.sin(Math.PI / 3); + + /** + * The cosine of 60 degrees. + * + * @private + */ + private static const COS_60:Number = Math.cos(Math.PI / 3); + + /** + * The drawing commands to be passed to Graphics.drawPath() + * + * @private + */ + private static var _gCommands:Vector. = new Vector.(7, true); + + /** + * The coordinates to be passed to Graphics.drawPath() + * + * @private + */ + private static var _gCoords:Vector. = new Vector.(14, true); + + /** + * The side length of the last honeycomb created. + */ + private static var _lastSide:Number; + + /** + * The horizontal space difference (between the leftmost and topmost vertex) of the last hexagon drawn. + * + * @private + */ + private static var _lastHSpace:Number; + + /** + * The heightof the last hexagon drawn. + * + * @private + */ + private static var _lastHeight:Number; + + { + _staticInit(); + } + + /** + * Initialises the Honeycomb class. + * + * @private + */ + private static function _staticInit():void { + _gCommands[0] = GraphicsPathCommand.MOVE_TO; + _gCommands[1] = _gCommands[2] = _gCommands[3] = _gCommands[4] = _gCommands[5] = _gCommands[6] = GraphicsPathCommand.LINE_TO; + } + + /** + * Calculates the points of the hexagon for a given side length. + * + * @param side The length of the side. + */ + private static function _calculatePoints(side:Number):void { + + var height:Number = side * SIN_60 * 2; + var hSpace:Number = side * COS_60; + + _gCoords[0] = _gCoords[12] = 0; + _gCoords[2] = _gCoords[10] = hSpace; + _gCoords[4] = _gCoords[8] = hSpace + side; + _gCoords[6] = side + hSpace * 2; + + _gCoords[1] = _gCoords[7] = _gCoords[13] = height / 2; + _gCoords[3] = _gCoords[5] = height; + _gCoords[9] = _gCoords[11] = 0; + + _lastSide = side; + _lastHSpace = hSpace; + _lastHeight = height; + + } + + /** + * The side length of the honeycomb. + * + * @private + */ + private var _side:Number; + + /** + * The text field displaying the character in the honeycomb. + * + * @private + */ + private var _text:TextField; + + /** + * The character code of the character in the honeycomb. + * + * @private + */ + private var _charCode:uint; + + /** + * Whether the honeycomb has been activated (i.e. the activate() method has been called). + * + * @private + */ + private var _activated:Boolean = false; + + /** + * Creates a new Honeycomb object. + * + * @param side The length of the side of the honeycomb. + * @param fill The honeycomb's fill colour. + * @param letter The character code of the letter to be displayed in the honeycomb. + * @param textColour The colour of the letter displayed inside the honeycomb. + */ + public function Honeycomb(side:Number, fill:uint, letter:uint, textColour:uint) { + _init(side, fill, letter, textColour); + } + + /** + * Initialises the Honeycomb object. + * + * @param side The length of the side of the honeycomb. + * @param fill The honeycomb's fill colour. + * @param letter The character code of the letter to be displayed in the honeycomb. + * @param textColour The colour of the letter displayed inside the honeycomb. + */ + private function _init(side:Number, fill:uint, letter:uint, textColour:uint):void { + + mouseChildren = false; + buttonMode = true; + useHandCursor = false; + + graphics.beginFill(fill); + graphics.lineStyle(3, 0x000000); + + if ( side != _lastSide ) + _calculatePoints(side); + + _side = side; + _charCode = letter; + + graphics.drawPath(_gCommands, _gCoords); + + _text = new TextField(); + _text.autoSize = TextFieldAutoSize.CENTER; + _text.defaultTextFormat = new TextFormat('_sans', side * 1.2, textColour, true); + _text.text = String.fromCharCode(letter); + _text.x = (side + _lastHSpace * 2 - _text.width) / 2; + _text.y = (_lastHeight - _text.height) / 2; + + addChild(_text); + + } + + /** + * The character code of the character in the honeycomb. + */ + public function get charCode():uint { + return _charCode; + } + + /** + * Whether the honeycomb has been activated (i.e. the activate() method has been called). + */ + public function get activated():Boolean { + return _activated; + } + + /** + * Activates the honeycomb and changes its colour. + * + * @param backColour The new fill colour of the honeycomb. + * @param textColour The new text colour of the honeycomb. + */ + public function activate(backColour:uint, textColour:uint):void { + + if ( _side != _lastSide ) + _calculatePoints(_side); + + graphics.beginFill(backColour); + graphics.drawPath(_gCommands, _gCoords); + + var textFormat:TextFormat = _text.getTextFormat(); + textFormat.color = textColour; + _text.setTextFormat(textFormat); + + _activated = true; + + } + + } + +} diff --git a/Task/Honeycombs/ActionScript/honeycombs-2.as b/Task/Honeycombs/ActionScript/honeycombs-2.as new file mode 100644 index 0000000000..3cd67169b0 --- /dev/null +++ b/Task/Honeycombs/ActionScript/honeycombs-2.as @@ -0,0 +1,166 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + import flash.utils.Dictionary; + + /** + * The Honeycomb game. + */ + public class Main extends Sprite { + + /** + * The fill colour for unselected honeycombs. + * + * @private + */ + private static const FILL_COLOUR1:uint = 0xFFFF00; + + /** + * The text colour for unselected honeycombs. + * + * @private + */ + private static const FILL_COLOUR2:uint = 0xFF00FF; + + /** + * The fill colour for selected honeycombs. + * + * @private + */ + private static const TEXT_COLOUR1:uint = 0xFF0000; + + /** + * The text colour for selected honeycombs. + * + * @private + */ + private static const TEXT_COLOUR2:uint = 0x000000; + + /** + * The honeycombs being displayed. They can be accesses using their character code as the key. + * + * @private + */ + private var _honeycombs:Dictionary = new Dictionary(); + + /** + * The text field showing the selected letters. + * + * @private + */ + private var _selectedLettersOutputField:TextField; + + /** + * Entry point of the application. + */ + public function Main() { + if ( stage ) init(); + else addEventListener(Event.ADDED_TO_STAGE, init) + } + + /** + * Initialises the Main object when it is added to the stage. + * + * @private + */ + private function init(e:Event = null):void { + + removeEventListener(Event.ADDED_TO_STAGE, init); + + var side:uint = 35; + var hSpace:Number = side * Math.cos(Math.PI / 3); + var height:Number = side * Math.sin(Math.PI / 3) * 2; + + var i:uint, j:uint, comb:Honeycomb, colX:Number = 0, rowY:Number = 0, char:uint; + var usedCodes:Vector. = new Vector.(); + + for ( i = 0; i < 5; i++ ) { + for ( j = 0; j < 4; j++ ) { + + // Select a character to display. If it is already used, repeat this process until an unused + // character is found. + + do + char = uint(Math.random() * 26) + 0x41; + while ( usedCodes.indexOf(char) != -1 ); + + usedCodes[usedCodes.length] = char; + + comb = new Honeycomb(side, FILL_COLOUR1, char, TEXT_COLOUR1); + comb.x = colX + 30; + comb.y = rowY + 30 + height * j; + addChild(comb); + + _honeycombs[char] = comb; + + } + + if ( rowY == 0 ) + rowY = height / 2; + else + rowY = 0; + + colX += side + hSpace; + } + + _selectedLettersOutputField = new TextField(); + _selectedLettersOutputField.x = 30; + _selectedLettersOutputField.y = 30 + height * 5; + _selectedLettersOutputField.defaultTextFormat = new TextFormat(null, 18); + _selectedLettersOutputField.multiline = true; + _selectedLettersOutputField.autoSize = TextFieldAutoSize.LEFT; + _selectedLettersOutputField.text = "Selected letters:\n"; + + addChild(_selectedLettersOutputField); + + // Since the MouseEvent.CLICK event bubbles, it is sufficient to add the listener to the Main object + // itself rather than to each honeycomb individually, and the event's target property will always + // be the clicked honeycomb. + + addEventListener(MouseEvent.CLICK, _onMouseClick); + stage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown); + + } + + /** + * Function called when a honeycomb is clicked. + * + * @private + */ + private function _onMouseClick(e:MouseEvent):void { + var comb:Honeycomb = e.target as Honeycomb; + + if ( comb && ! comb.activated ) { + comb.activate(FILL_COLOUR2, TEXT_COLOUR2); + _selectedLettersOutputField.appendText(String.fromCharCode(comb.charCode)); + } + } + + /** + * Function called when a keyboard key is pressed. + * + * @private + */ + private function _onKeyDown(e:KeyboardEvent):void { + var char:uint = e.charCode; + if ( char > 0x60 ) + // Convert lowercase to uppercase + char -= 0x20; + + var comb:Honeycomb = _honeycombs[char] as Honeycomb; + + if ( comb && ! comb.activated ) { + comb.activate(FILL_COLOUR2, TEXT_COLOUR2); + _selectedLettersOutputField.appendText(String.fromCharCode(char)); + } + } + + } + +} diff --git a/Task/Horizontal-sundial-calculations/Go/horizontal-sundial-calculations.go b/Task/Horizontal-sundial-calculations/Go/horizontal-sundial-calculations.go index b172de86c8..a128a72bab 100644 --- a/Task/Horizontal-sundial-calculations/Go/horizontal-sundial-calculations.go +++ b/Task/Horizontal-sundial-calculations/Go/horizontal-sundial-calculations.go @@ -1,28 +1,16 @@ package main import ( - "bufio" "fmt" "math" "os" - "strconv" - "strings" ) func getnum(prompt string) (r float64) { - in := bufio.NewReader(os.Stdin) - for { - fmt.Print(prompt) - s, err := in.ReadString('\n') - if err != nil { - fmt.Println(err) - os.Exit(-1) - } - r, err = strconv.ParseFloat(strings.TrimSpace(s), 64) - if err == nil { - break - } + fmt.Print(prompt) + if _, err := fmt.Scan(&r); err != nil { fmt.Println(err) + os.Exit(-1) } return } @@ -38,7 +26,8 @@ func main() { fmt.Println("\nHour, sun hour angle, dial hour line angle from 6am to 6pm") for h := -6.; h <= 6; h++ { hra := 15*h - diff - hla := math.Atan(slat*math.Tan(hra*math.Pi/180)) * 180 / math.Pi + s, c := math.Sincos(hra * math.Pi / 180) + hla := math.Atan2(slat*s, c) * 180 / math.Pi fmt.Printf("%2.0f %8.3f %8.3f\n", h, hra, hla) } } diff --git a/Task/Host-introspection/Applesoft-BASIC/host-introspection.applesoft b/Task/Host-introspection/Applesoft-BASIC/host-introspection.applesoft new file mode 100644 index 0000000000..3c588728a0 --- /dev/null +++ b/Task/Host-introspection/Applesoft-BASIC/host-introspection.applesoft @@ -0,0 +1,12 @@ +1 DATA248,169,153,24,105,1,48 +2 DATA6,24,251,144,2,251,56 +3 DATA216,105,0,133,251,96 +4 FOR I = 768 TO 787 +5 READ B: POKE I,B: NEXT +6 CALL 768:M = PEEK (251) +7 PRINT " WORD SIZE: "; +8 IF NOT M THEN PRINT 8 +9 M$ = "HYBRID 8/16" +10 IF M THEN PRINT M$ +11 PRINT "ENDIANNESS: "; +12 PRINT "LITTLE-ENDIAN" diff --git a/Task/Host-introspection/Icon/host-introspection.icon b/Task/Host-introspection/Icon/host-introspection.icon new file mode 100644 index 0000000000..9f4a71200d --- /dev/null +++ b/Task/Host-introspection/Icon/host-introspection.icon @@ -0,0 +1,6 @@ +procedure main() + write(if 0 = ishift(1,-1) then "little" else "big"," endian") + if match("flags",line := !open("/proc/cpuinfo")) then # Unix-like only + write(if find(" lm ",line) then 64 else 32," bits per word") + else write("Cannot determine word size.") +end diff --git a/Task/Host-introspection/Seed7/host-introspection.seed7 b/Task/Host-introspection/Seed7/host-introspection.seed7 new file mode 100644 index 0000000000..5a710807b5 --- /dev/null +++ b/Task/Host-introspection/Seed7/host-introspection.seed7 @@ -0,0 +1,13 @@ +$ include "seed7_05.s7i"; + include "cc_conf.s7i"; + +const proc: main is func + begin + writeln("Word size: " <& ccConf.POINTER_SIZE); + write("Endianness: "); + if ccConf.LITTLE_ENDIAN_INTTYPE then + writeln("Little endian"); + else + writeln("Big endian"); + end if; + end func; diff --git a/Task/Hostname/AutoHotkey/hostname.ahk b/Task/Hostname/AutoHotkey/hostname-1.ahk similarity index 100% rename from Task/Hostname/AutoHotkey/hostname.ahk rename to Task/Hostname/AutoHotkey/hostname-1.ahk diff --git a/Task/Hostname/AutoHotkey/hostname-2.ahk b/Task/Hostname/AutoHotkey/hostname-2.ahk new file mode 100644 index 0000000000..c5ef6db5aa --- /dev/null +++ b/Task/Hostname/AutoHotkey/hostname-2.ahk @@ -0,0 +1,2 @@ +for objItem in ComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_ComputerSystem") + MsgBox, % "Hostname:`t" objItem.Name diff --git a/Task/Hostname/Limbo/hostname.limbo b/Task/Hostname/Limbo/hostname.limbo new file mode 100644 index 0000000000..41a086b6d0 --- /dev/null +++ b/Task/Hostname/Limbo/hostname.limbo @@ -0,0 +1,31 @@ +implement Hostname; + +include "sys.m"; sys: Sys; +include "draw.m"; + +Hostname: 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; + buf := array[Sys->ATOMICIO] of byte; + + fd := sys->open("/dev/sysname", Sys->OREAD); + if(fd == nil) + die("Couldn't open /dev/sysname"); + + n := sys->read(fd, buf, len buf - 1); + if(n < 1) + die("Couldn't read /dev/sysname"); + + buf[n++] = byte '\n'; + sys->write(sys->fildes(1), buf, n); +} + +die(s: string) +{ + sys->fprint(sys->fildes(2), "hostname: %s: %r", s); + raise "fail:errors"; +} diff --git a/Task/Huffman-coding/PL-I/huffman-coding.pli b/Task/Huffman-coding/PL-I/huffman-coding.pli new file mode 100644 index 0000000000..fc781ebf64 --- /dev/null +++ b/Task/Huffman-coding/PL-I/huffman-coding.pli @@ -0,0 +1,258 @@ +*process source attributes xref or(!); + hencode: Proc Options(main); + /*-------------------------------------------------------------------- + * 28.12.013 Walter Pachl translated from REXX + *-------------------------------------------------------------------*/ + Dcl debug Bit(1) Init('0'b); + Dcl (i,j,k) Bin Fixed(15); + Dcl c Char(1); + Dcl s Char(100) Var Init('this is an example for huffman encoding'); + Dcl sc Char(1000) Var Init(''); + Dcl sr Char(100) Var Init(''); + Dcl 1 cocc(100), + 2 c Char(1), + 2 occ Bin Fixed(31); + Dcl cocc_n Bin Fixed(15) Init(0); + dcl 1 node, + 2 id Bin Fixed(15), /* Node id */ + 2 c Char(1), /* character */ + 2 occ Bin Fixed(15), /* number of occurrences */ + 2 left Bin Fixed(15), /* left child */ + 2 rite Bin Fixed(15), /* right child */ + 2 father Bin Fixed(15), /* father */ + 2 digit Pic'9', /* digit (0 or 1) */ + 2 term Pic'9'; /* 1=terminal node */ + node=''; + Dcl 1 m(100) Like node; + Dcl m_n Bin Fixed(15) Init(0); + Dcl father(100) Bin Fixed(15); + + Dcl 1 t(100), + 2 char Char(1), + 2 code Char(20) Var; + Dcl t_n Bin Fixed(15) Init(0); + + Do i=1 To length(s); /* first collect used characters */ + c=substr(s,i,1); /* and number of occurrences */ + Do j=1 To cocc_n; + If cocc(j).c=c Then Leave; + End; + If j<= cocc_n Then + cocc(j).occ+=1; + Else Do; + cocc(j).c=c; + cocc(j).occ=1; + cocc_n+=1; + End; + End; + + Do j=1 To cocc_n; /* create initial node list */ + node.id+=1; + node.c=cocc(j).c; + node.occ=cocc(j).occ; + node.term=1; + Call add_node; + End; + + If debug Then + Call show; + + Do While(pairs()); /* while there is more than one fatherless node */ + Call mk_node; /* create a father node */ + If debug Then + Call show; + End; + + Call show; /* show the node table */ + + Call mk_trans; /* create the translate table */ + Put Edit('The translate table:')(Skip,a); + Do i=1 To t_n; /* show it */ + Put Edit(t(i).char,' -> ',t(i).code)(Skip,a,a,a); + End; + + Call encode; /* encode the string s -> sc */ + + Put Edit('length(sc)=',length(sc)) /* show it */ + (Skip,a,f(3)); + Do i=1 By 70 To length(sc); + Put Edit(substr(sc,i,70))(Skip,a); + End; + + Call decode; /* decode the string sc -> sr */ + Put Edit('input : ',s)(skip,a,a); + Put Edit('result: ',sr)(skip,a,a); + Return; + + add_node: Proc; + /*-------------------------------------------------------------------- + * Insert the node according to increasing occurrences + *-------------------------------------------------------------------*/ + il: + Do i=1 To m_n; + If m(i).occ>=node.occ Then Do; + Do k=m_n To i By -1; + m(k+1)=m(k); + End; + Leave il; + End; + End; + m(i)=node; + m_n+=1; + End; + + show: Proc; + /*-------------------------------------------------------------------- + * Show the contents of the node table + *-------------------------------------------------------------------*/ + Put Edit('The list of nodes:')(Skip,a); + Put Edit('id c oc l r f d t')(Skip,a); + Do i=1 To m_n; + Put Edit(m(i).id,m(i).c,m(i).occ, + m(i).left,m(i).rite,m(i).father,m(i).digit,m(i).term) + (Skip,f(2),x(1),a,4(f(3)),f(2),f(3)); + End; + End; + + mk_node: Proc; + /*-------------------------------------------------------------------- + * construct and store a new intermediate node or the top node + *-------------------------------------------------------------------*/ + Dcl z Bin Fixed(15); + node=''; + node.id=m_n+1; /* the next node id */ + node.c='*'; + ni=m_n+1; + loop: + Do i=1 To m_n; /* loop over node lines */ + If m(i).father=0 Then Do; /* a fatherless node */ + z=m(i).id; /* its id */ + If node.left=0 Then Do; /* new node has no left child */ + node.left=z; /* make this the lect child */ + node.occ=m(i).occ; /* occurrences */ + m(i).father=ni; /* store father info */ + m(i).digit=0; /* digit 0 to be used */ + father(z)=ni; /* remember z's father (redundant) */ + End; + Else Do; /* New node has already left child */ + node.rite=z; /* make this the right child */ + node.occ=node.occ+m(i).occ; /* add in the occurrences */ + m(i).father=ni; /* store father info */ + m(i).digit=1; /* digit 1 to be used */ + father(z)=ni; /* remember z's father (redundant) */ + Leave loop; + End; + End; + End; + Call add_node; + End; + + pairs: Proc Returns(Bit(1)); + /*-------------------------------------------------------------------- + * Return true if there are at least 2 fatherless nodes + *-------------------------------------------------------------------*/ + Dcl i Bin Fixed(15); + Dcl cnt Bin Fixed(15) Init(0); + Do i=1 To m_n; + If m(i).father=0 Then Do; + cnt+=1; + If cnt>1 Then + Return('1'b); + End; + End; + Return('0'b); + End; + + mk_trans: Proc; + /*-------------------------------------------------------------------- + * Compute the codes for all terminal nodes (characters) + * and store the relation char -> code in array t(*) + *-------------------------------------------------------------------*/ + Dcl (i,fi,fid,fidz,node,z) Bin Fixed(15); + Dcl code Char(20) Var; + Do i=1 To m_n; /* now we loop over all lines representing nodes */ + If m(i).term Then Do; /* for each terminal node */ + code=m(i).digit; /* its digit is the last code digit */ + node=m(i).id; /* its id */ + Do fi=1 To 1000; /* actually Forever */ + fid=father(node); /* id of father */ + If fid>0 Then Do; /* father exists */ + fidz=zeile(fid); /* line that contains the father */ + code=m(fidz).digit!!code; /* prepend the digit */ + node=fid; /* look for next father */ + End; + Else /* no father (we reached the top */ + Leave; + End; + If length(code)>1 Then /* more than one character in input */ + code=substr(code,2); /* remove the the top node's 0 */ + call dbg(m(i).c!!' -> '!!code); /* character is encoded this way*/ + ti_loop: + Do ti=1 To t_n; + If t(ti).char>m(i).c Then Do; + Do tj=t_n To ti By -1 + t(tj+1)=t(tj); + End; + Leave ti_loop; + End; + End; + t(ti).char=m(i).c; + t(ti).code=code; + t_n+=1; + Call dbg(t(ti).char!!' -> '!!t(ti).code); + End; + End; + End; + + zeile: Proc(nid) Returns(Bin Fixed(15)); + /*-------------------------------------------------------------------- + * find and return line number containing node-id + *-------------------------------------------------------------------*/ + Dcl (nid,i) Bin Fixed(15); + do i=1 To m_n; + If m(i).id=nid Then + Return(i); + End; + Stop; + End; + + dbg: Proc(txt); + /*-------------------------------------------------------------------- + * Show text if debug is enabled + *-------------------------------------------------------------------*/ + Dcl txt Char(*); + If debug Then + Put Skip List(txt); + End; + + encode: Proc; + /*-------------------------------------------------------------------- + * encode the string s -> sc + *-------------------------------------------------------------------*/ + Dcl (i,j) Bin Fixed(15); + Do i=1 To length(s); + c=substr(s,i,1); + Do j=1 To t_n; + If c=t(j).char Then + Leave; + End; + sc=sc!!t(j).code; + End; + End; + + decode: Proc; + /*-------------------------------------------------------------------- + * decode the string sc -> sr + *-------------------------------------------------------------------*/ + Dcl (i,j) Bin Fixed(15); + Do While(sc>''); + Do j=1 To t_n; + If substr(sc,1,length(t(j).code))=t(j).code Then + Leave; + End; + sr=sr!!t(j).char; + sc=substr(sc,length(t(j).code)+1); + End; + End; + + End; diff --git a/Task/Huffman-coding/REXX/huffman-coding.rexx b/Task/Huffman-coding/REXX/huffman-coding.rexx new file mode 100644 index 0000000000..563e21756c --- /dev/null +++ b/Task/Huffman-coding/REXX/huffman-coding.rexx @@ -0,0 +1,257 @@ +/* REXX --------------------------------------------------------------- +* 27.12.2013 Walter Pachl +* 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) +* Stem m contains eventually the following node data +* m.i.0id Node id +* m.i.0c character +* m.i.0o number of occurrences +* m.i.0l left child +* m.i.0r right child +* m.i.0f father +* m.i.0d digit (0 or 1) +* m.i.0t 1=a terminal node 0=an intermediate or the top node +*--------------------------------------------------------------------*/ +Parse Arg s +If s='' Then + s='this is an example for huffman encoding' +Say 'We encode this string:' +Say s +debug=0 +o.=0 +c.=0 +codel.=0 +code.='' +father.=0 +cl='' /* list of characters */ +do i=1 To length(s) + Call memorize substr(s,i,1) + End +If debug Then Do + Do i=1 To c.0 + c=c.i + Say i c o.c + End + End +n.=0 +Do i=1 To c.0 + c=c.i + n.i.0c=c + n.i.0o=o.c + n.i.0id=i + Call dbg i n.i.0id n.i.0c n.i.0o + End +n=c.0 /* number of nodes */ +m.=0 +Do i=1 To n /* construct initial array */ + Do j=1 To m.0 /* sorted by occurrences */ + If m.j.0o>n.i.0o Then + Leave + End + Do k=m.0 To j By -1 + k1=k+1 + m.k1.0id=m.k.0id + m.k1.0c =m.k.0c + m.k1.0o =m.k.0o + m.k1.0t =m.k.0t + End + m.j.0id=i + m.j.0c =n.i.0c + m.j.0o =n.i.0o + m.j.0t =1 + m.0=m.0+1 + End +If debug Then + Call show + +Do While pairs()>1 /* while there are at least 2 fatherless nodes */ + Call mknode /* create and fill a new father node */ + If debug Then + Call show + End + +Call show +c.=0 +Do i=1 To m.0 /* now we loop over all lines representing nodes */ + If m.i.0t Then Do /* for each terminal node */ + code=m.i.0d /* its digit is the last code digit */ + node=m.i.0id /* its id */ + Do fi=1 To 1000 /* actually Forever */ + fid=father.node /* id of father */ + If fid<>0 Then Do /* father exists */ + fidz=zeile(fid) /* line that contains the father */ + code=m.fidz.0d||code /* prepend the digit */ + node=fid /* look for next father */ + End + Else /* no father (we reached the top */ + Leave + End + If length(code)>1 Then /* more than one character in input */ + code=substr(code,2) /* remove the the top node's 0 */ + call dbg m.i.0c '->' code /* character is encoded this way */ + char=m.i.0c + code.char=code + z=codel.0+1 + codel.z=code + codel.0=z + char.code=char + End + End + +Call show_char2code /* show used characters and corresponding codes */ + +codes.=0 /* now we build the array of codes/characters */ +Do j=1 To codel.0 + z=codes.0+1 + code=codel.j + codes.z=code + chars.z=char.code + codes.0=z + Call dbg codes.z '----->' chars.z + End + +sc='' /* here we ecnode the string */ +Do i=1 To length(s) /* loop over input */ + c=substr(s,i,1) /* a character */ + sc=sc||code.c /* append the corresponding code */ + End +Say 'Length of encoded string:' length(sc) +Do i=1 To length(sc) by 70 + Say substr(sc,i,70) + End + +sr='' /* now decode the string */ +Do si=1 To 999 While sc<>'' + Do i=codes.0 To 1 By -1 /* loop over codes */ + cl=length(codes.i) /* length of code */ + If left(sc,cl)==codes.i Then Do /* found on top of string */ + sr=sr||chars.i /* append character to result */ + sc=substr(sc,cl+1) /* cut off the used code */ + Leave /* this was one character */ + End + End + End +Say 'Input ' s +Say 'result' sr + +Exit + +show: +/*--------------------------------------------------------------------- +* show all lines representing node data +*--------------------------------------------------------------------*/ +Say ' i pp id c f l r d' +Do i=1 To m.0 + Say right(i,2) right(m.i.0o,3) right(m.i.0id,2), + right(m.i.0f,2) right(m.i.0l,2) right(m.i.0r,2) m.i.0d m.i.0t + End +Call dbg copies('-',21) +Return + +pairs: Procedure Expose m. +/*--------------------------------------------------------------------- +* return number of fatherless nodes +*--------------------------------------------------------------------*/ + res=0 + Do i=1 To m.0 + If m.i.0f=0 Then + res=res+1 + End + Return res + +mknode: +/*--------------------------------------------------------------------- +* construct and store a new intermediate or the top node +*--------------------------------------------------------------------*/ +new.=0 +ni=m.0+1 /* the next node id */ +Do i=1 To m.0 /* loop over node lines */ + If m.i.0f=0 Then Do /* a fatherless node */ + z=m.i.0id /* its id */ + If new.0l=0 Then Do /* new node has no left child */ + new.0l=z /* make this the lect child */ + new.0o=m.i.0o /* occurrences */ + m.i.0f=ni /* store father info */ + m.i.0d='0' /* digit 0 to be used */ + father.z=ni /* remember z's father (redundant) */ + End + Else Do /* New node has already left child */ + new.0r=z /* make this the right child */ + new.0o=new.0o+m.i.0o /* add in the occurrences */ + m.i.0f=ni /* store father info */ + m.i.0d=1 /* digit 1 to be used */ + father.z=ni /* remember z's father (redundant) */ + Leave + End + End + End +Do i=1 To m.0 /* Insert new node according to occurrences */ + If m.i.0o>=new.0o Then Do + Do k=m.0 To i By -1 + k1=k+1 + m.k1.0id=m.k.0id + m.k1.0o =m.k.0o + m.k1.0c =m.k.0c + m.k1.0l =m.k.0l + m.k1.0r =m.k.0r + m.k1.0f =m.k.0f + m.k1.0d =m.k.0d + m.k1.0t =m.k.0t + End + Leave + End + End +m.i.0id=ni +m.i.0c ='*' +m.i.0o =new.0o +m.i.0l =new.0l +m.i.0r =new.0r +m.i.0t =0 +father.ni=0 +m.0=ni +Return + +zeile: +/*--------------------------------------------------------------------- +* find and return line number containing node-id +*--------------------------------------------------------------------*/ + do fidz=1 To m.0 + If m.fidz.0id=arg(1) Then + Return fidz + End + Call dbg arg(1) 'not found' + Pull . + +dbg: +/*--------------------------------------------------------------------- +* Show text if debug is enabled +*--------------------------------------------------------------------*/ + If debug=1 Then + Say arg(1) + Return + + +memorize: Procedure Expose c. o. +/*--------------------------------------------------------------------- +* store characters and corresponding occurrences +*--------------------------------------------------------------------*/ + Parse Arg c + If o.c=0 Then Do + z=c.0+1 + c.z=c + c.0=z + End + o.c=o.c+1 + Return + +show_char2code: +/*--------------------------------------------------------------------- +* show used characters and corresponding codes +*--------------------------------------------------------------------*/ +cl=xrange('00'x,'ff'x) +Say 'char --> code' +Do While cl<>'' + Parse Var cl c +1 cl + If code.c<>'' Then + Say ' 'c '-->' code.c + End +Return diff --git a/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk b/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk new file mode 100644 index 0000000000..12b8f0481d --- /dev/null +++ b/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk @@ -0,0 +1,22 @@ +WordList := URL_ToVar("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +WordList := RegExReplace(WordList, "i)cie", "", cieN) +WordList := RegExReplace(WordList, "i)cei", "", ceiN) +RegExReplace(WordList, "i)ie", "", ieN) +RegExReplace(WordList, "i)ei", "", eiN) + +cei := ceiN / cieN > 2 ? "plausible" : "implausible" +ei := ieN / eiN > 2 ? "plausible" : "implausible" +ova := cei = "plausible." && ei = "plausible" ? "plausible" : "implausible" + +MsgBox, % """I before E when not preceded by C"" is " ei ".`n" + . ieN " cases for and " eiN " cases against is a ratio of " ieN / eiN ".`n`n" + . """E before I when preceded by C"" is " cei ".`n" + . ceiN " cases for and " cieN " cases against is a ratio of " ceiN / cieN ".`n`n" + . "Overall the rule is " ova "." + +URL_ToVar(URL) { + WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1") + WebRequest.Open("GET", URL) + WebRequest.Send() + return, WebRequest.ResponseText +} diff --git a/Task/I-before-E-except-after-C/C++/i-before-e-except-after-c.cpp b/Task/I-before-E-except-after-C/C++/i-before-e-except-after-c.cpp new file mode 100644 index 0000000000..38231fc85b --- /dev/null +++ b/Task/I-before-E-except-after-C/C++/i-before-e-except-after-c.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include +#include +#include + + + +struct Claim { + Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { + } + + void add_pro(const std::string& pat) { + propats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); + } + void add_against(const std::string& pat) { + againstpats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); + } + bool plausible() const { return pro_ > against_*2; } + void check(const char * buf, uint32_t len) { + for (auto i = propats_.begin(), ii = propats_.end(); i != ii; ++i) { + uint32_t pos = 0; + boost::cmatch m; + if (std::get<1>(*i) && pos > 0) continue; + while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) { + ++pro_; + if (pos > 0) std::cerr << name_ << " [pro] multiple matches in: " << buf << "\n"; + pos += m.position() + m.length(); + } + } + for (auto i = againstpats_.begin(), ii = againstpats_.end(); i != ii; ++i) { + uint32_t pos = 0; + boost::cmatch m; + if (std::get<1>(*i) && pos > 0) continue; + while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) { + ++against_; + if (pos > 0) std::cerr << name_ << " [against] multiple matches in: " << buf << "\n"; + pos += m.position() + m.length(); + } + } + } + friend std::ostream& operator<<(std::ostream& os, const Claim& c); +private: + std::string name_; + uint32_t pro_; + uint32_t against_; + // tuple + std::vector> propats_; + std::vector> againstpats_; +}; + +std::ostream& operator<<(std::ostream& os, const Claim& c) { + os << c.name_ << ": matches: " << c.pro_ << " vs. counter matches: " << c.against_ << ". "; + os << "Plausibility: " << (c.plausible() ? "yes" : "no") << "."; + return os; +} + + +int main(int argc, char ** argv) { + try { + if (argc < 2) throw std::runtime_error("No input file."); + std::ifstream is(argv[1]); + if (! is) throw std::runtime_error("Input file not valid."); + + Claim ieclaim("[^c]ie"); + ieclaim.add_pro("[^c]ie"); + ieclaim.add_pro("^ie"); + ieclaim.add_against("[^c]ei"); + ieclaim.add_against("^ei"); + + Claim ceiclaim("cei"); + ceiclaim.add_pro("cei"); + ceiclaim.add_against("cie"); + + { + const uint32_t MAXLEN = 32; + char buf[MAXLEN]; + uint32_t longest = 0; + while (is) { + is.getline(buf, sizeof(buf)); + if (is.gcount() <= 0) break; + else if (is.gcount() > longest) longest = is.gcount(); + ieclaim.check(buf, is.gcount()); + ceiclaim.check(buf, is.gcount()); + } + if (longest >= MAXLEN) throw std::runtime_error("Buffer too small."); + } + + std::cout << ieclaim << "\n"; + std::cout << ceiclaim << "\n"; + std::cout << "Overall plausibility: " << (ieclaim.plausible() && ceiclaim.plausible() ? "yes" : "no") << "\n"; + + + } catch (const std::exception& ex) { + std::cerr << "*** Error: " << ex.what() << "\n"; + return -1; + } + return 0; +} diff --git a/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs b/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs new file mode 100644 index 0000000000..0873316010 --- /dev/null +++ b/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs @@ -0,0 +1,25 @@ +import Network.HTTP +import Text.Regex.TDFA +import Text.Printf + +getWordList :: IO String +getWordList = do + response <- simpleHTTP.getRequest$ url + getResponseBody response + where url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" + +main = do + words <- getWordList + putStrLn "Checking Rule 1: \"I before E when not preceded by C\"..." + let numTrueRule1 = matchCount (makeRegex "[^c]ie" :: Regex) words + numFalseRule1 = matchCount (makeRegex "[^c]ei" :: Regex) words + rule1Plausible = numTrueRule1 > (2*numFalseRule1) + printf "Rule 1 is correct for %d\n incorrect for %d\n" numTrueRule1 numFalseRule1 + printf "*** Rule 1 is %splausible.\n" (if rule1Plausible then "" else "im") + + putStrLn "Checking Rule 2: \"E before I when preceded by C\"..." + let numTrueRule2 = matchCount (makeRegex "cei" :: Regex) words + numFalseRule2 = matchCount (makeRegex "cie" :: Regex) words + rule2Plausible = numTrueRule2 > (2*numFalseRule2) + printf "Rule 2 is correct for %d\n incorrect for %d\n" numTrueRule2 numFalseRule2 + printf "*** Rule 2 is %splausible.\n" (if rule2Plausible then "" else "im") diff --git a/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb b/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb new file mode 100644 index 0000000000..525ed57ba8 --- /dev/null +++ b/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb @@ -0,0 +1,19 @@ +require 'open-uri' + +plausibility_ratio = 2 +counter = Hash.new(0) +path = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' +rules = [['I before E when not preceded by C:', 'ie', 'ei'], + ['E before I when preceded by C:', 'cei', 'cie']] + +open(path){|f| f.each{|line| line.scan(/ie|ei|cie|cei/){|match| counter[match] += 1 }}} + +overall_plausible = rules.all? do |(str, x, y)| + num_x, num_y, ratio = counter[x], counter[y], counter[x] / counter[y].to_f + plausibility = ratio > plausibility_ratio + puts str + puts "#{x}: #{num_x}; #{y}: #{num_y}; Ratio: #{ratio.round(2)}: #{ plausibility ? 'Plausible' : 'Implausible'}" + plausibility +end + +puts "Overall: #{overall_plausible ? 'Plausible' : 'Implausible'}." diff --git a/Task/Identity-matrix/GAP/identity-matrix.gap b/Task/Identity-matrix/GAP/identity-matrix.gap new file mode 100644 index 0000000000..004cbe8bba --- /dev/null +++ b/Task/Identity-matrix/GAP/identity-matrix.gap @@ -0,0 +1,5 @@ +# Built-in +IdentityMat(3); + +# One can also specify the base ring +IdentityMat(3, Integers mod 10); diff --git a/Task/Image-noise/PL-I/image-noise.pli b/Task/Image-noise/PL-I/image-noise.pli new file mode 100644 index 0000000000..788badca35 --- /dev/null +++ b/Task/Image-noise/PL-I/image-noise.pli @@ -0,0 +1,27 @@ +Image_Noise: procedure options (main); /* 3 November 2013 */ + declare (start_time, end_time) float (18); + declare (frame, m, n) fixed binary; + + start_time = secs(); + get (m, n); + do frame = 1 to 100; /* Generate 100 frames. */ + call display (m, n); + put skip data (frame); + end; + end_time = secs(); + + put skip list ('Average FPS =' || fixed(100/(end_time-start_time), 6) ); + +display: procedure (m, n); + declare (m, n) fixed binary; + declare screen(0:m, 0:n) bit (1); + declare i fixed binary; + declare random builtin; + + screen = '0'b; /* clear screen for this frame */ + do i = 0 to m*n*random; + screen(random*m, random*n) = random > 0.5; + end; +end display; + +end Image_Noise; diff --git a/Task/Include-a-file/Batch-File/include-a-file.bat b/Task/Include-a-file/Batch-File/include-a-file.bat new file mode 100644 index 0000000000..f4a7a51974 --- /dev/null +++ b/Task/Include-a-file/Batch-File/include-a-file.bat @@ -0,0 +1 @@ +call file2.bat diff --git a/Task/Include-a-file/Clipper/include-a-file.clipper b/Task/Include-a-file/Clipper/include-a-file.clipper new file mode 100644 index 0000000000..24d9a31a05 --- /dev/null +++ b/Task/Include-a-file/Clipper/include-a-file.clipper @@ -0,0 +1 @@ + #include "inkey.ch" diff --git a/Task/Include-a-file/Julia/include-a-file-1.julia b/Task/Include-a-file/Julia/include-a-file-1.julia new file mode 100644 index 0000000000..cd41f8c216 --- /dev/null +++ b/Task/Include-a-file/Julia/include-a-file-1.julia @@ -0,0 +1 @@ +include("foo.jl") diff --git a/Task/Include-a-file/Julia/include-a-file-2.julia b/Task/Include-a-file/Julia/include-a-file-2.julia new file mode 100644 index 0000000000..db900fe88c --- /dev/null +++ b/Task/Include-a-file/Julia/include-a-file-2.julia @@ -0,0 +1 @@ +import MyModule diff --git a/Task/Include-a-file/Julia/include-a-file-3.julia b/Task/Include-a-file/Julia/include-a-file-3.julia new file mode 100644 index 0000000000..2b5d05e5c0 --- /dev/null +++ b/Task/Include-a-file/Julia/include-a-file-3.julia @@ -0,0 +1 @@ +using MyModule diff --git a/Task/Include-a-file/LabVIEW/include-a-file.labview b/Task/Include-a-file/LabVIEW/include-a-file.labview new file mode 100644 index 0000000000..18dae8c720 --- /dev/null +++ b/Task/Include-a-file/LabVIEW/include-a-file.labview @@ -0,0 +1 @@ +web_response -> include('my_file.inc') diff --git a/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia index 5265f224c7..fb52ededa8 100644 --- a/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia +++ b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia @@ -1 +1 @@ -+(s::String, n::Integer) = string(int(s) + n) ++(s::String, n::Integer) = string(parseint(typeof(n), s) + n) diff --git a/Task/Infinity/Julia/infinity-1.julia b/Task/Infinity/Julia/infinity-1.julia index 4e53508d64..2b946033a4 100644 --- a/Task/Infinity/Julia/infinity-1.julia +++ b/Task/Infinity/Julia/infinity-1.julia @@ -1,3 +1 @@ -function infinity() - return Inf -end +infinity() = Inf diff --git a/Task/Infinity/Julia/infinity-2.julia b/Task/Infinity/Julia/infinity-2.julia index 6f1881e9b2..e038dcc472 100644 --- a/Task/Infinity/Julia/infinity-2.julia +++ b/Task/Infinity/Julia/infinity-2.julia @@ -1,2 +1,3 @@ -inf(Float64) # Inf -inf(Float32) # Inf +inf(Float64) # 64-bit Inf +inf(Float32) # 32-bit Inf32 +inf(BigFloat) # infinity for arbitrary-precision floating-point arithmetic diff --git a/Task/Inheritance-Single/Julia/inheritance-single.julia b/Task/Inheritance-Single/Julia/inheritance-single.julia new file mode 100644 index 0000000000..ebf34b8b4d --- /dev/null +++ b/Task/Inheritance-Single/Julia/inheritance-single.julia @@ -0,0 +1,6 @@ +abstract Animal +abstract Dog <: Animal +abstract Cat <: Animal + +type Lab <: Dog end +type Collie <: Dog end diff --git a/Task/Input-loop/BASIC/input-loop-1.basic b/Task/Input-loop/BASIC/input-loop-1.basic new file mode 100644 index 0000000000..c92e8c8dff --- /dev/null +++ b/Task/Input-loop/BASIC/input-loop-1.basic @@ -0,0 +1,14 @@ +100 INPUT "FILENAME:";F$ +110 D$ = CHR$(4) +120 PRINT D$"VERIFY"F$ +130 PRINT D$"OPEN"F$ +140 PRINT D$"READ"F$ +150 ONERR GOTO 190 + +160 GET C$ +170 PRINT CHR$(0)C$; +180 GOTO 160 + +190 POKE 216,0 +200 IF PEEK(222) <> 5 THEN RESUME +210 PRINT D$"CLOSE"F$ diff --git a/Task/Input-loop/BASIC/input-loop-2.basic b/Task/Input-loop/BASIC/input-loop-2.basic new file mode 100644 index 0000000000..3fc5f6e1dc --- /dev/null +++ b/Task/Input-loop/BASIC/input-loop-2.basic @@ -0,0 +1,11 @@ + STD_INPUT_HANDLE = -10 + STD_OUTPUT_HANDLE = -11 + SYS "GetStdHandle", STD_INPUT_HANDLE TO @hfile%(1) + SYS "GetStdHandle", STD_OUTPUT_HANDLE TO @hfile%(2) + SYS "SetConsoleMode", @hfile%(1), 0 + *INPUT 13 + *OUTPUT 14 + REPEAT + INPUT A$ + PRINT A$ + UNTIL FALSE diff --git a/Task/Input-loop/Batch-File/input-loop.bat b/Task/Input-loop/Batch-File/input-loop.bat new file mode 100644 index 0000000000..7abe392f96 --- /dev/null +++ b/Task/Input-loop/Batch-File/input-loop.bat @@ -0,0 +1 @@ +for /f %%i in (file.txt) do if %%i@ neq @ echo %%i diff --git a/Task/Input-loop/COBOL/input-loop.cobol b/Task/Input-loop/COBOL/input-loop.cobol new file mode 100644 index 0000000000..271cc93ff1 --- /dev/null +++ b/Task/Input-loop/COBOL/input-loop.cobol @@ -0,0 +1,33 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. input-loop. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT in-stream ASSIGN TO KEYBOARD *> or any other file/stream + ORGANIZATION LINE SEQUENTIAL + FILE STATUS in-stream-status. + + DATA DIVISION. + FILE SECTION. + FD in-stream. + 01 stream-line PIC X(80). + + WORKING-STORAGE SECTION. + 01 in-stream-status PIC 99. + 88 end-of-stream VALUE 10. + + PROCEDURE DIVISION. + OPEN INPUT in-stream + + PERFORM UNTIL EXIT + READ in-stream + AT END + EXIT PERFORM + END-READ + DISPLAY stream-line + END-PERFORM + + CLOSE in-stream + . + END PROGRAM input-loop. diff --git a/Task/Input-loop/Deja-Vu/input-loop.djv b/Task/Input-loop/Deja-Vu/input-loop.djv new file mode 100644 index 0000000000..cefb004056 --- /dev/null +++ b/Task/Input-loop/Deja-Vu/input-loop.djv @@ -0,0 +1,4 @@ +while /= :eof dup !read-line!stdin: + !print( "Read a line: " !decode!utf-8 swap ) +drop +!print "End of file." diff --git a/Task/Integer-comparison/Clipper/integer-comparison.clipper b/Task/Integer-comparison/Clipper/integer-comparison.clipper new file mode 100644 index 0000000000..873724c2b4 --- /dev/null +++ b/Task/Integer-comparison/Clipper/integer-comparison.clipper @@ -0,0 +1,9 @@ + Function Compare(a, b) + IF a < b + ? "A is less than B" + ELSEIF a > b + ? "A is more than B" + ELSE + ? "A equals B" + ENDIF + Return Nil diff --git a/Task/Integer-comparison/D/integer-comparison.d b/Task/Integer-comparison/D/integer-comparison.d index e4402d9f6f..8078354845 100644 --- a/Task/Integer-comparison/D/integer-comparison.d +++ b/Task/Integer-comparison/D/integer-comparison.d @@ -1,10 +1,10 @@ -import std.stdio, std.conv, std.string; - void main() { + import std.stdio, std.conv, std.string; + int a = 10, b = 20; try { - a = to!int(readln().strip()); - b = to!int(readln().strip()); + a = readln.strip.to!int; + b = readln.strip.to!int; } catch (StdioException) {} if (a < b) diff --git a/Task/Integer-comparison/RPG/integer-comparison.rpg b/Task/Integer-comparison/RPG/integer-comparison.rpg new file mode 100644 index 0000000000..7b6d3f2610 --- /dev/null +++ b/Task/Integer-comparison/RPG/integer-comparison.rpg @@ -0,0 +1,22 @@ + h dftactgrp(*no) + + d pi + d integer1 10i 0 + d integer2 10i 0 + + d message s 50a + + if integer1 < integer2; + message = 'Integer 1 is less than integer 2'; + endif; + + if integer1 > integer2; + message = 'Integer 1 is greater than integer 2'; + endif; + + if integer1 = integer2; + message = 'Integer 1 is equal to integer 2'; + endif; + + dsply message; + *inlr = *on; diff --git a/Task/Integer-sequence/Deja-Vu/integer-sequence.djv b/Task/Integer-sequence/Deja-Vu/integer-sequence.djv new file mode 100644 index 0000000000..c8051790e5 --- /dev/null +++ b/Task/Integer-sequence/Deja-Vu/integer-sequence.djv @@ -0,0 +1,7 @@ +1 + +while /= -- dup dup: + !. dup + ++ + +drop diff --git a/Task/Integer-sequence/Julia/integer-sequence.julia b/Task/Integer-sequence/Julia/integer-sequence.julia new file mode 100644 index 0000000000..dae3eca9c9 --- /dev/null +++ b/Task/Integer-sequence/Julia/integer-sequence.julia @@ -0,0 +1,4 @@ +i = zero(BigInt) # or i = big(0) +while true + println(i += 1) +end diff --git a/Task/Integer-sequence/Limbo/integer-sequence.limbo b/Task/Integer-sequence/Limbo/integer-sequence.limbo new file mode 100644 index 0000000000..7345bf4ddc --- /dev/null +++ b/Task/Integer-sequence/Limbo/integer-sequence.limbo @@ -0,0 +1,23 @@ +implement CountToInfinity; + +include "sys.m"; sys: Sys; +include "draw.m"; +include "ipints.m"; ipints: IPints; + IPint: import ipints; + +CountToInfinity: 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; + ipints = load IPints IPints->PATH; + + i := IPint.inttoip(0); + one := IPint.inttoip(1); + for(;;) { + sys->print("%s\n", i.iptostr(10)); + i = i.add(one); + } +} diff --git a/Task/Integer-sequence/Rust/integer-sequence.rust b/Task/Integer-sequence/Rust/integer-sequence.rust new file mode 100644 index 0000000000..026cb47b1b --- /dev/null +++ b/Task/Integer-sequence/Rust/integer-sequence.rust @@ -0,0 +1,13 @@ +extern mod extra; +use extra::bigint::BigUint; +use std::num::One; + +fn main() { + let one: BigUint = One::one(); + let mut i: BigUint = One::one(); + + loop { + println!("{:s}", i.to_str()); + i = i + one; + } +} diff --git a/Task/Interactive-programming/Deja-Vu/interactive-programming.djv b/Task/Interactive-programming/Deja-Vu/interactive-programming.djv new file mode 100644 index 0000000000..9f92a943ec --- /dev/null +++ b/Task/Interactive-programming/Deja-Vu/interactive-programming.djv @@ -0,0 +1,6 @@ +$ vu +<1:1> f str1 str2 sep: +<1:2> join sep [ str2 "" str1 ] +<1:3> +<2:1> . f "Rosetta" "Code" ":" +"Rosetta::Code" diff --git a/Task/Introspection/AWK/introspection.awk b/Task/Introspection/AWK/introspection.awk new file mode 100644 index 0000000000..fdef37cdf8 --- /dev/null +++ b/Task/Introspection/AWK/introspection.awk @@ -0,0 +1,14 @@ +# syntax: GAWK -f INTROSPECTION.AWK +BEGIN { + if (PROCINFO["version"] < "4.1.0") { + print("version is too old") + exit(1) + } + bloop = -1 + if (PROCINFO["identifiers"]["abs"] == "user" && bloop != "") { + printf("bloop = %s\n",bloop) + printf("abs(bloop) = %s\n",abs(bloop)) + } + exit(0) +} +function abs(x) { if (x >= 0) { return x } else { return -x } } diff --git a/Task/Introspection/D/introspection.d b/Task/Introspection/D/introspection.d index 92017362f0..ce70838c92 100644 --- a/Task/Introspection/D/introspection.d +++ b/Task/Introspection/D/introspection.d @@ -1,22 +1,31 @@ -import std.compiler, std.math; +// Some module-level variables (D doesn't have a global scope). +immutable x = 3, y = 100, z = 3_000; +short w = 1; // Not an int, must be ignored. +immutable s = "some string"; // Not an int, must be ignored. void main() { + import std.compiler, std.math, std.traits; + // Compile-time constants of the compiler version: - static if (version_major < 2 && version_minor > 50) { - // this prevents further compilation - static assert(false, "I can't cope with this compiler version"); - } else { - pragma(msg, "The compiler version is acceptable."); - } + static assert(version_major > 1 && version_minor > 50, + "I can't cope with this compiler version."); immutable bloop = 10; // To check if something compiles: - //static if (__traits(compiles, bloop.abs)) { - static if (__traits(compiles, abs(bloop))) { + static if (__traits(compiles, bloop.abs)) { pragma(msg, "The expression is compilable."); auto x = bloop.abs; } else { pragma(msg, "The expression can't be compiled."); } + + import std.stdio; + immutable s = 10_000; // Not at module scope, must be ignored. + + int tot = 0; + /*static*/ foreach (name; __traits(allMembers, mixin(__MODULE__))) + static if (is(int == Unqual!(typeof(mixin("." ~ name))))) + tot += mixin("." ~ name); + writeln("Total of the module-level ints (could overflow): ", tot); } diff --git a/Task/Introspection/PL-I/introspection.pli b/Task/Introspection/PL-I/introspection-1.pli similarity index 100% rename from Task/Introspection/PL-I/introspection.pli rename to Task/Introspection/PL-I/introspection-1.pli diff --git a/Task/Introspection/PL-I/introspection-2.pli b/Task/Introspection/PL-I/introspection-2.pli new file mode 100644 index 0000000000..b9a3aa35aa --- /dev/null +++ b/Task/Introspection/PL-I/introspection-2.pli @@ -0,0 +1,22 @@ +*process source attributes options m or(!); + /********************************************************************* + * 02-11.2013 Walter Pachl + * I modified this to run on my Windows PL/I + *********************************************************************/ + v: Proc Options(main); + %version: Proc Returns(char); + Dcl res char; + res=sysversion; + Return(''''!!res!!''''); + %End; + %Act version; + Dcl s char(31) Init(''); + s=version; + if substr(S,15,3) < '7.5' then Do; + put Skip list('Version of compiler ('!!substr(S,15,3)!! + ') is too old'); + stop; + End; + Else + Put Skip List('Version is '!!s); + End diff --git a/Task/Introspection/REXX/introspection-7.rexx b/Task/Introspection/REXX/introspection-7.rexx index 97dd8e4fe9..d4e71b36d4 100644 --- a/Task/Introspection/REXX/introspection-7.rexx +++ b/Task/Introspection/REXX/introspection-7.rexx @@ -3,7 +3,7 @@ if testxyz() then say 'function XYZ not found.' exit testxyz: signal on syntax -y='XYZ'(123) +call XYZ return 0 syntax: return 1 diff --git a/Task/Introspection/Scala/introspection.scala b/Task/Introspection/Scala/introspection.scala new file mode 100644 index 0000000000..70187c1242 --- /dev/null +++ b/Task/Introspection/Scala/introspection.scala @@ -0,0 +1,9 @@ +object VersCheck extends App { + val minimalVersion = 1.7 + + val vers = System.getProperty("java.specification.version"); + println(if (vers.toDouble >= minimalVersion) "YAY!" else s"Must use Java >= $minimalVersion"); + + val bloop = Option(-42) + if (bloop.isDefined) bloop.get.abs +} diff --git a/Task/Inverted-index/OCaml/inverted-index.ocaml b/Task/Inverted-index/OCaml/inverted-index.ocaml index cdedbc064d..e2904f314b 100644 --- a/Task/Inverted-index/OCaml/inverted-index.ocaml +++ b/Task/Inverted-index/OCaml/inverted-index.ocaml @@ -37,12 +37,11 @@ let combine words i inv_index = let h = Hashtbl.create (List.length inv_index) in List.iter (fun (w, from) -> Hashtbl.replace h w from) inv_index; List.iter (fun w -> - if Hashtbl.mem h w - then begin - let from = Hashtbl.find h w in - Hashtbl.replace h w (i::from) - end else - Hashtbl.add h w [i] + let from = + try Hashtbl.find h w + except Not_found -> [] + in + Hashtbl.replace h w (i::from) ) words; Hashtbl.fold (fun w from acc -> (w, from) :: acc) h [] diff --git a/Task/JSON/Julia/json.julia b/Task/JSON/Julia/json.julia new file mode 100644 index 0000000000..3164713e32 --- /dev/null +++ b/Task/JSON/Julia/json.julia @@ -0,0 +1,7 @@ +julia> import JSON + +julia> JSON.parse("""{ "blue": [1,2], "ocean": "water" }""") +["ocean"=>"water","blue"=>{1,2}] + +julia> JSON.json({"blue" => [1,2] , "ocean" => "water"}) +"{\"ocean\":\"water\",\"blue\":[1,2]}" diff --git a/Task/JSON/Objective-C/json.m b/Task/JSON/Objective-C/json.m index ddae2c630d..cf92878b2d 100644 --- a/Task/JSON/Objective-C/json.m +++ b/Task/JSON/Objective-C/json.m @@ -1,6 +1,6 @@ NSString *jsonString = @"{ \"foo\": 1, \"bar\": [10, \"apples\"] }"; id obj = [NSJSONSerialization - JSONObjectWithData: [json_string dataUsingEncoding: NSUTF8StringEncoding] + JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: NULL]; NSLog(@"%@", obj); diff --git a/Task/Jensens-Device/Groovy/jensens-device.groovy b/Task/Jensens-Device/Groovy/jensens-device.groovy new file mode 100644 index 0000000000..867017dbbc --- /dev/null +++ b/Task/Jensens-Device/Groovy/jensens-device.groovy @@ -0,0 +1,5 @@ +def sum = { i, lo, hi, term -> + (lo..hi).sum { i.value = it; term() } +} +def obj = [:] +println (sum(obj, 1, 100, { 1 / obj.value })) diff --git a/Task/Josephus-problem/AWK/josephus-problem.awk b/Task/Josephus-problem/AWK/josephus-problem.awk new file mode 100644 index 0000000000..7e2494c134 --- /dev/null +++ b/Task/Josephus-problem/AWK/josephus-problem.awk @@ -0,0 +1,37 @@ +# syntax: GAWK -f JOSEPHUS_PROBLEM.AWK +# converted from PL/I +BEGIN { + main(5,2,1) + main(41,3,1) + main(41,3,3) + exit(0) +} +function main(n,k,s, dead,errors,found,i,killed,nn,p,survived) { +# n - number of prisoners +# k - kill every k'th prisoner +# s - number of survivors + printf("\nn=%d k=%d s=%d\n",n,k,s) # show arguments + if (s > n) { print("s>n"); errors++ } + if (k <= 0) { print("k<=0"); errors++ } + if (errors > 0) { return(0) } + nn = n # wrap around boundary + p = -1 # start here + while (n != s) { # until survivor count is met + found = 0 # start looking + while (found != k) { # until we have the k-th prisoner + if (++p == nn) { p = 0 } # wrap around + if (dead[p] != 1) { found++ } # if prisoner is alive increment found + } + dead[p] = 1 # kill the unlucky one + killed = killed p " " # build killed list + n-- # reduce size of circle + } + for (i=0; i<=nn-1; i++) { + if (dead[i] != 1) { + survived = survived i " " # build survivor list + } + } + printf("killed: %s\n",killed) + printf("survived: %s\n",survived) + return(1) +} diff --git a/Task/Josephus-problem/D/josephus-problem.d b/Task/Josephus-problem/D/josephus-problem.d index ab2546044c..2680bfb656 100644 --- a/Task/Josephus-problem/D/josephus-problem.d +++ b/Task/Josephus-problem/D/josephus-problem.d @@ -7,7 +7,7 @@ T pop(T)(ref T[] items, in size_t i) pure { return aux; } -string josephus(in int n, in int k) /*pure*/ { +string josephus(in int n, in int k) pure { auto p = n.iota.array; int i; int[] seq; diff --git a/Task/Josephus-problem/Forth/josephus-problem.fth b/Task/Josephus-problem/Forth/josephus-problem.fth new file mode 100644 index 0000000000..85d66fb4fc --- /dev/null +++ b/Task/Josephus-problem/Forth/josephus-problem.fth @@ -0,0 +1 @@ +: josephus 0 1 begin dup 41 <= while swap 3 + over mod swap 1+ repeat drop ; diff --git a/Task/Josephus-problem/Groovy/josephus-problem.groovy b/Task/Josephus-problem/Groovy/josephus-problem.groovy new file mode 100644 index 0000000000..4478a1d728 --- /dev/null +++ b/Task/Josephus-problem/Groovy/josephus-problem.groovy @@ -0,0 +1,36 @@ +int[] Josephus (int size, int kill, int survivors) { + // init user pool + def users = new int[size]; + + // give initial values such that [0] = 1 (first person) [1] = 2 (second person) etc + users.eachWithIndex() {obj, i -> users[i] = i + 1}; + + // keep track of which person we are on (ranging from 1 to kill) + def person = 1; + + // keep going until we have the desired number of survivors + while (users.size() > survivors) + { + // for each person, if they are the kill'th person, set them to -1 to show eliminated + users.eachWithIndex() {obj, i -> + if (person++ % kill == 0) { + users[i] = -1; + } + + // if person overflowed kill then reset back to 1 + if (person > kill) {person = 1;} + } + + // clear out all eliminated persons + users = users.findAll{w -> w >= 0}; + } + + // resulting set is the safe positions + return users; +} + +// Run some test cases + +println "Final survivor for n = 10201 and k = 17: " + Josephus(10201,17,1)[0]; + +println "4 safe spots for n = 10201 and k = 17: " + Josephus(10201,17,4); diff --git a/Task/Josephus-problem/Lua/josephus-problem.lua b/Task/Josephus-problem/Lua/josephus-problem.lua new file mode 100644 index 0000000000..6d4ea1adc2 --- /dev/null +++ b/Task/Josephus-problem/Lua/josephus-problem.lua @@ -0,0 +1,24 @@ +function josephus(n, k, m) + local positions={} + for i=1,n do + table.insert(positions, i-1) + end + local i,j=1,1 + local s='Execution order: ' + while #positions>m do + if j==k then + s=s .. positions[i] .. ', ' + table.remove(positions, i) + i=i-1 + end + i=i+1 + j=j+1 + if i>#positions then i=1 end + if j>k then j=1 end + end + print(s:sub(1,#s-2) .. '.') + local s='Survivors: ' + for _,v in pairs(positions) do s=s .. v .. ', ' end + print(s:sub(1,#s-2) .. '.') +end +josephus(41,3, 1) diff --git a/Task/Josephus-problem/REBOL/josephus-problem-1.rebol b/Task/Josephus-problem/REBOL/josephus-problem-1.rebol new file mode 100644 index 0000000000..a8d65c5e02 --- /dev/null +++ b/Task/Josephus-problem/REBOL/josephus-problem-1.rebol @@ -0,0 +1,13 @@ +Rebol [] + +execute: func [death-list [block!] kill [integer!]] [ + assert [not empty? death-list] + until [ + loop kill - 1 [append death-list take death-list] + (1 == length? remove death-list) + ] +] + +prisoner: [] for n 0 40 1 [append prisoner n] +execute prisoner 3 +print ["Prisoner" prisoner "survived"] diff --git a/Task/Josephus-problem/REBOL/josephus-problem-2.rebol b/Task/Josephus-problem/REBOL/josephus-problem-2.rebol new file mode 100644 index 0000000000..e19e1638a7 --- /dev/null +++ b/Task/Josephus-problem/REBOL/josephus-problem-2.rebol @@ -0,0 +1,3 @@ +for-the-chop: [Joe Jack William Averell Rantanplan] +execute for-the-chop 2 +print [for-the-chop "survived"] diff --git a/Task/Joystick-position/Applesoft-BASIC/joystick-position.applesoft b/Task/Joystick-position/Applesoft-BASIC/joystick-position.applesoft new file mode 100644 index 0000000000..f0ca79e2a4 --- /dev/null +++ b/Task/Joystick-position/Applesoft-BASIC/joystick-position.applesoft @@ -0,0 +1,38 @@ +100 GOSUB 400 +110 P2 = PDL(2) : IF P2 <> O2 THEN O2 = P2 : VTAB 23 : HTAB 33 : PRINT P2; TAB(37); +120 B2 = FNB(2) : IF B2 <> N2 THEN N2 = B2 : VTAB 24 : HTAB 15 : PRINT P$(B2); +130 P3 = PDL(3) : IF P3 <> O3 THEN O3 = P3 : VTAB 23 : HTAB 37 : PRINT P3; : CALL -868 +140 X = INT(P3 * RX) : Y = INT(P2 * RY(F)) +150 O = (X1 = X2 AND Y1 = Y2) + 1 +160 N = (X = X1 AND Y = Y1) + 1 +170 IF X <> X2 OR Y <> Y2 THEN XDRAW N AT X, Y : XDRAW O AT X2, Y2 : X2 = X : Y2 = Y : O = N +200 P0 = PDL(0) : IF P0 <> O0 THEN O0 = P0 : VTAB 22 : HTAB 33 : PRINT P0; TAB(37); +210 B0 = FNB(0) : IF B0 <> N0 THEN N0 = B0 : VTAB 22 : HTAB 15 : PRINT P$(B0); +220 P1 = PDL(1) : IF P1 <> O1 THEN O1 = P1 : VTAB 22 : HTAB 37 : PRINT P1; : CALL -868 +230 B1 = FNB(1) : IF B1 <> N1 THEN N1 = B1 : VTAB 23 : HTAB 15 : PRINT P$(B1); +240 X = INT(P0 * RX) : Y = INT(P1 * RY(F)) +250 O = (X1 = X2 AND Y1 = Y2) + 1 +260 N = (X = X2 AND Y = Y2) + 1 +270 IF X <> X1 OR Y <> Y1 THEN XDRAW N AT X, Y : XDRAW O AT X1, Y1 : X1 = X : Y1 = Y +300 K = PEEK(-16384) : IF K < 128 THEN 110 +310 POKE-16368,0 +320 IF K = 198 OR K = 200 THEN F = PEEK(-16302) ^ 0 : GOTO 110HIDE +330 IF K = 155 OR K = 211 THEN F = PEEK(-16301) * 0 : GOTO 110SHOW +340 TEXT : END +400 HOME : HGR +410 DEF FN B(B) = PEEK(49249 + B) > 127 +420 P$(0) = "NOT PRESSED" : P$(1) = "PRESSED " +430 VTAB 21 : PRINT "BUTTON:"; +440 PRINT TAB(28); "JOYSTICK:" +450 PRINT " OPEN APPLE "P$(0); +460 PRINT TAB(29); "ONE" +470 PRINT " CLOSED APPLE "P$(0); +480 PRINT TAB(29); "TWO" +490 PRINT TAB(9); "SHIFT "P$(0); +500 RX = 35 / 32 : RY(0) = 5 / 8 : RY(1) = 3 / 4 +510 DATA2,0,6,0,3,0,29,15,20,6,0 +520 FOR I = 768 TO 778 : READ B +530 POKE I, B : NEXT : POKE 232, 0 : POKE 233, 3 +550 ROT = 0 : SCALE = 7 : XDRAW 1 AT X1, Y1 +560 O0 = -1 : O1 = O0 : O2 = O0 : O3 = O0 +570 RETURN diff --git a/Task/Jump-anywhere/BASIC/jump-anywhere-3.basic b/Task/Jump-anywhere/BASIC/jump-anywhere-3.basic new file mode 100644 index 0000000000..18c9ed0bb0 --- /dev/null +++ b/Task/Jump-anywhere/BASIC/jump-anywhere-3.basic @@ -0,0 +1,22 @@ + 0 REM GOTO +100 GOTO 110 : REM JUMP TO A SPECIFIC LINE +110 RUN 120 : REM START THE PROGRAM RUNNING FROM A SPECIFIC LINE +120 IF 1 GOTO 130 : REM CONDITIONAL JUMP +130 IF 1 THEN 140 : REM THEN ALSO WORKS IN PLACE OF GOTO +140 IF 1 THEN GOTO 150 : REM BE VERBOSE BY USING THEN GOTO +150 ON A GOTO 170, 180, 190 : REM JUMP A SPECIFIC LINE NUMBER IN THE LIST INDEXED BY THE VALUE OF A STARTING AT 1, IF A IS OUT OF RANGE DO NOT JUMP +160 ON ERR GOTO 270 : REM WHEN AN ERROR OCCURS JUMP TO A SPECIFIC LINE +170 GOSUB 180 : REM JUMP TO LINE 180, PUSHING THE CURRENT PLACE ON THE STACK +180 POP : REM POP THE CURRENT PLACE FROM THE STACK, EFFECTIVELY MAKING THE PREVIOUS LINE A JUMP +190 CALL -151 : REM CALL ANY MACHINE LANGUAGE SUBROUTINE, IT MIGHT RETURN, IT MIGHT NOT +200 & : REM CALL THE USER-DEFINED AMPERSAND ROUTINE, IT MIGHT RETURN, IT MIGHT NOT +210 ? USR(0) : REM CALL THE USER-DEFINED FUNCTION, IT MIGHT RETURN, IT MIGHT NOT +220 S = 6 : ?CHR$(4)"PR#"S : REM CALL THE ROM ROUTINE IN SLOT S +230 S = 6 : ?CHR$(4)"IN#"S : REM CALL THE ROM ROUTINE IN SLOT S +240 ?CHR$(4)"RUN PROGRAM" : REM RUN A BASIC PROGRAM FROM DISK +250 ?CHR$(4)"BRUN BINARY PROGRAM": REM RUN A MACHINE LANGUAGE BINARY PROGRAM FROM DISK +260 ?CHR$(4)"EXEC PROGRAM.EX" : REM EXECUTE THE TEXT THAT IS CONTAINED IN THE FILE PROGRAM.EX +270 RESUME : REM JUMP BACK TO THE STATEMENT THAT CAUSED THE ERROR +280 STOP : REM BREAK THE PROGRAM +290 END : REM END THE PROGRAM +300 GOTO : REM NO LINE NUMBER, JUMPS TO LINE 0 diff --git a/Task/Jump-anywhere/BASIC/jump-anywhere-4.basic b/Task/Jump-anywhere/BASIC/jump-anywhere-4.basic new file mode 100644 index 0000000000..c00991c827 --- /dev/null +++ b/Task/Jump-anywhere/BASIC/jump-anywhere-4.basic @@ -0,0 +1 @@ +CONT : REM CONTINUE, JUMP BACK TO WHERE THE PROGRAM STOPPED diff --git a/Task/Jump-anywhere/BASIC/jump-anywhere-5.basic b/Task/Jump-anywhere/BASIC/jump-anywhere-5.basic new file mode 100644 index 0000000000..4fd97e55e1 --- /dev/null +++ b/Task/Jump-anywhere/BASIC/jump-anywhere-5.basic @@ -0,0 +1,20 @@ +for i = 1 to 10 + if i = 5 then goto [label5] +next i +end + +[label5] +print i +while i < 10 + if i = 6 then goto [label6] +i = i + 1 +wend +end + +[label6] +print i +if i = 6 then goto [finish] +print "Why am I here" + +[finish] + print "done" diff --git a/Task/Jump-anywhere/Deja-Vu/jump-anywhere.djv b/Task/Jump-anywhere/Deja-Vu/jump-anywhere.djv new file mode 100644 index 0000000000..72b8232feb --- /dev/null +++ b/Task/Jump-anywhere/Deja-Vu/jump-anywhere.djv @@ -0,0 +1,8 @@ +example: + !print "First part" + yield + !print "Second part" + +local :continue example +!print "Interrupted" +continue diff --git a/Task/K-means++-clustering/D/k-means++-clustering.d b/Task/K-means++-clustering/D/k-means++-clustering.d index 5012bb18af..cbc6331606 100644 --- a/Task/K-means++-clustering/D/k-means++-clustering.d +++ b/Task/K-means++-clustering/D/k-means++-clustering.d @@ -15,7 +15,7 @@ in { assert(result.length == nPoints); foreach (const ref p; result) { assert(p.cluster == 0); - assert(!isNaN(p.x) && !isNaN(p.y)); + assert(!p.x.isNaN && !p.y.isNaN); } } body { Point[] points; @@ -23,10 +23,9 @@ in { // This is not a uniform 2D distribution. foreach (immutable i; 0 .. nPoints) { - immutable double r = uniform(0.0, radius, rnd); - immutable double ang = uniform(0.0, 2 * PI, rnd); - // Can't use normal array assign because x,y are immutable. - points ~= Point(r * cos(ang), r * sin(ang)); // sincos? + immutable r = uniform(0.0, radius, rnd); + immutable ang = uniform(0.0, 2 * PI, rnd); + points ~= Point(r * ang.cos, r * ang.sin); // Sincos? } return points; @@ -49,11 +48,11 @@ in { assert(points.length >= nclusters); assert(nclusters > 0); foreach (const ref p; points) - assert(!isNaN(p.x) && !isNaN(p.y)); + assert(!p.x.isNaN && !p.y.isNaN); } out(result) { assert(result.length == nclusters); foreach (const ref cc; result) - assert(!isNaN(cc.x) && !isNaN(cc.y)); + assert(!cc.x.isNaN && !cc.y.isNaN); } body { /// Distance and index of the closest cluster center. static Tuple!(size_t, double) @@ -64,20 +63,19 @@ in { } out(result) { assert(result[0] < centers.length); immutable ClusterCenter c = centers[result[0]]; - /*immutable*/ - double d = (c.x - point.x) ^^ 2 + (c.y - point.y) ^^ 2; - assert(feqrel(cast(double)result[1], d) > 45); // Arbitrary. + immutable d = (c.x - point.x) ^^ 2 + (c.y - point.y) ^^ 2; + assert(feqrel(cast()result[1], cast()d) > 45); // Arbitrary. } body { static double sqrDistance2D(in ref ClusterCenter a, in ref Point b) pure nothrow { - return (a.x - b.x) ^^ 2 + (a.y - b.y) ^^ 2; + return (a.x - b.x) ^^ 2 + (a.y - b.y) ^^ 2; } size_t minIndex = point.cluster; double minDist = double.max; foreach (immutable i, const ref cc; centers) { - immutable double d = sqrDistance2D(cc, point); + immutable d = sqrDistance2D(cc, point); if (minDist > d) { minDist = d; minIndex = i; @@ -162,16 +160,15 @@ in { void printEps(in Point[] points, in ClusterCenter[] centers, - immutable size_t W = 400, - immutable size_t H = 400) nothrow + in size_t W = 400, in size_t H = 400) nothrow in { assert(points.length >= centers.length); assert(centers.length > 0); assert(W > 0 && H > 0); foreach (const ref p; points) - assert(!isNaN(p.x) && !isNaN(p.y)); + assert(!p.x.isNaN && !p.y.isNaN); foreach (const ref cc; centers) - assert(!isNaN(cc.x) && !isNaN(cc.y)); + assert(!cc.x.isNaN && !cc.y.isNaN); } body { auto findBoundingBox() nothrow { double min_x, max_x, min_y, max_y; @@ -187,8 +184,7 @@ in { assert(max_x > min_x && max_y > min_y); return tuple(min(W / (max_x - min_x), H / (max_y - min_y)), - (max_x + min_x) / 2, - (max_y + min_y) / 2); + (max_x + min_x) / 2, (max_y + min_y) / 2); } //immutable (scale, cx, cy) = findBoundingBox(); immutable sc_cx_cy = findBoundingBox(); @@ -231,14 +227,14 @@ in { (cc.y - cy) * scale + H / 2); } - printf("\n%%%%EOF"); + "\n%%%%EOF".printf; } void main() { enum size_t nPoints = 100_000; enum size_t nClusters = 11; // k. - auto rnd = Xorshift(1); // For speed and repeatability. + auto rnd = 1.Xorshift; // For speed and repeatability. auto points = generatePoints(nPoints, 10, rnd); const clusterCenters = lloyd(points, nClusters, rnd); diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/Scala/keyboard-input-flush-the-keyboard-buffer.scala b/Task/Keyboard-input-Flush-the-keyboard-buffer/Scala/keyboard-input-flush-the-keyboard-buffer.scala new file mode 100644 index 0000000000..26cf66b40c --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/Scala/keyboard-input-flush-the-keyboard-buffer.scala @@ -0,0 +1 @@ +def flush() { out.flush() } diff --git a/Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check-1.basic b/Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check-1.basic new file mode 100644 index 0000000000..84ac017bbe --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check-1.basic @@ -0,0 +1 @@ +K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(K) diff --git a/Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check.basic b/Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check-2.basic similarity index 100% rename from Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check.basic rename to Task/Keyboard-input-Keypress-check/BASIC/keyboard-input-keypress-check-2.basic diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/AWK/keyboard-input-obtain-a-y-or-n-response.awk b/Task/Keyboard-input-Obtain-a-Y-or-N-response/AWK/keyboard-input-obtain-a-y-or-n-response.awk new file mode 100644 index 0000000000..aa1a7d67e4 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/AWK/keyboard-input-obtain-a-y-or-n-response.awk @@ -0,0 +1,17 @@ +# syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK +BEGIN { + printf("you entered %s\n",prompt_user()) + exit(0) +} +function prompt_user( rec) { +# AWK lacks the ability to get keyboard input without pressing the enter key. + while (1) { + printf("enter Y or N ") + getline rec <"con" + gsub(/ /,"",rec) # optional + if (rec ~ /^[nyNY]$/) { + break + } + } + return(rec) +} diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Scala/keyboard-input-obtain-a-y-or-n-response.scala b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Scala/keyboard-input-obtain-a-y-or-n-response.scala new file mode 100644 index 0000000000..d5f0b035e1 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Scala/keyboard-input-obtain-a-y-or-n-response.scala @@ -0,0 +1 @@ + println(if (readBoolean) "Yes typed." else "Something else.") diff --git a/Task/Knapsack-problem-0-1/SQL/knapsack-problem-0-1.sql b/Task/Knapsack-problem-0-1/SQL/knapsack-problem-0-1.sql new file mode 100644 index 0000000000..2dfb8d50ce --- /dev/null +++ b/Task/Knapsack-problem-0-1/SQL/knapsack-problem-0-1.sql @@ -0,0 +1,46 @@ +WITH KnapsackItems (item, [weight], value) AS +( + SELECT 'map',9, 150 + UNION ALL SELECT 'compass',13, 35 + UNION ALL SELECT 'water',153, 200 + UNION ALL SELECT 'sandwich',50, 160 + UNION ALL SELECT 'glucose',15, 60 + UNION ALL SELECT 'tin',68, 45 + UNION ALL SELECT 'banana',27, 60 + UNION ALL SELECT 'apple',39, 40 + UNION ALL SELECT 'cheese',23, 30 + UNION ALL SELECT 'beer',52, 10 + UNION ALL SELECT 'suntan cream',11, 70 + UNION ALL SELECT 'camera',32, 30 + UNION ALL SELECT 'T-shirt',24, 15 + UNION ALL SELECT 'trousers',48, 10 + UNION ALL SELECT 'umbrella',73, 40 + UNION ALL SELECT 'waterproof trousers',42, 70 + UNION ALL SELECT 'waterproof overclothes',43, 75 + UNION ALL SELECT 'note-case',22, 80 + UNION ALL SELECT 'sunglasses',7, 20 + UNION ALL SELECT 'towel',18, 12 + UNION ALL SELECT 'socks',4, 50 + UNION ALL SELECT 'book',30, 10 +) +SELECT * +INTO #KnapsackItems +FROM KnapsackItems; + +WITH UNIQUEnTuples (n, Tuples, ID, [weight], value) AS ( + SELECT 1, CAST(item AS VARCHAR(8000)), item, [weight], value + FROM #KnapsackItems + UNION ALL + SELECT 1 + n.n, t.item + ',' + n.Tuples, item, n.[weight] + t.[weight], n.value + t.value + FROM UNIQUEnTuples n + CROSS APPLY ( + SELECT item, [weight], value + FROM #KnapsackItems t + WHERE t.item < n.ID AND n.[weight] + t.[weight] < 400) t + ) +SELECT TOP 5 * +FROM UNIQUEnTuples +ORDER BY value DESC, n, Tuples; + +GO +DROP TABLE #KnapsackItems; diff --git a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d index aa7dc89783..4785b01030 100644 --- a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d +++ b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d @@ -1,10 +1,10 @@ -import std.stdio, std.algorithm, std.string, std.conv; +import std.stdio, std.algorithm, std.string; struct Item { string name; real amount, value; - @property real valuePerKG() const pure nothrow { + @property real valuePerKG() @safe const pure nothrow { return value / amount; } @@ -14,27 +14,26 @@ struct Item { } } -real sum(string field)(in Item[] items) pure nothrow { +real sumBy(string field)(in Item[] items) @safe pure nothrow { return reduce!("a + b." ~ field)(0.0L, items); } void main() { - Item[] raw = [{"beef", 3.8, 36.0}, - {"pork", 5.4, 43.0}, - {"ham", 3.6, 90.0}, - {"greaves", 2.4, 45.0}, - {"flitch", 4.0, 30.0}, - {"brawn", 2.5, 56.0}, - {"welt", 3.7, 67.0}, - {"salami", 3.0, 95.0}, - {"sausage", 5.9, 98.0}]; - - // Reverse sorted by Value per amount. - const items = raw.sort!q{a.valuePerKG > b.valuePerKG}.release; + const items = [Item("beef", 3.8, 36.0), + Item("pork", 5.4, 43.0), + Item("ham", 3.6, 90.0), + Item("greaves", 2.4, 45.0), + Item("flitch", 4.0, 30.0), + Item("brawn", 2.5, 56.0), + Item("welt", 3.7, 67.0), + Item("salami", 3.0, 95.0), + Item("sausage", 5.9, 98.0)] + .schwartzSort!(it => -it.valuePerKG) + .release; immutable(Item)[] chosen; real space = 15.0; - foreach (item; items) + foreach (const item; items) if (item.amount < space) { chosen ~= item; space -= item.amount; @@ -45,5 +44,5 @@ void main() { writefln("%10s %7s %7s %7s", "ITEM", "AMOUNT", "VALUE", "$/unit"); writefln("%(%s\n%)", chosen); - Item("TOTAL", chosen.sum!"amount", chosen.sum!"value").writeln; + Item("TOTAL", chosen.sumBy!"amount", chosen.sumBy!"value").writeln; } diff --git a/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl b/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl new file mode 100644 index 0000000000..aa2a05f734 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl @@ -0,0 +1,36 @@ +-module( knapsack_problem_continuous ). + +-export( [price_per_weight/1, select/2, task/0] ). + +price_per_weight( Items ) -> [{Name, Weight, Price / Weight} || {Name, Weight, Price} <-Items]. + +select( Max_weight, Items ) -> + {_Remains, Selected_items} = lists:foldr( fun select_until/2, {Max_weight, []}, lists:keysort(3, Items) ), + Selected_items. + +task() -> + Items = items(), + io:fwrite( "The robber takes the following to maximize the value~n" ), + [io:fwrite("~.2f of ~p~n", [Weight, Name]) || {Name, Weight} <- select( 15, price_per_weight(Items) )]. + + + +items() -> + [{"beef", 3.8, 36}, + {"pork", 5.4, 43}, + {"ham", 3.6, 90}, + {"greaves", 2.4, 45}, + {"flitch", 4.0, 30}, + {"brawn", 2.5, 56}, + {"welt", 3.7 , 67}, + {"salami", 3.0, 95}, + {"sausage", 5.9 , 98} + ]. + +select_until( {Name, Weight, _Price}, {Remains, Acc} ) when Remains > 0 -> + Selected_weight = select_until_weight( Weight, Remains ), + {Remains - Selected_weight, [{Name, Selected_weight} | Acc]}; +select_until( _Item, Acc ) -> Acc. + +select_until_weight( Weight, Remains ) when Weight < Remains -> Weight; +select_until_weight( _Weight, Remains ) -> Remains. diff --git a/Task/Knights-tour/Erlang/knights-tour.erl b/Task/Knights-tour/Erlang/knights-tour.erl new file mode 100644 index 0000000000..7f4f099d9b --- /dev/null +++ b/Task/Knights-tour/Erlang/knights-tour.erl @@ -0,0 +1,78 @@ +-module( knights_tour ). + +-export( [display/1, solve/1, task/0] ). + +display( Moves ) -> + %% The knigh walks the moves {Position, Step_nr} order. + %% Top left corner is {$a, 8}, Bottom right is {$h, 1}. + io:fwrite( "Moves:" ), + lists:foldl( fun display_moves/2, erlang:length(Moves), lists:keysort(2, Moves) ), + io:nl(), + [display_row(Y, Moves) || Y <- lists:seq(8, 1, -1)]. + +solve( First_square ) -> + try + bt_loop( 1, next_moves(First_square), [{First_square, 1}] ) + + catch + _:{ok, Moves} -> Moves + + end. + +task() -> + io:fwrite( "Starting {a, 1}~n" ), + Moves = solve( {$a, 1} ), + display( Moves ). + + + +bt( N, Move, Moves ) -> bt_reject( is_not_allowed_knight_move(Move, Moves), N, Move, [{Move, N} | Moves] ). + +bt_accept( true, _N, _Move, Moves ) -> erlang:throw( {ok, Moves} ); +bt_accept( false, N, Move, Moves ) -> bt_loop( N, next_moves(Move), Moves ). + +bt_loop( N, New_moves, Moves ) -> [bt( N+1, X, Moves ) || X <- New_moves]. + +bt_reject( true, _N, _Move, _Moves ) -> backtrack; +bt_reject( false, N, Move, Moves ) -> bt_accept( is_all_knights(Moves), N, Move, Moves ). + +display_moves( {{X, Y}, 1}, Max ) -> + io:fwrite(" ~p. N~c~p", [1, X, Y]), + Max; +display_moves( {{X, Y}, Max}, Max ) -> + io:fwrite(" N~c~p~n", [X, Y]), + Max; +display_moves( {{X, Y}, Step_nr}, Max ) when Step_nr rem 8 =:= 0 -> + io:fwrite(" N~c~p~n~p. N~c~p", [X, Y, Step_nr, X, Y]), + Max; +display_moves( {{X, Y}, Step_nr}, Max ) -> + io:fwrite(" N~c~p ~p. N~c~p", [X, Y, Step_nr, X, Y]), + Max. + +display_row( Row, Moves ) -> + [io:fwrite(" ~2b", [proplists:get_value({X, Row}, Moves)]) || X <- [$a, $b, $c, $d, $e, $f, $g, $h]], + io:nl(). + +is_all_knights( Moves ) when erlang:length(Moves) =:= 64 -> true; +is_all_knights( _Moves ) -> false. + +is_asymetric( Start_column, Start_row, Stop_column, Stop_row ) -> + erlang:abs( Start_column - Stop_column ) =/= erlang:abs( Start_row - Stop_row ). + +is_not_allowed_knight_move( Move, Moves ) -> + no_such_move =/= proplists:get_value( Move, Moves, no_such_move ). + +next_moves( {Column, Row} ) -> + [{X, Y} || X <- next_moves_column(Column), Y <- next_moves_row(Row), is_asymetric(Column, Row, X, Y)]. + +next_moves_column( $a ) -> [$b, $c]; +next_moves_column( $b ) -> [$a, $c, $d]; +next_moves_column( $g ) -> [$e, $f, $h]; +next_moves_column( $h ) -> [$g, $f]; +next_moves_column( C ) -> [C - 2, C - 1, C + 1, C + 2]. + +next_moves_row( 1 ) -> [2, 3]; +next_moves_row( 2 ) -> [1, 3, 4]; +next_moves_row( 7 ) -> [5, 6, 8]; +next_moves_row( 8 ) -> [6, 7]; +next_moves_row( N ) -> [N - 2, N - 1, N + 1, N + 2]. diff --git a/Task/Knuth-shuffle/D/knuth-shuffle-1.d b/Task/Knuth-shuffle/D/knuth-shuffle-1.d index 53bbdc68ba..f56000d2cb 100644 --- a/Task/Knuth-shuffle/D/knuth-shuffle-1.d +++ b/Task/Knuth-shuffle/D/knuth-shuffle-1.d @@ -1,7 +1,7 @@ -import std.stdio, std.random; - void main() { + import std.stdio, std.random; + auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; - a.randomShuffle(); - writeln(a); + a.randomShuffle; + a.writeln; } diff --git a/Task/Knuth-shuffle/D/knuth-shuffle-2.d b/Task/Knuth-shuffle/D/knuth-shuffle-2.d index 7de58d7fdf..34b4ecd81c 100644 --- a/Task/Knuth-shuffle/D/knuth-shuffle-2.d +++ b/Task/Knuth-shuffle/D/knuth-shuffle-2.d @@ -1,12 +1,14 @@ -import std.stdio, std.algorithm, std.random; +import std.stdio, std.algorithm, std.random, std.range; -void shuffle(Range)(Range r) { - foreach_reverse (i; 1 .. r.length) - swap(r[i], r[uniform(0, i + 1)]); +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)]); } void main() { auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; - a.shuffle(); - writeln(a); + a.knuthShuffle; + a.writeln; } diff --git a/Task/Knuth-shuffle/NetRexx/knuth-shuffle.netrexx b/Task/Knuth-shuffle/NetRexx/knuth-shuffle-1.netrexx similarity index 100% rename from Task/Knuth-shuffle/NetRexx/knuth-shuffle.netrexx rename to Task/Knuth-shuffle/NetRexx/knuth-shuffle-1.netrexx diff --git a/Task/Knuth-shuffle/NetRexx/knuth-shuffle-2.netrexx b/Task/Knuth-shuffle/NetRexx/knuth-shuffle-2.netrexx new file mode 100644 index 0000000000..556f505ad8 --- /dev/null +++ b/Task/Knuth-shuffle/NetRexx/knuth-shuffle-2.netrexx @@ -0,0 +1,34 @@ +/* NetRexx ------------------------------------------------------------ +* 08.01.2014 Walter Pachl modified to show state development a la Rexx +*--------------------------------------------------------------------*/ +options replace format comments java crossref savelog symbols nobinary + +import java.util.List + +cards = [String '1','2','3','4','5','6','7','8','9','10'] +cardsLen = cards.length +deck = ArrayList(cardsLen) +loop c_ = 0 to cardsLen - 1 + deck.add(String(cards[c_])) + end c_ + +showHand(deck,'In ') +deck = ArrayList shuffle(deck) +showHand(deck,'Out') +return + +method shuffle(deck = List) public static binary returns List + rn = Random() + dl = deck.size + loop i_ = dl - 1 to 1 by -1 + j_ = rn.nextInt(i_) + __ = deck.get(i_) + deck.set(i_, deck.get(j_)) + deck.set(j_, __) + say i_ j_ ArrayList(deck.subList(0,i_+1)).toString + end i_ + return deck + +method showHand(deck = ArrayList,tag=REXX) public static binary + say tag ArrayList(deck.subList(0,deck.size)).toString + return diff --git a/Task/Knuth-shuffle/PL-I/knuth-shuffle.pli b/Task/Knuth-shuffle/PL-I/knuth-shuffle-1.pli similarity index 100% rename from Task/Knuth-shuffle/PL-I/knuth-shuffle.pli rename to Task/Knuth-shuffle/PL-I/knuth-shuffle-1.pli diff --git a/Task/Knuth-shuffle/PL-I/knuth-shuffle-2.pli b/Task/Knuth-shuffle/PL-I/knuth-shuffle-2.pli new file mode 100644 index 0000000000..4792f8db03 --- /dev/null +++ b/Task/Knuth-shuffle/PL-I/knuth-shuffle-2.pli @@ -0,0 +1,23 @@ + kn: Proc Options(main); + /*-------------------------------------------------------------------- + * 07.01.2014 Walter Pachl translated from REXX version 2 + * Iteration i: only the first i elements are candidates for swapping + *-------------------------------------------------------------------*/ + Dcl T(10) Bin Fixed(15) Init(1,2,3,4,5,6,7,8,9,10); + Dcl (i,j,temp) Bin Fixed(15) init(0); + Dcl h Char(6); + Call show('In',10); /* show start */ + do i = 10 To 2 By -1; /* shuffle */ + j=random()*i+1; + Put string(h)Edit(i,j)(f(2),f(3)); + temp=t(i); t(i)=t(j); t(j)=temp; /* t(i) <-> t(j) */ + Call show(h,i); /* show intermediate states */ + end; + Call show('Out',10); /* show final state */ + + show: Proc(txt,n); + Dcl txt Char(*); + Dcl n Bin Fixed(15); + Put Edit(txt,(t(k) do k=1 To n))(Skip,a(7),10(f(3))); + End; + end; diff --git a/Task/Knuth-shuffle/REXX/knuth-shuffle-1.rexx b/Task/Knuth-shuffle/REXX/knuth-shuffle-1.rexx new file mode 100644 index 0000000000..cbbb6784c1 --- /dev/null +++ b/Task/Knuth-shuffle/REXX/knuth-shuffle-1.rexx @@ -0,0 +1,23 @@ +/*REXX program shuffles a deck of playing cards using the Knuth shuffle.*/ +rank='A 2 3 4 5 6 7 8 9 10 J Q K' /*pips of the playing cards. */ +suit='♣♠♦♥' /*suit " " " " */ +parse arg seed .; if seed\=='' then call random ,,seed /*repeatability?*/ +say '────────────────── getting a new deck out of the box ···' +deck.1='highJoker' /*good decks have a color joker, */ +deck.2='lowJoker' /*··· and a black & white joker. */ +cards=2 /*now, two cards are in the deck.*/ + do j =1 for length(suit) + do k=1 for words(rank); cards=cards+1 + deck.cards=substr(suit,j,1)word(rank,k) + end /*k*/ + end /*j*/ +call showDeck +say '────────────────── shuffling' cards "cards ···" + do s=cards by -1 to 2; rand=random(1,s) + parse value deck.rand deck.s with deck.s deck.rand + /* [↑] swap two cards in the deck*/ + end /*s*/ +call showDeck +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOWDECK subroutine─────────────────*/ +showDeck: _=; do m=1 for cards; _=_ deck.m; end /*m*/; say _; say; return diff --git a/Task/Knuth-shuffle/REXX/knuth-shuffle-2.rexx b/Task/Knuth-shuffle/REXX/knuth-shuffle-2.rexx new file mode 100644 index 0000000000..c10027388b --- /dev/null +++ b/Task/Knuth-shuffle/REXX/knuth-shuffle-2.rexx @@ -0,0 +1,30 @@ +/*REXX program shuffles a deck of playing cards using the Knuth shuffle.*/ +rank = 'ace deuce trey 4 5 6 7 8 9 10 jack queen king' /*use pip names.*/ +suit = 'club spade diamond heart' /* " suit " */ +say '────────────────── getting a new deck out of the box ···' +deck.1 = ' color joker' /*good decks have a color joker, */ +deck.2 = ' b&w joker' /*··· and a black & white joker. */ +cards=2 /*now, two cards are in the deck.*/ + do j =1 for words(suit) + do k=1 for words(rank); cards=cards+1 /*bump counter.*/ + deck.cards=right(word(suit,j),7) word(rank,k) /*assign.*/ + end /*k*/ + end /*j*/ + +call showDeck 'ace' /*inserts blank when ACE is found*/ +say '────────────────── shuffling' cards "cards ···" + + do s=cards by -1 to 2; rand=random(1,s) /*get random number for swap*/ + _=deck.rand; deck.rand=deck.s; deck.s=_ /*swap 2 cards in card deck.*/ + end /*s*/ + +call showDeck +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOWDECK subroutine─────────────────*/ +showDeck: parse arg break; say /*get sep card, shows blank line*/ + do m=1 for cards /*traipse through the deck. */ + if pos(break,deck.m)\==0 then say /*a blank: easier to read cards.*/ + say 'card' right(m,2) '───►' deck.m /*display a particular card. */ + end /*m*/ +say /*show a trailing blank line. */ +return diff --git a/Task/Knuth-shuffle/REXX/knuth-shuffle-3.rexx b/Task/Knuth-shuffle/REXX/knuth-shuffle-3.rexx new file mode 100644 index 0000000000..5c673ced73 --- /dev/null +++ b/Task/Knuth-shuffle/REXX/knuth-shuffle-3.rexx @@ -0,0 +1,23 @@ +/* REXX --------------------------------------------------------------- +* 05.01.2014 Walter Pachl +* borrow one improvement from version 1 +* 06.01.2014 removed -"- (many tests cost more than few "swaps") +*--------------------------------------------------------------------*/ +Call random ,,123456 /* seed for random */ +Do i=1 To 10; a.i=i; End; /* fill array */ +Call show 'In',10 /* show start */ +do i = 10 To 2 By -1 /* shuffle */ + j=random(i-1)+1; + h=right(i,2) right(j,2) + Parse Value a.i a.j With a.j a.i /* a.i <-> a.j */ + Call show h,i /* show intermediate states */ + end; +Call show 'Out',10 /* show fomaö state */ +Exit + +show: Procedure Expose a. +Parse Arg txt,n +ol=left(txt,6); +Do k=1 To n; ol=ol right(a.k,2); End +Say ol +Return diff --git a/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx b/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx deleted file mode 100644 index ebf3dcae29..0000000000 --- a/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx +++ /dev/null @@ -1,37 +0,0 @@ -/*REXX program shuffles a deck of playing cards using the Knuth shuffle.*/ -rank='ace deuce trey 4 5 6 7 8 9 10 jack queen king' -suit='club spade diamond heart' -say '────────────────── getting a new deck out of the box...' -deck.1=' color joker' /*good decks have a color joker, */ -deck.2=' b&w joker' /*∙∙∙ and a black & white joker. */ -cards=2 /*now, two cards are in the deck.*/ - do j =1 for words(suit) - do k=1 for words(rank) - cards=cards+1 - deck.cards=right(word(suit,j),7) word(rank,k) - end /*k*/ - end /*j*/ - -call showDeck 'ace' /*inserts blank when ACE is found*/ -say '────────────────── shuffling' cards "cards..." - - do s=cards by -1 to 1; rand=random(1,s) - if rand\==s then do /*swap two cards in the card deck*/ - _=deck.rand - deck.rand=deck.s - deck.s=_ - end - end /*s*/ - -call showDeck -say '────────────────── ready to play schafkopf (take out jokers first).' -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────SHOWDECK subroutine─────────────────*/ -showDeck: parse arg break; say - do m=1 for cards - if pos(break,deck.m)\==0 then say /*blank, easier to read cards*/ - say 'card' right(m,2) '───►' deck.m - end /*m*/ -say -return diff --git a/Task/Knuth-shuffle/Rust/knuth-shuffle.rust b/Task/Knuth-shuffle/Rust/knuth-shuffle.rust new file mode 100644 index 0000000000..5440c9fdd2 --- /dev/null +++ b/Task/Knuth-shuffle/Rust/knuth-shuffle.rust @@ -0,0 +1,22 @@ +use std::iter; +use std::rand; +use std::rand::Rng; +use std::vec; + +fn knuth_shuffle(v: &mut [T]) { + let mut rng = rand::rng(); + let l = v.len(); + + for n in iter::range(0, l) { + let i = rng.gen_range(0, l - n); + v.swap(i, l - n - 1); + } +} + +fn main() { + let mut v = vec::from_fn(10, |i| i); + + println!("before: {:?}", v); + knuth_shuffle(v); + println!("after: {:?}", v); +} diff --git a/Task/LU-decomposition/D/lu-decomposition.d b/Task/LU-decomposition/D/lu-decomposition.d index 2492490dde..cc940f59a1 100644 --- a/Task/LU-decomposition/D/lu-decomposition.d +++ b/Task/LU-decomposition/D/lu-decomposition.d @@ -28,13 +28,13 @@ in { } /// Creates the pivoting matrix for m. -T[][] pivotize(T)(immutable T[][] m) /*pure nothrow*/ +T[][] pivotize(T)(immutable T[][] m) pure nothrow in { assert(m.isSquare); } body { immutable n = m.length; auto id = iota(n) - .map!(j=> n.iota.map!(i => cast(T)(i == j)).array) + .map!((in j) => n.iota.map!(i => cast(T)(i == j)).array) .array; foreach (immutable i; 0 .. n) { @@ -56,7 +56,7 @@ in { /// Decomposes a square matrix A by PA=LU and returns L, U and P. Tuple!(T[][],"L", T[][],"U", const T[][],"P") -lu(T)(immutable T[][] A) /*pure nothrow*/ +lu(T)(immutable T[][] A) pure nothrow in { assert(A.isSquare); } body { @@ -68,8 +68,8 @@ in { U[i][0 .. i] = 0; } - const P = A.pivotize!T; - const A2 = matrixMul!T(P, A); + immutable P = A.pivotize!T; + immutable A2 = matrixMul!T(P, A); foreach (immutable j; 0 .. n) { L[j][j] = 1; @@ -99,8 +99,7 @@ void main() { [3.0, 17, 18, 1], [2.0, 5, 7, 1]]; - //auto f = "[%([%(%.1f, %)],\n %)]]\n\n".replicate(3); - auto f = std.array.replicate("[%([%(%.1f, %)],\n %)]]\n\n", 3); - foreach (m; [a, b]) + auto f = "[%([%(%.1f, %)],\n %)]]\n\n".replicate(3); + foreach (immutable m; [a, b]) writefln(f, lu(m).tupleof); } diff --git a/Task/LU-decomposition/PL-I/lu-decomposition.pli b/Task/LU-decomposition/PL-I/lu-decomposition.pli new file mode 100644 index 0000000000..f56851743f --- /dev/null +++ b/Task/LU-decomposition/PL-I/lu-decomposition.pli @@ -0,0 +1,87 @@ +(subscriptrange, fofl, size): /* 2 Nov. 2013 */ +LU_Decomposition: procedure options (main); + declare a1(3,3) float (18) initial ( 1, 3, 5, + 2, 4, 7, + 1, 1, 0); + declare a2(4,4) float (18) initial (11, 9, 24, 2, + 1, 5, 2, 6, + 3, 17, 18, 1, + 2, 5, 7, 1); + call check(a1); + call check(a2); + + +/* In-situ decomposition */ +LU: procedure(a, p); + declare a(*,*) float (18); + declare p(*) fixed binary; + declare (maximum, rtemp) float (18); + declare (n, i, j, k, ii, temp) fixed binary; + + n = hbound(a,1); + do i = 1 to n; p(i) = i; end; + + do k = 1 to n-1; + + maximum = 0; ii = k; + do i = k to n; + if maximum < abs(a(p(i),k)) then + do; maximum = abs(a(p(i),k)); ii = i; end; + end; + if ii ^= k then do; temp = p(k); p(k) = p(ii); p(ii) = temp; end; + + do i = k+1 to n; a(p(i),k) = a(p(i),k) / a(p(k),k); end; + + do j = k+1 to n; + do i = k+1 to n; + a(p(i),j) = a(p(i),j) - a(p(i),k) * a(p(k),j); + end; + end; + + end; +end LU; + +CHECK: procedure(a); + declare a(*,*) float (18) nonassignable; + + declare aa(hbound(a,1), hbound(a,2)) float (18); + declare L(hbound(a,1), hbound(a,2)) float (18); + declare U(hbound(a,1), hbound(a,2)) float (18); + declare (p(hbound(a,1), hbound(a,2)), ipiv(hbound(a,1)) ) fixed binary; + declare pp(hbound(a,1), hbound(a,2)) fixed binary; + declare (i, j, n, temp(hbound(a,1))) fixed binary; + + n = hbound(a,1); + aa = A; /* work with a copy */ + P = 0; L = 0; U = 0; + do i = 1 to n; + p(i,i) = 1; L(i,i) = 1; /* convert permutation vector to a matrix */ + end; + + call LU(aa, ipiv); + + do i = 1 to n; + do j = 1 to i-1; L(i,j) = aa(ipiv(i),j); end; + do j = i to n; U(i,j) = aa(ipiv(i),j); end; + end; + + pp = p; + do i = 1 to n; + p(ipiv(i), *) = pp(i,*); + end; + + put skip list ('A'); + put edit (A) (skip, (n) f(10,5)); + + put skip list ('P'); + put edit (P) (skip, (n) f(11)); + + put skip list ('L'); + put edit (L) (skip, (n) f(10,5)); + + put skip list ('U'); + put edit (U) (skip, (n) f(10,5)); + +end CHECK; + +end LU_Decomposition; diff --git a/Task/LU-decomposition/Python/lu-decomposition.py b/Task/LU-decomposition/Python/lu-decomposition.py index 80c649fe40..82772b74fd 100644 --- a/Task/LU-decomposition/Python/lu-decomposition.py +++ b/Task/LU-decomposition/Python/lu-decomposition.py @@ -9,7 +9,7 @@ def pivotize(m): n = len(m) ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)] for j in xrange(n): - row = max(xrange(j, n), key=lambda i: m[i][j]) + row = max(xrange(j, n), key=lambda i: abs(m[i][j])) if j != row: ID[j], ID[row] = ID[row], ID[j] return ID diff --git a/Task/LZW-compression/D/lzw-compression-2.d b/Task/LZW-compression/D/lzw-compression-2.d index a8e5448136..6529c7801a 100644 --- a/Task/LZW-compression/D/lzw-compression-2.d +++ b/Task/LZW-compression/D/lzw-compression-2.d @@ -1,6 +1,6 @@ -import std.array: empty; - struct LZW { + import std.array: empty; + // T is ubyte instead of char because D strings are UTF-8. alias T = ubyte; alias Tcomp = ushort; @@ -11,12 +11,11 @@ struct LZW { static immutable ubyte[initDictSize] bytes; static this() { foreach (immutable i; 0 .. initDictSize) - bytes[i] = cast(T)i; + bytes[i] = cast(T)i; //* } - //static Tcomp[] compress(in T[] original) - static Tcomp[] compress(immutable scope T[] original) - /*pure nothrow*/ out(result) { + static Tcomp[] compress(immutable scope T[] original) pure nothrow + out(result) { if (!original.empty) assert(result[0] < initDictSize); } body { @@ -26,7 +25,7 @@ struct LZW { foreach (immutable b; bytes) dict[[b]] = b; - // In this algorithm regular slices give lower efficiency. + // Here built-in slices give lower efficiency. struct Slice { size_t start, end; @property opSlice() const pure nothrow { @@ -38,16 +37,13 @@ struct LZW { Slice w; Tcomp[] result; foreach (immutable i; 0 .. original.length) { - auto wc = Slice(w.start, w.end + 1); + auto wc = Slice(w.start, w.end + 1); // Extend slice. if (wc in dict) { w = wc; } else { result ~= dict[w]; - // AA.length is not pure nor nothrow. - //assert(dict.length <= Tcomp.max); - //dict[wc] = cast(Tcomp)dict.length; assert(dict.length < Tcomp.max); // Overflow guard. - dict[wc] = cast(Tcomp)(dict.length - 1); + dict[wc] = cast(Tcomp)dict.length; w = Slice(i, i + 1); } } @@ -90,10 +86,11 @@ struct LZW { } void main() { - import std.stdio; + import std.stdio, std.string; + immutable txt = "TOBEORNOTTOBEORTOBEORNOT"; - /*immutable*/ const compressed = LZW.compress(cast(LZW.Ta)txt); - writeln(compressed); - immutable decompressed = LZW.decompress(compressed); - writeln(cast(string)decompressed); + immutable compressed = LZW.compress(txt.representation); + compressed.writeln; + //LZW.decompress(compressed).unrepresentation.writeln; + writeln(cast(string)LZW.decompress(compressed)); } diff --git a/Task/Langtons-ant/AutoIt/langtons-ant.autoit b/Task/Langtons-ant/AutoIt/langtons-ant.autoit new file mode 100644 index 0000000000..4d4a9625b0 --- /dev/null +++ b/Task/Langtons-ant/AutoIt/langtons-ant.autoit @@ -0,0 +1,76 @@ +Global $iCountMax = 100000 +Global $aFields[100][100][2] +Global $iDelayStep = 10 ; stop between steps in msec + +Global $aDirection[4][4] = [ _ ; [ direction 0-3 ][ left change x, y, right change x, y ] +[-1, 0, +1, 0], _ ; == direction 0 +[ 0, -1, 0, +1], _ ; == direction 1 +[+1, 0, -1, 0], _ ; == direction 2 +[ 0, +1, 0, -1]] ; == direction 3 + +Global $hGui = GUICreate("Langton's ant", 100*8, 100*8) +GUISetBkColor(0xFFFFFF) + +For $i = 0 To 99 + For $j = 0 To 99 + $aFields[$i][$j][0] = GUICtrlCreateLabel('', $j*8, $i*8) + GUICtrlSetColor(-1, 0xFF0000) + $aFields[$i][$j][1] = 0 + Next +Next + +GUISetState() + +GUICtrlSetData($aFields[49][49][0], '#') + +Do + Sleep($iDelayStep) +Until Not _SetAnt() + +Do +Until GUIGetMsg() = -3 + + +Func _SetAnt() + Local Static $iRowLast = 49, $iColLast = 49, $iCount = 0 + Local Static $aCol[2] = [0xFFFFFF,0x000000], $iDirection = 0 + Local $iRow, $iCol, $fRight = False + If $iCount = $iCountMax Then Return 0 + + ; == get current color + Local $iLastColor = $aFields[$iRowLast][$iColLast][1] + + ; == go to left/right + If $iLastColor = 0 Then $fRight = True + + ; == set the ant to the next field + Local $indexX = 0, $indexY = 1 + If $fRight Then + $indexX = 2 + $indexY = 3 + EndIf + $iRow = $iRowLast + ($aDirection[$iDirection][$indexX]) + $iCol = $iColLast + ($aDirection[$iDirection][$indexY]) + If $iRow < 0 Or $iRow > 99 Or $iCol < 0 Or $iCol > 99 Then Return 0 + GUICtrlSetData($aFields[$iRowLast][$iColLast][0], '') + GUICtrlSetData($aFields[$iRow][$iCol][0], '#') + + ; == direction for next step + If $fRight Then + $iDirection += 1 + If $iDirection = 4 Then $iDirection = 0 + Else + $iDirection -= 1 + If $iDirection = -1 Then $iDirection = 3 + EndIf + + ; == change the color of the current field + GUICtrlSetBkColor($aFields[$iRowLast][$iColLast][0], $aCol[(Not $iLastColor)*1]) + $aFields[$iRowLast][$iColLast][1] = (Not $iLastColor)*1 + + $iRowLast = $iRow + $iColLast = $iCol + $iCount += 1 + WinSetTitle($hGui, '', "Langton's ant [ step: " & StringFormat('%06d', $iCount) & " ]") + Return 1 +EndFunc ;==>_SetAnt diff --git a/Task/Langtons-ant/Perl/langtons-ant.pl b/Task/Langtons-ant/Perl/langtons-ant.pl index 6cb8e4868c..589f99b7f6 100644 --- a/Task/Langtons-ant/Perl/langtons-ant.pl +++ b/Task/Langtons-ant/Perl/langtons-ant.pl @@ -21,7 +21,7 @@ my $dir = int rand @dirs; my $move; for ($move = 0; $x >= 0 && $x < $size && $y >= 0 && $y < $size; $move++) { # toggle cell's value (white->black or black->white) - if ($plane[$x][$y] = 1 - $plane[$x][$y]) { + if ($plane[$x][$y] = 1 - ($plane[$x][$y] ||= 0)) { # if it's now true (black), then it was white, so turn right $dir = ($dir - 1) % @dirs; } else { diff --git a/Task/Langtons-ant/Processing/langtons-ant b/Task/Langtons-ant/Processing/langtons-ant index 81ee466db2..e14d3a7cfc 100644 --- a/Task/Langtons-ant/Processing/langtons-ant +++ b/Task/Langtons-ant/Processing/langtons-ant @@ -1,6 +1,6 @@ /* * we use the following conventions: - * directions 0: up, 1: right, 2: down: 3: left + * directions 0: up, 1: left, 2: down: 3: right * * pixel white: true, black: false * @@ -36,7 +36,7 @@ int count=0; void draw() { for(int i=0;i 0 & p[1] <= n & p[2] > 0 & p[2] <= n) { + if(map[p[1], p[2]] == 1) { + map[p[1], p[2]] = 0 + p = p + switch(d, c(0, 1), c(-1, 0), c(0, -1), c(1, 0)) + d = ifelse(d == 4, 1, d + 1) + } else { + map[p[1], p[2]] = 1 + p = p + switch(d, c(0, -1), c(1, 0), c(0, 1), c(-1, 0)) + d = ifelse(d == 1, 4, d - 1) + } + } + return(map) +} + +image(langton.ant(), xaxt = "n", yaxt = "n", bty = "n") diff --git a/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-1.l b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-1.l new file mode 100644 index 0000000000..f0572c96e9 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-1.l @@ -0,0 +1 @@ +(load "@lib/simul.l") # For 'permute' diff --git a/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-2.l b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-2.l new file mode 100644 index 0000000000..04093324c0 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-2.l @@ -0,0 +1,2 @@ +(for L '((1 34 3 98 9 76 45 4) (54 546 548 60)) + (prinl (maxi format (permute L))) ) diff --git a/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-3.l b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-3.l new file mode 100644 index 0000000000..6b9ed6f3a9 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-3.l @@ -0,0 +1,7 @@ +(for L '((1 34 3 98 9 76 45 4) (54 546 548 60)) + (prinl + (sort L + '((A B) + (> + (format (pack A B)) + (format (pack B A)) ) ) ) ) ) diff --git a/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-4.l b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-4.l new file mode 100644 index 0000000000..d59638337d --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/PicoLisp/largest-int-from-concatenated-ints-4.l @@ -0,0 +1,4 @@ +(for L '((1 34 3 98 9 76 45 4) (54 546 548 60)) + (prinl + (flip + (by '((N) (apply circ (chop N))) sort L) ) ) ) diff --git a/Task/Largest-int-from-concatenated-ints/Prolog/largest-int-from-concatenated-ints-1.pro b/Task/Largest-int-from-concatenated-ints/Prolog/largest-int-from-concatenated-ints-1.pro new file mode 100644 index 0000000000..ef082f87dc --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Prolog/largest-int-from-concatenated-ints-1.pro @@ -0,0 +1,9 @@ +largest_int_v1(In, Out) :- + maplist(name, In, LC), + aggregate(max(V), get_int(LC, V), Out). + + +get_int(LC, V) :- + permutation(LC, P), + append(P, LV), + name(V, LV). diff --git a/Task/Largest-int-from-concatenated-ints/Prolog/largest-int-from-concatenated-ints-2.pro b/Task/Largest-int-from-concatenated-ints/Prolog/largest-int-from-concatenated-ints-2.pro new file mode 100644 index 0000000000..e297a42da2 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Prolog/largest-int-from-concatenated-ints-2.pro @@ -0,0 +1,35 @@ +largest_int_v2(In, Out) :- + maplist(name, In, LC), + predsort(my_sort,LC, LCS), + append(LCS, LC1), + name(Out, LC1). + + +my_sort(R, L1, L2) :- + append(L1, L2, V1), name(I1, V1), + append(L2, L1, V2), name(I2, V2), + ( I1 < I2, R = >; I1 = I2, R = '='; R = <). + + + +% particular case 95 958 +my_sort(>, [H1], [H1, H2 | _]) :- + H1 > H2. + +my_sort(<, [H1], [H1, H2 | _]) :- + H1 < H2. + +my_sort(R, [H1], [H1, H1 | T]) :- + my_sort(R, [H1], [H1 | T]). + + + +% particular case 958 95 +my_sort(>, [H1, H2 | _], [H1]) :- + H1 > H2. + +my_sort(<, [H1, H2 | _], [H1]) :- + H1 < H2. + +my_sort(R, [H1, H1 | T], [H1]) :- + my_sort(R, [H1 | T], [H1]) . diff --git a/Task/Last-Friday-of-each-month/AutoIt/last-friday-of-each-month.autoit b/Task/Last-Friday-of-each-month/AutoIt/last-friday-of-each-month.autoit new file mode 100644 index 0000000000..fe1392e0e6 --- /dev/null +++ b/Task/Last-Friday-of-each-month/AutoIt/last-friday-of-each-month.autoit @@ -0,0 +1,22 @@ +#include + +$iYear = InputBox('Last Friday in each month', 'Please input the year:') + +_GetLastFridays($iYear) + +Func _GetLastFridays($_iYear) + Local $sResult = 'last fridays in ' & $_iYear & @LF, $iDay + Local $aDaysInMonth[12] = [31,28,31,30,31,30,31,31,30,31,30,31] + If _DateIsLeapYear($_iYear) Then $aDaysInMonth[1] = 29 + For $i = 1 To 12 + $iDay = $aDaysInMonth[$i-1] + While 1 + If _DateToDayOfWeekISO($_iYear, $i, $iDay) = 5 Then + $sResult &= StringFormat('%4d-%02d-%02d', $_iYear, $i, $iDay) & @LF + ExitLoop + EndIf + $iDay -= 1 + WEnd + Next + ConsoleWrite($sResult) +EndFunc ;==>_GetFridays diff --git a/Task/Last-Friday-of-each-month/Groovy/last-friday-of-each-month.groovy b/Task/Last-Friday-of-each-month/Groovy/last-friday-of-each-month.groovy new file mode 100644 index 0000000000..d9b7e11ec4 --- /dev/null +++ b/Task/Last-Friday-of-each-month/Groovy/last-friday-of-each-month.groovy @@ -0,0 +1,3 @@ +def ymd = { it.format('yyyy-MM-dd') } +def lastFridays = lastWeekDays.curry(Day.Fri) +lastFridays(args[0] as int).each { println (ymd(it)) } diff --git a/Task/Last-Friday-of-each-month/J/last-friday-of-each-month-1.j b/Task/Last-Friday-of-each-month/J/last-friday-of-each-month-1.j index 90589cb2b9..000449c354 100644 --- a/Task/Last-Friday-of-each-month/J/last-friday-of-each-month-1.j +++ b/Task/Last-Friday-of-each-month/J/last-friday-of-each-month-1.j @@ -1,2 +1,2 @@ -require'dates' -last_fridays=: 12 {. [:({:/.~ }:"1)@(#~ 5 = weekday)@todate (i.366) + todayno@,&1 1 +require 'dates' +last_fridays=: 12 {. [: ({:/.~ }:"1)@(#~ 5 = weekday)@todate (i.366) + todayno@,&1 1 diff --git a/Task/Last-Friday-of-each-month/PicoLisp/last-friday-of-each-month-1.l b/Task/Last-Friday-of-each-month/PicoLisp/last-friday-of-each-month-1.l index 24e198a569..76c0202e70 100644 --- a/Task/Last-Friday-of-each-month/PicoLisp/last-friday-of-each-month-1.l +++ b/Task/Last-Friday-of-each-month/PicoLisp/last-friday-of-each-month-1.l @@ -1,5 +1,5 @@ (de lastFridays (Y) - (for M `(range 1 12) + (for M 12 (prinl (dat$ (find '((D) (= "Friday" (day D))) diff --git a/Task/Leap-year/AutoIt/leap-year.autoit b/Task/Leap-year/AutoIt/leap-year.autoit index 2c518e8765..836025003b 100644 --- a/Task/Leap-year/AutoIt/leap-year.autoit +++ b/Task/Leap-year/AutoIt/leap-year.autoit @@ -1,15 +1,12 @@ -;AutoIt Version: 3.2.10.0 -$Yr=1600 -ConsoleWrite ($Yr &" is ") -if isLeapYear($Yr) Then - ConsoleWrite ("leap year") -Else - ConsoleWrite ("not leap year") -EndIf +; AutoIt Version: 3.3.8.1 +$Year = 2012 +$sNot = " not" -Func isLeapYear($year) - If IsInt($year/100) Then - Return IsInt($year/400) - EndIf - Return IsInt($year/4) +If IsLeapYear($Year) Then $sNot = "" +ConsoleWrite ($Year & " is" & $sNot & " a leap year." & @LF) + +Func IsLeapYear($_year) + Return Not Mod($_year, 4) And (Mod($_year, 100) Or Not Mod($_year, 400)) EndFunc + +; == But it exists the standard UDF "Date.au3" with this function: "_IsLeapYear($Year)" diff --git a/Task/Leap-year/Clipper/leap-year.clipper b/Task/Leap-year/Clipper/leap-year.clipper new file mode 100644 index 0000000000..7b3a0bb98f --- /dev/null +++ b/Task/Leap-year/Clipper/leap-year.clipper @@ -0,0 +1,2 @@ +Function IsLeapYear( nYear ) +Return Iif( nYear%100 == 0, (nYear%400 == 0), (nYear%4 == 0) ) diff --git a/Task/Leap-year/Java/leap-year.java b/Task/Leap-year/Java/leap-year.java new file mode 100644 index 0000000000..211aae7bbb --- /dev/null +++ b/Task/Leap-year/Java/leap-year.java @@ -0,0 +1,16 @@ +import java.util.GregorianCalendar; +import java.text.MessageFormat; + +public class Leapyear { + public static void main(String[] argv) { + int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100}; + GregorianCalendar cal = new GregorianCalendar(); + for (int year : yrs) { + System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.", year, cal.isLeapYear(year), is_leapyear(year))); + } + + } + public static boolean is_leapyear(int year) { + return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0); + } +} diff --git a/Task/Leap-year/Prolog/leap-year-3.pro b/Task/Leap-year/Prolog/leap-year-3.pro new file mode 100644 index 0000000000..2badacefe9 --- /dev/null +++ b/Task/Leap-year/Prolog/leap-year-3.pro @@ -0,0 +1,2 @@ +?- findall(Y, (between(1990,2030,Y),day_of_the_year(date(Y,12,31),366)), L). +L = [1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028]. diff --git a/Task/Least-common-multiple/AutoIt/least-common-multiple-1.autoit b/Task/Least-common-multiple/AutoIt/least-common-multiple-1.autoit new file mode 100644 index 0000000000..805c750d81 --- /dev/null +++ b/Task/Least-common-multiple/AutoIt/least-common-multiple-1.autoit @@ -0,0 +1,13 @@ +Func _LCM($a, $b) + Local $c, $f, $m = $a, $n = $b + $c = 1 + While $c <> 0 + $f = Int($a / $b) + $c = $a - $b * $f + If $c <> 0 Then + $a = $b + $b = $c + EndIf + WEnd + Return $m * $n / $b +EndFunc ;==>_LCM diff --git a/Task/Least-common-multiple/AutoIt/least-common-multiple-2.autoit b/Task/Least-common-multiple/AutoIt/least-common-multiple-2.autoit new file mode 100644 index 0000000000..c2c88110ab --- /dev/null +++ b/Task/Least-common-multiple/AutoIt/least-common-multiple-2.autoit @@ -0,0 +1,3 @@ +ConsoleWrite(_LCM(12,18) & @LF) +ConsoleWrite(_LCM(-5,12) & @LF) +ConsoleWrite(_LCM(13,0) & @LF) diff --git a/Task/Least-common-multiple/BASIC/least-common-multiple-1.basic b/Task/Least-common-multiple/BASIC/least-common-multiple-1.basic new file mode 100644 index 0000000000..f7c1e715d6 --- /dev/null +++ b/Task/Least-common-multiple/BASIC/least-common-multiple-1.basic @@ -0,0 +1,22 @@ +10 DEF FN MOD(A) = INT((A / B - INT(A / B)) * B + .05) * SGN(A / B) +20 INPUT"M=";M% +30 INPUT"N=";N% +40 GOSUB 100 +50 PRINT R +60 END + +100 REM LEAST COMMON MULTIPLE M% N% +110 R = 0 +120 IF M% = 0 OR N% = 0 THEN RETURN +130 A% = M% : B% = N% : GOSUB 200"GCD +140 R = ABS(M%*N%)/R +150 RETURN + +200 REM GCD ITERATIVE EUCLID A% B% +210 FOR B = B% TO 0 STEP 0 +220 C% = A% +230 A% = B +240 B = FN MOD(C%) +250 NEXT B +260 R = ABS(A%) +270 RETURN diff --git a/Task/Least-common-multiple/BASIC/least-common-multiple-2.basic b/Task/Least-common-multiple/BASIC/least-common-multiple-2.basic new file mode 100644 index 0000000000..6c028c9b40 --- /dev/null +++ b/Task/Least-common-multiple/BASIC/least-common-multiple-2.basic @@ -0,0 +1,11 @@ + DEF FN_LCM(M%,N%) + IF M%=0 OR N%=0 THEN =0 ELSE =ABS(M%*N%)/FN_GCD_Iterative_Euclid(M%, N%) + + DEF FN_GCD_Iterative_Euclid(A%, B%) + LOCAL C% + WHILE B% + C% = A% + A% = B% + B% = C% MOD B% + ENDWHILE + = ABS(A%) diff --git a/Task/Least-common-multiple/D/least-common-multiple.d b/Task/Least-common-multiple/D/least-common-multiple.d index 56456e6f74..a10ee536a4 100644 --- a/Task/Least-common-multiple/D/least-common-multiple.d +++ b/Task/Least-common-multiple/D/least-common-multiple.d @@ -1,24 +1,22 @@ -import std.stdio, std.bigint; +import std.stdio, std.bigint, std.math; -T lcm(T)(/*in*/ T m, /*in*/ T n) /*pure nothrow*/ { - if (m == 0) return m; - if (n == 0) return n; - T r = (m * n) / gcd(m, n); - //return abs(r); - return (r < 0) ? -r : r; -} - -T gcd(T)(/*in*/ T a, /*in*/ T b) /*pure nothrow*/ { - while (b != 0) { - auto t = b; +T gcd(T)(T a, T b) pure /*nothrow*/ { + while (b) { + immutable t = b; b = a % b; a = t; } return a; } -void main() { - writeln(lcm(12, 18)); - writeln(lcm(BigInt("2562047788015215500854906332309589561"), - BigInt("6795454494268282920431565661684282819"))); +T lcm(T)(T m, T n) pure /*nothrow*/ { + if (m == 0) return m; + if (n == 0) return n; + return abs((m * n) / gcd(m, n)); +} + +void main() { + lcm(12, 18).writeln; + lcm("2562047788015215500854906332309589561".BigInt, + "6795454494268282920431565661684282819".BigInt).writeln; } diff --git a/Task/Least-common-multiple/JavaScript/least-common-multiple.js b/Task/Least-common-multiple/JavaScript/least-common-multiple.js new file mode 100644 index 0000000000..20993bb6b1 --- /dev/null +++ b/Task/Least-common-multiple/JavaScript/least-common-multiple.js @@ -0,0 +1,14 @@ +function LCM(A) // A is an integer array (e.g. [-50,25,-45,-18,90,447]) +{ + var n = A.length, a = Math.abs(A[0]); + for (var i = 1; i < n; i++) + { var b = Math.abs(A[i]), c = a; + while (a && b){ a > b ? a %= b : b %= a; } + a = Math.abs(c*A[i])/(a+b); + } + return a; +} + +/* For example: + LCM([-50,25,-45,-18,90,447]) -> 67050 +*/ diff --git a/Task/Least-common-multiple/Julia/least-common-multiple.julia b/Task/Least-common-multiple/Julia/least-common-multiple.julia new file mode 100644 index 0000000000..28a4b387ff --- /dev/null +++ b/Task/Least-common-multiple/Julia/least-common-multiple.julia @@ -0,0 +1 @@ +lcm(m,n) diff --git a/Task/Least-common-multiple/NetRexx/least-common-multiple.netrexx b/Task/Least-common-multiple/NetRexx/least-common-multiple.netrexx new file mode 100644 index 0000000000..94eedfdf25 --- /dev/null +++ b/Task/Least-common-multiple/NetRexx/least-common-multiple.netrexx @@ -0,0 +1,70 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 3000 + +runSample(arg) +return + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +method lcm(m_, n_) public static + L_ = m_ * n_ % gcd(m_, n_) + return L_ + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- Euclid's algorithm - iterative implementation +method gcd(m_, n_) public static + loop while n_ > 0 + c_ = m_ // n_ + m_ = n_ + n_ = c_ + end + return m_ + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg samples + if samples = '' | samples = '.' then + samples = '-6 14 = 42 |' - + '3 4 = 12 |' - + '18 12 = 36 |' - + '2 0 = 0 |' - + '0 85 = 0 |' - + '12 18 = 36 |' - + '5 12 = 60 |' - + '12 22 = 132 |' - + '7 31 = 217 |' - + '117 18 = 234 |' - + '38 46 = 874 |' - + '18 12 -5 = 180 |' - + '-5 18 12 = 180 |' - -- confirm that other permutations work + '12 -5 18 = 180 |' - + '18 12 -5 97 = 17460 |' - + '30 42 = 210 |' - + '30 42 = . |' - -- 210; no verification requested + '18 12' -- 36 + + loop while samples \= '' + parse samples sample '|' samples + loop while sample \= '' + parse sample mnvals '=' chk sample + if chk = '' then chk = '.' + mv = mnvals.word(1) + loop w_ = 2 to mnvals.words mnvals + nv = mnvals.word(w_) + mv = mv.abs + nv = nv.abs + mv = lcm(mv, nv) + end w_ + lv = mv + select case chk + when '.' then state = '' + when lv then state = '(verified)' + otherwise state = '(failed)' + end + mnvals = mnvals.space(1, ',').changestr(',', ', ') + say 'lcm of' mnvals.right(15.max(mnvals.length)) 'is' lv.right(5.max(lv.length)) state + end + end + + return diff --git a/Task/List-comprehensions/Mercury/list-comprehensions.mercury b/Task/List-comprehensions/Mercury/list-comprehensions.mercury new file mode 100644 index 0000000000..7e5d7b01ca --- /dev/null +++ b/Task/List-comprehensions/Mercury/list-comprehensions.mercury @@ -0,0 +1,24 @@ +:- module pythtrip. +:- interface. +:- import_module io. +:- import_module int. + +:- type triple ---> triple(int, int, int). + +:- pred pythTrip(int::in,triple::out) is nondet. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module list. +:- import_module solutions. +:- import_module math. + +pythTrip(Limit,triple(X,Y,Z)) :- + nondet_int_in_range(1,Limit,X), + nondet_int_in_range(X,Limit,Y), + nondet_int_in_range(Y,Limit,Z), + pow(Z,2) = pow(X,2) + pow(Y,2). + +main(!IO) :- + solutions((pred(Triple::out) is nondet :- pythTrip(20,Triple)),Result), + write(Result,!IO). diff --git a/Task/List-comprehensions/PicoLisp/list-comprehensions-4.l b/Task/List-comprehensions/PicoLisp/list-comprehensions-4.l index df3eebb244..d90f96e319 100644 --- a/Task/List-comprehensions/PicoLisp/list-comprehensions-4.l +++ b/Task/List-comprehensions/PicoLisp/list-comprehensions-4.l @@ -2,5 +2,6 @@ (for @X @N) (for @Y @X @N) (for @Z @Y @N) - (@ let (X (-> @X) Y (-> @Y) Z (-> @Z)) - (= (+ (* X X) (* Y Y)) (* Z Z)) ) ) + (^ @ + (let (X (-> @X) Y (-> @Y) Z (-> @Z)) + (= (+ (* X X) (* Y Y)) (* Z Z)) ) ) ) diff --git a/Task/List-comprehensions/Visual-Prolog/list-comprehensions.pro b/Task/List-comprehensions/Visual-Prolog/list-comprehensions.pro new file mode 100644 index 0000000000..58b7f7f7b3 --- /dev/null +++ b/Task/List-comprehensions/Visual-Prolog/list-comprehensions.pro @@ -0,0 +1,26 @@ +implement main + open core, std + +domains + pythtrip = pt(integer, integer, integer). + +class predicates + pythTrips : (integer) -> pythtrip nondeterm (i). + +clauses + pythTrips(Limit) = pt(X,Y,Z) :- + X = fromTo(1,Limit), + Y = fromTo(X,Limit), + Z = fromTo(Y,Limit), + Z^2 = X^2 + Y^2. + + run():- + console::init(), + Triples = [ X || X = pythTrips(20) ], + console::write(Triples), + Junk = console::readLine(), + succeed(). +end implement main + +goal + mainExe::run(main::run). diff --git a/Task/Literals-Floating-point/GAP/literals-floating-point.gap b/Task/Literals-Floating-point/GAP/literals-floating-point.gap new file mode 100644 index 0000000000..68acee998e --- /dev/null +++ b/Task/Literals-Floating-point/GAP/literals-floating-point.gap @@ -0,0 +1,3 @@ +-3.14 +22.03e4 +4.54e-5 diff --git a/Task/Literals-Integer/Emacs-Lisp/literals-integer.l b/Task/Literals-Integer/Emacs-Lisp/literals-integer.l new file mode 100644 index 0000000000..908d7b541e --- /dev/null +++ b/Task/Literals-Integer/Emacs-Lisp/literals-integer.l @@ -0,0 +1,5 @@ +123 ;; decimal all Emacs +#b101 ;; binary Emacs 21 up, XEmacs 21 +#o77 ;; octal Emacs 21 up, XEmacs 21 +#xFF ;; hex Emacs 21 up, XEmacs 21 +#3r210 ;; any radix 2-36 Emacs 21 up (but not XEmacs 21.4) diff --git a/Task/Literals-Integer/GAP/literals-integer.gap b/Task/Literals-Integer/GAP/literals-integer.gap new file mode 100644 index 0000000000..0768fb8d4e --- /dev/null +++ b/Task/Literals-Integer/GAP/literals-integer.gap @@ -0,0 +1,3 @@ +# Only decimal integers, but of any length +31415926 +1606938044258990275541962092341162602522202993782792835301376 diff --git a/Task/Literals-Integer/REXX/literals-integer.rexx b/Task/Literals-Integer/REXX/literals-integer.rexx index a07914a2ce..91116ec73d 100644 --- a/Task/Literals-Integer/REXX/literals-integer.rexx +++ b/Task/Literals-Integer/REXX/literals-integer.rexx @@ -1,5 +1,6 @@ -thing=37 -thing='37' /*this is exactly the same as above. */ +thing = 37 +thing = '37' /*this is exactly the same as above. */ +thing = "37" /*this is exactly the same as above also. */ say 'base 10=' thing say 'base 2=' x2b(d2x(thing)) diff --git a/Task/Literals-String/BASIC/literals-string-3.basic b/Task/Literals-String/BASIC/literals-string-3.basic index 5c33406be3..eece863373 100644 --- a/Task/Literals-String/BASIC/literals-string-3.basic +++ b/Task/Literals-String/BASIC/literals-string-3.basic @@ -1,6 +1,4 @@ -10 REM Print some quotes -20 PRINT CHR$(34) -30 REM Print some more doublequotes -40 PRINT """" -50 REM Output the word hello enclosed in doublequotes -60 PRINT """Hello""" +M$ = CHR$(13) : Q$ = CHR$(34) +A$ = "THERE ARE" + M$ +A$ = A$ + "NO " + Q$ + "HERE" + Q$ + " STRINGS." +? A$ diff --git a/Task/Literals-String/BASIC/literals-string-4.basic b/Task/Literals-String/BASIC/literals-string-4.basic new file mode 100644 index 0000000000..5c33406be3 --- /dev/null +++ b/Task/Literals-String/BASIC/literals-string-4.basic @@ -0,0 +1,6 @@ +10 REM Print some quotes +20 PRINT CHR$(34) +30 REM Print some more doublequotes +40 PRINT """" +50 REM Output the word hello enclosed in doublequotes +60 PRINT """Hello""" diff --git a/Task/Literals-String/Deja-Vu/literals-string.djv b/Task/Literals-String/Deja-Vu/literals-string.djv new file mode 100644 index 0000000000..49aa52bbfb --- /dev/null +++ b/Task/Literals-String/Deja-Vu/literals-string.djv @@ -0,0 +1,3 @@ +local :s "String literal" +local :s2 "newline \n carriage return \r tab \t" +!print "backslash \\ quote \q decimal character \{8364}" diff --git a/Task/Literals-String/REXX/literals-string-3.rexx b/Task/Literals-String/REXX/literals-string-3.rexx index f5a876199b..645bcaf90b 100644 --- a/Task/Literals-String/REXX/literals-string-3.rexx +++ b/Task/Literals-String/REXX/literals-string-3.rexx @@ -11,6 +11,6 @@ Binary strings are also possible: jjj='01011011'B jjj='01011011'b -jjj='0101 1011'b +jjj="0101 1011"b jjj='0101 1011 1111'b longjjj='11110000 10100001 10110010 11100011 11100100'B diff --git a/Task/Logical-operations/Clipper/logical-operations.clipper b/Task/Logical-operations/Clipper/logical-operations.clipper new file mode 100644 index 0000000000..2f728739f7 --- /dev/null +++ b/Task/Logical-operations/Clipper/logical-operations.clipper @@ -0,0 +1,6 @@ + Function Foo( a, b ) + // a and b was defined as .F. (false) or .T. (true) + ? a .AND. b + ? a .OR. b + ? .NOT. a, .NOT. b + Return Nil diff --git a/Task/Long-multiplication/BASIC/long-multiplication-3.basic b/Task/Long-multiplication/BASIC/long-multiplication-3.basic new file mode 100644 index 0000000000..73d140e89e --- /dev/null +++ b/Task/Long-multiplication/BASIC/long-multiplication-3.basic @@ -0,0 +1,33 @@ + 100 A$ = "18446744073709551616" + 110 B$ = A$ + 120 GOSUB 400 + 130 PRINT E$ + 140 END + + 400 REM MULTIPLY A$ * B$ + 410 C$ = "":D$ = "0" + 420 FOR I = LEN (B$) TO 1 STEP - 1 + 430 C = 0:B = VAL ( MID$ (B$,I,1)) + 440 FOR J = LEN (A$) TO 1 STEP - 1 + 450 V = B * VAL ( MID$ (A$,J,1)) + C + 460 C = INT (V / 10):V = V - C * 10 + 470 C$ = STR$ (V) + C$ + 480 NEXT J + 490 IF C THEN C$ = STR$ (C) + C$ + 510 GOSUB 600"ADD C$ + D$ + 520 D$ = E$:C$ = "0":J = LEN (B$) - I + 530 IF J THEN J = J - 1:C$ = C$ + "0": GOTO 530 + 550 NEXT I + 560 RETURN + + 600 REM ADD C$ + D$ + 610 E = LEN (D$):E$ = "":C = 0 + 620 FOR J = LEN (C$) TO 1 STEP - 1 + 630 IF E THEN D = VAL ( MID$ (D$,E,1)) + 640 V = VAL ( MID$ (C$,J,1)) + D + C + 650 C = V > 9:V = V - 10 * C + 660 E$ = STR$ (V) + E$ + 670 IF E THEN E = E - 1:D = 0 + 680 NEXT J + 700 IF E THEN V = VAL ( MID$ (D$,E,1)) + C:C = V > 9:V = V - 10 * C:E$ = STR$ (V) + E$:E = E - 1: GOTO 700 + 720 RETURN diff --git a/Task/Long-multiplication/D/long-multiplication-2.d b/Task/Long-multiplication/D/long-multiplication-2.d index 030fa58501..733d7ac09a 100644 --- a/Task/Long-multiplication/D/long-multiplication-2.d +++ b/Task/Long-multiplication/D/long-multiplication-2.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range, std.ascii; -auto longMult(in string x1, in string x2) /*pure nothrow*/ { +auto longMult(in string x1, in string x2) pure /*nothrow*/ { auto digits1 = x1.retro.map!q{a - '0'}; immutable digits2 = x2.retro.map!q{a - '0'}.array; uint[] res; 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 cb5816c7d4..c24732d210 100644 --- a/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d +++ b/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d @@ -20,7 +20,7 @@ uint[] lensLCS(R)(R xs, R ys) pure nothrow { } void calculateLCS(T)(in T[] xs, in T[] ys, bool[] xs_in_lcs, - in size_t idx=0) /*pure nothrow*/ { + in size_t idx=0) pure nothrow { immutable nx = xs.length; immutable ny = ys.length; @@ -50,11 +50,11 @@ void calculateLCS(T)(in T[] xs, in T[] ys, bool[] xs_in_lcs, } } -const(T)[] lcs(T)(in T[] xs, in T[] ys) /*pure nothrow*/ { +const(T)[] lcs(T)(in T[] xs, in T[] ys) pure /*nothrow*/ { auto xs_in_lcs = new bool[xs.length]; calculateLCS(xs, ys, xs_in_lcs); - return zip(xs, xs_in_lcs) + return zip(xs, xs_in_lcs) // Not nothrow. .filter!q{ a[1] } .map!q{ a[0] } .array; diff --git a/Task/Longest-common-subsequence/Dart/longest-common-subsequence.dart b/Task/Longest-common-subsequence/Dart/longest-common-subsequence.dart index e49efbd31c..5269a87bc3 100644 --- a/Task/Longest-common-subsequence/Dart/longest-common-subsequence.dart +++ b/Task/Longest-common-subsequence/Dart/longest-common-subsequence.dart @@ -1,12 +1,13 @@ +import 'dart:math'; + String lcsRecursion(String a, String b) { int aLen = a.length; int bLen = b.length; if (aLen == 0 || bLen == 0) { return ""; - } else if (a.charCodeAt(aLen-1) == b.charCodeAt(bLen-1)) { - return lcsRecursion(a.substring(0,aLen-1),b.substring(0,bLen-1)) - + a[aLen-1]; + } else if (a[aLen-1] == b[bLen-1]) { + return lcsRecursion(a.substring(0,aLen-1),b.substring(0,bLen-1)) + a[aLen-1]; } else { var x = lcsRecursion(a, b.substring(0,bLen-1)); var y = lcsRecursion(a.substring(0,aLen-1), b); @@ -15,56 +16,52 @@ String lcsRecursion(String a, String b) { } String lcsDynamic(String a, String b) { - List> lengths = new List>(a.length+1); - for(int i=0; i>.generate(a.length + 1, + (_) => new List.filled(b.length+1, 0), growable: false); // row 0 and column 0 are initialized to 0 already for (int i = 0; i < a.length; i++) { for (int j = 0; j < b.length; j++) { - if (a.charCodeAt(i) == b.charCodeAt(j)) { + if (a[i] == b[j]) { lengths[i+1][j+1] = lengths[i][j] + 1; } else { - lengths[i+1][j+1] = Math.max(lengths[i+1][j], lengths[i][j+1]); + lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1]); } } } // read the substring out from the matrix - StringBuffer sb = new StringBuffer(); - for (int x = a.length, y = b.length; x!=0 && y!=0;) { + StringBuffer reversedLcsBuffer = new StringBuffer(); + for (int x = a.length, y = b.length; x != 0 && y != 0;) { if (lengths[x][y] == lengths[x-1][y]) { x--; } else if (lengths[x][y] == lengths[x][y-1]) { y--; } else { - assert(a.charCodeAt(x-1) == b.charCodeAt(y-1)); - sb.add(a[x-1]); + assert(a[x-1] == b[y-1]); + reversedLcsBuffer.write(a[x-1]); x--; y--; } } // reverse String - var l = sb.toString().splitChars(); - StringBuffer sb2 = new StringBuffer(); - for(int i=l.length-1; i>=0; i--) { - sb2.add(l[i]); + var reversedLCS = reversedLcsBuffer.toString(); + var lcsBuffer = new StringBuffer(); + for(var i = reversedLCS.length - 1; i>=0; i--) { + lcsBuffer.write(reversedLCS[i]); } - - return sb2.toString(); + return lcsBuffer.toString(); } void main() { - print("lcsDynamic('1234', '1224533324') = " + lcsDynamic("1234", "1224533324")); - print("lcsDynamic('thisisatest', 'testing123testing') = " + lcsDynamic("thisisatest", "testing123testing")); - print("lcsDynamic('', 'x') = " + lcsDynamic("", "x")); - print("lcsDynamic('x', 'x') = " + lcsDynamic("x", "x")); - print(""); - print("lcsRecursion('1234', '1224533324') = " + lcsRecursion("1234", "1224533324")); - print("lcsRecursion('thisisatest', 'testing123testing') = " + lcsRecursion("thisisatest", "testing123testing")); - print("lcsRecursion('', 'x') = " + lcsRecursion("", "x")); - print("lcsRecursion('x', 'x') = " + lcsRecursion("x", "x")); + print("lcsDynamic('1234', '1224533324') = ${lcsDynamic('1234', '1224533324')}"); + print("lcsDynamic('thisisatest', 'testing123testing') = ${lcsDynamic('thisisatest', 'testing123testing')}"); + print("lcsDynamic('', 'x') = ${lcsDynamic('', 'x')}"); + print("lcsDynamic('x', 'x') = ${lcsDynamic('x', 'x')}"); + print(''); + print("lcsRecursion('1234', '1224533324') = ${lcsRecursion('1234', '1224533324')}"); + print("lcsRecursion('thisisatest', 'testing123testing') = ${lcsRecursion('thisisatest', 'testing123testing')}"); + print("lcsRecursion('', 'x') = ${lcsRecursion('', 'x')}"); + print("lcsRecursion('x', 'x') = ${lcsRecursion('x', 'x')}"); } diff --git a/Task/Look-and-say-sequence/00DESCRIPTION b/Task/Look-and-say-sequence/00DESCRIPTION index 5b523ad917..df134fb4b6 100644 --- a/Task/Look-and-say-sequence/00DESCRIPTION +++ b/Task/Look-and-say-sequence/00DESCRIPTION @@ -17,5 +17,6 @@ The [[wp:Look_and_say_sequence|sequence]] is from [[wp:John Horton Conway|John C '''See also''' * This task is related to, and an application of, the [[Run-length encoding]] task. +* Sequence [https://oeis.org/A005150 A005150] on The On-Line Encyclopedia of Integer Sequences. __TOC__ diff --git a/Task/Look-and-say-sequence/D/look-and-say-sequence-1.d b/Task/Look-and-say-sequence/D/look-and-say-sequence-1.d index c83da4436e..0e07335266 100644 --- a/Task/Look-and-say-sequence/D/look-and-say-sequence-1.d +++ b/Task/Look-and-say-sequence/D/look-and-say-sequence-1.d @@ -1,15 +1,7 @@ -import std.stdio, std.conv, std.algorithm; +import std.stdio, std.algorithm, std.range; -string lookAndSay(string input) { - string result; - foreach (digit, count; input.group()) - result ~= text(count, digit); - return result; -} +enum say = (in string s) pure => s.group.map!q{ text(a[1],a[0]) }.join; void main() { - auto terms = ["1"]; - foreach (_; 0 .. 7) - terms ~= terms[$ - 1].lookAndSay(); - writeln(terms); + "1".recurrence!((t, n) => t[n - 1].say).take(8).writeln; } diff --git a/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d b/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d index a8a0a31803..c1b5c593ad 100644 --- a/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d +++ b/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d @@ -1,9 +1,94 @@ -import std.stdio, std.algorithm, std.conv, std.range; +import core.stdc.stdio, std.math, std.conv, std.algorithm, std.array; -string say(in string t) pure /*nothrow*/ { - return t.group.map!q{ text(a[1], a[0]) }.join; +void showLookAndSay(bool showArrays)(in uint n) nothrow { + if (n == 0) // No sequences to generate and show. + return; + + enum Digit : char { nil = '\0', one = '1', two = '2', thr = '3' } + + // Allocate an approximate upper bound size for the array. + static Digit* allocBuffer(in uint m) nothrow { + immutable len = cast(size_t)(100 + 1.05 * + exp(0.269 * m + 0.2686)) + 1; + auto a = len.uninitializedArray!(Digit[]); + printf("Allocated %d bytes.\n", a.length * Digit.sizeof); + return a.ptr; + } + + // Can't be expressed in the D type system: + // a1 and a2 are immutable pointers to mutable data. + auto a1 = allocBuffer(n % 2 ? n : n - 1); + auto a2 = allocBuffer(n % 2 ? n - 1 : n); + printf("\n"); + + a1[0] = Digit.one; + size_t len1 = 1; + a1[len1] = Digit.nil; + + foreach (immutable i; 0 .. n - 1) { + static if (showArrays) + printf("%2u: %s\n", i + 1, a1); + else + printf("%2u: n. digits: %u\n", i + 1, len1); + auto p1 = a1, + p2 = a2; + + S0: final switch (*p1++) with (Digit) { // Initial state. + case nil: goto END; + case one: goto S1; + case two: goto S2; + case thr: goto S3; + } + S1: final switch (*p1++) with (Digit) { + case nil: *p2++ = one; *p2++ = one; goto END; + case one: goto S11; + case two: *p2++ = one; *p2++ = one; goto S2; + case thr: *p2++ = one; *p2++ = one; goto S3; + } + S2: final switch (*p1++) with (Digit) { + case nil: *p2++ = one; *p2++ = two; goto END; + case one: *p2++ = one; *p2++ = two; goto S1; + case two: goto S22; + case thr: *p2++ = one; *p2++ = two; goto S3; + } + S3: final switch (*p1++) with (Digit) { + case nil: *p2++ = one; *p2++ = thr; goto END; + case one: *p2++ = one; *p2++ = thr; goto S1; + case two: *p2++ = one; *p2++ = thr; goto S2; + case thr: goto S33; + } + S11: final switch (*p1++) with (Digit) { + case nil: *p2++ = two; *p2++ = one; goto END; + case one: *p2++ = thr; *p2++ = one; goto S0; + case two: *p2++ = two; *p2++ = one; goto S2; + case thr: *p2++ = two; *p2++ = one; goto S3; + } + S22: final switch (*p1++) with (Digit) { + case nil: *p2++ = two; *p2++ = two; goto END; + case one: *p2++ = two; *p2++ = two; goto S1; + case two: *p2++ = thr; *p2++ = two; goto S0; + case thr: *p2++ = two; *p2++ = two; goto S3; + } + S33: final switch (*p1++) with (Digit) { + case nil: *p2++ = two; *p2++ = thr; goto END; + case one: *p2++ = two; *p2++ = thr; goto S1; + case two: *p2++ = two; *p2++ = thr; goto S2; + case thr: *p2++ = thr; *p2++ = thr; goto S0; + } + END: + immutable len2 = p2 - a2; + a2[len2] = Digit.nil; + a1.swap(a2); + len1 = len2; + } + + static if (showArrays) + printf("%2u: %s\n", n, a1); + else + printf("%2u: n. digits: %u\n", n, len1); } -void main() { - "1".recurrence!((t, n) => t[n - 1].say).take(8).writeln; +void main(in string[] args) { + immutable n = (args.length == 2) ? args[1].to!uint : 10; + n.showLookAndSay!true; } diff --git a/Task/Look-and-say-sequence/D/look-and-say-sequence-3.d b/Task/Look-and-say-sequence/D/look-and-say-sequence-3.d new file mode 100644 index 0000000000..3370855c2f --- /dev/null +++ b/Task/Look-and-say-sequence/D/look-and-say-sequence-3.d @@ -0,0 +1 @@ +70.showLookAndSay!false; diff --git a/Task/Look-and-say-sequence/D/look-and-say-sequence-4.d b/Task/Look-and-say-sequence/D/look-and-say-sequence-4.d new file mode 100644 index 0000000000..1b2ae04591 --- /dev/null +++ b/Task/Look-and-say-sequence/D/look-and-say-sequence-4.d @@ -0,0 +1,19 @@ +void main(in string[] args) { + import std.stdio, std.conv, std.algorithm, std.array, std.string; + + immutable n = (args.length == 2) ? args[1].to!uint : 10; + if (n == 0) + return; + + auto seq = ['1']; + writefln("%2d: n. digits: %d", 1, seq.length); + foreach (immutable i; 2 .. n + 1) { + Appender!(typeof(seq)) result; + foreach (const digit, const count; seq.representation.group) { + result ~= "123"[count - 1]; + result ~= digit; + } + seq = result.data; + writefln("%2d: n. digits: %d", i, seq.length); + } +} diff --git a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir new file mode 100644 index 0000000000..f0b55835ba --- /dev/null +++ b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir @@ -0,0 +1,25 @@ +defmodule LookAndSay do + def next(n) do + Enum.chunks_by(to_char_list(n), &(&1)) + |> Enum.map(fn cl=[h|_] -> + Enum.concat(to_char_list(length cl), [h]) end) + |> Enum.concat + |> list_to_integer + end + + def sequence_from(n) do + Stream.iterate n, &(LookAndSay.next/1) + end + + def main([start_str|_]) do + {start_val,_} = Integer.parse(start_str) + :io.format("~w~n", [LookAndSay.sequence_from(start_val) |> Enum.take 9] ) + exit 0 + end + + def main([]) do + main(["1"]) + end +end + +LookAndSay.main(System.argv) diff --git a/Task/Look-and-say-sequence/Metafont/look-and-say-sequence.metafont b/Task/Look-and-say-sequence/Metafont/look-and-say-sequence-1.metafont similarity index 100% rename from Task/Look-and-say-sequence/Metafont/look-and-say-sequence.metafont rename to Task/Look-and-say-sequence/Metafont/look-and-say-sequence-1.metafont diff --git a/Task/Look-and-say-sequence/Metafont/look-and-say-sequence-2.metafont b/Task/Look-and-say-sequence/Metafont/look-and-say-sequence-2.metafont new file mode 100644 index 0000000000..637f7e2d8f --- /dev/null +++ b/Task/Look-and-say-sequence/Metafont/look-and-say-sequence-2.metafont @@ -0,0 +1,21 @@ +proc NextInLookAndSaySequence (current: string): string = + assert(len(current) > 0) + Result = "" + var ch = current[0] + var count = 1 + for i in countup(1, len(current)-1): + if current[i] != ch: + Result &= $count & ch + ch = current[i] + count = 1 + else: + count += 1 + Result &= $count & ch + +proc LookAndSay (n = 10) = + var next = "1" + for i in countup(1, n): + next = NextInLookAndSaySequence(next) + echo next + +LookAndSay() diff --git a/Task/Look-and-say-sequence/Objective-C/look-and-say-sequence.m b/Task/Look-and-say-sequence/Objective-C/look-and-say-sequence.m new file mode 100644 index 0000000000..d29571899c --- /dev/null +++ b/Task/Look-and-say-sequence/Objective-C/look-and-say-sequence.m @@ -0,0 +1,35 @@ +#import + +-(NSString*)lookAndSay:(NSString *)word{ + if (!word) { + return nil; + } + NSMutableString *result = [NSMutableString new]; + + char repeat = [word characterAtIndex:0]; + int times = 1; + word = [NSString stringWithFormat:@"%@ ",[word substringFromIndex:1] ]; + + for (NSInteger index = 0; index < word.length; index++) { + char actual = [word characterAtIndex:index]; + if (actual != repeat) { + [result appendFormat:@"%d%c", times, repeat]; + times = 1; + repeat = actual; + } else { + times ++; + } + } + + return [result copy]; +} + +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification +{ + NSString *num = @"1"; + for (int i=1;i<=10;i++) { + NSLog(@"%@", num); + + num = [self lookAndSay:num]; + } +} diff --git a/Task/Look-and-say-sequence/REXX/look-and-say-sequence-1.rexx b/Task/Look-and-say-sequence/REXX/look-and-say-sequence-1.rexx new file mode 100644 index 0000000000..5ff7e26755 --- /dev/null +++ b/Task/Look-and-say-sequence/REXX/look-and-say-sequence-1.rexx @@ -0,0 +1,21 @@ +/*REXX pgm displays the sequence (or lengths) for the look & say series.*/ +parse arg N ! .; if N=='' then N=20 /*No nums given? Then use default*/ +if !=='' then !=1 /*Null? Then assume 1st number.*/ + + do j=1 for abs(N) /*repeat a # times to show NUMS.*/ + if j\==1 then !=$lookAndSay(!) /*invoke sub to calculate next #.*/ + if N<0 then say 'length['j"]:" length(!) /*show its length.*/ + else say ! /*show the number to the screen. */ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────$LOOKANDSAY subroutine──────────────*/ +$lookAndSay: procedure; parse arg x,,$ /*define the argument passed {X}.*/ +fin = '0'x /*use unique char to end scanning*/ +x=x || fin /*append FIN character to string.*/ + do k=1 by 0 /*now, process the given sequence*/ + y=substr(x,k,1) /*pick off one char to examine. */ + if y==fin then return $ /*if we're at the end, then done.*/ + _=verify(x,y,,k) - k /*see how many chars we have of Y*/ + $=$ || _ || y /*build the "say" thingy list. */ + k=k + _ /*now, point to the next char. */ + end /*k*/ diff --git a/Task/Look-and-say-sequence/REXX/look-and-say-sequence-2.rexx b/Task/Look-and-say-sequence/REXX/look-and-say-sequence-2.rexx new file mode 100644 index 0000000000..638064c27e --- /dev/null +++ b/Task/Look-and-say-sequence/REXX/look-and-say-sequence-2.rexx @@ -0,0 +1,27 @@ +/*REXX pgm displays the sequence (or lengths) for the look & say series.*/ +parse arg N ! .; if N=='' then N=20 /*No nums given? Then use default*/ +if !=='' then !=1 /*Null? Then assume 1st number.*/ + + do j=1 for abs(N) /*repeat a # times to show NUMS.*/ + if j\==1 then !=$lookAndSay(!) /*invoke sub to calculate next #.*/ + if N<0 then say 'length['j"]:" length(!) /*show its length.*/ + else say '['j"]:" ! /*show the number to the screen. */ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────$LOOKANDSAY subroutine──────────────*/ +$lookAndSay: procedure; parse arg x,,$ ! /*define argument passed {X}.*/ +chunkSize=1000 /*define a sensible chunk size. */ +fin = '0'x /*use unique char to end scanning*/ +x=x || fin /*append FIN character to string.*/ + do k=1 by 0 /*now, process the given sequence*/ + y=substr(x,k,1) /*pick off one char to examine. */ + if y==fin then leave /*if we're at the end, then done.*/ + _=verify(x,y,,k) - k /*see how many chars we have of Y*/ + $=$ || _ || y /*build the "say" thingy list. */ + k=k + _ /*now, point to the next char. */ + if length($) ~[int] { + assert!(!in_seq.is_empty()); + + let mut result = ~[]; + let mut current_number = in_seq[0]; + let mut current_runlength = 1; + + for i in in_seq.slice_from(1).iter() { + if current_number == *i { + current_runlength += 1; + } else { + result.push(current_runlength); + result.push(current_number); + current_runlength = 1; + current_number = *i; + } + } + result.push(current_runlength); + result.push(current_number); + + result +} + +fn main() { + let mut seq = ~[1]; + + for i in iter::range(0, 10) { + println!("Sequence {}: {:?}", i, seq); + seq = next_sequence(seq); + } +} diff --git a/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap b/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap new file mode 100644 index 0000000000..bbb7688238 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap @@ -0,0 +1,32 @@ +# The Loop function will apply some function to every tuple built by taking +# the i-th element of each list. If one of them is exhausted before the others, +# the loop continues at its begining. Only the longests lists will be precessed only once. +Loop := function(a, f) + local i, j, m, n, v; + n := Length(a); + v := List(a, Length); + m := Maximum(v); + for j in [1 .. m] do + f(List([1 .. n], i -> a[i][1 + RemInt(j - 1, v[i])])); + od; +end; + +# Here we simply print each "row" +f := function(u) + Perform(u, Print); + Print("\n"); +end; + +Loop([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]], f); + +aA1 +bB2 +cC3 + +Loop([["a", "b"], ["A", "B", "C", "D", "E"], [1, 2, 3]], f); + +aA1 +bB2 +aC3 +bD1 +aE2 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust b/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust new file mode 100644 index 0000000000..2e7729bfb4 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust @@ -0,0 +1,11 @@ +// rust 0.9-pre + +fn main() { + let a1 = ["a", "b", "c"]; + let a2 = ["A", "B", "C"]; + let a3 = [1, 2, 3]; + + for ((&x, &y), &z) in a1.iter().zip(a2.iter()).zip(a3.iter()) { + println!("{}{}{}", x, y, z); + } +} diff --git a/Task/Loops-Continue/Clipper/loops-continue.clipper b/Task/Loops-Continue/Clipper/loops-continue.clipper new file mode 100644 index 0000000000..a664ac97cb --- /dev/null +++ b/Task/Loops-Continue/Clipper/loops-continue.clipper @@ -0,0 +1,8 @@ +FOR i := 1 TO 10 + ?? i + IF i % 5 == 0 + ? + LOOP + ENDIF + ?? ", " +NEXT diff --git a/Task/Loops-Do-while/Clipper/loops-do-while.clipper b/Task/Loops-Do-while/Clipper/loops-do-while.clipper new file mode 100644 index 0000000000..7e677e2c58 --- /dev/null +++ b/Task/Loops-Do-while/Clipper/loops-do-while.clipper @@ -0,0 +1,7 @@ + Local n := 0 + DO WHILE .T. + ? ++n + IF n % 6 == 0 + EXIT + ENDIF + ENDDO diff --git a/Task/Loops-Do-while/GAP/loops-do-while.gap b/Task/Loops-Do-while/GAP/loops-do-while.gap new file mode 100644 index 0000000000..c91db433e3 --- /dev/null +++ b/Task/Loops-Do-while/GAP/loops-do-while.gap @@ -0,0 +1,5 @@ +n := 0; +repeat + n := n + 1; + Print(n, "\n"); +until RemInt(n, 6) = 0; diff --git a/Task/Loops-Do-while/Scala/loops-do-while-1.scala b/Task/Loops-Do-while/Scala/loops-do-while-1.scala new file mode 100644 index 0000000000..041ec09f7c --- /dev/null +++ b/Task/Loops-Do-while/Scala/loops-do-while-1.scala @@ -0,0 +1,8 @@ + { + var (x, l) = (0, List[Int]()) + do { + x += 1 + l :+= x // A new copy of this list with List(x) appended. + } while (x % 6 != 0) + l + }.foreach(println(_)) diff --git a/Task/Loops-Do-while/Scala/loops-do-while-2.scala b/Task/Loops-Do-while/Scala/loops-do-while-2.scala new file mode 100644 index 0000000000..d442b804ad --- /dev/null +++ b/Task/Loops-Do-while/Scala/loops-do-while-2.scala @@ -0,0 +1,6 @@ + def loop(iter: Int, cond: (Int) => Boolean, accu: List[Int]): List[Int] = { + val succ = iter + 1 + val temp = accu :+ succ + if (cond(succ)) loop(succ, cond, temp) else temp + } + println(loop(0, (_ % 6 != 0), Nil)) diff --git a/Task/Loops-Do-while/Scala/loops-do-while-3.scala b/Task/Loops-Do-while/Scala/loops-do-while-3.scala new file mode 100644 index 0000000000..9ee54783df --- /dev/null +++ b/Task/Loops-Do-while/Scala/loops-do-while-3.scala @@ -0,0 +1,5 @@ + def loop(i: Int, cond: (Int) => Boolean): Stream[Int] = { + val succ = i + 1; + succ #:: (if (cond(succ)) loop(succ, cond) else Stream.empty) + } + loop(0, (_ % 6 != 0)).foreach(println(_)) diff --git a/Task/Loops-Do-while/Scala/loops-do-while.scala b/Task/Loops-Do-while/Scala/loops-do-while.scala deleted file mode 100644 index 9e1abcdde4..0000000000 --- a/Task/Loops-Do-while/Scala/loops-do-while.scala +++ /dev/null @@ -1,5 +0,0 @@ -var x=0 -do { - println(x) - x+=1 -} while(x%6!=0) diff --git a/Task/Loops-Downward-for/BASIC/loops-downward-for.basic b/Task/Loops-Downward-for/BASIC/loops-downward-for-1.basic similarity index 100% rename from Task/Loops-Downward-for/BASIC/loops-downward-for.basic rename to Task/Loops-Downward-for/BASIC/loops-downward-for-1.basic diff --git a/Task/Loops-Downward-for/BASIC/loops-downward-for-2.basic b/Task/Loops-Downward-for/BASIC/loops-downward-for-2.basic new file mode 100644 index 0000000000..b21320f647 --- /dev/null +++ b/Task/Loops-Downward-for/BASIC/loops-downward-for-2.basic @@ -0,0 +1 @@ +FOR I = 10 TO 0 STEP -1 : PRINT I : NEXT I diff --git a/Task/Loops-Downward-for/Clipper/loops-downward-for.clipper b/Task/Loops-Downward-for/Clipper/loops-downward-for.clipper new file mode 100644 index 0000000000..3f83aca974 --- /dev/null +++ b/Task/Loops-Downward-for/Clipper/loops-downward-for.clipper @@ -0,0 +1,3 @@ + FOR i := 10 TO 0 STEP -1 + ? i + NEXT diff --git a/Task/Loops-Downward-for/GAP/loops-downward-for.gap b/Task/Loops-Downward-for/GAP/loops-downward-for.gap new file mode 100644 index 0000000000..24fd418a00 --- /dev/null +++ b/Task/Loops-Downward-for/GAP/loops-downward-for.gap @@ -0,0 +1,3 @@ +for i in [10, 9 .. 0] do + Print(i, "\n"); +od; diff --git a/Task/Loops-Downward-for/Julia/loops-downward-for.julia b/Task/Loops-Downward-for/Julia/loops-downward-for.julia new file mode 100644 index 0000000000..c14073ac87 --- /dev/null +++ b/Task/Loops-Downward-for/Julia/loops-downward-for.julia @@ -0,0 +1,3 @@ +for i in 10:-1:0 + println(i) +end diff --git a/Task/Loops-Downward-for/Python/loops-downward-for.py b/Task/Loops-Downward-for/Python/loops-downward-for-1.py similarity index 100% rename from Task/Loops-Downward-for/Python/loops-downward-for.py rename to Task/Loops-Downward-for/Python/loops-downward-for-1.py diff --git a/Task/Loops-Downward-for/Python/loops-downward-for-2.py b/Task/Loops-Downward-for/Python/loops-downward-for-2.py new file mode 100644 index 0000000000..9bef1922b7 --- /dev/null +++ b/Task/Loops-Downward-for/Python/loops-downward-for-2.py @@ -0,0 +1 @@ +[i for i in xrange(10, -1, -1)] diff --git a/Task/Loops-Downward-for/Python/loops-downward-for-3.py b/Task/Loops-Downward-for/Python/loops-downward-for-3.py new file mode 100644 index 0000000000..d553273fbe --- /dev/null +++ b/Task/Loops-Downward-for/Python/loops-downward-for-3.py @@ -0,0 +1,2 @@ +import pprint +pprint.pprint([i for i in xrange(10, -1, -1)]) diff --git a/Task/Loops-Downward-for/Rust/loops-downward-for.rust b/Task/Loops-Downward-for/Rust/loops-downward-for.rust new file mode 100644 index 0000000000..d4074b270e --- /dev/null +++ b/Task/Loops-Downward-for/Rust/loops-downward-for.rust @@ -0,0 +1,7 @@ +// rust 0.9-pre + +fn main() { + for i in std::iter::range_inclusive(0, 10).invert() { + println!("{}", i); + } +} diff --git a/Task/Loops-For-with-a-specified-step/Ada/loops-for-with-a-specified-step.ada b/Task/Loops-For-with-a-specified-step/Ada/loops-for-with-a-specified-step.ada new file mode 100644 index 0000000000..4290712600 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Ada/loops-for-with-a-specified-step.ada @@ -0,0 +1,63 @@ +with Loopers; +use Loopers; + + +procedure For_Main is +begin + Looper_1; + Looper_2; + Looper_3; +end For_Main; + + +package Loopers is + procedure Looper_1; + procedure Looper_2; + procedure Looper_3; +end Loopers; + +with Ada.Text_IO, Ada.Integer_Text_IO; +use Ada.Text_IO, Ada.Integer_Text_IO; + +package body Loopers is + procedure Looper_1 is + Values : array(1..5) of Integer := (2,4,6,8,10); + begin + for I in Values'Range loop + Put(Values(I),0); + if I = Values'Last then + Put_Line("."); + else + Put(","); + end if; + end loop; + end Looper_1; + + procedure Looper_2 is + E : Integer := 5; + begin + for I in 1..E loop + Put(I*2,0); + if I = E then + Put_Line("."); + else + Put(","); + end if; + end loop; + end Looper_2; + + procedure Looper_3 is + Values : array(1..10) of Integer := (1,2,3,4,5,6,7,8,9,10); + Indices : array(1..5) of Integer := (2,4,6,8,10); + begin + for I in Indices'Range loop + Put(Values(Indices(I)),0); + if I = Indices'Last then + Put_Line("."); + else + Put(","); + end if; + end loop; + end Looper_3; + +end Loopers; diff --git a/Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step.basic b/Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-1.basic similarity index 100% rename from Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step.basic rename to Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-1.basic diff --git a/Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-2.basic b/Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-2.basic new file mode 100644 index 0000000000..c3e890aede --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-2.basic @@ -0,0 +1 @@ +FOR I = 2 TO 8 STEP 2 : PRINT I; ", "; : NEXT I : PRINT "WHO DO WE APPRECIATE?" diff --git a/Task/Loops-For-with-a-specified-step/GAP/loops-for-with-a-specified-step.gap b/Task/Loops-For-with-a-specified-step/GAP/loops-for-with-a-specified-step.gap new file mode 100644 index 0000000000..4265d1433d --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/GAP/loops-for-with-a-specified-step.gap @@ -0,0 +1,10 @@ +for i in [1, 3 .. 11] do + Print(i, "\n"); +od; + +1 +3 +5 +7 +9 +11 diff --git a/Task/Loops-For-with-a-specified-step/Julia/loops-for-with-a-specified-step.julia b/Task/Loops-For-with-a-specified-step/Julia/loops-for-with-a-specified-step.julia new file mode 100644 index 0000000000..e832a7c2f4 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Julia/loops-for-with-a-specified-step.julia @@ -0,0 +1,4 @@ +for i in 2:2:8 + print(i, ", ") +end +println("whom do we appreciate?") diff --git a/Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step.rexx b/Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step-1.rexx similarity index 100% rename from Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step.rexx rename to Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step-1.rexx diff --git a/Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step-2.rexx b/Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step-2.rexx new file mode 100644 index 0000000000..6507d8886f --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/REXX/loops-for-with-a-specified-step-2.rexx @@ -0,0 +1,3 @@ + do thing=1 by 3/2 to 10 + say thing + end diff --git a/Task/Loops-For/BASIC/loops-for-10.basic b/Task/Loops-For/BASIC/loops-for-10.basic new file mode 100644 index 0000000000..5ceebe6ca5 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-10.basic @@ -0,0 +1,6 @@ +FOR i = 1 TO 5 + FOR j = 1 TO i + PRINT "*"; + NEXT j + PRINT +NEXT i diff --git a/Task/Loops-For/BASIC/loops-for-11.basic b/Task/Loops-For/BASIC/loops-for-11.basic new file mode 100644 index 0000000000..611a057478 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-11.basic @@ -0,0 +1,7 @@ +Local i,j +ClrIO +For i, 1, 5 + For j, 1, i + Output i*8, j*6, "*" + EndFor +EndFor diff --git a/Task/Loops-For/BASIC/loops-for-12.basic b/Task/Loops-For/BASIC/loops-for-12.basic new file mode 100644 index 0000000000..6cc6794172 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-12.basic @@ -0,0 +1,15 @@ +'This Prints to the Debug-Window! +Dim i As Integer +Dim ii As Integer +Dim x As Integer +Dim out As String + +output = "" + +For i = 1 To 5 + For ii = 1 To i + out = out + "*" + Next ii + Debug.Print (out) + out = "" +Next i diff --git a/Task/Loops-For/BASIC/loops-for-13.basic b/Task/Loops-For/BASIC/loops-for-13.basic new file mode 100644 index 0000000000..a38aab1aa9 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-13.basic @@ -0,0 +1,6 @@ +For x As Integer = 0 To 4 + For y As Integer = 0 To x + Console.Write("*") + Next + Console.WriteLine() +Next diff --git a/Task/Loops-For/BASIC/loops-for-14.basic b/Task/Loops-For/BASIC/loops-for-14.basic new file mode 100644 index 0000000000..f47f2192b5 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-14.basic @@ -0,0 +1,6 @@ +10 FOR i = 1 TO 5 +20 FOR j = 1 TO i +30 PRINT "*"; +40 NEXT j +50 PRINT +60 NEXT i diff --git a/Task/Loops-For/BASIC/loops-for-2.basic b/Task/Loops-For/BASIC/loops-for-2.basic index f47f2192b5..52a635f7f4 100644 --- a/Task/Loops-For/BASIC/loops-for-2.basic +++ b/Task/Loops-For/BASIC/loops-for-2.basic @@ -1,6 +1 @@ -10 FOR i = 1 TO 5 -20 FOR j = 1 TO i -30 PRINT "*"; -40 NEXT j -50 PRINT -60 NEXT i +FOR I = 1 TO 5 : FOR J = 1 TO I : PRINT "*"; : NEXT J : PRINT : NEXT diff --git a/Task/Loops-For/BASIC/loops-for-3.basic b/Task/Loops-For/BASIC/loops-for-3.basic new file mode 100644 index 0000000000..37e6000e61 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-3.basic @@ -0,0 +1,6 @@ + FOR I% = 1 TO 5 + FOR J% = 1 TO I% + PRINT"*"; + NEXT + PRINT + NEXT diff --git a/Task/Loops-For/BASIC/loops-for-4.basic b/Task/Loops-For/BASIC/loops-for-4.basic new file mode 100644 index 0000000000..d17d2bd4f8 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-4.basic @@ -0,0 +1,21 @@ +OPENCONSOLE + +FOR X=1 TO 5 + + FOR Y=1 TO X + + PRINT"*",:'No line feed or carriage return after printing. + + NEXT Y + +PRINT + +NEXT X + +PRINT:PRINT"Press any key to end." + +DO:UNTIL INKEY$<>"" + +CLOSECONSOLE + +END diff --git a/Task/Loops-For/BASIC/loops-for-5.basic b/Task/Loops-For/BASIC/loops-for-5.basic new file mode 100644 index 0000000000..9e65d215a2 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-5.basic @@ -0,0 +1,6 @@ +10 FOR I = 1 TO 5 +20 FOR J = 1 TO I +30 PRINT "*"; +40 NEXT J +50 PRINT +60 NEXT I diff --git a/Task/Loops-For/BASIC/loops-for-6.basic b/Task/Loops-For/BASIC/loops-for-6.basic new file mode 100644 index 0000000000..dfa52d4db4 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-6.basic @@ -0,0 +1,8 @@ +#APPTYPE CONSOLE +FOR dim i = 1 TO 5 + FOR dim j = 1 TO i + PRINT "*"; + NEXT j + PRINT +NEXT i +Pause diff --git a/Task/Loops-For/BASIC/loops-for-7.basic b/Task/Loops-For/BASIC/loops-for-7.basic new file mode 100644 index 0000000000..d3ebfb48cb --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-7.basic @@ -0,0 +1,19 @@ +OPENCONSOLE + +FOR X=1 TO 5 + + FOR Y=1 TO X + + LOCATE X,Y:PRINT"*" + + NEXT Y + +NEXT X + +PRINT + +CLOSECONSOLE + +END + +'Could also have been written the same way as the Creative Basic example, with no LOCATE command. diff --git a/Task/Loops-For/BASIC/loops-for-8.basic b/Task/Loops-For/BASIC/loops-for-8.basic new file mode 100644 index 0000000000..e4a28dceba --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-8.basic @@ -0,0 +1,6 @@ +for i = 1 to 5 + for j = 1 to i + print "*"; + next + print +next diff --git a/Task/Loops-For/BASIC/loops-for-9.basic b/Task/Loops-For/BASIC/loops-for-9.basic new file mode 100644 index 0000000000..4274287f65 --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-9.basic @@ -0,0 +1,11 @@ +If OpenConsole() + Define i, j + For i=1 To 5 + For j=1 To i + Print("*") + Next j + PrintN("") + Next i + Print(#LFCR$+"Press ENTER to quit"): Input() + CloseConsole() +EndIf diff --git a/Task/Loops-Foreach/Ada/loops-foreach-1.ada b/Task/Loops-Foreach/Ada/loops-foreach-1.ada index 4dea4b8ce0..0086bb452d 100644 --- a/Task/Loops-Foreach/Ada/loops-foreach-1.ada +++ b/Task/Loops-Foreach/Ada/loops-foreach-1.ada @@ -8,7 +8,7 @@ procedure For_Each is begin for Num in A'Range loop - put( A (Num) ); + Put( A (Num) ); end loop; end For_Each; diff --git a/Task/Loops-Foreach/Ada/loops-foreach-2.ada b/Task/Loops-Foreach/Ada/loops-foreach-2.ada index 4de6489961..732fffde3b 100644 --- a/Task/Loops-Foreach/Ada/loops-foreach-2.ada +++ b/Task/Loops-Foreach/Ada/loops-foreach-2.ada @@ -1,25 +1,3 @@ -with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists; -use Ada.Integer_Text_IO, Ada.Containers; - -procedure Doubly_Linked_List is - - package DL_List_Pkg is new Doubly_Linked_Lists (Integer); - use DL_List_Pkg; - - procedure Print_Node (Position : Cursor) is - begin - Put (Element (Position)); - end Print_Node; - - DL_List : List; - -begin - - DL_List.Append (1); - DL_List.Append (2); - DL_List.Append (3); - - -- Iterates through every node of the list. - DL_List.Iterate (Print_Node'Access); - -end Doubly_Linked_List; + for Item of A loop + Put( Item ); + end loop; diff --git a/Task/Loops-Foreach/Ada/loops-foreach-3.ada b/Task/Loops-Foreach/Ada/loops-foreach-3.ada index bce1757376..4de6489961 100644 --- a/Task/Loops-Foreach/Ada/loops-foreach-3.ada +++ b/Task/Loops-Foreach/Ada/loops-foreach-3.ada @@ -1,25 +1,25 @@ -with Ada.Integer_Text_IO, Ada.Containers.Vectors; +with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists; use Ada.Integer_Text_IO, Ada.Containers; -procedure Vector_Example is +procedure Doubly_Linked_List is - package Vector_Pkg is new Vectors (Natural, Integer); - use Vector_Pkg; + package DL_List_Pkg is new Doubly_Linked_Lists (Integer); + use DL_List_Pkg; - procedure Print_Element (Position : Cursor) is + procedure Print_Node (Position : Cursor) is begin Put (Element (Position)); - end Print_Element; + end Print_Node; - V : Vector; + DL_List : List; begin - V.Append (1); - V.Append (2); - V.Append (3); + DL_List.Append (1); + DL_List.Append (2); + DL_List.Append (3); - -- Iterates through every element of the vector. - V.Iterate (Print_Element'Access); + -- Iterates through every node of the list. + DL_List.Iterate (Print_Node'Access); -end Vector_Example; +end Doubly_Linked_List; diff --git a/Task/Loops-Foreach/Ada/loops-foreach-4.ada b/Task/Loops-Foreach/Ada/loops-foreach-4.ada new file mode 100644 index 0000000000..bce1757376 --- /dev/null +++ b/Task/Loops-Foreach/Ada/loops-foreach-4.ada @@ -0,0 +1,25 @@ +with Ada.Integer_Text_IO, Ada.Containers.Vectors; +use Ada.Integer_Text_IO, Ada.Containers; + +procedure Vector_Example is + + package Vector_Pkg is new Vectors (Natural, Integer); + use Vector_Pkg; + + procedure Print_Element (Position : Cursor) is + begin + Put (Element (Position)); + end Print_Element; + + V : Vector; + +begin + + V.Append (1); + V.Append (2); + V.Append (3); + + -- Iterates through every element of the vector. + V.Iterate (Print_Element'Access); + +end Vector_Example; diff --git a/Task/Loops-Foreach/GAP/loops-foreach.gap b/Task/Loops-Foreach/GAP/loops-foreach.gap new file mode 100644 index 0000000000..151e036907 --- /dev/null +++ b/Task/Loops-Foreach/GAP/loops-foreach.gap @@ -0,0 +1,16 @@ +for p in AlternatingGroup(4) do + Print(p, "\n"); +od; + +() +(1,3,2) +(1,2,3) +(1,4,3) +(2,4,3) +(1,3)(2,4) +(1,2,4) +(1,4)(2,3) +(2,3,4) +(1,3,4) +(1,2)(3,4) +(1,4,2) diff --git a/Task/Loops-Foreach/Julia/loops-foreach.julia b/Task/Loops-Foreach/Julia/loops-foreach.julia new file mode 100644 index 0000000000..3836606cec --- /dev/null +++ b/Task/Loops-Foreach/Julia/loops-foreach.julia @@ -0,0 +1,3 @@ +for i in collection + println(i) +end diff --git a/Task/Loops-Infinite/Deja-Vu/loops-infinite-1.djv b/Task/Loops-Infinite/Deja-Vu/loops-infinite-1.djv index b6f4207e01..671eb53f57 100644 --- a/Task/Loops-Infinite/Deja-Vu/loops-infinite-1.djv +++ b/Task/Loops-Infinite/Deja-Vu/loops-infinite-1.djv @@ -1,2 +1,2 @@ -while True: - print "SPAM" +while true: + !print "SPAM" diff --git a/Task/Loops-Infinite/Deja-Vu/loops-infinite-2.djv b/Task/Loops-Infinite/Deja-Vu/loops-infinite-2.djv index 00f4fa5359..5b60c705eb 100644 --- a/Task/Loops-Infinite/Deja-Vu/loops-infinite-2.djv +++ b/Task/Loops-Infinite/Deja-Vu/loops-infinite-2.djv @@ -1,4 +1,4 @@ labda: - print "SPAM" + !print "SPAM" recurse call diff --git a/Task/Loops-Infinite/GAP/loops-infinite.gap b/Task/Loops-Infinite/GAP/loops-infinite.gap new file mode 100644 index 0000000000..a9f3476695 --- /dev/null +++ b/Task/Loops-Infinite/GAP/loops-infinite.gap @@ -0,0 +1,3 @@ +while true do + Print("SPAM\n"); +od; diff --git a/Task/Loops-N-plus-one-half/GAP/loops-n-plus-one-half.gap b/Task/Loops-N-plus-one-half/GAP/loops-n-plus-one-half.gap new file mode 100644 index 0000000000..77f0783556 --- /dev/null +++ b/Task/Loops-N-plus-one-half/GAP/loops-n-plus-one-half.gap @@ -0,0 +1,9 @@ +n := 10; +for i in [1 .. n] do + Print(i); + if i < n then + Print(", "); + else + Print("\n"); + fi; +od; diff --git a/Task/Loops-Nested/GAP/loops-nested.gap b/Task/Loops-Nested/GAP/loops-nested.gap new file mode 100644 index 0000000000..f81cce4e71 --- /dev/null +++ b/Task/Loops-Nested/GAP/loops-nested.gap @@ -0,0 +1,18 @@ +# You can't break an outer loop unless you return from the whole function. +n := 40; +a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));; + +Find := function(a, x) + local i, j, n; + n := Length(a); + for i in [1 .. n] do + for j in [1 .. n] do + if a[i][j] = x then + return [i, j]; + fi; + od; + od; + return fail; +end; + +Find(a, 20); diff --git a/Task/Loops-Nested/Rust/loops-nested.rust b/Task/Loops-Nested/Rust/loops-nested.rust new file mode 100644 index 0000000000..6588a72044 --- /dev/null +++ b/Task/Loops-Nested/Rust/loops-nested.rust @@ -0,0 +1,23 @@ +// rust 0.9-pre + +use std::rand::Rng; + +fn main() { + let mut matrix = [[0u8, .. 10], .. 10]; + let mut rng = std::rand::os::OSRng::new(); + + for row in matrix.mut_iter() { + for item in row.mut_iter() { + *item = rng.gen_range(0u8, 21); + } + } + + 'outer: + for row in matrix.iter() { + for &item in row.iter() { + print!("{:2} ", item); + if item == 20 { break 'outer; } + } + println!(""); + } +} diff --git a/Task/Loops-Nested/Seed7/loops-nested.seed7 b/Task/Loops-Nested/Seed7/loops-nested.seed7 new file mode 100644 index 0000000000..c910928737 --- /dev/null +++ b/Task/Loops-Nested/Seed7/loops-nested.seed7 @@ -0,0 +1,28 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var integer: i is 0; + var integer: j is 0; + var array array integer: a is 10 times 10 times 0; + const EXCEPTION: FOUND20 is enumlit; + begin + for i range 1 to 10 do + for j range 1 to 10 do + a[i][j] := rand(1, 20); + end for; + end for; + block + for i range 1 to 10 do + for j range 1 to 10 do + write(a[i][j] lpad 2 <& ", "); + if a[i][j] = 20 then + raise FOUND20; + end if; + end for; + writeln; + end for; + exception + catch FOUND20: writeln; + end block; + end func; diff --git a/Task/Loops-While/ColdFusion/loops-while-1.cfm b/Task/Loops-While/ColdFusion/loops-while-1.cfm index 852aa9c44c..e99d889e9e 100644 --- a/Task/Loops-While/ColdFusion/loops-while-1.cfm +++ b/Task/Loops-While/ColdFusion/loops-while-1.cfm @@ -1,5 +1,3 @@ - - - #i#< br /> + #i#< br /> diff --git a/Task/Loops-While/ColdFusion/loops-while-2.cfm b/Task/Loops-While/ColdFusion/loops-while-2.cfm index 35b184f0fa..3ae4d1c5c6 100644 --- a/Task/Loops-While/ColdFusion/loops-while-2.cfm +++ b/Task/Loops-While/ColdFusion/loops-while-2.cfm @@ -1,5 +1,4 @@ - - i = 1024; + i = 1024; while( i > 0 ) { writeOutput( i + "< br/ >" ); diff --git a/Task/Loops-While/Erlang/loops-while.erl b/Task/Loops-While/Erlang/loops-while.erl index 6ff754a098..69f4e0329a 100644 --- a/Task/Loops-While/Erlang/loops-while.erl +++ b/Task/Loops-While/Erlang/loops-while.erl @@ -1,4 +1,3 @@ -%% Implemented by Arjun Sunel -module(while). -export([loop/0]). diff --git a/Task/Loops-While/GAP/loops-while.gap b/Task/Loops-While/GAP/loops-while.gap new file mode 100644 index 0000000000..9573d67ce9 --- /dev/null +++ b/Task/Loops-While/GAP/loops-while.gap @@ -0,0 +1,5 @@ +n := 1024; +while n > 0 do + Print(n, "\n"); + n := QuoInt(n, 2); +od; diff --git a/Task/Loops-While/Maple/loops-while.maple b/Task/Loops-While/Maple/loops-while.maple index 8627fed3f2..f2fef2a2d7 100644 --- a/Task/Loops-While/Maple/loops-while.maple +++ b/Task/Loops-While/Maple/loops-while.maple @@ -1,22 +1,12 @@ > n := 1024: while n > 0 do print(n); n := iquo(n,2) end: 1024 - 512 - 256 - 128 - 64 - 32 - 16 - 8 - 4 - 2 - 1 diff --git a/Task/Loops-While/Neko/loops-while.neko b/Task/Loops-While/Neko/loops-while.neko new file mode 100644 index 0000000000..fad5cf0d10 --- /dev/null +++ b/Task/Loops-While/Neko/loops-while.neko @@ -0,0 +1,6 @@ +var a = 5; +var i = 0; + +while(i < a) { + i = i + 1; +} diff --git a/Task/Loops-While/REXX/loops-while-1.rexx b/Task/Loops-While/REXX/loops-while-1.rexx index 8855f88654..b02b32db13 100644 --- a/Task/Loops-While/REXX/loops-while-1.rexx +++ b/Task/Loops-While/REXX/loops-while-1.rexx @@ -1,6 +1,7 @@ -/*REXX program to show a DO WHILE construct. */ -j=1024 - do while j>0 - say j - j=j%2 /*in REXX, % is integer division. */ - end +/*REXX program demonstrates a DO WHILE with index reduction construct.*/ +j=1024 /*define the initial value of J.*/ + do while j>0 /*test if made at the top of DO.*/ + say j + j=j%2 /*in REXX, % is integer division.*/ + end + /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-While/REXX/loops-while-2.rexx b/Task/Loops-While/REXX/loops-while-2.rexx index b1152c6d20..13ca669cb7 100644 --- a/Task/Loops-While/REXX/loops-while-2.rexx +++ b/Task/Loops-While/REXX/loops-while-2.rexx @@ -1,6 +1,7 @@ -/*REXX program to show a DO WHILE construct. */ -x=1024 - do while x>0 - say right(x,10) /*pretty up the output by aligning.*/ - x=x%2 /*in REXX, % is integer division. */ - end +/*REXX program demonstrates a DO WHILE with index reduction construct.*/ +x=1024 /*define the initial value of X.*/ + do while x>0 /*test if made at the top of DO.*/ + say right(x,10) /*pretty output by aligning right*/ + x=x%2 /*in REXX, % is integer division.*/ + end + /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-While/REXX/loops-while-3.rexx b/Task/Loops-While/REXX/loops-while-3.rexx index 8348a486a6..4a62e44482 100644 --- a/Task/Loops-While/REXX/loops-while-3.rexx +++ b/Task/Loops-While/REXX/loops-while-3.rexx @@ -1,6 +1,7 @@ -/*REXX program to show a DO WHILE construct. */ -x=1024 - do while x>>0 /*this is an exact comparison. */ - say right(x,10) /*pretty up the output by aligning.*/ - x=x%2 /*in REXX, % is integer division. */ - end +/*REXX program demonstrates a DO WHILE with index reduction construct.*/ +x=1024 /*define the initial value of X.*/ + do while x>>0 /*this is an exact comparison. */ + say right(x,10) /*pretty output by aligning right*/ + x=x%2 /*in REXX, % is integer division.*/ + end + /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-While/REXX/loops-while-4.rexx b/Task/Loops-While/REXX/loops-while-4.rexx new file mode 100644 index 0000000000..4f49d9d3eb --- /dev/null +++ b/Task/Loops-While/REXX/loops-while-4.rexx @@ -0,0 +1,7 @@ +/*REXX program demonstrates a DO WHILE with index reduction construct.*/ + /* [↓] note: BY defaults to 1*/ + do j=1024 by 0 while j>>0 /*this is an exact comparison. */ + say right(j,10) /*pretty output by aligning right*/ + j=j%2 /*in REXX, % is integer division.*/ + end + /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-While/Racket/loops-while.rkt b/Task/Loops-While/Racket/loops-while-1.rkt similarity index 100% rename from Task/Loops-While/Racket/loops-while.rkt rename to Task/Loops-While/Racket/loops-while-1.rkt diff --git a/Task/Loops-While/Racket/loops-while-2.rkt b/Task/Loops-While/Racket/loops-while-2.rkt new file mode 100644 index 0000000000..d33eed33fe --- /dev/null +++ b/Task/Loops-While/Racket/loops-while-2.rkt @@ -0,0 +1,11 @@ +#lang racket +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(define n 0) +(while (< n 10) + (displayln n) + (set! n (add1 n))) diff --git a/Task/Loops-While/Scala/loops-while.scala b/Task/Loops-While/Scala/loops-while-1.scala similarity index 100% rename from Task/Loops-While/Scala/loops-while.scala rename to Task/Loops-While/Scala/loops-while-1.scala diff --git a/Task/Loops-While/Scala/loops-while-2.scala b/Task/Loops-While/Scala/loops-while-2.scala new file mode 100644 index 0000000000..26c210baff --- /dev/null +++ b/Task/Loops-While/Scala/loops-while-2.scala @@ -0,0 +1,8 @@ + @tailrec + def loop(iter: Int) { + if ((iter > 0)) { + println(iter) + loop(iter / 2) + } + } + loop(1024) diff --git a/Task/Loops-While/Scala/loops-while-3.scala b/Task/Loops-While/Scala/loops-while-3.scala new file mode 100644 index 0000000000..50f3ff7b5f --- /dev/null +++ b/Task/Loops-While/Scala/loops-while-3.scala @@ -0,0 +1,6 @@ + def loop = new Iterator[Int] { + var i = 1024 + def hasNext = i > 0 + def next(): Int = { val tmp = i; i = i / 2; tmp } + } + loop.foreach(println(_)) diff --git a/Task/Loops-While/Scala/loops-while-4.scala b/Task/Loops-While/Scala/loops-while-4.scala new file mode 100644 index 0000000000..7187220926 --- /dev/null +++ b/Task/Loops-While/Scala/loops-while-4.scala @@ -0,0 +1,2 @@ + def loop(i: Int): Stream[Int] = i #:: (if (i > 0) loop(i / 2) else Stream.empty) + loop(1024).takeWhile(_ > 0).foreach(println(_)) diff --git a/Task/Loops-While/Suneido/loops-while.suneido b/Task/Loops-While/Suneido/loops-while.suneido new file mode 100644 index 0000000000..99017f911b --- /dev/null +++ b/Task/Loops-While/Suneido/loops-while.suneido @@ -0,0 +1,6 @@ +i = 1024 +while (i > 0) + { + Print(i) + i = (i / 2).Floor() + } diff --git a/Task/Lucas-Lehmer-test/AWK/lucas-lehmer-test.awk b/Task/Lucas-Lehmer-test/AWK/lucas-lehmer-test.awk new file mode 100644 index 0000000000..7ca1ae5491 --- /dev/null +++ b/Task/Lucas-Lehmer-test/AWK/lucas-lehmer-test.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -f LUCAS-LEHMER_TEST.AWK +# converted from Pascal +BEGIN { + printf("Mersenne primes:") + n = 1 + for (exponent=2; exponent<=32; exponent++) { + s = (exponent == 2) ? 0 : 4 + n = (n+1)*2-1 + for (i=1; i<=exponent-2; i++) { + s = (s*s-2)%n + } + if (s == 0) { + printf(" M%s",exponent) + } + } + printf("\n") + exit(0) +} diff --git a/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d b/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d index e558142e26..a217bcfd78 100644 --- a/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d +++ b/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d @@ -1,30 +1,30 @@ import std.stdio, std.math, std.bigint; -bool isPrime(int p) pure nothrow { +bool isPrime(in int p) pure nothrow { if (p < 2 || p % 2 == 0) return p == 2; - foreach (i; 3 .. cast(uint)(sqrt(cast(real)p)) + 1) + foreach (immutable i; 3 .. cast(uint)(sqrt(cast(real)p)) + 1) if (p % i == 0) return false; return true; } -bool isMersennePrime(int p) /*pure nothrow*/ { - if (!isPrime(p)) +bool isMersennePrime(in int p) pure /*nothrow*/ { + if (!p.isPrime) return false; if (p == 2) return true; - auto mp = (BigInt(1) << p) - 1; - auto s = BigInt(4); - foreach (_; 3 .. p + 1) + immutable mp = (1.BigInt << p) - 1; + auto s = 4.BigInt; + foreach (immutable _; 3 .. p + 1) s = (s ^^ 2 - 2) % mp; return s == 0; } void main() { - foreach (p; 2 .. 2_300) - if (isMersennePrime(p)) { - write(" M", p); - stdout.flush(); + foreach (immutable p; 2 .. 2_300) + if (p.isMersennePrime) { + write('M', p, ' '); + stdout.flush; } } diff --git a/Task/Lucas-Lehmer-test/GAP/lucas-lehmer-test.gap b/Task/Lucas-Lehmer-test/GAP/lucas-lehmer-test.gap new file mode 100644 index 0000000000..e96e0c9fe5 --- /dev/null +++ b/Task/Lucas-Lehmer-test/GAP/lucas-lehmer-test.gap @@ -0,0 +1,18 @@ +LucasLehmer := function(n) + local i, m, s; + if n = 2 then + return true; + elif not IsPrime(n) then + return false; + else + m := 2^n - 1; + s := 4; + for i in [3 .. n] do + s := RemInt(s*s, m) - 2; + od; + return s = 0; + fi; +end; + +Filtered([1 .. 2000], LucasLehmer); +[2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279] diff --git a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test.py b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-1.py similarity index 100% rename from Task/Lucas-Lehmer-test/Python/lucas-lehmer-test.py rename to Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-1.py diff --git a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py new file mode 100644 index 0000000000..f6839cf8d9 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py @@ -0,0 +1,42 @@ +def isqrt(n): + if n < 0: + raise ValueError + elif n < 2: + return n + else: + a = 1 << ((1 + n.bit_length()) >> 1) + while True: + b = (a + n // a) >> 1 + if b >= a: + return a + a = b + +def isprime(n): + if n < 5: + return n == 2 or n == 3 + elif n%2 == 0: + return False + else: + r = isqrt(n) + k = 3 + while k <= r: + if n%k == 0: + return False + k += 2 + return True + +def lucas_lehmer_fast(n): + if n == 2: + return True + elif not isprime(n): + return False + else: + m = 2**n - 1 + s = 4 + for i in range(2, n): + sqr = s*s + r = (sqr & m) + (sqr >> n) + if r >= m: + r -= m + s = r - 2 + return s == 0 diff --git a/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx b/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx index 7054a4c471..f41356099a 100644 --- a/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx +++ b/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx @@ -1,20 +1,18 @@ -/*REXX program to verify credit card numbers via the Luhn algorithm.*/ -cc. = /*default value for the CC# list.*/ +/*REXX program validates credit card numbers via the Luhn algorithm.*/ +cc. =; @@='the Luhn test for a credit card number.' /*literal*/ cc.1 = 49927398716 /*sample credit card number one. */ cc.2 = 49927398717 /* " " " " two. */ cc.3 = 1234567812345678 /* " " " " three*/ cc.4 = 1234567812345670 /* " " " " four.*/ - @.0=' passed'; @.1="flunked" - do k=1 while cc.k\==''; retCode=LuhnChecksum(cc.k) - say right(cc.k, 30) @.retCode "the Luhn test." - end /*k*/ + do k=1 while cc.k\=='' /*process all the credit card #s.*/ + say right(cc.k, 30) LuhnTest(cc.k) @@ /*see if valid.*/ + end /*k*/ /* [↑] show if it passed/flunked.*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────LUHNCHECKSUM subroutine─────────────*/ -LuhnChecksum: procedure; parse arg t /*checksum for credit card nums. */ -if length(t)//2 then t='0't /*odd #digs? Pad # on left with 0*/ -t=reverse(t); s=0 +/*──────────────────────────────────LUHNTEST subroutine─────────────────*/ +LuhnTest: procedure; parse arg t; s=0 /*get credit card#, set S to zero*/ +t=reverse(left(0,length(t)//2)t) /*add leading 0 if needed,reverse*/ do j=1 to length(t)-1 by 2; q=2*substr(t,j+1,1) - if q>9 then q=left(q,1) + right(q,1) - s=s + substr(t,j,1) + q - end /*j*/ -return s//10\==0 /*returns: 0 (passed), 1 (failed)*/ + s=s + substr(t,j,1) + left(q,1) + substr(q,2,1,0) + end /*j*/ /* [↑] sum odd and even digits.*/ +if s//10==0 then return 'passed ' /*if ending in zero, then passed.*/ + else return 'flunked' /*if ¬ ending in 0, not so good.*/ diff --git a/Task/MD4/AutoHotkey/md4.ahk b/Task/MD4/AutoHotkey/md4.ahk new file mode 100644 index 0000000000..8f88889705 --- /dev/null +++ b/Task/MD4/AutoHotkey/md4.ahk @@ -0,0 +1,52 @@ +str := "Rosetta Code" +MsgBox, % "String:`n" (str) "`n`nMD4:`n" MD4(str) + + + +; MD4 =============================================================================== +MD4(string, encoding = "utf-8") +{ + return CalcStringHash(string, 0x8002, encoding) +} + +; CalcAddrHash ====================================================================== +CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) +{ + static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] + static b := h.minIndex() + o := "" + if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) + { + if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) + { + if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) + { + if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) + { + VarSetCapacity(hash, hashlength, 0) + if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) + { + loop, % hashlength + { + v := NumGet(hash, A_Index - 1, "UChar") + o .= h[(v >> 4) + b] h[(v & 0xf) + b] + } + } + } + } + DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) + } + DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) + } + return o +} + +; CalcStringHash ==================================================================== +CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) +{ + 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) + return CalcAddrHash(&data, length, algid, hash, hashlength) +} diff --git a/Task/MD4/Emacs-Lisp/md4.l b/Task/MD4/Emacs-Lisp/md4.l new file mode 100644 index 0000000000..497d62bcb1 --- /dev/null +++ b/Task/MD4/Emacs-Lisp/md4.l @@ -0,0 +1,7 @@ +(require 'md4) +(let* ((s "Rosetta Code") + (m (md4 s (length s)))) ;; m = 16 binary bytes + (require 'hex-util) + (encode-hex-string m)) +=> +"a52bcfc6a0d0d300cdc5ddbfbefe478b" diff --git a/Task/MD4/Seed7/md4.seed7 b/Task/MD4/Seed7/md4.seed7 new file mode 100644 index 0000000000..2268adff4e --- /dev/null +++ b/Task/MD4/Seed7/md4.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "msgdigest.s7i"; + +const proc: main is func + begin + writeln(hex(md4("Rosetta Code"))); + end func; diff --git a/Task/MD5-Implementation/Seed7/md5-implementation.seed7 b/Task/MD5-Implementation/Seed7/md5-implementation.seed7 new file mode 100644 index 0000000000..a7ded1876d --- /dev/null +++ b/Task/MD5-Implementation/Seed7/md5-implementation.seed7 @@ -0,0 +1,120 @@ +$ include "seed7_05.s7i"; + include "bytedata.s7i"; + include "bin32.s7i"; + include "float.s7i"; + include "math.s7i"; + +# Use binary integer part of the sines of integers (Radians) as constants: +const func array integer: createMd5Table is func + result + var array integer: k is 64 times 0; + local + var integer: index is 0; + begin + for index range 1 to 64 do + k[index] := trunc(abs(sin(flt(index))) * 2.0 ** 32); + end for; + end func; + +const func string: md5 (in var string: message) is func + result + var string: digest is ""; + local + # Specify the per-round shift amounts + const array integer: shiftAmount is [] ( + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21); + const array integer: k is createMd5Table; + var integer: length is 0; + var integer: chunkIndex is 0; + var integer: index is 0; + var array bin32: m is 16 times bin32.value; + var integer: a0 is 16#67452301; # a + var integer: b0 is 16#efcdab89; # b + var integer: c0 is 16#98badcfe; # c + var integer: d0 is 16#10325476; # d + var bin32: a is bin32(0); + var bin32: b is bin32(0); + var bin32: c is bin32(0); + var bin32: d is bin32(0); + var bin32: f is bin32(0); + var integer: g is 0; + var bin32: temp is bin32(0); + begin + length := length(message); + # Append the bit '1' to the message. + 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; + # Append length of message (before pre-processing), in bits, as 64-bit little-endian integer. + message &:= int64AsEightBytesLe(8 * length); + + # Process the message in successive 512-bit chunks: + 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])); + end for; + + a := bin32(a0 mod 16#100000000); + b := bin32(b0 mod 16#100000000); + c := bin32(c0 mod 16#100000000); + d := bin32(d0 mod 16#100000000); + + for index range 1 to 64 do + if index <= 16 then + f := d >< (b & (c >< d)); + g := index; + elsif index <= 32 then + f := c >< (d & (b >< c)); + g := (5 * index - 4) mod 16 + 1; + elsif index <= 48 then + f := b >< c >< d; + g := (3 * index + 2) mod 16 + 1; + else + f := c >< (b | (bin32(16#FFFFFFFF) >< d)); + g := (7 * pred(index)) mod 16 + 1; + end if; + + temp := d; + d := c; + c := b; + b := bin32((ord(b) + + ord(rotLeft(bin32((ord(a) + ord(f) + k[index] + ord(m[g])) mod 16#100000000), + shiftAmount[index]))) mod 16#100000000); + a := temp; + end for; + + # Add this chunk's hash to result so far: + a0 +:= ord(a); + b0 +:= ord(b); + c0 +:= ord(c); + d0 +:= ord(d); + end for; + + # Produce the final hash value: + digest := int32AsFourBytesLe(a0) & + int32AsFourBytesLe(b0) & + int32AsFourBytesLe(c0) & + int32AsFourBytesLe(d0); + end func; + +const func boolean: checkMd5 (in string: message, in string: hexMd5) is + return hex(md5(message)) = hexMd5; + +const proc: main is func + begin + if checkMd5("", "d41d8cd98f00b204e9800998ecf8427e") and + checkMd5("a", "0cc175b9c0f1b6a831c399e269772661") and + checkMd5("abc", "900150983cd24fb0d6963f7d28e17f72") and + checkMd5("message digest", "f96b697d7cb7938d525a2f31aaf161d0") and + checkMd5("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b") and + checkMd5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f") and + checkMd5("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a") then + writeln("md5 is computed correct"); + else + writeln("There is an error in the md5 function"); + end if; + end func; diff --git a/Task/MD5/Emacs-Lisp/md5-1.l b/Task/MD5/Emacs-Lisp/md5-1.l new file mode 100644 index 0000000000..27cf16d62b --- /dev/null +++ b/Task/MD5/Emacs-Lisp/md5-1.l @@ -0,0 +1,3 @@ +(md5 "The quick brown fox jumped over the lazy dog's back") +=> +"e38ca1d920c4b8b8d3946b2c72f01680" diff --git a/Task/MD5/Emacs-Lisp/md5-2.l b/Task/MD5/Emacs-Lisp/md5-2.l new file mode 100644 index 0000000000..335ce0d03c --- /dev/null +++ b/Task/MD5/Emacs-Lisp/md5-2.l @@ -0,0 +1,6 @@ +(require 'hmac-md5) +(require 'hex-util) +(encode-hex-string + (md5-binary "The quick brown fox jumped over the lazy dog's back")) +=> +"e38ca1d920c4b8b8d3946b2c72f01680" diff --git a/Task/MD5/Seed7/md5.seed7 b/Task/MD5/Seed7/md5.seed7 new file mode 100644 index 0000000000..ceaef8de9e --- /dev/null +++ b/Task/MD5/Seed7/md5.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "msgdigest.s7i"; + +const proc: main is func + begin + writeln(hex(md5("The quick brown fox jumped over the lazy dog's back"))); + end func; diff --git a/Task/Mad-Libs/AWK/mad-libs-1.awk b/Task/Mad-Libs/AWK/mad-libs-1.awk new file mode 100644 index 0000000000..ea8fb07835 --- /dev/null +++ b/Task/Mad-Libs/AWK/mad-libs-1.awk @@ -0,0 +1,34 @@ +# syntax: GAWK -f MAD_LIBS.AWK +BEGIN { + print("enter story:") +} +{ story_arr[++nr] = $0 + if ($0 ~ /^ *$/) { + exit + } + while ($0 ~ /[<>]/) { + L = index($0,"<") + R = index($0,">") + changes_arr[substr($0,L,R-L+1)] = "" + sub(//,"",$0) + } +} +END { + PROCINFO["sorted_in"] = "@ind_str_asc" + print("enter values for:") + for (i in changes_arr) { # prompt for replacement values + printf("%s ",i) + getline rec + sub(/ +$/,"",rec) + changes_arr[i] = rec + } + printf("\nrevised story:\n") + for (i=1; i<=nr; i++) { # print the story + for (j in changes_arr) { + gsub(j,changes_arr[j],story_arr[i]) + } + printf("%s\n",story_arr[i]) + } + exit(0) +} diff --git a/Task/Mad-Libs/AWK/mad-libs-2.awk b/Task/Mad-Libs/AWK/mad-libs-2.awk new file mode 100644 index 0000000000..f70982a677 --- /dev/null +++ b/Task/Mad-Libs/AWK/mad-libs-2.awk @@ -0,0 +1,48 @@ +#include +#include +using namespace std; + +int main() +{ + string story, input; + + //Loop + while(true) + { + //Get a line from the user + getline(cin, input); + + //If it's blank, break this loop + if(input == "\r") + break; + + //Add the line to the story + story += input; + } + + //While there is a '<' in the story + int begin; + while((begin = story.find("<")) != string::npos) + { + //Get the category from between '<' and '>' + int end = story.find(">"); + string cat = story.substr(begin + 1, end - begin - 1); + + //Ask the user for a replacement + cout << "Give me a " << cat << ": "; + cin >> input; + + //While there's a matching category + //in the story + while((begin = story.find("<" + cat + ">")) != string::npos) + { + //Replace it with the user's replacement + story.replace(begin, cat.length()+2, input); + } + } + + //Output the final story + cout << endl << story; + + return 0; +} diff --git a/Task/Mad-Libs/AutoHotkey/mad-libs.ahk b/Task/Mad-Libs/AutoHotkey/mad-libs.ahk new file mode 100644 index 0000000000..416fb01ebb --- /dev/null +++ b/Task/Mad-Libs/AutoHotkey/mad-libs.ahk @@ -0,0 +1,13 @@ +FileSelectFile, filename, , %A_ScriptDir%, Select a Mad Libs template, *.txt +If ErrorLevel + ExitApp ; the user canceled the file selection +FileRead, contents, %filename% +pos := match := 0 +While pos := RegExMatch(contents, "<[^>]+>", match, pos+strLen(match)) +{ + InputBox, repl, Mad Libs, Enter a replacement for %match%: + If ErrorLevel ; cancelled inputbox + ExitApp + StringReplace, contents, contents, %match%, %repl%, All +} +MsgBox % contents diff --git a/Task/Mad-Libs/PL-I/mad-libs.pli b/Task/Mad-Libs/PL-I/mad-libs.pli new file mode 100644 index 0000000000..f76c8c0fbf --- /dev/null +++ b/Task/Mad-Libs/PL-I/mad-libs.pli @@ -0,0 +1,71 @@ +(stringrange, stringsize): /* 2 Nov. 2013 */ +Mad_Libs: procedure options (main); + declare (line, left, right) character (100) varying; + declare true bit(1) value ('1'b), false bit (1) value ('0'b); + declare name character (20) varying, seen_name bit (1) initial (false); + declare pronoun character (20) varying, seen_pronoun bit (1) initial (false); + declare noun character (20) varying, seen_noun bit (1) initial (false); + declare replaced_all bit (1); + declare in file input; + + open file (in) title ('/MADLIBS.DAT,type(text),recsize(100)'); + + do forever; + get file (in) edit (line) (L); + if line = '' then leave; + + do until (replaced_all); + replaced_all = true; + if index(line, '') > 0 then + if seen_name then + do until (index(line, '') = 0); + call split(line, '', left, right); + line = left || name || right; + replaced_all = false; + end; + else + do; + put skip list ('Please type a name:'); + get edit (name) (L); + seen_name = true; replaced_all = false; + end; + if index(line, '') > 0 then + if seen_pronoun then + do until (index(line, '') = 0); + call split(line, '', left, right); + line = left || pronoun || right; + replaced_all = false; + end; + else + do; + put skip list ('Please type a pronoun (he or she):'); + get edit (pronoun) (L); + seen_pronoun = true; replaced_all = false; + end; + if index(line, '') > 0 then + if seen_noun then + do until (index(line, '') = 0); + call split(line, '', left, right); + line = left || noun || right; + replaced_all = false; + end; + else + do; + put skip list ('Please type a noun:'); + get edit (noun) (L); + seen_noun = true; replaced_all = false; + end; + end; + put skip list (line); + end; + +split: procedure (line, text, Left, Right); + declare (line, text, left, right) character (*) varying; + declare i fixed binary; + + i = index(line, text); + left = substr(line, 1, i-1); + right = substr(line, i+length(text), length(line) - (i + length(text)) + 1 ); +end split; + +end Mad_Libs; diff --git a/Task/Mad-Libs/Perl/mad-libs.pl b/Task/Mad-Libs/Perl/mad-libs.pl new file mode 100644 index 0000000000..3496a9a7fd --- /dev/null +++ b/Task/Mad-Libs/Perl/mad-libs.pl @@ -0,0 +1,19 @@ +#!/usr/bin/perl +use warnings; +use strict; + +my $template = shift; +open my $IN, '<', $template or die $!; +my $story = do { local $/ ; <$IN> }; + +my %blanks; +undef $blanks{$_} for $story =~ m/<(.*?)>/g; + +for my $blank (sort keys %blanks) { + print "$blank: "; + chomp (my $replacement = <>); + $blanks{$blank} = $replacement; +} + +$story =~ s/<(.*?)>/$blanks{$1}/g; +print $story; diff --git a/Task/Man-or-boy-test/Deja-Vu/man-or-boy-test.djv b/Task/Man-or-boy-test/Deja-Vu/man-or-boy-test.djv new file mode 100644 index 0000000000..a1d2d84b0d --- /dev/null +++ b/Task/Man-or-boy-test/Deja-Vu/man-or-boy-test.djv @@ -0,0 +1,13 @@ +a k x1 x2 x3 x4 x5: + local b: + set :k -- k + a k @b @x1 @x2 @x3 @x4 + if <= k 0: + + x4 x5 + else: + b +local x i: + labda: + i + +!. a 10 x 1 x -1 x -1 x 1 x 0 diff --git a/Task/Man-or-boy-test/Groovy/man-or-boy-test-1.groovy b/Task/Man-or-boy-test/Groovy/man-or-boy-test-1.groovy new file mode 100644 index 0000000000..83e4959c7e --- /dev/null +++ b/Task/Man-or-boy-test/Groovy/man-or-boy-test-1.groovy @@ -0,0 +1,8 @@ +def a; a = { k, x1, x2, x3, x4, x5 -> + def b; b = { + a (--k, b, x1, x2, x3, x4) + } + k <= 0 ? x4() + x5() : b() +} + +def x = { n -> { it -> n } } diff --git a/Task/Man-or-boy-test/Groovy/man-or-boy-test-2.groovy b/Task/Man-or-boy-test/Groovy/man-or-boy-test-2.groovy new file mode 100644 index 0000000000..fc2585a174 --- /dev/null +++ b/Task/Man-or-boy-test/Groovy/man-or-boy-test-2.groovy @@ -0,0 +1 @@ +println (a(10, x(1), x(-1), x(-1), x(1), x(0))) diff --git a/Task/Man-or-boy-test/Groovy/man-or-boy-test-3.groovy b/Task/Man-or-boy-test/Groovy/man-or-boy-test-3.groovy new file mode 100644 index 0000000000..9f36122a6c --- /dev/null +++ b/Task/Man-or-boy-test/Groovy/man-or-boy-test-3.groovy @@ -0,0 +1,3 @@ +(0..20).each { k -> + printf ("%3d: %7d\n", k, a(k, x(1), x(-1), x(-1), x(1), x(0))) +} diff --git a/Task/Mandelbrot-set/D/mandelbrot-set-1.d b/Task/Mandelbrot-set/D/mandelbrot-set-1.d index 86887653b8..551c8ea6fe 100644 --- a/Task/Mandelbrot-set/D/mandelbrot-set-1.d +++ b/Task/Mandelbrot-set/D/mandelbrot-set-1.d @@ -1,15 +1,12 @@ void main() { - import std.stdio, std.complex, std.range; + import std.stdio, std.complex; - enum maxIter = 100; - foreach (immutable y; iota(-1.2, 1.2, 0.05)) { - foreach (immutable x; iota(-2.05, 0.55, 0.03)) { - immutable c = complex(x, y); - auto z = complex(0), - i = 0; - for (; i < maxIter && z.abs < 4; i++) - z = z ^^ 2 + c; - write(i == maxIter ? '#' : '.'); + for (real y = -1.2; y < 1.2; y += 0.05) { + for (real x = -2.05; x < 0.55; x += 0.03) { + auto z = 0.complex; + foreach (_; 0 .. 100) + z = z ^^ 2 + complex(x, y); + write(z.abs < 2 ? '#' : '.'); } writeln; } diff --git a/Task/Mandelbrot-set/D/mandelbrot-set-2.d b/Task/Mandelbrot-set/D/mandelbrot-set-2.d index f9c4297fbf..e555458f0b 100644 --- a/Task/Mandelbrot-set/D/mandelbrot-set-2.d +++ b/Task/Mandelbrot-set/D/mandelbrot-set-2.d @@ -1,27 +1,8 @@ -import qd; - -double lensqr(cdouble c) { return c.re * c.re + c.im * c.im; } - -const Limit = 150; - void main() { - screen(640, 480); - for (int y = 0; y < screen.h; ++y) { - flip; events; - for (int x = 0; x < screen.w; ++x) { - auto - c_x = x * 1.0 / screen.w - 0.5, - c_y = y * 1.0 / screen.h - 0.5, - c = c_y * 2.0i + c_x * 3.0 - 1.0, - z = 0.0i + 0.0, - i = 0; - for (; i < Limit; ++i) { - z = z * z + c; - if (lensqr(z) > 4) break; - } - auto value = cast(ubyte) (i * 255.0 / Limit); - pset(x, y, rgb(value, value, value)); - } - } - while (true) { flip; events; } + import std.stdio, std.complex, std.range, std.algorithm; + + foreach (immutable y; iota(-1.2, 1.2, 0.05)) + iota(-2.05, 0.55, 0.03).map!(x => 0.complex + .recurrence!((a, n) => a[n - 1] ^^ 2 + complex(x, y)) + .drop(100).front.abs < 2 ? '#' : '.').writeln; } diff --git a/Task/Mandelbrot-set/D/mandelbrot-set-3.d b/Task/Mandelbrot-set/D/mandelbrot-set-3.d new file mode 100644 index 0000000000..f9c4297fbf --- /dev/null +++ b/Task/Mandelbrot-set/D/mandelbrot-set-3.d @@ -0,0 +1,27 @@ +import qd; + +double lensqr(cdouble c) { return c.re * c.re + c.im * c.im; } + +const Limit = 150; + +void main() { + screen(640, 480); + for (int y = 0; y < screen.h; ++y) { + flip; events; + for (int x = 0; x < screen.w; ++x) { + auto + c_x = x * 1.0 / screen.w - 0.5, + c_y = y * 1.0 / screen.h - 0.5, + c = c_y * 2.0i + c_x * 3.0 - 1.0, + z = 0.0i + 0.0, + i = 0; + for (; i < Limit; ++i) { + z = z * z + c; + if (lensqr(z) > 4) break; + } + auto value = cast(ubyte) (i * 255.0 / Limit); + pset(x, y, rgb(value, value, value)); + } + } + while (true) { flip; events; } +} diff --git a/Task/Mandelbrot-set/Mathematica/mandelbrot-set.math b/Task/Mandelbrot-set/Mathematica/mandelbrot-set-1.math similarity index 100% rename from Task/Mandelbrot-set/Mathematica/mandelbrot-set.math rename to Task/Mandelbrot-set/Mathematica/mandelbrot-set-1.math diff --git a/Task/Mandelbrot-set/Mathematica/mandelbrot-set-2.math b/Task/Mandelbrot-set/Mathematica/mandelbrot-set-2.math new file mode 100644 index 0000000000..f934377d57 --- /dev/null +++ b/Task/Mandelbrot-set/Mathematica/mandelbrot-set-2.math @@ -0,0 +1,7 @@ +cf = With[{ + mandel = Block[{z = #, c = #}, + Catch@Do[If[Abs[z] > 2, Throw@i]; z = z^2 + c, {i, 100}]] & + }, + Compile[{},Table[mandel[y + x I], {x, -1, 1, 0.005}, {y, -2, 0.5, 0.005}]] + ]; +ArrayPlot[cf[]] diff --git a/Task/Map-range/AWK/map-range.awk b/Task/Map-range/AWK/map-range.awk new file mode 100644 index 0000000000..aded11a371 --- /dev/null +++ b/Task/Map-range/AWK/map-range.awk @@ -0,0 +1,14 @@ +# syntax: GAWK -f MAP_RANGE.AWK +BEGIN { + a1 = 0 + a2 = 10 + b1 = -1 + b2 = 0 + for (i=a1; i<=a2; i++) { + printf("%g maps to %g\n",i,map_range(a1,a2,b1,b2,i)) + } + exit(0) +} +function map_range(a1,a2,b1,b2,num) { + return b1 + ((num-a1) * (b2-b1) / (a2-a1)) +} diff --git a/Task/Map-range/Julia/map-range.julia b/Task/Map-range/Julia/map-range.julia new file mode 100644 index 0000000000..35c8707e3f --- /dev/null +++ b/Task/Map-range/Julia/map-range.julia @@ -0,0 +1,3 @@ +maprange(s, a, b) = let a1 = minimum(a), a2 = maximum(a), b1 = minimum(b), b2 = maximum(b) + b1 + (s-a1) * (b2-b1) / (a2-a1) +end diff --git a/Task/Map-range/REXX/map-range-4.rexx b/Task/Map-range/REXX/map-range-4.rexx new file mode 100644 index 0000000000..6543c0d9f7 --- /dev/null +++ b/Task/Map-range/REXX/map-range-4.rexx @@ -0,0 +1,11 @@ +/*REXX program maps a number from one range to another range. */ +/* 31.10.2013 Walter Pachl +/* 'translated' from version 1 without using Procedure */ + do j=0 to 10 + say right(j,3) ' maps to ' mapRange(0,10,-1,0,j) + end +exit /*stick a fork in it, we're done.*/ + +/*──────────────────────────────────MAPRANGE subroutine─────────────────*/ +mapRange: return arg(3)+(arg(5)-arg(1))*(arg(4)-arg(3))/(arg(2)-arg(1)) +/* Arguments are arg a1,a2,b1,b2,x */ diff --git a/Task/Matrix-arithmetic/D/matrix-arithmetic.d b/Task/Matrix-arithmetic/D/matrix-arithmetic.d index 58ad1a48f6..0c72dc70c3 100644 --- a/Task/Matrix-arithmetic/D/matrix-arithmetic.d +++ b/Task/Matrix-arithmetic/D/matrix-arithmetic.d @@ -1,7 +1,7 @@ import std.algorithm, std.range, std.traits, permutations2, permutations_by_swapping1; -auto prod(Range)(/*in*/ Range r) /*pure nothrow*/ { +auto prod(Range)(Range r) /*pure*/ nothrow { return reduce!q{a * b}(cast(ForeachType!Range)1, r); } diff --git a/Task/Matrix-arithmetic/Go/matrix-arithmetic.go b/Task/Matrix-arithmetic/Go/matrix-arithmetic.go new file mode 100644 index 0000000000..417f55a10c --- /dev/null +++ b/Task/Matrix-arithmetic/Go/matrix-arithmetic.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "permute" +) + +func determinant(m [][]float64) (d float64) { + p := make([]int, len(m)) + for i := range p { + p[i] = i + } + it := permute.Iter(p) + for s := it(); s != 0; s = it() { + pr := 1. + for i, σ := range p { + pr *= m[i][σ] + } + d += float64(s) * pr + } + return +} + +func permanent(m [][]float64) (d float64) { + p := make([]int, len(m)) + for i := range p { + p[i] = i + } + it := permute.Iter(p) + for s := it(); s != 0; s = it() { + pr := 1. + for i, σ := range p { + pr *= m[i][σ] + } + d += pr + } + return +} + +var m2 = [][]float64{ + {1, 2}, + {3, 4}} + +var m3 = [][]float64{ + {2, 9, 4}, + {7, 5, 3}, + {6, 1, 8}} + +func main() { + fmt.Println(determinant(m2), permanent(m2)) + fmt.Println(determinant(m3), permanent(m3)) +} diff --git a/Task/Matrix-arithmetic/Julia/matrix-arithmetic-1.julia b/Task/Matrix-arithmetic/Julia/matrix-arithmetic-1.julia new file mode 100644 index 0000000000..c0dd32ed96 --- /dev/null +++ b/Task/Matrix-arithmetic/Julia/matrix-arithmetic-1.julia @@ -0,0 +1 @@ +det(A) diff --git a/Task/Matrix-arithmetic/Julia/matrix-arithmetic-2.julia b/Task/Matrix-arithmetic/Julia/matrix-arithmetic-2.julia new file mode 100644 index 0000000000..776b7df4ee --- /dev/null +++ b/Task/Matrix-arithmetic/Julia/matrix-arithmetic-2.julia @@ -0,0 +1,5 @@ +function perm(A) + m, n = size(A) + if m != n; throw(ArgumentError("permanent is for square matrices only")); end + sum(σ -> prod(i -> A[i,σ[i]], 1:n), permutations(1:n)) +end diff --git a/Task/Matrix-arithmetic/Julia/matrix-arithmetic-3.julia b/Task/Matrix-arithmetic/Julia/matrix-arithmetic-3.julia new file mode 100644 index 0000000000..c34f7799ac --- /dev/null +++ b/Task/Matrix-arithmetic/Julia/matrix-arithmetic-3.julia @@ -0,0 +1,3 @@ +julia> A = [2 9 4; 7 5 3; 6 1 8] +julia> det(A), perm(A) +(-360.0,900) diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-2.d b/Task/Matrix-multiplication/D/matrix-multiplication-2.d index 711ddcc1b9..de5a108536 100644 --- a/Task/Matrix-multiplication/D/matrix-multiplication-2.d +++ b/Task/Matrix-multiplication/D/matrix-multiplication-2.d @@ -1,6 +1,6 @@ import std.stdio, std.range, std.array, std.numeric, std.algorithm; -T[][] matMul(T)(in T[][] A, in T[][] B) /*pure nothrow*/ { +T[][] matMul(T)(in T[][] A, in T[][] B) /*pure*/ nothrow { const Bt = B[0].length.iota.map!(i=> B.transversal(i).array).array; return A.map!(a => Bt.map!(b => a.dotProduct(b)).array).array; } diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-3.d b/Task/Matrix-multiplication/D/matrix-multiplication-3.d index edd95884d2..f89ce5bff6 100644 --- a/Task/Matrix-multiplication/D/matrix-multiplication-3.d +++ b/Task/Matrix-multiplication/D/matrix-multiplication-3.d @@ -1,30 +1,18 @@ -import std.stdio, std.string, std.conv, std.numeric, std.array, - std.algorithm, std.traits; +import std.stdio, std.range, std.numeric, std.algorithm; -alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1)) - [M2.init[0].length][M1.length]; - -void matrixMul(T, T2, size_t k, size_t m, size_t n) - (in ref T[m][k] A, in ref T[n][m] B, - /*out*/ ref T2[n][k] result) pure nothrow -if (is(T2 == Unqual!T)) { - T2[m] aux; - foreach (immutable j; 0 .. n) { - foreach (immutable k, const row; B) - aux[k] = row[j]; - foreach (immutable i, const ai; A) - result[i][j] = dotProduct(ai, aux); - } +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; } void main() { - immutable int[2][3] a = [[1, 2], [3, 4], [3, 6]]; - immutable int[3][2] b = [[-3, -8, 3,], [-2, 1, 4]]; + immutable a = [[1, 2], [3, 4], [3, 6]]; + immutable b = [[-3, -8, 3,], [-2, 1, 4]]; - enum form = "[%([%(%d, %)],\n %)]]"; + immutable form = "[%([%(%d, %)],\n %)]]"; writefln("A = \n" ~ form ~ "\n", a); writefln("B = \n" ~ form ~ "\n", b); - TMMul_helper!(typeof(a), typeof(b)) result = void; - matrixMul(a, b, result); - writefln("A * B = \n" ~ form, result); + writefln("A * B = \n" ~ form, matMul(a, b)); } diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-4.d b/Task/Matrix-multiplication/D/matrix-multiplication-4.d new file mode 100644 index 0000000000..ed0c098146 --- /dev/null +++ b/Task/Matrix-multiplication/D/matrix-multiplication-4.d @@ -0,0 +1,29 @@ +import std.stdio, std.string, std.numeric, std.algorithm, std.traits; + +alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1)) + [M2.init[0].length][M1.length]; + +void matrixMul(T, T2, size_t k, size_t m, size_t n) + (in ref T[m][k] A, in ref T[n][m] B, + /*out*/ ref T2[n][k] result) pure nothrow +if (is(T2 == Unqual!T)) { + T2[m] aux; + foreach (immutable j; 0 .. n) { + foreach (immutable i, const ref bi; B) + aux[i] = bi[j]; + foreach (immutable i, const ref ai; A) + result[i][j] = dotProduct(ai, aux); + } +} + +void main() { + immutable int[2][3] a = [[1, 2], [3, 4], [3, 6]]; + immutable int[3][2] b = [[-3, -8, 3,], [-2, 1, 4]]; + + enum form = "[%([%(%d, %)],\n %)]]"; + writefln("A = \n" ~ form ~ "\n", a); + writefln("B = \n" ~ form ~ "\n", b); + TMMul_helper!(typeof(a), typeof(b)) result = void; + matrixMul(a, b, result); + writefln("A * B = \n" ~ form, result); +} diff --git a/Task/Matrix-multiplication/Ruby/matrix-multiplication-2.rb b/Task/Matrix-multiplication/Ruby/matrix-multiplication-2.rb index b30b2072af..d67ce2d1d4 100644 --- a/Task/Matrix-multiplication/Ruby/matrix-multiplication-2.rb +++ b/Task/Matrix-multiplication/Ruby/matrix-multiplication-2.rb @@ -1,7 +1,7 @@ def matrix_mult(a, b) a.map do |ar| b.transpose.map do |bc| - ar.zip(bc).map {|x,y| x*y}.inject {|z,w| z+w} + ar.zip(bc).map(&:*).inject(&:+) end end end diff --git a/Task/Matrix-transposition/D/matrix-transposition-1.d b/Task/Matrix-transposition/D/matrix-transposition-1.d index 42276d985f..163f341201 100644 --- a/Task/Matrix-transposition/D/matrix-transposition-1.d +++ b/Task/Matrix-transposition/D/matrix-transposition-1.d @@ -1,17 +1,8 @@ -import std.stdio; - -T[][] transpose(T)(immutable /*in*/ T[][] m) pure nothrow { - auto r = new typeof(return)(m[0].length, m.length); - foreach (nr, row; m) - foreach (nc, c; row) - r[nc][nr] = c; - return r; -} - void main() { - immutable M = [[10, 11, 12, 13], - [14, 15, 16, 17], - [18, 19, 20, 21]]; - immutable T = transpose(M); - writefln("%(%(%2d %)\n%)", T); + import std.stdio, std.range; + + /*immutable*/ auto M = [[10, 11, 12, 13], + [14, 15, 16, 17], + [18, 19, 20, 21]]; + writefln("%(%(%2d %)\n%)", M.transposed); } diff --git a/Task/Matrix-transposition/D/matrix-transposition-2.d b/Task/Matrix-transposition/D/matrix-transposition-2.d index 7df595ab61..42873ed063 100644 --- a/Task/Matrix-transposition/D/matrix-transposition-2.d +++ b/Task/Matrix-transposition/D/matrix-transposition-2.d @@ -1,13 +1,16 @@ -import std.stdio, std.algorithm, std.range; - -auto transpose(T)(in T[][] m) /*pure nothrow*/ { - return m[0].length.iota.map!(i => m.transversal(i)); +T[][] transpose(T)(in T[][] m) pure nothrow { + auto r = new typeof(return)(m[0].length, m.length); + foreach (immutable nr, const row; m) + foreach (immutable nc, immutable c; row) + r[nc][nr] = c; + return r; } void main() { + import std.stdio; + immutable M = [[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]]; - /*immutable*/ auto T = M.transpose; - writefln("%(%(%2d %)\n%)", T); + writefln("%(%(%2d %)\n%)", M.transpose); } diff --git a/Task/Matrix-transposition/D/matrix-transposition-3.d b/Task/Matrix-transposition/D/matrix-transposition-3.d new file mode 100644 index 0000000000..996994adb1 --- /dev/null +++ b/Task/Matrix-transposition/D/matrix-transposition-3.d @@ -0,0 +1,12 @@ +import std.stdio, std.algorithm, std.range, std.functional; + +auto transpose(T)(in T[][] m) pure nothrow { + return m[0].length.iota.map!(curry!(transversal, m)); +} + +void main() { + immutable M = [[10, 11, 12, 13], + [14, 15, 16, 17], + [18, 19, 20, 21]]; + writefln("%(%(%2d %)\n%)", M.transpose); +} diff --git a/Task/Maze-generation/D/maze-generation.d b/Task/Maze-generation/D/maze-generation.d index 616d51f9c9..721c69a14a 100644 --- a/Task/Maze-generation/D/maze-generation.d +++ b/Task/Maze-generation/D/maze-generation.d @@ -1,21 +1,18 @@ -import std.stdio, std.algorithm, std.range, std.random; -alias R = std.array.replicate; - void main() { - enum int w = 14, h = 10; - auto vis = new bool[][](h, w), - hor = iota(h + 1).map!(_ => ["+---"].R(w)).array, - ver = h.iota.map!(_ => ["| "].R(w) ~ "|").array; + import std.stdio, std.algorithm, std.range, std.random; - void walk(in int x, in int y) /*nothrow*/ { + enum uint w = 14, h = 10; + auto vis = new bool[][](h, w), + hor = iota(h + 1).map!(_ => ["+---"].replicate(w)).array, + ver = h.iota.map!(_ => ["| "].replicate(w) ~ "|").array; + + void walk(in uint x, in uint y) /*nothrow*/ { vis[y][x] = true; - static struct P { immutable uint x, y; } // Will wrap-around. - auto d = [P(x-1, y), P(x, y+1), P(x+1, y), P(x, y-1)]; - foreach (p; d.randomCover) { - if (p.x >= w || p.y >= h || vis[p.y][p.x]) continue; - if (p.x == x) hor[max(y, p.y)][x] = "+ "; - if (p.y == y) ver[y][max(x, p.x)] = " "; - walk(p.tupleof); + foreach (p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) { + if (p[0] >= w || p[1] >= h || vis[p[1]][p[0]]) continue; + if (p[0] == x) hor[max(y, p[1])][x] = "+ "; + if (p[1] == y) ver[y][max(x, p[0])] = " "; + walk(p[0], p[1]); } } walk(uniform(0, w), uniform(0, h)); diff --git a/Task/Maze-generation/Scala/maze-generation.scala b/Task/Maze-generation/Scala/maze-generation.scala new file mode 100644 index 0000000000..9f92f6fd75 --- /dev/null +++ b/Task/Maze-generation/Scala/maze-generation.scala @@ -0,0 +1,86 @@ +import scala.util.Random + +object MazeTypes { + case class Direction(val dx: Int, val dy: Int) + + case class Loc(val x: Int, val y: Int) { + def +(that: Direction): Loc = Loc(x + that.dx, y + that.dy) + } + + case class Door(val from: Loc, to: Loc) + + val North = Direction(0,-1) + val South = Direction(0,1) + val West = Direction(-1,0) + val East = Direction(1,0) + val directions = Set(North, South, West, East) +} + +object MazeBuilder { + import MazeTypes._ + + def shuffle[T](set: Set[T]): List[T] = Random.shuffle(set.toList) + + def buildImpl(current: Loc, grid: Grid): Grid = { + var newgrid = grid.markVisited(current) + val nbors = shuffle(grid.neighbors(current)) + nbors.foreach { n => + if (!newgrid.isVisited(n)) { + newgrid = buildImpl(n, newgrid.markVisited(current).addDoor(Door(current, n))) + } + } + newgrid + } + + def build(width: Int, height: Int): Grid = { + val exit = Loc(width-1, height-1) + buildImpl(exit, new Grid(width, height, Set(), Set())) + } +} + +class Grid(val width: Int, val height: Int, val doors: Set[Door], val visited: Set[Loc]) { + + def addDoor(door: Door): Grid = + new Grid(width, height, doors + door, visited) + + def markVisited(loc: Loc): Grid = + new Grid(width, height, doors, visited + loc) + + def isVisited(loc: Loc): Boolean = + visited.contains(loc) + + def neighbors(current: Loc): Set[Loc] = + directions.map(current + _).filter(inBounds(_)) -- visited + + def printGrid(): List[String] = { + (0 to height).toList.flatMap(y => printRow(y)) + } + + private def inBounds(loc: Loc): Boolean = + loc.x >= 0 && loc.x < width && loc.y >= 0 && loc.y < height + + private def printRow(y: Int): List[String] = { + val row = (0 until width).toList.map(x => printCell(Loc(x, y))) + val rightSide = if (y == height-1) " " else "|" + val newRow = row :+ List("+", rightSide) + List.transpose(newRow).map(_.mkString) + } + + private val entrance = Loc(0,0) + + private def printCell(loc: Loc): List[String] = { + if (loc.y == height) + List("+--") + else List( + if (openNorth(loc)) "+ " else "+--", + if (openWest(loc) || loc == entrance) " " else "| " + ) + } + + def openNorth(loc: Loc): Boolean = openInDirection(loc, North) + + def openWest(loc: Loc): Boolean = openInDirection(loc, West) + + private def openInDirection(loc: Loc, dir: Direction): Boolean = + doors.contains(Door(loc, loc + dir)) || doors.contains(Door(loc + dir, loc)) +} diff --git a/Task/Maze-solving/Icon/maze-solving-3.icon b/Task/Maze-solving/Icon/maze-solving-3.icon index 863b145068..ca7f6f4294 100644 --- a/Task/Maze-solving/Icon/maze-solving-3.icon +++ b/Task/Maze-solving/Icon/maze-solving-3.icon @@ -11,7 +11,7 @@ procedure main(A) mz := DisplayMaze(GenerateMaze(mh,mw)) # Build and show maze - QMouse(mz.maze,findStart(mz.maze)) # Start first quantum mouse + QMouse(mz.maze,findStart(mz.maze),&null,0) # Start first quantum mouse waitForCompletion() # block until all quantum mice have finished # Mark the best path into the maze and display it. @@ -44,9 +44,11 @@ $define SOUTH 2 $define WEST 1 $define EMPTY 0 # like new -class QMouse(maze, loc, path, val) +class QMouse(maze, loc, parent, len, val) - method getPath(); return path; end + method getLoc(); return loc; end + method getParent(); return \parent; end + method getLen(); return len; end method atEnd(); return EMPTY ~= iand(val, FINISH); end method goNorth(); if EMPTY ~= iand(val,NORTH) then return visit(loc.r-1, loc.c); end method goSouth(); if EMPTY ~= iand(val,SOUTH) then return visit(loc.r+1, loc.c); end @@ -55,7 +57,7 @@ class QMouse(maze, loc, path, val) method visit(r,c) critical region[r,c]: if EMPTY = iand(maze[r,c],SEEN) then { - if /bestMouse | (*path <= *bestMouse.path) then { # Keep going? + if /bestMouse | (len <= bestMouse.getLen()) then { # Keep going? mark(maze, r,c) unlock(region[r,c]) return Position(r,c) @@ -63,7 +65,7 @@ class QMouse(maze, loc, path, val) } end -initially (m, l, p) +initially (m, l, p, n) initial { # Construct critical region mutexes and completion condvar qMice := mutex(set()) qMiceEmpty := condvar() @@ -74,21 +76,20 @@ initially (m, l, p) } maze := m loc := l + parent := p + len := n+1 val := maze[loc.r,loc.c] | fail # Fail if outside maze - /path := [] - if \p then path := copy(p) - put(path, loc) insert(qMice, self) thread { if atEnd() then { critical bestMouseLock: - if /bestMouse | (*path < bestMouse.path) then bestMouse := self + if /bestMouse | (len < bestMouse.getLen()) then bestMouse := self } else { # Spawn more mice to look for finish - QMouse(maze, goNorth(), path) - QMouse(maze, goSouth(), path) - QMouse(maze, goEast(), path) - QMouse(maze, goWest(), path) + QMouse(maze, goNorth(), self, len) + QMouse(maze, goSouth(), self, len) + QMouse(maze, goEast(), self, len) + QMouse(maze, goWest(), self, len) } delete(qMice, self) @@ -114,8 +115,12 @@ procedure findStart(maze) # Anywhere in maze end procedure showPath(maze) - if \bestMouse then { # Mark it in maze - every p := !bestMouse.path do maze[p.r,p.c] +:= PATH + if path := \bestMouse then { # Mark it in maze + repeat { + loc := path.getLoc() + maze[loc.r,loc.c] +:= PATH + path := \path.getParent() | break + } return } end diff --git a/Task/Menu/Ruby/menu.rb b/Task/Menu/Ruby/menu.rb index cbf5f1a5d7..4ae83f1987 100644 --- a/Task/Menu/Ruby/menu.rb +++ b/Task/Menu/Ruby/menu.rb @@ -1,21 +1,21 @@ def select(prompt, items) - return "" if items.length == 0 - while true + return "" if items.empty? + loop do items.each_index {|i| puts "#{i}. #{items[i]}"} print "#{prompt}: " begin - answer = Integer(gets()) + answer = Integer(gets) rescue ArgumentError redo end - return items[answer] if answer.between?(0, items.length - 1) + return items[answer] if (0...items.length).cover?(answer) end end # test empty list response = select("Which is empty", []) puts "empty list returns: >#{response}<" -puts "" +puts # "real" test items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] diff --git a/Task/Metered-concurrency/Groovy/metered-concurrency-1.groovy b/Task/Metered-concurrency/Groovy/metered-concurrency-1.groovy new file mode 100644 index 0000000000..9e978a1f0a --- /dev/null +++ b/Task/Metered-concurrency/Groovy/metered-concurrency-1.groovy @@ -0,0 +1,18 @@ +class CountingSemaphore { + private int count = 0 + private final int max + + CountingSemaphore(int max) { this.max = max } + + synchronized int acquire() { + while (count >= max) { wait() } + ++count + } + + synchronized int release() { + if (count) { count--; notifyAll() } + count + } + + synchronized int getCount() { count } +} diff --git a/Task/Metered-concurrency/Groovy/metered-concurrency-2.groovy b/Task/Metered-concurrency/Groovy/metered-concurrency-2.groovy new file mode 100644 index 0000000000..728e9c151f --- /dev/null +++ b/Task/Metered-concurrency/Groovy/metered-concurrency-2.groovy @@ -0,0 +1,14 @@ +def cs = new CountingSemaphore(4) +(1..12).each { threadID -> + Thread.start { + def id = "Thread #${(threadID as String).padLeft(2,'0')}" + try { + def sCount = cs.acquire() + println("${id} has acquired Semaphore at count = ${sCount}") + sleep(2000) + } finally { + println("${id} is releasing Semaphore at count = ${cs.count}") + cs.release() + } + } +} diff --git a/Task/Metered-concurrency/Perl-6/metered-concurrency.pl6 b/Task/Metered-concurrency/Perl-6/metered-concurrency.pl6 new file mode 100644 index 0000000000..8d9eab35ff --- /dev/null +++ b/Task/Metered-concurrency/Perl-6/metered-concurrency.pl6 @@ -0,0 +1,23 @@ +class Semaphore { + has $.tickets = Channel.new; + method new ($max) { + my $s = self.bless; + $s.tickets.send(True) xx $max; + $s; + } + method acquire { $.tickets.receive } + method release { $.tickets.send(True) } +} + +sub MAIN ($units = 5, $max = 2) { + my $sem = Semaphore.new($max); + + my @units = do for ^$units -> $u { + start { + $sem.acquire; say "unit $u acquired"; + sleep 2; + $sem.release; say "unit $u released"; + } + } + await @units; +} diff --git a/Task/Middle-three-digits/AutoHotkey/middle-three-digits.ahk b/Task/Middle-three-digits/AutoHotkey/middle-three-digits.ahk new file mode 100644 index 0000000000..5aedfde740 --- /dev/null +++ b/Task/Middle-three-digits/AutoHotkey/middle-three-digits.ahk @@ -0,0 +1,13 @@ +Numbers:="123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" +Loop, parse, Numbers, `, +{ + if A_LoopField is not number + log := log . A_LoopField . "`t: Not a valid number`n" + else if((d:=StrLen(n:=RegExReplace(A_LoopField,"\D")))<3) + log := log . A_LoopField . "`t: Too short`n" + else if(!Mod(d,2)) + log := log . A_LoopField . "`t: Not an odd number of digits`n" + else + log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n" +} +MsgBox % log diff --git a/Task/Middle-three-digits/BASIC/middle-three-digits-1.basic b/Task/Middle-three-digits/BASIC/middle-three-digits-1.basic new file mode 100644 index 0000000000..88297dfd89 --- /dev/null +++ b/Task/Middle-three-digits/BASIC/middle-three-digits-1.basic @@ -0,0 +1,22 @@ +100 DEF FN L(N) = LEN(STR$(INT(ABS(N)))) +110 DEF FN N(N) = VAL(MID$(STR$(INT(ABS(N))),(FN L(N)-1)/2,3)) +120 DEF FN EVEN(N) = INT(N/2) = N/2 +130 FOR I = 1 TO 20 +140 READ N +150 PRINT N":", +160 GOSUB 100"MIDDLE THREE DIGITS +170 PRINT R$ +180 NEXT +190 END +200 R$ = "" +210 IF FN EVEN(FN L(N)) THEN R$ = "?EVEN," +220 IF FN L(N) < 3 THEN R$ = R$ + "ONLY " + STR$(FN L(N)) + " DIGIT" + MID$("S",FN L(N) - 1, 1) +230 IF RIGHT$(R$, 1) = "," THEN R$ = LEFT$(R$, LEN(R$) - 1) : RETURN +240 IF LEFT$(R$, 1) = "?" THEN RETURN +250 IF R$ <> "" THEN R$ = "?" + R$ : RETURN +260 R$ = STR$(FN N(N)) +270 IF LEN(R$) = 1 THEN R$ = "00" + R$ +280 IF LEN(R$) = 2 THEN R$ = "0" + R$ +290 RETURN +300 DATA123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345 +310 DATA1,2,-1,-10,2002,-2002,0 diff --git a/Task/Middle-three-digits/BASIC/middle-three-digits-2.basic b/Task/Middle-three-digits/BASIC/middle-three-digits-2.basic new file mode 100644 index 0000000000..46990d4d99 --- /dev/null +++ b/Task/Middle-three-digits/BASIC/middle-three-digits-2.basic @@ -0,0 +1,45 @@ +#APPTYPE CONSOLE + +DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" +DIM dict[] = Split(numbers, ",") +DIM num AS INTEGER +DIM num2 AS INTEGER +DIM powered AS INTEGER + +FOR DIM i = 0 TO COUNT(dict) - 1 + num2 = dict[i] + num = ABS(num2) + IF num < 100 THEN + display(num2, "is too small") + ELSE + FOR DIM j = 9 DOWNTO 1 + powered = 10 ^ j + IF num >= powered THEN + IF j MOD 2 = 1 THEN + display(num2, "has even number of digits") + ELSE + display(num2, middle3(num, j)) + END IF + EXIT FOR + END IF + NEXT + END IF +NEXT + +PAUSE + +FUNCTION display(num, msg) + PRINT LPAD(num, 11, " "), " --> ", msg +END FUNCTION + +FUNCTION middle3(n, pwr) + DIM power AS INTEGER = (pwr \ 2) - 1 + DIM m AS INTEGER = n + m = m \ (10 ^ power) + m = m MOD 1000 + IF m = 0 THEN + RETURN "000" + ELSE + RETURN m + END IF +END FUNCTION diff --git a/Task/Middle-three-digits/BASIC/middle-three-digits-3.basic b/Task/Middle-three-digits/BASIC/middle-three-digits-3.basic new file mode 100644 index 0000000000..e35d5c73d7 --- /dev/null +++ b/Task/Middle-three-digits/BASIC/middle-three-digits-3.basic @@ -0,0 +1,28 @@ +Procedure.s middleThreeDigits(x.q) + Protected x$, digitCount + + If x < 0: x = -x: EndIf + + x$ = Str(x) + digitCount = Len(x$) + If digitCount < 3 + ProcedureReturn "invalid input: too few digits" + ElseIf digitCount % 2 = 0 + ProcedureReturn "invalid input: even number of digits" + EndIf + + ProcedureReturn Mid(x$,digitCount / 2, 3) +EndProcedure + +If OpenConsole() + Define testValues$ = "123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0" + + Define i, value.q, numTests = CountString(testValues$, " ") + 1 + For i = 1 To numTests + value = Val(StringField(testValues$, i, " ")) + PrintN(RSet(Str(value), 12, " ") + " : " + middleThreeDigits(value)) + Next + + Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Middle-three-digits/BASIC/middle-three-digits-4.basic b/Task/Middle-three-digits/BASIC/middle-three-digits-4.basic new file mode 100644 index 0000000000..7a77efa890 --- /dev/null +++ b/Task/Middle-three-digits/BASIC/middle-three-digits-4.basic @@ -0,0 +1,13 @@ +x$ = "123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0" + +while word$(x$,i+1,",") <> "" + i = i + 1 + a1$ = trim$(word$(x$,i,",")) + if left$(a1$,1) = "-" then a$ = mid$(a1$,2) else a$ = a1$ + if (len(a$) and 1) = 0 or len(a$) < 3 then + print a1$;chr$(9);" length < 3 or is even" + else + print mid$(a$,((len(a$)-3)/2)+1,3);" ";a1$ + end if +wend +end diff --git a/Task/Middle-three-digits/C/middle-three-digits-2.c b/Task/Middle-three-digits/C/middle-three-digits-2.c index 8573a03216..0a4fa323b5 100644 --- a/Task/Middle-three-digits/C/middle-three-digits-2.c +++ b/Task/Middle-three-digits/C/middle-three-digits-2.c @@ -2,46 +2,55 @@ #include #include -char input[50]; -int midPoint; - void midThree(char arg[]) { char output[4]; + int midPoint; + arg[0]=='-'?midPoint = ((strlen(arg) + 1) / 2):midPoint = ((strlen(arg) + 1) / 2) - 1; + + if(strlen(arg) < 3) + { + printf("Error, %d is too short.\n",atoi(arg)); + return ; + } + else if(strlen(arg) == 4 || strlen(arg) == 3) + { + printf("Error, %d has %d digits, no 3 middle digits.\n",atoi(arg),arg[0]=='-'?strlen(arg)-1:strlen(arg)); + return ; + } + else{ for(int i=0; i<3; i++) { - output[i] = input[(midPoint-1) + i]; + output[i] = arg[(midPoint-1) + i]; } output[3] = '\0'; printf("The middle three digits of %s are %s.\n",arg,output); -} +}} int main(int argc, char * argv[]) { + char input[50]; + int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, + -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, + 1234567890},i; + if(argc < 2) { printf("Usage: %s \n",argv[0]); + printf("Examples with preloaded data shown below :\n"); + + for(i=0;i<18;i++) + { + midThree(itoa(x[i],argv[0],10)); + } return 1; } else { - sprintf(input,"%d",abs(atoi(argv[1]))); - if(strlen(input) < 3) - { - printf("Error, %d is too short.\n",atoi(argv[1])); - return 1; - } - else if(strlen(input) % 2 == 0) - { - printf("Error, %d is even.\n",atoi(argv[1])); - return 1; - } - else - { - midPoint = ((strlen(input) + 1) / 2) - 1; + sprintf(input,"%d",atoi(argv[1])); midThree(argv[1]); return 0; - } + } } diff --git a/Task/Middle-three-digits/D/middle-three-digits-1.d b/Task/Middle-three-digits/D/middle-three-digits-1.d index d78bda49c0..2bb5990917 100644 --- a/Task/Middle-three-digits/D/middle-three-digits-1.d +++ b/Task/Middle-three-digits/D/middle-three-digits-1.d @@ -1,7 +1,7 @@ -import std.stdio, std.traits, std.conv; +import std.stdio, std.traits, std.conv, std.range; string middleThreeDigits(T)(in T n) if (isIntegral!T) { - auto s = n < 0 ? n.text()[1 .. $] : n.text(); + auto s = n < 0 ? n.text().dropOne : n.text(); auto len = s.length; if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; @@ -15,7 +15,7 @@ void main() { foreach (n; passing) writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n)); - immutable failing = [1, 2, -1, -10, 2002, -2002, 0,int.min,int.max]; + immutable failing = [1, 2, -1, -10, 2002, -2002, 0, int.min, int.max]; foreach (n; failing) writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n)); } diff --git a/Task/Middle-three-digits/Forth/middle-three-digits.fth b/Task/Middle-three-digits/Forth/middle-three-digits.fth new file mode 100644 index 0000000000..5a4618e061 --- /dev/null +++ b/Task/Middle-three-digits/Forth/middle-three-digits.fth @@ -0,0 +1,4 @@ +: middle3 ( n1 -- a n2) + abs s>d <# #s #> dup 2/ 0<> over 1 and 0<> and + if 2/ 1- chars + 3 else drop 0 then +; diff --git a/Task/Middle-three-digits/Julia/middle-three-digits.julia b/Task/Middle-three-digits/Julia/middle-three-digits.julia index aa287ec766..1ad00a891e 100644 --- a/Task/Middle-three-digits/Julia/middle-three-digits.julia +++ b/Task/Middle-three-digits/Julia/middle-three-digits.julia @@ -1,13 +1,26 @@ function middle(i) - let s = string(abs(i)) , l = length(s) , mid = int((l+1)/2) + s = string(abs(i)) + l = length(s) + mid = int((l+1)/2) l < 3 ? "error: not enough digits" : iseven(l) ? "error: number of digits is even" : - s[mid-1:mid+1] - end + join((s[mid-1],s[mid],s[mid+1])) end +function dummy(x,y,z=5) + """ + A dummy docstring over two lines + for text coloration. + """ + print("this is just some text to show text", 1.0, 3) + # and comment coloration + // and comment coloration 2 +end + +julia> + for n = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] println (@sprintf("%10d : ", n), middle(n)) diff --git a/Task/Middle-three-digits/PHP/middle-three-digits.php b/Task/Middle-three-digits/PHP/middle-three-digits.php new file mode 100644 index 0000000000..ad932fb2ff --- /dev/null +++ b/Task/Middle-three-digits/PHP/middle-three-digits.php @@ -0,0 +1,39 @@ +// 32-bit builds of PHP: Integers can be from -2147483648 to 2147483647 +// 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807 + +function middlethree($integer) +{ + $int = (int)str_replace('-','',$integer); + $length = strlen($int); + + if(is_int($int)) + { + if($length >= 3) + { + if($length % 2 == 1) + { + $middle = floor($length / 2) - 1; + return substr($int,$middle, 3); + } + else + { + return 'The value must contain an odd amount of digits...'; + } + } + else + { + return 'The value must contain at least three digits...'; + } + } + else + { + return 'The value does not appear to be an integer...'; + } +} + +$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); + +foreach($numbers as $nums) +{ + echo $nums.' : '.middlethree($nums). '
'; +} diff --git a/Task/Middle-three-digits/PL-I/middle-three-digits.pli b/Task/Middle-three-digits/PL-I/middle-three-digits.pli new file mode 100644 index 0000000000..b64a318427 --- /dev/null +++ b/Task/Middle-three-digits/PL-I/middle-three-digits.pli @@ -0,0 +1,24 @@ +middle: procedure options (main); /* 29 October 2013 */ + declare n fixed (15); + declare s character (25) varying; + declare in file input; + + open file (in) title ('/MIDDLE.DAT,type(text),recsize(100)'); + on endfile (in) stop; + + do forever; + get file (in) list (n); put skip list (n); + n = abs(n); + s = trim(n); + if length(s) < 3 then put list ('not possible'); + else if mod(length(s), 2) = 0 then put list ('not possible'); + else + do; + do while (length(s) > 3); + s = substr(s, 2, length(s)-2); + end; + put list ('The middle three digits are: ' || s); + end; + end; + +end middle; diff --git a/Task/Middle-three-digits/PicoLisp/middle-three-digits-1.l b/Task/Middle-three-digits/PicoLisp/middle-three-digits-1.l new file mode 100644 index 0000000000..0f8d7e8400 --- /dev/null +++ b/Task/Middle-three-digits/PicoLisp/middle-three-digits-1.l @@ -0,0 +1,10 @@ +(de middle3digits (N) + (let (Lst (chop (abs N)) Len (length Lst)) + (tab (10 -2 -30) + N + ":" + (cond + ((> 3 Len) "not enough digits") + ((bit? 1 Len) + (head 3 (nth Lst (/ Len 2))) ) + (T "even number of digits") ) ) ) ) diff --git a/Task/Middle-three-digits/PicoLisp/middle-three-digits-2.l b/Task/Middle-three-digits/PicoLisp/middle-three-digits-2.l new file mode 100644 index 0000000000..1d6be1216a --- /dev/null +++ b/Task/Middle-three-digits/PicoLisp/middle-three-digits-2.l @@ -0,0 +1,3 @@ +(mapc middle3digits + (123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 + 1 2 -1 -10 2002 -2002 0 ) ) diff --git a/Task/Middle-three-digits/Ruby/middle-three-digits.rb b/Task/Middle-three-digits/Ruby/middle-three-digits.rb index 27f58bda62..37f8b56187 100644 --- a/Task/Middle-three-digits/Ruby/middle-three-digits.rb +++ b/Task/Middle-three-digits/Ruby/middle-three-digits.rb @@ -1,16 +1,16 @@ def middle_three_digits(n) - # minus sign doesn't factor into digit count, - # and calling #abs acts as a duck-type assertion - n = n.abs + # minus sign doesn't factor into digit count, + # and calling #abs acts as a duck-type assertion + n = n.abs - # convert to string and find length - l = (s = n.to_s).length + # convert to string and find length + l = (s = n.to_s).length - # check validity - raise ArgumentError, "Number must have at least three digits" if l < 3 - raise ArgumentError, "Number must have an odd number of digits" if l % 2 == 0 + # check validity + raise ArgumentError, "Number must have at least three digits" if l < 3 + raise ArgumentError, "Number must have an odd number of digits" if l.even? - return s[l/2-1,3].to_i + return s[l/2-1,3].to_i end samples = [ @@ -21,10 +21,10 @@ samples = [ width = samples.map { |n| n.to_s.length }.max samples.each do |n| - print "%#{width}d: " % n - begin - puts "%03d" % middle_three_digits(n) - rescue ArgumentError => e - puts e.to_s - end + print "%#{width}d: " % n + begin + puts "%03d" % middle_three_digits(n) + rescue ArgumentError => e + puts e + end end diff --git a/Task/Middle-three-digits/Seed7/middle-three-digits.seed7 b/Task/Middle-three-digits/Seed7/middle-three-digits.seed7 new file mode 100644 index 0000000000..26165faedb --- /dev/null +++ b/Task/Middle-three-digits/Seed7/middle-three-digits.seed7 @@ -0,0 +1,24 @@ +$include "seed7_05.s7i"; + +const func string: middle3 (in integer: number) is func + result + var string: middle3 is ""; + begin + middle3 := str(abs(number)); + if not odd(length(middle3)) or length(middle3) < 3 then + middle3 := "error"; + else + middle3 := middle3[succ((length(middle3) - 3) div 2) len 3]; + end if; + end func; + +const proc: main is func + local + var integer: number is 0; + var string: mid3 is ""; + begin + for number range [] (123, 12345, 1234567, 987654321, 10001, -10001, -123, + -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) do + writeln(number <& ": " <& middle3(number)); + end for; + end func; diff --git a/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon b/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon index d8c05e9561..367bf45a2d 100644 --- a/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon +++ b/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon @@ -1,22 +1,33 @@ -procedure main() - every writes(primeTest(901 to 1000, 10)," ") - write() +procedure main(A) + every n := !A do write(n," is ",(mrp(n,5),"probably prime")|"composite") end -procedure primeTest(n, k) - if n = 2 then return n +procedure mrp(n, k) + if n = 2 then return "" if n%2 = 0 then fail - s := 0 - d := n-1 - while (d%2 ~= 0, s+:=1, d/:=2) - - every (1 to k, x := ((1+?(n-2))^d)%n) do { - if x = (1 | (n-1)) then next - every (1 to s-1, x := (x^2)%n) do { + nm1 := decompose(n-1) + s := nm1[1] + d := nm1[2] + every !k do { + a := ?(n-2)+1 + x := (a^d)%n + if x = (1|(n-1)) then next + every !(s-1) do { + x := (x*x)%n if x = 1 then fail - if x = n-1 then break next + if x = (n-1) then break next } fail } - return n + return "" +end + +procedure decompose(nm1) + s := 1 + d := nm1 + while d%2 = 0 do { + d /:= 2 + s +:= 1 + } + return [s,d] end diff --git a/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia b/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia new file mode 100644 index 0000000000..579ac6e856 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia @@ -0,0 +1,27 @@ +witnesses(n::Union(Uint8,Int8,Uint16,Int16)) = (2,3) +witnesses(n::Union(Uint32,Int32)) = n < 1373653 ? (2,3) : (2,7,61) +witnesses(n::Union(Uint64,Int64)) = + n < 1373653 ? (2,3) : + n < 4759123141 ? (2,7,61) : + n < 2152302898747 ? (2,3,5,7,11) : + n < 3474749660383 ? (2,3,5,7,11,13) : + (2,325,9375,28178,450775,9780504,1795265022) + +function isprime(n::Integer) + n == 2 && return true + (n < 2) | iseven(n) && return false + s = trailing_zeros(n-1) + d = (n-1) >>> s + for a in witnesses(n) + a < n || break + x = powermod(a,d,n) + x == 1 && continue + t = s + while x != n-1 + (t-=1) <= 0 && return false + x = oftype(n, Base.widemul(x,x) % n) + x == 1 && return false + end + end + return true +end diff --git a/Task/Modular-exponentiation/GAP/modular-exponentiation.gap b/Task/Modular-exponentiation/GAP/modular-exponentiation.gap new file mode 100644 index 0000000000..92d44dd0f6 --- /dev/null +++ b/Task/Modular-exponentiation/GAP/modular-exponentiation.gap @@ -0,0 +1,21 @@ +# Built-in +a := 2988348162058574136915891421498819466320163312926952423791023078876139; +b := 2351399303373464486466122544523690094744975233415544072992656881240319; +PowerModInt(a, b, 10^40); +1527229998585248450016808958343740453059 + +# Implementation +PowerModAlt := function(a, n, m) + local r; + r := 1; + while n > 0 do + if IsOddInt(n) then + r := RemInt(r*a, m); + fi; + n := QuoInt(n, 2); + a := RemInt(a*a, m); + od; + return r; +end; + +PowerModAlt(a, b, 10^40); diff --git a/Task/Modular-exponentiation/Julia/modular-exponentiation.julia b/Task/Modular-exponentiation/Julia/modular-exponentiation.julia new file mode 100644 index 0000000000..906850648a --- /dev/null +++ b/Task/Modular-exponentiation/Julia/modular-exponentiation.julia @@ -0,0 +1,5 @@ +julia> a = BigInt("2988348162058574136915891421498819466320163312926952423791023078876139") + b = BigInt("2351399303373464486466122544523690094744975233415544072992656881240319") + m = BigInt(10)^40 + powermod(a, b, m) +1527229998585248450016808958343740453059 diff --git a/Task/Modular-inverse/Julia/modular-inverse-1.julia b/Task/Modular-inverse/Julia/modular-inverse-1.julia new file mode 100644 index 0000000000..8311fd98b4 --- /dev/null +++ b/Task/Modular-inverse/Julia/modular-inverse-1.julia @@ -0,0 +1 @@ +invmod(a, b) diff --git a/Task/Modular-inverse/Julia/modular-inverse-2.julia b/Task/Modular-inverse/Julia/modular-inverse-2.julia new file mode 100644 index 0000000000..85f702fb31 --- /dev/null +++ b/Task/Modular-inverse/Julia/modular-inverse-2.julia @@ -0,0 +1,11 @@ +function modinv{T<:Integer}(a::T, b::T) + b0 = b + x0, x1 = zero(T), one(T) + while a > 1 + q = div(a, b) + a, b = b, a % b + x0, x1 = x1 - q * x0, x0 + end + x1 < 0 ? x1 + b0 : x1 +end +modinv(a::Integer, b::Integer) = modinv(promote(a,b)...) diff --git a/Task/Monte-Carlo-methods/AWK/monte-carlo-methods.awk b/Task/Monte-Carlo-methods/AWK/monte-carlo-methods.awk index 206d3b7dc8..eb899d24d9 100644 --- a/Task/Monte-Carlo-methods/AWK/monte-carlo-methods.awk +++ b/Task/Monte-Carlo-methods/AWK/monte-carlo-methods.awk @@ -1,8 +1,8 @@ # --- with command line argument "throws" --- BEGIN{ th=ARGV[1]; - for(i=0; i; enum Strategy ; sub play (Strategy $strategy, Int :$doors = 3) returns Prize { + # Call the door with a car behind it door 0. Number the # remaining doors starting from 1. my Prize @doors = Car, Goat xx $doors - 1; + # The player chooses a door. - my Prize $initial_pick = remove @doors, @doors.keys().pick; + my Prize $initial_pick = @doors.splice(@doors.keys.pick,1)[0]; + # Of the n doors remaining, the host chooses n - 1 that have # goats behind them and opens them, removing them from play. - remove @doors, $_ + @doors.splice($_,1) for pick @doors.elems - 1, grep { @doors[$_] == Goat }, keys @doors; + # If the player stays, they get their initial pick. Otherwise, # they get whatever's behind the remaining door. - return $strategy == Stay ?? $initial_pick !! @doors[0]; + return $strategy === Stay ?? $initial_pick !! @doors[0]; } -constant TRIALS = 100; +constant TRIALS = 1000; for 3, 10 -> $doors { my %wins; diff --git a/Task/Monty-Hall-problem/REXX/monty-hall-problem.rexx b/Task/Monty-Hall-problem/REXX/monty-hall-problem-1.rexx similarity index 100% rename from Task/Monty-Hall-problem/REXX/monty-hall-problem.rexx rename to Task/Monty-Hall-problem/REXX/monty-hall-problem-1.rexx diff --git a/Task/Monty-Hall-problem/REXX/monty-hall-problem-2.rexx b/Task/Monty-Hall-problem/REXX/monty-hall-problem-2.rexx new file mode 100644 index 0000000000..ccd41f694d --- /dev/null +++ b/Task/Monty-Hall-problem/REXX/monty-hall-problem-2.rexx @@ -0,0 +1,14 @@ +/*REXX program simulates a # of trials of the classic Monty Hall problem*/ +parse arg t .; if t=='' then t=1000000 /*Not specified? Then use default*/ +wins.=0 /*wins.0=stay; wins.1=switching.*/ + /*door values: 0=goat 1=car */ + do t /*perform this loop T times. */ + door.=0 /*set all doors to zero. */ + car=random(1,3); door.car=1 /*TV show hides a car randomly. */ + ?=random(1,3) ; _=door.? /*contestant picks a random door.*/ + wins._=wins._+1 /*bump the type of win strategy. */ + end /*DO t*/ + +say 'switching wins ' format(wins.0/t*100,,1)"% of the time." +say ' staying wins ' format(wins.1/t*100,,1)"% of the time."; say +say 'performed' t "times." /*stick a fork in it, we're done.* diff --git a/Task/Monty-Hall-problem/Ruby/monty-hall-problem.rb b/Task/Monty-Hall-problem/Ruby/monty-hall-problem.rb index 8731944578..530180767c 100644 --- a/Task/Monty-Hall-problem/Ruby/monty-hall-problem.rb +++ b/Task/Monty-Hall-problem/Ruby/monty-hall-problem.rb @@ -5,8 +5,7 @@ stay = switch = 0 #sum of each strategy's wins n.times do #play the game n times #the doors reveal 2 goats and a car - doors = [ :goat , :goat , :goat ] - doors[rand(3)] = :car + doors = [ :goat, :goat, :car ].shuffle #random guess guess = rand(3) @@ -14,11 +13,13 @@ n.times do #play the game n times #random door shown, but it is neither the guess nor the car begin shown = rand(3) end while shown == guess || doors[shown] == :car - #staying with the initial guess wins if the initial guess is the car - stay += 1 if doors[guess] == :car - - #switching guesses wins if the unshown door is the car - switch += 1 if doors[3-guess-shown] == :car + if doors[guess] == :car + #staying with the initial guess wins if the initial guess is the car + stay += 1 + else + #switching guesses wins if the unshown door is the car + switch += 1 + end end diff --git a/Task/Mouse-position/ActionScript/mouse-position.as b/Task/Mouse-position/ActionScript/mouse-position.as new file mode 100644 index 0000000000..9a27df1a43 --- /dev/null +++ b/Task/Mouse-position/ActionScript/mouse-position.as @@ -0,0 +1,37 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + + public class MousePosition extends Sprite { + + private var _textField:TextField = new TextField(); + + public function MousePosition() { + if ( stage ) init(); + else addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(e:Event = null):void { + removeEventListener(Event.ADDED_TO_STAGE, init); + + _textField.autoSize = TextFieldAutoSize.RIGHT; + _textField.x = stage.stageWidth - 10; + _textField.defaultTextFormat = new TextFormat(null, 15); + _textField.text = "Mouse position: X = 0, Y = 0"; + _textField.y = stage.stageHeight - _textField.textHeight - 14; + addChild(_textField); + + addEventListener(Event.ENTER_FRAME, _onEnterFrame); + } + + private function _onEnterFrame(e:Event):void { + _textField.text = "Mouse position: X = " + stage.mouseX + ", Y = " + stage.mouseY; + } + + } + +} diff --git a/Task/Mouse-position/AutoHotkey/mouse-position.ahk b/Task/Mouse-position/AutoHotkey/mouse-position-1.ahk similarity index 100% rename from Task/Mouse-position/AutoHotkey/mouse-position.ahk rename to Task/Mouse-position/AutoHotkey/mouse-position-1.ahk diff --git a/Task/Mouse-position/AutoHotkey/mouse-position-2.ahk b/Task/Mouse-position/AutoHotkey/mouse-position-2.ahk new file mode 100644 index 0000000000..0ae3fc3435 --- /dev/null +++ b/Task/Mouse-position/AutoHotkey/mouse-position-2.ahk @@ -0,0 +1,14 @@ +GetCursorPos() +{ + static POINT, init := VarSetCapacity(POINT, 8, 0) && NumPut(8, POINT, "Int") + if (DllCall("User32.dll\GetCursorPos", "Ptr", &POINT)) + { + return, { 0 : NumGet(POINT, 0, "Int"), 1 : NumGet(POINT, 4, "Int") } + } +} +GetCursorPos := GetCursorPos() + +MsgBox, % "GetCursorPos function`n" + . "POINT structure`n`n" + . "x-coordinate:`t`t" GetCursorPos[0] "`n" + . "y-coordinate:`t`t" GetCursorPos[1] diff --git a/Task/Mouse-position/AutoHotkey/mouse-position-3.ahk b/Task/Mouse-position/AutoHotkey/mouse-position-3.ahk new file mode 100644 index 0000000000..6348d3b4a1 --- /dev/null +++ b/Task/Mouse-position/AutoHotkey/mouse-position-3.ahk @@ -0,0 +1,14 @@ +GetPhysicalCursorPos() +{ + static POINT, init := VarSetCapacity(POINT, 8, 0) && NumPut(8, POINT, "Int") + if (DllCall("User32.dll\GetPhysicalCursorPos", "Ptr", &POINT)) + { + return, { 0 : NumGet(POINT, 0, "Int"), 1 : NumGet(POINT, 4, "Int") } + } +} +GetPhysicalCursorPos := GetPhysicalCursorPos() + +MsgBox, % "GetPhysicalCursorPos function`n" + . "POINT structure`n`n" + . "x-coordinate:`t`t" GetPhysicalCursorPos[0] "`n" + . "y-coordinate:`t`t" GetPhysicalCursorPos[1] diff --git a/Task/Mouse-position/Perl-6/mouse-position.pl6 b/Task/Mouse-position/Perl-6/mouse-position.pl6 new file mode 100644 index 0000000000..8e79cba812 --- /dev/null +++ b/Task/Mouse-position/Perl-6/mouse-position.pl6 @@ -0,0 +1,5 @@ +use java::awt::MouseInfo:from; + +given MouseInfo.getPointerInfo.getLocation { + say .getX, 'x', .getY; +} diff --git a/Task/Mouse-position/Rust/mouse-position.rust b/Task/Mouse-position/Rust/mouse-position.rust index b21703f529..e5f8d43c2f 100644 --- a/Task/Mouse-position/Rust/mouse-position.rust +++ b/Task/Mouse-position/Rust/mouse-position.rust @@ -12,27 +12,27 @@ struct POINT { y: LONG } -#[link_args = "-luser32"] -extern "stdcall" { +#[link_name = "user32"] +extern "system" { pub fn GetCursorPos(lpPoint:&mut POINT) -> BOOL; pub fn GetForegroundWindow() -> HWND; pub fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT); } -#[fixed_stack_segment] fn main() { let mut pt = POINT{x:0, y:0}; loop { - std::rt::io::timer::sleep(100); // sleep duration in milliseconds + std::io::timer::sleep(100); // sleep duration in milliseconds let pt_prev = pt; unsafe { GetCursorPos(&mut pt) }; if pt != pt_prev { let h = unsafe { GetForegroundWindow() }; if h == mut_null() { continue } - let mut ptc = pt; - unsafe { ScreenToClient(h, &mut ptc) }; - println!("x: {}, y: {}", ptc.x, ptc.y); + + let mut pt_client = pt; + unsafe { ScreenToClient(h, &mut pt_client) }; + println!("x: {}, y: {}", pt_client.x, pt_client.y); } } } diff --git a/Task/Multifactorial/D/multifactorial.d b/Task/Multifactorial/D/multifactorial.d index a0ca731660..835707f7b5 100644 --- a/Task/Multifactorial/D/multifactorial.d +++ b/Task/Multifactorial/D/multifactorial.d @@ -1,12 +1,12 @@ import std.stdio, std.algorithm, std.range; -T multifactorial(T=long)(in int n, in int m) /*pure*/ { +T multifactorial(T=long)(in int n, in int m) pure /*nothrow*/ { T one = 1; return reduce!q{a * b}(one, iota(n, 0, -m)); } void main() { - foreach (m; 1 .. 11) + foreach (immutable m; 1 .. 11) writefln("%2d: %s", m, iota(1, 11) - .map!(n => multifactorial(n, m))()); + .map!(n => multifactorial(n, m))); } diff --git a/Task/Multifactorial/GAP/multifactorial.gap b/Task/Multifactorial/GAP/multifactorial.gap new file mode 100644 index 0000000000..722892e965 --- /dev/null +++ b/Task/Multifactorial/GAP/multifactorial.gap @@ -0,0 +1,21 @@ +MultiFactorial := function(n, k) + local r; + r := 1; + while n > 1 do + r := r*n; + n := n - k; + od; + return r; +end; + +PrintArray(List([1 .. 10], n -> List([1 .. 5], k -> MultiFactorial(n, k)))); +[ [ 1, 1, 1, 1, 1 ], + [ 2, 2, 2, 2, 2 ], + [ 6, 3, 3, 3, 3 ], + [ 24, 8, 4, 4, 4 ], + [ 120, 15, 10, 5, 5 ], + [ 720, 48, 18, 12, 6 ], + [ 5040, 105, 28, 21, 14 ], + [ 40320, 384, 80, 32, 24 ], + [ 362880, 945, 162, 45, 36 ], + [ 3628800, 3840, 280, 120, 50 ] ] diff --git a/Task/Multifactorial/Haskell/multifactorial.hs b/Task/Multifactorial/Haskell/multifactorial-1.hs similarity index 100% rename from Task/Multifactorial/Haskell/multifactorial.hs rename to Task/Multifactorial/Haskell/multifactorial-1.hs diff --git a/Task/Multifactorial/Haskell/multifactorial-2.hs b/Task/Multifactorial/Haskell/multifactorial-2.hs new file mode 100644 index 0000000000..4b2e49eb6c --- /dev/null +++ b/Task/Multifactorial/Haskell/multifactorial-2.hs @@ -0,0 +1,14 @@ +procedure main(A) + l := integer(A[1]) | 10 + every writeRow(n := !l, [: mf(!10,n) :]) +end + +procedure writeRow(n, r) + writes(right(n,3),": ") + every writes(right(!r,8)|"\n") +end + +procedure mf(n, m) + if n <= 0 then return 1 + return n*mf(n-m, m) +end diff --git a/Task/Multifactorial/PL-I/multifactorial.pli b/Task/Multifactorial/PL-I/multifactorial.pli new file mode 100644 index 0000000000..d48fee28e8 --- /dev/null +++ b/Task/Multifactorial/PL-I/multifactorial.pli @@ -0,0 +1,21 @@ +multi: procedure options (main); /* 29 October 2013 */ + declare (i, j, n) fixed binary; + declare text character (6) static initial ('n!!!!!'); + + do i = 1 to 5; + put skip edit (substr(text, 1, i+1), '=' ) (A, COLUMN(8)); + do n = 1 to 10; + put edit ( trim( multifactorial(n,i) ) ) (X(1), A); + end; + end; + +multifactorial: procedure (n, j) returns (fixed(15)); + declare (n, j) fixed binary; + declare f fixed (15), m fixed(15); + + f, m = n; + do while (m > j); f = f * (m-fixed(j)); m = m - j; end; + return (f); +end multifactorial; + +end multi; diff --git a/Task/Multifactorial/REXX/multifactorial.rexx b/Task/Multifactorial/REXX/multifactorial.rexx index 311d2653c0..15ef9e4f9b 100644 --- a/Task/Multifactorial/REXX/multifactorial.rexx +++ b/Task/Multifactorial/REXX/multifactorial.rexx @@ -1,20 +1,21 @@ /*REXX pgm calculates K-fact (multifactorial) of non-negative integers.*/ numeric digits 1000 /*lets get ka-razy with precision*/ parse arg num deg . /*allow user to specify num & deg*/ -if num=='' | num==',' then num=12 /*Not specified? Then use default*/ -if deg=='' | deg==',' then deg=10 /* " " " " " */ +if num=='' | num==',' then num=15 /*Not specified? Then use default*/ +if deg=='' | deg==',' then deg=10 /* " " " " " */ +say '═══showing multiple factorials (1 ──►' deg") for numbers 1 ──►" num +say + do d=1 for deg /*the factorializing (º) of !'s. */ + _= /*the list of factorials so far. */ + do f=1 for num /* ◄── do a ! from 1 to num.*/ + _=_ Kfact(f,d) /*construct a list of factorials.*/ + end /*f*/ /*(above) D can default to 1.*/ - do d=1 to deg /*the degree of factorialization.*/ - _= /*the list of factorials so far. */ - do f=1 to num - _=_ Kfact(f,d) /*construct a list of factorials.*/ - end /*f*/ /*(above) D can be omitted. */ - - say 'degree' right(d,length(num))':' _ /*show factorials.*/ - end /*d*/ + say right('n'copies("!", d),1+deg) right('['d"]",2+length(num))':' _ + end /*d*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────KFACT subroutine────────────────────*/ -Kfact: procedure; !=1; do j=arg(1) to 2 by -word(arg(2) 1, 1) +Kfact: procedure; !=1; do j=arg(1) to 2 by -word(arg(2) 1, 1) !=!*j end /*j*/ return ! diff --git a/Task/Multifactorial/Seed7/multifactorial.seed7 b/Task/Multifactorial/Seed7/multifactorial.seed7 new file mode 100644 index 0000000000..1763229bc2 --- /dev/null +++ b/Task/Multifactorial/Seed7/multifactorial.seed7 @@ -0,0 +1,25 @@ +$ include "seed7_05.s7i"; + +const func integer: multiFact (in var integer: num, in integer: degree) is func + result + var integer: multiFact is 1; + begin + while num > 1 do + multiFact *:= num; + num -:= degree; + end while; + end func; + +const proc: main is func + local + var integer: degree is 0; + var integer: num is 0; + begin + for degree range 1 to 5 do + write("Degree " <& degree <& ": "); + for num range 1 to 10 do + write(multiFact(num, degree) <& " "); + end for; + writeln; + end for; + end func; diff --git a/Task/Multiple-distinct-objects/Groovy/multiple-distinct-objects-1.groovy b/Task/Multiple-distinct-objects/Groovy/multiple-distinct-objects-1.groovy new file mode 100644 index 0000000000..e97eba584a --- /dev/null +++ b/Task/Multiple-distinct-objects/Groovy/multiple-distinct-objects-1.groovy @@ -0,0 +1 @@ +def createFoos1 = { n -> (0.. [new Foo()] * n } diff --git a/Task/Multiple-distinct-objects/Groovy/multiple-distinct-objects-3.groovy b/Task/Multiple-distinct-objects/Groovy/multiple-distinct-objects-3.groovy new file mode 100644 index 0000000000..15f7333e6a --- /dev/null +++ b/Task/Multiple-distinct-objects/Groovy/multiple-distinct-objects-3.groovy @@ -0,0 +1,13 @@ +[createFoos1, createFoos2].each { createFoos -> + print "Objects distinct for n = " + (2..<20).each { n -> + def foos = createFoos(n) + foos.eachWithIndex { here, i -> + foos.eachWithIndex { there, j -> + assert (here == there) == (i == j) + } + } + print "${n} " + } + println() +} diff --git a/Task/Multiple-regression/Julia/multiple-regression.julia b/Task/Multiple-regression/Julia/multiple-regression.julia new file mode 100644 index 0000000000..5d5ad31196 --- /dev/null +++ b/Task/Multiple-regression/Julia/multiple-regression.julia @@ -0,0 +1,4 @@ +x = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83] +y = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46] +X = [x.^0 x.^1 x.^2]; +b = X \ y diff --git a/Task/Multiplication-tables/AWK/multiplication-tables.awk b/Task/Multiplication-tables/AWK/multiplication-tables.awk index 9fdacef8eb..e859ce00d1 100644 --- a/Task/Multiplication-tables/AWK/multiplication-tables.awk +++ b/Task/Multiplication-tables/AWK/multiplication-tables.awk @@ -1,10 +1,10 @@ BEGIN{ for(i=1;i<13;i++){ for(j=1;j<13;j++){ - if(j>=i||j==1){printf("%4d",i*j);} - else {printf(" ");} + if(j>=i||j==1){printf "%4d",i*j} + else {printf " "} } - print; + print } } diff --git a/Task/Multiplication-tables/ActionScript/multiplication-tables.as b/Task/Multiplication-tables/ActionScript/multiplication-tables.as new file mode 100644 index 0000000000..968ec69b07 --- /dev/null +++ b/Task/Multiplication-tables/ActionScript/multiplication-tables.as @@ -0,0 +1,79 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + + [SWF (width = 550, height = 550)] + public class MultiplicationTable extends Sprite { + + public function MultiplicationTable() { + if ( stage ) _init(); + else addEventListener(Event.ADDED_TO_STAGE, _init); + } + + private function _init(e:Event = null):void { + + removeEventListener(Event.ADDED_TO_STAGE, _init); + + var format:TextFormat = new TextFormat(); + format.size = 15; + var blockSize:uint = 40; + var max:uint = 12; + + var i:uint, j:uint; + var tf:TextField; + + for ( i = 1; i <= max; i++ ) { + tf = new TextField(); + tf.defaultTextFormat = format; + tf.x = blockSize * i; + tf.y = 0; + tf.width = tf.height = blockSize; + tf.autoSize = TextFieldAutoSize.CENTER; + tf.text = String(i); + addChild(tf); + + tf = new TextField(); + tf.defaultTextFormat = format; + tf.x = 0; + tf.y = blockSize * i; + tf.width = tf.height = blockSize; + tf.autoSize = TextFieldAutoSize.CENTER; + tf.text = String(i); + addChild(tf); + } + + var yOffset:Number = tf.textHeight / 2; + y += yOffset; + + graphics.lineStyle(1, 0x000000); + graphics.moveTo(blockSize, -yOffset); + graphics.lineTo(blockSize, (blockSize * (max + 1)) - yOffset); + graphics.moveTo(0, blockSize - yOffset); + graphics.lineTo(blockSize * (max + 1), blockSize - yOffset); + + + for ( i = 1; i <= max; i++ ) { + for ( j = 1; j <= max; j++ ) { + if ( j > i ) + continue; + + tf = new TextField(); + tf.defaultTextFormat = format; + tf.x = blockSize * i; + tf.y = blockSize * j; + tf.width = tf.height = blockSize; + tf.autoSize = TextFieldAutoSize.CENTER; + tf.text = String(i * j); + addChild(tf); + } + } + + } + + } + +} diff --git a/Task/Multiplication-tables/BASIC/multiplication-tables.basic b/Task/Multiplication-tables/BASIC/multiplication-tables-1.basic similarity index 100% rename from Task/Multiplication-tables/BASIC/multiplication-tables.basic rename to Task/Multiplication-tables/BASIC/multiplication-tables-1.basic diff --git a/Task/Multiplication-tables/BASIC/multiplication-tables-2.basic b/Task/Multiplication-tables/BASIC/multiplication-tables-2.basic new file mode 100644 index 0000000000..c12bb84339 --- /dev/null +++ b/Task/Multiplication-tables/BASIC/multiplication-tables-2.basic @@ -0,0 +1,10 @@ +100 M = 12 +110 DEF FN T(X) = X * 3 + (X < 4) * (4 - X) + (X > 10) * (X - 10) - 1 +120 FOR N = -1 TO M +130 IF NOT N THEN PRINT CHR$(13) TAB(5); : FOR J = 5 TO FN T(M + 1) - 2 : PRINT "-"; : NEXT J, N +140 I = ABS(N) +150 IF N > 0 THEN PRINT CHR$(13) MID$(" ", 1, I < 10) I" !"; +160 FOR J = I TO M +170 V$ = STR$(I * J) +180 PRINT TAB(FN T(J)) MID$(" ", 1, 3 - LEN(V$) - (J < 4)) V$; +190 NEXT J, N diff --git a/Task/Multiplication-tables/Bracmat/multiplication-tables.bracmat b/Task/Multiplication-tables/Bracmat/multiplication-tables.bracmat new file mode 100644 index 0000000000..4ea44708b8 --- /dev/null +++ b/Task/Multiplication-tables/Bracmat/multiplication-tables.bracmat @@ -0,0 +1,56 @@ + ( multiplicationTable + = high i j row row2 matrix padFnc tmp + , celPad leftCelPad padFnc celDashes leftDashes + . !arg:?high + & ( padFnc + = L i w d + . @(!arg:? [?L) + & 1+(!L:?i):?L + & " ":?w + & "-":?d + & whl + ' ( !i+-1:~<0:?i + & " " !w:?w + & "-" !d:?d + ) + & str$!w:?w + & ( + ' ( + . @(str$(rev$!arg ()$w):?arg [($L) ?) + & rev$!arg + ) + . str$!d + ) + ) + & padFnc$(!high^2):((=?celPad).?celDashes) + & @(!high:?tmp [-2 ?) + & padFnc$!tmp:((=?leftCelPad).?leftDashes) + & 0:?i + & :?row:?row2 + & whl + ' ( 1+!i:~>!high:?i + & !row celPad$!i:?row + & !celDashes !row2:?row2 + ) + & str$(leftCelPad$X "|" !row \n !leftDashes "+" !row2 \n) + : ?matrix + & 0:?j + & whl + ' ( 1+!j:~>!high:?j + & 0:?i + & :?row + & whl + ' ( 1+!i:!high:?i + & !row celPad$(!i*!j):?row + ) + & !matrix str$(!row \n):?matrix + ) + & str$!matrix + ) +& out$(multiplicationTable$12) +& done; diff --git a/Task/Multiplication-tables/D/multiplication-tables.d b/Task/Multiplication-tables/D/multiplication-tables.d index 3b1251f959..47d2e0535e 100644 --- a/Task/Multiplication-tables/D/multiplication-tables.d +++ b/Task/Multiplication-tables/D/multiplication-tables.d @@ -1,21 +1,9 @@ -import std.stdio, std.array; - void main() { - enum int max = 12; - write(" | "); - foreach (row; 1 .. max+1) - writef("%4d", row); - writeln(); - writeln("--+-", "-".replicate(max * 4)); - foreach (row; 1 .. max+1) { - writef("%2d", row); - write("| "); - foreach (column; 1 .. max+1) { - if (column < row) - write(" "); - else - writef("%4d", row * column); - } - writeln(); - } + import std.stdio, std.array, std.range, std.algorithm; + + enum n = 12; + writefln(" %(%4d%)\n%s", iota(1, n+1), "-".replicate(4*n + 4)); + foreach (immutable y; 1 .. n + 1) + writefln("%4d" ~ " ".replicate(4 * (y - 1)) ~ "%(%4d%)", y, + iota(y, n + 1).map!(x => x * y)); } diff --git a/Task/Multiplicative-order/Julia/multiplicative-order.julia b/Task/Multiplicative-order/Julia/multiplicative-order.julia new file mode 100644 index 0000000000..72ad281ebc --- /dev/null +++ b/Task/Multiplicative-order/Julia/multiplicative-order.julia @@ -0,0 +1,23 @@ +function factors(n) + f = [one(n)] + for (p,e) in factor(n) + f = reduce(vcat, f, [f*p^j for j in 1:e]) + end + return length(f) == 1 ? [one(n), n] : sort!(f) +end + +function multorder(a, m) + gcd(a,m) == 1 || error("$a and $m are not coprime") + res = one(m) + for (p,e) in factor(m) + m = p^e + t = div(m, p) * (p-1) + for f in factors(t) + if powermod(a, f, m) == 1 + res = lcm(res, f) + break + end + end + end + res +end diff --git a/Task/Multiplicative-order/Seed7/multiplicative-order.seed7 b/Task/Multiplicative-order/Seed7/multiplicative-order.seed7 new file mode 100644 index 0000000000..737b410108 --- /dev/null +++ b/Task/Multiplicative-order/Seed7/multiplicative-order.seed7 @@ -0,0 +1,118 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const type: oneFactor is new struct + var bigInteger: prime is 0_; + var integer: exp is 0; + end struct; + +const func oneFactor: oneFactor (in bigInteger: prime, in integer: exp) is func + result + var oneFactor: aFactor is oneFactor.value; + begin + aFactor.prime := prime; + aFactor.exp := exp; + end func; + +const func array oneFactor: factor (in var bigInteger: n) is func + result + var array oneFactor: pf is 0 times oneFactor.value; + local + var integer: e is 0; + var bigInteger: d is 0_; + var bigInteger: s is 0_; + begin + e := lowestSetBit(n); + if e > 0 then + n >>:= e; + pf := [] (oneFactor(2_, e)); + end if; + s := sqrt(n); + d := 3_; + while n > 1_ do + if d > s then + d := n; + end if; + e := 0; + while n rem d = 0_ do + n := n div d; + incr(e); + end while; + if e > 0 then + pf &:= oneFactor(d, e); + s := sqrt(n); + end if; + d +:= 2_; + end while; + end func; + +const func bigInteger: moBachShallit58(in bigInteger: a, in bigInteger: n, in array oneFactor: pf) is func + result + var bigInteger: mo is 0_; + local + var bigInteger: n1 is 0_; + var oneFactor: pe is oneFactor.value; + var bigInteger: x is 0_; + var bigInteger: y is 0_; + var integer: o is 0; + var bigInteger: o1 is 0_; + begin + n1 := n - 1_; + mo := 1_; + for pe range pf do + y := n1 div pe.prime ** pe.exp; + x := modPow(a, y, n); + o := 0; + while x > 1_ do + x := modPow(x, pe.prime, n); + incr(o); + end while; + o1 := pe.prime ** o; + mo *:= o1 div gcd(mo, o1); + end for; + end func; + +const func boolean: isProbablyPrime (in bigInteger: primeCandidate, in var integer: count) is func + result + var boolean: isProbablyPrime is TRUE; + local + var bigInteger: aRandomNumber is 0_; + begin + while isProbablyPrime and count > 0 do + aRandomNumber := rand(1_, pred(primeCandidate)); + isProbablyPrime := modPow(aRandomNumber, pred(primeCandidate), primeCandidate) = 1_; + decr(count); + end while; + # writeln(count); + end func; + +const proc: moTest (in bigInteger: a, in bigInteger: n) is func + begin + if bitLength(a) < 100 then + write("ord(" <& a <& ")"); + else + write("ord([big])"); + end if; + if bitLength(n) < 100 then + write(" mod " <& n <& " "); + else + write(" mod [big] "); + end if; + if not isProbablyPrime(n, 20) then + writeln("not computed. modulus must be prime for this algorithm.") + else + writeln("= " <& moBachShallit58(a, n, factor(n - 1_))); + end if; + end func; + +const proc: main is func + local + var bigInteger: b is 100_; + begin + moTest(37_, 3343_); + moTest(10_ ** 100 + 1_, 7919_); + moTest(10_ ** 1000 + 1_, 15485863_); + moTest(10_ ** 10000 - 1_, 22801763489_); + moTest(1511678068_, 7379191741_); + moTest(3047753288_, 2257683301_); + end func; diff --git a/Task/Multisplit/AWK/multisplit.awk b/Task/Multisplit/AWK/multisplit.awk new file mode 100644 index 0000000000..6232153fee --- /dev/null +++ b/Task/Multisplit/AWK/multisplit.awk @@ -0,0 +1,23 @@ +# syntax: GAWK -f MULTISPLIT.AWK +BEGIN { + str = "a!===b=!=c" + sep = "(==|!=|=)" + printf("str: %s\n",str) + printf("sep: %s\n\n",sep) + n = split(str,str_arr,sep,sep_arr) + printf("parsed: ") + for (i=1; i<=n; i++) { + printf("'%s'",str_arr[i]) + if (iy - last=.next=.0 - r=.2 0$0 - while.next<#begin do. - r=.r,.(last}.x{.~next{begin);next{t - last=.next{end - next=.1 i.~(begin>next{begin)*.begin>:last + last=. next=. 0 + r=. 2 0$0 + while. next<#begin do. + r=. r,.(last}.x{.~next{begin);next{t + last=. next{end + next=. 1 i.~(begin>next{begin)*.begin>:last end. - r=.r,.'';~last}.x + r=. r,.'';~last}.x ) diff --git a/Task/Multisplit/J/multisplit-2.j b/Task/Multisplit/J/multisplit-2.j index f672231976..830fba97a5 100644 --- a/Task/Multisplit/J/multisplit-2.j +++ b/Task/Multisplit/J/multisplit-2.j @@ -1,4 +1,4 @@ - S=:'a!===b=!=c' + S=: 'a!===b=!=c' S multisplit '==';'!=';'=' ┌───┬───┬───┬───┬─┐ │a │ │b │ │c│ diff --git a/Task/Multisplit/Python/multisplit-2.py b/Task/Multisplit/Python/multisplit-2.py index 45feb10454..a06f92a263 100644 --- a/Task/Multisplit/Python/multisplit-2.py +++ b/Task/Multisplit/Python/multisplit-2.py @@ -1,24 +1,22 @@ ->>> def ms(txt="a!===b=!=c", sep=["==", "!=", "="]): - if not txt or not sep: - return [] - size = [len(s) for s in sep] - ans, pos0 = [], 0 - def getfinds(): - return [(-txt.find(s, pos0), -sepnum, size[sepnum]) - for sepnum, s in enumerate(sep) - if s in txt[pos0:]] +def multisplit(text, sep): + lastmatch = i = 0 + matches = [] + while i < len(text): + for j, s in enumerate(sep): + if text[i:].startswith(s): + if i > lastmatch: + matches.append(text[lastmatch:i]) + matches.append((j, i)) # Replace the string containing the matched separator with a tuple of which separator and where in the string the match occured + lastmatch = i + len(s) + i += len(s) + break + else: + i += 1 + if i > lastmatch: + matches.append(text[lastmatch:i]) + return matches - finds = getfinds() - while finds: - pos, snum, sz = max(finds) - pos, snum = -pos, -snum - ans += [ txt[pos0:pos], [snum, pos] ] - pos0 = pos+sz - finds = getfinds() - if txt[pos0:]: ans += [ txt[pos0:] ] - return ans - ->>> ms() -['a', [1, 1], '', [0, 3], 'b', [2, 6], '', [1, 7], 'c'] ->>> ms(txt="a!===b=!=c", sep=["=", "!=", "=="]) -['a', [1, 1], '', [0, 3], '', [0, 4], 'b', [0, 6], '', [1, 7], 'c'] +>>> multisplit('a!===b=!=c', ['==', '!=', '=']) +['a', (1, 1), (0, 3), 'b', (2, 6), (1, 7), 'c'] +>>> multisplit('a!===b=!=c', ['!=', '==', '=']) +['a', (0, 1), (1, 3), 'b', (2, 6), (0, 7), 'c'] diff --git a/Task/Mutex/Perl-6/mutex.pl6 b/Task/Mutex/Perl-6/mutex.pl6 new file mode 100644 index 0000000000..1b409522aa --- /dev/null +++ b/Task/Mutex/Perl-6/mutex.pl6 @@ -0,0 +1,3 @@ +my $lock = Lock.new; + +$lock.protect: { your-ad-here() } diff --git a/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv b/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv index 435f74a6f7..df044197fc 100644 --- a/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv +++ b/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv @@ -11,4 +11,4 @@ M n: 0 for i range 0 10: - .( M i F i ) + !.( M i F i ) diff --git a/Task/Mutual-recursion/Julia/mutual-recursion.julia b/Task/Mutual-recursion/Julia/mutual-recursion.julia new file mode 100644 index 0000000000..6e5ff90674 --- /dev/null +++ b/Task/Mutual-recursion/Julia/mutual-recursion.julia @@ -0,0 +1,2 @@ +F(n) = n < 1 ? one(n) : n - M(F(n - 1)) +M(n) = n < 1 ? zero(n) : n - F(M(n - 1)) diff --git a/Task/N-queens-problem/D/n-queens-problem-1.d b/Task/N-queens-problem/D/n-queens-problem-1.d index 64113b9f40..0803f563e1 100644 --- a/Task/N-queens-problem/D/n-queens-problem-1.d +++ b/Task/N-queens-problem/D/n-queens-problem-1.d @@ -1,44 +1,9 @@ -import std.stdio; - -enum int SIDE = 8; -int[SIDE] board; - -bool unsafe(in int y) nothrow { - immutable int x = board[y]; - foreach (i; 1 .. y + 1) { - int t = board[y - i]; - if ((t == x) || (t == x - i) || (t == x + i)) - return true; - } - - return false; -} - -void showBoard() { - static int s = 1; - writeln("\nSolution #", s++); - foreach (y; 0 .. SIDE) { - foreach (x; 0 .. SIDE) - write(board[y] == x ? '*' : '.'); - writeln(); - } -} - void main() { - int y = 0; - board[0] = -1; + import std.stdio, std.algorithm, std.range, permutations2; - while (y >= 0) { - do { - board[y]++; - } while (board[y] < SIDE && unsafe(y)); - - if (board[y] < SIDE) { - if (y < (SIDE - 1)) - board[++y] = -1; - else - showBoard(); - } else - y--; - } + enum n = 8; + n.iota.array.permutations.filter!(p => + n.iota.map!(i => p[i] + i).array.sort().uniq.count == n && + n.iota.map!(i => p[i] - i).array.sort().uniq.count == n) + .count.writeln; } diff --git a/Task/N-queens-problem/D/n-queens-problem-2.d b/Task/N-queens-problem/D/n-queens-problem-2.d index 9dbd775941..0a49b9e595 100644 --- a/Task/N-queens-problem/D/n-queens-problem-2.d +++ b/Task/N-queens-problem/D/n-queens-problem-2.d @@ -1,90 +1,44 @@ -import std.stdio, std.conv; +enum side = 8; +__gshared int[side] board; -ulong nQueens(in uint nn) pure nothrow -in { - assert(nn > 0 && nn <= 27, - "'side' value must be in 1 .. 27."); -} body { - if (nn < 4) - return nn == 1; - - enum uint ulen = uint.sizeof * 8; - immutable uint full = uint.max - ((1 << (ulen - nn)) - 1); - immutable n = nn - 3; - - typeof(return) count; - uint[32] l=void, r=void, c=void; - uint[33] mm; // mm and mmi are a stack. - - // Require second queen to be left of the first queen, so - // we ever only test half of the possible solutions. This - // is why we can't handle n=1 here. - for (uint b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) { - for (uint b1 = b0 << 2; b1; b1 <<= 1) { - uint d = n; - // c: columns occupied by previous queens. - c[n] = b0 | b1; - // l: columns attacked by left diagonals. - l[n] = (b0 << 2) | (b1 << 1); - // r: by right diagnoals. - r[n] = (b0 >> 2) | (b1 >> 1); - - // Availabe columns on current row. - uint bits = full & ~(l[n] | r[n] | c[n]); - - uint mmi = 1; - mm[mmi] = bits; - - while (bits) { - // d: depth, aka row. counting backwards. - // Because !d is often faster than d != n. - while (d) { - // immutable uint pos = 1U << bits.bsf; // Slower. - immutable uint pos = -(cast(int)bits) & bits; - - // Mark bit used. Only put current bits on - // stack if not zero, so backtracking will - // skip exhausted rows (because reading stack - // variable is slow compared to registers). - bits &= ~pos; - if (bits) { - mm[mmi] = bits | d; - mmi++; - } - - d--; - l[d] = (l[d + 1] | pos) << 1; - r[d] = (r[d + 1] | pos) >> 1; - c[d] = c[d + 1] | pos; - - bits = full & ~(l[d] | r[d] | c[d]); - - if (!bits) - break; - if (!d) { - count++; - break; - } - } - - // Bottom of stack m is a zero'd field acting as - // sentinel. When saving to stack, left 27 bits - // are the available columns, while right 5 bits - // is the depth. Hence solution is limited to size - // 27 board -- not that it matters in foreseeable - // future. - mmi--; - bits = mm[mmi]; - d = bits & 31U; - bits &= ~31U; - } - } +bool isUnsafe(in int y) nothrow { + immutable int x = board[y]; + foreach (immutable i; 1 .. y + 1) { + immutable int t = board[y - i]; + if (t == x || t == x - i || t == x + i) + return true; } - return count * 2; + return false; } -void main(in string[] args) { - immutable uint side = (args.length >= 2) ? args[1].to!uint : 8; - writefln("N-queens(%d) = %d solutions.", side, side.nQueens); +void showBoard() nothrow { + import core.stdc.stdio; + + static int s = 1; + printf("\nSolution #%d:\n", s++); + foreach (immutable y; 0 .. side) { + foreach (immutable x; 0 .. side) + putchar(board[y] == x ? 'Q' : '.'); + putchar('\n'); + } +} + +void main() nothrow { + int y = 0; + board[0] = -1; + + while (y >= 0) { + do { + board[y]++; + } while (board[y] < side && y.isUnsafe); + + if (board[y] < side) { + if (y < (side - 1)) + board[++y] = -1; + else + showBoard; + } else + y--; + } } diff --git a/Task/N-queens-problem/D/n-queens-problem-3.d b/Task/N-queens-problem/D/n-queens-problem-3.d new file mode 100644 index 0000000000..9dbd775941 --- /dev/null +++ b/Task/N-queens-problem/D/n-queens-problem-3.d @@ -0,0 +1,90 @@ +import std.stdio, std.conv; + +ulong nQueens(in uint nn) pure nothrow +in { + assert(nn > 0 && nn <= 27, + "'side' value must be in 1 .. 27."); +} body { + if (nn < 4) + return nn == 1; + + enum uint ulen = uint.sizeof * 8; + immutable uint full = uint.max - ((1 << (ulen - nn)) - 1); + immutable n = nn - 3; + + typeof(return) count; + uint[32] l=void, r=void, c=void; + uint[33] mm; // mm and mmi are a stack. + + // Require second queen to be left of the first queen, so + // we ever only test half of the possible solutions. This + // is why we can't handle n=1 here. + for (uint b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) { + for (uint b1 = b0 << 2; b1; b1 <<= 1) { + uint d = n; + // c: columns occupied by previous queens. + c[n] = b0 | b1; + // l: columns attacked by left diagonals. + l[n] = (b0 << 2) | (b1 << 1); + // r: by right diagnoals. + r[n] = (b0 >> 2) | (b1 >> 1); + + // Availabe columns on current row. + uint bits = full & ~(l[n] | r[n] | c[n]); + + uint mmi = 1; + mm[mmi] = bits; + + while (bits) { + // d: depth, aka row. counting backwards. + // Because !d is often faster than d != n. + while (d) { + // immutable uint pos = 1U << bits.bsf; // Slower. + immutable uint pos = -(cast(int)bits) & bits; + + // Mark bit used. Only put current bits on + // stack if not zero, so backtracking will + // skip exhausted rows (because reading stack + // variable is slow compared to registers). + bits &= ~pos; + if (bits) { + mm[mmi] = bits | d; + mmi++; + } + + d--; + l[d] = (l[d + 1] | pos) << 1; + r[d] = (r[d + 1] | pos) >> 1; + c[d] = c[d + 1] | pos; + + bits = full & ~(l[d] | r[d] | c[d]); + + if (!bits) + break; + if (!d) { + count++; + break; + } + } + + // Bottom of stack m is a zero'd field acting as + // sentinel. When saving to stack, left 27 bits + // are the available columns, while right 5 bits + // is the depth. Hence solution is limited to size + // 27 board -- not that it matters in foreseeable + // future. + mmi--; + bits = mm[mmi]; + d = bits & 31U; + bits &= ~31U; + } + } + } + + return count * 2; +} + +void main(in string[] args) { + 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/Erlang/n-queens-problem.erl b/Task/N-queens-problem/Erlang/n-queens-problem.erl new file mode 100644 index 0000000000..644ab1138a --- /dev/null +++ b/Task/N-queens-problem/Erlang/n-queens-problem.erl @@ -0,0 +1,83 @@ +-module( n_queens ). + +-export( [display/1, solve/1, task/0] ). + +display( Board ) -> + %% Queens are in the positions in the Board list. + %% Top left corner is {1, 1}, Bottom right is {N, N}. There is a queen in the max column. + N = lists:max( [X || {X, _Y} <- Board] ), + [display_row(Y, N, Board) || Y <- lists:seq(1, N)]. + +solve( N ) -> + Positions = [{X, Y} || X <- lists:seq(1, N), Y <- lists:seq(1, N)], + try + bt( N, Positions, [] ) + + catch + _:{ok, Board} -> Board + + end. + +task() -> + task( 4 ), + task( 8 ). + + + +bt( N, Positions, Board ) -> bt_reject( is_not_allowed_queen_placement(N, Board), N, Positions, Board ). + +bt_accept( true, _N, _Positions, Board ) -> erlang:throw( {ok, Board} ); +bt_accept( false, N, Positions, Board ) -> bt_loop( N, Positions, [], Board ). + +bt_loop( _N, [], _Rejects, _Board ) -> failed; +bt_loop( N, [Position | T], Rejects, Board ) -> + bt( N, T ++ Rejects, [Position | Board] ), + bt_loop( N, T, [Position | Rejects], Board ). + +bt_reject( true, _N, _Positions, _Board ) -> backtrack; +bt_reject( false, N, Positions, Board ) -> bt_accept( is_all_queens(N, Board), N, Positions, Board ). + +diagonals( N, {X, Y} ) -> + D1 = diagonals( N, X + 1, fun diagonals_add1/1, Y + 1, fun diagonals_add1/1 ), + D2 = diagonals( N, X + 1, fun diagonals_add1/1, Y - 1, fun diagonals_subtract1/1 ), + D3 = diagonals( N, X - 1, fun diagonals_subtract1/1, Y + 1, fun diagonals_add1/1 ), + D4 = diagonals( N, X - 1, fun diagonals_subtract1/1, Y - 1, fun diagonals_subtract1/1 ), + D1 ++ D2 ++ D3 ++ D4. + +diagonals( _N, 0, _Change_x, _Y, _Change_y ) -> []; +diagonals( _N, _X, _Change_x, 0, _Change_y ) -> []; +diagonals( N, X, _Change_x, _Y, _Change_y ) when X > N -> []; +diagonals( N, _X, _Change_x, Y, _Change_y ) when Y > N -> []; +diagonals( N, X, Change_x, Y, Change_y ) -> [{X, Y} | diagonals( N, Change_x(X), Change_x, Change_y(Y), Change_y )]. + +diagonals_add1( N ) -> N + 1. + +diagonals_subtract1( N ) -> N - 1. + +display_row( Row, N, Board ) -> + [io:fwrite("~s", [display_queen(X, Row, Board)]) || X <- lists:seq(1, N)], + io:nl(). + +display_queen( X, Y, Board ) -> display_queen( lists:member({X, Y}, Board) ). +display_queen( true ) -> " Q"; +display_queen( false ) -> " .". + +is_all_queens( N, Board ) -> N =:= erlang:length( Board ). + +is_diagonal( _N, [] ) -> false; +is_diagonal( N, [Position | T] ) -> + Diagonals = diagonals( N, Position ), + T =/= (T -- Diagonals) + orelse is_diagonal( N, T ). + +is_not_allowed_queen_placement( N, Board ) -> + Pieces = erlang:length( Board ), + {Xs, Ys} = lists:unzip( Board ), + Pieces =/= erlang:length( lists:usort(Xs) ) + orelse Pieces =/= erlang:length( lists:usort(Ys) ) + orelse is_diagonal( N, Board ). + +task( N ) -> + io:fwrite( "N = ~p. One solution.~n", [N] ), + Board = solve( N ), + display( Board ). diff --git a/Task/N-queens-problem/GAP/n-queens-problem.gap b/Task/N-queens-problem/GAP/n-queens-problem.gap new file mode 100644 index 0000000000..e9f1a405df --- /dev/null +++ b/Task/N-queens-problem/GAP/n-queens-problem.gap @@ -0,0 +1,37 @@ +# Quick and dirty solution, checking all permutations without backtracking (thus it's slow) +IsSafe := function(a) + local n, i, j; + n := Length(a); + for i in [1 .. n - 1] do + for j in [i + 1 .. n] do + if AbsInt(a[j] - a[i]) = j - i then + return false; + fi; + od; + od; + return true; +end; + +Queens := function(n) + local p, a, v; + v := []; + for p in SymmetricGroup(n) do + a := List([1 .. n], i -> i^p); + if IsSafe(a) then + Add(v, a); + fi; + od; + return v; +end; + +v := Queens(8);; +Length(v); +PrintArray(PermutationMat(PermListList([1 .. 8], v[1]), 8)); +[ [ 0, 0, 1, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 1, 0, 0 ], + [ 0, 1, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 1, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 0, 0, 1 ], + [ 1, 0, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 0, 1, 0 ], + [ 0, 0, 0, 1, 0, 0, 0, 0 ] ] diff --git a/Task/N-queens-problem/Haskell/n-queens-problem-3.hs b/Task/N-queens-problem/Haskell/n-queens-problem-3.hs new file mode 100644 index 0000000000..ef4e2b8160 --- /dev/null +++ b/Task/N-queens-problem/Haskell/n-queens-problem-3.hs @@ -0,0 +1,12 @@ +import Data.List (nub, permutations) + +-- checks if queens are on the same diagonal +-- with [0..] we place each queen on her own row +check f = length . nub . zipWith f [0..] + +-- filters out results where 2 or more queens are on the same diagonal +-- with [0..n-1] we place each queeen on her own column +generate n = filter (\x -> check (+) x == n && check (-) x == n) $ permutations [0..n-1] + +-- 8 is for "8 queens" +main = print $ generate 8 diff --git a/Task/N-queens-problem/Liberty-BASIC/n-queens-problem.liberty b/Task/N-queens-problem/Liberty-BASIC/n-queens-problem.liberty new file mode 100644 index 0000000000..c33944d250 --- /dev/null +++ b/Task/N-queens-problem/Liberty-BASIC/n-queens-problem.liberty @@ -0,0 +1,84 @@ +'N queens +'>10 would not work due to way permutations used +'anyway, 10 doesn't fit in memory +Input "Input N for N queens puzzle (4..9) ";N +if N<4 or N>9 then print "N out of range - quitting": end + +ABC$= " " +dash$ = "" +for i = 0 to N-1 + ABC$=ABC$+" "+chr$(asc("a")+i) + dash$ = dash$+"--" +next + +dim q(N) +t0=time$("ms") + +fact = 1 +for i = 1 to N + fact = fact*i +next + +dim anagram$(fact) +global nPerms +print "Filling permutations array" +t0=time$("ms") + res$=permutation$("", left$("0123456789", N)) +t1=time$("ms") +print "Created all possible permutations ";t1-t0 + +t0=time$("ms") +'actually fact = nPerms +for k=1 to nPerms + for i=0 to N-1 + q(i)=val(mid$(anagram$(k),i+1,1)) + 'print q(i); + next + 'print + + fail = 0 + for i=0 to N-1 + for j=i+1 to N-1 + 'check rows are different + if q(i)=q(j) then fail = 1: exit for + 'check diagonals are different + if i+q(i)=j+q(j) then fail = 1: exit for + 'check other diagonals are different + if i-q(i)=j-q(j) then fail = 1: exit for + next + if fail then exit for + next + + if not(fail) then + num=num+1 + print " ";dash$ + for i=0 to N-1 + print N-i; space$(2*q(i));" *" + next + print " ";dash$ + print ABC$ + end if + +next + +t1=time$("ms") +print "Time taken ";t1-t0 +print "Number of solutions ";num + +'---------------------------------- +'from +'http://babek.info/libertybasicfiles/lbnews/nl124/wordgames.htm +'Programming a Word Game by Janet Terra, +'The Liberty Basic Newsletter - Issue #124 - September 2004 +Function permutation$(pre$, post$) +'Note the variable nPerms must first be stated as a global variable. + lgth = Len(post$) + If lgth < 2 Then + nPerms = nPerms + 1 + anagram$(nPerms) = pre$;post$ + Else + For i = 1 To lgth + tmp$=permutation$(pre$+Mid$(post$,i,1),Left$(post$,i-1)+Right$(post$,lgth-i)) + Next i + End If +End Function diff --git a/Task/Narcissist/Deja-Vu/narcissist.djv b/Task/Narcissist/Deja-Vu/narcissist.djv index 36ec426894..562ba22573 100644 --- a/Task/Narcissist/Deja-Vu/narcissist.djv +++ b/Task/Narcissist/Deja-Vu/narcissist.djv @@ -1 +1 @@ -= concat( over over rot chr 34 ) "= concat( over over chr 34 ) " +!. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) " diff --git a/Task/Narcissist/Perl/narcissist-1.pl b/Task/Narcissist/Perl/narcissist-1.pl index d984aa5c2b..834015bc5c 100644 --- a/Task/Narcissist/Perl/narcissist-1.pl +++ b/Task/Narcissist/Perl/narcissist-1.pl @@ -1,2 +1,3 @@ # this is file narc.pl -print do { local $/; open 0, $0 or die $!; <0> } eq <> ? "accept" : "reject" +local $/; +print do { open 0; <0> } eq <> ? "accept" : "reject"; diff --git a/Task/Nautical-bell/PL-I/nautical-bell.pli b/Task/Nautical-bell/PL-I/nautical-bell.pli new file mode 100644 index 0000000000..b3b831a0a8 --- /dev/null +++ b/Task/Nautical-bell/PL-I/nautical-bell.pli @@ -0,0 +1,14 @@ +nautical: procedure options (main); /* 29 October 2013 */ + declare (hour, t, i) fixed binary; + + do until (substr(time(), 3, 4) = '0000'); delay (1000); end; + hour = substr(time(), 1, 2); + + do while ('1'b); + do i = 1 to hour; + put edit ('07'X) (a); put skip edit ('gong ') (a); delay (500); + end; + t = substr(time(), 5); + delay (60*60*1000 - t); + end; +end nautical; diff --git a/Task/Non-decimal-radices-Input/PL-I/non-decimal-radices-input.pli b/Task/Non-decimal-radices-Input/PL-I/non-decimal-radices-input.pli index d7f148e800..5301c9d314 100644 --- a/Task/Non-decimal-radices-Input/PL-I/non-decimal-radices-input.pli +++ b/Task/Non-decimal-radices-Input/PL-I/non-decimal-radices-input.pli @@ -1,3 +1,4 @@ +declare N fixed binary; get edit (N) (A(7)); /* decimal input of 7 columns */ put skip list (N); diff --git a/Task/Nth-root/Julia/nth-root.julia b/Task/Nth-root/Julia/nth-root.julia new file mode 100644 index 0000000000..3a66710c2b --- /dev/null +++ b/Task/Nth-root/Julia/nth-root.julia @@ -0,0 +1,15 @@ +function nthroot(n::Integer, A::Real) + A < 0 || n == 0 && throw(DomainError()) + n < 0 && return 1/nthroot(-n, A) + A == 0 && return A + x = A / n + prevdx = A + while true + y = x^(n-1) + dx = (A - y*x) / (n * y) + abs(dx) >= abs(prevdx) && return x + x += dx + prevdx = dx + end +end +@vectorize_2arg Number nthroot diff --git a/Task/Null-object/BASIC/null-object-1.basic b/Task/Null-object/BASIC/null-object-1.basic new file mode 100644 index 0000000000..bd4a34decf --- /dev/null +++ b/Task/Null-object/BASIC/null-object-1.basic @@ -0,0 +1,5 @@ +TRUE = 1 : FALSE = 0 +NULL = TRUE +IF NULL THEN PRINT "NULL" +NULL = FALSE +IF NOT NULL THEN PRINT "NOT NULL" diff --git a/Task/Null-object/BASIC/null-object-2.basic b/Task/Null-object/BASIC/null-object-2.basic new file mode 100644 index 0000000000..6480acd3a8 --- /dev/null +++ b/Task/Null-object/BASIC/null-object-2.basic @@ -0,0 +1,13 @@ + PROCtestobjects + END + + DEF PROCtestobjects + PRIVATE a(), b(), s{}, t{} + DIM a(123) + DIM s{a%, b#, c$} + + IF !^a() <= 1 PRINT "a() is null" ELSE PRINT "a() is not null" + IF !^b() <= 1 PRINT "b() is null" ELSE PRINT "b() is not null" + IF !^s{} <= 1 PRINT "s{} is null" ELSE PRINT "s{} is not null" + IF !^t{} <= 1 PRINT "t{} is null" ELSE PRINT "t{} is not null" + ENDPROC diff --git a/Task/Null-object/Deja-Vu/null-object.djv b/Task/Null-object/Deja-Vu/null-object.djv new file mode 100644 index 0000000000..b28cec6511 --- /dev/null +++ b/Task/Null-object/Deja-Vu/null-object.djv @@ -0,0 +1,5 @@ +if not obj: + pass #obj is seen as null + +if = :nil obj: + pass #obj is seen as null diff --git a/Task/Number-names/Scala/number-names.scala b/Task/Number-names/Scala/number-names.scala index 26c0d4b4ce..6fbbebc9a8 100644 --- a/Task/Number-names/Scala/number-names.scala +++ b/Task/Number-names/Scala/number-names.scala @@ -1,51 +1,35 @@ package org.rosettacode package numbernames -import annotation.tailrec -import collection.parallel.ParSeq +import scala.annotation.tailrec +import scala.collection.parallel.ParSeq -/** Spells a number longhand +/** Spells a English numeral longhand. The numbers are expressed using words. * * The implementation goes up to 1069-1 and also supports negative and zero inputs. * * @example longhand( 1234 ) // results in: "one thousand two hundred thirty-four". */ -object SpellNumber extends App { - +trait LongHand { /** Spells a number longhand * - * The solution is recursive by the triplets of decimal numbers. - * @param v the numeric value to be converted + * Done by recursively process the triplets of decimal numbers. + * @param numeral the numeric value to be converted * @param showAnd flag the output extra and in output, default off * @param zeroString the word for 0, default to "zero" - * @param showHyphen shows the hyphen e.g. twenty-four, default is on + * @param showHyphen hyphenate all compound numbers e.g. twenty-four, default is on * @return the numeric value in words */ - def longhand(v: BigInt, + def longhand(numeral: BigInt, zeroString: String = "zero", showAnd: Boolean = false, showHyphen: Boolean = true): String = { - val onesAndTeens = { - val a1 = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ") - val a2 = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ") - (Array[String]("") ++ a1 ++ a2).par - } - - val tens = (Array[String]("", "") ++ ("twen thir for fif six seven eigh nine".split(' ')). - map(_ + "ty")).par - val hundredString = "hundred " val condAndString = if (showAnd) "and " else "" val condHyphenString = if (showHyphen) "-" else " " - val powersOfThousands = { - val p1 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ").par - val p2 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ").par - val p3 = "vigint cent".split(' ').map(_ + "illion ") ++ Array("overflow trap").par - (Array("", "thousand ") ++ p1 ++ p2 ++ p3).par - } - // 234 becomes "two hundred [and] thirty-four" - def tripletGroup(nnn: String, isLSDgroup: Boolean, strE3: String): String = { + // 234 Becomes "two hundred [and] thirty-four" + def composeScale(nnn: String, isLSDgroup: Boolean, strE3: String): String = { nnn match { // Rare exceptions confirms the rule case "000" => "" case "100" => onesAndTeens(1) + hundredString + strE3 // Solves the faulty hundred AND thousand problem @@ -63,13 +47,13 @@ object SpellNumber extends App { }.mkString + strE3 } } - } // def tripletGroup(… + } // def composeScale(… def compose(n: BigInt): String = { // "1234" becomes List((1,"thousand"), (234, "")) val decGroups = n.toString.reverse.grouped(3).map(_.reverse).toSeq.par // Group into powers of thousands - .zip(powersOfThousands) // // Name the powers of Thousands - .reverse // // Put it back to most-significant first + .zip(shortScale) // // Name the powers of Thousands + .reverse // // Put it back to most-significant first if (decGroups.size < 24) // Detect overflow trap { // Send per group sections to composeScale @@ -77,7 +61,7 @@ object SpellNumber extends App { def iter(elems: Seq[(String, String)], acc: String): String = { elems match { case (group, powers) :: tail => { - iter(tail, acc + tripletGroup(group, tail == Nil, powers)) + iter(tail, acc + composeScale(group, tail == Nil, powers)) } case _ => acc } @@ -87,9 +71,27 @@ object SpellNumber extends App { } // def compose(… // Here starts def longhand(… - if (v < 0) "minus " + compose(-v) else compose(v) + if (numeral < 0) "minus " + compose(-numeral) else compose(numeral) } // End def longhand(… @ 91 lines + val onesAndTeens = { + def lowNumerals = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ") + def tenties = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ") + ParSeq("") ++ lowNumerals ++ tenties + } + + val tens = (Array[String]("", "") ++ ("twen thir for fif six seven eigh nine".split(' ')). + map(_ + "ty")).par + def hundredString = "hundred " + lazy val shortScale = { + def p1 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ").par + def p2 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ").par + def p3 = ("vigint cent".split(' ').map(_ + "illion ") :+ "overflow trap").par + ParSeq("", "thousand ") ++ p1 ++ p2 ++ p3 + } +} // trait LongHand + +object SpellNumber extends LongHand with App { // Main entry A little test... { // Anonymous ordered list as test set def testVal1 = BigInt("1" * 69) @@ -105,6 +107,6 @@ object SpellNumber extends App { ParSeq(-Long.MaxValue, -1000000000, 12, 13, 19, 20, 21, 112, 1001, 1012, 1013, Long.MaxValue - 1, Long.MaxValue - 13, testVal1, testVal9)) ++ (for (z <- 0 to 69) yield BigInt(10).pow(z)) // powers of ten - }.seq.sorted. - foreach(num => println(f"""$num%+,80d -> ${longhand(v = num, showAnd = true)}""")) -} // object SpellNumber + + }.seq.sorted.foreach(num => println(f"$num%+,80d -> ${longhand(numeral = num, showAnd = true)}")) +} // object SpellNumber @ line 110 diff --git a/Task/Number-reversal-game/Seed7/number-reversal-game.seed7 b/Task/Number-reversal-game/Seed7/number-reversal-game.seed7 new file mode 100644 index 0000000000..9ffe990916 --- /dev/null +++ b/Task/Number-reversal-game/Seed7/number-reversal-game.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const array integer: sortedList is [] ( 1, 2, 3, 4, 5, 6, 7, 8, 9); + var array integer: list is 0 times 0; + var array integer: reversedList is 0 times 0; + var integer: score is 0; + var integer: index is 0; + var integer: number is 0; + var integer: reverse is 0; + begin + for number range sortedList do + index := rand(1, succ(length(list))); + list := list[.. pred(index)] & [] (number) & list[index ..]; + end for; + repeat + write("Current list: "); + for number range list do + write(number <& " "); + end for; + repeat + write(" Digits to reverse? "); + readln(reverse); + if reverse < 2 or reverse > 9 then + write("Please enter a value between 2 and 9."); + end if; + until reverse >= 2 and reverse <= 9; + incr(score); + reversedList := 0 times 0; + for index range reverse downto 1 do + reversedList &:= list[index]; + end for; + list := reversedList & list[succ(reverse) ..]; + until list = sortedList; + writeln("Congratulations, you sorted the list in " <& score <& " reversals."); + end func; diff --git a/Task/Numeric-error-propagation/C/numeric-error-propagation.c b/Task/Numeric-error-propagation/C/numeric-error-propagation.c index 2a3eb896e0..2dde616b7a 100644 --- a/Task/Numeric-error-propagation/C/numeric-error-propagation.c +++ b/Task/Numeric-error-propagation/C/numeric-error-propagation.c @@ -1,52 +1,75 @@ +#include +#include #include #include -struct imprecise { +typedef struct{ double value; double delta; -}; +}imprecise; #define SQR(x) ((x) * (x)) -struct imprecise imprecise_add(struct imprecise a, struct imprecise b) +imprecise imprecise_add(imprecise a, imprecise b) { - struct imprecise ret; + imprecise ret; ret.value = a.value + b.value; ret.delta = sqrt(SQR(a.delta) + SQR(b.delta)); return ret; } -struct imprecise imprecise_mul(struct imprecise a, struct imprecise b) +imprecise imprecise_mul(imprecise a, imprecise b) { - struct imprecise ret; + imprecise ret; ret.value = a.value * b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)); return ret; } -struct imprecise imprecise_div(struct imprecise a, struct imprecise b) +imprecise imprecise_div(imprecise a, imprecise b) { - struct imprecise ret; + imprecise ret; ret.value = a.value / b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value); return ret; } -struct imprecise imprecise_pow(struct imprecise a, double c) +imprecise imprecise_pow(imprecise a, double c) { - struct imprecise ret; + imprecise ret; ret.value = pow(a.value, c); ret.delta = fabs(ret.value * c * a.delta / a.value); return ret; } +char* printImprecise(imprecise val) +{ + char principal[30],error[30],*string,sign[2]; + sign[0] = 241; /* ASCII code for ±, technical notation for denoting errors */ + sign[1] = 00; + + sprintf(principal,"%f",val.value); + sprintf(error,"%f",val.delta); + + string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char)); + + strcpy(string,principal); + strcat(string,sign); + strcat(string,error); + + return string; +} + int main(void) { - struct imprecise x1 = {100, 1.1}; - struct imprecise y1 = {50, 1.2}; - struct imprecise x2 = {-200, 2.2}; - struct imprecise y2 = {-100, 2.3}; - struct imprecise d; + imprecise x1 = {100, 1.1}; + imprecise y1 = {50, 1.2}; + imprecise x2 = {-200, 2.2}; + imprecise y2 = {-100, 2.3}; + imprecise d; d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5); - printf("d = %f \\pm %f\n", d.value, d.delta); + printf("Distance, d, between the following points :"); + printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1)); + printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2)); + printf("\nis d = %s", printImprecise(d)); return 0; } diff --git a/Task/Numeric-error-propagation/PicoLisp/numeric-error-propagation-1.l b/Task/Numeric-error-propagation/PicoLisp/numeric-error-propagation-1.l index cfd0e3376e..9339d8c5e3 100644 --- a/Task/Numeric-error-propagation/PicoLisp/numeric-error-propagation-1.l +++ b/Task/Numeric-error-propagation/PicoLisp/numeric-error-propagation-1.l @@ -91,4 +91,4 @@ (pack (round (car N) 10) " ± " - (round (sqrt (* 1.0 (cdr N))) 8) ) ) ) + (round (sqrt (cdr N) 1.0) 8) ) ) ) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.delphi b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.delphi new file mode 100644 index 0000000000..1b6b3a24bc --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.delphi @@ -0,0 +1,94 @@ +program Legendre; + +{$APPTYPE CONSOLE} + +const Order = 5; + Epsilon = 1E-12; + +var Roots : array[0..Order-1] of double; + Weight : array[0..Order-1] of double; + LegCoef : array [0..Order,0..Order] of double; + +function F(X:double) : double; +begin + Result := Exp(X); +end; + +procedure PrepCoef; +var I, N : integer; +begin + for I:=0 to Order do + for N := 0 to Order do + LegCoef[I,N] := 0; + LegCoef[0,0] := 1; + LegCoef[1,1] := 1; + For N:=2 to Order do + begin + LegCoef[N,0] := -(N-1) * LegCoef[N-2,0] / N; + For I := 1 to Order do + LegCoef[N,I] := ((2*N-1) * LegCoef[N-1,I-1] - (N-1)*LegCoef[N-2,I]) / N; + end; +end; + +function LegEval(N:integer; X:double) : double; +var I : integer; +begin + Result := LegCoef[n][n]; + for I := N-1 downto 0 do + Result := Result * X + LegCoef[N][I]; +end; + +function LegDiff(N:integer; X:double) : double; +begin + Result := N * (X * LegEval(N,X) - LegEval(N-1,X)) / (X*X-1); +end; + +procedure LegRoots; +var I : integer; + X, X1 : double; +begin + for I := 1 to Order do + begin + X := Cos(Pi * (I-0.25) / (Order+0.5)); + repeat + X1 := X; + X := X - LegEval(Order,X) / LegDiff(Order, X); + until Abs (X-X1) < Epsilon; + Roots[I-1] := X; + X1 := LegDiff(Order,X); + Weight[I-1] := 2 / ((1-X*X) * X1*X1); + end; +end; + +function LegInt(A,B:double) : double; +var I : integer; + C1, C2 : double; +begin + C1 := (B-A)/2; + C2 := (B+A)/2; + Result := 0; + For I := 0 to Order-1 do + Result := Result + Weight[I] * F(C1*Roots[I] + C2); + Result := C1 * Result; +end; + +var I : integer; + +begin + PrepCoef; + LegRoots; + + Write('Roots: '); + for I := 0 to Order-1 do + Write (' ',Roots[I]:13:10); + Writeln; + + Write('Weight: '); + for I := 0 to Order-1 do + Write (' ', Weight[I]:13:10); + writeln; + + Writeln('Integrating Exp(x) over [-3, 3]: ',LegInt(-3,3):13:10); + Writeln('Actual value: ',Exp(3)-Exp(-3):13:10); + Readln; +end. diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f index a6f0a8703a..15f6f5dd44 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f @@ -34,7 +34,6 @@ program gauss end do do i = 1, n x = cos(pi*(i-0.25_p)/(n+0.5_p)) - iter = 0 do iter = 1, 10 f = p1(1); df = 0._p do k = 2, size(p1) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.julia b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.julia new file mode 100644 index 0000000000..5f77bd5191 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.julia @@ -0,0 +1,4 @@ +function gauss(a,b, N) + λ, Q = eig(SymTridiagonal(zeros(N), [ n / sqrt(4n^2 - 1) for n = 1:N-1 ])) + return (λ + 1) * (b-a)/2 + a, [ 2*Q[1,i]^2 for i = 1:N ] * (b-a)/2 +end diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/PL-I/numerical-integration-gauss-legendre-quadrature.pli b/Task/Numerical-integration-Gauss-Legendre-Quadrature/PL-I/numerical-integration-gauss-legendre-quadrature.pli new file mode 100644 index 0000000000..aab0f354cf --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/PL-I/numerical-integration-gauss-legendre-quadrature.pli @@ -0,0 +1,54 @@ +(subscriptrange, size, fofl): +Integration_Gauss: procedure options (main); + + declare (n, k) fixed binary; + declare r(*,*) float (18) controlled; + declare (z, a, b, exact) float (18); + + do n = 1 to 20; + a = -3; b = 3; + if allocation(r) > 0 then free r; + allocate r(2, n); r = 0; + call gaussquad(n, r); + z = (b-a)/2 * sum(r(2,*) * exp((a+b)/2+r(1,*)*(b-a)/2)); + exact = exp(3.0q0)-exp(-3.0q0); + put skip edit (n, z, z-exact) (f(5), f(25,16), e(15,2)); + end; + +gaussquad: procedure(n, r); +/*declare n fixed binary, r(2, n) float (18);*/ + declare n fixed binary, r(2, *) float (18);/* corrected */ + declare pi float (18) value (4*atan(1.0q0)); + declare (x, f, df, dx) float (18); + declare (i, iter, L) fixed binary; + declare (p0(*), p1(*), tmp(*), tmp2(*)) float (18) controlled; + + allocate p0(1) initial (1); + allocate p1(2) initial (1, 0); + + do k = 2 to n; + allocate tmp(hbound(p1)+1); do L = 1 to hbound(p1); tmp(L) = p1(L); end; tmp(L) = 0; + allocate tmp2(hbound(p0)+2); tmp2(1), tmp2(2) = 0; + do L = 1 to hbound(p0); tmp2(L+2) = p0(L); end; + tmp = ((2*k-1)*tmp - (k-1)*tmp2)/k; + free p0; allocate p0(hbound(p1)); p0 = p1; + free p1; allocate p1(hbound(tmp)); p1 = tmp; + free tmp, tmp2; + end; + do i = 1 to n; + x = cos(pi*(i-0.25q0)/(n+0.5q0)); + do iter = 1 to 10; + f = p1(1); df = 0; + do k = 2 to hbound(p1); + df = f + x*df; + f = p1(k) + x * f; + end; + dx = f / df; + x = x - dx; + if abs(dx) < 10*epsilon(dx) then leave; + end; + r(1,i) = x; + r(2,i) = 2/((1-x**2)*df**2); + end; + end gaussquad; +end Integration_Gauss; diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-1.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-1.rexx new file mode 100644 index 0000000000..047978cd28 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-1.rexx @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------- +* 31.10.2013 Walter Pachl Translation from PL/I +* 01.11.2014 -"- see Version 2 for improvements +*--------------------------------------------------------------------*/ +Call time 'R' +prec=60 +Numeric Digits prec +epsilon=1/10**prec +pi=3.141592653589793238462643383279502884197169399375105820974944592307 +exact = exp(3,prec)-exp(-3,prec) +Do n = 1 To 20 + a = -3; b = 3 + r.=0 + call gaussquad + sum=0 + Do j=1 To n + sum=sum + r.2.j * exp((a+b)/2+r.1.j*(b-a)/2,prec) + End + z = (b-a)/2 * sum + Say right(n,2) format(z,2,40) format(z-exact,2,4,,0) + End + Say ' ' exact '(exact)' + say '... and took' format(time('E'),,2) "seconds" + Exit + + gaussquad: + p0.0=1; p0.1=1 + p1.0=2; p1.1=1; p1.2=0 + Do k = 2 To n + tmp.0=p1.0+1 + Do L = 1 To p1.0 + tmp.l = p1.l + End + tmp.l=0 + tmp2.0=p0.0+2 + tmp2.1=0 + tmp2.2=0 + Do L = 1 To p0.0 + l2=l+2 + tmp2.l2=p0.l + End + Do j=1 To tmp.0 + tmp.j = ((2*k-1)*tmp.j - (k-1)*tmp2.j)/k + End + p0.0=p1.0 + Do j=1 To p0.0 + p0.j = p1.j + End + p1.0=tmp.0 + Do j=1 To p1.0 + p1.j=tmp.j + End + End + Do i = 1 To n + x = cos(pi*(i-0.25)/(n+0.5),prec) + Do iter = 1 To 10 + f = p1.1; df = 0 + Do k = 2 To p1.0 + df = f + x*df + f = p1.k + x * f + End + dx = f / df + x = x - dx + If abs(dx) < epsilon then leave + End + r.1.i = x + r.2.i = 2/((1-x**2)*df**2) + End + Return + +cos: Procedure +/* REXX **************************************************************** +* Return cos(x) -- with specified precision +* cos(x) = 1-(x**2/2!)+(x**4/4!)-(x**6/6!)+-... +* 920903 Walter Pachl +***********************************************************************/ + Parse Arg x,prec + If prec='' Then prec=9 + Numeric Digits (2*prec) + Numeric Fuzz 3 + o=1 + u=1 + r=1 + Do i=1 By 2 + ra=r + o=-o*x*x + u=u*i*(i+1) + r=r+(o/u) + If r=ra Then Leave + End + Numeric Digits prec + Return r+0 + +exp: Procedure +/*********************************************************************** +* Return exp(x) -- with reasonable precision +* 920903 Walter Pachl +***********************************************************************/ + Parse Arg x,prec + If prec<9 Then prec=9 + Numeric Digits (2*prec) + Numeric Fuzz 3 + o=1 + u=1 + r=1 + Do i=1 By 1 + ra=r + o=o*x + u=u*i + r=r+(o/u) + If r=ra Then Leave + End + Numeric Digits (prec) + Return r+0 diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx new file mode 100644 index 0000000000..a1a26bbac7 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx @@ -0,0 +1,58 @@ +/*REXX pgm does numerical integration using Gauss-Legendre Quadrature. */ +parse arg digs .; if digs=='' then digs=40 /*assume the DIGS default?*/ +numeric digits digs*2+10 /*use higher working DIGs.*/ +pi=pi(); a=-3; b=3; bma =b-a; bpa =b+a; tiny ='1E-' || (digs*2) +true = exp(b)-exp(a); bmaH=bma/2; bpaH=bpa/2; times= digs%2 + 1 +numeric digits digs+10 /*use lower working DIGITs*/ +say 'step' center("iterative value",digs+3) ' difference ' /*show hdr*/ +sep='────' copies('─' ,digs+3) '────────────'; say sep + + do step=1 for times; p0z=1; p0.1=1; step_=step+.5 + p1z=2; p1.1=1; p1.2=0; r.=0 +/*█*/ do k=2 to step; km=k-1 +/*█*/ do L=1 for p1z; T.L=p1.L +/*█*/ end /*L*/ +/*█*/ T.L=0; TT.=0 +/*█*/ do L=1 for p0z; L2=L+2; TT.L2=p0.L +/*█*/ end /*L*/ +/*█*/ +/*█*/ do j=1 for p1z+1;T.j=((k+km)*T.j-km*TT.j)/k; end /*j*/ +/*█*/ p0z=p1z; do j=1 for p0z; p0.j=p1.j ; end /*j*/ +/*█*/ p1z=p1z+1; do j=1 for p1z; p1.j= T.j ; end /*j*/ +/*█*/ end /*k*/ + + /*▓*/ do !=1 for step + /*▓*/ x=cos(pi*(!-.25)/step_) + /*▓*/ do times%2 until abs(dx).5 then ix=ix+sign(x) + x=x-ix; z=1; _=1; do j=1 until p==z; p=z; _=_*x/j; z=z+_; end + if z\==0 then z=z*e()**ix; return z +/*──────────────────────────────────PI subroutine──────────────────────────────────────*/ +pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 +/*──────────────────────────────────R2R subroutine──────────────────────*/ +r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ diff --git a/Task/Numerical-integration/Julia/numerical-integration.julia b/Task/Numerical-integration/Julia/numerical-integration.julia new file mode 100644 index 0000000000..c715fd324f --- /dev/null +++ b/Task/Numerical-integration/Julia/numerical-integration.julia @@ -0,0 +1,8 @@ +function simpson(f, a,b, n) + h = (b-a)/n + s = f(a + h/2) + for i in 1:(n-1) + s += f(a + h*i + h/2) + 0.5 * f(a + h*i) + end + h/6 * (f(a) + f(b) + 4*s) +end 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 index 4fc4924ef9..f5e55587d7 100644 --- 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 @@ -1,7 +1,7 @@ my @c = <_ #>; -my @array = '_###_##_#_#_#_#__#__'.comb.map: { $_ eq '#' }; +my @array = '_###_##_#_#_#_#__#__'.comb »eq» '#'; repeat until @array eqv my @prev { - say @c[@prev = @array]; + say @c[@prev = @array].join; @array = ((@array Z+ @array.rotate(1)) Z+ @array.rotate(-1)) X== 2; } diff --git a/Task/Optional-parameters/Julia/optional-parameters-1.julia b/Task/Optional-parameters/Julia/optional-parameters-1.julia new file mode 100644 index 0000000000..fd79e875d5 --- /dev/null +++ b/Task/Optional-parameters/Julia/optional-parameters-1.julia @@ -0,0 +1,4 @@ +sorttable(T; ordering=<, column=1, reverse=false) = + sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering) +sorttable(T, ordering=<, column=1, reverse=false) = + sorttable(T, ordering=ordering, column=column, reverse=reverse) diff --git a/Task/Optional-parameters/Julia/optional-parameters-2.julia b/Task/Optional-parameters/Julia/optional-parameters-2.julia new file mode 100644 index 0000000000..ce6087728b --- /dev/null +++ b/Task/Optional-parameters/Julia/optional-parameters-2.julia @@ -0,0 +1,17 @@ +julia> data = {["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]} +3-element Array{Any,1}: + ["a","b","c"] + ["","q","z"] + ["zap","zip","Zot"] + +julia> sorttable(data, column=2, reverse=true) # named arguments +3-element Array{Any,1}: + ["zap","zip","Zot"] + ["","q","z"] + ["a","b","c"] + +julia> sorttable(data, >, 2) # the same thing, with positional arguments +3-element Array{Any,1}: + ["zap","zip","Zot"] + ["","q","z"] + ["a","b","c"] diff --git a/Task/Ordered-words/D/ordered-words-2.d b/Task/Ordered-words/D/ordered-words-2.d index ef128f1503..482bdc7ec8 100644 --- a/Task/Ordered-words/D/ordered-words-2.d +++ b/Task/Ordered-words/D/ordered-words-2.d @@ -1,12 +1,11 @@ -import std.stdio, std.algorithm, std.file, std.range; - void main() { + import std.stdio, std.algorithm, std.file, std.range; string[] result; size_t maxWalkLen; - foreach (word; std.array.splitter(readText("unixdict.txt"))) { - if (word.length >= maxWalkLen && word.isSorted()) { - immutable wlen = word.walkLength(); + foreach (word; "unixdict.txt".readText.splitter) { + if (word.length >= maxWalkLen && word.isSorted) { + immutable wlen = word.walkLength; if (wlen > maxWalkLen) { result.length = 0; maxWalkLen = wlen; diff --git a/Task/Ordered-words/Rust/ordered-words.rust b/Task/Ordered-words/Rust/ordered-words.rust index d7c3892cde..8a013cd952 100644 --- a/Task/Ordered-words/Rust/ordered-words.rust +++ b/Task/Ordered-words/Rust/ordered-words.rust @@ -1,10 +1,8 @@ -// rust 0.8 - -use std::io::ReaderUtil; +// rust 0.9-pre (1b12dca 2013-12-11 12:56:22 -0800) fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; - for c in s.iter() { + for c in s.chars() { if c < prev { return false; } @@ -14,11 +12,11 @@ fn is_ordered(s: &str) -> bool { return true; } -fn find_longest_ordered_words(dict: ~[~str]) -> ~[~str] { +fn find_longest_ordered_words(dict: ~[&str]) -> ~[~str] { let mut result = ~[]; let mut longest_length = 0; - for s in dict.move_iter() { + for &s in dict.iter() { if is_ordered(s) { let n = s.len(); if n > longest_length { @@ -26,7 +24,7 @@ fn find_longest_ordered_words(dict: ~[~str]) -> ~[~str] { result.truncate(0); } if n == longest_length { - result.push(s); + result.push(s.to_owned()); } } } @@ -35,9 +33,10 @@ fn find_longest_ordered_words(dict: ~[~str]) -> ~[~str] { } fn main() { - let reader = std::io::file_reader(&Path("unixdict.txt")).unwrap(); + let raw = std::io::File::open(&Path::new("unixdict.txt")).read_to_end(); + let lines:~[&str] = std::str::from_utf8(raw).lines_any().collect(); - let longest_ordered = find_longest_ordered_words(reader.read_lines()); + let longest_ordered = find_longest_ordered_words(lines); for s in longest_ordered.iter() { println(s.to_str()); diff --git a/Task/Palindrome-detection/AWK/palindrome-detection-1.awk b/Task/Palindrome-detection/AWK/palindrome-detection-1.awk index d55fa23f85..b972765882 100644 --- a/Task/Palindrome-detection/AWK/palindrome-detection-1.awk +++ b/Task/Palindrome-detection/AWK/palindrome-detection-1.awk @@ -1,5 +1,5 @@ function is_palindro(s) { - if ( s == reverse(s) ) return 1; + if ( s == reverse(s) ) return 1 return 0 } diff --git a/Task/Palindrome-detection/AWK/palindrome-detection-2.awk b/Task/Palindrome-detection/AWK/palindrome-detection-2.awk index 0741449adf..ec3df62a48 100644 --- a/Task/Palindrome-detection/AWK/palindrome-detection-2.awk +++ b/Task/Palindrome-detection/AWK/palindrome-detection-2.awk @@ -1,6 +1,6 @@ function is_palindro_r(s) { - if ( length(s) < 2 ) return 1; - if ( substr(s, 1, 1) != substr(s, length(s), 1) ) return 0; + if ( length(s) < 2 ) return 1 + if ( substr(s, 1, 1) != substr(s, length(s), 1) ) return 0 return is_palindro_r(substr(s, 2, length(s)-2)) } diff --git a/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft b/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft index ba69dd7b68..76664f5158 100644 --- a/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft +++ b/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft @@ -3,8 +3,12 @@ 120 DATA"1 ON 1" 130 DATA"IN GIRUM IMUS NOCTE ET CONSUMIMUR IGNI" 140 DATA"A man, a plan, a canal: Panama!" +150 DATA"KAYAK" +160 DATA"REDDER" +170 DATA"H" +180 DATA"" -200 FOR L1 = 1 TO 4 +200 FOR L1 = 1 TO 9 210 READ W$ : GOSUB 300" IS PALINDROME? 220 PRINT CHR$(34); W$; CHR$(34); " IS "; 230 IF NOT PALINDROME THEN PRINT "NOT "; @@ -13,12 +17,10 @@ 260 END 300 REMIS PALINDROME? -310 FW$ = "" -320 BW$ = "" -330 FOR L0 = 1 TO LEN(W$) -340 C = ASC(MID$(W$, L0, 1)) -350 C$ = CHR$(C - (C > 95) * 32) -360 IF (C$ >= "A" AND C$ <= "Z") OR (C$ >= "0" AND C$ <= "9") THEN FW$ = FW$ + C$ : BW$ = C$ + BW$ -370 NEXT L0 -380 PA = FW$ = BW$ -390 RETURN +310 PA = 1 +320 L = LEN(W$) +330 IF L = 0 THEN RETURN +340 FOR L0 = 1 TO L / 2 + .5 +350 PA = MID$(W$, L0, 1) = MID$(W$, L - L0 + 1, 1) +360 IF PALINDROME THEN NEXT L0 +370 RETURN diff --git a/Task/Palindrome-detection/AutoHotkey/palindrome-detection.ahk b/Task/Palindrome-detection/AutoHotkey/palindrome-detection.ahk index ac92476218..d018b150d0 100644 --- a/Task/Palindrome-detection/AutoHotkey/palindrome-detection.ahk +++ b/Task/Palindrome-detection/AutoHotkey/palindrome-detection.ahk @@ -1,7 +1,5 @@ -IsPalindrome( Str ){ - StringLower, str, str - str := (RegexReplace(str,"\W+" )) +IsPalindrome(Str){ Loop, Parse, Str - reversedStr := A_LoopField . ReversedStr - Return ( ReversedStr = Str ) + ReversedStr := A_LoopField . ReversedStr + return, (ReversedStr == Str)?"Exact":(RegExReplace(ReversedStr,"\W")=RegExReplace(Str,"\W"))?"Inexact":"False" } diff --git a/Task/Palindrome-detection/AutoIt/palindrome-detection-1.autoit b/Task/Palindrome-detection/AutoIt/palindrome-detection-1.autoit new file mode 100644 index 0000000000..95ab96c763 --- /dev/null +++ b/Task/Palindrome-detection/AutoIt/palindrome-detection-1.autoit @@ -0,0 +1,31 @@ +;== AutoIt Version: 3.3.8.1 + +Global $aString[7] = [ _ +"In girum imus nocte, et consumimur igni", _ ; inexact palindrome +"Madam, I'm Adam.", _ ; inexact palindrome +"salàlas", _ ; exact palindrome +"radar", _ ; exact palindrome +"Lagerregal", _ ; exact palindrome +"Ein Neger mit Gazelle zagt im Regen nie.", _ ; inexact palindrome +"something wrong"] ; no palindrome +Global $sSpace42 = " " + +For $i = 0 To 6 + If _IsPalindrome($aString[$i]) Then + ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is an exact palindrome.' & @LF) + Else + If _IsPalindrome( StringRegExpReplace($aString[$i], '\W', '') ) Then + ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is an inexact palindrome.' & @LF) + Else + ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is not a palindrome.' & @LF) + EndIf + EndIf +Next + +Func _IsPalindrome($_string) + Local $iLen = StringLen($_string) + For $i = 1 To Int($iLen/2) + If StringMid($_string, $i, 1) <> StringMid($_string, $iLen-($i-1), 1) Then Return False + Next + Return True +EndFunc diff --git a/Task/Palindrome-detection/AutoIt/palindrome-detection-2.autoit b/Task/Palindrome-detection/AutoIt/palindrome-detection-2.autoit new file mode 100644 index 0000000000..0377cadd2f --- /dev/null +++ b/Task/Palindrome-detection/AutoIt/palindrome-detection-2.autoit @@ -0,0 +1,7 @@ +"In girum imus nocte, et consumimur igni" is an inexact palindrome. +"Madam, I'm Adam." is an inexact palindrome. +"salàlas" is an exact palindrome. +"radar" is an exact palindrome. +"Lagerregal" is an exact palindrome. +"Ein Neger mit Gazelle zagt im Regen nie." is an inexact palindrome. +"something wrong" is not a palindrome. diff --git a/Task/Palindrome-detection/AutoIt/palindrome-detection.autoit b/Task/Palindrome-detection/AutoIt/palindrome-detection.autoit deleted file mode 100644 index 804ee56798..0000000000 --- a/Task/Palindrome-detection/AutoIt/palindrome-detection.autoit +++ /dev/null @@ -1,52 +0,0 @@ -;AutoIt Version: 3.2.10.0 - -$mystring="In girum imus nocte, et consumimur igni" -MsgBox(0, "Palindrome", $mystring & " is palindrome: " & isPalindrome($mystring)) -;output is: "In girum imus nocte, et consumimur igni is palindrome: True" -$mystring="Madam, I'm Adam." -MsgBox(0, "Palindrome", $mystring & " is palindrome: " & isPalindrome($mystring)) -;output is: "Madam, I'm Adam. is palindrome: True" -$mystring="no salàlas no" -MsgBox(0, "Palindrome", $mystring & " is palindrome: " & isPalindrome($mystring)) -;output is: "no salàlas no is palindrome: False" - -Func isPalindrome($Str_palindrome) - $palindrome="False" - $Str_palindrome=StringLower($Str_palindrome) - $str_length = StringLen($Str_palindrome) - $new_str="" ;to rebuild string with only alphanumeric characters - - For $i = 1 to $str_length - $nth_chr = StringTrimRight(StringRight($Str_palindrome, $i),$i-1) - if StringIsAlpha($nth_chr) Then - $new_str=$new_str & $nth_chr ; add in string if alphabet - EndIf - if StringIsAlNum($nth_chr) Then - $new_str=$new_str & $nth_chr ; add in string if numeric - EndIf - - Next - $Str_palindrome=$new_str ;string without punctuations and spaces - $Str_reverse=reverse($Str_palindrome) ;reverse this string - - ;compare characters from both strings until half string is compared - For $i=1 to $str_length/2 - $First=StringLeft($Str_palindrome, 1) - $Last=StringLeft($Str_reverse, 1) - If $First == $Last Then - $palindrome="True" - EndIf - Next - - Return $palindrome -EndFunc - -; returns reverse of input string -Func reverse($string) - $str_length = StringLen($string) - $rev_str = "" - For $i = 1 to $str_length - $rev_str = $rev_str & StringTrimRight(StringRight($string, $i), $i-1) - Next - Return $rev_str -EndFunc diff --git a/Task/Palindrome-detection/Deja-Vu/palindrome-detection.djv b/Task/Palindrome-detection/Deja-Vu/palindrome-detection.djv new file mode 100644 index 0000000000..f003c39b86 --- /dev/null +++ b/Task/Palindrome-detection/Deja-Vu/palindrome-detection.djv @@ -0,0 +1,11 @@ +palindrome?: + local :seq chars + local :len-seq -- len seq + + for i range 0 / len-seq 2: + if /= seq! i seq! - len-seq i: + return false + true + +!. palindrome? "ingirumimusnocteetconsumimurigni" +!. palindrome? "nope" diff --git a/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl b/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl index 14134e8e70..e06e6b794e 100644 --- a/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl +++ b/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl @@ -1,27 +1,27 @@ #APPTYPE CONSOLE -FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER - DIM sTemp AS STRING = LCASE(s) - DIM n AS INTEGER = 1, nLen = STRLEN(sTemp) - DO - IF n >= nLen THEN EXIT DO - IF sTemp{n} < "a" OR sTemp{n} > "z" THEN - sTemp = STRDEL(sTemp, n, 1) - nLen = STRLEN(sTemp) - ELSE - n = n + 1 +FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING + DIM sTemp AS STRING = "" + DIM c AS STRING + FOR DIM i = 1 TO LEN(s) + c = MID(s, i, 1) + IF INSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c, 0, 1) THEN + sTemp = stemp & c END IF - LOOP - - FOR DIM i = 1 TO STRLEN(sTemp) \ 2 ' only check half of the string, if scanning from both ends - IF sTemp{i} <> sTemp{STRLEN - (i - 1)} THEN RETURN FALSE + NEXT + RETURN sTemp +END FUNCTION + +FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER + FOR DIM i = 1 TO STRLEN(s) \ 2 ' only check half of the string, as scanning from both ends + IF s{i} <> s{STRLEN - (i - 1)} THEN RETURN FALSE 'comparison is not case sensitive NEXT RETURN TRUE END FUNCTION -PRINT IsPalindrome("a toyota") -PRINT IsPalindrome("madam i'm adam") -PRINT IsPalindrome("the rain in Spain falls mainly on the rooftops") +PRINT IsPalindrome(stripNonAlpha("A Toyota")) +PRINT IsPalindrome(stripNonAlpha("Madam, I'm Adam")) +PRINT IsPalindrome(stripNonAlpha("the rain in Spain falls mainly on the rooftops")) PAUSE diff --git a/Task/Palindrome-detection/GML/palindrome-detection.gml b/Task/Palindrome-detection/GML/palindrome-detection.gml index 08a6d0115c..22fa4d1c0e 100644 --- a/Task/Palindrome-detection/GML/palindrome-detection.gml +++ b/Task/Palindrome-detection/GML/palindrome-detection.gml @@ -1,13 +1,15 @@ //Setting a var from an argument passed to the script -str=argument0 +var str; +str = argument0 //Takes out all spaces/anything that is not a letter or a number and turns uppercase letters to lowercase -str=string_lettersdigits(string_lower(string_replace(str,' ',''))); -inv=''; +str = string_lettersdigits(string_lower(string_replace(str,' ',''))); +var inv; +inv = ''; //for loop that reverses the sequence -for (i=0;i testLen){ + return true; + } + if(testMe.charAt(index) != testMe.charAt(strLen-index)){ + return false; + } + return rPaliHelp(testMe, strLen, testLen, index + 1); } diff --git a/Task/Palindrome-detection/Java/palindrome-detection-4.java b/Task/Palindrome-detection/Java/palindrome-detection-4.java new file mode 100644 index 0000000000..7c52cbb7e1 --- /dev/null +++ b/Task/Palindrome-detection/Java/palindrome-detection-4.java @@ -0,0 +1,3 @@ +public static boolean pali(String testMe){ + return testMe.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)"); +} diff --git a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-1.liberty b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-1.liberty new file mode 100644 index 0000000000..bca4d4cedd --- /dev/null +++ b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-1.liberty @@ -0,0 +1,22 @@ +print isPalindrome("In girum imus nocte et consumimur igni") +print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S")) +print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC")) + +function isPalindrome(string$) + isPalindrome = 1 + for i = 1 to int(len(string$)/2) + if mid$(string$, i, 1) <> mid$(string$, len(string$)-i+1, 1) then isPalindrome = 0 : exit function + next i +end function + +function removePunctuation$(string$, remove$) + 'P = remove puctuation. S = remove spaces C = remove case + If instr(upper$(remove$), "C") then string$ = lower$(string$) + If instr(upper$(remove$), "P") then removeCharacters$ = ",.!'()-&*?<>:;~[]{}" + If instr(upper$(remove$), "S") then removeCharacters$ = removeCharacters$;" " + + for i = 1 to len(string$) + if instr(removeCharacters$, mid$(string$, i, 1)) then string$ = left$(string$, i-1);right$(string$, len(string$)-i) : i = i - 1 + next i + removePunctuation$ = string$ +end function diff --git a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-2.liberty b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-2.liberty new file mode 100644 index 0000000000..bb5ee5c21e --- /dev/null +++ b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-2.liberty @@ -0,0 +1,3 @@ +0 +0 +1 diff --git a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty deleted file mode 100644 index cb2a660453..0000000000 --- a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty +++ /dev/null @@ -1,22 +0,0 @@ -Print isPalindrome("In girum imus nocte et consumimur igni") -Print isPalindrome("atta") - -Function isPalindrome(string$) - string$ = Lower$(removeSpaces$(string$)) - reverseString$ = reverseString$(string$) - If string$ = reverseString$ Then isPalindrome = 1 -End Function - -Function reverseString$(string$) - For i = Len(string$) To 1 Step -1 - reverseString$ = reverseString$ + Mid$(string$, i, 1) - Next i -End Function - -Function removeSpaces$(string$) - For i = 1 To Len(string$) - If Mid$(string$, i, 1) <> " " Then - removeSpaces$ = removeSpaces$ + Mid$(string$, i, 1) - End If - Next i -End Function diff --git a/Task/Palindrome-detection/OCaml/palindrome-detection-1.ocaml b/Task/Palindrome-detection/OCaml/palindrome-detection-1.ocaml index b54b038ce6..82ea616369 100644 --- a/Task/Palindrome-detection/OCaml/palindrome-detection-1.ocaml +++ b/Task/Palindrome-detection/OCaml/palindrome-detection-1.ocaml @@ -1,10 +1,5 @@ -let is_palindrome str = - let last = String.length str - 1 in - try - for i = 0 to last / 2 do - let j = last - i in - if str.[i] <> str.[j] then raise Exit - done; - (true) - with Exit -> - (false) +let is_palindrome s = + let l = String.length s in + let rec comp n = + n = 0 || (s.[l-n] = s.[n-1] && comp (n-1)) in + comp (l / 2) diff --git a/Task/Parallel-calculations/Erlang/parallel-calculations.erl b/Task/Parallel-calculations/Erlang/parallel-calculations.erl new file mode 100644 index 0000000000..63e3bb99e3 --- /dev/null +++ b/Task/Parallel-calculations/Erlang/parallel-calculations.erl @@ -0,0 +1,42 @@ +-module( parallel_calculations ). + +-export( [fun_results/2, task/0] ). + +fun_results( Fun, Datas ) -> + My_pid = erlang:self(), + Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], + [fun_receive(X) || X <- Pids]. + +task() -> + Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], + Results = fun_results( fun factors/1, Numbers ), + Min_results = [lists:min(X) || X <- Results], + {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), + {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), + io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ). + + + +factors(N) -> factors(N,2,[]). + +factors(1,_,Acc) -> Acc; +factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); +factors(N,K,Acc) -> factors(N,K+1,Acc). + +fun_receive( Pid ) -> + receive + {ok, Result, Pid} -> Result; + {Type, Error, Pid} -> erlang:Type( Error ) + end. + +fun_spawn( Fun, Data, My_pid ) -> + erlang:spawn( fun() -> + Result = try + {ok, Fun(Data), erlang:self()} + + catch + Type:Error -> {Type, Error, erlang:self()} + + end, + My_pid ! Result + end ). diff --git a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs index 2f1de1ea22..eaea3b3346 100644 --- a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs +++ b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs @@ -1,8 +1,9 @@ -import Control.Parallel.Strategies +mport Control.Parallel.Strategies import Control.DeepSeq import Data.List import Data.Function +nums :: [Integer] nums = [112272537195293 ,112582718962171 ,112272537095293 @@ -10,21 +11,20 @@ nums = [112272537195293 ,115797840077099 ,1099726829285419] -factors :: Integral a => a -> [a] -factors n | n `rem` 2 == 0 = [2] ++ factors (n `quot` 2) - | otherwise = y - where y = [x | x <- [3,5..ceiling . sqrt $ fromIntegral n] - ++ [n], n `rem` x == 0] +lowestFactor :: Integral a => a -> a -> a +lowestFactor s n | n `rem` 2 == 0 = 2 + | otherwise = head $ y + where y = [x | x <- [s..ceiling . sqrt $ fromIntegral n] + ++ [n], n `rem` x == 0, x `rem` 2 /= 0] -minPrimes :: [Integer] -> (Integer, [Integer]) -minPrimes ns = (\(x, y) -> (x, y:factors ( x `quot` y))) $ - maximumBy (compare `on` snd) - (zip ns (parMap rdeepseq (head . factors) ns)) +primeFactors l n = f n l [] + where f n l xs = if n > 1 then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l:xs) + else xs + +minPrimes ns = (\(x,y) -> (x,primeFactors y x)) $ + maximumBy (compare `on` snd) $ + zip ns (parMap rdeepseq (lowestFactor 3) ns) main :: IO () main = do - putStrLn . concat $ ["The number with the " - , "largest minimum prime factor was:\n" - , show x, "\nWith factors: "] - mapM_ print y - where (x, y) = (minPrimes nums) + print $ minPrimes nums diff --git a/Task/Parametric-polymorphism/Dart/parametric-polymorphism.dart b/Task/Parametric-polymorphism/Dart/parametric-polymorphism.dart new file mode 100644 index 0000000000..94890d3da5 --- /dev/null +++ b/Task/Parametric-polymorphism/Dart/parametric-polymorphism.dart @@ -0,0 +1,42 @@ +class TreeNode { + + T value; + TreeNode left; + TreeNode right; + + TreeNode(this.value); + + TreeNode map(T f(T t)) { + var node = new TreeNode(f(value)); + if(left != null) { + node.left = left.map(f); + } + if(right != null) { + node.right = right.map(f); + } + return node; + } + + void forEach(void f(T t)) { + f(value); + if(left != null) { + left.forEach(f); + } + if(right != null) { + right.forEach(f); + } + } +} + +void main() { + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.right = new TreeNode(4); + + print('first tree'); + root.forEach(print); + var newRoot = root.map((t) => t * 222); + print('second tree'); + newRoot.forEach(print); +} diff --git a/Task/Parametric-polymorphism/Icon/parametric-polymorphism.icon b/Task/Parametric-polymorphism/Icon/parametric-polymorphism.icon new file mode 100644 index 0000000000..cdcdc6acc2 --- /dev/null +++ b/Task/Parametric-polymorphism/Icon/parametric-polymorphism.icon @@ -0,0 +1,10 @@ +procedure main() + bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] + mapTree(bTree, write) + bTree := [1, ["two", ["four", [7]], [5]], [3, ["six", ["eight"], [9]]]] + mapTree(bTree, write) +end + +procedure mapTree(tree, f) + every f(\tree[1]) | mapTree(!tree[2:0], f) +end diff --git a/Task/Parametric-polymorphism/Perl-6/parametric-polymorphism.pl6 b/Task/Parametric-polymorphism/Perl-6/parametric-polymorphism.pl6 index a98b49ccda..54fa04bc2d 100644 --- a/Task/Parametric-polymorphism/Perl-6/parametric-polymorphism.pl6 +++ b/Task/Parametric-polymorphism/Perl-6/parametric-polymorphism.pl6 @@ -1,12 +1,12 @@ role BinaryTree[::T] { - has T $!value; + has T $.value; has BinaryTree[T] $.left; has BinaryTree[T] $.right; method replace-all(T $value) { $!value = $value; - $.left.?replace-all($value); - $.right.?replace-all($value); + $!left.replace-all($value) if $!left.defined; + $!right.replace-all($value) if $!right.defined; } } diff --git a/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx b/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx new file mode 100644 index 0000000000..7b7940f0bf --- /dev/null +++ b/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx @@ -0,0 +1,35 @@ +/*REXX program demonstrates a method of parametric polymorphism in REXX.*/ +call newRoot 1.00, 3 /*new root and indicate 3 stems. */ + /* [↓] no need to label the stems*/ +call addStem 1.10 /*new stem and its initial value.*/ +call addStem 1.11 /* " " " " " " */ +call addStem 1.12 /* " " " " " " */ +call addStem 1.20 /* " " " " " " */ +call addStem 1.21 /* " " " " " " */ +call addStem 1.22 /* " " " " " " */ +call sayNodes /*display nicely formatted values*/ +call modRoot 50 /*MOD will add 50 to all stems. */ +call sayNodes /*display nicely formatted values*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────MODROOT─────────────────────────────*/ +modRoot: do j=1 for nodes /*traipse through all the nodes. */ + do k=1 for stems; _=root.j.k; ?=datatype(_,'N') + if ? then root.j.k=_+arg(1) /*can stem be added to?*/ + end /*k*/ /* [↑] only add if it's numeric.*/ + end /*j*/ +return +/*──────────────────────────────────NEWROOT─────────────────────────────*/ +newRoot: stems=arg(2); nodes=-1; /*set NODES to a kind of "null". */ +call addStem copies('─',9); call addStem arg(1) +return +/*──────────────────────────────────SAYNODES────────────────────────────*/ +sayNodes: say; do j=0 to nodes; _= /*each node gets shown*/ + do k=1 for stems; _=_ right(root.j.k,9); end /*k*/ + say substr(_,2) /*ignore the 1st blank*/ + end /*j*/ + +say left('', stems*9+stems) || '('nodes" nodes)" /*also show # of nodes*/ +return +/*──────────────────────────────────ADDSTEM─────────────────────────────*/ +addStem: nodes=nodes+1; do j=1 for stems; root.nodes.j=arg(1); end /*j*/ +return diff --git a/Task/Parametric-polymorphism/Visual-Prolog/parametric-polymorphism.pro b/Task/Parametric-polymorphism/Visual-Prolog/parametric-polymorphism.pro new file mode 100644 index 0000000000..cbf5429085 --- /dev/null +++ b/Task/Parametric-polymorphism/Visual-Prolog/parametric-polymorphism.pro @@ -0,0 +1,19 @@ +domains + tree{Type} = branch(tree{Type} Left, tree{Type} Right); leaf(Type Value). + +class predicates + treewalk : (tree{X},function{X,Y}) -> tree{Y} procedure (i,i). + +clauses + treewalk(branch(Left,Right),Func) = branch(NewLeft,NewRight) :- + NewLeft = treewalk(Left,Func), NewRight = treewalk(Right,Func). + + treewalk(leaf(Value),Func) = leaf(X) :- + X = Func(Value). + + run():- + init(), + X = branch(leaf(2), branch(leaf(3),leaf(4))), + Y = treewalk(X,addone), + write(Y), + succeed(). diff --git a/Task/Parametrized-SQL-statement/Perl-6/parametrized-sql-statement.pl6 b/Task/Parametrized-SQL-statement/Perl-6/parametrized-sql-statement.pl6 new file mode 100644 index 0000000000..ce9e292fc1 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Perl-6/parametrized-sql-statement.pl6 @@ -0,0 +1,7 @@ +use DBIish; + +my $db = DBIish.connect('DBI:mysql:mydatabase:host','login','password'); + +my $update = $db.prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?"); + +my $rows-affected = $update.execute("Smith, Steve",42,'true',99); diff --git a/Task/Parsing-RPN-calculator-algorithm/Liberty-BASIC/parsing-rpn-calculator-algorithm.liberty b/Task/Parsing-RPN-calculator-algorithm/Liberty-BASIC/parsing-rpn-calculator-algorithm.liberty new file mode 100644 index 0000000000..a3efd4a6a5 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Liberty-BASIC/parsing-rpn-calculator-algorithm.liberty @@ -0,0 +1,85 @@ +global stack$ + +expr$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +" +print "Expression:" +print expr$ +print + +print "Input","Operation","Stack after" + +stack$="" +token$ = "#" +i = 1 +token$ = word$(expr$, i) +token2$ = " "+token$+" " + +do + print "Token ";i;": ";token$, + select case + 'operation + case instr("+-*/^",token$)<>0 + print "operate", + op2$=pop$() + op1$=pop$() + if op1$="" then + print "Error: stack empty for ";i;"-th token: ";token$ + end + end if + + op1=val(op1$) + op2=val(op2$) + + select case token$ + case "+" + res = op1+op2 + case "-" + res = op1-op2 + case "*" + res = op1*op2 + case "/" + res = op1/op2 + case "^" + res = op1^op2 + end select + + call push str$(res) + 'default:number + case else + print "push", + call push token$ + end select + print "Stack: ";reverse$(stack$) + i = i+1 + token$ = word$(expr$, i) + token2$ = " "+token$+" " +loop until token$ ="" + +res$=pop$() +print +print "Result:" ;res$ +extra$=pop$() +if extra$<>"" then + print "Error: extra things on a stack: ";extra$ +end if +end + +'--------------------------------------- +function reverse$(s$) + reverse$ = "" + token$="#" + while token$<>"" + i=i+1 + token$=word$(s$,i,"|") + reverse$ = token$;" ";reverse$ + wend +end function +'--------------------------------------- +sub push s$ + stack$=s$+"|"+stack$ 'stack +end sub + +function pop$() + 'it does return empty on empty stack + pop$=word$(stack$,1,"|") + stack$=mid$(stack$,instr(stack$,"|")+1) +end function diff --git a/Task/Parsing-RPN-to-infix-conversion/Haskell/parsing-rpn-to-infix-conversion.hs b/Task/Parsing-RPN-to-infix-conversion/Haskell/parsing-rpn-to-infix-conversion.hs new file mode 100644 index 0000000000..2dc03fa0dd --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Haskell/parsing-rpn-to-infix-conversion.hs @@ -0,0 +1,39 @@ +data Expression = Const String | Exp Expression String Expression + +precedence :: Expression -> Int +precedence (Const _) = 5 +precedence (Exp _ op _) + | op `elem` ["^"] = 4 + | op `elem` ["*","/"] = 3 + | op `elem` ["+","-"] = 2 + | otherwise = 0 + +leftAssoc :: Expression -> Bool +leftAssoc (Const _) = False +leftAssoc (Exp _ op _) = op `notElem` ["^","*","+"] + +rightAssoc :: Expression -> Bool +rightAssoc (Const _) = False +rightAssoc (Exp _ op _) = op `elem` ["^"] + +instance Show Expression where + show (Const x) = x + show exp@(Exp l op r) = left++" "++op++" "++right + where left = if leftNeedParen then "( "++(show l)++" )" else show l + right = if rightNeedParen the "( "++(show r)++" )" else show r + leftNeedParen = (leftPrec < opPrec) || ((leftPrec == opPrec) && (rightAssoc exp)) + rightNeedParen = (rightPrec < opPrec) || ((rightPrec == opPrec) && (leftAssoc exp)) + leftPrec = precedence l + rightPrec = precedence r + opPrec = precedence exp + +buildExp :: [Expression] -> String -> [Expression] +buildExp stack x + | not.isOp $ x = Const x : stack + | otherwise = Exp l x r : rest + where r:l:rest = stack + isOp = (`elem` ["^","*","/","+","-"]) + +main = do + contents <- getContents + mapM_ (print.head.(foldl buildExp []).words) (lines contents) diff --git a/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs index 9f8f1849c7..7492e9220e 100644 --- a/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs +++ b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs @@ -9,7 +9,8 @@ prec "-" = 2 leftAssoc "^" = False leftAssoc _ = True -isOp t = t `elem` (map (:[]) "-+/*^") +isOp (t:[]) = t `elem` "-+/*^" +isOp _ = False simSYA xs = final ++ [lastStep] where final = scanl f ([],[],"") xs diff --git a/Task/Parsing-Shunting-yard-algorithm/Liberty-BASIC/parsing-shunting-yard-algorithm.liberty b/Task/Parsing-Shunting-yard-algorithm/Liberty-BASIC/parsing-shunting-yard-algorithm.liberty new file mode 100644 index 0000000000..0b74603579 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Liberty-BASIC/parsing-shunting-yard-algorithm.liberty @@ -0,0 +1,115 @@ +global stack$,queue$ +stack$="" +queue$="" + +in$ = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" +print "Input:" +print in$ + +token$ = "#" +print "No", "token", "stack", "queue" + +while 1 + i=i+1 + token$ = word$(in$, i) + if token$ = "" then i=i-1: exit while + print i, token$, reverse$(stack$), queue$ + + select case + case token$ = "(" + call stack.push token$ + + case token$ = ")" + while stack.peek$() <> "(" + 'if stack is empty + if stack$="" then print "Error: no matching '(' for token ";i: end + call queue.push stack.pop$() + wend + discard$=stack.pop$() 'discard "(" + + case isOperator(token$) + op1$=token$ + while(isOperator(stack.peek$())) + op2$=stack.peek$() + select case + case op2$<>"^" and precedence(op1$) = precedence(op2$) + '"^" is the only right-associative operator + call queue.push stack.pop$() + case precedence(op1$) < precedence(op2$) + call queue.push stack.pop$() + case else + exit while + end select + wend + call stack.push op1$ + + case else 'number + 'actually, wrong operator could end up here, like say % + 'If the token is a number, then add it to the output queue. + call queue.push token$ + end select + +wend + +while stack$<>"" + if stack.peek$() = "(" then print "no matching ')'": end + call queue.push stack.pop$() +wend + +print "Output:" +while queue$<>"" + print queue.pop$();" "; +wend +print + +end + +'------------------------------------------ +function isOperator(op$) + isOperator = instr("+-*/^", op$)<>0 AND len(op$)=1 +end function + +function precedence(op$) + if isOperator(op$) then + precedence = 1 _ + + (instr("+-*/^", op$)<>0) _ + + (instr("*/^", op$)<>0) _ + + (instr("^", op$)<>0) + end if +end function + +'------------------------------------------ +sub stack.push s$ + stack$=s$+"|"+stack$ +end sub + +sub queue.push s$ + queue$=queue$+s$+"|" +end sub + +function queue.pop$() + 'it does return empty on empty stack or queue + queue.pop$=word$(queue$,1,"|") + queue$=mid$(queue$,instr(queue$,"|")+1) +end function + +function stack.pop$() + 'it does return empty on empty stack or queue + stack.pop$=word$(stack$,1,"|") + stack$=mid$(stack$,instr(stack$,"|")+1) +end function + +function stack.peek$() + 'it does return empty on empty stack or queue + stack.peek$=word$(stack$,1,"|") +end function + +function reverse$(s$) + reverse$ = "" + token$="#" + while token$<>"" + i=i+1 + token$=word$(s$,i,"|") + reverse$ = token$;" ";reverse$ + wend +end function diff --git a/Task/Partial-function-application/REXX/partial-function-application.rexx b/Task/Partial-function-application/REXX/partial-function-application.rexx new file mode 100644 index 0000000000..3c8f4957cb --- /dev/null +++ b/Task/Partial-function-application/REXX/partial-function-application.rexx @@ -0,0 +1,24 @@ +/*REXX program demonstrates a method of partial function application. */ +s=; do a=0 to 3 /*build 1st series, low integers.*/ + s=strip(s a) /*append to the integer to S list*/ + end /*a*/ + +call fs 'f1',s; say 'for f1: series=' s", result=" result +call fs 'f2',s; say 'for f2: series=' s", result=" result + +s=; do b=2 to 8 by 2 /*build 2nd series, low even ints*/ + s=strip(s b) /*append to the integer to S list*/ + end /*b*/ + +call fs 'f1',s; say 'for f1: series=' s", result=" result +call fs 'f2',s; say 'for f2: series=' s", result=" result +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────F1 subroutine───────────────────────*/ +f1: return arg(1)*2 +/*──────────────────────────────────F2 subroutine───────────────────────*/ +f2: return arg(1)**2 +/*──────────────────────────────────FS subroutine───────────────────────*/ +fs: procedure; arg f,s; $=; do j=1 for words(s); z=word(s,j) + interpret '$=$' f"("z')' + end /*j*/ +return strip($) diff --git a/Task/Pascals-triangle-Puzzle/Perl-6/pascals-triangle-puzzle.pl6 b/Task/Pascals-triangle-Puzzle/Perl-6/pascals-triangle-puzzle.pl6 new file mode 100644 index 0000000000..23d3265e1a --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Perl-6/pascals-triangle-puzzle.pl6 @@ -0,0 +1,43 @@ +# set up triangle +my $rows = 5; +my @tri = (1..$rows).map: { [ { x => 0, z => 0, v => 0, rhs => Nil } xx $_ ] } +@tri[0][0] = 151; +@tri[2][0] = 40; +@tri[4][0] = 1; +@tri[4][1] = 11; +@tri[4][2] = 1; +@tri[4][2] = 1; +@tri[4][3] = 4; +@tri[4][4] = 1; + +# aggregate from bottom to top +for @tri - 2 ... 0 -> $row { + for 0 ..^ @tri[$row] -> $col { + @tri[$row][$col]{$_} = @tri[$row+1][$col]{$_} + @tri[$row+1][$col+1]{$_} for 'x','z','v'; + } +} + +# find equations +my @eqn = gather for @tri -> $row { + for @$row -> $cell { + take [ $cell, $cell, $cell - $cell ] if defined $cell; + } +} + +# print equations +say "Equations:"; +say " x + z = y"; +for @eqn -> [$x,$z,$y] { say "$x x + $z z = $y" } + +# solve +my $f = @eqn[0][1] / @eqn[1][1]; +@eqn[0][$_] -= $f * @eqn[1][$_] for 0..2; +$f = @eqn[1][0] / @eqn[0][0]; +@eqn[1][$_] -= $f * @eqn[0][$_] for 0..2; + +# print solution +say "Solution:"; +my $x = @eqn[0][2] / @eqn[0][0]; +my $z = @eqn[1][2] / @eqn[1][1]; +my $y = $x + $z; +say "x=$x, y=$y, z=$z"; diff --git a/Task/Pascals-triangle-Puzzle/Perl/pascals-triangle-puzzle.pl b/Task/Pascals-triangle-Puzzle/Perl/pascals-triangle-puzzle.pl new file mode 100644 index 0000000000..5c2db11eb6 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Perl/pascals-triangle-puzzle.pl @@ -0,0 +1,40 @@ +# set up triangle +my $rows = 5; +my @tri = map { [ map { {x=>0,z=>0,v=>0,rhs=>undef} } 1..$_ ] } 1..$rows; +$tri[0][0]{rhs} = 151; +$tri[2][0]{rhs} = 40; +$tri[4][0]{x} = 1; +$tri[4][1]{v} = 11; +$tri[4][2]{x} = 1; +$tri[4][2]{z} = 1; +$tri[4][3]{v} = 4; +$tri[4][4]{z} = 1; + +# aggregate from bottom to top +for my $row ( reverse 0..@tri-2 ) { + for my $col ( 0..@{$tri[$row]}-1 ){ + $tri[$row][$col]{$_} = $tri[$row+1][$col]{$_}+$tri[$row+1][$col+1]{$_} for 'x','z','v'; + } +} +# find equations +my @eqn; +for my $row ( @tri ) { + for my $col ( @$row ){ + push @eqn, [ $$col{x}, $$col{z}, $$col{rhs}-$$col{v} ] if defined $$col{rhs}; + } +} +# print equations +print "Equations:\n"; +print " x + z = y\n"; +printf "%d x + %d z = %d\n", @$_ for @eqn; +# solve +my $f = $eqn[0][1] / $eqn[1][1]; +$eqn[0][$_] -= $f * $eqn[1][$_] for 0..2; +$f = $eqn[1][0] / $eqn[0][0]; +$eqn[1][$_] -= $f * $eqn[0][$_] for 0..2; +# print solution +print "Solution:\n"; +my $x = $eqn[0][2]/$eqn[0][0]; +my $z = $eqn[1][2]/$eqn[1][1]; +my $y = $x+$z; +printf "x=%d, y=%d, z=%d\n", $x, $y, $z; diff --git a/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l b/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l index 59edc8419d..b3f657a8d9 100644 --- a/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l +++ b/Task/Pascals-triangle-Puzzle/PicoLisp/pascals-triangle-puzzle.l @@ -1,25 +1,25 @@ (be number (@N @Max) - (@C box 0) + (^ @C (box 0)) (repeat) (or - ((@ >= (val (-> @C)) (-> @Max)) T (fail)) - ((@N inc (-> @C))) ) ) + ((^ @ (>= (val (-> @C)) (-> @Max))) T (fail)) + ((^ @N (inc (-> @C)))) ) ) (be + (@A @B @Sum) - (@ -> @A) - (@ -> @B) - (@Sum + (-> @A) (-> @B)) ) + (^ @ (-> @A)) + (^ @ (-> @B)) + (^ @Sum (+ (-> @A) (-> @B))) ) (be + (@A @B @Sum) - (@ -> @A) - (@ -> @Sum) - (@B - (-> @Sum) (-> @A)) + (^ @ (-> @A)) + (^ @ (-> @Sum)) + (^ @B (- (-> @Sum) (-> @A))) T - (@ ge0 (-> @B)) ) + (^ @ (ge0 (-> @B))) ) (be + (@A @B @Sum) (number @A @Sum) - (@B - (-> @Sum) (-> @A)) ) + (^ @B (- (-> @Sum) (-> @A))) ) #{ 151 diff --git a/Task/Pascals-triangle/Eiffel/pascals-triangle.e b/Task/Pascals-triangle/Eiffel/pascals-triangle.e new file mode 100644 index 0000000000..ded8428035 --- /dev/null +++ b/Task/Pascals-triangle/Eiffel/pascals-triangle.e @@ -0,0 +1,101 @@ +note + description : "Prints pascal's triangle" + output : "[ + Per requirements of the RosettaCode example, execution will print the first n rows of pascal's triangle + ]" + date : "19 December 2013" + authors : "Sandro Meier", "Roman Brunner" + revision : "1.0" + libraries : "Relies on HASH_TABLE from EIFFEL_BASE library" + implementation : "[ + Recursive implementation to calculate the n'th row. + ]" + warning : "[ + Will not work for large n's (INTEGER_32) + ]" + +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} -- Initialization + + make + local + n:INTEGER + do + create {HASH_TABLE[ARRAY[INTEGER],INTEGER]}pascal_lines.make (n) --create the hash_table object + io.new_line + n:=25 + draw(n) + end +feature + line(n:INTEGER):ARRAY[INTEGER] + --Calculates the n'th line + local + upper_line:ARRAY[INTEGER] + i:INTEGER + do + if n=1 then --trivial case first line + create Result.make_filled (0, 1, n+2) + Result.put (0, 1) + Result.put (1, 2) + Result.put (0, 3) + elseif pascal_lines.has (n) then --checks if the result was already calculated + Result := pascal_lines.at (n) + else --calculates the n'th line recursively + create Result.make_filled(0,1,n+2) --for caluclation purposes add a 0 at the beginning of each line + Result.put (0, 1) + upper_line:=line(n-1) + from + i:=1 + until + i>upper_line.count-1 + loop + Result.put(upper_line[i]+upper_line[i+1],i+1) + i:=i+1 + end + Result.put (0, n+2) --for caluclation purposes add a 0 at the end of each line + pascal_lines.put (Result, n) + end + end + + draw(n:INTEGER) + --draw n lines of pascal's triangle + local + space_string:STRING + width, i:INTEGER + + do + space_string:=" " --question of design: add space_string at the beginning of each line + width:=line(n).count + space_string.multiply (width) + from + i:=1 + until + i>n + loop + space_string.remove_tail (1) + io.put_string (space_string) + across line(i) as c + loop + if + c.item/=0 + then + io.put_string (c.item.out+" ") + end + end + io.new_line + i:=i+1 + end + end + +feature --Access + pascal_lines:HASH_TABLE[ARRAY[INTEGER],INTEGER] + --Contains all already calculated lines +end diff --git a/Task/Pattern-matching/Perl/pattern-matching.pl b/Task/Pattern-matching/Perl/pattern-matching.pl new file mode 100644 index 0000000000..fe37f0ee24 --- /dev/null +++ b/Task/Pattern-matching/Perl/pattern-matching.pl @@ -0,0 +1,65 @@ +#!perl +use 5.010; +use strict; +use warnings qw(FATAL all); + +my $balanced = qr{([^<>,]++|<(?-1),(?-1),(?-1),(?-1)>)}; +my ($a, $b, $c, $d, $x, $y, $z) = map +qr((?<$_>$balanced)), + 'a'..'d', 'x'..'z'; +my $col = qr{(?[RB])}; + +sub balance { + local $_ = shift; + if( /^,$y,$c>,$z,$d>\z/ or + /^>,$z,$d>\z/ or + /^,$z,$d>>\z/ or + /^>>\z/ ) + { + my ($aa, $bb, $cc, $dd) = @+{'a'..'d'}; + my ($xx, $yy, $zz) = @+{'x'..'z'}; + ",$yy,>"; + } else { + $_; + } +} + +sub ins { + my ($xx, $tree) = @_; + if($tree =~ m{^<$col,$a,$y,$b>\z} ) { + my ($color, $aa, $bb, $yy) = @+{qw(col a b y)}; + if( $xx < $yy ) { + return balance "<$color,".ins($xx,$aa).",$yy,$bb>"; + } elsif( $xx > $yy ) { + return balance "<$color,$aa,$yy,".ins($xx,$bb).">"; + } else { + return $tree; + } + } elsif( $tree !~ /,/) { + return ""; + } else { + print "Unexpected failure!\n"; + print "Tree parts are: \n"; + print $_, "\n" for $tree =~ /$balanced/g; + exit; + } +} + +sub insert { + my $tree = ins(@_); + $tree =~ m{^<$col,$a,$y,$b>\z} or die; + ""; +} + +MAIN: { + my @a = 1..10; + for my $aa ( 1 .. $#a ) { + my $bb = int rand( 1 + $aa ); + @a[$aa, $bb] = @a[$bb, $aa]; + } + my $t = "!"; + for( @a ) { + $t = insert( $_, $t ); + print "Tree: $t.\n"; + } +} +print "Done\n"; diff --git a/Task/Pattern-matching/PicoLisp/pattern-matching-1.l b/Task/Pattern-matching/PicoLisp/pattern-matching-1.l index 2006330b6f..16725bd711 100644 --- a/Task/Pattern-matching/PicoLisp/pattern-matching-1.l +++ b/Task/Pattern-matching/PicoLisp/pattern-matching-1.l @@ -20,12 +20,12 @@ (be ins (@X E (T R E @X E))) (be ins (@X (T @C @A @Y @B) @R) - (@ < (-> @X) (-> @Y)) + (^ @ (> (-> @Y) (-> @X))) (ins @X @A @Ao) (balance @C @Ao @Y @B @R) T ) (be ins (@X (T @C @A @Y @B) @R) - (@ > (-> @X) (-> @Y)) + (^ @ (> (-> @X) (-> @Y))) (ins @X @B @Bo) (balance @C @A @Y @Bo @R) T ) diff --git a/Task/Perfect-numbers/D/perfect-numbers-2.d b/Task/Perfect-numbers/D/perfect-numbers-2.d index 17199420c2..91ac976953 100644 --- a/Task/Perfect-numbers/D/perfect-numbers-2.d +++ b/Task/Perfect-numbers/D/perfect-numbers-2.d @@ -1,9 +1,12 @@ import std.stdio, std.algorithm, std.range; -bool isPerfect(in int n) /*pure nothrow*/ { - return n == iota(1, n - 1).reduce!((s, i) => n % i ? s : s + i); +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)); } void main() { - iota(3, 10_000).filter!isPerfect.writeln; + iota(1, 10_000).filter!isPerfect.writeln; } diff --git a/Task/Perfect-numbers/Nimrod/perfect-numbers.nimrod b/Task/Perfect-numbers/Nimrod/perfect-numbers.nimrod new file mode 100644 index 0000000000..bed6c11f8a --- /dev/null +++ b/Task/Perfect-numbers/Nimrod/perfect-numbers.nimrod @@ -0,0 +1,14 @@ +import math + +proc isperfect(n: int): bool = + let max: int = (sqrt(n.toFloat)).toInt + var sum: int = 1 + for i in 2..max: + if n mod i == 0: + let q: int = n div i + sum += (i + q) + return (n == sum) + +for i in 2..10_000: + if isperfect(i): + echo(i) diff --git a/Task/Permutation-test/Perl/permutation-test.pl b/Task/Permutation-test/Perl/permutation-test.pl new file mode 100644 index 0000000000..c9ee288b4e --- /dev/null +++ b/Task/Permutation-test/Perl/permutation-test.pl @@ -0,0 +1,84 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use List::Util qw{ sum }; + + +sub means { + my @groups = @_; + return map sum(@$_) / @$_, @groups; +} + + +sub following { + my $pattern = shift; + my $orig_count = grep $_, @$pattern; + my $count; + do { + my $i = $#{$pattern}; + until (0 > $i) { + $pattern->[$i] = $pattern->[$i] ? 0 : 1; + last if $pattern->[$i]; + --$i; + } + $count = grep $_, @$pattern; + } until $count == $orig_count or not $count; + undef @$pattern unless $count; +} + + +my @groups; +my $i = 0; +while () { + chomp; + $i++, next if /^$/; + push @{ $groups[$i] }, $_; +} + +my @orig_means = means(@groups); +my $orig_cmp = $orig_means[0] - $orig_means[1]; + +my $pattern = [ (0) x @{ $groups[0] }, + (1) x @{ $groups[1] } + ]; + +my @cmp = (0) x 3; +while (@$pattern) { + my @perms = map { my $g = $_; + [ (@{ $groups[0] }, @{ $groups[1] } ) [ grep $pattern->[$_] == $g, 0 .. $#{$pattern} ] ]; + } 0, 1; + my @means = means(@perms); + $cmp[ ($means[0] - $means[1]) <=> $orig_cmp ]++; +} continue { + following($pattern); +} +my $all = sum(@cmp); +my $length = length $all; +for (0, -1, 1) { + printf "%-7s %${length}d %6.3f%%\n", + (qw(equal greater less))[$_], $cmp[$_], 100 * $cmp[$_] / $all; +} + + +__DATA__ +85 +88 +75 +66 +25 +29 +83 +39 +97 + +68 +41 +10 +49 +16 +65 +32 +92 +28 +98 diff --git a/Task/Permutations-Derangements/D/permutations-derangements-1.d b/Task/Permutations-Derangements/D/permutations-derangements-1.d index 57ca50a784..7dd0481a71 100644 --- a/Task/Permutations-Derangements/D/permutations-derangements-1.d +++ b/Task/Permutations-Derangements/D/permutations-derangements-1.d @@ -1,26 +1,38 @@ -import std.stdio, std.algorithm, std.typecons, std.array, - std.conv, std.range, std.traits; +import std.stdio, std.algorithm, std.typecons, std.conv, std.range; + +T factorial(T)(in T n) pure nothrow { + Unqual!T result = 1; + foreach (immutable i; 2 .. n + 1) + result *= i; + return result; +} + +T subfact(T)(in T n) pure nothrow { + if (0 <= n && n <= 2) + return n != 1; + return (n - 1) * (subfact(n - 1) + subfact(n - 2)); +} auto derangements(in size_t n, in bool countOnly=false) -/*pure nothrow*/ { - size_t[] seq = iota(n).array(); - auto ori = seq.idup; +pure /*nothrow*/ { + size_t[] seq = n.iota.array; + auto ori = seq.idup; // Not nothrow. size_t[][] all; size_t cnt = n == 0; - foreach (tot; 0 .. fact(n)-1) { + foreach (immutable tot; 0 .. n.factorial - 1) { size_t j = n - 2; while (seq[j] > seq[j + 1]) j--; size_t k = n - 1; while (seq[j] > seq[k]) k--; - swap(seq[k], seq[j]); + seq[k].swap(seq[j]); size_t r = n - 1; size_t s = j + 1; while (r > s) { - swap(seq[s], seq[r]); + seq[s].swap(seq[r]); r--; s++; } @@ -32,34 +44,21 @@ auto derangements(in size_t n, in bool countOnly=false) if (countOnly) cnt++; else - all ~= seq.dup; + all ~= seq.dup; // Not nothrow. } } return tuple(all, cnt); } -T fact(T)(in T n) pure nothrow { - Unqual!T result = 1; - for (Unqual!T i = 2; i <= n; i++) - result *= i; - return result; -} - -T subfact(T)(in T n) pure nothrow { - if (0 <= n && n <= 2) - return n != 1; - return (n - 1) * (subfact(n - 1) + subfact(n - 2)); -} - void main() { - writeln("derangements for n = 4\n"); - foreach (d; derangements(4)[0]) - writeln(d); + "Derangements for n = 4:".writeln; + foreach (const d; 4.derangements[0]) + d.writeln; - writeln("\ntable of n vs counted vs calculated derangements\n"); - foreach (i; 0 .. 10) - writefln("%s %-7s%-7s", i, derangements(i, 1)[1], subfact(i)); + "\nTable of n vs counted vs calculated derangements:".writeln; + foreach (immutable i; 0 .. 10) + writefln("%s %-7s%-7s", i, derangements(i, 1)[1], i.subfact); - writefln("\n!20 = %s", subfact(20L)); + writefln("\n!20 = %s", 20L.subfact); } diff --git a/Task/Permutations-Derangements/D/permutations-derangements-2.d b/Task/Permutations-Derangements/D/permutations-derangements-2.d index 0709f036d7..165868b0f3 100644 --- a/Task/Permutations-Derangements/D/permutations-derangements-2.d +++ b/Task/Permutations-Derangements/D/permutations-derangements-2.d @@ -1,29 +1,8 @@ -import std.stdio, std.algorithm, std.typecons, std.array, - std.conv, std.range, std.traits; +import std.stdio, std.algorithm, std.typecons, std.conv, std.range; -auto derangementsR(in size_t n, in bool countOnly=false) { - auto seq = iota(n).array(); - immutable ori = seq.idup; - const(size_t[])[] res; - size_t cnt; - - void perms(in size_t[] s, in size_t[] pre=null) nothrow { - if (s.length) { - foreach (i, c; s) - perms(s[0 .. i] ~ s[i + 1 .. $], pre ~ c); - } else if (mismatch!q{a != b}(pre, ori)[0].length == 0) { - if (countOnly) cnt++; - else res ~= pre; - } - } - - perms(seq); - return tuple(res, cnt); -} - -T fact(T)(in T n) pure nothrow { +T factorial(T)(in T n) pure nothrow { Unqual!T result = 1; - for (Unqual!T i = 2; i <= n; i++) + foreach (immutable i; 2 .. n + 1) result *= i; return result; } @@ -34,14 +13,35 @@ T subfact(T)(in T n) pure nothrow { return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } -void main() { - writeln("derangements for n = 4\n"); - foreach (const d; derangementsR(4)[0]) - writeln(d); +auto derangementsR(in size_t n, in bool countOnly=false) +pure /*nothrow*/ { + auto seq = n.iota.array; + immutable ori = seq.idup; // Not nothrow. + const(size_t[])[] res; + size_t cnt; - writeln("\ntable of n vs counted vs calculated derangements\n"); - foreach (i; 0 .. 10) - writefln("%s %-7s%-7s", i, derangementsR(i,1)[1], subfact(i)); + void perms(in size_t[] s, in size_t[] pre=null) /*nothrow*/ { + if (s.length) { + foreach (immutable i, immutable c; s) + perms(s[0 .. i] ~ s[i + 1 .. $], pre ~ c); + } else if (zip(pre, ori).all!(po => po[0] != po[1])) { + if (countOnly) cnt++; + else res ~= pre; + } + } - writefln("\n!20 = %s", subfact(20L)); + perms(seq); + return tuple(res, cnt); +} + +void main() { + "Derangements for n = 4:".writeln; + foreach (const d; 4.derangementsR[0]) + d.writeln; + + "\nTable of n vs counted vs calculated derangements:".writeln; + foreach (immutable i; 0 .. 10) + writefln("%s %-7s%-7s", i, derangementsR(i, 1)[1], i.subfact); + + writefln("\n!20 = %s", 20L.subfact); } diff --git a/Task/Permutations-by-swapping/Go/permutations-by-swapping-1.go b/Task/Permutations-by-swapping/Go/permutations-by-swapping-1.go new file mode 100644 index 0000000000..5c709e2915 --- /dev/null +++ b/Task/Permutations-by-swapping/Go/permutations-by-swapping-1.go @@ -0,0 +1,50 @@ +package permute + +// Iter takes a slice p and returns an iterator function. The iterator +// permutes p in place and returns the sign. After all permutations have +// been generated, the iterator returns 0 and p is left in its initial order. +func Iter(p []int) func() int { + f := pf(len(p)) + return func() int { + return f(p) + } +} + +// Recursive function used by perm, returns a chain of closures that +// implement a loopless recursive SJT. +func pf(n int) func([]int) int { + sign := 1 + switch n { + case 0, 1: + return func([]int) (s int) { + s = sign + sign = 0 + return + } + default: + p0 := pf(n - 1) + i := n + var d int + return func(p []int) int { + switch { + case sign == 0: + case i == n: + i-- + sign = p0(p[:i]) + d = -1 + case i == 0: + i++ + sign *= p0(p[1:]) + d = 1 + if sign == 0 { + p[0], p[1] = p[1], p[0] + } + default: + p[i], p[i-1] = p[i-1], p[i] + sign = -sign + i += d + } + return sign + } + } +} diff --git a/Task/Permutations-by-swapping/Go/permutations-by-swapping-2.go b/Task/Permutations-by-swapping/Go/permutations-by-swapping-2.go new file mode 100644 index 0000000000..6ee6b6db3a --- /dev/null +++ b/Task/Permutations-by-swapping/Go/permutations-by-swapping-2.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "permute" +) + +func main() { + p := []int{11, 22, 33} + i := permute.Iter(p) + for sign := i(); sign != 0; sign = i() { + fmt.Println(p, sign) + } +} diff --git a/Task/Permutations-by-swapping/Perl/permutations-by-swapping-1.pl b/Task/Permutations-by-swapping/Perl/permutations-by-swapping-1.pl new file mode 100644 index 0000000000..1a8c9cc6bb --- /dev/null +++ b/Task/Permutations-by-swapping/Perl/permutations-by-swapping-1.pl @@ -0,0 +1,59 @@ +#!perl +use strict; +use warnings; + +# This code uses "Even's Speedup," as described on +# the Wikipedia page about the Steinhaus–Johnson– +# Trotter algorithm. + +# Any resemblance between this code and the Python +# code elsewhere on the page is purely a coincidence, +# caused by them both implementing the same algorithm. + +# The code was written to be read relatively easily +# while demonstrating some common perl idioms. + +sub perms(&@) { + my $callback = shift; + my @perm = map [$_, -1], @_; + $perm[0][1] = 0; + + my $sign = 1; + while( ) { + $callback->($sign, map $_->[0], @perm); + $sign *= -1; + + my ($chosen, $index) = (-1, -1); + for my $i ( 0 .. $#perm ) { + ($chosen, $index) = ($perm[$i][0], $i) + if $perm[$i][1] and $perm[$i][0] > $chosen; + } + return if $index == -1; + + my $direction = $perm[$index][1]; + my $next = $index + $direction; + + @perm[ $index, $next ] = @perm[ $next, $index ]; + + if( $next <= 0 or $next >= $#perm ) { + $perm[$next][1] = 0; + } elsif( $perm[$next + $direction][0] > $chosen ) { + $perm[$next][1] = 0; + } + + for my $i ( 0 .. $next - 1 ) { + $perm[$i][1] = +1 if $perm[$i][0] > $chosen; + } + for my $i ( $next + 1 .. $#perm ) { + $perm[$i][1] = -1 if $perm[$i][0] > $chosen; + } + } +} + +my $n = shift(@ARGV) || 4; + +perms { + my ($sign, @perm) = @_; + print "[", join(", ", @perm), "]"; + print $sign < 0 ? " => -1\n" : " => +1\n"; +} 1 .. $n; diff --git a/Task/Permutations-by-swapping/Perl/permutations-by-swapping-2.pl b/Task/Permutations-by-swapping/Perl/permutations-by-swapping-2.pl new file mode 100644 index 0000000000..2ad66e8d3a --- /dev/null +++ b/Task/Permutations-by-swapping/Perl/permutations-by-swapping-2.pl @@ -0,0 +1,25 @@ +#!perl +use strict; +use warnings; + +sub perms { + my ($xx) = (shift); + my @perms = ([+1]); + for my $x ( 1 .. $xx ) { + my $sign = -1; + @perms = map { + my ($s, @p) = @$_; + map [$sign *= -1, @p[0..$_-1], $x, @p[$_..$#p]], + $s < 0 ? 0 .. @p : reverse 0 .. @p; + } @perms; + } + @perms; +} + +my $n = shift() || 4; + +for( perms($n) ) { + my $s = shift @$_; + $s = '+1' if $s > 0; + print "[", join(", ", @$_), "] => $s\n"; +} diff --git a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx new file mode 100644 index 0000000000..6e9dc53c17 --- /dev/null +++ b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx @@ -0,0 +1,60 @@ +/*REXX pgm generates all permutations of N different objects by swapping*/ +parse arg things bunch inbetween names /*get optional C.L. args*/ +if things=='' | things==',' then things=4 /*use the default? */ +if bunch =='' | bunch ==',' then bunch =things /* " " " */ + /* ┌────────────────────────────────────────────────────────────────┐ + │ things (optional) defaults to 4. │ + │ bunch (optional) defaults to THINGS. │ + │ inbetween (optional) defaults to a [null]. │ + │ names (optional) defaults to digits (and letters). │ + └────────────────────────────────────────────────────────────────┘ */ +upper inbetween; if inbetween=='NONE' | inbetween="NULL" then inbetween= +call permSets things, bunch, inbetween, names +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────! {factorial} subroutine────────────*/ +!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end; return ! +/*──────────────────────────────────GETONE subroutine───────────────────*/ +getOne: if length(z)==y then return substr(z,arg(1),1) + else return sep||word(translate(z,,','),arg(1) ) +/*──────────────────────────────────P subroutine (Pick one)─────────────*/ +p: return word(arg(1),1) +/*──────────────────────────────────PERMSETS subroutine─────────────────*/ +permSets: procedure; parse arg x,y,between,uSyms /*X things Y at a time.*/ +sep=; !.=0 /*X can't be > length(@0abcs). */ +@abc = 'abcdefghijklmnopqrstuvwxyz'; parse upper var @abc @abcU +@abcS= @abcU || @abc; @0abcS=123456789 || @abcS +z= + do i=1 for x /*build a list of (perm) symbols.*/ + _=p(word(uSyms,i) p(substr(@0abcS,i,1) k)) /*get or gen a symbol.*/ + if length(_)\==1 then sep=',' /*if not 1st char, then use sep. */ + z=z || sep || _ /*append it to the symbol list. */ + end /*i*/ + +if sep\=='' then z=strip(z,'L', ",") +!.z=1; #=1; times=!(x)%!(x-y); q=z; s=1; w=max(length(z),length('permute')) +say center('permutations for ' x ' with ' y "at a time",60,'═') +say +say 'permutation' center("permute",w,'─') 'sign' +say '───────────' center("───────",w,'─') '────' +say center(#,11) center(z ,w) right(s,4) + + do step=1 until #==times + do k=1 for x-1 + do m=k+1 to x /*method doesn't use adjaceny. */ + ?= + do n=1 for x /*build a new permutation by swap*/ + if n\==k & n\==m then ?=? || getOne(n) + else if n==k then ?=? || getOne(m) + else ?=? || getOne(k) + end /*n*/ + if sep\=='' then ?=strip(?,'L',sep) + z=? /*save this permute for next swap*/ + if !.? then iterate m /*if defined before, try next one*/ + #=#+1; s=-s; say center(#,11) center(?,w) right(s,4) + !.?=1 + iterate step + end /*m*/ + end /*k*/ + end /*step*/ + +return diff --git a/Task/Permutations/D/permutations-2.d b/Task/Permutations/D/permutations-2.d index 36916354f8..0735f6e9c0 100644 --- a/Task/Permutations/D/permutations-2.d +++ b/Task/Permutations/D/permutations-2.d @@ -6,7 +6,7 @@ struct Permutations(bool doCopy=true, T) if (isMutable!T) { private uint[31] indexes; private ulong tot; - this (/*in*/ T[] items) /*pure nothrow*/ + this (in T[] items) pure /*nothrow*/ in { static enum string L = text(indexes.length); // impure assert(items.length >= 0 && items.length <= indexes.length, @@ -66,21 +66,18 @@ struct Permutations(bool doCopy=true, T) if (isMutable!T) { } Permutations!(doCopy,T) permutations(bool doCopy=true, T) - (/*in*/ T[] items) -/*pure nothrow*/ if (isMutable!T) { + (in T[] items) +pure /*nothrow*/ if (isMutable!T) { return Permutations!(doCopy, T)(items); -} unittest { - import std.bigint; - foreach (p; permutations([BigInt(1), BigInt(2), BigInt(3)])) - assert((p[0] + 1) > 0); } version (permutations2_main) { void main() { import std.stdio, std.bigint; - foreach (p; permutations!false([1, 2, 3])) - writeln(p); - alias BigInt B; - foreach (p; permutations!false([B(1), B(2), B(3)])) {} + alias B = BigInt; + foreach (p; [B(1), B(2), B(3)].permutations) + assert((p[0] + 1) > 0); + [1, 2, 3].permutations!false.writeln; + [B(1), B(2), B(3)].permutations!false.writeln; } } diff --git a/Task/Permutations/Liberty-BASIC/permutations-1.liberty b/Task/Permutations/Liberty-BASIC/permutations-1.liberty new file mode 100644 index 0000000000..aa293595ea --- /dev/null +++ b/Task/Permutations/Liberty-BASIC/permutations-1.liberty @@ -0,0 +1,28 @@ +n=3 +dim a(n+1) '+1 needed due to bug in LB that checks loop condition + ' until (i=0) or (a(i)0 then + j=i+1 + while a(j)\pi Note: this task is about calculating pi. For information on built-in pi constants see [[Real constants and functions]]. + +Related Task [[Arithmetic-geometric mean/Calculate Pi]] diff --git a/Task/Pi/Julia/pi.julia b/Task/Pi/Julia/pi.julia new file mode 100644 index 0000000000..d1a5ce69bc --- /dev/null +++ b/Task/Pi/Julia/pi.julia @@ -0,0 +1,12 @@ +prec = get_bigfloat_precision() +spi = "" +digit = 1 +while true + if digit > length(spi) - 6 + prec *= 2 + set_bigfloat_precision(prec) + spi = string(big(π)) + end + print(spi[digit]) + digit += 1 +end diff --git a/Task/Pi/Lua/pi.lua b/Task/Pi/Lua/pi.lua new file mode 100644 index 0000000000..cebfc89690 --- /dev/null +++ b/Task/Pi/Lua/pi.lua @@ -0,0 +1,41 @@ +a = {} +n = 1000 +len = math.modf( 10 * n / 3 ) + +for j = 1, len do + a[j] = 2 +end +nines = 0 +predigit = 0 +for j = 1, n do + q = 0 + for i = len, 1, -1 do + x = 10 * a[i] + q * i + a[i] = math.fmod( x, 2 * i - 1 ) + q = math.modf( x / ( 2 * i - 1 ) ) + end + a[1] = math.fmod( q, 10 ) + q = math.modf( q / 10 ) + if q == 9 then + nines = nines + 1 + else + if q == 10 then + io.write( predigit + 1 ) + for k = 1, nines do + io.write(0) + end + predigit = 0 + nines = 0 + else + io.write( predigit ) + predigit = q + if nines ~= 0 then + for k = 1, nines do + io.write( 9 ) + end + nines = 0 + end + end + end +end +print( predigit ) diff --git a/Task/Pi/REXX/pi.rexx b/Task/Pi/REXX/pi.rexx index 80eac76e54..70b206f1c6 100644 --- a/Task/Pi/REXX/pi.rexx +++ b/Task/Pi/REXX/pi.rexx @@ -1,24 +1,22 @@ -/*REXX program to spit out pi digits (few at a time) until Ctrl-Break. */ - -arg digs .; if digs=='' then digs=1e6 /*allow the specification of digs*/ -fn='PI_DIGITS.OUT' /*file that can be written to. */ +/*REXX program spits out digits of pi (one at a time) until Ctrl-Break.*/ +arg digs .; if digs=='' then digs=1e6 /*allow the specification of digs*/ +fn = 'PI_DIGITS.OUT' /*file used for output: PI digits*/ numeric digits digs /*big digs, the slower the spits.*/ -pi=0; s=16; r=4; v=5; vs=v*v; g=239; gs=g*g; old=; spewed=0; j=1 -call time 'E' - -/*─────────────────────────────────────John Machin's formula for pi. */ - do n=1 by 2 - pi=pi + s/(n*v) - r/(n*g) - if pi==old then leave /*no further with current DIGITS.*/ - s=-s; r=-r; v=v*vs; g=g*gs - if n\==1 then do j=spewed+1 to compare(pi,old) - spit=substr(pi,j,1) - call charout ,spit /*spit out 1 digit of pi.*/ - call charout fn,spit /* ...and also to a file.*/ - end - spewed=j-1 - old=pi +pi=0; s=16; r=4; v=5; vs=v*v; g=239; gg=g*g; j=1; spit=0; old= +call time 'Reset' /*reset the REXX wall-clock timer*/ + /*───calculate PI with increasing*/ + do n=1 by 2 /*───accuracy (up to DIGS digits)*/ + pi=pi + s/(n*v) - r/(n*g) /*───using John Machin's formula.*/ + if pi==old then leave /*have exceeded DIGITS accuracy. */ + s=-s; r=-r; v=v*vs; g=g*gg /*set some variable for shortcuts*/ + if n\==1 then do j=spit+1 to compare(pi,old) /*spit out some π digs.*/ + spit=substr(pi,j,1) /*obtain a digit of π to spit out*/ + call charout ,spit /*spit out one (new) digit of pi.*/ + call charout fn,spit /* ···and also echo it to a file.*/ + end /*j*/ + spit=j-1 /*adjust for DO index increment.*/ + old=pi /*use the "OLD" value next time. */ end /*n*/ -say; say n%2+1 'iterations took' format(time("E"),,2) 'seconds.' +say; say n%2+1 'iterations took' format(time("Elapsed"),,2) 'seconds.' /*stick a fork in it, we're done.*/ diff --git a/Task/Pi/Ruby/pi.rb b/Task/Pi/Ruby/pi.rb new file mode 100644 index 0000000000..be243ea97d --- /dev/null +++ b/Task/Pi/Ruby/pi.rb @@ -0,0 +1,28 @@ +def pi + q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 + dot = nil + loop do + if 4*q+r-t < n*t + yield n + if dot.nil? + yield '.' + dot = '.' + end + nr = 10*(r-n*t) + n = ((10*(3*q+r)) / t) - 10*n + q *= 10 + r = nr + else + nr = (2*q+r) * l + nn = (q*(7*k+2)+r*l) / (t*l) + q *= k + t *= l + l += 2 + k += 1 + n = nn + r = nr + end + end +end + +pi {|digit| print digit; $stdout.flush} diff --git a/Task/Pick-random-element/COBOL/pick-random-element.cobol b/Task/Pick-random-element/COBOL/pick-random-element.cobol new file mode 100644 index 0000000000..57889f8f17 --- /dev/null +++ b/Task/Pick-random-element/COBOL/pick-random-element.cobol @@ -0,0 +1,16 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. random-element. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 nums-area VALUE "123456789". + 03 nums PIC 9 OCCURS 9 TIMES. + +01 random-idx PIC 9 COMP. + +PROCEDURE DIVISION. + COMPUTE random-idx = FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:7)) * 9 + 1 + DISPLAY nums (random-idx) + . +END PROGRAM random-element. diff --git a/Task/Pick-random-element/Common-Lisp/pick-random-element.lisp b/Task/Pick-random-element/Common-Lisp/pick-random-element.lisp new file mode 100644 index 0000000000..c3a6bf625d --- /dev/null +++ b/Task/Pick-random-element/Common-Lisp/pick-random-element.lisp @@ -0,0 +1,5 @@ +(defvar *list* '(one two three four five)) + +(print (nth (random (length *list*)) *list*)) +(print (nth (random (length *list*)) *list*)) +(print (nth (random (length *list*)) *list*)) diff --git a/Task/Pick-random-element/Deja-Vu/pick-random-element.djv b/Task/Pick-random-element/Deja-Vu/pick-random-element.djv index e70ffd767b..07e09135d7 100644 --- a/Task/Pick-random-element/Deja-Vu/pick-random-element.djv +++ b/Task/Pick-random-element/Deja-Vu/pick-random-element.djv @@ -1 +1 @@ -print choose [ "one" "two" "chicken" ] +!print choose [ "one" "two" "chicken" ] diff --git a/Task/Pick-random-element/GAP/pick-random-element.gap b/Task/Pick-random-element/GAP/pick-random-element.gap new file mode 100644 index 0000000000..f50faabc15 --- /dev/null +++ b/Task/Pick-random-element/GAP/pick-random-element.gap @@ -0,0 +1,2 @@ +a := [2, 9, 4, 7, 5, 3]; +Random(a); diff --git a/Task/Pick-random-element/Julia/pick-random-element.julia b/Task/Pick-random-element/Julia/pick-random-element.julia new file mode 100644 index 0000000000..57cc330423 --- /dev/null +++ b/Task/Pick-random-element/Julia/pick-random-element.julia @@ -0,0 +1,2 @@ +array = [1,2,3] +array[rand(1:length(array))] 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 543de73806..7af1e74559 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 @@ -6,18 +6,27 @@ enum Moves { roll, hold } abstract class Player { public: - final void addCurrScore() { current_score += round_score; } - final int getCurrScore() const { return current_score; } - final int getRoundScore() const { return round_score; } - final void addRoundScore(in int rs) { round_score += rs; } - final void zeroRoundScore() { round_score = 0; } + final void addCurrScore() pure nothrow { + current_score += round_score; + } + final int getCurrScore() const pure nothrow { + return current_score; + } + final int getRoundScore() const pure nothrow { + return round_score; + } + final void addRoundScore(in int rs) pure nothrow { + round_score += rs; + } + final void zeroRoundScore() pure nothrow { + round_score = 0; + } Moves getMove(); - protected: - int current_score, round_score; + protected int current_score, round_score; } -final class PlayerRand : Player { +final class PlayerRand: Player { override Moves getMove() { if (round_score + current_score >= maxPoints) return Moves.hold; @@ -30,7 +39,7 @@ final class PlayerRand : Player { } } -final class PlayerQ2Win : Player { +final class PlayerQ2Win: Player { override Moves getMove() { if (round_score + current_score >= maxPoints) return Moves.hold; @@ -45,7 +54,7 @@ final class PlayerQ2Win : Player { } } -final class PlayerAL20 : Player { +final class PlayerAL20: Player { override Moves getMove() { if (round_score + current_score >= maxPoints) return Moves.hold; @@ -55,7 +64,7 @@ final class PlayerAL20 : Player { } } -final class PlayerAL20T : Player { +final class PlayerAL20T: Player { override Moves getMove() { if (round_score + current_score >= maxPoints) return Moves.hold; @@ -77,7 +86,7 @@ void main() { players[3] = new PlayerAL20T; void nextTurn(ref uint p) { - players[p].zeroRoundScore(); + players[p].zeroRoundScore; p = (p + 1) % nPlayers; } @@ -119,6 +128,5 @@ void main() { writeln("Player I (Rand): ", players[0].getCurrScore); writeln("Player II (Q2Win): ", players[1].getCurrScore); writeln("Player III (AL20): ", players[2].getCurrScore); - writeln("Player IV (AL20T): ", players[3].getCurrScore, - "\n\n"); + writeln("Player IV (AL20T): ", players[3].getCurrScore, "\n\n"); } diff --git a/Task/Pig-the-dice-game-Player/Erlang/pig-the-dice-game-player.erl b/Task/Pig-the-dice-game-Player/Erlang/pig-the-dice-game-player.erl new file mode 100644 index 0000000000..d063095dac --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Erlang/pig-the-dice-game-player.erl @@ -0,0 +1,54 @@ +-module( pig_dice_player ). + +-export( [task/0] ). + +task() -> + Goal = pig_dice:goal(), + Players_holds = [{"Player"++ erlang:integer_to_list(X), X} || X <- [5, 10, 15, 20]], + Fun = fun ({Player, Total}, Dict) when Total >= Goal -> dict:update_counter( Player, 1, Dict ); + (_Player_total, Dict) -> Dict + end, + Dict = lists:foldl( Fun, dict:new(), task_play(Players_holds, Goal, []) ), + display( dict:to_list(Dict) ). + + +display( Results ) -> + [{Name, Total} | Rest] = lists:reverse( lists:keysort(2, Results) ), + io:fwrite( "Winner is ~p with total of ~p wins~n", [Name, Total] ), + io:fwrite( "Then follows: " ), + [io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest]. + +is_goal_reached( Score, Player, Goal, Player, Game ) -> + Score + proplists:get_value(Player, pig_dice:players_totals(Game)) >= Goal; +is_goal_reached( _Score, _Other_player, _Goal, _Player, _Game ) -> false. + +loop( Hold, Hold, Goal, Player, Game ) -> + pig_dice:hold( Player, Game ), + loop( 1, Hold, Goal, Player, Game ); +loop( N, Hold, Goal, Player, Game ) -> + loop_await_my_turn( pig_dice:player_name(Game), Player, Game ), + pig_dice:roll( Player, Game ), + Is_goal_reached = is_goal_reached( pig_dice:score(Game), pig_dice:player_name(Game), Goal, Player, Game ), + loop_done( Is_goal_reached, N, Hold, Goal, Player, Game ). + +loop_await_my_turn( Player, Player, _Game ) -> ok; +loop_await_my_turn( _Other, Player, Game ) -> loop_await_my_turn( pig_dice:player_name(Game), Player, Game ). + +loop_done( true, _N, _Hold, _Goal, Player, Game ) -> pig_dice:hold( Player, Game ); +loop_done( false, N, Hold, Goal, Player, Game ) -> loop( N + 1, Hold, Goal, Player, Game ). + +rotate( [H | T] ) -> T ++ [H]. + +task_play( Players_holds, _Goal, Acc ) when erlang:length(Players_holds) =:= erlang:length(Acc) -> lists:flatten( Acc ); +task_play( Players_holds, Goal, Acc ) -> + Results = [task_play_n(Players_holds, Goal) || _X <- lists:seq(1, 100)], + task_play( rotate(Players_holds), Goal, [Results | Acc] ). + +task_play_n( Players_holds, Goal ) -> + Game = pig_dice:game( [X || {X, _Y} <- Players_holds] ), + Pids = [erlang:spawn(fun() -> loop(1, Y, Goal, X, Game) end) || {X, Y} <- Players_holds], + receive + {pig, Result, Game} -> + [erlang:exit(X, kill) || X <- [Game | Pids]], + Result + end. diff --git a/Task/Pig-the-dice-game/ActionScript/pig-the-dice-game.as b/Task/Pig-the-dice-game/ActionScript/pig-the-dice-game.as new file mode 100644 index 0000000000..ab22091064 --- /dev/null +++ b/Task/Pig-the-dice-game/ActionScript/pig-the-dice-game.as @@ -0,0 +1,426 @@ +package { + + import flash.display.Graphics; + import flash.display.Shape; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + + public class PigTheDiceGame extends Sprite { + + /** + * The name of the first player. + * + * @private + */ + private var _name1:String = "Player 1"; + + /** + * The name of the second player. + * + * @private + */ + private var _name2:String = "Player 2"; + + /** + * True if the next turn is of the second player, false if it is of the first player. + * + * @private + */ + private var _isPlayer2:Boolean = false; + + /** + * The score of the first player. + * + * @private + */ + private var __p1Score:uint; + + /** + * The score of the second player. + * + * @private + */ + private var __p2Score:uint; + + /** + * The number of points in the current turn. + * + * @private + */ + private var __turnPts:uint; + + /** + * The text field displaying the score of the first player. + * + * @private + */ + private var _p1ScoreText:TextField; + + /** + * The text field displaying the score of the second player. + * + * @private + */ + private var _p2ScoreText:TextField; + + /** + * The button which must be clicked for a player to roll the dice. + * + * @private + */ + private var _rollButton:Sprite; + + /** + * The button which must be clicked for a player to hold. + * + * @private + */ + private var _holdButton:Sprite; + + /** + * The text field displaying the name of the current player. + */ + private var _currentPlayerText:TextField; + + /** + * The text field displaying the number of points in the current turn. + * + * @private + */ + private var _ptsThisTurnText:TextField; + + /** + * The dice. + * + * @private + */ + private var _dice:Shape; + + /** + * The number of points required to win the game. + * + * @private + */ + private var _maxScore:uint = 100; + + /** + * The text field displaying additional information about the game. + * + * @private + */ + private var _statusText:TextField; + + /** + * Creates a new PigTheDiceGame instance. + */ + public function PigTheDiceGame() { + if ( stage ) _init(); + else addEventListener(Event.ADDED_TO_STAGE, _init); + } + + /** + * Function which constructs the dice game when the object is added to the stage. + * + * @private + */ + private function _init(e:Event = null):void { + + // Border and background + + graphics.beginFill(0xFFFFDD); + graphics.lineStyle(2, 0xFFCC00); + graphics.drawRect(0, 0, 450, 280) + + x = 20; + y = 20; + + // Text fields and labels + + var currentPlayerText:TextField = _createTextField(_name1 + "'s turn", 20, 0, 10, 0xDD0000, TextFieldAutoSize.CENTER, width); + var p1ScoreLabel:TextField = _createTextField(_name1 + "'s score:", 15, 20, currentPlayerText.y + currentPlayerText.height + 20, 0x000000, TextFieldAutoSize.LEFT, 120); + var p1ScoreText:TextField = _createTextField("0", 17, 135, p1ScoreLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50); + var p2ScoreLabel:TextField = _createTextField(_name2 + "'s score:", 15, 20, p1ScoreText.y + p1ScoreText.height + 5, 0x000000, TextFieldAutoSize.LEFT, 120); + var p2ScoreText:TextField = _createTextField("0", 17, 135, p2ScoreLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50); + var ptsThisTurnLabel:TextField = _createTextField("Points in this turn:", 15, 20, p2ScoreText.y + p2ScoreText.height + 15, 0x000000, TextFieldAutoSize.LEFT, 120); + var ptsThisTurnText:TextField = _createTextField("0", 17, 135, ptsThisTurnLabel.y, 0xFF0000, TextFieldAutoSize.RIGHT, 50); + + // Dice + + var dice:Shape = new Shape(); + dice.x = 201; + dice.y = ptsThisTurnText.y + ptsThisTurnText.height + 30; + dice.visible = false; + + var statusText:TextField = _createTextField("Start Play!", 15, 0, dice.y + 70, 0x0000A0, TextFieldAutoSize.CENTER, 450); + + // "Roll" button + + var rollButton:Sprite = new Sprite(); + var rollButtonText:TextField = _createTextField("Roll dice", 17, 0, 0, 0x000000, TextFieldAutoSize.CENTER, 100); + rollButton.mouseChildren = false; + rollButton.buttonMode = true; + rollButton.graphics.lineStyle(1, 0x444444); + rollButton.graphics.beginFill(0xDDDDDD); + rollButton.graphics.drawRect(0, 0, 100, rollButtonText.height); + rollButton.x = 330; + rollButton.y = 80; + rollButton.addChild(rollButtonText); + + // "Hold" button + + var holdButton:Sprite = new Sprite(); + var holdButtonText:TextField = _createTextField("Hold", 17, 0, 0, 0x000000, TextFieldAutoSize.CENTER, 100); + holdButton.mouseChildren = false; + holdButton.buttonMode = true; + holdButton.graphics.copyFrom(rollButton.graphics); + holdButton.x = 330; + holdButton.y = rollButton.y + rollButton.height + 10; + holdButton.addChild(holdButtonText); + + rollButton.addEventListener(MouseEvent.CLICK, _rollButtonClick); + holdButton.addEventListener(MouseEvent.CLICK, _holdButtonClick); + + _currentPlayerText = currentPlayerText; + _p1ScoreText = p1ScoreText; + _p2ScoreText = p2ScoreText; + _ptsThisTurnText = ptsThisTurnText; + _rollButton = rollButton; + _holdButton = holdButton; + _dice = dice; + _statusText = statusText; + + addChild(currentPlayerText); + addChild(p1ScoreLabel); + addChild(p1ScoreText); + addChild(p2ScoreLabel); + addChild(p2ScoreText); + addChild(ptsThisTurnLabel); + addChild(ptsThisTurnLabel); + addChild(ptsThisTurnText); + addChild(statusText); + addChild(_dice); + addChild(rollButton); + addChild(holdButton); + + } + + /** + * Creates a new text field. + * + * @param text The text to be displayed in the text field. + * @param size The font size of the text. + * @param x The x-coordinate of the text field. + * @param y The y-coordinate of the text field. + * @param colour The text colour. + * @param autoSize The text alignment mode. + * @param width The width of the text field. + * @return A TextField object. + * @private + */ + private function _createTextField(text:String, size:Number, x:Number, y:Number, colour:uint, autoSize:String, width:Number):TextField { + var t:TextField = new TextField(); + t.defaultTextFormat = new TextFormat(null, size, colour); + t.autoSize = autoSize; + t.x = x; + t.y = y; + t.width = width; + t.text = text; + t.height = t.textHeight + 5; + return t; + } + + /** + * Rolls the dice. + * + * @return The result of the roll (1-6) + * @private + */ + private function _rollDice():uint { + + // Since Math.random() returns a number between 0 and 1, multiplying it by 6 and then rounding down + // gives a number between 0 and 5, so add 1 to it. + + var roll:uint = uint(Math.random() * 6) + 1; + + _dice.visible = true; + var diceGraphics:Graphics = _dice.graphics; + + // Draw the dice. + + diceGraphics.clear(); + diceGraphics.lineStyle(2, 0x555555); + diceGraphics.beginFill(0xFFFFFF); + diceGraphics.drawRect(0, 0, 48, 48); + diceGraphics.beginFill(0x000000); + diceGraphics.lineStyle(0); + + switch ( roll ) { + case 1: + diceGraphics.drawCircle(24, 24, 3); + break; + case 2: + diceGraphics.drawCircle(16, 16, 3); + diceGraphics.drawCircle(32, 32, 3); + break; + case 3: + diceGraphics.drawCircle(12, 12, 3); + diceGraphics.drawCircle(24, 24, 3); + diceGraphics.drawCircle(36, 36, 3); + break; + case 4: + diceGraphics.drawCircle(16, 16, 3); + diceGraphics.drawCircle(16, 32, 3); + diceGraphics.drawCircle(32, 16, 3); + diceGraphics.drawCircle(32, 32, 3); + break; + case 5: + diceGraphics.drawCircle(12, 12, 3); + diceGraphics.drawCircle(24, 24, 3); + diceGraphics.drawCircle(36, 36, 3); + diceGraphics.drawCircle(36, 12, 3); + diceGraphics.drawCircle(12, 36, 3); + break; + case 6: + diceGraphics.drawCircle(16, 12, 3); + diceGraphics.drawCircle(16, 24, 3); + diceGraphics.drawCircle(16, 36, 3); + diceGraphics.drawCircle(32, 12, 3); + diceGraphics.drawCircle(32, 24, 3); + diceGraphics.drawCircle(32, 36, 3); + break; + } + + return roll; + + } + + /** + * The score of the first player. + * + * @private + */ + private function get _p1Score():uint { + return __p1Score; + } + + /** + * @private + */ + private function set _p1Score(value:uint):void { + __p1Score = value; + _p1ScoreText.text = String(value); + + if ( value >= _maxScore ) { + _currentPlayerText.text = "Game over!"; + _statusText.text = _name1 + " wins!"; + removeChild(_rollButton); + removeChild(_holdButton); + } + } + + /** + * The score of the second player. + * + * @private + */ + private function get _p2Score():uint { + return __p2Score; + } + + /** + * @private + */ + private function set _p2Score(value:uint):void { + __p2Score = value; + _p2ScoreText.text = String(value); + + if ( value >= _maxScore ) { + _currentPlayerText.text = "Game over!"; + _statusText.text = _name2 + " wins!"; + removeChild(_rollButton); + removeChild(_holdButton); + } + } + + /** + * The number of points in the current turn. + * + * @private + */ + private function get _turnPts():uint { + return __turnPts; + } + + /** + * @private + */ + private function set _turnPts(value:uint):void { + __turnPts = value; + _ptsThisTurnText.text = String(value); + + if ( _isPlayer2 && __p2Score + value >= _maxScore ) { + _ptsThisTurnText.text = "0"; + _p2Score += value; + } + else if ( ! _isPlayer2 && __p1Score + value >= _maxScore ) { + _ptsThisTurnText.text = "0"; + _p1Score += value; + } + } + + /** + * Function called when the "Roll dice" button is clicked. + * + * @private + */ + private function _rollButtonClick(e:MouseEvent):void { + var roll:uint = _rollDice(); + + if ( roll == 1 ) { + if ( _isPlayer2 ) { + _currentPlayerText.text = _name1 + "'s turn"; + _statusText.text = _name2 + " rolls 1 and loses " + __turnPts + " points. " + _name1 + "'s turn now."; + } + else { + _currentPlayerText.text = _name2 + "'s turn"; + _statusText.text = _name1 + " rolls 1 and loses " + __turnPts + " points. " + _name2 + "'s turn now."; + } + + _isPlayer2 = ! _isPlayer2; + _turnPts = 0; + } + else { + _turnPts += roll; + _statusText.text = ""; + } + } + + /** + * Function called when the "Hold" button is clicked. + * + * @private + */ + private function _holdButtonClick(e:MouseEvent):void { + if ( _isPlayer2 ) { + _currentPlayerText.text = _name1 + "'s turn"; + _statusText.text = _name2 + " holds and wins " + __turnPts + " points. " + _name1 + "'s turn now."; + _p2Score += __turnPts; + } + else { + _currentPlayerText.text = _name2 + "'s turn"; + _statusText.text = _name1 + " holds and wins " + __turnPts + " points. " + _name2 + "'s turn now."; + _p1Score += __turnPts; + } + + _dice.visible = false; + _turnPts = 0; + _isPlayer2 = ! _isPlayer2; + } + + } + +} diff --git a/Task/Pig-the-dice-game/D/pig-the-dice-game.d b/Task/Pig-the-dice-game/D/pig-the-dice-game.d index f6c0c38c12..5e0e979af0 100644 --- a/Task/Pig-the-dice-game/D/pig-the-dice-game.d +++ b/Task/Pig-the-dice-game/D/pig-the-dice-game.d @@ -1,6 +1,5 @@ -import std.stdio, std.string, std.algorithm, std.random; - void main() { + import std.stdio, std.string, std.algorithm, std.random; enum maxScore = 100; enum playerCount = 2; immutable confirmations = ["yes", "y", ""]; @@ -12,8 +11,8 @@ void main() { writef(" Player %d: (%d, %d). Rolling? (y/n) ", player, safeScore[player], score); if (safeScore[player] + score < maxScore && - confirmations.canFind(readln().strip().toLower())) { - immutable int rolled = uniform(1, 7); + confirmations.canFind(readln.strip.toLower)) { + immutable rolled = uniform(1, 7); writefln(" Rolled %d", rolled); if (rolled == 1) { writefln(" Bust! You lose %d but keep %d\n", diff --git a/Task/Pig-the-dice-game/Erlang/pig-the-dice-game.erl b/Task/Pig-the-dice-game/Erlang/pig-the-dice-game.erl new file mode 100644 index 0000000000..dbd60ec49b --- /dev/null +++ b/Task/Pig-the-dice-game/Erlang/pig-the-dice-game.erl @@ -0,0 +1,96 @@ +-module( pig_dice ). + +-export( [game/1, goal/0, hold/2, player_name/1, players_totals/1, quit/2, roll/2, score/1, task/0] ). + +-record( player, {name, score=0, total=0} ). + +game( [_Player | _T]=Players ) -> + My_pid = erlang:self(), + erlang:spawn_link( fun() -> random:seed(os:timestamp()), game_loop( [#player{name=X} || X <- Players], 100, My_pid ) end ). + +goal() -> 100. + +hold( Player, Game ) -> Game ! {next_player, Player}. + +players_totals( Game ) -> ask( Game, players_totals ). + +player_name( Game ) -> ask( Game, name ). + +quit( Player, Game ) -> Game ! {quit, Player}. + +roll( Player, Game ) -> Game ! {roll, Player}. + +score( Game ) -> ask( Game, score ). + +task() -> + Game = game( ["Player1", "Player2"] ), + Play = erlang:spawn( fun() -> play_loop( Game ) end ), + receive + {pig, Result, Game} -> + erlang:exit( Play, kill ), + task_display( Result ), + Result + end. + + + +ask( Game, Question ) -> + Game ! {Question, erlang:self()}, + receive + {Question, Answer, Game} -> Answer + end. + +game_loop( [], _Goal, Report_pid ) -> Report_pid ! {pig, game_over_all_quite. erlang:self()}; +game_loop( [#player{name=Name}=Player | T]=Players, Goal, Report_pid ) -> + receive + {name, Pid} -> + Pid ! {name, Player#player.name, erlang:self()}, + game_loop( Players, Goal, Report_pid ); + {next_player, Name} -> + New_players = game_loop_next_player( Player#player.total + Player#player.score, Players, Goal, Report_pid ), + game_loop( New_players, Goal, Report_pid ); + {players_totals, Pid} -> + Pid ! {players_totals, [{X#player.name, X#player.total} || X <- Players], erlang:self()}, + game_loop( Players, Goal, Report_pid ); + {quit, Name} -> game_loop( T, Goal, Report_pid ); + {roll, Name} -> + New_players = game_loop_roll( random:uniform(6), Players ), + game_loop( New_players, Goal, Report_pid ); + {score, Pid} -> + Pid ! {score, Player#player.score, erlang:self()}, + game_loop( Players, Goal, Report_pid ) + end. + +game_loop_next_player( Total, [Player | T], Goal, Report_pid ) when Total >= Goal -> + Report_pid ! {pig, [{X#player.name, X#player.total} || X <- [Player | T]]. erlang:self()}, + []; +game_loop_next_player( Total, [Player | T], _Goal, _Report_pid ) -> + T ++ [Player#player{score=0, total=Total}]. + +game_loop_roll( 1, [Player | T] ) -> T ++ [Player#player{score=0}]; +game_loop_roll( Score, [#player{score=Old_score}=Player | T] ) -> [Player#player{score=Old_score + Score} | T]. + +play_loop( Game ) -> + Name = player_name( Game ), + io:fwrite( "Currently ~p.~n", [players_totals(Game)] ), + io:fwrite( "Name ~p.~n", [Name] ), + roll( Name, Game ), + Score = score( Game ), + io:fwrite( "Rolled, score this round ~p.~n", [Score] ), + play_loop_next( Score, Name, Game ), + play_loop( Game ). + +play_loop_command( {ok, ["y" ++ _T]}, _Name, _Game ) -> ok; +play_loop_command( {ok, ["n" ++ _T]}, Name, Game ) -> hold( Name, Game ); +play_loop_command( {ok, ["q" ++ _T]}, Name, Game ) -> quit( Name, Game ); +play_loop_command( {ok, _T}, Name, Game ) -> play_loop_command( io:fread("Roll again (y/n/q): ", "~s"), Name, Game ). + +play_loop_next( 0, _Name, _Game ) -> io:fwrite( "~nScore 0, next player.~n" ); +play_loop_next( _Score, Name, Game ) -> play_loop_command( io:fread("Roll again (y/n/q): ", "~s"), Name, Game ). + +task_display( Results ) when is_list(Results) -> + [{Name, Total} | Rest] = lists:reverse( lists:keysort(2, Results) ), + io:fwrite( "Winner is ~p with total of ~p~n", [Name, Total] ), + io:fwrite( "Then follows: " ), + [io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest]; +task_display( Result ) -> io:fwrite( "Result: ~p~n", [Result] ). diff --git a/Task/Pig-the-dice-game/Perl/pig-the-dice-game.pl b/Task/Pig-the-dice-game/Perl/pig-the-dice-game.pl new file mode 100644 index 0000000000..536684f0dc --- /dev/null +++ b/Task/Pig-the-dice-game/Perl/pig-the-dice-game.pl @@ -0,0 +1,40 @@ +#!perl +use strict; +use warnings; +my @players = @ARGV; +@players = qw(Joe Mike); +my @scores = (0) x @players; +while( 1 ) { + PLAYER: for my $i ( 0 .. $#players ) { + my $name = $players[$i]; + my $score = $scores[$i]; + my $roundscore = 1 + int rand 6; + print "$name, your score so far is $score.\n"; + print "You rolled a $roundscore.\n"; + next PLAYER if $roundscore == 1; + while($score + $roundscore < 100) { + print "Roll again, or hold [r/h]: "; + my $answer = <>; + $answer = 'h' unless defined $answer; + if( $answer =~ /^h/i ) { + $score += $roundscore; + $scores[$i] = $score; + print "Your score is now $score.\n"; + next PLAYER; + } elsif( $answer =~ /^r/ ) { + my $die = 1 + int rand 6; + print "$name, you rolled a $die.\n"; + next PLAYER if $die == 1; + $roundscore += $die; + print "Your score for the round is now $roundscore.\n"; + } else { + print "I did not understand that.\n"; + } + } + $score += $roundscore; + print "With that, your score became $score.\n"; + print "You won!\n"; + exit; + } +} +__END__ diff --git a/Task/Pinstripe-Display/ActionScript/pinstripe-display.as b/Task/Pinstripe-Display/ActionScript/pinstripe-display.as new file mode 100644 index 0000000000..643ee3e1b6 --- /dev/null +++ b/Task/Pinstripe-Display/ActionScript/pinstripe-display.as @@ -0,0 +1,52 @@ +package { + + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.Sprite; + import flash.events.Event; + + public class Pinstripe extends Sprite { + + public function Pinstripe():void { + if (stage) init(); + else addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(e:Event = null):void { + + var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, false, 0xFFFFFFFF); + data.lock(); + + var w:uint = data.width, h:uint = data.height / 4; + var x:uint, y:uint = 0, i:uint, px:uint, colour:uint, maxy:uint = h; + + for ( i = 1; i <= 4; i++ ) { + + for ( ; y < maxy; y++ ) { + colour = 0xFF000000; + px = 1; + + for ( x = 0; x < w; x++ ) { + + if ( px == i ) { + colour = (colour == 0xFF000000) ? 0xFFFFFFFF : 0xFF000000; + px = 1; + } + else px++; + + data.setPixel32(x, y, colour); + + } + } + + maxy += h; + + } + + data.unlock(); + addChild(new Bitmap(data)); + } + + } + +} diff --git a/Task/Pinstripe-Display/C/pinstripe-display.c b/Task/Pinstripe-Display/C/pinstripe-display.c new file mode 100644 index 0000000000..7841759927 --- /dev/null +++ b/Task/Pinstripe-Display/C/pinstripe-display.c @@ -0,0 +1,28 @@ +/*Abhishek Ghosh, 6th November 2013, Rotterdam*/ +#include +#include + +#define sections 4 + +int main() +{ + int d=DETECT,m,maxX,maxY,x,y,increment=1; + initgraph(&d,&m,"c:/turboc3/bgi"); + + maxX = getmaxx(); + maxY = getmaxy(); + + for(y=0;y + + toString: => "#{@pip}#{@suit}" + +class Deck + pips = '2 3 4 5 6 7 8 9 10 J Q K A'.split ' ' + suits = '♣ ♥ ♠ ♦'.split ' ' + + constructor: (@cards) -> + if not @cards? + @cards = [] + for suit in suits + for pip in pips + @cards.push new Card(pip, suit) + + toString: => "[#{@cards.join(', ')}]" + + shuffle: => + for card, i in @cards + randomCard = parseInt @cards.length * Math.random() + @cards[i] = @cards.splice(randomCard, 1, card)[0] + + deal: -> @cards.shift() diff --git a/Task/Playing-cards/D/playing-cards-1.d b/Task/Playing-cards/D/playing-cards-1.d index 714e106da5..ec4282dede 100644 --- a/Task/Playing-cards/D/playing-cards-1.d +++ b/Task/Playing-cards/D/playing-cards-1.d @@ -1,43 +1,32 @@ -import std.stdio, std.random, std.string, std.array; +import std.stdio, std.typecons, std.algorithm, std.traits, std.array, + std.range, std.random; -struct Card { - enum suits = ["Clubs", "Hearts", "Spades", "Diamonds"]; - enum pips = ["2", "3", "4", "5", "6", "7", "8", "9", "10", - "Jack", "Queen", "King", "Ace"]; - string pip, suit; +enum Pip {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, + Jack, Queen, King, Ace} +enum Suit {Diamonds, Spades, Hearts, Clubs} +alias Card = Tuple!(Pip, Suit); - string toString() { - return pip ~ " of " ~ suit; - } +Card[] newDeck() /*pure nothrow*/ { + return cartesianProduct([EnumMembers!Pip], [EnumMembers!Suit]) + .array; } -class Deck { - Card[] deck; +alias shuffleDeck = randomShuffle; - this() { - foreach (suit; Card.suits) - foreach (pip; Card.pips) - deck ~= Card(pip, suit); - } +Card dealCard(ref Card[] deck) pure nothrow { + immutable card = deck.back; + deck.popBack; + return card; +} - void shuffle() { - deck.randomShuffle(); - } - - Card deal() { - auto card = deck.back; - deck.popBack(); - return card; - } - - override string toString() { - return format("%(%s\n%)", deck); - } +void show(in Card[] deck) { + writefln("Deck:\n%(%s\n%)\n", deck); } void main() { - auto deck = new Deck; // Make A new deck. - deck.shuffle(); // Shuffle the deck. - writeln("Card: ", deck.deal()); // Deal from the deck. - writeln(deck); // Print the current contents of the deck. + auto d = newDeck; + d.show; + d.shuffleDeck; + while (!d.empty) + d.dealCard.writeln; } diff --git a/Task/Playing-cards/Erlang/playing-cards.erl b/Task/Playing-cards/Erlang/playing-cards.erl new file mode 100644 index 0000000000..455516bbaa --- /dev/null +++ b/Task/Playing-cards/Erlang/playing-cards.erl @@ -0,0 +1,38 @@ +-module( playing_cards ). + +-export( [deal/2, deal/3, deck/0, print/1, shuffle/1, sort_pips/1, sort_suites/1, task/0] ). + +-record( card, {pip, suite} ). + +-spec( deal( N_cards::integer(), Deck::[#card{}]) -> {Hand::[#card{}], Deck::[#card{}]} ). +deal( N_cards, Deck ) -> lists:split( N_cards, Deck ). +-spec( deal( N_hands::integer(), N_cards::integer(), Deck::[#card{}]) -> {List_of_hands::[[#card{}]], Deck::[#card{}]} ). +deal( N_hands, N_cards, Deck ) -> lists:foldl( fun deal_hands/2, {lists:duplicate(N_hands, []), Deck}, lists:seq(1, N_cards * N_hands) ). + +deck() -> [#card{suite=X, pip=Y} || X <- suites(), Y <- pips()]. + +print( Cards ) -> [io:fwrite( " ~p", [X]) || X <- Cards], io:nl(). + +shuffle( Deck ) -> knuth_shuffle:list( Deck ). + +sort_pips( Cards ) -> lists:keysort( #card.pip, Cards ). + +sort_suites( Cards ) -> lists:keysort( #card.suite, Cards ). + +task() -> + Deck = deck(), + Shuffled = shuffle( Deck ), + {Hand, New_deck} = deal( 3, Shuffled ), + {Hands, _Deck} = deal( 2, 3, New_deck ), + io:fwrite( "Hand:" ), + print( Hand ), + io:fwrite( "Hands:~n" ), + [print(X) || X <- Hands]. + + + +deal_hands( _N, {[Hand | T], [Card | Deck]} ) -> {T ++ [[Card | Hand]], Deck}. + +pips() -> ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]. + +suites() -> ["Clubs", "Hearts", "Spades", "Diamonds"]. diff --git a/Task/Playing-cards/Python/playing-cards.py b/Task/Playing-cards/Python/playing-cards-1.py similarity index 100% rename from Task/Playing-cards/Python/playing-cards.py rename to Task/Playing-cards/Python/playing-cards-1.py diff --git a/Task/Playing-cards/Python/playing-cards-2.py b/Task/Playing-cards/Python/playing-cards-2.py new file mode 100644 index 0000000000..f3fdcebe0b --- /dev/null +++ b/Task/Playing-cards/Python/playing-cards-2.py @@ -0,0 +1,25 @@ +from pokerhand import Card, suit, face +from itertools import product +from random import randrange + +class Deck(): + def __init__(self): + self.__deck = [Card(f, s) for f,s in product(face, suit)] + + def __repr__(self): + return 'Deck of ' + ' '.join(repr(card) for card in self.__deck) + + def shuffle(self): + pass + + def deal(self): + return self.__deck.pop(randrange(len(self.__deck))) + +if __name__ == '__main__': + deck = Deck() + print('40 cards from a deck:\n') + for i in range(5): + for j in range(8): + print(deck.deal(), end=' ') + print() + print('\nThe remaining cards are a', deck) diff --git a/Task/Polymorphic-copy/Racket/polymorphic-copy-1.rkt b/Task/Polymorphic-copy/Racket/polymorphic-copy-1.rkt new file mode 100644 index 0000000000..ccbec09e6e --- /dev/null +++ b/Task/Polymorphic-copy/Racket/polymorphic-copy-1.rkt @@ -0,0 +1,18 @@ +#lang racket/base + +(define (copy-prefab-struct str) + (apply make-prefab-struct (vector->list (struct->vector str)))) + +(struct point (x y) #:prefab) +(struct point/color point (color) #:prefab) + + +(let* ([original (point 0 0)] + [copied (copy-prefab-struct original)]) + (displayln copied) + (displayln (eq? original copied))) + +(let* ([original (point/color 0 0 'black)] + [copied (copy-prefab-struct original)]) + (displayln copied) + (displayln (eq? original copied))) diff --git a/Task/Polymorphic-copy/Racket/polymorphic-copy-2.rkt b/Task/Polymorphic-copy/Racket/polymorphic-copy-2.rkt new file mode 100644 index 0000000000..10496b43f8 --- /dev/null +++ b/Task/Polymorphic-copy/Racket/polymorphic-copy-2.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/Groovy/polymorphism-1.groovy b/Task/Polymorphism/Groovy/polymorphism-1.groovy new file mode 100644 index 0000000000..9e48a212f2 --- /dev/null +++ b/Task/Polymorphism/Groovy/polymorphism-1.groovy @@ -0,0 +1,18 @@ +@Canonical +@TupleConstructor(force = true) +@ToString(includeNames = true) +class Point { + Point(Point p) { x = p.x; y = p.y } + void print() { println toString() } + Number x + Number y +} + +@Canonical +@TupleConstructor(force = true) +@ToString(includeNames = true, includeSuper = true) +class Circle extends Point { + Circle(Circle c) { super(c); r = c.r } + void print() { println toString() } + Number r +} diff --git a/Task/Polymorphism/Groovy/polymorphism-2.groovy b/Task/Polymorphism/Groovy/polymorphism-2.groovy new file mode 100644 index 0000000000..6db3b60bb1 --- /dev/null +++ b/Task/Polymorphism/Groovy/polymorphism-2.groovy @@ -0,0 +1,8 @@ +def p = new Point(x: 3, y: 4) +def c = new Circle(x: 4, y: 3, r: 5) + +[(p): new Point(p), (c): new Circle(c)].each { v1, v2 -> + print "Verifying $v1 == " + v2.print() + assert v1 == v2 +} diff --git a/Task/Polymorphism/Julia/polymorphism.julia b/Task/Polymorphism/Julia/polymorphism.julia new file mode 100644 index 0000000000..470e508927 --- /dev/null +++ b/Task/Polymorphism/Julia/polymorphism.julia @@ -0,0 +1,30 @@ +import Base.print + +type Point + x::Float64 + y::Float64 +end + +print(p::Point) = println("Point($(p.x), $(p.y))") + +x(p::Point) = p.x +y(p::Point) = p.y + +setx(p::Point, x) = (p.x = x) +sety(p::Point, y) = (p.y = y) + +type Circle + x::Float64 + y::Float64 + r::Float64 +end + +x(c::Circle) = c.x +y(c::Circle) = c.y +r(c::Circle) = c.r + +setx(c::Circle, x) = (c.x = x) +sety(c::Circle, y) = (c.y = y) +setr(c::Circle, r) = (c.r = r) + +print(c::Circle) = println("Circle($(c.x), $(c.y), $(c.r))") diff --git a/Task/Polynomial-long-division/D/polynomial-long-division.d b/Task/Polynomial-long-division/D/polynomial-long-division.d index 7f435c0597..ef236f3c11 100644 --- a/Task/Polynomial-long-division/D/polynomial-long-division.d +++ b/Task/Polynomial-long-division/D/polynomial-long-division.d @@ -16,10 +16,9 @@ pure /*nothrow*/ { if (dD < 0) throw new Error("ZeroDivisionError"); if (dN >= dD) { - //q = [0.0].replicate(dN); - q = std.array.replicate([0.0], dN); + q = [0.0].replicate(dN); while (dN >= dD) { - auto d = std.array.replicate([0.0], dN - dD) ~ D; + auto d = [0.0].replicate(dN - dD) ~ D; immutable mult = q[dN - dD] = N[$ - 1] / d[$ - 1]; d[] *= mult; N[] -= d[]; diff --git a/Task/Polynomial-regression/Julia/polynomial-regression-1.julia b/Task/Polynomial-regression/Julia/polynomial-regression-1.julia new file mode 100644 index 0000000000..b397000990 --- /dev/null +++ b/Task/Polynomial-regression/Julia/polynomial-regression-1.julia @@ -0,0 +1,4 @@ +function polyfit(x, y, n) + A = [ float(x[i])^p for i = 1:length(x), p = 0:n ] + A \ y +end diff --git a/Task/Polynomial-regression/Julia/polynomial-regression-2.julia b/Task/Polynomial-regression/Julia/polynomial-regression-2.julia new file mode 100644 index 0000000000..973047c0c5 --- /dev/null +++ b/Task/Polynomial-regression/Julia/polynomial-regression-2.julia @@ -0,0 +1,7 @@ +julia> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +julia> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] +julia> polyfit(x, y, 2) +3-element Array{Float64,1}: + 1.0 + 2.0 + 3.0 diff --git a/Task/Power-set/00DESCRIPTION b/Task/Power-set/00DESCRIPTION index 63529df894..d64acaec6e 100644 --- a/Task/Power-set/00DESCRIPTION +++ b/Task/Power-set/00DESCRIPTION @@ -1,6 +1,6 @@ A [[set]] is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
-'''Task : ''' By using a library or build-in set type, or defining a set type with necessary operations, write a function with a set S as input that yields a power set 2S of S. +'''Task : ''' By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of {1,2,3,4} is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. diff --git a/Task/Power-set/Bracmat/power-set.bracmat b/Task/Power-set/Bracmat/power-set.bracmat new file mode 100644 index 0000000000..f10b57068d --- /dev/null +++ b/Task/Power-set/Bracmat/power-set.bracmat @@ -0,0 +1,10 @@ +( ( powerset + = done todo first + . !arg:(?done.?todo) + & ( !todo:%?first ?todo + & (powerset$(!done !first.!todo),powerset$(!done.!todo)) + | !done + ) + ) +& out$(powerset$(.1 2 3 4)) +); diff --git a/Task/Power-set/Common-Lisp/power-set-4.lisp b/Task/Power-set/Common-Lisp/power-set-4.lisp new file mode 100644 index 0000000000..5a4d13b71d --- /dev/null +++ b/Task/Power-set/Common-Lisp/power-set-4.lisp @@ -0,0 +1,5 @@ +(defun power-set (list) + (let ((pow-set (list nil))) + (dolist (element (reverse list) pow-set) + (dolist (set pow-set) + (push (cons element set) pow-set))))) diff --git a/Task/Power-set/Deja-Vu/power-set.djv b/Task/Power-set/Deja-Vu/power-set.djv new file mode 100644 index 0000000000..825bbd24f2 --- /dev/null +++ b/Task/Power-set/Deja-Vu/power-set.djv @@ -0,0 +1,10 @@ +powerset s: + local :out [ set{ } ] + for value in keys s: + for subset in copy out: + local :subset+1 copy subset + set-to subset+1 value true + push-to out subset+1 + out + +!. powerset set{ 1 2 3 4 } diff --git a/Task/Power-set/Go/power-set.go b/Task/Power-set/Go/power-set.go index eba24baf66..81bae2ce43 100644 --- a/Task/Power-set/Go/power-set.go +++ b/Task/Power-set/Go/power-set.go @@ -10,7 +10,7 @@ import ( // element is an interface, allowing different kinds of elements to be // implemented and stored in sets. type element interface { - // an element must be disinguishable from other elements to satisfy + // an element must be distinguishable from other elements to satisfy // the mathematical definition of a set. a.eq(b) must give the same // result as b.eq(a). eq(element) bool diff --git a/Task/Power-set/Java/power-set-1.java b/Task/Power-set/Java/power-set-1.java index 8b9f365407..4829562068 100644 --- a/Task/Power-set/Java/power-set-1.java +++ b/Task/Power-set/Java/power-set-1.java @@ -7,7 +7,7 @@ public static ArrayList getpowerset(int a[],int n,ArrayList ps) if(n==0) { if(ps==null) - ps=new ArrayList(); + ps=new ArrayList(); ps.add(" "); return ps; } diff --git a/Task/Power-set/Julia/power-set.julia b/Task/Power-set/Julia/power-set.julia new file mode 100644 index 0000000000..19a2c77785 --- /dev/null +++ b/Task/Power-set/Julia/power-set.julia @@ -0,0 +1,7 @@ +function powerset (x) + result = {{}} + for i in x, j = 1:length(result) + push!(result, [result[j],i]) + end + result +end diff --git a/Task/Power-set/OPL/power-set-1.opl b/Task/Power-set/OPL/power-set-1.opl new file mode 100644 index 0000000000..51b4fc7fc0 --- /dev/null +++ b/Task/Power-set/OPL/power-set-1.opl @@ -0,0 +1,8 @@ +{string} s={"A","B","C","D"}; +range r=1.. ftoi(pow(2,card(s))); +{string} s2 [k in r] = {i | i in s: ((k div (ftoi(pow(2,(ord(s,i))))) mod 2) == 1)}; + +execute +{ + writeln(s2); +} diff --git a/Task/Power-set/OPL/power-set-2.opl b/Task/Power-set/OPL/power-set-2.opl new file mode 100644 index 0000000000..23c33b0cc9 --- /dev/null +++ b/Task/Power-set/OPL/power-set-2.opl @@ -0,0 +1,3 @@ +[{} {"A"} {"B"} {"A" "B"} {"C"} {"A" "C"} {"B" "C"} {"A" "B" "C"} {"D"} {"A" + "D"} {"B" "D"} {"A" "B" "D"} {"C" "D"} {"A" "C" "D"} {"B" "C" "D"} + {"A" "B" "C" "D"}] diff --git a/Task/Power-set/PL-I/power-set.pli b/Task/Power-set/PL-I/power-set.pli new file mode 100644 index 0000000000..80ccc8ce66 --- /dev/null +++ b/Task/Power-set/PL-I/power-set.pli @@ -0,0 +1,66 @@ +*process source attributes xref or(!); + /*-------------------------------------------------------------------- + * 06.01.2014 Walter Pachl translated from REXX + *-------------------------------------------------------------------*/ + powerset: Proc Options(main); + Dcl (hbound,index,left,substr) Builtin; + Dcl sysprint Print; + Dcl s(4) Char(5) Var Init('one','two','three','four'); + Dcl ps Char(1000) Var; + Dcl (n,chunk,p) Bin Fixed(31); + n=hbound(s); /* number of items in the list. */ + ps='{} '; /* start with a null power set. */ + Do chunk=1 To n; /* loop through the ... . */ + ps=ps!!combn(chunk); /* a CHUNK at a time. */ + End; + Do While(ps>''); + p=index(ps,' '); + Put Edit(left(ps,p-1))(Skip,a); + ps=substr(ps,p+1); + End; + + combn: Proc(y) Returns(Char(1000) Var); + /*-------------------------------------------------------------------- + * returns the list of subsets with y elements of set s + *-------------------------------------------------------------------*/ + Dcl (y,base,bbase,ym,p,j,d,u) Bin Fixed(31); + Dcl (z,l) Char(1000) Var Init(''); + Dcl a(20) Bin Fixed(31) Init((20)0); + Dcl i Bin Fixed(31); + base=hbound(s)+1; + bbase=base-y; + ym=y-1; + Do p=1 To y; + a(p)=p; + End; + Do j=1 By 1; + l=''; + Do d=1 To y; + u=a(d); + l=l!!','!!s(u); + End; + z=z!!'{'!!substr(l,2)!!'} '; + a(y)=a(y)+1; + If a(y)=base Then + If combu(ym) Then + Leave; + End; + /* Put Edit('combn',y,z)(Skip,a,f(2),x(1),a); */ + Return(z); + + combu: Proc(d) Recursive Returns(Bin Fixed(31)); + Dcl (d,u) Bin Fixed(31); + If d=0 Then + Return(1); + p=a(d); + Do u=d To y; + a(u)=p+1; + If a(u)=bbase+u Then + Return(combu(u-1)); + p=a(u); + End; + Return(0); + End; + End; + + End; diff --git a/Task/Price-fraction/REXX/price-fraction-2.rexx b/Task/Price-fraction/REXX/price-fraction-2.rexx index a6503aca45..1c3d17f2fb 100644 --- a/Task/Price-fraction/REXX/price-fraction-2.rexx +++ b/Task/Price-fraction/REXX/price-fraction-2.rexx @@ -1,7 +1,13 @@ /* REXX *************************************************************** * Inspired by some other solutions tested with version 1 (above) * 20.04.2013 Walter Pachl +* 03.11.2013 -"- move r. computation (once is enough) **********************************************************************/ +rl='0.10 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62', + '0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.00' +Do i=1 To 20 + Parse Var rl r.i rl + End Do x=0 To 1 By 0.01 old=adjprice(x) new=adjprice2(x) @@ -11,12 +17,6 @@ Do x=0 To 1 By 0.01 End Exit -adjprice2: Procedure - rl='0.10 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62', - '0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.00' - Do i=1 To 20 - Parse Var rl r.i rl - End - Parse Arg p - i=((100*p-1)%5+1) +adjprice2: Procedure Expose r. + i=((100*arg(1)-1)%5+1) Return r.i diff --git a/Task/Primality-by-trial-division/Maxima/primality-by-trial-division.maxima b/Task/Primality-by-trial-division/Maxima/primality-by-trial-division.maxima new file mode 100644 index 0000000000..69d300e1fc --- /dev/null +++ b/Task/Primality-by-trial-division/Maxima/primality-by-trial-division.maxima @@ -0,0 +1,6 @@ +isprme(n):= catch( + for k: 2 thru sqrt(n) do if mod(n, k)=0 then throw(false), + true); + +map(isprme, [2, 3, 4, 65, 100, 181, 901]); +/* [true, true, false, false, false, true, false] */ diff --git a/Task/Prime-decomposition/Applesoft-BASIC/prime-decomposition.applesoft b/Task/Prime-decomposition/Applesoft-BASIC/prime-decomposition.applesoft new file mode 100644 index 0000000000..294309e912 --- /dev/null +++ b/Task/Prime-decomposition/Applesoft-BASIC/prime-decomposition.applesoft @@ -0,0 +1,13 @@ +9040 PF(0) = 0 : SC = 0 +9050 FOR CA = 2 TO INT( SQR(I)) +9060 IF I = 1 THEN RETURN +9070 IF INT(I / CA) * CA = I THEN GOSUB 9200 : GOTO 9060 +9080 CA = CA + SC : SC = 1 +9090 NEXT CA +9100 IF I = 1 THEN RETURN +9110 CA = I + +9200 PF(0) = PF(0) + 1 +9210 PF(PF(0)) = CA +9220 I = I / CA +9230 RETURN diff --git a/Task/Prime-decomposition/AutoHotkey/prime-decomposition.ahk b/Task/Prime-decomposition/AutoHotkey/prime-decomposition.ahk index ae169a3cbe..ca0b352e43 100644 --- a/Task/Prime-decomposition/AutoHotkey/prime-decomposition.ahk +++ b/Task/Prime-decomposition/AutoHotkey/prime-decomposition.ahk @@ -1,18 +1,17 @@ -MsgBox % factor(8388607) ; 47 * 178481 +MsgBox % factor(8388607) ; 47 * 178481 factor(n) { - If (n = 1) - Return - f = 2 - While (f <= n) - { - If (Mod(n, f) = 0) + if (n = 1) + return + f = 2 + while (f <= n) { - next := factor(n / f) - factors = %f%`n%next% - Return factors + if (Mod(n, f) = 0) + { + next := factor(n / f) + return, % f "`n" next + } + f++ } - f++ - } } diff --git a/Task/Prime-decomposition/D/prime-decomposition.d b/Task/Prime-decomposition/D/prime-decomposition.d index 73b055d288..6c82bcf504 100644 --- a/Task/Prime-decomposition/D/prime-decomposition.d +++ b/Task/Prime-decomposition/D/prime-decomposition.d @@ -1,6 +1,6 @@ -import std.traits: Unqual; +import std.stdio, std.bigint, std.algorithm, std.traits; -Unqual!T[] decompose(T)(T number) /*pure nothrow*/ +Unqual!T[] decompose(T)(in T number) pure /*nothrow*/ in { assert(number > 1); } body { @@ -25,13 +25,11 @@ in { } void main() { - import std.stdio, std.bigint, std.algorithm; - foreach (immutable n; 2 .. 10) - writeln(decompose(n)); + n.decompose.writeln; - writeln(decompose(1023 * 1024)); - writeln(decompose(BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17))); - writeln(decompose(BigInt(16860167264933UL) * 179951)); - writeln(group(decompose(BigInt(2) ^^ 100_000))); + decompose(1023 * 1024).writeln; + BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17).decompose.writeln; + decompose(16860167264933UL.BigInt * 179951).writeln; + decompose(2.BigInt ^^ 100_000).group.writeln; } diff --git a/Task/Prime-decomposition/Julia/prime-decomposition.julia b/Task/Prime-decomposition/Julia/prime-decomposition.julia new file mode 100644 index 0000000000..c6c4b5afbf --- /dev/null +++ b/Task/Prime-decomposition/Julia/prime-decomposition.julia @@ -0,0 +1,2 @@ +julia> factor(8796093022207) +[9719=>1,431=>1,2099863=>1] diff --git a/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima b/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima index 5b76e2edd6..6d6ab5cbae 100644 --- a/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima +++ b/Task/Prime-decomposition/Maxima/prime-decomposition-2.maxima @@ -1,7 +1,7 @@ -prime_dec(n) := apply(append, create_list(makelist(a[1], a[2]), a, ifactors(n)))$ +prime_dec(n) := flatten(create_list(makelist(a[1], a[2]), a, ifactors(n)))$ /* or, slighlty more "functional" */ -prime_dec(n) := apply(append, map(lambda([a], apply(makelist, a)), ifactors(n)))$ +prime_dec(n) := flatten(map(lambda([a], apply(makelist, a)), ifactors(n)))$ prime_dec(2^4*3^5*5*7^2); /* [2, 2, 2, 2, 3, 3, 3, 3, 3, 5, 7, 7] */ diff --git a/Task/Prime-decomposition/REXX/prime-decomposition.rexx b/Task/Prime-decomposition/REXX/prime-decomposition.rexx index 445525c94f..f295d6cc0d 100644 --- a/Task/Prime-decomposition/REXX/prime-decomposition.rexx +++ b/Task/Prime-decomposition/REXX/prime-decomposition.rexx @@ -23,16 +23,18 @@ exit /*stick a fork in it, we're done.*/ factr: procedure; parse arg x 1 z,list /*sets X&Z to arg1, LIST to null.*/ if x==1 then return '' /*handle the special case of X=1.*/ j=2; call .factr /*factor for the only even prime.*/ -j=3; call .factr /*factor for the first odd prime.*/ - /* [↓] could be optimized more.*/ - do j=5 to 17 by 2 /*small prime factors (up to 17).*/ - if j//3\==0 then call .factr /*J prime? See if it's a factor.*/ - end /*j*/ /* [↑] J=19 when DO loop ends.*/ -j=17 /* [↓] DO loop starts at 17+2.*/ - do y=0 by 2; j=j+2+y//4 /*insure J isn't divisible by 3.*/ - if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ - if j>z then leave /*num. reduced to a small number?*/ - if j*j>x then leave /*are we higher than the √ of X ?*/ +j=3; call .factr /*factor for the 1st odd prime.*/ +j=5; call .factr /*factor for the 2nd odd prime.*/ +j=7; call .factr /*factor for the 3rd odd prime.*/ +j=11; call .factr /*factor for the 4th odd prime.*/ +j=13; call .factr /*factor for the 5th odd prime.*/ +j=17; call .factr /*factor for the 6th odd prime.*/ + /* [↑] could be optimized more.*/ + /* [↓] J in loop starts at 17+2*/ + do y=0 by 2; j=j+2+y//4 /*insure J isn't divisible by 3. */ + if right(j,1)==5 then iterate /*fast check for divisible by 5. */ + if j*j>z then leave /*are we higher than the √ of Z ?*/ + if j>Z then leave /*are we higher than value of Z ?*/ call .factr /*invoke .FACTR for some factors.*/ end /*y*/ /* [↑] only tests up to the √ X.*/ /* [↓] LIST has a leading blank.*/ @@ -42,5 +44,5 @@ if z==1 then return list /*if residual=unity, don't append*/ .factr: do while z//j==0 /*keep dividing until we can't. */ list=list j /*add number to the list (J). */ z=z%j /*% (percent) is integer divide.*/ - end /*do while z···*/ /* // ◄───remainder integer ÷.*/ + end /*while z··· */ /* // ◄───remainder integer ÷.*/ return /*finished, now return to invoker*/ diff --git a/Task/Priority-queue/C/priority-queue-1.c b/Task/Priority-queue/C/priority-queue-1.c index 74c80eabbd..29ffba4151 100644 --- a/Task/Priority-queue/C/priority-queue-1.c +++ b/Task/Priority-queue/C/priority-queue-1.c @@ -9,123 +9,123 @@ typedef struct { q_elem_t *buf; int n, alloc; } pri_queue_t, *pri_queue; /* first element in array not used to simplify indices */ pri_queue priq_new(int size) { - if (size < 4) size = 4; + if (size < 4) size = 4; - pri_queue q = malloc(sizeof(pri_queue_t)); - q->buf = malloc(sizeof(q_elem_t) * size); - q->alloc = size; - q->n = 1; + pri_queue q = malloc(sizeof(pri_queue_t)); + q->buf = malloc(sizeof(q_elem_t) * size); + q->alloc = size; + q->n = 1; - return q; + return q; } void priq_push(pri_queue q, void *data, int pri) { - q_elem_t *b; - int n, m; + q_elem_t *b; + int n, m; - if (q->n >= q->alloc) { - q->alloc *= 2; - b = q->buf = realloc(q->buf, sizeof(q_elem_t) * q->alloc); - } else - b = q->buf; + if (q->n >= q->alloc) { + q->alloc *= 2; + b = q->buf = realloc(q->buf, sizeof(q_elem_t) * q->alloc); + } else + b = q->buf; - n = q->n++; - /* append at end, then up heap */ - while ((m = n / 2) && pri < b[m].pri) { - b[n] = b[m]; - n = m; - } - b[n].data = data; - b[n].pri = pri; + n = q->n++; + /* append at end, then up heap */ + while ((m = n / 2) && pri < b[m].pri) { + b[n] = b[m]; + n = m; + } + b[n].data = data; + b[n].pri = pri; } /* remove top item. returns 0 if empty. *pri can be null. */ void * priq_pop(pri_queue q, int *pri) { - void *out; - if (q->n == 1) return 0; + void *out; + if (q->n == 1) return 0; - q_elem_t *b = q->buf; + q_elem_t *b = q->buf; - out = b[1].data; - if (pri) *pri = b[1].pri; + out = b[1].data; + if (pri) *pri = b[1].pri; - /* pull last item to top, then down heap. */ - --q->n; + /* pull last item to top, then down heap. */ + --q->n; - int n = 1, m; - while ((m = n * 2) < q->n) { - if (m + 1 < q->n && b[m].pri > b[m + 1].pri) m++; + int n = 1, m; + while ((m = n * 2) < q->n) { + if (m + 1 < q->n && b[m].pri > b[m + 1].pri) m++; - if (b[q->n].pri <= b[m].pri) break; - b[n] = b[m]; - n = m; - } + if (b[q->n].pri <= b[m].pri) break; + b[n] = b[m]; + n = m; + } - b[n] = b[q->n]; - if (q->n < q->alloc / 2 && q->n >= 16) - q->buf = realloc(q->buf, (q->alloc /= 2) * sizeof(b[0])); + b[n] = b[q->n]; + if (q->n < q->alloc / 2 && q->n >= 16) + q->buf = realloc(q->buf, (q->alloc /= 2) * sizeof(b[0])); - return out; + return out; } /* get the top element without removing it from queue */ void* priq_top(pri_queue q, int *pri) { - if (q->n == 1) return 0; - if (pri) *pri = q->buf[1].pri; - return q->buf[1].data; + if (q->n == 1) return 0; + if (pri) *pri = q->buf[1].pri; + return q->buf[1].data; } /* this is O(n log n), but probably not the best */ void priq_combine(pri_queue q, pri_queue q2) { - int i; - q_elem_t *e = q2->buf + 1; + int i; + q_elem_t *e = q2->buf + 1; - for (i = q2->n - 1; i >= 1; i--, e++) - priq_push(q, e->data, e->pri); - priq_purge(q2); + for (i = q2->n - 1; i >= 1; i--, e++) + priq_push(q, e->data, e->pri); + priq_purge(q2); } int main() { - int i, p; - const char *c, *tasks[] ={ - "Clear drains", "Feed cat", "Make tea", "Solve RC tasks", "Tax return" }; - int pri[] = { 3, 4, 5, 1, 2 }; + int i, p; + const char *c, *tasks[] ={ + "Clear drains", "Feed cat", "Make tea", "Solve RC tasks", "Tax return" }; + int pri[] = { 3, 4, 5, 1, 2 }; - /* make two queues */ - pri_queue q = priq_new(0), q2 = priq_new(0); + /* make two queues */ + pri_queue q = priq_new(0), q2 = priq_new(0); - /* push all 5 tasks into q */ - for (i = 0; i < 5; i++) - priq_push(q, tasks[i], pri[i]); + /* push all 5 tasks into q */ + for (i = 0; i < 5; i++) + priq_push(q, tasks[i], pri[i]); - /* pop them and print one by one */ - while ((c = priq_pop(q, &p))) - printf("%d: %s\n", p, c); + /* pop them and print one by one */ + while ((c = priq_pop(q, &p))) + printf("%d: %s\n", p, c); - /* put a million random tasks in each queue */ - for (i = 0; i < 1 << 20; i++) { - p = rand() / ( RAND_MAX / 5 ); - priq_push(q, tasks[p], pri[p]); + /* put a million random tasks in each queue */ + for (i = 0; i < 1 << 20; i++) { + p = rand() / ( RAND_MAX / 5 ); + priq_push(q, tasks[p], pri[p]); - p = rand() / ( RAND_MAX / 5 ); - priq_push(q2, tasks[p], pri[p]); - } + p = rand() / ( RAND_MAX / 5 ); + priq_push(q2, tasks[p], pri[p]); + } - printf("\nq has %d items, q2 has %d items\n", priq_size(q), priq_size(q2)); + printf("\nq has %d items, q2 has %d items\n", priq_size(q), priq_size(q2)); - /* merge q2 into q; q2 is empty */ - priq_combine(q, q2); - printf("After merge, q has %d items, q2 has %d items\n", - priq_size(q), priq_size(q2)); + /* merge q2 into q; q2 is empty */ + priq_combine(q, q2); + printf("After merge, q has %d items, q2 has %d items\n", + priq_size(q), priq_size(q2)); - /* pop q until it's empty */ - for (i = 0; (c = priq_pop(q, 0)); i++); - printf("Popped %d items out of q\n", i); + /* pop q until it's empty */ + for (i = 0; (c = priq_pop(q, 0)); i++); + printf("Popped %d items out of q\n", i); - return 0; + return 0; } diff --git a/Task/Priority-queue/Component-Pascal/priority-queue-1.component b/Task/Priority-queue/Component-Pascal/priority-queue-1.component index 60947be73e..afaa88ed8f 100644 --- a/Task/Priority-queue/Component-Pascal/priority-queue-1.component +++ b/Task/Priority-queue/Component-Pascal/priority-queue-1.component @@ -2,87 +2,87 @@ MODULE PQueues; IMPORT StdLog,Boxes; TYPE - Rank* = POINTER TO RECORD - p-: LONGINT; (* Priority *) - value-: Boxes.Object - END; - - PQueue* = POINTER TO RECORD - a: POINTER TO ARRAY OF Rank; - size-: LONGINT; - END; - - PROCEDURE NewRank*(p: LONGINT; v: Boxes.Object): Rank; - VAR - r: Rank; - BEGIN - NEW(r);r.p := p;r.value := v; - RETURN r - END NewRank; - - PROCEDURE NewPQueue*(cap: LONGINT): PQueue; - VAR - pq: PQueue; - BEGIN - NEW(pq);pq.size := 0; - NEW(pq.a,cap);pq.a[0] := NewRank(MIN(INTEGER),NIL); - RETURN pq - END NewPQueue; - - PROCEDURE (pq: PQueue) Push*(r:Rank), NEW; - VAR - i: LONGINT; - BEGIN - INC(pq.size); - i := pq.size; - WHILE r.p < pq.a[i DIV 2].p DO - pq.a[i] := pq.a[i DIV 2];i := i DIV 2 - END; - pq.a[i] := r - END Push; - - PROCEDURE (pq: PQueue) Pop*(): Rank,NEW; - VAR - r,y: Rank; - i,j: LONGINT; - ok: BOOLEAN; - BEGIN - r := pq.a[1]; (* Priority object *) - y := pq.a[pq.size]; DEC(pq.size); i := 1; ok := FALSE; - WHILE (i <= pq.size DIV 2) & ~ok DO - j := i + 1; - IF (j < pq.size) & (pq.a[i].p > pq.a[j + 1].p) THEN INC(j) END; - IF y.p > pq.a[j].p THEN pq.a[i] := pq.a[j]; i := j ELSE ok := TRUE END - END; - pq.a[i] := y; - RETURN r - END Pop; - - PROCEDURE (pq: PQueue) IsEmpty*(): BOOLEAN,NEW; - BEGIN - RETURN pq.size = 0 - END IsEmpty; - - PROCEDURE Test*; - VAR - pq: PQueue; - r: Rank; - PROCEDURE ShowRank(r:Rank); - BEGIN - StdLog.Int(r.p);StdLog.String(":> ");StdLog.String(r.value.AsString());StdLog.Ln; - END ShowRank; - BEGIN - pq := NewPQueue(128); - pq.Push(NewRank(3,Boxes.NewString("Clear drains"))); - pq.Push(NewRank(4,Boxes.NewString("Feed cat"))); - pq.Push(NewRank(5,Boxes.NewString("Make tea"))); - pq.Push(NewRank(1,Boxes.NewString("Solve RC tasks"))); - pq.Push(NewRank(2,Boxes.NewString("Tax return"))); - ShowRank(pq.Pop()); - ShowRank(pq.Pop()); - ShowRank(pq.Pop()); - ShowRank(pq.Pop()); - ShowRank(pq.Pop()); - END Test; - + Rank* = POINTER TO RECORD + p-: LONGINT; (* Priority *) + value-: Boxes.Object + END; + + PQueue* = POINTER TO RECORD + a: POINTER TO ARRAY OF Rank; + size-: LONGINT; + END; + + PROCEDURE NewRank*(p: LONGINT; v: Boxes.Object): Rank; + VAR + r: Rank; + BEGIN + NEW(r);r.p := p;r.value := v; + RETURN r + END NewRank; + + PROCEDURE NewPQueue*(cap: LONGINT): PQueue; + VAR + pq: PQueue; + BEGIN + NEW(pq);pq.size := 0; + NEW(pq.a,cap);pq.a[0] := NewRank(MIN(INTEGER),NIL); + RETURN pq + END NewPQueue; + + PROCEDURE (pq: PQueue) Push*(r:Rank), NEW; + VAR + i: LONGINT; + BEGIN + INC(pq.size); + i := pq.size; + WHILE r.p < pq.a[i DIV 2].p DO + pq.a[i] := pq.a[i DIV 2];i := i DIV 2 + END; + pq.a[i] := r + END Push; + + PROCEDURE (pq: PQueue) Pop*(): Rank,NEW; + VAR + r,y: Rank; + i,j: LONGINT; + ok: BOOLEAN; + BEGIN + r := pq.a[1]; (* Priority object *) + y := pq.a[pq.size]; DEC(pq.size); i := 1; ok := FALSE; + WHILE (i <= pq.size DIV 2) & ~ok DO + j := i + 1; + IF (j < pq.size) & (pq.a[i].p > pq.a[j + 1].p) THEN INC(j) END; + IF y.p > pq.a[j].p THEN pq.a[i] := pq.a[j]; i := j ELSE ok := TRUE END + END; + pq.a[i] := y; + RETURN r + END Pop; + + PROCEDURE (pq: PQueue) IsEmpty*(): BOOLEAN,NEW; + BEGIN + RETURN pq.size = 0 + END IsEmpty; + + PROCEDURE Test*; + VAR + pq: PQueue; + r: Rank; + PROCEDURE ShowRank(r:Rank); + BEGIN + StdLog.Int(r.p);StdLog.String(":> ");StdLog.String(r.value.AsString());StdLog.Ln; + END ShowRank; + BEGIN + pq := NewPQueue(128); + pq.Push(NewRank(3,Boxes.NewString("Clear drains"))); + pq.Push(NewRank(4,Boxes.NewString("Feed cat"))); + pq.Push(NewRank(5,Boxes.NewString("Make tea"))); + pq.Push(NewRank(1,Boxes.NewString("Solve RC tasks"))); + pq.Push(NewRank(2,Boxes.NewString("Tax return"))); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + END Test; + END PQueues. diff --git a/Task/Priority-queue/Component-Pascal/priority-queue-2.component b/Task/Priority-queue/Component-Pascal/priority-queue-2.component index e7b62014af..9ca41c8e02 100644 --- a/Task/Priority-queue/Component-Pascal/priority-queue-2.component +++ b/Task/Priority-queue/Component-Pascal/priority-queue-2.component @@ -1,22 +1,22 @@ DEFINITION PQueues; - IMPORT Boxes; + IMPORT Boxes; - TYPE - PQueue = POINTER TO RECORD - size-: LONGINT; - (pq: PQueue) IsEmpty (): BOOLEAN, NEW; - (pq: PQueue) Pop (): Rank, NEW; - (pq: PQueue) Push (r: Rank), NEW - END; + TYPE + PQueue = POINTER TO RECORD + size-: LONGINT; + (pq: PQueue) IsEmpty (): BOOLEAN, NEW; + (pq: PQueue) Pop (): Rank, NEW; + (pq: PQueue) Push (r: Rank), NEW + END; - Rank = POINTER TO RECORD - p-: LONGINT; - value-: Boxes.Object - END; + Rank = POINTER TO RECORD + p-: LONGINT; + value-: Boxes.Object + END; - PROCEDURE NewPQueue (cap: LONGINT): PQueue; - PROCEDURE NewRank (p: LONGINT; v: Boxes.Object): Rank; - PROCEDURE Test; + PROCEDURE NewPQueue (cap: LONGINT): PQueue; + PROCEDURE NewRank (p: LONGINT; v: Boxes.Object): Rank; + PROCEDURE Test; END PQueues. diff --git a/Task/Priority-queue/Erlang/priority-queue.erl b/Task/Priority-queue/Erlang/priority-queue.erl index c86478d6a6..f6206698a1 100644 --- a/Task/Priority-queue/Erlang/priority-queue.erl +++ b/Task/Priority-queue/Erlang/priority-queue.erl @@ -7,22 +7,22 @@ create() -> gb_trees:empty(). insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ). peek( Queue ) -> - {_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ), - Element. + {_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ), + Element. task() -> - Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}], - Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ), - io:fwrite( "peek priority: ~p~n", [peek( Queue )] ), - lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ). + Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}], + Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ), + io:fwrite( "peek priority: ~p~n", [peek( Queue )] ), + lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ). top( Queue ) -> - {_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ), - {Element, New_queue}. + {_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ), + {Element, New_queue}. write_top( Q ) -> - {Element, New_queue} = top( Q ), - io:fwrite( "top priority: ~p~n", [Element] ), - New_queue. + {Element, New_queue} = top( Q ), + io:fwrite( "top priority: ~p~n", [Element] ), + New_queue. diff --git a/Task/Priority-queue/Groovy/priority-queue.groovy b/Task/Priority-queue/Groovy/priority-queue.groovy new file mode 100644 index 0000000000..22b31e377a --- /dev/null +++ b/Task/Priority-queue/Groovy/priority-queue.groovy @@ -0,0 +1,18 @@ +import groovy.transform.Canonical + +@Canonical +class Task implements Comparable { + int priority + String name + int compareTo(Task o) { priority <=> o?.priority } +} + +new PriorityQueue().with { + add new Task(priority: 3, name: 'Clear drains') + add new Task(priority: 4, name: 'Feed cat') + add new Task(priority: 5, name: 'Make tea') + add new Task(priority: 1, name: 'Solve RC tasks') + add new Task(priority: 2, name: 'Tax return') + + while (!empty) { println remove() } +} diff --git a/Task/Priority-queue/Haskell/priority-queue-2.hs b/Task/Priority-queue/Haskell/priority-queue-2.hs index 299d0926d5..db1392ee9b 100644 --- a/Task/Priority-queue/Haskell/priority-queue-2.hs +++ b/Task/Priority-queue/Haskell/priority-queue-2.hs @@ -1,27 +1,27 @@ data MinHeap a = Nil | MinHeap { v::a, cnt::Int, l::MinHeap a, r::MinHeap a } - deriving (Show, Eq) + deriving (Show, Eq) hPush :: (Ord a) => a -> MinHeap a -> MinHeap a hPush x Nil = MinHeap {v = x, cnt = 1, l = Nil, r = Nil} hPush x h = if x < vv -- insert element, try to keep the tree balanced - then if hLength (l h) <= hLength (r h) - then MinHeap { v=x, cnt=cc, l=hPush vv ll, r=rr } - else MinHeap { v=x, cnt=cc, l=ll, r=hPush vv rr } - else if hLength (l h) <= hLength (r h) - then MinHeap { v=vv, cnt=cc, l=hPush x ll, r=rr } - else MinHeap { v=vv, cnt=cc, l=ll, r=hPush x rr } - where (vv, cc, ll, rr) = (v h, 1 + cnt h, l h, r h) + then if hLength (l h) <= hLength (r h) + then MinHeap { v=x, cnt=cc, l=hPush vv ll, r=rr } + else MinHeap { v=x, cnt=cc, l=ll, r=hPush vv rr } + else if hLength (l h) <= hLength (r h) + then MinHeap { v=vv, cnt=cc, l=hPush x ll, r=rr } + else MinHeap { v=vv, cnt=cc, l=ll, r=hPush x rr } + where (vv, cc, ll, rr) = (v h, 1 + cnt h, l h, r h) hPop :: (Ord a) => MinHeap a -> (a, MinHeap a) hPop h = (v h, pq) where -- just pop, heed not the tree balance - pq | l h == Nil = r h - | r h == Nil = l h - | v (l h) <= v (r h) = let (vv,hh) = hPop (l h) in - MinHeap {v = vv, cnt = hLength hh + hLength (r h), - l = hh, r = r h} - | otherwise = let (vv,hh) = hPop (r h) in - MinHeap {v = vv, cnt = hLength hh + hLength (l h), - l = l h, r = hh} + pq | l h == Nil = r h + | r h == Nil = l h + | v (l h) <= v (r h) = let (vv,hh) = hPop (l h) in + MinHeap {v = vv, cnt = hLength hh + hLength (r h), + l = hh, r = r h} + | otherwise = let (vv,hh) = hPop (r h) in + MinHeap {v = vv, cnt = hLength hh + hLength (l h), + l = l h, r = hh} hLength :: (Ord a) => MinHeap a -> Int hLength Nil = 0 @@ -36,8 +36,8 @@ hToList = unfoldr f where f h = Just $ hPop h main = mapM_ print $ hToList $ hFromList [ - (3, "Clear drains"), - (4, "Feed cat"), - (5, "Make tea"), - (1, "Solve RC tasks"), - (2, "Tax return")] + (3, "Clear drains"), + (4, "Feed cat"), + (5, "Make tea"), + (1, "Solve RC tasks"), + (2, "Tax return")] diff --git a/Task/Priority-queue/Icon/priority-queue.icon b/Task/Priority-queue/Icon/priority-queue.icon index 6bb8dae255..2349a3d928 100644 --- a/Task/Priority-queue/Icon/priority-queue.icon +++ b/Task/Priority-queue/Icon/priority-queue.icon @@ -1,4 +1,4 @@ -import Utils # For Closure class +import Utils # For Closure class import Collections # For Heap (dense priority queue) class procedure main() diff --git a/Task/Priority-queue/Mercury/priority-queue.mercury b/Task/Priority-queue/Mercury/priority-queue.mercury new file mode 100644 index 0000000000..0dab7bec2c --- /dev/null +++ b/Task/Priority-queue/Mercury/priority-queue.mercury @@ -0,0 +1,35 @@ +:- module test_pqueue. + +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module int. +:- import_module list. +:- import_module pqueue. +:- import_module string. + +:- pred build_pqueue(pqueue(int,string)::in, pqueue(int,string)::out) is det. +build_pqueue(!PQ) :- + pqueue.insert(3, "Clear drains", !PQ), + pqueue.insert(4, "Feed cat", !PQ), + pqueue.insert(5, "Make tea", !PQ), + pqueue.insert(1, "Solve RC tasks", !PQ), + pqueue.insert(2, "Tax return", !PQ). + +:- pred display_pqueue(pqueue(int, string)::in, io::di, io::uo) is det. +display_pqueue(PQ, !IO) :- + ( pqueue.remove(K, V, PQ, PQO) -> + io.format("Key = %d, Value = %s\n", [i(K), s(V)], !IO), + display_pqueue(PQO, !IO) + ; + true + ). + +main(!IO) :- + build_pqueue(pqueue.init, PQO), + display_pqueue(PQO, !IO). diff --git a/Task/Priority-queue/Perl/priority-queue-1.pl b/Task/Priority-queue/Perl/priority-queue-1.pl index fcd8704fd5..0eeb9cd06e 100644 --- a/Task/Priority-queue/Perl/priority-queue-1.pl +++ b/Task/Priority-queue/Perl/priority-queue-1.pl @@ -6,9 +6,9 @@ my $h = new Heap::Priority; $h->highest_first(); # higher or lower number is more important $h->add(@$_) for ["Clear drains", 3], - ["Feed cat", 4], - ["Make tea", 5], - ["Solve RC tasks", 1], - ["Tax return", 2]; + ["Feed cat", 4], + ["Make tea", 5], + ["Solve RC tasks", 1], + ["Tax return", 2]; say while ($_ = $h->pop); diff --git a/Task/Priority-queue/Prolog/priority-queue.pro b/Task/Priority-queue/Prolog/priority-queue.pro index 3b177e627a..bfcfe652f4 100644 --- a/Task/Priority-queue/Prolog/priority-queue.pro +++ b/Task/Priority-queue/Prolog/priority-queue.pro @@ -1,28 +1,28 @@ priority-queue :- - TL0 = [3-'Clear drains', - 4-'Feed cat'], + TL0 = [3-'Clear drains', + 4-'Feed cat'], - % we can create a priority queue from a list - list_to_heap(TL0, Heap0), - - % alternatively we can start from an empty queue - % get from empty_heap/1. - - % now we add the other elements - add_to_heap(Heap0, 5, 'Make tea', Heap1), - add_to_heap(Heap1, 1, 'Solve RC tasks', Heap2), - add_to_heap(Heap2, 2, 'Tax return', Heap3), + % we can create a priority queue from a list + list_to_heap(TL0, Heap0), - % we list the content of the heap: - heap_to_list(Heap3, TL1), - writeln('Content of the queue'), maplist(writeln, TL1), - nl, + % alternatively we can start from an empty queue + % get from empty_heap/1. - % now we retrieve the minimum-priority pair - get_from_heap(Heap3, Priority, Key, Heap4), - format('Retrieve top of the queue : Priority ~w, Element ~w~n', [Priority, Key]), - nl, + % now we add the other elements + add_to_heap(Heap0, 5, 'Make tea', Heap1), + add_to_heap(Heap1, 1, 'Solve RC tasks', Heap2), + add_to_heap(Heap2, 2, 'Tax return', Heap3), - % we list the content of the heap: - heap_to_list(Heap4, TL2), - writeln('Content of the queue'), maplist(writeln, TL2). + % we list the content of the heap: + heap_to_list(Heap3, TL1), + writeln('Content of the queue'), maplist(writeln, TL1), + nl, + + % now we retrieve the minimum-priority pair + get_from_heap(Heap3, Priority, Key, Heap4), + format('Retrieve top of the queue : Priority ~w, Element ~w~n', [Priority, Key]), + nl, + + % we list the content of the heap: + heap_to_list(Heap4, TL2), + writeln('Content of the queue'), maplist(writeln, TL2). diff --git a/Task/Priority-queue/Python/priority-queue-1.py b/Task/Priority-queue/Python/priority-queue-1.py index ae72b9408b..1f25f961c4 100644 --- a/Task/Priority-queue/Python/priority-queue-1.py +++ b/Task/Priority-queue/Python/priority-queue-1.py @@ -1,13 +1,13 @@ >>> import queue >>> pq = queue.PriorityQueue() >>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")): - pq.put(item) + pq.put(item) + - >>> while not pq.empty(): - print(pq.get_nowait()) + print(pq.get_nowait()) + - (1, 'Solve RC tasks') (2, 'Tax return') (3, 'Clear drains') diff --git a/Task/Priority-queue/Python/priority-queue-3.py b/Task/Priority-queue/Python/priority-queue-3.py index 3b6c92b085..3513fecc40 100644 --- a/Task/Priority-queue/Python/priority-queue-3.py +++ b/Task/Priority-queue/Python/priority-queue-3.py @@ -2,9 +2,9 @@ >>> items = [(3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")] >>> heapify(items) >>> while items: - print(heappop(items)) + print(heappop(items)) + - (1, 'Solve RC tasks') (2, 'Tax return') (3, 'Clear drains') diff --git a/Task/Priority-queue/REXX/priority-queue.rexx b/Task/Priority-queue/REXX/priority-queue.rexx new file mode 100644 index 0000000000..788e6a7737 --- /dev/null +++ b/Task/Priority-queue/REXX/priority-queue.rexx @@ -0,0 +1,31 @@ +/*REXX pgm implements a priority queue; with insert/show/delete top task*/ +numeric digits 100; #=0; @.= /*big #, 0 tasks, null priority queue*/ +say '══════ inserting tasks.'; call .ins 3 'Clear drains' + call .ins 4 'Feed cat' + call .ins 5 'Make tea' + call .ins 1 'Solve RC tasks' + call .ins 2 'Tax return' + call .ins 6 'Relax' + call .ins 6 'Enjoy' +say '══════ showing tasks.'; call .show +say '══════ deletes top task.'; do # /*number of tasks. */ + say .del() /*delete top task. */ + end /* [↑] do top first.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────.INS subroutine─────────────────────*/ +.ins: procedure expose @. #; #=#+1; @.#=arg(1); return # /*entry,P,task.*/ +/*──────────────────────────────────.DEL subroutine─────────────────────*/ +.del: procedure expose @. #; parse arg p; if p=='' then p=.top() +x=@.p; @.p= /*delete the top task entry. */ +return x /*return task that was deleted. */ +/*──────────────────────────────────.SHOW subroutine────────────────────*/ +.show: procedure expose @. # + do j=1 for #; _=@.j; if _=='' then iterate; say _ + end /*j*/ /* [↑] show whole list or just 1.*/ +return +/*──────────────────────────────────.TOP subroutine─────────────────────*/ +.top: procedure expose @. #; top=; top#= + do j=1 for #; _=word(@.j,1); if _=='' then iterate + if top=='' | _>top then do; top=_; top#=j; end + end /*j*/ +return top# diff --git a/Task/Priority-queue/Run-BASIC/priority-queue.run b/Task/Priority-queue/Run-BASIC/priority-queue.run index 033e7f0b45..e5a5d8a45f 100644 --- a/Task/Priority-queue/Run-BASIC/priority-queue.run +++ b/Task/Priority-queue/Run-BASIC/priority-queue.run @@ -23,7 +23,7 @@ gosub [getQueue] what$ = " -------------- Delete Highest Priority ---------------------" mem$ = "DELETE FROM queue WHERE priority = (select max(q.priority) FROM queue as q)" -#mem execute(mem$) +#mem execute(mem$) what$ = " -------------- List Priority Sequence ---------------------" mem$ = "SELECT * FROM queue ORDER BY priority" @@ -33,13 +33,13 @@ end [getQueue] print what$ -#mem execute(mem$) +#mem execute(mem$) rows = #mem ROWCOUNT() print "Priority Description" for i = 1 to rows - #row = #mem #nextrow() - priority = #row priority() - descr$ = #row descr$() + #row = #mem #nextrow() + priority = #row priority() + descr$ = #row descr$() print priority;" ";descr$ next i RETURN diff --git a/Task/Problem-of-Apollonius/PL-I/problem-of-apollonius.pli b/Task/Problem-of-Apollonius/PL-I/problem-of-apollonius.pli new file mode 100644 index 0000000000..39b304ecdf --- /dev/null +++ b/Task/Problem-of-Apollonius/PL-I/problem-of-apollonius.pli @@ -0,0 +1,69 @@ +Apollonius: procedure options (main); /* 29 October 2013 */ + + define structure + 1 circle, + 2 x float (15), + 2 y float (15), + 2 radius float (15); + + declare (c1 , c2, c3, result) type (circle); + + c1.x = 0; c1.y = 0; c1.radius = 1; + c2.x = 4; c2.y = 0; c2.radius = 1; + c3.x = 2; c3.y = 4; c3.radius = 2; + + result = Solve_Apollonius(c1, c2, c3, 1, 1, 1); + put skip edit ('External tangent:', result.x, result.y, result.radius) (a, 3 f(12,8)); + + result = Solve_Apollonius(c1, c2, c3, -1, -1, -1); + put skip edit ('Internal tangent:', result.x, result.y, result.radius) (a, 3 f(12,8)); + + + +Solve_Apollonius: procedure (c1, c2, c3, s1, s2, s3) returns(type(circle)); + declare (c1, c2, c3) type(circle); + declare res type (circle); + declare (s1, s2, s3) fixed binary; + + declare ( + v11, v12, v13, v14, + v21, v22, v23, v24, + w12, w13, w14, + w22, w23, w24, + p, q, m, n, a, b, c, det) float (15); + + v11 = 2*c2.x - 2*c1.x; + v12 = 2*c2.y - 2*c1.y; + v13 = c1.x**2 - c2.x**2 + c1.y**2 - c2.y**2 - c1.radius**2 + c2.radius**2; + v14 = 2*s2*c2.radius - 2*s1*c1.radius; + + v21 = 2*c3.x - 2*c2.x; + v22 = 2*c3.y - 2*c2.y; + v23 = c2.x**2 - c3.x**2 + c2.y**2 - c3.y**2 - c2.radius**2 + c3.radius**2; + v24 = 2*s3*c3.radius - 2*s2*c2.radius; + + w12 = v12/v11; + w13 = v13/v11; + w14 = v14/v11; + + w22 = v22/v21-w12; + w23 = v23/v21-w13; + w24 = v24/v21-w14; + + p = -w23/w22; + q = w24/w22; + m = -w12*P - w13; + n = w14 - w12*q; + + a = n*n + q*q - 1; + b = 2*m*n - 2*n*c1.x + 2*p*q - 2*q*c1.y + 2*s1*c1.radius; + c = c1.x**2 + m*m - 2*m*c1.x + p*p + c1.y**2 - 2*p*c1.y - c1.radius**2; + + det = b*b - 4*a*c; + res.radius = (-b-sqrt(det)) / (2*a); + res.x = m + n*res.radius; + res.y = p + q*res.radius; + + return (res); +end Solve_Apollonius; +end Apollonius; diff --git a/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx b/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx index 0877cda329..42eecf76a6 100644 --- a/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx +++ b/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx @@ -1,14 +1,12 @@ /*REXX program to solve the problem of Apollonius, named after the */ /* Greek, Apollonius of Perga [Pergaeus] (circa 262 BC ──► 190 BC).*/ - -w=15; numeric digits w /*width used to display numbers. */ +w=20; numeric digits w-5 /*width used to display numbers. */ c1.x=0; c1.y=0; c1.r=1 c2.x=4; c2.y=0; c2.r=1 c3.x=2; c3.y=4; c3.r=2 call tell 'external tangent:', solveApollonius( 1, 1, 1) call tell 'internal tangent:', solveApollonius(-1,-1,-1) exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────SOLVEAPOLLONIUS subroutine──────────*/ /*───────────────────this code should be covered with a very think tarp.*/ solveApollonius: arg s1,s2,s3 /*internal or external tangent ? */ @@ -19,8 +17,8 @@ r1=c1.r; r2=c2.r; r3=c3.r va=2*x2-2*x1; vb=2*y2-2*y1; vc=x1*x1-x2*x2+y1*y1-y2*y2-r1*r1+r2*r2 vd=2*s2*r2-2*s1*r1; ve=2*x3-2*x2; vf=2*y3-2*y2 vg=x2*x2-x3*x3+y2*y2-y3*y3-r2*r2+r3*r3; vh=2*s3*r3-2*s2*r2 -vj=vb/va; vk=vc/va; vm=vd/va -vn=vf/ve-vj; vp=vg/ve-vk; vr=vh/ve-vm; +vj=vb/va; vk=vc/va; vm=vd/va +vn=vf/ve-vj; vp=vg/ve-vk; vr=vh/ve-vm p=-vp/vn q= vr/vn m=-vj*p-vk @@ -29,16 +27,15 @@ a=n*n+q*q-1 b=2*m*n-2*n*x1+2*p*q-2*q*y1+2*s1*r1 c=x1*x1+m*m-2*m*x1+p*p+y1*y1-2*p*y1-r1*r1 _=b*b-4*a*c; $.r=(-b-sqrt(_))/(a+a); $.x=m+n*$.r; $.y=p+q*$.r -return $.x $.y $.r /*return with the money. */ - -/*──────────────────────────────────SQRT subroutine──────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0;d=digits();numeric digits 11 - g=.sqGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end; do k=j+5 to 0 by -1 - if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;numeric digits d;return g/1 - -.sqGuess: if x<0 then say 'negative number' x; numeric form; m.=11 - p=d+d%4+2; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 - +numeric digits digits()%3 /*reset DIGITS to the original.*/ +return $.x+0 $.y+0 $.r+0 /*return with 3 args, normalized.*/ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +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*/ + numeric digits m.0; return (g/1)i /*──────────────────────────────────TELL subroutine─────────────────────*/ tell: parse arg _,a b c; say _ left(a/1,w) left(b/1,w) left(c/1,w); return /*dividing by 1 reformats #s to W*/ diff --git a/Task/Program-name/D/program-name-4.d b/Task/Program-name/D/program-name-4.d new file mode 100644 index 0000000000..327a1add40 --- /dev/null +++ b/Task/Program-name/D/program-name-4.d @@ -0,0 +1,9 @@ +// thisExePath function was introduced in D 2.064 (November 5, 2013) + +import std.file; +import std.stdio; + +void main(string[] args) +{ + writeln("Program: ", thisExePath()); +} diff --git a/Task/Program-name/Deja-Vu/program-name.djv b/Task/Program-name/Deja-Vu/program-name.djv new file mode 100644 index 0000000000..bc973d8a40 --- /dev/null +++ b/Task/Program-name/Deja-Vu/program-name.djv @@ -0,0 +1 @@ +!print( "Name of this file: " get-from !args 0 ) diff --git a/Task/Program-name/Make/program-name.make b/Task/Program-name/Make/program-name.make new file mode 100644 index 0000000000..d5d6a1e140 --- /dev/null +++ b/Task/Program-name/Make/program-name.make @@ -0,0 +1,4 @@ +NAME=$(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) + +all: + @echo $(NAME) diff --git a/Task/Program-name/TXR/program-name.txr b/Task/Program-name/TXR/program-name.txr new file mode 100644 index 0000000000..e869d07d59 --- /dev/null +++ b/Task/Program-name/TXR/program-name.txr @@ -0,0 +1,2 @@ +#!/usr/local/bin/txr +@(bind my-name @*self-path*) diff --git a/Task/Pythagorean-triples/C/pythagorean-triples-1.c b/Task/Pythagorean-triples/C/pythagorean-triples-1.c index 2fc5d14db2..54c0740a73 100644 --- a/Task/Pythagorean-triples/C/pythagorean-triples-1.c +++ b/Task/Pythagorean-triples/C/pythagorean-triples-1.c @@ -6,41 +6,41 @@ typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { - ulong t; - while (n) { t = n; n = m % n; m = t; } - return m; + ulong t; + while (n) { t = n; n = m % n; m = t; } + return m; } int main() { - ulong a, b, c, pytha = 0, prim = 0, max_p = 100; - xint aa, bb, cc; + ulong a, b, c, pytha = 0, prim = 0, max_p = 100; + xint aa, bb, cc; - for (a = 1; a <= max_p / 3; a++) { - aa = (xint)a * a; - printf("a = %lu\r", a); /* show that we are working */ - fflush(stdout); + for (a = 1; a <= max_p / 3; a++) { + aa = (xint)a * a; + printf("a = %lu\r", a); /* show that we are working */ + fflush(stdout); - /* max_p/2: valid limit, because one side of triangle - * must be less than the sum of the other two - */ - for (b = a + 1; b < max_p/2; b++) { - bb = (xint)b * b; - for (c = b + 1; c < max_p/2; c++) { - cc = (xint)c * c; - if (aa + bb < cc) break; - if (a + b + c > max_p) break; + /* max_p/2: valid limit, because one side of triangle + * must be less than the sum of the other two + */ + for (b = a + 1; b < max_p/2; b++) { + bb = (xint)b * b; + for (c = b + 1; c < max_p/2; c++) { + cc = (xint)c * c; + if (aa + bb < cc) break; + if (a + b + c > max_p) break; - if (aa + bb == cc) { - pytha++; - if (gcd(a, b) == 1) prim++; - } - } - } - } + if (aa + bb == cc) { + pytha++; + if (gcd(a, b) == 1) prim++; + } + } + } + } - printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", - max_p, pytha, prim); + printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", + max_p, pytha, prim); - return 0; + return 0; } diff --git a/Task/Pythagorean-triples/C/pythagorean-triples-3.c b/Task/Pythagorean-triples/C/pythagorean-triples-3.c index 5b2c8c35ce..2371ddcc53 100644 --- a/Task/Pythagorean-triples/C/pythagorean-triples-3.c +++ b/Task/Pythagorean-triples/C/pythagorean-triples-3.c @@ -8,41 +8,41 @@ typedef unsigned long xint; xint total, prim, max_peri; xint U[][9] = {{ 1, -2, 2, 2, -1, 2, 2, -2, 3}, - { 1, 2, 2, 2, 1, 2, 2, 2, 3}, - {-1, 2, 2, -2, 1, 2, -2, 2, 3}}; + { 1, 2, 2, 2, 1, 2, 2, 2, 3}, + {-1, 2, 2, -2, 1, 2, -2, 2, 3}}; void new_tri(xint in[]) { - int i; - xint t[3], p = in[0] + in[1] + in[2]; + int i; + xint t[3], p = in[0] + in[1] + in[2]; - if (p > max_peri) return; + if (p > max_peri) return; - prim ++; + prim ++; - /* for every primitive triangle, its multiples would be right-angled too; - * count them up to the max perimeter */ - total += max_peri / p; + /* for every primitive triangle, its multiples would be right-angled too; + * count them up to the max perimeter */ + total += max_peri / p; - /* recursively produce next tier by multiplying the matrices */ - for (i = 0; i < 3; i++) { - t[0] = U[i][0] * in[0] + U[i][1] * in[1] + U[i][2] * in[2]; - t[1] = U[i][3] * in[0] + U[i][4] * in[1] + U[i][5] * in[2]; - t[2] = U[i][6] * in[0] + U[i][7] * in[1] + U[i][8] * in[2]; - new_tri(t); - } + /* recursively produce next tier by multiplying the matrices */ + for (i = 0; i < 3; i++) { + t[0] = U[i][0] * in[0] + U[i][1] * in[1] + U[i][2] * in[2]; + t[1] = U[i][3] * in[0] + U[i][4] * in[1] + U[i][5] * in[2]; + t[2] = U[i][6] * in[0] + U[i][7] * in[1] + U[i][8] * in[2]; + new_tri(t); + } } int main() { - xint seed[3] = {3, 4, 5}; + xint seed[3] = {3, 4, 5}; - for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) { - total = prim = 0; - new_tri(seed); + for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) { + total = prim = 0; + new_tri(seed); - printf( "Up to "FMT": "FMT" triples, "FMT" primitives.\n", - max_peri, total, prim); - } - return 0; + printf( "Up to "FMT": "FMT" triples, "FMT" primitives.\n", + max_peri, total, prim); + } + return 0; } diff --git a/Task/Pythagorean-triples/C/pythagorean-triples-5.c b/Task/Pythagorean-triples/C/pythagorean-triples-5.c index f365882c1a..e9f610bb51 100644 --- a/Task/Pythagorean-triples/C/pythagorean-triples-5.c +++ b/Task/Pythagorean-triples/C/pythagorean-triples-5.c @@ -10,42 +10,42 @@ xint total, prim, max_peri; void new_tri(xint in[]) { - int i; - xint t[3], p; - xint x = in[0], y = in[1], z = in[2]; + int i; + xint t[3], p; + xint x = in[0], y = in[1], z = in[2]; -recur: p = x + y + z; - if (p > max_peri) return; +recur: p = x + y + z; + if (p > max_peri) return; - prim ++; - total += max_peri / p; + prim ++; + total += max_peri / p; - t[0] = x - 2 * y + 2 * z; - t[1] = 2 * x - y + 2 * z; - t[2] = t[1] - y + z; - new_tri(t); + t[0] = x - 2 * y + 2 * z; + t[1] = 2 * x - y + 2 * z; + t[2] = t[1] - y + z; + new_tri(t); - t[0] += 4 * y; - t[1] += 2 * y; - t[2] += 4 * y; - new_tri(t); + t[0] += 4 * y; + t[1] += 2 * y; + t[2] += 4 * y; + new_tri(t); - z = t[2] - 4 * x; - y = t[1] - 4 * x; - x = t[0] - 2 * x; - goto recur; + z = t[2] - 4 * x; + y = t[1] - 4 * x; + x = t[0] - 2 * x; + goto recur; } int main() { - xint seed[3] = {3, 4, 5}; + xint seed[3] = {3, 4, 5}; - for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) { - total = prim = 0; - new_tri(seed); + for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) { + total = prim = 0; + new_tri(seed); - printf( "Up to "FMT": "FMT" triples, "FMT" primitives.\n", - max_peri, total, prim); - } - return 0; + printf( "Up to "FMT": "FMT" triples, "FMT" primitives.\n", + max_peri, total, prim); + } + return 0; } diff --git a/Task/Pythagorean-triples/Common-Lisp/pythagorean-triples-1.lisp b/Task/Pythagorean-triples/Common-Lisp/pythagorean-triples-1.lisp index cc1b0ec5fe..7457f3b6bd 100644 --- a/Task/Pythagorean-triples/Common-Lisp/pythagorean-triples-1.lisp +++ b/Task/Pythagorean-triples/Common-Lisp/pythagorean-triples-1.lisp @@ -1,18 +1,18 @@ (defun mmul (a b) (loop for x in a collect - (loop for y in x - for z in b sum (* y z)))) + (loop for y in x + for z in b sum (* y z)))) (defun count-tri (lim) (let ((prim 0) (cnt 0)) (labels ((count1 (tr) (let ((peri (reduce #'+ tr))) - (when (<= peri lim) - (incf prim) - (incf cnt (truncate lim peri)) - (count1 (mmul '(( 1 -2 2) ( 2 -1 2) ( 2 -2 3)) tr)) - (count1 (mmul '(( 1 2 2) ( 2 1 2) ( 2 2 3)) tr)) - (count1 (mmul '((-1 2 2) (-2 1 2) (-2 2 3)) tr)))))) + (when (<= peri lim) + (incf prim) + (incf cnt (truncate lim peri)) + (count1 (mmul '(( 1 -2 2) ( 2 -1 2) ( 2 -2 3)) tr)) + (count1 (mmul '(( 1 2 2) ( 2 1 2) ( 2 2 3)) tr)) + (count1 (mmul '((-1 2 2) (-2 1 2) (-2 2 3)) tr)))))) (count1 '(3 4 5)) (format t "~a: ~a prim, ~a all~%" lim prim cnt)))) diff --git a/Task/Pythagorean-triples/Erlang/pythagorean-triples.erl b/Task/Pythagorean-triples/Erlang/pythagorean-triples.erl index 6a86c839b8..887294727e 100644 --- a/Task/Pythagorean-triples/Erlang/pythagorean-triples.erl +++ b/Task/Pythagorean-triples/Erlang/pythagorean-triples.erl @@ -4,7 +4,7 @@ -module(triples). -export([main/1]). -%% Transformations t1, t2 and t3 to generate new triples +%% Transformations t1, t2 and t3 to generate new triples t1(A, B, C) -> {A-2*B+2*C, 2*A-B+2*C, 2*A-2*B+3*C}. t2(A, B, C) -> @@ -17,10 +17,10 @@ count_triples(A, B, C, Tot_acc, Cnt_acc, Max_perimeter) when (A+B+C) =< Max_peri Tot1 = Tot_acc + Max_perimeter div (A+B+C), {A1, B1, C1} = t1(A, B, C), {Tot2, Cnt2} = count_triples(A1, B1, C1, Tot1, Cnt_acc+1, Max_perimeter), - + {A2, B2, C2} = t2(A, B, C), {Tot3, Cnt3} = count_triples(A2, B2, C2, Tot2, Cnt2, Max_perimeter), - + {A3, B3, C3} = t3(A, B, C), {Tot4, Cnt4} = count_triples(A3, B3, C3, Tot3, Cnt3, Max_perimeter), {Tot4, Cnt4}; diff --git a/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs b/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs index ed08a31726..6001ba71e5 100644 --- a/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs +++ b/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs @@ -1,15 +1,15 @@ triangles :: Int -> [[Int]] triangles max_peri | max_peri < 12 = [] - | otherwise = concat tiers where - tiers = takeWhile (not.null) $ iterate tier [[3,4,5]] - tier = concatMap (filter ((<=max_peri).sum).tmul) - tmul t = map (map (sum . zipWith (*) t)) - [[[ 1,-2,2],[ 2,-1,2],[ 2,-2,3]], - [[ 1, 2,2],[ 2, 1,2],[ 2, 2,3]], - [[-1, 2,2],[-2, 1,2],[-2, 2,3]]] + | otherwise = concat tiers where + tiers = takeWhile (not.null) $ iterate tier [[3,4,5]] + tier = concatMap (filter ((<=max_peri).sum).tmul) + tmul t = map (map (sum . zipWith (*) t)) + [[[ 1,-2,2],[ 2,-1,2],[ 2,-2,3]], + [[ 1, 2,2],[ 2, 1,2],[ 2, 2,3]], + [[-1, 2,2],[-2, 1,2],[-2, 2,3]]] triangle_count max_p = (length t, sum $ map ((max_p `div`).sum) t) - where t = triangles max_p + where t = triangles max_p main = mapM_ putStrLn $ - map (\n -> show n ++ " " ++ show (triangle_count n)) $ map (10^) [1..] + map (\n -> show n ++ " " ++ show (triangle_count n)) $ map (10^) [1..] diff --git a/Task/Pythagorean-triples/Java/pythagorean-triples-2.java b/Task/Pythagorean-triples/Java/pythagorean-triples-2.java index be94ccdf07..717b1f0203 100644 --- a/Task/Pythagorean-triples/Java/pythagorean-triples-2.java +++ b/Task/Pythagorean-triples/Java/pythagorean-triples-2.java @@ -29,10 +29,10 @@ public class Triples{ public static void main(String[] args){ for(long i = 100; i <= 10000000; i*=10){ - LIMIT = BigInteger.valueOf(i); - primCount = tripCount = 0; - parChild(THREE, FOUR, FIVE); - System.out.println(LIMIT + ": " + tripCount + " triples, " + primCount + " primitive."); + LIMIT = BigInteger.valueOf(i); + primCount = tripCount = 0; + parChild(THREE, FOUR, FIVE); + System.out.println(LIMIT + ": " + tripCount + " triples, " + primCount + " primitive."); } } } diff --git a/Task/Pythagorean-triples/MATLAB/pythagorean-triples.m b/Task/Pythagorean-triples/MATLAB/pythagorean-triples.m index 3d780f21a3..c308d7a388 100644 --- a/Task/Pythagorean-triples/MATLAB/pythagorean-triples.m +++ b/Task/Pythagorean-triples/MATLAB/pythagorean-triples.m @@ -10,7 +10,7 @@ N= 100; z = sqrt(x.^2+y.^2); ix = (z+x+y<100) & (x < y) & (y < z); - p = find(gcd(x(ix),y(ix))==1); % find primitive triples + p = find(gcd(x(ix),y(ix))==1); % find primitive triples printf('There are %i Pythagorean Triples and %i primitive triples with a perimeter smaller than %i.\n',... sum(ix), length(p), N); diff --git a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 index 772591bfc4..755bb92d39 100644 --- a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 +++ b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 @@ -5,7 +5,7 @@ sub triples($limit) { sub oyako($a, $b, $c) { my $perim = $a + $b + $c; return if $perim > $limit; - ++$primitive; $civilized += $limit div $perim; + ++$primitive; $civilized += $limit div $perim; oyako( $a - 2*$b + 2*$c, 2*$a - $b + 2*$c, 2*$a - 2*$b + 3*$c); oyako( $a + 2*$b + 2*$c, 2*$a + $b + 2*$c, 2*$a + 2*$b + 3*$c); oyako(-$a + 2*$b + 2*$c, -2*$a + $b + 2*$c, -2*$a + 2*$b + 3*$c); diff --git a/Task/Pythagorean-triples/Perl/pythagorean-triples.pl b/Task/Pythagorean-triples/Perl/pythagorean-triples.pl new file mode 100644 index 0000000000..11b38b740a --- /dev/null +++ b/Task/Pythagorean-triples/Perl/pythagorean-triples.pl @@ -0,0 +1,26 @@ +sub gcd { + my ($n, $m) = @_; + while($n){ + my $t = $n; + $n = $m % $n; + $m = $t; + } + return $m; +} + +sub tripel { + my $pmax = shift; + my $prim = 0; + my $count = 0; + my $nmax = sqrt($pmax)/2; + for( my $n=1; $n<=$nmax; $n++ ) { + for( my $m=$n+1; (my $p = 2*$m*($m+$n)) <= $pmax; $m+=2 ) { + next unless 1==gcd($m,$n); + $prim++; + $count += int $pmax/$p; + } + } + printf "Max. perimeter: %d, Total: %d, Primitive: %d\n", $pmax, $count, $prim; +} + +tripel 10**$_ for 1..8; diff --git a/Task/Pythagorean-triples/Python/pythagorean-triples-2.py b/Task/Pythagorean-triples/Python/pythagorean-triples-2.py index 8a0a6f222e..5727416a26 100644 --- a/Task/Pythagorean-triples/Python/pythagorean-triples-2.py +++ b/Task/Pythagorean-triples/Python/pythagorean-triples-2.py @@ -2,13 +2,13 @@ from sys import setrecursionlimit setrecursionlimit(2000) # 2000 ought to be big enough for everybody def triples(lim, a = 3, b = 4, c = 5): - l = a + b + c - if l > lim: return (0, 0) - return reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), [ - (1, lim / l), - triples(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c), - triples(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c), - triples(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c) ]) + l = a + b + c + if l > lim: return (0, 0) + return reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), [ + (1, lim / l), + triples(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c), + triples(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c), + triples(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c) ]) for peri in [10 ** e for e in range(1, 8)]: - print peri, triples(peri) + print peri, triples(peri) diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx index 72c4cb2afa..66c3e56a6a 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx @@ -1,28 +1,28 @@ /*REXX pgm counts number of Pythagorean triples that exist given a max */ /* perimeter of N, and also counts how many of them are primitives.*/ trips=0; prims=0 -parse arg N .; if N=='' then n=100 /*get "N". If none, then assume.*/ +parse arg N .; if N=='' then n=100 /*get "N". If none, then assume.*/ - do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ + do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ do b=a+1 /*triangle can't be isosceles. */ ab=a+b /*compute partial perimeter. */ - if ab>=n then iterate a /*a+b>perimeter? Try different A*/ + if ab>=n then iterate a /*a+b>perimeter? Try different A*/ aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ - do c=b+1; cc=c*c /*3rd side: also compute c² */ + do c=b+1; cc=c*c /*3rd side: also compute c² */ if ab+c>n then iterate a /*a+b+c > perimeter? Try diff A.*/ if cc>aabb then iterate b /*c² > a²+b² ? Try different B.*/ if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ trips=trips+1 /*eureka. */ - prims=prims+(gcd(a,b)==1) /*is this triple a primative ? */ + prims=prims+(gcd(a,b)==1) /*is this triple a primitive? */ end /*a*/ end /*b*/ end /*c*/ -say 'max perimeter = 'N, /*show a single line of output. */ - left('',7) "Pythagorean triples =" trips, /*left('',0) ≡ 7 blanks.*/ - left('',7) 'primitives =' prims +say 'max perimeter =' N, /*show a single line of output. */ + left('',7) "Pythagorean triples =" trips, /*left('',0)≡7 blanks.*/ + left('',7) 'primitives =' prims exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────GCD subroutine──────────────────────*/ gcd: procedure; arg x,y; do until _==0; _=x//y; x=y; y=_; end; return x diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx index 1ed4d94266..6a6be76599 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx @@ -1,35 +1,35 @@ /*REXX pgm counts number of Pythagorean triples that exist given a max */ -/* perimeter of N, and also counts how many of them are primatives.*/ +/* perimeter of N, and also counts how many of them are primitives.*/ @.=0; trips=0; prims=0 parse arg N .; if N=='' then n=100 /*get "N". If none, then assume.*/ - do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ - aEven=a//2==0 + do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ + aEven= a//2==0 do b=a+1 by 1+aEven /*triangle can't be isosceles. */ ab=a+b /*compute partial perimeter. */ - if ab>=n then iterate a /*a+b>perimeter? Try different A*/ + if ab>=n then iterate a /*a+b>perimeter? Try different A*/ aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ - do c=b+1; cc=c*c /*3rd side: also compute c² */ - if aEven then if c//2==0 then iterate + do c=b+1; cc=c*c /*3rd side: also compute c² */ + if aEven then if c//2==0 then iterate if ab+c>n then iterate a /*a+b+c > perimeter? Try diff A.*/ if cc>aabb then iterate b /*c² > a²+b² ? Try different B.*/ if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ - if @.a.b.c then iterate + if @.a.b.c then iterate trips=trips+1 /*eureka. */ prims=prims+1 /*count this primitive triple. */ do m=2; !a=a*m; !b=b*m; !c=c*m /*gen non-primitives.*/ - if !a+!b+!c>N then leave /*is this multiple a triple ? */ + if !a+!b+!c>N then leave /*is this multiple a triple ? */ trips=trips+1 /*yuppers, then we found another.*/ - if m//2 then @.!a.!b.!c=1 /*don't mark if an even multiple.*/ + if m//2 then @.!a.!b.!c=1 /*don't mark if an even multiple.*/ end /*m*/ end /*d*/ end /*b*/ end /*a*/ -say 'max perimeter = 'N, /*show a single line of output. */ +say 'max perimeter =' N, /*show a single line of output. */ left('',7) "Pythagorean triples =" trips, /*left('',0) = 7 blanks.*/ - left('',7) 'primitives =' prims + left('',7) 'primitives =' prims /*stick a fork in it, we're done.*/ diff --git a/Task/Pythagorean-triples/Tcl/pythagorean-triples.tcl b/Task/Pythagorean-triples/Tcl/pythagorean-triples.tcl index 83bc140337..380b756a7e 100644 --- a/Task/Pythagorean-triples/Tcl/pythagorean-triples.tcl +++ b/Task/Pythagorean-triples/Tcl/pythagorean-triples.tcl @@ -2,20 +2,20 @@ proc countPythagoreanTriples {limit} { lappend q 3 4 5 set idx [set count [set prim 0]] while {$idx < [llength $q]} { - set a [lindex $q $idx] - set b [lindex $q [incr idx]] - set c [lindex $q [incr idx]] - incr idx - if {$a + $b + $c <= $limit} { - incr prim - for {set i 1} {$i*$a+$i*$b+$i*$c <= $limit} {incr i} { - incr count - } - lappend q \ - [expr {$a + 2*($c-$b)}] [expr {2*($a+$c) - $b}] [expr {2*($a-$b) + 3*$c}] \ - [expr {$a + 2*($b+$c)}] [expr {2*($a+$c) + $b}] [expr {2*($a+$b) + 3*$c}] \ - [expr {2*($b+$c) - $a}] [expr {2*($c-$a) + $b}] [expr {2*($b-$a) + 3*$c}] - } + set a [lindex $q $idx] + set b [lindex $q [incr idx]] + set c [lindex $q [incr idx]] + incr idx + if {$a + $b + $c <= $limit} { + incr prim + for {set i 1} {$i*$a+$i*$b+$i*$c <= $limit} {incr i} { + incr count + } + lappend q \ + [expr {$a + 2*($c-$b)}] [expr {2*($a+$c) - $b}] [expr {2*($a-$b) + 3*$c}] \ + [expr {$a + 2*($b+$c)}] [expr {2*($a+$c) + $b}] [expr {2*($a+$b) + 3*$c}] \ + [expr {2*($b+$c) - $a}] [expr {2*($c-$a) + $b}] [expr {2*($b-$a) + 3*$c}] + } } return [list $count $prim] } diff --git a/Task/QR-decomposition/Julia/qr-decomposition.julia b/Task/QR-decomposition/Julia/qr-decomposition.julia new file mode 100644 index 0000000000..dbf961d4ac --- /dev/null +++ b/Task/QR-decomposition/Julia/qr-decomposition.julia @@ -0,0 +1 @@ +Q, R = qr([12 -51 4; 6 167 -68; -4 24 -41]) diff --git a/Task/Quaternion-type/00DESCRIPTION b/Task/Quaternion-type/00DESCRIPTION index d5f351843e..7bd61e5f08 100644 --- a/Task/Quaternion-type/00DESCRIPTION +++ b/Task/Quaternion-type/00DESCRIPTION @@ -2,8 +2,9 @@ A complex number has a real and complex part written sometimes as a + bi, where a and b stand for real numbers and i stands for the square root of minus 1. An example of a complex number might be -3 + 2i, where the real part, a is -3.0 and the complex part, b is +2.0. -A quaternion has one real part and ''three'' imaginary parts, i, j, and k. A quaternion might be written as a + bi + cj + dk. In this numbering system, ii = jj = kk = ijk = -1. The order of multiplication is important, as, in general, for two quaternions q1 and q2; q1q2 != q2q1. An example of a quaternion might be 1 +2i +3j +4k +A quaternion has one real part and ''three'' imaginary parts, i, j, and k. A quaternion might be written as a + bi + cj + dk. In this numbering system, ii = jj = kk = ijk = -1. The order of multiplication is important, as, in general, for two quaternions q1 and q2; q1q2 != q2q1. +An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. So the example above would be written as (1, 2, 3, 4) '''Task Description'''
diff --git a/Task/Quaternion-type/GAP/quaternion-type.gap b/Task/Quaternion-type/GAP/quaternion-type.gap index 2cad375014..94fc6c2588 100644 --- a/Task/Quaternion-type/GAP/quaternion-type.gap +++ b/Task/Quaternion-type/GAP/quaternion-type.gap @@ -9,10 +9,23 @@ b := BasisVectors(Basis(A)); q := [1, 2, 3, 4]*b; # e+(2)*i+(3)*j+(4)*k -# Computing norm may be difficult, since the result would be in a quadratic field (Sqrt exists in GAP, is quite unusual, see ?E in GAP, and the following example +# Conjugate +ComplexConjugate(q); +# e+(-2)*i+(-3)*j+(-4)*k + +# Division +1/q; +# (1/30)*e+(-1/15)*i+(-1/10)*j+(-2/15)*k + +# Computing norm may be difficult, since the result would be in a quadratic field. +# Sqrt exists in GAP, but it is quite unusual: see ?E in GAP documentation, and the following example Sqrt(5/3); # 1/3*E(60)^7+1/3*E(60)^11-1/3*E(60)^19-1/3*E(60)^23-1/3*E(60)^31+1/3*E(60)^43-1/3*E(60)^47+1/3*E(60)^59 +# However, the square of the norm is easy to compute +q*ComplexConjugate(q); +# (30)*e + q1 := [2, 3, 4, 5]*b; # (2)*e+(3)*i+(4)*j+(5)*k @@ -23,17 +36,75 @@ q1*q2 - q2*q1; # (-2)*i+(4)*j+(-2)*k # Can't add directly to a rational, one must make a quaternion of it -r:=5/3*b[1]; +r := 5/3*b[1]; # (5/3)*e r + q; # (8/3)*e+(2)*i+(3)*j+(4)*k # For multiplication, no problem (we are in an algebra over rationals !) -r * q; +r*q; # (5/3)*e+(10/3)*i+(5)*j+(20/3)*k -5/3 * q; +5/3*q; # (5/3)*e+(10/3)*i+(5)*j+(20/3)*k # Negative -q; (-1)*e+(-2)*i+(-3)*j+(-4)*k + + +# While quaternions are built-in, you can define an algebra in GAP by specifying it's multiplication table. +# See tutorial, p. 60, and reference of the functions used below. + +# A multiplication table of dimension 4. + +T := EmptySCTable(4, 0); +SetEntrySCTable(T, 1, 1, [1, 1]); +SetEntrySCTable(T, 1, 2, [1, 2]); +SetEntrySCTable(T, 1, 3, [1, 3]); +SetEntrySCTable(T, 1, 4, [1, 4]); +SetEntrySCTable(T, 2, 1, [1, 2]); +SetEntrySCTable(T, 2, 2, [-1, 1]); +SetEntrySCTable(T, 2, 3, [1, 4]); +SetEntrySCTable(T, 2, 4, [-1, 3]); +SetEntrySCTable(T, 3, 1, [1, 3]); +SetEntrySCTable(T, 3, 2, [-1, 4]); +SetEntrySCTable(T, 3, 3, [-1, 1]); +SetEntrySCTable(T, 3, 4, [1, 2]); +SetEntrySCTable(T, 4, 1, [1, 4]); +SetEntrySCTable(T, 4, 2, [1, 3]); +SetEntrySCTable(T, 4, 3, [-1, 2]); +SetEntrySCTable(T, 4, 4, [-1, 1]); + +A := AlgebraByStructureConstants(Rationals, T, ["e", "i", "j", "k"]); +b := GeneratorsOfAlgebra(A); + +IsAssociative(A); +# true + +IsCommutative(A); +# false + +# Then, like above + +q := [1, 2, 3, 4]*b; +# e+(2)*i+(3)*j+(4)*k + +# However, as is, GAP does not know division or conjugate on this algebra. +# QuaternionAlgebra is useful as well for extensions of rationals, +# and this one _has_ conjugate and division, as seen previously. + +# Try this on Q[z] where z is the square root of 5 (in GAP it's ER(5)) +F := FieldByGenerators([ER(5)]); +A := QuaternionAlgebra(F); +b := GeneratorsOfAlgebra(A); + +q := [1, 2, 3, 4]*b; +# e+(2)*i+(3)*j+(4)*k + +# Conjugate and division + +ComplexConjugate(q); +# e+(-2)*i+(-3)*j+(-4)*k + +1/q; +# (1/30)*e+(-1/15)*i+(-1/10)*j+(-2/15)*k diff --git a/Task/Quaternion-type/Julia/quaternion-type-1.julia b/Task/Quaternion-type/Julia/quaternion-type-1.julia new file mode 100644 index 0000000000..34e0abd8d4 --- /dev/null +++ b/Task/Quaternion-type/Julia/quaternion-type-1.julia @@ -0,0 +1,48 @@ +import Base: convert, promote_rule, show, real, imag, conj, abs, abs2, inv, +, -, /, * + +immutable Quaternion{T<:Real} <: Number + q0::T + q1::T + q2::T + q3::T +end + +Quaternion(q0::Real,q1::Real,q2::Real,q3::Real) = Quaternion(promote(q0,q1,q2,q3)...) + +convert{T}(::Type{Quaternion{T}}, x::Real) = + Quaternion(convert(T,x), zero(T), zero(T), zero(T)) +convert{T}(::Type{Quaternion{T}}, z::Complex) = + Quaternion(convert(T,real(z)), convert(T,imag(z)), zero(T), zero(T)) +convert{T}(::Type{Quaternion{T}}, z::Quaternion) = + Quaternion(convert(T,z.q0), convert(T,z.q1), convert(T,z.q2), convert(T,z.q3)) + +promote_rule{T,S}(::Type{Complex{T}}, ::Type{Quaternion{S}}) = Quaternion{promote_type(T,S)} +promote_rule{T<:Real,S}(::Type{T}, ::Type{Quaternion{S}}) = Quaternion{promote_type(T,S)} +promote_rule{T,S}(::Type{Quaternion{T}}, ::Type{Quaternion{S}}) = Quaternion{promote_type(T,S)} + +function show(io::IO, z::Quaternion) + pm(x) = x < 0 ? " - $(-x)" : " + $x" + print(io, z.q0, pm(z.q1), "i", pm(z.q2), "j", pm(z.q3), "k") +end + +real(z::Quaternion) = z.q0 +imag(z::Quaternion) = z.q1 + +conj(z::Quaternion) = Quaternion(z.q0, -z.q1, -z.q2, -z.q3) +abs(z::Quaternion) = sqrt(z.q0*z.q0 + z.q1*z.q1 + z.q2*z.q2 + z.q3*z.q3) +abs2(z::Quaternion) = z.q0*z.q0 + z.q1*z.q1 + z.q2*z.q2 + z.q3*z.q3 +inv(z::Quaternion) = conj(z)/abs2(z) + +(-)(z::Quaternion) = Quaternion(-z.q0, -z.q1, -z.q2, -z.q3) + +(/)(z::Quaternion, x::Real) = Quaternion(z.q0/x, z.q1/x, z.q2/x, z.q3/x) + +(+)(z::Quaternion, w::Quaternion) = Quaternion(z.q0 + w.q0, z.q1 + w.q1, + z.q2 + w.q2, z.q3 + w.q3) +(-)(z::Quaternion, w::Quaternion) = Quaternion(z.q0 - w.q0, z.q1 - w.q1, + z.q2 - w.q2, z.q3 - w.q3) +(*)(z::Quaternion, w::Quaternion) = Quaternion(z.q0*w.q0 - z.q1*w.q1 - z.q2*w.q2 - z.q3*w.q3, + z.q0*w.q1 + z.q1*w.q0 + z.q2*w.q3 - z.q3*w.q2, + z.q0*w.q2 - z.q1*w.q3 + z.q2*w.q0 + z.q3*w.q1, + z.q0*w.q3 + z.q1*w.q2 - z.q2*w.q1 + z.q3*w.q0) +(/)(z::Quaternion, w::Quaternion) = z*inv(w) diff --git a/Task/Quaternion-type/Julia/quaternion-type-2.julia b/Task/Quaternion-type/Julia/quaternion-type-2.julia new file mode 100644 index 0000000000..b7da677917 --- /dev/null +++ b/Task/Quaternion-type/Julia/quaternion-type-2.julia @@ -0,0 +1,26 @@ +julia> q = Quaternion(1,0,0,0) +julia> q = Quaternion (1, 2, 3, 4) + q1 = Quaternion(2, 3, 4, 5) + q2 = Quaternion(3, 4, 5, 6) + r = 7. + +julia> norm(q) +5.477225575051661 + +julia> -q +-1 - 2i - 3j - 4k + +julia> conj(q) +1 - 2i - 3j - 4k + +julia> r + q, q + r +(8.0 + 2.0i + 3.0j + 4.0k,8.0 + 2.0i + 3.0j + 4.0k) + +julia> q1 + q2 +5 + 7i + 9j + 11k + +julia> r*q, q*r +(7.0 + 14.0i + 21.0j + 28.0k,7.0 + 14.0i + 21.0j + 28.0k) + +julia> q1*q2, q2*q1, q1*q2 != q2*q1 +(-56 + 16i + 24j + 26k,-56 + 18i + 20j + 28k,true) diff --git a/Task/Quaternion-type/Perl-6/quaternion-type.pl6 b/Task/Quaternion-type/Perl-6/quaternion-type.pl6 index 11d6997c9a..c182379045 100644 --- a/Task/Quaternion-type/Perl-6/quaternion-type.pl6 +++ b/Task/Quaternion-type/Perl-6/quaternion-type.pl6 @@ -1,34 +1,47 @@ -class Qu { +class Quaternion { has Real ( $.r, $.i, $.j, $.k ); multi method new ( Real $r, Real $i, Real $j, Real $k ) { - self.bless: *, :$r, :$i, :$j, :$k; + self.bless: :$r, :$i, :$j, :$k; } - method Str ( ) { "$.r + {$.i}i + {$.j}j + {$.k}k" } - method reals ( ) { $.r, $.i, $.j, $.k } - method conj ( ) { self.new: $.r, -$.i, -$.j, -$.k } - method norm ( ) { sqrt [+] self.reals X** 2 } -} + multi qu(*@r) is export { Quaternion.new: |@r } + sub postfix:(Real $x) is export { qu 0, 0, $x, 0 } + sub postfix:(Real $x) is export { qu 0, 0, 0, $x } -multi sub infix: ( Qu $a, Qu $b ) { [and] $a.reals Z== $b.reals } -multi sub infix:<+> ( Qu $a, Real $b ) { $a.new: $b+$a.r, $a.i, $a.j, $a.k } -multi sub infix:<+> ( Real $a, Qu $b ) { $b.new: $a+$b.r, $b.i, $b.j, $b.k } -multi sub infix:<+> ( Qu $a, Qu $b ) { $a.new: |( $a.reals Z+ $b.reals ) } -multi sub prefix:<-> ( Qu $a ) { $a.new: |( $a.reals X* -1 ) } -multi sub infix:<*> ( Qu $a, Real $b ) { $a.new: |( $a.reals X* $b ) } -multi sub infix:<*> ( Real $a, Qu $b ) { $b.new: |( $b.reals X* $a ) } -multi sub infix:<*> ( Qu $a, Qu $b ) { - my @a_rijk = $a.reals; - my ( $r, $i, $j, $k ) = $b.reals; - return $a.new: ( [+] @a_rijk Z* $r, -$i, -$j, -$k ), # real - ( [+] @a_rijk Z* $i, $r, $k, -$j ), # i - ( [+] @a_rijk Z* $j, -$k, $r, $i ), # j - ( [+] @a_rijk Z* $k, $j, -$i, $r ); # k -} + method Str () { "$.r + {$.i}i + {$.j}j + {$.k}k" } + method reals () { $.r, $.i, $.j, $.k } + method conj () { qu $.r, -$.i, -$.j, -$.k } + method norm () { sqrt [+] self.reals X** 2 } -my Qu $q .= new: 1, 2, 3, 4; -my Qu $q1 .= new: 2, 3, 4, 5; -my Qu $q2 .= new: 3, 4, 5, 6; + multi infix: ( Quaternion $a, Quaternion $b ) is export { $a.reals eqv $b.reals } + + multi infix:<+> ( Quaternion $a, Real $b ) is export { qu $b+$a.r, $a.i, $a.j, $a.k } + multi infix:<+> ( Real $a, Quaternion $b ) is export { qu $a+$b.r, $b.i, $b.j, $b.k } + multi infix:<+> ( Quaternion $a, Complex $b ) is export { qu $b.re + $a.r, $b.im + $a.i, $a.j, $a.k } + multi infix:<+> ( Complex $a, Quaternion $b ) is export { qu $a.re + $b.r, $a.im + $b.i, $b.j, $b.k } + multi infix:<+> ( Quaternion $a, Quaternion $b ) is export { qu $a.reals Z+ $b.reals } + + multi prefix:<-> ( Quaternion $a ) is export { qu $a.reals X* -1 } + + multi infix:<*> ( Quaternion $a, Real $b ) is export { qu $a.reals X* $b } + multi infix:<*> ( Real $a, Quaternion $b ) is export { qu $b.reals X* $a } + multi infix:<*> ( Quaternion $a, Complex $b ) is export { $a * qu $b.reals, 0, 0 } + multi infix:<*> ( Complex $a, Quaternion $b ) is export { $b R* qu $a.reals, 0, 0 } + + multi infix:<*> ( Quaternion $a, Quaternion $b ) is export { + my @a_rijk = $a.reals; + my ( $r, $i, $j, $k ) = $b.reals; + return qu [+]( @a_rijk Z* $r, -$i, -$j, -$k ), # real + [+]( @a_rijk Z* $i, $r, $k, -$j ), # i + [+]( @a_rijk Z* $j, -$k, $r, $i ), # j + [+]( @a_rijk Z* $k, $j, -$i, $r ); # k + } +} +import Quaternion; + +my $q = 1 + 2i + 3j + 4k; +my $q1 = 2 + 3i + 4j + 5k; +my $q2 = 3 + 4i + 5j + 6k; my $r = 7; say "1) q norm = {$q.norm}"; diff --git a/Task/Queue-Definition/C/queue-definition-1.c b/Task/Queue-Definition/C/queue-definition-1.c index fd4dd69a3f..c91306c380 100644 --- a/Task/Queue-Definition/C/queue-definition-1.c +++ b/Task/Queue-Definition/C/queue-definition-1.c @@ -4,47 +4,47 @@ typedef int DATA; /* type of data to store in queue */ typedef struct { - DATA *buf; - size_t head, tail, alloc; + DATA *buf; + size_t head, tail, alloc; } queue_t, *queue; queue q_new() { - queue q = malloc(sizeof(queue_t)); - q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); - q->head = q->tail = 0; - return q; + queue q = malloc(sizeof(queue_t)); + q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); + q->head = q->tail = 0; + return q; } int empty(queue q) { - return q->tail == q->head; + return q->tail == q->head; } void enqueue(queue q, DATA n) { - if (q->tail >= q->alloc) q->tail = 0; - q->buf[q->tail++] = n; - if (q->tail == q->head) { /* needs more room */ - q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); - if (q->head) { - memcpy(q->buf + q->head + q->alloc, q->buf + q->head, - sizeof(DATA) * (q->alloc - q->head)); - q->head += q->alloc; - } else - q->tail = q->alloc; - q->alloc *= 2; - } + if (q->tail >= q->alloc) q->tail = 0; + q->buf[q->tail++] = n; + if (q->tail == q->head) { /* needs more room */ + q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); + if (q->head) { + memcpy(q->buf + q->head + q->alloc, q->buf + q->head, + sizeof(DATA) * (q->alloc - q->head)); + q->head += q->alloc; + } else + q->tail = q->alloc; + q->alloc *= 2; + } } int dequeue(queue q, DATA *n) { - if (q->head == q->tail) return 0; - *n = q->buf[q->head++]; - if (q->head >= q->alloc) { /* reduce allocated storage no longer needed */ - q->head = 0; - if (q->alloc >= 512 && q->tail < q->alloc / 2) - q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); - } - return 1; + if (q->head == q->tail) return 0; + *n = q->buf[q->head++]; + if (q->head >= q->alloc) { /* reduce allocated storage no longer needed */ + q->head = 0; + if (q->alloc >= 512 && q->tail < q->alloc / 2) + q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); + } + return 1; } diff --git a/Task/Queue-Definition/C/queue-definition-2.c b/Task/Queue-Definition/C/queue-definition-2.c index 37aa06ad99..9ee2476dec 100644 --- a/Task/Queue-Definition/C/queue-definition-2.c +++ b/Task/Queue-Definition/C/queue-definition-2.c @@ -8,36 +8,36 @@ struct node_t { int val; node prev, next; }; #define TAIL(q) q->next queue q_new() { - node q = malloc(sizeof(node_t)); - q->next = q->prev = 0; - return q; + node q = malloc(sizeof(node_t)); + q->next = q->prev = 0; + return q; } int empty(queue q) { - return !HEAD(q); + return !HEAD(q); } void enqueue(queue q, int n) { - node nd = malloc(sizeof(node_t)); - nd->val = n; - if (!HEAD(q)) HEAD(q) = nd; - nd->prev = TAIL(q); - if (nd->prev) nd->prev->next = nd; - TAIL(q) = nd; - nd->next = 0; + node nd = malloc(sizeof(node_t)); + nd->val = n; + if (!HEAD(q)) HEAD(q) = nd; + nd->prev = TAIL(q); + if (nd->prev) nd->prev->next = nd; + TAIL(q) = nd; + nd->next = 0; } int dequeue(queue q, int *val) { - node tmp = HEAD(q); - if (!tmp) return 0; - *val = tmp->val; + node tmp = HEAD(q); + if (!tmp) return 0; + *val = tmp->val; - HEAD(q) = tmp->next; - if (TAIL(q) == tmp) TAIL(q) = 0; - free(tmp); + HEAD(q) = tmp->next; + if (TAIL(q) == tmp) TAIL(q) = 0; + free(tmp); - return 1; + return 1; } diff --git a/Task/Queue-Definition/C/queue-definition-3.c b/Task/Queue-Definition/C/queue-definition-3.c index 0fa1a53f80..1117a6d230 100644 --- a/Task/Queue-Definition/C/queue-definition-3.c +++ b/Task/Queue-Definition/C/queue-definition-3.c @@ -1,22 +1,22 @@ int main() { - int i, n; - queue q = q_new(); + int i, n; + queue q = q_new(); - for (i = 0; i < 100000000; i++) { - n = rand(); - if (n > RAND_MAX / 2) { - // printf("+ %d\n", n); - enqueue(q, n); - } else { - if (!dequeue(q, &n)) { - // printf("empty\n"); - continue; - } - // printf("- %d\n", n); - } - } - while (dequeue(q, &n));// printf("- %d\n", n); + for (i = 0; i < 100000000; i++) { + n = rand(); + if (n > RAND_MAX / 2) { + // printf("+ %d\n", n); + enqueue(q, n); + } else { + if (!dequeue(q, &n)) { + // printf("empty\n"); + continue; + } + // printf("- %d\n", n); + } + } + while (dequeue(q, &n));// printf("- %d\n", n); - return 0; + return 0; } diff --git a/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee b/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee index 816f29aa77..b0629ab927 100644 --- a/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee +++ b/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee @@ -2,6 +2,6 @@ { number: 1 } { number: 5000000 } -real 0m2.394s -user 0m2.089s -sys 0m0.265s +real 0m2.394s +user 0m2.089s +sys 0m0.265s diff --git a/Task/Queue-Definition/Component-Pascal/queue-definition-1.component b/Task/Queue-Definition/Component-Pascal/queue-definition-1.component index e842e7f35b..55a9fa1123 100644 --- a/Task/Queue-Definition/Component-Pascal/queue-definition-1.component +++ b/Task/Queue-Definition/Component-Pascal/queue-definition-1.component @@ -2,62 +2,62 @@ MODULE Queue; IMPORT StdLog,Boxes; TYPE - Queue* = POINTER TO RECORD - first,last: LONGINT; - queue: POINTER TO ARRAY OF Boxes.Object; - END; - - PROCEDURE NewQueue*(cap: LONGINT): Queue; - VAR - q: Queue; - BEGIN - NEW(q);q.first := 0; q.last := 0; - NEW(q.queue,cap); - RETURN q - END NewQueue; - - PROCEDURE (q: Queue) IsEmpty*(): BOOLEAN, NEW; - VAR - BEGIN - RETURN (q.first = q.last) - END IsEmpty; - - PROCEDURE (q: Queue) Push*(o: Boxes.Object),NEW; - VAR - i,j,oldSize,newSize: LONGINT; - queue: POINTER TO ARRAY OF Boxes.Object; - BEGIN - IF q.IsEmpty() THEN - q.queue[q.last] := o; - q.last := (q.last + 1) MOD LEN(q.queue) - ELSE - q.queue[q.last] := o; - q.last := (q.last + 1) MOD LEN(q.queue); - IF q.first = q.last THEN - (* grow queue *) - newSize := LEN(q.queue) + (LEN(q.queue) DIV 2); - (* new queue*) - NEW(queue,newSize); - (* move data from old queue to new queue *) - i := q.first; j := 0;oldSize := LEN(q.queue) - q.first + q.last; - WHILE (j < oldSize ) & (j < LEN(queue) - 1) DO - queue[j] := q.queue[i]; - i := (i + 1) MOD LEN(q.queue);INC(j) - END; - q.queue := queue;q.first := 0;q.last := j - END - END; - END Push; - - PROCEDURE (q: Queue) Pop*(): Boxes.Object, NEW; - VAR - o: Boxes.Object; - BEGIN - ASSERT(~q.IsEmpty()); - o := q.queue[q.first]; - q.queue[q.first] := NIL; - q.first := (q.first + 1) MOD LEN(q.queue); - RETURN o; - END Pop; + Queue* = POINTER TO RECORD + first,last: LONGINT; + queue: POINTER TO ARRAY OF Boxes.Object; + END; + + PROCEDURE NewQueue*(cap: LONGINT): Queue; + VAR + q: Queue; + BEGIN + NEW(q);q.first := 0; q.last := 0; + NEW(q.queue,cap); + RETURN q + END NewQueue; + + PROCEDURE (q: Queue) IsEmpty*(): BOOLEAN, NEW; + VAR + BEGIN + RETURN (q.first = q.last) + END IsEmpty; + + PROCEDURE (q: Queue) Push*(o: Boxes.Object),NEW; + VAR + i,j,oldSize,newSize: LONGINT; + queue: POINTER TO ARRAY OF Boxes.Object; + BEGIN + IF q.IsEmpty() THEN + q.queue[q.last] := o; + q.last := (q.last + 1) MOD LEN(q.queue) + ELSE + q.queue[q.last] := o; + q.last := (q.last + 1) MOD LEN(q.queue); + IF q.first = q.last THEN + (* grow queue *) + newSize := LEN(q.queue) + (LEN(q.queue) DIV 2); + (* new queue*) + NEW(queue,newSize); + (* move data from old queue to new queue *) + i := q.first; j := 0;oldSize := LEN(q.queue) - q.first + q.last; + WHILE (j < oldSize ) & (j < LEN(queue) - 1) DO + queue[j] := q.queue[i]; + i := (i + 1) MOD LEN(q.queue);INC(j) + END; + q.queue := queue;q.first := 0;q.last := j + END + END; + END Push; + + PROCEDURE (q: Queue) Pop*(): Boxes.Object, NEW; + VAR + o: Boxes.Object; + BEGIN + ASSERT(~q.IsEmpty()); + o := q.queue[q.first]; + q.queue[q.first] := NIL; + q.first := (q.first + 1) MOD LEN(q.queue); + RETURN o; + END Pop; END Queue. diff --git a/Task/Queue-Definition/Component-Pascal/queue-definition-2.component b/Task/Queue-Definition/Component-Pascal/queue-definition-2.component index ba8fc4a7d7..9d16421abe 100644 --- a/Task/Queue-Definition/Component-Pascal/queue-definition-2.component +++ b/Task/Queue-Definition/Component-Pascal/queue-definition-2.component @@ -1,14 +1,14 @@ DEFINITION Queue; - IMPORT Boxes; + IMPORT Boxes; - TYPE - Queue = POINTER TO RECORD - (q: Queue) IsEmpty (): BOOLEAN, NEW; - (q: Queue) Pop (): Boxes.Object, NEW; - (q: Queue) Push (o: Boxes.Object), NEW - END; + TYPE + Queue = POINTER TO RECORD + (q: Queue) IsEmpty (): BOOLEAN, NEW; + (q: Queue) Pop (): Boxes.Object, NEW; + (q: Queue) Push (o: Boxes.Object), NEW + END; - PROCEDURE NewQueue (cap: LONGINT): Queue; + PROCEDURE NewQueue (cap: LONGINT): Queue; END Queue. diff --git a/Task/Queue-Definition/Deja-Vu/queue-definition.djv b/Task/Queue-Definition/Deja-Vu/queue-definition.djv new file mode 100644 index 0000000000..3e92bd2db2 --- /dev/null +++ b/Task/Queue-Definition/Deja-Vu/queue-definition.djv @@ -0,0 +1,16 @@ +queue: + { :start 0 :end 0 } + +enqueue q item: + set-to q q!end item + set-to q :end ++ q!end + +dequeue q: + if empty q: + Raise :value-error "popping from empty queue" + q! q!start + delete-from q q!start + set-to q :start ++ q!start + +empty q: + = q!start q!end diff --git a/Task/Queue-Definition/Elisa/queue-definition-1.elisa b/Task/Queue-Definition/Elisa/queue-definition-1.elisa index fbce757f72..aa38f25bfd 100644 --- a/Task/Queue-Definition/Elisa/queue-definition-1.elisa +++ b/Task/Queue-Definition/Elisa/queue-definition-1.elisa @@ -15,7 +15,7 @@ begin Push ( queue, element ) = [ exception (Full(queue), "Queue Overflow"); queue.length:= queue.length + 1; - add (queue.list, element)]; + add (queue.list, element)]; Pull ( queue ) = [ exception (Empty(queue), "Queue Underflow"); queue.length:= queue.length - 1; diff --git a/Task/Queue-Definition/Java/queue-definition.java b/Task/Queue-Definition/Java/queue-definition.java index 835ee25cb8..ca64e3df4e 100644 --- a/Task/Queue-Definition/Java/queue-definition.java +++ b/Task/Queue-Definition/Java/queue-definition.java @@ -1,40 +1,40 @@ public class Queue{ - Node head = null, tail = null; + Node head = null, tail = null; - static class Node{ - E value; - Node next; + static class Node{ + E value; + Node next; - Node(E value, Node next){ - this.value= value; - this.next= next; - } + Node(E value, Node next){ + this.value= value; + this.next= next; + } - } + } - public Queue(){ - } + public Queue(){ + } - public void enqueue(E value){ //standard queue name for "push" - Node newNode= new Node(value, null); - if(empty()){ - head= newNode; - }else{ - tail.next = newNode; - } - tail= newNode; - } + public void enqueue(E value){ //standard queue name for "push" + Node newNode= new Node(value, null); + if(empty()){ + head= newNode; + }else{ + tail.next = newNode; + } + tail= newNode; + } - public E dequeue() throws java.util.NoSuchElementException{//standard queue name for "pop" - if(empty()){ - throw new java.util.NoSuchElementException("No more elements."); - } - E retVal= head.value; - head= head.next; - return retVal; - } + public E dequeue() throws java.util.NoSuchElementException{//standard queue name for "pop" + if(empty()){ + throw new java.util.NoSuchElementException("No more elements."); + } + E retVal= head.value; + head= head.next; + return retVal; + } - public boolean empty(){ - return head == null; - } + public boolean empty(){ + return head == null; + } } diff --git a/Task/Queue-Definition/MATLAB/queue-definition-3.m b/Task/Queue-Definition/MATLAB/queue-definition-3.m index 9ee87003bc..8ed4d60fc0 100644 --- a/Task/Queue-Definition/MATLAB/queue-definition-3.m +++ b/Task/Queue-Definition/MATLAB/queue-definition-3.m @@ -2,7 +2,7 @@ myQueue = - FIFOQueue + FIFOQueue >> push(myQueue,'jello') >> pop(myQueue) diff --git a/Task/Queue-Definition/Prolog/queue-definition.pro b/Task/Queue-Definition/Prolog/queue-definition.pro index 806ddfba4f..3632ab1ec4 100644 --- a/Task/Queue-Definition/Prolog/queue-definition.pro +++ b/Task/Queue-Definition/Prolog/queue-definition.pro @@ -1,11 +1,11 @@ empty(U-V) :- - unify_with_occurs_check(U, V). + unify_with_occurs_check(U, V). push(Queue, Value, NewQueue) :- - append_dl(Queue, [Value|X]-X, NewQueue). + append_dl(Queue, [Value|X]-X, NewQueue). % when queue is empty pop fails. pop([X|V]-U, X, V-U) :- - \+empty([X|V]-U). + \+empty([X|V]-U). append_dl(X-Y, Y-Z, X-Z). diff --git a/Task/Queue-Definition/R/queue-definition-2.r b/Task/Queue-Definition/R/queue-definition-2.r index ac01170826..6be51c02d4 100644 --- a/Task/Queue-Definition/R/queue-definition-2.r +++ b/Task/Queue-Definition/R/queue-definition-2.r @@ -1,27 +1,27 @@ # The usual Scheme way : build a function that takes commands as parameters (it's like message passing oriented programming) queue <- function() { - v <- list() - f <- function(cmd, val=NULL) { - if(cmd == "push") { - v <<- c(v, val) - invisible() - } else if(cmd == "pop") { - if(length(v) == 0) { - stop("empty queue") - } else { - x <- v[[1]] - v[[1]] <<- NULL - x - } - } else if(cmd == "length") { - length(v) - } else if(cmd == "empty") { - length(v) == 0 - } else { - stop("unknown command") - } - } - f + v <- list() + f <- function(cmd, val=NULL) { + if(cmd == "push") { + v <<- c(v, val) + invisible() + } else if(cmd == "pop") { + if(length(v) == 0) { + stop("empty queue") + } else { + x <- v[[1]] + v[[1]] <<- NULL + x + } + } else if(cmd == "length") { + length(v) + } else if(cmd == "empty") { + length(v) == 0 + } else { + stop("unknown command") + } + } + f } # Create two queues diff --git a/Task/Queue-Definition/REBOL/queue-definition.rebol b/Task/Queue-Definition/REBOL/queue-definition.rebol index 473aac6811..4c6f1bd0e1 100644 --- a/Task/Queue-Definition/REBOL/queue-definition.rebol +++ b/Task/Queue-Definition/REBOL/queue-definition.rebol @@ -8,12 +8,12 @@ rebol [ ; Define fifo class: fifo: make object! [ - queue: copy [] - push: func [x][append queue x] - pop: func [/local x][ ; Make 'x' local so it won't pollute global namespace. - if empty [return none] - x: first queue remove queue x] - empty: does [empty? queue] + queue: copy [] + push: func [x][append queue x] + pop: func [/local x][ ; Make 'x' local so it won't pollute global namespace. + if empty [return none] + x: first queue remove queue x] + empty: does [empty? queue] ] ; Create and populate a FIFO: diff --git a/Task/Queue-Definition/Scala/queue-definition-1.scala b/Task/Queue-Definition/Scala/queue-definition-1.scala index 310673f9a5..7934ac40d8 100644 --- a/Task/Queue-Definition/Scala/queue-definition-1.scala +++ b/Task/Queue-Definition/Scala/queue-definition-1.scala @@ -13,7 +13,7 @@ class Queue[T] { if(isEmpty) head=Some(n) else tail.get.append(n) tail=Some(n) } - + def dequeue:T=head match { case Some(item) => head=item.next; item.value case None => throw new java.util.NoSuchElementException() diff --git a/Task/Queue-Definition/Scheme/queue-definition-2.ss b/Task/Queue-Definition/Scheme/queue-definition-2.ss index 21d6532bf4..0a19bae4cc 100644 --- a/Task/Queue-Definition/Scheme/queue-definition-2.ss +++ b/Task/Queue-Definition/Scheme/queue-definition-2.ss @@ -2,16 +2,16 @@ (let ((q (cons '() '()))) (lambda (cmd . arg) (case cmd - ((empty?) (null? (car q))) - ((put) (let ((a (cons (car arg) '()))) - (if (null? (car q)) - (begin (set-car! q a) (set-cdr! q a)) - (begin (set-cdr! (cdr q) a) (set-cdr! q a))))) - ((get) (if (null? (car q)) 'empty - (let ((x (caar q))) - (set-car! q (cdar q)) - (if (null? (car q)) (set-cdr! q '())) - x))) + ((empty?) (null? (car q))) + ((put) (let ((a (cons (car arg) '()))) + (if (null? (car q)) + (begin (set-car! q a) (set-cdr! q a)) + (begin (set-cdr! (cdr q) a) (set-cdr! q a))))) + ((get) (if (null? (car q)) 'empty + (let ((x (caar q))) + (set-car! q (cdar q)) + (if (null? (car q)) (set-cdr! q '())) + x))) )))) (define q (make-queue)) diff --git a/Task/Queue-Usage/AppleScript/queue-usage.applescript b/Task/Queue-Usage/AppleScript/queue-usage.applescript index c323f653a0..eecf2b9872 100644 --- a/Task/Queue-Usage/AppleScript/queue-usage.applescript +++ b/Task/Queue-Usage/AppleScript/queue-usage.applescript @@ -1,29 +1,29 @@ on push(StackRef, value) - set StackRef's contents to {value} & StackRef's contents - return StackRef + set StackRef's contents to {value} & StackRef's contents + return StackRef end push on pop(StackRef) - set R to missing value - if StackRef's contents ≠ {} then - set R to StackRef's contents's item 1 - set StackRef's contents to {} & rest of StackRef's contents - end if - return R + set R to missing value + if StackRef's contents ≠ {} then + set R to StackRef's contents's item 1 + set StackRef's contents to {} & rest of StackRef's contents + end if + return R end pop on isStackEmpty(StackRef) - if StackRef's contents = {} then return true - return false + if StackRef's contents = {} then return true + return false end isStackEmpty set theStack to {} repeat with i from 1 to 5 - push(a reference to theStack, i) - log result + push(a reference to theStack, i) + log result end repeat repeat until isStackEmpty(theStack) = true - pop(a reference to theStack) - log result + pop(a reference to theStack) + log result end repeat diff --git a/Task/Queue-Usage/C/queue-usage.c b/Task/Queue-Usage/C/queue-usage.c index cf3869b6e7..d3518c62ac 100644 --- a/Task/Queue-Usage/C/queue-usage.c +++ b/Task/Queue-Usage/C/queue-usage.c @@ -23,9 +23,9 @@ int main() printf("%d\n", i); fprintf(stderr, "FIFO list %s\n", - ( m_dequeue(&i, &head) ) ? - "had still an element" : - "is void!"); + ( m_dequeue(&i, &head) ) ? + "had still an element" : + "is void!"); exit(0); } diff --git a/Task/Queue-Usage/Component-Pascal/queue-usage.component b/Task/Queue-Usage/Component-Pascal/queue-usage.component index 9bee03947a..d47dcd773d 100644 --- a/Task/Queue-Usage/Component-Pascal/queue-usage.component +++ b/Task/Queue-Usage/Component-Pascal/queue-usage.component @@ -3,20 +3,20 @@ IMPORT StdLog,Queue,Boxes; PROCEDURE Do*; VAR - q: Queue.Queue; - o: Boxes.Object; - BEGIN - q := Queue.NewQueue(6); - q.Push(Boxes.NewInteger(1)); - q.Push(Boxes.NewInteger(2)); - q.Push(Boxes.NewInteger(3)); - o := q.Pop(); - o := q.Pop(); - q.Push(Boxes.NewInteger(4)); - o := q.Pop(); - o := q.Pop(); - q.Push(Boxes.NewInteger(5)); - o := q.Pop(); - StdLog.String("Is empty: ");StdLog.Bool(q.IsEmpty());StdLog.Ln + q: Queue.Queue; + o: Boxes.Object; + BEGIN + q := Queue.NewQueue(6); + q.Push(Boxes.NewInteger(1)); + q.Push(Boxes.NewInteger(2)); + q.Push(Boxes.NewInteger(3)); + o := q.Pop(); + o := q.Pop(); + q.Push(Boxes.NewInteger(4)); + o := q.Pop(); + o := q.Pop(); + q.Push(Boxes.NewInteger(5)); + o := q.Pop(); + StdLog.String("Is empty: ");StdLog.Bool(q.IsEmpty());StdLog.Ln END Do; END UseQueue. diff --git a/Task/Queue-Usage/Deja-Vu/queue-usage.djv b/Task/Queue-Usage/Deja-Vu/queue-usage.djv new file mode 100644 index 0000000000..d3081ab255 --- /dev/null +++ b/Task/Queue-Usage/Deja-Vu/queue-usage.djv @@ -0,0 +1,11 @@ +local :Q queue +!. empty Q +enqueue Q "HELLO" +enqueue Q 123 +enqueue Q "It's a magical place" +!. empty Q +!. dequeue Q +!. dequeue Q +!. dequeue Q +!. empty Q +!. dequeue Q diff --git a/Task/Queue-Usage/Prolog/queue-usage.pro b/Task/Queue-Usage/Prolog/queue-usage.pro index 62c2048fcb..1191e485a2 100644 --- a/Task/Queue-Usage/Prolog/queue-usage.pro +++ b/Task/Queue-Usage/Prolog/queue-usage.pro @@ -1,14 +1,14 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% definitions of queue empty(U-V) :- - unify_with_occurs_check(U, V). + unify_with_occurs_check(U, V). push(Queue, Value, NewQueue) :- - append_dl(Queue, [Value|X]-X, NewQueue). + append_dl(Queue, [Value|X]-X, NewQueue). pop([X|V]-U, X, V-U) :- - \+empty([X|V]-U). + \+empty([X|V]-U). @@ -17,32 +17,32 @@ append_dl(X-Y, Y-Z, X-Z). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% use of queue queue :- - % create an empty queue - empty(Q), - format('Create queue ~w~n~n', [Q]), + % create an empty queue + empty(Q), + format('Create queue ~w~n~n', [Q]), - % add numbers 1 and 2 - write('Add numbers 1 and 2 : '), - push(Q, 1, Q1), - push(Q1, 2, Q2), + % add numbers 1 and 2 + write('Add numbers 1 and 2 : '), + push(Q, 1, Q1), + push(Q1, 2, Q2), - % display queue - format('~w~n~n', [Q2]), + % display queue + format('~w~n~n', [Q2]), - % pop element - pop(Q2, V, Q3), + % pop element + pop(Q2, V, Q3), - % display results - format('Pop : Value ~w Queue : ~w~n~n', [V, Q3]), + % display results + format('Pop : Value ~w Queue : ~w~n~n', [V, Q3]), - % test the queue - write('Test of the queue : '), - ( empty(Q3) -> writeln('Queue empy'); writeln('Queue not empty')), nl, + % test the queue + write('Test of the queue : '), + ( empty(Q3) -> writeln('Queue empy'); writeln('Queue not empty')), nl, - % pop the elements - write('Pop the queue : '), - pop(Q3, V1, Q4), - format('Value ~w Queue : ~w~n~n', [V1, Q4]), + % pop the elements + write('Pop the queue : '), + pop(Q3, V1, Q4), + format('Value ~w Queue : ~w~n~n', [V1, Q4]), - write('Pop the queue : '), - pop(Q4, _V, _Q5). + write('Pop the queue : '), + pop(Q4, _V, _Q5). diff --git a/Task/Quine/COBOL/quine-1.cobol b/Task/Quine/COBOL/quine-1.cobol index 79c601ebf6..d7d3ecf8c9 100644 --- a/Task/Quine/COBOL/quine-1.cobol +++ b/Task/Quine/COBOL/quine-1.cobol @@ -281,7 +281,7 @@ " ML-99. ". 03 FILLER PIC X(40) VALUE " ". - 03 FILLER PIC X(40) VALUE + lang Ada>with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:=' 03 FILLER PIC X(40) VALUE " CLOSE OUTPUT-FILE. ". 03 FILLER PIC X(40) VALUE " ". diff --git a/Task/Quine/Deja-Vu/quine.djv b/Task/Quine/Deja-Vu/quine.djv index 5645bb280f..9487ba22a9 100644 --- a/Task/Quine/Deja-Vu/quine.djv +++ b/Task/Quine/Deja-Vu/quine.djv @@ -1,2 +1,2 @@ -"print . dup" -print . dup +"!print !. dup" +!print !. dup diff --git a/Task/Quine/Elixir/quine.elixir b/Task/Quine/Elixir/quine.elixir new file mode 100644 index 0000000000..4c75c390bd --- /dev/null +++ b/Task/Quine/Elixir/quine.elixir @@ -0,0 +1,2 @@ +a = <<"a = ~p~n:io.fwrite(a,[a])~n">> +:io.fwrite(a,[a]) diff --git a/Task/Quine/Perl/quine-4.pl b/Task/Quine/Perl/quine-4.pl index d0cddc2027..60ab4cb889 100644 --- a/Task/Quine/Perl/quine-4.pl +++ b/Task/Quine/Perl/quine-4.pl @@ -1 +1 @@ -$_=q{print"\$_=q{$_};eval"};eval +open 0; print <0>; diff --git a/Task/Quine/Perl/quine-5.pl b/Task/Quine/Perl/quine-5.pl index 8ce57b5f62..d0cddc2027 100644 --- a/Task/Quine/Perl/quine-5.pl +++ b/Task/Quine/Perl/quine-5.pl @@ -1,47 +1 @@ -{local$_=q{ -{ - package Quine; - use strict; - use warnings; - our $VERSION = sprintf "%d.%02d", q$Revision: 0.2 $ =~ /(\d+)/g; - my $head = '{local$_=q' . "\x7B\n"; - my $tail = 'print"{local\$_=q{$_};eval}\n"' . "\x7D;eval}\n"; - - sub new { - my $class = shift; - my $quine = $head . shift; - my $ret = shift || 1; - my $ln = ( $quine =~ tr/\n/\n/ ); - $ln++; - $quine .= "return $ret if caller(1)or(caller)[2]!=$ln;$tail"; - bless \$quine, $class; - } - - sub from_file { - my ( $class, $fn, $ret ) = @_; - local $/; - open my $fh, '<', $fn or die "$fn : $!"; - my $src = <$fh>; - close $fh; - $class->new( $src, $ret ); - } - - sub quine { ${ $_[0] } } - -=head1 NAME - -Quine - turn your perl modules/apps into a true quine! - -=head1 VERSION - -$Id: Quine.pm,v 0.2 2010/09/15 20:23:53 dankogai Exp dankogai $ - -=head1 SYNOPSIS - - use Quine; - print Quine->from_file("woot.pl")->quine; - print Quine->from_file("moot.psgi", '$app')->quine; - -=cut -} -return 1 if caller(1);print"{local\$_=q{$_};eval}\n"};eval} +$_=q{print"\$_=q{$_};eval"};eval diff --git a/Task/Quine/Perl/quine-6.pl b/Task/Quine/Perl/quine-6.pl new file mode 100644 index 0000000000..8ce57b5f62 --- /dev/null +++ b/Task/Quine/Perl/quine-6.pl @@ -0,0 +1,47 @@ +{local$_=q{ +{ + package Quine; + use strict; + use warnings; + our $VERSION = sprintf "%d.%02d", q$Revision: 0.2 $ =~ /(\d+)/g; + my $head = '{local$_=q' . "\x7B\n"; + my $tail = 'print"{local\$_=q{$_};eval}\n"' . "\x7D;eval}\n"; + + sub new { + my $class = shift; + my $quine = $head . shift; + my $ret = shift || 1; + my $ln = ( $quine =~ tr/\n/\n/ ); + $ln++; + $quine .= "return $ret if caller(1)or(caller)[2]!=$ln;$tail"; + bless \$quine, $class; + } + + sub from_file { + my ( $class, $fn, $ret ) = @_; + local $/; + open my $fh, '<', $fn or die "$fn : $!"; + my $src = <$fh>; + close $fh; + $class->new( $src, $ret ); + } + + sub quine { ${ $_[0] } } + +=head1 NAME + +Quine - turn your perl modules/apps into a true quine! + +=head1 VERSION + +$Id: Quine.pm,v 0.2 2010/09/15 20:23:53 dankogai Exp dankogai $ + +=head1 SYNOPSIS + + use Quine; + print Quine->from_file("woot.pl")->quine; + print Quine->from_file("moot.psgi", '$app')->quine; + +=cut +} +return 1 if caller(1);print"{local\$_=q{$_};eval}\n"};eval} diff --git a/Task/Quine/Python/quine-7.py b/Task/Quine/Python/quine-7.py new file mode 100644 index 0000000000..c7c6469de7 --- /dev/null +++ b/Task/Quine/Python/quine-7.py @@ -0,0 +1,11 @@ +$ cat reproducing.py + File "reproducing.py", line 1 + File "reproducing.py", line 1 + ^ +IndentationError: unexpected indent + +$ python reproducing.py + File "reproducing.py", line 1 + File "reproducing.py", line 1 + ^ +IndentationError: unexpected indent diff --git a/Task/Quine/R/quine.r b/Task/Quine/R/quine.r index f01e4698c9..fe0346a5f2 100644 --- a/Task/Quine/R/quine.r +++ b/Task/Quine/R/quine.r @@ -1 +1,2 @@ -(function(){x<-intToUtf8(34);s<-"(function(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})() +(function(){x<-intToUtf8(34);s<-"(functio = 3 TO DATACOUNT - 1" + DATA " PRINT #1, s(nn(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})() diff --git a/Task/Quine/Rust/quine.rust b/Task/Quine/Rust/quine.rust new file mode 100644 index 0000000000..2cd701eaf6 --- /dev/null +++ b/Task/Quine/Rust/quine.rust @@ -0,0 +1,60 @@ +// 0.9-pre compatible +fn main() +{ + let q = 34u8; + let p = 44u8; + let l = [ + "fn main()", + "{", + " let q = 34u8;", + " let p = 44u8;", + " let l = [", + " ", + " ];", + " let mut i = 0;", + " while i < 5", + " {", + " println(l[i]);", + " i+=1;", + " }", + " i = 0;", + " while i < l.len()", + " {", + " print(l[5]);", + " print((q as char).to_str());", + " print(l[i]);", + " print((q as char).to_str());", + " println((p as char).to_str());", + " i+=1;", + " }", + " i = 6;", + " while i < l.len()", + " {", + " println(l[i]);", + " i+=1;", + " }", + "}", + ]; + let mut i = 0; + while i < 5 + { + println(l[i]); + i+=1; + } + i = 0; + while i < l.len() + { + print(l[5]); + print((q as char).to_str()); + print(l[i]); + print((q as char).to_str()); + println((p as char).to_str()); + i+=1; + } + i = 6; + while i < l.len() + { + println(l[i]); + i+=1; + } +} diff --git a/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 b/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 index a58c0cb26e..f7efef4e4b 100644 --- a/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 +++ b/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 @@ -1,8 +1,7 @@ -=begin CREDITS +=for CREDITS Crypto-JS v2.0.0 http:#code.google.com/p/crypto-js/ Copyright (c) 2009, Jeff Mott. All rights reserved. -=end CREDITS sub rotl($n, $b) { $n +< $b +| $n +> (32 - $b) } sub prefix: { +^$^x % 2**32 } @@ -46,9 +45,9 @@ constant F = constant K1 = <0x00000000 0x5a827999 0x6ed9eba1 0x8f1bbcdc 0xa953fd4e> »xx» 16; constant K2 = <0x50a28be6 0x5c4dd124 0x6d703ef3 0x7a6d76e9 0x00000000> »xx» 16; -our proto rmd160($) returns Buf {*} +our proto rmd160($) returns Blob {*} multi rmd160(Str $s) { rmd160 $s.encode: 'ascii' } -multi rmd160(Buf $data) { +multi rmd160(Blob $data) { my @b = $data.list, 0x80; push @b, 0 until (8*@b-448) %% 512; my $len = 8 * $data.elems; @@ -60,22 +59,22 @@ multi rmd160(Buf $data) { my @h = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0; loop (my $i = 0; $i < @word; $i += 16) { - my @X = my @Y = @h; - for ^80 -> $j { - my $T = rotl( - @X[0] m+ F[$j div 16](|@X[1..3]) m+ (@word[$i+r1[$j]] // 0) m+ K1[$j], - s1[$j] - ) m+ @X[4]; - @X = @X[4], $T, @X[1], rotl(@X[2], 10) % 2**32, @X[3]; - $T = rotl( - @Y[0] m+ F[(79-$j) div 16](|@Y[1..3]) m+ (@word[$i+r2[$j]] // 0) m+ K2[$j], - s2[$j] - ) m+ @Y[4]; - @Y = @Y[4], $T, @Y[1], rotl(@Y[2], 10) % 2**32, @Y[3]; - } - @h = @h[1..4,^1] Z[m+] @X[2..4,^2] Z[m+] @Y[3..4,^3]; + my @X = my @Y = @h; + for ^80 -> $j { + my $T = rotl( + @X[0] m+ F[$j div 16](|@X[1..3]) m+ (@word[$i+r1[$j]] // 0) m+ K1[$j], + s1[$j] + ) m+ @X[4]; + @X = @X[4], $T, @X[1], rotl(@X[2], 10) % 2**32, @X[3]; + $T = rotl( + @Y[0] m+ F[(79-$j) div 16](|@Y[1..3]) m+ (@word[$i+r2[$j]] // 0) m+ K2[$j], + s2[$j] + ) m+ @Y[4]; + @Y = @Y[4], $T, @Y[1], rotl(@Y[2], 10) % 2**32, @Y[3]; + } + @h = @h[1..4,^1] Z[m+] @X[2..4,^2] Z[m+] @Y[3..4,^3]; } - return Buf.new: gather for @h -> $word is rw { + return Blob.new: gather for @h -> $word is rw { for ^4 { take $word % 256; $word div= 256 } } } diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--1.c b/Task/Random-number-generator--device-/C/random-number-generator--device--1.c index c7ee966414..ad2e957ecc 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--1.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--1.c @@ -8,15 +8,15 @@ int main(int argc, char **argv) FILE *r = fopen("/dev/urandom", "r"); if (r == NULL) { - perror("/dev/urandom"); - return 1; + perror("/dev/urandom"); + return 1; } size_t br = fread(&v, sizeof v, 1, r); if (br < 1) { - fputs("/dev/urandom: Not enough bytes\n", stderr); - return 1; + fputs("/dev/urandom: Not enough bytes\n", stderr); + return 1; } printf("%" PRIu32 "\n", v); diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--2.c b/Task/Random-number-generator--device-/C/random-number-generator--device--2.c index e89e92b863..6478ade105 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--2.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--2.c @@ -1,10 +1,10 @@ -#include /* PRIu32 */ -#include /* arc4random */ -#include /* printf */ +#include /* PRIu32 */ +#include /* arc4random */ +#include /* printf */ int main() { - printf("%" PRIu32 "\n", arc4random()); - return 0; + printf("%" PRIu32 "\n", arc4random()); + return 0; } diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--3.c b/Task/Random-number-generator--device-/C/random-number-generator--device--3.c index a31b0f4d4a..dea1380232 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--3.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--3.c @@ -7,12 +7,12 @@ int main() { - uint32_t v; + uint32_t v; - if (RAND_bytes((unsigned char *)&v, sizeof v) == 0) { - ERR_print_errors_fp(stderr); - return 1; - } - printf("%" PRIu32 "\n", v); - return 0; + if (RAND_bytes((unsigned char *)&v, sizeof v) == 0) { + ERR_print_errors_fp(stderr); + return 1; + } + printf("%" PRIu32 "\n", v); + return 0; } diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--4.c b/Task/Random-number-generator--device-/C/random-number-generator--device--4.c index bee536d54b..08a28316fa 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--4.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--4.c @@ -1,23 +1,23 @@ -#include /* printf */ +#include /* printf */ #include -#include /* CryptAcquireContext, CryptGenRandom */ +#include /* CryptAcquireContext, CryptGenRandom */ int main() { - HCRYPTPROV p; - ULONG i; + HCRYPTPROV p; + ULONG i; - if (CryptAcquireContext(&p, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) { - fputs("CryptAcquireContext failed.\n", stderr); - return 1; - } - if (CryptGenRandom(p, sizeof i, (BYTE *)&i) == FALSE) { - fputs("CryptGenRandom failed.\n", stderr); - return 1; - } - printf("%lu\n", i); - CryptReleaseContext(p, 0); - return 0; + if (CryptAcquireContext(&p, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) { + fputs("CryptAcquireContext failed.\n", stderr); + return 1; + } + if (CryptGenRandom(p, sizeof i, (BYTE *)&i) == FALSE) { + fputs("CryptGenRandom failed.\n", stderr); + return 1; + } + printf("%lu\n", i); + CryptReleaseContext(p, 0); + return 0; } diff --git a/Task/Random-number-generator--device-/Icon/random-number-generator--device-.icon b/Task/Random-number-generator--device-/Icon/random-number-generator--device-.icon new file mode 100644 index 0000000000..dcb5ef3a6e --- /dev/null +++ b/Task/Random-number-generator--device-/Icon/random-number-generator--device-.icon @@ -0,0 +1,12 @@ +procedure main(A) + n := integer(A[1])|5 + every !n do write(rand(4)) +end + +procedure rand(n) + f := open("/dev/urandom") | stop("Cannot get to urandom!") + x := 0 + every !n do x := x*256 + ord(reads(f,1)) + close(f) + return x +end diff --git a/Task/Random-number-generator--device-/Java/random-number-generator--device-.java b/Task/Random-number-generator--device-/Java/random-number-generator--device-.java index 4488ccc251..e1cdbfc342 100644 --- a/Task/Random-number-generator--device-/Java/random-number-generator--device-.java +++ b/Task/Random-number-generator--device-/Java/random-number-generator--device-.java @@ -1,10 +1,10 @@ import java.security.SecureRandom; public class RandomExample { - public static void main(String[] args) { - SecureRandom rng = new SecureRandom(); + public static void main(String[] args) { + SecureRandom rng = new SecureRandom(); - /* Prints a random signed 32-bit integer. */ - System.out.println(rng.nextInt()); - } + /* Prints a random signed 32-bit integer. */ + System.out.println(rng.nextInt()); + } } diff --git a/Task/Random-number-generator--included-/Deja-Vu/random-number-generator--included-.djv b/Task/Random-number-generator--included-/Deja-Vu/random-number-generator--included-.djv index 5e9a8005a9..e10f52558e 100644 --- a/Task/Random-number-generator--included-/Deja-Vu/random-number-generator--included-.djv +++ b/Task/Random-number-generator--included-/Deja-Vu/random-number-generator--included-.djv @@ -1 +1 @@ -print rand 0 1 # prints a pseudo-random floating-point number between 0 and 1 +!print random-int # prints a 32-bit random integer diff --git a/Task/Random-number-generator--included-/Scala/random-number-generator--included-.scala b/Task/Random-number-generator--included-/Scala/random-number-generator--included-.scala new file mode 100644 index 0000000000..949d575df2 --- /dev/null +++ b/Task/Random-number-generator--included-/Scala/random-number-generator--included-.scala @@ -0,0 +1,12 @@ +import scala.util.Random + +/** + * Histogram of 200 throws with two dices. + */ +object Throws extends App { + Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2) + .take(200).groupBy(identity).toList.sortBy(_._1) + .foreach { + case (a, b) => println(f"$a%2d:" + "X" * b.size) + } +} diff --git a/Task/Random-numbers/Julia/random-numbers.julia b/Task/Random-numbers/Julia/random-numbers.julia new file mode 100644 index 0000000000..dedb85ea80 --- /dev/null +++ b/Task/Random-numbers/Julia/random-numbers.julia @@ -0,0 +1 @@ +randn(1000) * 0.5 + 1 diff --git a/Task/Range-expansion/D/range-expansion.d b/Task/Range-expansion/D/range-expansion.d index f45897a7b6..0e146a1398 100644 --- a/Task/Range-expansion/D/range-expansion.d +++ b/Task/Range-expansion/D/range-expansion.d @@ -1,14 +1,8 @@ -import std.stdio, std.regex, std.string, std.conv, std.range, - std.algorithm; +import std.stdio, std.regex, std.conv, std.range, std.algorithm; -int[] rangeExpand(in string txt) /*pure nothrow*/ { - return txt.split(",").map!((r) { - const m = r.match(r"^(-?\d+)(-?(-?\d+))?$").captures.array; - return m[2].empty ? [m[1].to!int] : - iota(m[1].to!int, m[3].to!int + 1).array; - }).join; -} +enum rangeEx = (string s) /*pure*/ => s.matchAll(`(-?\d+)-?(-?\d+)?,?`) + .map!q{ a[1].to!int.iota(a[1 + !a[2].empty].to!int + 1) }.join; void main() { - "-6,-3--1,3-5,7-11,14,15,17-20".rangeExpand.writeln; + "-6,-3--1,3-5,7-11,14,15,17-20".rangeEx.writeln; } diff --git a/Task/Range-expansion/TXR/range-expansion.txr b/Task/Range-expansion/TXR/range-expansion.txr new file mode 100644 index 0000000000..d5bb587cd0 --- /dev/null +++ b/Task/Range-expansion/TXR/range-expansion.txr @@ -0,0 +1,49 @@ +@(define num (n))@(local tok)@{tok /[+\-]?\d+/}@(bind n @(int-str tok))@(end) +@(define entry (e))@\ + @(local n1 n2)@\ + @(cases)@\ + @(num n1)@/\s*-\s*/@(num n2)@\ + @(bind e (n1 n2))@\ + @(or)@\ + @(num n1)@\ + @(bind e n1)@\ + @(end)@\ +@(end) +@(define rangelist (list))@\ + @(local first rest)@\ + @(cases)@\ + @(entry first)@/\s*,\s*/@(rangelist rest)@\ + @(bind list @(cons first rest))@\ + @(or)@\ + @(entry first)@\ + @(bind list (first))@\ + @(or)@\ + @(bind list nil)@\ + @(end)@\ +@(end) +@(do + (defun expand-helper (list) + (cond + ((null list) nil) + ((consp (first list)) + (append (range (first (first list)) + (second (first list))) + (rangeexpand (rest list)))) + (t (cons (first list) (rangeexpand (rest list)))))) + + (defun sortdup (list) + (let ((h (hash))) + (each ((n list)) + (set [h n] n)) + [sort (hash-keys h) <])) + + (defun rangeexpand (list) + (sortdup (expand-helper list)))) +@(repeat) +@(rangelist x)@{trailing-junk} +@(output) +raw syntax: @x +expansion: @(rangeexpand x) +your junk: @{trailing-junk} +@(end) +@(end) diff --git a/Task/Rate-counter/Erlang/rate-counter.erl b/Task/Rate-counter/Erlang/rate-counter.erl new file mode 100644 index 0000000000..9d25f8fa6f --- /dev/null +++ b/Task/Rate-counter/Erlang/rate-counter.erl @@ -0,0 +1,32 @@ +-module( rate_counter ). + +-export( [fun_during_seconds/2, task/0] ). + +fun_during_seconds( Fun, Seconds ) -> + My_pid = erlang:self(), + Ref = erlang:make_ref(), + Pid = erlang:spawn( fun() -> fun_during_seconds_loop( My_pid, Fun ) end ), + timer:send_after( Seconds * 1000, My_pid, {stop, Ref} ), + N = fun_during_seconds_receive_loop( Ref, Pid, 0 ), + erlang:exit( Pid, kill ), + N. + +task() -> + Results = [timer:tc( fun() -> io:fwrite("Hello, world!~n") end ) || _X <- lists:seq(1, 3)], + Times = [X || {X, _Returned} <- Results], + io:fwrite( "Times ~p, average ~p microseconds.~n", [Times, lists:sum(Times) / erlang:length(Times)]), + N = fun_during_seconds( fun() -> math:sqrt(123) end, 2 ), + io:fwrite( "Square root of 123, during 2 seconds, was done ~p times.~n", [N] ). + + + +fun_during_seconds_loop( Pid, Fun ) -> + Fun(), + Pid ! {one_time, erlang:self()}, + fun_during_seconds_loop( Pid, Fun ). + +fun_during_seconds_receive_loop( Ref, Pid, N ) -> + receive + {stop, Ref} -> N; + {one_time, Pid} -> fun_during_seconds_receive_loop( Ref, Pid, N + 1 ) + end. diff --git a/Task/Rate-counter/Ruby/rate-counter.rb b/Task/Rate-counter/Ruby/rate-counter.rb new file mode 100644 index 0000000000..17dd864027 --- /dev/null +++ b/Task/Rate-counter/Ruby/rate-counter.rb @@ -0,0 +1,15 @@ +require 'benchmark' +Document = Struct.new(:id,:a,:b,:c) +documents_a = [] +documents_h = {} +1.upto(10_000) do |n| + d = Document.new(n) + documents_a << d + documents_h[d.id] = d +end +searchlist = Array.new(1000){ rand(10_000)+1 } + +Benchmark.bm(10) do |x| + x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} } + x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} } +end diff --git a/Task/Read-a-configuration-file/00DESCRIPTION b/Task/Read-a-configuration-file/00DESCRIPTION index f629bf5f2d..5a3746b863 100644 --- a/Task/Read-a-configuration-file/00DESCRIPTION +++ b/Task/Read-a-configuration-file/00DESCRIPTION @@ -2,7 +2,7 @@ The task is to read a configuration file in standard configuration file, and set # This is a configuration file in standard configuration file format # - # Lines begininning with a hash or a semicolon are ignored by the application + # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter @@ -40,3 +40,6 @@ We also have an option that contains multiple parameters. These may be stored in * otherfamily(1) = Rhu Barber * otherfamily(2) = Harry Barber + +'''See also:''' +* [[Update a configuration file]] diff --git a/Task/Read-a-configuration-file/AWK/read-a-configuration-file.awk b/Task/Read-a-configuration-file/AWK/read-a-configuration-file.awk new file mode 100644 index 0000000000..55b957ad78 --- /dev/null +++ b/Task/Read-a-configuration-file/AWK/read-a-configuration-file.awk @@ -0,0 +1,33 @@ +# syntax: GAWK -f READ_A_CONFIGURATION_FILE.AWK +BEGIN { + fullname = favouritefruit = "" + needspeeling = seedsremoved = "false" + fn = "READ_A_CONFIGURATION_FILE.INI" + while (getline rec 0) { + tmp = tolower(rec) + if (tmp ~ /^ *fullname/) { fullname = extract(rec) } + else if (tmp ~ /^ *favouritefruit/) { favouritefruit = extract(rec) } + else if (tmp ~ /^ *needspeeling/) { needspeeling = "true" } + else if (tmp ~ /^ *seedsremoved/) { seedsremoved = "true" } + else if (tmp ~ /^ *otherfamily/) { split(extract(rec),otherfamily,",") } + } + close(fn) + printf("fullname=%s\n",fullname) + printf("favouritefruit=%s\n",favouritefruit) + printf("needspeeling=%s\n",needspeeling) + printf("seedsremoved=%s\n",seedsremoved) + for (i=1; i<=length(otherfamily); i++) { + sub(/^ +/,"",otherfamily[i]) # remove leading spaces + sub(/ +$/,"",otherfamily[i]) # remove trailing spaces + printf("otherfamily(%d)=%s\n",i,otherfamily[i]) + } + exit(0) +} +function extract(rec, pos,str) { + sub(/^ +/,"",rec) # remove leading spaces before parameter name + pos = match(rec,/[= ]/) # determine where data begins + str = substr(rec,pos) # extract the data + gsub(/^[= ]+/,"",str) # remove leading "=" and spaces + sub(/ +$/,"",str) # remove trailing spaces + return(str) +} diff --git a/Task/Read-a-configuration-file/Groovy/read-a-configuration-file-1.groovy b/Task/Read-a-configuration-file/Groovy/read-a-configuration-file-1.groovy new file mode 100644 index 0000000000..cdc55a4b60 --- /dev/null +++ b/Task/Read-a-configuration-file/Groovy/read-a-configuration-file-1.groovy @@ -0,0 +1,15 @@ +def config = [:] +def loadConfig = { File file -> + String regex = /^(;{0,1})\s*(\S+)\s*(.*)$/ + file.eachLine { line -> + (line =~ regex).each { matcher, invert, key, value -> + if (key == '' || key.startsWith("#")) return + parts = value ? value.split(/\s*,\s*/) : (invert ? [false] : [true]) + if (parts.size() > 1) { + parts.eachWithIndex{ part, int i -> config["$key(${i + 1})"] = part} + } else { + config[key] = parts[0] + } + } + } +} diff --git a/Task/Read-a-configuration-file/Groovy/read-a-configuration-file-2.groovy b/Task/Read-a-configuration-file/Groovy/read-a-configuration-file-2.groovy new file mode 100644 index 0000000000..1d6c13fdb2 --- /dev/null +++ b/Task/Read-a-configuration-file/Groovy/read-a-configuration-file-2.groovy @@ -0,0 +1,2 @@ +loadConfig new File('config.ini') +config.each { println it } diff --git a/Task/Read-a-configuration-file/Icon/read-a-configuration-file.icon b/Task/Read-a-configuration-file/Icon/read-a-configuration-file.icon new file mode 100644 index 0000000000..09a73c6557 --- /dev/null +++ b/Task/Read-a-configuration-file/Icon/read-a-configuration-file.icon @@ -0,0 +1,30 @@ +procedure main(A) + ws := ' \t' + vars := table() + every line := !&input do { + line ? { + tab(many(ws)) + if any('#;') | pos(0) then next + vars[map(tab(upto(ws)\1|0))] := getValue() + } + } + show(vars) +end + +procedure getValue() + ws := ' \t' + a := [] + while not pos(0) do { + tab(many(ws)) + put(a, trim(tab(upto(',')|0))) + move(1) + } + return a +end + +procedure show(t) + every pair := !sort(t) do { + every (s := pair[1]||" = ") ||:= !pair[2] || ", " + write(s[1:-2]) + } +end diff --git a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l b/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l index de382f05a4..b1c7dfb9d2 100644 --- a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l +++ b/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l @@ -1,4 +1,5 @@ (de rdConf (File) (pipe (in File (while (echo "#" ";") (till "^J"))) (while (read) + (skip) (set @ (or (line T) T)) ) ) ) diff --git a/Task/Read-a-configuration-file/Run-BASIC/read-a-configuration-file.run b/Task/Read-a-configuration-file/Run-BASIC/read-a-configuration-file.run new file mode 100644 index 0000000000..e48cd6513f --- /dev/null +++ b/Task/Read-a-configuration-file/Run-BASIC/read-a-configuration-file.run @@ -0,0 +1,36 @@ +dim param$(6) +dim paramVal$(6) +param$(1) = "fullname" +param$(2) = "favouritefruit" +param$(3) = "needspeeling" +param$(4) = "seedsremoved" +param$(5) = "otherfamily" +for i = 1 to 6 + paramVal$(i) = "false" +next i + +open DefaultDir$ + "\public\a.txt" for binary as #f +while not(eof(#f)) + line input #f, a$ + a$ = trim$(a$) + if instr("#;",left$(a$,1)) = 0 and a$ <> "" then + thisParam$ = lower$(word$(a$,1," ")) + for i = 1 to 5 + if param$(i) = thisParam$ then + paramVal$(i) = "true" + aa$ = trim$(mid$(a$,len(thisParam$)+2)) + if aa$ <> "" then paramVal$(i) = aa$ + end if + next i + end if +wend +close #f +for i = 1 to 5 + if instr(paramVal$(i),",") > 0 then + for j = 1 to 2 + print param$(i);"(";j;")";chr$(9);trim$(word$(paramVal$(i),j,",")) + next j + else + print param$(i);chr$(9);paramVal$(i) + end if +next i diff --git a/Task/Read-a-configuration-file/Scala/read-a-configuration-file-1.scala b/Task/Read-a-configuration-file/Scala/read-a-configuration-file-1.scala new file mode 100644 index 0000000000..7d0ec416cb --- /dev/null +++ b/Task/Read-a-configuration-file/Scala/read-a-configuration-file-1.scala @@ -0,0 +1,10 @@ +val conf = scala.io.Source.fromFile("config.file"). + getLines. + toList. + filter(_.trim.size > 0). + filterNot("#;" contains _(0)). + map(_ split(" ", 2) toList). + map(_ :+ "true" take 2). + map { + s:List[String] => (s(0).toLowerCase, s(1).split(",").map(_.trim).toList) + }.toMap diff --git a/Task/Read-a-configuration-file/Scala/read-a-configuration-file-2.scala b/Task/Read-a-configuration-file/Scala/read-a-configuration-file-2.scala new file mode 100644 index 0000000000..ab7adbdf1a --- /dev/null +++ b/Task/Read-a-configuration-file/Scala/read-a-configuration-file-2.scala @@ -0,0 +1,8 @@ +for ((k,v) <- conf) { + if (v.size == 1) + println("%s: %s" format (k, v(0))) + else + for (i <- 0 until v.size) + println("%s(%s): %s" format (k, i+1, v(i))) + +} diff --git a/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia b/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia index 6fbadf647e..678f0f6c85 100644 --- a/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia +++ b/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia @@ -1,5 +1,5 @@ -open("input_file","w") do f - for line in each_line(f) - #line operations +open("input_file","r") do f + for line in eachline(f) + println("read line: ", line) end end diff --git a/Task/Read-a-specific-line-from-a-file/TUSCRIPT/read-a-specific-line-from-a-file.tu b/Task/Read-a-specific-line-from-a-file/TUSCRIPT/read-a-specific-line-from-a-file.tu index 8368c485e5..1bd7ae9d4f 100644 --- a/Task/Read-a-specific-line-from-a-file/TUSCRIPT/read-a-specific-line-from-a-file.tu +++ b/Task/Read-a-specific-line-from-a-file/TUSCRIPT/read-a-specific-line-from-a-file.tu @@ -2,16 +2,3 @@ $$ MODE TUSCRIPT file="lines.txt" ERROR/STOP OPEN (file,READ,-std-) line2fetch=7 - ---> solution 1 -ACCESS file: READ/RECORDS/UTF8 $file s,line -LOOP n=1,99 -READ/NEXT/EXIT file -IF (n==line2fetch) PRINT line -ENDLOOP -ENDACCESS file - ---> solution 2 -line1to7=FILE (file,#line2fetch) -line=SELECT (line1to7,#line2fetch) -PRINT line diff --git a/Task/Read-entire-file/Deja-Vu/read-entire-file.djv b/Task/Read-entire-file/Deja-Vu/read-entire-file.djv new file mode 100644 index 0000000000..85214a3cf3 --- /dev/null +++ b/Task/Read-entire-file/Deja-Vu/read-entire-file.djv @@ -0,0 +1 @@ +local :filecontents !decode!utf-8 !read "file.txt" diff --git a/Task/Read-entire-file/Julia/read-entire-file-1.julia b/Task/Read-entire-file/Julia/read-entire-file-1.julia new file mode 100644 index 0000000000..6d32ab1a8c --- /dev/null +++ b/Task/Read-entire-file/Julia/read-entire-file-1.julia @@ -0,0 +1,2 @@ +readall("/devel/myfile.txt") # read file into a string +open(readbytes, "/devel/myfile.txt") # read file into an array of bytes diff --git a/Task/Read-entire-file/Julia/read-entire-file-2.julia b/Task/Read-entire-file/Julia/read-entire-file-2.julia new file mode 100644 index 0000000000..96339a82f6 --- /dev/null +++ b/Task/Read-entire-file/Julia/read-entire-file-2.julia @@ -0,0 +1,2 @@ +f = open("/devel/myfile.txt", "r") +A = mmap_array(Uint8, (filesize("/devel/myfile.txt"),), f) diff --git a/Task/Read-entire-file/Julia/read-entire-file.julia b/Task/Read-entire-file/Julia/read-entire-file.julia deleted file mode 100644 index d7cf6437e6..0000000000 --- a/Task/Read-entire-file/Julia/read-entire-file.julia +++ /dev/null @@ -1,4 +0,0 @@ -sample_filepath = "/devel/myfile.txt" -f = open(sample_filepath) -file_contents = readall(f) # load all into a single String -close(f) diff --git a/Task/Read-entire-file/Run-BASIC/read-entire-file.run b/Task/Read-entire-file/Run-BASIC/read-entire-file.run new file mode 100644 index 0000000000..e7c0b07c0f --- /dev/null +++ b/Task/Read-entire-file/Run-BASIC/read-entire-file.run @@ -0,0 +1,5 @@ +open DefaultDir$ + "/public/test.txt" for binary as #f +fileLen = LOF(#f) +a$ = input$(#f, fileLen) +print a$ +close #f diff --git a/Task/Read-entire-file/Scala/read-entire-file.scala b/Task/Read-entire-file/Scala/read-entire-file.scala new file mode 100644 index 0000000000..c70fafa841 --- /dev/null +++ b/Task/Read-entire-file/Scala/read-entire-file.scala @@ -0,0 +1,6 @@ +object TextFileSlurper extends App { + val fileLines = + try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch { + case e: java.io.FileNotFoundException => "" + } +} diff --git a/Task/Read-entire-file/Scheme/read-entire-file-1.ss b/Task/Read-entire-file/Scheme/read-entire-file-1.ss new file mode 100644 index 0000000000..732bb4a323 --- /dev/null +++ b/Task/Read-entire-file/Scheme/read-entire-file-1.ss @@ -0,0 +1,8 @@ +(with-input-from-file "foo.txt" + (lambda () + (reverse-list->string + (let loop ((char (read-char)) + (result '())) + (if (eof-object? char) + result + (loop (read-char) (cons char result))))))) diff --git a/Task/Read-entire-file/Scheme/read-entire-file-2.ss b/Task/Read-entire-file/Scheme/read-entire-file-2.ss new file mode 100644 index 0000000000..8da9ce3edf --- /dev/null +++ b/Task/Read-entire-file/Scheme/read-entire-file-2.ss @@ -0,0 +1 @@ +(with-input-from-file "foo.txt" read-string) diff --git a/Task/Read-entire-file/Seed7/read-entire-file.seed7 b/Task/Read-entire-file/Seed7/read-entire-file.seed7 new file mode 100644 index 0000000000..4420108f69 --- /dev/null +++ b/Task/Read-entire-file/Seed7/read-entire-file.seed7 @@ -0,0 +1,9 @@ +$ include "seed7_05.s7i"; + include "getf.s7i"; + +const proc: main is func + local + var string: fileContent is ""; + begin + fileContent := getf("text.txt"); + end func; diff --git a/Task/Real-constants-and-functions/Julia/real-constants-and-functions.julia b/Task/Real-constants-and-functions/Julia/real-constants-and-functions.julia new file mode 100644 index 0000000000..ba7a113f71 --- /dev/null +++ b/Task/Real-constants-and-functions/Julia/real-constants-and-functions.julia @@ -0,0 +1,9 @@ +e +π, pi +sqrt(x) +log(x) +exp(x) +abs(x) +floor(x) +ceil(x) +x^y diff --git a/Task/Real-constants-and-functions/PicoLisp/real-constants-and-functions.l b/Task/Real-constants-and-functions/PicoLisp/real-constants-and-functions.l index 4d8d55427f..535cfb5d07 100644 --- a/Task/Real-constants-and-functions/PicoLisp/real-constants-and-functions.l +++ b/Task/Real-constants-and-functions/PicoLisp/real-constants-and-functions.l @@ -5,7 +5,7 @@ (prinl (format pi *Scl)) # pi (prinl (format (pow 2.0 0.5) *Scl)) # sqare root -(prinl (format (sqrt (* 2.0 1.0)) *Scl)) +(prinl (format (sqrt 2.0 1.0) *Scl)) (prinl (format (log 2.0) *Scl)) # logarithm (prinl (format (exp 4.0) *Scl)) # exponential diff --git a/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb b/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb index dbd4d5b7f0..8830d3a83e 100644 --- a/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb +++ b/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb @@ -2,6 +2,7 @@ Math::E #e Math::PI #pi Math.sqrt(x) #square root Math.log(x) #natural logarithm +Math.log(x, y) #logarithm base y Math.log10(x) #base 10 logarithm Math.exp(x) #exponential x.abs #absolute value diff --git a/Task/Regular-expressions/Julia/regular-expressions-1.julia b/Task/Regular-expressions/Julia/regular-expressions-1.julia index fec476817e..85db99cb5d 100644 --- a/Task/Regular-expressions/Julia/regular-expressions-1.julia +++ b/Task/Regular-expressions/Julia/regular-expressions-1.julia @@ -1,5 +1,4 @@ -julia> ismatch(r"^\s*(?:#|$)", "not a comment") -false - -julia> ismatch(r"^\s*(?:#|$)", "# a comment") -true +s = "I am a string" +if ismatch(r"string$", s) + println("'$s' ends with 'string'") +end diff --git a/Task/Regular-expressions/Julia/regular-expressions-2.julia b/Task/Regular-expressions/Julia/regular-expressions-2.julia index 5694f93d56..8e4395eede 100644 --- a/Task/Regular-expressions/Julia/regular-expressions-2.julia +++ b/Task/Regular-expressions/Julia/regular-expressions-2.julia @@ -1,41 +1,2 @@ -julia> m = match(r"(a|b)(c)?(d)", "acd") -RegexMatch("acd", 1="a", 2="c", 3="d") - -julia> m.match -"acd" - -julia> m.captures -3-element Union(UTF8String,ASCIIString,Nothing) Array: - "a" - "c" - "d" - -julia> m.offset -1 - -julia> m.offsets -3-element Int64 Array: - 1 - 2 - 3 - -julia> m = match(r"(a|b)(c)?(d)", "ad") -RegexMatch("ad", 1="a", 2=nothing, 3="d") - -julia> m.match -"ad" - -julia> m.captures -3-element Union(UTF8String,ASCIIString,Nothing) Array: - "a" - nothing - "d" - -julia> m.offset -1 - -julia> m.offsets -3-element Int64 Array: - 1 - 0 - 2 +s = "I am a string" +s = replace(s, r" (a|an) ", " another ") diff --git a/Task/Remove-duplicate-elements/Deja-Vu/remove-duplicate-elements.djv b/Task/Remove-duplicate-elements/Deja-Vu/remove-duplicate-elements.djv new file mode 100644 index 0000000000..0d703fe964 --- /dev/null +++ b/Task/Remove-duplicate-elements/Deja-Vu/remove-duplicate-elements.djv @@ -0,0 +1,4 @@ +} +for item in [ 1 10 1 :hi :hello :hi :hi ]: + @item +!. keys set{ diff --git a/Task/Rename-a-file/Clipper/rename-a-file.clipper b/Task/Rename-a-file/Clipper/rename-a-file.clipper index 9ad0109608..e05e2f589e 100644 --- a/Task/Rename-a-file/Clipper/rename-a-file.clipper +++ b/Task/Rename-a-file/Clipper/rename-a-file.clipper @@ -1,2 +1,7 @@ FRename( "input.txt","output.txt") +or +RENAME input.txt TO output.txt + FRename("\input.txt","\output.txt") +or +RENAME \input.txt TO \output.txt diff --git a/Task/Rename-a-file/Julia/rename-a-file.julia b/Task/Rename-a-file/Julia/rename-a-file.julia new file mode 100644 index 0000000000..9a80f7012a --- /dev/null +++ b/Task/Rename-a-file/Julia/rename-a-file.julia @@ -0,0 +1,4 @@ +mv("input.txt", "output.txt") +mv("docs", "mydocs") +mv("/input.txt", "/output.txt") +mv("/docs", "/mydocs") diff --git a/Task/Repeat-a-string/Deja-Vu/repeat-a-string.djv b/Task/Repeat-a-string/Deja-Vu/repeat-a-string.djv new file mode 100644 index 0000000000..49800e4ad8 --- /dev/null +++ b/Task/Repeat-a-string/Deja-Vu/repeat-a-string.djv @@ -0,0 +1 @@ +!. concat( rep 5 "ha" ) diff --git a/Task/Repeat-a-string/Nimrod/repeat-a-string.nimrod b/Task/Repeat-a-string/Nimrod/repeat-a-string.nimrod new file mode 100644 index 0000000000..5e600de07c --- /dev/null +++ b/Task/Repeat-a-string/Nimrod/repeat-a-string.nimrod @@ -0,0 +1,2 @@ +import strutils +repeatStr(5, "ha") diff --git a/Task/Repeat-a-string/VBA/repeat-a-string.vba b/Task/Repeat-a-string/VBA/repeat-a-string-1.vba similarity index 100% rename from Task/Repeat-a-string/VBA/repeat-a-string.vba rename to Task/Repeat-a-string/VBA/repeat-a-string-1.vba diff --git a/Task/Repeat-a-string/VBA/repeat-a-string-2.vba b/Task/Repeat-a-string/VBA/repeat-a-string-2.vba new file mode 100644 index 0000000000..2b0e33fbc1 --- /dev/null +++ b/Task/Repeat-a-string/VBA/repeat-a-string-2.vba @@ -0,0 +1,3 @@ +Public Function RepeatString(stText As String, iQty As Integer) As String +RepeatString = Replace(String(iQty, "x"), "x", stText) +End Function diff --git a/Task/Repeat-a-string/VBScript/repeat-a-string.vb b/Task/Repeat-a-string/VBScript/repeat-a-string.vb new file mode 100644 index 0000000000..8f2f2124d8 --- /dev/null +++ b/Task/Repeat-a-string/VBScript/repeat-a-string.vb @@ -0,0 +1,7 @@ +' VBScript has a String() function that can repeat a character a given number of times +' but this only works with single characters (or the 1st char of a string): +WScript.Echo String(10, "123") ' Displays "1111111111" + +' To repeat a string of chars, you can use either of the following "hacks"... +WScript.Echo Replace(Space(10), " ", "Ha") +WScript.Echo Replace(String(10, "X"), "X", "Ha") diff --git a/Task/Resistor-mesh/Julia/resistor-mesh.julia b/Task/Resistor-mesh/Julia/resistor-mesh.julia new file mode 100644 index 0000000000..887fcf9fb7 --- /dev/null +++ b/Task/Resistor-mesh/Julia/resistor-mesh.julia @@ -0,0 +1,7 @@ +N = 10 +D1 = speye(N-1,N) - spdiagm(ones(N-1),1,N-1,N) +D = [ kron(D1, speye(N)); kron(speye(N), D1) ] +i, j = N*1 + 2, N*7+7 +b = zeros(N^2); b[i], b[j] = 1, -1 +v = (D' * D) \ b +v[i] - v[j] diff --git a/Task/Return-multiple-values/C++/return-multiple-values.cpp b/Task/Return-multiple-values/C++/return-multiple-values.cpp index 24cb067615..384eeffcfa 100644 --- a/Task/Return-multiple-values/C++/return-multiple-values.cpp +++ b/Task/Return-multiple-values/C++/return-multiple-values.cpp @@ -1,19 +1,18 @@ #include #include -#include +#include -std::tr1::tuple minmax ( const int * numbers , const int num ) { +std::tuple minmax ( const int * numbers , const int num ) { const int *maximum = std::max_element ( numbers , numbers + num ) ; const int *minimum = std::min_element ( numbers , numbers + num ) ; - std::tr1::tuple result( *maximum , *minimum ) ; - return result ; + return std::make_tuple( *maximum , *minimum ) ; } int main( ) { const int numbers[ ] = { 17 , 88 , 9 , 33 , 4 , 987 , -10 , 2 } ; int numbersize = sizeof( numbers ) / sizeof ( int ) ; - std::tr1::tuple result = minmax( numbers , numbersize ) ; - std::cout << "The greatest number is " << std::tr1::get<0>( result ) - << " , the smallest " << std::tr1::get<1>( result ) << " !\n" ; + std::tuple result = minmax( numbers , numbersize ) ; + std::cout << "The greatest number is " << std::get<0>( result ) + << " , the smallest " << std::get<1>( result ) << " !\n" ; return 0 ; } diff --git a/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv b/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv index 08266e85bb..aa3e690fe4 100644 --- a/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv +++ b/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv @@ -1,4 +1,4 @@ function-returning-multiple-values: 10 20 -print print function-returning-multiple-values +!print !print function-returning-multiple-values diff --git a/Task/Reverse-a-string/Deja-Vu/reverse-a-string.djv b/Task/Reverse-a-string/Deja-Vu/reverse-a-string.djv new file mode 100644 index 0000000000..dc92ae01db --- /dev/null +++ b/Task/Reverse-a-string/Deja-Vu/reverse-a-string.djv @@ -0,0 +1 @@ +!print concat chars "Hello" diff --git a/Task/Reverse-a-string/VBScript/reverse-a-string.vb b/Task/Reverse-a-string/VBScript/reverse-a-string.vb new file mode 100644 index 0000000000..7fef075410 --- /dev/null +++ b/Task/Reverse-a-string/VBScript/reverse-a-string.vb @@ -0,0 +1 @@ +WScript.Echo StrReverse("asdf") diff --git a/Task/Rock-paper-scissors/PL-I/rock-paper-scissors.pli b/Task/Rock-paper-scissors/PL-I/rock-paper-scissors.pli new file mode 100644 index 0000000000..4f250d06ac --- /dev/null +++ b/Task/Rock-paper-scissors/PL-I/rock-paper-scissors.pli @@ -0,0 +1,31 @@ +rock: procedure options (main); /* 30 October 2013 */ + declare move character (1), cm fixed binary; + + put ('The Rock-Paper-Scissors game'); + put skip list ("please type 'r' for rock, 'p' for paper, 's' for scissors."); + put skip list ("Anything else finishes:"); + do forever; + get edit (move) (a(1)); + move = lowercase(move); + if index('rpsq', move) = 0 then iterate; + if move = 'q' then stop; + cm = random()*3; /* computer moves: 0 = rock, 1 = paper, 2 = scissors */ + select (cm); + when (0) select (move); + when ('r') put list ('rock and rock: A draw'); + when ('p') put list ('paper beats rock: You win'); + when ('s') put list ('rock breaks scissors: I win'); + end; + when (1) select (move); + when ('r') put list ('paper beats rock: I win'); + when ('p') put list ('paper and paper: A draw'); + when ('s') put list ('scissors cut paper: You win'); + end; + when (2) select (move); + when ('r') put list ('rock breaks scissors: You win'); + when ('p') put list ('scissors cuts paper: I win'); + when ('s') put list ('Scissors and Scissors: A draw'); + end; + end; + end; +end rock; diff --git a/Task/Rock-paper-scissors/UNIX-Shell/rock-paper-scissors.sh b/Task/Rock-paper-scissors/UNIX-Shell/rock-paper-scissors.sh new file mode 100644 index 0000000000..af89915669 --- /dev/null +++ b/Task/Rock-paper-scissors/UNIX-Shell/rock-paper-scissors.sh @@ -0,0 +1,63 @@ +#!/bin/bash +choices=(rock paper scissors) + +# comparison function, works like Perl +# winner x y = 2 if y beats x, 1 if x beats 1, 0 if it's a tie +winner() { + local left="$1" right="$2" + echo $(( (3 + left - right) % 3 )) +} + + +human_counts=(1 1 1) +human_count=3 +computer_counts=(0 0 0) +games=0 human=0 computer=0 + +PS3="What do you throw? " +while true; do + select choice in rock paper scissors quit; do + if [ -z "$choice" ]; then choice="$REPLY"; fi + if [ "$choice" = "quit" ]; then + break 2 + fi + for (( h=0; h<${#choices[@]}; ++h )); do + if [ "${choices[h]}" = "$choice" ]; then + break + fi + done + if (( h < 3 )); then + break + fi + echo "Unrecognized choice. Try again!" + done + + let n=RANDOM%human_count + for (( c=0; c<${#human_counts[@]}; ++c )); do + let n-=${human_counts[c]} + if (( n < 0 )); then + break + fi + done + let computer_counts[c]+=1 + echo + echo "You chose ${choices[h]^^}" + echo "I chose ${choices[c]^^}" + w="$(winner "$c" "$h")" + case "$w" in + 2) echo "YOU WIN!"; let human+=1;; + 0) echo "TIE!";; + 1) echo "I WIN!"; let computer+=1;; + *) echo "winner returned weird result '$w'";; + esac + echo + let games+=1 + (( human_counts[(h+1)%3]+=1, human_count+=1 )) +done + +echo +echo "We played $games games. You won $human, and I won $computer." +for (( i=0; i<3; ++i )); do + echo "You picked ${choices[i]} $(( human_counts[ (i+1)%3 ] - 1 )) times." + echo "I picked ${choices[i]} $(( computer_counts[i] )) times." +done diff --git a/Task/Roman-numerals-Decode/Ada/roman-numerals-decode.ada b/Task/Roman-numerals-Decode/Ada/roman-numerals-decode.ada index 36ebbb7da5..f6eaedd0bb 100644 --- a/Task/Roman-numerals-Decode/Ada/roman-numerals-decode.ada +++ b/Task/Roman-numerals-Decode/Ada/roman-numerals-decode.ada @@ -1,46 +1,151 @@ -with Ada.Text_IO; +Pragma Ada_2012; +Pragma Assertion_Policy( Check ); -procedure Decode_Roman_Numerals is +With +Unchecked_Conversion, +Ada.Text_IO; - function Roman_To_Integer(A_Roman: String) return Integer is +Procedure Test_Roman_Numerals is - function Decode_Roman_Digit (A_Char: Character) return Integer is - begin - case A_Char is - when 'M' | 'm' => return 1000; - when 'D' | 'd' => return 500; - when 'C' | 'c' => return 100; - when 'L' | 'l' => return 50; - when 'X' | 'x' => return 10; - when 'V' | 'v' => return 5; - when 'I' | 'i' => return 1; - when others => return 0; - end case; - end Decode_Roman_Digit; + -- We create an enumeration of valid characters, note that they are + -- character-literals, this is so that we can use literal-strings, + -- and that their size is that of Integer. + Type Roman_Digits is ('I', 'V', 'X', 'L', 'C', 'D', 'M' ) + with Size => Integer'Size; - L_Curr_Val: Integer; - L_Last_Val: Integer; + -- We use a representation-clause ensure the proper integral-value + -- of each individual character. + For Roman_Digits use + ( + 'I' => 1, + 'V' => 5, + 'X' => 10, + 'L' => 50, + 'C' => 100, + 'D' => 500, + 'M' => 1000 + ); - Result: Integer; - begin - Result := 0; + -- To convert a Roman_Digit to an integer, we now only need to + -- read its value as an integer. + Function Convert is new Unchecked_Conversion + ( Source => Roman_Digits, Target => Integer ); - L_Last_Val := 0; + -- Romena_Numeral is a string of Roman_Digit. + Type Roman_Numeral is array (Positive range <>) of Roman_Digits; - for i in reverse 1 .. A_Roman'Length loop - L_Curr_Val := Decode_Roman_Digit(A_Roman(I)); - if L_Curr_Val < L_Last_Val then - Result := Result - L_Curr_Val; - else - Result := Result + L_Curr_Val; - end if; - L_Last_Val := L_Curr_Val; - end loop; - return Result; - end Roman_To_Integer; + -- The Numeral_List type is used herein only for testing + -- and verification-data. + Type Numeral_List is array (Positive range <>) of + not null access Roman_Numeral; -begin - Ada.Text_IO.Put_Line(Integer'Image(Roman_To_Integer("MCMXC"))); -- 1990 - Ada.Text_IO.Put_Line(Integer'Image(Roman_To_Integer("MMVIII"))); -- 2008 - Ada.Text_IO.Put_Line(Integer'Image(Roman_To_Integer("MDCLXVI"))); -- 1666 -end Decode_Roman_Numerals; + -- The Test_Cases subtype ensures that Test_Data and Validation_Data + -- both contain the same number of elements, and that the indecies + -- are the same; essentially the same as: + -- + -- pragma Assert( Test_Data'Length = Validation_Data'Length + -- AND Test_Data'First = Validation_Data'First); + + subtype Test_Cases is Positive range 1..14; + + Test_Data : constant Numeral_List(Test_Cases):= + ( + New Roman_Numeral'("III"), -- 3 + New Roman_Numeral'("XXX"), -- 30 + New Roman_Numeral'("CCC"), -- 300 + New Roman_Numeral'("MMM"), -- 3000 + + New Roman_Numeral'("VII"), -- 7 + New Roman_Numeral'("LXVI"), -- 66 + New Roman_Numeral'("CL"), -- 150 + New Roman_Numeral'("MCC"), -- 1200 + + New Roman_Numeral'("IV"), -- 4 + New Roman_Numeral'("IX"), -- 9 + New Roman_Numeral'("XC"), -- 90 + + New Roman_Numeral'("ICM"), -- 901 + New Roman_Numeral'("CIM"), -- 899 + + New Roman_Numeral'("MDCLXVI") -- 1666 + ); + + Validation_Data : constant array(Test_Cases) of Natural:= + ( 3, 30, 300, 3000, + 7, 66, 150, 1200, + 4, 9, 90, + 901, 899, + 1666 + ); + + + -- In Roman numerals, the subtractive form [IV = 4] was used + -- very infrequently, the most common form was the addidive + -- form [IV = 6]. (Consider military logistics and squads.) + + -- SUM returns the Number, read in the additive form. + Function Sum( Number : Roman_Numeral ) return Natural is + begin + Return Result : Natural:= 0 do + For Item of Number loop + Result:= Result + Convert( Item ); + end loop; + End Return; + end Sum; + + -- EVAL returns Number read in the subtractive form. + Function Eval( Number : Roman_Numeral ) return Natural is + Current : Roman_Digits:= 'I'; + begin + Return Result : Natural:= 0 do + For Item of Number loop + if Current < Item then + Result:= Convert(Item) - Result; + Current:= Item; + else + Result:= Result + Convert(Item); + end if; + end loop; + End Return; + end Eval; + + -- Display the given Roman_Numeral via Text_IO. + Procedure Put( S: Roman_Numeral ) is + begin + For Ch of S loop + declare + -- The 'Image attribute returns the character inside + -- single-quotes; so we select the character itself. + C : Character renames Roman_Digits'Image(Ch)(2); + begin + Ada.Text_IO.Put( C ); + end; + end loop; + end; + + -- This displays pass/fail dependant on the parameter. + Function PF ( Value : Boolean ) Return String is + begin + Return Result : String(1..4):= ( if Value then"pass"else"fail" ); + End PF; + +Begin + Ada.Text_IO.Put_Line("Starting Test:"); + + for Index in Test_Data'Range loop + declare + Item : Roman_Numeral renames Test_Data(Index).all; + Value : constant Natural := Eval(Item); + begin + Put( Item ); + + Ada.Text_IO.Put( ASCII.HT & "= "); + Ada.Text_IO.Put( Value'Img ); + Ada.Text_IO.Put_Line( ASCII.HT & '[' & + PF( Value = Validation_Data(Index) )& ']'); + end; + end loop; + + + Ada.Text_IO.Put_Line("Testing complete."); +End Test_Roman_Numerals; 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 new file mode 100644 index 0000000000..19a7c263ea --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj @@ -0,0 +1,5 @@ +; 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)) ) 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 new file mode 100644 index 0000000000..72280618c8 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj @@ -0,0 +1,7 @@ +; 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) )) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-3.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-3.clj new file mode 100644 index 0000000000..33cc424dbe --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-3.clj @@ -0,0 +1,11 @@ +; v1.1 if solutions: 0, nil; 1, float; 2, list +(defn quad_func_1_1 [a b c] + (def d + (- (* b b) + (* 4 a c)) ) + (if (< d 0) + nil + (if (> d 0) + (list (quad_func_sign a b d -1) + (quad_func_sign a b d +1)) + (quad_func_sign a b d +1)) )) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-4.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-4.clj new file mode 100644 index 0000000000..27b95f21b6 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-4.clj @@ -0,0 +1,11 @@ +; v1.2 return a list +(defn quad_func [a b c] + (def d + (- (* b b) + (* 4 a c)) ) + (if (< d 0) + (list) + (if (> d 0) + (list (quad_func_sign a b d -1) + (quad_func_sign a b d +1)) + (list (quad_func_sign a b d +1)) )) ) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-5.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-5.clj new file mode 100644 index 0000000000..d2e6cc0eb3 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-5.clj @@ -0,0 +1,6 @@ +user=> (quad_func 1.0 1.0 1.0) +() +user=> (quad_func 1.0 2.0 1.0) +(1.0) +user=> (quad_func 1.0 3.0 1.0) +(0.3819660112501051 2.618033988749895) diff --git a/Task/Roots-of-a-quadratic-function/GAP/roots-of-a-quadratic-function.gap b/Task/Roots-of-a-quadratic-function/GAP/roots-of-a-quadratic-function.gap index 213cc8954c..d0a390b289 100644 --- a/Task/Roots-of-a-quadratic-function/GAP/roots-of-a-quadratic-function.gap +++ b/Task/Roots-of-a-quadratic-function/GAP/roots-of-a-quadratic-function.gap @@ -8,3 +8,7 @@ end; QuadraticRoots(2, 2, -1); # [ 1/2*E(12)^4-1/2*E(12)^7+1/2*E(12)^8+1/2*E(12)^11, # 1/2*E(12)^4+1/2*E(12)^7+1/2*E(12)^8-1/2*E(12)^11 ] + +# This works also with floating-point numbers +QuadraticRoots(2.0, 2.0, -1.0); +# [ 0.366025, -1.36603 ] diff --git a/Task/Roots-of-a-quadratic-function/Icon/roots-of-a-quadratic-function.icon b/Task/Roots-of-a-quadratic-function/Icon/roots-of-a-quadratic-function.icon new file mode 100644 index 0000000000..a22809d56d --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Icon/roots-of-a-quadratic-function.icon @@ -0,0 +1,10 @@ +procedure main() + solve(1.0, -10.0e5, 1.0) +end + +procedure solve(a,b,c) + d := sqrt(b*b - 4.0*a*c) + roots := if b < 0 then [r1 := (-b+d)/2.0*a, c/(a*r1)] + else [r1 := (-b-d)/2.0*a, c/(a*r1)] + write(a,"*x^2 + ",b,"*x + ",c," has roots ",roots[1]," and ",roots[2]) +end diff --git a/Task/Roots-of-unity/D/roots-of-unity.d b/Task/Roots-of-unity/D/roots-of-unity.d index 5134deeea5..d60a93329c 100644 --- a/Task/Roots-of-unity/D/roots-of-unity.d +++ b/Task/Roots-of-unity/D/roots-of-unity.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.range, std.algorithm; -auto nthRoots(in int n) /*pure nothrow*/ { +auto nthRoots(in int n) pure nothrow { return n.iota.map!(k => expi(PI * 2 * (k + 1) / n)); } diff --git a/Task/Roots-of-unity/Julia/roots-of-unity.julia b/Task/Roots-of-unity/Julia/roots-of-unity.julia new file mode 100644 index 0000000000..51dbc9d7b4 --- /dev/null +++ b/Task/Roots-of-unity/Julia/roots-of-unity.julia @@ -0,0 +1 @@ +nthroots(n::Integer) = [ cospi(2k/n)+sinpi(2k/n)im for k = 0:n-1 ] diff --git a/Task/Rosetta-Code-Count-examples/Perl-6/rosetta-code-count-examples.pl6 b/Task/Rosetta-Code-Count-examples/Perl-6/rosetta-code-count-examples.pl6 new file mode 100644 index 0000000000..c40edbd79d --- /dev/null +++ b/Task/Rosetta-Code-Count-examples/Perl-6/rosetta-code-count-examples.pl6 @@ -0,0 +1,10 @@ +use LWP::Simple; + +my $site = "http://rosettacode.org"; +my $list-url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; + +for get("$site$list_url").comb(/'cm' .*? 'title="' <( .*? )> '"'/) { + my $slug = .trans(' ' => '_'); + my $count = +get("$site/wiki/$slug").comb(/'toclevel-1'/); + say "$_: $count examples"; +} diff --git a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags.rexx b/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags.rexx new file mode 100644 index 0000000000..499c7783a7 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags.rexx @@ -0,0 +1,21 @@ +/*REXX program fixes (changes) depreciated code tags with newer tags.*/ +@ = '<' /*ensure RC doesn't get confused.*/ +old. = /*define a default value for OLD.*/ +old.1 = @'%s>' ; new.1 = @'lang %s>' +old.2 = @'/%s>' ; new.2 = @'/lang>' +old.3 = @'code %s>' ; new.3 = @'lang %s>' +old.4 = @'/code>' ; new.4 = @'/lang>' + +ifid = 'Wikisource.txt' /* Input File IDentifier. */ +ofid = 'converted.txt' /*Output " " */ + + do while lines(ifid) \== 0 /*keep trunkin' until it's done. */ + _=linein(ifid) /*read a record from input file. */ + + do j=1 while old.j \== '' /*change old ──► new until done. */ + _=changestr(new.j,_,old.j) /*let REXX do the heavy lifting. */ + end /*j*/ + + call lineout ofid,_ /*write the re-formatted record. */ + end /*while lines(ifid...*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION index 6309f92369..ac484bda6e 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 October 15 2013: +Sample output on January 15 2014: -
  1. 759 - Tcl
-  2. 722 - Racket
-  3. 707 - Python
-  4. 672 - C
-  5. 642 - J
-  6. 634 - Perl 6
-  7. 631 - D
-  8. 627 - PicoLisp
-  9. 610 - Go
- 10. 610 - Ruby
- 11. 578 - Perl
- 12. 574 - Ada
- 13. 565 - Mathematica
- 14. 556 - Haskell
- 15. 543 - REXX
- 16. 524 - Java
- 17. 521 - BBC BASIC
- 18. 511 - Unicon
- 19. 484 - OCaml
- 20. 471 - C++
- 21. 470 - Icon
+
  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. 442 - Common Lisp
- 24. 435 - C sharp
- 25. 430 - AutoHotkey
- 26. 381 - Erlang
- 27. 381 - JavaScript
- 28. 374 - Scala
- 29. 369 - Clojure
- 30. 358 - PARI/GP
- 31. 335 - Lua
- 32. 331 - R
- 33. 330 - Seed7
- 34. 327 - ALGOL 68
- 35. 327 - PHP
- 36. 323 - Forth
- 37. 320 - Fortran
- 38. 312 - F Sharp
- 39. 310 - Pascal
- 40. 306 - Groovy
+ 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
+ 40. 307 - Liberty BASIC
 ...
-A complete ranked listing of all '''498''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. +A complete ranked listing of all '''505''' 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/D/rosetta-code-rank-languages-by-popularity.d b/Task/Rosetta-Code-Rank-languages-by-popularity/D/rosetta-code-rank-languages-by-popularity.d index 68a84f343d..840be3d71d 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/D/rosetta-code-rank-languages-by-popularity.d +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/D/rosetta-code-rank-languages-by-popularity.d @@ -1,24 +1,20 @@ -import std.stdio, std.algorithm, std.conv, std.array, std.regex, - std.typecons, std.net.curl; - void main() { - // Get a list of just the programming languages. + import std.stdio, std.algorithm, std.conv, std.array, std.regex, + std.typecons, std.net.curl; + immutable r1 = `"title":"Category:([^"]+)"`; const languages = get("www.rosettacode.org/w/api.php?action=query"~ "&list=categorymembers&cmtitle=Category:Pro"~ "gramming_Languages&cmlimit=500&format=json") - .match(r1.regex("g")).map!q{a[1].dup}.array; + .matchAll(r1).map!q{ a[1].dup }.array; - // Get a pagecount for all categories. - immutable r2 = `title="Category:([^"]+)">[^<]+` ~ - `[^(]+\((\d+) members\)`; - const pairs = get("www.rosettacode.org/w/index.php?" ~ + auto pairs = get("www.rosettacode.org/w/index.php?" ~ "title=Special:Categories&limit=5000") - .match(r2.regex("g")) + .matchAll(`title="Category:([^"]+)">[^<]+` ~ + `[^(]+\((\d+) members\)`) .filter!(m => languages.canFind(m[1])) - .map!(m => tuple(m[2].to!uint, m[1].dup)) - .array.sort!q{a > b}.release; + .map!(m => tuple(m[2].to!uint, m[1].dup)); - foreach (i, res; pairs) + foreach (i, res; pairs.array.sort!q{a > b}.release) writefln("%3d. %3d - %s", i + 1, res[]); } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Groovy/rosetta-code-rank-languages-by-popularity.groovy b/Task/Rosetta-Code-Rank-languages-by-popularity/Groovy/rosetta-code-rank-languages-by-popularity.groovy new file mode 100644 index 0000000000..8012045e73 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Groovy/rosetta-code-rank-languages-by-popularity.groovy @@ -0,0 +1,9 @@ +def html = new URL('http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000').getText([ + connectTimeout:500, + readTimeout:15000, + requestProperties: [ 'User-Agent': 'Firefox/2.0.0.4']]) +def count = [:] +(html =~ '
  • ]+>([^<]+)[^(]*[(](\\d+) member[s]*[)]
  • ').each { match, language, members -> + count[language] = (members as int) +} +count.sort { v1, v2 -> v2.value <=> v1.value }.eachWithIndex { value, index -> println "${index + 1} $value" } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/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 4f49619b43..ccb563d7ef 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 @@ -1,100 +1,101 @@ -/*REXX program read two files and produces a ranked list of RC languages*/ -sep='█'; L.=0; #.=0; u.=0; catHeap= /*assign variable defaults.*/ -parse arg cutoff CinFID LinFID outFID . /*obtain specified options.*/ -if cutoff==',' | cutoff=='' then cutoff=0 /*assume no cutoff default.*/ - -if CinFID=='' then CinFID='RC_POP.CAT' /*not specified? Use default. */ -if LinFID=='' then LinFID='RC_POP.LAN' /*not specified? Use default. */ -if outFID=='' then outFID='RC_POP.OUT' /*not specified? Use default. */ - -call tell center('timestamp: ' date() time('Civil'),79,'═'), 1, 1 -#langs=reader('lang') /*assign to L.ααα */ -#cats =reader('cat') /*append to the catHeap*/ +/*REXX pgm reads 2 files, shows a ranked list of Rosetta Code languages.*/ +sep='█'; L.=0; #.=0; u.=0; catHeap=; old.= /*assign variable defaults. */ +parse arg cutoff CinFID LinFID outFID . /*obtain specified options. */ +if cutoff==',' | cutoff=='' then cutoff=0 /*assume no cutoff default. */ +if CinFID=='' then CinFID = 'RC_POP.CAT' /*Not specified? Use default.*/ +if LinFID=='' then LinFID = 'RC_POP.LAN' /* " " " " */ +if outFID=='' then outFID = 'RC_POP.OUT' /* " " " " */ +call tell center('timestamp: ' date() time('Civil'),79,'═'), 2, 1 +call reader 'lang' /*assign to L.ααα */ +call reader 'cat' /*append to the catHeap*/ #=0 /*number of categories.*/ - do j=1 until catHeap=='' /*process heap of cats.*/ - parse var catHeap cat.j (sep) catHeap /*pick off a category. */ - parse var cat.j cat.j '<' '(' mems . /*untangle the string. */ - cat.j=space(cat.j); _=cat.j; upper _ /*remove excess blanks.*/ + do j=1 until catHeap=='' /*process heap of cats.*/ + parse var catHeap cat.j (sep) catHeap /*pick off a category. */ + parse var cat.j cat.j '<' "(" mems . /*untangle the string. */ + cat.j=space(cat.j); _=cat.j; upper _ /*remove excess blanks.*/ if _=='' | \L._ then iterate /*blank or ¬ a language*/ if \datatype(mems,'W') then iterate /*"members" ¬ numeric.*/ - /*handle duplicates. */ - if u._\==0 then do /*(next) Possible echo the duplicate to screen.*/ - /*─── say duplicate found: ' cat.j ───*/ - do f=1 for # until _==@u.f; end /*f*/ -say cat.j 'is a dup, old=' #.f 'add mems='mems + if u._\==0 then do /*[↓] handle duplicates*/ + do f=1 for # until _==@u.f; end /*f*/ #.f=#.f+mems; iterate j - end + end /* [↑] languages that are in different cases.*/ u._=u._+1 - #=#+1; #.#=mems; @.#=cat.j; @u.#=_; #.#=mems /*bump counter, assign.*/ - end /*j*/ + #=#+1; #.#=#.#+mems; @.#=cat.j; @u.#=_ /*bump counter, assign.*/ + end /*j=1 until ···*/ +!.= /*array holds indication of TIED.*/ +call tell right(#,9) '(total) number of languages detected.', , 1 +call eSort #,0 /*sort the languages along with #*/ +r=0 /*add true rank (tR) ──► entries.*/ +tied=; do j=# by -1 for #; r=r+1; tR=r; !tR.j=r; jp=j+1; jm=j-1 + if tied=='' then pR=r; tied= /*handle if the rank is untied.*/ + if #.j==#.jp | #.j==#.jm then do; !.j='[tied]'; tied=!.j; end + if #.j==#.jp then do; tR=pR; !tR.j=pR; end + else pR=r + end /*j=# by ···*/ -call tell # '(total) number of languages detected, ', - # 'language's(#) "found with number of entries ≥" cutoff, 1, 1 -call esort # /*sort the languages along with #*/ -rank=0; tied= /* [↓] show by ascending rank. */ +call eSort #,1 /*sort the languages along with @*/ +listed=0; w=length(#); rank=0 /* [↓] show by ascending rank. */ - do j=# by -1 for # while #.j>=cutoff; rank=rank+1 - if tied=='' then pRank=rank - tRank=rank; jp=j+1; jm=j-1; tied= - if #.j==#.jp | #.j==#.jm then tied='(tied)' - if #.j==#.jp then tRank=pRank - else pRank= Rank + do j=# by -1 for # while #.j>=cutoff; listed=listed+1; rank=rank+1 + call tell right('rank:' right(!tR.j,w),20-1) right(!.j,7), + right('('#.j left("entr"s(#.j,'ies',"y")')', 9),20) @.j + end /*j=# by ···*/ /* [↑] s(···) pluralizes a word*/ - call tell right('rank:'right(tRank,4),20) left(tied,6), - right('('#.j left("entr"s(#.j,'ies',"y")')',9),20) @.j - end /*j*/ - call tell ' ☼ end-of-list. ☼', 1, 2 -if cutoff>0 then call tell ' Listing stopped due to a cutoff of' cutoff"." +call tell left('',27) '☼ end-of-list. ☼', 1, 2 +if cutoff==0 then exit /*was there a CUTOFF speciified? */ +call tell ' Listing stopped due to a cutoff of' cutoff".", 1 +call tell listed 'language's(#) "found with number of entries ≥" cutoff,1,1 exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────ESORT subroutine───────────────────────*/ -esort: procedure expose #. @.; arg N; h=N - do while h>1; h=h%2 - do i=1 for N-h; j=i; k=h+i - do while #.k<#.j /*use hard swaps: @. have blanks.*/ - @=@.j; #=#.j; @.j=@.k; #.j=#.k; @.k=@; #.k=# - if h>=j then leave; j=j-h; k=k-h - end /*while #.k<#.j*/ - end /*i*/ - end /*while h>1*/ +/*──────────────────────────────────ESORT subroutine────────────────────*/ +eSort: procedure expose #. @. !tr.; arg N,p2; h=N /*sort by # entries*/ + do while h>1; h=h%2 /*sort kinda halved*/ + do i=1 for N-h; j=i; k=h+i /*sort this part. */ + if p2 then do while !tR.k==!tR.j & @.k>@.j /*using hard swap ↓*/ + @=@.j; #=!tR.j; @.j=@.k; !tR.j=!tR.k; @.k=@; !tR.k=# + if h>=j then leave; j=j-h; k=k-h + end /*while !tR·k==···*/ + else do while #.k<#.j /*using hard swap ↓*/ + @=@.j; #=#.j; @.j=@.k; #.j=#.k; @.k=@; #.k=# + if h>=j then leave; j=j-h; k=k-h + end /*while #.k<#.j*/ + end /*i*/ + end /*while h>1*/ return -/*───────────────────────────────READER subroutine──────────────────────*/ -reader: arg which 2; n=0; ig_ast=1 /*ARG uppers WHICH, gets 1st char*/ +/*──────────────────────────────────READER subroutine───────────────────*/ +reader: arg which 2; ig_ast=1 /*ARG uppers WHICH, gets 1st char*/ if which=='L' then inFID=Linfid /*use this fileID for languages. */ if which=='C' then inFID=Cinfid /* " " " " categories.*/ -oldMc='╬£C++'; newMc= "µC++" /*Unicode ╬£C++ ──> ASCII-8: µC++*/ -oldUc='UC++' /*old UC++ ──> ASCII-8: µC++*/ -oldMK='╨£╨Ü-'; newMK= "MK-" /*Unicode ╨£╨Ü- ──> ASCII-8: MK- */ -oldDV='D├⌐j├á'; newDV= 'Déjá' /*Unicode ├⌐j├á ──> ASCII-8: Déjá*/ -oldCA='Cach├⌐'; newCA= 'Caché' /*Unicode ach├⌐ ──> ASCII-8: aché*/ +old.1='╬£C++' ; new.1= "µC++" /*Unicode ╬£C++ ──►ASCII-8: µC++ */ +old.2='UC++' ; new.2= "µC++" /*old UC++ ──►ASCII-8: µC++ */ +old.3='╨£╨Ü-' ; new.3= "MK-" /*Unicode ╨£╨Ü- ──►ASCII-8: MK- */ +old.4='D├⌐j├á' ; new.4= 'Déjá' /*Unicode ├⌐j├á ──►ASCII-8: Déjá */ +old.5='Cach├⌐' ; new.5= 'Caché' /*Unicode ach├⌐ ──►ASCII-8: Caché*/ +old.6='??-61/52' ; new.6= 'MK-61/52' /*somewhere a mistranslated: MK- */ - do while lines(inFID)\==0 /*read a file, 1 line at a time.*/ + do recs=0 while lines(inFID)\==0 /*read a file, 1 line at a time.*/ $=translate(linein(inFID),,'9'x) /*handle any stray tab characters*/ $$=space($); if $$=='' then iterate /*ignore all blank lines. */ - if pos(oldMc,$$)\==0 then $$=changestr(oldMc,$$,newMc) /*convert micro*/ - if pos(oldUc,$$)\==0 then $$=changestr(oldUc,$$,newMc) /*convert µC++ */ - if pos(oldMK,$$)\==0 then $$=changestr(oldMK,$$,newMK) /*convert MK- */ - if pos(oldDV,$$)\==0 then $$=changestr(oldDV,$$,newDV) /*convert Déjá */ - if pos(oldCA,$$)\==0 then $$=changestr(oldCA,$$,newCA) /*convert Caché*/ - $u=$; upper $u /*get an uppercase version. */ - if ig_ast then do; ig_ast=pos(' * ',$u)==0; if ig_ast then iterate; end + do k=1 while old.k\=='' /*translate Unicode variations. */ + if pos(old.k, $$) \==0 then $$=changestr(old.k, $$, new.k) + end /*k*/ /* [↑] handle different spellings*/ + if ig_ast then do; ig_ast=pos(' * ',$)==0; if ig_ast then iterate; end + $u=$$; upper $u /*get an uppercase version. */ if pos('RETRIEVED FROM',$u)\==0 then leave /*a pseudo End-Of-Data.*/ - n=n+1 /*bump counter: legimate records.*/ - if which=='L' then do - if left($$,1)\=='*' then iterate /*legimate?*/ - parse upper var $$ '*' $$ '<'; $$=space($$) - L.$$=1 /*languages are stored uppercase.*/ - iterate /*iterates the DO WHILE LINES(...*/ - end /*(above) pick off language name.*/ - + if which=='L' then do + if left($$,1)\=='*' then iterate /*legimate?*/ + parse upper var $$ '*' $$ "<"; $$=space($$) + L.$$=1 /*languages are stored uppercase.*/ + iterate /*iterates the DO WHILE LINES(···*/ + end /*(above) pick off language name.*/ if left($$,1)=='*' then $$=sep || space(substr($$,2)) catHeap=catHeap $$ /*append to the (CATegory) heap. */ - end /*while lines...*/ + end /*while lines···*/ -call tell right(n,9) 'records read from file: ' inFID -return n -/*───────────────────────────────S subroutine───────────────────────────*/ +call tell right(recs,9) 'records read from file: ' inFID +return +/*──────────────────────────────────S subroutine────────────────────────*/ s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ -/*───────────────────────────────TELL subroutine────────────────────────*/ +/*──────────────────────────────────TELL subroutine─────────────────────*/ tell: do '0'arg(2); call lineout outFID,' ' ; say ; end call lineout outFID,arg(1) ; say arg(1) do '0'arg(3); call lineout outFID,' ' ; say ; end diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala b/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala index 074da05f0c..86c1abd347 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala @@ -1,46 +1,137 @@ -def scrapeRosettaCodeLanguageRanks() : Seq[(String,Int)] = { +import akka.actor.{ Actor, ActorSystem, Props } +import scala.collection.immutable.TreeSet +import scala.xml.XML - // - // The Programming Languages - // - val langs = { - val langsXML = scala.xml.XML.load("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=xml") +// Reports a list with all languages recorded in the Wiki - (langsXML \\ "categorymembers" \ "cm") map (c => (c \ "@title").text) +private object Acquisition { + val (endPoint, prefix) = ("http://rosettacode.org/mw/api.php", "Category:") + val (maxPlaces, correction) = (50, 2) + + def convertPathArgsToURL(endPoint: String, pathArgs: Map[String, String]) = { + pathArgs.map(argPair => argPair._1 + "=" + argPair._2) + .mkString(endPoint + (if (pathArgs.nonEmpty) "?" else ""), "&", "") } - // - // The Categories - // - val cats = { - - // The categories include a page for the language and a count of the pages linked - // therein, this count is the data we need to scrape. - val catsXML = scala.xml.XML.load("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000") + /* The categories include a page for the language and a count of the pages + * linked therein, this count is the data we need to scrape. + * Reports a list with language, count pair recorded in the Wiki + * All strings starts with the prefixes "Category:" + */ + def mineCatos = { + val endPoint = "http://rosettacode.org/mw/index.php" + Concurrent.logInfo("Acquisition of categories started.") + val categories = + (XML.load(convertPathArgsToURL(endPoint, + Map("title" -> "Special:Categories", "limit" -> "5000"))) \\ "ul" \ "li") + .withFilter(p => (p \ "a" \ "@title").text.startsWith(prefix)) + .map // Create a tuple pair, eg. ("Category:Erlang", 195) + { cat => + ((cat \ "a" \ "@title").text, // Takes the sibling of "a" and extracts the number + ("[0-9]+".r.findFirstIn((cat.child.drop(1)).text).getOrElse("0").toInt)) + } + Concurrent.logInfo(s"Got ${categories.size} categories..") + categories + } - (catsXML \\ "ul" \ "li") map {c => + // The languages + // All strings starts with the prefixes "Category:" + def mineLangs = { + Concurrent.logInfo("Acquisition of languages started...") + val languages = ( + TreeSet[String]() ++ (XML.load(convertPathArgsToURL(endPoint, Map("action" -> "query", + "list" -> "categorymembers", + "cmtitle" -> (prefix + "Programming_Languages"), + "cmlimit" -> "505", "format" -> "xml"))) \\ + "categorymembers" \ "cm").map(c => (c \ "@title").text)) + Concurrent.logInfo(s"Got ${languages.size} languages..") + languages + } - // Create a tuple pair, eg. ("Category:Erlang", 195) - ( - (c \ "a" \ "@title").toString, - ("[0-9]+".r.findFirstIn((c.child.drop(1)).text).getOrElse("0").toInt) // Takes the sibling of "a" and extracts the number - ) + def joinRosettaCodeWithLanguage(catos: Seq[(String, Int)], + langs: TreeSet[String]) = + for { + cato <- catos //Clean up the tuple pairs, eg ("Category:Erlang", 195) becomes ("Erlang", 192) + if langs.exists(_ == cato._1) + } yield (cato._1.drop(prefix.size), cato._2 - correction max 0) // Correct count + + def printScrape(languages: TreeSet[String], category: Seq[(String, Int)]) { + + val join = joinRosettaCodeWithLanguage(category, languages) + val total = join.foldLeft(0)(_ + _._2) + + Concurrent.logInfo("Data processed") + + println(f"\nTop$maxPlaces%3d Rosetta Code Languages by Popularity as ${new java.util.Date}%tF:\n") + (join.groupBy(_._2).toSeq.sortBy(-_._1).take(maxPlaces) :+ (0, Seq(("...", 0)))) + .zipWithIndex // Group the ex aequo + .foreach { + case ((score, languages), rank) => + println(f"${rank + 1}%2d. $score%3d - ${languages.map(_._1).mkString(", ")}") + } + + println(s"\nCross section yields ${join.size} languages, total of $total solutions") + println(s"Resulting average is ${total / join.size} solutions per language") + } + + def printScrape(): Unit = printScrape(mineLangs, mineCatos) +} // object Acquisition + +private object Concurrent extends AppCommons { + var (category: Option[Seq[(String, Int)]], language: Option[TreeSet[String]]) = (None, None) + + class Worker extends Actor { + def receive = { + case 'Catalogue => sender ! Acquisition.mineCatos + case 'Language => sender ! Acquisition.mineLangs } } - val ranks = ((langs map { s => cats.find( c => (c._1 == s) ) }).flatten) map {e => + class Listener extends Actor { // Create and signal the worker actors + context.actorOf(Props[Worker], "worker0") ! 'Catalogue + context.actorOf(Props[Worker], "worker1") ! 'Language - // Clean up the tuple pairs, eg ("Category:Erlang", 195) becomes ("Erlang", 192) - ( - (if( e._1.contains("Category:") ) e._1.split("Category:")(1) else e._1), - ((e._2 - 3) max 0) // 3 members (or links) are not of a task - ) - } sortBy ( - _._2 ) + def printCompleteScape() = + if (category.isDefined && language.isDefined) { + Acquisition.printScrape(language.get, category.get) + context.system.shutdown + appEnd() + } - ranks + def receive = { + case content: TreeSet[String] => { + language = Some(content) + printCompleteScape() + } + case content: Seq[(String, Int)] => { + category = Some(content) + printCompleteScape() + } + case whatever => logInfo(whatever.toString) + } // def receive + } // class Listener +} // object Concurrent + +trait AppCommons { + val execStart: Long = System.currentTimeMillis() + System.setProperty("http.agent", "*") + + def logInfo(info: String) { + println(f"[Info][${System.currentTimeMillis() - execStart}%5d ms]" + info) + } + + def appEnd() { logInfo("Run succesfully completed") } } -val ranks = scrapeRosettaCodeLanguageRanks() +// Main entry for sequential version (slower) +object GhettoParserSeq extends App with AppCommons { + Concurrent.logInfo("Sequential version started") + Acquisition.printScrape() + appEnd() +} -println("Top 50 Rosetta Code Languages by Popularity, %tF:".format(new java.util.Date) + "\n" ) -ranks.take(50).zipWithIndex foreach {case ((lang,rank),i) => println( s"${i+1}. $rank - $lang" )} +// Entry for parallel version (faster) +object GhettoParserPar extends App { + Concurrent.logInfo("Parallel version started") + ActorSystem("Main").actorOf(Props[Concurrent.Listener]) +} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Seed7/rosetta-code-rank-languages-by-popularity.seed7 b/Task/Rosetta-Code-Rank-languages-by-popularity/Seed7/rosetta-code-rank-languages-by-popularity.seed7 new file mode 100644 index 0000000000..5b9e0f705a --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Seed7/rosetta-code-rank-languages-by-popularity.seed7 @@ -0,0 +1,58 @@ +$ include "seed7_05.s7i"; + include "gethttp.s7i"; + include "scanstri.s7i"; + +const type: popularityHash is hash [string] integer; +const type: rankingHash is hash [integer] array string; + +const func array string: getLangs (in string: buffer) is func + result + var array string: langs is 0 times ""; + local + var integer: pos is 0; + begin + pos := pos(buffer, "Category:"); + while pos <> 0 do + pos +:= 9; + langs &:= buffer[pos .. pred(pos(buffer, '"', pos))]; + pos := pos(buffer, "Category:", pos); + end while; + end func; + +const proc: main is func + local + var string: categories is ""; + var popularityHash: popularity is popularityHash.value; + var rankingHash: ranking is rankingHash.value; + var array integer: numList is 0 times 0; + var string: lang is ""; + var integer: pos is 0; + var string: numStri is ""; + var integer: listIdx is 0; + var integer: index is 0; + var integer: place is 1; + begin + categories := getHttp("www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000"); + for lang range getLangs(getHttp("rosettacode.org/mw/api.php?action=query&list=categorymembers&\ + \cmtitle=Category:Programming_Languages&cmlimit=500&format=json")) do + pos := pos(categories, "title=\"Category:" & lang); + if pos <> 0 then + pos := pos(categories, "", succ(pos)); + if pos <> 0 then + pos := pos(categories, "(", succ(pos)); + if pos <> 0 then + numStri := categories[succ(pos) len 10]; + popularity @:= [lang] integer parse getDigits(numStri); + end if; + end if; + end if; + end for; + ranking := flip(popularity); + numList := sort(keys(ranking)); + for listIdx range maxIdx(numList) downto minIdx(numList) do + for key index range ranking[numList[listIdx]] do + writeln(place lpad 3 <& ". " <& numList[listIdx] <& " - " <& ranking[numList[listIdx]][index]); + end for; + place +:= length(ranking[numList[listIdx]]); + end for; + end func; diff --git a/Task/Rot-13/Deja-Vu/rot-13.djv b/Task/Rot-13/Deja-Vu/rot-13.djv new file mode 100644 index 0000000000..93a39c5232 --- /dev/null +++ b/Task/Rot-13/Deja-Vu/rot-13.djv @@ -0,0 +1,16 @@ +rot-13: + ) + for ch in chars swap: + ord ch + if <= 65 dup: + if >= 90 dup: + + 13 - swap 65 + + 65 % swap 26 + if <= 97 dup: + if >= 122 dup: + + 13 - swap 97 + + 97 % swap 26 + chr + concat( + +!print rot-13 "Snape kills Frodo with Rosebud." diff --git a/Task/Rot-13/GML/rot-13-1.gml b/Task/Rot-13/GML/rot-13-1.gml index 20bc46b323..11ec25ca3c 100644 --- a/Task/Rot-13/GML/rot-13-1.gml +++ b/Task/Rot-13/GML/rot-13-1.gml @@ -1,16 +1,23 @@ #define rot13 -{ - out = ''; - for (x = 1; x <= string_length(argument0); x += 1) { - working = ord(string_char_at(argument0, x)); - if ((working > 64) && (working < 91)) { - working += 13; - if (working > 90) working -= 26; - } else if ((working > 96) && (working < 123)) { - working += 13; - if (working > 122) working -= 26; +var in, out, i, working; +in = argument0; +out = ""; +for (i = 1; i <= string_length(in); i += 1) + { + working = ord(string_char_at(in, i)); + if ((working > 64) && (working < 91)) + { + working += 13; + if (working > 90) + { + working -= 26; + } } - out = out + chr(working); + else if ((working > 96) && (working < 123)) + { + working += 13; + if (working > 122) working -= 26; + } + out += chr(working); } - return out; -} +return out; diff --git a/Task/Rot-13/Limbo/rot-13.limbo b/Task/Rot-13/Limbo/rot-13.limbo new file mode 100644 index 0000000000..2e73e1cb13 --- /dev/null +++ b/Task/Rot-13/Limbo/rot-13.limbo @@ -0,0 +1,73 @@ +implement Rot13; + +include "sys.m"; sys: Sys; +include "draw.m"; + +Rot13: module +{ + init: fn(ctxt: ref Draw->Context, argv: list of string); +}; + +stdout: ref Sys->FD; +tab: array of int; + +init(nil: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + stdout = sys->fildes(1); + inittab(); + args = tl args; + if(args == nil) + args = "-" :: nil; + for(; args != nil; args = tl args){ + file := hd args; + if(file != "-"){ + fd := sys->open(file, Sys->OREAD); + if(fd == nil){ + sys->fprint(sys->fildes(2), "rot13: cannot open %s: %r\n", file); + raise "fail:bad open"; + } + rot13cat(fd, file); + }else + rot13cat(sys->fildes(0), ""); + } +} + +inittab() +{ + tab = array[256] of int; + for(i := 0; i < 256; i++) + tab[i] = i; + + for(i = 'a'; i <= 'z'; i++) + tab[i] = (((i - 'a') + 13) % 26) + 'a'; + for(i = 'A'; i <= 'Z'; i++) + tab[i] = (((i - 'A') + 13) % 26) + 'A'; +} + + +rot13(s: string): string +{ + for(i := 0; i < len s; i++) { + if(s[i] < 256) + s[i] = tab[s[i]]; + } + return s; +} + +rot13cat(fd: ref Sys->FD, file: string) +{ + buf := array[Sys->ATOMICIO] of byte; + + while((n := sys->read(fd, buf, len buf)) > 0) { + obuf := array of byte (rot13(string buf)); + if(sys->write(stdout, obuf, n) < n) { + sys->fprint(sys->fildes(2), "rot13: write error: %r\n"); + raise "fail:write error"; + } + } + if(n < 0) { + sys->fprint(sys->fildes(2), "rot13: error reading %s: %r\n", file); + raise "fail:read error"; + } +} diff --git a/Task/Run-length-encoding/COBOL/run-length-encoding.cobol b/Task/Run-length-encoding/COBOL/run-length-encoding.cobol new file mode 100644 index 0000000000..cb7b1237e5 --- /dev/null +++ b/Task/Run-length-encoding/COBOL/run-length-encoding.cobol @@ -0,0 +1,124 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. run-length-encoding. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION encode + FUNCTION decode + . +DATA DIVISION. +WORKING-STORAGE SECTION. +01 input-str PIC A(100). +01 encoded PIC X(200). +01 decoded PIC X(200). + +PROCEDURE DIVISION. + ACCEPT input-str + MOVE encode(FUNCTION TRIM(input-str)) TO encoded + DISPLAY "Encoded: " FUNCTION TRIM(encoded) + DISPLAY "Decoded: " FUNCTION TRIM(decode(encoded)) + . +END PROGRAM run-length-encoding. + + +IDENTIFICATION DIVISION. +FUNCTION-ID. encode. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 str-len PIC 9(3) COMP. + +01 i PIC 9(3) COMP. + +01 current-char PIC A. + +01 num-chars PIC 9(3) COMP. +01 num-chars-disp PIC Z(3). + +01 encoded-pos PIC 9(3) COMP VALUE 1. + +LINKAGE SECTION. +01 str PIC X ANY LENGTH. + +01 encoded PIC X(200). + +PROCEDURE DIVISION USING str RETURNING encoded. + MOVE FUNCTION LENGTH(str) TO str-len + MOVE str (1:1) TO current-char + MOVE 1 TO num-chars + PERFORM VARYING i FROM 2 BY 1 UNTIL i > str-len + IF str (i:1) <> current-char + CALL "add-num-chars" USING encoded, encoded-pos, + CONTENT current-char, num-chars + + MOVE str (i:1) TO current-char + MOVE 1 TO num-chars + ELSE + ADD 1 TO num-chars + END-IF + END-PERFORM + + CALL "add-num-chars" USING encoded, encoded-pos, CONTENT current-char, + num-chars + . +END FUNCTION encode. + +IDENTIFICATION DIVISION. +PROGRAM-ID. add-num-chars. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 num-chars-disp PIC Z(3). + +LINKAGE SECTION. +01 str PIC X(200). + +01 current-pos PIC 9(3) COMP. + +01 char-to-encode PIC X. + +01 num-chars PIC 9(3) COMP. + +PROCEDURE DIVISION USING str, current-pos, char-to-encode, num-chars. + MOVE num-chars TO num-chars-disp + MOVE FUNCTION TRIM(num-chars-disp) TO str (current-pos:3) + ADD FUNCTION LENGTH(FUNCTION TRIM(num-chars-disp)) TO current-pos + MOVE char-to-encode TO str (current-pos:1) + ADD 1 TO current-pos + . +END PROGRAM add-num-chars. + + +IDENTIFICATION DIVISION. +FUNCTION-ID. decode. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 encoded-pos PIC 9(3) COMP VALUE 1. +01 decoded-pos PIC 9(3) COMP VALUE 1. + +01 num-of-char PIC 9(3) COMP VALUE 0. + +LINKAGE SECTION. +01 encoded PIC X(200). + +01 decoded PIC X(100). + +PROCEDURE DIVISION USING encoded RETURNING decoded. + PERFORM VARYING encoded-pos FROM 1 BY 1 + UNTIL encoded (encoded-pos:2) = SPACES OR encoded-pos > 200 + IF encoded (encoded-pos:1) IS NUMERIC + COMPUTE num-of-char = num-of-char * 10 + + FUNCTION NUMVAL(encoded (encoded-pos:1)) + ELSE + PERFORM UNTIL num-of-char = 0 + MOVE encoded (encoded-pos:1) TO decoded (decoded-pos:1) + ADD 1 TO decoded-pos + SUBTRACT 1 FROM num-of-char + END-PERFORM + END-IF + END-PERFORM + . +END FUNCTION decode. diff --git a/Task/Run-length-encoding/D/run-length-encoding-2.d b/Task/Run-length-encoding/D/run-length-encoding-2.d index 925a5b14b9..d267d1c852 100644 --- a/Task/Run-length-encoding/D/run-length-encoding-2.d +++ b/Task/Run-length-encoding/D/run-length-encoding-2.d @@ -1,29 +1,30 @@ import std.stdio, std.array, std.conv; // Similar to the 'look and say' function. -string encode(in string input) { - if (input.empty) return input; +string encode(in string input) pure /*nothrow*/ { + if (input.empty) + return input; char last = input[$ - 1]; string output; int count; - foreach_reverse (c; input) { + foreach_reverse (immutable c; input) { if (c == last) { count++; } else { - output = text(count) ~ last ~ output; + output = count.text ~ last ~ output; count = 1; last = c; } } - return text(count) ~ last ~ output; + return count.text ~ last ~ output; } -string decode(in string input) { +string decode(in string input) pure { string i, result; - foreach (c; input) + foreach (immutable c; input) switch (c) { case '0': .. case '9': i ~= c; @@ -32,12 +33,11 @@ string decode(in string input) { if (i.empty) throw new Exception("Can not repeat a letter " ~ "without a number of repetitions"); - result ~= replicate([c], to!int(i)); + result ~= [c].replicate(i.to!int); i.length = 0; break; default: - throw new Exception("'" ~ c ~ - "' is not alphanumeric"); + throw new Exception("'" ~ c ~ "' is not alphanumeric"); } return result; @@ -47,7 +47,7 @@ void main() { immutable txt = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW" ~ "WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; writeln("Input: ", txt); - immutable encoded = encode(txt); + immutable encoded = txt.encode; writeln("Encoded: ", encoded); - assert(txt == decode(encoded)); + assert(txt == encoded.decode); } diff --git a/Task/Run-length-encoding/Deja-Vu/run-length-encoding.djv b/Task/Run-length-encoding/Deja-Vu/run-length-encoding.djv new file mode 100644 index 0000000000..bde88e3f95 --- /dev/null +++ b/Task/Run-length-encoding/Deja-Vu/run-length-encoding.djv @@ -0,0 +1,29 @@ +rle: + if not dup: + drop + return [] + + swap ] + + local :source chars + pop-from source + 1 + for c in source: + if = c over: + ++ + else: + 1 c & + & + return [ + +rld: + ) + for pair in swap: + repeat &< pair: + &> pair + concat( + + +rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +!. dup +!. rld diff --git a/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx b/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx index 7b68abb01c..3435e38c35 100644 --- a/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx +++ b/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx @@ -1,21 +1,20 @@ -/*REXX program encodes string by using a run-length scheme (min len=2).*/ -parse arg x /*normally, input would be a file*/ -def='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' -if x=='' then x=def /*No input? Then use the default*/ +/*REXX program encodes a string by using a run-length scheme. */ +parse arg x . /*normally, input would be a file*/ +/*═══ arg x . ═══*/ /*◄── use if X must be uppercase.*/ +def= 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' +if x='' then x=def /*No input? Then use the default.*/ Lx=length(x) /*get the length of the X string.*/ y= /*Y is the output string (so far)*/ - do j=1 to Lx /*warning! J is modified below.*/ + do j=1 by 0 to Lx /*J is incremented (below). */ c=substr(x,j,1) /*pick a character, check for err*/ - if \datatype(c,'m') then do;say "error!: data isn't alphabetic";exit 13; end + if \datatype(c,'M') then do; say "error!: data isn't alphabetic:" c; exit 13; end r=0 /*R is NOT the number of chars. */ - - do k=j+1 to Lx while substr(x,k,1)==c - r=r+1 /*R is a replication count. */ - end /*k*/ - - if r==0 then Y = Y || c /*C wan't repeated, just OUT it.*/ - else Y = Y || r || c /*add it to the encoded string. */ - j=j+r /*A bad thing to do, but simple. */ + do k=j+1 to Lx while substr(x,k,1)==c + r=r+1 /*R is a replication count. */ + end /*k*/ + j=j+1+r /*modify (add to) the do index. */ + if r==0 then r= /*don't use R if R is zero.*/ + Y = Y || r || c /*add it to the encoded string.*/ end /*j*/ say ' input=' x diff --git a/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx b/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx index ba2e4e6ffe..1ff19df869 100644 --- a/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx +++ b/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx @@ -1,22 +1,21 @@ -/*REXX program decodes string by using a run-length scheme (min len=2).*/ -parse arg x /*normally, input would be a file*/ +/*REXX program decodes a string by using a run-length scheme. */ +parse arg x . /*normally, input would be a file*/ if x=='' then x='11WB11W2B23WB13W' /*No input? Then use the default*/ Lx=length(x) /*get the length of the X string.*/ y= /*Y is the output string (so far)*/ - do j=1 to Lx /*warning! J is modified below.*/ + do j=1 by 0 to Lx /*warning! J is modified below.*/ c=substr(x,j,1) if \datatype(c,'W') then do /*a loner char, simply add to OUT*/ - y=y || c - iterate + y=y || c; j=j+1; iterate /*j*/ end d=1 do k=j+1 to Lx while datatype(substr(x,k,1),'w') /*look for #end*/ - d=d+1 /*d is the number of digs so far.*/ + d=d+1 /*D is the number of digs so far.*/ end /*k*/ n=substr(x,j,d)+1 /*D is length of encoded number.*/ y=y || copies(substr(x,k,1),n) /*N is now the number of chars. */ - j=j+d /*A bad thing to do, but simple. */ + j=j+1+d /*increment the DO loop index. */ end /*j*/ say ' input=' x diff --git a/Task/Runtime-evaluation-In-an-environment/Deja-Vu/runtime-evaluation-in-an-environment.djv b/Task/Runtime-evaluation-In-an-environment/Deja-Vu/runtime-evaluation-in-an-environment.djv new file mode 100644 index 0000000000..361826ce4d --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Deja-Vu/runtime-evaluation-in-an-environment.djv @@ -0,0 +1,11 @@ +local fib n: + if <= n 1: + n + else: + + fib - n 1 fib - n 2 + +local :code !compile-string dup "-- fib x" #one less than the xth fibonacci number + +!run-blob-in { :fib @fib :x 4 } code +!run-blob-in { :fib @fib :x 6 } code +!. - diff --git a/Task/Runtime-evaluation/Deja-Vu/runtime-evaluation.djv b/Task/Runtime-evaluation/Deja-Vu/runtime-evaluation.djv new file mode 100644 index 0000000000..42105f8b8a --- /dev/null +++ b/Task/Runtime-evaluation/Deja-Vu/runtime-evaluation.djv @@ -0,0 +1 @@ +!run-blob !compile-string "(fake filename)" "!print \qHello world\q" diff --git a/Task/S-Expressions/Haskell/s-expressions.hs b/Task/S-Expressions/Haskell/s-expressions.hs index 5917db847f..7aa77a370a 100644 --- a/Task/S-Expressions/Haskell/s-expressions.hs +++ b/Task/S-Expressions/Haskell/s-expressions.hs @@ -5,10 +5,10 @@ import Text.ParserCombinators.Parsec.Language (haskellDef) data Val = Int Integer - | Float Double - | String String - | Symbol String - | List [Val] deriving (Eq, Show) + | Float Double + | String String + | Symbol String + | List [Val] deriving (Eq, Show) lexer = makeTokenParser haskellDef diff --git a/Task/S-Expressions/TXR/s-expressions-1.txr b/Task/S-Expressions/TXR/s-expressions-1.txr new file mode 100644 index 0000000000..1890604753 --- /dev/null +++ b/Task/S-Expressions/TXR/s-expressions-1.txr @@ -0,0 +1,4 @@ +$ txr -c '@(do (print (read)) (put-line ""))' +((data "quoted data" 123 4.5) <- input from TTY + (data (!@# (4.5) "(more" "data)"))) +((data "quoted data" 123 4.5) (data (! (sys:var #) (4.5) "(more" "data)"))) <- output diff --git a/Task/S-Expressions/TXR/s-expressions-2.txr b/Task/S-Expressions/TXR/s-expressions-2.txr new file mode 100644 index 0000000000..483f5e8515 --- /dev/null +++ b/Task/S-Expressions/TXR/s-expressions-2.txr @@ -0,0 +1,44 @@ +@(define float (f))@\ + @(local (tok))@\ + @(cases)@\ + @{tok /[+\-]?\d+\.\d*([Ee][+\-]?\d+)?/}@\ + @(or)@\ + @{tok /[+\-]?\d*\.\d+([Ee][+\-]?\d+)?/}@\ + @(or)@\ + @{tok /[+\-]?\d+[Ee][+\-]?\d+/}@\ + @(end)@\ + @(bind f @(flo-str tok))@\ +@(end) +@(define int (i))@\ + @(local (tok))@\ + @{tok /[+\-]?\d+/}@\ + @(bind i @(int-str tok))@\ +@(end) +@(define sym (s))@\ + @(local (tok))@\ + @{tok /[^\s()]+/}@\ + @(bind s @(intern tok))@\ +@(end) +@(define str (s))@\ + @(local (tok))@\ + @{tok /"(\\"|[^"])*"/}@\ + @(bind s @[tok 1..-1])@\ +@(end) +@(define atom (a))@\ + @(cases)@\ + @(float a)@(or)@(int a)@(or)@(str a)@(or)@(sym a)@\ + @(end)@\ +@(end) +@(define expr (e))@\ + @(cases)@\ + @/\s*/@(atom e)@\ + @(or)@\ + @/\s*\(\s*/@(coll :vars (e))@(expr e)@/\s*/@(last))@(end)@\ + @(end)@\ +@(end) +@(freeform) +@(expr e)@junk +@(output) +expr: @(format nil "~s" e) +junk: @junk +@(end) diff --git a/Task/S-Expressions/TXR/s-expressions-3.txr b/Task/S-Expressions/TXR/s-expressions-3.txr new file mode 100644 index 0000000000..e60497e242 --- /dev/null +++ b/Task/S-Expressions/TXR/s-expressions-3.txr @@ -0,0 +1 @@ + @/\s*\(\s*/@(coll :vars (e))@(expr e)@/\s*/@(last))@(end) diff --git a/Task/SEDOLs/COBOL/sedols.cobol b/Task/SEDOLs/COBOL/sedols.cobol new file mode 100644 index 0000000000..6627f9d22f --- /dev/null +++ b/Task/SEDOLs/COBOL/sedols.cobol @@ -0,0 +1,79 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. sedol. + +ENVIRONMENT DIVISION. +INPUT-OUTPUT SECTION. +FILE-CONTROL. + SELECT sedol-file ASSIGN "sedol.txt" + ORGANIZATION LINE SEQUENTIAL + FILE STATUS sedol-file-status. + +DATA DIVISION. +FILE SECTION. +FD sedol-file. +01 sedol PIC X(6). + +WORKING-STORAGE SECTION. +01 sedol-file-status PIC XX. + 88 sedol-file-ok VALUE "00". + +01 digit-num PIC 9 COMP. + +01 digit-weights-area VALUE "1317391". + 03 digit-weights PIC 9 OCCURS 7 TIMES. + +01 weighted-sum-parts-area. + 03 weighted-sum-parts PIC 9(3) COMP OCCURS 6 TIMES. + +01 weighted-sum PIC 9(3) COMP. + +01 check-digit PIC 9. + +PROCEDURE DIVISION. + OPEN INPUT sedol-file + PERFORM UNTIL NOT sedol-file-ok + READ sedol-file + AT END + EXIT PERFORM + END-READ + + MOVE FUNCTION UPPER-CASE(sedol) TO sedol + + PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 + EVALUATE TRUE + WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER + IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U" + DISPLAY "Invalid SEDOL: " sedol + EXIT PERFORM CYCLE + END-IF + + COMPUTE weighted-sum-parts (digit-num) = + (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A") + + 10) * digit-weights (digit-num) + + WHEN sedol (digit-num:1) IS NUMERIC + MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1)) + BY digit-weights (digit-num) + GIVING weighted-sum-parts (digit-num) + + WHEN OTHER + DISPLAY "Invalid SEDOL: " sedol + EXIT PERFORM CYCLE + END-EVALUATE + END-PERFORM + + INITIALIZE weighted-sum + PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6 + ADD weighted-sum-parts (digit-num) TO weighted-sum + END-PERFORM + + COMPUTE check-digit = + FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10) + + DISPLAY sedol check-digit + END-PERFORM + + CLOSE sedol-file + . +END PROGRAM sedol. diff --git a/Task/SHA-1/AutoHotkey/sha-1.ahk b/Task/SHA-1/AutoHotkey/sha-1.ahk new file mode 100644 index 0000000000..cda0d62e0b --- /dev/null +++ b/Task/SHA-1/AutoHotkey/sha-1.ahk @@ -0,0 +1,52 @@ +str := "Rosetta Code" +MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) + + + +; SHA =============================================================================== +SHA(string, encoding = "utf-8") +{ + return CalcStringHash(string, 0x8004, encoding) +} + +; CalcAddrHash ====================================================================== +CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) +{ + static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] + static b := h.minIndex() + o := "" + if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) + { + if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) + { + if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) + { + if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) + { + VarSetCapacity(hash, hashlength, 0) + if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) + { + loop, % hashlength + { + v := NumGet(hash, A_Index - 1, "UChar") + o .= h[(v >> 4) + b] h[(v & 0xf) + b] + } + } + } + } + DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) + } + DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) + } + return o +} + +; CalcStringHash ==================================================================== +CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) +{ + 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) + return CalcAddrHash(&data, length, algid, hash, hashlength) +} diff --git a/Task/SHA-1/Perl-6/sha-1.pl6 b/Task/SHA-1/Perl-6/sha-1.pl6 index baa36f3a48..db1e008b4e 100644 --- a/Task/SHA-1/Perl-6/sha-1.pl6 +++ b/Task/SHA-1/Perl-6/sha-1.pl6 @@ -1,6 +1,6 @@ -sub postfix:(\x) { x % 2**32 } -sub infix:<⊕>(\x,\y) { (x + y)mod2³² } -sub S(\n,\X) { (X +< n)mod2³² +| (X +> (32-n)) } +sub postfix: { $^x % 2**32 } +sub infix:<⊕> { ($^x + $^y)mod2³² } +sub S { ($^x +< $^n)mod2³² +| ($x +> (32-$n)) } my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D) }, -> \B,\C,\D { B +^ C +^ D }, @@ -12,32 +12,33 @@ my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6; sub sha1-pad(Blob $msg) { my \bits = 8 * $msg.elems; - my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); + my @padded = $msg.list, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64); @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²; } sub sha1-block(@H is rw, @M) { my @W = @M; - @W.push: S(1, @W[$_-3] +^ @W[$_-8] +^ @W[$_-14] +^ @W[$_-16]) for 16..79; + @W.push: S(1, [+^] @W[$_ «-« <3 8 14 16>] ) for 16 .. 79; my ($A,$B,$C,$D,$E) = @H; for 0..79 -> \t { - my \TEMP = S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @W[t] ⊕ K[t div 20]; - $E = $D; $D = $C; $C = S(30,$B); $B = $A; $A = TEMP; + ($A, $B, $C, $D, $E) = + S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @W[t] ⊕ K[t div 20], + $A, S(30,$B), $C, $D; } - @H «⊕=» ($A,$B,$C,$D,$E); + @H »⊕=« ($A,$B,$C,$D,$E); } -sub sha1(Blob $msg) +sub sha1(Blob $msg) returns Blob { my @M = sha1-pad($msg); my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0; - sha1-block(@H,@M[$_..$_+15]) for 0,16...^+@M; - @H; + sha1-block(@H,@M[$_..$_+15]) for 0, 16...^ +@M; + Blob.new: map -> $w is rw { reverse gather for ^4 { take $w % 256; $w div= 256 } }, @H; } -say sha1(.encode('ascii'))».base(16), " $_" +say sha1(.encode('ascii')), " $_" for 'abc', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', 'Rosetta Code', diff --git a/Task/SHA-1/Seed7/sha-1.seed7 b/Task/SHA-1/Seed7/sha-1.seed7 new file mode 100644 index 0000000000..c147543158 --- /dev/null +++ b/Task/SHA-1/Seed7/sha-1.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "msgdigest.s7i"; + +const proc: main is func + begin + writeln(hex(sha1("Rosetta Code"))); + end func; diff --git a/Task/SHA-256/AutoHotkey/sha-256.ahk b/Task/SHA-256/AutoHotkey/sha-256.ahk new file mode 100644 index 0000000000..3d52aa3cce --- /dev/null +++ b/Task/SHA-256/AutoHotkey/sha-256.ahk @@ -0,0 +1,52 @@ +str := "Rosetta code" +MsgBox, % "File:`n" (file) "`n`nSHA-256:`n" FileSHA256(file) + + + +; SHA256 ============================================================================ +SHA256(string, encoding = "utf-8") +{ + return CalcStringHash(string, 0x800c, encoding) +} + +; CalcAddrHash ====================================================================== +CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) +{ + static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] + static b := h.minIndex() + o := "" + if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) + { + if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) + { + if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) + { + if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) + { + VarSetCapacity(hash, hashlength, 0) + if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) + { + loop, % hashlength + { + v := NumGet(hash, A_Index - 1, "UChar") + o .= h[(v >> 4) + b] h[(v & 0xf) + b] + } + } + } + } + DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) + } + DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) + } + return o +} + +; CalcStringHash ==================================================================== +CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) +{ + 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) + return CalcAddrHash(&data, length, algid, hash, hashlength) +} diff --git a/Task/SHA-256/Seed7/sha-256.seed7 b/Task/SHA-256/Seed7/sha-256.seed7 new file mode 100644 index 0000000000..912662183f --- /dev/null +++ b/Task/SHA-256/Seed7/sha-256.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "msgdigest.s7i"; + +const proc: main is func + begin + writeln(hex(sha256("Rosetta code"))); + end func; diff --git a/Task/SQL-based-authentication/Racket/sql-based-authentication.rkt b/Task/SQL-based-authentication/Racket/sql-based-authentication.rkt new file mode 100644 index 0000000000..b0caf0f5e6 --- /dev/null +++ b/Task/SQL-based-authentication/Racket/sql-based-authentication.rkt @@ -0,0 +1,65 @@ +#lang racket +(require db file/md5) +(define-logger authentication) +(current-logger authentication-logger) + +(define DB-HOST "localhost") +(define DB-USER "devel") +(define DB-PASS "devel") +(define DB-NAME "test") + +(define (connect-db) + (mysql-connect + #:user DB-USER + #:database DB-NAME + #:password DB-PASS)) + +(define (salt+password->hash salt password #:hex-encode? (hex-encode? #f)) + (md5 (bytes-append salt password) hex-encode?)) + +(define (report-sql-error e) + (log-authentication-error "Failed to create user:~s" (exn-message e)) + #f) + +(define (create-user db username passwd) + ; if user was successfully created, returns its ID else #f + (define salt (list->bytes (for/list ((i (in-range 16))) (random 256)))) + (define hash (salt+password->hash salt passwd)) + (with-handlers ((exn:fail:sql? report-sql-error)) + (query db "INSERT INTO users (username, pass_salt, pass_md5) VALUES (?, ?, ?)" + username salt hash))) + +(define (authenticate-user db username password) + (or + (match (query-maybe-row db "SELECT pass_salt, pass_md5 FROM users WHERE username = ?" username) + [#f #f] + [(vector salt hash) (bytes=? hash (salt+password->hash salt password))]) + ; don't let the deviants know whether it's the username or password that's dodgy + (error "the username, password combination does not exist in system"))) + +(module+ test + (require rackunit) + (define test-DB (connect-db)) + ; typically, you only do this the once (or risk upsetting your users bigtime!) + ; call this just the once! + (define (create-users-table db) + (query-exec db "DROP TABLE IF EXISTS users") + (query-exec db #< + +#define sqr(x) x*x +#define greet printf("\nHello There !"); + +int twice(int x) +{ + return 2*x; +} + +int main() +{ + int x; + printf("\nThis will demonstrate function and label scopes."); + printf("\nAll output is happening throung printf(), a function declared in the header file stdio.h, which is external to this program."); + printf("\nEnter a number : "); + scanf("%d",&x); + + switch(x%2){ + default:printf("\nCase labels in switch statements have scope local to the switch block."); + case 0: printf("\nYou entered an even number."); + printf("\nIt's square is %d, which was computed by a macro. It has global scope within the program file.",sqr(x)); + break; + case 1: printf("\nYou entered an odd number."); + goto sayhello; + jumpin: printf("\n2 times %d is %d, which was computed by a function defined in this file. It has global scope within the program file.",x,twice(x)); + printf("\nSince you jumped in, you will now be greeted, again !"); + sayhello: greet + if(x==-1)goto scram; + break; + }; + + printf("\nWe now come to goto, it's extremely powerful but it's also prone to misuse. It's use is discouraged and it wasn't even adopted by Java and later languages."); + + if(x!=-1){ + x = -1; /*To break goto infinite loop.*/ + goto jumpin; + } + + scram: printf("\nIf you are trying to figure out what happened, you now understand goto."); + return 0; +} + diff --git a/Task/Scope-modifiers/BASIC/scope-modifiers-1.basic b/Task/Scope-modifiers/BASIC/scope-modifiers-1.basic new file mode 100644 index 0000000000..461e418737 --- /dev/null +++ b/Task/Scope-modifiers/BASIC/scope-modifiers-1.basic @@ -0,0 +1,5 @@ + 10 X = 1 + 20 DEF FN F(X) = X + 30 DEF FN G(N) = X + 40 PRINT FN F(2) + 50 PRINT FN G(3) diff --git a/Task/Scope-modifiers/BASIC/scope-modifiers-2.basic b/Task/Scope-modifiers/BASIC/scope-modifiers-2.basic new file mode 100644 index 0000000000..364fb9a4df --- /dev/null +++ b/Task/Scope-modifiers/BASIC/scope-modifiers-2.basic @@ -0,0 +1,33 @@ + var1$ = "Global1" + var2$ = "Global2" + + PRINT "Before function call:" + PRINT "var1$ = """ var1$ """" + PRINT "var2$ = """ var2$ """" + + PROCtestscope(var1$) + PROCtestscope(var1$) + + PRINT "After function call:" + PRINT "var1$ = """ var1$ """" + PRINT "var2$ = """ var2$ """" + END + + DEF PROCtestscope(var2$) + PRINT "On entry to function:" + PRINT "var1$ = """ var1$ """" + PRINT "var2$ = """ var2$ """" + + LOCAL var1$ + PRIVATE var2$ + PRINT "After LOCAL/PRIVATE:" + PRINT "var1$ = """ var1$ """" + PRINT "var2$ = """ var2$ """" + + var1$ = "Local" + var2$ = "Private" + PRINT "After assignments:" + PRINT "var1$ = """ var1$ """" + PRINT "var2$ = """ var2$ """" + + ENDPROC diff --git a/Task/Scope-modifiers/Deja-Vu/scope-modifiers.djv b/Task/Scope-modifiers/Deja-Vu/scope-modifiers.djv new file mode 100644 index 0000000000..28191dbf8b --- /dev/null +++ b/Task/Scope-modifiers/Deja-Vu/scope-modifiers.djv @@ -0,0 +1,7 @@ +set :a "global" +if true: + !print a + local :a "local" + !print a + !print getglobal :a +!print a diff --git a/Task/Search-a-list/Common-Lisp/search-a-list.lisp b/Task/Search-a-list/Common-Lisp/search-a-list-1.lisp similarity index 100% rename from Task/Search-a-list/Common-Lisp/search-a-list.lisp rename to Task/Search-a-list/Common-Lisp/search-a-list-1.lisp diff --git a/Task/Search-a-list/Common-Lisp/search-a-list-2.lisp b/Task/Search-a-list/Common-Lisp/search-a-list-2.lisp new file mode 100644 index 0000000000..d2e2ce46d9 --- /dev/null +++ b/Task/Search-a-list/Common-Lisp/search-a-list-2.lisp @@ -0,0 +1,8 @@ +CL-USER> (defparameter *list* '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)) +*LIST* +CL-USER> (position 'Bush *list*) +4 +CL-USER> (position 'Bush *list* :from-end t) +7 +CL-USER> (position 'Washington *list*) +NIL diff --git a/Task/Search-a-list/Julia/search-a-list.julia b/Task/Search-a-list/Julia/search-a-list.julia new file mode 100644 index 0000000000..10a96ba8a0 --- /dev/null +++ b/Task/Search-a-list/Julia/search-a-list.julia @@ -0,0 +1,13 @@ +julia> findfirst(x -> x=="yes", {"no","?","yes","maybe","yes"}) +3 +julia> indexin({"yes"},{"no","?","yes","maybe","yes"}) +1-element Array{Int64,1}: + 5 +julia> findin({"no","?","yes","maybe","yes"},{"yes"}) +2-element Array{Int64,1}: + 3 + 5 +julia> find(x -> x=="yes", {"no","?","yes","maybe","yes"}) +2-element Array{Int64,1}: + 3 + 5 diff --git a/Task/Self-referential-sequence/D/self-referential-sequence-2.d b/Task/Self-referential-sequence/D/self-referential-sequence-2.d index d9cd53edc5..778dbfe160 100644 --- a/Task/Self-referential-sequence/D/self-referential-sequence-2.d +++ b/Task/Self-referential-sequence/D/self-referential-sequence-2.d @@ -8,7 +8,7 @@ struct Permutations(bool doCopy=true, T) { static if (!doCopy) T[] result; - this(T)(T[] items, int r=-1) /*pure nothrow*/ { + this(T)(T[] items, int r=-1) pure /*nothrow*/ { this.items = items; immutable int n = items.length; if (r < 0) @@ -19,7 +19,7 @@ struct Permutations(bool doCopy=true, T) { this.stopped = true; } else { this.stopped = false; - this.indices = n.iota.array; // Not pure nothrow. + this.indices = n.iota.array; this.cycles = iota(n, n_minus_r, -1).array; } @@ -75,7 +75,7 @@ struct Permutations(bool doCopy=true, T) { Permutations!(doCopy, T) permutations(bool doCopy=true, T) (T[] items, int r=-1) -/*pure nothrow*/ { +pure /*nothrow*/ { return Permutations!(doCopy, T)(items, r); } diff --git a/Task/Self-referential-sequence/D/self-referential-sequence-3.d b/Task/Self-referential-sequence/D/self-referential-sequence-3.d index 3bbbaf4bfa..2a66b2d602 100644 --- a/Task/Self-referential-sequence/D/self-referential-sequence-3.d +++ b/Task/Self-referential-sequence/D/self-referential-sequence-3.d @@ -1,44 +1,39 @@ import core.stdc.stdio, core.stdc.stdlib; -struct MemoryPool(T, int MAX_BLOCK_BYTES=1 << 17) { +struct MemoryPool(T, int MAX_BLOCK_BYTES = 1 << 17) { static assert(!is(T == class), "MemoryPool is designed for native data."); static assert(MAX_BLOCK_BYTES >= 1, "MemoryPool: MAX_BLOCK_BYTES must be >= 1 bytes."); + static assert(MAX_BLOCK_BYTES >= T.sizeof, + "MemoryPool: MAX_BLOCK_BYTES must be" ~ + " bigger than a T."); + static if (T.sizeof * 5 > MAX_BLOCK_BYTES) + pragma(msg, "MemoryPool: Block is very small."); - static struct Block { - static assert(MAX_BLOCK_BYTES >= T.sizeof, - "MemoryPool: MAX_BLOCK_BYTES must be" ~ - " bigger than a T."); - static if ((T.sizeof * 5) > MAX_BLOCK_BYTES) - pragma(msg, "MemoryPool: Block is very small."); - - T[(MAX_BLOCK_BYTES / T.sizeof)] items; - } - - __gshared static Block*[] blocks; - - __gshared static T* nextFree, lastFree; + alias Block = T[MAX_BLOCK_BYTES / T.sizeof]; + static __gshared Block*[] blocks; + static __gshared T* nextFree, lastFree; static T* newItem() nothrow { if (nextFree >= lastFree) { blocks ~= cast(Block*)calloc(1, Block.sizeof); if (blocks[$ - 1] == null) exit(1); - nextFree = blocks[$ - 1].items.ptr; - lastFree = nextFree + Block.items.length; + nextFree = blocks[$ - 1].ptr; + lastFree = nextFree + Block.length; } return nextFree++; } - static void freeAll() nothrow { - foreach (block_ptr; blocks) - free(block_ptr); - blocks.length = 0; - nextFree = null; - lastFree = null; - } +// static void freeAll() nothrow { +// foreach (blockPtr; blocks) +// free(blockPtr); +// blocks.length = 0; +// nextFree = null; +// lastFree = null; +// } } struct Rec { // Tree node @@ -135,5 +130,5 @@ void main() nothrow { } printf("Allocated %d Rec tree nodes.\n", nNodes); - //recPool.freeAll(); + //recPool.freeAll; } diff --git a/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy b/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy new file mode 100644 index 0000000000..e72e9eedd6 --- /dev/null +++ b/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy @@ -0,0 +1,13 @@ +Number.metaClass.getSelfReferentialSequence = { + def number = delegate as String; def sequence = [] + + while (!sequence.contains(number)) { + sequence << number + def encoded = new StringBuilder() + ((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit -> + encoded.append(text.size()).append(digit) + } + number = encoded.toString() + } + sequence +} diff --git a/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy b/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy new file mode 100644 index 0000000000..b061ddef87 --- /dev/null +++ b/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy @@ -0,0 +1 @@ +9009.selfReferentialSequence.each { println it } diff --git a/Task/Semordnilap/D/semordnilap.d b/Task/Semordnilap/D/semordnilap-1.d similarity index 73% rename from Task/Semordnilap/D/semordnilap.d rename to Task/Semordnilap/D/semordnilap-1.d index d2c5fc5de4..9fe4275413 100644 --- a/Task/Semordnilap/D/semordnilap.d +++ b/Task/Semordnilap/D/semordnilap-1.d @@ -4,8 +4,8 @@ void main() { bool[string] seenWords; size_t pairCount = 0; - foreach (word; readText("unixdict.txt").toLower().splitter()) { - auto drow = word.dup.reverse; + foreach (const word; readText("unixdict.txt").toLower.splitter) { + const drow = word.dup.reverse; // Deprecated. if (drow in seenWords) { if (pairCount++ < 5) writeln(word, " ", drow); diff --git a/Task/Semordnilap/D/semordnilap-2.d b/Task/Semordnilap/D/semordnilap-2.d new file mode 100644 index 0000000000..654fb301d6 --- /dev/null +++ b/Task/Semordnilap/D/semordnilap-2.d @@ -0,0 +1,9 @@ +void main() { + import std.stdio, std.file, std.algorithm, std.string, std.range; + + auto words = "unixdict.txt".readText.split.zip(0.repeat).assocArray; + auto pairs = zip(words.byKey, words.byKey.map!(w => w.dup.reverse)) + .filter!(wr => wr[0] < wr[1] && wr[1] in words) + .zip(0.repeat).assocArray; + writeln(pairs.length, "\n", pairs.byKey.take(5)); +} diff --git a/Task/Semordnilap/PicoLisp/semordnilap.l b/Task/Semordnilap/PicoLisp/semordnilap.l new file mode 100644 index 0000000000..da2e705332 --- /dev/null +++ b/Task/Semordnilap/PicoLisp/semordnilap.l @@ -0,0 +1,7 @@ +(let Semordnilap + (mapcon + '((Lst) + (when (member (reverse (car Lst)) (cdr Lst)) + (cons (pack (car Lst))) ) ) + (make (in "unixdict.txt" (while (line) (link @)))) ) + (println (length Semordnilap) (head 5 Semordnilap)) ) diff --git a/Task/Send-an-unknown-method-call/Common-Lisp/send-an-unknown-method-call.lisp b/Task/Send-an-unknown-method-call/Common-Lisp/send-an-unknown-method-call.lisp new file mode 100644 index 0000000000..0d0cb575d2 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Common-Lisp/send-an-unknown-method-call.lisp @@ -0,0 +1 @@ +(funcall (intern "SOME-METHOD") my-object a few arguments) diff --git a/Task/Send-an-unknown-method-call/Deja-Vu/send-an-unknown-method-call.djv b/Task/Send-an-unknown-method-call/Deja-Vu/send-an-unknown-method-call.djv new file mode 100644 index 0000000000..35249d67c1 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Deja-Vu/send-an-unknown-method-call.djv @@ -0,0 +1,4 @@ +local :object { :add @+ } +local :method :add + +!. object! method 1 2 diff --git a/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call.go b/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call.go new file mode 100644 index 0000000000..165aa68ed0 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "reflect" +) + +type example struct{} + +// the method must be exported to be accessed through reflection. +func (example) Foo() int { + return 42 +} + +func main() { + // create an object with a method + var e example + // get the method by name + m := reflect.ValueOf(e).MethodByName("Foo") + // call the method with no argments + r := m.Call(nil) + // interpret first return value as int + fmt.Println(r[0].Int()) // => 42 +} diff --git a/Task/Send-an-unknown-method-call/Groovy/send-an-unknown-method-call-1.groovy b/Task/Send-an-unknown-method-call/Groovy/send-an-unknown-method-call-1.groovy new file mode 100644 index 0000000000..2965351438 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Groovy/send-an-unknown-method-call-1.groovy @@ -0,0 +1,11 @@ +class Example { + def foo(value) { + "Invoked with '$value'" + } +} + +def example = new Example() +def method = "foo" +def arg = "test value" + +assert "Invoked with 'test value'" == example."$method"(arg) diff --git a/Task/Send-an-unknown-method-call/Groovy/send-an-unknown-method-call-2.groovy b/Task/Send-an-unknown-method-call/Groovy/send-an-unknown-method-call-2.groovy new file mode 100644 index 0000000000..623167b44a --- /dev/null +++ b/Task/Send-an-unknown-method-call/Groovy/send-an-unknown-method-call-2.groovy @@ -0,0 +1,12 @@ +procedure main() + x := foo() # create object + x.m1() # static call of m1 method + # two examples where the method string can be dynamically constructed ... + "foo_m1"(x) # ... need to know class name and method name to construct name + x.__m["m1"] # ... general method (better) +end + +class foo(a,b,c) # define object +method m1(x) +end +end diff --git a/Task/Set-consolidation/PL-I/set-consolidation.pli b/Task/Set-consolidation/PL-I/set-consolidation.pli new file mode 100644 index 0000000000..026312a82c --- /dev/null +++ b/Task/Set-consolidation/PL-I/set-consolidation.pli @@ -0,0 +1,58 @@ +Set: procedure options (main); /* 13 November 2013 */ + declare set(20) character (200) varying; + declare e character (1); + declare (i, n) fixed binary; + + set = ''; + n = 1; + do until (e = ']'); + get edit (e) (a(1)); put edit (e) (a(1)); + if e = '}' then n = n + 1; /* end of set. */ + if e ^= '{' & e ^= ',' & e ^= '}' & e ^= ' ' then + set(n) = set(n) || e; /* Build set */ + end; + /* We have read in all sets. */ + n = n - 1; /* we have n sets */ + /* Display the sets: */ + put skip list ('The original sets:'); + do i = 1 to n; + call print(i); + end; + /* Look for sets to combine: */ + do i = 2 to n; + if length(set(i)) > 0 then + if search(set(1), set(i)) > 0 then + /* there's at least one common element */ + do; call combine (1, i); set(i) = ''; end; + end; + + put skip (2) list ('Results:'); + do i = 1 to n; + if length(set(i)) > 0 then call print (i); + end; + +combine: procedure (p, q); + declare (p, q) fixed binary; + declare e character (1); + declare i fixed binary; + + do i = 1 to length(set(q)); + e = substr(set(q), i, 1); + if index(set(p), e) = 0 then set(p) = set(p) || e; + end; + +end combine; + +print: procedure(k); + declare k fixed binary; + declare i fixed binary; + + put edit ('{') (a); + do i = 1 to length(set(k)); + put edit (substr(set(k), i, 1)) (a); + if i < length(set(k)) then put edit (',') (a); + end; + put edit ('} ') (a); +end print; + +end Set; diff --git a/Task/Set-consolidation/Perl-6/set-consolidation.pl6 b/Task/Set-consolidation/Perl-6/set-consolidation.pl6 index 4d0d8a5518..cb06cc12c2 100644 --- a/Task/Set-consolidation/Perl-6/set-consolidation.pl6 +++ b/Task/Set-consolidation/Perl-6/set-consolidation.pl6 @@ -2,14 +2,14 @@ multi consolidate() { () } multi consolidate(Set \this is copy, *@those) { gather { for consolidate |@those -> \that { - if this ∩ that { this ∪= that } + if this ∩ that { this = this ∪ that } else { take that } } take this; } } -enum Elems ('A'..'Z'); +enum Elems ; say $_, "\n ==> ", consolidate |$_ for [set(A,B), set(C,D)], [set(A,B), set(B,D)], diff --git a/Task/Set-consolidation/Ruby/set-consolidation.rb b/Task/Set-consolidation/Ruby/set-consolidation.rb new file mode 100644 index 0000000000..12418f2bdc --- /dev/null +++ b/Task/Set-consolidation/Ruby/set-consolidation.rb @@ -0,0 +1,17 @@ +require 'set' + +tests = [[['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']]] +tests = tests.map{|sets| sets.map(&:to_set)} + +tests.map do |sets| + loop until sets.combination(2).none? do |a,b| + if a.intersect?(b) then + a.merge(b) + sets.delete(b) + end + end + p sets +end diff --git a/Task/Set-puzzle/Erlang/set-puzzle.erl b/Task/Set-puzzle/Erlang/set-puzzle.erl new file mode 100644 index 0000000000..9b9090419d --- /dev/null +++ b/Task/Set-puzzle/Erlang/set-puzzle.erl @@ -0,0 +1,83 @@ +-module( set ). + +-export( [deck/0, is_set/3, shuffle_deck/1, task/0] ). + +-record( card, {number, symbol, shading, colour} ). + +deck() -> [#card{number=N, symbol=Sy, shading=Sh, colour=C} || N <- [1,2,3], Sy <- [diamond, squiggle, oval], Sh <- [solid, striped, open], C <- [red, green, purple]]. + +is_set( Card1, Card2, Card3 ) -> + is_colour_correct( Card1, Card2, Card3 ) + andalso is_number_correct( Card1, Card2, Card3 ) + andalso is_shading_correct( Card1, Card2, Card3 ) + andalso is_symbol_correct( Card1, Card2, Card3 ). + +shuffle_deck( Deck ) -> knuth_shuffle:list( Deck ). + +task() -> + basic(), + advanced(). + + + +advanced() -> common( 6, 12 ). + +basic() -> common( 4, 9 ). + +common( X, Y ) -> + {Sets, Cards} = find_x_sets_in_y_cards( X, Y, deck() ), + io:fwrite( "Cards ~p~n", [Cards] ), + io:fwrite( "Gives sets:~n" ), + [io:fwrite( "~p~n", [S] ) || S <- Sets]. + +find_x_sets_in_y_cards( X, Y, Deck ) -> + {Cards, _T} = lists:split( Y, shuffle_deck(Deck) ), + find_x_sets_in_y_cards( X, Y, Cards, make_sets1(Cards, []) ). + +find_x_sets_in_y_cards( X, _Y, _Deck, Cards, Sets ) when erlang:length(Sets) =:= X -> {Sets, Cards}; +find_x_sets_in_y_cards( X, Y, Deck, _Cards, _Sets ) -> find_x_sets_in_y_cards( X, Y, Deck ). + +is_colour_correct( Card1, Card2, Card3 ) -> is_colour_different( Card1, Card2, Card3 ) orelse is_colour_same( Card1, Card2, Card3 ). + +is_colour_different( #card{colour=C1}, #card{colour=C2}, #card{colour=C3} ) when C1 =/= C2, C1 =/= C3, C2 =/= C3 -> true; +is_colour_different( _Card1, _Card2, _Card3 ) -> false. + +is_colour_same( #card{colour=C}, #card{colour=C}, #card{colour=C} ) -> true; +is_colour_same( _Card1, _Card2, _Card3 ) -> false. + +is_number_correct( Card1, Card2, Card3 ) -> is_number_different( Card1, Card2, Card3 ) orelse is_number_same( Card1, Card2, Card3 ). + +is_number_different( #card{number=N1}, #card{number=N2}, #card{number=N3} ) when N1 =/= N2, N1 =/= N3, N2 =/= N3 -> true; +is_number_different( _Card1, _Card2, _Card3 ) -> false. + +is_number_same( #card{number=N}, #card{number=N}, #card{number=N} ) -> true; +is_number_same( _Card1, _Card2, _Card3 ) -> false. + +is_shading_correct( Card1, Card2, Card3 ) -> is_shading_different( Card1, Card2, Card3 ) orelse is_shading_same( Card1, Card2, Card3 ). + +is_shading_different( #card{shading=S1}, #card{shading=S2}, #card{shading=S3} ) when S1 =/= S2, S1 =/= S3, S2 =/= S3 -> true; +is_shading_different( _Card1, _Card2, _Card3 ) -> false. + +is_shading_same( #card{shading=S}, #card{shading=S}, #card{shading=S} ) -> true; +is_shading_same( _Card1, _Card2, _Card3 ) -> false. + +is_symbol_correct( Card1, Card2, Card3 ) -> is_symbol_different( Card1, Card2, Card3 ) orelse is_symbol_same( Card1, Card2, Card3 ). + +is_symbol_different( #card{symbol=S1}, #card{symbol=S2}, #card{symbol=S3} ) when S1 =/= S2, S1 =/= S3, S2 =/= S3 -> true; +is_symbol_different( _Card1, _Card2, _Card3 ) -> false. + +is_symbol_same( #card{symbol=S}, #card{symbol=S}, #card{symbol=S} ) -> true; +is_symbol_same( _Card1, _Card2, _Card3 ) -> false. +%% Nested loops 1, 2 and 3 +make_sets1( [_Second_to_last, _Last], Sets ) -> Sets; +make_sets1( [Card | T], Sets ) -> make_sets1( T, make_sets2(Card, T, Sets) ). + +make_sets2( _Card, [_Last], Sets ) -> Sets; +make_sets2( Card1, [Card2 | T], Sets ) -> make_sets2( Card1, T, make_sets3( Card1, Card2, T, Sets) ). + +make_sets3( _Card1, _Card2, [], Sets ) -> Sets; +make_sets3( Card1, Card2, [Card3 | T], Sets ) -> + make_sets3( Card1, Card2, T, make_sets_acc(is_set(Card1, Card2, Card3), {Card1, Card2, Card3}, Sets) ). + +make_sets_acc( true, Set, Sets ) -> [Set | Sets]; +make_sets_acc( false, _Set, Sets ) -> Sets. diff --git a/Task/Set-puzzle/Go/set-puzzle.go b/Task/Set-puzzle/Go/set-puzzle.go new file mode 100644 index 0000000000..5c680a48ad --- /dev/null +++ b/Task/Set-puzzle/Go/set-puzzle.go @@ -0,0 +1,85 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +var ( + number = []string{"1", "2", "3"} + color = []string{"red", "green", "purple"} + shade = []string{"solid", "open", "striped"} + shape = []string{"oval", "squiggle", "diamond"} +) + +type card int + +func (c card) String() string { + return fmt.Sprintf("%s %s %s %s", + number[c/27], + color[c/9%3], + shade[c/3%3], + shape[c%3]) +} + +func main() { + rand.Seed(time.Now().Unix()) + basic() + advanced() +} + +func basic() { + game("Basic", 9, 4) +} + +func advanced() { + game("Advanced", 12, 6) +} + +func game(level string, cards, sets int) { + // create deck + d := make([]card, 81) + for i := range d { + d[i] = card(i) + } + var found [][3]card + for len(found) != sets { + found = found[:0] + // deal + for i := 0; i < cards; i++ { + j := rand.Intn(81 - i) + d[i], d[j] = d[j], d[i] + } + // consider all triplets + for i := 2; i < cards; i++ { + c1 := d[i] + for j := 1; j < i; j++ { + c2 := d[j] + l3: + for _, c3 := range d[:j] { + for f := card(1); f < 81; f *= 3 { + if (c1/f%3+c2/f%3+c3/f%3)%3 != 0 { + continue l3 // not a set + } + } + // it's a set + found = append(found, [3]card{c1, c2, c3}) + } + } + } + } + // found the right number + fmt.Printf("%s game. %d cards, %d sets.\n", level, cards, sets) + fmt.Println("Cards:") + for _, c := range d[:cards] { + fmt.Println(" ", c) + } + fmt.Println("Sets:") + for _, s := range found { + fmt.Println(" ", s[0]) + fmt.Println(" ", s[1]) + fmt.Println(" ", s[2]) + fmt.Println() + } +} diff --git a/Task/Set-puzzle/J/set-puzzle-1.j b/Task/Set-puzzle/J/set-puzzle-1.j index 91a8bb01d4..04362826d1 100644 --- a/Task/Set-puzzle/J/set-puzzle-1.j +++ b/Task/Set-puzzle/J/set-puzzle-1.j @@ -18,7 +18,7 @@ set_puzzle=: verb define Hand=. y drawRandom Deck end. echo 'Dealt ',(": y),' Cards:' - echo sayCards Hand - echo 'Found ',(":target),' Sets:' - echo sayCards getSets Hand + echo sayCards sort Hand + echo LF,'Found ',(":target),' Sets:' + echo sayCards sort"2 getSets Hand ) diff --git a/Task/Set-puzzle/J/set-puzzle-2.j b/Task/Set-puzzle/J/set-puzzle-2.j index 080de3666c..37a60f4a72 100644 --- a/Task/Set-puzzle/J/set-puzzle-2.j +++ b/Task/Set-puzzle/J/set-puzzle-2.j @@ -1,27 +1,28 @@ set_puzzle 9 Dealt 9 Cards: +one, red, solid, oval +one, green, open, squiggle +two, purple, striped, squiggle +three, red, solid, squiggle +three, red, open, oval +three, green, solid, oval +three, green, open, diamond three, purple, open, oval -three, green, open, diamond -three, red, solid, squiggle -three, green, solid, oval three, purple, striped, oval -three, red, open, oval -one, red, solid, oval -one, green, open, squiggle -two, purple, striped, squiggle + Found 4 Sets: -three, green, open, diamond three, red, solid, squiggle +three, green, open, diamond three, purple, striped, oval -three, green, open, diamond one, red, solid, oval two, purple, striped, squiggle +three, green, open, diamond -three, red, solid, squiggle one, green, open, squiggle two, purple, striped, squiggle +three, red, solid, squiggle +three, red, open, oval three, green, solid, oval three, purple, striped, oval -three, red, open, oval diff --git a/Task/Set-puzzle/Perl/set-puzzle.pl b/Task/Set-puzzle/Perl/set-puzzle.pl new file mode 100644 index 0000000000..8abd90bc91 --- /dev/null +++ b/Task/Set-puzzle/Perl/set-puzzle.pl @@ -0,0 +1,79 @@ +#!perl +use strict; +use warnings; + +# This code was adapted from the perl6 solution for this task. + +# Each element of the deck is an integer, which, when written +# in octal, has four digits, which are all either 1, 2, or 4. + +my $fmt = '%4o'; +my @deck = grep sprintf($fmt, $_) !~ tr/124//c, 01111 .. 04444; + +# Given a feature digit (1, 2, or 4), produce the feature's name. +# Note that digits 0 and 3 are unused. +my @features = map [split ' '], split /\n/,<<''; +! red green ! purple +! one two ! three +! oval squiggle ! diamond +! solid open ! striped + +81 == @deck or die "There are ".@deck." cards (should be 81)"; + +# By default, draw 9 cards, but if the user +# supplied a parameter, use that. +my $draw = shift(@ARGV) || 9; +my $goal = int($draw/2); + +# Get the possible combinations of 3 indices into $draw elements. +my @combinations = combine(3, 0 .. $draw-1); + +my @sets; + +do { + # Shuffle the first $draw elements of @deck. + for my $i ( 0 .. $draw-1 ) { + my $j = $i + int rand(@deck - $i); + @deck[$i, $j] = @deck[$j, $i]; + } + + # Find all valid sets using the shuffled elements. + @sets = grep { + my $or = 0; + $or |= $_ for @deck[@$_]; + # If all colors (or whatever) are the same, then + # a 1, 2, or 4 will result when we OR them together. + # If they're all different, then a 7 will result. + # If any other digit occurs, the set is invalid. + sprintf($fmt, $or) !~ tr/1247//c; + } @combinations; + + # Continue until there are exactly $goal valid sets. +} until @sets == $goal; + +print "Drew $draw cards:\n"; +for my $i ( 0 .. $#sets ) { + print "Set ", $i+1, ":\n"; + my @cards = @deck[ @{$sets[$i]} ]; + for my $card ( @cards ) { + my @octal = split //, sprintf '%4o', $card; + my @f = map $features[$_][$octal[$_]], 0 .. 3; + printf " %-6s %-5s %-8s %s\n", @f; + } +} + +exit; + +# This function is adapted from the perl5i solution for the +# RosettaCode Combinations task. +sub combine { + my $n = shift; + return unless @_; + return map [$_], @_ if $n == 1; + my $head = shift; + my @result = combine( $n-1, @_ ); + unshift @$_, $head for @result; + @result, combine( $n, @_ ); +} + +__END__ diff --git a/Task/Set-puzzle/Ruby/set-puzzle.rb b/Task/Set-puzzle/Ruby/set-puzzle.rb index eecc11d0a4..c21d4b258a 100644 --- a/Task/Set-puzzle/Ruby/set-puzzle.rb +++ b/Task/Set-puzzle/Ruby/set-puzzle.rb @@ -2,13 +2,7 @@ COLORS = %i(red green purple) #use [:red, :green, :purple] in Ruby < 2.0 SYMBOLS = %i(oval squiggle diamond) NUMBERS = %i(one two three) SHADINGS = %i(solid open striped) -FEATURES = [COLORS, SYMBOLS, NUMBERS, SHADINGS] - -@hand_size = 9 -@num_sets_goal = 4 - -#create an enumerator which deals all combinations of @hand_size cards -@dealer = FEATURES[0].product(*FEATURES[1..-1]).shuffle.combination(@hand_size) +DECK = COLORS.product(SYMBOLS, NUMBERS, SHADINGS) def get_all_sets(hand) hand.combination(3).select do |candidate| @@ -17,22 +11,26 @@ def get_all_sets(hand) end end -def get_puzzle_and_answer - sets = [] - until sets.size == @num_sets_goal do - hand = @dealer.next +def get_puzzle_and_answer(hand_size, num_sets_goal) + begin + hand = DECK.sample(hand_size) sets = get_all_sets(hand) - end + end until sets.size == num_sets_goal [hand, sets] end def print_cards(cards) - cards.each{|card| puts card.join(", ")} + puts cards.map{|card| " %-8s" * 4 % card} puts end -puzzle, sets = get_puzzle_and_answer -puts "Dealt #{puzzle.size} cards:" -print_cards(puzzle) -puts "Containing #{sets.size} sets:" -sets.each{|set| print_cards(set)} +def set_puzzle(deal, goal=deal/2) + puzzle, sets = get_puzzle_and_answer(deal, goal) + puts "Dealt #{puzzle.size} cards:" + print_cards(puzzle) + puts "Containing #{sets.size} sets:" + sets.each{|set| print_cards(set)} +end + +set_puzzle(9) +set_puzzle(12) diff --git a/Task/Set/D/set.d b/Task/Set/D/set.d index 0c963530a7..811b877730 100644 --- a/Task/Set/D/set.d +++ b/Task/Set/D/set.d @@ -1,18 +1,21 @@ -import std.stdio, std.algorithm; - void main() { - auto set1 = [1, 2, 3, 4, 5, 6]; - auto set2 = [2, 5, 6, 3, 4, 8].sort; // [2, 3, 4, 5, 6, 8] - auto set3 = [1, 2, 5]; + import std.stdio, std.algorithm, std.range; - assert(equal(setUnion(set1, set2), [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 8])); - assert(equal(setIntersection(set1, set2), [2, 3, 4, 5, 6])); - assert(equal(setDifference(set1, set2), [1])); - assert(equal(setSymmetricDifference(set1, set2), [1, 8])); - assert(equal(setDifference(set3, set1), new int[](0))); // subset - assert(set1 != set2); + // Not true sets, items can be repeated, but must be sorted. + auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted; + auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8]. + auto s3 = [1, 2, 5].assumeSorted; - auto set4 = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; - auto set5 = [ 1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8 ]; - assert(equal(nWayUnion(set4), set5)); + assert(s1.canFind(4)); // Linear search. + assert(s1.contains(4)); // Binary search. + assert(s1.setUnion(s2).equal([1,2,2,3,3,4,4,5,5,6,6,8])); + assert(s1.setIntersection(s2).equal([2, 3, 4, 5, 6])); + assert(s1.setDifference(s2).equal([1])); + assert(s1.setSymmetricDifference(s2).equal([1, 8])); + assert(s3.setDifference(s1).empty); // It's a subset. + assert(!s1.equal(s2)); + + auto s4 = [[1, 4, 7, 8], [1, 7], [1, 7, 8], [4], [7]]; + const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8]; + assert(s4.nWayUnion.equal(s5)); } diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Perl/seven-sided-dice-from-five-sided-dice.pl b/Task/Seven-sided-dice-from-five-sided-dice/Perl/seven-sided-dice-from-five-sided-dice.pl new file mode 100644 index 0000000000..5d07ce2e53 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Perl/seven-sided-dice-from-five-sided-dice.pl @@ -0,0 +1,13 @@ +sub dice5 { 1+int rand(5) } + +sub dice7 { + while(1) { + my $d7 = (5*dice5()+dice5()-6) % 8; + return $d7 if $d7; + } +} + +my %count7; +my $n = 1000000; +$count7{dice7()}++ for 1..$n; +printf "%s: %5.2f%%\n", $_, 100*($count7{$_}/$n*7-1) for sort keys %count7; diff --git a/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk b/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk index 30bd4db726..2b1fa83243 100644 --- a/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk +++ b/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk @@ -1,17 +1,17 @@ #!/usr/bin/awk -f BEGIN { - print (a(1) && b(1)); - print (a(1) || b(1)); - print (a(0) && b(1)); - print (a(0) || b(1)); + print (a(1) && b(1)) + print (a(1) || b(1)) + print (a(0) && b(1)) + print (a(0) || b(1)) } function a(x) { - print " x:"x; - return x; + print " x:"x + return x } function b(y) { - print " y:"y; - return y; + print " y:"y + return y } diff --git a/Task/Show-the-epoch/Limbo/show-the-epoch-1.limbo b/Task/Show-the-epoch/Limbo/show-the-epoch-1.limbo new file mode 100644 index 0000000000..08ff268d46 --- /dev/null +++ b/Task/Show-the-epoch/Limbo/show-the-epoch-1.limbo @@ -0,0 +1,17 @@ +implement Epoch; + +include "sys.m"; sys: Sys; +include "draw.m"; +include "daytime.m"; daytime: Daytime; + Tm: import daytime; + +Epoch: 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; + daytime = load Daytime Daytime->PATH; + sys->print("%s\n", daytime->text(daytime->gmt(0))); +} diff --git a/Task/Show-the-epoch/Limbo/show-the-epoch-2.limbo b/Task/Show-the-epoch/Limbo/show-the-epoch-2.limbo new file mode 100644 index 0000000000..7aae0fc8d0 --- /dev/null +++ b/Task/Show-the-epoch/Limbo/show-the-epoch-2.limbo @@ -0,0 +1,34 @@ +implement Epoch; + +include "sys.m"; sys: Sys; +include "draw.m"; +include "daytime.m"; daytime: Daytime; + Tm: import daytime; + +Epoch: 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; + daytime = load Daytime Daytime->PATH; + + # Create a file containing a zero: + fd := sys->open("/tmp/0", Sys->OWRITE); + if(fd == nil) { + sys->fprint(sys->fildes(2), "Couldn't open /tmp/0 for writing: %r\n"); + raise "fail:errors"; + } + sys->fprint(fd, "0"); + fd = nil; # Files with no references are closed immediately. + + # Fork the namespace so as not to disturb the parent + # process's concept of time: + sys->pctl(Sys->FORKNS, nil); + # Bind that file over /dev/time: + sys->bind("/tmp/0", "/dev/time", Sys->MREPL); + + # Print the "current" date, now the epoch: + sys->print("%s\n", daytime->text(daytime->gmt(daytime->now()))); +} diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d index aabb949d5b..c4f15b4087 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d @@ -1,23 +1,27 @@ -import std.stdio, std.algorithm, std.range, std.conv; +import std.stdio, std.array; -string sierpinskiCarpet(in int n) /*pure nothrow*/ { - static bool inCarpet(int x, int y) pure nothrow { - while (x != 0 && y != 0) { - if (x % 3 == 1 && y % 3 == 1) - return false; - x /= 3; - y /= 3; +char[][] sierpinskiCarpet(in size_t n) pure nothrow { + auto mat = uninitializedArray!(typeof(return))(3 ^^ n, 3 ^^ n); + + foreach (immutable r, row; mat) { + row[] = '#'; + foreach (immutable c, ref cell; row) { + size_t r2 = r, c2 = c; + while (r2 && c2) { + if (r2 % 3 == 1 && c2 % 3 == 1) { + cell = ' '; + break; + } + r2 /= 3; + c2 /= 3; + } } - return true; } - return iota(3 ^^ n) - .map!(i => iota(3 ^^ n) - .map!(j=> cast(dchar)(inCarpet(i,j)? '#' : ' '))) - .joiner("\n") - .text; + return mat; } void main() { - 3.sierpinskiCarpet.writeln; + writefln("%-(%s\n%)", 3.sierpinskiCarpet); + 7.sierpinskiCarpet.length.writeln; } diff --git a/Task/Sierpinski-triangle-Graphical/ActionScript/sierpinski-triangle-graphical-1.as b/Task/Sierpinski-triangle-Graphical/ActionScript/sierpinski-triangle-graphical-1.as new file mode 100644 index 0000000000..b5cff9c2f3 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/ActionScript/sierpinski-triangle-graphical-1.as @@ -0,0 +1,79 @@ +package { + + import flash.display.GraphicsPathCommand; + import flash.display.Sprite; + + /** + * A Sierpinski triangle. + */ + public class SierpinskiTriangle extends Sprite { + + /** + * Creates a new SierpinskiTriangle object. + * + * @param n The order of the Sierpinski triangle. + * @param c1 The background colour. + * @param c2 The foreground colour. + * @param width The width of the triangle. + * @param height The height of the triangle. + */ + public function SierpinskiTriangle(n:uint, c1:uint, c2:uint, width:Number, height:Number):void { + _init(n, c1, c2, width, height); + } + + /** + * Generates the triangle. + * + * @param n The order of the Sierpinski triangle. + * @param c1 The background colour. + * @param c2 The foreground colour. + * @param width The width of the triangle. + * @param height The height of the triangle. + * @private + */ + private function _init(n:uint, c1:uint, c2:uint, width:Number, height:Number):void { + + if ( n <= 0 ) + return; + + // Draw the outer triangle. + + graphics.beginFill(c1); + graphics.moveTo(width / 2, 0); + graphics.lineTo(0, height); + graphics.lineTo(width, height); + graphics.lineTo(width / 2, 0); + + // Draw the inner triangle. + + graphics.beginFill(c2); + graphics.moveTo(width / 4, height / 2); + graphics.lineTo(width * 3 / 4, height / 2); + graphics.lineTo(width / 2, height); + graphics.lineTo(width / 4, height / 2); + + if ( n == 1 ) + return; + + // Recursively generate three Sierpinski triangles of half the size and order n - 1 and position them appropriately. + + var sub1:SierpinskiTriangle = new SierpinskiTriangle(n - 1, c1, c2, width / 2, height / 2); + var sub2:SierpinskiTriangle = new SierpinskiTriangle(n - 1, c1, c2, width / 2, height / 2); + var sub3:SierpinskiTriangle = new SierpinskiTriangle(n - 1, c1, c2, width / 2, height / 2); + + sub1.x = width / 4; + sub1.y = 0; + sub2.x = 0; + sub2.y = height / 2; + sub3.x = width / 2; + sub3.y = height / 2; + + addChild(sub1); + addChild(sub2); + addChild(sub3); + + } + + } + +} diff --git a/Task/Sierpinski-triangle-Graphical/ActionScript/sierpinski-triangle-graphical-2.as b/Task/Sierpinski-triangle-Graphical/ActionScript/sierpinski-triangle-graphical-2.as new file mode 100644 index 0000000000..2a12d8a987 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/ActionScript/sierpinski-triangle-graphical-2.as @@ -0,0 +1,22 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + + public class Main extends Sprite { + + public function Main():void { + if ( stage ) init(); + else addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(e:Event = null):void { + var s:SierpinskiTriangle = new SierpinskiTriangle(5, 0x0000FF, 0xFFFF00, 300, 150 * Math.sqrt(3)); + // Equilateral triangle (blue and yellow) + s.x = s.y = 20; + addChild(s); + } + + } + +} diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust new file mode 100644 index 0000000000..f51faa5dfe --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust @@ -0,0 +1,28 @@ +use std::vec; +use std::num; +use std::iter; + +fn int_sqrt(n: uint) -> uint { + num::sqrt(n as f64) as uint +} + +fn simple_sieve(limit: uint) -> ~[uint] { + if limit < 2 { + return ~[]; + } + + let mut primes = vec::from_elem(limit + 1, true); + + for prime in iter::range_inclusive(2, int_sqrt(limit) + 1) { + if primes[prime] { + for multiple in iter::range_step(prime * prime, limit + 1, prime) { + primes[multiple] = false + } + } + } + iter::range_inclusive(2, limit).filter(|&n| primes[n]).collect() +} + +fn main() { + println!("{:?}", simple_sieve(100)) +} diff --git a/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia new file mode 100644 index 0000000000..00c1a078c0 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia @@ -0,0 +1,27 @@ +type Node{T} + data::T + next::Node{T} + + function Node(data::T) + n = new() + n.data = data + # mark the end of the list. Julia does not have nil or null. + n.next = n + n + end +end + +# convenience. Let use write Node(10) or Node(10.0) instead of Node{Int64}(10), Node{Float64}(10.0) +function Node(data) + return Node{typeof(data)}(data) +end + +islast(n::Node) = (n == n.next) + +function append{T}(n::Node{T}, data::T) + tmp = Node(data) + if !islast(n) + tmp.next = n.next + end + n.next = tmp +end diff --git a/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-2.julia b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-2.julia new file mode 100644 index 0000000000..713d618280 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-2.julia @@ -0,0 +1,3 @@ +head = Node(1) +n = append(head, 2) +n = append(n, 3) diff --git a/Task/Singly-linked-list-Element-definition/PL-I/singly-linked-list-element-definition.pli b/Task/Singly-linked-list-Element-definition/PL-I/singly-linked-list-element-definition.pli new file mode 100644 index 0000000000..c9d89b0abd --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/PL-I/singly-linked-list-element-definition.pli @@ -0,0 +1,3 @@ +declare 1 node based (p), + 2 value fixed, + 2 link pointer; diff --git a/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx b/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx index 73d1520f29..0bc593cca0 100644 --- a/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx +++ b/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx @@ -1,34 +1,38 @@ -/*REXX program to show how to create and show a single-linked list. */ -@.=0 /*define a null linked list (so far). */ -call set@ ,3 /*build linked list of 12 proth primes.*/ -call set@ ,5 -call set@ ,13 -call set@ ,17 -call set@ ,41 -call set@ ,97 -call set@ ,113 -call set@ ,193 -call set@ ,241 -call set@ ,257 -call set@ ,353 -call set@ ,449 -w=length(@._last) /*use width of the last item number. */ - - do j=1 for @._last /*show all entries of the linked list.*/ - say "item" right(j,w) '=' right(@.j._value,@.max_width) - end /*j*/ -exit /*stick a fork in it, we're done. */ -/*───────────────────────────────SET@ subroutine────────────────────────*/ -set@: procedure expose @.; parse arg #,y -if arg(1,'o') then do /*if 1st arg omitted, then add to list*/ - _=@._last+1 /*bump the last ptr in the linked list*/ - @._last=_ /*define the next item in linked list.*/ - #=_ /*point to this item in linked list.*/ - end -@.#._value=y /*set the item to the value specified.*/ +/*REXX program demonstrates how to create and show a single-linked list.*/ +@.=0 /*define a null linked list. */ +call set@ 3 /*linked list: 12 Proth Primes. */ +call set@ 5 +call set@ 13 +call set@ 17 +call set@ 41 +call set@ 97 +call set@ 113 +call set@ 193 +call set@ 241 +call set@ 257 +call set@ 353 +call set@ 449 +w=@.max_width /*use the maximum width of nums. */ +call list@ /*list all the elements in list. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────LIST@ subroutine────────────────────*/ +list@: say; w=max(7, @.max_width ) /*use the max width of nums or 7.*/ +say center('item',6) center('value',w) center('next',6) +say center('' ,6,'─') center('' ,w,'─') center('' ,6,'─') +p=1 + do j=1 until p==0 /*show all entries of linked list*/ + say right(j,6) right(@.p._value,w) right(@.p._next,6) + p=@.p._next + end /*j*/ +return +/*──────────────────────────────────SET@ subroutine─────────────────────*/ +set@: procedure expose @.; parse arg y /*get element to be added to list*/ +_=@._last /*set the previous last element. */ +n=_+1 /*bump last ptr in linked list. */ +@._._next=n /*set the next pointer value. */ +@._last=n /*define next item in linked list*/ +@.n._value=y /*set item to the value specified*/ +@.n._next=0 /*set the next pointer value. */ +@..y=n /*set a locator pointer to self. */ @.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/ -if #\==1 then do /*if not the first item, link it. */ - prev=#-1 /*figure out what the previous item is*/ - @.prev._next=# /*now, link the previous item to here.*/ - end -return /*return to the invoker of this sub. *// +return /*return to invoker of this sub. */ diff --git a/Task/Singly-linked-list-Element-insertion/PL-I/singly-linked-list-element-insertion.pli b/Task/Singly-linked-list-Element-insertion/PL-I/singly-linked-list-element-insertion.pli new file mode 100644 index 0000000000..e560c1cb2a --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/PL-I/singly-linked-list-element-insertion.pli @@ -0,0 +1,7 @@ +/* Let H be a pointer to a node in a one-way-linked list. */ +/* Insert an element, whose value is given by variable V, following that node. */ + +allocate node set (Q); +node.p = H; /* The new node now points at the list where we want to insert it. */ +node.value = V; +H->p = Q; /* Break the list at H, and point it at the new node. */ diff --git a/Task/Singly-linked-list-Element-insertion/REXX/singly-linked-list-element-insertion.rexx b/Task/Singly-linked-list-Element-insertion/REXX/singly-linked-list-element-insertion.rexx new file mode 100644 index 0000000000..9fb634abed --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/REXX/singly-linked-list-element-insertion.rexx @@ -0,0 +1,54 @@ +/*REXX program demonstrates how to create and show a single-linked list.*/ +@.=0 /*define a null linked list. */ +call set@ 3 /*linked list: 12 Proth primes. */ +call set@ 5 +call set@ 13 +call set@ 17 +call set@ 41 +call set@ 97 +call set@ 113 +call set@ 193 +call set@ 241 +call set@ 257 +call set@ 353 +call set@ 449 +call list@ + after = 97 /* ◄──── REXX code to do insert. */ + newVal=100 /* ◄──── " " " " " */ + #=@..after /* ◄──── " " " " " */ + call ins@ #,newVal /* ◄──── " " " " " */ +say +say 'a new value of' newval "has been inserted after element value:" after +call list@ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────INS@ subroutine─────────────────────*/ +ins@: procedure expose @.; parse arg #,y +@._last=@._last+1 /*bump number of list elements. */ +_=@._last +@._._value=y /*define new value list element. */ +@._._next=@.#._next +@.#._next=_ +@..y=_ /*set a locator pointer to self. */ +@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/ +return /*return to invoker of this sub. */ +/*──────────────────────────────────LIST@ subroutine────────────────────*/ +list@: say; w=max(7, @.max_width ) /*use the max width of nums or 7.*/ +say center('item',6) center('value',w) center('next',6) +say center('' ,6,'─') center('' ,w,'─') center('' ,6,'─') +p=1 + do j=1 until p==0 /*show all entries of linked list*/ + say right(j,6) right(@.p._value,w) right(@.p._next,6) + p=@.p._next + end /*j*/ +return +/*──────────────────────────────────SET@ subroutine─────────────────────*/ +set@: procedure expose @.; parse arg y /*get element to be added to list*/ +_=@._last /*set the previous last element. */ +n=_+1 /*bump last ptr in linked list. */ +@._._next=n /*set the next pointer value. */ +@._last=n /*define next item in linked list*/ +@.n._value=y /*set item to the value specified*/ +@.n._next=0 /*set the next pointer value. */ +@..y=n /*set a locator pointer to self. */ +@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/ +return /*return to invoker of this sub. */ diff --git a/Task/Sleep/VBA/sleep.vba b/Task/Sleep/VBA/sleep.vba new file mode 100644 index 0000000000..f5ed64bdcf --- /dev/null +++ b/Task/Sleep/VBA/sleep.vba @@ -0,0 +1,5 @@ +Function Sleep(iSecsWait As Integer) +Debug.Print Now(), "Sleeping..." +Application.Wait Now + iSecsWait / 86400 'Time is stored as fractions of 24 hour day +Debug.Print Now(), "Awake!" +End Function diff --git a/Task/Sokoban/D/sokoban-1.d b/Task/Sokoban/D/sokoban-1.d index 63cf2bd9e0..4d180f3337 100644 --- a/Task/Sokoban/D/sokoban-1.d +++ b/Task/Sokoban/D/sokoban-1.d @@ -1,36 +1,44 @@ import std.string, std.typecons, std.exception, std.algorithm; -import queue_usage2; // No queue in Phobos 2.063. +import queue_usage2; // No queue in Phobos 2.064. const struct Board { - private enum El : char { floor=' ', wall='#', goal='.', - box='$', player='@', boxOnGoal='*' } - private alias string CTable; + private enum El { floor = ' ', wall = '#', goal = '.', + box = '$', player = '@', boxOnGoal='*' } + private alias CTable = string; private immutable size_t ncols; private immutable CTable sData, dData; private immutable int playerx, playery; this(in string[] board) pure nothrow const in { - foreach (row; board) { + foreach (const row; board) { assert(row.length == board[0].length, "Unequal board rows."); - foreach (c; row) + foreach (immutable c; row) assert(c.inPattern(" #.$@*"), "Not valid input"); } } body { - immutable sMap=[' ':' ', '.':'.', '@':' ', '#':'#', '$':' ']; - immutable dMap=[' ':' ', '.':' ', '@':'@', '#':' ', '$':'*']; + immutable sMap = [' ':' ', '.':'.', '@':' ', '#':'#', '$':' ']; + immutable dMap = [' ':' ', '.':' ', '@':'@', '#':' ', '$':'*']; ncols = board[0].length; - foreach (r, row; board) - foreach (c, ch; row) { - sData ~= sMap[ch]; - dData ~= dMap[ch]; + int plx = 0, ply = 0; + CTable sDataBuild, dDataBuild; + + foreach (immutable r, const row; board) + foreach (immutable c, const ch; row) { + sDataBuild ~= sMap[ch]; + dDataBuild ~= dMap[ch]; if (ch == El.player) { - playerx = c; - playery = r; + plx = c; + ply = r; } } + + this.sData = sDataBuild; + this.dData = dDataBuild; + this.playerx = plx; + this.playery = ply; } private bool move(in int x, in int y, in int dx, @@ -72,7 +80,7 @@ const struct Board { string solve() pure { bool[immutable CTable] visitedSet = [dData: true]; - alias Tuple!(CTable, string, int, int) Four; + alias Four = Tuple!(CTable, string, int, int); GrowableCircularQueue!Four open; open.push(Four(dData, "", playerx, playery)); @@ -84,16 +92,16 @@ const struct Board { while (open.length) { //immutable (cur, cSol, x, y) = open.pop; immutable item = open.pop; - immutable CTable cur = item[0]; - immutable string cSol = item[1]; - immutable int x = item[2]; - immutable int y = item[3]; + immutable cur = item[0]; + immutable cSol = item[1]; + immutable x = item[2]; + immutable y = item[3]; - foreach (di; dirs) { + foreach (immutable di; dirs) { CTable temp = cur; //immutable (dx, dy) = di[0 .. 2]; - immutable int dx = di[0]; - immutable int dy = di[1]; + immutable dx = di[0]; + immutable dy = di[1]; if (temp[(y + dy) * ncols + x + dx] == El.boxOnGoal) { if (push(x, y, dx, dy, temp) && temp !in visitedSet) { diff --git a/Task/Sokoban/D/sokoban-2.d b/Task/Sokoban/D/sokoban-2.d index c2d0f495b4..5bf8ab8226 100644 --- a/Task/Sokoban/D/sokoban-2.d +++ b/Task/Sokoban/D/sokoban-2.d @@ -1,66 +1,83 @@ import core.stdc.stdio: printf, puts, fflush, stdout, putchar; import core.stdc.stdlib: malloc, calloc, realloc, free, alloca, exit; -import core.stdc.string: memcpy, memset, memcmp; -alias ushort cidx_t; -alias uint hash_t; +enum Cell : ubyte { space, wall, player, box } +alias CellIndex = ushort; +alias Thash = uint; -// Board configuration is represented by an array of cell -// indices of player and boxes. -struct State { - hash_t h; - State* prev, next, qnext; - cidx_t[0] c; -} -__gshared int w, h, n_boxes; -__gshared ubyte* board, goals, live; -__gshared size_t state_size, block_size = 32; -__gshared State* block_root, block_head; +/// Board configuration is represented by an array of cell +/// indices of player and boxes. +struct State { // Variable length struct. + Thash h; + State* prev, next, qNext; + CellIndex[0] c_; -State* newState(State* parent) nothrow { - static State* next_of(State *s) nothrow { - return cast(State*)(cast(ubyte*)s + state_size); + CellIndex get(in size_t i) inout pure nothrow { + return c_.ptr[i]; } - State *ptr; - if (!block_head) { - block_size *= 2; - State* p = cast(State*)malloc(block_size * state_size); - if (p == null) exit(1); - State* q; - p.next = block_root; - block_root = p; - ptr = cast(State*)(cast(ubyte*)p + state_size * block_size); - p = block_head = next_of(p); - for (q = next_of(p); q < ptr; p = q, q = next_of(q)) + void set(in size_t i, in CellIndex v) pure nothrow { + c_.ptr[i] = v; + } + + CellIndex[] slice(in size_t i, in size_t j) pure nothrow { + return c_.ptr[i .. j]; + } +} + + +__gshared Cell[] board; +__gshared bool[] goals, live; +__gshared size_t w, h, nBoxes, stateSize, blockSize = 32; +__gshared State* blockRoot, blockHead, nextLevel, done; +__gshared State*[] buckets; +__gshared Thash hashSize, fillLimit, filled; + + +State* newState(State* parent) nothrow { + static State* nextOf(State *s) nothrow { + return cast(State*)(cast(ubyte*)s + stateSize); + } + + State* ptr; + if (!blockHead) { + blockSize *= 2; + auto p = cast(State*)malloc(blockSize * stateSize); + if (p == null) + exit(1); + + p.next = blockRoot; + blockRoot = p; + ptr = cast(State*)(cast(ubyte*)p + stateSize * blockSize); + p = blockHead = nextOf(p); + for (auto q = nextOf(p); q < ptr; p = q, q = nextOf(q)) p.next = q; p.next = null; } - ptr = block_head; - block_head = block_head.next; - + ptr = blockHead; + blockHead = blockHead.next; ptr.prev = parent; ptr.h = 0; return ptr; } + void unNewState(State* p) nothrow { - p.next = block_head; - block_head = p; + p.next = blockHead; + blockHead = p; } -enum Cell { space, wall, player, box } -// mark up positions where a box definitely should not be -void markLive(in int c) nothrow { - immutable int y = c / w; - immutable int x = c % w; +/// Mark up positions where a box definitely should not be. +void markLive(in size_t c) nothrow { + immutable y = c / w; + immutable x = c % w; if (live[c]) return; - live[c] = 1; + live[c] = true; if (y > 1 && board[c - w] != Cell.wall && board[c - w * 2] != Cell.wall) markLive(c - w); @@ -75,120 +92,100 @@ void markLive(in int c) nothrow { markLive(c + 1); } -State* parseBoard(in int y, in int x, const char* s) nothrow { - w = x, h = y; - board = cast(ubyte*)calloc(w * h, ubyte.sizeof); - if (board == null) exit(2); - goals = cast(ubyte*)calloc(w * h, ubyte.sizeof); - if (goals == null) exit(3); - live = cast(ubyte*)calloc(w * h, ubyte.sizeof); - if (live == null) exit(4); - n_boxes = 0; +State* parseBoard(in size_t y, in size_t x, in char* s) nothrow { + static T[] myCalloc(T)(in size_t n) nothrow { + auto ptr = cast(T*)calloc(n, T.sizeof); + if (ptr == null) + exit(1); + return ptr[0 .. n]; + } + + w = x, h = y; + board = myCalloc!Cell(w * h); + goals = myCalloc!bool(w * h); + live = myCalloc!bool(w * h); + + nBoxes = 0; for (int i = 0; s[i]; i++) { switch(s[i]) { case '#': board[i] = Cell.wall; continue; case '.', '+': - goals[i] = 1; + goals[i] = true; goto case; case '@': continue; case '*': - goals[i] = 1; + goals[i] = true; goto case; case '$': - n_boxes++; + nBoxes++; continue; default: continue; } } - enum int int_size = int.sizeof; - state_size = (State.sizeof + - (1 + n_boxes) * cidx_t.sizeof + - int_size - 1) - / int_size * int_size; + enum int intSize = int.sizeof; + stateSize = (State.sizeof + + (1 + nBoxes) * CellIndex.sizeof + + intSize - 1) + / intSize * intSize; - State* state = newState(null); + auto state = null.newState; - for (cidx_t i = 0, j = 0; i < w * h; i++) { + for (CellIndex i = 0, j = 0; i < w * h; i++) { if (goals[i]) - markLive(i); + i.markLive; if (s[i] == '$' || s[i] == '*') - (cast(cidx_t*)&state.c)[++j] = i; + state.set(++j, i); else if (s[i] == '@' || s[i] == '+') - (cast(cidx_t*)&state.c)[0] = i; + state.set(0, i); } return state; } -void showBoard(const State* s) nothrow { - static immutable char*[] glyph1 = [" ", "#", "@", "$"]; - static immutable char*[] glyph2 = [".", "#", "@", "$"]; - auto ptr = cast(char*)alloca(w * h * char.sizeof); - if (ptr == null) exit(5); - auto b = ptr[0 .. w * h]; - - memcpy(b.ptr, board, w * h); - - b[(cast(cidx_t*)&s.c)[0]] = Cell.player; - for (int i = 1; i <= n_boxes; i++) - b[(cast(cidx_t*)&s.c)[i]] = Cell.box; - - for (int i = 0; i < w * h; i++) { - printf((goals[i] ? glyph2 : glyph1)[b[i]]); - if (!((1 + i) % w)) - putchar('\n'); - } -} - -// K&R hash function -void hash(State* s) nothrow { +/// K&R hash function. +void hash(State* s, in size_t nBoxes) pure nothrow { if (!s.h) { - hash_t ha = 0; - cidx_t* p = cast(cidx_t*)&s.c; - for (int i = 0; i <= n_boxes; i++) - ha = p[i] + 31 * ha; + Thash ha = 0; + foreach (immutable i; 0 .. nBoxes + 1) + ha = s.get(i) + 31 * ha; s.h = ha; } } -__gshared State** buckets; -__gshared hash_t hash_size, fill_limit, filled; void extendTable() nothrow { - int old_size = hash_size; + int oldSize = hashSize; - if (!old_size) { - hash_size = 1024; + if (!oldSize) { + hashSize = 1024; filled = 0; - fill_limit = hash_size * 3 / 4; // 0.75 load factor + fillLimit = hashSize * 3 / 4; // 0.75 load factor. } else { - hash_size *= 2; - fill_limit *= 2; + hashSize *= 2; + fillLimit *= 2; } - buckets = cast(State**)realloc(buckets, - (State*).sizeof * hash_size); - if (buckets == null) exit(6); + auto ptr = cast(State**)realloc(buckets.ptr, + (State*).sizeof * hashSize); + if (ptr == null) + exit(6); + buckets = ptr[0 .. hashSize]; + buckets[oldSize .. hashSize] = null; - // rehash - memset(buckets + old_size, - 0, - (State*).sizeof * (hash_size - old_size)); - - immutable hash_t bits = hash_size - 1; - for (int i = 0; i < old_size; i++) { - State *head = buckets[i]; + immutable Thash bits = hashSize - 1; + foreach (immutable i; 0 .. oldSize) { + auto head = buckets[i]; buckets[i] = null; while (head) { - State* next = head.next; - immutable int j = head.h & bits; + auto next = head.next; + immutable j = head.h & bits; head.next = buckets[j]; buckets[j] = head; head = next; @@ -196,44 +193,47 @@ void extendTable() nothrow { } } + State* lookup(State *s) nothrow { - hash(s); - State *f = buckets[s.h & (hash_size - 1)]; + s.hash(nBoxes); + auto f = buckets[s.h & (hashSize - 1)]; for (; f; f = f.next) { - if (!memcmp((cast(cidx_t*)&s.c), (cast(cidx_t*)&f.c), - cidx_t.sizeof * (1 + n_boxes))) + if (s.slice(0, nBoxes + 1) == f.slice(0, nBoxes + 1)) break; } return f; } + bool addToTable(State* s) nothrow { - if (lookup(s)) { - unNewState(s); + if (s.lookup) { + s.unNewState; return false; } - if (filled++ >= fill_limit) - extendTable(); + if (filled++ >= fillLimit) + extendTable; - immutable hash_t i = s.h & (hash_size - 1); + immutable Thash i = s.h & (hashSize - 1); s.next = buckets[i]; buckets[i] = s; return true; } -bool success(const State* s) nothrow { - for (int i = 1; i <= n_boxes; i++) - if (!goals[(cast(cidx_t*)&s.c)[i]]) + +bool success(in State* s) nothrow { + foreach (immutable i; 1 .. nBoxes + 1) + if (!goals[s.get(i)]) return false; return true; } -State* moveMe(State* s, int dy, int dx) nothrow { - immutable int y = (cast(cidx_t*)&s.c)[0] / w; - immutable int x = (cast(cidx_t*)&s.c)[0] % w; + +State* moveMe(State* s, in int dy, in int dx) nothrow { + immutable int y = s.get(0) / w; + immutable int x = s.get(0) % w; immutable int y1 = y + dy; immutable int x1 = x + dx; immutable int c1 = y1 * w + x1; @@ -241,41 +241,40 @@ State* moveMe(State* s, int dy, int dx) nothrow { if (y1 < 0 || y1 > h || x1 < 0 || x1 > w || board[c1] == Cell.wall) return null; - int at_box = 0; - for (int i = 1; i <= n_boxes; i++) { - if ((cast(cidx_t*)&s.c)[i] == c1) { - at_box = i; + int atBox = 0; + foreach (immutable i; 1 .. nBoxes + 1) + if (s.get(i) == c1) { + atBox = i; break; } - } int c2; - if (at_box) { + if (atBox) { c2 = c1 + dy * w + dx; if (board[c2] == Cell.wall || !live[c2]) return null; - for (int i = 1; i <= n_boxes; i++) - if ((cast(cidx_t*)&s.c)[i] == c2) + foreach (immutable i; 1 .. nBoxes + 1) + if (s.get(i) == c2) return null; } - State* n = newState(s); - memcpy((cast(cidx_t*)&n.c) + 1, - (cast(cidx_t*)&s.c) + 1, - cidx_t.sizeof * n_boxes); + auto n = s.newState; + n.slice(1, nBoxes + 1)[] = s.slice(1, nBoxes + 1); - cidx_t* p = (cast(cidx_t*)&n.c); - p[0] = cast(cidx_t)c1; + n.set(0, cast(CellIndex)c1); - if (at_box) - p[at_box] = cast(cidx_t)c2; + if (atBox) + n.set(atBox, cast(CellIndex)c2); - // Bubble sort - for (int i = n_boxes; --i; ) { - cidx_t t = 0; - for (int j = 1; j < i; j++) { - if (p[j] > p[j + 1]) - t = p[j], p[j] = p[j+1], p[j+1] = t; + // Bubble sort. + for (size_t i = nBoxes; --i; ) { + CellIndex t = 0; + foreach (immutable j; 1 .. i) { + if (n.get(j) > n.get(j + 1)) { + t = n.get(j); + n.set(j, n.get(j + 1)); + n.set(j + 1, t); + } } if (!t) break; @@ -284,42 +283,65 @@ State* moveMe(State* s, int dy, int dx) nothrow { return n; } -__gshared State* next_level, done; bool queueMove(State *s) nothrow { - if (!s || !addToTable(s)) + if (!s || !s.addToTable) return false; - if (success(s)) { - puts("\nSuccess!"); + if (s.success) { + "\nSuccess!".puts; done = s; return true; } - s.qnext = next_level; - next_level = s; + s.qNext = nextLevel; + nextLevel = s; return false; } -bool do_move(State* s) nothrow { - return queueMove(moveMe(s, 1, 0)) || - queueMove(moveMe(s, -1, 0)) || - queueMove(moveMe(s, 0, 1)) || - queueMove(moveMe(s, 0, -1)); + +bool doMove(State* s) nothrow { + return s.moveMe( 1, 0).queueMove || + s.moveMe(-1, 0).queueMove || + s.moveMe( 0, 1).queueMove || + s.moveMe( 0, -1).queueMove; } + +void showBoard(in State* s) nothrow { + static immutable glyphs1 = " #@$", glyphs2 = ".#@$"; + + auto ptr = cast(ubyte*)alloca(w * h * ubyte.sizeof); + if (ptr == null) + exit(5); + auto b = ptr[0 .. w * h]; + b[] = cast(typeof(b))board[]; + + b[s.get(0)] = Cell.player; + foreach (immutable i; 1 .. nBoxes + 1) + b[s.get(i)] = Cell.box; + + foreach (immutable i, immutable bi; b) { + putchar((goals[i] ? glyphs2 : glyphs1)[bi]); + if (!((1 + i) % w)) + '\n'.putchar; + } +} + + void showMoves(in State* s) nothrow { if (s.prev) - showMoves(s.prev); - printf("\n"); - showBoard(s); + s.prev.showMoves; + "\n".printf; + s.showBoard; } -int main() nothrow { - enum BIG = 0; - static if (BIG == 0) { - State* s = parseBoard(8, 7, +int main() nothrow { + enum uint problem = 0; + + static if (problem == 0) { + auto s = parseBoard(8, 7, "#######"~ "# #"~ "# #"~ @@ -329,16 +351,16 @@ int main() nothrow { "#.# @#"~ "#######"); - } else static if (BIG == 1) { - State* s = parseBoard(5, 13, + } else static if (problem == 1) { + auto s = parseBoard(5, 13, "#############"~ "# # #"~ "# $$$$$$$ @#"~ "#....... #" "#############"); - } else { - State* s = parseBoard(11, 19, + } else static if (problem == 2) { + auto s = parseBoard(11, 19, " ##### "~ " # # "~ " # # "~ @@ -350,37 +372,39 @@ int main() nothrow { "##### ### #@## .#"~ " # #########"~ " ####### "); + } else { + asset(0, "Not present problem."); } - showBoard(s); - extendTable(); - queueMove(s); + s.showBoard; + extendTable; + s.queueMove; for (int i = 0; !done; i++) { printf("depth %d\r", i); - fflush(stdout); + stdout.fflush; - State *head = next_level; - for (next_level = null; head && !done; head = head.qnext) - do_move(head); + auto head = nextLevel; + for (nextLevel = null; head && !done; head = head.qNext) + head.doMove; - if (!next_level) { - puts("No solution?"); + if (!nextLevel) { + "No solution?".puts; return 1; } } - showMoves(done); + done.showMoves; - version (none) { - free(buckets); - free(board); - free(goals); - free(live); + version (none) { // Free all allocated memory. + buckets.ptr.free; + board.ptr.free; + goals.ptr.free; + live.ptr.free; - while (block_root) { - auto tmp = block_root.next; - free(block_root); - block_root = tmp; + while (blockRoot) { + auto tmp = blockRoot.next; + blockRoot.free; + blockRoot = tmp; } } diff --git a/Task/Sokoban/OCaml/sokoban.ocaml b/Task/Sokoban/OCaml/sokoban.ocaml index da8d03d7ef..23552382eb 100644 --- a/Task/Sokoban/OCaml/sokoban.ocaml +++ b/Task/Sokoban/OCaml/sokoban.ocaml @@ -9,7 +9,7 @@ let cols = ref 0 let delta = function U -> -(!cols) | D -> !cols | L -> -1 | R -> 1 let store = Hashtbl.create 251 -let mark t = Hashtbl.add store t true +let mark t = Hashtbl.replace store t () let marked t = Hashtbl.mem store t let show ml = diff --git a/Task/Sokoban/Perl-6/sokoban.pl6 b/Task/Sokoban/Perl-6/sokoban.pl6 new file mode 100644 index 0000000000..a22108e98f --- /dev/null +++ b/Task/Sokoban/Perl-6/sokoban.pl6 @@ -0,0 +1,101 @@ +sub MAIN() { + my $level = q:to//; +####### +# # +# # +#. # # +#. $$ # +#.$$ # +#.# @# +####### + + say 'level:'; + print $level; + say 'solution:'; + say solve($level); +} + +class State { + has Str $.board; + has Str $.sol; + has Int $.pos; + + method move(Int $delta --> Str) { + my $new = $!board; + if $new.substr($!pos,1) eq '@' { + substr-rw($new,$!pos,1) = ' '; + } else { + substr-rw($new,$!pos,1) = '.'; + } + my $pos := $!pos + $delta; + if $new.substr($pos,1) eq ' ' { + substr-rw($new,$pos,1) = '@'; + } else { + substr-rw($new,$pos,1) = '+'; + } + return $new; + } + + method push(Int $delta --> Str) { + my $pos := $!pos + $delta; + my $box := $pos + $delta; + return '' unless $!board.substr($box,1) eq ' ' | '.'; + my $new = $!board; + if $new.substr($!pos,1) eq '@' { + substr-rw($new,$!pos,1) = ' '; + } else { + substr-rw($new,$!pos,1) = '.'; + } + if $new.substr($pos,1) eq '$' { + substr-rw($new,$pos,1) = '@'; + } else { + substr-rw($new,$pos,1) = '+'; + } + if $new.substr($box,1) eq ' ' { + substr-rw($new,$box,1) = '$'; + } else { + substr-rw($new,$box,1) = '*'; + } + return $new; + } +} + +sub solve(Str $start --> Str) { + my $board = $start; + my $width = $board.lines[0].chars + 1; + my @dirs = + ["u", "U", -$width], + ["r", "R", 1], + ["d", "D", $width], + ["l", "L", -1]; + + my %visited = $board => True; + + my $pos = $board.index('@'); + my @open = State.new(:$board, :sol(''), :$pos); + while @open { + my $state = @open.shift; + for @dirs -> [$move, $push, $delta] { + my $board; + my $sol; + my $pos = $state.pos + $delta; + given $state.board.substr($pos,1) { + when '$' | '*' { + $board = $state.push($delta); + next if $board eq "" || %visited{$board}; + $sol = $state.sol ~ $push; + return $sol unless $board ~~ /<[ . + ]>/; + } + when ' ' | '.' { + $board = $state.move($delta); + next if %visited{$board}; + $sol = $state.sol ~ $move; + } + default { next } + } + @open.push: State.new: :$board, :$sol, :$pos; + %visited{$board} = True; + } + } + return "No solution"; +} diff --git a/Task/Sokoban/Perl/sokoban.pl b/Task/Sokoban/Perl/sokoban.pl new file mode 100644 index 0000000000..72df2898e4 --- /dev/null +++ b/Task/Sokoban/Perl/sokoban.pl @@ -0,0 +1,204 @@ +#!perl +use strict; +use warnings qw(FATAL all); +my @initial = split /\n/, <<''; +############# +# # # +# $$$$$$$ @# +#....... # +############# + +####### +# # +# # +#. # # +#. $$ # +#.$$ # +#.# @# +####### + +=for +space is an empty square +# is a wall +@ is the player +$ is a box +. is a goal ++ is the player on a goal +* is a box on a goal +=cut + + +my $cols = length($initial[0]); +my $initial = join '', @initial; +my $size = length($initial); +die unless $size == $cols * @initial; + +sub WALL() { 1 } +sub PLAYER() { 2 } +sub BOX() { 4 } +sub GOAL() { 8 } + +my %input = ( + ' ' => 0, '#' => WALL, '@' => PLAYER, '$' => BOX, + '.' => GOAL, '+' => PLAYER|GOAL, '*' => BOX|GOAL, +); +my %output = reverse(%input); + +sub packed_initial { + my $ret = ''; + vec( $ret, $_, 4 ) = $input{substr $initial, $_, 1} + for( 0 .. $size-1 ); + $ret; +} + +sub printable_board { + my $board = shift; + my @c = @output{map vec($board, $_, 4), 0 .. $size-1}; + my $ret = ''; + while( my @row = splice @c, 0, $cols ) { + $ret .= join '', @row, "\n"; + } + $ret; +} + +my $packed = packed_initial(); + +my @udlr = qw(u d l r); +my @UDLR = qw(U D L R); +my @deltas = (-$cols, +$cols, -1, +1); + +my %fseen; +INIT_FORWARD: { + $initial =~ /(\@|\+)/ or die; + use vars qw(@ftodo @fnext); + @ftodo = (["", $packed, $-[0]]); + $fseen{$packed} = ''; +} + +my %rseen; +INIT_REVERSE: { + my $goal = $packed; + vec($goal, $ftodo[0][2], 4) -= PLAYER; + my @u = grep { my $t = vec($goal, $_, 4); $t & GOAL and not $t & BOX } 0 .. $size-1; + my @b = grep { my $t = vec($goal, $_, 4); $t & BOX and not $t & GOAL } 0 .. $size-1; + die unless @u == @b; + vec($goal, $_, 4) += BOX for @u; + vec($goal, $_, 4) -= BOX for @b; + use vars qw(@rtodo @rnext); + FINAL_PLACE: for my $player (0 .. $size-1) { + next if vec($goal, $player, 4); + FIND_GOAL: { + vec($goal, $player + $_, 4) & GOAL and last FIND_GOAL for @deltas; + next FINAL_PLACE; + } + my $a_goal = $goal; + vec($a_goal, $player, 4) += PLAYER; + push @rtodo, ["", $a_goal, $player ]; + $rseen{$a_goal} = ''; + #print printable_board($a_goal); + } +} + +my $movelen = -1; +my ($solution); +MAIN: while( @ftodo and @rtodo ) { + + FORWARD: { + my ($moves, $level, $player) = @{pop @ftodo}; + die unless vec($level, $player, 4) & PLAYER; + + for my $dir_num (0 .. 3) { + my $delta = $deltas[$dir_num]; + my @loc = map $player + $delta * $_, 0 .. 2; + my @val = map vec($level, $_, 4), @loc; + + next if $val[1] & WALL or ($val[1] & BOX and $val[2] & (BOX|WALL)); + + my $new = $level; + vec($new, $loc[0], 4) -= PLAYER; + vec($new, $loc[1], 4) += PLAYER; + my $nmoves; + if( $val[1] & BOX ) { + vec($new, $loc[1], 4) -= BOX; + vec($new, $loc[2], 4) += BOX; + $nmoves = $moves . $UDLR[$dir_num]; + } else { + $nmoves = $moves . $udlr[$dir_num]; + } + + next if exists $fseen{$new}; + $fseen{$new} = $nmoves; + + push @fnext, [ $nmoves, $new, $loc[1] ]; + + exists $rseen{$new} or next; + #print(($val[1] & BOX) ? "Push $UDLR[$dir_num]\n" : "Fwalk $udlr[$dir_num]\n"); + $solution = $new; + last MAIN; + } + + last FORWARD if @ftodo; + use vars qw(*ftodo *fnext); + (*ftodo, *fnext) = (\@fnext, \@ftodo); + } # end FORWARD + + BACKWARD: { + my ($moves, $level, $player) = @{pop @rtodo}; + die "<$level>" unless vec($level, $player, 4) & PLAYER; + + for my $dir_num (0 .. 3) { + my $delta = $deltas[$dir_num]; + # look behind and in front of the player. + my @loc = map $player + $delta * $_, -1 .. 1; + my @val = map vec($level, $_, 4), @loc; + + # unlike the forward solution, we cannot push boxes + next if $val[0] & (WALL|BOX); + my $new = $level; + vec($new, $loc[0], 4) += PLAYER; + vec($new, $loc[1], 4) -= PLAYER; + # unlike the forward solution, if we have a box behind us + # we can *either* pull it or not. This means there are + # two "successors" to this board. + if( $val[2] & BOX ) { + my $pull = $new; + vec($pull, $loc[2], 4) -= BOX; + vec($pull, $loc[1], 4) += BOX; + goto RWALK if exists $rseen{$pull}; + my $pmoves = $UDLR[$dir_num] . $moves; + $rseen{$pull} = $pmoves; + push @rnext, [$pmoves, $pull, $loc[0]]; + goto RWALK unless exists $fseen{$pull}; + print "Doing pull\n"; + $solution = $pull; + last MAIN; + } + RWALK: + next if exists $rseen{$new}; # next direction. + my $wmoves = $udlr[$dir_num] . $moves; + $rseen{$new} = $wmoves; + push @rnext, [$wmoves, $new, $loc[0]]; + next unless exists $fseen{$new}; + print "Rwalk\n"; + $solution = $new; + last MAIN; + } + + last BACKWARD if @rtodo; + use vars qw(*rtodo *rnext); + (*rtodo, *rnext) = (\@rnext, \@rtodo); + } # end BACKWARD +} + +if( $solution ) { + my $fmoves = $fseen{$solution}; + my $rmoves = $rseen{$solution}; + print "Solution found!\n"; + print "Time: ", (time() - $^T), " seconds\n"; + print "Moves: $fmoves $rmoves\n"; + print "Move Length: ", length($fmoves . $rmoves), "\n"; + print "Middle Board: \n", printable_board($solution); +} else { + print "No solution found!\n"; +} +__END__ diff --git a/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c b/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c index 95c85bf491..5b37a8108b 100644 --- a/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c +++ b/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c @@ -5,7 +5,7 @@ int *board, *flood, *known, top = 0, w, h; -inline int idx(int y, int x) { return y * w + x; } +static inline int idx(int y, int x) { return y * w + x; } int neighbors(int c, int *p) /* @@ -69,11 +69,12 @@ void make_board(int x, int y, const char *s) int i; w = x, h = y; + top = 0; x = w * h; - known = calloc(sizeof(int*), x + 1); - board = calloc(sizeof(int), x); - flood = calloc(sizeof(int), x); + known = calloc(x + 1, sizeof(int)); + board = calloc(x, sizeof(int)); + flood = calloc(x, sizeof(int)); while (x--) board[x] = -1; diff --git a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d index 0f3d22dd17..e6e6405299 100644 --- a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d +++ b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d @@ -1,28 +1,32 @@ -import std.stdio, std.array, std.conv, std.algorithm; +import std.stdio, std.array, std.conv, std.algorithm, std.string; int[][] board; int[] given, start; void setup(string s) { - auto lines = s.split("\n"); - auto cols = lines[0].split().length; + auto lines = s.splitLines; + auto cols = lines[0].split.length; auto rows = lines.length; given.length = 0; board = new int[][](rows + 2, cols + 2); - foreach (i; 0 .. rows + 2) - board[i][] = -1; + foreach (row; board) + row[] = -1; foreach (r, row; lines) { - foreach (c, cell; row.split()) { + foreach (c, cell; row.split) { switch (cell) { - case "__" : board[r + 1][c + 1] = 0; break; - case "." : break; - default : - int val = to!int(cell); + case "__": + board[r + 1][c + 1] = 0; + break; + case ".": + break; + default: + int val = cell.to!int; board[r + 1][c + 1] = val; given ~= val; - if (val == 1) start = [r + 1, c + 1]; + if (val == 1) + start = [r + 1, c + 1]; } } } @@ -30,7 +34,8 @@ void setup(string s) { } bool solve(int r, int c, int n, int next = 0) { - if (n > given[$-1]) return true; + if (n > given.back) + return true; if (board[r][c] && board[r][c] != n) return false; @@ -51,10 +56,10 @@ bool solve(int r, int c, int n, int next = 0) { } void printBoard() { - foreach (r; 0 .. board.length) { - foreach (c; board[r]) - writef(c == -1 ? " " : !c ? "__ " : "%2d ", c); - write('\n'); + foreach (row; board) { + foreach (c; row) + writef(c == -1 ? " . " : c ? "%2d " : "__ ", c); + writeln; } } @@ -68,8 +73,9 @@ void main() { . . . . __ 7 __ __ . . . . . . 5 __"; - setup(hi); - printBoard(); + hi.setup; + printBoard; + "\nFound:".writeln; solve(start[0], start[1], 1); - printBoard(); + printBoard; } 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 93451db906..0bf6486c89 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 @@ -1,53 +1,66 @@ -import std.stdio, std.string, std.conv, std.array, std.algorithm, - std.exception; +import std.stdio, std.conv, std.ascii, std.array, std.string, + std.algorithm, std.exception, std.range, std.typetuple; struct Hidato { - // alias Cell = RangedValue!(int, -2, int.max); + // alias Cell = RangedValue!(int, -1, int.max); alias Cell = int; - enum : Cell { emptyCell = -2, unknownCell = -1 } + alias Pos = size_t; + enum : Cell { emptyCell = -1, unknownCell = 0 } - alias KnownT = int[2][Cell]; - immutable KnownT known; immutable Cell boardMax; - Cell[][] board; + immutable size_t nCols, nRows; + Cell[] board; + Pos[] known; + bool[] flood; - this(in string input) pure + this(in string input) @safe pure in { - assert(!input.empty); + assert(!input.strip.empty); } out { - immutable nRows = board.length; - immutable nCols = board[0].length; - assert(boardMax > 0 && boardMax <= nRows * nCols); - assert(known.length >= 2 && known.length <= nRows * nCols); - assert(1 in known && boardMax in known); + assert(nCols > 0 && nRows > 0); + immutable size = nCols * nRows; + assert(board.length == size); + assert(known.length == size + 1); + assert(flood.length == size); + assert(boardMax > 0 && boardMax <= size); + assert(board.reduce!max == boardMax); + assert(board.canFind(1) && board.canFind(boardMax)); + assert(flood.all!(f => f == 0)); + assert(known.all!(rc => rc >= 0 && rc < size)); - foreach (const row; board) - foreach (immutable cell; row) - assert(cell == Hidato.emptyCell || - cell == Hidato.unknownCell || - (cell >= 1 && cell <= nRows * nCols)); - - foreach (/*immutable*/ n, immutable rc; known) { - assert(n > 0 && n <= boardMax); - assert(rc[0] >= 0 && rc[0] < nRows); - assert(rc[1] >= 0 && rc[1] < nCols); + foreach (immutable i, immutable cell; board) { + assert(cell == Hidato.emptyCell || + cell == Hidato.unknownCell || + (cell >= 1 && cell <= size)); + if (cell > 0) + assert(i == known[cast(size_t)cell]); } } body { bool[Cell] pathSeen; // A set. - KnownT knownMutable; - const lines = input.splitLines; - immutable nCols = lines[0].split.length; - foreach (immutable int r, immutable row; lines) { + /*immutable*/ const 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[] = emptyCell; + this.known = new typeof(this.known[0])[size + 1]; + this.flood = new typeof(this.flood[0])[size]; + + auto boardMaxMutable = Cell.min; + Pos i = 0; + + foreach (immutable row; lines) { assert(row.split.length == nCols, text("Wrong cols n.: ", row.split.length)); - auto boardRow = new typeof(board[0])(nCols); - foreach (immutable int c, immutable cell; row.split) { + + foreach (immutable cell; row.split) { switch (cell) { - case ".": - boardRow[c] = Hidato.emptyCell; - break; case "_": - boardRow[c] = Hidato.unknownCell; + this.board[i] = Hidato.unknownCell; + break; + case ".": + this.board[i] = Hidato.emptyCell; break; default: // Known. immutable val = cell.to!Cell; @@ -55,56 +68,118 @@ struct Hidato { enforce(val !in pathSeen, text("Duplicated path number: ", val)); pathSeen[val] = true; - boardRow[c] = val; - knownMutable[val] = [r, c]; - boardMax = max(boardMax, val); + this.board[i] = val; + this.known[val] = i; + boardMaxMutable = max(boardMaxMutable, val); + } + i++; + } + } + + this.boardMax = boardMaxMutable; + } + + + private Pos idx(in size_t r, in size_t c) const pure nothrow { + return r * nCols + c; + } + + private uint nNeighbors(in Pos pos, ref Pos[8] neighbours) + const pure nothrow { + immutable r = pos / nCols; + immutable c = pos % nCols; + typeof(return) n = 0; + + foreach (immutable sr; TypeTuple!(-1, 0, 1)) { + immutable size_t i = r + sr; // Can wrap-around. + if (i >= nRows) + continue; + foreach (immutable sc; TypeTuple!(-1, 0, 1)) { + immutable size_t j = c + sc; // Can wrap-around. + if ((sc != 0 || sr != 0) && j < nCols) { + immutable pos2 = idx(i, j); + neighbours[n] = pos2; + if (board[pos2] != Hidato.emptyCell) + n++; } } - board ~= boardRow; } - known = knownMutable.assumeUnique; // Not verified. + return n; } - bool solve() pure nothrow - in { - assert(1 in known); - } body { - bool fill(in int r, in int c, in Cell n) pure nothrow { - if (n > boardMax) - return true; + /// Fill all free cells around 'cell' with true and write + /// output to variable "flood". + private void floodFill(in Pos pos) pure nothrow { + Pos[8] n = void; - if (c < 0 || c >= board[0].length || - r < 0 || r >= board.length) + // For all neighbours. + foreach (immutable i; 0 .. nNeighbors(pos, n)) { + // If pos is not free, choose another neighbour. + if (board[n[i]] || flood[n[i]]) + continue; + flood[n[i]] = true; + floodFill(n[i]); + } + } + + /// Check all empty cells are reachable from higher known cells. + private bool checkConnectity(in uint lowerBound) pure nothrow { + flood[] = false; + + foreach (immutable i; lowerBound + 1 .. boardMax + 1) + if (known[i]) + floodFill(known[i]); + + foreach (immutable i; 0 .. nCols * nRows) + // If there are free cells which could not be + // reached from floodFill. + if (!board[i] && !flood[i]) return false; + return true; + } - if ((board[r][c] != Hidato.unknownCell && - board[r][c] != n) || - (n in known && known[n] != [r, c])) - return false; - - board[r][c] = n; - foreach (immutable i; -1 .. 2) - foreach (immutable j; -1 .. 2) - if (fill(r + i, c + j, n + 1)) - return true; - - board[r][c] = Hidato.unknownCell; + private bool fill(in Pos pos, in uint n) pure nothrow { + if ((board[pos] && board[pos] != n) || + (known[n] && known[n] != pos)) return false; - } - return fill(known[1][0], known[1][1], 1); + if (n == boardMax) + return true; + + immutable ko = known[n]; + immutable bo = board[pos]; + board[pos] = n; + + Pos[8] p = void; + if (checkConnectity(n)) + foreach (immutable i; 0 .. nNeighbors(pos, p)) + if (fill(p[i], n + 1)) + return true; + + board[pos] = bo; + known[n] = ko; + return false; } - string toString() const pure /*nothrow*/ { + void solve() pure nothrow + in { + assert(!known.empty); + } body { + fill(known[1], 1); + } + + string toString() const pure { immutable d = [Hidato.emptyCell: ".", Hidato.unknownCell: "_"]; immutable form = "%" ~ text(boardMax.text.length + 1) ~ "s"; string result; - foreach (const row; board) { - foreach (immutable c; row) - result ~= format(form, d.get(c, c.text)); + foreach (immutable r; 0 .. nRows) { + foreach (immutable c; 0 .. nCols) { + immutable cell = board[idx(r, c)]; + result ~= format(form, d.get(cell, cell.text)); + } result ~= "\n"; } return result; @@ -112,11 +187,10 @@ struct Hidato { } void solveHidato(in string problem) { - auto hi = problem.Hidato; - writeln("Problem:\n", hi); - hi.solve; - writeln("Solution:\n", hi); - writeln; + auto game = problem.Hidato; + writeln("Problem:\n", game); + game.solve; + writeln("Solution:\n", game); } void main() { @@ -137,5 +211,5 @@ void main() { "1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74 . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ." -); + ); } diff --git a/Task/Solve-a-Hidato-puzzle/Erlang/solve-a-hidato-puzzle.erl b/Task/Solve-a-Hidato-puzzle/Erlang/solve-a-hidato-puzzle.erl new file mode 100644 index 0000000000..69b42f3098 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Erlang/solve-a-hidato-puzzle.erl @@ -0,0 +1,104 @@ +-module( solve_hidato_puzzle ). + +-export( [create/2, solve/1, task/0] ). + +-compile({no_auto_import,[max/2]}). + +create( Grid_list, Number_list ) -> + Squares = lists:flatten( [create_column(X, Y) || {X, Y} <- Grid_list] ), + lists:foldl( fun store/2, dict:from_list(Squares), Number_list ). + +print( Grid_list ) when is_list(Grid_list) -> print( create(Grid_list, []) ); +print( Grid_dict ) -> + Max_x = max_x( Grid_dict ), + Max_y = max_y( Grid_dict ), + Print_row = fun (Y) -> [print(X, Y, Grid_dict) || X <- lists:seq(1, Max_x)], io:nl() end, + [Print_row(Y) || Y <- lists:seq(1, Max_y)]. + +solve( Dict ) -> + {find_start, [Start]} = {find_start, dict:fold( fun start/3, [], Dict )}, + Max = dict:size( Dict ), + {stop_ok, {Max, Max, [Stop]}} = {stop_ok, dict:fold( fun stop/3, {Max, 0, []}, Dict )}, + My_pid = erlang:self(), + erlang:spawn( fun() -> path(Start, Stop, Dict, My_pid, []) end ), + receive + {grid, Grid, path, Path} -> {Grid, Path} + end. + +task() -> + %% Square is {X, Y}, N}. N = 0 for empty square. These are created if not present. + %% Leftmost column is X=1. Top row is Y=1. + %% Optimised for the example, grid is a list of {X, {Y_min, Y_max}}. + %% When there are holes, X is repeated as many times as needed with two new Y values each time. + Start = {{7,5}, 1}, + Stop = {{5,4}, 40}, + Grid_list = [{1, {1,5}}, {2, {1,5}}, {3, {1,6}}, {4, {1,6}}, {5, {1,7}}, {6, {3,7}}, {7, {5,8}}, {8, {7,8}}], + Number_list = [Start, Stop, {{1,5}, 27}, {{2,1}, 33}, {{2,4}, 26}, {{3,1}, 35}, {{3,2}, 24}, + {{4,2}, 22}, {{4,3}, 21}, {{4,4}, 13}, {{5,5}, 9}, {{5,6}, 18}, {{6,4}, 11}, {{6,7}, 7}, {{7,8}, 5}], + Grid = create( Grid_list, Number_list ), + io:fwrite( "Start grid~n" ), + print( Grid ), + {New_grid, Path} = solve( create(Grid_list, Number_list) ), + io:fwrite( "Start square ~p, Stop square ~p.~nPath ~p~n", [Start, Stop, Path] ), + print( New_grid ). + + +create_column( X, {Y_min, Y_max} ) -> [{{X, Y}, 0} || Y <- lists:seq(Y_min, Y_max)]. + +is_filled( Dict ) -> [] =:= dict:fold( fun keep_0_square/3, [], Dict ). + +keep_0_square( Key, 0, Acc ) -> [Key | Acc]; +keep_0_square( _Key, _Value, Acc ) -> Acc. + +max( Position, Keys ) -> + [Square | _T] = lists:reverse( lists:keysort(Position, Keys) ), + Square. + +max_x( Dict ) -> + {X, _Y} = max( 1, dict:fetch_keys(Dict) ), + X. + +max_y( Dict ) -> + {_X, Y} = max( 2, dict:fetch_keys(Dict) ), + Y. + + +neighbourhood( Square, Dict ) -> + Potentials = neighbourhood_potential_squares( Square ), + neighbourhood_squares( dict:find(Square, Dict), Potentials, Dict ). + +neighbourhood_potential_squares( {X, Y} ) -> [{Sx, Sy} || Sx <- [X-1, X, X+1], Sy <- [Y-1, Y, Y+1], {X, Y} =/= {Sx, Sy}]. + +neighbourhood_squares( {ok, Value}, Potentials, Dict ) -> + Square_values = lists:flatten( [neighbourhood_square_value(X, dict:find(X, Dict)) || X <- Potentials] ), + Next_value = Value + 1, + neighbourhood_squares_next_value( lists:keyfind(Next_value, 2, Square_values), Square_values, Next_value ). + +neighbourhood_squares_next_value( {Square, Value}, _Square_values, Value ) -> [{Square, Value}]; +neighbourhood_squares_next_value( false, Square_values, Value ) -> [{Square, Value} || {Square, Y} <- Square_values, Y =:= 0]. + +neighbourhood_square_value( Square, {ok, Value} ) -> [{Square, Value}]; +neighbourhood_square_value( _Square, error ) -> []. + +path( Square, Square, Dict, Pid, Path ) -> path_correct( is_filled(Dict), Pid, [Square | Path], Dict ); +path( Square, Stop, Dict, Pid, Path ) -> + Reversed_path = [Square | Path], + Neighbours = neighbourhood( Square, Dict ), + [erlang:spawn( fun() -> path(Next_square, Stop, dict:store(Next_square, Value, Dict), Pid, Reversed_path) end ) || {Next_square, Value} <- Neighbours]. + +path_correct( true, Pid, Path, Dict ) -> Pid ! {grid, Dict, path, lists:reverse( Path )}; +path_correct( false, _Pid, _Path, _Dict ) -> dead_end. + +print( X, Y, Dict ) -> print_number( dict:find({X, Y}, Dict) ). + +print_number( {ok, 0} ) -> io:fwrite( "~3s", ["."] ); % . is less distracting than 0 +print_number( {ok, Value} ) -> io:fwrite( "~3b", [Value] ); +print_number( error ) -> io:fwrite( "~3s", [" "] ). + +start( Key, 1, Acc ) -> [Key | Acc]; % Allow check that we only have one key with value 1. +start( _Key, _Value, Acc ) -> Acc. + +stop( Key, Max, {Max, Max_found, Stops} ) -> {Max, erlang:max(Max, Max_found), [Key | Stops]}; % Allow check that we only have one key with value Max. +stop( _Key, Value, {Max, Max_found, Stops} ) -> {Max, erlang:max(Value, Max_found), Stops}. % Allow check that Max is Max. + +store( {Key, Value}, Dict ) -> dict:store( Key, Value, Dict ). diff --git a/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs b/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs new file mode 100644 index 0000000000..be5857acbd --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs @@ -0,0 +1,66 @@ +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE Rank2Types #-} +import qualified Data.IntMap as I +import Data.IntMap (IntMap) +import Data.List +import Data.Maybe +import Data.Time.Clock + +data BoardProblem = Board { cells :: IntMap (IntMap Int) + , endVal :: Int + , onePos :: (Int,Int) + , givens :: [Int] } deriving (Show,Eq) + +tupIns x y v m = I.insert x (I.insert y v (I.findWithDefault I.empty x m)) m +tupLookup x y m = I.lookup x m >>= I.lookup y + +makeBoard = (\x -> x{givens = dropWhile (<=1) $ sort $ givens x}) + . foldl' f (Board I.empty 0 (0,0) []) . concatMap (zip [0..]) + . zipWith (\y w -> map (y,) $ words w) [0..] + where f bd (x,(y,v)) = if v=="." then bd else + Board (tupIns x y (read v) (cells bd)) + (if read v > endVal bd then read v else endVal bd) + (if v=="1" then (x,y) else onePos bd) + (read v:givens bd) + +hidato brd = listToMaybe $ h 2 (cells brd) (onePos brd) (givens brd) where + h nval pmap (x,y) gs | nval == endVal brd = [pmap] + | nval == head gs = if null nvalAdj then [] + else h (nval+1) pmap (fst $ head nvalAdj) (tail gs) + | not $ null nvalAdj = h (nval+1) pmap + (fst $ head nvalAdj) gs + | otherwise = hEmptyAdj + where around = [(x-1,y-1),(x,y-1),(x+1,y-1), (x-1,y),(x+1,y) + ,(x-1,y+1),(x,y+1),(x+1,y+1)] + lkdUp = map (\(x,y) -> ((x,y),tupLookup x y pmap)) around + nvalAdj = filter ((==Just nval) . snd) lkdUp + hEmptyAdj = concatMap (\((nx,ny),_) -> h (nval+1) + (tupIns nx ny nval pmap) (nx,ny) gs) + $ filter ((==Just 0) . snd) lkdUp + +printCellMap cellmap = putStrLn $ concat strings + where maxPos = xyBy I.findMax maximum + minPos = xyBy I.findMin minimum + xyBy :: (forall a. IntMap a -> (Int,a)) -> ([Int] -> Int) -> (Int, Int) + xyBy a b = (fst (a cellmap) + , b $ map (fst . a . snd) $ I.toList cellmap) + strings = map f [(x,y) | y<-[snd minPos..snd maxPos] + , x<-[fst minPos..fst maxPos]] + f (x,y) = let z = if x == fst maxPos then "\n" else " " in + case tupLookup x y cellmap of + Nothing -> " " ++ z + Just n -> (if n<10 then ' ':show n else show n) ++ z + +main = do + let sampleBoard = makeBoard sample + printCellMap $ cells sampleBoard + printCellMap $ fromJust $ hidato sampleBoard + +sample = [" 0 33 35 0 0" + ," 0 0 24 22 0" + ," 0 0 0 21 0 0" + ," 0 26 0 13 40 11" + ,"27 0 0 0 9 0 1" + ,". . 0 0 18 0 0" + ,". . . . 0 7 0 0" + ,". . . . . . 5 0"] diff --git a/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-2.hs b/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-2.hs new file mode 100644 index 0000000000..b29be440cd --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-2.hs @@ -0,0 +1,105 @@ +global nCells, cMap, best +record Pos(r,c) + +procedure main(A) + puzzle := showPuzzle("Input",readPuzzle()) + QMouse(puzzle,findStart(puzzle),&null,0) + showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") +end + +procedure readPuzzle() + # Start with a reduced puzzle space + p := [[-1]] + nCells := maxCols := 0 + every line := !&input do { + put(p,[: -1 | gencells(line) | -1 :]) + maxCols <:= *p[-1] + } + put(p, [-1]) + # Now normalize all rows to the same length + every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] + return p +end + +procedure gencells(s) + static WS, NWS + initial { + NWS := ~(WS := " \t") + cMap := table() # Map to/from internal model + cMap["#"] := -1; cMap["_"] := 0 + cMap[-1] := " "; cMap[0] := "_" + } + + s ? while not pos(0) do { + w := (tab(many(WS))|"", tab(many(NWS))) | break + w := numeric(\cMap[w]|w) + if -1 ~= w then nCells +:= 1 + suspend w + } +end + +procedure showPuzzle(label, p) + write(label," with ",nCells," cells:") + every r := !p do { + every c := !r do writes(right((\cMap[c]|c),*nCells+1)) + write() + } + return p +end + +procedure findStart(p) + if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) +end + +procedure solvePuzzle(puzzle) + if path := \best then { + repeat { + loc := path.getLoc() + puzzle[loc.r][loc.c] := path.getVal() + path := \path.getParent() | break + } + return puzzle + } +end + +class QMouse(puzzle, loc, parent, val) + method getVal(); return val; end + method getLoc(); return loc; end + method getParent(); return parent; end + method atEnd(); return (nCells = val) = puzzle[loc.r][loc.c]; end + method goNorth(); return visit(loc.r-1,loc.c); end + method goNE(); return visit(loc.r-1,loc.c+1); end + method goEast(); return visit(loc.r, loc.c+1); end + method goSE(); return visit(loc.r+1,loc.c+1); end + method goSouth(); return visit(loc.r+1,loc.c); end + method goSW(); return visit(loc.r+1,loc.c-1); end + method goWest(); return visit(loc.r, loc.c-1); end + method goNW(); return visit(loc.r-1,loc.c-1); end + + method visit(r,c) + if /best & validPos(r,c) then return Pos(r,c) + end + + method validPos(r,c) + xv := puzzle[r][c] + if xv = (val+1) then return + if xv = 0 then { # make sure this path hasn't already gone there + ancestor := self + while xl := (ancestor := \ancestor.getParent()).getLoc() do + if (xl.r = r) & (xl.c = c) then fail + return + } + end + +initially + val +:= 1 + if atEnd() then return best := self + QMouse(puzzle, goNorth(), self, val) + QMouse(puzzle, goNE(), self, val) + QMouse(puzzle, goEast(), self, val) + QMouse(puzzle, goSE(), self, val) + QMouse(puzzle, goSouth(), self, val) + QMouse(puzzle, goSW(), self, val) + QMouse(puzzle, goWest(), self, val) + QMouse(puzzle, goNW(), self, val) +end diff --git a/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx b/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx new file mode 100644 index 0000000000..b3617e4710 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx @@ -0,0 +1,55 @@ +/*REXX pgm solves a Hidato or Numbrix puzzle, displays puzzle & solution*/ +maxr=0; maxc=0; maxx=0; minr=9e9; minc=9e9; minx=9e9; cells=0; @.= +parse arg xxx; PZ='Hidato puzzle' /*get cell definitions from C.L. */ + do while xxx\=''; parse var xxx r c marks ',' xxx + do while marks\=''; _=@.r.c + parse var marks x marks + if datatype(x,'N') then do; x=x/1 /*normalize X*/ + if x<0 then PZ='Numbrix puzzle' + x=abs(x) /*use │x│ */ + end + minr=min(minr,r); maxr=max(maxr,r) + minc=min(minc,c); maxc=max(maxc,c) + if x==1 then do; !r=r; !c=c; end /*start cell.*/ + if _\=='' then call err "cell at" r c 'is already occupied with:' _ + @.r.c=x; c=c+1; cells=cells+1 /*assign mark*/ + if x==. then iterate /*hole? Skip.*/ + if \datatype(x,'W') then call err 'illegal marker specified:' x + minx=min(minx,x); maxx=max(maxx,x) /*min & max X*/ + end /*while marks¬='' */ + end /*while xxx ¬='' */ +call showGrid /* [↓] used for making fast moves*/ +Nr = '0 1 0 -1 -1 1 1 -1' /*possible row for the next move.*/ +Nc = '1 0 -1 0 1 -1 1 -1' /* " col " " " " */ +pMoves=words(Nr) -4*(left(PZ,1)=='N') /*is this to be a Numbrix puzzle?*/ + do i=1 for pMoves; Nr.i=word(Nr,i); Nc.i=word(Nc,i); end /*fast moves*/ +if \next(2,!r,!c) then call err 'No solution possible.' +say; say 'A solution for the' PZ "exists."; say; call showGrid +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ERR subroutine──────────────────────*/ +err: say; say '***error!*** (from' PZ"): " arg(1); say; exit 13 +/*──────────────────────────────────NEXT subroutine─────────────────────*/ +next: procedure expose @. Nr. Nc. cells pMoves; parse arg #,r,c; ##=#+1 + do t=1 for pMoves /* [↓] try some moves.*/ + parse value r+Nr.t c+Nc.t with nr nc /*next move coördinates*/ + if @.nr.nc==. then do; @.nr.nc=# /*a move.*/ + if #==cells then leave /*last 1?*/ + if next(##,nr,nc) then return 1 + @.nr.nc=. /*undo the above move. */ + iterate /*go & try another move*/ + end + if @.nr.nc==# then do /*is this a fill-in ? */ + if #==cells then return 1 /*last 1.*/ + if next(##,nr,nc) then return 1 /*fill-in*/ + end + end /*t*/ +return 0 /*This ain't working. */ +/*──────────────────────────────────SHOWGRID subroutine─────────────────*/ +showGrid: if maxr<1 | maxc<1 then call err 'no legal cell was specified.' +if minx<1 then call err 'no 1 was specified for the puzzle start' +if maxx\==cells then call err 'no' cells "was specified for the puzzle end" +w=length(maxx); do r=maxr to minr by -1; _= + do c=minc to maxc; _=_ right(@.r.c,w); end /*c*/ + say _ + end /*r*/ +return 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 b4de67b362..6010baeaa0 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,29 +3,27 @@ # 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 - $zbl[value] = false unless value == nil + $zbl[value] = true unless value.nil? @value = value end - def try(value) - return false if @value == nil - return true if value > E + def try(value=1) + return false if @value.nil? + return true if value > $end return false if @t return false if @value > 0 and @value != value - return false if @value == 0 and not $zbl[value] + return false if @value == 0 and $zbl[value] @t = true - @adj.each{|x| - if (Board[x[0]][x[1]].try(value+1)) then + @adj.each do |x,y| + if $board[x][y].try(value+1) @value = value return true end - } + end @t = false - return false - end - def value - return @value end + attr_reader :value 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 0202b1d46a..3a622b83f2 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,15 @@ -Rows = 3 -Cols = 3 -E = 7 -$zbl = Array.new(E+1,true) -Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new(1,2,4) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(2,1,0) ,Cell.new(2,2,7) ,Cell.new(2,3,0) ,Cell.new()], - [Cell.new(),Cell.new(3,1,1) ,Cell.new(3,2,0) ,Cell.new(3,3,0) ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] - require 'benchmark' -puts Benchmark.measure {Board[3][1].try(1)} -(1..Rows).each{|r| - (1..Cols).each{|c| printf("%2s",Board[r][c].value)} - puts ""} + +def print_out(rows, cols, msg=nil) + puts msg if msg + (1..rows).each do |r| + puts (1..cols).map{|c| "%3s" % $board[r][c].value}.join + end + puts +end + +def test(rows, cols, x, y) + print_out(rows, cols, 'Problem:') + puts Benchmark.measure {$board[x][y].try} + print_out(rows, cols, 'Solution:') +end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb index 0448776b18..ac2724a03e 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb @@ -1,19 +1,11 @@ -Rows = 8 -Cols = 8 -E = 40 -$zbl = Array.new(E+1,true) -Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(1,1,0) ,Cell.new(1,2,33) ,Cell.new(1,3,35) ,Cell.new(1,4,0) ,Cell.new(1,5,0) ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(2,1,0) ,Cell.new(2,2,0) ,Cell.new(2,3,24) ,Cell.new(2,4,22) ,Cell.new(2,5,0) ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(3,1,0) ,Cell.new(3,2,0) ,Cell.new(3,3,0) ,Cell.new(3,4,21) ,Cell.new(3,5,0) ,Cell.new(3,6,0) ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(4,1,0) ,Cell.new(4,2,26) ,Cell.new(4,3,0) ,Cell.new(4,4,13) ,Cell.new(4,5,40) ,Cell.new(4,6,11) ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(5,1,27) ,Cell.new(5,2,0) ,Cell.new(5,3,0) ,Cell.new(5,4,0) ,Cell.new(5,5,9) ,Cell.new(5,6,0) ,Cell.new(5,7,1) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new(6,3,0) ,Cell.new(6,4,0) ,Cell.new(6,5,18) ,Cell.new(6,6,0) ,Cell.new(6,7,0) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(7,5,0) ,Cell.new(7,6,7) ,Cell.new(7,7,0) ,Cell.new(7,8,0) ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(8,7,5) ,Cell.new(8,8,0) ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] -require 'benchmark' -puts Benchmark.measure {Board[5][7].try(1)} -(1..Rows).each{|r| - (1..Cols).each{|c| printf("%3s",Board[r][c].value)} - puts ""} +rows = 3 +cols = 3 +$end = 7 +$zbl = Array.new($end+1,false) +$board = [[Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], + [Cell[] ,Cell[] ,Cell[1,2,4] ,Cell[] ,Cell[]], + [Cell[] ,Cell[2,1,0] ,Cell[2,2,7] ,Cell[2,3,0] ,Cell[]], + [Cell[] ,Cell[3,1,1] ,Cell[3,2,0] ,Cell[3,3,0] ,Cell[]], + [Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]]] + +test(rows, cols, 3, 1) diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb index 1cedae6782..21928b6013 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb @@ -1,14 +1,16 @@ -Rows = 3 -Cols = 50 -E = 74 -$zbl = Array.new(E+1,true) -Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(1,1,1) ,Cell.new(1,2,0) ,Cell.new(1,3,0) ,Cell.new() ,Cell.new() ,Cell.new(1,6,0) ,Cell.new(1,7,0) ,Cell.new() ,Cell.new() ,Cell.new(1,10,0) ,Cell.new(1,11,0) ,Cell.new() ,Cell.new() ,Cell.new(1,14,0) ,Cell.new(1,15,0) ,Cell.new() ,Cell.new() ,Cell.new(1,18,0) ,Cell.new(1,19,0) ,Cell.new() ,Cell.new() ,Cell.new(1,22,0) ,Cell.new(1,23,0) ,Cell.new() ,Cell.new() ,Cell.new(1,26,0) ,Cell.new(1,27,0) ,Cell.new() ,Cell.new() ,Cell.new(1,30,0) ,Cell.new(1,31,0) ,Cell.new() ,Cell.new() ,Cell.new(1,34,0) ,Cell.new(1,35,0) ,Cell.new() ,Cell.new() ,Cell.new(1,38,0) ,Cell.new(1,39,0) ,Cell.new() ,Cell.new() ,Cell.new(1,42,0) ,Cell.new(1,43,0) ,Cell.new() ,Cell.new() ,Cell.new(1,46,0) ,Cell.new(1,47,0) ,Cell.new() ,Cell.new() ,Cell.new(1,50,74),Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new(2,3,0) ,Cell.new() ,Cell.new(2,5,0) ,Cell.new() ,Cell.new(2,7,0) ,Cell.new() ,Cell.new(2,9,0) ,Cell.new() ,Cell.new(2,11,0) ,Cell.new() ,Cell.new(2,13,0) ,Cell.new() ,Cell.new(2,15,0) ,Cell.new() ,Cell.new(2,17,0) ,Cell.new() ,Cell.new(2,19,0) ,Cell.new() ,Cell.new(2,21,0) ,Cell.new() ,Cell.new(2,23,0) ,Cell.new() ,Cell.new(2,25,0) ,Cell.new() ,Cell.new(2,27,0) ,Cell.new() ,Cell.new(2,29,0) ,Cell.new() ,Cell.new(2,31,0) ,Cell.new() ,Cell.new(2,33,0) ,Cell.new() ,Cell.new(2,35,0) ,Cell.new() ,Cell.new(2,37,0) ,Cell.new() ,Cell.new(2,39,0) ,Cell.new() ,Cell.new(2,41,0) ,Cell.new() ,Cell.new(2,43,0) ,Cell.new() ,Cell.new(2,45,0) ,Cell.new() ,Cell.new(2,47,0) ,Cell.new() ,Cell.new(2,49,0) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(3,4,0) ,Cell.new(3,5,0) ,Cell.new() ,Cell.new() ,Cell.new(3,8,0) ,Cell.new(3,9,0) ,Cell.new() ,Cell.new() ,Cell.new(3,12,0) ,Cell.new(3,13,0) ,Cell.new() ,Cell.new() ,Cell.new(3,16,0) ,Cell.new(3,17,0) ,Cell.new() ,Cell.new() ,Cell.new(3,20,0) ,Cell.new(3,21,0) ,Cell.new() ,Cell.new() ,Cell.new(3,24,0) ,Cell.new(3,25,0) ,Cell.new() ,Cell.new() ,Cell.new(3,28,0) ,Cell.new(3,29,0) ,Cell.new() ,Cell.new() ,Cell.new(3,32,0) ,Cell.new(3,33,0) ,Cell.new() ,Cell.new() ,Cell.new(3,36,0) ,Cell.new(3,37,0) ,Cell.new() ,Cell.new() ,Cell.new(3,40,0) ,Cell.new(3,41,0) ,Cell.new() ,Cell.new() ,Cell.new(3,44,0) ,Cell.new(3,45,0) ,Cell.new() ,Cell.new() ,Cell.new(3,48,0) ,Cell.new(3,49,0) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] -require 'benchmark' -puts Benchmark.measure {Board[1][1].try(1)} -(1..Rows).each{|r| - (1..Cols).each{|c| printf("%3s",Board[r][c].value)} - puts ""} +rows = 8 +cols = 8 +$end = 40 +$zbl = Array.new($end+1,false) +$board = [[Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], + [Cell[], Cell[1,1,0] ,Cell[1,2,33] ,Cell[1,3,35] ,Cell[1,4,0] ,Cell[1,5,0] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], + [Cell[], Cell[2,1,0] ,Cell[2,2,0] ,Cell[2,3,24] ,Cell[2,4,22] ,Cell[2,5,0] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], + [Cell[], Cell[3,1,0] ,Cell[3,2,0] ,Cell[3,3,0] ,Cell[3,4,21] ,Cell[3,5,0] ,Cell[3,6,0] ,Cell[] ,Cell[] ,Cell[]], + [Cell[], Cell[4,1,0] ,Cell[4,2,26] ,Cell[4,3,0] ,Cell[4,4,13] ,Cell[4,5,40] ,Cell[4,6,11] ,Cell[] ,Cell[] ,Cell[]], + [Cell[], Cell[5,1,27] ,Cell[5,2,0] ,Cell[5,3,0] ,Cell[5,4,0] ,Cell[5,5,9] ,Cell[5,6,0] ,Cell[5,7,1] ,Cell[] ,Cell[]], + [Cell[], Cell[] ,Cell[] ,Cell[6,3,0] ,Cell[6,4,0] ,Cell[6,5,18] ,Cell[6,6,0] ,Cell[6,7,0] ,Cell[] ,Cell[]], + [Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[7,5,0] ,Cell[7,6,7] ,Cell[7,7,0] ,Cell[7,8,0] ,Cell[]], + [Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[8,7,5] ,Cell[8,8,0] ,Cell[]], + [Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]]] + +test(rows, cols, 5, 7) diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb index 824bd28ca9..8f45988efa 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb @@ -1,9 +1,11 @@ -Rows = 3 -Cols = 50 -E = 74 -$zbl = Array.new(E+1,true) -Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new(1,1,1) ,Cell.new(1,2,0) ,Cell.new(1,3,0) ,Cell.new() ,Cell.new() ,Cell.new(1,6,0) ,Cell.new(1,7,0) ,Cell.new() ,Cell.new() ,Cell.new(1,10,0) ,Cell.new(1,11,0) ,Cell.new() ,Cell.new() ,Cell.new(1,14,0) ,Cell.new(1,15,0) ,Cell.new() ,Cell.new() ,Cell.new(1,18,0) ,Cell.new(1,19,0) ,Cell.new() ,Cell.new() ,Cell.new(1,22,0) ,Cell.new(1,23,0) ,Cell.new() ,Cell.new() ,Cell.new(1,26,0) ,Cell.new(1,27,0) ,Cell.new() ,Cell.new() ,Cell.new(1,30,0) ,Cell.new(1,31,0) ,Cell.new() ,Cell.new() ,Cell.new(1,34,0) ,Cell.new(1,35,0) ,Cell.new() ,Cell.new() ,Cell.new(1,38,0) ,Cell.new(1,39,0) ,Cell.new() ,Cell.new() ,Cell.new(1,42,0) ,Cell.new(1,43,0) ,Cell.new() ,Cell.new() ,Cell.new(1,46,0) ,Cell.new(1,47,0) ,Cell.new() ,Cell.new() ,Cell.new(1,50,74),Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new(2,3,0) ,Cell.new() ,Cell.new(2,5,0) ,Cell.new() ,Cell.new(2,7,0) ,Cell.new() ,Cell.new(2,9,0) ,Cell.new() ,Cell.new(2,11,0) ,Cell.new() ,Cell.new(2,13,0) ,Cell.new() ,Cell.new(2,15,0) ,Cell.new() ,Cell.new(2,17,0) ,Cell.new() ,Cell.new(2,19,0) ,Cell.new() ,Cell.new(2,21,0) ,Cell.new() ,Cell.new(2,23,0) ,Cell.new() ,Cell.new(2,25,0) ,Cell.new() ,Cell.new(2,27,0) ,Cell.new() ,Cell.new(2,29,0) ,Cell.new() ,Cell.new(2,31,0) ,Cell.new() ,Cell.new(2,33,0) ,Cell.new() ,Cell.new(2,35,0) ,Cell.new() ,Cell.new(2,37,0) ,Cell.new() ,Cell.new(2,39,0) ,Cell.new() ,Cell.new(2,41,0) ,Cell.new() ,Cell.new(2,43,0) ,Cell.new() ,Cell.new(2,45,0) ,Cell.new() ,Cell.new(2,47,0) ,Cell.new() ,Cell.new(2,49,0) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(3,4,0) ,Cell.new(3,5,0) ,Cell.new() ,Cell.new() ,Cell.new(3,8,11) ,Cell.new(3,9,0) ,Cell.new() ,Cell.new() ,Cell.new(3,12,0) ,Cell.new(3,13,0) ,Cell.new() ,Cell.new() ,Cell.new(3,16,23) ,Cell.new(3,17,0) ,Cell.new() ,Cell.new() ,Cell.new(3,20,0) ,Cell.new(3,21,0) ,Cell.new() ,Cell.new() ,Cell.new(3,24,35) ,Cell.new(3,25,0) ,Cell.new() ,Cell.new() ,Cell.new(3,28,0) ,Cell.new(3,29,0) ,Cell.new() ,Cell.new() ,Cell.new(3,32,47) ,Cell.new(3,33,0) ,Cell.new() ,Cell.new() ,Cell.new(3,36,0) ,Cell.new(3,37,0) ,Cell.new() ,Cell.new() ,Cell.new(3,40,0) ,Cell.new(3,41,0) ,Cell.new() ,Cell.new() ,Cell.new(3,44,65) ,Cell.new(3,45,0) ,Cell.new() ,Cell.new() ,Cell.new(3,48,0) ,Cell.new(3,49,0) ,Cell.new() ,Cell.new()], - [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] +rows = 3 +cols = 50 +$end = 74 +$zbl = Array.new($end+1,false) +$board = [[Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], + [Cell[] ,Cell[1,1,1] ,Cell[1,2,0] ,Cell[1,3,0] ,Cell[] ,Cell[] ,Cell[1,6,0] ,Cell[1,7,0] ,Cell[] ,Cell[] ,Cell[1,10,0] ,Cell[1,11,0] ,Cell[] ,Cell[] ,Cell[1,14,0] ,Cell[1,15,0] ,Cell[] ,Cell[] ,Cell[1,18,0] ,Cell[1,19,0] ,Cell[] ,Cell[] ,Cell[1,22,0] ,Cell[1,23,0] ,Cell[] ,Cell[] ,Cell[1,26,0] ,Cell[1,27,0] ,Cell[] ,Cell[] ,Cell[1,30,0] ,Cell[1,31,0] ,Cell[] ,Cell[] ,Cell[1,34,0] ,Cell[1,35,0] ,Cell[] ,Cell[] ,Cell[1,38,0] ,Cell[1,39,0] ,Cell[] ,Cell[] ,Cell[1,42,0] ,Cell[1,43,0] ,Cell[] ,Cell[] ,Cell[1,46,0] ,Cell[1,47,0] ,Cell[] ,Cell[] ,Cell[1,50,74] ,Cell[]], + [Cell[] ,Cell[] ,Cell[] ,Cell[2,3,0] ,Cell[] ,Cell[2,5,0] ,Cell[] ,Cell[2,7,0] ,Cell[] ,Cell[2,9,0] ,Cell[] ,Cell[2,11,0] ,Cell[] ,Cell[2,13,0] ,Cell[] ,Cell[2,15,0] ,Cell[] ,Cell[2,17,0] ,Cell[] ,Cell[2,19,0] ,Cell[] ,Cell[2,21,0] ,Cell[] ,Cell[2,23,0] ,Cell[] ,Cell[2,25,0] ,Cell[] ,Cell[2,27,0] ,Cell[] ,Cell[2,29,0] ,Cell[] ,Cell[2,31,0] ,Cell[] ,Cell[2,33,0] ,Cell[] ,Cell[2,35,0] ,Cell[] ,Cell[2,37,0] ,Cell[] ,Cell[2,39,0] ,Cell[] ,Cell[2,41,0] ,Cell[] ,Cell[2,43,0] ,Cell[] ,Cell[2,45,0] ,Cell[] ,Cell[2,47,0] ,Cell[] ,Cell[2,49,0] ,Cell[] ,Cell[]], + [Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[3,4,0] ,Cell[3,5,0] ,Cell[] ,Cell[] ,Cell[3,8,0] ,Cell[3,9,0] ,Cell[] ,Cell[] ,Cell[3,12,0] ,Cell[3,13,0] ,Cell[] ,Cell[] ,Cell[3,16,0] ,Cell[3,17,0] ,Cell[] ,Cell[] ,Cell[3,20,0] ,Cell[3,21,0] ,Cell[] ,Cell[] ,Cell[3,24,0] ,Cell[3,25,0] ,Cell[] ,Cell[] ,Cell[3,28,0] ,Cell[3,29,0] ,Cell[] ,Cell[] ,Cell[3,32,0] ,Cell[3,33,0] ,Cell[] ,Cell[] ,Cell[3,36,0] ,Cell[3,37,0] ,Cell[] ,Cell[] ,Cell[3,40,0] ,Cell[3,41,0] ,Cell[] ,Cell[] ,Cell[3,44,0] ,Cell[3,45,0] ,Cell[] ,Cell[] ,Cell[3,48,0] ,Cell[3,49,0] ,Cell[] ,Cell[]], + [Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]]] + +test(rows, cols, 1, 1) diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb index 27e7c8472d..0664c6ec52 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb @@ -3,46 +3,38 @@ # Nigel_Galloway # May 6th., 2012. class Cell + def self.[](*args) self.new(*args) end def initialize(row=0, col=0, value=nil) @adj = [[row-1,col-1],[row,col-1],[row+1,col-1],[row-1,col],[row+1,col],[row-1,col+1],[row,col+1],[row+1,col+1]] @t = false - $zbl[value] = false unless value == nil + $zbl[value] = true unless value.nil? @value = value end - def try(value) - return false if @value == nil - return true if value > E + def try(value=1) + return false if @value.nil? + return true if value > $end return false if @t return false if @value > 0 and @value != value - return false if @value == 0 and not $zbl[value] + return false if @value == 0 and $zbl[value] @t = true h = Hash.new - n = 0 - @adj.each{|x| - h[Board[x[0]][x[1]].wdof*10+n] = Board[x[0]][x[1]] - n += 1 - } - h.sort.each{|key,cell| - if (cell.try(value+1)) then + @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 - return false end def wdon - return 0 if @value == nil - return 0 if @value > 0 - return 0 if @t - return 1 + (@value.nil? or @value > 0 or @t) ? 0 : 1 end def wdof - res = 0 - @adj.each{|x| res += Board[x[0]][x[1]].wdon} - return res - end - def value - return @value + @adj.inject(0){|res, (x,y)| res += $board[x][y].wdon} end + attr_reader :value end diff --git a/Task/Sort-an-integer-array/AWK/sort-an-integer-array.awk b/Task/Sort-an-integer-array/AWK/sort-an-integer-array.awk new file mode 100644 index 0000000000..5712aefedf --- /dev/null +++ b/Task/Sort-an-integer-array/AWK/sort-an-integer-array.awk @@ -0,0 +1,15 @@ +# syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK +BEGIN { + split("9,10,3,1234,99,1,200,2,0,-2",arr,",") + show("@unsorted","unsorted") + show("@val_num_asc","sorted ascending") + show("@val_num_desc","sorted descending") + exit(0) +} +function show(sequence,description, i) { + PROCINFO["sorted_in"] = sequence + for (i in arr) { + printf("%s ",arr[i]) + } + printf("\t%s\n",description) +} diff --git a/Task/Sort-an-integer-array/Deja-Vu/sort-an-integer-array.djv b/Task/Sort-an-integer-array/Deja-Vu/sort-an-integer-array.djv new file mode 100644 index 0000000000..a67e76628f --- /dev/null +++ b/Task/Sort-an-integer-array/Deja-Vu/sort-an-integer-array.djv @@ -0,0 +1 @@ +!. sort [ 5 4 3 2 1 ] diff --git a/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia b/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia index af1e251c8b..2d6401ca01 100644 --- a/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia +++ b/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia @@ -4,8 +4,7 @@ julia> a = [4,2,3,1] 2 3 1 -julia>#non-mutating sort -sort(a) +julia> sort(a) #out-of-place/non-mutating sort 4-element Int32 Array: 1 2 @@ -19,8 +18,7 @@ julia> a 3 1 -julia>#mutating sort - sort!(a) +julia> sort!(a) # in-place/mutating sort 4-element Int32 Array: 1 2 diff --git a/Task/Sort-using-a-custom-comparator/AWK/sort-using-a-custom-comparator.awk b/Task/Sort-using-a-custom-comparator/AWK/sort-using-a-custom-comparator.awk new file mode 100644 index 0000000000..b390a462b8 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/AWK/sort-using-a-custom-comparator.awk @@ -0,0 +1,27 @@ +# syntax: GAWK -f SORT_USING_A_CUSTOM_COMPARATOR.AWK +# +# sorting: +# PROCINFO["sorted_in"] is used by GAWK +# SORTTYPE is used by Thompson Automation's TAWK +# +BEGIN { + words = "This Is A Set Of Strings To Sort duplicated" + n = split(words " " tolower(words),tmp_arr," ") + print("unsorted:") + for (i=1; i<=n; i++) { + word = tmp_arr[i] + arr[length(word)][word]++ + print(word) + } + print("\nsorted:") + PROCINFO["sorted_in"] = "@ind_num_desc" ; SORTTYPE = 9 + for (i in arr) { + PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 2 + for (j in arr[i]) { + for (k=1; k<=arr[i][j]; k++) { + print(j) + } + } + } + exit(0) +} diff --git a/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb b/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb index b50dd015a4..dcaf4c5fe0 100644 --- a/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb +++ b/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb @@ -1,19 +1,16 @@ class Array - def beadsort - self.map {|e| [1] * e}.columns.columns.map {|e| e.length} - end + def beadsort + map {|e| [1] * e}.columns.columns.map {|e| e.length} + end - def columns - y = self.length - x = self.map {|l| l.length}.max - - Array.new(x) do |row| - Array.new(y) { |column| - self[column][row] - }.compact # Remove nulls. - end - end + def columns + y = length + x = map {|l| l.length}.max + Array.new(x) do |row| + Array.new(y) { |column| self[column][row] }.compact # Remove nils. + end + end end # Demonstration code: -[5,3,1,7,4,1,1].beadsort +p [5,3,1,7,4,1,1].beadsort diff --git a/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort.awk b/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort-1.awk similarity index 100% rename from Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort.awk rename to Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort-1.awk diff --git a/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort-2.awk b/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort-2.awk new file mode 100644 index 0000000000..ad27b9c39d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort-2.awk @@ -0,0 +1,45 @@ +# Test this example file from command line with: +# +# awk -f file.awk /dev/null +# +# Code by Jari Aalto +# Licensed and released under GPL-2+, see http://spdx.org/licenses + +function alen(array, dummy, len) { + for (dummy in array) + len++; + + return len; +} + +function sort(array, haschanged, len, tmp, i) +{ + len = alen(array) + haschanged = 1 + + while ( haschanged == 1 ) + { + haschanged = 0 + + for (i = 1; i <= len - 1; i++) + { + if (array[i] > array[i+1]) + { + tmp = array[i] + array[i] = array[i + 1] + array[i + 1] = tmp + haschanged = 1 + } + } + } +} + +# An Example. Sorts array to order: b, c, z +{ + array[1] = "c" + array[2] = "z" + array[3] = "b" + sort(array) + print array[1] " " array[2] " " array[3] + exit +} diff --git a/Task/Sorting-algorithms-Bubble-sort/TorqueScript/sorting-algorithms-bubble-sort.torque b/Task/Sorting-algorithms-Bubble-sort/TorqueScript/sorting-algorithms-bubble-sort.torque new file mode 100644 index 0000000000..b3be7f1732 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/TorqueScript/sorting-algorithms-bubble-sort.torque @@ -0,0 +1,18 @@ +//Note that we're assuming that the list of numbers is separated by tabs. +function bubbleSort(%list) +{ + %ct = getFieldCount(%list); + for(%i = 0; %i < %ct; %i++) + { + for(%k = 0; %k < (%ct - %i - 1); %k++) + { + if(getField(%list, %k) > getField(%list, %k+1)) + { + %tmp = getField(%list, %k); + %list = setField(%list, %k, getField(%list, %k+1)); + %list = setField(%list, %k+1, %tmp); + } + } + } + return %list; +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort.rb b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-1.rb similarity index 80% rename from Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort.rb rename to Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-1.rb index 147e1049e7..01c0832c39 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort.rb +++ b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-1.rb @@ -8,7 +8,7 @@ class Array swapped = true end end - break if not swapped + break unless swapped swapped = false (length - 2).downto(0) do |i| @@ -21,6 +21,3 @@ class Array self end end -ary = [7,6,5,9,8,4,3,1,2,0] -ary.cocktailsort! -# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-2.rb b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-2.rb new file mode 100644 index 0000000000..0ddc928521 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-2.rb @@ -0,0 +1,17 @@ +class Array + def cocktailsort! + start, finish, way = 0, size-1, 1 + loop do + swapped = false + start.step(finish-way, way) do |i| + if (self[i] <=> self[i + way]) == way + self[i], self[i + way] = self[i + way], self[i] + swapped = i + end + end + break unless swapped + start, finish, way = swapped, start, -way + end + self + end +end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-3.rb b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-3.rb new file mode 100644 index 0000000000..5ca810237e --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort-3.rb @@ -0,0 +1,4 @@ +ary = [7,6,5,9,8,4,3,1,2,0] +p ary.cocktailsort! +ary = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"] +p ary.cocktailsort! diff --git a/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb b/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb index 199f52faac..138bdc9dda 100644 --- a/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb +++ b/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb @@ -2,8 +2,8 @@ class Array def combsort! gap = size swaps = true - until gap <= 1 and swaps - gap = (gap / 1.25).to_int + while gap > 1 or swaps + gap = [1, (gap / 1.25).to_i].max swaps = false 0.upto(size - gap - 1) do |i| if self[i] > self[i+gap] diff --git a/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-3.groovy b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-3.groovy new file mode 100644 index 0000000000..75c6f8e9b0 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-3.groovy @@ -0,0 +1,19 @@ +split = { list -> + list.collate((list.size()+1)/2 as int) +} + +merge = { left, right, headBuffer=[] -> + if(left.size() == 0) headBuffer+right + else if(right.size() == 0) headBuffer+left + else if(left.head() <= right.head()) merge.trampoline(left.tail(), right, headBuffer+left.head()) + else merge.trampoline(right.tail(), left, headBuffer+right.head()) +}.trampoline() + +mergesort = { List list -> + if(list.size() < 2) list + else merge(split(list).collect {mergesort it}) +} + +assert mergesort((500..1)) == (1..500) +assert mergesort([5,4,6,3,1,2]) == [1,2,3,4,5,6] +assert mergesort([3,3,1,4,6,78,9,1,3,5]) == [1,1,3,3,3,4,5,6,9,78] diff --git a/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-4.groovy b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-4.groovy new file mode 100644 index 0000000000..08e244a6bc --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-4.groovy @@ -0,0 +1,4 @@ +split = { list, left=[], right=[] -> + if(list.size() <2) [list+left, right] + else split.trampoline(list.tail().tail(), [list.head()]+left,[list.tail().head()]+right) +}.trampoline() diff --git a/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs index 65bdb16785..78378b38c8 100644 --- a/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs +++ b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs @@ -1,7 +1,7 @@ -merge [] ys = ys -merge xs [] = xs -merge xs@(x:xs') ys@(y:ys') | x <= y = x : merge xs' ys - | otherwise = y : merge xs ys' +merge [] ys = ys +merge xs [] = xs +merge xs@(x:xt) ys@(y:yt) | x <= y = x : merge xt ys + | otherwise = y : merge xs yt split (x:y:zs) = let (xs,ys) = split zs in (x:xs,y:ys) split [x] = ([x],[]) diff --git a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb index 328b661a8d..0abad2adaa 100644 --- a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb +++ b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb @@ -1,34 +1,26 @@ def merge_sort(m) - if m.length <= 1 - return m - end + return m if m.length <= 1 - middle = m.length / 2 - left = m[0,middle] - right = m[middle..-1] + middle = m.length / 2 + left = m[0,middle] + right = m[middle..-1] - left = merge_sort(left) - right = merge_sort(right) - merge(left, right) + left = merge_sort(left) + right = merge_sort(right) + merge(left, right) end def merge(left, right) - result = [] - - until left.empty? || right.empty? - # change the direction of this comparison to change the direction of the sort - if left.first <= right.first - result << left.shift - else - result << right.shift - end + result = [] + until left.empty? || right.empty? + if left.first <= right.first + result << left.shift + else + result << right.shift end - - unless left.empty? - result += left - end - unless right.empty? - result += right - end - result + end + result + left + right end + +ary = [7,6,5,9,8,4,3,1,2,0] +p merge_sort(ary) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb index 0354595a9d..bf42206371 100644 --- a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb +++ b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb @@ -1,36 +1,32 @@ class Array def mergesort(&comparitor) - if length <= 1 - self - else - unless comparitor - comparitor = lambda {|a, b| a <=> b} - end - middle = length / 2 - left = self[0, middle].mergesort(&comparitor) - right = self[middle..-1].mergesort(&comparitor) - merge(left, right, comparitor) - end + return self if length <= 1 + comparitor ||= lambda {|a, b| a <=> b} + middle = length / 2 + left = self[0, middle].mergesort(&comparitor) + right = self[middle..-1].mergesort(&comparitor) + merge(left, right, comparitor) end - protected + private def merge(left, right, comparitor) - if left.empty? - right - elsif right.empty? - left - elsif comparitor.call(left.first, right.first) <= 0 - [left.first] + merge(left[1..-1], right, comparitor) - else - [right.first] + merge(left, right[1..-1], comparitor) + result = [] + until left.empty? || right.empty? + # change the direction of this comparison to change the direction of the sort + if comparitor[left.first, right.first] <= 0 + result << left.shift + else + result << right.shift + end end + result + left + right end end ary = [7,6,5,9,8,4,3,1,2,0] -ary.mergesort # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -ary.mergesort {|a, b| b <=> a} # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] +p ary.mergesort # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +p ary.mergesort {|a, b| b <=> a} # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] -ary.mergesort {|a, b| a[1] <=> b[1]} +p ary.mergesort {|a, b| a[1] <=> b[1]} # => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]] diff --git a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d index 23f2557e7b..3a1545f37d 100644 --- a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d +++ b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, permutations2; -void permutationSort(T)(T[] items) /*pure nothrow*/ { +void permutationSort(T)(T[] items) pure /*nothrow*/ { foreach (const perm; items.permutations!false) if (perm.isSorted) { items[] = perm[]; diff --git a/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb b/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb index 58b0a0b16a..edfeb79db3 100644 --- a/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb +++ b/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb @@ -1,10 +1,6 @@ class Array def permutationsort - permutations = permutation - begin - perm = permutations.next - end until perm.sorted? - perm + permutation.each{|perm| return perm if perm.sorted?} end def sorted? diff --git a/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffee b/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffee index efe43b686f..3015c57b13 100644 --- a/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffee +++ b/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffee @@ -1,35 +1,5 @@ -# This shows quicksort-in-place. -quicksort = (a) -> - swap = (i, j) -> - return if i == j - [a[i], a[j]] = [a[j], a[i]] - - divide = (v, start, end) -> - first_big = start - j = start - while j <= end - if a[j] < v - swap first_big, j - first_big += 1 - j += 1 - first_big - - partition = (start, end) -> - v = a[end] - first_big = divide v, start, end-1 - swap first_big, end - first_big - - qs = (start, end) -> - return if start >= end - m = partition start, end - qs start, m-1 - qs m+1, end - - qs 0, a.length - 1 - -# test -do -> - a = [1, 3, 5, 7, 9, 8, 6, 4, 2, 0, 3.5] - quicksort(a) - console.log a # [ 0, 1, 2, 3, 3.5, 4, 5, 6, 7, 8, 9 ] +quicksort = ([x, xs...]) -> + return [] unless x? + smallerOrEqual = (a for a in xs when a <= x) + larger = (a for a in xs when a > x) + (quicksort smallerOrEqual).concat(x).concat(quicksort larger) diff --git a/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs index 57a0c178fd..0feb6d0d34 100644 --- a/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs +++ b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs @@ -1,2 +1,2 @@ -qsort [] = [] +qsort [] = [] qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x] diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-4.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-4.py new file mode 100644 index 0000000000..5d3252964f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-4.py @@ -0,0 +1,8 @@ +from random import * + +def qSort(a): + if len(a) <= 1: + return a + else: + q = choice(a) + return qSort([elem for elem in a if elem < q]) + [q] * a.count(q) + qSort([elem for elem in a if elem > q]) diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-5.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-5.py new file mode 100644 index 0000000000..98d0f52b0b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-5.py @@ -0,0 +1,15 @@ +def quickSort(a): + if len(a) <= 1: + return a + else: + less = [] + more = [] + pivot = choice(a) + for i in a: + if i < pivot: + less.append(i) + if i > pivot: + more.append(i) + less = quickSort(less) + more = quickSort(more) + return less + [pivot] * a.count(pivot) + more diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx index 2939321bd4..a3bc7dd9be 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx @@ -9,7 +9,7 @@ quickSort: procedure expose @. /*access the caller's local var. */ a.1=1; b.1=arg(1); $=1 do while $\==0; l=a.$; t=b.$; $=$-1 - if t<2 then iterate + if t<2 then iterate h=l+t-1 ?=l+t%2 if @.h<@.l then if @.?<@.h then do; p=@.h; @.h=@.l; end @@ -23,86 +23,86 @@ a.1=1; b.1=arg(1); $=1 do forever do j=j while j<=k & @.j<=p; end /*a tinie-tiny loop*/ do k=k by -1 while j =p; end /*another tiny loop*/ - if j>=k then leave + if j>=k then leave _=@.j; @.j=@.k; @.k=_ end /*forever*/ k=j-1; @.l=@.k; @.k=p $=$+1 - if j<=? then do; a.$=j; b.$=h-j+1; $=$+1; a.$=l; b.$=k-l; end - else do; a.$=l; b.$=k-l; $=$+1; a.$=j; b.$=h-j+1; end + if j<=? then do; a.$=j; b.$=h-j+1; $=$+1; a.$=l; b.$=k-l; end + else do; a.$=l; b.$=k-l; $=$+1; a.$=j; b.$=h-j+1; end end /*while $\==0*/ return /*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.=''; maxL=0 /*assign default value. */ -@.1 =" Rivers that form part of a state's (USA) border " -@.2 ='=' -@.3 ="Chattahoochee River: Alabama, Georgia" -@.4 ="Colorado River: Arizona, Nevada, California, Baja California (Mexico)" -@.5 ="St. Francis River: Arkansas, Missouri" -@.6 ="Poteau River: Arkansas, Oklahoma" -@.7 ="Byram River: Connecticut, New York" -@.8 ="Pawcatuck River: Connecticut, Rhode Island" -@.9 ="Perdido River: Florida, Alabama" -@.10="St. Marys River: Florida, Georgia" -@.11="Chattooga River: Georgia, South Carolina" -@.12="Tugaloo River: Georgia, South Carolina" -@.13="Snake River: Idaho, Washington, Oregon" -@.14="Wabash River: Illinois, Indiana" -@.15="Ohio River: Illinois, Indiana, Ohio, Kentucky, West Virginia" -@.16="Des Moines River: Iowa, Missouri" -@.17="Tennessee River: Kentucky, Tennessee, Mississippi, Alabama" -@.18="Big Sandy River: Kentucky, West Virginia" -@.19="Tug Fork River: Kentucky, West Virginia, Virginia" -@.20="Monument Creek: Maine, New Brunswick (Canda)" -@.21="St. Croix River: Maine, New Brunswick (Canda)" -@.22="Piscataqua River: Maine, New Hampshire" -@.23="St. Francis River: Maine, Quebec (Canada)" -@.24="St. John River: Maine, Quebec (Canada)" -@.25="Pocomoke River: Maryland, Virginia" -@.26="Potomac River: Maryland, Virginia, city of Washington (District of Columbia), West Virginia" -@.27="Montreal River: Michigan (upper peninsula ), Wisconsin" -@.28="Detroit River: Michigan, Ontario (Canada)" -@.29="St. Clair River: Michigan, Ontario (Canada)" -@.30="St. Marys River: Michigan, Ontario (Canada)" -@.31="Brule River: Michigan, Wisconsin" -@.32="Menominee River: Michigan, Wisconsin" -@.33="Pigeon River: Minnesota, Ontario (Canada)" -@.34="Rainy River: Minnesota, Ontario (Canada)" -@.35="St. Croix River: Minnesota, Wisconsin" -@.36="St. Louis River: Minnesota, Wisconsin" -@.37="Mississippi River: Minnesota, Wisconsin, Iowa, Illinois, Missouri, Kentucky, Tennesse, Arkansas, Mississippi, Louisiana" -@.38="Pearl River: Mississippi, Louisiana" -@.39="Halls Stream: New Hampshire, Canada" -@.40="Salmon Falls River: New Hampshire, Maine" -@.41="Connecticut River: New Hampshire, Vermont" -@.42="Hudson River (lower part only): New Jersey, New York" -@.43="Arthur Kill: New Jersey, New York (tidal strait)" -@.44="Kill Van Kull: New Jersey, New York (tidal strait)" -@.45="Rio Grande: New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila De Zaragoza (Mexico), Chihuahua (Mexico)" -@.46="Niagara River: New York, Ontario (Canada)" -@.47="St. Lawrence River: New York, Ontario (Canada)" -@.48="Delaware River: New York, Pennsylvania, New Jersey, Delaware" -@.49="Catawba River: North Carolina, South Carolina" -@.50="Red River of the North: North Dakota, Minnesota" -@.51="Great Miami River (mouth only): Ohio, Indiana" -@.52="Arkansas River: Oklahoma, Arkansas" -@.53="Palmer River: Rhode Island, Massachusetts" -@.54="Runnins River: Rhode Island, Massachusetts" -@.55="Savannah River: South Carolina, Georgia" -@.56="Big Sioux River: South Dakota, Iowa" -@.57="Bois de Sioux River: South Dakota, Minnesota, North Dakota" -@.58="Missouri River: South Dakota, Nebraska, Iowa, Missouri, Kansas" -@.59="Sabine River: Texas, Louisiana" -@.60="Red River (Mississippi watershed): Texas, Oklahoma, Arkansas" -@.61="Poultney River: Vermont, New York" -@.62="Blackwater River: Virginia, North Carolina" -@.63="Columbia River: Washington, Oregon" +gen@: @.=; maxL=0 /*assign default value for array.*/ +@.1 =" Rivers that form part of a state's (USA) border " /*adj. later,*/ +@.2 ='=' /*this value is expanded later. */ +@.3 ="Perdido River: Alabama, Florida" +@.4 ="Chattahoochee River: Alabama, Georgia" +@.5 ="Tennessee River: Alabama, Kentucky, Mississippi, Tennessee" +@.6 ="Colorado River: Arizona, California, Nevada, Baja California (Mexico)" +@.7 ="Mississippi River: Arkansas, Illinois, Iowa, Kentucky, Minnesota, Mississippi, Missouri, Tennesse, Louisiana, Wisconsin" +@.8 ="St. Francis River: Arkansas, Missouri" +@.9 ="Poteau River: Arkansas, Oklahoma" +@.10="Arkansas River: Arkansas, Oklahoma" +@.11="Red River (Mississippi watershed): Arkansas, Oklahoma, Texas" +@.12="Byram River: Connecticut, New York" +@.13="Pawcatuck River: Connecticut, Rhode Island" +@.14="Delaware River: Delaware, New Jersey, New York, Pennsylvania" +@.15="Potomac River: District of Columbia, Maryland, Virginia, West Virginia" +@.16="St. Marys River: Florida, Georgia" +@.17="Chattooga River: Georgia, South Carolina" +@.18="Tugaloo River: Georgia, South Carolina" +@.19="Savannah River: Georgia, South Carolina" +@.20="Snake River: Idaho, Oregon, Washington" +@.21="Wabash River: Illinois, Indiana" +@.22="Ohio River: Illinois, Indiana, Kentucky, Ohio, West Virginia" +@.23="Great Miami River (mouth only): Indiana, Ohio" +@.24="Des Moines River: Iowa, Missouri" +@.25="Big Sioux River: Iowa, South Dakota" +@.26="Missouri River: Kansas, Iowa, Missouri, Nebraska, South Dakota" +@.27="Tug Fork River: Kentucky, Virginia, West Virginia" +@.28="Big Sandy River: Kentucky, West Virginia" +@.29="Pearl River: Louisiana, Mississippi" +@.30="Sabine River: Louisiana, Texas" +@.31="Monument Creek: Maine, New Brunswick (Canda)" +@.32="St. Croix River: Maine, New Brunswick (Canda)" +@.33="Piscataqua River: Maine, New Hampshire" +@.34="St. Francis River: Maine, Quebec (Canada)" +@.35="St. John River: Maine, Quebec (Canada)" +@.36="Pocomoke River: Maryland, Virginia" +@.37="Palmer River: Massachusetts, Rhode Island" +@.38="Runnins River: Massachusetts, Rhode Island" +@.39="Montreal River: Michigan (upper peninsula), Wisconsin" +@.40="Detroit River: Michigan, Ontario (Canada)" +@.41="St. Clair River: Michigan, Ontario (Canada)" +@.42="St. Marys River: Michigan, Ontario (Canada)" +@.43="Brule River: Michigan, Wisconsin" +@.44="Menominee River: Michigan, Wisconsin" +@.45="Red River of the North: Minnesota, North Dakota" +@.46="Bois de Sioux River: Minnesota, North Dakota, South Dakota" +@.47="Pigeon River: Minnesota, Ontario (Canada)" +@.48="Rainy River: Minnesota, Ontario (Canada)" +@.49="St. Croix River: Minnesota, Wisconsin" +@.50="St. Louis River: Minnesota, Wisconsin" +@.51="Halls Stream: New Hampshire, Canada" +@.52="Salmon Falls River: New Hampshire, Maine" +@.53="Connecticut River: New Hampshire, Vermont" +@.54="Arthur Kill: New Jersey, New York (tidal strait)" +@.55="Kill Van Kull: New Jersey, New York (tidal strait)" +@.56="Hudson River (lower part only): New Jersey, New York" +@.57="Rio Grande: New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila De Zaragoza (Mexico), Chihuahua (Mexico)" +@.58="Niagara River: New York, Ontario (Canada)" +@.59="St. Lawrence River: New York, Ontario (Canada)" +@.60="Poultney River: New York, Vermont" +@.61="Catawba River: North Carolina, South Carolina" +@.62="Blackwater River: North Carolina, Virginia" +@.63="Columbia River: Oregon, Washington" - do highItem=1 while @.highItem\=='' /*find how many entries, and also*/ + do highItem=1 while @.highItem\=='' /*find how many entries, and also*/ maxL=max(maxL,length(@.highItem)) /* find the maximum width entry.*/ - end + end /*highItem*/ highItem=highItem-1 /*adjust highItem slightly. */ @.1=centre(@.1,maxL,'-') /*adjust the header information. */ @@ -111,9 +111,9 @@ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ show@: widthH=length(highItem) /*maximum width of any line. */ - do j=1 for highItem /*show each array item.*/ - say 'element' right(j,widthH) arg(1)':' @.j - end + do j=1 for highItem /*display each item in the array.*/ + say 'element' right(j,widthH) arg(1)':' @.j + end /*j*/ -say copies('█',maxL+widthH+22) /*show a separator line. */ +say copies('█',maxL+widthH+22) /*display a separator line. */ return diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb index cfbb58e0c3..11aef435dd 100644 --- a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb @@ -1,7 +1,7 @@ class Array def quick_sort return self if length <= 1 - pivot = self[length / 2] + pivot = sample find_all { |i| i < pivot }.quick_sort + find_all { |i| i == pivot } + find_all { |i| i > pivot }.quick_sort diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb index 6780ffb011..2361ae2527 100644 --- a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb @@ -3,8 +3,6 @@ class Array return self if length <= 1 pivot = self[0] less, greatereq = self[1..-1].partition { |x| x < pivot } - less.quick_sort + - [pivot] + - greatereq.quick_sort + less.quick_sort + [pivot] + greatereq.quick_sort end end diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb new file mode 100644 index 0000000000..be8e6e9bf2 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb @@ -0,0 +1,9 @@ +class Array + def quick_sort + return self if length <= 1 + pivot = sample + group = group_by{ |x| x <=> pivot } + group.default = [] + group[-1].quick_sort + group[0] + group[1].quick_sort + end +end diff --git a/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli b/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli new file mode 100644 index 0000000000..e19b7a937a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli @@ -0,0 +1,28 @@ +Selection: procedure options (main); /* 2 November 2013 */ + + declare a(10) fixed b inary initial ( + 5, 7, 3, 98, 4, -3, 25, 20, 60, 17); + + put edit (trim(a)) (a, x(1)); + + call Selection_Sort (a); + + put skip edit (trim(a)) (a, x(1)); + +Selection_sort: procedure (a); + declare a(*) fixed binary; + declare t fixed binary; + declare n fixed binary; + declare (i, j, k) fixed binary; + + n = hbound(a,1); + do j = 1 to n; + k = j; t = a(j); + do i = j+1 to n; + if t > a(i) then do; t = a(i); k = i; end; + end; + a(k) = a(j); a(j) = t; + end; +end Selection_Sort; + +end Selection; diff --git a/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb b/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb index 5b3430c1e5..9fc00d410f 100644 --- a/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb +++ b/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb @@ -1,18 +1,15 @@ class Array def selectionsort! - 0.upto(length - 2) do |i| - (min_idx = i + 1).upto(length - 1) do |j| - if self[j] < self[min_idx] - min_idx = j - end - end - if self[i] > self[min_idx] - self[i], self[min_idx] = self[min_idx], self[i] + for i in 0..length-2 + min_idx = i + for j in (i+1)...length + min_idx = j if self[j] < self[min_idx] end + self[i], self[min_idx] = self[min_idx], self[i] end self end end ary = [7,6,5,9,8,4,3,1,2,0] -ary.selectionsort! +p ary.selectionsort! # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cobol b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cobol new file mode 100644 index 0000000000..864b59a804 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cobol @@ -0,0 +1,100 @@ + ******************************************************* + IDENTIFICATION DIVISION. + ******************************************************* + PROGRAM-ID. SHELLSRT. + ************************************************************ + *** SHELLSORT **** + ************************************************************ + ENVIRONMENT DIVISION. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 II PIC S9(008) COMP-5. + 01 IJ PIC S9(008) COMP-5. + 01 IZ PIC S9(008) COMP-5. + 01 IA PIC S9(008) COMP-5. + 01 STRT1 PIC S9(008) COMP-5. + 01 STRT2 PIC S9(008) COMP-5. + 01 LGT PIC S9(008) COMP-5. + 01 ORG PIC S9(008) COMP-5. + 01 DST PIC S9(008) COMP-5. + * + 01 GAP PIC S9(008) COMP-5. + 01 NEGAP PIC S9(008) COMP-5. + 01 TEMP PIC X(32768). + 77 KEY-RESULT PIC X. + * + LINKAGE SECTION. + 01 SRT-ARRAY PIC X(1000000). + 01 NUM-ITEM PIC 9(008) COMP-5. + 01 SRT-DATA. + 03 LGT-ITEM PIC 9(004) COMP-5. + 03 SRT-KEYS. + 05 SRT-KEY OCCURS 10. + 07 K-START PIC S9(004) COMP-5. + 07 K-LENGTH PIC S9(004) COMP-5. + 07 K-ASC PIC X. + * + * P R O C E D U R E D I V I S I O N + * + PROCEDURE DIVISION USING SRT-ARRAY NUM-ITEM SRT-DATA. + + COMPUTE GAP = NUM-ITEM / 2. + PERFORM UNTIL GAP < 1 + COMPUTE NEGAP = GAP * -1 + PERFORM VARYING II FROM GAP BY 1 + UNTIL II GREATER NUM-ITEM + MOVE ' ' TO KEY-RESULT + COMPUTE ORG = (II - 1) * LGT-ITEM + 1 + MOVE SRT-ARRAY(ORG:LGT-ITEM) TO TEMP(1:LGT-ITEM) + PERFORM VARYING IJ FROM II BY NEGAP + UNTIL IJ NOT GREATER GAP + OR (KEY-RESULT NOT EQUAL '<' AND ' ') + COMPUTE IA = IJ - GAP + IF IA < 1 + MOVE 1 TO IA + END-IF + PERFORM COMPARE-KEYS + IF KEY-RESULT = '<' + COMPUTE ORG = (IA - 1) * LGT-ITEM + 1 + COMPUTE DST = (IJ - 1) * LGT-ITEM + 1 + MOVE SRT-ARRAY(ORG:LGT-ITEM) + TO SRT-ARRAY(DST:LGT-ITEM) + COMPUTE DST = (IA - 1) * LGT-ITEM + 1 + MOVE TEMP(1:LGT-ITEM) TO SRT-ARRAY(DST:LGT-ITEM) + END-IF + END-PERFORM + END-PERFORM + IF GAP = 2 + MOVE 1 TO GAP + ELSE + COMPUTE GAP = GAP / 2.2 + END-IF + END-PERFORM. + GOBACK. + * + COMPARE-KEYS. + MOVE ' ' TO KEY-RESULT + PERFORM VARYING IZ FROM 1 BY 1 + UNTIL IZ GREATER 10 + OR (KEY-RESULT NOT EQUAL '=' AND ' ') + IF SRT-KEY(IZ) GREATER LOW-VALUES + COMPUTE STRT1 = (IJ - 1) * LGT-ITEM + K-START(IZ) + COMPUTE STRT2 = (IA - 1) * LGT-ITEM + K-START(IZ) + MOVE K-LENGTH(IZ) TO LGT + IF SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'A' + OR SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'D' + MOVE '>' TO KEY-RESULT + END-IF + IF SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'A' + OR SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'D' + MOVE '<' TO KEY-RESULT + END-IF + END-IF + END-PERFORM. + IF KEY-RESULT = ' ' + MOVE '=' TO KEY-RESULT + END-IF. diff --git a/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort.cobol b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-2.cobol similarity index 100% rename from Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort.cobol rename to Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-2.cobol diff --git a/Task/Sorting-algorithms-Shell-sort/Delphi/sorting-algorithms-shell-sort.delphi b/Task/Sorting-algorithms-Shell-sort/Delphi/sorting-algorithms-shell-sort.delphi new file mode 100644 index 0000000000..40df74ec25 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Delphi/sorting-algorithms-shell-sort.delphi @@ -0,0 +1,23 @@ +Procedure ShellSort(var buf:Array of Integer); +const + gaps:array[0..7] of Integer = (701, 301, 132, 57, 23, 10, 4, 1); + +var + whichGap, i, j, n, gap, temp : Integer; + +begin + n := high(buf); + for whichGap := 0 to high(gaps) do begin + gap := gaps[whichGap]; + for i := gap to n do begin + temp := buf[i]; + + j := i; + while ( (j >= gap ) and ( (buf[j-gap] > dt) ) do begin + buf[j] := buf[j-gap]; + dec(j, gap); + end; + buf[j] := temp; + end; + end; +end; diff --git a/Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cobol b/Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cobol new file mode 100644 index 0000000000..747422d413 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cobol @@ -0,0 +1,80 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. stooge-sort-test. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 Arr-Len CONSTANT 7. + +01 arr-area VALUE "00004001000020000005000230000000000". + 03 arr-elt PIC 9(5) OCCURS Arr-Len TIMES + INDEXED BY arr-idx. + +PROCEDURE DIVISION. + DISPLAY "Unsorted: " NO ADVANCING + PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx + DISPLAY arr-elt (arr-idx) " " NO ADVANCING + END-PERFORM + DISPLAY SPACE + + CALL "stooge-sort" USING arr-area, OMITTED, OMITTED + + DISPLAY "Sorted: " NO ADVANCING + PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx + DISPLAY arr-elt (arr-idx) " " NO ADVANCING + END-PERFORM + DISPLAY SPACE + . +END PROGRAM stooge-sort-test. + + +IDENTIFICATION DIVISION. +PROGRAM-ID. stooge-sort RECURSIVE. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 Arr-Len CONSTANT 7. + +01 i PIC 99 COMP. +01 j PIC 99 COMP. + +01 temp PIC 9(5). + +01 t PIC 99 COMP. + +LINKAGE SECTION. +01 arr-area. + 03 arr-elt PIC 9(5) OCCURS Arr-Len TIMES. + +01 i-val PIC 99 COMP. +01 j-val PIC 99 COMP. + +PROCEDURE DIVISION USING arr-area, OPTIONAL i-val, OPTIONAL j-val. + IF i-val IS OMITTED + MOVE 1 TO i + ELSE + MOVE i-val TO i + END-IF + IF j-val IS OMITTED + MOVE Arr-Len TO j + ELSE + MOVE j-val TO j + END-IF + + IF arr-elt (j) < arr-elt (i) + MOVE arr-elt (i) TO temp + MOVE arr-elt (j) TO arr-elt (i) + MOVE temp TO arr-elt (j) + END-IF + + IF j - i + 1 >= 3 + COMPUTE t = (j - i + 1) / 3 + SUBTRACT t FROM j + CALL "stooge-sort" USING arr-area, CONTENT i, j + ADD t TO i, j + CALL "stooge-sort" USING arr-area, CONTENT i, j + SUBTRACT t FROM i, j + CALL "stooge-sort" USING arr-area, CONTENT i, j + END-IF + . +END PROGRAM stooge-sort. diff --git a/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d index 18453b7819..9c68af56fb 100644 --- a/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d +++ b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d @@ -1,7 +1,7 @@ import std.stdio, std.array; -T[] strandSort(T)(/*in*/ T[] list) pure nothrow { - static T[] merge(T[] left, T[] right) pure nothrow { +T[] strandSort(T)(const(T)[] list) pure nothrow { + static T[] merge(const(T)[] left, const(T)[] right) pure nothrow { T[] res; while (!left.empty && !right.empty) { if (left.front <= right.front) { @@ -19,8 +19,8 @@ T[] strandSort(T)(/*in*/ T[] list) pure nothrow { while (!list.empty) { auto sorted = list[0 .. 1]; list.popFront; - T[] leftover; - foreach (item; list) + typeof(sorted) leftover; + foreach (const item; list) (sorted.back <= item ? sorted : leftover) ~= item; result = merge(sorted, result); list = leftover; @@ -30,6 +30,6 @@ T[] strandSort(T)(/*in*/ T[] list) pure nothrow { } void main() { - auto arr = [-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2]; + const arr = [-2, 0, -2, 5, 5, 3, -1, -3, 5, 5, 0, 2, -4, 4, 2]; arr.strandSort.writeln; } diff --git a/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb b/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb index ba23a270fe..497c5be305 100644 --- a/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb +++ b/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb @@ -2,32 +2,25 @@ class Array def strandsort a = self.dup result = [] - while a.length > 0 + until a.empty? sublist = [a.shift] - a.each_with_index . - inject([]) do |remove, (val, idx)| - if val > sublist[-1] - sublist << val - remove.unshift(idx) - end - remove - end . - each {|idx| a.delete_at(idx)} + a.each_with_index.each_with_object([]) { |(val, idx), remove| + next if val <= sublist.last + sublist << val + remove << idx + }.reverse_each {|idx| a.delete_at(idx)} - idx = 0 - while idx < result.length and not sublist.empty? - if sublist[0] < result[idx] - result.insert(idx, sublist.shift) - end - idx += 1 + result.each_index do |idx| + break if sublist.empty? + result.insert(idx, sublist.shift) if sublist[0] < result[idx] end - result += sublist if not sublist.empty? + result += sublist end result end def strandsort! - self.replace(strandsort) + replace(strandsort) end end diff --git a/Task/Special-variables/Deja-Vu/special-variables.djv b/Task/Special-variables/Deja-Vu/special-variables.djv new file mode 100644 index 0000000000..91107d6daf --- /dev/null +++ b/Task/Special-variables/Deja-Vu/special-variables.djv @@ -0,0 +1,2 @@ +!print "hey" #is really short for +eva!print "hey" diff --git a/Task/Special-variables/Erlang/special-variables.erl b/Task/Special-variables/Erlang/special-variables.erl new file mode 100644 index 0000000000..34394812cd --- /dev/null +++ b/Task/Special-variables/Erlang/special-variables.erl @@ -0,0 +1,5 @@ +-module( special_variables ). + +-export( [task/0] ). + +task() -> ok. diff --git a/Task/Special-variables/PL-I/special-variables.pli b/Task/Special-variables/PL-I/special-variables.pli new file mode 100644 index 0000000000..937e52a85e --- /dev/null +++ b/Task/Special-variables/PL-I/special-variables.pli @@ -0,0 +1,21 @@ +Special variables in PL/I are termed "Pseudo-variables". +They are used only on the LHS of an assignment statement. + +They include: + REAL to assign the real part of a COMPLEX variable; + IMAG to assign the imaginary part of a COMPLEX variable; + SUBSTR is used to assign part of a string (used on the LHS of an assignment); + STRING when used on the left-hand of an assignment; + UNSPEC used to assign a bit pattern to a variable; + ENTRYADDR is used to assign an address to an ENTRY variable that is + to be invoked; + ONCHAR resets the current value of the CHAR built-in function (when + a data conversion error occurs, and it is desired to re-attempt + the conversion); + ONSOURCE assigns a new value to the ONSOURCE built-in function + (may be used when a data conversion error occurs, + and a re-try of the conversion is to be attempted with modified data); + ONGSOURCE assigns a new value to the ONGSOURCE built-in function + (may be used when a data conversion error occurs, + and may be used when a re-try of the conversion is to be + attempted with modified data). diff --git a/Task/Speech-synthesis/Groovy/speech-synthesis.groovy b/Task/Speech-synthesis/Groovy/speech-synthesis.groovy new file mode 100644 index 0000000000..a5b4f44ed5 --- /dev/null +++ b/Task/Speech-synthesis/Groovy/speech-synthesis.groovy @@ -0,0 +1 @@ +'say "This is an example of speech synthesis."'.execute() diff --git a/Task/Speech-synthesis/Perl/speech-synthesis.pl b/Task/Speech-synthesis/Perl/speech-synthesis.pl new file mode 100644 index 0000000000..5d31bc43ec --- /dev/null +++ b/Task/Speech-synthesis/Perl/speech-synthesis.pl @@ -0,0 +1,8 @@ +use Speech::Synthesis; + +($engine) = Speech::Synthesis->InstalledEngines(); +($voice) = Speech::Synthesis->InstalledVoices(engine => $engine); + +Speech::Synthesis + ->new(engine => $engine, voice => $voice->{id}) + ->speak("This is an example of speech synthesis."); diff --git a/Task/Speech-synthesis/REXX/speech-synthesis.rexx b/Task/Speech-synthesis/REXX/speech-synthesis.rexx new file mode 100644 index 0000000000..33d7915796 --- /dev/null +++ b/Task/Speech-synthesis/REXX/speech-synthesis.rexx @@ -0,0 +1,16 @@ +/*REXX pgm uses a CLI cmd to invoke Windows/XP SAM for speech synthesis.*/ +parse arg t; t=space(t) /*get the (optional) text from CL*/ +if t=='' then exit /*Nothing to say? Then exit pgm.*/ +homedrive=value('HOMEDRIVE',,'SYSTEM') /*get HOMEDRIVE location of \TEMP*/ +tmp =value('TEMP',,'SYSTEM') /* " TEMP directory name. */ +if homedrive=='' then homedrive='C:' /*use default if none found. */ +if tmp=='' then tmp=homedrive'\TEMP' /* " " " " " */ + /*code could be added here to get*/ + /*a unique name for the TEMP file*/ +tFN='SPEAK_IT'; tFT='$$$' /*use this for the TEMP's fileID.*/ +tFID=homedrive||'\TEMP\' || tFN"."tFT /*create temp name for the output*/ +call lineout tFID,t /*write text──►a temp output file*/ +call lineout tFID /*close the file just to be neat.*/ +'NIRCMD' "speak file" tFID /*NIRCMD invokes the MS Sam voice*/ +'ERASE' tfid /*clean up (delete) the TEMP file*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Speech-synthesis/Scala/speech-synthesis.scala b/Task/Speech-synthesis/Scala/speech-synthesis.scala new file mode 100644 index 0000000000..977dbe7a44 --- /dev/null +++ b/Task/Speech-synthesis/Scala/speech-synthesis.scala @@ -0,0 +1,37 @@ +import java.util.Locale +import javax.speech.Central +import javax.speech.synthesis.{ Synthesizer, SynthesizerModeDesc } + +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() + } + } + } + + speech("If it ain't Dutch, It ain't much.") +} diff --git a/Task/Spiral-matrix/Ruby/spiral-matrix.rb b/Task/Spiral-matrix/Ruby/spiral-matrix.rb index 7d8e0d1ee2..0feeced787 100644 --- a/Task/Spiral-matrix/Ruby/spiral-matrix.rb +++ b/Task/Spiral-matrix/Ruby/spiral-matrix.rb @@ -4,13 +4,8 @@ def spiral(n) delta = [[1,0], [0,1], [-1,0], [0,-1]].cycle x, y, value = -1, 0, -1 for run in runs - dx,dy = delta.next - run.times do |i| - x += dx - y += dy - value += 1 - spiral[y][x] = value - end + dx, dy = delta.next + run.times { spiral[y+=dy][x+=dx] = (value+=1) } end spiral end diff --git a/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d b/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d index 6dcefac149..cc957e4bba 100644 --- a/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d +++ b/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d @@ -3,9 +3,9 @@ import std.stdio, std.algorithm, std.array; enum F { abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan } enum M { abe, bob, col, dan, ed, fred, gav, hal, ian, jon } -alias M[][F] PrefMapF; -alias F[][M] PrefMapM; -alias M[F] Couples; +alias PrefMapF = M[][F]; +alias PrefMapM = F[][M]; +alias Couples = M[F]; immutable PrefMapF womenPref; immutable PrefMapM menPref; @@ -41,30 +41,27 @@ pure nothrow static this() { } /// Does 'first' appear before 'second' in preference list? -bool prefers(T)(in T[] prefer, in T first, in T second) +bool prefers(T)(in T[] preference, in T first, in T second) pure nothrow if (is(T == F) || is(T == M)) { - foreach (p; prefer) { - if (p == first) return true; - if (p == second) return false; - } - return false; // no preference + const found = preference.findAmong([first, second]); + return !(found.empty || found.front == second); } void checkStability(in Couples engaged, in PrefMapM menPref, in PrefMapF womenPref) { - writeln("Stablility:"); + "Stablility:".writeln; bool stable = true; - foreach (bride, groom; engaged) { + foreach (immutable bride, immutable groom; engaged) { const prefList = menPref[groom]; - foreach (pr; prefList) { - if (pr == bride) // he prefers his bride + foreach (immutable pr; prefList) { + if (pr == bride) // He prefers his bride. break; if (prefers(prefList, pr, bride) && - // he prefers another woman + // He prefers another woman. prefers(womenPref[pr], groom, engaged[pr])) { - // other woman prefers him + // Other woman prefers him. writeln("\t", pr, " prefers ", groom, " over ", engaged[pr], " and ", groom, " prefers ", pr, " over ", bride); @@ -74,23 +71,23 @@ void checkStability(in Couples engaged, in PrefMapM menPref, } if (stable) - writeln("\t(all marriages stable)"); + "\t(all marriages stable)".writeln; } void main() { - M[] bachelors = menPref.keys.sort().release();// No queue in Phobos + auto bachelors = menPref.keys.sort().release;// No queue in Phobos. Couples engaged; - writeln("Matchmaking:"); + "Matchmaking:".writeln; while (!bachelors.empty) { immutable suitor = bachelors[0]; - bachelors.popFront(); + bachelors.popFront; immutable prefList = menPref[suitor]; - foreach (bride; prefList) { - if (bride !in engaged) { // she's available + foreach (immutable bride; prefList) { + if (bride !in engaged) { // She's available. writeln("\t", bride, " and ", suitor); - engaged[bride] = suitor; // hook up + engaged[bride] = suitor; // Hook up. break; } @@ -98,21 +95,21 @@ void main() { if (prefers(womenPref[bride], suitor, groom)) { writeln("\t", bride, " dumped ", groom, " for ", suitor); - bachelors ~= groom; // dump that zero - engaged[bride] = suitor; // get a hero + bachelors ~= groom; // Dump that zero. + engaged[bride] = suitor; // Get a hero. break; } } } - writeln("Engagements:"); - foreach (first, second; engaged) + "Engagements:".writeln; + foreach (immutable first, immutable second; engaged) writeln("\t", first, " and ", second); checkStability(engaged, menPref, womenPref); - writeln("Perturb:"); - swap(engaged[F.abi], engaged[F.bea]); + "Perturb:".writeln; + engaged[F.abi].swap(engaged[F.bea]); writeln("\tengage abi with ", engaged[F.abi], " and bea with ", engaged[F.bea]); diff --git a/Task/Stack-traces/D/stack-traces.d b/Task/Stack-traces/D/stack-traces.d index 29487329b2..bcfa5244e7 100644 --- a/Task/Stack-traces/D/stack-traces.d +++ b/Task/Stack-traces/D/stack-traces.d @@ -1,22 +1,10 @@ -import std.stdio; +import std.stdio, core.runtime; -void inner() { - try - throw new Exception(null); - catch (Exception e) - writeln(e); - - writeln("running"); -} - -void middle() { - inner(); -} - -void outer() { - middle(); -} +void inner() { defaultTraceHandler.writeln; } +void middle() { inner; } +void outer() { middle; } void main() { - outer(); + outer; + "After the stack trace.".writeln; } diff --git a/Task/Stack/Deja-Vu/stack.djv b/Task/Stack/Deja-Vu/stack.djv new file mode 100644 index 0000000000..7be3933e97 --- /dev/null +++ b/Task/Stack/Deja-Vu/stack.djv @@ -0,0 +1,12 @@ +local :stack [] #lists used to be stacks in DV + +push-to stack 1 +push-to stack 2 +push-to stack 3 + +!. pop-from stack #prints 3 +!. pop-from stack #prints 2 +!. pop-from stack #prints 1 + +if stack: #empty lists are falsy + error #this stack should be empty now! diff --git a/Task/Stack/Java/stack-1.java b/Task/Stack/Java/stack-1.java index ccab120716..a92d64aa43 100644 --- a/Task/Stack/Java/stack-1.java +++ b/Task/Stack/Java/stack-1.java @@ -1,29 +1,21 @@ -public class Stack{ - private Node first = null; - public boolean isEmpty(){ - return first == null; - } - public Object Pop(){ - if(isEmpty()) - throw new Exception("Can't Pop from an empty Stack."); - else{ - Object temp = first.value; - first = first.next; - return temp; - } - } - public void Push(Object o){ - first = new Node(o, first); - } - class Node{ - public Node next; - public Object value; - public Node(Object value){ - this(value, null); - } - public Node(Object value, Node next){ - this.next = next; - this.value = value; - } +import java.util.Stack; + +public class StackTest { + public static void main( final String[] args ) { + final Stack stack = new Stack(); + + System.out.println( "New stack empty? " + stack.empty() ); + + stack.push( "There can be only one" ); + System.out.println( "Pushed stack empty? " + stack.empty() ); + System.out.println( "Popped single entry: " + stack.pop() ); + + stack.push( "First" ); + stack.push( "Second" ); + System.out.println( "Popped entry should be second: " + stack.pop() ); + + // Popping an empty stack will throw... + stack.pop(); + stack.pop(); } } diff --git a/Task/Stack/Java/stack-2.java b/Task/Stack/Java/stack-2.java index cf3740bc04..ccab120716 100644 --- a/Task/Stack/Java/stack-2.java +++ b/Task/Stack/Java/stack-2.java @@ -1,27 +1,27 @@ -public class Stack{ +public class Stack{ private Node first = null; public boolean isEmpty(){ return first == null; } - public T Pop(){ + public Object Pop(){ if(isEmpty()) throw new Exception("Can't Pop from an empty Stack."); else{ - T temp = first.value; + Object temp = first.value; first = first.next; return temp; } } - public void Push(T o){ + public void Push(Object o){ first = new Node(o, first); } class Node{ public Node next; - public T value; - public Node(T value){ + public Object value; + public Node(Object value){ this(value, null); } - public Node(T value, Node next){ + public Node(Object value, Node next){ this.next = next; this.value = value; } diff --git a/Task/Stack/Java/stack-3.java b/Task/Stack/Java/stack-3.java new file mode 100644 index 0000000000..cf3740bc04 --- /dev/null +++ b/Task/Stack/Java/stack-3.java @@ -0,0 +1,29 @@ +public class Stack{ + private Node first = null; + public boolean isEmpty(){ + return first == null; + } + public T Pop(){ + if(isEmpty()) + throw new Exception("Can't Pop from an empty Stack."); + else{ + T temp = first.value; + first = first.next; + return temp; + } + } + public void Push(T o){ + first = new Node(o, first); + } + class Node{ + public Node next; + public T value; + public Node(T value){ + this(value, null); + } + public Node(T value, Node next){ + this.next = next; + this.value = value; + } + } +} diff --git a/Task/Stack/Julia/stack.julia b/Task/Stack/Julia/stack.julia new file mode 100644 index 0000000000..d7171a8086 --- /dev/null +++ b/Task/Stack/Julia/stack.julia @@ -0,0 +1,8 @@ +stack = {} +push!(stack, 1) +push!(stack, 2) +push!(stack, 3) +println(pop!(stack)) # 3 +println(length(stack)) # 2 +empty!(stack) +println(length(stack)) # 0 diff --git a/Task/Stack/Nimrod/stack.nimrod b/Task/Stack/Nimrod/stack.nimrod new file mode 100644 index 0000000000..372b4abd7d --- /dev/null +++ b/Task/Stack/Nimrod/stack.nimrod @@ -0,0 +1,73 @@ +import math + +type + EStackEmpty = object of E_Base + + TStack* [A] = object + data: seq[A] + count: int + +proc initStack*[A](initialSize = 32): TStack[A] = + assert isPowerOfTwo(initialSize) + result.count = 0 + newSeq(result.data,initialSize) + +proc cap*[A] (s: TStack[A]): int = + result = s.data.len + +proc len*[A](stack: TStack[A]): int = + result = stack.count + +proc push*[A](s: var TStack[A], item: A) = + if s.count == s.data.len: + # not enough room, make container bigger + var d: Seq[A] + newSeq(d,s.len * 2) + for i in 0 .. s.data.len - 1: + shallowCopy(d[i],s.data[i]) + shallowCopy(s.data,d) + s.data[s.count] = item + inc(s.count) + +proc pop*[A](s: var TStack[A]): A {.raises: [EStackEmpty].}= + if s.count == 0: + raise newException(EStackEmpty,"the stack is empty") + dec(s.count) + result = s.data[s.count] + +proc top*[A](s: TStack[A]): A = + result = s.data[s.count - 1] + +proc isEmpty*[A](s: var TStack[A]): bool = + return s.count == 0 + +#Tests +when isMainModule: + var stk: TStack[char] = initStack[char](4) + stk.push('a') + stk.push('b') + stk.push('c') + stk.push('d') + + assert(stk.count == 4) + assert(stk.data.len == 4) + stk.push('e') + assert(stk.cap == 8) + assert(stk.top == 'e') + + + discard stk.pop + discard stk.pop + discard stk.pop + discard stk.pop + assert(stk.isEmpty == false) + discard stk.pop + assert(stk.isEmpty == true) + + try: + discard stk.pop + except: + let + e = getCurrentException() + msg = getCurrentExceptionMsg() + echo "Exception: [[", repr(e), "]] msg: ", msg diff --git a/Task/Standard-deviation/COBOL/standard-deviation-1.cobol b/Task/Standard-deviation/COBOL/standard-deviation-1.cobol new file mode 100644 index 0000000000..7298ace86a --- /dev/null +++ b/Task/Standard-deviation/COBOL/standard-deviation-1.cobol @@ -0,0 +1 @@ +FUNCTION STANDARD-DEVIATION(2, 4, 4, 4, 5, 5, 7, 9) diff --git a/Task/Standard-deviation/COBOL/standard-deviation-2.cobol b/Task/Standard-deviation/COBOL/standard-deviation-2.cobol new file mode 100644 index 0000000000..53e193c268 --- /dev/null +++ b/Task/Standard-deviation/COBOL/standard-deviation-2.cobol @@ -0,0 +1 @@ +FUNCTION SQRT(FUNCTION VARIANCE(2, 4, 4, 4, 5, 5, 7, 9)) diff --git a/Task/Standard-deviation/COBOL/standard-deviation-3.cobol b/Task/Standard-deviation/COBOL/standard-deviation-3.cobol new file mode 100644 index 0000000000..bfe81fa569 --- /dev/null +++ b/Task/Standard-deviation/COBOL/standard-deviation-3.cobol @@ -0,0 +1,55 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. std-dev. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION sum-arr + . +DATA DIVISION. +WORKING-STORAGE SECTION. +78 Arr-Len VALUE 8. +01 arr-area VALUE "0204040405050709". + 03 arr PIC 99 OCCURS Arr-Len TIMES. + +01 i PIC 99. + +01 avg PIC 9(3)V99. + +01 std-dev PIC 9(3)V99. + +PROCEDURE DIVISION. + DIVIDE FUNCTION sum-arr(arr-area) BY Arr-Len GIVING avg ROUNDED + + PERFORM VARYING i FROM 1 BY 1 UNTIL i > Arr-Len + COMPUTE arr (i) = (arr (i) - avg) ** 2 + END-PERFORM + + COMPUTE std-dev = FUNCTION SQRT(FUNCTION sum-arr(arr-area) / Arr-Len) + DISPLAY std-dev + . +END PROGRAM std-dev. + + +IDENTIFICATION DIVISION. +FUNCTION-ID. sum-arr. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 i PIC 99. + +LINKAGE SECTION. +78 Arr-Len VALUE 8. +01 arr-area. + 03 arr PIC 99 OCCURS Arr-Len TIMES. + +01 arr-sum PIC 99. + +PROCEDURE DIVISION USING arr-area RETURNING arr-sum. + INITIALIZE arr-sum *> Without this, arr-sum is initialised incorrectly. + PERFORM VARYING i FROM 1 BY 1 UNTIL i > Arr-Len + ADD arr (i) TO arr-sum + END-PERFORM + . +END FUNCTION sum-arr. diff --git a/Task/Standard-deviation/Erlang/standard-deviation.erl b/Task/Standard-deviation/Erlang/standard-deviation.erl new file mode 100644 index 0000000000..ebc60aa085 --- /dev/null +++ b/Task/Standard-deviation/Erlang/standard-deviation.erl @@ -0,0 +1,41 @@ +-module( standard_deviation ). + +-export( [add_sample/2, create/0, destroy/1, get/1, task/0] ). + +-compile({no_auto_import,[get/1]}). + +add_sample( Pid, N ) -> Pid ! {add, N}. + +create() -> erlang:spawn_link( fun() -> loop( [] ) end ). + +destroy( Pid ) -> Pid ! stop. + +get( Pid ) -> + Pid ! {get, erlang:self()}, + receive + {get, Value, Pid} -> Value + end. + +task() -> + Pid = create(), + [add_print(Pid, X, add_sample(Pid, X)) || X <- [2,4,4,4,5,5,7,9]], + destroy( Pid ). + + + +add_print( Pid, N, _Add ) -> io:fwrite( "Standard deviation ~p when adding ~p~n", [get(Pid), N] ). + +loop( Ns ) -> + receive + {add, N} -> loop( [N | Ns] ); + {get, Pid} -> + Pid ! {get, loop_calculate( Ns ), erlang:self()}, + loop( Ns ); + stop -> ok + end. + +loop_calculate( Ns ) -> + Average = loop_calculate_average( Ns ), + math:sqrt( loop_calculate_average([math:pow(X - Average, 2) || X <- Ns]) ). + +loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ). diff --git a/Task/Standard-deviation/SAS/standard-deviation.sas b/Task/Standard-deviation/SAS/standard-deviation.sas new file mode 100644 index 0000000000..a55e2ca60b --- /dev/null +++ b/Task/Standard-deviation/SAS/standard-deviation.sas @@ -0,0 +1,32 @@ +*--Load the test data; +data test1; + input x @@; + obs=_n_; +datalines; +2 4 4 4 5 5 7 9 +; +run; + +*--Create a dataset with the cummulative data for each set of data for which the SD should be calculated; +data test2 (drop=i obs); + set test1; + y=x; + do i=1 to n; + set test1 (rename=(obs=setid)) nobs=n point=i; + if obs<=setid then output; + end; +proc sort; + by setid; +run; + +*--Calulate the standards deviation (and mean) using PROC MEANS; +proc means data=test2 vardef=n noprint; *--use vardef=n option to calculate the population SD; + by setid; + var y; + output out=stat1 n=n mean=mean std=sd; +run; + +*--Output the calculated standard deviations; +proc print data=stat1 noobs; + var n sd /*mean*/; +run; diff --git a/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c b/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c new file mode 100644 index 0000000000..11b4dd1027 --- /dev/null +++ b/Task/Start-from-a-main-routine/C/start-from-a-main-routine.c @@ -0,0 +1,10 @@ +/*Abhishek Ghosh, 7th November 2013, Rotterdam*/ +#include + +#define start main() + +int start +{ + printf("Hello World !"); + return 0; +} diff --git a/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot.rb b/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot-1.rb similarity index 100% rename from Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot.rb rename to Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot-1.rb diff --git a/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot-2.rb b/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot-2.rb new file mode 100644 index 0000000000..dee76711ae --- /dev/null +++ b/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot-2.rb @@ -0,0 +1,29 @@ +class StemLeafPlot + def initialize(data, leaf_digits=1) + @leaf_digits = leaf_digits + multiplier = 10 ** @leaf_digits + @plot = data.sort.group_by{|x| x / multiplier} + @plot.default = [] + @plot.each{|k,v| @plot[k] = v.map{|val| val % multiplier}} + end + + def print + min, max = @plot.keys.minmax + stem_width = max.to_s.size + (min..max).each do |stem| + leaves = @plot[stem].inject("") {|str,leaf| str << "%0*d " % [@leaf_digits, leaf]} + puts "%*s | %s" % [stem_width, stem, leaves] + end + end +end + +data = DATA.read.split.map {|s| Integer(s)} +StemLeafPlot.new(data).print + +__END__ +12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 +115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 +121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 +27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 +111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 +133 45 120 30 127 31 116 146 diff --git a/Task/String-case/6502-Assembly/string-case.6502 b/Task/String-case/6502-Assembly/string-case.6502 index fc6b9714ca..8ae883459b 100644 --- a/Task/String-case/6502-Assembly/string-case.6502 +++ b/Task/String-case/6502-Assembly/string-case.6502 @@ -15,37 +15,37 @@ ;------------------------------------------------------ ; Constant Section ; -StrPtr = $6 0-page temp pointer (2 bytes) -Low = $8 0-page temp low bound -High = $9 0-page temp high bound -CharOut = $fded Specific to the Apple II -BigA = "A" 'A' for normal ascii -BigZ = "Z" 'Z' " " " -LittleA = "a" 'a' " " " -LittleZ = "z" 'z' " " " +StrPtr = $6 ;0-page temp pointer (2 bytes) +Low = $8 ;0-page temp low bound +High = $9 ;0-page temp high bound +CharOut = $fded ;Specific to the Apple II +BigA = "A" ;'A' for normal ascii +BigZ = "Z" ;'Z' " " " +LittleA = "a" ;'a' " " " +LittleZ = "z" ;'z' " " " ;====================================================== .or $0f00 ;------------------------------------------------------ ; The main program ; -main ldx #sTest Point to the test string +main ldx #sTest ;Point to the test string lda /sTest - jsr puts print it to stdout - jsr toUpper convert to UPPER-case - jsr puts print it - jsr toLower convert to lower-case - jmp puts print it and return to caller + jsr puts ;print it to stdout + jsr toUpper ;convert to UPPER-case + jsr puts ;print it + jsr toLower ;convert to lower-case + jmp puts ;print it and return to caller ;------------------------------------------------------ toUpper ldy #LittleA - sty Low set up the flip range + sty Low ;set up the flip range ldy #LittleZ - bne toLow2 return via toLower's tail + bne toLow2 ;return via toLower's tail ;------------------------------------------------------ toLower ldy #BigA - sty Low set up the flip range + sty Low ;set up the flip range ldy #BigZ toLow2 sty High - ; return via fall-thru to flip + ; ;return via fall-thru to flip ;------------------------------------------------------ ; Given a NUL-terminated string at A:X, flip the case ; of any chars in the range [Low..High], inclusive; @@ -54,23 +54,23 @@ toLow2 sty High ; Preserves: A, X ; Trashes: Y ; -flip stx StrPtr init string pointer +flip stx StrPtr ;init string pointer sta StrPtr+1 ldy #0 - pha save A -flip2 lda (StrPtr),y get string char - beq flip5 done if NUL + pha ;save A +flip2 lda (StrPtr),y ;get string char + beq flip5 ;done if NUL cmp Low - bcc flip4 if Low <= char <= High + bcc flip4 ;if Low <= char <= High cmp High beq flip3 bcs flip4 -flip3 eor #$20 then flip the case +flip3 eor #$20 ; then flip the case sta (StrPtr),y -flip4 iny point to next char - bne flip2 loop up to 255 times -flip5 pla restore A - rts return +flip4 iny ;point to next char + bne flip2 ;loop up to 255 times +flip5 pla ;restore A + rts ;return ;------------------------------------------------------ ; Output NUL-terminated string @ A:X; strings longer ; than 256 bytes are truncated there @@ -78,17 +78,17 @@ flip5 pla restore A ; Preserves: A, X ; Trashes: Y ; -puts stx StrPtr init string pointer +puts stx StrPtr ;init string pointer sta StrPtr+1 ldy #0 - pha save A -puts2 lda (StrPtr),y get string char - beq puts3 done if NUL - jsr CharOut output the char - iny point to next char - bne puts2 loop up to 255 times -puts3 pla restore A - rts return + pha ;save A +puts2 lda (StrPtr),y ;get string char + beq puts3 ;done if NUL + jsr CharOut ;output the char + iny ;point to next char + bne puts2 ;loop up to 255 times +puts3 pla ;restore A + rts ;return ;------------------------------------------------------ ; Test String (in '+128' ascii, Apple II style) ; diff --git a/Task/String-case/BASIC/string-case.basic b/Task/String-case/BASIC/string-case-1.basic similarity index 100% rename from Task/String-case/BASIC/string-case.basic rename to Task/String-case/BASIC/string-case-1.basic diff --git a/Task/String-case/BASIC/string-case-2.basic b/Task/String-case/BASIC/string-case-2.basic new file mode 100644 index 0000000000..087ca8fe7f --- /dev/null +++ b/Task/String-case/BASIC/string-case-2.basic @@ -0,0 +1,5 @@ +S$ = "alphaBETA" + +UP$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : UP$ = UP$ + CHR$(C - (C > 96 AND C < 123) * 32) : NEXT I : ? UP$ + +LO$ = "" : FOR I = 1 TO LEN(S$) : C = ASC(MID$(S$, I, 1)) : LO$ = LO$ + CHR$(C + (C > 64 AND C < 91) * 32) : NEXT I : ? LO$ diff --git a/Task/String-case/BASIC/string-case-3.basic b/Task/String-case/BASIC/string-case-3.basic new file mode 100644 index 0000000000..6ee5644f87 --- /dev/null +++ b/Task/String-case/BASIC/string-case-3.basic @@ -0,0 +1,7 @@ + INSTALL @lib$+"STRINGLIB" + + original$ = "alphaBETA" + PRINT "Original: " original$ + PRINT "Lower case: " FN_lower(original$) + PRINT "Upper case: " FN_upper(original$) + PRINT "Title case: " FN_title(original$) diff --git a/Task/String-case/BASIC/string-case-4.basic b/Task/String-case/BASIC/string-case-4.basic new file mode 100644 index 0000000000..da9027da89 --- /dev/null +++ b/Task/String-case/BASIC/string-case-4.basic @@ -0,0 +1,7 @@ +input$ ="alphaBETA" + +print input$ +print upper$( input$) +print lower$( input$) + +end diff --git a/Task/String-case/BASIC/string-case-5.basic b/Task/String-case/BASIC/string-case-5.basic new file mode 100644 index 0000000000..e4c32a7e33 --- /dev/null +++ b/Task/String-case/BASIC/string-case-5.basic @@ -0,0 +1,5 @@ +string s="alphaBETA" + +print lcase(s) " "+ + ucase(s) " "+ + ucase(left(s,1))+mid(s,2) 'capitalised diff --git a/Task/String-case/BASIC/string-case-6.basic b/Task/String-case/BASIC/string-case-6.basic new file mode 100644 index 0000000000..c9d40658ff --- /dev/null +++ b/Task/String-case/BASIC/string-case-6.basic @@ -0,0 +1,3 @@ +s$ = "alphaBETA" +upper$ = UCase(s$) ;uppercase +lower$ = LCase(s$) ;lowercase diff --git a/Task/String-case/BASIC/string-case-7.basic b/Task/String-case/BASIC/string-case-7.basic new file mode 100644 index 0000000000..623adb7125 --- /dev/null +++ b/Task/String-case/BASIC/string-case-7.basic @@ -0,0 +1,5 @@ +a$ ="alphaBETA" + +print a$ '=> alphaBETA +print upper$(a$) '=> ALPHABETA +print lower$(a$) '=> alphabeta diff --git a/Task/String-case/BASIC/string-case-8.basic b/Task/String-case/BASIC/string-case-8.basic new file mode 100644 index 0000000000..10cde0efea --- /dev/null +++ b/Task/String-case/BASIC/string-case-8.basic @@ -0,0 +1,8 @@ +' Define 's' +Dim s AS String = "alphaBETA" + +' Change 's' to Upper Case. +s = s.ToUpper() + +' Change 's' to Lower Case. +s = s.ToLower() diff --git a/Task/String-case/BASIC/string-case-9.basic b/Task/String-case/BASIC/string-case-9.basic new file mode 100644 index 0000000000..7306e81b4b --- /dev/null +++ b/Task/String-case/BASIC/string-case-9.basic @@ -0,0 +1,18 @@ +:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9 +:"abcdefghijklmnopqrstuvwxyz"→Str0 +:Input ">",Str1 +:":"+Str1+":"→Str1 +:Prompt U +:If U:Then +:For(I,2,length(Str1)) +:If inString(Str0,sub(Str1,I,1)) and sub(Str1,I,1)≠":" +:sub(Str1,1,I-1)+sub(Str9,inString(Str0,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1 +:End +:Else +:For(I,2,length(Str1)) +:If inString(Str9,sub(Str1,I,1)) and sub(Str1,I,1)≠":" +:sub(Str1,1,I-1)+sub(Str0,inString(Str9,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1 +:End +:End +:sub(Str1,2,length(Str1)-2)→Str1 +:Pause Str1 diff --git a/Task/String-case/GAP/string-case.gap b/Task/String-case/GAP/string-case.gap new file mode 100644 index 0000000000..33d4c1c089 --- /dev/null +++ b/Task/String-case/GAP/string-case.gap @@ -0,0 +1,2 @@ +LowercaseString("alphaBETA"); +UppercaseString("alphaBETA"); diff --git a/Task/String-case/Go/string-case.go b/Task/String-case/Go/string-case.go index b687ce429c..3a2f98bfbd 100644 --- a/Task/String-case/Go/string-case.go +++ b/Task/String-case/Go/string-case.go @@ -10,16 +10,19 @@ import ( func main() { show("alphaBETA") show("alpha BETA") - show("DŽLjnj") // should render similar to DZLjnj + // Three digraphs that should render similar to DZ, Lj, and nj. + show("DŽLjnj") + // Unicode apostrophe in third word. + show("o'hare O'HARE o’hare don't") } func show(s string) { - fmt.Println("\nstring: ", s, "len:", utf8.RuneCountInString(s)) + fmt.Println("\nstring: ", + s, " len:", utf8.RuneCountInString(s), "runes") // DZLjnj fmt.Println("All upper case: ", strings.ToUpper(s)) // DZLJNJ fmt.Println("All lower case: ", strings.ToLower(s)) // dzljnj fmt.Println("All title case: ", strings.ToTitle(s)) // DzLjNj - // notice Title() only modifies first letters of words - // non-first letters keep their case. - fmt.Println("Title words: ", strings.Title(s)) // Dzljnj - fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) + fmt.Println("Title words: ", strings.Title(s)) // Dzljnj + fmt.Println("Swapping case: ", // DzLjNJ + strings.Map(unicode.SimpleFold, s)) } diff --git a/Task/String-case/Julia/string-case.julia b/Task/String-case/Julia/string-case.julia new file mode 100644 index 0000000000..c306d91570 --- /dev/null +++ b/Task/String-case/Julia/string-case.julia @@ -0,0 +1,5 @@ +julia> uppercase("alphaBETA") +"ALPHABETA" + +julia> lowercase("alphaBETA") +"alphabeta" diff --git a/Task/String-case/VBA/string-case.vba b/Task/String-case/VBA/string-case.vba new file mode 100644 index 0000000000..173dd959c7 --- /dev/null +++ b/Task/String-case/VBA/string-case.vba @@ -0,0 +1,7 @@ +Function StringCase() +Dim s As String +s = "alphaBETA" +Debug.Print UCase(s) +Debug.Print LCase(s) +Debug.Print WorksheetFunction.Proper(s) +End Function diff --git a/Task/String-comparison/Clipper/string-comparison-1.clipper b/Task/String-comparison/Clipper/string-comparison-1.clipper new file mode 100644 index 0000000000..c28bd10416 --- /dev/null +++ b/Task/String-comparison/Clipper/string-comparison-1.clipper @@ -0,0 +1,12 @@ + IF s1 == s2 + ? "The strings are equal" + ENDIF + IF .NOT. (s1 == s2) + ? "The strings are not equal" + ENDIF + IF s1 > s2 + ? "s2 is lexically ordered before than s1" + ENDIF + IF s1 < s2 + ? "s2 is lexically ordered after than s1" + ENDIF diff --git a/Task/String-comparison/Clipper/string-comparison-2.clipper b/Task/String-comparison/Clipper/string-comparison-2.clipper new file mode 100644 index 0000000000..791a1d9cd1 --- /dev/null +++ b/Task/String-comparison/Clipper/string-comparison-2.clipper @@ -0,0 +1,3 @@ + IF Upper(s1) == Upper(s2) + ? "The strings are equal" + ENDIF diff --git a/Task/String-comparison/REXX/string-comparison-1.rexx b/Task/String-comparison/REXX/string-comparison-1.rexx index 8b9934678e..be0b864303 100644 --- a/Task/String-comparison/REXX/string-comparison-1.rexx +++ b/Task/String-comparison/REXX/string-comparison-1.rexx @@ -1,17 +1,37 @@ -animal = 'dog' -if animal = 'cat' then say animal "is lexically equal to cat" -if animal \= 'cat' then say animal "is not lexically equal cat" -if animal > 'cat' then say animal "is lexically higher than cat" -if animal < 'cat' then say animal "is lexically lower than cat" -if animal >= 'cat' then say animal "is not lexically lower than cat" -if animal <= 'cat' then say animal "is not lexically higher than cat" +/*REXX program shows different ways to compare two character strings.*/ +say 'This is an ' word('ASCII EBCDIC', 1+(1=='f1')) ' system.' +say + cat = 'cat' + animal = 'dog' +if animal = cat then say $(animal) "is lexically equal to" $(cat) +if animal \= cat then say $(animal) "is not lexically equal to" $(cat) +if animal > cat then say $(animal) "is lexically higher than" $(cat) +if animal < cat then say $(animal) "is lexically lower than" $(cat) +if animal > cat then say $(animal) "is not lexically lower than" $(cat) +if animal < cat then say $(animal) "is not lexically higher than" $(cat) - /*The above comparative operators do not consider */ - /*leading and trailing whitespace when making comparisons.*/ + /*──── [↑] The above comparative operators don't */ + /*────consider any leading and/or trailing white- */ + /*────space when making comparisons, but the case */ + /*────is honored (uppercase, lowercase). */ -if ' cat ' = 'cat' then say "this will print because whitespace is stripped" +fatcat=' cat ' /*pad the cat with leading and trailing blanks. */ +if fatcat = cat then say $(fatcat) " is equal to" $(cat) - /*To consider any whitespace in a comparison, */ - /*we need to use strict comparative operators.*/ + /*────To consider any whitespace in a comparison, */ + /*────we need to use strict comparative operators.*/ -if ' cat ' == 'cat' then say "this will not print because comparison is strict" +if fatcat == cat then say $(fatcat) "is strictly equal to" $(cat) + + /*────To perform caseless comparisons, the easiest*/ + /*────method would be to uppercase a copy of both */ + /*────operands. Uppercasing is only done for the */ + /*────Latin (or Roman) alphabet in REXX. [↓] */ +kat='cAt' +if caselessComp(cat,kat) then say $(cat) 'and' $(kat) "are equal caseless" +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────$ subroutine────────────────────────*/ +$: return '──►'arg(1)'◄──' /*bracket the string with ──►α◄──*/ +/*──────────────────────────────────CASELESSCOMP subroutine─────────────*/ +caselessComp: procedure; arg a,b /*ARG uppercases the A & B args.*/ + return a==b /*if exactly equal, return 1. */ diff --git a/Task/String-comparison/Ruby/string-comparison.rb b/Task/String-comparison/Ruby/string-comparison.rb index 873936a923..6687d8d920 100644 --- a/Task/String-comparison/Ruby/string-comparison.rb +++ b/Task/String-comparison/Ruby/string-comparison.rb @@ -1,5 +1,5 @@ method_names = [:==,:!=, :>, :>=, :<, :<=, :<=>, :casecmp] -[["YUP", "YUP"], ["YUP", "Yup"], ["bot","bat"],["zz", "aaa"]].each do |(str1, str2)| - method_names.each{|m| print str1," ", m," ", str2,"\t", str1.send(m, str2),"\n"} +[["YUP", "YUP"], ["YUP", "Yup"], ["bot","bat"], ["aaa", "zz"]].each do |str1, str2| + method_names.each{|m| puts "%s %s %s\t%s" % [str1, m, str2, str1.send(m, str2)]} puts end diff --git a/Task/String-concatenation/BASIC/string-concatenation-2.basic b/Task/String-concatenation/BASIC/string-concatenation-2.basic index 43cff30ba9..7be32e9836 100644 --- a/Task/String-concatenation/BASIC/string-concatenation-2.basic +++ b/Task/String-concatenation/BASIC/string-concatenation-2.basic @@ -1,4 +1,4 @@ - stringvar1$ = "Hello," - stringvar2$ = stringvar1$ + " world!" - PRINT "Variable 1 is """ stringvar1$ """" - PRINT "Variable 2 is """ stringvar2$ """" +S$ = "HELLO" +PRINT S$;" LITERAL" :REM OR S$ + " LITERAL" +S2$ = S$ + " LITERAL" +PRINT S2$ diff --git a/Task/String-concatenation/BASIC/string-concatenation-3.basic b/Task/String-concatenation/BASIC/string-concatenation-3.basic index e71db46ad2..43cff30ba9 100644 --- a/Task/String-concatenation/BASIC/string-concatenation-3.basic +++ b/Task/String-concatenation/BASIC/string-concatenation-3.basic @@ -1,3 +1,4 @@ -10 LET s$="Hello" -20 LET s$=s$+" World!" -30 PRINT s$ + stringvar1$ = "Hello," + stringvar2$ = stringvar1$ + " world!" + PRINT "Variable 1 is """ stringvar1$ """" + PRINT "Variable 2 is """ stringvar2$ """" diff --git a/Task/String-concatenation/BASIC/string-concatenation-4.basic b/Task/String-concatenation/BASIC/string-concatenation-4.basic new file mode 100644 index 0000000000..e71db46ad2 --- /dev/null +++ b/Task/String-concatenation/BASIC/string-concatenation-4.basic @@ -0,0 +1,3 @@ +10 LET s$="Hello" +20 LET s$=s$+" World!" +30 PRINT s$ diff --git a/Task/String-concatenation/Deja-Vu/string-concatenation.djv b/Task/String-concatenation/Deja-Vu/string-concatenation.djv new file mode 100644 index 0000000000..94369ca53d --- /dev/null +++ b/Task/String-concatenation/Deja-Vu/string-concatenation.djv @@ -0,0 +1,3 @@ +local :s1 "hello" +local :s2 concat( s1 ", world" ) +!print s2 diff --git a/Task/String-concatenation/Julia/string-concatenation.julia b/Task/String-concatenation/Julia/string-concatenation.julia new file mode 100644 index 0000000000..7b6336c7a6 --- /dev/null +++ b/Task/String-concatenation/Julia/string-concatenation.julia @@ -0,0 +1,2 @@ +s = "hello" +println(s + " there!") diff --git a/Task/String-concatenation/Ruby/string-concatenation.rb b/Task/String-concatenation/Ruby/string-concatenation.rb index b12f3bb23c..8f1d8feb63 100644 --- a/Task/String-concatenation/Ruby/string-concatenation.rb +++ b/Task/String-concatenation/Ruby/string-concatenation.rb @@ -1,5 +1,10 @@ s = "hello" -puts s + " literal" +p s + " literal" #=> "hello literal" s1 = s + " literal" -puts s1 +p s1 #=> "hello literal" s1 << " another" # append to s1 +p s1 #=> "hello literal another" + +s = "hello" +p s.concat(" literal") #=> "hello literal" +p s #=> "hello literal" diff --git a/Task/String-concatenation/Scala/string-concatenation.scala b/Task/String-concatenation/Scala/string-concatenation.scala index 06438ffd27..ac09b63ccc 100644 --- a/Task/String-concatenation/Scala/string-concatenation.scala +++ b/Task/String-concatenation/Scala/string-concatenation.scala @@ -1,3 +1,5 @@ -val s = "hello" -val s2 = s + " world" -println(s2) + val s = "hello" //> s : String = hello + val s2 = s + " world" //> s2 : String = hello world + val f2 = () => " !" //> f2 : () => String = + + println(s2 + f2()) //> hello world ! diff --git a/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk b/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk index 47442c5bb3..1bc3fcbd2d 100644 --- a/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk +++ b/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk @@ -1,6 +1,6 @@ #!/usr/bin/awk -f BEGIN { - str="Mary had a # lamb; # and blue."; - gsub(/#/,"big",str); - print str; + str="Mary had a # lamb." + gsub(/#/, "little", str) + print str } diff --git a/Task/String-interpolation--included-/Julia/string-interpolation--included-.julia b/Task/String-interpolation--included-/Julia/string-interpolation--included-.julia new file mode 100644 index 0000000000..ef6c0cf1fa --- /dev/null +++ b/Task/String-interpolation--included-/Julia/string-interpolation--included-.julia @@ -0,0 +1,2 @@ +X = "little" +"Mary had a $X lamb" diff --git a/Task/String-length/ActionScript/string-length-1.as b/Task/String-length/ActionScript/string-length-1.as new file mode 100644 index 0000000000..331e44cd2d --- /dev/null +++ b/Task/String-length/ActionScript/string-length-1.as @@ -0,0 +1,34 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + import flash.utils.ByteArray; + + public class StringByteLength extends Sprite { + + public function StringByteLength() { + if ( stage ) _init(); + else addEventListener(Event.ADDED_TO_STAGE, _init); + } + + private function _init(e:Event = null):void { + var s1:String = "The quick brown fox jumps over the lazy dog"; + var s2:String = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + var s3:String = "José"; + + var b:ByteArray = new ByteArray(); + b.writeUTFBytes(s1); + trace(b.length); // 43 + + b.clear(); + b.writeUTFBytes(s2); + trace(b.length); // 28 + + b.clear(); + b.writeUTFBytes(s3); + trace(b.length); // 5 + } + + } + +} diff --git a/Task/String-length/ActionScript/string-length-2.as b/Task/String-length/ActionScript/string-length-2.as new file mode 100644 index 0000000000..a05c91bc3c --- /dev/null +++ b/Task/String-length/ActionScript/string-length-2.as @@ -0,0 +1,4 @@ +var s1:String = "The quick brown fox jumps over the lazy dog"; +var s2:String = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; +var s3:String = "José"; +trace(s1.length, s2.length, s3.length); // 43, 14, 4 diff --git a/Task/String-length/ActionScript/string-length.as b/Task/String-length/ActionScript/string-length.as deleted file mode 100644 index ec9270ff1f..0000000000 --- a/Task/String-length/ActionScript/string-length.as +++ /dev/null @@ -1 +0,0 @@ -myStrVar.length() diff --git a/Task/String-length/COBOL/string-length-1.cobol b/Task/String-length/COBOL/string-length-1.cobol new file mode 100644 index 0000000000..bcc3c28aa7 --- /dev/null +++ b/Task/String-length/COBOL/string-length-1.cobol @@ -0,0 +1 @@ +FUNCTION BYTE-LENGTH(str) diff --git a/Task/String-length/COBOL/string-length-2.cobol b/Task/String-length/COBOL/string-length-2.cobol new file mode 100644 index 0000000000..cbad0021b5 --- /dev/null +++ b/Task/String-length/COBOL/string-length-2.cobol @@ -0,0 +1 @@ +LENGTH OF str diff --git a/Task/String-length/COBOL/string-length-3.cobol b/Task/String-length/COBOL/string-length-3.cobol new file mode 100644 index 0000000000..b6ae88a20d --- /dev/null +++ b/Task/String-length/COBOL/string-length-3.cobol @@ -0,0 +1 @@ +FUNCTION LENGTH-AN(str) diff --git a/Task/String-length/COBOL/string-length-4.cobol b/Task/String-length/COBOL/string-length-4.cobol new file mode 100644 index 0000000000..bf0be62e30 --- /dev/null +++ b/Task/String-length/COBOL/string-length-4.cobol @@ -0,0 +1 @@ +FUNCTION LENGTH(str) diff --git a/Task/String-length/Clojure/string-length-1.clj b/Task/String-length/Clojure/string-length-1.clj index 6388a4f936..fdf5f19e51 100644 --- a/Task/String-length/Clojure/string-length-1.clj +++ b/Task/String-length/Clojure/string-length-1.clj @@ -1,2 +1,8 @@ -(count (.getBytes "Hello, world!")) ; 13 bytes -(count (.getBytes "π")) ; two bytes +(def utf-8-octet-length #(-> % (.getBytes "UTF-8") count)) +(map utf-8-octet-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (7 28 14) + +(def utf-16-octet-length (comp (partial * 2) count)) +(map utf-16-octet-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (10 28 18) + +(def code-unit-length count) +(map code-unit-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (5 14 9) diff --git a/Task/String-length/Clojure/string-length-2.clj b/Task/String-length/Clojure/string-length-2.clj index a7fa06fd2a..92dad1ae33 100644 --- a/Task/String-length/Clojure/string-length-2.clj +++ b/Task/String-length/Clojure/string-length-2.clj @@ -1 +1,2 @@ -(count "Hello, world!") +(def character-length #(.codePointCount % 0 (count %))) +(map character-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (5 7 9) diff --git a/Task/String-length/Clojure/string-length-3.clj b/Task/String-length/Clojure/string-length-3.clj new file mode 100644 index 0000000000..490b85db7d --- /dev/null +++ b/Task/String-length/Clojure/string-length-3.clj @@ -0,0 +1,8 @@ +(def grapheme-length + #(->> (doto (java.text.BreakIterator/getCharacterInstance) + (.setText %)) + (partial (memfn next)) + repeatedly + (take-while (partial not= java.text.BreakIterator/DONE)) + count)) +(map grapheme-length ["møøse" "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" "J\u0332o\u0332s\u0332e\u0301\u0332"]) ; (5 7 4) diff --git a/Task/String-length/Deja-Vu/string-length-1.djv b/Task/String-length/Deja-Vu/string-length-1.djv new file mode 100644 index 0000000000..fa1b942606 --- /dev/null +++ b/Task/String-length/Deja-Vu/string-length-1.djv @@ -0,0 +1,2 @@ +!. len !encode!utf-8 "møøse" +!. len !encode!utf-8 "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" diff --git a/Task/String-length/Deja-Vu/string-length-2.djv b/Task/String-length/Deja-Vu/string-length-2.djv new file mode 100644 index 0000000000..beecee7183 --- /dev/null +++ b/Task/String-length/Deja-Vu/string-length-2.djv @@ -0,0 +1,2 @@ +!. len "møøse" +!. len "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" diff --git a/Task/String-length/Julia/string-length-1.julia b/Task/String-length/Julia/string-length-1.julia new file mode 100644 index 0000000000..795cd87aef --- /dev/null +++ b/Task/String-length/Julia/string-length-1.julia @@ -0,0 +1,2 @@ +sizeof("Hello, world!") # gives 13 +sizeof("Hellö, wørld!") # gives 15 diff --git a/Task/String-length/Julia/string-length-2.julia b/Task/String-length/Julia/string-length-2.julia new file mode 100644 index 0000000000..515d4c3cef --- /dev/null +++ b/Task/String-length/Julia/string-length-2.julia @@ -0,0 +1,2 @@ +length("Hello, world!") # gives 13 +length("Hellö, wørld!") # gives 13 diff --git a/Task/String-length/PL-I/string-length.pli b/Task/String-length/PL-I/string-length.pli index 7f440f0205..d0942af6fb 100644 --- a/Task/String-length/PL-I/string-length.pli +++ b/Task/String-length/PL-I/string-length.pli @@ -4,4 +4,4 @@ put skip list ('Byte length=', size(WS)); declare SM graphic (13) initial ('Hello world'); put ('Character length=', length(SM)); -put skip list ('Byte length=', size(trim(SM)); +put skip list ('Byte length=', size(trim(SM))); diff --git a/Task/String-length/Python/string-length-1.py b/Task/String-length/Python/string-length-1.py index 374ea95e04..8935dfa5cb 100644 --- a/Task/String-length/Python/string-length-1.py +++ b/Task/String-length/Python/string-length-1.py @@ -1,6 +1,2 @@ -#!/bin/env python -# -*- coding: UTF-8 -*- -s = u"møøse" -assert len(s) == 5 -assert len(s.encode('UTF-8')) == 7 -assert len(s.encode('UTF-16')) == 12 # The extra character is probably a leading Unicode byte-order mark (BOM). +print len('ascii') +# 5 diff --git a/Task/String-length/Python/string-length-10.py b/Task/String-length/Python/string-length-10.py new file mode 100644 index 0000000000..d4376f23e1 --- /dev/null +++ b/Task/String-length/Python/string-length-10.py @@ -0,0 +1,2 @@ +print(len("𝔘𝔫𝔦𝔠𝔬𝔡𝔢")) +# 7 diff --git a/Task/String-length/Python/string-length-11.py b/Task/String-length/Python/string-length-11.py new file mode 100644 index 0000000000..3610912849 --- /dev/null +++ b/Task/String-length/Python/string-length-11.py @@ -0,0 +1,2 @@ +import sys +sys.maxunicode # 1114111 on a wide build, 65535 on a narrow build diff --git a/Task/String-length/Python/string-length-12.py b/Task/String-length/Python/string-length-12.py new file mode 100644 index 0000000000..0794fea909 --- /dev/null +++ b/Task/String-length/Python/string-length-12.py @@ -0,0 +1,4 @@ +print(len('ascii')) +# 5 +print(len('\u05d0')) # the letter Alef as unicode literal +# 1 diff --git a/Task/String-length/Python/string-length-13.py b/Task/String-length/Python/string-length-13.py new file mode 100644 index 0000000000..dbbb129190 --- /dev/null +++ b/Task/String-length/Python/string-length-13.py @@ -0,0 +1,2 @@ +print(len(b'\xd7\x90'.decode('utf-8'))) # Alef encoded as utf-8 byte sequence +# 1 diff --git a/Task/String-length/Python/string-length-14.py b/Task/String-length/Python/string-length-14.py new file mode 100644 index 0000000000..51a8075166 --- /dev/null +++ b/Task/String-length/Python/string-length-14.py @@ -0,0 +1,2 @@ +print(hex(sys.maxunicode), len(unichr(0x1F4A9))) +# ('0x10ffff', 1) diff --git a/Task/String-length/Python/string-length-15.py b/Task/String-length/Python/string-length-15.py new file mode 100644 index 0000000000..0afedf0338 --- /dev/null +++ b/Task/String-length/Python/string-length-15.py @@ -0,0 +1,2 @@ +print(hex(sys.maxunicode), len(unichr(0x1F4A9))) +# ('0xffff', 2) diff --git a/Task/String-length/Python/string-length-2.py b/Task/String-length/Python/string-length-2.py index e33b1cec01..c6bbdca6d3 100644 --- a/Task/String-length/Python/string-length-2.py +++ b/Task/String-length/Python/string-length-2.py @@ -1,6 +1,5 @@ -#!/bin/env python -# -*- coding: UTF-8 -*- -s = "møøse" -assert len(s) == 5 -assert len(s.encode('UTF-8')) == 7 -assert len(s.encode('UTF-16')) == 12 # The extra character is probably a leading Unicode byte-order mark (BOM). +# The letter Alef +print len(u'\u05d0'.encode('utf-8')) +# 2 +print len(u'\u05d0'.encode('iso-8859-8')) +# 1 diff --git a/Task/String-length/Python/string-length-3.py b/Task/String-length/Python/string-length-3.py new file mode 100644 index 0000000000..60fb7bbda6 --- /dev/null +++ b/Task/String-length/Python/string-length-3.py @@ -0,0 +1,6 @@ +#!/bin/env python +# -*- coding: UTF-8 -*- +s = u"møøse" +assert len(s) == 5 +assert len(s.encode('UTF-8')) == 7 +assert len(s.encode('UTF-16-BE')) == 10 # There are 3 different UTF-16 encodings: LE and BE are little endian and big endian respectively, the third one (without suffix) adds 2 extra leading bytes: the byte-order mark (BOM). diff --git a/Task/String-length/Python/string-length-4.py b/Task/String-length/Python/string-length-4.py new file mode 100644 index 0000000000..3610912849 --- /dev/null +++ b/Task/String-length/Python/string-length-4.py @@ -0,0 +1,2 @@ +import sys +sys.maxunicode # 1114111 on a wide build, 65535 on a narrow build diff --git a/Task/String-length/Python/string-length-5.py b/Task/String-length/Python/string-length-5.py new file mode 100644 index 0000000000..12a21f6ad6 --- /dev/null +++ b/Task/String-length/Python/string-length-5.py @@ -0,0 +1,8 @@ +print len('ascii') +# 5 +print len(u'\u05d0') # the letter Alef as unicode literal +# 1 +print len('\xd7\x90'.decode('utf-8')) # Same encoded as utf-8 string +# 1 +print hex(sys.maxunicode), len(unichr(0x1F4A9)) +# ('0x10ffff', 1) diff --git a/Task/String-length/Python/string-length-6.py b/Task/String-length/Python/string-length-6.py new file mode 100644 index 0000000000..5f3032e599 --- /dev/null +++ b/Task/String-length/Python/string-length-6.py @@ -0,0 +1,2 @@ +print hex(sys.maxunicode), len(unichr(0x1F4A9)) +# ('0xffff', 2) diff --git a/Task/String-length/Python/string-length-7.py b/Task/String-length/Python/string-length-7.py new file mode 100644 index 0000000000..a7bccb53db --- /dev/null +++ b/Task/String-length/Python/string-length-7.py @@ -0,0 +1,2 @@ +print(len(b'Hello, World!')) +# 13 diff --git a/Task/String-length/Python/string-length-8.py b/Task/String-length/Python/string-length-8.py new file mode 100644 index 0000000000..514b7827d4 --- /dev/null +++ b/Task/String-length/Python/string-length-8.py @@ -0,0 +1,5 @@ +# The letter Alef +print(len('\u05d0'.encode())) # the default encoding is utf-8 in Python3 +# 2 +print(len('\u05d0'.encode('iso-8859-8'))) +# 1 diff --git a/Task/String-length/Python/string-length-9.py b/Task/String-length/Python/string-length-9.py new file mode 100644 index 0000000000..ef265453a4 --- /dev/null +++ b/Task/String-length/Python/string-length-9.py @@ -0,0 +1,9 @@ +#!/bin/env python +# -*- coding: UTF-8 -*- +s = "møøse" +assert len(s) == 5 +assert len(s.encode('UTF-8')) == 7 +assert len(s.encode('UTF-16-BE')) == 10 # There are 3 different UTF-16 encodings: LE and BE are little endian and big endian respectively, the third one (without suffix) adds 2 extra leading bytes: the byte-order mark (BOM). +u="𝔘𝔫𝔦𝔠𝔬𝔡𝔢" +assert len(u.encode()) == 28 +assert len(u.encode('UTF-16-BE')) == 28 diff --git a/Task/Strip-a-set-of-characters-from-a-string/VBA/strip-a-set-of-characters-from-a-string.vba b/Task/Strip-a-set-of-characters-from-a-string/VBA/strip-a-set-of-characters-from-a-string.vba new file mode 100644 index 0000000000..7eca8524d8 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/VBA/strip-a-set-of-characters-from-a-string.vba @@ -0,0 +1,12 @@ +Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) +Dim i As Integer, stReplace As String + If bSpace = True Then + stReplace = " " + Else + stReplace = "" + End If + For i = 1 To Len(stStripChars) + stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) + Next i + StripChars = stString +End Function diff --git a/Task/Strip-block-comments/AutoHotkey/strip-block-comments.ahk b/Task/Strip-block-comments/AutoHotkey/strip-block-comments.ahk new file mode 100644 index 0000000000..44c5e453e7 --- /dev/null +++ b/Task/Strip-block-comments/AutoHotkey/strip-block-comments.ahk @@ -0,0 +1,27 @@ +code = +( + /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +) +;Open-Close Comment delimiters + openC:="/*" + closeC:="*/" +;Make it "Regex-Safe" + openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0") + closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0") +;Display final result + MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")") diff --git a/Task/Strip-comments-from-a-string/00DESCRIPTION b/Task/Strip-comments-from-a-string/00DESCRIPTION index 76ecbb9da8..5c1187161e 100644 --- a/Task/Strip-comments-from-a-string/00DESCRIPTION +++ b/Task/Strip-comments-from-a-string/00DESCRIPTION @@ -2,7 +2,7 @@ The task is to remove text that follow any of a set of comment markers, (in thes '''Whitespace debacle:''' There is some confusion about whether to remove any whitespace from the input line. As of [http://rosettacode.org/mw/index.php?title=Strip_comments_from_a_string&oldid=119409 2 September 2011], at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason. '''Please discuss this issue at [[{{TALKPAGENAME}}]].''' -* From [http://rosettacode.org/mw/index.php?title=Strip_comments_from_a_string&oldid=103978 29 March 2011], this task required that: ''"The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or training whitespace before being produced as a result."'' The task had 28 languages, which did not all meet this new requirement. +* From [http://rosettacode.org/mw/index.php?title=Strip_comments_from_a_string&oldid=103978 29 March 2011], this task required that: ''"The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result."'' The task had 28 languages, which did not all meet this new requirement. * From [http://rosettacode.org/mw/index.php?title=Strip_comments_from_a_string&oldid=103978 28 March 2011], this task required that: ''"Whitespace before the comment marker should be removed."'' * From [http://rosettacode.org/mw/index.php?title=Strip_comments_from_a_string&offset=20101206204307&action=history 30 October 2010], this task did not specify whether or not to remove whitespace. diff --git a/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl b/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl new file mode 100644 index 0000000000..fb688ae1a4 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl @@ -0,0 +1,16 @@ +-module( strip_comments_from_string ). + +-export( [task/0] ). + +task() -> + io:fwrite( "~s~n", [keep_until_comment("apples, pears and bananas")] ), + io:fwrite( "~s~n", [keep_until_comment("apples, pears # and bananas")] ), + io:fwrite( "~s~n", [keep_until_comment("apples, pears ; and bananas")] ). + + + +keep_until_comment( String ) -> lists:takewhile( fun not_comment/1, String ). + +not_comment( $# ) -> false; +not_comment( $; ) -> false; +not_comment( _ ) -> true. diff --git a/Task/Strip-comments-from-a-string/Groovy/strip-comments-from-a-string-1.groovy b/Task/Strip-comments-from-a-string/Groovy/strip-comments-from-a-string-1.groovy new file mode 100644 index 0000000000..75457e65b8 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Groovy/strip-comments-from-a-string-1.groovy @@ -0,0 +1 @@ +def stripComments = { it.replaceAll(/\s*[#;].*$/, '') } diff --git a/Task/Strip-comments-from-a-string/Groovy/strip-comments-from-a-string-2.groovy b/Task/Strip-comments-from-a-string/Groovy/strip-comments-from-a-string-2.groovy new file mode 100644 index 0000000000..5ccdc4df3d --- /dev/null +++ b/Task/Strip-comments-from-a-string/Groovy/strip-comments-from-a-string-2.groovy @@ -0,0 +1,2 @@ +assert 'apples, pears' == stripComments('apples, pears # and bananas') +assert 'apples, pears' == stripComments('apples, pears ; and bananas') diff --git a/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb b/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb index 5f30d04365..4dcad84e75 100644 --- a/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb +++ b/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb @@ -1,10 +1,19 @@ class String def strip_comment( markers = ['#',';'] ) re = Regexp.union( markers ) # construct a regular expression which will match any of the markers - self[0, self =~ re] # slice the string where the regular expression matches, and return it. + if index = (self =~ re) + self[0, index].rstrip # slice the string where the regular expression matches, and return it. + else + rstrip + end end end -puts 'apples, pears # and bananas'.strip_comment +p 'apples, pears # and bananas'.strip_comment str = 'apples, pears ; and bananas' -puts str.strip_comment +p str.strip_comment +str = 'apples, pears and bananas ' +p str.strip_comment +p str.strip_comment('and') +p " \t \n ;".strip_comment +p "".strip_comment diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Erlang/strip-control-codes-and-extended-characters-from-a-string.erl b/Task/Strip-control-codes-and-extended-characters-from-a-string/Erlang/strip-control-codes-and-extended-characters-from-a-string.erl new file mode 100644 index 0000000000..ebf3a7d7f1 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Erlang/strip-control-codes-and-extended-characters-from-a-string.erl @@ -0,0 +1,18 @@ +-module( strip_control_codes ). + +-export( [is_not_control_code/1, is_not_control_code_nor_extended_character/1, task/0] ). + +is_not_control_code( C ) when C > 127 -> true; +is_not_control_code( C ) when C < 32; C =:= 127 -> false; +is_not_control_code( _C ) -> true. + +is_not_control_code_nor_extended_character( C ) when C > 127 -> false; +is_not_control_code_nor_extended_character( C ) -> is_not_control_code( C ). + +task() -> + String = lists:seq( 0, 255 ), + io:fwrite( "String (~p characters): ~s~n", [erlang:length(String), String] ), + String_without_cc = lists:filter( fun is_not_control_code/1, String ), + io:fwrite( "String without control codes (~p characters): ~s~n", [erlang:length(String_without_cc), String_without_cc] ), + String_without_cc_nor_ec = lists:filter( fun is_not_control_code_nor_extended_character/1, String ), + io:fwrite( "String without control codes nor extended characters (~p characters): ~s~n", [erlang:length(String_without_cc_nor_ec), String_without_cc_nor_ec] ). diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/TXR/strip-control-codes-and-extended-characters-from-a-string.txr b/Task/Strip-control-codes-and-extended-characters-from-a-string/TXR/strip-control-codes-and-extended-characters-from-a-string.txr new file mode 100644 index 0000000000..a5e53d76a8 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/TXR/strip-control-codes-and-extended-characters-from-a-string.txr @@ -0,0 +1,6 @@ +@(do + (defun strip-controls (str) + (regsub #/[\x0-\x1F\x7F]+/ "" str)) + + (defun strip-controls-and-extended (str) + (regsub #/[^\x20-\x7F]+/ "" str))) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail.cobol b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail.cobol new file mode 100644 index 0000000000..b746c0692b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail.cobol @@ -0,0 +1,3 @@ +DISPLAY "'" FUNCTION TRIM(str, LEADING) "'" +DISPLAY "'" FUNCTION TRIM(str, TRAILING) "'" +DISPLAY "'" FUNCTION TRIM(str) "'" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia b/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia index ee2f3c1eaf..37da03a88b 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia @@ -1,11 +1,11 @@ -strip(string[, chars]) -Return string with any leading and trailing whitespace removed. If a string chars is provided, instead remove characters contained in that string. +julia> s = " \t \r \n String with spaces \t \r \n " +" \t \r \n String with spaces \t \r \n " -lstrip(string[, chars]) -Return string with any leading whitespace removed. If a string chars is provided, instead remove characters contained in that string. +julia> lstrip(s) +"String with spaces \t \r \n " -rstrip(string[, chars]) -Return string with any trailing whitespace removed. If a string chars is provided, instead remove characters contained in that string. +julia> rstrip(s) +" \t \r \n String with spaces" -chomp(string) -Remove a trailing newline from a string +julia> strip(s) +"String with spaces" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb index bbe9078692..580562f1bf 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb @@ -1,2 +1,5 @@ -s = " \t\v\r\n\ffoo \t\v\r\n\f" -p [s, s.lstrip, s.rstrip, s.strip] +s = " \t\v\r\n\ffoo bar \t\v\r\n\f" +p s +p s.lstrip # remove leading whitespaces +p s.rstrip # remove trailing whitespaces +p s.strip # remove both leading and trailing whitespace diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala b/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala index d9c03e1dff..a9425e7c35 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala @@ -1,13 +1,16 @@ -def trimLeft(str:String)=str dropWhile (_.isWhitespace) -def trimRight(str:String)=str take (str.lastIndexWhere(!_.isWhitespace) + 1) -def trimRight2(str:String)=trimLeft(str reverse) reverse -def trim(str:String)=str trim +def trimLeft(str: String) = str dropWhile(_.isWhitespace) + +def trimRight(str: String) = str take (str.lastIndexWhere(!_.isWhitespace) + 1) + +def trimRight2(str: String) = trimLeft(str reverse) reverse + +def trim(str: String) = str trim -def testTrim()={ - val str=" \u001F String with spaces \t \n \r " - println("original : |"+str+"|") - println("trimLeft : |"+trimLeft(str)+"|") - println("trimRight : |"+trimRight(str)+"|") - println("trimRight2: |"+trimRight2(str)+"|") - println("trim : |"+trim(str)+"|") +def testTrim() = { + val str = " \u001F String with spaces \t \n \r " + println("original : |" + str + "|") + println("trimLeft : |" + trimLeft(str) + "|") + println("trimRight : |" + trimRight(str) + "|") + println("trimRight2: |" + trimRight2(str) + "|") + println("trim : |" + trim(str) + "|") } diff --git a/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia b/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia index 4d686d2928..4e2f322f50 100644 --- a/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia +++ b/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia @@ -1,8 +1,8 @@ -julia> "My String"[2:end] #without first character +julia> "My String"[2:end] # without first character "y String" -julia> "My String"[1:end-1] #without last character +julia> "My String"[1:end-1] # without last character "My Strin" -julia> chop("My String") #alternate remove last character -"My Strin" +julia> "My String"[2:end-1] # without first and last characters +"y Strin" diff --git a/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro b/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro index 30c0204c53..f7f7872ffe 100644 --- a/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro +++ b/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro @@ -9,5 +9,4 @@ remove_first_last_chars :- writef('Without first/last chars : %s\n', [L3]). remove_last(L, LR) :- - reverse(L, [_ | L1]), - reverse(L1, LR). + append(LR, [_], L). diff --git a/Task/Sudoku/Erlang/sudoku.erl b/Task/Sudoku/Erlang/sudoku.erl new file mode 100644 index 0000000000..91f407eba4 --- /dev/null +++ b/Task/Sudoku/Erlang/sudoku.erl @@ -0,0 +1,162 @@ +-module( sudoku ). + +-export( [display/1, start/1, solve/1, task/0] ). + +display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)]. +%% A known value is {{Column, Row}, Value} +%% Top left corner is {1, 1}, Bottom right corner is {9,9} +start( Knowns ) -> dict:from_list( Knowns ). + +solve( Grid ) -> + Sure = solve_all_sure( Grid ), + solve_unsure( potentials(Sure), Sure ). + +task() -> + Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7}, + {{4, 2}, 3}, {{7, 2}, 4}, + {{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2}, + {{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9}, + {{1, 5}, 6}, {{9, 5}, 7}, + {{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8}, + {{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8}, + {{3, 8}, 9}, {{6, 8}, 8}, + {{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}], + task( Simple ), + Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5}, + {{3, 3}, 1}, {{5, 3}, 2}, + {{4, 4}, 5}, {{6, 4}, 7}, + {{3, 5}, 4}, {{7, 5}, 1}, + {{2, 6}, 9}, + {{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3}, + {{3, 8}, 2}, {{5, 8}, 1}, + {{5, 9}, 4}, {{9, 9}, 9}], + task( Difficult ). + + + +bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ). + +bt_accept( true, Board ) -> erlang:throw( {ok, Board} ); +bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ). + +bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values]. + +bt_reject( true, _Grid ) -> backtrack; +bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ). + +display_row( Row, Grid ) -> + [display_row_group( X, Row, Grid ) || X <- [1, 4, 7]], + display_row_nl( Row ). + +display_row_group( Start, Row, Grid ) -> + [io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]], + io:fwrite( " " ). + +display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl(); +display_row_nl( _N ) -> io:nl(). + +display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ). + +display_value( error ) -> $.; +display_value( {ok, Value} ) -> Value + $0. + +is_all_correct( Grid ) -> dict:size( Grid ) =:= 81. + +is_not_allowed( Grid ) -> + is_not_allowed_rows( Grid ) + orelse is_not_allowed_columns( Grid ) + orelse is_not_allowed_groups( Grid ). + +is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ). + +is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ). + +is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ). + +is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ). + +group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)]. + +group_positions_close( N ) when N < 4 -> [1,2,3]; +group_positions_close( N ) when N < 7 -> [4,5,6]; +group_positions_close( _N ) -> [7,8,9]. + +positions_not_in_grid( Grid ) -> + Keys = dict:fetch_keys( Grid ), + [{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)]. + +potentials_one_position( Grid ) -> + [{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ), + {Position, Values}. + +potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ). + +potentials( Position, Grid ) -> + Useds = potentials_used_values( Position, Grid ), + {Position, [Value || Value <- lists:seq(1, 9) -- Useds]}. + +potentials_used_values( {X, Y}, Grid ) -> + Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X], + Row_values = potentials_values( Row_positions, Grid ), + Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y], + Column_values = potentials_values( Column_positions, Grid ), + Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ), + Group_values = potentials_values( Group_positions, Grid ), + Row_values ++ Column_values ++ Group_values. + +potentials_values( Keys, Grid ) -> + Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys], + [Value || {ok, Value} <- Row_values_unfiltered]. + +values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)]. + +values_all_columns( X, Grid ) -> + Positions = [{X, Y} || Y <- lists:seq(1, 9)], + potentials_values( Positions, Grid ). + +values_all_groups( Grid ) -> + [G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]], + [G1,G2,G3] = G123, + [G4,G5,G6] = G456, + [G7,G8,G9] = G789, + [G1,G2,G3,G4,G5,G6,G7,G8,G9]. + +values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]]. + +values_all_groups( _X, X_offset, Grid ) -> + Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)], + potentials_values( Positions, Grid ). + +values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)]. + +values_all_rows( Y, Grid ) -> + Positions = [{X, Y} || X <- lists:seq(1, 9)], + potentials_values( Positions, Grid ). + +solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ). + +solve_all_sure( [], Grid ) -> Grid; +solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ). + +solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)]. + +solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ). + +solve_unsure( [], Grid ) -> Grid; +solve_unsure( _Potentials, Grid ) -> + try + bt( Grid ) + + catch + _:{ok, Board} -> Board + + end. + +task( Knowns ) -> + io:fwrite( "Start~n" ), + Start = start( Knowns ), + display( Start ), + io:fwrite( "Solved~n" ), + Solved = solve( Start ), + display( Solved ), + io:nl(). diff --git a/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array.basic b/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array-1.basic similarity index 100% rename from Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array.basic rename to Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array-1.basic diff --git a/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array-2.basic b/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array-2.basic new file mode 100644 index 0000000000..f62a4ac246 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array-2.basic @@ -0,0 +1,9 @@ + 10 N = 5 + 20 S = 0:P = 1: DATA 1,2,3,4,5 + 30 N = N - 1: DIM A(N) + 40 FOR I = 0 TO N + 50 READ A(I): NEXT + 60 FOR I = 0 TO N + 70 S = S + A(I):P = P * A(I) + 80 NEXT + 90 PRINT "SUM="S,"PRODUCT="P diff --git a/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap b/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap index fe8df7db92..34231e703d 100644 --- a/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap +++ b/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap @@ -5,3 +5,11 @@ Sum(v); Product(v); # 40320 + +# You can sum or multiply the result of a function + +Sum(v, n -> n^2); +# 204 + +Product(v, n -> 1/n); +# 1/40320 diff --git a/Task/Sum-digits-of-an-integer/AutoHotkey/sum-digits-of-an-integer.ahk b/Task/Sum-digits-of-an-integer/AutoHotkey/sum-digits-of-an-integer.ahk new file mode 100644 index 0000000000..9f6a7b10b6 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/AutoHotkey/sum-digits-of-an-integer.ahk @@ -0,0 +1,22 @@ +MsgBox % sprintf("%d %d %d %d %d`n" + ,SumDigits(1, 10) + ,SumDigits(12345, 10) + ,SumDigits(123045, 10) + ,SumDigits(0xfe, 16) + ,SumDigits(0xf0e, 16) ) + +SumDigits(n,base) { + sum := 0 + while (n) + { + sum += Mod(n,base) + n /= base + } + return sum +} + +sprintf(s,fmt*) { + for each, f in fmt + StringReplace,s,s,`%d, % f + return s +} diff --git a/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer.basic b/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer-1.basic similarity index 100% rename from Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer.basic rename to Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer-1.basic diff --git a/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer-2.basic b/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer-2.basic new file mode 100644 index 0000000000..47bc0d490f --- /dev/null +++ b/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer-2.basic @@ -0,0 +1,18 @@ +10 BASE = 10 +20 N$ = "1" : GOSUB 100 : PRINT N +30 N$ = "1234" : GOSUB 100 : PRINT N +40 BASE = 16 +50 N$ = "FE" : GOSUB 100 : PRINT N +60 N$ = "F0E" : GOSUB 100 : PRINT N +90 END + +100 REM SUM DIGITS OF N$, BASE +110 IF BASE = 1 THEN N = LEN(N$) : RETURN +120 IF BASE < 2 THEN BASE = 10 +130 N = 0 : V$ = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", BASE) +140 FOR I = 1 TO LEN(N$) : C$ = MID$(N$, I, 1) +150 FOR J = 1 TO LEN(V$) +160 IF C$ <> MID$(V$, J, 1) THEN NEXT J : N = SQR(-1) : STOP +170 N = N + J - 1 +180 NEXT I +190 RETURN diff --git a/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d b/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d index e545bc575c..3860ffe4c7 100644 --- a/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d +++ b/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d @@ -1,6 +1,6 @@ import std.stdio, std.bigint; -uint sumDigits(T)(T n, in uint base=10) /*pure nothrow*/ +uint sumDigits(T)(T n, in uint base=10) pure /*nothrow*/ in { assert(base > 1); } body { @@ -11,9 +11,9 @@ in { } void main() { - sumDigits(1).writeln; - sumDigits(1_234).writeln; + 1.sumDigits.writeln; + 1_234.sumDigits.writeln; sumDigits(0xfe, 16).writeln; sumDigits(0xf0e, 16).writeln; - sumDigits(1_234.BigInt).writeln; + 1_234.BigInt.sumDigits.writeln; } diff --git a/Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.julia b/Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.julia new file mode 100644 index 0000000000..032901dbf5 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.julia @@ -0,0 +1 @@ +sumdigits(n, base=10) = sum(digits(n, base)) 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 ce4cdea080..b3cde6c503 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,7 +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}(); +auto series(alias F)(in int end, in int start=1) pure { + return iota(start, end + 1).map!F.reduce!q{a + b}; } void main() { diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia index a90a7c1803..e4840cf0e3 100644 --- a/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia +++ b/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia @@ -1,4 +1,4 @@ -julia> sum([1/k^2 for k = 1:1000]) +julia> sum(k -> 1/k^2, 1:1000) 1.643934566681559 julia> pi^2/6 diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia index d1c2d880d7..763e8c15bb 100644 --- a/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia +++ b/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia @@ -1,5 +1,10 @@ -julia> f(x) = sum(1/[1:x].^2) -# method added to generic function f +julia> function f(n) + s = 0.0 + for k = 1:n + s += 1/k^2 + end + return s +end julia> f(1000) 1.6439345666815615 diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 index 291b0c27f9..ae20eb890b 100644 --- a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 @@ -1,2 +1,2 @@ -sub ζ($s) { [\+] map -> \n { 1 / n**$s }, 1..* } +sub ζ($s) { (state %){$s} //= [\+] map * **-$s, 1..* } say ζ(2)[1000]; diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr new file mode 100644 index 0000000000..e77e480dc7 --- /dev/null +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr @@ -0,0 +1,2 @@ +txr -c '@(bind sum @[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0])' +sum="1.64393456668156" diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr new file mode 100644 index 0000000000..44552ce771 --- /dev/null +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr @@ -0,0 +1,2 @@ +txr -c '@(bind sum @[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0])' +sum="1.64393456668156" diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr new file mode 100644 index 0000000000..c6fc9896f4 --- /dev/null +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr @@ -0,0 +1,2 @@ +txr -c '@(bind sum @[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000])' +sum="1.64393456668156" diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr new file mode 100644 index 0000000000..e0eaa1cad4 --- /dev/null +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr @@ -0,0 +1,2 @@ +txr -c '@(bind sum @[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0])' +sum="1.64393456668156" diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr new file mode 100644 index 0000000000..06570640cb --- /dev/null +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr @@ -0,0 +1,2 @@ +txr -c '@(bind sum @[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0])' +sum="1.64393456668156" diff --git a/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d b/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d index d2a7b35f6b..5652700dd3 100644 --- a/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d +++ b/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d @@ -13,7 +13,7 @@ struct Vec2 { // To be replaced with Phobos code. } immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon) -/*pure nothrow*/ in { +pure /*nothrow*/ in { assert(subjectPolygon.length > 1); assert(clipPolygon.length > 1); // Probably clipPolygon needs to be convex and probably @@ -23,10 +23,9 @@ immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon) } body { alias Edge = Tuple!(Vec2,"p", Vec2,"q"); - static bool isInside(in Vec2 p, in Edge cle) pure nothrow { - return (cle.q.x - cle.p.x) * (p.y - cle.p.y) > - (cle.q.y - cle.p.y) * (p.x - cle.p.x); - } + static enum isInside = (in Vec2 p, in Edge cle) pure nothrow => + (cle.q.x - cle.p.x) * (p.y - cle.p.y) > + (cle.q.y - cle.p.y) * (p.x - cle.p.x); static Vec2 intersection(in Edge se, in Edge cle) pure nothrow { immutable dc = cle.p - cle.q; @@ -39,12 +38,11 @@ immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon) } // How much slower is this compared to lower-level code? - static edges(in Vec2[] poly) /*pure nothrow*/ { - // return poly[$ - 1 .. $].chain(poly).zip!Edge(poly); - return poly[$ - 1 .. $].chain(poly).zip(poly).map!Edge; - } + static enum edges = (in Vec2[] poly) pure nothrow => + // poly[$ - 1 .. $].chain(poly).zip!Edge(poly); + poly[$ - 1 .. $].chain(poly).zip(poly).map!Edge; - immutable(Vec2)[] result = subjectPolygon.idup; // // Not nothrow. + immutable(Vec2)[] result = subjectPolygon.idup; // Not nothrow. foreach (immutable clipEdge; edges(clipPolygon)) { immutable inputList = result; @@ -101,7 +99,7 @@ in { eps.writefln("c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs"); eps.writefln("%%%%EOF"); - eps.close(); + eps.close; writeln(fileName, " written."); } diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb b/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb index b22457c63a..d90672a810 100644 --- a/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb +++ b/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb @@ -1,11 +1,13 @@ -Point = Struct.new(:x,:y) +Point = Struct.new(:x,:y) do + def to_s; "(#{x}, #{y})" end +end -def sutherland_hodgman subjectPolygon, clipPolygon +def sutherland_hodgman(subjectPolygon, clipPolygon) # These inner functions reduce the argument passing to - # _inside_ and _intersection_. - cp1, cp2, e, s = nil + # "inside" and "intersection". + cp1, cp2, s, e = nil inside = proc do |p| - next (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) + (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) end intersection = proc do dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y @@ -13,23 +15,21 @@ def sutherland_hodgman subjectPolygon, clipPolygon n1 = cp1.x*cp2.y - cp1.y*cp2.x n2 = s.x*e.y - s.y*e.x n3 = 1.0 / (dcx*dpy - dcy*dpx) - next Point.new((n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3) + Point[(n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3] end outputList = subjectPolygon cp1 = clipPolygon.last - clipPolygon.each do |point| - cp2 = point + for cp2 in clipPolygon inputList = outputList outputList = [] s = inputList.last - inputList.each do |point| - e = point + for e in inputList if inside[e] - outputList << intersection[] if !inside[s] - outputList << e + outputList << intersection[] unless inside[s] + outputList << e elsif inside[s] - outputList << intersection[] + outputList << intersection[] end s = e end @@ -38,12 +38,10 @@ def sutherland_hodgman subjectPolygon, clipPolygon outputList end -$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], - [250, 300], [200, 250], [150, 350], [100, 250], - [100, 200]].collect{|pnt| Point.new(*pnt)} +subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], + [250, 300], [200, 250], [150, 350], [100, 250], + [100, 200]].collect{|pnt| Point[*pnt]} -$clipPolygon = [[100, 100], [300, 100], [300, 300], - [100, 300]].collect{|pnt| Point.new(*pnt)} +clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]].collect{|pnt| Point[*pnt]} -puts sutherland_hodgman($subjectPolygon, $clipPolygon).collect{|pnt| - "(#{pnt.x},#{pnt.y})"}.join(", ") +puts sutherland_hodgman(subjectPolygon, clipPolygon) diff --git a/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv b/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv index eab0a418bd..0846f2204b 100644 --- a/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv +++ b/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv @@ -11,4 +11,4 @@ symmetric-difference A B: b set{ -. symmetric-difference setA setB +!. symmetric-difference setA setB diff --git a/Task/Symmetric-difference/JavaScript/symmetric-difference.js b/Task/Symmetric-difference/JavaScript/symmetric-difference-1.js similarity index 100% rename from Task/Symmetric-difference/JavaScript/symmetric-difference.js rename to Task/Symmetric-difference/JavaScript/symmetric-difference-1.js diff --git a/Task/Symmetric-difference/JavaScript/symmetric-difference-2.js b/Task/Symmetric-difference/JavaScript/symmetric-difference-2.js new file mode 100644 index 0000000000..6ffea3afe9 --- /dev/null +++ b/Task/Symmetric-difference/JavaScript/symmetric-difference-2.js @@ -0,0 +1,29 @@ +function Difference(A,B) +{ + var a = A.length, b = B.length, c = 0, C = []; + for (var i = 0; i < a; i++) + { var j = 0, k = 0; + while (j < b && B[j] !== A[i]) j++; + while (k < c && C[k] !== A[i]) k++; + if (j == b && k == c) C[c++] = A[i]; + } + return C; +} + +function SymmetricDifference(A,B) +{ + var D1 = Difference(A,B), D2 = Difference(B,A), + a = D1.length, b = D2.length; + for (var i = 0; i < b; i++) D1[a++] = D2[i]; + return D1; +} + + +/* Example + A = ['John', 'Serena', 'Bob', 'Mary', 'Serena']; + B = ['Jim', 'Mary', 'John', 'Jim', 'Bob']; + + Difference(A,B); // 'Serena' + Difference(B,A); // 'Jim' + SymmetricDifference(A,B); // 'Serena','Jim' +*/ diff --git a/Task/Symmetric-difference/REXX/symmetric-difference-1.rexx b/Task/Symmetric-difference/REXX/symmetric-difference-1.rexx new file mode 100644 index 0000000000..6c6fcbda4c --- /dev/null +++ b/Task/Symmetric-difference/REXX/symmetric-difference-1.rexx @@ -0,0 +1,43 @@ +/*REXX pgm finds symmetric difference and symm. AND (between two lists).*/ +a.=0 /*falsify the booleans*/ +a= '["John", "Serena", "Bob", "Mary", "Serena"]' /*note the duplicate. */ +b= '["Jim", "Mary", "John", "Jim", "Bob"]' /* " " " */ +a.1=a; say '──────────────list A =' a /*assign and display. */ +a.2=b; say '──────────────list B =' b /* " " " */ +SD= ; SA= /*Sym. Diff; Sym And.*/ +SD.=0; SA.=0 /*falsify SD & SA bool*/ +/*══════════════════════════════════════════════════parse the two lists.*/ + do k=1 for 2 /*process both lists (stemmed array).*/ + a.k=strip(strip(a.k,,"["),,']') /*strip leading and trailing brackets*/ + do j=1 until a.k='' /*parse names [they may have blanks]*/ + a.k=strip(a.k,,',') /*strip comma (if any)*/ + parse var a.k '"' _ '"' a.k /*get the list's name.*/ + a.k.j=_ /*store the list name.*/ + a.k._=1 /*make a boolean val. */ + end /*j*/ + a.k.0=j-1 /*number of list names*/ + end /*k*/ +/*══════════════════════════════════════════════════find symmetric DIFF.*/ + do k=1 for 2 /*process both lists. */ + ko=word(2 1,k) /*point to other list.*/ + do j=1 for a.k.0; _=a.k.j /*process list names. */ + if \a.ko._ & \SD._ then do /*if not in both··· */ + SD=SD '"'_'",' /*add to sym diff list*/ + SD._=1 /*"trueify" a boolean.*/ + end + end /*j*/ + end /*k*/ + +SD= "["strip(strip(SD),'T',",")']' /*clean up and [ ] it*/ +say; say 'symmetric difference =' SD /*show symmetric DIFF.*/ +/*══════════════════════════════════════════════════find symmetric AND. */ + do j=1 for a.1.0; _=a.1.j /*process A list names*/ + if a.1._ & a.2._ & \SA._ then do /*if common to both···*/ + SA=SA '"'_'",' /*add to symmetric AND*/ + SA._=1 /*"trueify" a boolean.*/ + end + end /*j*/ + +SA="["strip(strip(SA),'T',",")']' /*clean up and [ ] it*/ +say; say ' symmetric AND =' SA /*show symmetric DIFF.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Symmetric-difference/REXX/symmetric-difference-2.rexx b/Task/Symmetric-difference/REXX/symmetric-difference-2.rexx new file mode 100644 index 0000000000..6c08231e73 --- /dev/null +++ b/Task/Symmetric-difference/REXX/symmetric-difference-2.rexx @@ -0,0 +1,7 @@ +/*REXX pgm finds symmetric difference and symm. AND (between two lists).*/ +a.=0 /*falsify the booleans*/ +a= '["Zahn", "Yi", "Stands with a Fist", "", "Hungry Wolf", "Yi"]' +b= '["Draag Ng [Jr.]", "Patzy", "Zahn", "Yi", "Robert the Bruce"]' + ∙ + ∙ + ∙ diff --git a/Task/Symmetric-difference/REXX/symmetric-difference-3.rexx b/Task/Symmetric-difference/REXX/symmetric-difference-3.rexx new file mode 100644 index 0000000000..0c09d6a135 --- /dev/null +++ b/Task/Symmetric-difference/REXX/symmetric-difference-3.rexx @@ -0,0 +1,25 @@ +/* REXX --------------------------------------------------------------- +* 14.12.2013 Walter Pachl a short solution +* 16.12.2013 fix duplicate element problem in input +* 16.12.2013 added duplicate to t. +* Handles only sets the elements of which do not contain blanks +*--------------------------------------------------------------------*/ +s='John Bob Mary Serena' +t='Jim Mary John Bob Jim ' +Say difference(s,t) +Exit +difference: +Parse Arg a,b +res='' +Do i=1 To words(a) + If wordpos(word(a,i),b)=0 Then + Call out word(a,i) + End +Do i=1 To words(b) + If wordpos(word(b,i),a)=0 Then + Call out word(b,i) + End +Return strip(res) +out: parse Arg e +If wordpos(e,res)=0 Then res=res e +Return diff --git a/Task/Symmetric-difference/REXX/symmetric-difference.rexx b/Task/Symmetric-difference/REXX/symmetric-difference.rexx deleted file mode 100644 index ae2c67e39b..0000000000 --- a/Task/Symmetric-difference/REXX/symmetric-difference.rexx +++ /dev/null @@ -1,46 +0,0 @@ -/*REXX program to find the symmetric difference (between two strings). */ -a.=0 /*falisify all the a.k._ booleans. */ -a= '["John", "Serena", "Bob", "Mary", "Serena"]' -b= '["Jim", "Mary", "John", "Jim", "Bob"]' -a.1=a; say '──────────────list A =' a -a.2=b; say '──────────────list B =' b -SD= ; SA= /*Sym. Diff, Sym "And"*/ -SD.=0; SA.=0 /*falsify SD & SA bool*/ - - do k=1 for 2 /*process both lists (stemmed array).*/ - a.k=strip(strip(a.k,,"["),,']') /*strip leading and trailing brackets*/ - - do j=1 until a.k='' /*parse names, they may have blanks. */ - a.k=strip(a.k,,',') /*strip comma (if any)*/ - parse var a.k '"' _ '"' a.k /*get the list's name.*/ - a.k.j=_ /*store the list name.*/ - a.k._=1 /*make a boolean val. */ - end /*j*/ - a.k.0=j-1 /*number of list names*/ - end /*k*/ -/*══════════════════════════════════════════════════find symmetric diff.*/ - do k=1 for 2 /*process both lists. */ - ko=word(2 1,k) /*point to other list.*/ - - do j=1 for a.k.0; _=a.k.j /*process list names. */ - if \a.ko._ & \SD._ then do /*if not in both... */ - SD=SD '"'_'",' /*add to sym diff list*/ - SD._=1 /*"trueify" a boolean.*/ - end - end /*j*/ - end /*k*/ - -SD= "["strip(space(SD),'T',",")']' /*clean up and bracket*/ -say; say 'symmetric difference =' SD /*show and tell the SD*/ - -/*══════════════════════════════════════════════════find symmetric AND. */ - do j=1 for a.1.0; _=a.1.j /*process A list names*/ - if a.1._ & a.2._ & \SA._ then do /*if common to both...*/ - SA=SA '"'_'",' /*add to sym AND list.*/ - SA._=1 /*"trueify" a boolean.*/ - end - end /*j*/ - -SA="["strip(space(SA),'T',",")']' /*clean up and bracket*/ -say; say ' symmetric AND =' SA /*show and tell the SA*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala b/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala index 9343825bfe..bc22a6c1b3 100644 --- a/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala +++ b/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala @@ -1,21 +1,22 @@ -case class HowMany(asker:Actor) +case class HowMany(asker: Actor) val printer = actor { var count = 0 - while(true){ - receive{ - case line:String => print(line); count = count + 1 - case HowMany(asker:Actor) => asker ! count ; exit() - } + while (true) { + receive { + case line: String => + print(line); count = count + 1 + case HowMany(asker: Actor) => asker ! count; exit() } + } } -def reader(printer:Actor) { - scala.io.Source.fromFile("c:\\input.txt").getLines foreach {printer ! _ } +def reader(printer: Actor) { + scala.io.Source.fromFile("c:\\input.txt").getLines foreach { printer ! _ } printer ! HowMany( actor { - receive{ - case count:Int => println("line count = "+count) + receive { + case count: Int => println("line count = " + count) } }) } diff --git a/Task/System-time/C++/system-time.cpp b/Task/System-time/C++/system-time-1.cpp similarity index 100% rename from Task/System-time/C++/system-time.cpp rename to Task/System-time/C++/system-time-1.cpp diff --git a/Task/System-time/C++/system-time-2.cpp b/Task/System-time/C++/system-time-2.cpp new file mode 100644 index 0000000000..a9c6e82743 --- /dev/null +++ b/Task/System-time/C++/system-time-2.cpp @@ -0,0 +1,8 @@ +#include +#include //for conversion std::ctime() +#include + +int main() { + auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + std::cout << std::ctime(&timenow) << std::endl; +} diff --git a/Task/System-time/Ruby/system-time.rb b/Task/System-time/Ruby/system-time.rb index 92d77bbb0c..f92f64778c 100644 --- a/Task/System-time/Ruby/system-time.rb +++ b/Task/System-time/Ruby/system-time.rb @@ -1,10 +1,10 @@ t = Time.now # textual -puts t # => Wed Aug 05 20:14:50 -0400 2009 +puts t # => 2013-12-27 18:00:23 +0900 # epoch time -puts t.to_i # => 1249517690 +puts t.to_i # => 1388134823 # epoch time with fractional seconds -puts t.to_f # => 1249517690.74388 +puts t.to_f # => 1388134823.9801579 diff --git a/Task/System-time/VBA/system-time.vba b/Task/System-time/VBA/system-time.vba new file mode 100644 index 0000000000..4d824771d3 --- /dev/null +++ b/Task/System-time/VBA/system-time.vba @@ -0,0 +1 @@ +Debug.Print Now() diff --git a/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk b/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk index a52539d64b..8dbe74f56f 100644 --- a/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk +++ b/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk @@ -1,32 +1,32 @@ #!/bin/sh -f awk ' BEGIN { - print "Creating table..."; - dbExec("address.db", "create table address (street, city, state, zip);"); - print "Done."; - exit; + print "Creating table..." + dbExec("address.db", "create table address (street, city, state, zip);") + print "Done." + exit } function dbExec(db, qry, result) { dbMakeQuery(db, qry) | getline result - dbErrorCheck(result); + dbErrorCheck(result) } function dbMakeQuery(db, qry, q) { - q = dbEscapeQuery(qry) ";"; + q = dbEscapeQuery(qry) ";" return "echo \"" q "\" | sqlite3 " db } function dbEscapeQuery(qry, q) { - q = qry; - gsub(/"/, "\\\"", q); - return q; + q = qry + gsub(/"/, "\\\"", q) + return q } function dbErrorCheck(res) { if (res ~ "SQL error") { - print res; - exit; + print res + exit } } diff --git a/Task/Table-creation-Postal-addresses/Erlang/table-creation-postal-addresses.erl b/Task/Table-creation-Postal-addresses/Erlang/table-creation-postal-addresses.erl new file mode 100644 index 0000000000..6103421197 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Erlang/table-creation-postal-addresses.erl @@ -0,0 +1,9 @@ +-module( table_creation ). + +-export( [task/0] ). + +-record( address, {id, street, city, zip} ). + +task() -> + mnesia:start(), + mnesia:create_table( address, [{attributes, record_info(fields, address)}] ). diff --git a/Task/Table-creation-Postal-addresses/Haskell/table-creation-postal-addresses.hs b/Task/Table-creation-Postal-addresses/Haskell/table-creation-postal-addresses.hs new file mode 100644 index 0000000000..91213db643 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Haskell/table-creation-postal-addresses.hs @@ -0,0 +1,15 @@ +{-# LANGUAGE OverloadedStrings #-} + +import Database.SQLite.Simple + +main = do + db <- open "postal.db" + execute_ db "\ + \CREATE TABLE address (\ + \addrID INTEGER PRIMARY KEY AUTOINCREMENT, \ + \addrStreet TEXT NOT NULL, \ + \addrCity TEXT NOT NULL, \ + \addrState TEXT NOT NULL, \ + \addrZIP TEXT NOT NULL \ + \)" + close db diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx index b51922fb90..01bbbca72f 100644 --- a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx @@ -3,11 +3,11 @@ │ Format of an entry in the USA address/city/state/zipcode structure.│ │ │ │ The "structure" name can be any legal variable name, but here the │ - │ name will be shorted to make these comments (and program) easier │ - │ to read; it's name will be @USA (in any case). In addition,│ + │ name will be shortened to make these comments (and program) easier │ + │ to read; its name will be @USA (in any case). In addition, │ │ the following variables names (stemmed array tails) will need to │ - │ be kept unitialized (that is, not used for any variable name). │ - │ To that end, each of these "hands-off" variable names will have a │ + │ be kept uninitialized (that is, not used for any variable name). │ + │ To that end, each of these "hands-off" variable names will have an │ │ underscore in the beginning of each name. Other possibilities are │ │ to have a trailing underscore (or both leading and trailing), some │ │ other special eye-catching character such as: ! @ # $ ? │ @@ -30,9 +30,9 @@ │ @USA.nnn._addr3 = 3rd street address │ │ @USA.nnn._addrNN = ... (any number, but in sequential order). │ ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._state = US postal code for the state/terrority/etc. │ + │ @USA.nnn._state = US postal code for the state/territory/etc. │ ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._city = offical city name, may include any char. │ + │ @USA.nnn._city = official city name, may include any char. │ ├────────────────────────────────────────────────────────────────────┤ │ @USA.nnn._zip = US postal zipcode, 5 digit format or │ │ 10 char format. │ 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 496fd13b27..c1e903bf93 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,4 +1,4 @@ -import std.stdio, std.file, std.string, std.datetime; +import std.stdio, std.file, std.string, std.datetime, std.range; void main(string[] args) { immutable filename = "NOTES.TXT"; @@ -9,6 +9,6 @@ void main(string[] args) { } else { auto f = File(filename, "a+"); f.writefln("%s", cast(DateTime)Clock.currTime); - f.writefln("\t%s", args[1 .. $].join(" ")); + f.writefln("\t%s", args.dropOne.join(" ")); } } diff --git a/Task/Temperature-conversion/AutoHotkey/temperature-conversion.ahk b/Task/Temperature-conversion/AutoHotkey/temperature-conversion.ahk new file mode 100644 index 0000000000..6c844e9c63 --- /dev/null +++ b/Task/Temperature-conversion/AutoHotkey/temperature-conversion.ahk @@ -0,0 +1,17 @@ +MsgBox, % "Kelvin:`t`t 21.00 K`n" + . "Celsius:`t`t" kelvinToCelsius(21) " C`n" + . "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n" + . "Rankine:`t`t" kelvinToRankine(21) " R`n" + +kelvinToCelsius(k) +{ + return, round(k - 273.15, 2) +} +kelvinToFahrenheit(k) +{ + return, round(k * 1.8 - 459.67, 2) +} +kelvinToRankine(k) +{ + return, round(k * 1.8, 2) +} diff --git a/Task/Temperature-conversion/Objeck/temperature-conversion.objeck b/Task/Temperature-conversion/Objeck/temperature-conversion.objeck index 53732c76df..60d1a3e94e 100644 --- a/Task/Temperature-conversion/Objeck/temperature-conversion.objeck +++ b/Task/Temperature-conversion/Objeck/temperature-conversion.objeck @@ -1,4 +1,4 @@ -class Temperature { +class Temperature { function : Main(args : String[]) ~ Nil { k := System.IO.Console->ReadString()->ToFloat(); c := KelvinToCelsius(k); diff --git a/Task/Temperature-conversion/PicoLisp/temperature-conversion-1.l b/Task/Temperature-conversion/PicoLisp/temperature-conversion-1.l new file mode 100644 index 0000000000..13c1c8e5e4 --- /dev/null +++ b/Task/Temperature-conversion/PicoLisp/temperature-conversion-1.l @@ -0,0 +1,12 @@ +(scl 2) + +(de convertKelvin (Kelvin) + (for X + (quote + (K . prog) + (C (K) (- K 273.15)) + (F (K) (- (*/ K 1.8 1.0) 459.67)) + (R (K) (*/ K 1.8 1.0)) ) + (tab (-3 8) + (car X) + (format ((cdr X) Kelvin) *Scl) ) ) ) diff --git a/Task/Temperature-conversion/PicoLisp/temperature-conversion-2.l b/Task/Temperature-conversion/PicoLisp/temperature-conversion-2.l new file mode 100644 index 0000000000..3af07f91fc --- /dev/null +++ b/Task/Temperature-conversion/PicoLisp/temperature-conversion-2.l @@ -0,0 +1 @@ +(convertKelvin 21.0) diff --git a/Task/Temperature-conversion/Ruby/temperature-conversion-1.rb b/Task/Temperature-conversion/Ruby/temperature-conversion-1.rb new file mode 100644 index 0000000000..c1d9efbf99 --- /dev/null +++ b/Task/Temperature-conversion/Ruby/temperature-conversion-1.rb @@ -0,0 +1,47 @@ +module TempConvert + + FROM_TEMP_SCALE_TO_K = + {'kelvin' => lambda{|t| t}, + 'celsius' => lambda{|t| t + 273.15}, + 'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0}, + 'rankine' => lambda{|t| t * 5/9.0}, + 'delisle' => lambda{|t| 373.15 - t * 2/3.0}, + 'newton' => lambda{|t| t * 100/33.0 + 273.15}, + 'reaumur' => lambda{|t| t * 5/4.0 + 273.15}, + 'roemer' => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}} + + TO_TEMP_SCALE_FROM_K = + {'kelvin' => lambda{|t| t}, + 'celsius' => lambda{|t| t - 273.15}, + 'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67}, + 'rankine' => lambda{|t| t * 9/5.0}, + 'delisle' => lambda{|t| (373.15 - t) * 3/2.0}, + 'newton' => lambda{|t| (t - 273.15) * 33/100.0}, + 'reaumur' => lambda{|t| (t - 273.15) * 4/5.0}, + 'roemer' => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}} + + SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|') + + def self.method_missing(meth, *args, &block) + if valid_temperature_conversion?(meth) then + convert_temperature(meth, *args) + else + super + end + end + + def self.respond_to_missing?(meth, include_private = false) + valid_temperature_conversion?(meth) || super + end + + def self.valid_temperature_conversion?(meth) + !!(meth.to_s =~ /(#{SUPPORTED_SCALES})_to_(#{SUPPORTED_SCALES})/) + end + + def self.convert_temperature(meth, temp) + from_scale, to_scale = meth.to_s.split("_to_") + return temp.to_f if from_scale == to_scale # no kelvin roundtrip + TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2) + end + +end diff --git a/Task/Temperature-conversion/Ruby/temperature-conversion-2.rb b/Task/Temperature-conversion/Ruby/temperature-conversion-2.rb new file mode 100644 index 0000000000..1446ca01c6 --- /dev/null +++ b/Task/Temperature-conversion/Ruby/temperature-conversion-2.rb @@ -0,0 +1,11 @@ +TempConvert.kelvin_to_celsius 100 #=> -173.15 +TempConvert.kelvin_to_fahrenheit 100 #=> -279.67 +TempConvert.kelvin_to_rankine 100 #=> 180.0 +TempConvert.kelvin_to_delisle 100 #=> 409.73 +TempConvert.kelvin_to_newton 100 #=> -57.14 +TempConvert.kelvin_to_reaumur 100 #=> -138.52 +TempConvert.kelvin_to_roemer 100 #=> -83.4 + +TempConvert.newton_to_celsius 100 #=> 303.03 +TempConvert.newton_to_fahrenheit 100 #=> 577.45 +# All 64 combinations possible diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-1.basic similarity index 100% rename from Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen.basic rename to Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-1.basic diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-2.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-2.basic new file mode 100644 index 0000000000..ad9fc6e378 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-2.basic @@ -0,0 +1 @@ +HOME diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-3.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-3.basic new file mode 100644 index 0000000000..1990de62cc --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-3.basic @@ -0,0 +1 @@ + CLS diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-4.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-4.basic new file mode 100644 index 0000000000..747b079d8b --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-4.basic @@ -0,0 +1 @@ + VDU 12 diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-5.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-5.basic new file mode 100644 index 0000000000..a311bea00d --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-5.basic @@ -0,0 +1 @@ + PRINT CHR$(12); diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-6.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-6.basic new file mode 100644 index 0000000000..d8ed2b0aef --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-6.basic @@ -0,0 +1 @@ +10 CLS diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-7.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-7.basic new file mode 100644 index 0000000000..c7e42b6386 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-7.basic @@ -0,0 +1 @@ +ClearConsole() diff --git a/Task/Terminal-control-Clear-the-screen/Fortran/terminal-control-clear-the-screen.f b/Task/Terminal-control-Clear-the-screen/Fortran/terminal-control-clear-the-screen.f new file mode 100644 index 0000000000..2c4c7507ee --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Fortran/terminal-control-clear-the-screen.f @@ -0,0 +1 @@ +call execute_command_line('clear') diff --git a/Task/Terminal-control-Cursor-movement/AutoHotkey/terminal-control-cursor-movement.ahk b/Task/Terminal-control-Cursor-movement/AutoHotkey/terminal-control-cursor-movement.ahk new file mode 100644 index 0000000000..2e0acd27de --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/AutoHotkey/terminal-control-cursor-movement.ahk @@ -0,0 +1,73 @@ +DllCall("AllocConsole") +hConsole:=DllCall("GetConsoleWindow","UPtr") +Stdout:=FileOpen(DllCall("GetStdHandle", "int", -11, "ptr"), "h `n") +Stdin:=FileOpen(DllCall("GetStdHandle", "int", -10, "ptr"), "h `n") + +;move the cursor one position to the left +GetPos(x,y) +SetPos(x-1) + +;move the cursor one position to the right +GetPos(x,y) +SetPos(x+1) + +;move the cursor up one line (without affecting its horizontal position) +GetPos(x,y) +SetPos(x,y-1) + +;move the cursor down one line (without affecting its horizontal position) +GetPos(x,y) +SetPos(x,y+1) + +;move the cursor to the beginning of the line +GetPos(x,y) +SetPos(0,y) + +;move the cursor to the end of the line +;requires previous knowledge of screen width -- typically 80 +SetPos(79) ;minus 1 because origin is (0,0) + +;move the cursor to the top left corner of the screen +SetPos(0,0) + +;move the cursor to the bottom right corner of the screen +GetConsoleSize(w,h) +SetPos(w-1,h-1) ;minus 1 because origin is (0,0) + +GetPos(ByRef x, ByRef y) { + global Stdout + VarSetCapacity(struct,22,0) + e:=DllCall("GetConsoleScreenBufferInfo","UPtr",Stdout.__Handle,"Ptr",&struct) + if (!e) or (ErrorLevel) + return 0 ;Failure + x:=NumGet(&struct,4,"UShort") + y:=NumGet(&struct,6,"UShort") + return 1 +} + +SetPos(x="",y="") { + global Stdout + GetPos(ox,oy) + if x is not Integer + x:=ox + if y is not Integer + y:=oy + VarSetCapacity(struct,4,0) + Numput(x,struct,"UShort") + Numput(y,struct,2,"UShort") + e:=DllCall("SetConsoleCursorPosition","Ptr",Stdout.__Handle,"uint",Numget(struct,"uint")) + if (!e) or (ErrorLevel) + return 0 ;Failure + return 1 +} + +GetConsoleSize(ByRef bufferwidth, ByRef bufferheight) { + global Stdout + VarSetCapacity(struct,22,0) + x:=DllCall("GetConsoleScreenBufferInfo","UPtr",Stdout.__Handle,"Ptr",&struct) + if (!x) or (ErrorLevel) + return 0 ;Failure + bufferwidth:=NumGet(&struct,"UShort") + bufferheight:=NumGet(&struct,2,"UShort") + return 1 +} diff --git a/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c b/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c new file mode 100644 index 0000000000..088820950b --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/C/terminal-control-cursor-movement.c @@ -0,0 +1,84 @@ +/*Abhishek Ghosh, 7th November 2013, Rotterdam*/ +#include +#include + +char *strings[] = {"The cursor will move one position to the left", + "The cursor will move one position to the right", + "The cursor will move vetically up one line", + "The cursor will move vertically down one line", + "The cursor will move to the beginning of the line", + "The cursor will move to the end of the line", + "The cursor will move to the top left corner of the screen", + "The cursor will move to the bottom right corner of the screen"}; + +int main() +{ + int i,j,MAXROW,MAXCOL; + struct text_info tInfo; + gettextinfo(&tInfo); + MAXROW = tInfo.screenheight; + MAXCOL = tInfo.screenwidth; + + clrscr(); + cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue."); + getch(); + + for(i=0;i<8;i++) + { + clrscr(); + gotoxy(5,MAXROW/2); + + cprintf("%s",strings[i]); + getch(); + + switch(i){ + case 0:gotoxy(wherex()-1,wherey()); + break; + case 1:gotoxy(wherex()+1,wherey()); + break; + case 2:gotoxy(wherex(),wherey()-1); + break; + case 3:gotoxy(wherex(),wherey()+1); + break; + case 4:for(j=0;j 1.9.3 +puts "£" diff --git a/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor.basic b/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor-1.basic similarity index 100% rename from Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor.basic rename to Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor-1.basic diff --git a/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor-2.basic b/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor-2.basic new file mode 100644 index 0000000000..c80a8f70b6 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor-2.basic @@ -0,0 +1 @@ +WAIT 49152,128 diff --git a/Task/Terminal-control-Hiding-the-cursor/Ruby/terminal-control-hiding-the-cursor.rb b/Task/Terminal-control-Hiding-the-cursor/Ruby/terminal-control-hiding-the-cursor.rb new file mode 100644 index 0000000000..b94a495962 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Ruby/terminal-control-hiding-the-cursor.rb @@ -0,0 +1,14 @@ +require "curses" +include Curses + +init_screen +begin + curs_set(1) #visible cursor + sleep 3 + curs_set(0) #invisible cursor + sleep 3 + curs_set(1) #visible cursor + sleep 3 +ensure + close_screen +end diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic index 51bf9d9664..918d1ea253 100644 --- a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic @@ -1,2 +1 @@ -10 CALL &bb9c:PRINT "inverse"; -20 CALL &bb9c:PRINT "normal" +INVERSE:?"ROSETTA";:NORMAL:?" CODE" diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic index 5df2772b6d..68cc00506e 100644 --- a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic @@ -1,4 +1,6 @@ -10 INVERSE 1 -20 PRINT "FOO"; -30 INVERSE 0 -40 PRINT "BAR" + COLOUR 128 : REM Black background + COLOUR 15 : REM White foreground + PRINT "Inverse"; + COLOUR 128+15 : REM White background + COLOUR 0 : REM Black foreground + PRINT " video" diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-3.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-3.basic new file mode 100644 index 0000000000..1b6f4e4bb8 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-3.basic @@ -0,0 +1,3 @@ + inverse$ = CHR$(17)+CHR$(128)+CHR$(17)+CHR$(15) + normal$ = CHR$(17)+CHR$(128+15)+CHR$(17)+CHR$(0) + PRINT inverse$ + "Inverse" + normal$ + " video" diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-4.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-4.basic new file mode 100644 index 0000000000..51bf9d9664 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-4.basic @@ -0,0 +1,2 @@ +10 CALL &bb9c:PRINT "inverse"; +20 CALL &bb9c:PRINT "normal" diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-5.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-5.basic new file mode 100644 index 0000000000..f917ae3d6e --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-5.basic @@ -0,0 +1,9 @@ +If OpenConsole() + ConsoleColor(0, 15) ;use the colors black (background) and white (forground) + PrintN("Inverse Video") + ConsoleColor(15, 0) ;use the colors white (background) and black (forground) + PrintN("Normal Video") + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-6.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-6.basic new file mode 100644 index 0000000000..35efdfc74b --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-6.basic @@ -0,0 +1,8 @@ +' ---------- foo is reverse -------------- +x$ = shell$("tput mr +echo 'foo'") + +' ---------- bar is normal -------------- +x$ = shell$("tput me +echo 'bar'") +wait diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic new file mode 100644 index 0000000000..5df2772b6d --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic @@ -0,0 +1,4 @@ +10 INVERSE 1 +20 PRINT "FOO"; +30 INVERSE 0 +40 PRINT "BAR" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/D/terminal-control-ringing-the-terminal-bell.d b/Task/Terminal-control-Ringing-the-terminal-bell/D/terminal-control-ringing-the-terminal-bell.d new file mode 100644 index 0000000000..0a92f95f46 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/D/terminal-control-ringing-the-terminal-bell.d @@ -0,0 +1,4 @@ +void main() { + import std.stdio; + writeln('\a'); +} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/NetRexx/terminal-control-ringing-the-terminal-bell.netrexx b/Task/Terminal-control-Ringing-the-terminal-bell/NetRexx/terminal-control-ringing-the-terminal-bell.netrexx new file mode 100644 index 0000000000..e30e10ca96 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/NetRexx/terminal-control-ringing-the-terminal-bell.netrexx @@ -0,0 +1,21 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + do + BEL = 8x07 + jtk = java.awt.toolkit.getDefaultToolkit() + say 'Bing!'(Rexx BEL).d2c + Thread.sleep(500) + say 'Ding\x07-ding\u0007!' + Thread.sleep(500) + say 'Beep!' + jtk.beep() + catch ex = Exception + ex.printStackTrace() + end + return diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Scala/terminal-control-ringing-the-terminal-bell.scala b/Task/Terminal-control-Ringing-the-terminal-bell/Scala/terminal-control-ringing-the-terminal-bell.scala new file mode 100644 index 0000000000..655373ebb2 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Scala/terminal-control-ringing-the-terminal-bell.scala @@ -0,0 +1 @@ +java.awt.Toolkit.getDefaultToolkit().beep() diff --git a/Task/Terminal-control-Unicode-output/AutoHotkey/terminal-control-unicode-output.ahk b/Task/Terminal-control-Unicode-output/AutoHotkey/terminal-control-unicode-output.ahk new file mode 100644 index 0000000000..fff23ff95f --- /dev/null +++ b/Task/Terminal-control-Unicode-output/AutoHotkey/terminal-control-unicode-output.ahk @@ -0,0 +1,55 @@ +DllCall("AllocConsole") +hConsole:=DllCall("GetConsoleWindow","UPtr") +Stdout:=FileOpen(DllCall("GetStdHandle", "int", -11, "ptr"), "h `n") +Stdin:=FileOpen(DllCall("GetStdHandle", "int", -10, "ptr"), "h `n") + +;Full Unicode-support font needed +e:=SetConsoleOutputCP(65001) +if (e && A_IsUnicode) +{ + Print("△ - Unicode delta (U+25b3)") + GetPos(x,y) + if (x=0 && y=0) ;nothing prints if Non-Unicode font + Print("Non-Unicode font") +} +else + Print("Unicode not supported") +Pause() + +Print(string=""){ + global Stdout + if (!StrLen(string)) + return 1 + e:=DllCall("WriteConsole" . ((A_IsUnicode) ? "W" : "A") + , "UPtr", Stdout.__Handle + , "Str", string + , "UInt", strlen(string) + , "UInt*", Written + , "uint", 0) + if (!e) or (ErrorLevel) + return 0 ;Failure + Stdout.Read(0) + return e +} + +SetConsoleOutputCP(codepage) { + e:=DllCall("SetConsoleOutputCP","UInt",codepage) + if (!e) or (ErrorLevel) + return 0 ;Failure + return 1 +} + +GetPos(ByRef x, ByRef y) { + global Stdout + VarSetCapacity(struct,22,0) + e:=DllCall("GetConsoleScreenBufferInfo","UPtr",Stdout.__Handle,"Ptr",&struct) + if (!e) or (ErrorLevel) + return 0 ;Failure + x:=NumGet(&struct,4,"UShort") + y:=NumGet(&struct,6,"UShort") + return 1 +} + +Pause() { + RunWait, %comspec% /c pause>NUL +} diff --git a/Task/Terminal-control-Unicode-output/Ruby/terminal-control-unicode-output.rb b/Task/Terminal-control-Unicode-output/Ruby/terminal-control-unicode-output.rb new file mode 100644 index 0000000000..d9cf891f57 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Ruby/terminal-control-unicode-output.rb @@ -0,0 +1,7 @@ +#encoding: UTF-8 # superfluous in Ruby >1.9.3 + +if ENV.values_at("LC_ALL","LC_CTYPE","LANG").compact.first.include?("UTF-8") + puts "△" +else + raise "Terminal can't handle UTF-8" +end diff --git a/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl b/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl index 0fb1c714ca..1b8c6a8011 100644 --- a/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl +++ b/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl @@ -5,7 +5,7 @@ out_dates_from_file( Name ) -> {ok, Binary} = file:read_file( Name ), Lines = binary:split( Binary, <<"\n">>, [global] ), - {_N, Dict} = lists:foldl( fun out_dates/2, {0, dict:new()}, Lines ), + {_N, _Date, Dict} = lists:foldl( fun out_dates/2, {0, "", dict:new()}, Lines ), [{X, dict:fetch(X, Dict)} || X <- dict:fetch_keys( Dict )]. task() -> @@ -15,11 +15,11 @@ task() -> out_dates( <<>>, Acc ) -> Acc; -out_dates( Line, {N, Dict} ) -> - [_License, Direction, <<"@">>, Date | _T] = [X || X <- binary:split(Line, <<" ">>, [global]), X =/= <<>>], +out_dates( Line, {N, Date, Dict} ) -> + [_License, Direction, <<"@">>, New_date | _T] = [X || X <- binary:split(Line, <<" ">>, [global]), X =/= <<>>], New_n = out_dates_n( N, Direction ), New_dict = out_dates_dict( N, New_n, Date, Dict ), - {New_n, New_dict}. + {New_n, New_date, New_dict}. out_dates_dict( N, New_n, Date, Dict ) when N > New_n -> dict:append( N, Date, Dict ); out_dates_dict( _N, _New_n, _Date, Dict ) -> Dict. diff --git a/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math b/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math index 8f9ed9fd98..07c76084ba 100644 --- a/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math +++ b/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math @@ -4,6 +4,3 @@ LC = 0; LCMax = 0; Scan[ If[LCMax == LC, AppendTo[LCMaxtimes, #[[4]]]], LC--;] &, Import["mlijobs.txt", "Table"]] Print["The maximum number of licenses used was ", LCMax, ", at ", LCMaxtimes] - -output: --> The maximum number of licenses used was 99, at {2008/10/03_08:39:34,2008/10/03_08:40:40} diff --git a/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d b/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d index b62c39d352..bf9eb0a045 100644 --- a/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d +++ b/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d @@ -1,67 +1,68 @@ import std.stdio, std.range, std.array, std.algorithm, std.math; struct Domain { - real b, e, s; + const real b, e, s; - auto range() const /*pure nothrow*/ { - // return iota(b, e + s, s); - return iota(cast()b, e + s, s); + auto range() const pure /*nothrow*/ { + return iota(b, e + s, s); } } real eval0(alias RY, alias X, alias Y)(in real x) pure nothrow { real a = 0.0L; - foreach_reverse (i; 2 .. X.length - 3) + foreach_reverse (immutable i; 2 .. X.length - 3) a = (x - X[i]) / (RY[i] - RY[i-2] + a); return Y[1] + (x - X[1]) / (RY[1] + a); } -struct Thiele { +immutable struct Thiele { immutable real[] Y, X, rhoY, rhoX; - this(real[] y, real[] x) /*pure nothrow*/ + this(real[] y, real[] x) immutable pure /*nothrow*/ in { assert(x.length > 2, "at leat 3 values"); assert(x.length == y.length, "input arrays not of same size"); } body { - this.Y = y.idup; + this.Y = y.idup; // Not nothrow. this.X = x.idup; rhoY = rhoN(Y, X); rhoX = rhoN(X, Y); } - this(in real delegate(real) f, - Domain d=Domain(0.0L, 1.55L, 0.05L)) { - auto xrng = d.range().array(); - this(array(map!f(xrng)), xrng); + this(in real function(real) pure nothrow f, + Domain d=Domain(0.0L, 1.55L, 0.05L)) + immutable pure /*nothrow*/ { + auto xrng = d.range.array; + this(xrng.map!f.array, xrng); } - auto rhoN(immutable(real)[] y, immutable(real)[] x) /*pure*/ { - int N = x.length; - real[][] p = new real[][](N, N); - p[0][] = y[]; // array/vector operation follow - p[1][0..$-1] = (x[0 .. $-1] - x[1 .. $]) / - (p[0][0 .. $-1] - p[0][1 .. $]); - foreach (int j; 2 .. N - 1) { + auto rhoN(immutable(real)[] y, immutable(real)[] x) + pure nothrow { + immutable int N = x.length; + auto p = new real[][](N, N); + p[0][] = y[]; + p[1][0 .. $ - 1] = (x[0 .. $-1] - x[1 .. $]) / + (p[0][0 .. $-1] - p[0][1 .. $]); + foreach (immutable int j; 2 .. N - 1) { immutable M = N - j - 1; p[j][0..M] = p[j-2][1..M+1] + (x[0..M] - x[j..M+j]) / (p[j-1][0 .. M] - p[j-1][1 .. M+1]); } - return p.map!q{a[1]}().array().idup; + return p.map!q{ a[1] }.array; } - alias eval0!(rhoY, X, Y) eval; - alias eval0!(rhoX, Y, X) inverse; + alias eval = eval0!(rhoY, X, Y); + alias inverse = eval0!(rhoX, Y, X); } void main() { - // can't pass sin,cos,tan directly - auto tsin = Thiele((real x) => sin(x)); - auto tcos = Thiele((real x) => cos(x)); - auto ttan = Thiele((real x) => tan(x)); + // Can't pass sin, cos and tan directly. + immutable tsin = Thiele(x => x.sin); + immutable tcos = Thiele(x => x.cos); + immutable ttan = Thiele(x => x.tan); writefln(" %d interpolating points\n", tsin.X.length); - writefln("std.math.sin(0.5): %20.18f", sin(0.5L)); + writefln("std.math.sin(0.5): %20.18f", 0.5L.sin); writefln(" Thiele sin(0.5): %20.18f\n", tsin.eval(0.5L)); writefln("*%20.19f library constant", PI); diff --git a/Task/Tic-tac-toe/D/tic-tac-toe.d b/Task/Tic-tac-toe/D/tic-tac-toe.d index 0b41f6f465..78e042ca98 100644 --- a/Task/Tic-tac-toe/D/tic-tac-toe.d +++ b/Task/Tic-tac-toe/D/tic-tac-toe.d @@ -1,48 +1,44 @@ -import std.stdio, std.string, std.algorithm, std.conv, - std.random, std.ascii, std.array, std.range; +import std.stdio, std.string, std.algorithm, std.conv, std.random, + std.ascii, std.array, std.range, std.math; struct GameBoard { dchar[9] board = "123456789"; - enum : char { human = 'X', computer = 'O' } + enum : dchar { human = 'X', computer = 'O' } enum Game { going, humanWins, computerWins, draw } const pure nothrow invariant() { + int nHuman = 0, nComputer = 0; foreach (immutable i, immutable c; board) if (c.isDigit) - assert(i == c - '1'); // in correct position? - else + assert(i == c - '1'); // In correct position? + else { assert(c == human || c == computer); + (c == human ? nHuman : nComputer)++; + } + assert(abs(nHuman - nComputer) <= 1); } string toString() const pure { - return format("%(%-(%s|%)\n-+-+-\n%)", board.dup.chunks(3)); + return format("%(%-(%s|%)\n-+-+-\n%)", board[].chunks(3)); } bool isAvailable(in int i) const pure nothrow { - if (i < 0 || i >= 9) - return false; - return board[i].isDigit; + return i >= 0 && i < 9 && board[i].isDigit; } int[] availablePositions() const pure nothrow { - // not pure not nothrow: - //return 9.iota.filter!(i => board[i].isDigit).array; - int[] result; - foreach (immutable i; 0 .. 9) - if (isAvailable(i)) - result ~= i; - return result; + return 9.iota.filter!(i => isAvailable(i)).array; } Game winner() const pure nothrow { - immutable wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], - [0, 3, 6], [1, 4, 7], [2, 5, 8], - [0, 4, 8], [2, 4, 6]]; + static immutable wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], + [0, 3, 6], [1, 4, 7], [2, 5, 8], + [0, 4, 8], [2, 4, 6]]; foreach (immutable win; wins) { immutable bw0 = board[win[0]]; if (bw0.isDigit) - continue; // nobody wins on this one + continue; // Nobody wins on this one. if (bw0 == board[win[1]] && bw0 == board[win[2]]) return bw0 == GameBoard.human ? @@ -53,16 +49,16 @@ struct GameBoard { return availablePositions.empty ? Game.draw: Game.going; } - bool finished() const pure nothrow { + bool isFinished() const pure nothrow { return winner != Game.going; } - int computerMove() const // random move + int computerMove() const // Random move. out(res) { assert(res >= 0 && res < 9 && isAvailable(res)); } body { - // return choice(availablePositions()); - return randomCover(availablePositions, rndGen).front; + // return availablePositions.choice; + return availablePositions[uniform(0, $)]; } } @@ -71,7 +67,7 @@ GameBoard playGame() { GameBoard board; bool playsHuman = true; - while (!board.finished) { + while (!board.isFinished) { board.writeln; int move; @@ -85,7 +81,7 @@ GameBoard playGame() { return board; } while (!board.isAvailable(move)); } else - move = board.computerMove(); + move = board.computerMove; assert(board.isAvailable(move)); writefln("\n%s chose %d", playsHuman ? "You" : "I", move + 1); @@ -99,21 +95,21 @@ GameBoard playGame() { void main() { - writeln("Tic-tac-toe game player.\n"); + "Tic-tac-toe game player.\n".writeln; immutable outcome = playGame.winner; final switch (outcome) { case GameBoard.Game.going: - writeln("Game stopped."); + "Game stopped.".writeln; break; case GameBoard.Game.humanWins: - writeln("\nYou win!"); + "\nYou win!".writeln; break; case GameBoard.Game.computerWins: - writeln("\nI win."); + "\nI win.".writeln; break; case GameBoard.Game.draw: - writeln("\nDraw"); + "\nDraw".writeln; break; } } diff --git a/Task/Tic-tac-toe/Erlang/tic-tac-toe.erl b/Task/Tic-tac-toe/Erlang/tic-tac-toe.erl new file mode 100644 index 0000000000..57496c6b36 --- /dev/null +++ b/Task/Tic-tac-toe/Erlang/tic-tac-toe.erl @@ -0,0 +1,105 @@ +-module(tic_tac_toe). + +-export( [task/0] ). + +task() -> io:fwrite( "Result: ~p.~n", [turn(player(random:uniform()), board())] ). + + + +board() -> [{X, erlang:integer_to_list(X)} || X <- lists:seq(1, 9)]. + +board_tuples( Selections, Board ) -> [lists:keyfind(X, 1, Board) || X <- Selections]. + +computer_move( Player, Board ) -> + [N | _T] = lists:flatten( [X(Player, Board) || X <- [fun computer_move_win/2, fun computer_move_block/2, fun computer_move_middle/2, fun computer_move_random/2]] ), + N. + +computer_move_block( Player, Board ) -> computer_move_two_same_player( player(false, Player), Board ). + +computer_move_middle( _Player, Board ) -> + {5, Y} = lists:keyfind( 5, 1, Board ), + computer_move_middle( is_empty(Y) ). + +computer_move_middle( true ) -> [5]; +computer_move_middle( false ) -> []. + +computer_move_random( _Player, Board ) -> + Ns = [X || {X, Y} <- Board, is_empty(Y)], + [lists:nth( random:uniform(erlang:length(Ns)), Ns )]. + +computer_move_two_same_player( Player, Board ) -> + Selections = [X || X <- three_in_row_all(), is_two_same_player(Player, X, Board)], + computer_move_two_same_player( Player, Board, Selections ). + +computer_move_two_same_player( _Player, _Board, [] ) -> []; +computer_move_two_same_player( _Player, Board, [Selection | _T] ) -> [X || {X, Y} <- board_tuples(Selection, Board), is_empty(Y)]. + +computer_move_win( Player, Board ) -> computer_move_two_same_player( Player, Board ). + +is_empty( Square ) -> Square =< "9". % Do not use < "10". + +is_finished( Board ) -> is_full( Board ) orelse is_three_in_row( Board ). + +is_full( Board ) -> [] =:= [X || {X, Y} <- Board, is_empty(Y)]. + +is_three_in_row( Board ) -> + Fun = fun(Selections) -> is_three_in_row_same_player( board_tuples(Selections, Board) ) end, + lists:any( Fun, three_in_row_all() ). + +is_three_in_row_same_player( Selected ) -> three_in_row_player( Selected ) =/= no_player. + +is_two_same_player( Player, Selections, Board ) -> is_two_same_player( Player, [{X, Y} || {X, Y} <- board_tuples(Selections, Board), not is_empty(Y)] ). + +is_two_same_player( Player, [{_X, Player}, {_Y, Player}] ) -> true; +is_two_same_player( _Player, _Selected ) -> false. + +player( Random ) when Random > 0.5 -> "O"; +player( _Random ) -> "X". + +player( true, _Player ) -> finished; +player( false, "X" ) -> "O"; +player( false, "O" ) -> "X". + +result( Board ) -> result( is_full(Board), Board ). + +result( true, _Board ) -> draw; +result( false, Board ) -> + [Winners] = [Selections || Selections <- three_in_row_all(), three_in_row_player(board_tuples(Selections, Board)) =/= no_player], + "Winner is " ++ three_in_row_player( board_tuples(Winners, Board) ). + +three_in_row_all() -> three_in_row_horisontal() ++ three_in_row_vertical() ++ three_in_row_diagonal(). +three_in_row_diagonal() -> [[1,5,9], [3,5,7]]. +three_in_row_horisontal() -> [[1,2,3], [4,5,6], [7,8,9]]. +three_in_row_vertical() -> [[1,4,7], [2,5,8], [3,6,9]]. + +three_in_row_player( [{_X, Player}, {_Y, Player}, {_Z, Player}] ) -> three_in_row_player( not is_empty(Player), Player ); +three_in_row_player( _Selected ) -> no_player. + +three_in_row_player( true, Player ) -> Player; +three_in_row_player( false, _Player ) -> no_player. + +turn( finished, Board ) -> result( Board ); +turn( "X"=Player, Board ) -> + N = computer_move( Player, Board ), + io:fwrite( "Computer, ~p, selected ~p~n", [Player, N] ), + New_board = [{N, Player} | lists:keydelete(N, 1, Board)], + turn( player(is_finished(New_board), Player), New_board ); +turn( "O"=Player, Board ) -> + [turn_board_write_horisontal(X, Board) || X <- three_in_row_horisontal()], + Ns = [X || {X, Y} <- Board, is_empty(Y)], + Prompt = lists:flatten( io_lib:format("Player, ~p, select one of ~p: ", [Player, Ns]) ), + N = turn_next_move( Prompt, Ns ), + New_board = [{N, Player} | lists:keydelete(N, 1, Board)], + turn( player(is_finished(New_board), Player), New_board ). + +turn_board_write_horisontal( Selections, Board ) -> + Tuples = [lists:keyfind(X, 1, Board) || X <- Selections], + [io:fwrite( "~p ", [Y]) || {_X, Y} <- Tuples], + io:fwrite( "~n" ). + +turn_next_move( Prompt, Ns ) -> + {ok,[N]} = io:fread( Prompt, "~d" ), + turn_next_move_ok( lists:member(N, Ns), Prompt, Ns, N ). + +turn_next_move_ok( true, _Prompt, _Ns, N ) -> N; +turn_next_move_ok( false, Prompt, Ns, _N ) -> turn_next_move( Prompt, Ns ). diff --git a/Task/Tic-tac-toe/Java/tic-tac-toe-3.java b/Task/Tic-tac-toe/Java/tic-tac-toe-3.java new file mode 100644 index 0000000000..2260d5bfe2 --- /dev/null +++ b/Task/Tic-tac-toe/Java/tic-tac-toe-3.java @@ -0,0 +1,474 @@ +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; + + +//Make sure the name of the class is the same as the .java file name. +//If you change the class name you should change the class object name in runGUI method +public class ticTacToeCallum implements ActionListener { + + static JFrame frame; + static JPanel contentPane; + static JLabel lblEnterFirstPlayerName, lblEnterSecondPlayerName, lblFirstPlayerScore, lblSecondPlayerScore; + static JButton btnButton1, btnButton2, btnButton3, btnButton4, btnButton5, btnButton6, btnButton7, btnButton8, btnButton9, btnClearBoard, btnClearAll, btnCloseGame; + static JTextField txtEnterFirstPlayerName, txtEnterSecondPlayerName; + static Icon imgicon = new ImageIcon("saveIcon.JPG"); + + Font buttonFont = new Font("Arial", Font.PLAIN, 20); + + + //to adjust the frame size change the values in pixels + static int width = 600; + static int length = 400; + static int firstPlayerScore = 0; + static int secondPlayerScore = 0; + static int playerTurn = 1; + static int roundComplete = 0; + static int button1 = 1, button2 = 1, button3 = 1, button4 = 1, button5 = 1, button6 = 1, button7 = 1, button8 = 1, button9 = 1; // 1 is true, 0 is false + + + public ticTacToeCallum(){ + + frame = new JFrame("Tic Tac Toe ^_^"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + contentPane = new JPanel(); + contentPane.setLayout(new GridLayout(6, 3, 10, 10)); + contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); + + btnButton1 = new JButton(""); + btnButton1.setFont(buttonFont); + btnButton1.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton1.setIcon(imgicon); + btnButton1.setActionCommand("CLICK1"); + btnButton1.addActionListener(this); + contentPane.add(btnButton1); + + btnButton2 = new JButton(""); + btnButton2.setFont(buttonFont); + btnButton2.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton2.setIcon(imgicon); + btnButton2.setActionCommand("CLICK2"); + btnButton2.addActionListener(this); + contentPane.add(btnButton2); + + btnButton3 = new JButton(""); + btnButton3.setFont(buttonFont); + btnButton3.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton3.setIcon(imgicon); + btnButton3.setActionCommand("CLICK3"); + btnButton3.addActionListener(this); + contentPane.add(btnButton3); + + btnButton4 = new JButton(""); + btnButton4.setFont(buttonFont); + btnButton4.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton4.setIcon(imgicon); + btnButton4.setActionCommand("CLICK4"); + btnButton4.addActionListener(this); + contentPane.add(btnButton4); + + btnButton5 = new JButton(""); + btnButton5.setFont(buttonFont); + btnButton5.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton5.setIcon(imgicon); + btnButton5.setActionCommand("CLICK5"); + btnButton5.addActionListener(this); + contentPane.add(btnButton5); + + btnButton6 = new JButton(""); + btnButton6.setFont(buttonFont); + btnButton6.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton6.setIcon(imgicon); + btnButton6.setActionCommand("CLICK6"); + btnButton6.addActionListener(this); + contentPane.add(btnButton6); + + btnButton7 = new JButton(""); + btnButton7.setFont(buttonFont); + btnButton7.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton7.setIcon(imgicon); + btnButton7.setActionCommand("CLICK7"); + btnButton7.addActionListener(this); + contentPane.add(btnButton7); + + btnButton8 = new JButton(""); + btnButton8.setFont(buttonFont); + btnButton8.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton8.setIcon(imgicon); + btnButton8.setActionCommand("CLICK8"); + btnButton8.addActionListener(this); + contentPane.add(btnButton8); + + btnButton9 = new JButton(""); + btnButton9.setFont(buttonFont); + btnButton9.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnButton9.setIcon(imgicon); + btnButton9.setActionCommand("CLICK9"); + btnButton9.addActionListener(this); + contentPane.add(btnButton9); + + lblEnterFirstPlayerName = new JLabel("Enter First Player's Name"); + contentPane.add(lblEnterFirstPlayerName); + + txtEnterFirstPlayerName = new JTextField(""); + contentPane.add(txtEnterFirstPlayerName); + + lblFirstPlayerScore = new JLabel("Score: " + firstPlayerScore); + contentPane.add(lblFirstPlayerScore); + + lblEnterSecondPlayerName = new JLabel("Enter Second Player's Name"); + contentPane.add(lblEnterSecondPlayerName); + + txtEnterSecondPlayerName = new JTextField(""); + contentPane.add(txtEnterSecondPlayerName); + + lblSecondPlayerScore = new JLabel("Score: " + secondPlayerScore); + contentPane.add(lblSecondPlayerScore); + + btnClearBoard = new JButton("Clear Board"); + btnClearBoard.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnClearBoard.setIcon(imgicon); + btnClearBoard.setActionCommand("CLICKClearBoard"); + btnClearBoard.addActionListener(this); + contentPane.add(btnClearBoard); + + btnClearAll = new JButton("Clear All"); + btnClearAll.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnClearAll.setIcon(imgicon); + btnClearAll.setActionCommand("CLICKClearAll"); + btnClearAll.addActionListener(this); + contentPane.add(btnClearAll); + + btnCloseGame = new JButton("Close Game"); + btnCloseGame.setAlignmentX(JButton.CENTER_ALIGNMENT); + btnCloseGame.setIcon(imgicon); + btnCloseGame.setActionCommand("CLICKCloseGame"); + btnCloseGame.addActionListener(this); + contentPane.add(btnCloseGame); + + frame.setContentPane(contentPane); + frame.pack(); + frame.setSize(width,length); + frame.setVisible(true); + + } + + public void actionPerformed(ActionEvent event) { + String eventName = event.getActionCommand(); + if (eventName.equals("CLICK1")) { + if (button1 == 1){ + if (playerTurn == 1){ + btnButton1.setForeground(Color.RED); + btnButton1.setText("X"); + playerTurn = 2; + button1 = 0; + } else if (playerTurn == 2) { + btnButton1.setForeground(Color.GREEN); + btnButton1.setText("O"); + playerTurn = 1; + button1 = 0; + } + } + } else if (eventName.equals ("CLICK2")) { + if (button2 == 1){ + if (playerTurn == 1){ + btnButton2.setForeground(Color.RED); + btnButton2.setText("X"); + playerTurn = 2; + button2 = 0; + } else if (playerTurn == 2) { + btnButton2.setForeground(Color.GREEN); + btnButton2.setText("O"); + playerTurn = 1; + button2 = 0; + } + } + } else if (eventName.equals ("CLICK3")) { + if (button3 == 1){ + if (playerTurn == 1){ + btnButton3.setForeground(Color.RED); + btnButton3.setText("X"); + playerTurn = 2; + button3 = 0; + } else if (playerTurn == 2) { + btnButton3.setForeground(Color.GREEN); + btnButton3.setText("O"); + playerTurn = 1; + button3 = 0; + } + } + } else if (eventName.equals ("CLICK4")) { + if (button4 == 1){ + if (playerTurn == 1){ + btnButton4.setForeground(Color.RED); + btnButton4.setText("X"); + playerTurn = 2; + button4 = 0; + } else if (playerTurn == 2) { + btnButton4.setForeground(Color.GREEN); + btnButton4.setText("O"); + playerTurn = 1; + button4 = 0; + } + } + } else if (eventName.equals ("CLICK5")) { + if (button5 == 1){ + if (playerTurn == 1){ + btnButton5.setForeground(Color.RED); + btnButton5.setText("X"); + playerTurn = 2; + button5 = 0; + } else if (playerTurn == 2) { + btnButton5.setForeground(Color.GREEN); + btnButton5.setText("O"); + playerTurn = 1; + button5 = 0; + } + } + } else if (eventName.equals ("CLICK6")) { + if (button6 == 1){ + if (playerTurn == 1){ + btnButton6.setForeground(Color.RED); + btnButton6.setText("X"); + playerTurn = 2; + button6 = 0; + } else if (playerTurn == 2) { + btnButton6.setForeground(Color.GREEN); + btnButton6.setText("O"); + playerTurn = 1; + button6 = 0; + } + } + } else if (eventName.equals ("CLICK7")) { + if (button7 == 1){ + if (playerTurn == 1){ + btnButton7.setForeground(Color.RED); + btnButton7.setText("X"); + playerTurn = 2; + button7 = 0; + } else if (playerTurn == 2) { + btnButton7.setForeground(Color.GREEN); + btnButton7.setText("O"); + playerTurn = 1; + button7 = 0; + } + } + } else if (eventName.equals ("CLICK8")) { + if (button8 == 1){ + if (playerTurn == 1){ + btnButton8.setForeground(Color.RED); + btnButton8.setText("X"); + playerTurn = 2; + button8 = 0; + } else if (playerTurn == 2) { + btnButton8.setForeground(Color.GREEN); + btnButton8.setText("O"); + playerTurn = 1; + button8 = 0; + } + } + } else if (eventName.equals ("CLICK9")) { + if (button9 == 1){ + if (playerTurn == 1){ + btnButton9.setForeground(Color.RED); + btnButton9.setText("X"); + playerTurn = 2; + button9 = 0; + } else if (playerTurn == 2) { + btnButton9.setForeground(Color.GREEN); + btnButton9.setText("O"); + playerTurn = 1; + button9 = 0; + } + } + } else if (eventName.equals ("CLICKClearBoard")) { + + btnButton1.setText(""); + btnButton2.setText(""); + btnButton3.setText(""); + btnButton4.setText(""); + btnButton5.setText(""); + btnButton6.setText(""); + btnButton7.setText(""); + btnButton8.setText(""); + btnButton9.setText(""); + + button1 = 1; + button2 = 1; + button3 = 1; + button4 = 1; + button5 = 1; + button6 = 1; + button7 = 1; + button8 = 1; + button9 = 1; + + playerTurn = 1; + + roundComplete = 0; + + } else if (eventName.equals ("CLICKClearAll")) { + + btnButton1.setText(""); + btnButton2.setText(""); + btnButton3.setText(""); + btnButton4.setText(""); + btnButton5.setText(""); + btnButton6.setText(""); + btnButton7.setText(""); + btnButton8.setText(""); + btnButton9.setText(""); + + firstPlayerScore = 0; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + secondPlayerScore = 0; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + + txtEnterFirstPlayerName.setText(""); + txtEnterSecondPlayerName.setText(""); + + button1 = 1; + button2 = 1; + button3 = 1; + button4 = 1; + button5 = 1; + button6 = 1; + button7 = 1; + button8 = 1; + button9 = 1; + + playerTurn = 1; + + roundComplete = 0; + + } else if (eventName.equals ("CLICKCloseGame")) { + System.exit(0); + } + score(); + } + + + public static void score(){ + if (roundComplete == 0){ + if (btnButton1.getText().equals(btnButton2.getText()) && btnButton1.getText().equals(btnButton3.getText())){ + if (btnButton1.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton1.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton1.getText().equals(btnButton4.getText()) && btnButton1.getText().equals(btnButton7.getText())){ + if (btnButton1.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton1.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton1.getText().equals(btnButton5.getText()) && btnButton1.getText().equals(btnButton9.getText())){ + if (btnButton1.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton1.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton7.getText().equals(btnButton8.getText()) && btnButton7.getText().equals(btnButton9.getText())){ + if (btnButton7.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton7.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton7.getText().equals(btnButton5.getText()) && btnButton7.getText().equals(btnButton3.getText())){ + if (btnButton7.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton7.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton3.getText().equals(btnButton6.getText()) && btnButton3.getText().equals(btnButton9.getText())){ + if (btnButton3.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton3.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton4.getText().equals(btnButton5.getText()) && btnButton4.getText().equals(btnButton6.getText())){ + if (btnButton4.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton4.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + if (btnButton2.getText().equals(btnButton5.getText()) && btnButton2.getText().equals(btnButton8.getText())){ + if (btnButton2.getText().equals("X")){ + firstPlayerScore += 1; + lblFirstPlayerScore.setText("Score: " + firstPlayerScore); + roundComplete = 1; + } else if (btnButton2.getText().equals("O")){ + secondPlayerScore += 1; + lblSecondPlayerScore.setText("Score: " + secondPlayerScore); + roundComplete = 1; + } + } + } + if (roundComplete == 1){ + button1 = 0; + button2 = 0; + button3 = 0; + button4 = 0; + button5 = 0; + button6 = 0; + button7 = 0; + button8 = 0; + button9 = 0; + } + } + + /** + * Create and show the GUI. + */ + private static void runGUI() { + ticTacToeCallum greeting = new ticTacToeCallum(); + } + + + + //Do not change this method + public static void main(String[] args) { + /* Methods that create and show a GUI should be run from an event-dispatching thread */ + javax.swing.SwingUtilities.invokeLater(new Runnable() { + public void run() { + runGUI(); + } + }); + } +} diff --git a/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb b/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb index cf0c48c982..83f410bf30 100644 --- a/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb +++ b/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb @@ -1,4 +1,5 @@ module TicTacToe + ROWS = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]] class Game def initialize(player1Class, player2Class) @@ -9,9 +10,8 @@ module TicTacToe puts "#{@players[@turn]} goes first." @players[@turn].marker = "X" @players[nextTurn].marker = "O" - @winning_rows = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]] end - attr_reader :free_positions, :winning_rows, :board + attr_reader :free_positions, :board, :turn def play loop do @@ -22,10 +22,10 @@ module TicTacToe @free_positions.delete(idx) # check for a winner - @winning_rows.each do |row| + ROWS.each do |row| if row.all? {|idx| @board[idx] == player.marker} puts "#{player} wins!" - print + print_board return end end @@ -33,7 +33,7 @@ module TicTacToe # no winner, is board full? if @free_positions.empty? puts "It's a draw." - print + print_board return end @@ -42,7 +42,7 @@ module TicTacToe end def nextTurn - (@turn + 1) % 2 + 1 - @turn end def nextTurn! @@ -53,12 +53,9 @@ module TicTacToe @players[nextTurn] end - def print - puts [1,2,3].map {|i| @board[i].nil? ? i : @board[i]}.join("|") - puts "-+-+-" - puts [4,5,6].map {|i| @board[i].nil? ? i : @board[i]}.join("|") - puts "-+-+-" - puts [7,8,9].map {|i| @board[i].nil? ? i : @board[i]}.join("|") + def print_board + display =lambda{|row| row.map {|i| @board[i] ? @board[i] : i}.join("|")} + puts display[[1,2,3]], "-+-+-", display[[4,5,6]], "-+-+-", display[[7,8,9]] end end @@ -71,20 +68,13 @@ module TicTacToe end class HumanPlayer < Player - def initialize(game) - super(game) - end - def select - @game.print + @game.print_board loop do print "Select your #{marker} position: " - selection = $stdin.gets.to_i - if not @game.free_positions.include?(selection) - puts "Position #{selection} is not available. Try again." - next - end - return selection + selection = gets.to_i + return selection if @game.free_positions.include?(selection) + puts "Position #{selection} is not available. Try again." end end @@ -94,50 +84,45 @@ module TicTacToe end class ComputerPlayer < Player - def initialize(game) - super(game) - end - - def group_row(row, opponent) - markers = {self.marker => [], opponent.marker => [], nil => []} . - merge(row.group_by {|idx| @game.board[idx]}) - #p [row, markers].inspect + def group_row(row) + markers = row.group_by {|idx| @game.board[idx]} + markers.default = [] markers end def select - index = nil - opponent = @game.opponent + opponent_marker = @game.opponent.marker # look for winning rows - @game.winning_rows.each do |row| - markers = group_row(row, opponent) - if markers[self.marker].length == 2 and markers[nil].length == 1 + for row in ROWS + markers = group_row(row) + next if markers[nil].length != 1 + if markers[self.marker].length == 2 return markers[nil].first + elsif markers[opponent_marker].length == 2 + idx = markers[nil].first end end # look for opponent's winning rows to block - @game.winning_rows.each do |row| - markers = group_row(row, opponent) - if markers[opponent.marker].length == 2 and markers[nil].length == 1 - return markers[nil].first - end - end + return idx if idx # need some logic here to get the computer to pick a smarter position # simply pick a position in order of preference - [5].concat([1,3,7,9].shuffle).concat([2,4,6,8].shuffle).each do |pos| - return pos if @game.free_positions.include?(pos) + ([5] + [1,3,7,9].shuffle + [2,4,6,8].shuffle).find do |pos| + @game.free_positions.include?(pos) end end def to_s - "Computer" + "Computer#{@game.turn}" end end end -TicTacToe::Game.new(TicTacToe::ComputerPlayer, TicTacToe::ComputerPlayer).play -TicTacToe::Game.new(TicTacToe::HumanPlayer, TicTacToe::ComputerPlayer).play +include TicTacToe + +Game.new(ComputerPlayer, ComputerPlayer).play +puts +Game.new(HumanPlayer,ComputerPlayer).play diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-1.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-1.basic new file mode 100644 index 0000000000..0e9b29bd70 --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-1.basic @@ -0,0 +1,20 @@ +100 T$ = "HELLO,HOW,ARE,YOU,TODAY" +110 GOSUB 200"TOKENIZE +120 FOR I = 1 TO N +130 PRINT A$(I) "." ; +140 NEXT +150 PRINT +160 END + +200 IF N = 0 THEN DIM A$(256) +210 N = 1 +220 A$(N) = " +230 FOR TI = 1 TO LEN(T$) +240 C$ = MID$(T$, TI, 1) +250 T = C$ = "," +260 IF T THEN C$ = " +270 N = N + T +280 IF T THEN A$(N) = C$ +290 A$(N) = A$(N) + C$ +300 NEXT TI +310 RETURN diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic new file mode 100644 index 0000000000..e6220da699 --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic @@ -0,0 +1,14 @@ +Sub Main() + Dim parseMe As String, parsed As Variant + parseMe = "Hello,How,Are,You,Today" + + parsed = Split(parseMe, ",") + + Dim L0 As Long, outP As String + outP = parsed(0) + For L0 = 1 To UBound(parsed) + outP = outP & "." & parsed(L0) + Next + + MsgBox outP +End Sub diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic new file mode 100644 index 0000000000..ed538d7a3d --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic @@ -0,0 +1,8 @@ + INSTALL @lib$+"STRINGLIB" + + text$ = "Hello,How,Are,You,Today" + n% = FN_split(text$, ",", array$()) + FOR i% = 0 TO n%-1 + PRINT array$(i%) "." ; + NEXT + PRINT diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic new file mode 100644 index 0000000000..02fe2206ae --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic @@ -0,0 +1,7 @@ +'Note that Liberty Basic's array usage can reach element #10 before having to DIM the array +For i = 0 To 4 + array$(i) = Word$("Hello,How,Are,You,Today", (i + 1), ",") + array$ = array$ + array$(i) + "." +Next i + +Print Left$(array$, (Len(array$) - 1)) diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic new file mode 100644 index 0000000000..2f5dbd573f --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic @@ -0,0 +1,15 @@ +FUNCTION PBMAIN () AS LONG + DIM parseMe AS STRING + parseMe = "Hello,How,Are,You,Today" + + REDIM parsed(PARSECOUNT(parseMe) - 1) AS STRING + PARSE parseMe, parsed() 'comma is default delimiter + + DIM L0 AS LONG, outP AS STRING + outP = parsed(0) + FOR L0 = 1 TO UBOUND(parsed) 'could reuse parsecount instead of ubound + outP = outP & "." & parsed(L0) + NEXT + + MSGBOX outP +END FUNCTION diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic new file mode 100644 index 0000000000..28e4e237da --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic @@ -0,0 +1,10 @@ +NewList MyStrings.s() + +For i=1 To 5 + AddElement(MyStrings()) + MyStrings()=StringField("Hello,How,Are,You,Today",i,",") +Next i + +ForEach MyStrings() + Print(MyStrings()+".") +Next diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic new file mode 100644 index 0000000000..c68564a14c --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic @@ -0,0 +1 @@ +Print(ReplaceString("Hello,How,Are,You,Today",",",".")) diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-7.basic similarity index 100% rename from Task/Tokenize-a-string/BASIC/tokenize-a-string.basic rename to Task/Tokenize-a-string/BASIC/tokenize-a-string-7.basic diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic new file mode 100644 index 0000000000..7c11088ae7 --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic @@ -0,0 +1,5 @@ +text$ = "Hello,How,Are,You,Today" +FOR i = 1 to 5 + textArray$(i) = word$(text$,i,",") + print textArray$(i);" "; +NEXT diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic new file mode 100644 index 0000000000..2e5b6a5fa3 --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic @@ -0,0 +1 @@ +WScript.Echo Join(Split("Hello,How,Are,You,Today", ","), ".") diff --git a/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj b/Task/Tokenize-a-string/Clojure/tokenize-a-string-1.clj similarity index 100% rename from Task/Tokenize-a-string/Clojure/tokenize-a-string.clj rename to Task/Tokenize-a-string/Clojure/tokenize-a-string-1.clj diff --git a/Task/Tokenize-a-string/Clojure/tokenize-a-string-2.clj b/Task/Tokenize-a-string/Clojure/tokenize-a-string-2.clj new file mode 100644 index 0000000000..b550ad22bc --- /dev/null +++ b/Task/Tokenize-a-string/Clojure/tokenize-a-string-2.clj @@ -0,0 +1 @@ +(clojure.string/join "." (clojure.string/split "Hello,How,Are,You,Today" #",")) diff --git a/Task/Tokenize-a-string/Deja-Vu/tokenize-a-string.djv b/Task/Tokenize-a-string/Deja-Vu/tokenize-a-string.djv new file mode 100644 index 0000000000..4345d87a08 --- /dev/null +++ b/Task/Tokenize-a-string/Deja-Vu/tokenize-a-string.djv @@ -0,0 +1 @@ +!print join "." split "Hello,How,Are,You,Today" "," diff --git a/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx b/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx index a9ecce8af8..377e0f9985 100644 --- a/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx +++ b/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx @@ -1,17 +1,17 @@ -/*REXX program to seperate a string of comma-delimited words, and echo. */ +/*REXX program seperates a string of comma-delimited words, and echoes. */ sss = 'Hello,How,Are,You,Today' /*words seperated by commas (,). */ -say 'input string='sss /*display the original string. */ +say 'input string =' sss /*display the original string. */ new=sss /*make a copy of the string. */ - - do items=1 until new=='' /*keep going until SSS is empty. */ - parse var new a.items ',' new /*parse words delinated by comma.*/ - end /*items*/ + /* [↓] string NEW is destroyed. */ + do items=1 until new=='' /*keep going until NEW is empty.*/ + parse var new a.items ',' new /*parse words delinated by comma.*/ + end /*items*/ /* [↑] the array is named A. */ say; say 'Words in the string:' /*display a header for the list. */ - do k=1 for items /*now, display all the words. */ - say a.k'.' /*append a period to the word. */ - end /*k*/ + do j=1 for items /*now, display all the words. */ + say a.j || left('.', j\==items) /*append period to word, maybe. */ + end /*j*/ /* [↑] don't append "." if last.*/ say 'End-of-list.' /*display a trailer for the list.*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Top-rank-per-group/Bracmat/top-rank-per-group.bracmat b/Task/Top-rank-per-group/Bracmat/top-rank-per-group.bracmat new file mode 100644 index 0000000000..f3ec04f9df --- /dev/null +++ b/Task/Top-rank-per-group/Bracmat/top-rank-per-group.bracmat @@ -0,0 +1,40 @@ + (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) + : ?employees +& ( toprank + = employees N n P "Employee Name" "Employee ID" SalaryDepartment + . !arg:(?employees.?N) + & 1:?P + & whl + ' ( !employees + : (?"Employee Name",?"Employee ID",?Salary,?Department) + ?employees + & !Department^(!Salary.!"Employee Name".!"Employee ID")*!P:?P + ) + & out$(Top !N "salaries per department.") + & whl + ' ( !P:%?Department^?employees*?P + & out$(str$("Department " !Department ":")) + & !N:?n + & whl + ' ( !n+-1:~<0:?n + & !employees + : ?employees+(?Salary.?"Employee Name".?"Employee ID") + & out + $ (str$(" " !"Employee Name" " (" !"Employee ID" "):" !Salary)) + ) + ) + ) +& toprank$(!employees.3) +& ; diff --git a/Task/Top-rank-per-group/PL-I/top-rank-per-group.pli b/Task/Top-rank-per-group/PL-I/top-rank-per-group.pli new file mode 100644 index 0000000000..d3b4a395b9 --- /dev/null +++ b/Task/Top-rank-per-group/PL-I/top-rank-per-group.pli @@ -0,0 +1,83 @@ +(subrg, stringrange, stringsize): +rank: procedure options (main); /* 10 November 2013 */ + + declare 1 employee (13), + 2 name char (15) varying, + 2 ID char (6), + 2 salary fixed (5), + 2 department char (4); + declare done(hbound(employee)) bit (1); + declare ptr(hbound(employee)) fixed binary; + declare true bit(1) value ('1'b), false bit(1) value ('0'b); + declare dept character (4); + declare text character (80) varying; + declare (i, j, l, k, m, n, p, t) fixed binary; + declare in file input; + + open file (in) title ('/TOP-RANK.DAT, RECSIZE(80), TYPE(TEXT)' ); + + on endfile (in) go to completed_input; + j = 0; + do forever; + get file (in) edit (text) (L); + j = j + 1; + i = index(text, ','); + name(j) = substr(text, 1, i-1); + k = index(text, ',', i+1); + ID(j) = substr(text, i+1, k-(i+1)); + i = k; k = index(text, ',', i+1); + salary(j) = substr(text, i+1, k-(i+1)); + department(j) = substr(text, k+1); + end; + +completed_input: + m = hbound(employee); + put skip list ('How many highest-paid employees do you want?'); + get (n); + put skip edit ('Looking for the ', trim(n), + ' highest-paid employees in each department') (a); + done = false; + do i = 1 to m; + do j = 1 to m; + if done(j) then iterate; + dept = department(j); + /* done(j) = true; */ + leave; + end; + /* Locate all the employees of this department. */ + k = 0; + do j = 1 to m; + if ^done(j) & (department(j) = dept) then + do; + k = k + 1; + ptr(k) = j; + done(j) = true; + end; + end; + if k = 0 then leave; /* (No more departments.) */ + + put skip list ('Employees in department ' || dept || ' are:-' ); + do j = 1 to k; + put skip list (employee(ptr(j))); + end; + /* We now have k employees in "dept". Now find the maximum n salaries. */ + /* ptr points to all of them. */ + /* Use a bubble sort to move n values to one end. */ + do p = 1 to min(n, k); + do j = 1 to k-1; + if salary(ptr(j)) > salary(ptr(j+1)) then + do; + t = ptr(j+1); ptr(j+1) = ptr(j); ptr(j) = t; + end; + end; + end; + + /* Having moved the largest n values to the end of our list, */ + /* we print them. */ + put skip list ('Highest-paid employees in department ' || dept || ':-'); + do j = k to k-min(k,n)+1 by -1; + put skip list (employee(ptr(j)) ); + end; + end; + put skip list ('FINISHED'); +end rank; diff --git a/Task/Top-rank-per-group/Ruby/top-rank-per-group.rb b/Task/Top-rank-per-group/Ruby/top-rank-per-group.rb index 10493e8745..aad205702e 100644 --- a/Task/Top-rank-per-group/Ruby/top-rank-per-group.rb +++ b/Task/Top-rank-per-group/Ruby/top-rank-per-group.rb @@ -1,32 +1,32 @@ Employee = Struct.new(:name, :employee_id, :salary, :department) -def get_employees - [ - Employee.new("Tyler Bennett", "E10297", 32000, "D101"), - Employee.new("John Rappl", "E21437", 47000, "D050"), - Employee.new("George Woltman", "E00127", 53500, "D101"), - Employee.new("Adam Smith", "E63535", 18000, "D202"), - Employee.new("Claire Buckman", "E39876", 27800, "D202"), +employees = [ + Employee.new("Tyler Bennett", "E10297", 32000, "D101"), + Employee.new("John Rappl", "E21437", 47000, "D050"), + Employee.new("George Woltman", "E00127", 53500, "D101"), + Employee.new("Adam Smith", "E63535", 18000, "D202"), + Employee.new("Claire Buckman", "E39876", 27800, "D202"), Employee.new("David McClellan", "E04242", 41500, "D101"), - Employee.new("Rich Holcomb", "E01234", 49500, "D202"), - Employee.new("Nathan Adams", "E41298", 21900, "D050"), - Employee.new("Richard Potter", "E43128", 15900, "D101"), + Employee.new("Rich Holcomb", "E01234", 49500, "D202"), + Employee.new("Nathan Adams", "E41298", 21900, "D050"), + Employee.new("Richard Potter", "E43128", 15900, "D101"), Employee.new("David Motsinger", "E27002", 19250, "D202"), - Employee.new("Tim Sampair", "E03033", 27000, "D101"), - Employee.new("Kim Arlich", "E10001", 57000, "D190"), - Employee.new("Timothy Grove", "E16398", 29900, "D190"), - ] -end + Employee.new("Tim Sampair", "E03033", 27000, "D101"), + Employee.new("Kim Arlich", "E10001", 57000, "D190"), + Employee.new("Timothy Grove", "E16398", 29900, "D190"), +] def show_top_salaries_per_group(groups, n) groups.each do |dept, emps| puts dept # sort by salary descending - emps.sort_by {|emp| -emp.salary}[0,n].each {|e| p e} + emps.sort_by {|emp| -emp.salary}.first(n).each do |e| + puts " %-16s %6s %7d" % [e.name, e.employee_id, e.salary] + end puts end end -groups = get_employees.group_by {|emp| emp.department} +groups = employees.group_by {|emp| emp.department}.sort show_top_salaries_per_group(groups,3) 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 index 2e7cce61ba..383db88067 100644 --- a/Task/Top-rank-per-group/Scala/top-rank-per-group.scala +++ b/Task/Top-rank-per-group/Scala/top-rank-per-group.scala @@ -1,6 +1,8 @@ -object TopRank extends Application { - import scala.io._ - val data = """Tyler Bennett,E10297,32000,D101 +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 @@ -14,12 +16,19 @@ 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 = id +"\t"+salary+"\t"+name - } - Source.fromString(data).getLines().map(_.split(",")).map(x => new Employee(x(0), x(1), x(2).toInt, x(3) )).toList // read data into list of employees - .sortBy(x => (x.department, -x.salary)).groupBy(_.department).foreach{ group => // sort and group by - println("Department: "+group._1) - group._2.take(3).foreach{x => println("\t"+x) } - } + 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/Topic-variable/Forth/topic-variable-1.fth b/Task/Topic-variable/Forth/topic-variable-1.fth new file mode 100644 index 0000000000..78f2b2c68f --- /dev/null +++ b/Task/Topic-variable/Forth/topic-variable-1.fth @@ -0,0 +1 @@ +: myloop 11 1 do i . loop cr ; myloop diff --git a/Task/Topic-variable/Forth/topic-variable-2.fth b/Task/Topic-variable/Forth/topic-variable-2.fth new file mode 100644 index 0000000000..5905ab39e8 --- /dev/null +++ b/Task/Topic-variable/Forth/topic-variable-2.fth @@ -0,0 +1,5 @@ +: ^2 dup * ; +: sqrt 0 tuck ?do 1+ dup 2* 1+ +loop ; +: topic >r r@ ^2 . r@ sqrt . r> drop ; + +23 topic diff --git a/Task/Topic-variable/PicoLisp/topic-variable-1.l b/Task/Topic-variable/PicoLisp/topic-variable-1.l new file mode 100644 index 0000000000..ab67987acc --- /dev/null +++ b/Task/Topic-variable/PicoLisp/topic-variable-1.l @@ -0,0 +1,9 @@ +PicoLisp sets the value of the variable (symbol) '@' to the result of +conditional and controlling expressions in flow- and logic-functions (cond, if, +and, when, while, etc.). + +Within a function or method '@' behaves like a local variable, i.e. its value is +automatically saved upon function entry and restored at exit. + +For example, to read the current input channel until EOF, and print the square +of every item which is a number: diff --git a/Task/Topic-variable/PicoLisp/topic-variable-2.l b/Task/Topic-variable/PicoLisp/topic-variable-2.l new file mode 100644 index 0000000000..f918af0c2e --- /dev/null +++ b/Task/Topic-variable/PicoLisp/topic-variable-2.l @@ -0,0 +1,9 @@ +(while (read) + (when (num? @) + (println (* @ @)) ) ) +abc # Not a number +7 # Number +49 # -> print square +xyz # Not a number +3 # Number +9 # -> print square diff --git a/Task/Topswops/Erlang/topswops.erl b/Task/Topswops/Erlang/topswops.erl new file mode 100644 index 0000000000..2f56bc750a --- /dev/null +++ b/Task/Topswops/Erlang/topswops.erl @@ -0,0 +1,21 @@ +-module( topswops ). + +-export( [get_1_first/1, swap/1, task/0] ). + +get_1_first( [1 | _T] ) -> 0; +get_1_first( List ) -> 1 + get_1_first( swap(List) ). + +swap( [N | _T]=List ) -> + {Swaps, Remains} = lists:split( N, List ), + lists:reverse( Swaps ) ++ Remains. + +task() -> + Permutations = [{X, permute:permute(lists:seq(1, X))} || X <- lists:seq(1, 10)], + Swops = [{N, get_1_first_many(N_permutations)} || {N, N_permutations} <- Permutations], + Topswops = [{N, lists:max(N_swops)} || {N, N_swops} <- Swops], + io:fwrite( "N topswaps~n" ), + [io:fwrite("~p ~p~n", [N, Max]) || {N, Max} <- Topswops]. + + + +get_1_first_many( N_permutations ) -> [get_1_first(X) || X <- N_permutations]. diff --git a/Task/Topswops/PL-I/topswops.pli b/Task/Topswops/PL-I/topswops.pli new file mode 100644 index 0000000000..a4580b876d --- /dev/null +++ b/Task/Topswops/PL-I/topswops.pli @@ -0,0 +1,32 @@ +(subscriptrange): +topswap: procedure options (main); /* 12 November 2013 */ + declare cards(*) fixed (2) controlled, t fixed (2); + declare dealt(*) bit(1) controlled; + declare (count, i, m, n, c1, c2) fixed binary; + declare random builtin; + + do n = 1 to 10; + allocate cards(n), dealt(n); + /* Take the n cards, in order ... */ + do i = 1 to n; cards(i) = i; end; + /* ... and shuffle them. */ + do i = 1 to n; + c1 = random*n+1; c2 = random*n+1; + t = cards(c1); cards(c1) = cards(c2); cards(c2) = t; + end; + /* If '1' is the first card, game is trivial; swap it with another. */ + if cards(1) = 1 & n > 1 then + do; t = cards(1); cards(1) = cards(2); cards(2) = t; end; + + count = 0; + do until (cards(1) = 1); + /* take the value of the first card, M, and reverse the first M cards. */ + m = cards(1); + do i = 1 to m/2; + t = cards(i); cards(i) = cards(m-i+1); cards(m-i+1) = t; + end; + count = count + 1; + end; + put skip edit (n, ':', count) (f(2), a, f(4)); + end; +end topswap; diff --git a/Task/Topswops/Perl/topswops.pl b/Task/Topswops/Perl/topswops.pl new file mode 100644 index 0000000000..e24bf6afce --- /dev/null +++ b/Task/Topswops/Perl/topswops.pl @@ -0,0 +1,35 @@ +sub next_swop { + my( $max, $level, $p, $d ) = @_; + my $swopped = 0; + for( 2..@$p ){ # find possibilities + my @now = @$p; + if( $_ == $now[$_-1] ) { + splice @now, 0, 0, reverse splice @now, 0, $_; + $swopped = 1; + next_swop( $max, $level+1, \@now, [ @$d ] ); + } + } + for( 1..@$d ) { # create possibilities + my @now = @$p; + my $next = shift @$d; + if( not $now[$next-1] ) { + $now[$next-1] = $next; + splice @now, 0, 0, reverse splice @now, 0, $next; + $swopped = 1; + next_swop( $max, $level+1, \@now, [ @$d ] ); + } + push @$d, $next; + } + $$max = $level if !$swopped and $level > $$max; +} + +sub topswops { + my $n = shift; + my @d = 2..$n; + my @p = ( 1, (0) x ($n-1) ); + my $max = 0; + next_swop( \$max, 0, \@p, \@d ); + return $max; +} + +printf "Maximum swops for %2d cards: %2d\n", $_, topswops $_ for 1..10; diff --git a/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic deleted file mode 100644 index 30bf2aaf7e..0000000000 --- a/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic +++ /dev/null @@ -1,26 +0,0 @@ -10 DIM N(1024), F(1024), T(1024), V(1024): REM STACK PER PARAMETER -20 SP = 0: REM STACK POINTER -30 N(SP) = 4: REM START WITH 4 DISCS -40 F(SP) = 1: REM ON PEG 1 -50 T(SP) = 2: REM MOVE TO PEG 2 -60 V(SP) = 3: REM VIA PEG 3 -70 GOSUB 100 -80 END -90 REM MOVE SUBROUTINE -100 IF N(SP) = 0 THEN RETURN -110 OS = SP: REMEMBER STACK POINTER -120 SP = SP + 1: REM INCREMENT STACK POINTER -130 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS -140 F(SP) = F(OS) : REM FROM START PEG -150 T(SP) = V(OS) : REM TO VIA PEG -160 V(SP) = T(OS) : REM VIA TO PEG -170 GOSUB 100 -180 OS = SP - 1: REM OS WILL HAVE CHANGED -190 PRINT "MOVE DISC FROM"; F(OS); "TO"; T(OS) -200 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS -210 F(SP) = V(OS) : REM FROM VIA PEG -220 T(SP) = T(OS) : REM TO DEST PEG -230 V(SP) = F(OS) : REM VIA FROM PEG -240 GOSUB 100 -250 SP = SP - 1 : REM RESTORE STACK POINTER FOR CALLER -260 RETURN diff --git a/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi.cobol b/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi.cobol new file mode 100644 index 0000000000..7db3fbff4e --- /dev/null +++ b/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi.cobol @@ -0,0 +1,28 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. towers-of-hanoi. + +PROCEDURE DIVISION. + CALL "move-disk" USING 4, 1, 2, 3 + . +END PROGRAM towers-of-hanoi. + +IDENTIFICATION DIVISION. +PROGRAM-ID. move-disk RECURSIVE. + +DATA DIVISION. +LINKAGE SECTION. +01 n PIC 9 USAGE COMP. +01 from-pole PIC 9 USAGE COMP. +01 to-pole PIC 9 USAGE COMP. +01 via-pole PIC 9 USAGE COMP. + +PROCEDURE DIVISION USING n, from-pole, to-pole, via-pole. + IF n > 0 + SUBTRACT 1 FROM n + CALL "move-disk" USING CONTENT n, from-pole, via-pole, to-pole + DISPLAY "Move disk from pole " from-pole " to pole " to-pole + CALL "move-disk" USING CONTENT n, via-pole, to-pole, from-pole + END-IF + . +END PROGRAM move-disk. diff --git a/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d b/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d index 5d46e90c78..a4eff3782d 100644 --- a/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d +++ b/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d @@ -1,18 +1,18 @@ -import std.stdio, std.conv, std.typetuple; - +// Code found and then improved by Glenn C. Rhoads, +// then some more by M. Kolar (2000). void main(in string[] args) { - // Code found and then improved by Glenn C. Rhoads, - // then some more by M. Kolar (2000). + import core.stdc.stdio, std.conv, std.typetuple; - immutable size_t n = (args.length > 1) ? to!size_t(args[1]) : 3; + immutable size_t n = (args.length > 1) ? args[1].to!size_t : 3; size_t[3] p = [(1 << n) - 1, 0, 0]; - printf("\n|"); - foreach_reverse (size_t i; 1 .. n + 1) - printf(" %zd", i); - printf("\n|\n|\n"); + // Show the start configuration of the pegs. + '|'.putchar; + foreach_reverse (immutable i; 1 .. n + 1) + printf(" %d", i); + "\n|\n|".puts; - foreach (size_t x; 1 .. (1 << n)) { + foreach (immutable size_t x; 1 .. (1 << n)) { { immutable size_t i1 = x & (x - 1); immutable size_t fr = (i1 + i1 / 3) & 3; @@ -20,7 +20,7 @@ void main(in string[] args) { immutable size_t to = (i2 + i2 / 3) & 3; size_t j = 1; - for (int w = x; !(w & 1); w >>= 1, j <<= 1) {} + for (size_t w = x; !(w & 1); w >>= 1, j <<= 1) {} // Now j is not the number of the disk to move, // it contains the single bit to be moved: @@ -28,16 +28,16 @@ void main(in string[] args) { p[to] |= j; } - foreach (immutable(size_t) k; TypeTuple!(0, 1, 2)) { - printf("\n|"); + // Show the current configuration of pegs. + foreach (immutable size_t k; TypeTuple!(0, 1, 2)) { + "\n|".printf; size_t j = 1 << n; - foreach_reverse (size_t w; 1 .. n + 1) { + foreach_reverse (immutable size_t w; 1 .. n + 1) { j >>= 1; if (j & p[k]) printf(" %zd", w); } } - - putchar('\n'); + '\n'.putchar; } } diff --git a/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy index ab463c0910..3f457d6375 100644 --- a/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy +++ b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy @@ -1,11 +1,11 @@ enum Ring { - S('°'), M('o'), L('O'), XL('()'); + S('°'), M('o'), L('O'), XL('( )'); private sym private Ring(sym) { this.sym=sym } String toString() { sym } } -report = { STACK.keySet().each { println "${it}: ${STACK[it]}" }; println() } +report = { STACK.each { k, v -> println "${k}: ${v}" }; println() } check = { to -> assert to == ([] + to).sort().reverse() } Ring.values().reverseEach { STACK.A << it } diff --git a/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb index 9f3f00215a..a9cecc1be4 100644 --- a/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb +++ b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb @@ -1,10 +1,14 @@ -def move(num_disks, starting_stick, target_stick, using_stick) +def move(num_disks, start=0, target=1, using=2) if num_disks == 1 - target_stick << starting_stick.shift - status + @towers[target] << @towers[start].pop + puts "Move disk from #{start} to #{target} : #{@towers}" else - move(num_disks-1, starting_stick, using_stick, target_stick) - move(1, starting_stick, target_stick, using_stick) - move(num_disks-1, using_stick, target_stick, starting_stick) + move(num_disks-1, start, using, target) + move(1, start, target, using) + move(num_disks-1, using, target, start) end end + +n = 5 +@towers = [[*1..n].reverse, [], []] +move(n) diff --git a/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb index 5bb8c7aad6..592a43a1aa 100644 --- a/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb +++ b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb @@ -1,4 +1,3 @@ -require 'pp' # solve(source, via, target) # Example: # solve([5, 4, 3, 2, 1], [], []) @@ -8,7 +7,7 @@ def solve(*towers) # total number of disks disks = towers.inject(0){|sum, tower| sum+tower.length} x=0 # sequence number - pp towers # initial trace + p towers # initial trace # have we solved the puzzle yet? while towers.last.length < disks do x+=1 # assume the next step @@ -21,8 +20,10 @@ def solve(*towers) if !bottom || bottom > top # ok, do it! towers[to].push(towers[from].pop) - pp towers # trace + p towers # trace end end end end + +solve([5, 4, 3, 2, 1], [], []) diff --git a/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust b/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust new file mode 100644 index 0000000000..3aa300aa82 --- /dev/null +++ b/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust @@ -0,0 +1,11 @@ +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)); + move(n - 1, via, to, from); + } +} + +fn main() { + move(4, 1,2,3); +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/AWK/trabb-pardo-knuth-algorithm.awk b/Task/Trabb-Pardo-Knuth-algorithm/AWK/trabb-pardo-knuth-algorithm.awk new file mode 100644 index 0000000000..2bd4424963 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/AWK/trabb-pardo-knuth-algorithm.awk @@ -0,0 +1,17 @@ +# syntax: GAWK -f TRABB_PARDO-KNUTH_ALGORITHM.AWK +BEGIN { + printf("enter 11 numbers: ") + getline S + n = split(S,arr," ") + if (n != 11) { + printf("%d numbers entered; S/B 11\n",n) + exit(1) + } + for (i=n; i>0; i--) { + x = f(arr[i]) + printf("f(%s) = %s\n",arr[i],(x>400) ? "too large" : x) + } + exit(0) +} +function abs(x) { if (x >= 0) { return x } else { return -x } } +function f(x) { return sqrt(abs(x)) + 5 * x ^ 3 } diff --git a/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d b/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d index 691cb480c8..2ef00c00eb 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d +++ b/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d @@ -1,20 +1,21 @@ -import std.stdio, std.math, std.range, std.conv, std.algorithm; +import std.stdio, std.math, std.conv, std.algorithm, std.array; double f(in double x) pure nothrow { - return x.abs().sqrt() + 5 * x ^^ 3; + return x.abs.sqrt + 5 * x ^^ 3; } void main() { double[] data; + while (true) { - write("Please enter eleven numbers on a line: "); - data = readln().split().map!(to!double)().array(); + "Please enter eleven numbers on a line: ".write; + data = readln.split.map!(to!double).array; if (data.length == 11) break; writeln("Those aren't eleven numbers."); } - foreach (x; data.retro()) { - immutable y = f(x); - writefln("f(%0.3f) = %s", x, y > 400 ? "Too large" : text(y)); + foreach_reverse (immutable x; data) { + immutable y = x.f; + writefln("f(%0.3f) = %s", x, y > 400 ? "Too large" : y.text); } } diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Erlang/trabb-pardo-knuth-algorithm.erl b/Task/Trabb-Pardo-Knuth-algorithm/Erlang/trabb-pardo-knuth-algorithm.erl new file mode 100644 index 0000000000..6d61477277 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Erlang/trabb-pardo-knuth-algorithm.erl @@ -0,0 +1,23 @@ +-module( trabb_pardo_knuth ). + +-export( [task/0] ). + +task() -> + Sequence = get_11_numbers(), + S = lists:reverse( Sequence ), + [perform_operation( fun function/1, 400, X) || X <- S]. + + +alert( N ) -> io:fwrite( "Operation on ~p overflowed~n", [N] ). + +get_11_numbers() -> + {ok, Ns} = io:fread( "Input 11 integers. Space delimited, please: ", "~d ~d ~d ~d ~d ~d ~d ~d ~d ~d ~d" ), + 11 = erlang:length( Ns ), + Ns. + +function( X ) -> math:sqrt( erlang:abs(X) ) + 5 * math:pow( X, 3 ). + +perform_operation( Fun, Overflow, N ) -> perform_operation_check_overflow( N, Fun(N), Overflow ). + +perform_operation_check_overflow( N, Result, Overflow ) when Result > Overflow -> alert( N ); +perform_operation_check_overflow( N, Result, _Overflow ) -> io:fwrite( "f(~p) => ~p~n", [N, Result] ). diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PL-I/trabb-pardo-knuth-algorithm.pli b/Task/Trabb-Pardo-Knuth-algorithm/PL-I/trabb-pardo-knuth-algorithm.pli new file mode 100644 index 0000000000..baf241e252 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PL-I/trabb-pardo-knuth-algorithm.pli @@ -0,0 +1,25 @@ +Trabb: Procedure options (main); /* 11 November 2013 */ + + declare (i, n) fixed binary; + declare s fixed (5,1) controlled; + declare g fixed (15,5); + + put ('Please type 11 values:'); + do i = 1 to 11; + allocate s; + get (s); + put (s); + end; + put skip(2) ('Results:'); + do i = 1 to 11; + g = f(s); put skip list (s); + if g > 400 then put ('Too large'); else put (g); + free s; + end; + +f: procedure (x) returns (fixed(15,5)); + declare x fixed (5,1); + return (sqrt(abs(x)) + 5*x**3); +end f; + +end Trabb; diff --git a/Task/Tree-traversal/D/tree-traversal-3.d b/Task/Tree-traversal/D/tree-traversal-3.d new file mode 100644 index 0000000000..e2080f23d1 --- /dev/null +++ b/Task/Tree-traversal/D/tree-traversal-3.d @@ -0,0 +1,65 @@ +import std.stdio, std.algorithm, std.range, std.string; + +const struct Tree(T) { + T value; + Tree* left, right; +} + +alias VisitRange(T) = InputRange!(const Tree!T); + +VisitRange!T preOrder(T)(in Tree!T* t) /*pure nothrow*/ { + enum self = mixin("&" ~ __FUNCTION__.split(".").back); + if (t == null) + return typeof(return).init.takeNone.inputRangeObject; + return [*t] + .chain([t.left, t.right] + .filter!(t => t != null) + .map!(a => self(a)) + .joiner) + .inputRangeObject; +} + +VisitRange!T inOrder(T)(in Tree!T* t) /*pure nothrow*/ { + enum self = mixin("&" ~ __FUNCTION__.split(".").back); + if (t == null) + return typeof(return).init.takeNone.inputRangeObject; + return [t.left] + .filter!(t => t != null) + .map!(a => self(a)) + .joiner + .chain([*t]) + .chain([t.right] + .filter!(t => t != null) + .map!(a => self(a)) + .joiner) + .inputRangeObject; +} + +VisitRange!T postOrder(T)(in Tree!T* t) /*pure nothrow*/ { + enum self = mixin("&" ~ __FUNCTION__.split(".").back); + if (t == null) + return typeof(return).init.takeNone.inputRangeObject; + return [t.left, t.right] + .filter!(t => t != null) + .map!(a => self(a)) + .joiner + .chain([*t]) + .inputRangeObject; +} + +void main() { + alias N = Tree!int; + const tree = new N(1, + new N(2, + new N(4, + new N(7)), + new N(5)), + new N(3, + new N(6, + new N(8), + new N(9)))); + + tree.preOrder.map!(t => t.value).writeln; + tree.inOrder.map!(t => t.value).writeln; + tree.postOrder.map!(t => t.value).writeln; +} diff --git a/Task/Tree-traversal/Eiffel/tree-traversal-1.e b/Task/Tree-traversal/Eiffel/tree-traversal-1.e new file mode 100644 index 0000000000..89b08ac3e7 --- /dev/null +++ b/Task/Tree-traversal/Eiffel/tree-traversal-1.e @@ -0,0 +1,51 @@ +note + description : "Application for tree traversal demonstration" + output : "[ + Prints preorder, inorder, postorder and levelorder traversal of an example binary tree. + ]" + author : "Jascha Grübel" + date : "$2014-01-07$" + revision : "$1.0$" + +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Run Tree traversal example. + local + tree:NODE + do + create tree.make (1) + tree.set_left_child (create {NODE}.make (2)) + tree.set_right_child (create {NODE}.make (3)) + tree.left_child.set_left_child (create {NODE}.make (4)) + tree.left_child.set_right_child (create {NODE}.make (5)) + tree.left_child.left_child.set_left_child (create {NODE}.make (7)) + tree.right_child.set_left_child (create {NODE}.make (6)) + tree.right_child.left_child.set_left_child (create {NODE}.make (8)) + tree.right_child.left_child.set_right_child (create {NODE}.make (9)) + + Io.put_string ("preorder: ") + tree.print_preorder + Io.put_new_line + + Io.put_string ("inorder: ") + tree.print_inorder + Io.put_new_line + + Io.put_string ("postorder: ") + tree.print_postorder + Io.put_new_line + + Io.put_string ("level-order:") + tree.print_levelorder + Io.put_new_line + + end + +end -- class APPLICATION diff --git a/Task/Tree-traversal/Eiffel/tree-traversal-2.e b/Task/Tree-traversal/Eiffel/tree-traversal-2.e new file mode 100644 index 0000000000..a51d9080a1 --- /dev/null +++ b/Task/Tree-traversal/Eiffel/tree-traversal-2.e @@ -0,0 +1,127 @@ +note + description : "A simple node for a binary tree" + libraries : "Relies on LINKED_LIST from EiffelBase" + author : "Jascha Grübel" + date : "$2014-01-07$" + revision : "$1.0$" + implementation : "[ + All traversals but the levelorder traversal have been implemented recursively. + The levelorder traversal is solved iteratively. + ]" + +class + NODE +create + make + +feature {NONE} -- Initialization + + make (a_value:INTEGER) + -- Creates a node with no children. + do + value := a_value + set_right_child(Void) + set_left_child(Void) + end + +feature -- Modification + + set_right_child (a_node:NODE) + -- Sets `right_child' to `a_node'. + do + right_child:=a_node + end + + set_left_child (a_node:NODE) + -- Sets `left_child' to `a_node'. + do + left_child:=a_node + end + +feature -- Representation + + print_preorder + -- Recursively prints the value of the node and all its children in preorder + do + Io.put_string (" " + value.out) + if has_left_child then + left_child.print_preorder + end + if has_right_child then + right_child.print_preorder + end + end + + print_inorder + -- Recursively prints the value of the node and all its children in inorder + do + if has_left_child then + left_child.print_inorder + end + Io.put_string (" " + value.out) + if has_right_child then + right_child.print_inorder + end + end + + print_postorder + -- Recursively prints the value of the node and all its children in postorder + do + if has_left_child then + left_child.print_postorder + end + if has_right_child then + right_child.print_postorder + end + Io.put_string (" " + value.out) + end + + print_levelorder + -- Iteratively prints the value of the node and all its children in levelorder + local + l_linked_list:LINKED_LIST[NODE] + l_node:NODE + do + from + create l_linked_list.make + l_linked_list.extend (Current) + until + l_linked_list.is_empty + loop + l_node := l_linked_list.first + if l_node.has_left_child then + l_linked_list.extend (l_node.left_child) + end + if l_node.has_right_child then + l_linked_list.extend (l_node.right_child) + end + Io.put_string (" " + l_node.value.out) + l_linked_list.prune (l_node) + end + end + +feature -- Access + + value:INTEGER + -- Value stored in the node. + + right_child:NODE + -- Reference to right child, possibly void. + + left_child:NODE + -- Reference to left child, possibly void. + + has_right_child:BOOLEAN + -- Test right child for existence. + do + Result := right_child /= Void + end + + has_left_child:BOOLEAN + -- Test left child for existence. + do + Result := left_child /= Void + end + +end + -- class NODE diff --git a/Task/Tree-traversal/Julia/tree-traversal.julia b/Task/Tree-traversal/Julia/tree-traversal.julia new file mode 100644 index 0000000000..b415c27b9f --- /dev/null +++ b/Task/Tree-traversal/Julia/tree-traversal.julia @@ -0,0 +1,22 @@ +tree = {1, {2, {4, {7,{},{}}, + {}}, + {5, {},{}}}, + {3, {6, {8,{},{}}, + {9,{},{}}}, + {}}} + +preorder(t,f) = if !isempty(t) + f(t[1]) ; preorder(t[2],f) ; preorder(t[3],f) + end + +inorder(t,f) = if !isempty(t) + inorder(t[2],f) ; f(t[1]) ; inorder(t[3],f) + end + +postorder(t,f) = if !isempty(t) + postorder(t[2],f) ; postorder(t[3],f) ; f(t[1]) + end + +levelorder(t,f) = while !isempty(t) + t = mapreduce(x->isa(x,Number)? (f(x);{}): x, vcat, t) + end diff --git a/Task/Tree-traversal/Objeck/tree-traversal.objeck b/Task/Tree-traversal/Objeck/tree-traversal.objeck new file mode 100644 index 0000000000..f3ac00733d --- /dev/null +++ b/Task/Tree-traversal/Objeck/tree-traversal.objeck @@ -0,0 +1,112 @@ +use Collection; + +class Test { + function : Main(args : String[]) ~ Nil { + one := Node->New(1); + two := Node->New(2); + three := Node->New(3); + four := Node->New(4); + five := Node->New(5); + six := Node->New(6); + seven := Node->New(7); + eight := Node->New(8); + nine := Node->New(9); + + one->SetLeft(two); one->SetRight(three); + two->SetLeft(four); two->SetRight(five); + three->SetLeft(six); four->SetLeft(seven); + six->SetLeft(eight); six->SetRight(nine); + + "Preorder: "->Print(); Preorder(one); + "\nInorder: "->Print(); Inorder(one); + "\nPostorder: "->Print(); Postorder(one); + "\nLevelorder: "->Print(); Levelorder(one); + "\n"->Print(); + } + + function : Preorder(node : Node) ~ Nil { + if(node <> Nil) { + System.IO.Console->Print(node->GetData())->Print(", "); + Preorder(node->GetLeft()); + Preorder(node->GetRight()); + }; + } + + function : Inorder(node : Node) ~ Nil { + if(node <> Nil) { + Inorder(node->GetLeft()); + System.IO.Console->Print(node->GetData())->Print(", "); + Inorder(node->GetRight()); + }; + } + + function : Postorder(node : Node) ~ Nil { + if(node <> Nil) { + Postorder(node->GetLeft()); + Postorder(node->GetRight()); + System.IO.Console->Print(node->GetData())->Print(", "); + }; + } + + function : Levelorder(node : Node) ~ Nil { + nodequeue := Collection.Queue->New(); + if(node <> Nil) { + nodequeue->Add(node); + }; + + while(nodequeue->IsEmpty() = false) { + next := nodequeue->Remove()->As(Node); + System.IO.Console->Print(next->GetData())->Print(", "); + if(next->GetLeft() <> Nil) { + nodequeue->Add(next->GetLeft()); + }; + + if(next->GetRight() <> Nil) { + nodequeue->Add(next->GetRight()); + }; + }; + } +} + +class Node from BasicCompare { + @left : Node; + @right : Node; + @data : Int; + + New(data : Int) { + Parent(); + @data := data; + } + + method : public : GetData() ~ Int { + return @data; + } + + method : public : SetLeft(left : Node) ~ Nil { + @left := left; + } + + method : public : GetLeft() ~ Node { + return @left; + } + + method : public : SetRight(right : Node) ~ Nil { + @right := right; + } + + method : public : GetRight() ~ Node { + return @right; + } + + method : public : Compare(rhs : Compare) ~ Int { + right : Node := rhs->As(Node); + if(@data = right->GetData()) { + return 0; + } + else if(@data < right->GetData()) { + return -1; + }; + + return 1; + } +} diff --git a/Task/Tree-traversal/Perl-6/tree-traversal.pl6 b/Task/Tree-traversal/Perl-6/tree-traversal.pl6 index dad3253ac0..0703516899 100644 --- a/Task/Tree-traversal/Perl-6/tree-traversal.pl6 +++ b/Task/Tree-traversal/Perl-6/tree-traversal.pl6 @@ -39,7 +39,7 @@ class TreeNode { } } -my TreeNode $root = TreeNode.new( value => 1, +my TreeNode $root .= new( value => 1, left => TreeNode.new( value => 2, left => TreeNode.new( value => 4, left => TreeNode.new(value => 7)), right => TreeNode.new( value => 5) diff --git a/Task/Trigonometric-functions/D/trigonometric-functions.d b/Task/Trigonometric-functions/D/trigonometric-functions.d index a4edec07e4..1de0732a6e 100644 --- a/Task/Trigonometric-functions/D/trigonometric-functions.d +++ b/Task/Trigonometric-functions/D/trigonometric-functions.d @@ -1,21 +1,21 @@ -import std.stdio, std.math; - void main() { - enum real degrees = 45.0; - enum real t0 = degrees * PI / 180.0; + import std.stdio, std.math; + + enum degrees = 45.0L; + enum t0 = degrees * PI / 180.0L; writeln("Reference: 0.7071067811865475244008"); - writefln("Sine: %.20f %.20f", sin(PI_4), sin(t0)); - writefln("Cosine: %.20f %.20f", cos(PI_4), cos(t0)); - writefln("Tangent: %.20f %.20f", tan(PI_4), tan(t0)); + writefln("Sine: %.20f %.20f", PI_4.sin, t0.sin); + writefln("Cosine: %.20f %.20f", PI_4.cos, t0.cos); + writefln("Tangent: %.20f %.20f", PI_4.tan, t0.tan); - writeln(); + writeln; writeln("Reference: 0.7853981633974483096156"); - immutable real t1 = asin(sin(PI_4)); - writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0 / PI); + immutable real t1 = PI_4.sin.asin; + writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0L / PI); - immutable real t2 = acos(cos(PI_4)); - writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0 / PI); + immutable real t2 = PI_4.cos.acos; + writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0L / PI); - immutable real t3 = atan(tan(PI_4)); - writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0 / PI); + immutable real t3 = PI_4.tan.atan; + writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0L / PI); } diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx index 51f55126eb..18db955584 100644 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx @@ -40,13 +40,12 @@ sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) .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 -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits();numeric digits 11 - g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end - numeric digits d; return g/1 -.sqrtGuess: if x<0 then call sqrtErr; numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 - +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*/ + numeric digits m.0; return (g/1)i e: return, 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 /*Note: the "real: E subroutine returns E's accuracy that */ @@ -80,9 +79,8 @@ 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): │ + │ Not included here are (among others): │ │ some of the usual higher-math functions normally associated │ │ with trig functions: POW, GAMMA, LGGAMMA, ERF, ERFC, ROOT, │ │ LOG (LN), LOG2, LOG10, ATAN2, │ @@ -90,7 +88,8 @@ sqrtErr: call tellErr "sqrt(x), X can't be negative, X="||x │ (too many to name here). │ │ Angle conversions/normalizations: degrees/radians/grads/mils │ │ [a circle = 2 pi radians, 360 degrees, 400 grads, 6400 mils].│ - │ Some of the other trig functions (hypens added intentially): │ + │ Some of the other trig functions are (hyphens were added │ + │ intentionally): │ │ CHORD │ │ COT (co-tangent) │ │ CSC (co-secant) │ diff --git a/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb b/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb index 83845f17f8..7f6d4c708c 100644 --- a/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb +++ b/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb @@ -10,26 +10,26 @@ end # Arcsine of _y_, domain [-1, 1], range [-pi/2, pi/2]. def asin(y, prec) - # Handle angles with no tangent. - return -PI / 2 if y == -1 - return PI / 2 if y == 1 + # Handle angles with no tangent. + return -PI / 2 if y == -1 + return PI / 2 if y == 1 - # Tangent of angle is y / x, where x^2 + y^2 = 1. - atan(y / sqrt(1 - y * y, prec), prec) + # Tangent of angle is y / x, where x^2 + y^2 = 1. + atan(y / sqrt(1 - y * y, prec), prec) end # Arccosine of _x_, domain [-1, 1], range [0, pi]. def acos(x, prec) - # Handle angle with no tangent. - return PI / 2 if x == 0 + # Handle angle with no tangent. + return PI / 2 if x == 0 - # Tangent of angle is y / x, where x^2 + y^2 = 1. - a = atan(sqrt(1 - x * x, prec) / x, prec) - if a < 0 - a + PI(prec) - else - a - end + # Tangent of angle is y / x, where x^2 + y^2 = 1. + a = atan(sqrt(1 - x * x, prec) / x, prec) + if a < 0 + a + PI(prec) + else + a + end end diff --git a/Task/Truncatable-primes/REXX/truncatable-primes.rexx b/Task/Truncatable-primes/REXX/truncatable-primes.rexx index dc3a990f59..89b2d346d2 100644 --- a/Task/Truncatable-primes/REXX/truncatable-primes.rexx +++ b/Task/Truncatable-primes/REXX/truncatable-primes.rexx @@ -3,7 +3,7 @@ parse arg high .; if high=='' then high=1000000 /*assume 1 million.*/ !.=0; Lp=0; Rp=0; w=length(high) /*placeholders for primes, Lp, Rp*/ p.1=2; p.2=3; p.3=5; p.4=7; p.5=11; p.6=13; p.7=17 /*some low primes.*/ !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1 /*low prime flags.*/ -n=7; s.7=17**2 /*number of primes so far. */ +n=7; s.n=p.n**2 /*number of primes so far. */ /*───────────────────────────────────────generate more primes ≤ high. */ do j=p.n+2 by 2 to high /*only find odd primes from here.*/ if j//3 ==0 then iterate /*is J divisible by three? */ diff --git a/Task/Truncatable-primes/Ruby/truncatable-primes.rb b/Task/Truncatable-primes/Ruby/truncatable-primes.rb index ce18f3017e..bcfdb7ea89 100644 --- a/Task/Truncatable-primes/Ruby/truncatable-primes.rb +++ b/Task/Truncatable-primes/Ruby/truncatable-primes.rb @@ -1,32 +1,21 @@ def left_truncatable?(n) - return truncatable?(n, $left_truncate) + truncatable?(n) {|i| i.to_s[1..-1].to_i} end -$left_truncate = proc do |n| - begin - n = Integer(String(n)[1..-1]) - rescue ArgumentError - n = 0 - end - n -end def right_truncatable?(n) - return truncatable?(n, $right_truncate) + truncatable?(n) {|i| i/10} end -$right_truncate = proc {|n| n/10} - -def truncatable?(n, trunc_func) - return false if String(n).include? "0" +def truncatable?(n, &trunc_func) + return false if n.to_s.include? "0" loop do n = trunc_func.call(n) - return true if n == 0 - return false if not Prime.prime?(n) + return true if n.zero? + return false unless Prime.prime?(n) end end -############# require 'prime' primes = Prime.each(1_000_000).to_a.reverse diff --git a/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-3.sh b/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-3.sh new file mode 100644 index 0000000000..a2929b3cf6 --- /dev/null +++ b/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-3.sh @@ -0,0 +1,87 @@ +# 1. simplest one-liner +-bash$ >file + +# or the more clear/verbose: +echo -n>file + +# 2. checks for file as input prior to truncate: +f="file";echo -n<$f>$f + +# double-check file size +ls -1 file # it's trunc + +# 3. multiple files (glob) +glob=$(ls -1 file[0-9]); for f in $glob; do echo -n<$f>$f; done + + +## OUTPUT: +# 1. one-liner +-bash-4.2$ echo -n>bad ++ echo -n +-bash-4.2$ ls -l bad; cat bad ++ ls -l bad +-rw-r--r-- 1 fieldsa fieldsa 0 Dec 4 20:07 bad ++ cat bad +-bash-4.2$ + +# 2. checks +-bash-4.2$ set -x; f="bad"; echo -n<$f>$f ++ f=bad ++ echo -n +-bash: bad: No such file or directory + +# Try again with the shortest version: f="bad"<$f>$f ++ ls -l bad +-rw-r--r-- 1 fieldsa fieldsa 8192 Dec 5 01:04 bad +-bash-4.2$ f="bad" <$f>$f ++ f=bad +-bash-4.2$ ls -l ++ ls -l +-rw-r--r-- 1 fieldsa fieldsa 0 Dec 5 01:04 bad +-bash-4.2$ rm bad ++ rm bad +-bash-4.2$ f="bad" <$f>$f ++ f=bad +-bash: bad: No such file or directory + +# Now a bad file exists +-bash-4.2$ echo 'abc'>bad ++ echo abc +-bash-4.2$ ls -l bad;cat$f ++ f=bad ++ echo -n +-bash-4.2$ ls -l bad;cat$f ++ f=bad +-bash: bad: No such file or directory + +# 4. trunc(): trunc file size # truncate at length +-bash-4.2$ trunc() { IFS= read -N $2 b<"$1"; echo -n "$b">"$1"; } +-bash-4.2$ echo "abcdef">bad; ls -l bad; cat bad; trunc bad 3; ls -l bad; cat bad; echo "_EOF_" ++ echo abcdef ++ ls -l bad +-rw-r--r-- 1 fieldsa fieldsa 7 Dec 4 19:59 bad ++ cat bad +abcdef ++ trunc bad 3 ++ read -N 3 b ++ echo -n abc ++ ls -l bad +-rw-r--r-- 1 fieldsa fieldsa 3 Dec 4 19:59 bad ++ cat bad +abc+ echo _EOF_ +_EOF_ diff --git a/Task/Twelve-statements/Bracmat/twelve-statements.bracmat b/Task/Twelve-statements/Bracmat/twelve-statements.bracmat new file mode 100644 index 0000000000..210ca1d4c5 --- /dev/null +++ b/Task/Twelve-statements/Bracmat/twelve-statements.bracmat @@ -0,0 +1,265 @@ +( + ( number + = n done ntest oldFT + . !arg:(?done.(=?ntest).?oldFT) + & 0:?n + & ( !done + : ? + ( !ntest + . !oldFT&1+!n:?n&~ + ) + ? + | !n + ) + ) + & ( STATEMENTS + = ( (1."This is a numbered list of twelve statements.") + . 1 + . ( + = n nr done toDo + . !arg:(?done.?toDo) + & 0:?n + & whl + ' ( !done:(?nr.?) ?done + & 1+!n:!nr:?n + ) + & whl + ' ( !toDo:((?nr.?).?) ?toDo + & 1+!n:!nr:?n + ) + & (!n:12&true|false) + ) + ) + ( (2."Exactly 3 of the last 6 statements are true.") + . end + . ( + = done toDo lastSix + . !arg:(?done.?toDo) + & !done:? [-7 ?lastSix + & ( number$(!lastSix.(=?).true):3 + & true + | false + ) + ) + ) + ( (3."Exactly 2 of the even-numbered statements are true.") + . end + . ( + = done toDo ii + . !arg:(?done.?toDo) + & ( number + $ ( !done + . (=?ii&!ii*1/2:~/) + . true + ) + : 2 + & true + | false + ) + ) + ) + ( (4."If statement 5 is true, then statements 6 and 7 are both true.") + . 7 + . ( + = done toDo + . !arg:(?done.?toDo) + & ( !done + : ( ? (5.false) ? + | ? (6.true) ? + : ? (7.true) ? + ) + & true + | false + ) + ) + ) + ( (5."The 3 preceding statements are all false.") + . 5 + . ( + = done toDo + . !arg:(?done.?toDo) + & ( !done + : ? + (?.false) + (?.false) + (?.false) + (?.?) + & true + | false + ) + ) + ) + ( (6."Exactly 4 of the odd-numbered statements are true.") + . end + . ( + = done toDo i + . !arg:(?done.?toDo) + & ( number + $ ( !done + . (=?i&!i*1/2:/) + . true + ) + : 4 + & true + | false + ) + ) + ) + ( (7."Either statement 2 or 3 is true, but not both.") + . 7 + . ( + = done toDo + . !arg:(?done.?toDo) + & ( number + $ (!done.(=2|3).true) + : 1 + & true + | false + ) + ) + ) + ( (8."If statement 7 is true, then 5 and 6 are both true.") + . 8 + . ( + = done toDo + . !arg:(?done.?toDo) + & ( !done + : ( ? (7.false) ? + | ? (5.true) ? + : ? (6.true) ? + ) + & true + | false + ) + ) + ) + ( (9."Exactly 3 of the first 6 statements are true.") + . 9 + . ( + = done toDo firstSix + . !arg:(?done.?toDo) + & !done:?firstSix [6 ? + & ( number$(!firstSix.(=?).true):3 + & true + | false + ) + ) + ) + ( (10."The next two statements are both true.") + . 12 + . ( + = done toDo + . !arg:(?done.?toDo) + & ( !done:? (?.true) (?.true) + & true + | false + ) + ) + ) + ( (11."Exactly 1 of statements 7, 8 and 9 are true.") + . 11 + . ( + = done toDo + . !arg:(?done.?toDo) + & ( number + $ ( !done + . (=7|8|9) + . true + ) + : 1 + & true + | false + ) + ) + ) + ( (12."Exactly 4 of the preceding statements are true.") + . 12 + . ( + = done toDo preceding + . !arg:(?done.?toDo) + & !done:?preceding (?.?) + & ( number$(!preceding.(=?).true):4 + & true + | false + ) + ) + ) + ) + & ( TestTruth + = done toDo postponedTests testToBePostponed + , n when test FT oldFT A Z text + , postponedTest testNow + . !arg:(?done.?toDo.?postponedTests) + & ( !toDo: + & "We have come to the end of the list of tests. + Perform any tests that had to be postponed until now." + & whl + ' ( !postponedTests + : (?.?oldFT.(=?postponedTest)) ?A + & postponedTest$(!done.):!oldFT + & !A:?postponedTests + ) + & !postponedTests: + & out$("Solution:" !done) + & ~ + | !toDo + : ((?n.?text).?when.(=?test)) ?toDo + & "'false' and 'true' are just two symbols, not 'boolean values'. + You can choose other symbols if you like. + The program first guesses the first symbol and assigns it to the variable FT. + After backtracking, the second symbol is guessed and assigned to FT. + This is done for each statement." + & false true + : ? + %@?FT + ( ? + & 1+!guesses:?guesses + & (!n.!FT):?testNow + & "Do all tests that had to be postponed until now, unless one of those tests + fails. Remove the successful tests from the list of postponed tests." + & whl + ' ( !postponedTests + : ?A + (!n.?oldFT.(=?postponedTest)) + ?Z + & postponedTest$(!done !testNow.!toDo) + : !oldFT + & !A !Z:?postponedTests + ) + & "Check that all tests that had to be postponed until now are removed from + the list of postponed tests. Only then go on with looking at testing + the current statement. Backtrack if a test failed." + & !postponedTests:~(? (!n.?) ?) + & ( !when:>!n + & "The current statement cannot be tested right now. Postpone it to + the earliest coming statement where the current statement can be + tested. + (The earliest statement, denoted by 'when', is computed manually.)" + & (!when.!FT.'$test):?testToBePostponed + | "No need to postpone. Test the current statement now." + & :?testToBePostponed + & "If the test fails, backtrack. If it succeeds, go on to the next + statement." + & test$(!done !testNow.!toDo):!FT + ) + & "So far so good. Test the next statements. (recursively)" + & TestTruth + $ ( !done !testNow + . !toDo + . !testToBePostponed !postponedTests + ) + ) + ) + ) + & 0:?guesses + & TestTruth$(.!STATEMENTS.) +| out + $ ( str + $ ( "That's it. I made " + !guesses + " true/false guesses in all. (A brute force method needs 2^12=" + 2^12 + " guesses." + ) + ) +); diff --git a/Task/Twelve-statements/Forth/twelve-statements.fth b/Task/Twelve-statements/Forth/twelve-statements.fth new file mode 100644 index 0000000000..1b57480629 --- /dev/null +++ b/Task/Twelve-statements/Forth/twelve-statements.fth @@ -0,0 +1,43 @@ +: lastbit ( n1 -- n2) + dup if 1 swap begin dup 1 <> while swap 1+ swap 1 rshift repeat drop then +; + +: bit 1 swap lshift and 0<> ; ( n1 n2 -- f) +: bitcount 0 swap begin dup while dup 1- and swap 1+ swap repeat drop ; + +12 constant #stat \ number of statements + \ encoding of the statements +: s1 >r #stat 12 = r> 0 bit = ; \ heavy use of binary +: s2 >r r@ 4032 and bitcount 3 = r> 1 bit = ; +: s3 >r r@ 2730 and bitcount 2 = r> 2 bit = ; +: s4 >r r@ 4 bit 0= 96 r@ over and = or r> 3 bit = ; +: s5 >r r@ 14 and 0= r> 4 bit = ; +: s6 >r r@ 1365 and bitcount 4 = r> 5 bit = ; +: s7 >r r@ 1 bit r@ 2 bit xor r> 6 bit = ; +: s8 >r r@ 6 bit 0= 48 r@ over and = or r> 7 bit = ; +: s9 >r r@ 63 and bitcount 3 = r> 8 bit = ; +: s10 >r 3072 r@ over and = r> 9 bit = ; +: s11 >r r@ 448 and bitcount 1 = r> 10 bit = ; +: s12 >r r@ 2047 and bitcount 4 = r> 11 bit = ; +: list #stat 0 do dup i bit if i 1+ . then loop drop ; + +: nearmiss? \ do we have a near miss? + over #stat 1- = if ( true-pattern #true stat-pattern) + ." Near miss with statements " dup list ." true (failed " + >r over invert 1 #stat lshift 1- and lastbit 0 .r ." )" cr r> + then \ extract the failed statement +; + \ have we found a solution? +: solution? ( true-pattern #true stat-pattern) + over #stat = if ." Solution! with statements " dup list ." true." cr then +; + +: 12statements \ test the twelve patterns + 1 #stat lshift 0 do \ create another bit pattern + i s12 2* i s11 + 2* i s10 + 2* i s9 + 2* i s8 + 2* i s7 + 2* + i s6 + 2* i s5 + 2* i s4 + 2* i s3 + 2* i s2 + 2* i s1 + + abs dup bitcount i solution? nearmiss? drop drop drop + loop \ count number of bytes and evaluate +; + +12statements diff --git a/Task/Twelve-statements/Haskell/twelve-statements.hs b/Task/Twelve-statements/Haskell/twelve-statements.hs index ad9e1f4836..9cf3f1b8f6 100644 --- a/Task/Twelve-statements/Haskell/twelve-statements.hs +++ b/Task/Twelve-statements/Haskell/twelve-statements.hs @@ -5,20 +5,20 @@ tf = mapM (\_ -> [1,0]) wrongness b = findIndices id . zipWith (/=) b . map (fromEnum . ($ b)) statements = [ (==12) . length, - 3 ? [length statements-6..], - 2 ? [1,3..], - 4 ? [4..6], - 0 ? [1..3], - 4 ? [0,2..], - 1 ? [1,2], - 6 ? [4..6], - 3 ? [0..5], - 2 ? [10,11], - 1 ? [6,7,8], - 4 ? [0..10] + 3 ⊂ [length statements-6..], + 2 ⊂ [1,3..], + 4 → [4..6], + 0 ⊂ [1..3], + 4 ⊂ [0,2..], + 1 ⊂ [1,2], + 6 → [4..6], + 3 ⊂ [0..5], + 2 ⊂ [10,11], + 1 ⊂ [6,7,8], + 4 ⊂ [0..10] ] where - (s ? x) b = s == (sum . map (b!!) . takeWhile (< length b)) x - (a ? x) b = (b!!a == 0) || all ((==1).(b!!)) x + (s ⊂ x) b = s == (sum . map (b!!) . takeWhile (< length b)) x + (a → x) b = (b!!a == 0) || all ((==1).(b!!)) x testall s n = [(b, w) | b <- tf s, w <- [wrongness b s], length w == n] diff --git a/Task/Twelve-statements/J/twelve-statements-3.j b/Task/Twelve-statements/J/twelve-statements-3.j index f94bd4b865..a3e39b9eae 100644 --- a/Task/Twelve-statements/J/twelve-statements-3.j +++ b/Task/Twelve-statements/J/twelve-statements-3.j @@ -1,4 +1,4 @@ (#~0=#@{::~&_1"1) testall S -+------------------------+ -¦1 0 1 1 0 1 1 0 0 0 1 0¦¦ -+------------------------+ +┌───────────────────────┬┐ +│1 0 1 1 0 1 1 0 0 0 1 0││ +└───────────────────────┴┘ diff --git a/Task/Twelve-statements/J/twelve-statements-4.j b/Task/Twelve-statements/J/twelve-statements-4.j index 9a0cefa25e..d27ef187bc 100644 --- a/Task/Twelve-statements/J/twelve-statements-4.j +++ b/Task/Twelve-statements/J/twelve-statements-4.j @@ -1,34 +1,34 @@ (#~1=#@{::~&_1"1) testall S -+--------------------------+ -¦0 0 0 0 1 0 0 1 0 0 1 0¦0 ¦ -+-----------------------+--¦ -¦0 0 0 0 1 0 0 1 0 1 1 1¦0 ¦ -+-----------------------+--¦ -¦0 0 0 1 0 0 0 1 0 1 1 1¦0 ¦ -+-----------------------+--¦ -¦1 0 0 0 1 0 0 0 0 0 0 0¦7 ¦ -+-----------------------+--¦ -¦1 0 0 0 1 0 0 1 0 0 0 0¦10¦ -+-----------------------+--¦ -¦1 0 0 0 1 0 0 1 0 0 1 0¦11¦ -+-----------------------+--¦ -¦1 0 0 0 1 0 0 1 0 1 1 1¦11¦ -+-----------------------+--¦ -¦1 0 0 0 1 1 0 0 1 0 1 0¦7 ¦ -+-----------------------+--¦ -¦1 0 0 1 0 0 0 0 0 0 0 0¦7 ¦ -+-----------------------+--¦ -¦1 0 0 1 0 0 0 1 0 1 1 1¦11¦ -+-----------------------+--¦ -¦1 0 0 1 0 1 0 1 1 0 0 0¦5 ¦ -+-----------------------+--¦ -¦1 0 1 1 0 0 0 1 1 0 0 0¦6 ¦ -+-----------------------+--¦ -¦1 0 1 1 0 1 1 0 1 0 0 0¦8 ¦ -+-----------------------+--¦ -¦1 1 0 1 0 0 1 0 1 0 0 1¦11¦ -+-----------------------+--¦ -¦1 1 0 1 0 0 1 0 1 1 0 0¦9 ¦ -+-----------------------+--¦ -¦1 1 0 1 0 0 1 1 1 0 0 0¦7 ¦ -+--------------------------+ +┌───────────────────────┬──┐ +│0 0 0 0 1 0 0 1 0 0 1 0│0 │ +├───────────────────────┼──┤ +│0 0 0 0 1 0 0 1 0 1 1 1│0 │ +├───────────────────────┼──┤ +│0 0 0 1 0 0 0 1 0 1 1 1│0 │ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 0 0 0 0 0│7 │ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 1 0 0 0 0│10│ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 1 0 0 1 0│11│ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 1 0 1 1 1│11│ +├───────────────────────┼──┤ +│1 0 0 0 1 1 0 0 1 0 1 0│7 │ +├───────────────────────┼──┤ +│1 0 0 1 0 0 0 0 0 0 0 0│7 │ +├───────────────────────┼──┤ +│1 0 0 1 0 0 0 1 0 1 1 1│11│ +├───────────────────────┼──┤ +│1 0 0 1 0 1 0 1 1 0 0 0│5 │ +├───────────────────────┼──┤ +│1 0 1 1 0 0 0 1 1 0 0 0│6 │ +├───────────────────────┼──┤ +│1 0 1 1 0 1 1 0 1 0 0 0│8 │ +├───────────────────────┼──┤ +│1 1 0 1 0 0 1 0 1 0 0 1│11│ +├───────────────────────┼──┤ +│1 1 0 1 0 0 1 0 1 1 0 0│9 │ +├───────────────────────┼──┤ +│1 1 0 1 0 0 1 1 1 0 0 0│7 │ +└───────────────────────┴──┘ diff --git a/Task/Twelve-statements/Perl/twelve-statements.pl b/Task/Twelve-statements/Perl/twelve-statements.pl new file mode 100644 index 0000000000..5ec81f285a --- /dev/null +++ b/Task/Twelve-statements/Perl/twelve-statements.pl @@ -0,0 +1,28 @@ +use List::Util 'sum'; + +my @condition = ( + sub { 0 }, # dummy sub for index 0 + sub { 13==@_ }, + sub { 3==sum @_[7..12] }, + sub { 2==sum @_[2,4,6,8,10,12] }, + sub { $_[5] ? ($_[6] and $_[7]) : 1 }, + sub { !$_[2] and !$_[3] and !$_[4] }, + sub { 4==sum @_[1,3,5,7,9,11] }, + sub { $_[2]==1-$_[3] }, + sub { $_[7] ? ($_[5] and $_[6]) : 1 }, + sub { 3==sum @_[1..6] }, + sub { 2==sum @_[11..12] }, + sub { 1==sum @_[7,8,9] }, + sub { 4==sum @_[1..11] }, + ); + +sub miss { + return grep { $condition[$_]->(@_) != $_[$_] } 1..12; +} + +for (0..2**12-1) { + my @truth = split //, sprintf "0%012b", $_; + my @no = miss @truth; + print "Solution: true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 0 == @no; + print "1 miss (",$no[0],"): true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 1 == @no; +} diff --git a/Task/URL-decoding/MATLAB/url-decoding.m b/Task/URL-decoding/MATLAB/url-decoding.m new file mode 100644 index 0000000000..01ed75d8ba --- /dev/null +++ b/Task/URL-decoding/MATLAB/url-decoding.m @@ -0,0 +1,13 @@ +function u = urldecoding(s) + u = ''; + k = 1; + while k<=length(s) + if s(k) == '%' && k+3 <= length(s) + u = sprintf('%s%c', u, char(hex2dec(s((k+1):(k+2))))); + k = k + 3; + else + u = sprintf('%s%c', u, s(k)); + k = k + 1; + end + end +end diff --git a/Task/Undefined-values/Deja-Vu/undefined-values.djv b/Task/Undefined-values/Deja-Vu/undefined-values.djv new file mode 100644 index 0000000000..ffdf93ccc2 --- /dev/null +++ b/Task/Undefined-values/Deja-Vu/undefined-values.djv @@ -0,0 +1,6 @@ +try: + bogus +catch name-error: + !print "There is *no* :bogus in the current context" + return +!print "You won't see this." diff --git a/Task/Undefined-values/Erlang/undefined-values.erl b/Task/Undefined-values/Erlang/undefined-values.erl new file mode 100644 index 0000000000..09a5057ad1 --- /dev/null +++ b/Task/Undefined-values/Erlang/undefined-values.erl @@ -0,0 +1,10 @@ +-module( undefined_values ). + +-export( [task/0] ). + +-record( a_record, {member_1, member_2} ). + +task() -> + Record = #a_record{member_1=a_value}, + io:fwrite( "Record member_1 ~p, member_2 ~p~n", [Record#a_record.member_1, Record#a_record.member_2] ), + io:fwrite( "Member_2 is undefined ~p~n", [Record#a_record.member_2 =:= undefined] ). diff --git a/Task/Unicode-strings/Julia/unicode-strings-1.julia b/Task/Unicode-strings/Julia/unicode-strings-1.julia new file mode 100644 index 0000000000..b3c1d8def9 --- /dev/null +++ b/Task/Unicode-strings/Julia/unicode-strings-1.julia @@ -0,0 +1,3 @@ +julia> 四十二 = "voilà"; +julia> println(四十二) +voilà diff --git a/Task/Unicode-strings/Julia/unicode-strings-2.julia b/Task/Unicode-strings/Julia/unicode-strings-2.julia new file mode 100644 index 0000000000..276798143d --- /dev/null +++ b/Task/Unicode-strings/Julia/unicode-strings-2.julia @@ -0,0 +1,2 @@ +julia>println("\u2708") +✈ diff --git a/Task/Unicode-strings/Julia/unicode-strings.julia b/Task/Unicode-strings/Julia/unicode-strings.julia deleted file mode 100644 index 183e057a93..0000000000 --- a/Task/Unicode-strings/Julia/unicode-strings.julia +++ /dev/null @@ -1,12 +0,0 @@ -function surround(string ; border = :default) - - ve, ho, ul, ur, dl, dr = - border == :bold ? ("\u2503","\u2501","\u250F","\u2513","\u2517","\u251b") : - border == :double? ("\u2551","\u2550","\u2554","\u2557","\u255a","\u255d") : - border == :dotted? ("\u254e","\u254c","\u250c","\u2510","\u2514","\u2518") : - ("\u2502","\u2500","\u250c","\u2510","\u2514","\u2518") - - println(ul,ho^length(string),ur,"\n", - ve, string ,ve,"\n", - dl,ho^length(string),dr) -end diff --git a/Task/Unicode-strings/Perl-6/unicode-strings.pl6 b/Task/Unicode-strings/Perl-6/unicode-strings.pl6 index 6a99153313..e5b4c6ae52 100644 --- a/Task/Unicode-strings/Perl-6/unicode-strings.pl6 +++ b/Task/Unicode-strings/Perl-6/unicode-strings.pl6 @@ -1,2 +1,2 @@ -sub prefix:<∛> ($#56655;) { $#56655; ** (1/3) } +sub prefix:<∛> (\𝐕) { 𝐕 ** (1/3) } say ∛27; # prints 3 diff --git a/Task/Unicode-strings/Ruby/unicode-strings.rb b/Task/Unicode-strings/Ruby/unicode-strings.rb new file mode 100644 index 0000000000..8604a280ab --- /dev/null +++ b/Task/Unicode-strings/Ruby/unicode-strings.rb @@ -0,0 +1,5 @@ +def Σ(array) + array.inject(:+) +end + +puts Σ([4,5,6]) #=>15 diff --git a/Task/Unicode-variable-names/Deja-Vu/unicode-variable-names.djv b/Task/Unicode-variable-names/Deja-Vu/unicode-variable-names.djv new file mode 100644 index 0000000000..de733246f1 --- /dev/null +++ b/Task/Unicode-variable-names/Deja-Vu/unicode-variable-names.djv @@ -0,0 +1,3 @@ +set :Δ 1 +set :Δ ++ Δ +!. Δ diff --git a/Task/Unicode-variable-names/Prolog/unicode-variable-names-1.pro b/Task/Unicode-variable-names/Prolog/unicode-variable-names-1.pro new file mode 100644 index 0000000000..9dbfda2c06 --- /dev/null +++ b/Task/Unicode-variable-names/Prolog/unicode-variable-names-1.pro @@ -0,0 +1,11 @@ +% Unicode in predicate names: +是. % be: means, approximately, "True". +不是 :- \+ 是. % not be: means, approximately, "False". Defined as not 是. + +% Unicode in variable names: +test(Garçon, Δ) :- + Garçon = boy, + Δ = delta. + +% Call test2(1, Result) to have 2 assigned to Result. +test2(Δ, R) :- R is Δ + 1. diff --git a/Task/Unicode-variable-names/Prolog/unicode-variable-names-2.pro b/Task/Unicode-variable-names/Prolog/unicode-variable-names-2.pro new file mode 100644 index 0000000000..7f5a036d24 --- /dev/null +++ b/Task/Unicode-variable-names/Prolog/unicode-variable-names-2.pro @@ -0,0 +1,12 @@ +?- 是. +true. + +?- 不是. +false. + +?- test(X,Y). +X = boy, +Y = delta. + +?- test2(1,Result). +Result = 2. diff --git a/Task/Universal-Turing-machine/00DESCRIPTION b/Task/Universal-Turing-machine/00DESCRIPTION index 6cd990851d..e464f9c429 100644 --- a/Task/Universal-Turing-machine/00DESCRIPTION +++ b/Task/Universal-Turing-machine/00DESCRIPTION @@ -33,3 +33,27 @@ The input for this machine should be a tape of 1 1 1 ** (c, 1, 1, stay, halt) The input for this machine should be an empty tape. + +'''Bonus:''' + +'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia''' +* '''States:''' A, B, C, D, E, H +* '''Initial state:''' A +* '''Terminating states:''' H +* '''Permissible symbols:''' 0, 1 +* '''Blank symbol:''' 0 +* '''Rules:''' +** (A, 0, 1, right, B) +** (A, 1, 1, left, C) +** (B, 0, 1, right, C) +** (B, 1, 1, right, B) +** (C, 0, 1, right, D) +** (C, 1, 0, left, E) +** (D, 0, 1, left, A) +** (D, 1, 1, left, D) +** (E, 0, 1, stay, H) +** (E, 1, 0, left, A) + +The input for this machine should be an empty tape. + +This machine runs for more than 47 millions steps. diff --git a/Task/Universal-Turing-machine/D/universal-turing-machine-1.d b/Task/Universal-Turing-machine/D/universal-turing-machine-1.d new file mode 100644 index 0000000000..801fe67bd4 --- /dev/null +++ b/Task/Universal-Turing-machine/D/universal-turing-machine-1.d @@ -0,0 +1,243 @@ +import std.stdio, std.algorithm, std.string, std.conv, std.array, + std.exception, std.traits, std.math, std.range; + +struct UTM(State, Symbol, bool doShow=true) +if (is(State == enum) && is(Symbol == enum)) { + static assert(is(typeof({ size_t x = State.init; })), + "State must to be usable as array index."); + static assert([EnumMembers!State] + .equal(EnumMembers!State.length.iota), + "State must be a plain enum."); + static assert(is(typeof({ size_t x = Symbol.init; })), + "Symbol must to be usable as array index."); + static assert([EnumMembers!Symbol] + .equal(EnumMembers!Symbol.length.iota), + "Symbol must be a plain enum."); + + enum Direction { right, left, stay } + + private const TuringMachine tm; + private TapeHead head; + alias SymbolMap = string[EnumMembers!Symbol.length]; + + // The first index of this 'rules' matrix is a subtype of State + // because it can't contain H, but currently D can't enforce this, + // statically unlike Ada language. + Rule[EnumMembers!Symbol.length] + [EnumMembers!State.length - 1] mRules; + + static struct Rule { + Symbol toWrite; + Direction direction; + State nextState; + + this(in Symbol toWrite_, in Direction direction_, + in State nextState_) pure nothrow { + this.toWrite = toWrite_; + this.direction = direction_; + this.nextState = nextState_; + } + } + + // This is kept separated from the rest so it can be inialized + // one field at a time in the main function, yet it will become + // const. + static struct TuringMachine { + Symbol blank; + State initialState; + Rule[Symbol][State] rules; + Symbol[] input; + SymbolMap symbolMap; + } + + static struct TapeHead { + immutable Symbol blank; + Symbol[] tapeLeft, tapeRight; + int position; + const SymbolMap sMap; + size_t nSteps; + + this(in ref TuringMachine t) pure /*nothrow*/ { + this.blank = EnumMembers!Symbol[0]; + //tapeRight = t.input.empty ? [this.blank] : t.input.dup; + if (t.input.empty) + this.tapeRight = [this.blank]; + else + this.tapeRight = t.input.dup; // Not nothrow. + this.position = 0; + this.sMap = t.symbolMap; + } + + pure nothrow invariant() { + assert(this.tapeRight.length > 0); + if (this.position >= 0) + assert(this.position < this.tapeRight.length); + else + assert(this.position.abs <= this.tapeLeft.length); + } + + Symbol readSymb() const pure nothrow { + if (this.position >= 0) + return this.tapeRight[this.position]; + else + return this.tapeLeft[this.position.abs - 1]; + } + + void showSymb() const { + this.write; + } + + void writeSymb(in Symbol symbol) { + static if (doShow) + showSymb; + if (this.position >= 0) + this.tapeRight[this.position] = symbol; + else + this.tapeLeft[this.position.abs - 1] = symbol; + } + + void goRight() pure nothrow { + this.position++; + if (position > 0 && position == tapeRight.length) + tapeRight ~= blank; + } + + void goLeft() pure nothrow { + this.position--; + if (position < 0 && (position.abs - 1) == tapeLeft.length) + tapeLeft ~= blank; + } + + void move(in Direction dir) pure nothrow { + nSteps++; + final switch (dir) with (Direction) { + case left: goLeft; break; + case right: goRight; break; + case stay: /*Do nothing*/ break; + } + } + + string toString() const { + const pos = cast(int)tapeLeft.length + this.position + 4; + return format("...%-(%)...", tapeLeft.retro + .chain(tapeRight) + .map!(s => sMap[s])) ~ + '\n' ~ + format("%" ~ pos.text ~ "s", "^") ~ + '\n'; + } + } + + void show() const { + head.showSymb; + } + + this(in ref TuringMachine tm_) { + static assert(__traits(compiles, State.H), + "State needs a 'H' (Halt)."); + immutable errMsg = "Invalid input."; + auto runningStates = remove!(s => s == State.H) + ([EnumMembers!State]); + enforce(!runningStates.empty, errMsg); + enforce(tm_.rules.length == EnumMembers!State.length - 1, + errMsg); + enforce(State.H !in tm_.rules, errMsg); + enforce(runningStates.canFind(tm_.initialState), errMsg); + + // Create a matrix to reduce running time. + foreach (const State st, const rset; tm_.rules) + foreach (const Symbol sy, const rule; rset) + mRules[st][sy] = rule; + + this.tm = tm_; + head = TapeHead(this.tm); + + State state = tm.initialState; + while (state != State.H) { + immutable next = mRules[state][head.readSymb]; + head.writeSymb(next.toWrite); + head.move(next.direction); + state = next.nextState; + } + static if (doShow) + show; + writeln("Performed ", head.nSteps, " steps."); + } +} + +void main() { + "Incrementer:".writeln; + enum States1 : ubyte { A, H } + enum Symbols1 : ubyte { s0, s1 } + alias M1 = UTM!(States1, Symbols1); + M1.TuringMachine tm1; + with (tm1) with (States1) with (Symbols1) with (M1.Direction) { + alias R = M1.Rule; + initialState = A; + rules = [A: [s0: R(s1, stay, H), s1: R(s1, right, A)]]; + input = [s1, s1, s1]; + symbolMap = ["0", "1"]; + } + M1(tm1); + + // http://en.wikipedia.org/wiki/Busy_beaver + "\nBusy Beaver machine (3-state, 2-symbol):".writeln; + enum States2 : ubyte { A, B, C, H } + alias Symbols2 = Symbols1; + alias M2 = UTM!(States2, Symbols2); + M2.TuringMachine tm2; + with (tm2) with (States2) with (Symbols2) with (M2.Direction) { + alias R = M2.Rule; + initialState = A; + rules = [A: [s0: R(s1, right, B), s1: R(s1, left, C)], + B: [s0: R(s1, left, A), s1: R(s1, right, B)], + C: [s0: R(s1, left, B), s1: R(s1, stay, H)]]; + symbolMap = ["0", "1"]; + } + M2(tm2); + + "\nSorting stress test (12212212121212):".writeln; + enum States3 : ubyte { A, B, C, D, E, H } + enum Symbols3 : ubyte { s0, s1, s2, s3 } + alias M3 = UTM!(States3, Symbols3, false); + M3.TuringMachine tm3; + with (tm3) with (States3) with (Symbols3) with (M3.Direction) { + alias R = M3.Rule; + initialState = A; + rules = [A: [s1: R(s1, right, A), + s2: R(s3, right, B), + s0: R(s0, left, E)], + B: [s1: R(s1, right, B), + s2: R(s2, right, B), + s0: R(s0, left, C)], + C: [s1: R(s2, left, D), + s2: R(s2, left, C), + s3: R(s2, left, E)], + D: [s1: R(s1, left, D), + s2: R(s2, left, D), + s3: R(s1, right, A)], + E: [s1: R(s1, left, E), + s0: R(s0, stay, H)]]; + input = [s1, s2, s2, s1, s2, s2, s1, + s2, s1, s2, s1, s2, s1, s2]; + symbolMap = ["0", "1", "2", "3"]; + } + M3(tm3).show; + + "\nPossible best Busy Beaver machine (5-state, 2-symbol):".writeln; + alias States4 = States3; + alias Symbols4 = Symbols1; + alias M4 = UTM!(States4, Symbols4, false); + M4.TuringMachine tm4; + with (tm4) with (States4) with (Symbols4) with (M4.Direction) { + alias R = M4.Rule; + initialState = A; + rules = [A: [s0: R(s1, right, B), s1: R(s1, left, C)], + B: [s0: R(s1, right, C), s1: R(s1, right, B)], + C: [s0: R(s1, right, D), s1: R(s0, left, E)], + D: [s0: R(s1, left, A), s1: R(s1, left, D)], + E: [s0: R(s1, stay, H), s1: R(s0, left, A)]]; + symbolMap = ["0", "1"]; + } + M4(tm4); +} diff --git a/Task/Universal-Turing-machine/D/universal-turing-machine-2.d b/Task/Universal-Turing-machine/D/universal-turing-machine-2.d new file mode 100644 index 0000000000..3d2c7d73ae --- /dev/null +++ b/Task/Universal-Turing-machine/D/universal-turing-machine-2.d @@ -0,0 +1,52 @@ +import std.stdio, std.typecons, std.array, std.algorithm, std.string; + +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 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")]]); +} diff --git a/Task/Universal-Turing-machine/D/universal-turing-machine.d b/Task/Universal-Turing-machine/D/universal-turing-machine.d deleted file mode 100644 index 7cc82b8b05..0000000000 --- a/Task/Universal-Turing-machine/D/universal-turing-machine.d +++ /dev/null @@ -1,190 +0,0 @@ -import std.stdio, std.algorithm, std.string, std.conv, std.array, - std.exception; - -struct UTM(bool doShow=true) { - alias Symbol = uint; - alias State = char; // Typedef? - enum Direction { right, left, stay } - - private TapeHead head; - private const TuringMachine tm; - - static struct Rule { - Symbol toWrite; - Direction direction; - State nextState; - } - - static struct TuringMachine { - Symbol[] symbols; - Symbol blank; - State initialState; - State[] haltStates, runningStates; - Rule[Symbol][State] rules; - Symbol[] input; - } - - static struct TapeHead { - immutable Symbol blank; - Symbol[] tape; - size_t position; - - this(in ref TuringMachine t) pure /*nothrow*/ { - this.blank = t.blank; - this.tape = t.input.dup; // Not nothrow. - if (this.tape.empty) - this.tape = [this.blank]; - this.position = 0; - } - - pure nothrow invariant() { - assert(this.position < this.tape.length); - } - - Symbol read() const pure nothrow { - return this.tape[this.position]; - } - - void show() const { - .write(this); - } - - void write(in Symbol symbol) { - static if (doShow) - show(); - this.tape[this.position] = symbol; - } - - void right() pure nothrow { - this.position++; - if (this.position == this.tape.length) - this.tape ~= this.blank; - } - - void left() pure nothrow { - if (this.position == 0) - this.tape = this.blank ~ this.tape; - else - this.position--; - } - - void move(in Direction dir) { - final switch (dir) { - case Direction.left: left(); break; - case Direction.right: right(); break; - case Direction.stay: /*Do nothing.*/ break; - } - } - - string toString() const { - return format("...%(%)...", this.tape) - ~ '\n' - ~ format("%" ~ text(this.position + 4) ~ "s", "^") - ~ '\n'; - } - } - - void show() const { - head.show(); - } - - this(const ref TuringMachine tm_) { - immutable errMsg = "Invalid input."; - enforce(!tm_.runningStates.empty, errMsg); - enforce(!tm_.haltStates.empty, errMsg); - enforce(!tm_.symbols.empty, errMsg); - enforce(tm_.rules.length, errMsg); - enforce(tm_.runningStates.canFind(tm_.initialState), errMsg); - enforce(tm_.symbols.canFind(tm_.blank), errMsg); - const allStates = tm_.runningStates ~ tm_.haltStates; - foreach (const s; tm_.rules.keys.to!(dchar[])().sort()) - enforce(tm_.runningStates.canFind(s), errMsg); - foreach (const aa; tm_.rules.byValue) - foreach (/*const*/ s, const rule; aa) { - enforce(tm_.symbols.canFind(s), errMsg); - enforce(tm_.symbols.canFind(rule.toWrite), errMsg); - enforce(allStates.canFind(rule.nextState), errMsg); - } - - this.tm = tm_; - this.head = TapeHead(this.tm); - - State state = this.tm.initialState; - while (true) { - if (tm.haltStates.canFind(state)) - break; - if (!tm.runningStates.canFind(state)) - throw new Exception("Unknown state."); - immutable symbol = this.head.read(); - immutable rule = this.tm.rules[state][symbol]; - this.head.write(rule.toWrite); - this.head.move(rule.direction); - state = rule.nextState; - } - static if (doShow) - show(); - } -} - -void main() { - with (UTM!()) { - alias R = Rule; - writeln("Incrementer:"); - TuringMachine tm1; - tm1.symbols = [0, 1]; - tm1.blank = 0; - tm1.initialState = 'A'; - tm1.haltStates = ['H']; - tm1.runningStates = ['A']; - with (Direction) - tm1.rules = ['A': [0: R(1, left, 'H'), - 1: R(1, right, 'A')]]; - tm1.input = [1, 1, 1]; - UTM!()(tm1); - - // http://en.wikipedia.org/wiki/Busy_beaver - writeln("\nBusy beaver machine (3-state, 2-symbol):"); - TuringMachine tm2; - tm2.symbols = [0, 1]; - tm2.blank = 0; - tm2.initialState = 'A'; - tm2.haltStates = ['H']; - tm2.runningStates = ['A', 'B', 'C']; - with (Direction) - tm2.rules = ['A': [0: R(1, right, 'B'), - 1: R(1, left, 'C')], - 'B': [0: R(1, left, 'A'), - 1: R(1, right, 'B')], - 'C': [0: R(1, left, 'B'), - 1: R(1, stay, 'H')]]; - UTM!()(tm2); - } - - with (UTM!false) { - writeln("\nSorting stress test (12212212121212):"); - alias R = Rule; - TuringMachine tm3; - tm3.symbols = [0, 1, 2, 3]; - tm3.blank = 0; - tm3.initialState = 'A'; - tm3.haltStates = ['H']; - tm3.runningStates = ['A', 'B', 'C', 'D', 'E']; - with (Direction) - tm3.rules = ['A': [1: R(1, right, 'A'), - 2: R(3, right, 'B'), - 0: R(0, left, 'E')], - 'B': [1: R(1, right, 'B'), - 2: R(2, right, 'B'), - 0: R(0, left, 'C')], - 'C': [1: R(2, left, 'D'), - 2: R(2, left, 'C'), - 3: R(2, left, 'E')], - 'D': [1: R(1, left, 'D'), - 2: R(2, left, 'D'), - 3: R(1, right, 'A')], - 'E': [1: R(1, left, 'E'), - 0: R(0, right, 'H')]]; - tm3.input = [1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2]; - UTM!false(tm3).show(); - } -} diff --git a/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-1.djv b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-1.djv new file mode 100644 index 0000000000..48854d3328 --- /dev/null +++ b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-1.djv @@ -0,0 +1,42 @@ +transitions(: + local :t {} + while /= ) dup: + set-to t swap & rot & rot rot & + t drop + +take-from tape: + if tape: + pop-from tape + else: + :B + +paste-together a h b: + push-to b h + while a: + push-to b pop-from a + b + +universal-turing-machine transitions initial final tape: + local :tape-left [] + local :state initial + + local :head take-from tape + + local :move { :stay @pass } + + move!left: + push-to tape head + set :head take-from tape-left + + move!right: + push-to tape-left head + set :head take-from tape + + while /= state final: + if opt-get transitions & state head: + set :state &<> + set :head &<> + move! + else: + return paste-together tape-left head tape + paste-together tape-left head tape diff --git a/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-2.djv b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-2.djv new file mode 100644 index 0000000000..6158e60557 --- /dev/null +++ b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-2.djv @@ -0,0 +1,5 @@ +:q0 :qf [ 1 1 1 ] +) +:q0 1 1 :right :q0 +:q0 :B 1 :stay :qf +!. universal-turing-machine transitions( diff --git a/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-3.djv b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-3.djv new file mode 100644 index 0000000000..359e078226 --- /dev/null +++ b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-3.djv @@ -0,0 +1,9 @@ +:a :halt [] +) +:a :B 1 :right :b +:a 1 1 :left :c +:b :B 1 :left :a +:b 1 1 :right :b +:c :B 1 :left :b +:c 1 1 :stay :halt +!. universal-turing-machine transitions( diff --git a/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-4.djv b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-4.djv new file mode 100644 index 0000000000..1875015e79 --- /dev/null +++ b/Task/Universal-Turing-machine/Deja-Vu/universal-turing-machine-4.djv @@ -0,0 +1,13 @@ +:A :H [] +) +:A :B 1 :right :B +:A 1 1 :left :C +:B :B 1 :right :C +:B 1 1 :right :B +:C :B 1 :right :D +:C 1 :B :left :E +:D :B 1 :left :A +:D 1 1 :left :D +:E :B 1 :stay :H +:E 1 :B :left :A +!. universal-turing-machine transitions( diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine-1.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-1.hs new file mode 100644 index 0000000000..6b99af1e07 --- /dev/null +++ b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-1.hs @@ -0,0 +1,28 @@ +-- Some elementary types for Turing Machine +data Move = MLeft | MRight | Stay deriving (Show, Eq) +data Tape a = Tape a [a] [a] +data Action state val = Action val Move state deriving (Show) + +instance (Show a) => Show (Tape a) where + show (Tape x lts rts) = concat $ left ++ [hd] ++ right + where hd = "[" ++ show x ++ "]" + left = map show $ reverse $ take 10 lts + right = map show $ take 10 rts + +-- new tape +tape blank lts rts | null rts = Tape blank left blanks + | otherwise = Tape (head rts) left right + where blanks = repeat blank + left = reverse lts ++ blanks + right = tail rts ++ blanks + +-- Turing Machine +step rules (state, Tape x (lh:lts) (rh:rts)) = (state', tape') + where Action x' dir state' = rules state x + tape' = move dir + move Stay = Tape x' (lh:lts) (rh:rts) + move MLeft = Tape lh lts (x':rh:rts) + move MRight = Tape rh (x':lh:lts) rts + +runUTM rules stop start tape = steps ++ [final] + where (steps, final:_) = break ((== stop) . fst) $ iterate (step rules) (start, tape) diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine-2.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-2.hs new file mode 100644 index 0000000000..ca25e1689a --- /dev/null +++ b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-2.hs @@ -0,0 +1,5 @@ +incr "q0" 1 = Action 1 MRight "q0" +incr "q0" 0 = Action 1 Stay "qf" + +tape1 = tape 0 [] [1,1, 1] +machine1 = runUTM incr "qf" "q0" tape1 diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine-3.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-3.hs new file mode 100644 index 0000000000..3b7932d342 --- /dev/null +++ b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-3.hs @@ -0,0 +1,6 @@ +*Main> mapM_ print machine1 +("q0",0000000000[1]1100000000) +("q0",0000000001[1]1000000000) +("q0",0000000011[1]0000000000) +("q0",0000000111[0]0000000000) +("qf",0000000111[1]0000000000) diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine-4.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-4.hs new file mode 100644 index 0000000000..5890e85659 --- /dev/null +++ b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-4.hs @@ -0,0 +1,9 @@ +beaver "a" 0 = Action 1 MRight "b" +beaver "a" 1 = Action 1 MLeft "c" +beaver "b" 0 = Action 1 MLeft "a" +beaver "b" 1 = Action 1 MRight "b" +beaver "c" 0 = Action 1 MLeft "b" +beaver "c" 1 = Action 1 Stay "halt" + +tape2 = tape 0 [] [] +machine2 = runUTM beaver "halt" "a" tape2 diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine-5.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-5.hs new file mode 100644 index 0000000000..22e78a166c --- /dev/null +++ b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-5.hs @@ -0,0 +1,17 @@ +sorting "A" 1 = Action 1 MRight "A" +sorting "A" 2 = Action 3 MRight "B" +sorting "A" 0 = Action 0 MLeft "E" +sorting "B" 1 = Action 1 MRight "B" +sorting "B" 2 = Action 2 MRight "B" +sorting "B" 0 = Action 0 MLeft "C" +sorting "C" 1 = Action 2 MLeft "D" +sorting "C" 2 = Action 2 MLeft "C" +sorting "C" 3 = Action 2 MLeft "E" +sorting "D" 1 = Action 1 MLeft "D" +sorting "D" 2 = Action 2 MLeft "D" +sorting "D" 3 = Action 1 MRight "A" +sorting "E" 1 = Action 1 MLeft "E" +sorting "E" 0 = Action 0 MRight "STOP" + +tape3 = tape 0 [] [2,2,2,1,2,2,1,2,1,2,1,2,1,2] +machine3 = runUTM sorting "STOP" "A" tape3 diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine-6.hs similarity index 100% rename from Task/Universal-Turing-machine/Haskell/universal-turing-machine.hs rename to Task/Universal-Turing-machine/Haskell/universal-turing-machine-6.hs diff --git a/Task/Universal-Turing-machine/Python/universal-turing-machine.py b/Task/Universal-Turing-machine/Python/universal-turing-machine.py new file mode 100644 index 0000000000..77c6343419 --- /dev/null +++ b/Task/Universal-Turing-machine/Python/universal-turing-machine.py @@ -0,0 +1,87 @@ +from __future__ import print_function + +def run_utm( + state = None, + blank = None, + rules = [], + tape = [], + halt = None, + pos = 0): + st = state + if not tape: tape = [blank] + if pos < 0: pos += len(tape) + if pos >= len(tape) or pos < 0: raise Error( "bad init position") + rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) + + while True: + print(st, '\t', end=" ") + for i, v in enumerate(tape): + if i == pos: print("[%s]" % (v,), end=" ") + else: print(v, end=" ") + print() + + if st == halt: break + if (st, tape[pos]) not in rules: break + + (v1, dr, s1) = rules[(st, tape[pos])] + tape[pos] = v1 + if dr == 'left': + if pos > 0: pos -= 1 + else: tape.insert(0, blank) + if dr == 'right': + pos += 1 + if pos >= len(tape): tape.append(blank) + st = s1 + + +# EXAMPLES + +print("incr machine\n") +run_utm( + halt = 'qf', + state = 'q0', + tape = list("111"), + blank = 'B', + rules = map(tuple, + ["q0 1 1 right q0".split(), + "q0 B 1 stay qf".split()] + ) + ) + +print("\nbusy beaver\n") +run_utm( + halt = 'halt', + state = 'a', + blank = '0', + rules = map(tuple, + ["a 0 1 right b".split(), + "a 1 1 left c".split(), + "b 0 1 left a".split(), + "b 1 1 right b".split(), + "c 0 1 left b".split(), + "c 1 1 stay halt".split()] + ) + ) + +print("\nsorting test\n") +run_utm(halt = 'STOP', + state = 'A', + blank = '0', + tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), + rules = map(tuple, + ["A 1 1 right A".split(), + "A 2 3 right B".split(), + "A 0 0 left E".split(), + "B 1 1 right B".split(), + "B 2 2 right B".split(), + "B 0 0 left C".split(), + "C 1 2 left D".split(), + "C 2 2 left C".split(), + "C 3 2 left E".split(), + "D 1 1 left D".split(), + "D 2 2 left D".split(), + "D 3 1 right A".split(), + "E 1 1 left E".split(), + "E 0 0 right STOP".split()] + ) + ) diff --git a/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx b/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx new file mode 100644 index 0000000000..3332148d59 --- /dev/null +++ b/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx @@ -0,0 +1,41 @@ +/*REXX pgm executes a Turing machine based on initial state, tape, rules*/ +state = 'q0' /*initial Turing machine state. */ +term = 'qf' /*a state that is used for halt. */ +blank = 'B' /*this character is a true blank.*/ +call turing_rule 'q0 1 1 right q0' /*define a rule for the machine. */ +call turing_rule 'q0 B 1 stay qf' /* " " " " " " */ +call turing_init 1 1 1 /*initialize tape to string(s). */ +call turing_machine /*go invoke the Turning machine. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TURING_MACHINE subroutine───────────*/ +turing_machine: !=1; bot=1; top=1 /*start at the tape location 1. */ +say /*might as well show a blank line*/ + do cycle=1 until state==term /*do Turing machine instructions.*/ + do k=1 for rules /*process the Turning mach. rules*/ + parse var rule.k rState rTape rWrite rMove rNext . /*pick pieces*/ + if state\==rState | @.!\==rTape then iterate /*wrong rule?*/ + @.!=rWrite /*right rule; write it ──► tape.*/ + if rMove== 'left' then !=!-1 /*Move left? Then subtract one.*/ + if rMove=='right' then !=!+1 /*Move right? Then add one.*/ + bot=min(bot,!); top=max(top,!) /*find the tape bottom and top.*/ + state=rNext /*use this for the next state. */ + iterate cycle /*go process another instruction.*/ + end /*k*/ + say '***error!*** unknown state:' state; leave /*oops.*/ + end /*cycle*/ +$= /*start with empty string (tape).*/ + do t=bot to top; _=@.t; if _==blank then _=' ' /*translate?*/ + $=$ || pad || _ /*build chr by chr, maybe pad it.*/ + end /*t*/ /* [↑] build the tape's contents.*/ +if $='' then $= "[tape is blank.]" /*make an empty tape visible.*/ +say 'Turning machine used' rules "rules in" cycle 'cycles, tape is:' $ +return +/*──────────────────────────────────TURING_INIT subroutine──────────────*/ +turing_init: @.=blank; parse arg x + do j=1 for words(x); @.j=word(x,j); end /*j*/ +return +/*──────────────────────────────────TURING_RULE subroutine──────────────*/ +turing_rule: if symbol('RULES')=="LIT" then rules=0; rules=rules+1 +pad=left('',length(word(arg(1),2))\==1) /*used if any symbol's length>1.*/ +rule.rules=arg(1); say right('rule' rules,20) "═══►" rule.rules +return diff --git a/Task/Universal-Turing-machine/REXX/universal-turing-machine-2.rexx b/Task/Universal-Turing-machine/REXX/universal-turing-machine-2.rexx new file mode 100644 index 0000000000..5214339e8b --- /dev/null +++ b/Task/Universal-Turing-machine/REXX/universal-turing-machine-2.rexx @@ -0,0 +1,15 @@ +/*REXX pgm executes a Turing machine based on initial state, tape, rules*/ +state = 'a' /*initial Turing machine state. */ +term = 'halt' /*a state that is used for halt. */ +blank = 0 /*this character is a true blank.*/ +call turing_rule 'a 0 1 right b' /*define a rule for the machine. */ +call turing_rule 'a 1 1 left c' /* " " " " " " */ +call turing_rule 'b 0 1 left a' /* " " " " " " */ +call turing_rule 'b 1 1 right b' /* " " " " " " */ +call turing_rule 'c 0 1 left b' /* " " " " " " */ +call turing_rule 'c 1 1 stay halt' /* " " " " " " */ +call turing_init /*initialize tape to string(s). */ +call turing_machine /*go invoke the Turning machine. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TURING_MACHINE subroutine───────────*/ +turing_machine ∙∙∙ diff --git a/Task/Universal-Turing-machine/REXX/universal-turing-machine-3.rexx b/Task/Universal-Turing-machine/REXX/universal-turing-machine-3.rexx new file mode 100644 index 0000000000..3712274242 --- /dev/null +++ b/Task/Universal-Turing-machine/REXX/universal-turing-machine-3.rexx @@ -0,0 +1,19 @@ +/*REXX pgm executes a Turing machine based on initial state, tape, rules*/ +state = 'A' /*initial Turing machine state. */ +term = 'H' /*a state that is used for halt. */ +blank = 0 /*this character is a true blank.*/ +call turing_rule 'A 0 1 right B' /*define a rule for the machine. */ +call turing_rule 'A 1 1 left C' /* " " " " " " */ +call turing_rule 'B 0 1 right C' /* " " " " " " */ +call turing_rule 'B 1 1 right B' /* " " " " " " */ +call turing_rule 'C 0 1 right D' /* " " " " " " */ +call turing_rule 'C 1 1 left E' /* " " " " " " */ +call turing_rule 'D 0 1 left A' /* " " " " " " */ +call turing_rule 'D 1 1 left D' /* " " " " " " */ +call turing_rule 'E 0 1 stay H' /* " " " " " " */ +call turing_rule 'E 1 1 left A' /* " " " " " " */ +call turing_init /*initialize tape to string(s). */ +call turing_machine /*go invoke the Turning machine. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TURING_MACHINE subroutine───────────*/ +turing_machine ∙∙∙ diff --git a/Task/Universal-Turing-machine/REXX/universal-turing-machine-4.rexx b/Task/Universal-Turing-machine/REXX/universal-turing-machine-4.rexx new file mode 100644 index 0000000000..43996a20db --- /dev/null +++ b/Task/Universal-Turing-machine/REXX/universal-turing-machine-4.rexx @@ -0,0 +1,23 @@ +/*REXX pgm executes a Turing machine based on initial state, tape, rules*/ +state = 'A' /*initial Turing machine state. */ +term = 'halt' /*a state that is used for halt. */ +blank = 0 /*this character is a true blank.*/ +call turing_rule 'A 1 1 right A' /*define a rule for the machine. */ +call turing_rule 'A 2 3 right B' /* " " " " " " */ +call turing_rule 'A 0 0 left E' /* " " " " " " */ +call turing_rule 'B 1 1 right B' /* " " " " " " */ +call turing_rule 'B 2 2 right B' /* " " " " " " */ +call turing_rule 'B 0 0 left C' /* " " " " " " */ +call turing_rule 'C 1 2 left D' /* " " " " " " */ +call turing_rule 'C 2 2 left C' /* " " " " " " */ +call turing_rule 'C 3 2 left E' /* " " " " " " */ +call turing_rule 'D 1 1 left D' /* " " " " " " */ +call turing_rule 'D 2 2 left D' /* " " " " " " */ +call turing_rule 'D 3 1 right A' /* " " " " " " */ +call turing_rule 'E 1 1 left E' /* " " " " " " */ +call turing_rule 'E 0 0 right halt' /* " " " " " " */ +call turing_init 1 2 2 1 2 2 1 2 1 2 1 2 1 2 /*init. tape to string(s). */ +call turing_machine /*go invoke the Turning machine. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TURING_MACHINE subroutine───────────*/ +turing_machine ∙∙∙ diff --git a/Task/Update-a-configuration-file/Erlang/update-a-configuration-file.erl b/Task/Update-a-configuration-file/Erlang/update-a-configuration-file.erl new file mode 100644 index 0000000000..a60983b9a8 --- /dev/null +++ b/Task/Update-a-configuration-file/Erlang/update-a-configuration-file.erl @@ -0,0 +1,94 @@ +-module( update_configuration_file ). + +-export( [add/3, change/3, disable/2, enable/2, read/1, task/0, write/2] ). + +add( Option, Value, Lines ) -> + Upper = string:to_upper( Option ), + [string:join( [Upper, Value], " " ) | Lines]. + +change( Option, Value, Lines ) -> + Upper = string:to_upper( Option ), + change_done( Option, Value, Lines, [change_option(Upper, Value, X) || X <- Lines] ). + +disable( Option, Lines ) -> + Upper = string:to_upper( Option ), + [disable_option(Upper, X) || X <- Lines]. + +enable( Option, Lines ) -> + Upper = string:to_upper( Option ), + [enable_option(Upper, X) || X <- Lines]. + +read( Name ) -> + {ok, Binary} = file:read_file( Name ), + Lines = [binary:bin_to_list(X) || X <- binary:split( Binary, <<"\n">>, [global] )], + Lines_no_white = [string:strip(X) || X <- Lines], + Lines_no_control = [strip_control(X) || X <- Lines_no_white], + Lines_no_consecutive_space = [string:join(string:tokens(X, " "), " ") || X <- Lines_no_control], + Lines_no_consecutive_semicolon = [strip_semicolon(X) || X <- Lines_no_consecutive_space], + Lines_no_empty = lists:filter( fun strip_empty/1, Lines_no_consecutive_semicolon ), + Lines_upper = [to_upper(X) || X <- Lines_no_empty], + lists:reverse( lists:foldl(fun remove_duplicates/2, [], Lines_upper) ). + +task() -> + Lines = read( "priv/configuration_file2" ), + Disabled_lines = disable( "needspeeling", Lines ), + Enabled_lines = enable( "SEEDSREMOVED", Disabled_lines ), + Changed_lines1 = change( "NUMBEROFBANANAS", "1024", Enabled_lines ), + Changed_lines2 = change( "numberofstrawberries", "62000", Changed_lines1 ), + write( "configuration_file", Changed_lines2 ), + [io:fwrite( "Wrote this line: ~s~n", [X]) || X <- Changed_lines2]. + +write( Name, Lines ) -> file:write_file( Name, binary:list_to_bin(string:join(Lines, "\n")) ). + + + +change_done( Option, Value, Lines, Lines ) -> add( Option, Value, Lines ); +change_done( _Option, _Value, _Lines, New_lines ) -> New_lines. + +change_option( Option, Value, String ) -> change_option_same( string:str(String, Option), Value, String ). + +change_option_same( 1, Value, String ) -> + [Option | _T] = string:tokens( String, " " ), + string:join( [Option, Value], " " ); +change_option_same( _N, _Value, String ) -> String. + +disable_option( Option, String ) -> disable_option_same( string:str(String, Option), String ). + +disable_option_same( 1, String ) -> "; " ++ String; +disable_option_same( _N, String ) -> String. + +enable_option( Option, String ) -> enable_option_same( string:str(String, "; " ++ Option), String ). + +enable_option_same( 1, "; " ++ String ) -> String; +enable_option_same( _N, String ) -> String. + +is_semicolon( $; ) -> true; +is_semicolon( _C ) -> false. + +remove_duplicates( "#" ++_T=Line, Lines ) -> [Line | Lines]; +remove_duplicates( Line, Lines ) -> + Duplicates = [X || X <-Lines, 1 =:= string:str(Line, X)], + remove_duplicates( Duplicates, Line, Lines ). + +remove_duplicates( [], Line, Lines ) -> [Line | Lines]; +remove_duplicates( _Duplicates, _Line, Lines ) -> Lines. + +strip_control( "" ) -> ""; +strip_control( ";" ++ _T=String ) -> lists:filter( fun strip_control_codes:is_not_control_code_nor_extended_character/1, String ); +strip_control( String ) -> String. + +strip_empty( ";" ) -> false; +strip_empty( _String ) -> true. + + +strip_semicolon( ";" ++ _T=String ) -> ";" ++ lists:dropwhile( fun is_semicolon/1, String ); +strip_semicolon( String ) -> String. + +to_upper( "" ) -> ""; +to_upper( "#" ++ _T=String ) -> String; +to_upper( "; " ++ _T=String ) -> + [";", Option | T] = string:tokens( String, " " ), + string:join( [";", string:to_upper(Option) | T], " " ); +to_upper( String ) -> + [Option | T] = string:tokens( String, " " ), + string:join( [string:to_upper(Option) | T], " " ). diff --git a/Task/User-input-Text/Deja-Vu/user-input-text.djv b/Task/User-input-Text/Deja-Vu/user-input-text.djv new file mode 100644 index 0000000000..2f8fefd743 --- /dev/null +++ b/Task/User-input-Text/Deja-Vu/user-input-text.djv @@ -0,0 +1,11 @@ +input s: + !print\ s + !decode!utf-8 !read-line!stdin +local :astring input "Enter a string: " +true +while: + try: + to-num input "Enter the number 75000: " + /= 75000 + catch value-error: + true diff --git a/Task/User-input-Text/Java/user-input-text-1.java b/Task/User-input-Text/Java/user-input-text-1.java index 482df3bdb0..31e85fc104 100644 --- a/Task/User-input-Text/Java/user-input-text-1.java +++ b/Task/User-input-Text/Java/user-input-text-1.java @@ -1,10 +1,11 @@ -import java.io.BufferedReader; -import java.io.InputStreamReader; +import java.util.Scanner; public class GetInput { public static void main(String[] args) throws Exception { - BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); - int number = Integer.parseInt(sysin.readLine()); - String string = sysin.readLine(); + Scanner s = new Scanner(System.in); + System.out.print("Enter a string: "); + String str = s.nextLine(); + System.out.print("Enter an integer: "); + int i = Integer.parseInt(s.next()); } } diff --git a/Task/Vampire-number/Go/vampire-number.go b/Task/Vampire-number/Go/vampire-number.go new file mode 100644 index 0000000000..f43256310c --- /dev/null +++ b/Task/Vampire-number/Go/vampire-number.go @@ -0,0 +1,91 @@ +package main + +import ( + "fmt" + "math" +) + +func max(a, b uint64) uint64 { + if a > b { + return a + } + return b +} + +func min(a, b uint64) uint64 { + if a < b { + return a + } + return b +} + +func ndigits(x uint64) (n int) { + for ; x > 0; x /= 10 { + n++ + } + return +} + +func dtally(x uint64) (t uint64) { + for ; x > 0; x /= 10 { + t += 1 << (x % 10 * 6) + } + return +} + +var tens [20]uint64 + +func init() { + tens[0] = 1 + for i := 1; i < 20; i++ { + tens[i] = tens[i-1] * 10 + } +} + +func fangs(x uint64) (f []uint64) { + nd := ndigits(x) + if nd&1 == 1 { + return + } + nd /= 2 + lo := max(tens[nd-1], (x+tens[nd]-2)/(tens[nd]-1)) + hi := min(x/lo, uint64(math.Sqrt(float64(x)))) + t := dtally(x) + for a := lo; a <= hi; a++ { + b := x / a + if a*b == x && + (a%10 > 0 || b%10 > 0) && + t == dtally(a)+dtally(b) { + f = append(f, a) + } + } + return +} + +func showFangs(x uint64, f []uint64) { + fmt.Print(x) + if len(f) > 1 { + fmt.Println() + } + for _, a := range f { + fmt.Println(" =", a, "×", x/a) + } +} + +func main() { + for x, n := uint64(1), 0; n < 26; x++ { + if f := fangs(x); len(f) > 0 { + n++ + fmt.Printf("%2d: ", n) + showFangs(x, f) + } + } + fmt.Println() + for _, x := range []uint64{16758243290880, 24959017348650, 14593825548650} { + if f := fangs(x); len(f) > 0 { + showFangs(x, f) + } else { + fmt.Println(x, "is not vampiric") + } + } +} diff --git a/Task/Van-der-Corput-sequence/ActionScript/van-der-corput-sequence.as b/Task/Van-der-Corput-sequence/ActionScript/van-der-corput-sequence.as new file mode 100644 index 0000000000..6a04e5af9a --- /dev/null +++ b/Task/Van-der-Corput-sequence/ActionScript/van-der-corput-sequence.as @@ -0,0 +1,66 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + + public class VanDerCorput extends Sprite { + + public function VanDerCorput():void { + if (stage) init(); + else addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(e:Event = null):void { + + removeEventListener(Event.ADDED_TO_STAGE, init); + + var base2:Vector. = new Vector.(10, true); + var base3:Vector. = new Vector.(10, true); + var base4:Vector. = new Vector.(10, true); + var base5:Vector. = new Vector.(10, true); + var base6:Vector. = new Vector.(10, true); + var base7:Vector. = new Vector.(10, true); + var base8:Vector. = new Vector.(10, true); + + var i:uint; + + for ( i = 0; i < 10; i++ ) { + base2[i] = Math.round( _getTerm(i, 2) * 1000000 ) / 1000000; + base3[i] = Math.round( _getTerm(i, 3) * 1000000 ) / 1000000; + base4[i] = Math.round( _getTerm(i, 4) * 1000000 ) / 1000000; + base5[i] = Math.round( _getTerm(i, 5) * 1000000 ) / 1000000; + base6[i] = Math.round( _getTerm(i, 6) * 1000000 ) / 1000000; + base7[i] = Math.round( _getTerm(i, 7) * 1000000 ) / 1000000; + base8[i] = Math.round( _getTerm(i, 8) * 1000000 ) / 1000000; + } + + trace("Base 2: " + base2.join(', ')); + trace("Base 3: " + base3.join(', ')); + trace("Base 4: " + base4.join(', ')); + trace("Base 5: " + base5.join(', ')); + trace("Base 6: " + base6.join(', ')); + trace("Base 7: " + base7.join(', ')); + trace("Base 8: " + base8.join(', ')); + + } + + private function _getTerm(n:uint, base:uint = 2):Number { + + var r:Number = 0, p:uint, digit:uint; + var baseLog:Number = Math.log(base); + + while ( n > 0 ) { + p = Math.pow( base, uint(Math.log(n) / baseLog) ); + + digit = n / p; + n %= p; + r += digit / (p * base); + } + + return r; + + } + + } + +} diff --git a/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-1.clj b/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-1.clj new file mode 100644 index 0000000000..bb00e96510 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-1.clj @@ -0,0 +1,25 @@ +(defn van-der-corput + "Get the nth element of the van der Corput sequence." + ([n] + ;; Default base = 2 + (van-der-corput n 2)) + ([n base] + (let [s (/ 1 base)] ;; A multiplicand to shift to the right of the decimal. + ;; We essentially want to reverse the digits of n and put them after the + ;; decimal point. So, we repeatedly pull off the lowest digit of n, scale + ;; it to the right of the decimal point, and accumulate that. + (loop [sum 0 + n n + scale s] + (if (zero? n) + sum ;; Base case: no digits left, so we're done. + (recur (+ sum (* (rem n base) scale)) ;; Accumulate the least digit + (quot n base) ;; Drop a digit of n + (* scale s))))))) ;; Move farther past the decimal + +(clojure.pprint/print-table + (cons :base (range 10)) ;; column headings + (for [base (range 2 6)] ;; rows + (into {:base base} + (for [n (range 10)] ;; table entries + [n (van-der-corput n base)])))) diff --git a/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-2.clj b/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-2.clj new file mode 100644 index 0000000000..5663c98b59 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-2.clj @@ -0,0 +1,6 @@ +| :base | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +|-------+---+-----+-----+-----+------+------+------+-------+-------+-------| +| 2 | 0 | 1/2 | 1/4 | 3/4 | 1/8 | 5/8 | 3/8 | 7/8 | 1/16 | 9/16 | +| 3 | 0 | 1/3 | 2/3 | 1/9 | 4/9 | 7/9 | 2/9 | 5/9 | 8/9 | 1/27 | +| 4 | 0 | 1/4 | 1/2 | 3/4 | 1/16 | 5/16 | 9/16 | 13/16 | 1/8 | 3/8 | +| 5 | 0 | 1/5 | 2/5 | 3/5 | 4/5 | 1/25 | 6/25 | 11/25 | 16/25 | 21/25 | diff --git a/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-1.maxima b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-1.maxima new file mode 100644 index 0000000000..74f7947eb0 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-1.maxima @@ -0,0 +1,11 @@ +/* convert a decimal integer to a list of digits in base `base' */ +dec2digits(d, base):= block([digits: []], + while (d>0) do block([newdi: mod(d, base)], + digits: cons(newdi, digits), + d: round( (d - newdi) / base)), + digits)$ + +dec2digits(123, 10); +/* [1, 2, 3] */ +dec2digits( 8, 2); +/* [1, 0, 0, 0] */ diff --git a/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-2.maxima b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-2.maxima new file mode 100644 index 0000000000..d40577dfdb --- /dev/null +++ b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-2.maxima @@ -0,0 +1,9 @@ +/* convert a list of digits in base `base' to a decimal integer */ +digits2dec(l, base):= block([s: 0, po: 1], + for di in reverse(l) do (s: di*po + s, po: po*base), + s)$ + +digits2dec([1, 2, 3], 10); +/* 123 */ +digits2dec([1, 0, 0, 0], 2); +/* 8 */ diff --git a/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-3.maxima b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-3.maxima new file mode 100644 index 0000000000..7a805817ae --- /dev/null +++ b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-3.maxima @@ -0,0 +1,19 @@ +vdc(n, base):= makelist( + digits2dec( + dec2digits(k, base), + 1/base) / base, + k, n); + +vdc(10, 2); +/* + 1 1 3 1 5 3 7 1 9 5 +(%o123) [-, -, -, -, -, -, -, --, --, --] + 2 4 4 8 8 8 8 16 16 16 +*/ + +vdc(10, 5); +/* + 1 2 3 4 1 6 11 16 21 2 +(%o124) [-, -, -, -, --, --, --, --, --, --] + 5 5 5 5 25 25 25 25 25 25 +*/ diff --git a/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-4.maxima b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-4.maxima new file mode 100644 index 0000000000..2d87b4fb1f --- /dev/null +++ b/Task/Van-der-Corput-sequence/Maxima/van-der-corput-sequence-4.maxima @@ -0,0 +1,21 @@ +/* 11 in decimal is */ +digits: digits2dec([box(1), box(0), box(1), box(1)], box(2)); +aux: expand(digits2dec(digits, 1/base) / base)$ +simp: false$ +/* reflected this would become ... */ +subst(box(2), base, aux); +simp: true$ + +/* + + 3 2 + """ """ """ """ """ """ """ +(%o126) "2" "1" + "2" "0" + "2" "1" + "1" + """ """ """ """ """ """ """ + + - 4 - 3 - 2 - 1 + """ """ """ """ """ """ """ """ +(%o129) "1" "2" + "0" "2" + "1" "2" + "1" "2" + """ """ """ """ """ """ """ """ + +*/ diff --git a/Task/Variable-length-quantity/Bracmat/variable-length-quantity.bracmat b/Task/Variable-length-quantity/Bracmat/variable-length-quantity.bracmat new file mode 100644 index 0000000000..f49dee1129 --- /dev/null +++ b/Task/Variable-length-quantity/Bracmat/variable-length-quantity.bracmat @@ -0,0 +1,56 @@ +( ( VLQ + = b07 b8 vlq + . 0:?b8 + & :?vlq + & whl + ' ( !arg:>0 + & mod$(!arg.128):?b07 + & (chr$(!b8+!b07)|) !vlq:?vlq + & 128:?b8 + & div$(!arg.128):?arg + ) + & str$!vlq + ) +& ( NUM + = c num d + . 0:?num:?d + & whl + ' ( @(!arg:%@?c ?arg) + & asc$!c:?c:~<128 + & 128*(!c+-128+!num):?num + & 1+!d:?d + ) + & (!c:<128&!c+!num:?num|) + & !num + ) +& ( printVLQ + = c h + . :?h + & whl + ' ( @(!arg:%@?c ?arg) + & d2x$(asc$!c):?x + & !h (@(!x:? [1)&0|) !x + : ?h + ) + & ( asc$!c:~<128&!h 00:?h + | + ) + & out$("VLQ :" str$!h) + ) +& ( test + = vlq num + . out$("input:" !arg) + & VLQ$(x2d$!arg):?vlq + & printVLQ$!vlq + & NUM$!vlq:?num + & out$("back :" d2x$!num \n) + ) +& test$200000 +& test$1fffff +& test$00 +& test$7f +& test$80 +& test$81 +& test$82 +& test$894E410E0A +); diff --git a/Task/Variable-length-quantity/D/variable-length-quantity.d b/Task/Variable-length-quantity/D/variable-length-quantity.d index 0f778dfbcd..732ac78796 100644 --- a/Task/Variable-length-quantity/D/variable-length-quantity.d +++ b/Task/Variable-length-quantity/D/variable-length-quantity.d @@ -49,7 +49,7 @@ struct VLQ { return res; } - string toString() const /*pure nothrow*/ { + string toString() const pure /*nothrow*/ { return format("(%(%02X:%))", this.toVLQ); } } diff --git a/Task/Variable-length-quantity/TXR/variable-length-quantity.txr b/Task/Variable-length-quantity/TXR/variable-length-quantity.txr new file mode 100644 index 0000000000..ee98bf537f --- /dev/null +++ b/Task/Variable-length-quantity/TXR/variable-length-quantity.txr @@ -0,0 +1,22 @@ +@(do + ;; show the utf8 bytes from byte stream as hex + (defun put-utf8 (str : stream) + (set stream (or stream *stdout*)) + (for ((s (make-string-byte-input-stream str)) byte) + ((set byte (get-byte s))) + ((format stream "\\x~,02x" byte)))) + + ;; print + (put-utf8 (tostring 0)) + (put-line "") + (put-utf8 (tostring 42)) + (put-line "") + (put-utf8 (tostring #x200000)) + (put-line "") + (put-utf8 (tostring #x1fffff)) + (put-line "") + + ;; print to string and recover + + (format t "~a\n" (read (tostring #x200000))) + (format t "~a\n" (read (tostring #x1f0000)))) diff --git a/Task/Variable-size-Get/ActionScript/variable-size-get.as b/Task/Variable-size-Get/ActionScript/variable-size-get.as new file mode 100644 index 0000000000..8763add132 --- /dev/null +++ b/Task/Variable-size-Get/ActionScript/variable-size-get.as @@ -0,0 +1,32 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + import flash.sampler.getSize; + + public class VariableSizeGet extends Sprite { + + public function VariableSizeGet() { + if ( stage ) _init(); + else addEventListener(Event.ADDED_TO_STAGE, _init); + } + + private function _init(e:Event = null):void { + + var i:int = 1; + var n:Number = 0.5; + var s:String = "abc"; + var b:Boolean = true; + var date:Date = new Date(); + + trace("An int contains " + getSize(i) + " bytes."); // 4 + trace("A Number contains " + getSize(n) + " bytes."); // 8 + trace("The string 'abc' contains " + getSize(s) + " bytes."); // 24 + trace("A Boolean contains " + getSize(b) + " bytes."); // 4 + trace("A Date object contains " + getSize(date) + " bytes."); // 48 + + } + + } + +} diff --git a/Task/Variable-size-Get/Go/variable-size-get.go b/Task/Variable-size-Get/Go/variable-size-get-1.go similarity index 100% rename from Task/Variable-size-Get/Go/variable-size-get.go rename to Task/Variable-size-Get/Go/variable-size-get-1.go diff --git a/Task/Variable-size-Get/Go/variable-size-get-2.go b/Task/Variable-size-Get/Go/variable-size-get-2.go new file mode 100644 index 0000000000..b7143448c1 --- /dev/null +++ b/Task/Variable-size-Get/Go/variable-size-get-2.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "reflect" + "runtime" + "unsafe" +) + +func main() { + // unsafe.Sizeof returns the size in bytes. + var i int + fmt.Println(unsafe.Sizeof(i)) + // The size returned is that of the top level object and does not + // include any referenced data. A type like string always returns + // the same number, the size of the string header. + fmt.Println(unsafe.Sizeof("Rosetta")) + fmt.Println(unsafe.Sizeof("Code")) + // For some untrusted environments, package unsafe is not available + // but reflect is. The Size method of a type will return the same value + // as unsafe.Sizeof. + fmt.Println(reflect.TypeOf("Cod").Size()) + // Some sizes are implementation dependent. + fmt.Println(runtime.Version(), runtime.GOARCH) +} diff --git a/Task/Variable-size-Get/Julia/variable-size-get.julia b/Task/Variable-size-Get/Julia/variable-size-get.julia index ea192e76f9..f37333c18d 100644 --- a/Task/Variable-size-Get/Julia/variable-size-get.julia +++ b/Task/Variable-size-Get/Julia/variable-size-get.julia @@ -5,4 +5,4 @@ julia> t = 1 1 julia> sizeof(t) -4 +8 diff --git a/Task/Variables/Batch-File/variables.bat b/Task/Variables/Batch-File/variables.bat new file mode 100644 index 0000000000..31e995dc63 --- /dev/null +++ b/Task/Variables/Batch-File/variables.bat @@ -0,0 +1,16 @@ +@echo off + +::setting variables in defferent ways +set myInt1=5 +set myString1=Rosetta Code +set "myInt2=5" +set "myString2=Rosetta Code" + +::Arithmetic +set /a myInt1=%myInt1%+1 +set /a myInt2+=1 +set /a myInt3=myInt2+ 5 + +set myInt +set myString +pause>nul diff --git a/Task/Variables/COBOL/variables-4.cobol b/Task/Variables/COBOL/variables-4.cobol index 7844f8be18..a2be31238e 100644 --- a/Task/Variables/COBOL/variables-4.cobol +++ b/Task/Variables/COBOL/variables-4.cobol @@ -1,10 +1,4 @@ *> Group data items do not have a picture clause. -01 group-item. *> The 'implied' PIC for group-item is PIC X(20). +01 group-item. 03 sub-data PIC X(10). 03 more-sub-data PIC X(10). - -*> Example use of FILLER. -01 formatted-data. - 03 part-one PIC X(10). - 03 FILLER PIC X. - 03 part-two PIC X(10). diff --git a/Task/Variables/COBOL/variables-5.cobol b/Task/Variables/COBOL/variables-5.cobol index 36f77036c6..90480d0b39 100644 --- a/Task/Variables/COBOL/variables-5.cobol +++ b/Task/Variables/COBOL/variables-5.cobol @@ -6,6 +6,3 @@ WORKING-STORAGE SECTION. PROCEDURE DIVISION. DISPLAY initialized-data *> Shows 'Hello, World!' DISPLAY other-data *> Will probably show 15 spaces. - ... - *> Sets initialized-data back to "Hello, World!" and fills other-data with spaces. - INITIALIZE initialized-data, other-data diff --git a/Task/Variables/COBOL/variables-7.cobol b/Task/Variables/COBOL/variables-7.cobol index e798fec446..5499d7391a 100644 --- a/Task/Variables/COBOL/variables-7.cobol +++ b/Task/Variables/COBOL/variables-7.cobol @@ -2,7 +2,5 @@ some-str (1:1) *> Gets the first character from the string some-num (1:3) *> Get the first three digits from the number another-string (5:) *> Get everything from the 5th character/digit onwards. -*> To get a proper array slice, you must use reference modification on its parent data item: -some-table-area (4:6) *> Get 6 characters from the array after from the 4th char onwards *> To reference modify an array element some-table (1) (5:1) *> Get the 5th character from the 1st element in the table diff --git a/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk b/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk index 847a58e4e1..b74f49779f 100644 --- a/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk +++ b/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk @@ -1,3 +1,3 @@ printAll(4, 3, 5, 6, 4, 3) printAll(4, 3, 5) -printAll("Rosetta", "Code", "Is", "Awseome!") +printAll("Rosetta", "Code", "Is", "Awesome!") diff --git a/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk b/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk index afdbd63ebf..cc41b1787a 100644 --- a/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk +++ b/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk @@ -1,2 +1,2 @@ -args := ["Rosetta", "Code", "Is", "Awseome!"] +args := ["Rosetta", "Code", "Is", "Awesome!"] printAll(args*) diff --git a/Task/Variadic-function/D/variadic-function.d b/Task/Variadic-function/D/variadic-function.d index 002528ae9d..29697711ab 100644 --- a/Task/Variadic-function/D/variadic-function.d +++ b/Task/Variadic-function/D/variadic-function.d @@ -16,7 +16,7 @@ void showSum2(int[4] items...) { } void main() { - printAll(4, 5.6, "Rosetta", "Code", "is", "awseome"); + printAll(4, 5.6, "Rosetta", "Code", "is", "awesome"); writeln(); showSum1(1, 3, 50); showSum2(1, 3, 50, 10); diff --git a/Task/Variadic-function/Deja-Vu/variadic-function.djv b/Task/Variadic-function/Deja-Vu/variadic-function.djv new file mode 100644 index 0000000000..2a030a7fc1 --- /dev/null +++ b/Task/Variadic-function/Deja-Vu/variadic-function.djv @@ -0,0 +1,6 @@ +show-all(: + while /= ) dup: + !. + drop + +show-all( :foo "Hello" 42 [ true ] ) diff --git a/Task/Variadic-function/Haskell/variadic-function.hs b/Task/Variadic-function/Haskell/variadic-function.hs index 9e5e116cc4..6ff397e5a8 100644 --- a/Task/Variadic-function/Haskell/variadic-function.hs +++ b/Task/Variadic-function/Haskell/variadic-function.hs @@ -14,4 +14,4 @@ printAll = process [] main :: IO () main = do printAll 5 "Mary" "had" "a" "little" "lamb" printAll 4 3 5 - printAll "Rosetta" "Code" "Is" "Awseome!" + printAll "Rosetta" "Code" "Is" "Awesome!" diff --git a/Task/Variadic-function/Java/variadic-function-2.java b/Task/Variadic-function/Java/variadic-function-2.java index 0e43a38e15..b502e90906 100644 --- a/Task/Variadic-function/Java/variadic-function-2.java +++ b/Task/Variadic-function/Java/variadic-function-2.java @@ -1,3 +1,3 @@ printAll(4, 3, 5, 6, 4, 3); printAll(4, 3, 5); -printAll("Rosetta", "Code", "Is", "Awseome!"); +printAll("Rosetta", "Code", "Is", "Awesome!"); diff --git a/Task/Variadic-function/Java/variadic-function-3.java b/Task/Variadic-function/Java/variadic-function-3.java index d27e07c71d..be59c06a08 100644 --- a/Task/Variadic-function/Java/variadic-function-3.java +++ b/Task/Variadic-function/Java/variadic-function-3.java @@ -1,2 +1,2 @@ -Object[] args = {"Rosetta", "Code", "Is", "Awseome!"}; +Object[] args = {"Rosetta", "Code", "Is", "Awesome!"}; printAll(args); diff --git a/Task/Variadic-function/Java/variadic-function-4.java b/Task/Variadic-function/Java/variadic-function-4.java index 5e8b70335c..11397df3c7 100644 --- a/Task/Variadic-function/Java/variadic-function-4.java +++ b/Task/Variadic-function/Java/variadic-function-4.java @@ -1,3 +1,3 @@ -Object[] args = {"Rosetta", "Code", "Is", "Awseome,"}; +Object[] args = {"Rosetta", "Code", "Is", "Awesome,"}; printAll(args, "Dude!");//does not print "Rosetta Code Is Awesome, Dude!" //instead prints the type and hashcode for args followed by "Dude!" diff --git a/Task/Variadic-function/JavaScript/variadic-function-1.js b/Task/Variadic-function/JavaScript/variadic-function-1.js index e4896c9b23..a63123ae12 100644 --- a/Task/Variadic-function/JavaScript/variadic-function-1.js +++ b/Task/Variadic-function/JavaScript/variadic-function-1.js @@ -4,4 +4,4 @@ function printAll() { } printAll(4, 3, 5, 6, 4, 3); printAll(4, 3, 5); -printAll("Rosetta", "Code", "Is", "Awseome!"); +printAll("Rosetta", "Code", "Is", "Awesome!"); diff --git a/Task/Variadic-function/JavaScript/variadic-function-2.js b/Task/Variadic-function/JavaScript/variadic-function-2.js index 9071a0b660..9a1de4cdad 100644 --- a/Task/Variadic-function/JavaScript/variadic-function-2.js +++ b/Task/Variadic-function/JavaScript/variadic-function-2.js @@ -1,2 +1,2 @@ -args = ["Rosetta", "Code", "Is", "Awseome!"] +args = ["Rosetta", "Code", "Is", "Awesome!"] printAll.apply(null, args) diff --git a/Task/Variadic-function/Julia/variadic-function-1.julia b/Task/Variadic-function/Julia/variadic-function-1.julia index 44c20d160f..83205982bd 100644 --- a/Task/Variadic-function/Julia/variadic-function-1.julia +++ b/Task/Variadic-function/Julia/variadic-function-1.julia @@ -1 +1,6 @@ -bar(a,b,x...) = (a,b,x) +julia> print_each(X...) = for x in X; println(x); end + +julia> print_each(1, "hello", 23.4) +1 +hello +23.4 diff --git a/Task/Variadic-function/Julia/variadic-function-2.julia b/Task/Variadic-function/Julia/variadic-function-2.julia index a45ffc8d3a..be3b677b89 100644 --- a/Task/Variadic-function/Julia/variadic-function-2.julia +++ b/Task/Variadic-function/Julia/variadic-function-2.julia @@ -1,11 +1,10 @@ -julia> bar(1,2) -(1,2,()) +julia> args = [ "first", (1,2,17), "last" ] +3-element Array{Any,1}: + "first" + (1,2,17) + "last -julia> bar(1,2,3) -(1,2,(3,)) - -julia> bar(1,2,3,4) -(1,2,(3,4)) - -julia> bar(1,2,3,4,5,6) -(1,2,(3,4,5,6)) +julia> print_each(args...) +first +(1,2,17) +last diff --git a/Task/Variadic-function/Objective-C/variadic-function.m b/Task/Variadic-function/Objective-C/variadic-function.m index d920816610..171dd6315f 100644 --- a/Task/Variadic-function/Objective-C/variadic-function.m +++ b/Task/Variadic-function/Objective-C/variadic-function.m @@ -11,7 +11,7 @@ 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", @"Awseome!", nil); +logObjects(@"Rosetta", @"Code", @"Is", @"Awesome!", nil); logObjects([NSNumber numberWithInt:4], [NSNumber numberWithInt:3], @"foo", nil); diff --git a/Task/Variadic-function/PHP/variadic-function-1.php b/Task/Variadic-function/PHP/variadic-function-1.php index ea0999343b..9eaa03f447 100644 --- a/Task/Variadic-function/PHP/variadic-function-1.php +++ b/Task/Variadic-function/PHP/variadic-function-1.php @@ -8,4 +8,4 @@ function printAll() { } printAll(4, 3, 5, 6, 4, 3); printAll(4, 3, 5); -printAll("Rosetta", "Code", "Is", "Awseome!"); +printAll("Rosetta", "Code", "Is", "Awesome!"); diff --git a/Task/Variadic-function/PHP/variadic-function-2.php b/Task/Variadic-function/PHP/variadic-function-2.php index 7a377668d9..8834cfb8dc 100644 --- a/Task/Variadic-function/PHP/variadic-function-2.php +++ b/Task/Variadic-function/PHP/variadic-function-2.php @@ -1,2 +1,2 @@ -$args = array("Rosetta", "Code", "Is", "Awseome!"); +$args = array("Rosetta", "Code", "Is", "Awesome!"); call_user_func_array('printAll', $args); diff --git a/Task/Variadic-function/Perl/variadic-function-2.pl b/Task/Variadic-function/Perl/variadic-function-2.pl index ed2482f5c3..15edc90e44 100644 --- a/Task/Variadic-function/Perl/variadic-function-2.pl +++ b/Task/Variadic-function/Perl/variadic-function-2.pl @@ -1,3 +1,3 @@ print_all(4, 3, 5, 6, 4, 3); print_all(4, 3, 5); -print_all("Rosetta", "Code", "Is", "Awseome!"); +print_all("Rosetta", "Code", "Is", "Awesome!"); diff --git a/Task/Variadic-function/Perl/variadic-function-3.pl b/Task/Variadic-function/Perl/variadic-function-3.pl index dc8870e987..40bf55206e 100644 --- a/Task/Variadic-function/Perl/variadic-function-3.pl +++ b/Task/Variadic-function/Perl/variadic-function-3.pl @@ -1,2 +1,2 @@ -@args = ("Rosetta", "Code", "Is", "Awseome!"); +@args = ("Rosetta", "Code", "Is", "Awesome!"); print_all(@args); diff --git a/Task/Variadic-function/Python/variadic-function-2.py b/Task/Variadic-function/Python/variadic-function-2.py index c7218d045c..2fdbdc2d62 100644 --- a/Task/Variadic-function/Python/variadic-function-2.py +++ b/Task/Variadic-function/Python/variadic-function-2.py @@ -1,3 +1,3 @@ print_all(4, 3, 5, 6, 4, 3) print_all(4, 3, 5) -print_all("Rosetta", "Code", "Is", "Awseome!") +print_all("Rosetta", "Code", "Is", "Awesome!") diff --git a/Task/Variadic-function/Python/variadic-function-3.py b/Task/Variadic-function/Python/variadic-function-3.py index be843c2caa..16dbe40dfd 100644 --- a/Task/Variadic-function/Python/variadic-function-3.py +++ b/Task/Variadic-function/Python/variadic-function-3.py @@ -1,2 +1,2 @@ -args = ["Rosetta", "Code", "Is", "Awseome!"] +args = ["Rosetta", "Code", "Is", "Awesome!"] print_all(*args) diff --git a/Task/Variadic-function/REXX/variadic-function-1.rexx b/Task/Variadic-function/REXX/variadic-function-1.rexx index ba750aa516..2ce6a90080 100644 --- a/Task/Variadic-function/REXX/variadic-function-1.rexx +++ b/Task/Variadic-function/REXX/variadic-function-1.rexx @@ -1,5 +1,5 @@ -print_all: procedure +print_all: procedure /* [↓] is the # of args passed.*/ do j=1 for arg() - say arg(j) + say arg(j) end /*j*/ return diff --git a/Task/Variadic-function/REXX/variadic-function-2.rexx b/Task/Variadic-function/REXX/variadic-function-2.rexx index 591bad21e3..5c7f9d908d 100644 --- a/Task/Variadic-function/REXX/variadic-function-2.rexx +++ b/Task/Variadic-function/REXX/variadic-function-2.rexx @@ -1,5 +1,5 @@ -print_all: procedure +print_all: procedure /* [↓] is the # of args passed.*/ do j=1 for arg() - say '[argument' j"]: " arg(j) + say '[argument' j"]: " arg(j) end /*j*/ return diff --git a/Task/Variadic-function/REXX/variadic-function-3.rexx b/Task/Variadic-function/REXX/variadic-function-3.rexx index e8256135ea..037c4017cc 100644 --- a/Task/Variadic-function/REXX/variadic-function-3.rexx +++ b/Task/Variadic-function/REXX/variadic-function-3.rexx @@ -1,10 +1,10 @@ -call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 1 || 1, 'seven numbers are prime, 8th is null' - -call print_all "Hello", "World", "Bang", "Slash-N" +call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 8 || 6, 'seven numbers are prime, 8th is null' call print_all "One ringy-dingy,", "two ringy-dingy,", "three ringy-dingy...", "Hello? This is Ma Bell.", "Have you been misusing your instrument?", - "(Lily Tomlin routine)" /*example showing multi-line arguments.*/ + "(Lily Tomlin routine)" + + /* [↑] example showing multi-line arguments.*/ diff --git a/Task/Variadic-function/RapidQ/variadic-function.rapidq b/Task/Variadic-function/RapidQ/variadic-function.rapidq index 146e73d686..551cacaf00 100644 --- a/Task/Variadic-function/RapidQ/variadic-function.rapidq +++ b/Task/Variadic-function/RapidQ/variadic-function.rapidq @@ -9,4 +9,4 @@ END SUBI printAll 4, 3, 5, 6, 4, 3 printAll 4, 3, 5 -printAll "Rosetta", "Code", "Is", "Awseome!" +printAll "Rosetta", "Code", "Is", "Awesome!" diff --git a/Task/Variadic-function/Ruby/variadic-function-2.rb b/Task/Variadic-function/Ruby/variadic-function-2.rb index c7218d045c..2fdbdc2d62 100644 --- a/Task/Variadic-function/Ruby/variadic-function-2.rb +++ b/Task/Variadic-function/Ruby/variadic-function-2.rb @@ -1,3 +1,3 @@ print_all(4, 3, 5, 6, 4, 3) print_all(4, 3, 5) -print_all("Rosetta", "Code", "Is", "Awseome!") +print_all("Rosetta", "Code", "Is", "Awesome!") diff --git a/Task/Variadic-function/Ruby/variadic-function-3.rb b/Task/Variadic-function/Ruby/variadic-function-3.rb index be843c2caa..16dbe40dfd 100644 --- a/Task/Variadic-function/Ruby/variadic-function-3.rb +++ b/Task/Variadic-function/Ruby/variadic-function-3.rb @@ -1,2 +1,2 @@ -args = ["Rosetta", "Code", "Is", "Awseome!"] +args = ["Rosetta", "Code", "Is", "Awesome!"] print_all(*args) diff --git a/Task/Variadic-function/Scheme/variadic-function-3.ss b/Task/Variadic-function/Scheme/variadic-function-3.ss index b31c04cdf7..415e6b3546 100644 --- a/Task/Variadic-function/Scheme/variadic-function-3.ss +++ b/Task/Variadic-function/Scheme/variadic-function-3.ss @@ -1,3 +1,3 @@ (print-all 4 3 5 6 4 3) (print-all 4 3 5) -(print-all "Rosetta" "Code" "Is" "Awseome!") +(print-all "Rosetta" "Code" "Is" "Awesome!") diff --git a/Task/Variadic-function/Scheme/variadic-function-4.ss b/Task/Variadic-function/Scheme/variadic-function-4.ss index 0e15ae4d31..6b35aae07a 100644 --- a/Task/Variadic-function/Scheme/variadic-function-4.ss +++ b/Task/Variadic-function/Scheme/variadic-function-4.ss @@ -1,2 +1,2 @@ -(define args '("Rosetta" "Code" "Is" "Awseome!")) +(define args '("Rosetta" "Code" "Is" "Awesome!")) (apply print-all args) diff --git a/Task/Variadic-function/TIScript/variadic-function.ti b/Task/Variadic-function/TIScript/variadic-function.ti index 125ce876a5..367ad9b5aa 100644 --- a/Task/Variadic-function/TIScript/variadic-function.ti +++ b/Task/Variadic-function/TIScript/variadic-function.ti @@ -6,4 +6,4 @@ function printAll(separator,argv..) { } printAll(" ", 4, 3, 5, 6, 4, 3); printAll(",", 4, 3, 5); -printAll("! ","Rosetta", "Code", "Is", "Awseome"); +printAll("! ","Rosetta", "Code", "Is", "Awesome"); diff --git a/Task/Vector-products/PHP/vector-products.php b/Task/Vector-products/PHP/vector-products.php new file mode 100644 index 0000000000..fd0b3123ce --- /dev/null +++ b/Task/Vector-products/PHP/vector-products.php @@ -0,0 +1,104 @@ +values = $values; + } + + public function getValues() + { + if ($this->values == null) + $this->setValues(array ( + 0, + 0, + 0 + )); + return $this->values; + } + + public function Vector(array $values) + { + $this->setValues($values); + } + + public static function dotProduct(Vector $va, Vector $vb) + { + $a = $va->getValues(); + $b = $vb->getValues(); + return ($a[0] * $b[0]) + ($a[1] * $b[1]) + ($a[2] * $b[2]); + } + + public static function crossProduct(Vector $va, Vector $vb) + { + $a = $va->getValues(); + $b = $vb->getValues(); + return new Vector(array ( + ($a[1] * $b[2]) - ($a[2] * $b[1]), + ($a[2] * $b[0]) - ($a[0] * $b[2]), + ($a[0] * $b[1]) - ($a[1] * $b[0]) + )); + } + + public static function scalarTripleProduct(Vector $va, Vector $vb, Vector $vc) + { + return self::dotProduct($va, self::crossProduct($vb, $vc)); + } + + public static function vectorTrippleProduct(Vector $va, Vector $vb, Vector $vc) + { + return self::crossProduct($va, self::crossProduct($vb, $vc)); + } +} + +class Program +{ + + public function Program() + { + $a = array ( + 3, + 4, + 5 + ); + $b = array ( + 4, + 3, + 5 + ); + $c = array ( + -5, + -12, + -13 + ); + $va = new Vector($a); + $vb = new Vector($b); + $vc = new Vector($c); + + $result1 = Vector::dotProduct($va, $vb); + $result2 = Vector::crossProduct($va, $vb)->getValues(); + $result3 = Vector::scalarTripleProduct($va, $vb, $vc); + $result4 = Vector::vectorTrippleProduct($va, $vb, $vc)->getValues(); + + printf("\n"); + printf("A = (%0.2f, %0.2f, %0.2f)\n", $a[0], $a[1], $a[2]); + printf("B = (%0.2f, %0.2f, %0.2f)\n", $b[0], $b[1], $b[2]); + printf("C = (%0.2f, %0.2f, %0.2f)\n", $c[0], $c[1], $c[2]); + printf("\n"); + printf("A · B = %0.2f\n", $result1); + printf("A × B = (%0.2f, %0.2f, %0.2f)\n", $result2[0], $result2[1], $result2[2]); + printf("A · (B × C) = %0.2f\n", $result3); + printf("A × (B × C) =(%0.2f, %0.2f, %0.2f)\n", $result4[0], $result4[1], $result4[2]); + } +} + +new Program(); +?> diff --git a/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb index 273d929aea..79038bc2be 100644 --- a/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb +++ b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb @@ -1,34 +1,23 @@ -class VigenereCipher +module VigenereCipher BASE = 'A'.ord SIZE = 'Z'.ord - BASE + 1 - def key=(key) - @key = key.upcase.gsub(/[^A-Z]/, '') + def encrypt(text, key) + crypt(text, key, :+) end - def initialize(key) - self.key= key + def decrypt(text, key) + crypt(text, key, :-) end - def encrypt(text) - crypt(text, :+) - end - - def decrypt(text) - crypt(text, :-) - end - - def crypt(text, dir) - plaintext = text.upcase.gsub(/[^A-Z]/, '') - key_iterator = @key.chars.cycle - ciphertext = '' - plaintext.each_char do |plain_char| - offset = key_iterator.next.ord - BASE - ciphertext += - ((plain_char.ord - BASE).send(dir, offset) % SIZE + BASE).chr + def crypt(text, key, dir) + text = text.upcase.gsub(/[^A-Z]/, '') + key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle + text.each_char.inject('') do |ciphertext, char| + offset = key_iterator.next + ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr end - return ciphertext end end diff --git a/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb index 02c285509a..20c0dc55dd 100644 --- a/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb +++ b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb @@ -1,7 +1,10 @@ -vc = VigenereCipher.new('Vigenere cipher') +include VigenereCipher + plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!' -ciphertext = vc.encrypt(plaintext) -recovered = vc.decrypt(ciphertext) +key = 'Vigenere cipher' +ciphertext = VigenereCipher.encrypt(plaintext, key) +recovered = VigenereCipher.decrypt(ciphertext, key) + puts "Original: #{plaintext}" puts "Encrypted: #{ciphertext}" puts "Decrypted: #{recovered}" diff --git a/Task/Visualize-a-tree/Batch-File/visualize-a-tree.bat b/Task/Visualize-a-tree/Batch-File/visualize-a-tree.bat new file mode 100644 index 0000000000..32f07a70a7 --- /dev/null +++ b/Task/Visualize-a-tree/Batch-File/visualize-a-tree.bat @@ -0,0 +1 @@ +@tree %cd% diff --git a/Task/Visualize-a-tree/Icon/visualize-a-tree.icon b/Task/Visualize-a-tree/Icon/visualize-a-tree.icon new file mode 100644 index 0000000000..9155853959 --- /dev/null +++ b/Task/Visualize-a-tree/Icon/visualize-a-tree.icon @@ -0,0 +1,14 @@ +procedure main(A) + showTree("", " -", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ]) + write() + showTree("", " -", [1, [2,[3,[4]]], [5,[6],[7,[8],[9]],[10]] ]) +end + +procedure showTree(prefix, lastc, A) + write(prefix, lastc, "--", A[1]) + if *A > 1 then { + prefix ||:= if prefix[-1] == "|" then " " else " " + every showTree(prefix||"|", "-", !A[2:2 < *A]) + showTree(prefix, "`-", A[*A]) + } +end diff --git a/Task/Voronoi-diagram/D/voronoi-diagram.d b/Task/Voronoi-diagram/D/voronoi-diagram.d index dbb56ef6d7..a741155ec9 100644 --- a/Task/Voronoi-diagram/D/voronoi-diagram.d +++ b/Task/Voronoi-diagram/D/voronoi-diagram.d @@ -1,34 +1,34 @@ import std.random, std.algorithm, std.range, bitmap; -struct Point { int x, y; } +struct Point { uint x, y; } -Point[] randomPoints(in size_t nPoints, in size_t nx, in size_t ny) { - return iota(nPoints) - .map!((int) => Point(uniform(0, nx), uniform(0, ny))) - .array; -} +enum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) => + nPoints.iota + .map!((int) => Point(uniform(0, nx), uniform(0, ny))) + .array; Image!RGB generateVoronoi(in Point[] pts, - in size_t nx, in size_t ny) { - // Generate a random color for each site. - immutable RndRBG = (int) => RGB(cast(ubyte)uniform(0, 256), + in size_t nx, in size_t ny) /*nothrow*/ { + // Generate a random color for each centroid. + immutable rndRBG = (int) => RGB(cast(ubyte)uniform(0, 256), cast(ubyte)uniform(0, 256), cast(ubyte)uniform(0, 256)); - const colors = pts.length.iota.map!RndRBG.array; + const colors = pts.length.iota.map!rndRBG.array; // Generate diagram by coloring pixels with color of nearest site. auto img = new typeof(return)(nx, ny); foreach (immutable x; 0 .. nx) foreach (immutable y; 0 .. ny) { - immutable dCmp = (in Point a, in Point b) nothrow => + immutable dCmp = (in Point a, in Point b) pure nothrow => ((a.x - x) ^^ 2 + (a.y - y) ^^ 2) < ((b.x - x) ^^ 2 + (b.y - y) ^^ 2); - img[x, y] = colors[pts.length - minPos!dCmp(pts).length]; + // img[x, y] = colors[pts.reduce!(min!dCmp)]; + img[x, y] = colors[pts.length - pts.minPos!dCmp.length]; } - // Mark each site with a black dot. + // Mark each centroid with a white dot. foreach (immutable p; pts) - img[p.x, p.y] = RGB.black; + img[p.tupleof] = RGB.white; return img; } diff --git a/Task/Voronoi-diagram/Haskell/voronoi-diagram.hs b/Task/Voronoi-diagram/Haskell/voronoi-diagram.hs new file mode 100644 index 0000000000..0fdad5a811 --- /dev/null +++ b/Task/Voronoi-diagram/Haskell/voronoi-diagram.hs @@ -0,0 +1,60 @@ +-- Compile with: ghc -O2 -fllvm -fforce-recomp -threaded --make +{-# LANGUAGE BangPatterns #-} +module Main where + +import System.Random + +import Data.Word +import Data.Array.Repa as Repa +import Data.Array.Repa.IO.BMP + +{-# INLINE sqDistance #-} +sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32 +sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2) + +centers :: Int -> Int -> Array U DIM2 Word32 +centers nCenters nCells = + fromListUnboxed (Z :. nCenters :. 2) $ take (2*nCenters) $ randomRs (0, fromIntegral nCells) (mkStdGen 1) + +applyReduce2 arr f = + traverse arr (\(i :. j) -> i) $ \lookup (Z:.i) -> + f (lookup (Z:.i:.0)) (lookup (Z:.i:.1)) + +minimize1D arr = foldS f h t + where + indexed arr = traverse arr id (\src idx@(Z :. i) -> (src idx, (fromIntegral i))) + (Z :. n) = extent arr + iarr = indexed arr + h = iarr ! (Z :. 0) + t = extract (Z :. 1) (Z :. (n-1)) iarr + + f min@(!valMin, !iMin ) x@(!val, !i) | val < valMin = x + | otherwise = min + +voronoi :: Int -> Int -> Array D DIM2 Word32 +voronoi nCenters nCells = + let + {-# INLINE cellReducer #-} + cellReducer = applyReduce2 (centers nCenters nCells) + {-# INLINE nearestCenterIndex #-} + nearestCenterIndex = snd . (Repa.! Z) . minimize1D + in + Repa.fromFunction (Z :. nCells :. nCells :: DIM2) $ \ (Z:.i:.j) -> + nearestCenterIndex $ cellReducer (sqDistance (fromIntegral i) (fromIntegral j)) + +genColorTable :: Int -> Array U DIM1 (Word8, Word8, Word8) +genColorTable n = fromListUnboxed (Z :. n) $ zip3 l1 l2 l3 + where + randoms = randomRs (0,255) (mkStdGen 1) + (l1, rest1) = splitAt n randoms + (l2, rest2) = splitAt n rest1 + l3 = take n rest2 + +colorize :: Array U DIM1 (Word8, Word8, Word8) -> Array D DIM2 Word32 -> Array D DIM2 (Word8, Word8, Word8) +colorize ctable = Repa.map $ \x -> ctable Repa.! (Z:. fromIntegral x) + +main = do + let nsites = 150 + let ctable = genColorTable nsites + voro <- computeP $ colorize ctable (voronoi nsites 512) :: IO (Array U DIM2 (Word8, Word8, Word8)) + writeImageToBMP "out.bmp" voro diff --git a/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d b/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d index b1fbd30b76..ec4db09600 100644 --- a/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d +++ b/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d @@ -1,16 +1,5 @@ -import std.stdio; -import std.file; -import std.path; +void main() { + import std.stdio, std.file; -void main(string[] args) { - auto path = args.length > 1 ? args[1] : "." ; // default current - auto pattern = args.length > 2 ? args[2] : "*.*"; // default all file - - bool matchNPrint(DirEntry* de){ - if(!de.isdir && fnmatch(de.name, pattern)) - writefln(de.name) ; - return true ; // continue - } - - listdir(path, &matchNPrint) ; + dirEntries(".", "*.*", SpanMode.shallow).writeln; } diff --git a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively.d b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively.d new file mode 100644 index 0000000000..58f94420b7 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively.d @@ -0,0 +1,7 @@ +void main() { + import std.stdio, std.file; + + // Recursive breadth-first scan (use SpanMode.depth for + // a depth-first scan): + dirEntries("", "*.d", SpanMode.breadth).writeln; +} diff --git a/Task/Web-scraping/D/web-scraping.d b/Task/Web-scraping/D/web-scraping.d index 4865305442..3d694aa434 100644 --- a/Task/Web-scraping/D/web-scraping.d +++ b/Task/Web-scraping/D/web-scraping.d @@ -1,7 +1,7 @@ -import std.stdio, std.string, std.net.curl, std.algorithm; - void main() { + import std.stdio, std.string, std.net.curl, std.algorithm; + foreach (line; "http://tycho.usno.navy.mil/cgi-bin/timer.pl".byLine) - if (line.length > 4 && line.indexOf(" UTC") != -1) + if (line.canFind(" UTC")) line[4 .. $].writeln; } diff --git a/Task/Web-scraping/Erlang/web-scraping.erl b/Task/Web-scraping/Erlang/web-scraping.erl index d99062b287..d49899570b 100644 --- a/Task/Web-scraping/Erlang/web-scraping.erl +++ b/Task/Web-scraping/Erlang/web-scraping.erl @@ -5,6 +5,6 @@ main() -> inets:start(), - {ok, {_Status, _Header, HTML}} = http:request(?Url), + {ok, {_Status, _Header, HTML}} = httpc:request(?Url), {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]), io:format("~s~n",[Time]). diff --git a/Task/Window-management/Perl/window-management.pl b/Task/Window-management/Perl/window-management.pl new file mode 100644 index 0000000000..9e572de9e4 --- /dev/null +++ b/Task/Window-management/Perl/window-management.pl @@ -0,0 +1,77 @@ +#!perl +use strict; +use warnings; +use Tk; + +my $mw; +my $win; +my $lab; + +# How to open a window. +sub openWin { + if( $win ) { + $win->deiconify; + $win->wm('state', 'normal'); + } else { + eval { $win->destroy } if $win; + $win = $mw->Toplevel; + $win->Label(-text => "This is the window being manipulated") + ->pack(-fill => 'both', -expand => 1); + $lab->configure(-text => "The window object is:\n$win"); + } +} + +# How to close a window +sub closeWin { + return unless $win; + $win->destroy; + $lab->configure(-text => ''); + undef $win; +} + +# How to minimize a window +sub minimizeWin { + return unless $win; + $win->iconify; +} + +# How to maximize a window +sub maximizeWin { + return unless $win; + $win->wm('state', 'zoomed'); + eval { $win->wmAttribute(-zoomed => 1) }; # Hack for X11 +} + +# How to move a window +sub moveWin { + return unless $win; + my ($x, $y) = $win->geometry() =~ /\+(\d+)\+(\d+)\z/ or die; + $_ += 10 for $x, $y; + $win->geometry("+$x+$y"); +} + +# How to resize a window +sub resizeWin { + return unless $win; + my ($w, $h) = $win->geometry() =~ /^(\d+)x(\d+)/ or die; + $_ += 10 for $w, $h; + $win->geometry($w . "x" . $h); +} + +$mw = MainWindow->new; +for my $label0 ($mw->Label(-text => 'Window handle:')) { + $lab = $mw->Label(-text => ''); + $label0->grid($lab); +} + +my @binit = ('Open/Restore' => \&openWin, Close => \&closeWin, + Minimize => \&minimizeWin, Maximize => \&maximizeWin, + Move => \&moveWin, Resize => \&resizeWin); + +while( my ($text, $callback) = splice @binit, 0, 2 ) { + $mw->Button(-text => $text, -command => $callback)->grid('-'); +} + +MainLoop(); + +__END__ diff --git a/Task/Word-wrap/AutoHotkey/word-wrap.ahk b/Task/Word-wrap/AutoHotkey/word-wrap.ahk new file mode 100644 index 0000000000..545e5e464e --- /dev/null +++ b/Task/Word-wrap/AutoHotkey/word-wrap.ahk @@ -0,0 +1,9 @@ +MsgBox, % "72`n" WrapText(Clipboard, 72) "`n80`n" WrapText(Clipboard, 80) +return + +WrapText(Text, LineLength) { + StringReplace, Text, Text, `r`n, %A_Space%, All + while (p := RegExMatch(Text, "([\s\S]{1," LineLength "})(\s|\R|$)", Match, p ? p + StrLen(Match) : 1)) + Result .= Match1 (Match2 = A_Space || A_Tab ? "`n" : Match2) + return, Result +} diff --git a/Task/Word-wrap/Groovy/word-wrap-1.groovy b/Task/Word-wrap/Groovy/word-wrap-1.groovy new file mode 100644 index 0000000000..f98affffc8 --- /dev/null +++ b/Task/Word-wrap/Groovy/word-wrap-1.groovy @@ -0,0 +1,13 @@ +def wordWrap(text, length = 80) { + def sb = new StringBuilder() + def line = '' + + text.split(/\s/).each { word -> + if (line.size() + word.size() > length) { + sb.append(line.trim()).append('\n') + line = '' + } + line += " $word" + } + sb.append(line.trim()).toString() +} diff --git a/Task/Word-wrap/Groovy/word-wrap-2.groovy b/Task/Word-wrap/Groovy/word-wrap-2.groovy new file mode 100644 index 0000000000..8df9d3f22a --- /dev/null +++ b/Task/Word-wrap/Groovy/word-wrap-2.groovy @@ -0,0 +1,13 @@ +def text = """\ + In olden times when wishing still helped one, there lived a king + whose daughters were all beautiful, but the youngest was so beautiful + that the sun itself, which has seen so much, was astonished whenever + it shone in her face. Close by the king's castle lay a great dark + forest, and under an old lime tree in the forest was a well, and when + the day was very warm, the king's child went out into the forest and + sat down by the side of the cool fountain, and when she was bored she + took a golden ball, and threw it up on high and caught it, and this + ball was her favorite plaything.""".stripIndent().split('\n').join(' ') + +println wordWrap(text) +println wordWrap(text, 120) diff --git a/Task/Word-wrap/Ruby/word-wrap.rb b/Task/Word-wrap/Ruby/word-wrap.rb index feda615e00..cf58450f51 100644 --- a/Task/Word-wrap/Ruby/word-wrap.rb +++ b/Task/Word-wrap/Ruby/word-wrap.rb @@ -6,10 +6,10 @@ class String while i < txt.length j = i + width j -= 1 while txt[j] != " " - para << txt[i .. j-1] + para << txt[i ... j] i = j + 1 end - para.join("\n") + para end end diff --git a/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia b/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia index 00650d1c62..a04d92f1bc 100644 --- a/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia +++ b/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia @@ -2,8 +2,4 @@ xprecision = 3 yprecision = 5 x = round([1, 2, 3, 1e11],xprecision) y = round([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision) -file = open("filename","w") do f - for (a, b) in zip(x,y) - writedlm(f,[a b],'\t') - end -end +writedlm("filename", [x y], '\t') diff --git a/Task/Write-language-name-in-3D-ASCII/AWK/write-language-name-in-3d-ascii.awk b/Task/Write-language-name-in-3D-ASCII/AWK/write-language-name-in-3d-ascii.awk new file mode 100644 index 0000000000..74bbbfc2a9 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/AWK/write-language-name-in-3d-ascii.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -f WRITE_LANGUAGE_NAME_IN_3D_ASCII.AWK +BEGIN { + arr[1] = " xxxx x x x x" + arr[2] = "x x x x x x" + arr[3] = "x x x x x x" + arr[4] = "xxxxxx x x xx" + arr[5] = "x x x xx x xx" + arr[6] = "x x xx xx x x" + arr[7] = "x x xx xx x x" + arr[8] = "A V P J B W" + for (i=1; i<=8; i++) { + x = arr[i] + gsub(/./,"& ",x) + gsub(/[xA-Z] /,"_/",x) + print(x) + } + exit(0) +} diff --git a/Task/Write-language-name-in-3D-ASCII/AutoHotkey/write-language-name-in-3d-ascii.ahk b/Task/Write-language-name-in-3D-ASCII/AutoHotkey/write-language-name-in-3d-ascii.ahk new file mode 100644 index 0000000000..7e46267114 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/AutoHotkey/write-language-name-in-3d-ascii.ahk @@ -0,0 +1,18 @@ +AutoTrim, Off +draw = +( + ______ __ __ __ __ +/\ __ \/\ \_\ \/\ \/ / +\ \ __ \ \ __ \ \ _"-. + \ \_\ \_\ \_\ \_\ \_\ \_\ + \/_/\/_/\/_/\/_/\/_/\/_/ +) +Gui, +ToolWindow +Gui, Color, 1A1A1A, 1A1A1A +Gui, Font, s8 cLime w800, Courier New +Gui, Add, text, x4 y0 , % " " draw +Gui, Show, w192 h82, AHK in 3D +return + +GuiClose: +ExitApp diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-1.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-1.basic new file mode 100644 index 0000000000..e5def22212 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-1.basic @@ -0,0 +1,48 @@ +10 S$ = "BASIC" : REM OUR LANGUAGE NAME +20 DIM B(5,5) : REM OUR BIGMAP CHARACTERS +30 FOR L = 1 TO 5 : REM 5 CHARACTERS +40 FOR M = 1 TO 5 : REM 5 ROWS +50 READ B(L,M) +60 NEXT M, L + +100 GR : REM BLACK BACKGROUND +110 COLOR = 1 : REM OUR SHADOW WILL BE RED +120 HOME : REM CLS +130 R = 9 : REM SHADOW WILL START ON ROW 5 +140 C = 2 : REM SHADOW WILL START AT COLUMN 2 +150 GOSUB 2000"DRAW SHADOW +160 COLOR = 13 : REM OUR FOREGROUND WILL BE YELLOW +170 R = 10 : REM FOREGROUND WILL START ON ROW 6 +180 C = 3 : REM FOREGROUND WILL START ON COLUMN 3 +190 GOSUB 2000"DISPLAY THE LANGUAGE NAME + +999 STOP + +1000 REM CONVERT TO BINARY BIGMAP +1010 T = N : REM TEMPORARY VARIABLE +1020 G$ = "" : REM THIS WILL CONTAIN OUR 5 CHARACTER BINARY BIGMAP +1040 FOR Z = 5 TO 0 STEP -1 +1050 D$ = " " : REM ASSUME NEXT DIGIT IS ZERO (DRAW A SPACE) +1055 S = 2 ^ Z +1060 IF T >= S THEN D$ = "*" : T = T - S : REM IS A BLOCK +1070 G$ = G$ + D$ +1080 NEXT Z +1090 RETURN + +2000 REM DISPLAY THE BIG LETTERS +2010 FOR L = 1 TO 5 : REM OUR 5 ROWS +2020 X = C : Y = R + L - 1 : REM PRINT AT R+L-1,C; +2030 FOR M = 1 TO 5 : REM BIGMAP FOR EACH CHARACTER +2040 N = B(M, L) +2050 GOSUB 1000 +2060 FOR I = 1 TO LEN(G$) : IF MID$(G$, I, 1) <> " " THEN PLOT X,Y :REM 5 CHARACTER BIGMAP +2070 X = X + 1 : NEXT I +2080 X = X + 1 : REM PRINT " ";: REM SPACE BETWEEN EACH LETTER +2090 NEXT M, L +2100 RETURN + +9000 DATA 30,17,30,17,30: REM B +9010 DATA 14,17,31,17,17: REM A +9020 DATA 15,16,14,1,30: REM S +9030 DATA 31,4,4,4,31: REM I +9040 DATA 14,17,16,17,14: REM C diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-2.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-2.basic new file mode 100644 index 0000000000..9c416d07cd --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-2.basic @@ -0,0 +1,22 @@ + PROC3dname("BBC BASIC") + END + + DEF PROC3dname(name$) + LOCAL A%, X%, Y%, char%, row%, patt%, bit% + DIM X% 8 : A% = 10 : Y% = X% DIV 256 + FOR row% = 1 TO 8 + FOR char% = 1 TO LEN(name$) + ?X% = ASCMID$(name$,char%) + CALL &FFF1 + patt% = X%?row% + FOR bit% = 7 TO 0 STEP -1 + CASE TRUE OF + WHEN (patt% AND 2^bit%) <> 0 : PRINT "#"; + WHEN GET$(POS-1,VPOS-1) = "#": PRINT "\"; + OTHERWISE: PRINT " "; + ENDCASE + NEXT + NEXT char% + PRINT + NEXT row% + ENDPROC diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-3.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-3.basic new file mode 100644 index 0000000000..83dc7742eb --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-3.basic @@ -0,0 +1,27 @@ +dim as integer yres=hiword(width) +dim as integer xres=loword(width) + +#define map(a,b,x,c,d) ((d)-(c))*((x)-(a))/((b)-(a))+(c) +#define _X(num) int( map(0,xres,(num),0,loword(width))) +#define _Y(num) int( map(0,yres,(num),0,hiword(width))) + +Type pt + As Integer x,y +End Type +Dim As pt a(1 To ...)=_ +{(4,2),(6,2),(8,2),(12,2),(14,2),(16,2),(20,2),(22,2),(24,2),(28,2),(30,2),(32,2),_ +(4,3),(12,3),(16,3),(20,3),(28,3),_ +(4,4),(6,4),(12,4),(14,4),(16,4),(20,4),(22,4),(28,4),(30,4),_ +(4,5),(12,5),(20,5),(28,5),_ +(4,6),(12,6),(16,6),(20,6),(22,6),(24,6),(28,6),(30,6),(32,6)} + + +For i As Integer=0 To 12 + For n As Integer=Lbound(a) To Ubound(a) + Locate _Y(a(n).y+i),_X(a(n).x+i) + If i<12 Then Print "\" Else Print "#" + Next n +Next i +locate(csrlin-1,40) +print "BASIC" +Sleep diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-4.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-4.basic new file mode 100644 index 0000000000..80fc54172e --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-4.basic @@ -0,0 +1,18 @@ +r=21:s=9:c=s +For i=1 To 11 + Read d + If d <> 0 Then + For j=1 To 31 + If (d And(2^(31-j)))>0 Then + Locate c+1,r:Print "___"; + Locate c,r+1:Print "/_ /|"; + Locate c,r+2:Print "[_]/"; + End If + c=c+3 + Next + Else + s=1:c=s + End If + r=r-2:s=s+2:c=s + Next +Data 479667712,311470336,485697536,311699712,476292608,0,1976518785,1160267905,1171157123,1160267909,1171223529 diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-5.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-5.basic new file mode 100644 index 0000000000..10ef5ca043 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-5.basic @@ -0,0 +1,25 @@ +10 mode 2:defint a-z +20 locate 1,25 +30 print "Basic"; +40 ' add some kerning so the characters will fit in 80 columns: +50 off(2)=1:off(4)=-2:off(5)=-4 +60 for c=0 to 4 +70 for y=7 to 0 step -1 +80 for x=0 to 7 +90 v=test(x+8*c,2*y) +100 plot x+8*c,2*y,0 +110 if v>0 then gosub 180 +120 next x +130 next y +140 next c +150 call &bb06 ' wait for key press +160 end +170 ' print pixel +180 xp=16*c+2*x+1+y+off(c+1) +190 yp=8-y +200 if xp>77 then return +210 locate xp,yp +220 print "//\"; +230 locate xp,yp+1 +240 print "\\/"; +250 return diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic new file mode 100644 index 0000000000..ec0c10912b --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic @@ -0,0 +1,48 @@ +10 LET s$="BASIC": REM our language name +20 DIM b(5,5):REM our bigmap characters +30 FOR l = 1 TO 5: REM 5 characters +40 FOR m = 1 TO 5: REM 5 rows +50 READ b(l,m) +60 NEXT m +70 NEXT l + +100 PAPER 0: REM black background +110 INK 2: REM our shadow will be red +120 CLS +130 LET r=9: REM shadow will start on row 5 +140 LET c=2: REM shadow will start at column 2 +150 GO SUB 2000: REM draw shadow +160 INK 6: REM our forground will be yellow +170 LET r=10: REM foreground will start on row 6 +180 LET c=3: REM foreground will start on column 3 +190 GO SUB 2000: REM display the language name + +999 STOP + +1000 REM convert to binary bigmap +1010 LET t=n: REM temporary variable +1020 LET g$="": REM this will contain our 5 character binary bigmap +1040 FOR z=5 TO 0 STEP -1 +1050 LET d$=" ": REM assume next digit is zero (draw a space) +1060 IF t>=(2^z) THEN LET d$=CHR$(143): LET t=t-(2^z): LET sf=1: REM 143 is a block +1070 LET g$=g$+d$ +1080 NEXT z +1090 RETURN + +2000 REM display the big letters +2010 FOR l=1 TO 5: REM our 5 rows +2020 PRINT AT r+l-1,c; +2030 FOR m=1 TO 5: REM bigmap for each character +2040 LET n=b(l,m) +2050 GO SUB 1000 +2060 PRINT g$;: REM 5 character bigmap +2070 PRINT " ";: REM space between each letter +2080 NEXT m +2090 NEXT l +2100 RETURN + +9000 DATA 30,17,30,17,30: REM B +9010 DATA 14,17,31,17,17: REM A +9020 DATA 15,16,14,1,30: REM S +9030 DATA 31,4,4,4,31: REM I +9040 DATA 14,17,16,17,14: REM C diff --git a/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii.bf b/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii.bf new file mode 100644 index 0000000000..d472e67afc --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii.bf @@ -0,0 +1,35 @@ +v THE DATA IMAGE.(totally useless after loading into stack) +>89 v Made by gamemanj +v0000122010000000000022201220000020000< For rosettacode +>9 v The 'image' is upsidedown +v2220100010002220101000101000000000000< The 3d offset isn't applied on this +>9 v and it's encoded weirdly +v1010122012001010101022201220000010000< Is that enough decoding needed +>9 v for the '3d' ascii requirement? +v2220100010001010222010101000000010000< Huh.(sees Batch) I think so. +>9 v 0:blank +v1000122012200000000022201220000010000< 1:\ +>9 v 2:- +v p000< 9:newline +>:9-v Check for 9:Newline 8:end + v_v (note that cell 0,0 isn't ever used after the first tick!) + no yes | | >" ",v + >$55+,00g1+:00p:|: -1< Newline With Spacing Encoder +^ v# $< + : + 8 check for end + no-yes + v_v + >< make the program pause for the user forever.Ik,it's stupid + + Numeric Decoder \/ + >:1-v + v_vCheck for 1 '\' + NO: "YES + 2 \ + - " + v_ >v + " " +^ - + " " +^ $,< < < (code path reuse here,all 3 end in ,$ so I merged them) diff --git a/Task/Write-language-name-in-3D-ASCII/Groovy/write-language-name-in-3d-ascii-1.groovy b/Task/Write-language-name-in-3D-ASCII/Groovy/write-language-name-in-3d-ascii-1.groovy new file mode 100644 index 0000000000..867238f83c --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Groovy/write-language-name-in-3d-ascii-1.groovy @@ -0,0 +1,8 @@ +println """\ + _|_|_| +_| _| _|_| _|_| _|_| _| _| _| _| +_| _|_| _|_| _| _| _| _| _| _| _| _| +_| _| _| _| _| _| _| _| _| _| _| + _|_|_| _| _|_| _|_| _| _|_|_| + _| + _|_|""" diff --git a/Task/Write-language-name-in-3D-ASCII/Groovy/write-language-name-in-3d-ascii-2.groovy b/Task/Write-language-name-in-3D-ASCII/Groovy/write-language-name-in-3d-ascii-2.groovy new file mode 100644 index 0000000000..8f3c376504 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Groovy/write-language-name-in-3d-ascii-2.groovy @@ -0,0 +1,7 @@ +String.metaClass.getAsAsciiArt = { + def request = "http://www.network-science.de/ascii/ascii.php?TEXT=${delegate}&x=23&y=10&FONT=block&RICH=no&FORM=left&STRE=no&WIDT=80" + def html = new URL(request).text + (html =~ '
    ([^<]+)
    ')[-1][1] +} + +println "Groovy".asAsciiArt diff --git a/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii-1.scala b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii-1.scala new file mode 100644 index 0000000000..1ad72b06c6 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii-1.scala @@ -0,0 +1,62 @@ +def ASCII3D = { + +val name = """ + * + ** ** * * * + * * * * * * * + * * * * * * * + * * *** * *** + * * * * * * * + * * * * * * * + ** ** * * *** * * + * + * + """ + +// Create Array + +def getMaxSize(s: String): (Int, Int) = { + var width = 0 + var height = 0 + + val nameArray = s.split("\n") + height = nameArray.size + nameArray foreach { i => width = (i.size max width) } + + (width, height) +} + +val size = getMaxSize(name) +var arr = Array.fill(size._2 + 1, (size._1 * 3) + (size._2 + 1))(' ') + +// +// Map astrisk to 3D cube +// +val cubeTop = """///\""" //" +val cubeBottom = """\\\/""" //" + +val nameArray = name.split("\n") + +for (j <- (0 until nameArray.size)) { + for (i <- (0 until nameArray(j).size)) { + if (nameArray(j)(i) == '*') { + val indent = nameArray.size - j + arr(j) = arr(j) patch ((i * 3 + indent), cubeTop, cubeTop.size) + arr(j + 1) = arr(j + 1) patch ((i * 3 + indent), cubeBottom, cubeBottom.size) + } + } +} + +// +// Map Array to String +// +var name3D = "" + +for (j <- (0 until arr.size)) { + for (i <- (0 until arr(j).size)) { name3D += arr(j)(i) } + name3D += "\n" + } + name3D + } + + println(ASCII3D) diff --git a/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii-2.scala b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii-2.scala new file mode 100644 index 0000000000..c81c671409 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii-2.scala @@ -0,0 +1,39 @@ +object Ascii3D extends App { + def ASCII3D = { + val nameArray = """ * + ** ** * * * + * * * * * * * + * * * * * * * + * * *** * *** + * * * * * * * + * * * * * * * + ** ** * * *** * * + * + *""".split("\n") + + var arr = { + val (x, y) = // Get maximal format and create a 2-D array with it. + (nameArray.foldLeft(0)((i, s) => i max s.length), nameArray.size) + Array.fill(y + 1, (x * 3) + (y + 1))(' ') + } + + // + // Map asterisks to 3D cube + // + val (cubeTop, cubeBottom) = ("""///\""", """\\\/""") // " + + for { + y <- 0 until nameArray.size + x <- 0 until nameArray(y).size + if nameArray(y)(x) == '*' + indent = nameArray.size - y + } { + arr(y) = arr(y) patch ((x * 3 + indent), cubeTop, cubeTop.size) + arr(y + 1) = arr(y + 1) patch ((x * 3 + indent), cubeBottom, cubeBottom.size) + } + // Transform array to String + arr.map(_.mkString).mkString("\n") + } + + println(ASCII3D) +} diff --git a/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii.scala b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii.scala deleted file mode 100644 index 81ea8be9a8..0000000000 --- a/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii.scala +++ /dev/null @@ -1,76 +0,0 @@ -def ASCII3D = { - - val name = """ - * - ** ** * * * - * * * * * * * - * * * * * * * - * * *** * *** - * * * * * * * - * * * * * * * - ** ** * * *** * * - * - * - """ - - - // - // Create Array - // - - def getMaxSize( s:String ) : (Int,Int) = { - - var width = 0 - var height = 0 - - val nameArray = s.split("\n") - - height = nameArray.size - nameArray foreach {i => width = (i.size max width)} - - (width,height) - } - - val size = getMaxSize( name ) - - var arr = Array.fill( size._2+1, (size._1*3)+(size._2+1) )( ' ' ) - - - // - // Map astrisk to 3D cube - // - val cubeTop = """///\""" - val cubeBottom = """\\\/""" - - val nameArray = name.split("\n") - - for( j <- (0 until nameArray.size) ) { - - for( i <- (0 until nameArray(j).size) ) { - - if( nameArray(j)(i) == '*' ) - { - val indent = nameArray.size - j - - arr(j ) = arr(j ) patch ((i*3 + indent), cubeTop, cubeTop.size) - arr(j+1) = arr(j+1) patch ((i*3 + indent), cubeBottom, cubeBottom.size) - } - } - } - - // - // Map Array to String - // - var name3D = "" - - for( j <- (0 until arr.size) ) { - - for( i <- (0 until arr(j).size) ) { name3D += arr(j)(i) } - - name3D += "\n" - } - - name3D -} - -println(ASCII3D) diff --git a/Task/Write-language-name-in-3D-ASCII/Seed7/write-language-name-in-3d-ascii.seed7 b/Task/Write-language-name-in-3D-ASCII/Seed7/write-language-name-in-3d-ascii.seed7 new file mode 100644 index 0000000000..b84d823ce2 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Seed7/write-language-name-in-3d-ascii.seed7 @@ -0,0 +1,42 @@ +$include "seed7_05.s7i"; + +const array string: name is [] ( + " *** * ***** ", + "* * * ", + "* *** *** **** * ", + "* * * * * * * * ", + " *** * * * * * * * ", + " * ***** ***** * * * ", + " * * * * * * ", + " * * * * * * ", + " *** *** *** **** * "); + +const proc: main is func + local + var integer: index is 0; + var string: help is ""; + var string: line is ""; + var string: previousLine is ""; + var integer: pos is 0; + begin + for index range 1 to length(name) do + help := replace(name[index], " ", " "); + line := "" lpad length(name) - index <& + replace(replace(help, "*", "///"), "/ ", "/\\"); + if previousLine = "" then + writeln(line); + else + for pos range 1 to length(line) do + if line[pos] <> ' ' then + write(line[pos]); + else + write(previousLine[pos]); + end if; + end for; + writeln; + end if; + previousLine := "" lpad length(name) - index <& + replace(replace(help, "*", "\\\\\\"), "\\ ", "\\/"); + end for; + writeln(previousLine); + end func; diff --git a/Task/XML-Input/Erlang/xml-input.erl b/Task/XML-Input/Erlang/xml-input.erl new file mode 100644 index 0000000000..d0972f328b --- /dev/null +++ b/Task/XML-Input/Erlang/xml-input.erl @@ -0,0 +1,22 @@ +-module( xml_input ). + +-export( [task/0] ). + +-include_lib("xmerl/include/xmerl.hrl"). + +task() -> + {XML, []} = xmerl_scan:string( xml(), [{encoding, "iso-10646-utf-1"}] ), + Attributes = lists:flatten( [X || #xmlElement{name='Student', attributes=X} <- XML#xmlElement.content] ), + [io:fwrite("~s~n", [X]) || #xmlAttribute{name='Name', value=X} <- Attributes]. + + + +xml() -> " + + + + + + + +". diff --git a/Task/XML-Input/TUSCRIPT/xml-input.tu b/Task/XML-Input/TUSCRIPT/xml-input.tu index 3131508188..5819db109c 100644 --- a/Task/XML-Input/TUSCRIPT/xml-input.tu +++ b/Task/XML-Input/TUSCRIPT/xml-input.tu @@ -14,9 +14,8 @@ $$ MODE TUSCRIPT COMPILE LOOP x = xmldata SET name=GET_TAG_NAME (x) -IF (name=="student") THEN -SET studentname=GET_ATTRIBUTE (x,"Name") -IF (studentname!="") PRINT studentname -ENDIF +IF (name!="student") CYCLE + studentname=GET_ATTRIBUTE (x,"Name") + IF (studentname!="") PRINT studentname ENDLOOP ENDCOMPILE diff --git a/Task/XML-Output/Erlang/xml-output.erl b/Task/XML-Output/Erlang/xml-output.erl new file mode 100644 index 0000000000..44ade1afcb --- /dev/null +++ b/Task/XML-Output/Erlang/xml-output.erl @@ -0,0 +1,12 @@ +-module( xml_output ). + +-export( [task/0] ). + +-include_lib("xmerl/include/xmerl.hrl"). + +task() -> + Data = {'CharacterRemarks', [], [{'Character', [{name, X}], [[Y]]} || {X, Y} <- contents()]}, + lists:flatten( xmerl:export_simple([Data], xmerl_xml) ). + + +contents() -> [{"April", "Bubbly: I'm > Tam and <= Emily"}, {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""}, {"Emily", "Short & shrift"}]. diff --git a/Task/XML-XPath/Go/xml-xpath.go b/Task/XML-XPath/Go/xml-xpath.go new file mode 100644 index 0000000000..e3d97292c1 --- /dev/null +++ b/Task/XML-XPath/Go/xml-xpath.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "os" + + "launchpad.net/xmlpath" +) + +func main() { + f, err := os.Open("test3.xml") + if err != nil { + fmt.Println(err) + return + } + n, err := xmlpath.Parse(f) + f.Close() + if err != nil { + fmt.Println(err) + return + } + q1 := xmlpath.MustCompile("//item") + if _, ok := q1.String(n); !ok { + fmt.Println("no item") + } + q2 := xmlpath.MustCompile("//price") + for it := q2.Iter(n); it.Next(); { + fmt.Println(it.Node()) + } + q3 := xmlpath.MustCompile("//name") + names := []*xmlpath.Node{} + for it := q3.Iter(n); it.Next(); { + names = append(names, it.Node()) + } + if len(names) == 0 { + fmt.Println("no names") + } +} diff --git a/Task/Xiaolin-Wus-line-algorithm/Perl/xiaolin-wus-line-algorithm.pl b/Task/Xiaolin-Wus-line-algorithm/Perl/xiaolin-wus-line-algorithm.pl new file mode 100644 index 0000000000..0b5400d667 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Perl/xiaolin-wus-line-algorithm.pl @@ -0,0 +1,78 @@ +#!perl +use strict; +use warnings; + +sub plot { + my ($x, $y, $c) = @_; + printf "plot %d %d %.1f\n", $x, $y, $c if $c; +} + +sub ipart { + int shift; +} + +sub round { + int( 0.5 + shift ); +} + +sub fpart { + my $x = shift; + $x - int $x; +} + +sub rfpart { + 1 - fpart(shift); +} + +sub drawLine { + my ($x0, $y0, $x1, $y1) = @_; + + my $plot = \&plot; + + if( abs($y1 - $y0) > abs($x1 - $x0) ) { + $plot = sub { plot( @_[1, 0, 2] ) }; + ($x0, $y0, $x1, $y1) = ($y0, $x0, $y1, $x1); + } + + if( $x0 > $x1 ) { + ($x0, $x1, $y0, $y1) = ($x1, $x0, $y1, $y0); + } + + my $dx = $x1 - $x0; + my $dy = $y1 - $y0; + my $gradient = $dy / $dx; + + my @xends; + my $intery; + + # handle the endpoints + for my $xy ([$x0, $y0], [$x1, $y1]) { + my ($x, $y) = @$xy; + my $xend = round($x); + my $yend = $y + $gradient * ($xend - $x); + my $xgap = rfpart($x + 0.5); + + my $x_pixel = $xend; + my $y_pixel = ipart($yend); + push @xends, $x_pixel; + + $plot->($x_pixel, $y_pixel , rfpart($yend) * $xgap); + $plot->($x_pixel, $y_pixel+1, fpart($yend) * $xgap); + next if defined $intery; + # first y-intersection for the main loop + $intery = $yend + $gradient; + } + + # main loop + + for my $x ( $xends[0] + 1 .. $xends[1] - 1 ) { + $plot->($x, ipart ($intery), rfpart($intery)); + $plot->($x, ipart ($intery)+1, fpart($intery)); + $intery += $gradient; + } +} + +if( $0 eq __FILE__ ) { + drawLine( 0, 1, 10, 2 ); +} +__END__ diff --git a/Task/Y-combinator/D/y-combinator.d b/Task/Y-combinator/D/y-combinator.d index 54a47fe6b5..1c591fcdf3 100644 --- a/Task/Y-combinator/D/y-combinator.d +++ b/Task/Y-combinator/D/y-combinator.d @@ -1,31 +1,25 @@ import std.stdio, std.traits, std.algorithm, std.range; -auto Y(F)(F f) { - alias D = void delegate(); - alias Ret = ReturnType!(ParameterTypeTuple!F); - alias Args = ParameterTypeTuple!(ParameterTypeTuple!F); - - return ((Ret delegate(Args) delegate(D) x) => - x(cast(D)x))( - (D y) => - f((Args args) => - (cast(Ret delegate(Args))(cast(D delegate(D))y)(y))(args) - ) - ); +auto Y(S, T...)(S delegate(T) delegate(S delegate(T)) f) { + static struct F { + S delegate(T) delegate(F) f; + alias f this; + } + return (x => x(x))(F(x => f((T v) => x(x)(v)))); } -void main() { // Demo code -------------------- - auto factorial = Y((int delegate(int) self) => - (int n) => 0 == n ? 1 : n * self(n - 1) - ); +void main() { // Demo code: + auto factorial = Y((int delegate(int) self) => + (int n) => 0 == n ? 1 : n * self(n - 1) + ); - auto ackermann = Y((ulong delegate(ulong, ulong) self) => - (ulong m, ulong n) { - if (m == 0) return n + 1; - if (n == 0) return self(m - 1, 1); - return self(m - 1, self(m, n - 1)); + auto ackermann = Y((ulong delegate(ulong, ulong) self) => + (ulong m, ulong n) { + if (m == 0) return n + 1; + if (n == 0) return self(m - 1, 1); + return self(m - 1, self(m, n - 1)); }); - writeln("factorial: ", 10.iota.map!factorial); - writeln("ackermann(3, 5): ", ackermann(3, 5)); + writeln("factorial: ", 10.iota.map!factorial); + writeln("ackermann(3, 5): ", ackermann(3, 5)); } diff --git a/Task/Y-combinator/Deja-Vu/y-combinator.djv b/Task/Y-combinator/Deja-Vu/y-combinator.djv index f981f2aa03..5280feeb73 100644 --- a/Task/Y-combinator/Deja-Vu/y-combinator.djv +++ b/Task/Y-combinator/Deja-Vu/y-combinator.djv @@ -23,5 +23,5 @@ labda f: 1 set :fib Y -. fac 6 -. fib 6 +!. fac 6 +!. fib 6 diff --git a/Task/Y-combinator/Ruby/y-combinator-1.rb b/Task/Y-combinator/Ruby/y-combinator-1.rb index bb5b22e3e1..6726c7249c 100644 --- a/Task/Y-combinator/Ruby/y-combinator-1.rb +++ b/Task/Y-combinator/Ruby/y-combinator-1.rb @@ -1,14 +1,11 @@ -irb(main):001:0> Y = lambda do |f| -irb(main):002:1* lambda {|g| g[g]}[lambda do |g| -irb(main):003:3* f[lambda {|*args| g[g][*args]}] -irb(main):004:3> end] -irb(main):005:1> end -=> # -irb(main):006:0> Fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} -=> # -irb(main):007:0> Array.new(10) {|i| Y[Fac][i]} -=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] -irb(main):008:0> Fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} -=> # -irb(main):009:0> Array.new(10) {|i| Y[Fib][i]} -=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] +y = lambda do |f| + lambda {|g| g[g]}[lambda do |g| + f[lambda {|*args| g[g][*args]}] + end] +end + +fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} +p Array.new(10) {|i| y[fac][i]} #=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] + +fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} +p Array.new(10) {|i| y[fib][i]} #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Y-combinator/Ruby/y-combinator-2.rb b/Task/Y-combinator/Ruby/y-combinator-2.rb index 13cc62fcfd..79a7a0bfa8 100644 --- a/Task/Y-combinator/Ruby/y-combinator-2.rb +++ b/Task/Y-combinator/Ruby/y-combinator-2.rb @@ -4,10 +4,10 @@ def y(&f) end.tap {|g| break g[g]} end -Fac = y {|&f| lambda {|n| n < 2 ? 1 : n * f[n - 1]}} -Fib = y {|&f| lambda {|n| n < 2 ? n : f[n - 1] + f[n - 2]}} +fac = y {|&f| lambda {|n| n < 2 ? 1 : n * f[n - 1]}} +fib = y {|&f| lambda {|n| n < 2 ? n : f[n - 1] + f[n - 2]}} -p Array.new(10) {|i| Fac[i]} +p Array.new(10) {|i| fac[i]} # => [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] -p Array.new(10) {|i| Fib[i]} +p Array.new(10) {|i| fib[i]} # => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-1.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-1.pro new file mode 100644 index 0000000000..58bbd1c9d2 --- /dev/null +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-1.pro @@ -0,0 +1,21 @@ +select([A|As],S):- select(A,S,S1),select(As,S1). +select([],_). + +next_to(A,B,C):- left_of(A,B,C) ; left_of(B,A,C). +left_of(A,B,C):- append(_,[A,B|_],C). + +zebra(Owns, HS):- % color,nation,pet,drink,smokes + HS = [h(_,norwegian,_,_,_),_, h(_,_,_,milk,_),_,_], + select( [h(red,englishman,_,_,_),h(_,swede,dog,_,_), + h(_,dane,_,tea,_), h(_,german,_,_,prince)], HS), + select( [h(_,_,birds,_,pallmall),h(yellow,_,_,_,dunhill), + h(_,_,_,beer,bluemaster)], HS), + left_of( h(green,_,_,coffee,_), h(white,_,_,_,_), HS), + next_to( h(_,_,_,_,dunhill), h(_,_,horse,_,_), HS), + next_to( h(_,_,_,_,blend), h(_,_,cats, _,_), HS), + next_to( h(_,_,_,_,blend), h(_,_,_,water,_), HS), + next_to( h(_,norwegian,_,_,_), h(blue,_,_,_,_), HS), + member( h(_,Owns,zebra,_,_), HS). + +:- ?- time(( zebra(Who, HS), maplist(writeln,HS), nl, write(Who), nl, nl, fail + ; write('No more solutions.') )). diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro new file mode 100644 index 0000000000..1f98a6ed3d --- /dev/null +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro @@ -0,0 +1,30 @@ +% populate domain by selecting from it +nation(H,V):- memberchk( nation(X), H), X=V. % select the "nation" attribute +owns( H,V):- memberchk( owns( X), H), X=V. % ... +smoke( H,V):- memberchk( smoke( X), H), X=V. +color( H,V):- memberchk( color( X), H), X=V. +drink( H,V):- memberchk( drink( X), H), X=V. + +to_the_left(A,B,HS):- append(_,[A,B|_],HS). +next_to(A,B,HS):- to_the_left(A,B,HS) ; to_the_left(B,A,HS). +middle(A, [_,_,A,_,_]). +first(A, [A|_]). + +zebra(Zebra,Houses):- + length(Houses,5), + member(H2, Houses), nation(H2, englishman), color( H2, red), + member(H3, Houses), nation(H3, swede), owns( H3, dog), + member(H4, Houses), nation(H4, dane), drink( H4, tea), + to_the_left(H5,H5b,Houses), color(H5, green), color(H5b, white), + member(H6, Houses), drink( H6, coffee), color( H6, green), + member(H7, Houses), smoke( H7, 'Pall Mall'), owns( H7, birds), + member(H8, Houses), color( H8, yellow), smoke( H8, 'Dunhill'), + middle(H9, Houses), drink( H9, milk), + first(H10, Houses), nation(H10, norwegian), + next_to(H11,H11b,Houses), smoke( H11, 'Blend'), owns( H11b, cats), + next_to(H12,H12b,Houses), owns( H12, horse), smoke(H12b, 'Dunhill'), + member(H13, Houses), drink( H13, beer), smoke( H13, 'Blue Master'), + member(H14, Houses), nation(H14, german), smoke( H14, 'Prince'), + next_to(H15,H15b,Houses), nation(H15, norwegian), color(H15b, blue), + next_to(H16,H16b,Houses), drink( H16, water), smoke(H16b, 'Blend'), + member(Zebra,Houses), owns(Zebra, zebra). diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro new file mode 100644 index 0000000000..a89cdc3c6a --- /dev/null +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro @@ -0,0 +1,12 @@ +?- time(( zebra(Z,HS), ( maplist(length,HS,_) -> maplist(sort,HS,S), + maplist(writeln,S),nation(Z,R),nl,writeln(R) ), false ; true)). + +[color(yellow),drink(water), nation(norwegian), owns(cats), smoke(Dunhill) ] +[color(blue), drink(tea), nation(dane), owns(horse), smoke(Blend) ] +[color(red), drink(milk), nation(englishman),owns(birds), smoke(Pall Mall) ] +[color(green), drink(coffee),nation(german), owns(zebra), smoke(Prince) ] +[color(white), drink(beer), nation(swede), owns(dog), smoke(Blue Master)] + +german +% 138,899 inferences, 0.060 CPU in 0.110 seconds (55% CPU, 2311655 Lips) +true. diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle.pro deleted file mode 100644 index d593d97eaa..0000000000 --- a/Task/Zebra-puzzle/Prolog/zebra-puzzle.pro +++ /dev/null @@ -1,22 +0,0 @@ -select([A|As],S):- select(A,S,S1),select(As,S1). -select([],_). - -next_to(A,B,C):- left_of(A,B,C) ; left_of(B,A,C). -left_of(A,B,C):- append(_,[A,B|_],C). - -zebra(Owns, HS):- % color,nation,pet,drink,smokes - HS = [h(_,norwegian,_,_,_),_,h(_,_,_,milk,_),_,_], - select( [h(red,englishman,_,_,_),h(_,swede,dog,_,_),h(_,dane,_,tea,_), - h(_,german,_,_,prince)], HS), - select( [h(_,_,birds,_,pallmall),h(yellow,_,_,_,dunhill), - h(_,_,_,beer,bluemaster)], HS), - left_of( h(green,_,_,coffee,_),h(white,_,_,_,_), HS), - next_to( h(_,_,_,_,dunhill), h(_,_,horse,_,_), HS), - next_to( h(_,_,_,_,blend), h(_,_,cats, _,_), HS), - next_to( h(_,_,_,_,blend), h(_,_,_,water,_), HS), - next_to( h(_,norwegian,_,_,_), h(blue,_,_,_,_), HS), - member( h(_,Owns,zebra,_,_), HS). - -:- zebra(Who, HS), maplist(writeln,HS), nl, write(Who), nl, nl, fail - ; - write('No more solutions.'). diff --git a/Task/Zeckendorf-number-representation/Perl/zeckendorf-number-representation.pl b/Task/Zeckendorf-number-representation/Perl/zeckendorf-number-representation.pl new file mode 100644 index 0000000000..ca96f554fc --- /dev/null +++ b/Task/Zeckendorf-number-representation/Perl/zeckendorf-number-representation.pl @@ -0,0 +1,23 @@ +my @fib; + +sub fib { + my $n = shift; + return 1 if $n < 2; + return $fib[$n] //= fib($n-1)+fib($n-2); +} + +sub zeckendorf { + my $n = shift; + return "0" unless $n; + my $i = 1; + $i++ while fib($i) <= $n; + my $z = ''; + while( --$i ) { + $z .= "0", next if fib( $i ) > $n; + $z .= "1"; + $n -= fib( $i ); + } + return $z; +} + +printf "%4d: %8s\n", $_, zeckendorf($_) for 0..20; diff --git a/Task/Zeckendorf-number-representation/Ruby/zeckendorf-number-representation-1.rb b/Task/Zeckendorf-number-representation/Ruby/zeckendorf-number-representation-1.rb new file mode 100644 index 0000000000..1ee9fc1faa --- /dev/null +++ b/Task/Zeckendorf-number-representation/Ruby/zeckendorf-number-representation-1.rb @@ -0,0 +1,11 @@ +def zeckendorf + return to_enum(__method__) unless block_given? + x = 0 + loop do + bin = x.to_s(2) + yield bin unless bin.include?("11") + x += 1 + end +end + +zeckendorf.take(21).each_with_index{|x,i| puts "%3d: %8s"% [i, x]} diff --git a/Task/Zeckendorf-number-representation/Ruby/zeckendorf-number-representation-2.rb b/Task/Zeckendorf-number-representation/Ruby/zeckendorf-number-representation-2.rb new file mode 100644 index 0000000000..dbc45138be --- /dev/null +++ b/Task/Zeckendorf-number-representation/Ruby/zeckendorf-number-representation-2.rb @@ -0,0 +1,18 @@ +def zeckendorf(n) + return 0 if n.zero? + fib = [1,2] + fib << fib[-2] + fib[-1] while fib[-1] < n + dig = "" + fib.reverse_each do |f| + if f <= n + dig, n = dig + "1", n - f + else + dig += "0" + end + end + dig.to_i +end + +for i in 0..20 + puts '%3d: %8d' % [i, zeckendorf(i)] +end diff --git a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp index dafee601f6..5db0a96be4 100644 --- a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp +++ b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp @@ -16,7 +16,6 @@ auto_ptr< IntTable > getZigZagArray( int dimension ) // fill along diagonal stripes (oriented as "/") int lastValue = dimension * dimension - 1; - int currNum = 0; int currDiag = 0; int loopFrom; int loopTo; @@ -54,7 +53,7 @@ auto_ptr< IntTable > getZigZagArray( int dimension ) currDiag++; } - while ( currNum <= lastValue ); + while ( currDiag <= lastValue ); return zigZagArrayPtr; } diff --git a/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb b/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb index 50635bd620..9865f6fa39 100644 --- a/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb +++ b/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb @@ -8,8 +8,8 @@ def zigzag(n) end def print_matrix(m) - width = m.flatten.max.to_s.size - m.each {|row| row.each {|val| print "%#{width}d " % val}; puts} + format = "%#{m.flatten.max.to_s.size}d " + puts m.map {|row| row.map {|val| format % val}.join} end print_matrix zigzag(5)