R
R
Rodion Yurchenko2016-02-10 11:33:24
PHP
Rodion Yurchenko, 2016-02-10 11:33:24

Find identical elements in matrix rows?

Good afternoon
There is such a task
There is a Matrix (exactly 4 rows, the length of the columns is unknown)
It is known that at least one row will not be empty, the rest may be empty
It is tedious to find the elements that are in all EXISTING rows ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
angru, 2016-02-10
@angru

I don’t know if there are sets in php, but the algorithm is simple: the intersection of all lines is taken:

rows = [
    [1, 3, 4],
    [1, 2, 3, 5, 6],
    [1, 3, 5],
    [1, 3, 11]
]

res = set(rows[0])

for row in rows[1:]:
    res.intersection_update(row)

>>> {1, 3}

R
Rodion Yurchenko, 2016-02-10
@aassdds

Unfortunately, I didn’t find anything as beautiful in php as in python (post above)
But here’s what I got, if anyone is interested

$a = array(
            array(1,2,4,5,6,7),
            array(2,5,7,1),
            array(1,2),
            array(1,'a','g',2),
        );
        $res = array();
        for($i=0; $i<count($a[0]); $i++){
            $flag = 0;
            for($j=1; $j<count($a); $j++){
                for($k=0; $k<count($a[$j]); $k++){
                    if($a[0][$i] == $a[$j][$k]){
                        $flag ++ ;
                        if($flag == 3){ array_push($res, $a[0][$i]); }
                    }
                } // k
            } // j
        } // for i
        print_r($res);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question