Skip to content

Instantly share code, notes, and snippets.

@Ghostscypher
Last active December 24, 2023 05:27
Show Gist options
  • Save Ghostscypher/f5c0ec066edbbdb5307aa7e4391d6fc1 to your computer and use it in GitHub Desktop.
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
<?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])
);
@Ghostscypher
Copy link
Author

amount -> The target sum
ways -> The number of ways we can reach the target sum
chain -> simply shows a chain of how we can reach the target

For the example above, the output will be

Array
(
    [amount] => 5
    [ways] => 1
    [chain] => Array
        (
            [1] => Array
                (
                    [0] => 1
                    [1] => 1
                    [2] => 1
                    [3] => 1
                    [4] => 1
                )

            [4] => Array
                (
                    [0] => 4
                    [1] => 1
                )

            [5] => Array
                (
                    [0] => 5
                )

        )

)

We can read the chain as

  1. We can have 1 + 1 + 1 + 1 + 1
  2. Or 4 + 1
  3. Or simply 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment