我有一個 PHP 問題。我需要從一組數字 0-9 中寫出一個數字。每組有10個數字,每個數字一次。我需要計算我必須用來寫數字的套數。例如,數字 10 是從一組中寫入的,但數字 300 使用 2 組,因為它有兩個零。但是,問題是 6 和 9 被認為是相同的。它們可以旋轉 180 度。266號用一套,369號也用一套,5666用兩套。如果您能以某種方式幫助我,我將不勝感激。這是我開始和堅持的方式,不知道如何回圈。嘗試了很多東西,都沒有成功。
<?php
function countSet($num) {
$array = str_split($num);
$statarr = [0,1,2,3,4,5,6,7,8,9];
$a1 = $array; $a2 = $statarr;
$result = array_intersect($a1,$a2);
$count = array_count_values($result); }
?>
uj5u.com熱心網友回復:
如果您只需要知道一個數字需要多少組,您可以通過數數來解決。對于 9 的情況,只需將每個 9 替換為 6,然后將 6 的數量除以 2。像這樣的東西(對不起,如果有任何語法錯誤,我在手機上):
function countSet($input) {
// Convert the input into a string and replace every 9 by a 6. Then convert it to array
$numbers = str_split(str_replace("9", "6", strval($input)));
// Count occurrences for each number
$usedNumbers = array_count_values($numbers);
// If we have a 6, must divide it by 2 (6 represents 6 and 9
if (array_key_exists("6", $usedNumbers)) {
$usedNumbers["6"] = ceil($usedNumbers["6"] / 2);
}
// Now we just need to know the max number of occurrences for a single number as our result.
return max($usedNumbers);
}
在此處查看在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450408.html
上一篇:Python抓取回圈
下一篇:通過字典條件迭代
