比较两个整数和计数匹配数

时间:2018-04-08 18:42:21

标签: php

我有两个整数,例如“12345”和“98754”,它们有2个匹配的数字 即4和5,顺序无关紧要。

现在:我如何在PHP中查看类似的内容?

3 个答案:

答案 0 :(得分:4)

您可以将输入拆分为数组,并使用array_intersect查找匹配的数字。

$a = 12345;
$b = 98754;

//Create arrays of the numbers
$a = str_split($a);
$b = str_split($b);

// Find matching numbers
$matching = array_intersect($a, $b);
Var_dump($matching);
// Output: 4,5
Echo count($matching);
// Output: 2

https://3v4l.org/8tS3q

答案 1 :(得分:1)

  1. 将数字转换为字符串
  2. 使用strstr()或类似方法从0-9创建一个循环,以检查两个字符串中数字的外观
  3. 如果数字出现在
  4. 中,则将其存储在数组中

    编辑: 以代码为中心的解决方案:

    $a = 1231534;
    $b = 89058430;
    
    
        $matches = compare( $a, $b );   
        print count($matches);
    
    
        function compare ( $a, $b ) {
            $str_a = (string) $a;
            $str_b = (string) $b;
            $matches = [];
            for($i=0;$i<=9;$i++) {
                if (strstr($str_a, (string)$i) && strstr($str_b,(string)$i)) $matches[] = $i;
            }
    
            return $matches;
        }
    

答案 2 :(得分:0)

此处添加了一个示例,计算两个数字中出现的数字。 如果两者都出现多个数字,则包含以下内容:

<?php
function digits_in_both($x, $y)
{
    $in_both = [];
    $split_y = str_split($y);
    foreach(str_split($x) as $n) {
        $key = array_search($n, $split_y);
        if($key !== false) {
            $in_both[] = $n;
            unset($split_y[$key]);
        }
    }

    return $in_both;
}

$in_both = digits_in_both(123445, 4456);
var_export($in_both);
var_dump(count($in_both));

输出:

array (
  0 => '4',
  1 => '4',
  2 => '5',
)int(3)

与您对array_intersect的期望相反,订单的重要性如下所示:

var_export(array_intersect(str_split('024688'), str_split('248')));
var_export(array_intersect(str_split('248'), str_split('024688')));

输出:

array (
    1 => '2',
    2 => '4',
    4 => '8',
    5 => '8',
  )array (
  0 => '2',
  1 => '4',
  2 => '8',
)
相关问题