Even distribution of PHP arrays across columns - php

So, I want to distribute evenly lists across 3 columns. The lists cannot be broken up or reordered.
At the moment, I have 5 lists each containing respectively 4, 4, 6, 3 and 3 items.
My initial approach was:
$lists = [4,4,6,3,3];
$columns = 3;
$total_links = 20;
$items_per_column = ceil($total_links/$columns);
$current_column = 1;
$counter = 0;
$lists_by_column = [];
foreach ($lists as $total_items) {
$counter += $total_items;
$lists_by_column[$current_column][] = $total_items;
if ($counter > $current_column*$links_per_column) {
$current_column++;
}
}
Results in:
[
[4],
[4,6],
[3,3]
]
But, I want it to look like this:
[
[4,4],
[6],
[3,3]
]
I want to always have the least possible variation in length between the columns.
Other examples of expected results:
[6,4,4,6] => [[6], [4,4], [6]]
[4,4,4,4,6] => [[4,4], [4,4], [6]]
[10,4,4,3,5] => [[10], [4,4], [3,5]]
[2,2,4,6,4,3,3,3] => [[2,2,4], [6,4], [3,3,3]]

Roughly what you need to do is loop over the number of columns within your foreach(). That will distribute them for you.
$numrows = ceil(count($lists) / $columns);
$thisrow = 1;
foreach ($lists as $total_items) {
if($thisrow < $numrows){
for($i = 1; $i <= $columns; $i++){
$lists_by_column[$i][] = $total_items;
}
}else{
//this is the last row
//find out how many columns need to fit.
//1 column is easy, it goes in the first column
//2 columns is when you'll need to skip the middle one
//3 columns is easy because it's full
}
$thisrow++;
}
This will be an even distribution, from left to right. But you actually want a modified even distribution that will look symmetrical to the eye. So within the foreach loop, you'll need to keep track of 1.) if you're on the last row of three, and 2.) if there are 2 remainders, to have it skip col2 and push to col3 instead. You'll need to set that up to be able to play around with it,...but you're just a couple of logic gates away from the land of milk and honey.

So, I ended up using this code:
$lists = [4,4,6,3,3];
$columns = 3;
$total_links = 20;
$items_per_column = ceil($total_links/$columns);
$current_column = 1;
$lists_by_column = [];
for ($i = 0; $i < count($lists); $i++) {
$total = $lists[$i];
$lists_by_column[$current_column][] = $lists[$i];
//Loop until reaching the end of the column
while ($total < $items_per_column && $i+1 < count($lists)) {
if ($total + $lists[$i+1] > $items_per_column) {
break;
}
$i++;
$total += $lists[$i];
$lists_by_column[$current_column][] = $lists[$i];
}
//When exiting the loop the last time we need another break
if (!isset($lists[$i+1])) {break;}
//If the last item goes onto the next column
if (abs($total - $items_per_column) < abs($total + $lists[$i+1] - $items_per_column)) {
$current_column++;
//If the last item goes onto the current column
} else if ($total + $lists[$i+1] > $items_per_column) {
$i++;
$lists_by_column[$current_column][] = $lists[$i];
$current_column++;
}
}

Related

Optimisation of O(n4) complexity to O(n) in PHP nested for loop

I am writing one logic to iterate numbers first and then additional logic to putting them into particular subset of array.
What does this code do :
Code accept first $n
its create array of $n number from 1 to $n
Then started converting to subset of $main_array to possible one like
['1'] [1,2] [1,2,3] [2] [2,3] [3] etc. same like this
After creating subset i am counting those some subset which satisfy condition
Condition is xyz[0] should not come in subset with abc[0] vice versa xyz[i] should not come in subset abc[i]. Example 2 and 3 is coming subset then dont count that subset, same 1 and 4 is coming then dont count
here is my nested for loop :
$n = 1299;
$main_array = range(1,$n);
$counter = 0;
$count = sizeof($abc); // $abc and $xyz size will same always.
$abc = [2,1];
$xyz = [3,4];
for ($i=0; $i <$n; $i++) {
for($j = $i;$j < $n; $j++){
$interval_array = array();
for ($k = $i; $k <= $j; $k++){
array_push($interval_array,$main_array[$k]);
}
$counter++;
for ($l=0; $l < $count ; $l++) {
//if block here to additional condition using in_array() php function. which do $counter--
if(in_array($abc[$l], $interval_array) &&
in_array($xyz[$l], $interval_array)){
$counter--;
break;
}
}
}
}
$main_array i have to create on the spot after receiving $n values.
Following is cases :
when running $n = 4 its run in 4s
when running $n = 1200 or 1299 or more than 1000 its run in 60s-123s
Expected execution timing is 9s. I reduce from 124s to 65s by removing function calling inside for loop but its not coming to point.
Expectation of code is if i have array like
$array = [1,2,3];
then
subset need to generate :
[1],[1,2],[1,2,3],[2],[2,3],[3]
Any help in this ?
It's difficult to test performance against your experience, but this solution removes one of the loops.
The way you repeatedly build $interval_array is not needed, what this code does is to just add the new value from the main array on each $j loop. This array is then reset only in the outer loop and so it just keeps the last values and adds 1 extra value each time...
for ($i=0; $i <$n; $i++) {
$interval_array = array();
for($j = $i;$j < $n; $j++){
array_push($interval_array,$main_array[$j]);
// Check output
echo implode(",", $interval_array)."\n";
$counter++;
for ($l=0; $l < $count ; $l++) {
if(in_array($abc[$l], $interval_array) &&
in_array($xyz[$l], $interval_array)){
$counter--;
break 2;
}
}
}
}
adding "\n" to better understanding for subset flow.
import datetime
N = list(range(1, int(input("N:")) + 1))
affected_list = list(map(int, input("affected_list").split()))
poisoned_list = list(map(int, input("poisoned_list").split()))
start_time = datetime.datetime.now()
exclude_list = list(map(list, list(zip(affected_list, poisoned_list))))
final_list = []
for i in range(0, len(N)):
for j in range(i + 1, len(N) + 1):
if N[i:j] not in exclude_list:
final_list.append(N[i:j])
print(final_list)
end_time = datetime.datetime.now()
print("Total Time: ", (end_time - start_time).seconds)

Evenly reducing an indexed array by 10%

I have an array filled with data over the period of a month. The data is computed for every 15 minutes over that period, meaning it's got about 2880 entries.
I need to reduce it by about 10% in order to display the data in a chart (288 data points will render much more nicely than 2880).
Here's what I've tried (it works, but it might be a very bad method):
$count = count($this->Data1Month);
for($i = 0; $i < $count; $i += 10) {
$tempArray[] = $this->DataMonth[$i];
}
$this->Data1Month = $tempArray;
I think you have the most efficient solution, but you do have a mistake though. Array indexes start at zero so 0+10 needs to be 9, like so:
$count = count($this->Data1Month);
for($i = 0; $i < $count; $i += 9) {
$tempArray[] = $this->DataMonth[$i];
}
$this->Data1Month = $tempArray;

Do an action after two rounds of a for loop

I've got a $identifier, $start_number and $end_number.
The start number is the number where the for loop should start
counting from
The end number is where the loop should stop counting
The identifier determinates how much is getting added to the start number
This for loops looks something like this:
$start_number = 102;
$end_number = 1051;
$identifier = 24;
for($i = $start_number; $i <= $end_number; $i += $identifier) {
//The first two times, add 1 to the identifier
//The second two times (we're at 4 now) add 5 to the identifier
//The third two times (were at 6 now) add 10 to the identifier
//The fourth two times (we're at 8 now) add 20 to the identifier
//etc...
}
I want it to add a dynamic number (which changes) to the $identifier each 2 times it loops, how do i do this?
Just keep track of where you are in your loop by using a counter. Then you can use the modulus operator to determine if it an even number iteration. You can add the appropriate value by using an array to store the values to add to $identifier with the count being the key to get your correct value.
$start_number = 102;
$end_number = 1051;
$identifier = 24;
$add = array(
2 => 1,
4 => 5,
6 => 10,
8 => 20
);
$count = 1;
for($i = $start_number; $i <= $end_number; $i += $identifier) {
if ($count % 2 === 0) {
$identifier += $add[$count];
}
$count++;
}
for($i = $identifier; $i <= $end_number; $i += $identifier) {
if($i%2 == 0){
//do your work
}
}

Finding the difference between 2 dates and iterating an image based on the difference

Ive managed to loop through a table and get the difference in days between 2 dates adjacent to each other in the table.
Multiple entries have the same date, i have it now that when that date changes, it displays an image however i want it to display the image as many times as the difference in date
$sql = mysql_query("SELECT * FROM Films_Info")
or die(mysql_error());
$last_value = null;
while ($row = mysql_fetch_assoc($sql)) {
if (!is_null($last_value)) {
$a = new DateTime($row['FilmRelease']);
echo "<p>".$row['FilmName']."</p>";
$interval = $a->diff(new DateTime($last_value));
//echo $interval->format('%d days');
$i = 0;
}
$howManydays = $interval->days;
for ( $i; $howManydays; $i++) {
echo "<img src=\"day.jpg\" />";
$howManydays = 0;
}
$last_value = $row['FilmRelease'];
}
for ( $i = 0; $i < $howManydays; $i++) The second is a conditional statement telling when the loop should stop.
The first section in the for loop where it says $i = 0 initialized the variable $i to 0 and then tests the condition $i < $howManydays.
Let's say $howManydays equals 1. That means 0 < 1, so the loop will perform.
At the end of the loop, the third section is called ($i++), so $i is incremented and now equals 1. The second section is called again to test conditions $i < $howManydays which is asking if 1<1 which it's not, so the loop will exit.
So if $howManydays is greater than 0, the loop should happen the integer amount that is in $howManydays.
You will want to remove $howManydays = 0; within the for loop, if you don't want it to only fire once.
The for loop
for ( $i = 0; $i < $howManydays; $i++){
// ...
}
is somewhat equivalent to the while loop:
$i = 0;
while ( $i < $howManydays ){
// ...
$i++;
}
http://php.net/manual/en/control-structures.for.php for more information
In your code above, you should also check if interval was set. You should probably just do an if rather than a while, if only need one interval.
you could just do a simple division on the interval and print out the image that many times
$last_value_u = $last_value->format('U');
$a_u = $a->format('U');
$interval = $a_u - $last_value_u;
$image_count = intval($interval/86400);
for($i=0;$i<$image_count;$i++)
echo "<p><img src=\"day.jpg\" /></p>";
Update
An alternative option would be to loop through the interval:
for($i=$last_value_u;$i<$a_u;)
{
if(intval(($a_u - $i)/86400) == X)
{
// run special code for specific day
}
else
{
// run code for every other day
}
$i+=86400;
}

How can I check an array for consecutive times?

I have an array of qualified times from my database:
$avail_times = array("9","11","12","13","15","16","17","18");
I want to display 4 consecutive values if they exist, if not I want to continue. For example in the above array, the only place where there are four consecutive numbers that properly follow the one before is 15,16,17,and 18
Thoughts?
This may be a duplicate problem, but I have not found a solution. My situation is a bit different. I need to show only those numbers that are consecutive four or more times. This is what I have come up with, but it is not working properly:
$avail_times = array("9","10","11","13","14","15","16","17","19","20","21","22");
for($i=1, $max = count($times) + 4; $i < $max; $i++)
{
if ($avail_times[$i] == $avail_times[$i + 1] - 1)
{
echo $avail_times[$i];
}
}
This should do you:
$avail_times = array("9","10","11","13","14","15","16","17","19","20","21","22");
$consec_nums = 1;
for($i = 1; $i <count($avail_times); $i++) {
if($avail_times[$i] == ($avail_times[$i - 1] + 1)) {
$consec_nums++;
if($consec_nums == 4) break;
}
else {
$consec_nums = 1;
}
}
if($consec_nums == 4) {
echo "found: {$avail_times[$i-3]}, {$avail_times[$i-2]}, {$avail_times[$i-1]}, {$avail_times[$i]}\n";
}
And a few notes:
array indexing starts at 0, when your for loop starts with $i = 1, you are skipping the first element. Notice that while I start at $i=1, I am comparing $avail_times[$i] and $avail_times[$i-1] so I do cover $avail_times[0].
I don't know what you're doing with $max = count($times). You never define $times.

Categories