喝啤酒问题

啤酒2元1瓶、4个盖子可以换一瓶、2个瓶子可以换一瓶,问10元可以喝多少啤酒、剩多少盖子、多少瓶子

/**
 * 喝啤酒问题
 * 啤酒2元1瓶、4个盖子可以换一瓶、2个瓶子可以换一瓶,问10元可以喝多少啤酒、剩多少盖子、多少瓶子
 *
 * @param integer $amount 多少钱(元)
 * @param integer $cap    多少盖子(默认0)
 * @param integer $bottle 多少瓶子(默认0)
 *
 * @return array [喝了多少瓶酒, 剩多少盖子, 剩多少瓶子]
 */
function drinkBeer($amount, $cap = 0, $bottle = 0)
{
    $beer   = $amount >= 2 ? intval(floor($amount / 2)) : 0; // 钱可以买多少瓶啤酒
    $cap    += $beer;       // 多少个瓶盖
    $bottle += $beer;       // 多少个瓶子

    // 当盖子小于4个并且瓶子小于2个,不能兑换、直接返回
    if ($cap < 4 && $bottle < 2) {
        return [$beer, $cap, $bottle];
    }

    // 盖子可以换多少瓶酒
    $intCap = $cap >= 4 ? intval(floor($cap / 4)) : 0;

    // 瓶子可以换多少瓶酒
    $intBottle = $bottle >= 2 ? intval(floor($bottle / 2)) : 0;

    // 又可以喝多少瓶酒
    $newBeer = $intCap + $intBottle;

    // 继续兑换继续喝
    $array = drinkBeer(0, $newBeer + $cap % 4, $newBeer + $bottle % 2);

    // 总共喝了多少 = 买的 + 新兑换的 + 后面兑换的
    $array[0] += $beer + $newBeer;

    return $array;
}

var_dump(drinkBeer(10), drinkBeer(15));
php
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!