3
\$\begingroup\$

I have written code based on the Greedy Algorithm. The example can be found here.

Problem: Make a change of a given amount using the smallest possible number of coins.

Coins available are:

  1. dollars (100 cents)
  2. quarters (25 cents)
  3. dimes (10 cents)
  4. nickels (5 cents)
  5. pennies (1 cent)

This outputs an array of coins:

<?php
function makeChange($amount) {
 $c = array(100, 25, 10, 5, 1);
 $sol = array();
 $sum = 0;
 $i = 0;
 $ele = $c['0'];
 while ($sum != $amount) {
 $sum = $sum + $ele;
 if ($sum > $amount) {
 $sum = $sum - $ele;
 $i++;
 $ele = $c[$i];
 continue;
 }
 $sol[] = $ele;
 }
 return $sol;
}
$amount = 356;
$sol = makeChange($amount);
print_r($sol);
?>

Can this become more optimized?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 30, 2015 at 13:06
\$\endgroup\$
3
  • 3
    \$\begingroup\$ Did you test it? If your code doesn't work as intended, it's not ready for a peer review. \$\endgroup\$ Commented Sep 30, 2015 at 13:18
  • \$\begingroup\$ Why so many down votes? It really discourages the OP. However I have updated my question. \$\endgroup\$ Commented Oct 1, 2015 at 4:51
  • \$\begingroup\$ Since you say it's correct, you can revise the questions to no longer ask about correctness. The update statement can also be removed along with that. \$\endgroup\$ Commented Oct 1, 2015 at 4:55

1 Answer 1

4
\$\begingroup\$

The following is a bit of variation, exploiting that one does not need to subtract the same coin value one-by-one.

$c = array(100, 25, 10, 5, 1); // $coins
$n = array( 0, 0, 0, 0, 0); // Number of coins.
$i = 0;
while ($amount > 0) {
 $k = floor($amount / $c[$i]); // How many coins
 $n[$i] = $k;
 $amount -= $k * $c[$i];
 // Or shorter: $amount %= $c[$i];
 ++$i;
}

Also, I subtract from the original amount instead of adding to $sum.

Quill
12k5 gold badges41 silver badges93 bronze badges
answered Sep 30, 2015 at 14:44
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.