获取两组数据的固定乱序组合

修改自一个矩阵z形遍历代码,改成从中间开始遍历,乱序效果更好

function matrix_mess_order($rows, $cols) {
    $cuts = $rows + $cols - 1;
    $mid  = (int)($cuts/2);
    $result = array();
    for ($i = 0; $i < $cuts; $i++) {
        if ($i % 2 == 0) {
            $j = $mid - (int)($i % $mid);
        } else {
            $j = $mid + (int)($i % $mid);
        }
        $row_extra = ($j + 1) > $rows ? ($j + 1 - $rows) : 0; 
        $col_extra = ($j + 1) > $cols ? ($j + 1 - $cols) : 0; 
        $len = ($j + 1) - $row_extra - $col_extra;
        $topright_row = $col_extra;
        $topright_col = $j - $col_extra;
        $leftbotm_row = $j - $row_extra;
        $leftbotm_col = $row_extra;
        if ($j % 2 == 0) {
            while ($len -- > 0) {
                $result[] = array($leftbotm_row - $len, $leftbotm_col + $len);
            }
        } else {
            while ($len -- > 0) {
                $result[] = array($topright_row + $len, $topright_col - $len);
            }
        }
    }
    return $result;
}

评论已关闭。