Count the coins: Difference between revisions

(Added Quackery.)
(26 intermediate revisions by 12 users not shown)
Line 34:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F changes(amount, coins)
V ways = [Int64(0)] * (amount + 1)
ways[0] = 1
Line 43:
 
print(changes(100, [1, 5, 10, 25]))
print(changes(100000, [1, 5, 10, 25, 50, 100]))</langsyntaxhighlight>
 
Output:
Line 53:
=={{header|360 Assembly}}==
{{trans|AWK}}
<langsyntaxhighlight lang="360asm">* count the coins 04/09/2015
COINS CSECT
USING COINS,R12
Line 111:
PG DS CL12
YREGS
END COINS</langsyntaxhighlight>
{{out}}
<pre>
Line 121:
{{Works with|gnat/gcc}}
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Count_The_Coins is
Line 152:
Print(Count( 1_00, (25, 10, 5, 1)));
Print(Count(1000_00, (100, 50, 25, 10, 5, 1)));
end Count_The_Coins;</langsyntaxhighlight>
 
Output:<pre> 242
Line 160:
{{works with|ALGOL 68G|Any - tested with release 2.4.1}}
{{trans|Haskell}}
<syntaxhighlight lang="algol68">
<lang Algol68>
#
Rosetta Code "Count the coins"
Line 192:
print((ways to make change(denoms, 100), newline))
END
</syntaxhighlight>
</lang>
Output:<pre>
+242
Line 198:
{{works with|ALGOL 68G|Any - tested with release 2.8.4}}
{{trans|Haskell}}
<syntaxhighlight lang="algol68">
<lang Algol68>
#
Rosetta Code "Count the coins"
Line 231:
print((ways to make change((1, 5, 10, 25, 50, 100), 100000), newline))
END
</syntaxhighlight>
</lang>
Output:<pre>
+242
Line 242:
{{trans|Phix}}
 
<langsyntaxhighlight lang="applescript">-- All input values must be integers and multiples of the same monetary unit.
on countCoins(amount, denominations)
-- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros.
Line 271:
set c1 to countCoins(100, {25, 10, 5, 1})
set c2 to countCoins(1000 * 100, {100, 50, 25, 10, 5, 1})
return {c1, c2}</langsyntaxhighlight>
 
{{output}}
<syntaxhighlight lang ="applescript">{242, 13398445413854501}</langsyntaxhighlight>
 
=={{header|Applesoft 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}}==
<langsyntaxhighlight lang="rebol">changes: function [amount coins][
ways: map 0..amount+1 [x]-> 0
ways\0: 1
Line 290 ⟶ 293:
print changes 100 [1 5 10 25]
print changes 100000 [1 5 10 25 50 100]</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{trans|Go}}
{{Works with|AutoHotkey_L}}
<langsyntaxhighlight AHKlang="ahk">countChange(amount){
return cc(amount, 4)
}
Line 311 ⟶ 314:
return [1, 5, 10, 25][kindsOfCoins]
}
MsgBox % countChange(100)</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 317 ⟶ 320:
Iterative implementation, derived from Run BASIC:
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 343 ⟶ 346:
return count;
}
</syntaxhighlight>
</lang>
 
Run time:
Line 355 ⟶ 358:
Recursive implementation (derived from Scheme example):
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 382 ⟶ 385:
return koins[1]
}
</syntaxhighlight>
</lang>
 
Run time:
Line 396 ⟶ 399:
=={{header|BBC BASIC}}==
Non-recursive solution:
<langsyntaxhighlight lang="bbcbasic"> DIM uscoins%(3)
uscoins%() = 1, 5, 10, 25
PRINT FNchange(100, uscoins%()) " ways of making $1"
Line 432 ⟶ 435:
NEXT
= table(P%-1)
</syntaxhighlight>
</lang>
Output (BBC BASIC does not have large enough integers for the optional task):
<pre> 242 ways of making $1
Line 441 ⟶ 444:
=={{header|C}}==
Using some crude 128-bit integer type.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 540 ⟶ 543:
 
return 0;
}</langsyntaxhighlight>output (only the first two lines are required by task):<syntaxhighlight lang="text">242
13398445413854501
1333983445341383545001
Line 548 ⟶ 551:
10056050940818192726001
99341140660285639188927260001
992198221207406412424859964272600001</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
// Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
class Program
Line 573 ⟶ 576:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <stack>
Line 610 ⟶ 613:
std::cout << ways << std::endl;
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 616 ⟶ 619:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(def denomination-kind [1 5 10 25])
 
(defn- cc [amount denominations]
Line 629 ⟶ 632:
(cc amount denominations))
 
(count-change 15 denomination-kind) ; = 6 </langsyntaxhighlight>
 
=={{header|COBOL}}==
{{trans|C#}}
<langsyntaxhighlight lang="cobol">
identification division.
program-id. CountCoins.
Line 665 ⟶ 668:
end-perform
.
</syntaxhighlight>
</lang>
{{out}}
<pre>242</pre>
Line 673 ⟶ 676:
{{trans|Python}}
 
<langsyntaxhighlight lang="coco">changes = (amount, coins) ->
ways = [1].concat [0] * amount
for coin of coins
Line 680 ⟶ 683:
ways[amount]
console.log changes 100, [1 5 10 25]</langsyntaxhighlight>
 
=={{header|Commodore BASIC}}==
Line 695 ⟶ 698:
 
 
<langsyntaxhighlight lang="gwbasic">5 m=100:rem money = $1.00 or 100 pennies.
10 print chr$(147);chr$(14);"This program will calculate the number"
11 print "of combinations of 'change' that can be"
Line 721 ⟶ 724:
265 print left$(en$,2);":";mid$(en$,3,2);":";right$(en$,2);"."
270 end
1000 print count;tab(6);pc;tab(11);nc;tab(16);dc;tab(21);qc:return</langsyntaxhighlight>
 
'''Example 2:''' Commodore 64 with Screen Blanking
Line 729 ⟶ 732:
Enabling screen blanking (and therefore not printing each result) results in a total time of 1:44.
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
'''Example 3:''' Commodore 128 with VIC-II blanking, 2MHz fast mode.
Line 736 ⟶ 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:
 
<langsyntaxhighlight lang="gwbasic">145 if not yn then fast
245 en$=ti$:if not yn then slow</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
===Recursive Version With Cache===
<langsyntaxhighlight lang="lisp">(defun count-change (amount coins
&optional
(length (1- (length coins)))
Line 758 ⟶ 761:
(print (count-change 100 '(25 10 5 1))) ; = 242
(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501
(terpri)</langsyntaxhighlight>
 
===Iterative Version===
<langsyntaxhighlight lang="lisp">(defun count-change (amount coins &aux (ways (make-array (1+ amount) :initial-element 0)))
(setf (aref ways 0) 1)
(loop for coin in coins do
(loop for j from coin upto amount
do (incf (aref ways j) (aref ways (- j coin)))))
(aref ways amount))</langsyntaxhighlight>
 
=={{header|D}}==
===Basic Version===
{{trans|Go}}
<langsyntaxhighlight lang="d">import std.stdio, std.bigint;
 
auto changes(int amount, int[] coins) {
Line 785 ⟶ 788:
changes( 1_00, [25, 10, 5, 1]).writeln;
changes(1000_00, [100, 50, 25, 10, 5, 1]).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>242
Line 792 ⟶ 795:
===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.
<langsyntaxhighlight lang="d">import std.stdio, core.checkedint;
 
auto changes(int amount, int[] coins, ref bool overflow) {
Line 812 ⟶ 815:
if (overflow)
"Overflow".puts;
}</langsyntaxhighlight>
The output is the same.
 
===Faster Version===
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.bigint;
 
BigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ {
Line 858 ⟶ 861:
writeln;
}
}</langsyntaxhighlight>
{{out}}
<pre>242
Line 873 ⟶ 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.
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.bigint, std.algorithm, std.conv, std.functional;
 
struct Ucent { /// Simplified 128-bit integer (like ucent).
Line 932 ⟶ 935:
writeln;
}
}</langsyntaxhighlight>
 
===Printing Version===
This version prints all the solutions (so it can be used on the smaller input):
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.string, std.algorithm, std.range;
 
void printChange(in uint tot, in uint[] coins)
Line 967 ⟶ 970:
void main() {
printChange(1_00, [1, 5, 10, 25]);
}</langsyntaxhighlight>
{{out}}
<pre>1:5 5:1 10:4 25:2
Line 996 ⟶ 999:
 
=={{header|Dart}}==
Simple recursive version plus cached version using a map.
 
<lang Dart>
=== Dart 1 version: ===
<syntaxhighlight lang="dart">
var cache = new Map();
 
Line 1,053 ⟶ 1,058:
return(count);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,060 ⟶ 1,065:
... completed in 3.604 seconds
</pre>
 
=== Dart 2 version: ===
<syntaxhighlight lang="dart">
 
/// Provides the same result and performance as the Dart 1 version
/// but using the Dart 2 specifications.
Map<String, int> cache = {};
 
void main() {
Stopwatch stopwatch = Stopwatch()..start();
 
/// Use the brute-force recursion for the small problem
int amount = 100;
List<int> coinTypes = [25,10,5,1];
print ("${coins(amount,coinTypes)} ways for $amount using $coinTypes coins.");
 
/// Use the cache version for the big problem
amount = 100000;
coinTypes = [100,50,25,10,5,1];
print ("${cachedCoins(amount,coinTypes)} ways for $amount using $coinTypes coins.");
 
stopwatch.stop();
print ("... completed in ${stopwatch.elapsedMilliseconds/1000} seconds");
 
}
 
int cachedCoins(int amount, List<int> coinTypes) {
int count = 0;
 
/// This is more efficient, looks at last two coins.
/// But not fast enough for the optional exercise.
if(coinTypes.length == 2) return (amount ~/ coinTypes[0] + 1);
 
/// Looks like "100.[25,10,5,1]"
String key = "$amount.$coinTypes";
/// Check whether we have seen this before
var cacheValue = cache[key];
 
if(cacheValue != null) return(cacheValue);
 
count = 0;
/// Same recursion as simple method, but caches all subqueries too
for(int i=0; i<=amount ~/ coinTypes[0]; i++){
count += cachedCoins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)'
}
 
/// add this to the cache
cache[key] = count;
return count;
}
 
int coins(int amount, List<int> coinTypes) {
int count = 0;
 
/// Just pennies available, so only one way to make change
if(coinTypes.length == 1) return (1);
 
/// Brute force recursion
for(int i=0; i<=amount ~/ coinTypes[0]; i++){
/// sublist(1) is like lisp's '(rest ...)'
count += coins(amount - (i*coinTypes[0]),coinTypes.sublist(1));
}
 
/// Uncomment if you want to see intermediate steps
/// print("there are " + count.toString() +" ways to count change for ${amount.toString()} using ${coinTypes} coins.");
return count;
}
</syntaxhighlight>
{{out}}
<pre>
242 ways for 100 using [25, 10, 5, 1] coins.
13398445413854501 ways for 100000 using [100, 50, 25, 10, 5, 1] coins.
... completed in 2.921 seconds
 
Process finished with exit code 0
</pre>
 
=={{header|Delphi}}==
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Count_the_coins;
 
Line 1,092 ⟶ 1,174:
Readln;
end.
</syntaxhighlight>
</lang>
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc main() void:
[4]byte coins = (1, 5, 10, 25);
[101]byte tab;
word m, n;
 
for n from 1 upto 100 do tab[n] := 0 od;
tab[0] := 1;
 
for m from 0 upto 3 do
for n from coins[m] upto 100 do
tab[n] := tab[n] + tab[n - coins[m]]
od
od;
 
writeln(tab[100])
corp</syntaxhighlight>
{{out}}
<pre>242</pre>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func countCoins(coins, n) {
var xs = Array.Empty(n + 1, 0)
xs[0] = 1
Line 1,109 ⟶ 1,211:
 
var coins = [1, 5, 10, 25]
print(countCoins(coins, 100))</langsyntaxhighlight>
 
{{out}}
 
<pre>242</pre>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
len cache[] 100000 * 7 + 6
val[] = [ 1 5 10 25 50 100 ]
func count sum kind .
if sum = 0
return 1
.
if sum < 0 or kind = 0
return 0
.
chind = sum * 7 + kind
if cache[chind] > 0
return cache[chind]
.
r2 = count (sum - val[kind]) kind
r1 = count sum (kind - 1)
r = r1 + r2
cache[chind] = r
return r
.
print count 100 4
print count 10000 6
print count 100000 6
# this is not exact, since numbers
# are doubles and r > 2^53
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Recursive solution using memoization, adapted from CommonLisp and Racket.
<langsyntaxhighlight lang="scheme">
(lib 'compile) ;; for (compile)
(lib 'bigint) ;; integer results > 32 bits
Line 1,138 ⟶ 1,269:
 
(compile 'ways) ;; speed-up things
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define change '(25 10 5 1))
(define c-1 (list-tail change -1)) ;; pointer to (1)
Line 1,173 ⟶ 1,304:
→ 13398445413854501
 
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
Line 1,179 ⟶ 1,310:
 
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.
<langsyntaxhighlight lang="edsac">
["Count the coins" problem for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
Line 1,334 ⟶ 1,465:
E21Z [define entry point]
PF [enter with acc = 0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,344 ⟶ 1,475:
=={{header|Elixir}}==
Recursive Dynamic Programming solution in Elixir
<langsyntaxhighlight Elixirlang="elixir">defmodule Coins do
def find(coins,lim) do
vals = Map.new(0..lim,&{&1,0}) |> Map.put(0,1)
Line 1,367 ⟶ 1,498:
 
Coins.find([1,5,10,25],100)
Coins.find([1,5,10,25,50,100],100_000)</langsyntaxhighlight>
 
{{out}}
Line 1,376 ⟶ 1,507:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(coins).
-compile(export_all).
Line 1,408 ⟶ 1,539:
A2 = 100000, C2 = [100, 50, 25, 10, 5, 1],
print(A2,C2).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,419 ⟶ 1,550:
{{trans|OCaml}}
<p>Forward iteration, which can also be seen in Scala.</p>
<langsyntaxhighlight lang="fsharp">let changes amount coins =
let ways = Array.zeroCreate (amount + 1)
ways.[0] <- 1L
Line 1,431 ⟶ 1,562:
printfn "%d" (changes 100 [25; 10; 5; 1]);
printfn "%d" (changes 100000 [100; 50; 25; 10; 5; 1]);
0</langsyntaxhighlight>
{{out}}
<pre>242
Line 1,437 ⟶ 1,568:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators kernel locals math math.ranges sequences sets sorting ;
IN: rosetta.coins
 
Line 1,472 ⟶ 1,603:
: make-change ( cents coins -- ways )
members [ ] inv-sort-with ! Sort coins in descending order.
recursive-count ;</langsyntaxhighlight>
 
From the listener:
Line 1,485 ⟶ 1,616:
 
One might make use of the rosetta-code.count-the-coins vocabulary as shown:
<syntaxhighlight lang="text">
IN: scratchpad [ 100000 { 1 5 10 25 50 100 } make-change . ] time
13398445413854501
Running time: 0.020869274 seconds
</syntaxhighlight>
</lang>
For reference, the implementation is shown next.
<syntaxhighlight lang="text">
USING: arrays locals math math.ranges sequences sets sorting ;
IN: rosetta-code.count-the-coins
Line 1,512 ⟶ 1,643:
: make-change ( cents coins -- ways )
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.
<langsyntaxhighlight lang="factor">
USE: math.ranges
 
Line 1,535 ⟶ 1,666:
13398445413854501
Running time: 0.029163549 seconds
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 S C(1)=1;S C(2)=5;S C(3)=10;S C(4)=25
01.20 F N=1,100;S T(N)=0
01.30 S T(0)=1
01.40 F M=1,4;F N=C(M),100;S T(N)=T(N)+T(N-C(M))
01.50 T %3,T(100),!
01.60 Q</syntaxhighlight>
{{out}}
<pre>= 242</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ counting change (SICP section 1.2.2)
 
: table create does> swap cells + @ ;
Line 1,553 ⟶ 1,694:
then then ;
 
100 5 count-change .</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Translation from "Dynamic Programming Solution: Python version" on this webside [http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/]
<langsyntaxhighlight lang="freebasic">' version 09-10-2016
' compile with: fbc -s console
 
Line 1,622 ⟶ 1,763:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>
Line 1,632 ⟶ 1,773:
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">include "NSLog.incl"
include "ConsoleWindow"
 
void local fn Doit
dim as long penny, nickel, dime, quarter , count
long penny, nickel, dime, quarter, count = 0
 
penny = 1 : nickel = 1
NSLogSetTabInterval(30)
dime = 1 : quarter = 1
 
for penny = 0 to 100
for nickel = 0 to 20
for dime = 0 to 10
for quarter = 0 to 4
if penny + nickel * 5 + dime * 10 + quarter * 25 == 100
print penny; NSLog(@"%ld pennies "; nickel;"\t%ld nickels "; dime; "\t%ld dimes\t%ld quarters"; ,penny,nickel,dime,quarter; " quarters")
count++
end if
next quarter
next dime
next nickel
next penny
print count;" ways to make a dollar"
NSLog(@"\n%ld ways to make a dollar",count)
end fn
 
fn DoIt
</lang>
 
HandleEvents</syntaxhighlight>
 
Output:
<pre>0 pennies 0 nickels 0 dimes 4 quarters
<pre>
0 pennies 0 nickels 0 nickels 5 dimes 4 2 quarters
0 pennies 0 nickels 5 10 dimes 2 0 quarters
0 pennies 0 nickels 10 1 nickels 2 dimes 0 3 quarters
0 pennies 1 nickels 2 dimes 3 quarters
......
65 pennies 5 nickels 1 dimes 0 quarters
65 pennies 7 nickels 0 dimes 0 quarters
70 pennies 0 nickels 3 dimes 0 quarters
70 pennies 1 nickels 0 dimes 1 quarters
 
242 ways to make a dollar</pre>
 
 
</pre>
 
=={{header|Go}}==
{{trans|lisp}}
A translation of the Lisp code referenced by the task description:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,711 ⟶ 1,851:
}
panic(kindsOfCoins)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,717 ⟶ 1,857:
</pre>
Alternative algorithm, practical for the optional task.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,735 ⟶ 1,875:
}
return ways[amount]
}</langsyntaxhighlight>
Output:
<pre>
Line 1,744 ⟶ 1,884:
{{trans|Go}}
Intuitive Recursive Solution:
<langsyntaxhighlight lang="groovy">def ccR
ccR = { BigInteger tot, List<BigInteger> coins ->
BigInteger n = coins.size()
Line 1,756 ⟶ 1,896:
ccR(tot - coins[0], coins)
}
}</langsyntaxhighlight>
 
Fast Iterative Solution:
<langsyntaxhighlight lang="groovy">def ccI = { BigInteger tot, List<BigInteger> coins ->
List<BigInteger> ways = [0g] * (tot+1)
ways[0] = 1g
Line 1,768 ⟶ 1,908:
}
ways[tot]
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println '\nBase:'
[iterative: ccI, recursive: ccR].each { label, cc ->
print "${label} "
Line 1,784 ⟶ 1,924:
def ways = ccI(1000g * 100, [100g, 50g, 25g, 10g, 5g, 1g])
def elapsed = System.currentTimeMillis() - start
println ("answer: ${ways} elapsed: ${elapsed}ms")</langsyntaxhighlight>
 
Output:
Line 1,796 ⟶ 1,936:
=={{header|Haskell}}==
Naive implementation:
<langsyntaxhighlight lang="haskell">count :: (Integral t, Integral a) => t -> [t] -> a
count 0 _ = 1
count _ [] = 0
Line 1,805 ⟶ 1,945:
 
main :: IO ()
main = print (count 100 [1, 5, 10, 25])</langsyntaxhighlight>
 
Much faster, probably harder to read, is to update results from bottom up:
<langsyntaxhighlight lang="haskell">count :: Integral a => [Int] -> [a]
count = foldr addCoin (1 : repeat 0)
where
Line 1,818 ⟶ 1,958:
main = do
print (count [25, 10, 5, 1] !! 100)
print (count [100, 50, 25, 10, 5, 1] !! 10000)</langsyntaxhighlight>
 
Or equivalently, (reformulating slightly, and adding a further test):
 
<langsyntaxhighlight lang="haskell">import Data.Function (fix)
 
count
Line 1,843 ⟶ 1,983:
, ([100, 50, 25, 10, 5, 1], 1000000)
]
</syntaxhighlight>
</lang>
{{Out}}
<pre>242
Line 1,850 ⟶ 1,990:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
 
US_coins := [1, 5, 10, 25]
Line 1,868 ⟶ 2,008:
every (s := "[ ") ||:= !L || " "
return s || "]"
end</langsyntaxhighlight>
 
This is a naive implementation and very slow.
{{improve|Icon|Needs a better algorithm.}}
<langsyntaxhighlight Iconlang="icon">procedure CountCoins(amt,coins) # very slow, recurse by coin value
local count
static S
Line 1,890 ⟶ 2,030:
return (amt ~= 0) | 1
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,900 ⟶ 2,040:
 
Another one:
<syntaxhighlight lang="icon">
<lang Icon>
# coin.icn
# usage: coin value
Line 1,919 ⟶ 2,059:
write(" coins in ", count(coins, money), " different ways.")
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,927 ⟶ 2,067:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Coins.bas"
110 LET MONEY=100
120 LET COUNT=0
Line 1,944 ⟶ 2,084:
270 NEXT
280 NEXT
290 PRINT COUNT;"different combinations found."</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,950 ⟶ 2,090:
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).
 
<langsyntaxhighlight lang="j">merge=: ({:"1 (+/@:({."1),{:@{:)/. ])@;
count=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@]
init=: (1 ,. ,.)^:(0=#@$)
nsplits=: 0 { [: +/ [: (merge@:(count"1) init)/ }.@/:~@~.@,</langsyntaxhighlight>
 
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,959 ⟶ 2,099:
Thus:
 
<langsyntaxhighlight lang="j"> 100 nsplits 1 5 10 25
242</langsyntaxhighlight>
 
And, on a 64 bit machine with sufficient memory:
 
<langsyntaxhighlight lang="j"> 100000 nsplits 1 5 10 25 50 100
13398445413854501</langsyntaxhighlight>
 
Warning: the above version can miss one when the largest coin is equal to the total value.
Line 1,971 ⟶ 2,111:
For British viewers change from £10 using £10 £5 £2 £1 50p 20p 10p 5p 2p and 1p
 
<langsyntaxhighlight lang="j"> init =: 4 : '(1+x)$1'
length1 =: 4 : '1=#y'
f =: 4 : ',/ +/\ (-x) ]\ y'
Line 1,979 ⟶ 2,119:
 
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)</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
import java.math.BigInteger;
 
Line 2,029 ⟶ 2,169:
}
}
}</langsyntaxhighlight>
Output:
<pre>242
Line 2,047 ⟶ 2,187:
Efficient iterative algorithm (cleverly calculates number of combinations without permuting them)
 
<langsyntaxhighlight Javascriptlang="javascript">function countcoins(t, o) {
'use strict';
var targetsLength = t + 1;
Line 2,065 ⟶ 2,205:
 
return t[targetsLength - 1];
}</langsyntaxhighlight>
 
{{out}}
JavaScript hits integer limit for optional task
<langsyntaxhighlight JavaScriptlang="javascript">countcoins(100, [1,5,10,25]);
242</langsyntaxhighlight>
 
===Recursive===
Line 2,076 ⟶ 2,216:
Inefficient recursive algorithm (naively calculates number of combinations by actually permuting them)
 
<langsyntaxhighlight Javascriptlang="javascript">function countcoins(t, o) {
'use strict';
var operandsLength = o.length;
Line 2,100 ⟶ 2,240:
permutate(0, 0);
return solutions;
}</langsyntaxhighlight>
{{Out}}
Too slow for optional task
 
<langsyntaxhighlight JavaScriptlang="javascript">countcoins(100, [1,5,10,25]);
242</langsyntaxhighlight>
 
===Iterative again===
 
{{Trans|C#}}
<langsyntaxhighlight lang="javascript">var amount = 100,
coin = [1, 5, 10, 25]
var t = [1];
Line 2,117 ⟶ 2,257:
for (var ci = coin[i], a = ci; a <= amount; a++)
t[a] += t[a - ci]
document.write(t[amount])</langsyntaxhighlight>
{{Out}}
<pre>242</pre>
Line 2,123 ⟶ 2,263:
=={{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.
<langsyntaxhighlight lang="jq"># How many ways are there to make "target" cents, given a list of coin
# denominations as input.
# The strategy is to record at total[n] the number of ways to make n cents.
Line 2,138 ⟶ 2,278:
end
end ) )
| .[target] ;</langsyntaxhighlight>
'''Example''':
[1,5,10,25] | countcoins(100)
Line 2,146 ⟶ 2,286:
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">function changes(amount::Int, coins::Array{Int})::Int128
ways = zeros(Int128, amount + 1)
ways[1] = 1
Line 2,156 ⟶ 2,296:
 
@show changes(100, [1, 5, 10, 25])
@show changes(100000, [1, 5, 10, 25, 50, 100])</langsyntaxhighlight>
 
{{out}}
Line 2,164 ⟶ 2,304:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun countCoins(c: IntArray, m: Int, n: Int): Long {
Line 2,178 ⟶ 2,318:
println(countCoins(c, 4, 100))
println(countCoins(c, 6, 1000 * 100))
}</langsyntaxhighlight>
 
{{out}}
Line 2,188 ⟶ 2,328:
=={{header|Lasso}}==
Inspired by the javascript iterative example for the same task
<langsyntaxhighlight Lassolang="lasso">define cointcoins(
target::integer,
operands::array
Line 2,217 ⟶ 2,357:
cointcoins(100, array(1,5,10,25,))
'<br />'
cointcoins(100000, array(1, 5, 10, 25, 50, 100))</langsyntaxhighlight>
Output:
<pre>242
Line 2,224 ⟶ 2,364:
=={{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"...
<langsyntaxhighlight Lualang="lua">function countSums (amount, values)
local t = {}
for i = 1, amount do t[i] = 0 end
Line 2,235 ⟶ 2,375:
 
print(countSums(100, {1, 5, 10, 25}))
print(countSums(100000, {1, 5, 10, 25, 50, 100}))</langsyntaxhighlight>
{{out}}
<pre>242
Line 2,243 ⟶ 2,383:
===Fast O(n*m)===
Works with decimals in table()
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module FindCoins {
Function count(c(), n) {
Line 2,258 ⟶ 2,398:
}
FindCoins
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,267 ⟶ 2,407:
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 {
inventory c=" 0 0":=1@
Line 2,282 ⟶ 2,422:
}
CheckThisToo
</syntaxhighlight>
</lang>
 
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
DIMENSION TAB(101)
 
THROUGH ZERO, FOR N = 1, 1, N.G.100
ZERO TAB(N) = 0
TAB(0) = 1
 
THROUGH STEP, FOR VALUES OF COIN = 1, 5, 10, 25
THROUGH STEP, FOR N = COIN, 1, N.G.100
STEP TAB(N) = TAB(N) + TAB(N - COIN)
 
VECTOR VALUES FMT = $I3*$
PRINT FORMAT FMT, TAB(100)
END OF PROGRAM</syntaxhighlight>
{{out}}
<pre>242</pre>
 
=={{header|Maple}}==
Line 2,288 ⟶ 2,446:
Straightforward implementation with power series. Not very efficient for large amounts. Note that in the following, all amounts are in '''cents'''.
 
<langsyntaxhighlight lang="maple">assume(p::posint,abs(x)<1):
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):
Line 2,302 ⟶ 2,460:
 
ways(100000,[1,5,10,25,50,100]);
# 13398445413854501</langsyntaxhighlight>
 
A faster implementation.
 
<langsyntaxhighlight lang="maple">ways2:=proc(amount,purse)
local a,n,k;
a:=Array(1..amount);
Line 2,343 ⟶ 2,501:
 
ways2(100000000,[1,5,10,25,50,100]);
# 13333398333445333413833354500001</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight 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:
Line 2,356 ⟶ 2,514:
1333983445341383545001
133339833445334138335450001
13333398333445333413833354500001</langsyntaxhighlight>
 
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
 
<langsyntaxhighlight lang="maple">Q:=n->40/3*n^5+65*n^4+112*n^3+161/2*n^2+127/6*n+1:</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
{{trans|Go}}
<langsyntaxhighlight Mathematicalang="mathematica">CountCoins[amount_, coinlist_] := ( ways = ConstantArray[1, amount];
Do[For[j = coin, j <= amount, j++,
If[ j - coin == 0,
Line 2,371 ⟶ 2,529:
]]
, {coin, coinlist}];
ways[[amount]])</langsyntaxhighlight>
Example usage:
<pre>CountCoins[100, {25, 10, 5}]
Line 2,380 ⟶ 2,538:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
%% Count_The_Coins
clear;close all;clc;
Line 2,411 ⟶ 2,569:
end % End for
toc
</syntaxhighlight>
</lang>
Example Output:
<pre>Main Challenge: 242
Line 2,418 ⟶ 2,576:
 
=={{header|Mercury}}==
<langsyntaxhighlight Mercurylang="mercury">:- module coins.
:- interface.
:- import_module int, io.
Line 2,465 ⟶ 2,623:
show([P|T], !IO) :-
io.write(P, !IO), io.nl(!IO),
show(T, !IO).</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">proc changes(amount: int, coins: openArray[int]): int =
var ways = @[1]
ways.setLen(amount+1)
Line 2,478 ⟶ 2,636:
 
echo changes(100, [1, 5, 10, 25])
echo changes(100000, [1, 5, 10, 25, 50, 100])</langsyntaxhighlight>
Output:
<pre>242
Line 2,487 ⟶ 2,645:
Translation of the D minimal version:
 
<langsyntaxhighlight lang="ocaml">let changes amount coins =
let ways = Array.make (amount + 1) 0L in
ways.(0) <- 1L;
Line 2,500 ⟶ 2,658:
Printf.printf "%Ld\n" (changes 1_00 [25; 10; 5; 1]);
Printf.printf "%Ld\n" (changes 1000_00 [100; 50; 25; 10; 5; 1]);
;;</langsyntaxhighlight>
 
Output:
Line 2,509 ⟶ 2,667:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight 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([1,5,10,25],100)
ways([1,5,10,25,50,100],100000)</langsyntaxhighlight>
Output:
<pre>%1 = 242
Line 2,518 ⟶ 2,676:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use 5.01;
use Memoize;
 
Line 2,540 ⟶ 2,698:
say 'Ways to change $ 1000 with addition of less common coins: ',
cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 );
</syntaxhighlight>
</lang>
{{out}}
Ways to change $ 1 with common coins: 242
Line 2,547 ⟶ 2,705:
=={{header|Phix}}==
Very fast, from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change
<!--<langsyntaxhighlight Phixlang="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: #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,558 ⟶ 2,716:
<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>
<!--</langsyntaxhighlight>-->
An attempt to explain this algorithm further seems worthwhile:
<!--<langsyntaxhighlight Phixlang="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: #000080;font-style:italic;">-- start with 1 known way to achieve 0 (being no coins)
Line 2,605 ⟶ 2,763:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,621 ⟶ 2,779:
9,007,199,254,740,992 -- max precision (53 bits) of a 64-bit float
</pre>
 
=={{header|Picat}}==
Using dynamic programming with tabling.
 
<syntaxhighlight lang="picat">go =>
Problems = [[ 1*100, [25,10,5,1]], % 1 dollar
[ 100*100, [100,50,25,10,5,1]], % 100 dollars
[ 1_000*100, [100,50,25,10,5,1]], % 1000 dollars
[ 10_000*100, [100,50,25,10,5,1]], % 10000 dollars
[100_000*100, [100,50,25,10,5,1]] % 100000 dollars
],
foreach([N,L] in Problems)
initialize_table, % clear the tabling from previous run
println([n=N,l=L]),
time(println(num_sols=coins(L,N,1)))
end.
 
table
coins(Coins, Money, M) = Sum =>
Sum1 = 0,
Len = Coins.length,
if M == Len then
Sum1 := 1,
else
foreach(I in M..Len)
if Money - Coins[I] == 0 then
Sum1 := Sum1 + 1
end,
if Money - Coins[I] > 0 then
Sum1 := Sum1 + coins(Coins, Money-Coins[I], I)
end,
end
end,
Sum = Sum1.</syntaxhighlight>
 
{{Output}}
<pre>[n = 100,l = [25,10,5,1]]
num_sols = 242
 
CPU time 0.0 seconds.
 
[n = 10000,l = [100,50,25,10,5,1]]
num_sols = 139946140451
 
CPU time 0.005 seconds.
 
[n = 100000,l = [100,50,25,10,5,1]]
num_sols = 13398445413854501
 
CPU time 0.046 seconds.
 
[n = 1000000,l = [100,50,25,10,5,1]]
num_sols = 1333983445341383545001
 
CPU time 0.496 seconds.
 
[n = 10000000,l = [100,50,25,10,5,1]]
num_sols = 133339833445334138335450001
 
CPU time 5.402 seconds.</pre>
 
=={{header|PicoLisp}}==
{{trans|C}}
<langsyntaxhighlight PicoLisplang="picolisp">(de coins (Sum Coins)
(let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev)
(do Sum
Line 2,631 ⟶ 2,849:
(inc (rot L) Prev)
(setq Prev (car L)) ) )
Prev ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(for Coins '((100 50 25 10 5 1) (200 100 50 20 10 5 2 1))
(println (coins 100 (cddr Coins)))
(println (coins (* 1000 100) Coins))
(println (coins (* 10000 100) Coins))
(println (coins (* 100000 100) Coins))
(prinl) )</langsyntaxhighlight>
Output:
<pre>242
Line 2,653 ⟶ 2,871:
Basic version using brute force and constraint programming, the bonus version will work but takes a long time so skipped it.
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny
Line 2,662 ⟶ 2,880:
coins_for(T) :-
coins(Q,D,N,P,T),
maplist(indomain, [Q,D,N,P]).</langsyntaxhighlight>
{{out}}
<pre>
Line 2,672 ⟶ 2,890:
===Simple version===
{{trans|Go}}
<langsyntaxhighlight lang="python">def changes(amount, coins):
ways = [0] * (amount + 1)
ways[0] = 1
Line 2,681 ⟶ 2,899:
 
print changes(100, [1, 5, 10, 25])
print changes(100000, [1, 5, 10, 25, 50, 100])</langsyntaxhighlight>
Output:
<pre>242
Line 2,687 ⟶ 2,905:
===Fast version===
{{trans|C}}
<langsyntaxhighlight lang="python">try:
import psyco
psyco.full()
Line 2,724 ⟶ 2,942:
print count_changes(10000000, coins), "\n"
 
main()</langsyntaxhighlight>
Output:
<pre>242
Line 2,738 ⟶ 2,956:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is lim ( --> s )
 
[ swap dup 1+ lim put
Line 2,760 ⟶ 2,978:
say "With EU coins." 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</langsyntaxhighlight>
 
{{out}}
Line 2,775 ⟶ 2,993:
=={{header|Racket}}==
This is the basic recursive way:
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (ways-to-make-change cents coins)
(cond ((null? coins) 0)
Line 2,785 ⟶ 3,003:
 
(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:
<langsyntaxhighlight Racketlang="racket">#lang racket
(define memos (make-hash))
Line 2,811 ⟶ 3,029:
 
cpu time: 20223 real time: 20673 gc time: 10233
99341140660285639188927260001 |#</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,818 ⟶ 3,036:
{{trans|Ruby}}
 
<syntaxhighlight lang="raku" perl6line># Recursive (cached)
sub change-r($amount, @coins) {
my @cache = [1 xx @coins], |([] xx $amount);
Line 2,851 ⟶ 3,069:
say "\nRecursive:";
say change-r 1_00, [1,5,10,25];
say change-r 1000_00, [1,5,10,25,50,100];</langsyntaxhighlight>
{{out}}
<pre>Iterative:
Line 2,872 ⟶ 3,090:
 
The amount can be specified in cents (as a number), or in dollars (as for instance, &nbsp; $1000).
<langsyntaxhighlight 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 $.*/
parse arg N $ /*obtain optional arguments from the CL*/
Line 2,903 ⟶ 3,121:
if a==$.k then return f+1 /*handle this special case of A=a coin.*/
if a <$.k then return f /* " " " " " A<a coin.*/
return f+MKchg(a-$.k,k) /*use diminished amount ($) for change.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 2,918 ⟶ 3,136:
===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.
<langsyntaxhighlight 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 $.*/
parse arg N $ /*obtain optional arguments from the CL*/
Line 2,950 ⟶ 3,168:
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 + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the following input for the optional test case: &nbsp; &nbsp; <tt> $1000 &nbsp; 1 &nbsp; 5 &nbsp; 10 &nbsp; 25 &nbsp; 50 &nbsp; 100 </tt>}}
<pre>
Line 2,959 ⟶ 3,177:
===with error checking===
This REXX version is identical to the previous REXX version, but has error checking for the amount and the coins specified.
<langsyntaxhighlight 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 $.*/
parse arg N $ /*obtain optional arguments from the CL*/
Line 3,012 ⟶ 3,230:
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 + MKchg(a-$.k, k); return !.a.k /*compute, define, return. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is the same as the previous REXX version.}}<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
penny = 1
nickel = 1
Line 3,036 ⟶ 3,254:
next
see count + " ways to make a dollar" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,050 ⟶ 3,268:
 
242 ways to make a dollar
</pre>
 
=={{header|RPL}}==
'''Dynamic programming (space optimized)'''
 
Source: [https://www.geeksforgeeks.org/coin-change-dp-7/ GeeksforGeeks website]
« → coins sum
« sum 1 + 1 →LIST 0 CON <span style="color:grey">@ dp[ii] will be storing the # of solutions for ii-1</span>
1 1 PUT <span style="color:grey">@ base case</span>
1 coins SIZE '''FOR''' ii
coins ii GET SWAP
'''IF''' OVER sum ≤ '''THEN'''
<span style="color:grey">@ Pick all coins one by one and update dp[] values </span>
<span style="color:grey">@ after the index greater than or equal to the value of the picked coin </span>
OVER 1 + sum 1 + '''FOR''' j
DUP j GET
OVER j 5 PICK - GET +
j SWAP PUT
'''NEXT'''
'''END''' SWAP DROP
'''NEXT'''
DUP SIZE GET
» » '<span style="color:blue">COUNT</span>' STO
 
{ 1 5 10 25 } 100 <span style="color:blue">COUNT</span>
{{out}}
<pre>
1: 242
</pre>
 
Line 3,057 ⟶ 3,303:
'''Recursive, with caching'''
 
<langsyntaxhighlight lang="ruby">def make_change(amount, coins)
@cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)}
@coins = coins
Line 3,074 ⟶ 3,320:
 
p make_change( 1_00, [1,5,10,25])
p make_change(1000_00, [1,5,10,25,50,100])</langsyntaxhighlight>
 
outputs
Line 3,082 ⟶ 3,328:
'''Iterative'''
 
<langsyntaxhighlight lang="ruby">def make_change2(amount, coins)
n, m = amount, coins.size
table = Array.new(n+1){|i| Array.new(m, i.zero? ? 1 : nil)}
Line 3,095 ⟶ 3,341:
 
p make_change2( 1_00, [1,5,10,25])
p make_change2(1000_00, [1,5,10,25,50,100])</langsyntaxhighlight>
outputs
<pre>242
Line 3,101 ⟶ 3,347:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for penny = 0 to 100
for nickel = 0 to 20
for dime = 0 to 10
Line 3,113 ⟶ 3,359:
next nickel
next penny
print count;" ways to make a buck"</langsyntaxhighlight>Output:
<pre>0 pennies 0 nickels 0 dimes 4 quarters
0 pennies 0 nickels 5 dimes 2 quarters
Line 3,127 ⟶ 3,373:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn make_change(coins: &[usize], cents: usize) -> usize {
let size = cents + 1;
let mut ways = vec![0; size];
Line 3,142 ⟶ 3,388:
println!("{}", make_change(&[1,5,10,25], 100));
println!("{}", make_change(&[1,5,10,25,50,100], 100_000));
}</langsyntaxhighlight>
{{output}}
<pre>242
Line 3,149 ⟶ 3,395:
=={{header|SAS}}==
Generate the solutions using CLP solver in SAS/OR:
<langsyntaxhighlight lang="sas">/* call OPTMODEL procedure in SAS/OR */
proc optmodel;
/* declare set and names of coins */
Line 3,169 ⟶ 3,415:
/* print all solutions */
proc print data=sols;
run;</langsyntaxhighlight>
 
Output:
Line 3,188 ⟶ 3,434:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def countChange(amount: Int, coins:List[Int]) = {
val ways = Array.fill(amount + 1)(0)
ways(0) = 1
Line 3,199 ⟶ 3,445:
 
countChange (15, List(1, 5, 10, 25))
</syntaxhighlight>
</lang>
Output:
<pre>res0: Int = 6
Line 3,205 ⟶ 3,451:
 
Recursive implementation:
<langsyntaxhighlight lang="scala">def count(target: Int, coins: List[Int]): Int = {
if (target == 0) 1
else if (coins.isEmpty || target < 0) 0
Line 3,213 ⟶ 3,459:
 
count(100, List(25, 10, 5, 1))
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
A simple recursive implementation:
<langsyntaxhighlight lang="scheme">(define ways-to-make-change
(lambda (x coins)
(cond
Line 3,225 ⟶ 3,471:
[else (+ (ways-to-make-change x (cdr coins)) (ways-to-make-change (- x (car coins)) coins))])))
 
(ways-to-make-change 100)</langsyntaxhighlight>
Output:
<pre>242</pre>
Line 3,233 ⟶ 3,479:
===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.
<syntaxhighlight lang="text">amount=100;
coins=[25 10 5 1];
n_coins=zeros(coins);
Line 3,254 ⟶ 3,500:
end
 
disp(ways);</langsyntaxhighlight>
 
{{out}}
Line 3,263 ⟶ 3,509:
{{trans|Python}}
 
<syntaxhighlight lang="text">function varargout=changes(amount, coins)
ways = zeros(1,amount + 2);
ways(1) = 1;
Line 3,277 ⟶ 3,523:
a=changes(100, [1, 5, 10, 25]);
b=changes(100000, [1, 5, 10, 25, 50, 100]);
mprintf("%.0f, %.0f", a, b);</langsyntaxhighlight>
 
{{out}}
Line 3,284 ⟶ 3,530:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
Line 3,324 ⟶ 3,570:
writeln(changeCount( 100000, euCoins));
writeln(changeCount(1000000, euCoins));
end func;</langsyntaxhighlight>
 
Output:
Line 3,334 ⟶ 3,580:
99341140660285639188927260001
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program count_the_coins;
print(count([1, 5, 10, 25], 100));
print(count([1, 5, 10, 25, 50, 100], 1000 * 100));
 
proc count(coins, n);
tab := {[0, 1]};
loop for coin in coins do
loop for i in [coin..n] do
tab(i) +:= tab(i - coin) ? 0;
end loop;
end loop;
return tab(n);
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>242
13398445413854501</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func cc(_) { 0 }
func cc({ .is_neg }, *_) { 0 }
func cc({ .is_zero }, *_) { 1 }
Line 3,353 ⟶ 3,618:
 
var y = cc_optimized(1000 * 100, 1, 5, 10, 25, 50, 100);
say "Ways to change $1000 with addition of less common coins: #{y}";</langsyntaxhighlight>
{{out}}
<pre>
Line 3,363 ⟶ 3,628:
{{trans|Python}}
{{libheader|Attaswift BigInt}}
<langsyntaxhighlight lang="swift">import BigInt
 
func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt {
Line 3,406 ⟶ 3,671:
print(countCoins(amountCents: 10000000, coins: set))
print()
}</langsyntaxhighlight>
 
{{out}}
Line 3,421 ⟶ 3,686:
=={{header|Tailspin}}==
{{trans|Rust}}
<langsyntaxhighlight lang="tailspin">
templates makeChange&{coins:}
def paid: $;
Line 3,436 ⟶ 3,701:
100000 -> makeChange&{coins: [1,5,10,25,50,100]} -> '$; ways to change 1000 dollars with all coins
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,445 ⟶ 3,710:
=={{header|Tcl}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc makeChange {amount coins} {
Line 3,466 ⟶ 3,731:
# Making change with the EU coin set:
puts [makeChange 100 {1 2 5 10 20 50 100 200}]
puts [makeChange 100000 {1 2 5 10 20 50 100 200}]</langsyntaxhighlight>
Output:
<pre>
Line 3,477 ⟶ 3,742:
=={{header|uBasic/4tH}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="text">c = 0
for p = 0 to 100
for n = 0 to 20
Line 3,490 ⟶ 3,755:
next n
next p
print c;" ways to make a buck"</langsyntaxhighlight>
{{out}}
<pre>0 pennies 0 nickels 0 dimes 4 quarters
Line 3,507 ⟶ 3,772:
{{trans|Common Lisp}}
{{works with|bash}}
<langsyntaxhighlight lang="bash">function count_change {
local -i amount=$1 coin j
local ways=(1)
Line 3,519 ⟶ 3,784:
}
count_change 100 25 10 5 1
count_change 100000 100 50 25 10 5 1</langsyntaxhighlight>
 
{{works with|ksh|93}}
<langsyntaxhighlight lang="bash">function count_change {
typeset -i amount=$1 coin j
typeset ways
Line 3,535 ⟶ 3,800:
}
count_change 100 25 10 5 1
count_change 100000 100 50 25 10 5 1</langsyntaxhighlight>
 
{{works with|ksh|88}}
<langsyntaxhighlight lang="bash">function count_change {
typeset -i amount=$1 coin j
typeset ways
Line 3,553 ⟶ 3,818:
}
count_change 100 25 10 5 1
# (optional task exceeds a subscript limit in ksh88)</langsyntaxhighlight>
 
And just for fun, here's one that works even with the original V7 shell:
 
{{works with|sh|v7}}
<langsyntaxhighlight lang="bash">if [ $# -lt 2 ]; then
set ${1-100} 25 10 5 1
fi
Line 3,572 ⟶ 3,837:
done
done
eval "echo \$ways_$amount"</langsyntaxhighlight>
 
{{Out}}
Line 3,579 ⟶ 3,844:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight 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)
Dim s As Variant
Line 3,600 ⟶ 3,865:
us_coins = [{100,50,25, 10, 5, 1}]
Debug.Print coin_count(us_coins, 100000)
End Sub</langsyntaxhighlight>{{out}}
<pre> 242
13398445413854501 </pre>
Line 3,606 ⟶ 3,871:
=={{header|VBScript}}==
{{trans|C#}}
<syntaxhighlight lang="vb">
<lang vb>
Function count(coins,m,n)
ReDim table(n+1)
Line 3,627 ⟶ 3,892:
n = 100
WScript.StdOut.WriteLine count(arr,m,n)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,637 ⟶ 3,902:
{{trans|VBA}}
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Option Explicit
'----------------------------------------------------------------------
Private Function coin_count(coins As Variant, amount As Long) As Variant
Line 3,665 ⟶ 3,930:
Debug.Print coin_count(us_coins, 100000)
End Sub</langsyntaxhighlight>
{{out}}
<pre> 242
13398445413854501</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="go">
fn main() {
amount := 100
println("amount: $amount; ways to make change: ${count_change(amount)}")
}
fn count_change(amount int) i64 {
if amount.str().count('0') > 4 {exit(-1)} // can be too slow
return cc(amount, 4)
}
fn cc(amount int, kinds_of_coins int) i64 {
if amount == 0 {return 1}
else if amount < 0 || kinds_of_coins == 0 {return 0}
return cc(amount, kinds_of_coins-1) +
cc(amount - first_denomination(kinds_of_coins), kinds_of_coins)
}
fn first_denomination(kinds_of_coins int) int {
match kinds_of_coins {
1 {return 1}
2 {return 5}
3 {return 10}
4 {return 25}
else {exit(-2)}
}
return kinds_of_coins
}
</syntaxhighlight>
Output:
<pre>
amount, ways to make change: 100 242
</pre>
Alternate:
<syntaxhighlight lang="go">
fn main() {
amount := 100
coins := [25, 10, 5, 1]
println("amount: $amount; ways to make change: ${count(coins, amount)}")
}
 
fn count(coins []int, amount int) int {
mut ways := []int{len: amount + 1}
ways[0] = 1
for coin in coins {
for idx := coin; idx <= amount; idx++ {
ways[idx] += ways[idx - coin]
}
}
return ways[amount]
}
</syntaxhighlight>
Output:
<pre>
amount: 100; ways to make change: 242
</pre>
 
=={{header|Wren}}==
Line 3,674 ⟶ 3,998:
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./big" for BigInt
import "./fmt" for Fmt
 
var countCoins = Fn.new { |c, m, n|
Line 3,689 ⟶ 4,013:
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,000 using 6 coins = $,i", countCoins.call(c, 6, 1000 * 100))</langsyntaxhighlight>
 
{{out}}
Line 3,699 ⟶ 4,023:
=={{header|zkl}}==
{{trans|Scheme}}
<langsyntaxhighlight lang="zkl">fcn ways_to_make_change(x, coins=T(25,10,5,1)){
if(not coins) return(0);
if(x<0) return(0);
Line 3,705 ⟶ 4,029:
ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins)
}
ways_to_make_change(100).println();</langsyntaxhighlight>
{{out}}
<pre>242</pre>
Line 3,711 ⟶ 4,035:
 
{{trans|Ruby}}
<langsyntaxhighlight lang="zkl">fcn make_change2(amount, coins){
n, m := amount, coins.len();
table := (0).pump(n+1,List, (0).pump(m,List().write,1).copy);
Line 3,722 ⟶ 4,046:
 
println(make_change2( 100, T(1,5,10,25)));
make_change2(0d1000_00, T(1,5,10,25,50,100)) : "%,d".fmt(_).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 3,732 ⟶ 4,056:
{{trans|AWK}}
Test with emulator at full speed for reasonable performance.
<langsyntaxhighlight lang="zxbasic">10 LET amount=100
20 GO SUB 1000
30 STOP
Line 3,751 ⟶ 4,075:
1140 NEXT p
1150 PRINT count
1160 RETURN </langsyntaxhighlight>
1,150

edits