Find minimum number of coins that make a given value: Difference between revisions

→‎{{header|JavaScript}}: Added a version in JavaScript
(Added Perl)
(→‎{{header|JavaScript}}: Added a version in JavaScript)
Line 287:
1 * 2
1 * 1</pre>
 
=={{header|JavaScript}}==
{{Works with|ES6}}
<lang javascript>(() => {
"use strict";
 
// change :: [Int] -> Int -> [(Int, Int)]
const change = denominations => {
// A minimum list of (quantity, value) pairs for n.
// Unused denominations are excluded from the list.
const go = n => {
const m = abs(n);
 
return 0 < denominations.length && 0 < m ? (
() => {
const [h, ...t] = denominations;
const [q, r] = quotRem(m)(h);
 
return (
0 < q ? [
[q, h]
] : []
).concat(change(t)(r));
}
)() : [];
};
 
return go;
};
 
 
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
// Two sums tested with a set of denominations.
const f = change([200, 100, 50, 20, 10, 5, 2, 1]);
 
return [1024, 988].map(n => {
const
report = f(n).map(
([q, u]) => `${q} * ${u}`
)
.join("\n");
 
return `Summing to ${n}:\n${report}`;
}).join("\n\n");
};
 
 
// --------------------- GENERIC ---------------------
 
// abs :: Num -> Num
const abs =
// Absolute value - without the sign.
x => 0 > x ? (
-x
) : x;
 
 
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = m =>
// The quotient, tupled with the remainder.
n => [Math.trunc(m / n), m % n];
 
 
// MAIN ---
return main();
})();</lang>
{{Out}}
<pre>Summing to 1024:
5 * 200
1 * 20
2 * 2
 
Summing to 988:
4 * 200
1 * 100
1 * 50
1 * 20
1 * 10
1 * 5
1 * 2
1 * 1</pre>
 
 
=={{header|jq}}==
Line 336 ⟶ 420:
A total of 11 coins in all.</pre>
</pre>
 
=={{header|Julia}}==
=== Long version ===
9,655

edits