dtsc1684 2018-04-25 17:12
浏览 38
已采纳

在二维数组中查找配对

I have a two-dimensional array and look for a way to find the all double entries. E.g. if the array is of the form

$a = array(
   array('a','b','c'),
   array('d','a','e'),
   array('d','c','b')
)

the function should return the list

array(array(0,0),array(1,1))  // Since $a[0,0]=$a[1,1]
array(array(0,1),array(2,2))  // Since $a[0,1]=$a[2,2]
array(array(0,2),array(2,1))  // Since $a[0,2]=$a[2,1]
array(array(1,0),array(2,0))  // Since $a[1,0]=$a[2,0]
array(1,2)                    // Unmatched

Is there an elegant/efficient way to implement this?

  • 写回答

1条回答 默认 最新

  • dpndp64206 2018-04-25 17:16
    关注

    With a nested loop. Use the values as keys in the result and append the coordinates as arrays under those keys.

    foreach ($a as $x => $inner) {
        foreach ($inner as $y => $value) {
            $result[$value][] = [$x, $y];
        }
    }
    

    The $result will contain sets of coordinates for all the given values. You can group the results by size of set to identify which values are unmatched, pairs, or have even greater than two occurrences (if that's possible).

    foreach ($result as $value => $set) {
        $sets[count($set)][$value] = $set;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用