PHP中的矩阵排列问题 [英] Matrix arrangement issues in php

查看:55
本文介绍了PHP中的矩阵排列问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一些解决此问题的方法.

I would like to know some solutions to such a problem.

给定一个数字,可以说16,您必须以这种方式安排一个矩阵

It is given a number lets say 16 and you have to arrange a matrix this way

1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7

语言无关紧要,(最好是PHP);

the language doesn't matter, (preferably PHP);

推荐答案

如果语言无关紧要:

转到: http://rosettacode.org/wiki/Spiral_matrix

If language doesn't matter:

Go to: http://rosettacode.org/wiki/Spiral_matrix

您在这里:

<?php
function getSpiralArray($n)
{
    $pos = 0;
    $count = $n;
    $value = -$n;
    $sum = -1;

    do
    {
        $value = -1 * $value / $n;
        for ($i = 0; $i < $count; $i++)
        {
            $sum += $value;
            $result[$sum / $n][$sum % $n] = $pos++;
        }
        $value *= $n;
        $count--;
        for ($i = 0; $i < $count; $i++)
        {
            $sum += $value;
            $result[$sum / $n][$sum % $n] = $pos++;
        }
    } while ($count > 0);

    return $result;
}

function PrintArray($array)
{
    for ($i = 0; $i < count($array); $i++) {
        for ($j = 0; $j < count($array); $j++) {
            echo str_pad($array[$i][$j],3,' ');
        }
        echo '<br/>';
    }
}

$arr = getSpiralArray(4);
echo '<pre>';
PrintArray($arr);
echo '</pre>';
?>

这篇关于PHP中的矩阵排列问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆