PHP 从数组中写出一个数字
PHP write a number out of an array
我有一个 PHP 问题。
我需要从一组数字 0-9 中写出一个数字。每组有 10 个数字,每个数字一次。
我需要计算我必须用来写数字的套数。
例如,数字 10 是从一组写的,但数字 300 使用 2 组,因为它有两个零。
但是,问题是 6 和 9 被认为是相同的。它们可以旋转 180 度。
266号用的是一套,369也是用的一套,5666是用的2套。
如果你能以某种方式帮助我,我将不胜感激。
这是我开始和坚持的方式,不知道如何遍历它。尝试了很多东西,没有成功。
<?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); }
?>
如果你只是想知道一个数需要多少组,你可以通过数数来解决。对于 9 的情况,只需将每个 9 替换为 6,然后将 6 的数量除以二即可。类似这样的东西(抱歉,如果有任何语法错误,我在移动设备上):
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);
}
查看在线演示 here
我有一个 PHP 问题。 我需要从一组数字 0-9 中写出一个数字。每组有 10 个数字,每个数字一次。 我需要计算我必须用来写数字的套数。 例如,数字 10 是从一组写的,但数字 300 使用 2 组,因为它有两个零。 但是,问题是 6 和 9 被认为是相同的。它们可以旋转 180 度。 266号用的是一套,369也是用的一套,5666是用的2套。 如果你能以某种方式帮助我,我将不胜感激。 这是我开始和坚持的方式,不知道如何遍历它。尝试了很多东西,没有成功。
<?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); }
?>
如果你只是想知道一个数需要多少组,你可以通过数数来解决。对于 9 的情况,只需将每个 9 替换为 6,然后将 6 的数量除以二即可。类似这样的东西(抱歉,如果有任何语法错误,我在移动设备上):
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);
}
查看在线演示 here