How can I arrange numbers in this side-to-side pattern?
I am trying to make this pattern in PHP:
1 2 3 4
8 7 6 5
9 10 11 12
I tried this, but was unsuccessful:
$num = 0;
for ($i=0; $i<=2; $i++) {
for ($j=1; $j<=5; $j++) {
$num = $j - $i+$num;
echo $num."";
$num--;
}
echo "</br>";
}
Can anyone help me please?
Thanks in advance...
php loops numbers
New contributor
|
show 1 more comment
I am trying to make this pattern in PHP:
1 2 3 4
8 7 6 5
9 10 11 12
I tried this, but was unsuccessful:
$num = 0;
for ($i=0; $i<=2; $i++) {
for ($j=1; $j<=5; $j++) {
$num = $j - $i+$num;
echo $num."";
$num--;
}
echo "</br>";
}
Can anyone help me please?
Thanks in advance...
php loops numbers
New contributor
Look at modulus operator...oo the second row is backwards, thats a bit different
– user3783243
16 hours ago
1
What should the output look like for more than 12 numbers? Should there always be 4 columns? Or always 3 rows? Something else?
– Patrick Q
16 hours ago
5
(Do people really call that kind of pattern a “pyramid”? I’d say that is a Serpentine maybe, but I don’t see what is supposed to be pyramid…achical(?) about this.)
– 04FS
16 hours ago
I guess doingecho "1 2 3 4n8 7 6 5n9 10 11 12";
isn't fine? You could calculate what the max value of every second row is, and start to count back on indices from 0 if that makes any sense?
– Loek
16 hours ago
I can't get modulus operator for even to work as expected but here's a starting point. 3v4l.org/R4HhB
– user3783243
16 hours ago
|
show 1 more comment
I am trying to make this pattern in PHP:
1 2 3 4
8 7 6 5
9 10 11 12
I tried this, but was unsuccessful:
$num = 0;
for ($i=0; $i<=2; $i++) {
for ($j=1; $j<=5; $j++) {
$num = $j - $i+$num;
echo $num."";
$num--;
}
echo "</br>";
}
Can anyone help me please?
Thanks in advance...
php loops numbers
New contributor
I am trying to make this pattern in PHP:
1 2 3 4
8 7 6 5
9 10 11 12
I tried this, but was unsuccessful:
$num = 0;
for ($i=0; $i<=2; $i++) {
for ($j=1; $j<=5; $j++) {
$num = $j - $i+$num;
echo $num."";
$num--;
}
echo "</br>";
}
Can anyone help me please?
Thanks in advance...
php loops numbers
php loops numbers
New contributor
New contributor
edited 12 hours ago
Boann
37k1290121
37k1290121
New contributor
asked 16 hours ago
Smit PipaliyaSmit Pipaliya
4114
4114
New contributor
New contributor
Look at modulus operator...oo the second row is backwards, thats a bit different
– user3783243
16 hours ago
1
What should the output look like for more than 12 numbers? Should there always be 4 columns? Or always 3 rows? Something else?
– Patrick Q
16 hours ago
5
(Do people really call that kind of pattern a “pyramid”? I’d say that is a Serpentine maybe, but I don’t see what is supposed to be pyramid…achical(?) about this.)
– 04FS
16 hours ago
I guess doingecho "1 2 3 4n8 7 6 5n9 10 11 12";
isn't fine? You could calculate what the max value of every second row is, and start to count back on indices from 0 if that makes any sense?
– Loek
16 hours ago
I can't get modulus operator for even to work as expected but here's a starting point. 3v4l.org/R4HhB
– user3783243
16 hours ago
|
show 1 more comment
Look at modulus operator...oo the second row is backwards, thats a bit different
– user3783243
16 hours ago
1
What should the output look like for more than 12 numbers? Should there always be 4 columns? Or always 3 rows? Something else?
– Patrick Q
16 hours ago
5
(Do people really call that kind of pattern a “pyramid”? I’d say that is a Serpentine maybe, but I don’t see what is supposed to be pyramid…achical(?) about this.)
– 04FS
16 hours ago
I guess doingecho "1 2 3 4n8 7 6 5n9 10 11 12";
isn't fine? You could calculate what the max value of every second row is, and start to count back on indices from 0 if that makes any sense?
– Loek
16 hours ago
I can't get modulus operator for even to work as expected but here's a starting point. 3v4l.org/R4HhB
– user3783243
16 hours ago
Look at modulus operator...oo the second row is backwards, thats a bit different
– user3783243
16 hours ago
Look at modulus operator...oo the second row is backwards, thats a bit different
– user3783243
16 hours ago
1
1
What should the output look like for more than 12 numbers? Should there always be 4 columns? Or always 3 rows? Something else?
– Patrick Q
16 hours ago
What should the output look like for more than 12 numbers? Should there always be 4 columns? Or always 3 rows? Something else?
– Patrick Q
16 hours ago
5
5
(Do people really call that kind of pattern a “pyramid”? I’d say that is a Serpentine maybe, but I don’t see what is supposed to be pyramid…achical(?) about this.)
– 04FS
16 hours ago
(Do people really call that kind of pattern a “pyramid”? I’d say that is a Serpentine maybe, but I don’t see what is supposed to be pyramid…achical(?) about this.)
– 04FS
16 hours ago
I guess doing
echo "1 2 3 4n8 7 6 5n9 10 11 12";
isn't fine? You could calculate what the max value of every second row is, and start to count back on indices from 0 if that makes any sense?– Loek
16 hours ago
I guess doing
echo "1 2 3 4n8 7 6 5n9 10 11 12";
isn't fine? You could calculate what the max value of every second row is, and start to count back on indices from 0 if that makes any sense?– Loek
16 hours ago
I can't get modulus operator for even to work as expected but here's a starting point. 3v4l.org/R4HhB
– user3783243
16 hours ago
I can't get modulus operator for even to work as expected but here's a starting point. 3v4l.org/R4HhB
– user3783243
16 hours ago
|
show 1 more comment
10 Answers
10
active
oldest
votes
Here is the simplest and fastest code I was able to make using two loops. It's easier with three loops and there are multiple ways to achieve this but here is the simplest one according to me.
<?php
$num = 1;
$change = true;
$cols = 5;
$rows = 5;
for ($i = 0; $i < $rows; $i++) {
if (!$change) {
$num += ($cols - 1);
}
for ($j = 0; $j < $cols; $j++) {
echo $num . " ";
if (!$change) {
$num--;
} else {
$num++;
}
}
if (!$change) {
$num += ($cols + 1);
}
$change = !$change;
echo "<br>";
}
NOTE: You have to define the number of columns in $cols
variable. It will work with any case.
Why isn't$change
a Boolean?
– JustCarty
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
add a comment |
Using a for
loop and range
with array_reverse
:
https://3v4l.org/7QMGl
<?php
$number = 25;
$columnCount = 4;
for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
$range = range($i, $i+$columnCount - 1);
if($loopCounter % 2 === 0) {
$range = array_reverse($range);
}
foreach($range as $n) {
echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
}
echo "n";
}
We are increasing $i
by the $columnCount
on every iteration so we can always generate an array of the range of the numbers that have to be output in this row. That makes it very simple and clear if we have to reverse the numbers of the row.
str_pad
helps us to maintain the correct spacing for e.g. single digits
Note: You might have to swap echo "n";
for echo "<br>";
if you are looking at the output in a browser.
1
$columnCount = -1;
generates a strange result :)
– Tvde1
14 hours ago
add a comment |
Just to add a short version...
$columns = 4;
$rows = 3;
foreach ( array_chunk(range(1,$columns * $rows), $columns) as $row => $line ) {
echo implode(" ", ($row % 2 == 0 )?$line:array_reverse($line) )."<br />";
}
The idea being to use range
to create the numbers into an array and then use array_chunk
to split it into lines. Then use implode()
to output the lines - with the odd number lines reversed using array_reverse()
.
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
add a comment |
The following code will divide a range from 1 to 12 in chunks of 4. It will then walk through those chunks and print them forwards or backwards alternatively.
$forward = true;
array_walk(array_chunk(range(1, 12), 4), function ($a) use (&$forward) {
echo $forward ? implode(' ', $a) . '<br />' : implode(' ', array_reverse($a)) . '<br />';
$forward = $forward ? false : true;
});
add a comment |
I decided to opt for the array_chunk
method to create 'rows' which I then iterate over.
$max = 12; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D
// Print the data.
foreach ($arr as $key => $row) {
// This will reverse every other row
$row = ($key % 2 === 0) ? $row : array_reverse($row);
foreach ($row as $value) {
$value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
echo "{$value} ";
}
echo "<br />";
}
I've given you some options too so that you can change the column lengths or the number of elements you want to produce.
The string padding won't be visible in your browser unless you wrap the output in <pre>
tags because browsers only show one space at a time.
Code in action
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
add a comment |
$number = 12;
$elements_per_row = 4;
$left_to_right = true;
$processed_number_count = 0;
$result_array = ;
$temp = ;
for ($i=1; $i<=$number; $i++) {
$temp = $i;
$processed_number_count++;
if ($processed_number_count === $elements_per_row) {
$processed_number_count = 0;
if ($left_to_right) {
$result_array = $temp;
} else {
$result_array = array_reverse($temp);
}
$left_to_right = !$left_to_right;
$temp = ;
}
}
var_dump($result_array);
Then simply foreach $result_array to print desired pattern
This can be used variably for many other patterns which use same rule by modifying $number and $elements_per_row
add a comment |
Something like this.
bool forwardReverse = false;
int width = 4;
string line = "";
for (int i = 1; i < maxValue; i++)
{
if (i % width == 0)
{
forwardReverse = !forwardReverse;
Console.WriteLine(line);
line = "";
}
if (forwardReverse)
{
line = line + i;
}
else
{
line = i + line
}
}
Every time you get to the end of a row (width) the Boolean flag changes and the order that new values are added is switched between appending and prepending.
add a comment |
Here is another simple solution just by extending the OP's method. You can try it out with different row and column sizes by changing values for first 2 variables.
<?
$row_count = 3; //You can change this value depending to how many rows do you want to print
$column_count = 4; //You can change this value depending to how many columns will be at each row
$result = ''; //Variable to hold the output to print
$num = 0; //Variable to hold temporary value for each element
for ($i=1; $i<=$row_count; $i++) {
//Every row
for ($j=1; $j<=$column_count; $j++) {
//Every column
if($i % 2 == 1) {
//If row number is odd, increment the value starting from maximum element of previous row
$num = (($i - 1) * $column_count) + $j;
}
else {
//If row number is even, decrement the value starting from maximum element of current row
$num = ($i * $column_count) - ($j - 1);
}
//Add calculated number to output with an extra space if it's only one character
$result .= $num.($num < 9 ? ' ' : ' ');
}
$result .= '</br>';
}
?>
<html>
<head>
<style type="text/css">
body{
font-family: Courier;
}
</style>
</head>
<body>
<? echo $result; ?>
</body>
</html>
add a comment |
Pretty much Nigel's answer, walk through a chunked range, echoing out each row, reversing every other:
<?php
$cols = 4;
$rows = 3;
array_walk(
array_chunk(
range(1, $rows*$cols),
$cols
),
function($v, $k) {
if($k%2)
$v = array_reverse($v);
echo implode(' ', $v), "n";
}
);
Output:
1 2 3 4
8 7 6 5
9 10 11 12
add a comment |
The following will do exactly what you want. Short yet effective.
for ($i = 4; $i <= 12; $i += 4) {
echo (($i / 4) % 2) == 0 ? implode(' ', range($i, $i - 3)) . '<br />' : implode(' ', range($i - 3, $i)) . '<br />';
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Smit Pipaliya is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54652649%2fhow-can-i-arrange-numbers-in-this-side-to-side-pattern%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is the simplest and fastest code I was able to make using two loops. It's easier with three loops and there are multiple ways to achieve this but here is the simplest one according to me.
<?php
$num = 1;
$change = true;
$cols = 5;
$rows = 5;
for ($i = 0; $i < $rows; $i++) {
if (!$change) {
$num += ($cols - 1);
}
for ($j = 0; $j < $cols; $j++) {
echo $num . " ";
if (!$change) {
$num--;
} else {
$num++;
}
}
if (!$change) {
$num += ($cols + 1);
}
$change = !$change;
echo "<br>";
}
NOTE: You have to define the number of columns in $cols
variable. It will work with any case.
Why isn't$change
a Boolean?
– JustCarty
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
add a comment |
Here is the simplest and fastest code I was able to make using two loops. It's easier with three loops and there are multiple ways to achieve this but here is the simplest one according to me.
<?php
$num = 1;
$change = true;
$cols = 5;
$rows = 5;
for ($i = 0; $i < $rows; $i++) {
if (!$change) {
$num += ($cols - 1);
}
for ($j = 0; $j < $cols; $j++) {
echo $num . " ";
if (!$change) {
$num--;
} else {
$num++;
}
}
if (!$change) {
$num += ($cols + 1);
}
$change = !$change;
echo "<br>";
}
NOTE: You have to define the number of columns in $cols
variable. It will work with any case.
Why isn't$change
a Boolean?
– JustCarty
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
add a comment |
Here is the simplest and fastest code I was able to make using two loops. It's easier with three loops and there are multiple ways to achieve this but here is the simplest one according to me.
<?php
$num = 1;
$change = true;
$cols = 5;
$rows = 5;
for ($i = 0; $i < $rows; $i++) {
if (!$change) {
$num += ($cols - 1);
}
for ($j = 0; $j < $cols; $j++) {
echo $num . " ";
if (!$change) {
$num--;
} else {
$num++;
}
}
if (!$change) {
$num += ($cols + 1);
}
$change = !$change;
echo "<br>";
}
NOTE: You have to define the number of columns in $cols
variable. It will work with any case.
Here is the simplest and fastest code I was able to make using two loops. It's easier with three loops and there are multiple ways to achieve this but here is the simplest one according to me.
<?php
$num = 1;
$change = true;
$cols = 5;
$rows = 5;
for ($i = 0; $i < $rows; $i++) {
if (!$change) {
$num += ($cols - 1);
}
for ($j = 0; $j < $cols; $j++) {
echo $num . " ";
if (!$change) {
$num--;
} else {
$num++;
}
}
if (!$change) {
$num += ($cols + 1);
}
$change = !$change;
echo "<br>";
}
NOTE: You have to define the number of columns in $cols
variable. It will work with any case.
edited 15 hours ago
JustCarty
2,08631633
2,08631633
answered 16 hours ago
p01ymathp01ymath
845922
845922
Why isn't$change
a Boolean?
– JustCarty
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
add a comment |
Why isn't$change
a Boolean?
– JustCarty
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
Why isn't
$change
a Boolean?– JustCarty
15 hours ago
Why isn't
$change
a Boolean?– JustCarty
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
@JustCarty Yeah It can be a boolean too!
– p01ymath
15 hours ago
add a comment |
Using a for
loop and range
with array_reverse
:
https://3v4l.org/7QMGl
<?php
$number = 25;
$columnCount = 4;
for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
$range = range($i, $i+$columnCount - 1);
if($loopCounter % 2 === 0) {
$range = array_reverse($range);
}
foreach($range as $n) {
echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
}
echo "n";
}
We are increasing $i
by the $columnCount
on every iteration so we can always generate an array of the range of the numbers that have to be output in this row. That makes it very simple and clear if we have to reverse the numbers of the row.
str_pad
helps us to maintain the correct spacing for e.g. single digits
Note: You might have to swap echo "n";
for echo "<br>";
if you are looking at the output in a browser.
1
$columnCount = -1;
generates a strange result :)
– Tvde1
14 hours ago
add a comment |
Using a for
loop and range
with array_reverse
:
https://3v4l.org/7QMGl
<?php
$number = 25;
$columnCount = 4;
for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
$range = range($i, $i+$columnCount - 1);
if($loopCounter % 2 === 0) {
$range = array_reverse($range);
}
foreach($range as $n) {
echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
}
echo "n";
}
We are increasing $i
by the $columnCount
on every iteration so we can always generate an array of the range of the numbers that have to be output in this row. That makes it very simple and clear if we have to reverse the numbers of the row.
str_pad
helps us to maintain the correct spacing for e.g. single digits
Note: You might have to swap echo "n";
for echo "<br>";
if you are looking at the output in a browser.
1
$columnCount = -1;
generates a strange result :)
– Tvde1
14 hours ago
add a comment |
Using a for
loop and range
with array_reverse
:
https://3v4l.org/7QMGl
<?php
$number = 25;
$columnCount = 4;
for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
$range = range($i, $i+$columnCount - 1);
if($loopCounter % 2 === 0) {
$range = array_reverse($range);
}
foreach($range as $n) {
echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
}
echo "n";
}
We are increasing $i
by the $columnCount
on every iteration so we can always generate an array of the range of the numbers that have to be output in this row. That makes it very simple and clear if we have to reverse the numbers of the row.
str_pad
helps us to maintain the correct spacing for e.g. single digits
Note: You might have to swap echo "n";
for echo "<br>";
if you are looking at the output in a browser.
Using a for
loop and range
with array_reverse
:
https://3v4l.org/7QMGl
<?php
$number = 25;
$columnCount = 4;
for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
$range = range($i, $i+$columnCount - 1);
if($loopCounter % 2 === 0) {
$range = array_reverse($range);
}
foreach($range as $n) {
echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
}
echo "n";
}
We are increasing $i
by the $columnCount
on every iteration so we can always generate an array of the range of the numbers that have to be output in this row. That makes it very simple and clear if we have to reverse the numbers of the row.
str_pad
helps us to maintain the correct spacing for e.g. single digits
Note: You might have to swap echo "n";
for echo "<br>";
if you are looking at the output in a browser.
edited 15 hours ago
answered 15 hours ago
XatenevXatenev
5,23211233
5,23211233
1
$columnCount = -1;
generates a strange result :)
– Tvde1
14 hours ago
add a comment |
1
$columnCount = -1;
generates a strange result :)
– Tvde1
14 hours ago
1
1
$columnCount = -1;
generates a strange result :)– Tvde1
14 hours ago
$columnCount = -1;
generates a strange result :)– Tvde1
14 hours ago
add a comment |
Just to add a short version...
$columns = 4;
$rows = 3;
foreach ( array_chunk(range(1,$columns * $rows), $columns) as $row => $line ) {
echo implode(" ", ($row % 2 == 0 )?$line:array_reverse($line) )."<br />";
}
The idea being to use range
to create the numbers into an array and then use array_chunk
to split it into lines. Then use implode()
to output the lines - with the odd number lines reversed using array_reverse()
.
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
add a comment |
Just to add a short version...
$columns = 4;
$rows = 3;
foreach ( array_chunk(range(1,$columns * $rows), $columns) as $row => $line ) {
echo implode(" ", ($row % 2 == 0 )?$line:array_reverse($line) )."<br />";
}
The idea being to use range
to create the numbers into an array and then use array_chunk
to split it into lines. Then use implode()
to output the lines - with the odd number lines reversed using array_reverse()
.
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
add a comment |
Just to add a short version...
$columns = 4;
$rows = 3;
foreach ( array_chunk(range(1,$columns * $rows), $columns) as $row => $line ) {
echo implode(" ", ($row % 2 == 0 )?$line:array_reverse($line) )."<br />";
}
The idea being to use range
to create the numbers into an array and then use array_chunk
to split it into lines. Then use implode()
to output the lines - with the odd number lines reversed using array_reverse()
.
Just to add a short version...
$columns = 4;
$rows = 3;
foreach ( array_chunk(range(1,$columns * $rows), $columns) as $row => $line ) {
echo implode(" ", ($row % 2 == 0 )?$line:array_reverse($line) )."<br />";
}
The idea being to use range
to create the numbers into an array and then use array_chunk
to split it into lines. Then use implode()
to output the lines - with the odd number lines reversed using array_reverse()
.
answered 15 hours ago
Nigel RenNigel Ren
27.3k61833
27.3k61833
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
add a comment |
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
You made my code look so unnecessarily long aha!
– JustCarty
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
@JustCarty - short code isn't necessarily better. It's also isn't usually quicker.
– Nigel Ren
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
Very true, the other thing I noticed that your solution doesn't get is the padding of the smaller numbers. Aside from that "Great minds, think alike" and all that ;)
– JustCarty
15 hours ago
add a comment |
The following code will divide a range from 1 to 12 in chunks of 4. It will then walk through those chunks and print them forwards or backwards alternatively.
$forward = true;
array_walk(array_chunk(range(1, 12), 4), function ($a) use (&$forward) {
echo $forward ? implode(' ', $a) . '<br />' : implode(' ', array_reverse($a)) . '<br />';
$forward = $forward ? false : true;
});
add a comment |
The following code will divide a range from 1 to 12 in chunks of 4. It will then walk through those chunks and print them forwards or backwards alternatively.
$forward = true;
array_walk(array_chunk(range(1, 12), 4), function ($a) use (&$forward) {
echo $forward ? implode(' ', $a) . '<br />' : implode(' ', array_reverse($a)) . '<br />';
$forward = $forward ? false : true;
});
add a comment |
The following code will divide a range from 1 to 12 in chunks of 4. It will then walk through those chunks and print them forwards or backwards alternatively.
$forward = true;
array_walk(array_chunk(range(1, 12), 4), function ($a) use (&$forward) {
echo $forward ? implode(' ', $a) . '<br />' : implode(' ', array_reverse($a)) . '<br />';
$forward = $forward ? false : true;
});
The following code will divide a range from 1 to 12 in chunks of 4. It will then walk through those chunks and print them forwards or backwards alternatively.
$forward = true;
array_walk(array_chunk(range(1, 12), 4), function ($a) use (&$forward) {
echo $forward ? implode(' ', $a) . '<br />' : implode(' ', array_reverse($a)) . '<br />';
$forward = $forward ? false : true;
});
edited 14 hours ago
answered 15 hours ago
PeterPeter
4,41943771
4,41943771
add a comment |
add a comment |
I decided to opt for the array_chunk
method to create 'rows' which I then iterate over.
$max = 12; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D
// Print the data.
foreach ($arr as $key => $row) {
// This will reverse every other row
$row = ($key % 2 === 0) ? $row : array_reverse($row);
foreach ($row as $value) {
$value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
echo "{$value} ";
}
echo "<br />";
}
I've given you some options too so that you can change the column lengths or the number of elements you want to produce.
The string padding won't be visible in your browser unless you wrap the output in <pre>
tags because browsers only show one space at a time.
Code in action
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
add a comment |
I decided to opt for the array_chunk
method to create 'rows' which I then iterate over.
$max = 12; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D
// Print the data.
foreach ($arr as $key => $row) {
// This will reverse every other row
$row = ($key % 2 === 0) ? $row : array_reverse($row);
foreach ($row as $value) {
$value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
echo "{$value} ";
}
echo "<br />";
}
I've given you some options too so that you can change the column lengths or the number of elements you want to produce.
The string padding won't be visible in your browser unless you wrap the output in <pre>
tags because browsers only show one space at a time.
Code in action
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
add a comment |
I decided to opt for the array_chunk
method to create 'rows' which I then iterate over.
$max = 12; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D
// Print the data.
foreach ($arr as $key => $row) {
// This will reverse every other row
$row = ($key % 2 === 0) ? $row : array_reverse($row);
foreach ($row as $value) {
$value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
echo "{$value} ";
}
echo "<br />";
}
I've given you some options too so that you can change the column lengths or the number of elements you want to produce.
The string padding won't be visible in your browser unless you wrap the output in <pre>
tags because browsers only show one space at a time.
Code in action
I decided to opt for the array_chunk
method to create 'rows' which I then iterate over.
$max = 12; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D
// Print the data.
foreach ($arr as $key => $row) {
// This will reverse every other row
$row = ($key % 2 === 0) ? $row : array_reverse($row);
foreach ($row as $value) {
$value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
echo "{$value} ";
}
echo "<br />";
}
I've given you some options too so that you can change the column lengths or the number of elements you want to produce.
The string padding won't be visible in your browser unless you wrap the output in <pre>
tags because browsers only show one space at a time.
Code in action
edited 11 hours ago
answered 15 hours ago
JustCartyJustCarty
2,08631633
2,08631633
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
add a comment |
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
Can't you combine the two foreach loops into one?
– Jasper Lichte
14 hours ago
add a comment |
$number = 12;
$elements_per_row = 4;
$left_to_right = true;
$processed_number_count = 0;
$result_array = ;
$temp = ;
for ($i=1; $i<=$number; $i++) {
$temp = $i;
$processed_number_count++;
if ($processed_number_count === $elements_per_row) {
$processed_number_count = 0;
if ($left_to_right) {
$result_array = $temp;
} else {
$result_array = array_reverse($temp);
}
$left_to_right = !$left_to_right;
$temp = ;
}
}
var_dump($result_array);
Then simply foreach $result_array to print desired pattern
This can be used variably for many other patterns which use same rule by modifying $number and $elements_per_row
add a comment |
$number = 12;
$elements_per_row = 4;
$left_to_right = true;
$processed_number_count = 0;
$result_array = ;
$temp = ;
for ($i=1; $i<=$number; $i++) {
$temp = $i;
$processed_number_count++;
if ($processed_number_count === $elements_per_row) {
$processed_number_count = 0;
if ($left_to_right) {
$result_array = $temp;
} else {
$result_array = array_reverse($temp);
}
$left_to_right = !$left_to_right;
$temp = ;
}
}
var_dump($result_array);
Then simply foreach $result_array to print desired pattern
This can be used variably for many other patterns which use same rule by modifying $number and $elements_per_row
add a comment |
$number = 12;
$elements_per_row = 4;
$left_to_right = true;
$processed_number_count = 0;
$result_array = ;
$temp = ;
for ($i=1; $i<=$number; $i++) {
$temp = $i;
$processed_number_count++;
if ($processed_number_count === $elements_per_row) {
$processed_number_count = 0;
if ($left_to_right) {
$result_array = $temp;
} else {
$result_array = array_reverse($temp);
}
$left_to_right = !$left_to_right;
$temp = ;
}
}
var_dump($result_array);
Then simply foreach $result_array to print desired pattern
This can be used variably for many other patterns which use same rule by modifying $number and $elements_per_row
$number = 12;
$elements_per_row = 4;
$left_to_right = true;
$processed_number_count = 0;
$result_array = ;
$temp = ;
for ($i=1; $i<=$number; $i++) {
$temp = $i;
$processed_number_count++;
if ($processed_number_count === $elements_per_row) {
$processed_number_count = 0;
if ($left_to_right) {
$result_array = $temp;
} else {
$result_array = array_reverse($temp);
}
$left_to_right = !$left_to_right;
$temp = ;
}
}
var_dump($result_array);
Then simply foreach $result_array to print desired pattern
This can be used variably for many other patterns which use same rule by modifying $number and $elements_per_row
answered 15 hours ago
LearnerLearner
3,76311633
3,76311633
add a comment |
add a comment |
Something like this.
bool forwardReverse = false;
int width = 4;
string line = "";
for (int i = 1; i < maxValue; i++)
{
if (i % width == 0)
{
forwardReverse = !forwardReverse;
Console.WriteLine(line);
line = "";
}
if (forwardReverse)
{
line = line + i;
}
else
{
line = i + line
}
}
Every time you get to the end of a row (width) the Boolean flag changes and the order that new values are added is switched between appending and prepending.
add a comment |
Something like this.
bool forwardReverse = false;
int width = 4;
string line = "";
for (int i = 1; i < maxValue; i++)
{
if (i % width == 0)
{
forwardReverse = !forwardReverse;
Console.WriteLine(line);
line = "";
}
if (forwardReverse)
{
line = line + i;
}
else
{
line = i + line
}
}
Every time you get to the end of a row (width) the Boolean flag changes and the order that new values are added is switched between appending and prepending.
add a comment |
Something like this.
bool forwardReverse = false;
int width = 4;
string line = "";
for (int i = 1; i < maxValue; i++)
{
if (i % width == 0)
{
forwardReverse = !forwardReverse;
Console.WriteLine(line);
line = "";
}
if (forwardReverse)
{
line = line + i;
}
else
{
line = i + line
}
}
Every time you get to the end of a row (width) the Boolean flag changes and the order that new values are added is switched between appending and prepending.
Something like this.
bool forwardReverse = false;
int width = 4;
string line = "";
for (int i = 1; i < maxValue; i++)
{
if (i % width == 0)
{
forwardReverse = !forwardReverse;
Console.WriteLine(line);
line = "";
}
if (forwardReverse)
{
line = line + i;
}
else
{
line = i + line
}
}
Every time you get to the end of a row (width) the Boolean flag changes and the order that new values are added is switched between appending and prepending.
answered 14 hours ago
arsogio996arsogio996
62
62
add a comment |
add a comment |
Here is another simple solution just by extending the OP's method. You can try it out with different row and column sizes by changing values for first 2 variables.
<?
$row_count = 3; //You can change this value depending to how many rows do you want to print
$column_count = 4; //You can change this value depending to how many columns will be at each row
$result = ''; //Variable to hold the output to print
$num = 0; //Variable to hold temporary value for each element
for ($i=1; $i<=$row_count; $i++) {
//Every row
for ($j=1; $j<=$column_count; $j++) {
//Every column
if($i % 2 == 1) {
//If row number is odd, increment the value starting from maximum element of previous row
$num = (($i - 1) * $column_count) + $j;
}
else {
//If row number is even, decrement the value starting from maximum element of current row
$num = ($i * $column_count) - ($j - 1);
}
//Add calculated number to output with an extra space if it's only one character
$result .= $num.($num < 9 ? ' ' : ' ');
}
$result .= '</br>';
}
?>
<html>
<head>
<style type="text/css">
body{
font-family: Courier;
}
</style>
</head>
<body>
<? echo $result; ?>
</body>
</html>
add a comment |
Here is another simple solution just by extending the OP's method. You can try it out with different row and column sizes by changing values for first 2 variables.
<?
$row_count = 3; //You can change this value depending to how many rows do you want to print
$column_count = 4; //You can change this value depending to how many columns will be at each row
$result = ''; //Variable to hold the output to print
$num = 0; //Variable to hold temporary value for each element
for ($i=1; $i<=$row_count; $i++) {
//Every row
for ($j=1; $j<=$column_count; $j++) {
//Every column
if($i % 2 == 1) {
//If row number is odd, increment the value starting from maximum element of previous row
$num = (($i - 1) * $column_count) + $j;
}
else {
//If row number is even, decrement the value starting from maximum element of current row
$num = ($i * $column_count) - ($j - 1);
}
//Add calculated number to output with an extra space if it's only one character
$result .= $num.($num < 9 ? ' ' : ' ');
}
$result .= '</br>';
}
?>
<html>
<head>
<style type="text/css">
body{
font-family: Courier;
}
</style>
</head>
<body>
<? echo $result; ?>
</body>
</html>
add a comment |
Here is another simple solution just by extending the OP's method. You can try it out with different row and column sizes by changing values for first 2 variables.
<?
$row_count = 3; //You can change this value depending to how many rows do you want to print
$column_count = 4; //You can change this value depending to how many columns will be at each row
$result = ''; //Variable to hold the output to print
$num = 0; //Variable to hold temporary value for each element
for ($i=1; $i<=$row_count; $i++) {
//Every row
for ($j=1; $j<=$column_count; $j++) {
//Every column
if($i % 2 == 1) {
//If row number is odd, increment the value starting from maximum element of previous row
$num = (($i - 1) * $column_count) + $j;
}
else {
//If row number is even, decrement the value starting from maximum element of current row
$num = ($i * $column_count) - ($j - 1);
}
//Add calculated number to output with an extra space if it's only one character
$result .= $num.($num < 9 ? ' ' : ' ');
}
$result .= '</br>';
}
?>
<html>
<head>
<style type="text/css">
body{
font-family: Courier;
}
</style>
</head>
<body>
<? echo $result; ?>
</body>
</html>
Here is another simple solution just by extending the OP's method. You can try it out with different row and column sizes by changing values for first 2 variables.
<?
$row_count = 3; //You can change this value depending to how many rows do you want to print
$column_count = 4; //You can change this value depending to how many columns will be at each row
$result = ''; //Variable to hold the output to print
$num = 0; //Variable to hold temporary value for each element
for ($i=1; $i<=$row_count; $i++) {
//Every row
for ($j=1; $j<=$column_count; $j++) {
//Every column
if($i % 2 == 1) {
//If row number is odd, increment the value starting from maximum element of previous row
$num = (($i - 1) * $column_count) + $j;
}
else {
//If row number is even, decrement the value starting from maximum element of current row
$num = ($i * $column_count) - ($j - 1);
}
//Add calculated number to output with an extra space if it's only one character
$result .= $num.($num < 9 ? ' ' : ' ');
}
$result .= '</br>';
}
?>
<html>
<head>
<style type="text/css">
body{
font-family: Courier;
}
</style>
</head>
<body>
<? echo $result; ?>
</body>
</html>
answered 8 hours ago
Aycan YaşıtAycan Yaşıt
1,67542432
1,67542432
add a comment |
add a comment |
Pretty much Nigel's answer, walk through a chunked range, echoing out each row, reversing every other:
<?php
$cols = 4;
$rows = 3;
array_walk(
array_chunk(
range(1, $rows*$cols),
$cols
),
function($v, $k) {
if($k%2)
$v = array_reverse($v);
echo implode(' ', $v), "n";
}
);
Output:
1 2 3 4
8 7 6 5
9 10 11 12
add a comment |
Pretty much Nigel's answer, walk through a chunked range, echoing out each row, reversing every other:
<?php
$cols = 4;
$rows = 3;
array_walk(
array_chunk(
range(1, $rows*$cols),
$cols
),
function($v, $k) {
if($k%2)
$v = array_reverse($v);
echo implode(' ', $v), "n";
}
);
Output:
1 2 3 4
8 7 6 5
9 10 11 12
add a comment |
Pretty much Nigel's answer, walk through a chunked range, echoing out each row, reversing every other:
<?php
$cols = 4;
$rows = 3;
array_walk(
array_chunk(
range(1, $rows*$cols),
$cols
),
function($v, $k) {
if($k%2)
$v = array_reverse($v);
echo implode(' ', $v), "n";
}
);
Output:
1 2 3 4
8 7 6 5
9 10 11 12
Pretty much Nigel's answer, walk through a chunked range, echoing out each row, reversing every other:
<?php
$cols = 4;
$rows = 3;
array_walk(
array_chunk(
range(1, $rows*$cols),
$cols
),
function($v, $k) {
if($k%2)
$v = array_reverse($v);
echo implode(' ', $v), "n";
}
);
Output:
1 2 3 4
8 7 6 5
9 10 11 12
answered 8 hours ago
ProgrockProgrock
4,4131921
4,4131921
add a comment |
add a comment |
The following will do exactly what you want. Short yet effective.
for ($i = 4; $i <= 12; $i += 4) {
echo (($i / 4) % 2) == 0 ? implode(' ', range($i, $i - 3)) . '<br />' : implode(' ', range($i - 3, $i)) . '<br />';
}
add a comment |
The following will do exactly what you want. Short yet effective.
for ($i = 4; $i <= 12; $i += 4) {
echo (($i / 4) % 2) == 0 ? implode(' ', range($i, $i - 3)) . '<br />' : implode(' ', range($i - 3, $i)) . '<br />';
}
add a comment |
The following will do exactly what you want. Short yet effective.
for ($i = 4; $i <= 12; $i += 4) {
echo (($i / 4) % 2) == 0 ? implode(' ', range($i, $i - 3)) . '<br />' : implode(' ', range($i - 3, $i)) . '<br />';
}
The following will do exactly what you want. Short yet effective.
for ($i = 4; $i <= 12; $i += 4) {
echo (($i / 4) % 2) == 0 ? implode(' ', range($i, $i - 3)) . '<br />' : implode(' ', range($i - 3, $i)) . '<br />';
}
edited 14 hours ago
answered 15 hours ago
PeterPeter
4,41943771
4,41943771
add a comment |
add a comment |
Smit Pipaliya is a new contributor. Be nice, and check out our Code of Conduct.
Smit Pipaliya is a new contributor. Be nice, and check out our Code of Conduct.
Smit Pipaliya is a new contributor. Be nice, and check out our Code of Conduct.
Smit Pipaliya is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54652649%2fhow-can-i-arrange-numbers-in-this-side-to-side-pattern%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Look at modulus operator...oo the second row is backwards, thats a bit different
– user3783243
16 hours ago
1
What should the output look like for more than 12 numbers? Should there always be 4 columns? Or always 3 rows? Something else?
– Patrick Q
16 hours ago
5
(Do people really call that kind of pattern a “pyramid”? I’d say that is a Serpentine maybe, but I don’t see what is supposed to be pyramid…achical(?) about this.)
– 04FS
16 hours ago
I guess doing
echo "1 2 3 4n8 7 6 5n9 10 11 12";
isn't fine? You could calculate what the max value of every second row is, and start to count back on indices from 0 if that makes any sense?– Loek
16 hours ago
I can't get modulus operator for even to work as expected but here's a starting point. 3v4l.org/R4HhB
– user3783243
16 hours ago