I have created a loop which returns a random number between two values. Cool.
But now I want the script to return the following value too: The number of unique numbers between two similar numbers.
Example:
4
5
8
22
45
3
85
44
4
55
15
23
As you see there is a double which is the four and there are 7 numbers inbetween. So I would like the script to echo these numbers two so in this case it should echo 7 but if there are more doubles in the list it should echo all the numbers between certain doubles.
This is what I have:
for ($x = 0; $x <= 100; $x++) {
$min=0;
$max=50;
echo rand($min,$max);
echo "<br>";
}
Can someone help me or guide me? I'm learning :)
Thanks!
So You need to seperate script for three parts:
getting randoms and save them to array (name it 'result'),
analyze them,
print (echo) results
Simply - instead of printing every step of loop, save them to array(), exit loop, analyze every item with other, example:
take i element of list
check is i+j element is the same
if is it the same - save j-i to second array() (name it 'ranges')
And after this, print two arrays (named by me as 'result' and 'ranges')
UPDATE:
Here's solution, hope You enjoy:
$result = array(); #variable is set as array object
$ranges = array(); #same
# 1st part - collecting random numbers
for ($x = 0; $x < 20; $x++)
{
$min=0;
$max=50;
$result[] = rand($min,$max); #here's putting random number to array
}
$result_size = count($result); #variable which is containg size of $result array
# 2nd part - getting ranges between values
for ($i = 0; $i < $result_size; $i++)
{
for ($j = 0; $j < $result_size; $j++)
{
if($i == $j) continue; # we don't want to compare numbers with itself,so miss it and continue
else if($result[$i] == $result[$j])
{
$range = $i - $j; # get range beetwen numbers
if($range > 0 ) # this is for miss double results like 14 and -14 for same comparing
{
$ranges[$result[$i]] = $range;
}
}
}
}
#3rd part - priting results
echo("RANDOM NUMBERS:<br>");
foreach($result as $number)
{
echo ("$number ");
}
echo("<br><br>RANGES BETWEEN SAME VALUES:<br>");
foreach($ranges as $number => $range)
{
echo ("For numbers: $number range is: $range<br>");
}
Here's sample of echo ($x is set as 20):
RANDOM NUMBERS:
6 40 6 29 43 32 17 44 48 21 40 2 33 47 42 3 22 26 39 46
RANGES BETWEEN SAME VALUES:
For numbers: 6 range is: 2
For numbers: 40 range is: 9
Here is your fish:
Put the rand into an array $list = array(); and $list[] = rand($min,$max); then process the array with two for loops.
$min=0;
$max=50;
$list = array();
for ($x = 0; $x <= 100; ++$x) {
$list[] = rand($min,$max);
}
print "<pre>";print_r($list);print "</pre>";
$ranges = array();
$count = count($list);
for ($i = 0; $i < $count; ++$i) {
$a = $list[$i];
for ($j = $i+1; $j < $count; ++$j) {
$b = $list[$j];
if($a == $b) {
$ranges[] = $j-$i;
}
}
}
print "<pre>";print_r($ranges);print "</pre>";
Ok, I got a digital book of 30.000 lines. I want to show only the first 20 lines of a chapter as a preview, every chapter got 300 lines.
Anyone an idea how to solve this? I tried the following:
foreach ($lines as $n => $line) {
if ($n >= 0 && $n =< 20) {
echo $line;
}
This will result in showing the first 20 lines of the first chapter. So how do I repeat this for all the other lines?
show 0-20
show 300-320
show 600-620
show 900-920
etc..
Thanks in advance!
You can do it with:
$rgChapters = [];
$rFile = fopen('/path/to/file', 'r');
$iLines = 20;
$iChapter = 300;
$i = 0;
while($sData = fgets($rFile) && !feof($rFile))
{
if($i % $iChapter < $iLines)
{
$rgChapters[floor($i/$iChapter)].=$sData.PHP_EOL;
}
$i++;
}
fclose($rFile);
-as a result, you'll get an array with first 20 lines every 300 lines (or you can directly output data rather than store it in array)
To print chapter 5
$chapter = 5;
$pages = 20;
$start = $chapter*$pages;
for($i=$start, $c=$start+$pages-1; $i < $c; $i++)
{
echo $lines[$i];
}
Just found the answer myself on an earlier SO question:
foreach ($lines as $n => $line) {
if ($n % 300 > 0 && $n % 100 <= 20) {
echo $line; // or whatever
}
}
Based on the answer written by Michael Berkowski (PHP read in every 10 out of 100 lines)
Im trying to compare the first 10 lines of 100 lines of $completeGoogle(5000Lines) and count the number of matches with another file. However my count should be between 1-10 and I am getting an answer of 5010???
foreach(new SplFileObject($completeGoogle) as $n => $line)
if($n % 100 < 10)
{
$f_Api = fopen($apiFile,'r');
for ($i = 0 ;$i < 10; $i++)
{
$top10 = fgets($f_Api);
if ($line === $top10);
{
$count++;
}
}
fclose($f_Api);
}
You compare each 1-9, 100-109... line in one file with 10 lines from another and sum all matches in one variable $count.
If everything is equal you must get 500 (lines from first file) * 10 (lines from other) = 5000 matches.
The reason why this was failing my was because of a simple ";" after the if statement.
foreach(new SplFileObject($completeGoogle) as $n => $line)
if($n % 100 < 10)
{
$f_Api = fopen($apiFile,'r');
for ($i = 0 ;$i < 10; $i++)
{
$top10 = fgets($f_Api);
if ($line === $top10)
{
$count++;
}
}
fclose($f_Api);
}
I need this output..
1 3 5
2 4 6
I want to use array function like array(1,2,3,4,5,6). If I edit this array like array(1,2,3), it means the output need to show like
1 2 3
The concept is maximum 3 column only. If we give array(1,2,3,4,5), it means the output should be
1 3 5
2 4
Suppose we will give array(1,2,3,4,5,6,7,8,9), then it means output is
1 4 7
2 5 8
3 6 9
that is, maximum 3 column only. Depends upon the the given input, the rows will be created with 3 columns.
Is this possible with PHP? I am doing small Research & Development in array functions. I think this is possible. Will you help me?
For more info:
* input: array(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
* output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10
You can do a loop that will automatically insert a new line on each three elements:
$values = array(1,1,1,1,1);
foreach($values as $i => $value) {
printf('%-4d', $value);
if($i % 3 === 2) echo "\n";
}
EDIT: Since you added more information, here's what you want:
$values = array(1,2,3,4,5);
for($line = 0; $line < 2; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < count($values); $i+=2) {
printf('%-4d', $values[$i]);
}
}
And if you want to bundle all that in a function:
function print_values_table($array, $lines = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
EDIT 2: Here is a modified version which will limit the numbers of columns to 3.
function print_values_table($array, $maxCols = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
$lines = ceil($count / $maxCols);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
So, the following:
$values = range(1,25);
print_array_table($values);
Will output this:
1 10 19
2 11 20
3 12 21
4 13 22
5 14 23
6 15 24
7 16 25
8 17
9 18
One solution is to cut the array into chunks, representing the columns, and then print the values in row order:
$cols = array_chunk($arr, ceil(count($arr)/3));
for ($i=0, $n=count($cols[0]); $i<$n; $i++) {
echo $cols[0][$i];
if (isset($cols[1][$i])) echo $cols[1][$i];
if (isset($cols[2][$i])) echo $cols[2][$i];
}
If you don’t want to split your array, you can also do it directly:
for ($c=0, $n=count($arr), $m=ceil($n/3); $c<$m; $c++) {
echo $arr[$c];
for ($r=$m; $r<$n; $r+=$m) {
echo $arr[$c+$r];
}
}
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}\n{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}".PHP_EOL."{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
$second_row_start = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index == $second_row_start) echo PHP_EOL;
echo "$value ";
}
or, perhaps if you want a longer array split into columns of 3?
$a = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
$row_length = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index%$row_length == 0) echo PHP_EOL;
echo "$value ";
}
which gives
1 2 3
4 5 6
7 8 9
10 11 12
13
one solution is :
your array has N elements, and you want 3 columns, so you can get the value of each cell with $myarray[ column_index + (N/3) + line_index ] (with one or two loops for columns and lines, at least for lines)
I hope this will help you
Bye
Here's something I whipped up. I'm pretty sure this could be more easily accomplished if you were using HTML lists, I've assumed you can't use them.
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16);
$max = count($arr);
$cols = 3;
$block = ceil($max / $cols);
for ($i = 0; $i < $block ; $i++) {
echo $arr[$i] . ' ';
for ($j = 1; $j < $cols; $j++) {
$nexKey = $i + $block * $j;
if (!isset($arr[$nexKey])) break;
echo $arr[$nexKey] . ' ';
}
echo '<br>';
}
NOTE : You can easily refactor the code inside the loop that uses $nexkey variable by making it into a loop itself so that it works for any number of columns. I've hardcoded it.
Uses loops now.
assuming I have $rows = 4, and $cols = 4;, How do I create a array with 16 elements in a spiral order, like:
1, 2, 3, 4,
12,13,14,5,
11,16,15,6,
10,9, 8, 7,
My solution is quite verbose, because the intent is for you to examine it and learn how it works.
<?php
/**
* Creates a 2D array with the given dimensions,
* whose elements are numbers in increasing order
* rendered in a 'spiral' pattern.
*/
function createSpiral($w, $h) {
if ($w <= 0 || $h <= 0) return FALSE;
$ar = Array();
$used = Array();
// Establish grid
for ($j = 0; $j < $h; $j++) {
$ar[$j] = Array();
for ($i = 0; $i < $w; $i++)
$ar[$j][$i] = '-';
}
// Establish 'used' grid that's one bigger in each dimension
for ($j = -1; $j <= $h; $j++) {
$used[$j] = Array();
for ($i = -1; $i <= $w; $i++) {
if ($i == -1 || $i == $w || $j == -1 || $j == $h)
$used[$j][$i] = true;
else
$used[$j][$i] = false;
}
}
// Fill grid with spiral
$n = 0;
$i = 0;
$j = 0;
$direction = 0; // 0 - left, 1 - down, 2 - right, 3 - up
while (true) {
$ar[$j][$i] = $n++;
$used[$j][$i] = true;
// Advance
switch ($direction) {
case 0:
$i++; // go right
if ($used[$j][$i]) { // got to RHS
$i--; $j++; // go back left, then down
$direction = 1;
}
break;
case 1:
$j++; // go down
if ($used[$j][$i]) { // got to bottom
$j--; $i--; // go back up, then left
$direction = 2;
}
break;
case 2:
$i--; // go left
if ($used[$j][$i]) { // got to LHS
$i++; $j--; // go back left, then up
$direction = 3;
}
break;
case 3:
$j--; // go up
if ($used[$j][$i]) { // got to top
$j++; $i++; // go back down, then right
$direction = 0;
}
break;
}
// if the new position is in use, we're done!
if ($used[$j][$i])
return $ar;
}
}
/**
* Assumes the input is a 2D array.
*/
function print2DGrid($array) {
foreach ($array as $row) {
foreach ($row as $col) {
print sprintf("% 2d ", $col);
}
print "\n";
}
}
$width = 12;
$height = 8;
print2DGrid(createSpiral($width, $height));
?>
Here it is in action, giving the following output:
0 1 2 3 4 5 6 7 8 9 10 11
35 36 37 38 39 40 41 42 43 44 45 12
34 63 64 65 66 67 68 69 70 71 46 13
33 62 83 84 85 86 87 88 89 72 47 14
32 61 82 95 94 93 92 91 90 73 48 15
31 60 81 80 79 78 77 76 75 74 49 16
30 59 58 57 56 55 54 53 52 51 50 17
29 28 27 26 25 24 23 22 21 20 19 18
Hope this helps.
Use a vector and boolean values. Iterate on the X axis to start with until you reach the end of the row. Set the value to true for each position as you traverse it. Anytime you reach a border or boolean true, turn right.
So on the first row your "vector" would change the X increment to zero and the Y increment to 1. Then you would check the value of the increment at each turn and accommodate the 4 scenarios.
This is the first way I thought of.
The second way would not use booleans, but would instead simply keep track of how many columns or rows are left in front of the cursor on its path, decreasing the X or Y remaining on each turn. The rest of the logic would remain the same.
When you reach the center, you will hit a loop where there are no more iterations possible. You can catch this by verifying the number of possibilities around the square, or simply counting down from N number of total squares from where you began, and stopping when the number hits zero.
You can use the above method for a square of any size.
The algorith is not very dificult. You have to iterate from 1 up to $rows*$cols. During the iteration, you have to calculate the position of the current number in the matrix ($x,$y). The first on will be in (1,1) of course. The following one will be ($x+1,$y) because you are heading east. So, the position of each number is base on the position of the previous one and the currect direction.
The tricky part of the algorith is to calculate the direction. But if you look at it, you will see that the direction changes clockwise each time you bump into a used cell, or you get out of bounds.
All in all, this is going to be ~30 lines of PHP code.
I hope this helps.
There is a similar challenge in PHP golf: http://www.phpgolf.org/challenge/Spiral. Somebody solved it in only 130 characters!