Skip to content

Instantly share code, notes, and snippets.

@ara-ta3
Created December 29, 2014 14:14
Show Gist options
  • Save ara-ta3/3743b655d1dac79497ba to your computer and use it in GitHub Desktop.
Save ara-ta3/3743b655d1dac79497ba to your computer and use it in GitHub Desktop.
<?php
/**
* クーポン自体が独立しているから順次処理していく感じにした
* @param array $amount
* @param array $myCouponList
* @return array
*/
function selectOptimalCoupons($amount, $myCouponList){
$hydrate = function($coupons){
$hydrated = [];
foreach($coupons as $discount)
{
if( array_key_exists($discount, $hydrated) )
{
$hydrated[$discount]++;
}
else
{
$hydrated[$discount] = 1;
}
}
return $hydrated;
};
$sortByDiscount = function(array $hydrated)
{
$sorted = $hydrated;
krsort($sorted);
return $sorted;
};
$countUp = function($amount, array $sortedCoupons)
{
$usedCoupons = array_fill_keys(array_keys($sortedCoupons), 0);
foreach( $sortedCoupons as $discount => $nCoupon )
{
while($amount >= $discount && ($nCoupon - $usedCoupons[$discount]) > 0)
{
$amount -= $discount;
$usedCoupons[$discount]++;
}
}
return $usedCoupons;
};
$hydrated = $hydrate($myCouponList);
$sorted = $sortByDiscount($hydrated);
$usedCoupons = $countUp($amount, $sorted);
return $usedCoupons;
}
$test = [
[
'amount' => 100,
'couponList' => [],
],
[
'amount' => 100,
'couponList' => [
50,
50,
100,
],
],
[
'amount' => 470,
'couponList' => [
50,
50,
50,
100,
100,
100,
100,
100,
500,
],
],
[
'amount' => 1230,
'couponList' => [
50,
50,
50,
50,
50,
50,
100,
100,
100,
100,
100,
500,
500,
],
],
];
foreach( $test as $case )
{
print_r(
selectOptimalCoupons(
$case['amount'],
$case['couponList']
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment