I'm struggling with some loop in loop handling. I want to output one incremental item of the $additional array after each 3 items of the $items array. Also, when we arrive at item-15 in the $items array, I want to start from extra-1 again with $additional array.
$items = array(
"item-1",
"item-2",
"item-3",
"item-4",
"item-5",
"item-6",
"item-7",
"item-8",
"item-9",
"item-10",
"item-11",
"item-12",
"item-13",
"item-14",
"item-15",
);
$additional = array(
"extra-1",
"extra-2",
"extra-3",
"extra-4",
);
In the end I want to end up with something like this:
"item-1",
"item-2",
"item-3",
"extra-1",
"item-4",
"item-5",
"item-6",
"extra-2",
"item-7",
"item-8",
"item-9",
"extra-3",
"item-10",
"item-11",
"item-12",
"extra-4",
"item-13",
"item-14",
"item-15",
"extra-1"
I tried some stuff with different loops (for, foreach and while) in combination with different counters.
Any help is appreciated!
The following code does the job:
$length = count($items);
$additionalLength = count($additional);
for ($i = 1; $i <= $length; ++$i) {
echo $items[$i - 1] . "\n";
if ($i % 3 === 0) {
echo $additional[(($i / 3) - 1) % $additionalLength] . "\n";
}
}
Related
Excuse me, I want to ask about the iteration step.
i have productdata like this
and criteria data
and alternative data as a liaison / place for the main data from the two tables above
i want to make iteration or loop $nilaiprefensi like below
with calculations like this
$nilaiprefensi[0]= [["A1,A2"],[2-4],[5-9],[10-9],[3-9],[6-8],[4-8],[120-120]]
$nilaiprefensi[1]= [["A1,A3"],[2-3],[5-8],[10-6],[3-8],[6-16],[4-9],[120-155]]
..
$nilaiprefensi[5]= [["A2,A1"],[4-2],[9-5],[9-10],[9-3],[8-6],[8-4],[120,120]]
I've tried several times to make this loop function, but it doesn't work, here's my latest code
for ($i = 0; $i <$loop; $i++) { //30
for ($j = 0; $j < count($products); $j++) {
if ($i !== $j) {
$p[$i][$j][0] = ('A' . $i + 1) . ' , A' . $j + 1;
for ($k = 1; $k < count($kriteria); $k++) {
$p[$i][$j][$k]=$alternatif[$k-1]->kriteria_data."-".$alternatif[$i]->kriteria_data;
}
}
}
}
dd($p);
What is the correct looping function to get the expected result, please help, thanks 🙏🙏
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)
I want to print all combination of sub range in an given array. I have an array of y number of elements in it from which I want to print all combination of contiguous sub range.
Constraint is : each sub range should have at least 2 elements and each element in sub range should be contiguous. It should share same border of each element.
For example, We have an array of 7 elements [11,12,13,14,11,12,13]
So, the total number of sub range combination will [7 * (7-1) /2] = 21
So, the Output will be something like this:
11,12
12,13
13,14
14,11
11,12
12,13
11,12,13
12,13,14
13,14,11
...
11,12,13,14 and so on (total 21 combination as per above array)
we should not print any combination which is not contiguous. example: [11,12,14] is not valid combination as it skips the element "13" in between.
I am able to print the combination with 2 elements but i am having difficulty in printing more then 2 elements combination.
Below is what I have tried so far.
$data=array("11","12","13","14","11","12","13");
$totalCount=count($data);
for($i=0;$i<$totalCount;$i++){
if(($i+1) < ($totalCount)){
echo "[".$data[$i].",".$data[$i+1]."]<br>";
}
}
You can do that:
$arr = [11,12,13,14,11,12,13];
function genComb($arr, $from = 1, $to = -1) {
$arraySize = count($arr);
if ($to == -1) $to = $arraySize;
$sizeLimit = $to + 1;
for ($i = $from; $i < $sizeLimit; $i++) { // size loop
$indexLimit = $arraySize - $i + 1;
for ($j = 0; $j < $indexLimit; $j++) { // position loop
yield array_slice($arr, $j, $i);
}
}
}
$count = 0;
foreach (genComb($arr, 2) as $item) {
echo implode(',', $item), PHP_EOL;
$count++;
}
echo "total: $count\n";
Casimir et Hippolyte was faster, but you can gain huge performance by processing each contiguous section independently:
function getCombos(&$data) {
$combos = array();
$count = count($data);
$i = 0;
while ($i < $count) {
$start = $i++;
while ($i < $count && $data[$i - 1] + 1 == $data[$i]) // look for contiguous items
$i++;
if ($i - $start > 1) // only add if there are at least 2
addCombos($data, $start, $i, $combos); // see other answer
}
return $combos;
}
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++;
}
}
I have an array that I am looping through and breaking up into chunks of 50. However occasionally the number of items inside that array are more than what fits inside that chunk of 50 ex.:
$array = array(); // has 220 rows
for ($i = 0; $i < count($array); $i++) {
$j[] = $i;
if ($i % 50 == 1) {
print_r($j); // do something here with the 50 rows
$j = null;
}
}
The problem here is that this will not print anything after 201. I know there is some algebraic math involved in solving this but I am drawing a blank. Its times like these where I really wish I had paid attention in math class back in high school.
I think array_chunk fits up your requirement and no maths required.
$result_array = array_chunk($array, 50, true);
Add additional condition
if ($i % 50 == 1 || count($array)-1 == $i)
You just have to redeclare the array is my guess:
$array = array(); // has 220 rows
for ($i = 0; $i < count($array); $i++) {
$j[] = $i;
if ($i % 50 == 1) {
print_r($j); // do something here with the 50 rows
$j = array() ;
}
}
Once you perform $j = null there is no way you can do $j[] = $i
$array = array(); // has 220 rows
for ($i = 0; $i < count($array); $i++) {
$j[] = $i;
if ($i % 50 == 1) {
doSomething($j); // do something here with the 50 rows
$j = array(); // reset the array
}
}
doSomething($j); // with the last 20 entries
After your loop is finished, you will have the remaining 201 through 220 entries in $j, so just do your stuff again.
array_chunk
might be useful. Basically splits the array into chunks returning a multi dimensional array