Skip to content

Instantly share code, notes, and snippets.

@squalvj
Created September 30, 2018 05:46
Show Gist options
  • Save squalvj/6c020e8b7d95a25875e4ea4a6eaf197e to your computer and use it in GitHub Desktop.
Save squalvj/6c020e8b7d95a25875e4ea4a6eaf197e to your computer and use it in GitHub Desktop.
Find all greater change given the total (using greedy algorithms)
<?php
function kembalian($jumlah){
$kembali = [];
$total = 0;
$obj = array(
[
'name' => 'G2',
'val' => 200,
],
[
'name' => 'G1',
'val' => 100,
],
[
'name' => '50s',
'val' => 50,
],
[
'name' => '25s',
'val' => 25,
],
[
'name' => '10s',
'val' => 10,
],
[
'name' => '5s',
'val' => 5,
],
[
'name' => '1s',
'val' => 1,
],
);
foreach($obj as $key => $val){
while(($total + $obj[$key]['val']) <= $jumlah){
array_push($kembali, $val);
$total += $val['val'];
}
}
$counts = array();
foreach ($kembali as $key=>$subarr) {
// Add to the current group count if it exists
if (isset($counts[$subarr['name']])) {
$counts[$subarr['name']]++;
}
// or initialize to 1 if it doesn't exist
else $counts[$subarr['name']] = 1;
// Or the ternary one-liner version
// instead of the preceding if/else block
$counts[$subarr['name']] = isset($counts[$subarr['name']]) ? $counts[$subarr['name']]++ : 1;
}
return $counts;
}
$jumlah = 5202;
$tot = kembalian($jumlah);
echo 'Total: ' . $jumlah . '<br>';
foreach($tot as $key => $val){
echo $val . ' x ' . $key . '<br>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment