打印图案以显示最多5行5列的数字,如5 4 3 2 1和下一行4 3 2 1 5至第5行 [英] Print a pattern to display numbers up to 5 rows and 5 columns like 5 4 3 2 1 and in next line 4 3 2 1 5 till 5th row
问题描述
这是一个正方形模式,每行有5列,有5行,模式如下所示:
5 4 3 2 1
4 3 2 1 5
3 2 1 5 4
2 1 5 4 3
1 5 4 3 2
我的代码如下图所示,但是当计数器变为1并且显示时,我不能重置每个值各自的列值。
任何人都可以引导我,我缺乏逻辑吗? c $ c><?php
$ n = 5;
$ count = 5; ($ j = $ count; $ j> = 1; $ j--)
为$($ i = 5; $ i> = 1; $ i - ){
{
if($ count> = 1)
echo $ j。& nbsp;;
}
$ count--;
回显\\\
;
}
?>
我认为这是一个学习练习,
<?php
$ n = 5; ($ j = $ n; $ j> = 1; $ j--){$ b($ i = $ n; $ i> = 1; $ i--){
$ b echo($ i + $ j - 1)%$ n + 1;
echo''; //化妆品:)
}
回声\\\
;
}
?>
%是一个模运算符。 6%5 =其余的除以6 = 5 = 1。 5%5 = 0; 12%5 = 2。
这很容易从模运算( http://en.wikipedia.org/wiki/Modular_arithmetic )。除了一个简单的加法操作,每一个新的行都不是别的,而是在五模数字集中(每一行从较小的数字开始)。我认为这是解决这个问题的最佳方案。另外这个操作很简单,不费时。
最好的问候!
This is a square pattern with each row having 5 columns and there are 5 rows and the pattern looks as shown below:
5 4 3 2 1
4 3 2 1 5
3 2 1 5 4
2 1 5 4 3
1 5 4 3 2
My code is as below to get the pattern but I am not able reset the value in each when the counter comes to 1 and display in that respective column value.
Can anybody guide me where I am lacking the logic?
<?php
$n=5;
$count=5;
for($i=5;$i>=1;$i--){
for($j=$count;$j>=1;$j--)
{
if($count>=1)
echo $j." ";
}
$count--;
echo "\n";
}
?>
I think that this is a learning excercise, so it must be done with for loops.
<?php
$n=5;
for($i=$n; $i>=1; $i--) {
for($j=$n; $j>=1; $j--) {
echo ($i + $j - 1) % $n + 1;
echo ' '; // cosmetics :)
}
echo "\n";
}
?>
% is a modulo operator. 6 % 5 = the rest from dividing 6 by 5 = 1.
Examples: 1%5 = 1; 5%5 = 0; 12%5 = 2.
This is easy excersice from modular arithmetic (http://en.wikipedia.org/wiki/Modular_arithmetic). Every new row is nothing else, than a simple addition operation but in the 5-mod number set (for each row starting from smaller number). And I think this is the best and one-line solution for this problem. In addition the operation is easy, and is not time consuming.
Best regards!
这篇关于打印图案以显示最多5行5列的数字,如5 4 3 2 1和下一行4 3 2 1 5至第5行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!