Count the coins: Difference between revisions
Content added Content deleted
(Applesoft BASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 34: | Line 34: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F changes(amount, coins) |
||
V ways = [Int64(0)] * (amount + 1) |
V ways = [Int64(0)] * (amount + 1) |
||
ways[0] = 1 |
ways[0] = 1 |
||
Line 43: | Line 43: | ||
print(changes(100, [1, 5, 10, 25])) |
print(changes(100, [1, 5, 10, 25])) |
||
print(changes(100000, [1, 5, 10, 25, 50, 100]))</ |
print(changes(100000, [1, 5, 10, 25, 50, 100]))</syntaxhighlight> |
||
Output: |
Output: |
||
Line 53: | Line 53: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
{{trans|AWK}} |
{{trans|AWK}} |
||
< |
<syntaxhighlight lang="360asm">* count the coins 04/09/2015 |
||
COINS CSECT |
COINS CSECT |
||
USING COINS,R12 |
USING COINS,R12 |
||
Line 111: | Line 111: | ||
PG DS CL12 |
PG DS CL12 |
||
YREGS |
YREGS |
||
END COINS</ |
END COINS</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 121: | Line 121: | ||
{{Works with|gnat/gcc}} |
{{Works with|gnat/gcc}} |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Count_The_Coins is |
procedure Count_The_Coins is |
||
Line 152: | Line 152: | ||
Print(Count( 1_00, (25, 10, 5, 1))); |
Print(Count( 1_00, (25, 10, 5, 1))); |
||
Print(Count(1000_00, (100, 50, 25, 10, 5, 1))); |
Print(Count(1000_00, (100, 50, 25, 10, 5, 1))); |
||
end Count_The_Coins;</ |
end Count_The_Coins;</syntaxhighlight> |
||
Output:<pre> 242 |
Output:<pre> 242 |
||
Line 160: | Line 160: | ||
{{works with|ALGOL 68G|Any - tested with release 2.4.1}} |
{{works with|ALGOL 68G|Any - tested with release 2.4.1}} |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
<syntaxhighlight lang="algol68"> |
|||
<lang Algol68> |
|||
# |
# |
||
Rosetta Code "Count the coins" |
Rosetta Code "Count the coins" |
||
Line 192: | Line 192: | ||
print((ways to make change(denoms, 100), newline)) |
print((ways to make change(denoms, 100), newline)) |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output:<pre> |
Output:<pre> |
||
+242 |
+242 |
||
Line 198: | Line 198: | ||
{{works with|ALGOL 68G|Any - tested with release 2.8.4}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.4}} |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
<syntaxhighlight lang="algol68"> |
|||
<lang Algol68> |
|||
# |
# |
||
Rosetta Code "Count the coins" |
Rosetta Code "Count the coins" |
||
Line 231: | Line 231: | ||
print((ways to make change((1, 5, 10, 25, 50, 100), 100000), newline)) |
print((ways to make change((1, 5, 10, 25, 50, 100), 100000), newline)) |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output:<pre> |
Output:<pre> |
||
+242 |
+242 |
||
Line 242: | Line 242: | ||
{{trans|Phix}} |
{{trans|Phix}} |
||
< |
<syntaxhighlight lang="applescript">-- All input values must be integers and multiples of the same monetary unit. |
||
on countCoins(amount, denominations) |
on countCoins(amount, denominations) |
||
-- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros. |
-- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros. |
||
Line 271: | Line 271: | ||
set c1 to countCoins(100, {25, 10, 5, 1}) |
set c1 to countCoins(100, {25, 10, 5, 1}) |
||
set c2 to countCoins(1000 * 100, {100, 50, 25, 10, 5, 1}) |
set c2 to countCoins(1000 * 100, {100, 50, 25, 10, 5, 1}) |
||
return {c1, c2}</ |
return {c1, c2}</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<lang |
<syntaxhighlight lang="applescript">{242, 13398445413854501}</syntaxhighlight> |
||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
{{trans|Commodore BASIC}} |
{{trans|Commodore BASIC}} |
||
< |
<syntaxhighlight lang="gwbasic">C=0:M=100:F=25:T=10:S=5:Q=INT(M/F):FORI=0TOQ:D=INT((M-I*F)/T):FORJ=0TOD:N=INT((M-J*T)/S):FORK=0TON:P=M-K*S:FORL=0TOPSTEPS:C=C+(L+K*S+J*T+I*F=M):NEXTL,K,J,I:?C;</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">changes: function [amount coins][ |
||
ways: map 0..amount+1 [x]-> 0 |
ways: map 0..amount+1 [x]-> 0 |
||
ways\0: 1 |
ways\0: 1 |
||
Line 293: | Line 293: | ||
print changes 100 [1 5 10 25] |
print changes 100 [1 5 10 25] |
||
print changes 100000 [1 5 10 25 50 100]</ |
print changes 100000 [1 5 10 25 50 100]</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
{{Works with|AutoHotkey_L}} |
{{Works with|AutoHotkey_L}} |
||
< |
<syntaxhighlight lang="ahk">countChange(amount){ |
||
return cc(amount, 4) |
return cc(amount, 4) |
||
} |
} |
||
Line 314: | Line 314: | ||
return [1, 5, 10, 25][kindsOfCoins] |
return [1, 5, 10, 25][kindsOfCoins] |
||
} |
} |
||
MsgBox % countChange(100)</ |
MsgBox % countChange(100)</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 320: | Line 320: | ||
Iterative implementation, derived from Run BASIC: |
Iterative implementation, derived from Run BASIC: |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
BEGIN { |
BEGIN { |
||
Line 346: | Line 346: | ||
return count; |
return count; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Run time: |
Run time: |
||
Line 358: | Line 358: | ||
Recursive implementation (derived from Scheme example): |
Recursive implementation (derived from Scheme example): |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
BEGIN { |
BEGIN { |
||
Line 385: | Line 385: | ||
return koins[1] |
return koins[1] |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Run time: |
Run time: |
||
Line 399: | Line 399: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
Non-recursive solution: |
Non-recursive solution: |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM uscoins%(3) |
||
uscoins%() = 1, 5, 10, 25 |
uscoins%() = 1, 5, 10, 25 |
||
PRINT FNchange(100, uscoins%()) " ways of making $1" |
PRINT FNchange(100, uscoins%()) " ways of making $1" |
||
Line 435: | Line 435: | ||
NEXT |
NEXT |
||
= table(P%-1) |
= table(P%-1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output (BBC BASIC does not have large enough integers for the optional task): |
Output (BBC BASIC does not have large enough integers for the optional task): |
||
<pre> 242 ways of making $1 |
<pre> 242 ways of making $1 |
||
Line 444: | Line 444: | ||
=={{header|C}}== |
=={{header|C}}== |
||
Using some crude 128-bit integer type. |
Using some crude 128-bit integer type. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <stdint.h> |
#include <stdint.h> |
||
Line 543: | Line 543: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight>output (only the first two lines are required by task):<syntaxhighlight lang="text">242 |
||
13398445413854501 |
13398445413854501 |
||
1333983445341383545001 |
1333983445341383545001 |
||
Line 551: | Line 551: | ||
10056050940818192726001 |
10056050940818192726001 |
||
99341140660285639188927260001 |
99341140660285639188927260001 |
||
992198221207406412424859964272600001</ |
992198221207406412424859964272600001</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp"> |
||
// Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ |
// Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ |
||
class Program |
class Program |
||
Line 576: | Line 576: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <iostream> |
#include <iostream> |
||
#include <stack> |
#include <stack> |
||
Line 613: | Line 613: | ||
std::cout << ways << std::endl; |
std::cout << ways << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 619: | Line 619: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(def denomination-kind [1 5 10 25]) |
||
(defn- cc [amount denominations] |
(defn- cc [amount denominations] |
||
Line 632: | Line 632: | ||
(cc amount denominations)) |
(cc amount denominations)) |
||
(count-change 15 denomination-kind) ; = 6 </ |
(count-change 15 denomination-kind) ; = 6 </syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="cobol"> |
||
identification division. |
identification division. |
||
program-id. CountCoins. |
program-id. CountCoins. |
||
Line 668: | Line 668: | ||
end-perform |
end-perform |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>242</pre> |
<pre>242</pre> |
||
Line 676: | Line 676: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="coco">changes = (amount, coins) -> |
||
ways = [1].concat [0] * amount |
ways = [1].concat [0] * amount |
||
for coin of coins |
for coin of coins |
||
Line 683: | Line 683: | ||
ways[amount] |
ways[amount] |
||
console.log changes 100, [1 5 10 25]</ |
console.log changes 100, [1 5 10 25]</syntaxhighlight> |
||
=={{header|Commodore BASIC}}== |
=={{header|Commodore BASIC}}== |
||
Line 698: | Line 698: | ||
< |
<syntaxhighlight lang="gwbasic">5 m=100:rem money = $1.00 or 100 pennies. |
||
10 print chr$(147);chr$(14);"This program will calculate the number" |
10 print chr$(147);chr$(14);"This program will calculate the number" |
||
11 print "of combinations of 'change' that can be" |
11 print "of combinations of 'change' that can be" |
||
Line 724: | Line 724: | ||
265 print left$(en$,2);":";mid$(en$,3,2);":";right$(en$,2);"." |
265 print left$(en$,2);":";mid$(en$,3,2);":";right$(en$,2);"." |
||
270 end |
270 end |
||
1000 print count;tab(6);pc;tab(11);nc;tab(16);dc;tab(21);qc:return</ |
1000 print count;tab(6);pc;tab(11);nc;tab(16);dc;tab(21);qc:return</syntaxhighlight> |
||
'''Example 2:''' Commodore 64 with Screen Blanking |
'''Example 2:''' Commodore 64 with Screen Blanking |
||
Line 732: | Line 732: | ||
Enabling screen blanking (and therefore not printing each result) results in a total time of 1:44. |
Enabling screen blanking (and therefore not printing each result) results in a total time of 1:44. |
||
< |
<syntaxhighlight lang="gwbasic">145 if not yn then poke 53265,peek(53265) and 239 |
||
245 en$=ti$:if not yn then poke 53265,peek(53265) or 16</ |
245 en$=ti$:if not yn then poke 53265,peek(53265) or 16</syntaxhighlight> |
||
'''Example 3:''' Commodore 128 with VIC-II blanking, 2MHz fast mode. |
'''Example 3:''' Commodore 128 with VIC-II blanking, 2MHz fast mode. |
||
Line 739: | Line 739: | ||
Similar to above, however the Commodore 128 is capable of using a faster clock speed at the expense of any VIC-II graphics display. Timed result is 1:18. Add/change the following lines on the Commodore 128: |
Similar to above, however the Commodore 128 is capable of using a faster clock speed at the expense of any VIC-II graphics display. Timed result is 1:18. Add/change the following lines on the Commodore 128: |
||
< |
<syntaxhighlight lang="gwbasic">145 if not yn then fast |
||
245 en$=ti$:if not yn then slow</ |
245 en$=ti$:if not yn then slow</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
===Recursive Version With Cache=== |
===Recursive Version With Cache=== |
||
< |
<syntaxhighlight lang="lisp">(defun count-change (amount coins |
||
&optional |
&optional |
||
(length (1- (length coins))) |
(length (1- (length coins))) |
||
Line 761: | Line 761: | ||
(print (count-change 100 '(25 10 5 1))) ; = 242 |
(print (count-change 100 '(25 10 5 1))) ; = 242 |
||
(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501 |
(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501 |
||
(terpri)</ |
(terpri)</syntaxhighlight> |
||
===Iterative Version=== |
===Iterative Version=== |
||
< |
<syntaxhighlight lang="lisp">(defun count-change (amount coins &aux (ways (make-array (1+ amount) :initial-element 0))) |
||
(setf (aref ways 0) 1) |
(setf (aref ways 0) 1) |
||
(loop for coin in coins do |
(loop for coin in coins do |
||
(loop for j from coin upto amount |
(loop for j from coin upto amount |
||
do (incf (aref ways j) (aref ways (- j coin))))) |
do (incf (aref ways j) (aref ways (- j coin))))) |
||
(aref ways amount))</ |
(aref ways amount))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
===Basic Version=== |
===Basic Version=== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.bigint; |
||
auto changes(int amount, int[] coins) { |
auto changes(int amount, int[] coins) { |
||
Line 788: | Line 788: | ||
changes( 1_00, [25, 10, 5, 1]).writeln; |
changes( 1_00, [25, 10, 5, 1]).writeln; |
||
changes(1000_00, [100, 50, 25, 10, 5, 1]).writeln; |
changes(1000_00, [100, 50, 25, 10, 5, 1]).writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>242 |
<pre>242 |
||
Line 795: | Line 795: | ||
===Safe Ulong Version=== |
===Safe Ulong Version=== |
||
This version is very similar to the precedent, but it uses a faster ulong type, and performs a checked sum to detect overflows at run-time. |
This version is very similar to the precedent, but it uses a faster ulong type, and performs a checked sum to detect overflows at run-time. |
||
< |
<syntaxhighlight lang="d">import std.stdio, core.checkedint; |
||
auto changes(int amount, int[] coins, ref bool overflow) { |
auto changes(int amount, int[] coins, ref bool overflow) { |
||
Line 815: | Line 815: | ||
if (overflow) |
if (overflow) |
||
"Overflow".puts; |
"Overflow".puts; |
||
}</ |
}</syntaxhighlight> |
||
The output is the same. |
The output is the same. |
||
===Faster Version=== |
===Faster Version=== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.bigint; |
||
BigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ { |
BigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ { |
||
Line 861: | Line 861: | ||
writeln; |
writeln; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>242 |
<pre>242 |
||
Line 876: | Line 876: | ||
A much faster version that mixes high-level and low-level style programming. This version uses basic 128-bit unsigned integers, like the C version. The output is the same as the second D version. |
A much faster version that mixes high-level and low-level style programming. This version uses basic 128-bit unsigned integers, like the C version. The output is the same as the second D version. |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.bigint, std.algorithm, std.conv, std.functional; |
||
struct Ucent { /// Simplified 128-bit integer (like ucent). |
struct Ucent { /// Simplified 128-bit integer (like ucent). |
||
Line 935: | Line 935: | ||
writeln; |
writeln; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Printing Version=== |
===Printing Version=== |
||
This version prints all the solutions (so it can be used on the smaller input): |
This version prints all the solutions (so it can be used on the smaller input): |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.conv, std.string, std.algorithm, std.range; |
||
void printChange(in uint tot, in uint[] coins) |
void printChange(in uint tot, in uint[] coins) |
||
Line 970: | Line 970: | ||
void main() { |
void main() { |
||
printChange(1_00, [1, 5, 10, 25]); |
printChange(1_00, [1, 5, 10, 25]); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1:5 5:1 10:4 25:2 |
<pre>1:5 5:1 10:4 25:2 |
||
Line 1,000: | Line 1,000: | ||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
Simple recursive version plus cached version using a map. |
Simple recursive version plus cached version using a map. |
||
<syntaxhighlight lang="dart"> |
|||
<lang Dart> |
|||
var cache = new Map(); |
var cache = new Map(); |
||
Line 1,056: | Line 1,056: | ||
return(count); |
return(count); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,065: | Line 1,065: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{Trans|C#}} |
{{Trans|C#}} |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Count_the_coins; |
program Count_the_coins; |
||
Line 1,095: | Line 1,095: | ||
Readln; |
Readln; |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">func countCoins(coins, n) { |
||
var xs = Array.Empty(n + 1, 0) |
var xs = Array.Empty(n + 1, 0) |
||
xs[0] = 1 |
xs[0] = 1 |
||
Line 1,112: | Line 1,112: | ||
var coins = [1, 5, 10, 25] |
var coins = [1, 5, 10, 25] |
||
print(countCoins(coins, 100))</ |
print(countCoins(coins, 100))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,120: | Line 1,120: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
Recursive solution using memoization, adapted from CommonLisp and Racket. |
Recursive solution using memoization, adapted from CommonLisp and Racket. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'compile) ;; for (compile) |
(lib 'compile) ;; for (compile) |
||
(lib 'bigint) ;; integer results > 32 bits |
(lib 'bigint) ;; integer results > 32 bits |
||
Line 1,141: | Line 1,141: | ||
(compile 'ways) ;; speed-up things |
(compile 'ways) ;; speed-up things |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define change '(25 10 5 1)) |
(define change '(25 10 5 1)) |
||
(define c-1 (list-tail change -1)) ;; pointer to (1) |
(define c-1 (list-tail change -1)) ;; pointer to (1) |
||
Line 1,176: | Line 1,176: | ||
→ 13398445413854501 |
→ 13398445413854501 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
Line 1,182: | Line 1,182: | ||
Note: When the table is initialized, not only must the first entry be set to 1, but the other entries must be set to 0. It seems that the C# and Delphi solutions rely on the compiler to do this. In other languages, it may need to be done by the program. |
Note: When the table is initialized, not only must the first entry be set to 1, but the other entries must be set to 0. It seems that the C# and Delphi solutions rely on the compiler to do this. In other languages, it may need to be done by the program. |
||
< |
<syntaxhighlight lang="edsac"> |
||
["Count the coins" problem for Rosetta Code.] |
["Count the coins" problem for Rosetta Code.] |
||
[EDSAC program, Initial Orders 2.] |
[EDSAC program, Initial Orders 2.] |
||
Line 1,337: | Line 1,337: | ||
E21Z [define entry point] |
E21Z [define entry point] |
||
PF [enter with acc = 0] |
PF [enter with acc = 0] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,347: | Line 1,347: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
Recursive Dynamic Programming solution in Elixir |
Recursive Dynamic Programming solution in Elixir |
||
< |
<syntaxhighlight lang="elixir">defmodule Coins do |
||
def find(coins,lim) do |
def find(coins,lim) do |
||
vals = Map.new(0..lim,&{&1,0}) |> Map.put(0,1) |
vals = Map.new(0..lim,&{&1,0}) |> Map.put(0,1) |
||
Line 1,370: | Line 1,370: | ||
Coins.find([1,5,10,25],100) |
Coins.find([1,5,10,25],100) |
||
Coins.find([1,5,10,25,50,100],100_000)</ |
Coins.find([1,5,10,25,50,100],100_000)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,379: | Line 1,379: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(coins). |
-module(coins). |
||
-compile(export_all). |
-compile(export_all). |
||
Line 1,411: | Line 1,411: | ||
A2 = 100000, C2 = [100, 50, 25, 10, 5, 1], |
A2 = 100000, C2 = [100, 50, 25, 10, 5, 1], |
||
print(A2,C2). |
print(A2,C2). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,422: | Line 1,422: | ||
{{trans|OCaml}} |
{{trans|OCaml}} |
||
<p>Forward iteration, which can also be seen in Scala.</p> |
<p>Forward iteration, which can also be seen in Scala.</p> |
||
< |
<syntaxhighlight lang="fsharp">let changes amount coins = |
||
let ways = Array.zeroCreate (amount + 1) |
let ways = Array.zeroCreate (amount + 1) |
||
ways.[0] <- 1L |
ways.[0] <- 1L |
||
Line 1,434: | Line 1,434: | ||
printfn "%d" (changes 100 [25; 10; 5; 1]); |
printfn "%d" (changes 100 [25; 10; 5; 1]); |
||
printfn "%d" (changes 100000 [100; 50; 25; 10; 5; 1]); |
printfn "%d" (changes 100000 [100; 50; 25; 10; 5; 1]); |
||
0</ |
0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>242 |
<pre>242 |
||
Line 1,440: | Line 1,440: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: combinators kernel locals math math.ranges sequences sets sorting ; |
||
IN: rosetta.coins |
IN: rosetta.coins |
||
Line 1,475: | Line 1,475: | ||
: make-change ( cents coins -- ways ) |
: make-change ( cents coins -- ways ) |
||
members [ ] inv-sort-with ! Sort coins in descending order. |
members [ ] inv-sort-with ! Sort coins in descending order. |
||
recursive-count ;</ |
recursive-count ;</syntaxhighlight> |
||
From the listener: |
From the listener: |
||
Line 1,488: | Line 1,488: | ||
One might make use of the rosetta-code.count-the-coins vocabulary as shown: |
One might make use of the rosetta-code.count-the-coins vocabulary as shown: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
IN: scratchpad [ 100000 { 1 5 10 25 50 100 } make-change . ] time |
IN: scratchpad [ 100000 { 1 5 10 25 50 100 } make-change . ] time |
||
13398445413854501 |
13398445413854501 |
||
Running time: 0.020869274 seconds |
Running time: 0.020869274 seconds |
||
</syntaxhighlight> |
|||
</lang> |
|||
For reference, the implementation is shown next. |
For reference, the implementation is shown next. |
||
<lang> |
<syntaxhighlight lang="text"> |
||
USING: arrays locals math math.ranges sequences sets sorting ; |
USING: arrays locals math math.ranges sequences sets sorting ; |
||
IN: rosetta-code.count-the-coins |
IN: rosetta-code.count-the-coins |
||
Line 1,515: | Line 1,515: | ||
: make-change ( cents coins -- ways ) |
: make-change ( cents coins -- ways ) |
||
members [ ] inv-sort-with (make-change) ; |
members [ ] inv-sort-with (make-change) ; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or one could implement the algorithm like described in http://www.cdn.geeksforgeeks.org/dynamic-programming-set-7-coin-change. |
Or one could implement the algorithm like described in http://www.cdn.geeksforgeeks.org/dynamic-programming-set-7-coin-change. |
||
< |
<syntaxhighlight lang="factor"> |
||
USE: math.ranges |
USE: math.ranges |
||
Line 1,538: | Line 1,538: | ||
13398445413854501 |
13398445413854501 |
||
Running time: 0.029163549 seconds |
Running time: 0.029163549 seconds |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">\ counting change (SICP section 1.2.2) |
||
: table create does> swap cells + @ ; |
: table create does> swap cells + @ ; |
||
Line 1,556: | Line 1,556: | ||
then then ; |
then then ; |
||
100 5 count-change .</ |
100 5 count-change .</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Translation from "Dynamic Programming Solution: Python version" on this webside [http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/] |
Translation from "Dynamic Programming Solution: Python version" on this webside [http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/] |
||
< |
<syntaxhighlight lang="freebasic">' version 09-10-2016 |
||
' compile with: fbc -s console |
' compile with: fbc -s console |
||
Line 1,625: | Line 1,625: | ||
Print : Print "hit any key to end program" |
Print : Print "hit any key to end program" |
||
Sleep |
Sleep |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,635: | Line 1,635: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic">include "NSLog.incl" |
||
void local fn Doit |
void local fn Doit |
||
Line 1,660: | Line 1,660: | ||
fn DoIt |
fn DoIt |
||
HandleEvents</ |
HandleEvents</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,677: | Line 1,677: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{trans|lisp}} |
{{trans|lisp}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,713: | Line 1,713: | ||
} |
} |
||
panic(kindsOfCoins) |
panic(kindsOfCoins) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,719: | Line 1,719: | ||
</pre> |
</pre> |
||
Alternative algorithm, practical for the optional task. |
Alternative algorithm, practical for the optional task. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,737: | Line 1,737: | ||
} |
} |
||
return ways[amount] |
return ways[amount] |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,746: | Line 1,746: | ||
{{trans|Go}} |
{{trans|Go}} |
||
Intuitive Recursive Solution: |
Intuitive Recursive Solution: |
||
< |
<syntaxhighlight lang="groovy">def ccR |
||
ccR = { BigInteger tot, List<BigInteger> coins -> |
ccR = { BigInteger tot, List<BigInteger> coins -> |
||
BigInteger n = coins.size() |
BigInteger n = coins.size() |
||
Line 1,758: | Line 1,758: | ||
ccR(tot - coins[0], coins) |
ccR(tot - coins[0], coins) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Fast Iterative Solution: |
Fast Iterative Solution: |
||
< |
<syntaxhighlight lang="groovy">def ccI = { BigInteger tot, List<BigInteger> coins -> |
||
List<BigInteger> ways = [0g] * (tot+1) |
List<BigInteger> ways = [0g] * (tot+1) |
||
ways[0] = 1g |
ways[0] = 1g |
||
Line 1,770: | Line 1,770: | ||
} |
} |
||
ways[tot] |
ways[tot] |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">println '\nBase:' |
||
[iterative: ccI, recursive: ccR].each { label, cc -> |
[iterative: ccI, recursive: ccR].each { label, cc -> |
||
print "${label} " |
print "${label} " |
||
Line 1,786: | Line 1,786: | ||
def ways = ccI(1000g * 100, [100g, 50g, 25g, 10g, 5g, 1g]) |
def ways = ccI(1000g * 100, [100g, 50g, 25g, 10g, 5g, 1g]) |
||
def elapsed = System.currentTimeMillis() - start |
def elapsed = System.currentTimeMillis() - start |
||
println ("answer: ${ways} elapsed: ${elapsed}ms")</ |
println ("answer: ${ways} elapsed: ${elapsed}ms")</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,798: | Line 1,798: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Naive implementation: |
Naive implementation: |
||
< |
<syntaxhighlight lang="haskell">count :: (Integral t, Integral a) => t -> [t] -> a |
||
count 0 _ = 1 |
count 0 _ = 1 |
||
count _ [] = 0 |
count _ [] = 0 |
||
Line 1,807: | Line 1,807: | ||
main :: IO () |
main :: IO () |
||
main = print (count 100 [1, 5, 10, 25])</ |
main = print (count 100 [1, 5, 10, 25])</syntaxhighlight> |
||
Much faster, probably harder to read, is to update results from bottom up: |
Much faster, probably harder to read, is to update results from bottom up: |
||
< |
<syntaxhighlight lang="haskell">count :: Integral a => [Int] -> [a] |
||
count = foldr addCoin (1 : repeat 0) |
count = foldr addCoin (1 : repeat 0) |
||
where |
where |
||
Line 1,820: | Line 1,820: | ||
main = do |
main = do |
||
print (count [25, 10, 5, 1] !! 100) |
print (count [25, 10, 5, 1] !! 100) |
||
print (count [100, 50, 25, 10, 5, 1] !! 10000)</ |
print (count [100, 50, 25, 10, 5, 1] !! 10000)</syntaxhighlight> |
||
Or equivalently, (reformulating slightly, and adding a further test): |
Or equivalently, (reformulating slightly, and adding a further test): |
||
< |
<syntaxhighlight lang="haskell">import Data.Function (fix) |
||
count |
count |
||
Line 1,845: | Line 1,845: | ||
, ([100, 50, 25, 10, 5, 1], 1000000) |
, ([100, 50, 25, 10, 5, 1], 1000000) |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>242 |
<pre>242 |
||
Line 1,852: | Line 1,852: | ||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
US_coins := [1, 5, 10, 25] |
US_coins := [1, 5, 10, 25] |
||
Line 1,870: | Line 1,870: | ||
every (s := "[ ") ||:= !L || " " |
every (s := "[ ") ||:= !L || " " |
||
return s || "]" |
return s || "]" |
||
end</ |
end</syntaxhighlight> |
||
This is a naive implementation and very slow. |
This is a naive implementation and very slow. |
||
{{improve|Icon|Needs a better algorithm.}} |
{{improve|Icon|Needs a better algorithm.}} |
||
< |
<syntaxhighlight lang="icon">procedure CountCoins(amt,coins) # very slow, recurse by coin value |
||
local count |
local count |
||
static S |
static S |
||
Line 1,892: | Line 1,892: | ||
return (amt ~= 0) | 1 |
return (amt ~= 0) | 1 |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Icon Programming Library}} |
{{libheader|Icon Programming Library}} |
||
Line 1,902: | Line 1,902: | ||
Another one: |
Another one: |
||
<syntaxhighlight lang="icon"> |
|||
<lang Icon> |
|||
# coin.icn |
# coin.icn |
||
# usage: coin value |
# usage: coin value |
||
Line 1,921: | Line 1,921: | ||
write(" coins in ", count(coins, money), " different ways.") |
write(" coins in ", count(coins, money), " different ways.") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,929: | Line 1,929: | ||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "Coins.bas" |
||
110 LET MONEY=100 |
110 LET MONEY=100 |
||
120 LET COUNT=0 |
120 LET COUNT=0 |
||
Line 1,946: | Line 1,946: | ||
270 NEXT |
270 NEXT |
||
280 NEXT |
280 NEXT |
||
290 PRINT COUNT;"different combinations found."</ |
290 PRINT COUNT;"different combinations found."</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,952: | Line 1,952: | ||
In this draft intermediate results are a two column array. The first column is tallies -- the number of ways we have for reaching the total represented in the second column, which is unallocated value (which we will assume are pennies). We will have one row for each different in-range value which can be represented using only nickles (0, 5, 10, ... 95, 100). |
In this draft intermediate results are a two column array. The first column is tallies -- the number of ways we have for reaching the total represented in the second column, which is unallocated value (which we will assume are pennies). We will have one row for each different in-range value which can be represented using only nickles (0, 5, 10, ... 95, 100). |
||
< |
<syntaxhighlight lang="j">merge=: ({:"1 (+/@:({."1),{:@{:)/. ])@; |
||
count=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@] |
count=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@] |
||
init=: (1 ,. ,.)^:(0=#@$) |
init=: (1 ,. ,.)^:(0=#@$) |
||
nsplits=: 0 { [: +/ [: (merge@:(count"1) init)/ }.@/:~@~.@,</ |
nsplits=: 0 { [: +/ [: (merge@:(count"1) init)/ }.@/:~@~.@,</syntaxhighlight> |
||
This implementation special cases the handling of pennies and assumes that the lowest coin value in the argument is 1. If I needed additional performance, I would next special case the handling of nickles/penny combinations... |
This implementation special cases the handling of pennies and assumes that the lowest coin value in the argument is 1. If I needed additional performance, I would next special case the handling of nickles/penny combinations... |
||
Line 1,961: | Line 1,961: | ||
Thus: |
Thus: |
||
< |
<syntaxhighlight lang="j"> 100 nsplits 1 5 10 25 |
||
242</ |
242</syntaxhighlight> |
||
And, on a 64 bit machine with sufficient memory: |
And, on a 64 bit machine with sufficient memory: |
||
< |
<syntaxhighlight lang="j"> 100000 nsplits 1 5 10 25 50 100 |
||
13398445413854501</ |
13398445413854501</syntaxhighlight> |
||
Warning: the above version can miss one when the largest coin is equal to the total value. |
Warning: the above version can miss one when the largest coin is equal to the total value. |
||
Line 1,973: | Line 1,973: | ||
For British viewers change from £10 using £10 £5 £2 £1 50p 20p 10p 5p 2p and 1p |
For British viewers change from £10 using £10 £5 £2 £1 50p 20p 10p 5p 2p and 1p |
||
< |
<syntaxhighlight lang="j"> init =: 4 : '(1+x)$1' |
||
length1 =: 4 : '1=#y' |
length1 =: 4 : '1=#y' |
||
f =: 4 : ',/ +/\ (-x) ]\ y' |
f =: 4 : ',/ +/\ (-x) ]\ y' |
||
Line 1,981: | Line 1,981: | ||
NB. this is a foldLeft once initialised the intermediate right arguments are arrays |
NB. this is a foldLeft once initialised the intermediate right arguments are arrays |
||
1000 f 500 f 200 f 100 f 50 f 20 f 10 f 5 f 2 f (1000 init 0)</ |
1000 f 500 f 200 f 100 f 50 f 20 f 10 f 5 f 2 f (1000 init 0)</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{trans|D}} |
{{trans|D}} |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
< |
<syntaxhighlight lang="java5">import java.util.Arrays; |
||
import java.math.BigInteger; |
import java.math.BigInteger; |
||
Line 2,031: | Line 2,031: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242 |
<pre>242 |
||
Line 2,049: | Line 2,049: | ||
Efficient iterative algorithm (cleverly calculates number of combinations without permuting them) |
Efficient iterative algorithm (cleverly calculates number of combinations without permuting them) |
||
< |
<syntaxhighlight lang="javascript">function countcoins(t, o) { |
||
'use strict'; |
'use strict'; |
||
var targetsLength = t + 1; |
var targetsLength = t + 1; |
||
Line 2,067: | Line 2,067: | ||
return t[targetsLength - 1]; |
return t[targetsLength - 1]; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
JavaScript hits integer limit for optional task |
JavaScript hits integer limit for optional task |
||
< |
<syntaxhighlight lang="javascript">countcoins(100, [1,5,10,25]); |
||
242</ |
242</syntaxhighlight> |
||
===Recursive=== |
===Recursive=== |
||
Line 2,078: | Line 2,078: | ||
Inefficient recursive algorithm (naively calculates number of combinations by actually permuting them) |
Inefficient recursive algorithm (naively calculates number of combinations by actually permuting them) |
||
< |
<syntaxhighlight lang="javascript">function countcoins(t, o) { |
||
'use strict'; |
'use strict'; |
||
var operandsLength = o.length; |
var operandsLength = o.length; |
||
Line 2,102: | Line 2,102: | ||
permutate(0, 0); |
permutate(0, 0); |
||
return solutions; |
return solutions; |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Too slow for optional task |
Too slow for optional task |
||
< |
<syntaxhighlight lang="javascript">countcoins(100, [1,5,10,25]); |
||
242</ |
242</syntaxhighlight> |
||
===Iterative again=== |
===Iterative again=== |
||
{{Trans|C#}} |
{{Trans|C#}} |
||
< |
<syntaxhighlight lang="javascript">var amount = 100, |
||
coin = [1, 5, 10, 25] |
coin = [1, 5, 10, 25] |
||
var t = [1]; |
var t = [1]; |
||
Line 2,119: | Line 2,119: | ||
for (var ci = coin[i], a = ci; a <= amount; a++) |
for (var ci = coin[i], a = ci; a <= amount; a++) |
||
t[a] += t[a - ci] |
t[a] += t[a - ci] |
||
document.write(t[amount])</ |
document.write(t[amount])</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>242</pre> |
<pre>242</pre> |
||
Line 2,125: | Line 2,125: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
Currently jq uses IEEE 754 64-bit numbers. Large integers are approximated by floats, and therefore the answer that the following program provides for the optional task is only correct for the first 15 digits. |
Currently jq uses IEEE 754 64-bit numbers. Large integers are approximated by floats, and therefore the answer that the following program provides for the optional task is only correct for the first 15 digits. |
||
< |
<syntaxhighlight lang="jq"># How many ways are there to make "target" cents, given a list of coin |
||
# denominations as input. |
# denominations as input. |
||
# The strategy is to record at total[n] the number of ways to make n cents. |
# The strategy is to record at total[n] the number of ways to make n cents. |
||
Line 2,140: | Line 2,140: | ||
end |
end |
||
end ) ) |
end ) ) |
||
| .[target] ;</ |
| .[target] ;</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
[1,5,10,25] | countcoins(100) |
[1,5,10,25] | countcoins(100) |
||
Line 2,148: | Line 2,148: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="julia">function changes(amount::Int, coins::Array{Int})::Int128 |
||
ways = zeros(Int128, amount + 1) |
ways = zeros(Int128, amount + 1) |
||
ways[1] = 1 |
ways[1] = 1 |
||
Line 2,158: | Line 2,158: | ||
@show changes(100, [1, 5, 10, 25]) |
@show changes(100, [1, 5, 10, 25]) |
||
@show changes(100000, [1, 5, 10, 25, 50, 100])</ |
@show changes(100000, [1, 5, 10, 25, 50, 100])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,166: | Line 2,166: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun countCoins(c: IntArray, m: Int, n: Int): Long { |
fun countCoins(c: IntArray, m: Int, n: Int): Long { |
||
Line 2,180: | Line 2,180: | ||
println(countCoins(c, 4, 100)) |
println(countCoins(c, 4, 100)) |
||
println(countCoins(c, 6, 1000 * 100)) |
println(countCoins(c, 6, 1000 * 100)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,190: | Line 2,190: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
Inspired by the javascript iterative example for the same task |
Inspired by the javascript iterative example for the same task |
||
< |
<syntaxhighlight lang="lasso">define cointcoins( |
||
target::integer, |
target::integer, |
||
operands::array |
operands::array |
||
Line 2,219: | Line 2,219: | ||
cointcoins(100, array(1,5,10,25,)) |
cointcoins(100, array(1,5,10,25,)) |
||
'<br />' |
'<br />' |
||
cointcoins(100000, array(1, 5, 10, 25, 50, 100))</ |
cointcoins(100000, array(1, 5, 10, 25, 50, 100))</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242 |
<pre>242 |
||
Line 2,226: | Line 2,226: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua uses one-based indexes but table keys can be any value so you can define an element 0 just as easily as you can define an element "foo"... |
Lua uses one-based indexes but table keys can be any value so you can define an element 0 just as easily as you can define an element "foo"... |
||
< |
<syntaxhighlight lang="lua">function countSums (amount, values) |
||
local t = {} |
local t = {} |
||
for i = 1, amount do t[i] = 0 end |
for i = 1, amount do t[i] = 0 end |
||
Line 2,237: | Line 2,237: | ||
print(countSums(100, {1, 5, 10, 25})) |
print(countSums(100, {1, 5, 10, 25})) |
||
print(countSums(100000, {1, 5, 10, 25, 50, 100}))</ |
print(countSums(100000, {1, 5, 10, 25, 50, 100}))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>242 |
<pre>242 |
||
Line 2,245: | Line 2,245: | ||
===Fast O(n*m)=== |
===Fast O(n*m)=== |
||
Works with decimals in table() |
Works with decimals in table() |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module FindCoins { |
Module FindCoins { |
||
Function count(c(), n) { |
Function count(c(), n) { |
||
Line 2,260: | Line 2,260: | ||
} |
} |
||
FindCoins |
FindCoins |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,269: | Line 2,269: | ||
Using an inventory (a kind of vector) to save first search (but is slower than previous one) |
Using an inventory (a kind of vector) to save first search (but is slower than previous one) |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckThisToo { |
Module CheckThisToo { |
||
inventory c=" 0 0":=1@ |
inventory c=" 0 0":=1@ |
||
Line 2,284: | Line 2,284: | ||
} |
} |
||
CheckThisToo |
CheckThisToo |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
Line 2,290: | Line 2,290: | ||
Straightforward implementation with power series. Not very efficient for large amounts. Note that in the following, all amounts are in '''cents'''. |
Straightforward implementation with power series. Not very efficient for large amounts. Note that in the following, all amounts are in '''cents'''. |
||
< |
<syntaxhighlight lang="maple">assume(p::posint,abs(x)<1): |
||
coin:=unapply(sum(x^(p*n),n=0..infinity),p): |
coin:=unapply(sum(x^(p*n),n=0..infinity),p): |
||
ways:=(amount,purse)->coeff(series(mul(coin(k),k in purse),x,amount+1),x,amount): |
ways:=(amount,purse)->coeff(series(mul(coin(k),k in purse),x,amount+1),x,amount): |
||
Line 2,304: | Line 2,304: | ||
ways(100000,[1,5,10,25,50,100]); |
ways(100000,[1,5,10,25,50,100]); |
||
# 13398445413854501</ |
# 13398445413854501</syntaxhighlight> |
||
A faster implementation. |
A faster implementation. |
||
< |
<syntaxhighlight lang="maple">ways2:=proc(amount,purse) |
||
local a,n,k; |
local a,n,k; |
||
a:=Array(1..amount); |
a:=Array(1..amount); |
||
Line 2,345: | Line 2,345: | ||
ways2(100000000,[1,5,10,25,50,100]); |
ways2(100000000,[1,5,10,25,50,100]); |
||
# 13333398333445333413833354500001</ |
# 13333398333445333413833354500001</syntaxhighlight> |
||
Additionally, while it's not proved as is, we can see that the first values for an amount 10^k obey the following simple formula: |
Additionally, while it's not proved as is, we can see that the first values for an amount 10^k obey the following simple formula: |
||
< |
<syntaxhighlight lang="maple">P:=n->4/(3*10^9)*n^5+65/10^8*n^4+112/10^6*n^3+805/10^5*n^2+635/3000*n+1: |
||
for k from 2 to 8 do lprint(P(10^k)) od: |
for k from 2 to 8 do lprint(P(10^k)) od: |
||
Line 2,358: | Line 2,358: | ||
1333983445341383545001 |
1333983445341383545001 |
||
133339833445334138335450001 |
133339833445334138335450001 |
||
13333398333445333413833354500001</ |
13333398333445333413833354500001</syntaxhighlight> |
||
The polynomial P(n) seems to give the correct number of ways iff n is a multiple of 100 (tested up to n=10000000), i.e. the number of ways for 100n is |
The polynomial P(n) seems to give the correct number of ways iff n is a multiple of 100 (tested up to n=10000000), i.e. the number of ways for 100n is |
||
< |
<syntaxhighlight lang="maple">Q:=n->40/3*n^5+65*n^4+112*n^3+161/2*n^2+127/6*n+1:</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="mathematica">CountCoins[amount_, coinlist_] := ( ways = ConstantArray[1, amount]; |
||
Do[For[j = coin, j <= amount, j++, |
Do[For[j = coin, j <= amount, j++, |
||
If[ j - coin == 0, |
If[ j - coin == 0, |
||
Line 2,373: | Line 2,373: | ||
]] |
]] |
||
, {coin, coinlist}]; |
, {coin, coinlist}]; |
||
ways[[amount]])</ |
ways[[amount]])</syntaxhighlight> |
||
Example usage: |
Example usage: |
||
<pre>CountCoins[100, {25, 10, 5}] |
<pre>CountCoins[100, {25, 10, 5}] |
||
Line 2,382: | Line 2,382: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
<syntaxhighlight lang="matlab"> |
|||
<lang Matlab> |
|||
%% Count_The_Coins |
%% Count_The_Coins |
||
clear;close all;clc; |
clear;close all;clc; |
||
Line 2,413: | Line 2,413: | ||
end % End for |
end % End for |
||
toc |
toc |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example Output: |
Example Output: |
||
<pre>Main Challenge: 242 |
<pre>Main Challenge: 242 |
||
Line 2,420: | Line 2,420: | ||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury">:- module coins. |
||
:- interface. |
:- interface. |
||
:- import_module int, io. |
:- import_module int, io. |
||
Line 2,467: | Line 2,467: | ||
show([P|T], !IO) :- |
show([P|T], !IO) :- |
||
io.write(P, !IO), io.nl(!IO), |
io.write(P, !IO), io.nl(!IO), |
||
show(T, !IO).</ |
show(T, !IO).</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nim">proc changes(amount: int, coins: openArray[int]): int = |
||
var ways = @[1] |
var ways = @[1] |
||
ways.setLen(amount+1) |
ways.setLen(amount+1) |
||
Line 2,480: | Line 2,480: | ||
echo changes(100, [1, 5, 10, 25]) |
echo changes(100, [1, 5, 10, 25]) |
||
echo changes(100000, [1, 5, 10, 25, 50, 100])</ |
echo changes(100000, [1, 5, 10, 25, 50, 100])</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242 |
<pre>242 |
||
Line 2,489: | Line 2,489: | ||
Translation of the D minimal version: |
Translation of the D minimal version: |
||
< |
<syntaxhighlight lang="ocaml">let changes amount coins = |
||
let ways = Array.make (amount + 1) 0L in |
let ways = Array.make (amount + 1) 0L in |
||
ways.(0) <- 1L; |
ways.(0) <- 1L; |
||
Line 2,502: | Line 2,502: | ||
Printf.printf "%Ld\n" (changes 1_00 [25; 10; 5; 1]); |
Printf.printf "%Ld\n" (changes 1_00 [25; 10; 5; 1]); |
||
Printf.printf "%Ld\n" (changes 1000_00 [100; 50; 25; 10; 5; 1]); |
Printf.printf "%Ld\n" (changes 1000_00 [100; 50; 25; 10; 5; 1]); |
||
;;</ |
;;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,511: | Line 2,511: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">coins(v)=prod(i=1,#v,1/(1-'x^v[i])); |
||
ways(v,n)=polcoeff(coins(v)+O('x^(n+1)),n); |
ways(v,n)=polcoeff(coins(v)+O('x^(n+1)),n); |
||
ways([1,5,10,25],100) |
ways([1,5,10,25],100) |
||
ways([1,5,10,25,50,100],100000)</ |
ways([1,5,10,25,50,100],100000)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>%1 = 242 |
<pre>%1 = 242 |
||
Line 2,520: | Line 2,520: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use 5.01; |
||
use Memoize; |
use Memoize; |
||
Line 2,542: | Line 2,542: | ||
say 'Ways to change $ 1000 with addition of less common coins: ', |
say 'Ways to change $ 1000 with addition of less common coins: ', |
||
cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 ); |
cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Ways to change $ 1 with common coins: 242 |
Ways to change $ 1 with common coins: 242 |
||
Line 2,549: | Line 2,549: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Very fast, from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change |
Very fast, from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">coin_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">coins</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">amount</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">coin_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">coins</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">amount</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">amount</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">amount</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> |
||
Line 2,560: | Line 2,560: | ||
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">amount</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> |
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">amount</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
An attempt to explain this algorithm further seems worthwhile: |
An attempt to explain this algorithm further seems worthwhile: |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">coin_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">coins</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">amount</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">coin_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">coins</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">amount</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #000080;font-style:italic;">-- start with 1 known way to achieve 0 (being no coins) |
<span style="color: #000080;font-style:italic;">-- start with 1 known way to achieve 0 (being no coins) |
||
Line 2,607: | Line 2,607: | ||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">coin_count</span><span style="color: #0000FF;">({</span><span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #000000;">1_00</span><span style="color: #0000FF;">))</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">coin_count</span><span style="color: #0000FF;">({</span><span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #000000;">1_00</span><span style="color: #0000FF;">))</span> |
||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%,d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">coin_count</span><span style="color: #0000FF;">({</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #000000;">1000_00</span><span style="color: #0000FF;">))</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%,d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">coin_count</span><span style="color: #0000FF;">({</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">25</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #000000;">1000_00</span><span style="color: #0000FF;">))</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,627: | Line 2,627: | ||
Using dynamic programming with tabling. |
Using dynamic programming with tabling. |
||
< |
<syntaxhighlight lang="picat">go => |
||
Problems = [[ 1*100, [25,10,5,1]], % 1 dollar |
Problems = [[ 1*100, [25,10,5,1]], % 1 dollar |
||
[ 100*100, [100,50,25,10,5,1]], % 100 dollars |
[ 100*100, [100,50,25,10,5,1]], % 100 dollars |
||
Line 2,656: | Line 2,656: | ||
end |
end |
||
end, |
end, |
||
Sum = Sum1.</ |
Sum = Sum1.</syntaxhighlight> |
||
{{Output}} |
{{Output}} |
||
Line 2,686: | Line 2,686: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="picolisp">(de coins (Sum Coins) |
||
(let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev) |
(let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev) |
||
(do Sum |
(do Sum |
||
Line 2,693: | Line 2,693: | ||
(inc (rot L) Prev) |
(inc (rot L) Prev) |
||
(setq Prev (car L)) ) ) |
(setq Prev (car L)) ) ) |
||
Prev ) )</ |
Prev ) )</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="picolisp">(for Coins '((100 50 25 10 5 1) (200 100 50 20 10 5 2 1)) |
||
(println (coins 100 (cddr Coins))) |
(println (coins 100 (cddr Coins))) |
||
(println (coins (* 1000 100) Coins)) |
(println (coins (* 1000 100) Coins)) |
||
(println (coins (* 10000 100) Coins)) |
(println (coins (* 10000 100) Coins)) |
||
(println (coins (* 100000 100) Coins)) |
(println (coins (* 100000 100) Coins)) |
||
(prinl) )</ |
(prinl) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242 |
<pre>242 |
||
Line 2,715: | Line 2,715: | ||
Basic version using brute force and constraint programming, the bonus version will work but takes a long time so skipped it. |
Basic version using brute force and constraint programming, the bonus version will work but takes a long time so skipped it. |
||
< |
<syntaxhighlight lang="prolog">:- use_module(library(clpfd)). |
||
% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny |
% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny |
||
Line 2,724: | Line 2,724: | ||
coins_for(T) :- |
coins_for(T) :- |
||
coins(Q,D,N,P,T), |
coins(Q,D,N,P,T), |
||
maplist(indomain, [Q,D,N,P]).</ |
maplist(indomain, [Q,D,N,P]).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,734: | Line 2,734: | ||
===Simple version=== |
===Simple version=== |
||
{{trans|Go}} |
{{trans|Go}} |
||
< |
<syntaxhighlight lang="python">def changes(amount, coins): |
||
ways = [0] * (amount + 1) |
ways = [0] * (amount + 1) |
||
ways[0] = 1 |
ways[0] = 1 |
||
Line 2,743: | Line 2,743: | ||
print changes(100, [1, 5, 10, 25]) |
print changes(100, [1, 5, 10, 25]) |
||
print changes(100000, [1, 5, 10, 25, 50, 100])</ |
print changes(100000, [1, 5, 10, 25, 50, 100])</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242 |
<pre>242 |
||
Line 2,749: | Line 2,749: | ||
===Fast version=== |
===Fast version=== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="python">try: |
||
import psyco |
import psyco |
||
psyco.full() |
psyco.full() |
||
Line 2,786: | Line 2,786: | ||
print count_changes(10000000, coins), "\n" |
print count_changes(10000000, coins), "\n" |
||
main()</ |
main()</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242 |
<pre>242 |
||
Line 2,800: | Line 2,800: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ stack ] is lim ( --> s ) |
||
[ swap dup 1+ lim put |
[ swap dup 1+ lim put |
||
Line 2,822: | Line 2,822: | ||
say "With EU coins." cr |
say "With EU coins." cr |
||
100 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr |
100 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr |
||
100000 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr</ |
100000 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,837: | Line 2,837: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
This is the basic recursive way: |
This is the basic recursive way: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (ways-to-make-change cents coins) |
(define (ways-to-make-change cents coins) |
||
(cond ((null? coins) 0) |
(cond ((null? coins) 0) |
||
Line 2,847: | Line 2,847: | ||
(ways-to-make-change 100 '(25 10 5 1)) ; -> 242 |
(ways-to-make-change 100 '(25 10 5 1)) ; -> 242 |
||
</syntaxhighlight> |
|||
</lang> |
|||
This works for the small numbers, but the optional task is just too slow with this solution, so with little change to the code we can use memoization: |
This works for the small numbers, but the optional task is just too slow with this solution, so with little change to the code we can use memoization: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define memos (make-hash)) |
(define memos (make-hash)) |
||
Line 2,873: | Line 2,873: | ||
cpu time: 20223 real time: 20673 gc time: 10233 |
cpu time: 20223 real time: 20673 gc time: 10233 |
||
99341140660285639188927260001 |#</ |
99341140660285639188927260001 |#</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 2,880: | Line 2,880: | ||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
<lang |
<syntaxhighlight lang="raku" line># Recursive (cached) |
||
sub change-r($amount, @coins) { |
sub change-r($amount, @coins) { |
||
my @cache = [1 xx @coins], |([] xx $amount); |
my @cache = [1 xx @coins], |([] xx $amount); |
||
Line 2,913: | Line 2,913: | ||
say "\nRecursive:"; |
say "\nRecursive:"; |
||
say change-r 1_00, [1,5,10,25]; |
say change-r 1_00, [1,5,10,25]; |
||
say change-r 1000_00, [1,5,10,25,50,100];</ |
say change-r 1000_00, [1,5,10,25,50,100];</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Iterative: |
<pre>Iterative: |
||
Line 2,934: | Line 2,934: | ||
The amount can be specified in cents (as a number), or in dollars (as for instance, $1000). |
The amount can be specified in cents (as a number), or in dollars (as for instance, $1000). |
||
< |
<syntaxhighlight lang="rexx">/*REXX program counts the number of ways to make change with coins from an given amount.*/ |
||
numeric digits 20 /*be able to handle large amounts of $.*/ |
numeric digits 20 /*be able to handle large amounts of $.*/ |
||
parse arg N $ /*obtain optional arguments from the CL*/ |
parse arg N $ /*obtain optional arguments from the CL*/ |
||
Line 2,965: | Line 2,965: | ||
if a==$.k then return f+1 /*handle this special case of A=a coin.*/ |
if a==$.k then return f+1 /*handle this special case of A=a coin.*/ |
||
if a <$.k then return f /* " " " " " A<a coin.*/ |
if a <$.k then return f /* " " " " " A<a coin.*/ |
||
return f+MKchg(a-$.k,k) /*use diminished amount ($) for change.*/</ |
return f+MKchg(a-$.k,k) /*use diminished amount ($) for change.*/</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 2,980: | Line 2,980: | ||
===with memoization=== |
===with memoization=== |
||
This REXX version is more than a couple of orders of magnitude faster than the 1<sup>st</sup> version when using larger amounts. |
This REXX version is more than a couple of orders of magnitude faster than the 1<sup>st</sup> version when using larger amounts. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program counts the number of ways to make change with coins from an given amount.*/ |
||
numeric digits 20 /*be able to handle large amounts of $.*/ |
numeric digits 20 /*be able to handle large amounts of $.*/ |
||
parse arg N $ /*obtain optional arguments from the CL*/ |
parse arg N $ /*obtain optional arguments from the CL*/ |
||
Line 3,012: | Line 3,012: | ||
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+1; return !.a.k; end /*handle this special case.*/ |
||
if a <$.k then do; !.a.k= f ; return f ; end /* " " " " */ |
if a <$.k then do; !.a.k= f ; return f ; end /* " " " " */ |
||
!.a.k= f + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */</ |
!.a.k= f + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */</syntaxhighlight> |
||
{{out|output|text= when using the following input for the optional test case: <tt> $1000 1 5 10 25 50 100 </tt>}} |
{{out|output|text= when using the following input for the optional test case: <tt> $1000 1 5 10 25 50 100 </tt>}} |
||
<pre> |
<pre> |
||
Line 3,021: | Line 3,021: | ||
===with error checking=== |
===with error checking=== |
||
This REXX version is identical to the previous REXX version, but has error checking for the amount and the coins specified. |
This REXX version is identical to the previous REXX version, but has error checking for the amount and the coins specified. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program counts the number of ways to make change with coins from an given amount.*/ |
||
numeric digits 20 /*be able to handle large amounts of $.*/ |
numeric digits 20 /*be able to handle large amounts of $.*/ |
||
parse arg N $ /*obtain optional arguments from the CL*/ |
parse arg N $ /*obtain optional arguments from the CL*/ |
||
Line 3,074: | Line 3,074: | ||
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+1; return !.a.k; end /*handle this special case.*/ |
||
if a <$.k then do; !.a.k= f ; return f ; end /* " " " " */ |
if a <$.k then do; !.a.k= f ; return f ; end /* " " " " */ |
||
!.a.k= f + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */</ |
!.a.k= f + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */</syntaxhighlight> |
||
{{out|output|text= is the same as the previous REXX version.}}<br><br> |
{{out|output|text= is the same as the previous REXX version.}}<br><br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
penny = 1 |
penny = 1 |
||
nickel = 1 |
nickel = 1 |
||
Line 3,098: | Line 3,098: | ||
next |
next |
||
see count + " ways to make a dollar" + nl |
see count + " ways to make a dollar" + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,119: | Line 3,119: | ||
'''Recursive, with caching''' |
'''Recursive, with caching''' |
||
< |
<syntaxhighlight lang="ruby">def make_change(amount, coins) |
||
@cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)} |
@cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)} |
||
@coins = coins |
@coins = coins |
||
Line 3,136: | Line 3,136: | ||
p make_change( 1_00, [1,5,10,25]) |
p make_change( 1_00, [1,5,10,25]) |
||
p make_change(1000_00, [1,5,10,25,50,100])</ |
p make_change(1000_00, [1,5,10,25,50,100])</syntaxhighlight> |
||
outputs |
outputs |
||
Line 3,144: | Line 3,144: | ||
'''Iterative''' |
'''Iterative''' |
||
< |
<syntaxhighlight lang="ruby">def make_change2(amount, coins) |
||
n, m = amount, coins.size |
n, m = amount, coins.size |
||
table = Array.new(n+1){|i| Array.new(m, i.zero? ? 1 : nil)} |
table = Array.new(n+1){|i| Array.new(m, i.zero? ? 1 : nil)} |
||
Line 3,157: | Line 3,157: | ||
p make_change2( 1_00, [1,5,10,25]) |
p make_change2( 1_00, [1,5,10,25]) |
||
p make_change2(1000_00, [1,5,10,25,50,100])</ |
p make_change2(1000_00, [1,5,10,25,50,100])</syntaxhighlight> |
||
outputs |
outputs |
||
<pre>242 |
<pre>242 |
||
Line 3,163: | Line 3,163: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">for penny = 0 to 100 |
||
for nickel = 0 to 20 |
for nickel = 0 to 20 |
||
for dime = 0 to 10 |
for dime = 0 to 10 |
||
Line 3,175: | Line 3,175: | ||
next nickel |
next nickel |
||
next penny |
next penny |
||
print count;" ways to make a buck"</ |
print count;" ways to make a buck"</syntaxhighlight>Output: |
||
<pre>0 pennies 0 nickels 0 dimes 4 quarters |
<pre>0 pennies 0 nickels 0 dimes 4 quarters |
||
0 pennies 0 nickels 5 dimes 2 quarters |
0 pennies 0 nickels 5 dimes 2 quarters |
||
Line 3,189: | Line 3,189: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn make_change(coins: &[usize], cents: usize) -> usize { |
||
let size = cents + 1; |
let size = cents + 1; |
||
let mut ways = vec![0; size]; |
let mut ways = vec![0; size]; |
||
Line 3,204: | Line 3,204: | ||
println!("{}", make_change(&[1,5,10,25], 100)); |
println!("{}", make_change(&[1,5,10,25], 100)); |
||
println!("{}", make_change(&[1,5,10,25,50,100], 100_000)); |
println!("{}", make_change(&[1,5,10,25,50,100], 100_000)); |
||
}</ |
}</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<pre>242 |
<pre>242 |
||
Line 3,211: | Line 3,211: | ||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
Generate the solutions using CLP solver in SAS/OR: |
Generate the solutions using CLP solver in SAS/OR: |
||
< |
<syntaxhighlight lang="sas">/* call OPTMODEL procedure in SAS/OR */ |
||
proc optmodel; |
proc optmodel; |
||
/* declare set and names of coins */ |
/* declare set and names of coins */ |
||
Line 3,231: | Line 3,231: | ||
/* print all solutions */ |
/* print all solutions */ |
||
proc print data=sols; |
proc print data=sols; |
||
run;</ |
run;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,250: | Line 3,250: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def countChange(amount: Int, coins:List[Int]) = { |
||
val ways = Array.fill(amount + 1)(0) |
val ways = Array.fill(amount + 1)(0) |
||
ways(0) = 1 |
ways(0) = 1 |
||
Line 3,261: | Line 3,261: | ||
countChange (15, List(1, 5, 10, 25)) |
countChange (15, List(1, 5, 10, 25)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre>res0: Int = 6 |
<pre>res0: Int = 6 |
||
Line 3,267: | Line 3,267: | ||
Recursive implementation: |
Recursive implementation: |
||
< |
<syntaxhighlight lang="scala">def count(target: Int, coins: List[Int]): Int = { |
||
if (target == 0) 1 |
if (target == 0) 1 |
||
else if (coins.isEmpty || target < 0) 0 |
else if (coins.isEmpty || target < 0) 0 |
||
Line 3,275: | Line 3,275: | ||
count(100, List(25, 10, 5, 1)) |
count(100, List(25, 10, 5, 1)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
A simple recursive implementation: |
A simple recursive implementation: |
||
< |
<syntaxhighlight lang="scheme">(define ways-to-make-change |
||
(lambda (x coins) |
(lambda (x coins) |
||
(cond |
(cond |
||
Line 3,287: | Line 3,287: | ||
[else (+ (ways-to-make-change x (cdr coins)) (ways-to-make-change (- x (car coins)) coins))]))) |
[else (+ (ways-to-make-change x (cdr coins)) (ways-to-make-change (- x (car coins)) coins))]))) |
||
(ways-to-make-change 100)</ |
(ways-to-make-change 100)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>242</pre> |
<pre>242</pre> |
||
Line 3,295: | Line 3,295: | ||
===Straightforward solution=== |
===Straightforward solution=== |
||
Fairly simple solution for the task. Expanding it to the optional task is not recommend, for Scilab will spend a lot of time processing the nested <code>for</code> loops. |
Fairly simple solution for the task. Expanding it to the optional task is not recommend, for Scilab will spend a lot of time processing the nested <code>for</code> loops. |
||
<lang>amount=100; |
<syntaxhighlight lang="text">amount=100; |
||
coins=[25 10 5 1]; |
coins=[25 10 5 1]; |
||
n_coins=zeros(coins); |
n_coins=zeros(coins); |
||
Line 3,316: | Line 3,316: | ||
end |
end |
||
disp(ways);</ |
disp(ways);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,325: | Line 3,325: | ||
{{trans|Python}} |
{{trans|Python}} |
||
<lang>function varargout=changes(amount, coins) |
<syntaxhighlight lang="text">function varargout=changes(amount, coins) |
||
ways = zeros(1,amount + 2); |
ways = zeros(1,amount + 2); |
||
ways(1) = 1; |
ways(1) = 1; |
||
Line 3,339: | Line 3,339: | ||
a=changes(100, [1, 5, 10, 25]); |
a=changes(100, [1, 5, 10, 25]); |
||
b=changes(100000, [1, 5, 10, 25, 50, 100]); |
b=changes(100000, [1, 5, 10, 25, 50, 100]); |
||
mprintf("%.0f, %.0f", a, b);</ |
mprintf("%.0f, %.0f", a, b);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,346: | Line 3,346: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "bigint.s7i"; |
include "bigint.s7i"; |
||
Line 3,386: | Line 3,386: | ||
writeln(changeCount( 100000, euCoins)); |
writeln(changeCount( 100000, euCoins)); |
||
writeln(changeCount(1000000, euCoins)); |
writeln(changeCount(1000000, euCoins)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,399: | Line 3,399: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang="ruby">func cc(_) { 0 } |
||
func cc({ .is_neg }, *_) { 0 } |
func cc({ .is_neg }, *_) { 0 } |
||
func cc({ .is_zero }, *_) { 1 } |
func cc({ .is_zero }, *_) { 1 } |
||
Line 3,415: | Line 3,415: | ||
var y = cc_optimized(1000 * 100, 1, 5, 10, 25, 50, 100); |
var y = cc_optimized(1000 * 100, 1, 5, 10, 25, 50, 100); |
||
say "Ways to change $1000 with addition of less common coins: #{y}";</ |
say "Ways to change $1000 with addition of less common coins: #{y}";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,425: | Line 3,425: | ||
{{trans|Python}} |
{{trans|Python}} |
||
{{libheader|Attaswift BigInt}} |
{{libheader|Attaswift BigInt}} |
||
< |
<syntaxhighlight lang="swift">import BigInt |
||
func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt { |
func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt { |
||
Line 3,468: | Line 3,468: | ||
print(countCoins(amountCents: 10000000, coins: set)) |
print(countCoins(amountCents: 10000000, coins: set)) |
||
print() |
print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,483: | Line 3,483: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
{{trans|Rust}} |
{{trans|Rust}} |
||
< |
<syntaxhighlight lang="tailspin"> |
||
templates makeChange&{coins:} |
templates makeChange&{coins:} |
||
def paid: $; |
def paid: $; |
||
Line 3,498: | Line 3,498: | ||
100000 -> makeChange&{coins: [1,5,10,25,50,100]} -> '$; ways to change 1000 dollars with all coins |
100000 -> makeChange&{coins: [1,5,10,25,50,100]} -> '$; ways to change 1000 dollars with all coins |
||
' -> !OUT::write |
' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,507: | Line 3,507: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc makeChange {amount coins} { |
proc makeChange {amount coins} { |
||
Line 3,528: | Line 3,528: | ||
# Making change with the EU coin set: |
# Making change with the EU coin set: |
||
puts [makeChange 100 {1 2 5 10 20 50 100 200}] |
puts [makeChange 100 {1 2 5 10 20 50 100 200}] |
||
puts [makeChange 100000 {1 2 5 10 20 50 100 200}]</ |
puts [makeChange 100000 {1 2 5 10 20 50 100 200}]</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,539: | Line 3,539: | ||
=={{header|uBasic/4tH}}== |
=={{header|uBasic/4tH}}== |
||
{{trans|Run BASIC}} |
{{trans|Run BASIC}} |
||
<lang>c = 0 |
<syntaxhighlight lang="text">c = 0 |
||
for p = 0 to 100 |
for p = 0 to 100 |
||
for n = 0 to 20 |
for n = 0 to 20 |
||
Line 3,552: | Line 3,552: | ||
next n |
next n |
||
next p |
next p |
||
print c;" ways to make a buck"</ |
print c;" ways to make a buck"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 pennies 0 nickels 0 dimes 4 quarters |
<pre>0 pennies 0 nickels 0 dimes 4 quarters |
||
Line 3,569: | Line 3,569: | ||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">function count_change { |
||
local -i amount=$1 coin j |
local -i amount=$1 coin j |
||
local ways=(1) |
local ways=(1) |
||
Line 3,581: | Line 3,581: | ||
} |
} |
||
count_change 100 25 10 5 1 |
count_change 100 25 10 5 1 |
||
count_change 100000 100 50 25 10 5 1</ |
count_change 100000 100 50 25 10 5 1</syntaxhighlight> |
||
{{works with|ksh|93}} |
{{works with|ksh|93}} |
||
< |
<syntaxhighlight lang="bash">function count_change { |
||
typeset -i amount=$1 coin j |
typeset -i amount=$1 coin j |
||
typeset ways |
typeset ways |
||
Line 3,597: | Line 3,597: | ||
} |
} |
||
count_change 100 25 10 5 1 |
count_change 100 25 10 5 1 |
||
count_change 100000 100 50 25 10 5 1</ |
count_change 100000 100 50 25 10 5 1</syntaxhighlight> |
||
{{works with|ksh|88}} |
{{works with|ksh|88}} |
||
< |
<syntaxhighlight lang="bash">function count_change { |
||
typeset -i amount=$1 coin j |
typeset -i amount=$1 coin j |
||
typeset ways |
typeset ways |
||
Line 3,615: | Line 3,615: | ||
} |
} |
||
count_change 100 25 10 5 1 |
count_change 100 25 10 5 1 |
||
# (optional task exceeds a subscript limit in ksh88)</ |
# (optional task exceeds a subscript limit in ksh88)</syntaxhighlight> |
||
And just for fun, here's one that works even with the original V7 shell: |
And just for fun, here's one that works even with the original V7 shell: |
||
{{works with|sh|v7}} |
{{works with|sh|v7}} |
||
< |
<syntaxhighlight lang="bash">if [ $# -lt 2 ]; then |
||
set ${1-100} 25 10 5 1 |
set ${1-100} 25 10 5 1 |
||
fi |
fi |
||
Line 3,634: | Line 3,634: | ||
done |
done |
||
done |
done |
||
eval "echo \$ways_$amount"</ |
eval "echo \$ways_$amount"</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 3,641: | Line 3,641: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function coin_count(coins As Variant, amount As Long) As Variant 'return type will be Decimal |
||
'sequence s = Repeat(0, amount + 1) |
'sequence s = Repeat(0, amount + 1) |
||
Dim s As Variant |
Dim s As Variant |
||
Line 3,662: | Line 3,662: | ||
us_coins = [{100,50,25, 10, 5, 1}] |
us_coins = [{100,50,25, 10, 5, 1}] |
||
Debug.Print coin_count(us_coins, 100000) |
Debug.Print coin_count(us_coins, 100000) |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre> 242 |
<pre> 242 |
||
13398445413854501 </pre> |
13398445413854501 </pre> |
||
Line 3,668: | Line 3,668: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Function count(coins,m,n) |
Function count(coins,m,n) |
||
ReDim table(n+1) |
ReDim table(n+1) |
||
Line 3,689: | Line 3,689: | ||
n = 100 |
n = 100 |
||
WScript.StdOut.WriteLine count(arr,m,n) |
WScript.StdOut.WriteLine count(arr,m,n) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,699: | Line 3,699: | ||
{{trans|VBA}} |
{{trans|VBA}} |
||
{{works with|Visual Basic|6}} |
{{works with|Visual Basic|6}} |
||
< |
<syntaxhighlight lang="vb">Option Explicit |
||
'---------------------------------------------------------------------- |
'---------------------------------------------------------------------- |
||
Private Function coin_count(coins As Variant, amount As Long) As Variant |
Private Function coin_count(coins As Variant, amount As Long) As Variant |
||
Line 3,727: | Line 3,727: | ||
Debug.Print coin_count(us_coins, 100000) |
Debug.Print coin_count(us_coins, 100000) |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 242 |
<pre> 242 |
||
Line 3,734: | Line 3,734: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
{{trans|go}} |
{{trans|go}} |
||
< |
<syntaxhighlight lang="go">fn main() { |
||
amount := 100 |
amount := 100 |
||
println("amount, ways to make change: $amount ${count_change(amount)}")) |
println("amount, ways to make change: $amount ${count_change(amount)}")) |
||
Line 3,768: | Line 3,768: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,778: | Line 3,778: | ||
{{libheader|Wren-big}} |
{{libheader|Wren-big}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/big" for BigInt |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 3,793: | Line 3,793: | ||
var c = [1, 5, 10, 25, 50, 100] |
var c = [1, 5, 10, 25, 50, 100] |
||
Fmt.print("Ways to make change for $$1 using 4 coins = $,i", countCoins.call(c, 4, 100)) |
Fmt.print("Ways to make change for $$1 using 4 coins = $,i", countCoins.call(c, 4, 100)) |
||
Fmt.print("Ways to make change for $$1,000 using 6 coins = $,i", countCoins.call(c, 6, 1000 * 100))</ |
Fmt.print("Ways to make change for $$1,000 using 6 coins = $,i", countCoins.call(c, 6, 1000 * 100))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,803: | Line 3,803: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|Scheme}} |
{{trans|Scheme}} |
||
< |
<syntaxhighlight lang="zkl">fcn ways_to_make_change(x, coins=T(25,10,5,1)){ |
||
if(not coins) return(0); |
if(not coins) return(0); |
||
if(x<0) return(0); |
if(x<0) return(0); |
||
Line 3,809: | Line 3,809: | ||
ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins) |
ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins) |
||
} |
} |
||
ways_to_make_change(100).println();</ |
ways_to_make_change(100).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>242</pre> |
<pre>242</pre> |
||
Line 3,815: | Line 3,815: | ||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="zkl">fcn make_change2(amount, coins){ |
||
n, m := amount, coins.len(); |
n, m := amount, coins.len(); |
||
table := (0).pump(n+1,List, (0).pump(m,List().write,1).copy); |
table := (0).pump(n+1,List, (0).pump(m,List().write,1).copy); |
||
Line 3,826: | Line 3,826: | ||
println(make_change2( 100, T(1,5,10,25))); |
println(make_change2( 100, T(1,5,10,25))); |
||
make_change2(0d1000_00, T(1,5,10,25,50,100)) : "%,d".fmt(_).println();</ |
make_change2(0d1000_00, T(1,5,10,25,50,100)) : "%,d".fmt(_).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,836: | Line 3,836: | ||
{{trans|AWK}} |
{{trans|AWK}} |
||
Test with emulator at full speed for reasonable performance. |
Test with emulator at full speed for reasonable performance. |
||
< |
<syntaxhighlight lang="zxbasic">10 LET amount=100 |
||
20 GO SUB 1000 |
20 GO SUB 1000 |
||
30 STOP |
30 STOP |
||
Line 3,855: | Line 3,855: | ||
1140 NEXT p |
1140 NEXT p |
||
1150 PRINT count |
1150 PRINT count |
||
1160 RETURN </ |
1160 RETURN </syntaxhighlight> |