Last active
December 24, 2023 05:27
-
-
Save Ghostscypher/f5c0ec066edbbdb5307aa7e4391d6fc1 to your computer and use it in GitHub Desktop.
This get the number of ways you can count an array of integers given the sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This shows how many ways we can arrive at the amount using the given coins | |
function how_many_ways($m, $coins) | |
{ | |
// Use memoization to avoid repeated calculations | |
$memo = []; | |
$memo[0] = 1; | |
$chain = []; | |
for($i = 1; $i <= $m; $i++) | |
{ | |
foreach($coins as $coin) | |
{ | |
$diff = $i - $coin; | |
if($diff < 0) | |
{ | |
break; | |
} | |
if($diff >= 0 && isset($memo[$diff])) | |
{ | |
$memo[$i] = ($memo[$i] ?? 0) + $memo[$diff]; | |
$chain[$coin][] = $diff; | |
} | |
} | |
} | |
// To get the coins used to make up the amount, we can use the following code | |
$m_copy = $m; | |
foreach($chain as $coin => $ways) | |
{ | |
$chain[$coin] = []; | |
$m = $m_copy; | |
// Get the last coin used | |
$prev_coin = $ways[count($ways) - 1]; | |
while($m > 0) | |
{ | |
$m -= $coin; | |
if($m < 0) | |
{ | |
$chain[$coin][] = $prev_coin; | |
break; | |
} | |
$chain[$coin][] = $coin; | |
} | |
} | |
return [ | |
'amount' => $m_copy, | |
'ways' => $memo[$m] ?? 0, | |
'chain' => $chain, | |
]; | |
} | |
print_r( | |
how_many_ways(5, [1, 4, 5]) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
amount
-> The target sumways
-> The number of ways we can reach the target sumchain
-> simply shows a chain of how we can reach the targetFor the example above, the output will be
We can read the chain as
1 + 1 + 1 + 1 + 1
4 + 1
5