首先是問(wèn)了ai ,問(wèn)了豆包 文心 chatgpt mini 都是亂寫(xiě),不是死循環(huán),就是錯(cuò)誤,有高手幫解決,請(qǐng)喝咖啡
需求如下:
有個(gè)集卡游戲,卡片類(lèi)型有 卡片A、卡片B、卡片C、卡片D、卡片E 一共五種卡, 集齊5種可以合成超級(jí)卡,如果卡片不足,可以用用萬(wàn)能卡代替任意卡片, 用php寫(xiě)代碼,模擬有1個(gè)用戶(hù),他有很多張各種類(lèi)型的卡,統(tǒng)計(jì)最后他能合成幾張超級(jí)卡,其實(shí)就是支付寶的集五福。
//模擬查詢(xún)數(shù)據(jù)
$userCards = [
'A' => 1,
'B' => 1,
'C' => 10,
'D' => 1,
'E' => 1,
];
// 萬(wàn)能卡數(shù)量
$wan = 3;
好了可以開(kāi)始了,加油
尷尬死了,ai寫(xiě)的都是錯(cuò)誤的,上線前檢查出來(lái)了。
~~多問(wèn)了幾遍ai,已經(jīng)好了,咖啡就請(qǐng)ai喝了 代碼很簡(jiǎn)單,主要是用到了while,老愛(ài)死循環(huán),多喝ai說(shuō)幾句就修正了。
ai寫(xiě)的代碼如下:~~
function countSuperCards($userCards, $jokerCount)
{
$superCardCount = 0;
while (true) {
$hasAllCards = true;
$tempJokerCount = $jokerCount;
$requiredCards = ['A', 'B', 'C', 'D', 'E'];
foreach ($requiredCards as $card) {
if (!isset($userCards[$card]) || $userCards[$card] < 1) {
if ($tempJokerCount > 0) {
$tempJokerCount--;
} else {
$hasAllCards = false;
break;
}
} else {
$userCards[$card]--;
}
}
if (!$hasAllCards) {
break;
}
$superCardCount++;
$jokerCount = $tempJokerCount; // 更新萬(wàn)能卡數(shù)量
}
return $superCardCount;
}
// 示例調(diào)用
$userCards = [
'A' => 0,
'B' => 15,
'C' => 13,
'D' => 18,
'E' => 1,
];
// 萬(wàn)能卡數(shù)量
$jokerCount = 3;
echo "能合成超級(jí)卡的數(shù)量: " . countSuperCards($userCards, $jokerCount);