dtsc1684 2018-04-25 09: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 09: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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部