I want to calculate an array to another array and then add both like this :
Array1(4,8,7,12);
Array2(3,6);
the result is like this :
3x4+3x8+3x7+3x12+6x4+6x8+6x7+6x12 = 279
I tried with this code and since I'm still new with php I still didn't make any tips I'll be glad thanks in advance
<?php
tab1(4,8,7,12);
tab2(3,6);
$s=0;
for($i=0; $i<$tab1[3]; $i++){
for($j=0; $j<$tab2[1]; $j++){
$s = $s + tab[i] * tab[j];
}
echo "$s";
}
?>
This is actually a piece of cake. I am not sure what tab1 means but I assume you are trying to use this function to get an array of desired(input) numbers.
Using a foreach loop to loop over the two arrays, I came up with the code below:
<?php
$a = [4,8,7,12];
$b = [3,6];
$sum = 0;
foreach ($b as $valueInB) {
foreach ($a as $valueInA) {
$sum += $valueInA * $valueInB;
}
}
echo $sum;
?>
which results in:
279
if you are insisting on using a for loop you can run the code below to get the same result:
<?php
$a = [4,8,7,12];
$b = [3,6];
$sum = 0;
$bLength = count($b);
$aLength = count($a);
for ($i=0; $i < $bLength ; $i++) {
$valueInB = $b[$i];
for ($j=0; $j < $aLength ; $j++) {
$valueInA = $a[$j];
$sum += $valueInA * $valueInB;
}
}
echo $sum;
?>
Please note that you should use the count outside of the loop because looping over the array and calling count each time is not an efficient way. (Thanks to Will B for the comment)
For a more simplistic approach without iteration you can use array_sum on the two arrays.
Example: https://3v4l.org/3gtgE
$a = [4,8,7,12];
$b = [3,6];
$c = array_sum($a) * array_sum($b);
var_dump($c);
Result
int(279)
This works because of the order of operations of:
(3*4) + (3*8) + (3*7) + (3*12) + (6*4) + (6*8) + (6*7) + (6*12) = 279
Equates to the same as the sum of a multiplied by the sum of b:
(4+8+7+12) * (3+6) = 279
Related
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 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
I'm trying to make it so it loops fractions as 1, 1/2, 1/3, 1/4, etc up to 1/100, then add all them together and only show the sum and not the chain of fractions.
The code I have so far looks like this:
<?
$sum = 0;
for($n = 1; $n<=1/100; $n+=1/$n)
{
$sum = $sum + $n;
}
echo $sum;
But it never gives me the right answer, which is 5.18. Any advice?
You need to limit the loop. And you need to increment $n
$sum = 0;
for($n = 1; $n<=100; $n++)
{
$sum = $sum + (1/$n);
}
echo $sum;
//answer 5.1873775176396
Just FYI, for a simple operation like this, your for loop does not even need a body.
$sum = 0;
for($n=1; $n<=100; $sum +=(1/$n++));
echo $sum;
See example four in the php for documentation.
for($n = 1; $n<=; $n+=1/$n)
You must define a limit insecond parameter of for, it runs in infinity
EDIT:
Between second and third parameter, you must insert ;
<?php
$sum = 0;
for ($n=1; $n<=100; $n++) {
$sum = $sum + (1/$n);
}
echo $sum;
// or use round if you want it rounded
//echo round($sum,2);
This code is PSR-2 compliant
Try this:
for ($n = 0, $sum = 0; $n < 100; $n++, $sum += 1 / $n);
echo $sum;
I've created a for loop, but it does not print out the output according to the for loop conditions.
for( $c=0; $c < $total; $c++ )
{
$latestID = AccessControlEntry::orderBy('AccessControlID', 'desc')->first();
$numberID = explode("AC", $latestID->AccessControlID);
$numberID[1] = $numberID[1] + 1;
$newID = "AC";
$newID = $newID.$numberID[1];
}
I grabbed the last ID value (AccessControlID) from the database, and subsequently add 1 ($numberID[1] + 1) for every new entry in AccessControlID.
For eg: $total = 3.
From my understanding of for-loops logic, shouldn't it print out 2 sets of $newID?
Can anyone tell me where/what did I went wrong?
The solution is to bring outside the loop the lines of code which extract out from the DB the value.
$latestID = AccessControlEntry::orderBy('AccessControlID', 'desc')->first();
$numberID = explode("AC", $latestID->AccessControlID);
for( $c=0; $c < $total; $c++ ) {
$numberID[1] = $numberID[1] + 1;
$newID[] = $numberID[1];
}
print_r($newID);
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));