这是一个奇怪的矩阵。 如果输入为1,则输出为1。 但是,如果输入为2,则输出为矩阵3 ^ 2。 最奇怪的是,如果输入3则输出为矩阵5 ^ 2。 有人知道如何解决这个问题吗? 我真的需要答案才能找到工作!
答案 0 :(得分:0)
这很简单。矩阵的尺寸为(2 * input)+1,并且矩阵中的数字为距中心点的距离+1。请参见下面的python代码。
import math
def distance(x1, y1, x2, y2):
dist = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)
return int(math.sqrt(dist))+1
if __name__=='__main__':
x = int(input())
if(x < 1):
exit()
dimension = (2*x)-1
center = dimension // 2
mat = [[None for i in range(dimension)] for i in range(dimension)]
for i in range(dimension):
for j in range(dimension):
mat[i][j] = distance(center, center, i, j);
print(mat[i][j], end=' ')
print('')
答案 1 :(得分:0)
这是基于您的代码的php中的代码:
<?php
$x = 3;
$dimension = (2 * $x) -1 ;
$center = floor($dimension/2);
for($i = 1; $i <= $dimension; $i++)
{
for($j = 1; $j <= $dimension; $j++)
{
$dist = ($center - $i) * ($center - $i) + ($center - $j) * ($center - $j);
$result = floor(sqrt($dist)) + 1;
echo "(" . $i . ", " . $j . ")" . " = " . $result . "</br>";
}
}
?>
它给我的结果与输出不同。
答案 2 :(得分:0)
I've got how to do it in php, but I don't know how to optimize the code. Anyone know how to do it correctly?
<?php
$z = 3;
$dimension = (2 * $z) -1 ;
for($i = 1; $i <= $dimension; $i++)
{
for($j = 1; $j <= $dimension; $j++)
{
if(($i == 1|| $j == 1) || ($i == $dimension || $j == $dimension)){
echo $z . " ";
} else if(($i == 2 || $j == 2) || ($i == $dimension - 1 || $j == $dimension - 1)){
echo $z - 1 . " ";
}
else if(($i == 3 || $j == 3) || ($i == $dimension - 2 || $j == $dimension - 2)){
echo $z - 2 . " ";
}
else if(($i == 4 || $j == 4) || ($i == $dimension - 3 || $j == $dimension - 3)){
echo $z - 3 . " ";
}
else{
echo $z - 4 . " ";
}
if($j == $dimension){
echo "</br>";
}
}
}
?>