= 0, @now [$coin,*@later]) {
@cache[$n][+@later] //= ways($n - $coin, @now) + ways($n, @later);
}
multi ways($,@) { 0 }
- ways($amount, @coins.sort(-*)); # sort descending
+ ways($amount, @coins.sort(-*).list); # sort descending
}
say ways-to-make-change 1_00, [1,5,10,25];
diff --git a/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6 b/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6
index 9c0ff996db..f32cc567ab 100644
--- a/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6
+++ b/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6
@@ -1,6 +1,6 @@
sub ways-to-make-change-slowly(\n, @coins) {
my @table = [1 xx @coins], [0 xx @coins] xx n;
- for 1..n X ^@coins -> \i, \j {
+ for 1..n X ^@coins -> (\i, \j) {
my \c = @coins[j];
@table[i][j] = [+]
@table[i - c][j ] // 0,
diff --git a/Task/Count-the-coins/REXX/count-the-coins-1.rexx b/Task/Count-the-coins/REXX/count-the-coins-1.rexx
index 2d33e55871..0e1bbbfe15 100644
--- a/Task/Count-the-coins/REXX/count-the-coins-1.rexx
+++ b/Task/Count-the-coins/REXX/count-the-coins-1.rexx
@@ -1,21 +1,31 @@
-/*REXX program makes change from some amount with various specie (coins)*/
-parse arg N $ /*obtain optional args from C.L. */
-if N='' then N=100 /*Not specified? Use $1 default.*/
-if $='' then $=1 5 10 25 /*Use penny/nickel/dime/quarter ?*/
-coins=words($) /*count number of coins specified*/
- do j=1 for coins /*create a fast way of accessing.*/
- $.j=word($,j) /*define a stemmed array element.*/
- end /*j*/
-
-say 'with an amount of ' N " cents, there are " kaChing(N, coins)
-say 'ways to make change with coins of the following denominations: ' $
-exit /*stick a fork in it, we're done.*/
-/*──────────────────────────────────KACHING subroutine──────────────────*/
-kaChing: procedure expose $.; parse arg a,k /*sub is recursive. */
-if a==0 then return 1 /*unroll special case*/
-if k==1 then return 1 /* " " " */
-if k==2 then f=1 /*handle special case*/
- else f=kaChing(a, k-1) /*recurse the amount.*/
-if a==$.k then return f + 1 /*handle special case*/
-if a <$.k then return f /* " " " */
- return f + kaChing(a-$.k, k) /*use diminished $. */
+/*REXX program counts the ways to make change with coins from an given amount.*/
+numeric digits 20 /*be able to handle large amounts of $.*/
+parse arg N $ /*obtain optional arguments from the CL*/
+if N='' | N=',' then N=100 /*Not specified? Then Use $1 (≡100¢).*/
+if $='' | $=',' then $=1 5 10 25 /*Use penny/nickel/dime/quarter default*/
+if left(N,1)=='$' then N=100*substr(N,2) /*amount was specified in dollars.*/
+coins=words($) /*the number of coins specified. */
+NN=N; do j=1 for coins /*create a fast way of accessing specie*/
+ _=word($,j) /*define an array element for the coin.*/
+ if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/
+ if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/
+ $.j=_ /*assign the value to a particular coin*/
+ end /*j*/
+_=n//100; cnt=' cents' /* [↓] Is amount in whole $'s*/
+if _=0 then do; NN='$'||(NN%100); cnt=; end /*show amount in dollars, ¬ ¢.*/
+say 'with an amount of ' commas(NN)cnt", there are " commas(kaChing(N,coins))
+say 'ways to make change with coins of the following denominations: ' $
+exit /*stick a fork in it, we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M")
+ e=verify(n,#'0',,verify(n,#"0.",'M'))-4
+ do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _
+/*────────────────────────────────────────────────────────────────────────────*/
+kaChing: procedure expose $.; parse arg a,k /*this function is recursive.*/
+if a==0 then return 1 /*unroll for a special case. */
+if k==1 then return 1 /* " " " " " */
+if k==2 then f=1 /*handle this special case. */
+ else f=kaChing(a, k-1) /*count, recurse the amount. */
+if a==$.k then return f + 1 /*handle this special case. */
+if a <$.k then return f /* " " " " */
+ return f + kaChing(a-$.k, k) /*use a diminished amount ($)*/
diff --git a/Task/Count-the-coins/REXX/count-the-coins-2.rexx b/Task/Count-the-coins/REXX/count-the-coins-2.rexx
index 1fc2d16141..5b79377a44 100644
--- a/Task/Count-the-coins/REXX/count-the-coins-2.rexx
+++ b/Task/Count-the-coins/REXX/count-the-coins-2.rexx
@@ -1,24 +1,32 @@
-/*REXX program makes change from some amount with various specie (coins)*/
-numeric digits 20 /*be able to handle large amounts*/
-parse arg N $ /*obtain optional args from C.L. */
-if N='' then N=100 /*Not specified? Use $1 default.*/
-if $='' then $=1 5 10 25 /*Use penny/nickel/dime/quarter ?*/
-coins=words($) /*count number of coins specified*/
-!.=. /*used for memoization for A & K.*/
- do j=1 for coins /*create a fast way of accessing.*/
- $.j=word($,j) /*define a stemmed array element.*/
- end /*j*/
-
-say 'with an amount of ' N " cents, there are " kaChing(N, coins)
-say 'ways to make change with coins of the following denominations: ' $
-exit /*stick a fork in it, we're done.*/
-/*──────────────────────────────────KACHING subroutine──────────────────*/
-kaChing: procedure expose $. !.; parse arg a,k /*sub is recursive. */
-if a==0 then return 1 /*unroll special case*/
-if k==1 then return 1 /* " " " */
-if k==2 then f=1 /*handle special case*/
- else f=kaChing(a,k-1) /*recurse the amount.*/
-if !.a.k\==. then return !.a.k /*found A & K before?*/
-if a==$.k then do; !.a.k=f+1; return f+1; end /*handle special case*/
-if a <$.k then do; !.a.k=f; return f; end /* " " " */
-!.a.k=f + kaChing(a-$.k, k); return !.a.k /*compute,set,return.*/
+/*REXX program counts the ways to make change with coins from an given amount.*/
+numeric digits 20 /*be able to handle large amounts of $.*/
+parse arg N $ /*obtain optional arguments from the CL*/
+if N='' | N=',' then N=100 /*Not specified? Then Use $1 (≡100¢).*/
+if $='' | $=',' then $=1 5 10 25 /*Use penny/nickel/dime/quarter default*/
+if left(N,1)=='$' then N=100*substr(N,2) /*amount was specified in dollars.*/
+coins=words($) /*the number of coins specified. */
+!.=.; NN=N; do j=1 for coins /*create a fast way of accessing specie*/
+ _=word($,j) /*define an array element for the coin.*/
+ if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/
+ if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/
+ $.j=_ /*assign the value to a particular coin*/
+ end /*j*/
+_=n//100; cnt=' cents' /* [↓] Is amount in whole $'s*/
+if _=0 then do; NN='$'||(NN%100); cnt=; end /*show amount in dollars, ¬ ¢.*/
+say 'with an amount of ' commas(NN)cnt", there are " commas(kaChing(N,coins))
+say 'ways to make change with coins of the following denominations: ' $
+exit /*stick a fork in it, we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M")
+ e=verify(n,#'0',,verify(n,#"0.",'M'))-4
+ do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _
+/*────────────────────────────────────────────────────────────────────────────*/
+kaChing: procedure expose $. !.; parse arg a,k /*function is recursive. */
+if !.a.k\==. then return !.a.k /*found this A & K before? */
+if a==0 then return 1 /*unroll for a special case*/
+if k==1 then return 1 /* " " " " " */
+if k==2 then f=1 /*handle this special case.*/
+ else f=kaChing(a, k-1) /*count, recurse the amount*/
+if a==$.k then do; !.a.k=f+1; return !.a.k; end /*handle this special case.*/
+if a <$.k then do; !.a.k=f ; return f ; end /* " " " " */
+!.a.k=f + kaChing(a-$.k, k) ; return !.a.k /*compute, define, return. */
diff --git a/Task/Count-the-coins/REXX/count-the-coins-3.rexx b/Task/Count-the-coins/REXX/count-the-coins-3.rexx
new file mode 100644
index 0000000000..f240ae22db
--- /dev/null
+++ b/Task/Count-the-coins/REXX/count-the-coins-3.rexx
@@ -0,0 +1,53 @@
+/*REXX program counts the ways to make change with coins from an given amount.*/
+numeric digits 20 /*be able to handle large amounts of $.*/
+parse arg N $ /*obtain optional arguments from the CL*/
+if N='' | N=',' then N='$1' /*Not specified? Then Use $1 (≡100¢).*/
+if $='' | $=',' then $=1 5 10 25 /*Use penny/nickel/dime/quarter default*/
+X=N /*save original for possible error msgs*/
+if left(N,1)=='$' then do /*the amount has a leading dollar sign.*/
+ _=substr(N,2) /*amount was specified in dollars. */
+ if \isNum(_) then call ser "amount isn't numeric: " N
+ N=100*_ /*change amount (in $) ───► cents (¢).*/
+ end
+max$=10**digits() /*the maximum amount this pgm can have.*/
+if \isNum(N) then call ser X " amount isn't numeric."
+if N=0 then call ser X " amount can't be zero."
+if N<0 then call ser X " amount can't be negative."
+if N>max$ then call ser X " amount can't be greater than " max$'.'
+coins=words($); !.=.; NN=N; p=0 /*#coins specified; coins; amount; prev*/
+@.=0 /*verify a coin was only specified once*/
+ do j=1 for coins /*create a fast way of accessing specie*/
+ _=word($,j); ?=_ ' coin' /*define an array element for the coin.*/
+ if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/
+ if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/
+ if \isNum(_) then call ser ? "coin value isn't numeric."
+ if _<0 then call ser ? "coin value can't be negative."
+ if _<=0 then call ser ? "coin value can't be zero."
+ if @._ then call ser ? "coin was already specified."
+ if _N then call ser ? "coin must be less or equal to amount:" X
+ @._=1; p=_ /*signify coin was specified; set prev.*/
+ $.j=_ /*assign the value to a particular coin*/
+ end /*j*/
+_=n//100; cnt=' cents' /* [↓] Is amount in whole $'s*/
+if _=0 then do; NN='$'||(NN%100); cnt=; end /*show amount in dollars, ¬ ¢.*/
+say 'with an amount of ' commas(NN)cnt", there are " commas(kaChing(N,coins))
+say 'ways to make change with coins of the following denominations: ' $
+exit /*stick a fork in it, we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+isNum: return datatype(arg(1), 'N') /*return 1 if arg is numeric, 0 if not.*/
+ser: say; say '***error!***'; say; say arg(1); say; exit 13 /*error msg.*/
+/*────────────────────────────────────────────────────────────────────────────*/
+commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M")
+ e=verify(n,#'0',,verify(n,#"0.",'M'))-4
+ do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _
+/*────────────────────────────────────────────────────────────────────────────*/
+kaChing: procedure expose $. !.; parse arg a,k /*function is recursive. */
+if !.a.k\==. then return !.a.k /*found this A & K before? */
+if a==0 then return 1 /*unroll for a special case*/
+if k==1 then return 1 /* " " " " " */
+if k==2 then f=1 /*handle this special case.*/
+ else f=kaChing(a, k-1) /*count, recurse the amount*/
+if a==$.k then do; !.a.k=f+1; return !.a.k; end /*handle this special case.*/
+if a <$.k then do; !.a.k=f ; return f ; end /* " " " " */
+!.a.k=f + kaChing(a-$.k, k) ; return !.a.k /*compute, define, return. */
diff --git a/Task/Count-the-coins/Scala/count-the-coins.scala b/Task/Count-the-coins/Scala/count-the-coins-1.scala
similarity index 100%
rename from Task/Count-the-coins/Scala/count-the-coins.scala
rename to Task/Count-the-coins/Scala/count-the-coins-1.scala
diff --git a/Task/Count-the-coins/Scala/count-the-coins-2.scala b/Task/Count-the-coins/Scala/count-the-coins-2.scala
new file mode 100644
index 0000000000..694ed7eb64
--- /dev/null
+++ b/Task/Count-the-coins/Scala/count-the-coins-2.scala
@@ -0,0 +1,8 @@
+def count(target: Int, coins: List[Int]): Int = {
+ if (target == 0) 1
+ else if (coins.isEmpty || target < 0) 0
+ else count(target, coins.tail) + count(target - coins.head, coins)
+}
+
+
+count(100, List(25, 10, 5, 1))
diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-1.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-1.sh
new file mode 100644
index 0000000000..e2b32aae9a
--- /dev/null
+++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-1.sh
@@ -0,0 +1,13 @@
+function count_change {
+ local -i amount=$1 coin j
+ local ways=(1)
+ shift
+ for coin; do
+ for (( j=coin; j <= amount; j++ )); do
+ let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}
+ done
+ done
+ echo "${ways[amount]}"
+}
+count_change 100 25 10 5 1
+count_change 100000 100 50 25 10 5 1
diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-2.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-2.sh
new file mode 100644
index 0000000000..e4b9892745
--- /dev/null
+++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-2.sh
@@ -0,0 +1,14 @@
+function count_change {
+ typeset -i amount=$1 coin j
+ typeset ways
+ set -A ways 1
+ shift
+ for coin; do
+ for (( j=coin; j <= amount; j++ )); do
+ let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}
+ done
+ done
+ echo "${ways[amount]}"
+}
+count_change 100 25 10 5 1
+count_change 100000 100 50 25 10 5 1
diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-3.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-3.sh
new file mode 100644
index 0000000000..3bb7e06ae4
--- /dev/null
+++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-3.sh
@@ -0,0 +1,16 @@
+function count_change {
+ typeset -i amount=$1 coin j
+ typeset ways
+ set -A ways 1
+ shift
+ for coin; do
+ let j=coin
+ while (( j <= amount )); do
+ let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}
+ let j+=1
+ done
+ done
+ echo "${ways[amount]}"
+}
+count_change 100 25 10 5 1
+# (optional task exceeds a subscript limit in ksh88)
diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-4.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-4.sh
new file mode 100644
index 0000000000..e814f9ecc9
--- /dev/null
+++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-4.sh
@@ -0,0 +1,15 @@
+if [ $# -lt 2 ]; then
+ set ${1-100} 25 10 5 1
+fi
+amount=$1
+shift
+ways_0=1
+for coin in "$@"; do
+ j=$coin
+ while [ $j -le $amount ]; do
+ d=`expr $j - $coin`
+ eval "ways_$j=\`expr \${ways_$j-0} + \${ways_$d-0}\`"
+ j=`expr $j + 1`
+ done
+done
+eval "echo \$ways_$amount"
diff --git a/Task/Count-the-coins/VBScript/count-the-coins.vb b/Task/Count-the-coins/VBScript/count-the-coins.vb
new file mode 100644
index 0000000000..409c376f09
--- /dev/null
+++ b/Task/Count-the-coins/VBScript/count-the-coins.vb
@@ -0,0 +1,20 @@
+Function count(coins,m,n)
+ ReDim table(n+1)
+ table(0) = 1
+ i = 0
+ Do While i < m
+ j = coins(i)
+ Do While j <= n
+ table(j) = table(j) + table(j - coins(i))
+ j = j + 1
+ Loop
+ i = i + 1
+ Loop
+ count = table(n)
+End Function
+
+'testing
+arr = Array(1,5,10,25)
+m = UBound(arr) + 1
+n = 100
+WScript.StdOut.WriteLine count(arr,m,n)
diff --git a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION
index b0d6478dbd..1cb379e3d7 100644
--- a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION
+++ b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION
@@ -1,3 +1,4 @@
+{{omit from|Axe}}
{{omit from|AWK|not OO}}
{{omit from|BASIC|not OO}}
{{omit from|C|not OO}}
diff --git a/Task/Create-a-file/AWK/create-a-file.awk b/Task/Create-a-file/AWK/create-a-file.awk
index 754ca46545..4a3f7fdc7d 100644
--- a/Task/Create-a-file/AWK/create-a-file.awk
+++ b/Task/Create-a-file/AWK/create-a-file.awk
@@ -1,5 +1,8 @@
BEGIN {
printf "" > "output.txt"
- # try to create the file in the root (for *nix-like systems)
+ close("output.txt")
printf "" > "/output.txt"
+ close("/output.txt")
+ system("mkdir docs")
+ system("mkdir /docs")
}
diff --git a/Task/Create-a-file/Julia/create-a-file.julia b/Task/Create-a-file/Julia/create-a-file.julia
new file mode 100644
index 0000000000..9448f4efc1
--- /dev/null
+++ b/Task/Create-a-file/Julia/create-a-file.julia
@@ -0,0 +1,12 @@
+# many I/O functions have UNIX names
+
+touch("output.txt")
+mkdir("docs")
+
+# probably don't have permission
+try
+ touch("/output.txt")
+ mkdir("/docs")
+catch e
+ warn(e)
+end
diff --git a/Task/Create-a-file/VBScript/create-a-file.vb b/Task/Create-a-file/VBScript/create-a-file.vb
new file mode 100644
index 0000000000..3dca9a5df6
--- /dev/null
+++ b/Task/Create-a-file/VBScript/create-a-file.vb
@@ -0,0 +1,9 @@
+Set objFSO = CreateObject("Scripting.FileSystemObject")
+
+'current directory
+objFSO.CreateFolder(".\docs")
+objFSO.CreateTextFile(".\docs\output.txt")
+
+'root directory
+objFSO.CreateFolder("\docs")
+objFSO.CreateTextFile("\docs\output.txt")
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W/create-a-two-dimensional-array-at-runtime.alg b/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W/create-a-two-dimensional-array-at-runtime.alg
new file mode 100644
index 0000000000..17a50b7f20
--- /dev/null
+++ b/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W/create-a-two-dimensional-array-at-runtime.alg
@@ -0,0 +1,22 @@
+begin
+ integer dimension1UpperBound, dimension2UpperBound;
+ write( "upper bound for dimension 1: " );
+ read( dimension1UpperBound );
+ write( "upper bound for dimension 2: " );
+ read( dimension2UpperBound );
+
+ begin
+ % we start a new block because declarations must precede statements %
+ % and variables in array bounds must be from outside the block %
+ integer array matrix ( 1 :: dimension1UpperBound
+ , 1 :: dimension2UpperBound
+ );
+ % set the first element - the program will crash if the user input %
+ % upper bounds less than 1 %
+ matrix( 1, 1 ) := 3;
+ % write it %
+ write( matrix( 1, 1 ) );
+ % the array is automatically deleted when the block ends %
+ end
+
+end.
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC/create-a-two-dimensional-array-at-runtime.applesoft b/Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC/create-a-two-dimensional-array-at-runtime.applesoft
new file mode 100644
index 0000000000..cec3313822
--- /dev/null
+++ b/Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC/create-a-two-dimensional-array-at-runtime.applesoft
@@ -0,0 +1,7 @@
+10 INPUT "ENTER TWO INTEGERS:"; X%, Y%
+20 DIM A%(X% - 1, Y% - 1)
+30 X% = RND(1) * X%
+40 Y% = RND(1) * Y%
+50 A%(X%, Y%) = -32767
+60 PRINT A%(X%, Y%)
+70 CLEAR
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic
new file mode 100644
index 0000000000..58d8c59637
--- /dev/null
+++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic
@@ -0,0 +1,6 @@
+ CLS
+ INPUT a, b 'inputs need to be separated by commas
+ DIM array (1 TO a, 1 TO b)
+ array(1,1) = 42
+ PRINT array(1,1)
+ ERASE array
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js b/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js
index 1ef50ac024..ee349f1226 100644
--- a/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js
+++ b/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js
@@ -1,28 +1,17 @@
-var w = parseInt( get_input("Enter a width:") );
-var w = parseInt( get_input("Enter a height:") );
+var width = Number(prompt("Enter width: "));
+var height = Number(prompt("Enter height: "));
-// create the 2-D array
-var a = new Array(h);
-for (var i = 0; i < h; i++)
- a[i] = new Array(w);
+//make 2D array
+var arr = new Array(height);
-a[0][0] = 'foo';
-WScript.Echo('a[0][0] = ' + a[0][0]);
+for (var i = 0; i < h; i++) {
+ arr[i] = new Array(width);
+}
-a = null;
+//set value of element
+a[0][0] = 'foo';
+//print value of element
+console.log('arr[0][0] = ' + arr[0][0]);
-function get_input(prompt) {
- output(prompt);
- try {
- return WScript.StdIn.readLine();
- } catch(e) {
- return readline();
- }
-}
-function output(prompt) {
- try {
- return WScript.echo(prompt);
- } catch(e) {
- return print(prompt);
- }
-}
+//cleanup array
+arr = void(0);
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia b/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia
new file mode 100644
index 0000000000..9a12897b97
--- /dev/null
+++ b/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia
@@ -0,0 +1,38 @@
+julia> "Inspired by Python's `input` function."
+ function input(prompt::AbstractString="")
+ print(prompt)
+ chomp(readline())
+ end
+input (generic function with 2 methods)
+
+julia> n = parse(Int, input("Upper bound for dimension 1: ")) # parse as `Int`
+Upper bound for dimension 1: 5
+5
+
+julia> m = parse(Int, input("Upper bound for dimension 2: "))
+Upper bound for dimension 2: 5
+5
+
+julia> x = rand(n, m) # create an n·m random matrix
+5x5 Array{Float64,2}:
+ 0.80217 0.422318 0.594049 0.45547 0.208822
+ 0.0533981 0.304858 0.0276755 0.797732 0.828796
+ 0.522506 0.563856 0.216759 0.865961 0.034306
+ 0.792363 0.815744 0.868697 0.42509 0.588946
+ 0.112034 0.539611 0.674581 0.508299 0.939373
+
+julia> x[3, 3] # overloads `getindex` generic function
+0.21675944652281487
+
+julia> x[3, 3] = 5 # overloads `setindex!` generic function
+5
+
+julia> x::Matirx # `Matrix{T}` is an alias for `Array{T, 2}`
+5x5 Array{Float64,2}:
+ 0.80217 0.422318 0.594049 0.45547 0.208822
+ 0.0533981 0.304858 0.0276755 0.797732 0.828796
+ 0.522506 0.563856 5.0 0.865961 0.034306
+ 0.792363 0.815744 0.868697 0.42509 0.588946
+ 0.112034 0.539611 0.674581 0.508299 0.939373
+
+julia> x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6 b/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6
index 51bd3eac13..90f2bcf9a6 100644
--- a/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6
+++ b/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6
@@ -1,7 +1,7 @@
$ ./two-dee
Dimensions? 5x35
-@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
-@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
-@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
-@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
-@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
+[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
+[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
+[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
+[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
+[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]
diff --git a/Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC/create-a-two-dimensional-array-at-runtime.ti-83 b/Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC/create-a-two-dimensional-array-at-runtime.ti-83
new file mode 100644
index 0000000000..37fe624868
--- /dev/null
+++ b/Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC/create-a-two-dimensional-array-at-runtime.ti-83
@@ -0,0 +1,6 @@
+Input "ROWS? ",R
+Input "COLS? ",C
+{R,C}→dim([A])
+42→[A](1,1)
+Disp [A](1,1)
+DelVar [A]
diff --git a/Task/Create-an-HTML-table/Bracmat/create-an-html-table.bracmat b/Task/Create-an-HTML-table/Bracmat/create-an-html-table.bracmat
new file mode 100644
index 0000000000..ac96e3a6fa
--- /dev/null
+++ b/Task/Create-an-HTML-table/Bracmat/create-an-html-table.bracmat
@@ -0,0 +1,66 @@
+( ( makeTable
+ = headTexts
+ minRowNr
+ maxRowNr
+ headCells
+ cells
+ rows
+ Generator
+ Table
+ . get$"xmlio.bra" { A library that converts from Bracmat format to XML or HTML }
+ & !arg:(?headTexts.?minRowNr.?maxRowNr.?Generator)
+ & ( headCells
+ = cellText
+ . !arg:%?cellText ?arg
+ & (th.,!cellText) headCells$!arg
+ |
+ )
+ & ( cells
+ = cellText cellTexts numberGenerator
+ . !arg
+ : (%?cellText ?cellTexts.(=?numberGenerator))
+ & (td.,numberGenerator$)
+ cells$(!cellTexts.'$numberGenerator)
+ |
+ )
+ & ( rows
+ = headTexts rowNr maxRowNr Generator
+ . !arg:(?headTexts.?rowNr.?maxRowNr.?Generator)
+ & !rowNr:~>!maxRowNr
+ & ( tr
+ .
+ , (td.,!rowNr)
+ cells$(!headTexts.!Generator)
+ )
+ \n
+ rows$(!headTexts.!rowNr+1.!maxRowNr.!Generator)
+ |
+ )
+ & ( table
+ .
+ , ( thead
+ . (align.right)
+ , \n (tr.,(th.," ") headCells$!headTexts)
+ )
+ \n
+ ( tbody
+ . (align.right)
+ , \n
+ rows
+ $ (!headTexts.!minRowNr.!maxRowNr.!Generator)
+ )
+ )
+ : ?Table
+ & str$((XMLIO.convert)$!Table) { Call library function to create HTML }
+ )
+& makeTable
+ $ ( X Y Z { Column headers }
+ . 1 { Lowest row number }
+ . 4 { Highest row number }
+ . { Function that generates numbers 9, 10, ...}
+ ' ( cnt
+ . (cnt=$(new$(==8))) { This creates an object 'cnt' with scope as a local function variable that survives between calls. }
+ & !(cnt.)+1:?(cnt.)
+ )
+ )
+)
diff --git a/Task/Create-an-HTML-table/Common-Lisp/create-an-html-table.lisp b/Task/Create-an-HTML-table/Common-Lisp/create-an-html-table.lisp
new file mode 100644
index 0000000000..872785c172
--- /dev/null
+++ b/Task/Create-an-HTML-table/Common-Lisp/create-an-html-table.lisp
@@ -0,0 +1,12 @@
+(ql:quickload :closure-html)
+(use-package :closure-html)
+(serialize-lhtml
+ `(table nil
+ (tr nil ,@(mapcar (lambda (x)
+ (list 'th nil x))
+ '("" "X" "Y" "Z")))
+ ,@(loop for i from 1 to 4
+ collect `(tr nil
+ (th nil ,(format nil "~a" i))
+ ,@(loop repeat 3 collect `(td nil ,(format nil "~a" (random 10000)))))))
+ (make-string-sink))
diff --git a/Task/Create-an-HTML-table/JavaScript/create-an-html-table.js b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js
similarity index 100%
rename from Task/Create-an-HTML-table/JavaScript/create-an-html-table.js
rename to Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js
diff --git a/Task/Create-an-HTML-table/JavaScript/create-an-html-table-2.js b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-2.js
new file mode 100644
index 0000000000..a00095e387
--- /dev/null
+++ b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-2.js
@@ -0,0 +1,67 @@
+(function (lngCols, lngRows) {
+
+ //range(5, 20) --> [5..20]
+ //range('a', 'n') --> ['a'..'n']
+ function range(m, n) {
+ var blnAlpha = typeof m === 'string',
+ iFirst = blnAlpha ? m.charCodeAt(0) : m,
+ lstInt = Array.apply(
+ null,
+ Array((blnAlpha ? n.charCodeAt(0) : n) - iFirst + 1)
+ ).map(function (x, i) {
+ return iFirst + i;
+ });
+
+ return blnAlpha ? lstInt.map(
+ function (x) {
+ return String.fromCharCode(x);
+ }
+ ) : lstInt;
+ }
+
+ // Letter label for first column (last column will be 'Z')
+ var strFirstCol = String.fromCharCode('Z'.charCodeAt(0) - (lngCols - 1));
+
+ var lstData = [[''].concat(range(strFirstCol, 'Z'))].concat(
+ range(1, lngRows).map(
+ function (row) {
+ return [row].concat(
+ range(1, lngCols).map(
+ function () {
+ return Math.floor(
+ Math.random() * 9999
+ );
+ }
+ )
+ );
+ }
+ )
+ );
+
+ return [
+ '
',
+
+ ' ',
+ ' ' + lstData[0].reduce(
+ function (a, s) {
+ return a + '' + s + ' | ';
+ }, ''
+ ) + '
',
+ ' ',
+
+ ' ',
+ lstData.slice(1).map(
+ function (row) {
+ return ' ' + row.reduce(
+ function (a, s) {
+ return a + '' + s + ' | ';
+ }, ''
+ ) + '
';
+ }
+ ).join('\n'),
+ ' ',
+
+ '
'
+ ].join('\n');
+
+})(3, 4); // (3 columns --> [X..Z]), (4 rows --> [1..4])
diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh
index 038d7dc99d..d440a0c603 100644
--- a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh
+++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh
@@ -2,6 +2,9 @@
ConvertTo-Html -inputobject (Get-Date)
# Create a PowerShell object using a HashTable
-$object = New-Object -TypeName PSObject -Property (@{'A'=(Get-Random -Minimum 0 -Maximum 10);'B'=(Get-Random -Minimum 0 -Maximum 10);'C'=(Get-Random -Minimum 0 -Maximum 10)})
+$object = [PSCustomObject]@{
+ 'A'=(Get-Random -Minimum 0 -Maximum 10);
+ 'B'=(Get-Random -Minimum 0 -Maximum 10);
+ 'C'=(Get-Random -Minimum 0 -Maximum 10)}
$object | ConvertTo-Html
diff --git a/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx b/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx
index dea32ed52d..a24d204293 100644
--- a/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx
+++ b/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx
@@ -1,23 +1,23 @@
-/*REXX program to create an HTML table of five rows and three columns.*/
-arg rows .; if rows=='' then rows=5 /*no ROWS specified? Use default*/
- cols = 3 /*specify three columns for table*/
- maxRand = 9999 /*4-digit numbers, allow negative*/
-headerInfo = 'X Y Z' /*column header information. */
- oFID = 'a_table.html' /*name of the output file. */
- w = 0 /*number of writes to output file*/
+/*REXX program creates an HTML table of five rows and three columns. */
+arg rows .; if rows=='' then rows=5 /*no ROWS specified? Then use default.*/
+ cols = 3 /*specify three columns for the table. */
+ maxRand = 9999 /*4-digit numbers, allows negative nums*/
+headerInfo = 'X Y Z' /*specifify column header information. */
+ oFID = 'a_table.html' /*name of the output file. */
+ w = 0 /*number of writes to the output file. */
call wrt ""
call wrt ""
call wrt ""
call wrt ""
- do r=0 to rows /* [↓] handle row zero special. */
+ do r=0 to rows /* [↓] handle row 0 as being special.*/
if r==0 then call wrt " | "
- else call wrt "
---|
" r " | "
+ else call wrt "
---|
" r " | "
- do c=1 for cols /* [↓] for row zero, add hdrInfo*/
- if r==0 then call wrt "" word(headerInfo,c) " | "
- else call wrt "" rnd() " | "
+ do c=1 for cols /* [↓] for row 0, add the header info*/
+ if r==0 then call wrt "" word(headerInfo,c) " | "
+ else call wrt "" rnd() " | "
end /*c*/
end /*r*/
@@ -25,8 +25,7 @@ call wrt "
---|
"
call wrt ""
call wrt ""
say; say w ' records were written to the output file: ' oFID
-exit /*stick a fork in it, we're done.*/
-/*──────────────────────────────────one-liner subroutines───────────────*/
-rnd: return right(random(0,maxRand*2)-maxRand,5) /*REXX doesn't gen negs*/
-wrt: call lineout oFID,arg(1); say '══►' arg(1); w=w+1; return /*write.*/
- /* [↑] functions were subroutinized for better viewabilityness.*/
+exit /*stick a fork in it, we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+rnd: return right(random(0,maxRand*2)-maxRand,5) /*REXX doesn't gen neg RANDs.*/
+wrt: call lineout oFID,arg(1); say '══►' arg(1); w=w+1; return /*write.*/
diff --git a/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb
new file mode 100644
index 0000000000..35deed3f02
--- /dev/null
+++ b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb
@@ -0,0 +1,40 @@
+Set objFSO = CreateObject("Scripting.FileSystemObject")
+
+'Open the input csv file for reading. The file is in the same folder as the script.
+Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
+ "\in.csv",1)
+
+'Create the output html file.
+Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
+ "\out.html",2,True)
+
+'Write the html opening tags.
+objOutHTML.Write "" & vbCrLf
+
+'Declare table properties.
+objOutHTML.Write "" & vbCrLf
+
+'Write column headers.
+objOutHTML.Write " | X | Y | Z |
" & vbCrLf
+
+'Go through each line of the input csv file and write to the html output file.
+n = 1
+Do Until objInFile.AtEndOfStream
+ line = objInFile.ReadLine
+ If Len(line) > 0 Then
+ token = Split(line,",")
+ objOutHTML.Write "" & n & " | "
+ For i = 0 To UBound(token)
+ objOutHTML.Write "" & token(i) & " | "
+ Next
+ objOutHTML.Write "
" & vbCrLf
+ End If
+ n = n + 1
+Loop
+
+'Write the html closing tags.
+objOutHTML.Write "
"
+
+objInFile.Close
+objOutHTML.Close
+Set objFSO = Nothing
diff --git a/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c b/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c
index 5c5531feca..80e05041ab 100644
--- a/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c
+++ b/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c
@@ -1,15 +1,17 @@
+#include
+#include
+
// This is a port variable located at address 0x100
#define PORT_A (*(volatile uint32_t*)0x100)
-void main()
+int main()
{
uint32_t dat;
+ size_t addr;
PORT_A ^= 0x01; // Toggle bit 0 of PORT_A
dat = PORT_A; // Read PORT_A
addr = &PORT_A; // addr = 0x100
- while (1)
- {
- }
+ return 0;
}
diff --git a/Task/Currying/Clojure/currying.clj b/Task/Currying/Clojure/currying.clj
new file mode 100644
index 0000000000..c163ca9463
--- /dev/null
+++ b/Task/Currying/Clojure/currying.clj
@@ -0,0 +1,4 @@
+(def plus-a-hundred (partial + 100))
+(assert (=
+ (plus-a-hundred 1)
+ 101))
diff --git a/Task/Currying/JavaScript/currying.js b/Task/Currying/JavaScript/currying-1.js
similarity index 100%
rename from Task/Currying/JavaScript/currying.js
rename to Task/Currying/JavaScript/currying-1.js
diff --git a/Task/Currying/JavaScript/currying-2.js b/Task/Currying/JavaScript/currying-2.js
new file mode 100644
index 0000000000..ad04ebfba7
--- /dev/null
+++ b/Task/Currying/JavaScript/currying-2.js
@@ -0,0 +1 @@
+(a,b) => expr_using_a_and_b
diff --git a/Task/Currying/JavaScript/currying-3.js b/Task/Currying/JavaScript/currying-3.js
new file mode 100644
index 0000000000..9fc60dfb57
--- /dev/null
+++ b/Task/Currying/JavaScript/currying-3.js
@@ -0,0 +1 @@
+a => b => expr_using_a_and_b
diff --git a/Task/Currying/JavaScript/currying-4.js b/Task/Currying/JavaScript/currying-4.js
new file mode 100644
index 0000000000..c1058a8a69
--- /dev/null
+++ b/Task/Currying/JavaScript/currying-4.js
@@ -0,0 +1,23 @@
+let
+ fix = // This is a variant of the Applicative order Y combinator
+ f => (f => f(f))(g => f((...a) => g(g)(...a))),
+ curry =
+ f => (
+ fix(
+ z => (n,...a) => (
+ n>0
+ ?b => z(n-1,...a,b)
+ :f(...a)))
+ (f.length)),
+ curryrest =
+ f => (
+ fix(
+ z => (n,...a) => (
+ n>0
+ ?b => z(n-1,...a,b)
+ :(...b) => f(...a,...b)))
+ (f.length)),
+ curriedmax=curry(Math.max),
+ curryrestedmax=curryrest(Math.max);
+print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2));
+// 8,8,9
diff --git a/Task/Currying/Logtalk/currying.logtalk b/Task/Currying/Logtalk/currying.logtalk
new file mode 100644
index 0000000000..37ec3b753e
--- /dev/null
+++ b/Task/Currying/Logtalk/currying.logtalk
@@ -0,0 +1,3 @@
+| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T).
+T = 625
+yes
diff --git a/Task/Currying/Scala/currying.scala b/Task/Currying/Scala/currying.scala
new file mode 100644
index 0000000000..2ca6dbe51a
--- /dev/null
+++ b/Task/Currying/Scala/currying.scala
@@ -0,0 +1,3 @@
+def add(a: Int)(b: Int) = a + b
+val add5 = add(5) _
+add5(2)
diff --git a/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-1.e b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-1.e
new file mode 100644
index 0000000000..1802a1b9b5
--- /dev/null
+++ b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-1.e
@@ -0,0 +1,36 @@
+class
+ APPLICATION
+
+create
+ make
+
+feature {NONE} -- Initialization
+
+ make
+ -- Finds solution for cut a rectangle up to 10 x 10.
+ local
+ i, j, n: Integer
+ r: GRID
+ do
+ n := 10
+ from
+ i := 1
+ until
+ i > n
+ loop
+ from
+ j := 1
+ until
+ j > i
+ loop
+ if i.bit_and (1) /= 1 or j.bit_and (1) /= 1 then
+ create r.make (i, j)
+ r.print_solution
+ end
+ j := j + 1
+ end
+ i := i + 1
+ end
+ end
+
+end
diff --git a/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-2.e b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-2.e
new file mode 100644
index 0000000000..035fe0d7f0
--- /dev/null
+++ b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-2.e
@@ -0,0 +1,163 @@
+class
+ GRID
+
+create
+ make
+
+feature {NONE}
+
+ n: INTEGER
+
+ m: INTEGER
+
+feature
+
+ print_solution
+ -- Prints solution to cut a rectangle.
+ do
+ calculate_possibilities
+ io.put_string ("Rectangle " + n.out + " x " + m.out + ": " + count.out + " possibilities%N")
+ end
+
+ count: INTEGER
+ -- Number of solutions
+
+ make (a_n: INTEGER; a_m: INTEGER)
+ -- Initialize Problem with 'a_n' and 'a_m'.
+ require
+ a_n > 0
+ a_m > 0
+ do
+ n := a_n
+ m := a_m
+ count := 0
+ end
+
+ calculate_possibilities
+ -- Select all possible starting points.
+ local
+ i: INTEGER
+ do
+ if (n = 1 or m = 1) then
+ count := 1
+ end
+
+ from
+ i := 0
+ until
+ i > n or (n = 1 or m = 1)
+ loop
+ solve (create {POINT}.make_with_values (i, 0), create {POINT}.make_with_values (n - i, m), create {LINKED_LIST [POINT]}.make, create {LINKED_LIST [POINT]}.make)
+ i := i + 1
+ variant
+ n - i + 1
+ end
+ from
+ i := 0
+ until
+ i > m or (n = 1 or m = 1)
+ loop
+ solve (create {POINT}.make_with_values (n, i), create {POINT}.make_with_values (0, m - i), create {LINKED_LIST [POINT]}.make, create {LINKED_LIST [POINT]}.make)
+ i := i + 1
+ variant
+ m - i + 1
+ end
+ end
+
+feature {NONE}
+
+ solve (p, q: POINT; visited_p, visited_q: LINKED_LIST [POINT])
+ -- Recursive solution of cut a rectangle.
+ local
+ possible_next: LINKED_LIST [POINT]
+ next: LINKED_LIST [POINT]
+ opposite: POINT
+ do
+ if p.negative or q.negative then
+
+ elseif p.same (q) then
+ add_solution
+ else
+ possible_next := get_possible_next (p)
+ create next.make
+ across
+ possible_next as x
+ loop
+ if x.item.x >= n or x.item.y >= m then
+ -- Next point cannot be on the border. Do nothing.
+
+ elseif x.item.same (q) then
+ add_solution
+ elseif not contains (x.item, visited_p) and not contains (x.item, visited_q) then
+ next.extend (x.item)
+ end
+ end
+
+ across
+ next as x
+ loop
+ -- Move in one direction
+ -- Calculate the opposite end of the cut by moving into the opposite direction (compared to p -> x)
+ create opposite.make_with_values (q.x - (x.item.x - p.x), q.y - (x.item.y - p.y))
+
+ visited_p.extend (p)
+ visited_q.extend (q)
+
+ solve (x.item, opposite, visited_p, visited_q)
+
+ -- Remove last point again
+ visited_p.finish
+ visited_p.remove
+
+ visited_q.finish
+ visited_q.remove
+ end
+ end
+ end
+
+ get_possible_next (p: POINT): LINKED_LIST [POINT]
+ -- Four possible next points.
+ local
+ q: POINT
+ do
+ create Result.make
+
+ --up
+ create q.make_with_values (p.x + 1, p.y)
+ if q.valid and q.x <= n and q.y <= m then
+ Result.extend (q);
+ end
+
+ --down
+ create q.make_with_values (p.x - 1, p.y)
+ if q.valid and q.x <= n and q.y <= m then
+ Result.extend (q)
+ end
+
+ --left
+ create q.make_with_values (p.x, p.y - 1)
+ if q.valid and q.x <= n and q.y <= m then
+ Result.extend (q)
+ end
+
+ --right
+ create q.make_with_values (p.x, p.y + 1)
+ if q.valid and q.x <= n and q.y <= m then
+ Result.extend (q)
+ end
+ end
+
+ add_solution
+ -- Increment count.
+ do
+ count := count + 1
+ end
+
+ contains (p: POINT; set: LINKED_LIST [POINT]): BOOLEAN
+ -- Does set contain 'p'?
+ do
+ set.compare_objects
+ Result := set.has (p)
+ end
+
+end
diff --git a/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-3.e b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-3.e
new file mode 100644
index 0000000000..782c3f5369
--- /dev/null
+++ b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-3.e
@@ -0,0 +1,47 @@
+class
+ POINT
+
+create
+ make, make_with_values
+
+
+
+feature
+
+ make_with_values (a_x: INTEGER; a_y: INTEGER)
+ -- Initialize x and y with 'a_x' and 'a_y'.
+ do
+ x := a_x
+ y := a_y
+ end
+
+ make
+ -- Initialize x and y with 0.
+ do
+ x := 0
+ y := 0
+ end
+
+ x: INTEGER
+
+ y: INTEGER
+
+ negative: BOOLEAN
+ -- Are x or y negative?
+ do
+ Result := x < 0 or y < 0
+ end
+
+ same (other: POINT): BOOLEAN
+ -- Does x and y equal 'other's x and y?
+ do
+ Result := (x = other.x) and (y = other.y)
+ end
+
+ valid: BOOLEAN
+ -- Are x and y valid points?
+ do
+ Result := (x > 0) and (y > 0)
+ end
+
+end
diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx
new file mode 100644
index 0000000000..8fe0805a50
--- /dev/null
+++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx
@@ -0,0 +1,45 @@
+/*REXX program cuts rectangles into two symmetric pieces, the rectangles are */
+/*────────────────────────────── cut along unit dimensions and may be rotated.*/
+numeric digits 20 /*be able to handle some big integers. */
+parse arg N .; if N=='' then N=10 /*N not specified? Then use default.*/
+dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*four directions*/
+
+ do y=2 to N; say /*calculate rectangles up to size NxN.*/
+ do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/
+ _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output. */
+ say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.'
+ end /*x*/
+ end /*y*/
+exit /*stick a fork in it, we're all done. */
+/*──────────────────────────────────S subroutine──────────────────────────────*/
+s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
+/*──────────────────────────────────SOLVE subroutine──────────────────────────*/
+solve: procedure expose # dir. @. h len next. w
+parse arg hh 1 h,ww 1 w,recur; @.=0 /*get args; zero rectangle coördinates.*/
+if h//2 then do; t=w; w=h; h=t; if h//2 then return 0
+ end
+if w==1 then return 1
+if w==2 then return h
+if h==2 then return w /* % is REXX's integer division. */
+cy = h%2; cx=w%2 /*cut the [XY] rectangle in half. */
+len = (h+1) * (w+1) - 1 /*extend the area of the rectangle. */
+next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction and distance.*/
+if recur then #=0
+ do x=cx+1 to w-1; t=x+cy*(w+1)
+ @.t=1; _=len-t; @._=1; call walk cy-1,x
+ end /*x*/
+#=#+1
+if h==w then #=#+# /*double the count of rectangle cuts. */
+ else if w//2==0 & recur then call solve w,h,0
+return #
+/*──────────────────────────────────WALK subroutine───────────────────────────*/
+walk: procedure expose # dir. @. h len next. w; parse arg y,x
+if y==h | x==0 | x==w | y==0 then do; #=#=2; return; end
+t=x + y*(w+1); @.t=@.t+1; _=len-t
+@._=@._+1
+ do j=0 for 4; _ = t+next.j /*try four directions.*/
+ if @._==0 then call walk y+dir.j.0, x+dir.j.1
+ end /*j*/
+@.t=@.t-1
+_=len-t; @._=@._-1
+return
diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx
new file mode 100644
index 0000000000..ae1d4f557b
--- /dev/null
+++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx
@@ -0,0 +1,55 @@
+/*REXX program cuts rectangles into two symmetric pieces, the rectangles are */
+/*────────────────────────────── cut along unit dimensions and may be rotated.*/
+numeric digits 20 /*be able to handle some big integers. */
+parse arg N .; if N=='' then N=10 /*N not specified? Then use default.*/
+dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*four directions*/
+
+ do y=2 to N; say /*calculate rectangles up to size NxN.*/
+ do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/
+ _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output. */
+ say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.'
+ end /*x*/
+ end /*y*/
+exit /*stick a fork in it, we're all done. */
+/*──────────────────────────────────S subroutine──────────────────────────────*/
+s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
+/*──────────────────────────────────SOLVE subroutine──────────────────────────*/
+solve: procedure expose # dir. @. h len next. w
+parse arg hh 1 h,ww 1 w,recur; @.=0 /*get args; zero rectangle coördinates.*/
+if h//2 then do; parse value w h w with t w h; if h//2 then return 0
+ end
+if w==1 then return 1
+if w==2 then return h
+if h==2 then return w /* % is REXX's integer division. */
+cy = h%2; cx=w%2 /*cut the [XY] rectangle in half. */
+len = (h+1) * (w+1) - 1 /*extend the area of the rectangle. */
+next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction and distance.*/
+if recur then #=0
+ do x=cx+1 to w-1; t=x+cy*(w+1)
+ @.t=1; _=len-t; @._=1; call walk cy-1,x
+ end /*x*/
+#=#+1
+if h==w then #=#+# /*double the count of rectangle cuts. */
+ else if w//2==0 & recur then call solve w,h,0
+return #
+/*──────────────────────────────────WALK subroutine───────────────────────────*/
+walk: procedure expose # dir. @. h len next. w; parse arg y,x
+if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit. */
+if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */
+if x==w then do; #=#+2; return; end /* ◄──┤ " " " */
+if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */
+t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ ordered by most likely ►───┐ */
+@._=@._+1 /* └─────────────────────────────┘ */
+ do j=0 for 4; _ = t+next.j /*try four directions.*/
+ if @._==0 then do
+ yn=y+dir.j.0; xn=x+dir.j.1
+ if yn==h then do; #=#+2; iterate; end
+ if xn==0 then do; #=#+2; iterate; end
+ if xn==w then do; #=#+2; iterate; end
+ if yn==0 then do; #=#+2; iterate; end
+ call walk yn, xn
+ end
+ end /*j*/
+@.t=@.t-1
+_=len-t; @._=@._-1
+return
diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx
deleted file mode 100644
index fbc0af8bff..0000000000
--- a/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx
+++ /dev/null
@@ -1,50 +0,0 @@
-/*REXX program cuts rectangles into two symmetric pieces, the rectangles*/
-/*──────────────────── are cut along unit dimensions and may be rotated.*/
-numeric digits 20 /*be able to handle big integers.*/
-parse arg N .; if N=='' then N=10 /*N not specified? Use default.*/
-dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*directions.*/
-
- do y=2 to N; say /*calculate rectangles up to NxN.*/
- do x=1 for y; if x//2 & y//2 then iterate /*not if both odd.*/
- _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output*/
- say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.'
- end /*x*/
- end /*y*/
-exit /*stick a fork in it, we're done.*/
-/*──────────────────────────────────S subroutine────────────────────────*/
-s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*plurals*/
-/*──────────────────────────────────SOLVE subroutine────────────────────*/
-solve: procedure expose # dir. @. h len next. w
-parse arg hh 1 h,ww 1 w,recur; @.=0 /*zero the rectangle coördinates.*/
-
-if h//2 then do; t=w; w=h; h=t
- if h//2 then return 0
- end
-if w==1 then return 1
-if w==2 then return h
-if h==2 then return w
-cy = h%2; cx=w%2 /*cut the [XY] rectangle in half.*/
-len = (h+1) * (w+1) - 1 /*extended area of the rectangle.*/
-next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction distance.*/
-if recur then #=0
- do x=cx+1 to w-1; t=x+cy*(w+1)
- @.t=1; _=len-t; @._=1; call walk cy-1,x
- end /*x*/
-#=#+1
-if h==w then #=#+# /*double count of rectangle cuts.*/
- else if w//2==0 & recur then call solve w,h,0
-return #
-/*──────────────────────────────────WALK subroutine─────────────────────*/
-walk: procedure expose # dir. @. h len next. w; parse arg y,x
-if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit.*/
-if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */
-if x==w then do; #=#+2; return; end /* ◄──┤ " " " */
-if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */
-t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ ordered by most likely►─┐*/
-@._=@._+1 /* └─────────────────────────┘*/
- do j=0 for 4; _ = t+next.j /*try 4 directions*/
- if @._==0 then call walk y+dir.j.0, x+dir.j.1
- end /*j*/
-@.t=@.t-1
-_=len-t; @._=@._-1
-return
diff --git a/Task/DNS-query/Batch-File/dns-query.bat b/Task/DNS-query/Batch-File/dns-query.bat
new file mode 100644
index 0000000000..222f30a51b
--- /dev/null
+++ b/Task/DNS-query/Batch-File/dns-query.bat
@@ -0,0 +1,21 @@
+@echo off
+setlocal enabledelayedexpansion
+
+set "Temp_File=%TMP%\NSLOOKUP_%RANDOM%.TMP"
+set "Domain=www.kame.net"
+
+echo.Domain: %Domain%
+echo.
+echo.IP Addresses:
+
+ ::The Main Processor
+nslookup %Domain% >"%Temp_File%" 2>nul
+for /f "tokens=*" %%A in (
+'findstr /B /C:"Address" "%Temp_File%" ^& findstr /B /C:" " "%Temp_File%"'
+) do (
+ set data=%%A
+ echo.!data:*s: =!|findstr /VBC:"192.168." /VBC:"127.0.0.1"
+)
+del /Q "%Temp_File%"
+echo.
+pause
diff --git a/Task/DNS-query/Common-Lisp/dns-query-4.lisp b/Task/DNS-query/Common-Lisp/dns-query-4.lisp
new file mode 100644
index 0000000000..e78130dc32
--- /dev/null
+++ b/Task/DNS-query/Common-Lisp/dns-query-4.lisp
@@ -0,0 +1,3 @@
+(socket:ipaddr-to-dotted
+ (socket:dns-query "www.rosettacode.org"))
+"104.28.10.103"
diff --git a/Task/DNS-query/J/dns-query-1.j b/Task/DNS-query/J/dns-query-1.j
new file mode 100644
index 0000000000..fae50f6e08
--- /dev/null
+++ b/Task/DNS-query/J/dns-query-1.j
@@ -0,0 +1,7 @@
+ 2!:0'dig -4 +short www.kame.net'
+orange.kame.net.
+203.178.141.194
+
+ 2!:0'dig -6 +short www.kame.net'
+|interface error
+| 2!:0'dig -6 +short www.kame.net'
diff --git a/Task/DNS-query/J/dns-query-2.j b/Task/DNS-query/J/dns-query-2.j
new file mode 100644
index 0000000000..78757db877
--- /dev/null
+++ b/Task/DNS-query/J/dns-query-2.j
@@ -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-1.rexx b/Task/DNS-query/REXX/dns-query-1.rexx
new file mode 100644
index 0000000000..23eac7b49b
--- /dev/null
+++ b/Task/DNS-query/REXX/dns-query-1.rexx
@@ -0,0 +1,17 @@
+/*REXX program displays IPv4 and IPv6 addresses for a supplied domain name.*/
+trace off /*don't show PING none─zero return code*/
+parse arg tar . /*obtain optional domain name from C.L.*/
+if tar=='' then tar='www.kame.net' /*Not specified? Then use the default.*/
+tempFID='\TEMP\DNSQUERY.$$$.' /*define temp file to store the IPv4. */
+pingOpts='-l 0 -n 1 -w 1' tar /*define options for the PING command. */
+
+ do j=4 to 6 by 2 /*handle IPv4 and IPv6 addresses. */
+ 'PING' (-j) pingOpts ">" tempFID /*restrict PING's output to a minimum. */
+ q=charin(tempFID,1,999) /*read the output file from PING cmd.*/
+ parse var q '[' IPA ']' /*parse IP address from the output. */
+ say 'IPv'j 'for domain name ' tar " is " IPA /*IPv4 or IPv6 address.*/
+ call lineout tempFID /* ◄──┬─◄ needed by some REXXes to */
+ end /*j*/ /* └─◄ force file integrity.*/
+
+'ERASE' tempFID /*clean up (delete) the temporary file.*/
+ /*stick a fork in it, we're all done. */
diff --git a/Task/DNS-query/REXX/dns-query-2.rexx b/Task/DNS-query/REXX/dns-query-2.rexx
new file mode 100644
index 0000000000..e7d685aa6c
--- /dev/null
+++ b/Task/DNS-query/REXX/dns-query-2.rexx
@@ -0,0 +1,5 @@
+irb(main):001:0> require 'socket'
+=> true
+irb(main):002:0> Addrinfo.getaddrinfo("www.kame.net", nil, nil, :DGRAM) \
+irb(main):003:0* .map! { |ai| ai.ip_address }
+=> ["203.178.141.194", "2001:200:dff:fff1:216:3eff:feb1:44d7"]
diff --git a/Task/DNS-query/REXX/dns-query.rexx b/Task/DNS-query/REXX/dns-query.rexx
deleted file mode 100644
index a656d748dc..0000000000
--- a/Task/DNS-query/REXX/dns-query.rexx
+++ /dev/null
@@ -1,16 +0,0 @@
-/*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 ··· */
- end /*j*/ /* [↑] ··· force file integrity.*/
-
-'ERASE' tmp /*clean up the temporary file. */
- /*stick a fork in it, we're done.*/
diff --git a/Task/DNS-query/Scala/dns-query.scala b/Task/DNS-query/Scala/dns-query.scala
index 60c035648b..6c0c4231a1 100644
--- a/Task/DNS-query/Scala/dns-query.scala
+++ b/Task/DNS-query/Scala/dns-query.scala
@@ -1,9 +1,8 @@
-import java.net.{InetAddress,Inet4Address,Inet6Address}
+import java.net.{Inet4Address, Inet6Address, InetAddress}
object DnsQuery extends App {
- val ipAddresses = InetAddress.getAllByName("www.kame.net");
- ipAddresses.foreach { ipAddr =>
- if (ipAddr.isInstanceOf[Inet4Address]) println("IPv4 : " + ipAddr.getHostAddress())
- else if (ipAddr.isInstanceOf[Inet6Address]) println("IPv6 : " + ipAddr.getHostAddress())
+ InetAddress.getAllByName("google.com").foreach {
+ case x: Inet4Address => println(s"IPv4 : ${x.getHostAddress}")
+ case x: Inet6Address => println(s"IPv6 : ${x.getHostAddress}")
}
}
diff --git a/Task/DNS-query/VBScript/dns-query.vb b/Task/DNS-query/VBScript/dns-query.vb
new file mode 100644
index 0000000000..2636f7ad2b
--- /dev/null
+++ b/Task/DNS-query/VBScript/dns-query.vb
@@ -0,0 +1,16 @@
+Function dns_query(url,ver)
+ Set r = New RegExp
+ r.Pattern = "Pinging.+?\[(.+?)\].+"
+ Set objshell = CreateObject("WScript.Shell")
+ Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url)
+ WScript.StdOut.WriteLine "URL: " & url
+ Do Until objexec.StdOut.AtEndOfStream
+ line = objexec.StdOut.ReadLine
+ If r.Test(line) Then
+ WScript.StdOut.WriteLine "IP Version " &_
+ ver & ": " & r.Replace(line,"$1")
+ End If
+ Loop
+End Function
+
+Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
diff --git a/Task/Date-format/00DESCRIPTION b/Task/Date-format/00DESCRIPTION
index f7caf096b9..cb7e517319 100644
--- a/Task/Date-format/00DESCRIPTION
+++ b/Task/Date-format/00DESCRIPTION
@@ -1 +1,2 @@
-{{Clarified-review}}Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007".
+ {{Clarified-review}}
+Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007".
diff --git a/Task/Date-format/CoffeeScript/date-format-1.coffee b/Task/Date-format/CoffeeScript/date-format-1.coffee
index b660f6fc13..f934d1a151 100644
--- a/Task/Date-format/CoffeeScript/date-format-1.coffee
+++ b/Task/Date-format/CoffeeScript/date-format-1.coffee
@@ -1,26 +1,13 @@
-# JS does not have extensive formatting support out of the box. This code shows
-# how you could create a date formatter object.
-DateFormatter = ->
- weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
- months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
- pad = (n) ->
- if n < 10
- "0" + n
- else
- n
+date = new Date
- brief: (date) ->
- month = 1 + date.getMonth()
- "#{date.getFullYear()}-#{pad month}-#{pad date.getDate()}"
+console.log date.toLocaleDateString 'en-GB',
+ month: '2-digit'
+ day: '2-digit'
+ year: 'numeric'
+.split('/').reverse().join '-'
- verbose: (date) ->
- weekday = weekdays[date.getDay()]
- month = months[date.getMonth()]
- day = date.getDate()
- year = date.getFullYear();
- "#{weekday}, #{month} #{day}, #{year}"
-
-formatter = DateFormatter()
-date = new Date()
-console.log formatter.brief(date)
-console.log formatter.verbose(date)
+console.log date.toLocaleDateString 'en-US',
+ weekday: 'long'
+ month: 'long'
+ day: 'numeric'
+ year: 'numeric'
diff --git a/Task/Date-format/CoffeeScript/date-format-2.coffee b/Task/Date-format/CoffeeScript/date-format-2.coffee
index f8514694b2..b660f6fc13 100644
--- a/Task/Date-format/CoffeeScript/date-format-2.coffee
+++ b/Task/Date-format/CoffeeScript/date-format-2.coffee
@@ -1,3 +1,26 @@
-> coffee date_format.coffee
-2012-01-14
-Saturday, January 14, 2012
+# JS does not have extensive formatting support out of the box. This code shows
+# how you could create a date formatter object.
+DateFormatter = ->
+ weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
+ months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
+ pad = (n) ->
+ if n < 10
+ "0" + n
+ else
+ n
+
+ brief: (date) ->
+ month = 1 + date.getMonth()
+ "#{date.getFullYear()}-#{pad month}-#{pad date.getDate()}"
+
+ verbose: (date) ->
+ weekday = weekdays[date.getDay()]
+ month = months[date.getMonth()]
+ day = date.getDate()
+ year = date.getFullYear();
+ "#{weekday}, #{month} #{day}, #{year}"
+
+formatter = DateFormatter()
+date = new Date()
+console.log formatter.brief(date)
+console.log formatter.verbose(date)
diff --git a/Task/Date-format/Elixir/date-format.elixir b/Task/Date-format/Elixir/date-format.elixir
new file mode 100644
index 0000000000..6c5856b397
--- /dev/null
+++ b/Task/Date-format/Elixir/date-format.elixir
@@ -0,0 +1,25 @@
+defmodule Date do
+ def iso_date, do: iso_date(:erlang.date)
+
+ def iso_date(year, month, day), do: iso_date({year, month, day})
+
+ def iso_date(date), do:
+ :io.format("~4b-~2..0B-~2..0B~n", Tuple.to_list(date))
+
+ def long_date, do: long_date(:erlang.date)
+
+ def long_date(year, month, day), do: long_date({year, month, day})
+
+ def long_date(date = {year, month, day}) do
+ months = { "January", "February", "March", "April", "May", "June",
+ "July", "August", "September", "October", "November", "December" }
+ weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }
+ weekday = :calendar.day_of_the_week(date)
+ IO.puts "#{elem(weekdays, weekday-1)}, #{elem(months, month-1)} #{day}, #{year}"
+ end
+end
+
+Date.iso_date
+Date.iso_date(2007,11,10)
+Date.long_date
+Date.long_date(2007,11,10)
diff --git a/Task/Date-format/Julia/date-format.julia b/Task/Date-format/Julia/date-format.julia
new file mode 100644
index 0000000000..f15fd6125b
--- /dev/null
+++ b/Task/Date-format/Julia/date-format.julia
@@ -0,0 +1,5 @@
+ts = time()
+
+println("Today's date is:")
+println(" ", strftime("%F", ts))
+println(" ", strftime("%A, %B %d, %Y", ts))
diff --git a/Task/Date-format/VBScript/date-format.vb b/Task/Date-format/VBScript/date-format.vb
new file mode 100644
index 0000000000..039fb4d00a
--- /dev/null
+++ b/Task/Date-format/VBScript/date-format.vb
@@ -0,0 +1,5 @@
+'YYYY-MM-DD format
+WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2)
+
+'Weekday_Name, Month_Name DD, YYYY format
+WScript.StdOut.WriteLine FormatDateTime(Now,1)
diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-1.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-1.basic
new file mode 100644
index 0000000000..a8fcdd2b16
--- /dev/null
+++ b/Task/Day-of-the-week/BASIC/day-of-the-week-1.basic
@@ -0,0 +1,45 @@
+Declare Function modulo(x As Double, y As Double) As Double
+Declare Function wd(m As Double, d As Double, y As Double) As Integer
+
+Cls
+Dim yr As Double
+For yr = 2008 To 2121
+ If wd(12,25,yr) = 1 Then
+ Print "Dec " & 25 & ", " & yr
+ EndIf
+Next
+Sleep
+
+Function modulo(x As Double, y As Double) As Double
+ If y = 0 Then
+ Return x
+ Else
+ Return x - y * Int(x / y)
+ End If
+End Function
+
+Function wd(m As Double, d As Double, y As Double) As Integer
+ If m = 1 Or m = 2 Then
+ m += 12
+ y-= 1
+ End If
+ Return modulo(365 * y + Fix(y / 4) - Fix(y / 100) + Fix(y / 400) + d + Fix((153 * m + 8) / 5), 7) + 1
+End Function
+
+Dec 25, 2011
+Dec 25, 2016
+Dec 25, 2022
+Dec 25, 2033
+Dec 25, 2039
+Dec 25, 2044
+Dec 25, 2050
+Dec 25, 2061
+Dec 25, 2067
+Dec 25, 2072
+Dec 25, 2078
+Dec 25, 2089
+Dec 25, 2095
+Dec 25, 2101
+Dec 25, 2107
+Dec 25, 2112
+Dec 25, 2118
diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic
new file mode 100644
index 0000000000..eea41b6f14
--- /dev/null
+++ b/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic
@@ -0,0 +1,24 @@
+' version 17-06-2015
+' compile with: fbc -s console
+
+Function wd(m As Integer, d As Integer, y As Integer) As Integer
+ If m < 3 Then ' If m = 1 Or m = 2 Then
+ m += 12
+ y -= 1
+ End If
+ Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7
+End Function
+
+' ------=< MAIN >=------
+
+For yr As Integer = 2008 To 2121
+ If wd(12, 25, yr) = 0 Then
+ Print "Dec 25 "; yr
+ EndIf
+Next
+
+' empty keyboard buffer
+While InKey <> "" : Var _key_ = InKey : Wend
+Print : Print "hit any key to end program"
+Sleep
+End
diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic
new file mode 100644
index 0000000000..0662da8314
--- /dev/null
+++ b/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic
@@ -0,0 +1,17 @@
+' version 17-06-2015
+' Weekday And DateSerial only works with #Include "vbcompat.bi"
+' compile with: fbc -s console
+
+#Include Once "vbcompat.bi"
+Dim As Double a
+
+For yr As Integer = 2008 To 2121
+ a = DateSerial (yr, 12, 25)
+ If Weekday(a) = 1 Then Print Format(a, "dd-mm-yyyy") ' 1 = sunday, 2 = monday ...
+Next
+
+' empty keyboard buffer
+While InKey <> "" : Var _key_ = InKey : Wend
+Print : Print "hit any key to end program"
+Sleep
+End
diff --git a/Task/Day-of-the-week/Batch-File/day-of-the-week.bat b/Task/Day-of-the-week/Batch-File/day-of-the-week.bat
new file mode 100644
index 0000000000..2a71e2d127
--- /dev/null
+++ b/Task/Day-of-the-week/Batch-File/day-of-the-week.bat
@@ -0,0 +1,30 @@
+:: Day of the Week task from Rosetta Code Wiki
+:: Batch File Implementation
+::
+:: In what years between 2008 and 2121 will the 25th of December be a Sunday?
+::
+:: This implementation uses Zeller's Rule...
+
+@echo off
+
+::Set month code for December
+set mon=33
+
+::Set day number
+set day=25
+
+for /L %%w in (2008,1,2121) do (
+call :check_day %%w
+)
+pause>nul
+exit /b
+
+:check_day
+set yr=%1
+set /a a=%yr%/100
+set /a b=%yr%-(%a%*100)
+set /a weekday=(%day%+%mon%+%b%+(%b%/4)+(%a%/4)+(5*%a%))%%7
+if %weekday%==1 (
+echo Dec 25, %yr% is a Sunday.
+)
+goto :EOF
diff --git a/Task/Day-of-the-week/Delphi/day-of-the-week.delphi b/Task/Day-of-the-week/Delphi/day-of-the-week.delphi
index 41a1b469e0..f0c8f329aa 100644
--- a/Task/Day-of-the-week/Delphi/day-of-the-week.delphi
+++ b/Task/Day-of-the-week/Delphi/day-of-the-week.delphi
@@ -13,5 +13,8 @@ outputyears := '';
outputyears := outputyears + inttostr(i) + ' ';
end;
end;
+ //CONSOLE
+ //writeln(outputyears);
+ //GUI
form1.label1.caption := outputyears;
end;
diff --git a/Task/Day-of-the-week/Elixir/day-of-the-week.elixir b/Task/Day-of-the-week/Elixir/day-of-the-week.elixir
new file mode 100644
index 0000000000..02b7e8caa6
--- /dev/null
+++ b/Task/Day-of-the-week/Elixir/day-of-the-week.elixir
@@ -0,0 +1,4 @@
+Enum.each(2008..2121, fn year ->
+ wday = :calendar.day_of_the_week(year, 12, 25)
+ if wday==7, do: IO.puts "25 December #{year} is sunday"
+end)
diff --git a/Task/Day-of-the-week/Julia/day-of-the-week.julia b/Task/Day-of-the-week/Julia/day-of-the-week.julia
new file mode 100644
index 0000000000..298658aba8
--- /dev/null
+++ b/Task/Day-of-the-week/Julia/day-of-the-week.julia
@@ -0,0 +1,15 @@
+isdefined(:Date) || using Dates
+
+lo = 2008
+hi = 2121
+xmas = Date(lo, 12, 25):Year(1):Date(hi, 12, 25)
+
+smas = recur(xmas) do y
+ Dates.dayofweek(y) == Dates.Sun
+end
+
+println("Years (from ", lo, " to ", hi, ") having Christmas on a Sunday:")
+
+for y in smas
+ println(" ", Dates.year(y))
+end
diff --git a/Task/Day-of-the-week/Logo/day-of-the-week.logo b/Task/Day-of-the-week/Logo/day-of-the-week.logo
new file mode 100644
index 0000000000..6daea9a63e
--- /dev/null
+++ b/Task/Day-of-the-week/Logo/day-of-the-week.logo
@@ -0,0 +1,34 @@
+; Determine if a Gregorian calendar year is leap
+to leap? :year
+ output (and
+ equal? 0 modulo :year 4
+ not member? modulo :year 400 [100 200 300]
+ )
+end
+
+; Convert Gregorian calendar date to a simple day count from
+; day 1 = January 1, 1 CE
+to day_number :year :month :day
+ local "elapsed make "elapsed difference :year 1
+ output (sum product 365 :elapsed
+ int quotient :elapsed 4
+ minus int quotient :elapsed 100
+ int quotient :elapsed 400
+ int quotient difference product 367 :month 362 12
+ ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2
+ :day)
+end
+
+; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday
+to day_of_week :day_number
+ output modulo :day_number 7
+end
+
+; True if the given day is a Sunday
+to sunday? :year :month :day
+ output equal? 0 day_of_week day_number :year :month :day
+end
+
+; Put it all together to answer the question posed in the problem
+print filter [sunday? ? 12 25] iseq 2008 2121
+bye
diff --git a/Task/Day-of-the-week/Oberon-2/day-of-the-week.oberon-2 b/Task/Day-of-the-week/Oberon-2/day-of-the-week.oberon-2
new file mode 100644
index 0000000000..8abece7175
--- /dev/null
+++ b/Task/Day-of-the-week/Oberon-2/day-of-the-week.oberon-2
@@ -0,0 +1,13 @@
+MODULE DayOfWeek;
+IMPORT NPCT:Dates, Out;
+VAR
+ year: INTEGER;
+ date: Dates.Date;
+BEGIN
+ FOR year := 2008 TO 2121 DO
+ date := Dates.NewDate(25,12,year);
+ IF date.DayOfWeek() = Dates.sunday THEN
+ Out.Int(date.year,4);Out.Ln
+ END
+ END
+END DayOfWeek.
diff --git a/Task/Day-of-the-week/PARI-GP/day-of-the-week.pari b/Task/Day-of-the-week/PARI-GP/day-of-the-week.pari
new file mode 100644
index 0000000000..b1f2ad3784
--- /dev/null
+++ b/Task/Day-of-the-week/PARI-GP/day-of-the-week.pari
@@ -0,0 +1,10 @@
+njd(D) =
+{
+ my (m, y);
+
+ if (D[2] > 2, y = D[1]; m = D[2]+1, y = D[1]-1; m = D[2]+13);
+
+ (1461*y)\4 + (306001*m)\10000 + D[3] - 694024 + if (100*(100*D[1]+D[2])+D[3] > 15821004, 2 - y\100 + y\400)
+}
+
+for (y = 2008, 2121, if (njd([y,12,25]) % 7 == 1, print(y)));
diff --git a/Task/Day-of-the-week/Python/day-of-the-week.py b/Task/Day-of-the-week/Python/day-of-the-week.py
index 4b0627699f..1396944d3d 100644
--- a/Task/Day-of-the-week/Python/day-of-the-week.py
+++ b/Task/Day-of-the-week/Python/day-of-the-week.py
@@ -1,8 +1,6 @@
-import datetime
+from datetime import date
-def yuletide():
- sunday = 6
- days = (day.strftime('%d %b %Y') for day in (datetime.date(year, 12, 25) for year in range(2008,2122)) if day.weekday() == sunday)
- print '\n'.join(days)
-
-yuletide()
+for year in range(2008, 2122):
+ day = date(year, 12, 25)
+ if day.weekday() == 6:
+ print(day.strftime('%d %b %Y'))
diff --git a/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb b/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb
index ee9feb6b0b..a43d4d16a3 100644
--- a/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb
+++ b/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb
@@ -1,5 +1,3 @@
require 'date'
-(2008..2121).each do |year|
- puts "25 Dec #{year}" if Date.new(year, 12, 25).wday == 0 # Ruby 1.9: if Date.new(year, 12, 25).sunday?
-end
+(2008..2121).each {|year| puts "25 Dec #{year}" if Date.new(year, 12, 25).sunday? }
diff --git a/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83 b/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83
index 26e010e4db..8b47f5038e 100644
--- a/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83
+++ b/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83
@@ -1,5 +1,4 @@
-:For(A, 2008,2121
-:dayofWk(A,12,25
-:If Ans=1
+:For(A,2008,2121
+:If dayofWk(A,12,25)=1
:Disp A
:End
diff --git a/Task/Day-of-the-week/VBScript/day-of-the-week.vb b/Task/Day-of-the-week/VBScript/day-of-the-week.vb
new file mode 100644
index 0000000000..5c4fa890dc
--- /dev/null
+++ b/Task/Day-of-the-week/VBScript/day-of-the-week.vb
@@ -0,0 +1,6 @@
+For i = 2008 To 2121
+ If Weekday(i & "-12-25") = 1 Then
+ WScript.StdOut.Write i
+ WScript.StdOut.WriteLine
+ End If
+Next
diff --git a/Task/Deal-cards-for-FreeCell/Befunge/deal-cards-for-freecell.bf b/Task/Deal-cards-for-FreeCell/Befunge/deal-cards-for-freecell.bf
new file mode 100644
index 0000000000..ccf34c5359
--- /dev/null
+++ b/Task/Deal-cards-for-FreeCell/Befunge/deal-cards-for-freecell.bf
@@ -0,0 +1,5 @@
+vutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDC
+>4$0" :rebmun emaG">:#,_$&>55+,>"O?+"**2+*"C4'' "**v
+>8%!492*+*48*\-,1-:11p0g\0p11g#^_@A23456789TJQKCDHS*
+^+3:g11,g2+"/"%4,g2+g14/4:-\"v"g0:%g11+*-/2-10-1*<>+
+>8#8*#4*#::#%*#*/#*:#*0#:\#*`#:8#::#*:#8*#8:#2*#+^#<
diff --git a/Task/Deal-cards-for-FreeCell/Clojure/deal-cards-for-freecell.clj b/Task/Deal-cards-for-FreeCell/Clojure/deal-cards-for-freecell.clj
new file mode 100644
index 0000000000..4eb5751b2c
--- /dev/null
+++ b/Task/Deal-cards-for-FreeCell/Clojure/deal-cards-for-freecell.clj
@@ -0,0 +1,16 @@
+(def deck (into [] (for [rank "A23456789TJQK" suit "CDHS"] (str rank suit))))
+
+(defn lcg [seed]
+ (map #(bit-shift-right % 16)
+ (rest (iterate #(mod (+ (* % 214013) 2531011) (bit-shift-left 1 31)) seed))))
+
+(defn gen [seed]
+ (map (fn [rnd rng] (into [] [(mod rnd rng) (dec rng)]))
+ (lcg seed) (range 52 0 -1)))
+
+(defn xchg [v [src dst]] (assoc v dst (v src) src (v dst)))
+
+(defn show [seed] (map #(println %) (partition 8 8 ""
+ (reverse (reduce xchg deck (gen seed))))))
+
+(show 1)
diff --git a/Task/Deal-cards-for-FreeCell/Mathematica/deal-cards-for-freecell.math b/Task/Deal-cards-for-FreeCell/Mathematica/deal-cards-for-freecell.math
new file mode 100644
index 0000000000..eb509f0179
--- /dev/null
+++ b/Task/Deal-cards-for-FreeCell/Mathematica/deal-cards-for-freecell.math
@@ -0,0 +1,13 @@
+next[last_] := Mod[214013 last + 2531011, 2^31];
+deal[n_] :=
+ Module[{last = n, idx,
+ deck = StringJoin /@
+ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J",
+ "Q", "K"}, {"C", "D", "H", "S"}}], res = {}},
+ While[deck != {}, last = next[last];
+ idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1;
+ deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}];
+ AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res];
+format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]];
+Print[format[deal[1]]];
+Print[format[deal[617]]];
diff --git a/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6 b/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6
index 83cebfe439..6a269bc8b5 100644
--- a/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6
+++ b/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6
@@ -5,7 +5,7 @@ sub dealgame ($game-number = 1) {
my @ms-lcg := (&ms-lcg-method ... *).map: * +> 16;
constant CardBlock = '🂠'.ord;
- my @deck = gather for 1..11,13,14 X+ (48,32...0) -> $off {
+ my @deck = gather for flat(1..11,13,14) X+ (48,32...0) -> $off {
take chr CardBlock + $off;
}
diff --git a/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx b/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx
new file mode 100644
index 0000000000..5c01186044
--- /dev/null
+++ b/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx
@@ -0,0 +1,26 @@
+/*REXX pgm deals cards for a specific FreeCell solitaire card game (0──►32767)*/
+numeric digits 15 /*ensure enough digits for the random #*/
+parse arg g .; if g=='' then g=1 /*if game isn't specified, use default.*/
+state=g /*seed the random # generator with game*/
+if 8=='f8'x then suit='cdhs' /*EBCDIC? Then use letters for suits.*/
+ else suit='♣♦♥♠' /* ASCII? " " symbols " " */
+rank='A23456789TJQK' /*T in the rank represents a ten (10).*/
+__=left('', 13) /*used for indentation for the tableau.*/
+say center('tableau for FreeCell game' g,50,'─'); say /*show title for game#*/
+#=-1 /*$ is an array of all the 52 cards.*/
+ do r=1 for length(rank) /*build deck first by the rank.*/
+ do s=1 for length(suit); #=#+1 /* " " secondly by suit. */
+ $.#=substr(rank,r,1)substr(suit,s,1) /*build array 1 card at at time*/
+ end /*s*/ /* [↑] first card is number 0.*/
+ end /*r*/ /* [↑] build deck per FreeCell rules. */
+@=__ /*@: cards to be dealt, eight at a time*/
+ do cards=51 by -1 for 52 /* [↓] deal the cards for the tableau.*/
+ ?=rand() // (cards+1) /*get next rand#; card # is remainder.*/
+ @=@ $.?; $.?=$.cards /*swap 2 cards: random & last*/
+ if words(@)==8 then do; say @; @=__; end /*deal cards for the tableau.*/
+ end /*cards*/ /*8 cards are dealt to a row.*/
+ /* [↓] residual cards exist.*/
+ if @\=='' then say @ /*residual cards for tableau.*/
+exit /*stick a fork in it, we're all done. */
+/*──────────────────────────────────RAND subroutine───────────────────────────*/
+rand: state = (214013 * state + 2531011) // 2**31; return state % 2**16
diff --git a/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb b/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb
index 9ab3282702..07c725996e 100644
--- a/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb
+++ b/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb
@@ -1,55 +1,16 @@
-# Deal cards for FreeCell.
-# http://rosettacode.org/wiki/Deal_cards_for_FreeCell
-
-require 'optparse'
-
-# Parse command-line arguments.
# games = ARGV converted to Integer
# No arguments? Pick any of first 32000 games.
-games = nil
-OptionParser.new do |o|
- begin
- o.banner = "Usage: #{o.program_name} number..."
- o.parse!
- games = ARGV.map {|s| Integer(s)}
- games.empty? and games = [rand(32000)]
- rescue => e
- $stderr.puts e, o
- abort
- end
-end
-
-# Define methods for old Ruby versions.
-# Enumerable#each_slice appeared in Ruby 1.8.7.
-# Enumerable#flat_map appeared in Ruby 1.9.2.
-module Enumerable
- unless method_defined? :each_slice
- def each_slice(count)
- block_given? or return enum_for(:each_slice, count)
- ary = []
- each {|e|
- ary << e
- ary.length == count and (yield ary.dup; ary.clear)}
- ary.empty? or yield ary.dup
- nil
- end
- end
-
- unless method_defined? :flat_map
- def flat_map
- block_given? or return enum_for(:flat_map)
- ary = []
- each {|e|
- y = yield e
- ary.concat(y) rescue ary.push(y)}
- ary
- end
- end
+begin
+ games = ARGV.map {|s| Integer(s)}
+rescue => err
+ $stderr.puts err.inspect
+ $stderr.puts "Usage: #{__FILE__} number..."
+ abort
end
+games.empty? and games = [rand(32000)]
# Create original deck of 52 cards, not yet shuffled.
-orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K
-}.flat_map {|rank| %w{C D H S}.map {|suit| "#{rank}#{suit}"}}
+orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join)
games.each do |seed|
deck = orig_deck.dup
@@ -69,4 +30,5 @@ def flat_map
# Deal cards.
puts "Game ##{seed}"
deck.each_slice(8) {|row| puts " " + row.join(" ")}
+ puts
end
diff --git a/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust
index 24586a4c28..71003a7eac 100644
--- a/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust
+++ b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust
@@ -1,85 +1,59 @@
-/*
- * Microsoft C Run-time-Library-compatible Random Number Generator
- * Copyright by Shlomi Fish, 2011.
- * Released under the MIT/X11 License
- * ( http://en.wikipedia.org/wiki/MIT_License ).
- * */
-
-struct MSVC_Rand_Gen {
- seed: i32
+struct MSVCRandGen {
+ seed: u32
}
-impl MSVC_Rand_Gen {
- fn rand(&mut self) -> i32 {
- self.seed = ((self.seed * 214013 + 2531011) & 0x7FFFFFFF);
- return ((self.seed >> 16) & 0x7FFF);
+impl MSVCRandGen {
+ fn rand(&mut self) -> u32 {
+ self.seed = (self.seed.wrapping_mul(214013).wrapping_add(2531011)) % 0x80000000;
+ assert!(self.seed >> 16 < 32768);
+ (self.seed >> 16) & 0x7FFF
}
- fn max_rand(&mut self, mymax: i32) -> i32 {
- return self.rand() % mymax;
+ fn max_rand(&mut self, mymax: u32) -> u32 {
+ self.rand() % mymax
}
fn shuffle(&mut self, deck: &mut [T]) {
if deck.len() > 0 {
- let mut i = (deck.len() as i32) - 1;
+ let mut i = (deck.len() as u32) - 1;
while i > 0 {
let j = self.max_rand(i+1);
- vec::swap(deck, i as uint, j as uint);
+ deck.swap(i as usize, j as usize);
i = i-1;
}
}
}
}
-/*
- * Microsoft Windows Freecell / Freecell Pro boards generation.
- *
- * See:
- *
- * - http://rosettacode.org/wiki/Deal_cards_for_FreeCell
- *
- * - http://www.solitairelaboratory.com/mshuffle.txt
- *
- * Under MIT/X11 Licence.
- *
- * */
-
-
-fn deal_ms_fc_board(seed: i32) -> ~str {
- let mut randomizer = MSVC_Rand_Gen { seed: seed, };
+fn deal_ms_fc_board(seed: u32) -> String {
+ let mut randomizer = MSVCRandGen { seed: seed, };
let num_cols = 8;
- let mut columns = vec::from_elem(num_cols, ~[]);
- let mut deck = vec::from_fn(4*13, |i| i);
+ let mut columns = vec![Vec::new(); num_cols];
+ let mut deck: Vec<_> = (0..4*13).collect();
- let rank_strings = str::to_chars("A23456789TJQK");
- let suit_strings = str::to_chars("CDHS");
+ let rank_strings: Vec = "A23456789TJQK".chars().collect();
+ let suit_strings: Vec = "CDHS".chars().collect();
- randomizer.shuffle(deck);
+ randomizer.shuffle(&mut deck);
- vec::reverse(deck);
+ deck.reverse();
- for uint::range(0, 52) |i| {
+ for i in 0..52 {
columns[i % num_cols].push(deck[i]);
- };
-
- let render_card = |card: &uint| {
- let suit = card % 4;
- let rank = card / 4;
+ }
- fmt!("%c%c",rank_strings[rank], suit_strings[suit])
+ let render_card = |card: usize| -> String {
+ let (suit, rank) = (card % 4, card / 4);
+ format!("{}{}", rank_strings[rank], suit_strings[suit])
};
- let render_column = |col: &~[uint]| {
- fmt!(": %s\n", str::connect((col.map(render_card)), " "))
+ let render_column = |col: Vec| -> String {
+ format!(": {}\n", col.into_iter().map(&render_card).collect::>().join(" "))
};
- return str::concat(columns.map(render_column));
+ columns.into_iter().map(render_column).collect::>().join("")
}
fn main() {
- let args: ~[~str] = os::args();
-
- match uint::from_str(args[1]) {
- Some(x) => print(deal_ms_fc_board(x as i32)),
- None => println("I need a real number"),
- }
+ let arg: u32 = std::env::args().nth(1).and_then(|n| n.parse().ok()).expect("I need a number.");
+ print!("{}", deal_ms_fc_board(arg));
}
diff --git a/Task/Death-Star/J/death-star.j b/Task/Death-Star/J/death-star.j
new file mode 100644
index 0000000000..f0d3d92fd0
--- /dev/null
+++ b/Task/Death-Star/J/death-star.j
@@ -0,0 +1,40 @@
+load'graphics/viewmat'
+mag =: +/&.:*:"1
+norm=: %"1 0 mag
+dot =: +/@:*"1
+
+NB. (pos;posr;neg;negr) getvec (x,y)
+getvec =: 4 :0 "1
+ pt =. y
+ 'pos posr neg negr' =. x
+ if. (dot~ pt-}:pos) > *:posr do.
+ 0 0 0
+ else.
+ zb =. ({:pos) (-,+) posr -&.:*: pt mag@:- }:pos
+ if. (dot~ pt-}:neg) > *:negr do.
+ (pt,{:zb) - pos
+ else.
+ zs =. ({:neg) (-,+) negr -&.:*: pt mag@:- }:neg
+ if. zs >&{. zb do. (pt,{:zb) - pos
+ elseif. zs >&{: zb do. 0 0 0
+ elseif. ({.zs) < ({:zb) do. neg - (pt,{.zs)
+ elseif. do. (pt,{.zb) - pos end.
+ end.
+ end.
+)
+
+
+NB. (k;ambient;light) draw_sphere (pos;posr;neg;negr)
+draw_sphere =: 4 :0
+ 'pos posr neg negr' =. y
+ 'k ambient light' =. x
+ vec=. norm y getvec ,"0// (2{.pos) +/ i: 200 j.~ 0.5+posr
+
+ b=. (mag vec) * ambient + k * 0>. light dot vec
+)
+
+togray =: 256#. 255 255 255 <.@*"1 0 (%>./@,)
+
+env=.(2; 0.5; (norm _50 30 50))
+sph=. 20 20 0; 20; 1 1 _6; 20
+'rgb' viewmat togray env draw_sphere sph
diff --git a/Task/Death-Star/Perl-6/death-star.pl6 b/Task/Death-Star/Perl-6/death-star.pl6
index edd584b3c7..1873583d7d 100644
--- a/Task/Death-Star/Perl-6/death-star.pl6
+++ b/Task/Death-Star/Perl-6/death-star.pl6
@@ -33,7 +33,7 @@ sub MAIN ($outfile = 'deathstar-perl6.pgm') {
my $out = open( $outfile, :w, :bin ) or die "$!\n";
$out.say("P5\n$x $y\n$depth"); # .pgm header
say 'Calculating row:';
- $out.print( draw_ds(3, .15)».chrs );
+ $out.write( Blob.new( draw_ds(3, .15) ) );
$out.close;
}
@@ -41,7 +41,7 @@ sub draw_ds ( $k, $ambient ) {
my @pixels;
my $bs = "\b" x 8;
for ($pos.cy - $pos.r) .. ($pos.cy + $pos.r) -> $y {
- note $bs, $y, ' '; # monitor progress
+ print $bs, $y, ' '; # monitor progress
for ($pos.cx - $pos.r) .. ($pos.cx + $pos.r) -> $x {
# black if we don't hit positive sphere, ignore negative sphere
if not hit($pos, $x, $y, my $posz) {
@@ -69,10 +69,10 @@ sub draw_ds ( $k, $ambient ) {
}
# normalize a vector
-sub normalize (@vec) { return @vec »/» ([+] @vec Z* @vec).sqrt }
+sub normalize (@vec) { return @vec »/» ([+] @vec »*« @vec).sqrt }
# dot product of two vectors
-sub dot (@x, @y) { return -([+] @x Z* @y) max 0 }
+sub dot (@x, @y) { return -([+] @x »*« @y) max 0 }
# are the coordinates within the radius of the sphere?
sub hit ($sphere, $x is copy, $y is copy, $z is rw) {
diff --git a/Task/Death-Star/REXX/death-star.rexx b/Task/Death-Star/REXX/death-star.rexx
index 8e01935930..11a18d83b6 100644
--- a/Task/Death-Star/REXX/death-star.rexx
+++ b/Task/Death-Star/REXX/death-star.rexx
@@ -1,75 +1,58 @@
-/*REXX program to draw a "deathstar", a sphere with another subtracted. */
-signal on syntax; signal on noValue /*handle REXX program errors. */
-numeric digits 20 /*use a fair amount of precision.*/
- lightSource = norm('-50 30 50')
-call drawSphereM 2, .5, lightSource
-exit /*stick a fork in it, we're done.*/
-/*──────────────────────────────────DRAWSPHEREM subroutine──────────────*/
-drawSphereM: procedure; parse arg k,ambient,lightSource
-z1=0; z2=0
-parse var lightSource s1 s2 s3 /*break-apart the light source. */
-
- shading='·:!ºoe@░▒▓' /*shading chars for ASCI machines*/
-if 1=='f1'x then shading='.:!*oe%@' /*shading chars for EBCDIC machs.*/
-
-shadesLength=length(shading)
-shades.=' '; do i=1 for shadesLength
- shades.i=substr(shading,i,1)
- end /*i*/
-
-ship= 20 20 0 20 ; parse var ship ship.cx ship.cy ship.cz ship.radius
-hole=' 1 1 -6 20'; parse var hole hole.cx hole.cy hole.cz hole.radius
-
- do i=floor(ship.cy-ship.radius) to ceil(ship.cy+ship.radius)+1; y=i+.5; aLine=
- do j=trunc(floor(ship.cx - 2*ship.radius) ) to ,
- trunc( ceil(ship.cx + 2*ship.radius) +1)
- x=.5*(j-ship.cx) + .5 + ship.cx; !bg=0; !pos=0; !neg=0; z1=0; z2=0
- ?=hitSphere(ship, x, y); zb1=z1; zb2=z2
-
- if \? then !bg=1 /*ray lands in blank space, draw the background. */
- else do
- ?=hitsphere(hole, x, y); zs1=z1; zs2=z2
- if \? then !pos=1 /*ray hits ship but not the hole, draw ship surface. */
- else if zs1>zb1 then !pos=1 /*ray hits both, but ship front surface is closer. */
- else if zs2>zb2 then !bg=1 /*ship surface is inside hole, show background. */
- else if zs2>zb1 then !neg=1 /*back surface in hole is inside ship, the only place hole surface will be shown.*/
- else !pos=1
+/*REXX pgm draws a sphere with another sphere subtracted where superimposed. */
+call deathStar 2, .5, v3('-50 30 50')
+exit /*stick a fork in it, we're all done. */
+/*──────────────────────────────────one─liner subroutines────────────────────────────────────────*/
+dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0
+dot: procedure; parse arg x,y; s=0; do j=1 for words(x); s=s+word(x,j)*word(y,j); end; return s
+ceil: procedure; parse arg x; _=trunc(x); return _+(x>0)*(x\=_)
+floor: procedure; parse arg x; _=trunc(x); return _-(x<0)*(x\=_)
+v3: procedure; parse arg a b c; s=sqrt(a**2+b**2+c**2); return a/s b/s c/s
+/*──────────────────────────────────DEATHSTAR subroutine──────────────────────*/
+deathStar: procedure; parse arg k,ambient,sun /* [↓] draw deathstar*/
+parse var sun s1 s2 s3 /*identify the lightsource coördinates.*/
+
+if 6=='f6'x then shading= '.:!*oe%@' /*shading characters for EBCDIC machine*/
+ else shading= '·:!ºoe@░▒▓' /* " " " ASCII " */
+
+shadesLen=length(shading)
+shades.=' '; do i=1 for shadesLen; shades.i=substr(shading,i,1); end /*i*/
+
+ship= 20 20 0 20 ; parse var ship ship.cx ship.cy ship.cz ship.radius
+hole=' 1 1 -6 20'; parse var hole hole.cx hole.cy hole.cz hole.radius
+
+ do i=floor(ship.cy-ship.radius) to ceil(ship.cy+ship.radius) +1; y=i+.5; $=
+ do j=trunc(floor(ship.cx-2*ship.radius)) to trunc(ceil(ship.cx+2*ship.radius) +1)
+ x=.5*(j-ship.cx)+.5+ship.cx; !.=0
+ ?=hitSphere(ship, x, y); b1=!.z1; b2=!.z2 /*? is boolean, "true" indicates ray hits the sphere.*/
+
+ if \? then !.bg=1 /*ray lands in blank space, so draw the background. */
+ else do; ?=hitSphere(hole, x, y); s1=!.z1; s2=!.z2
+ if \? then !.pos=1 /*ray hits ship but not the hole, so draw ship surface. */
+ else if s1>b1 then !.pos=1 /*ray hits both, but ship front surface is closer. */
+ else if s2>b2 then !.bg=1 /*ship surface is inside hole, so show the background. */
+ else if s2>b1 then !.neg=1 /*hole back surface is inside ship; the only place hole surface will be shown.*/
+ else !.pos=1
end
select
- when !bg then do; aLine=aLine' '; iterate j; end
- when !pos then vec_=V3(x-ship.cx y-ship.cy zb1-ship.cz)
- when !neg then vec_=V3(hole.cx-x hole.cy-y hole.cz-zs2)
+ when !.bg then do; $=$' '; iterate j; end /*append a blank to the line to be displayed.*/
+ when !.pos then vec_=v3(x-ship.cx y-ship.cy b1-ship.cz)
+ when !.neg then vec_=v3(hole.cx-x hole.cy-y hole.cz-s2)
end /*select*/
- nvec=norm(vec_)
- b=dot.(lightSource,nvec)**k + ambient
- intensity=trunc((1-b) * shadesLength)
- intensity=min(shadesLength, max(0, intensity)) + 1
- aLine=aLine || shades.intensity
- end /*j*/
+ b=1+min(shadesLen,max(0,trunc((1-(dot.(sun,v3(vec_))**k+ambient))*shadesLen)))
+ $=$ || shades.b /*B is the ray's intensity│brightness*/
+ end /*j*/ /* [↑] build line for showing sphere.*/
- if aline\='' then say strip(aLine,'T')
- end /*i*/
+ if $\='' then say strip($,'T') /*strip any trailing blanks from line.*/
+ end /*i*/ /* [↑] show all lines for the sphere.*/
return
-/*──────────────────────────────────HITSPHERE subroutine────────────────*/
-hitSphere: procedure expose z1 z2; parse arg $.cx $.cy $.cz $.radius, x0, y0
- x=x0-$.cx
- y=y0-$.cy
- zsq=$.radius**2 - (x**2 + y**2); if zsq<0 then return 0
- _=sqrt(zsq)
- z1=$.cz-_
- z2=$.cz+_
- return 1
-/*──────────────────────────────────one─liner subroutines────────────────────────────────────────────────────────────────────────────────────────────────────────*/
-dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0
-dot: procedure; parse arg x,y; s=0; do j=1 for words(x); s=s+word(x,j)*word(y,j); end; return s
-err: say; say; say center(' error! ',max(40,linesize()%2),"*"); say; do j=1 for arg(); say arg(j); say; end; say; exit 13
-ceil: procedure; parse arg x; _=trunc(x); return _ + (x>0) * (x\=_)
-floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) * (x\=_)
-norm: parse arg _1 _2 _3; _=sqrt(_1**2+_2**2+_3**2); return _1/_ _2/_ _3/_
-noValue: syntax: call err 'REXX program' condition('C') "error", condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl)
-sqrt: procedure; parse arg x; if x=0 then return 0; return .sqrt(x)/1
-.sqrt: d=digits();numeric digits 11;g=.sqrtG();do j=0 while p>9;m.j=p;p=p%2+1;end;do k=j+5 by -1 to 0;if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;return g
-.sqrtG: numeric form; m.=11; p=d+d%4+2; v=format(x,2,1,,0) 'E0'; parse var v g 'E' _ .; return g*.5'E'_%2
-V3: procedure; parse arg v; return norm(v)
+/*──────────────────────────────────HITSPHERE subroutine──────────────────────────*/
+hitSphere: procedure expose !.; parse arg xx yy zz r,x0,y0; x=x0-xx; y=y0-yy
+z=r**2-(x**2+y**2); if z<0 then return 0; _=sqrt(z); !.z1=zz-_; !.z2=zz+_; return 1
+/*──────────────────────────────────SQRT subroutine───────────────────────────*/
+sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9
+ numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
+ parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
+ do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
+ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
diff --git a/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 b/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6
index edaec53b6e..255cf96994 100644
--- a/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6
+++ b/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6
@@ -1,10 +1,10 @@
sub deconvolve (@g, @f) {
my $h = 1 + @g - @f;
my @m;
- @m[^@g]>>.[^$h] >>+=>> 0;
- @m[^@g]>>.[$h] >>=<< @g;
+ @m[^@g;^$h] >>+=>> 0;
+ @m[^@g;$h] >>=<< @g;
for ^$h -> $j { for @f.kv -> $k, $v { @m[$j + $k][$j] = $v } }
- return rref( @m )[^$h]>>.[$h];
+ return rref( @m )[^$h;$h];
}
sub convolve (@f, @h) {
@@ -16,7 +16,7 @@ sub convolve (@f, @h) {
# Reduced Row Echelon Form simultaneous equation solver.
# Can handle over-specified systems of equations.
# (n unknowns in n + m equations)
-sub rref ($m is rw) {
+sub rref ($m is copy) {
return unless $m;
my ($lead, $rows, $cols) = 0, +$m, +$m[0];
@@ -41,7 +41,7 @@ sub rref ($m is rw) {
$m[$r] >>/=>> $lv;
for ^$rows -> $n {
next if $n == $r;
- $m[$n] >>-=>> $m[$r] >>*>> $m[$n][$lead];
+ $m[$n] >>-=>> $m[$r] >>*>> ($m[$n][$lead]//0);
}
++$lead;
}
diff --git a/Task/Deepcopy/Mathematica/deepcopy.math b/Task/Deepcopy/Mathematica/deepcopy.math
new file mode 100644
index 0000000000..3a16780eca
--- /dev/null
+++ b/Task/Deepcopy/Mathematica/deepcopy.math
@@ -0,0 +1,9 @@
+a = {"foo", \[Pi], {<|
+ "deep" -> {# +
+ 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \
+{{"programming"}, {"language!"}}}}|>}};
+b = a;
+a[[2]] -= 3;
+a[[3, 1, 1, 1]] = #^2 &;
+Print[a];
+Print[b];
diff --git a/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6 b/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6
index 8671ff92e6..df5e308092 100644
--- a/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6
+++ b/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6
@@ -1,4 +1,4 @@
-subset OneToTen of Int where 1..10
+subset OneToTen of Int where 1..10;
my OneToTen $n = 5;
$n += 6;
diff --git a/Task/Delegates/ALGOL-68/delegates.alg b/Task/Delegates/ALGOL-68/delegates.alg
new file mode 100644
index 0000000000..0c4d37a671
--- /dev/null
+++ b/Task/Delegates/ALGOL-68/delegates.alg
@@ -0,0 +1,75 @@
+# An Algol 68 approximation of delegates #
+
+# The delegate mode - the delegate is a STRUCT with a single field #
+# that is a REF PROC STRING. If this is NIL, it doesn't implement #
+# thing #
+MODE DELEGATE = STRUCT( REF PROC STRING thing );
+
+
+# A delegator mode that will invoke the delegate's thing method #
+# - if there is a delegate and the delegate has a thing method #
+MODE DELEGATOR = STRUCT( REF DELEGATE delegate
+ , PROC( REF DELEGATE )STRING thing
+ );
+
+# constructs a new DELEGATE with the specified PROC as its thing #
+# Algol 68 HEAP is like "new" in e.g. Java, but it can't take #
+# parameters, so this PROC does the equivalent #
+PROC new delegate = ( REF PROC STRING thing )REF DELEGATE:
+ BEGIN
+ REF DELEGATE result = HEAP DELEGATE;
+ thing OF result := thing;
+
+ result
+ END # new delegate #
+;
+
+# constructs a new DELEGATOR with the specified DELEGATE #
+PROC new delegator = ( REF DELEGATE delegate )REF DELEGATOR:
+ HEAP DELEGATOR := ( delegate
+ , # anonymous PROC to invoke the delegate's thing #
+ ( REF DELEGATE delegate )STRING:
+ IF delegate IS REF DELEGATE(NIL)
+ THEN
+ # we have no delegate #
+ "default implementation"
+
+ ELIF thing OF delegate IS REF PROC STRING(NIL)
+ THEN
+ # the delegate doesn't have an implementation #
+ "default implementation"
+
+ ELSE
+ # the delegate can thing #
+ thing OF delegate
+
+ FI
+ )
+;
+
+
+# invokes the delegate's thing via the delagator #
+# Because the PROCs of a STRUCT don't have an equivalent of e.g. Java's #
+# "this", we have to explicitly pass the delegate as a parameter #
+PROC invoke thing = ( REF DELEGATOR delegator )STRING:
+ # the following is Algol 68 for what would be written in Java as #
+ # "delegator.thing( delegator.delegate )" #
+ ( thing OF delegator )( delegate OF delegator )
+;
+
+main:
+(
+
+ print( ( "No delegate : "
+ , invoke thing( new delegator( NIL ) )
+ , newline
+ , "Delegate with no thing: "
+ , invoke thing( new delegator( new delegate( NIL ) ) )
+ , newline
+ , "Delegate with a thing : "
+ , invoke thing( new delegator( new delegate( HEAP PROC STRING := STRING: ( "delegate implementation" ) ) ) )
+ , newline
+ )
+ )
+
+)
diff --git a/Task/Delegates/Forth/delegates.fth b/Task/Delegates/Forth/delegates.fth
new file mode 100644
index 0000000000..2c07246b9a
--- /dev/null
+++ b/Task/Delegates/Forth/delegates.fth
@@ -0,0 +1,67 @@
+include FMS-SI.f
+
+-1 [if] \ add optional introspection facility to FMS
+
+: fm' ( selector-ID link -- xt | 0 ) \ find method, linked-list search
+ begin @ dup
+ while 2dup cell+ @ =
+ if [ 2 cells ] literal + nip @ exit then
+ repeat 2drop false ;
+
+: has-meth-L ( obj addr -- xt | 0 )
+ swap >class over @ + fm' ;
+
+: >xt' ( table-offset ^dispatch -- xt | 0 )
+ 2dup @ > if 2drop false exit then
+ + @ ;
+
+: has-meth-D ( obj addr -- xt | 0 )
+ @ swap @ >xt' ;
+
+: (has-meth) ( obj addr sel-type -- xt | 0 )
+ seltype-L =
+ if ( obj addr ) has-meth-L
+ else ( obj addr ) has-meth-D
+ then ;
+
+: [has-meth] ( obj "messageName" -- xt | 0 ) \ compile time only, can use ex-meth on xt to execute the method
+ ' >body dup postpone literal cell+ @ postpone literal postpone (has-meth) ; immediate
+
+: has-meth ( obj "messageName" -- xt | 0 ) \ interpret time only, can use ex-meth on xt to execute the method
+ ' >body dup cell+ @ (has-meth) ;
+[then]
+
+
+
+:class delegate
+ :m thing ." delegate implementation" ;m
+;class
+
+delegate slave
+
+:class delegator
+ ivar del \ object container
+ :m !: ( n -- ) del ! ;m
+ :m init: 0 del ! ;m
+ :m default ." default implementation" ;m
+ :m operation
+ del @ 0= if self default exit then
+ del @ [has-meth] thing
+ if del @ thing
+ else self default
+ then ;m
+;class
+
+delegator master
+
+\ First, without a delegate
+master operation \ => default implementation
+
+\ then with a delegate that does not implement "thing"
+object o
+o master !:
+master operation \ => default implementation
+
+\ and last with a delegate that implements "thing"
+slave master !:
+master operation \ => delegate implementation
diff --git a/Task/Delegates/Mathematica/delegates.math b/Task/Delegates/Mathematica/delegates.math
new file mode 100644
index 0000000000..6bdc6467aa
--- /dev/null
+++ b/Task/Delegates/Mathematica/delegates.math
@@ -0,0 +1,6 @@
+delegator[del_]@operate :=
+ If[StringQ[del@operate], del@operate, "default implementation"];
+del1 = Null;
+del2@banana = "phone";
+del3@operate = "delegate implementation";
+Print[delegator[#]@operate] & /@ {del1, del2, del3};
diff --git a/Task/Delete-a-file/Elixir/delete-a-file.elixir b/Task/Delete-a-file/Elixir/delete-a-file.elixir
new file mode 100644
index 0000000000..a3483b8fa5
--- /dev/null
+++ b/Task/Delete-a-file/Elixir/delete-a-file.elixir
@@ -0,0 +1,4 @@
+File.rm!("input.txt")
+File.rmdir!("docs")
+File.rm!("/input.txt")
+File.rmdir!("/docs")
diff --git a/Task/Delete-a-file/Mercury/delete-a-file.mercury b/Task/Delete-a-file/Mercury/delete-a-file.mercury
new file mode 100644
index 0000000000..7f609d3bf7
--- /dev/null
+++ b/Task/Delete-a-file/Mercury/delete-a-file.mercury
@@ -0,0 +1,14 @@
+:- module delete_file.
+:- interface.
+
+:- import_module io.
+
+:- pred main(io::di, io::uo) is det.
+
+:- implementation.
+
+main(!IO) :-
+ io.remove_file("input.txt", _, !IO),
+ io.remove_file("/input.txt", _, !IO),
+ io.remove_file("docs", _, !IO),
+ io.remove_file("/docs", _, !IO).
diff --git a/Task/Detect-division-by-zero/Batch-File/detect-division-by-zero.bat b/Task/Detect-division-by-zero/Batch-File/detect-division-by-zero.bat
new file mode 100644
index 0000000000..9e13612c89
--- /dev/null
+++ b/Task/Detect-division-by-zero/Batch-File/detect-division-by-zero.bat
@@ -0,0 +1,5 @@
+@echo off
+set /a dummy=5/0 2>nul
+
+if %errorlevel%==1073750993 echo I caught a division by zero operation...
+exit /b 0
diff --git a/Task/Detect-division-by-zero/Elixir/detect-division-by-zero.elixir b/Task/Detect-division-by-zero/Elixir/detect-division-by-zero.elixir
new file mode 100644
index 0000000000..e33e83d2c8
--- /dev/null
+++ b/Task/Detect-division-by-zero/Elixir/detect-division-by-zero.elixir
@@ -0,0 +1,15 @@
+defmodule Division do
+ def by_zero?(x,y) do
+ try do
+ _ = x / y
+ false
+ rescue
+ ArithmeticError -> true
+ end
+ end
+end
+
+[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}]
+|> Enum.each(fn {x,y} ->
+ IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}"
+end)
diff --git a/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-1.f b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-1.f
new file mode 100644
index 0000000000..0cd24de9d7
--- /dev/null
+++ b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-1.f
@@ -0,0 +1,41 @@
+program rosetta_divbyzero
+ implicit none
+ integer, parameter :: rdp = kind(1.d0)
+ real(rdp) :: normal,zero
+
+ normal = 1.d0
+ zero = 0.d0
+
+ call div_by_zero_check(normal,zero)
+
+ contains
+
+ subroutine div_by_zero_check(x,y)
+ use, intrinsic :: ieee_exceptions
+ use, intrinsic :: ieee_arithmetic
+ implicit none
+ real(rdp), intent(in) :: x,y
+
+ real(rdp) :: check
+ type(ieee_status_type) :: status_value
+ logical :: flag
+ flag = .false.
+ ! Get the flags
+ call ieee_get_status(status_value)
+ ! Set the flags quiet
+ call ieee_set_flag(ieee_divide_by_zero,.false.)
+ write(*,*)"Inf supported? ",ieee_support_inf(check)
+
+ ! Calculation involving exception handling
+ check = x/y
+ write(*,*)"Is check finite?",ieee_is_finite(check), check
+
+ call ieee_get_flag(ieee_divide_by_zero, flag)
+ if (flag) write(*,*)"Warning! Division by zero detected"
+
+ ! Restore the flags
+ call ieee_set_status(status_value)
+
+ end subroutine div_by_zero_check
+
+end program rosetta_divbyzero
diff --git a/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-2.f b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-2.f
new file mode 100644
index 0000000000..7d64715d79
--- /dev/null
+++ b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-2.f
@@ -0,0 +1,8 @@
+program rosetta_integer_divbyzero
+ implicit none
+ integer :: normal,zero,answer
+ normal = 1
+ zero = 0
+ answer = normal/ zero
+ write(*,*) answer
+end program rosetta_integer_divbyzero
diff --git a/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia b/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia
new file mode 100644
index 0000000000..9f378300aa
--- /dev/null
+++ b/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia
@@ -0,0 +1,13 @@
+function isdefinite{T<:Number}(n::T)
+ !isequal(n, NaN) && abs(n) != Inf
+end
+
+for n in {1, 1//1, 1.0, 1im, 0}
+ d = n/0
+ print("Divding ", n, " by 0 ")
+ if isdefinite(d)
+ println("results in ", d, ".")
+ else
+ println("yields an indefinite value (", d, ").")
+ end
+end
diff --git a/Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh b/Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh
new file mode 100644
index 0000000000..082dcaa5db
--- /dev/null
+++ b/Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh
@@ -0,0 +1,6 @@
+function div ($a, $b) {
+ try{$a/$b}
+ catch{"Bad parameters: `$a = $a and `$b = $b"}
+}
+div 10 2
+div 1 0
diff --git a/Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb b/Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb
new file mode 100644
index 0000000000..b123e4dd65
--- /dev/null
+++ b/Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb
@@ -0,0 +1,13 @@
+Function div(num,den)
+ On Error Resume Next
+ n = num/den
+ If Err.Number <> 0 Then
+ div = Err.Description & " is not allowed."
+ Else
+ div = n
+ End If
+End Function
+
+WScript.StdOut.WriteLine div(6,3)
+WScript.StdOut.WriteLine div(6,0)
+WScript.StdOut.WriteLine div(7,-4)
diff --git a/Task/Determine-if-a-string-is-numeric/00META.yaml b/Task/Determine-if-a-string-is-numeric/00META.yaml
index 88eb5468ca..ac97287d53 100644
--- a/Task/Determine-if-a-string-is-numeric/00META.yaml
+++ b/Task/Determine-if-a-string-is-numeric/00META.yaml
@@ -1,2 +1,4 @@
---
+category:
+- Simple
note: Text processing
diff --git a/Task/Determine-if-a-string-is-numeric/ALGOL-W/determine-if-a-string-is-numeric.alg b/Task/Determine-if-a-string-is-numeric/ALGOL-W/determine-if-a-string-is-numeric.alg
new file mode 100644
index 0000000000..8814170c90
--- /dev/null
+++ b/Task/Determine-if-a-string-is-numeric/ALGOL-W/determine-if-a-string-is-numeric.alg
@@ -0,0 +1,135 @@
+begin
+
+ % determnines whether the string contains an integer, real or imaginary %
+ % number. Returns true if it does, false otherwise %
+ logical procedure isNumeric( string(32) value text ) ;
+ begin
+
+ logical ok;
+ % the "number" cannot be blank %
+ ok := ( text not = " " );
+ if ok then begin
+
+ % there is at least one non-blank character %
+ % must have either an integer or real/immaginary number %
+ % integer: [+|-]digit-sequence %
+ % real: [+|-][digit-sequence].digit-sequence['integer][L] %
+ % or: [+|-]digit-sequence[.[digit-sequence]]'integer[L] %
+ % imaginary: %
+ % [+|-][digit-sequence].digit-sequence['integer][L]I%
+ % or: [+|-]digit-sequence[.[digit-sequence]]'integer[L]I%
+ % The "I" at the end of an imaginary number can appear %
+ % before or after the "L" (which indicates a long number) %
+ % the "I" and "L" can be in either case %
+
+ procedure nextChar ; charPos := charPos + 1;
+ logical procedure have( string(1) value ch ) ;
+ ( charPos <= maxChar and text(charPos//1) = ch ) ;
+
+ logical procedure haveDigit ;
+ ( charPos <= maxChar and text(charPos//1) >= "0" and text(charPos//1) <= "9" ) ;
+
+
+ integer charPos, maxChar;
+ logical hadDigits, isReal;
+ charPos := 0;
+ maxChar := 31;
+ hadDigits := false;
+ isReal := false;
+
+ % skip trailing spaces %
+ while maxChar > 0 and text(maxChar//1) = " " do maxChar := maxChar - 1;
+ % skip leading spacesx %
+ while have( " " ) do nextChar;
+
+ % skip optional sign %
+ if have( "+" ) or have( "-" ) then nextChar;
+
+ if haveDigit then begin
+ % have a digit sequence %
+ hadDigits := true;
+ while haveDigit do nextChar
+ end if_have_sign ;
+
+ if have( "." ) then begin
+ % real or imaginary number %
+ nextChar;
+ isReal := true;
+ hadDigits := hadDigits or haveDigit;
+ while haveDigit do nextChar
+ end if_have_point ;
+
+ % should have had some digits %
+ ok := hadDigits;
+
+ if ok and have( "'" ) then begin
+ % the number has an exponent %
+ isReal := true;
+ nextChar;
+ % skip optional sign %
+ if have( "+" ) or have( "-" ) then nextChar;
+ % must have a digit sequence %
+ ok := haveDigit;
+ while haveDigit do nextChar;
+ end if_ok_and_have_exponent ;
+
+ % if it is a real number, there could be L/I suffixes %
+ if ok and isReal then begin
+ integer LCount, ICount;
+ LCount := 0;
+ ICount := 0;
+ while have( "L" ) or have( "l" ) or have( "I" ) or have( "i" ) do begin
+ if have( "L" ) or have( "l" )
+ then LCount := LCount + 1
+ else ICount := ICount + 1;
+ nextChar
+ end while_have_L_or_I ;
+ % there can be at most one L and at most 1 I %
+ ok := ( LCount < 2 and ICount < 2 )
+ end if_ok_and_isReal ;
+
+ % must now be at the end if the number %
+ ok := ok and charPos >= maxChar
+
+ end if_ok ;
+
+ ok
+ end isNumeric ;
+
+
+ % test the isNumeric procedure %
+ procedure testIsNumeric( string(32) value n
+ ; logical value expectedResult
+ ) ;
+ begin
+ logical actualResult;
+ actualResult := isNumeric( n );
+ write( s_w := 0
+ , """", n, """ is "
+ , if actualResult then "" else "not "
+ , "numeric "
+ , if actualResult = expectedResult then "" else " NOT "
+ , "as expected"
+ )
+ end testIsNumeric ;
+
+
+ testIsNumeric( "", false );
+ testIsNumeric( "b", false );
+ testIsNumeric( ".", false );
+ testIsNumeric( ".'3", false );
+ testIsNumeric( "3.'", false );
+ testIsNumeric( "0.0z44", false );
+ testIsNumeric( "-1IL", false );
+ testIsNumeric( "4.5'23ILL", false );
+
+ write( "---------" );
+
+ testIsNumeric( "-1", true );
+ testIsNumeric( " +.345", true );
+ testIsNumeric( "4.5'23I", true );
+ testIsNumeric( "-5'+3i", true );
+ testIsNumeric( "-5'-3l", true );
+ testIsNumeric( " -.345LI", true );
+
+end.
diff --git a/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir b/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir
new file mode 100644
index 0000000000..a7381f48a5
--- /dev/null
+++ b/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir
@@ -0,0 +1,14 @@
+defmodule RC do
+ def is_numeric(str) do
+ case Float.parse(str) do
+ {_num, ""} -> true
+ {_num, _r} -> false # _r : remainder_of_bianry
+ :error -> false
+ end
+ end
+end
+
+strs = ["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"]
+Enum.each(strs, fn str ->
+ IO.puts "#{inspect str}\t=> #{RC.is_numeric(str)}"
+end)
diff --git a/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia b/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia
new file mode 100644
index 0000000000..71cc34b1a8
--- /dev/null
+++ b/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia
@@ -0,0 +1,23 @@
+function isnumeric{T<:String}(s::T)
+ isa(parse(s), Number)
+end
+
+tests = ["1",
+ "-121",
+ "one",
+ "pi",
+ "1 + 1",
+ "NaN",
+ "1234567890123456789",
+ "1234567890123456789123456789",
+ "1234567890123456789123456789.0",
+ "1.3",
+ "1.4e10",
+ "Inf",
+ "1//2",
+ "1.0 + 1.0im"]
+
+for t in tests
+ fl = isnumeric(t) ? "is" : "is not"
+ println(@sprintf(" %35s %s a direct numeric literal.", t, fl))
+end
diff --git a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6
index e7109f928d..34b7c53825 100644
--- a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6
+++ b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6
@@ -1,4 +1,4 @@
-my $name = $*PROGRAM_NAME;
+my $name = $*PROGRAM-NAME;
my $pid = $*PID;
my $lockdir = "/tmp";
diff --git a/Task/Determine-if-only-one-instance-is-running/REXX/determine-if-only-one-instance-is-running.rexx b/Task/Determine-if-only-one-instance-is-running/REXX/determine-if-only-one-instance-is-running.rexx
new file mode 100644
index 0000000000..9d924d919e
--- /dev/null
+++ b/Task/Determine-if-only-one-instance-is-running/REXX/determine-if-only-one-instance-is-running.rexx
@@ -0,0 +1,18 @@
+/* Simple ARexx program to open a port after checking if it's already open */
+IF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */
+ SAY 'This program may only be run in a single instance at a time.'
+ EXIT 5 /* Exit with a mild warning */
+ END
+ /* Open rexxsupport.library so that ports can be opened */
+IF ~Show('LIBRARIES','rexxsupport.library')
+ THEN CALL AddLib('rexxsupport.library',0,-30,0)
+
+IF ~OpenPort('ROSETTA') THEN EXIT 10 /* Open port, end if it fails */
+
+SAY 'Program is now running.'
+
+DO FOREVER /* Busyloop */
+ /* Program stuff here */
+ END
+
+EXIT 0
diff --git a/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir b/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir
new file mode 100644
index 0000000000..8e459c0f19
--- /dev/null
+++ b/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir
@@ -0,0 +1,37 @@
+defmodule Digital do
+ def mdroot(n), do: mdroot(n, 0)
+
+ defp mdroot(n, persist) when n < 10, do: {n, persist}
+ defp mdroot(n, persist), do: mdroot(product(n, 1), persist+1)
+
+ defp product(0, prod), do: prod
+ defp product(n, prod), do: product(div(n, 10), prod*rem(n, 10))
+
+ def task1(data) do
+ IO.puts "Number: MDR MP\n====== === =="
+ Enum.each(data, fn n ->
+ {mdr, persist} = mdroot(n)
+ :io.format "~6w: ~w ~2w~n", [n, mdr, persist]
+ end)
+ end
+
+ def task2(m \\ 5) do
+ IO.puts "\nMDR: [n0..n#{m-1}]\n=== ========"
+ map = add_map(0, m, Map.new)
+ Enum.each(0..9, fn i ->
+ first = map[i] |> Enum.reverse |> Enum.take(m)
+ IO.puts " #{i}: #{inspect first}"
+ end)
+ end
+
+ defp add_map(n, m, map) do
+ {mdr, _persist} = mdroot(n)
+ new_map = Dict.update(map, mdr, [n], fn vals -> [n | vals] end)
+ min_len = Dict.values(new_map) |> Enum.map(&length(&1)) |> Enum.min
+ if min_len < m, do: add_map(n+1, m, new_map),
+ else: new_map
+ end
+end
+
+Digital.task1([123321, 7739, 893, 899998])
+Digital.task2(5)
diff --git a/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia
new file mode 100644
index 0000000000..ae124d8ad9
--- /dev/null
+++ b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia
@@ -0,0 +1,10 @@
+function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10)
+ -1 < n && 1 < bs || throw(DomainError())
+ ds = n
+ pers = 0
+ while bs <= ds
+ ds = prod(digits(ds, bs))
+ pers += 1
+ end
+ return (pers, ds)
+end
diff --git a/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia
new file mode 100644
index 0000000000..98a205d2f9
--- /dev/null
+++ b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia
@@ -0,0 +1,34 @@
+const bs = 10
+const excnt = 5
+
+println("Testing Multiplicative Digital Root.\n")
+for i in [123321, 7739, 893, 899998]
+ (pers, ds) = digitalmultroot(i, bs)
+ print(@sprintf("%8d", i))
+ print(" has persistence ", pers)
+ println(" and digital root ", ds)
+end
+
+dmr = zeros(Int, bs, excnt)
+hasroom = trues(bs)
+dex = ones(Int, bs)
+
+i = 0
+while any(hasroom)
+ (pers, ds) = digitalmultroot(i, bs)
+ ds += 1
+ if hasroom[ds]
+ dmr[ds, dex[ds]] = i
+ dex[ds] += 1
+ if dex[ds] > excnt
+ hasroom[ds] = false
+ end
+ end
+ i += 1
+end
+
+println("\n MDR: First ", excnt, " numbers having this MDR")
+for (i, d) in enumerate(0:(bs-1))
+ print(@sprintf("%4d: ", d))
+ println(join([@sprintf("%6d", dmr[i, j]) for j in 1:excnt], ","))
+end
diff --git a/Task/Digital-root/ALGOL-W/digital-root.alg b/Task/Digital-root/ALGOL-W/digital-root.alg
new file mode 100644
index 0000000000..4ecfc22151
--- /dev/null
+++ b/Task/Digital-root/ALGOL-W/digital-root.alg
@@ -0,0 +1,63 @@
+begin
+
+ % calculates the digital root and persistence of an integer in base 10 %
+ % in order to allow for numbers larger than 2^31, the number is passed %
+ % as the lower and upper digits e.g. 393900588225 can be processed by %
+ % specifying upper = 393900, lower = 58825 %
+ procedure findDigitalRoot( integer value upper, lower
+ ; integer result digitalRoot, persistence
+ ) ;
+ begin
+
+ integer procedure sumDigits( integer value n ) ;
+ begin
+ integer digits, sum;
+
+ digits := abs n;
+ sum := 0;
+
+ while digits > 0
+ do begin
+ sum := sum + ( digits rem 10 );
+ digits := digits div 10
+ end % while digits > 0 % ;
+
+ % result: % sum
+ end sumDigits;
+
+ digitalRoot := sumDigits( upper ) + sumDigits( lower );
+ persistence := 1;
+
+ while digitalRoot > 9
+ do begin
+ persistence := persistence + 1;
+ digitalRoot := sumDigits( digitalRoot );
+ end % while digitalRoot > 9 % ;
+
+ end findDigitalRoot ;
+
+ % calculates and prints the digital root and persistence %
+ procedure printDigitalRootAndPersistence( integer value upper, lower ) ;
+ begin
+ integer digitalRoot, persistence;
+ findDigitalRoot( upper, lower, digitalRoot, persistence );
+ write( s_w := 0 % set field saeparator width for this statement %
+ , i_w := 8 % set integer field width for this statement %
+ , upper
+ , ", "
+ , lower
+ , i_w := 2 % change integer field width %
+ , ": digital root: "
+ , digitalRoot
+ , ", persistence: "
+ , persistence
+ )
+ end printDigitalRootAndPersistence ;
+
+ % test the digital root and persistence procedures %
+ printDigitalRootAndPersistence( 0, 627615 );
+ printDigitalRootAndPersistence( 0, 39390 );
+ printDigitalRootAndPersistence( 0, 588225 );
+ printDigitalRootAndPersistence( 393900, 588225 )
+
+end.
diff --git a/Task/Digital-root/Batch-File/digital-root.bat b/Task/Digital-root/Batch-File/digital-root.bat
new file mode 100644
index 0000000000..0b4075a2c0
--- /dev/null
+++ b/Task/Digital-root/Batch-File/digital-root.bat
@@ -0,0 +1,44 @@
+::
+::Digital Root Task from Rosetta Code Wiki
+::Batch File Implementation
+::
+::Base 10...
+::
+
+@echo off
+setlocal enabledelayedexpansion
+
+::THE MAIN THING...
+for %%x in (9876543214 393900588225 1985989328582 34559) do (
+ call :droot %%x
+)
+echo.
+pause
+exit /b
+::/THE MAIN THING...
+
+::THE FUNCTION
+:droot
+set inp2sum=%1&set persist=1
+
+:cyc1
+set sum=0
+set scan_digit=0
+:cyc2
+set digit=!inp2sum:~%scan_digit%,1!
+if "%digit%"=="" (goto :sumdone)
+set /a sum+=%digit%
+set /a scan_digit+=1
+goto :cyc2
+
+:sumdone
+if %sum% lss 10 (
+ echo.
+ echo ^(%1^)
+ echo Additive Persistence=%persist% Digital Root=%sum%.
+ goto :EOF
+)
+set /a persist+=1
+set inp2sum=%sum%
+goto :cyc1
+::/THE FUNCTION
diff --git a/Task/Digital-root/Befunge/digital-root.bf b/Task/Digital-root/Befunge/digital-root.bf
new file mode 100644
index 0000000000..c5d7ec77ab
--- /dev/null
+++ b/Task/Digital-root/Befunge/digital-root.bf
@@ -0,0 +1,8 @@
+0" :rebmun retnE">:#,_0 0v
+v\1:/+55p00:55+%00g+^>9`+#v_+\ 1+\^
+>|`9:p000<_v#`1\$< v"gi"<
+|> \ 1 + \ >0" :toor lat"^
+>$$00g\1+^@,+#+ 5<
+>:#,_$ . 5 5 ^>:#,_\.55+,v
+^"Additive Persistence: "<
diff --git a/Task/Digital-root/DCL/digital-root.dcl b/Task/Digital-root/DCL/digital-root.dcl
new file mode 100644
index 0000000000..df6205cd9b
--- /dev/null
+++ b/Task/Digital-root/DCL/digital-root.dcl
@@ -0,0 +1,18 @@
+$ x = p1
+$ count = 0
+$ sum = x
+$ loop1:
+$ length = f$length( x )
+$ if length .eq. 1 then $ goto done
+$ i = 0
+$ sum = 0
+$ loop2:
+$ digit = f$extract( i, 1, x )
+$ sum = sum + digit
+$ i = i + 1
+$ if i .lt. length then $ goto loop2
+$ x = f$string( sum )
+$ count = count + 1
+$ goto loop1
+$ done:
+$ write sys$output p1, " has additive persistence ", count, " and digital root of ", sum
diff --git a/Task/Digital-root/Elixir/digital-root.elixir b/Task/Digital-root/Elixir/digital-root.elixir
new file mode 100644
index 0000000000..5937d61023
--- /dev/null
+++ b/Task/Digital-root/Elixir/digital-root.elixir
@@ -0,0 +1,25 @@
+defmodule Digital do
+ def root(n, base \\ 10), do: root(n, base, 0)
+
+ def root(n, base, ap) when n < base, do: {n, ap}
+ def root(n, base, ap) do
+ Integer.to_string(n, base)
+ |> String.codepoints
+ |> Enum.reduce(0, fn x,acc -> acc + String.to_integer(x, base) end)
+ |> root(base, ap+1)
+ end
+end
+
+data = [627615, 39390, 588225, 393900588225]
+Enum.each(data, fn n ->
+ {dr, ap} = Digital.root(n)
+ IO.puts "#{n} has additive persistence #{ap} and digital root of #{dr}"
+end)
+
+base = 16
+IO.puts "\nBase = #{base}"
+fmt = "~.#{base}B(#{base}) has additive persistence ~w and digital root of ~w~n"
+Enum.each(data, fn n ->
+ {dr, ap} = Digital.root(n, base)
+ :io.format fmt, [n, ap, dr]
+end)
diff --git a/Task/Digital-root/Julia/digital-root.julia b/Task/Digital-root/Julia/digital-root.julia
new file mode 100644
index 0000000000..fcb5e22b15
--- /dev/null
+++ b/Task/Digital-root/Julia/digital-root.julia
@@ -0,0 +1,15 @@
+function digitalroot{S<:Integer,T<:Integer}(n::S, bs::T=10)
+ -1 < n && 1 < bs || throw(DomainError())
+ ds = n
+ pers = 0
+ while bs <= ds
+ ds = sum(digits(ds, bs))
+ pers += 1
+ end
+ return (pers, ds)
+end
+
+for i in {627615, 39390, 588225, 393900588225, big(2)^100}
+ (pers, ds) = digitalroot(i)
+ println(i, " has persistence ", pers, " and digital root ", ds)
+end
diff --git a/Task/Digital-root/Python/digital-root.py b/Task/Digital-root/Python/digital-root.py
index 53491cb521..1e12753de0 100644
--- a/Task/Digital-root/Python/digital-root.py
+++ b/Task/Digital-root/Python/digital-root.py
@@ -1,10 +1,13 @@
-def droot (n):
- x = [n]
- while x[-1] > 10:
- x.append(sum(int(dig) for dig in str(x[-1])))
- return len(x) - 1, x[-1]
+def digital_root (n):
+ ap = 0
+ n = abs(int(n))
+ while n >= 10:
+ n = sum(int(digit) for digit in str(n))
+ ap += 1
+ return ap, n
-for n in [627615, 39390, 588225, 393900588225]:
- a, d = droot (n)
- print "%12i has additive persistance %2i and digital root of %i" % (
- n, a, d)
+if __name__ == '__main__':
+ for n in [627615, 39390, 588225, 393900588225, 55]:
+ persistance, root = digital_root(n)
+ print("%12i has additive persistance %2i and digital root %i."
+ % (n, persistance, root))
diff --git a/Task/Digital-root/VBScript/digital-root.vb b/Task/Digital-root/VBScript/digital-root.vb
new file mode 100644
index 0000000000..11eb475c91
--- /dev/null
+++ b/Task/Digital-root/VBScript/digital-root.vb
@@ -0,0 +1,15 @@
+Function digital_root(n)
+ ap = 0
+ Do Until Len(n) = 1
+ x = 0
+ For i = 1 To Len(n)
+ x = x + CInt(Mid(n,i,1))
+ Next
+ n = x
+ ap = ap + 1
+ Loop
+ digital_root = "Additive Persistence = " & ap & vbCrLf &_
+ "Digital Root = " & n & vbCrLf
+End Function
+
+WScript.StdOut.Write digital_root(WScript.Arguments(0))
diff --git a/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION b/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION
index 5248139f09..27764ac02c 100644
--- a/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION
+++ b/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION
@@ -1,5 +1,5 @@
{{omit from|GUISS}}
-The task is to '''solve Dinesman's multiple dwelling [http://www-mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3.2 problem] but in a way that most naturally follows the problem statement given below'''.
+The task is to '''solve Dinesman's multiple dwelling [http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3.2 problem] but in a way that most naturally follows the problem statement given below'''.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
diff --git a/Task/Dinesmans-multiple-dwelling-problem/Elixir/dinesmans-multiple-dwelling-problem.elixir b/Task/Dinesmans-multiple-dwelling-problem/Elixir/dinesmans-multiple-dwelling-problem.elixir
new file mode 100644
index 0000000000..58d1bd541e
--- /dev/null
+++ b/Task/Dinesmans-multiple-dwelling-problem/Elixir/dinesmans-multiple-dwelling-problem.elixir
@@ -0,0 +1,27 @@
+defmodule Dinesman do
+ def problem do
+ names = ~w( Baker Cooper Fletcher Miller Smith )a
+ predicates = [fn(c)-> :Baker != List.last(c) end,
+ fn(c)-> :Cooper != List.first(c) end,
+ fn(c)-> :Fletcher != List.first(c) && :Fletcher != List.last(c) end,
+ fn(c)-> floor(c, :Miller) > floor(c, :Cooper) end,
+ fn(c)-> abs(floor(c, :Smith) - floor(c, :Fletcher)) != 1 end,
+ fn(c)-> abs(floor(c, :Cooper) - floor(c, :Fletcher)) != 1 end]
+
+ permutation(names)
+ |> Enum.filter(fn candidate ->
+ Enum.all?(predicates, fn predicate -> predicate.(candidate) end)
+ end)
+ |> Enum.each(fn name_list ->
+ Enum.with_index(name_list)
+ |> Enum.each(fn {name,i} -> IO.puts "#{name} lives on #{i+1}" end)
+ end)
+ end
+
+ defp floor(c, name), do: Enum.find_index(c, fn x -> x == name end)
+
+ defp permutation([]), do: [[]]
+ defp permutation(list), do: (for x <- list, y <- permutation(list -- [x]), do: [x|y])
+end
+
+Dinesman.problem
diff --git a/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh b/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh
index 2703a33864..d693852ba8 100644
--- a/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh
+++ b/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh
@@ -1,15 +1,21 @@
#!/bin/bash
+# NAMES is a list of names. It can be changed as needed. It can be more than five names, or less.
NAMES=(Baker Cooper Fletcher Miller Smith)
+# CRITERIA are the rules imposed on who lives where. Each criterion must be a valid bash expression
+# that will be evaluated. TOP is the top floor; BOTTOM is the bottom floor.
+
+# The CRITERIA can be changed to create different rules.
+
CRITERIA=(
- 'Baker != TOP'
- 'Cooper != BOTTOM'
- 'Fletcher != TOP'
- 'Fletcher != BOTTOM'
- 'Miller > Cooper'
- '$(abs $(( Smith - Fletcher )) ) > 1'
- '$(abs $(( Fletcher - Cooper )) ) > 1'
+ 'Baker != TOP' # Baker does not live on the top floor
+ 'Cooper != BOTTOM' # Cooper does not live on the bottom floor
+ 'Fletcher != TOP' # Fletcher does not live on the top floor
+ 'Fletcher != BOTTOM' # and Fletch also does not live on the bottom floor
+ 'Miller > Cooper' # Miller lives above Cooper
+ '$(abs $(( Smith - Fletcher )) ) > 1' # Smith and Fletcher are not on adjacent floors
+ '$(abs $(( Fletcher - Cooper )) ) > 1' # Fletcher and Cooper are not on adjacent floors
)
# Code below here shouldn't need to change to vary parameters
@@ -17,11 +23,7 @@ let BOTTOM=0
let TOP=${#NAMES[@]}-1
# Not available as a builtin
-function abs {
- let n=$1
- if (( n < 0 )); then let n=-n; fi
- echo "$n"
-}
+abs() { local n=$(( 10#$1 )) ; echo $(( n < 0 ? -n : n )) ; }
# Algorithm we use to iterate over the permutations
# requires that we start with the array sorted lexically
diff --git a/Task/Dining-philosophers/C++/dining-philosophers.cpp b/Task/Dining-philosophers/C++/dining-philosophers-1.cpp
similarity index 100%
rename from Task/Dining-philosophers/C++/dining-philosophers.cpp
rename to Task/Dining-philosophers/C++/dining-philosophers-1.cpp
diff --git a/Task/Dining-philosophers/C++/dining-philosophers-2.cpp b/Task/Dining-philosophers/C++/dining-philosophers-2.cpp
new file mode 100644
index 0000000000..12abd43ac3
--- /dev/null
+++ b/Task/Dining-philosophers/C++/dining-philosophers-2.cpp
@@ -0,0 +1,129 @@
+#include
+#include
+#include
+#include
+//We are using only standard library, so snprintf instead of Boost::Format
+#include
+#include
+#include
+#include
+#include
+#include