Getting total value of an array with condition - php

I need to get the total value of this array of all the numbers above or equal to 0.
This is the array
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
This is the code i have so far, but it only shows the highest number of the array and doesnt count the values up and shows the total.
$totaal = 0;
for($y=0; $y < count($aReeks); $y++)
{
if($totaal < $aReeks[$y] && $aReeks[$y] > 0)
$totaal = $aReeks[$y];
}
I have to do it with a for loop.

Here's a quick way:
$total = array_sum(array_filter($aReeks, function($n) { return $n > 0; }));
Filter the array for values greater than 0
Sum that array
Oh I now see the "I have to do it with a for loop.", so this won't be accepted for your homework I imagine.

$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
$total=0;
for($i =0 ; $i< count($aReeks) ; $i++)
{
if($aReeks[$i]>=0)
{
$total+= $aReeks[$i];
}
}
echo $total ;
?>
Output
11859

You are making 2 major mistakes one is in if condition which is $totaal < $aReeks[$y] you don't need this check at all. Secondly rather than summing up the value of each item to the total of all previous items... you are simply assigning the value to the $totaal variable inside the loop.
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
$totaal = 0;
for($y=0; $y < count($aReeks); $y++)
{
if($aReeks[$y] > 0)
$totaal = $totaal + $aReeks[$y];
}

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)

Exam Qn: Convert do while loop to for loop (PHP)

Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:
"Convert the following script using for loop without affecting the output:-"
<?php
//Convert into for loop
$x = 0;
$count = 10;
do
{
echo ($count. "<BR>");
$count = $count - 2;
$x = $x + $count;
}
while($count < 1)
echo ($x);
?>
Please help me as my computer sir is out of station and I am really puzzled by it.
Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.
Try:
$count = 10;
$x = 0;
$firstRun = true;
for(; $count > 1 || $firstRun;) {
$firstRun = false;
echo ($count . "<BR>");
$count -= 2;
$x = $x + $count;
}
echo ($x);
By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.
EDIT
$firstRun to avoid infiniteLoop
$count in loop
EDIT
Fixed code for new requirement
Removed unnecessary code
Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1.
The output of your teacher's code is:
10
8
I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output:
10
8
6
4
2
20
Then a good for() loop would have been :
$x = 0;
$count = 10;
for($i = $count; $i > 1; $i -= 2)
{
$count -= 2;
echo $i . "<br>";
$x += $count;
}
echo $x;
Which will output the same values.
If you can, ask your teacher for this, and comment the answer ^^ ahahah

Finding the averege in a loop counting to 100

I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.
for ($x = 3; $x < 100; $x+=3) {
echo $x.", ";
}
This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?
I believe the intention here is to learn about loops, otherwise this stuff can be done without looping too.
For learning purpose, you can simply introduce two variables count and sum and compute them inside the loop. For count, you just increment it on each iteration. For sum, you add the current value of x into sum. After the loop you print both variables.
$count = 0;
$sum = 0;
for ($x = 3; $x < 100; $x+=3) {
echo $x.", ";
$count++;
$sum+=$x;
}
echo $sum;
echo $count;
add your elements into an array and then use array_sum to sum the array elements , then divide the sum by the count of your array
$arr = [];
for ($x = 3; $x < 100; $x+=3) {
// echo $x.", \n";
$arr[] = $x;
}
print_r(array_sum($arr) / count($arr));
// Output : 51
$i=0;
$tempx=0;
for ($x = 3; $x < 100; $x+=3) {
//total sum
$tempx = $tempx + $x;
//count of how many times the loop ran in this case 33 times
$i++;
}
//first $i was 0 so we add 1
$i=$i + 1;
//getting the average
$average=$tempx / $i;
echo $average;
//output
For the last answer i think we should not do:
//first $i was 0 so we add 1 $i=$i + 1;
Regards

Iteration in PHP dynamic variable

function stepzero(){
$alcount = $_POST["alcount"];//retrieve number of row
$crcount = $_POST["crcount"];//retrieve number of coloumn
for ($x=1; $x <=$crcount ; $x++) { //Loop for coloumn
for ($y=1; $y <=$alcount ; $y++) { //Loop for row
${"v".$y."t".$x} = $_POST["r".$y."c".$x];//retrieve value of table
${"v".$y."t".$x} = ${"v".$y."t".$x}*${"v".$y."t".$x};//square the value
${"nv".$y."t".$x} = ${"nv".$y."t".$x} + ${"v".$y."t".$x}; //not working
echo ${"nv".$y."t".$x};
echo "<br>";
}
}
}
I have this function to retrieve value from table , square it and then sum it. But ${"nv".$y."t".$x} returns the same value as ${"v".$y."t".$x} (it didn't sum it). How can I fix this?
This code could be a lot simpler.
For example, these two lines:
${"v".$y."t".$x} = ${"v".$y."t".$x}*${"v".$y."t".$x};//square the value
${"nv".$y."t".$x} = ${"nv".$y."t".$x} + ${"v".$y."t".$x}; //not working
Could be better written as:
${"v".$y."t".$x} *= ${"v".$y."t".$x};//square the value
${"nv".$y."t".$x} += ${"v".$y."t".$x}; //not working
If you just want to get the sum of the squares of a bunch of values, try this:
function stepzero(){
$alcount = $_POST["alcount"];//retrieve number of row
$crcount = $_POST["crcount"];//retrieve number of coloumn
$sum = 0;
for ($x=1; $x <=$crcount ; $x++) { //Loop for coloumn
for ($y=1; $y <=$alcount ; $y++) { //Loop for row
$sum += $_POST["r".$y."c".$x] * $_POST["r".$y."c".$x];
}
}
return $sum;
}

php loop question

hello i'm beginner for programming I've got a homework. googled it but couldnt find anything...
i need to get the total value of numbers from 1 to 10. this need to be done in loop. but couldn't figure which loop should i use. if you can also give me an example code thats would be great.
This is a homework question, I'm not sure why people are just giving you an answer to copy-paste.
Achieving the sum of numbers 1..10 is pretty simple. You will need to initialise an empty int var before your loop, and for each iteration from 0 up to and including 10 you will add your int var to the current iteration.
For example:
sum = 0;
for num in range 1 to 10:
sum = sum + num;
<?php
$start = 0; // set the variable that will hold our total
for($i=1;$i<11;$i++){ // set a loop, read here: http://php.net/manual/en/control-structures.for.php for more info
$start += $i; // add $i to our start value
}
echo $start; // display our final value
I would use a for loop.
$total = 0;
for($i = 1; $i <= 10; $i++){
$total += $i;
}
Using the for loop:
<?php
$sum = 0;
for($i = 1; $i <= 10; $i++){
$sum += $i;
}
Using the foreach loop:
<?php
$sum = 0;
foreach(range(1,10) as $num){
$sum += $num;
}
echo $sum; // prints 55
And disregarding your assignment, here is an easier way:
echo array_sum(range(1,10));

Categories