I need to calculate the average increase of array values, and I've made a little script which works, but I'd like to know if:
There is a better, more efficient way of doing this
My logic is correct here in calculating the average increase
Lets say I have an array like so:
$array = array(5,10,15,10,0,15);
Lets also imagine that each array item is 1 day, and the value is some counter for that day. I would like to calculate the average increase/decrease in the counter.
What I've done, is looped through the array, and altered the values so that the current item = current item - previous item, what way I'm left with an array which would look like so:
$array = array(5,5,-5,-10,15);
Then I calculate the average as per normal, which in this example would give me a 2 average increase on a daily basis.
Code here:
$array = array(5,10,15,10,0,15);
$count = count($array);
for($i=0;$i<$count;$i++) {
if($i==0) {
$value = $array[$i];
unset($array[$i]);
}
else {
$tmp = $array[$i];
$array[$i] -= $value;
$value = $tmp;
}
}
echo array_sum($array) / count($array);
Is the logic correct here, and is there a more efficient way of doing this, maybe without the loop?
Thanks in advance :)
EDIT: Updated code to account for excluding first value
How about this:
function moving_average($array) {
for ($i = 1; $i < sizeof($array); $i++) {
$result[] = $array[$i] - $array[$i-1];
}
return array_sum($result)/count($result);
}
Try this :
$array = array(5,10,15,10,0,15);
$array2 = $array;
array_pop($array2);
array_unshift($array2, $array[0]);
$subtracted = array_map(function ($x, $y) { return $y-$x; } , $array2, $array);
array_shift($subtracted); /// Comment this if you want six values with 0 as first value
echo array_sum($subtracted) / count($subtracted);
Here's a snazzy one-liner for you:
$days = array(5, 10, 15, 10, 0, 15);
$deltas = array_slice(array_map(function($day1, $day2) {
return $day2 - $day1;
}, $days, array_slice($days, 1)), 0, -1);
var_dump(array_sum($deltas) / count($deltas));
$array = array(5,10,15,10,0,15);
list($prevVal) = array_slice($array, 1);
array_walk($array, function($value, $key, &$prevVal) use(&$array){
if ($key==0) { return; }
$array[$key] = ($value - $prevVal);
$prevVal = $value;
}, $prevVal);
echo array_sum($array) / count($array);
Outputs 1.6666666666667 in float(3.0994415283203E-5)
Related
I have an array of n elements and I need to get random 20% of those elements into another array. Is there any function which can achieve this?
Currently what I can think of is this:
foreach ($orders as $order) {
if (rand(1, 100) > 80) {
echo('20%');
} else {
echo('80%');
}
}
Is there a more optimal way?
You could shuffle the array and then take the first 20% elements.
$array = [1, 2, 3, 4];
shuffle($array);
$twenty = array_slice($array, 0, floor(count($array) / 5));
$eighty = array_slice($array, floor(count($array) / 5));
The simplest solution is probably to use shuffle:
shuffle($orders);
for ($i = 0; $i < count($orders) / 5; $i++) {
// do something with the first 20% of elements
}
for (; $i < count($orders); $i++) {
// do something with the rest of the array
}
To get two arrays by one function call, use array_splice function. After
shuffle($array);
$twenty = array_splice($array, floor(count($array) / 5 * 4));
$twenty will held 1/5 of source array and $array - other items
Shuffle is the simplest solution for this case
$array = [1,2,3,4]
shuffle($array);
$firstSlice = array_slice($array , 0 , count($array)/2);
$secondSlice = array_slice($array , count($array)/2 , count($array));
I have two arrays which I want to multiply and get the final sum. First one is fixed but the second one could have missing elements. For example:
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(1, 3, 5);
Lets say I've got missing elements $array2[1] and $array2[3]. I want to be able to multiply and sum up the rest as:
$sum = array_sum($array1[0] * $array2[0] + $array1[1] * $array2[1] + $array1[2] * $array2[2] + $array1[3] * $array2[3] + $array1[4] + $array2[5]);
Length of arrays may also vary so can't do it the way I've written it above. Any suggestions?
You can complete the array2 missing values as 1, then make the two array have the same length.
$missingKeys = [1,3];
foreach($missingKeys as $k)
{
$array2[$k] = 1;
}
$sum = 0;
foreach($array1 as $k => $v)
{
$sum += $v * $array1[$k];
}
Ok, I didn't use my own advise, but I think this might work?
$total = 0;
foreach ($array1 as $index => $value)
{
if (isset($array2[$index])) $total += $value*$array2[$index];
else $total += $value;
}
echo $total;
The assumption is that all elements of $array2 are present in $array1, but not necessarily the other way around.
As you wrote in your question that the first array is leading (has all the indexes) you only need to iterate over it and eventually multiply with the value from the second array or one:
$sum = 0;
foreach ($array1 as $k => $v) {
$sum += $v * ($array2[$k] ?? 1);
}
Different to the accepted answer, there is no need to manipulate the second array.
If I understood your question properly, and your looking for array multiplication, you could use 2 for loops, iterating one of them and multiplying. Your probably looking for something like this:
for ($i = 0; $i < count($array1); $i++) {
for ($j = 0; $j < count($array2); $j++) {
$sum += $array1[$i] * $array2[$j];
}
}
Given the following array:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
And assuming $n = 2, what is the most efficient way to get a count of each value in the array within $n of each value?
For example, 6 has 3 other values within $n: 5,7,7.
Ultimately I'd like a corresponding array with simply the counts within $n, like so:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
Is a simple foreach loop the way to go? CodePad Link
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);
My last answer was written without fully groking the problem...
Try sorting the array, before processing it, and leverage that when you run through it. This has a better runtime complexity.
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
asort($arr);
$n = 2;
$cnt = count($arr);
$counts = array_pad(array(), $cnt, 0);
for ($x=0; $x<$cnt; $x++) {
$low = $x - 1;
$lower_range_bound = $arr[$x]-$n;
while($low >= 0 && ($arr[$low] >= $lower_range_bound)) {
$counts[$x]++;
$low--;
}
$high = $x + 1;
$upper_range_bound = $arr[$x]+$n;
while($high < $cnt && $arr[$high] <= $upper_range_bound) {
$counts[$x]++;
$high++;
}
}
print_r($arr);
print_r($counts);
Play with it here: http://codepad.org/JXlZNCxW
If I have a PHP array:
$array
With values:
45,41,40,39,37,31
And I have a variable:
$number = 38;
How can I return the value?:
39
Because that is the closest value to 38 (counting up) in the array?
Regards,
taylor
<?php
function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array); // or return NULL;
}
?>
Here is a high-level process to get the desired results and work for any array data:
Filter the array keeping on values greater than or equal to the target and then select the lowest remaining value. This is the "best" value (which may be "nothing" if all the values were less) -- this is O(n)
Alternatively, sort the data first and see below -- this is O(n lg n) (hopefully)
Now, assuming that the array is sorted ASCENDING, this approach would work:
Loop through the array and find the first element which is larger than or equal to the target -- this is O(n)
And if the array is DESCENDING (as in the post), do as above, but either:
Iterate backwards -- this is O(n)
Sort it ASCENDING first (see fardjad's answer) -- this is O(n lg n) (hopefully)
Iterate forwards but keep a look-behind value (to remember "next highest" if the exact was skipped) -- this is O(n)
Happy coding.
EDIT typo on array_search
Yo... Seems easy enough. Here's a function
<?php
$array = array(45,41,40,39,37,31);
function closest($array, $number){
#does the array already contain the number?
if($i = array_search( $number, $array)) return $i;
#add the number to the array
$array[] = $number;
#sort and refind the number
sort($array);
$i = array_search($number, $array);
#check if there is a number above it
if($i && isset($array[$i+1])) return $array[$i+1];
//alternatively you could return the number itself here, or below it depending on your requirements
return null;
}
to Run echo closest($array, 38);
Here's a smaller function that will also return the closest value. Helpful if you don't want to sort the array (to preserve keys).
function closest($array, $number) {
//does an exact match exist?
if ($i=array_search($number, $array)) return $i;
//find closest
foreach ($array as $match) {
$diff = abs($number-$match); //get absolute value of difference
if (!isset($closeness) || (isset($closeness) && $closeness>$diff)) {
$closeness = $diff;
$closest = $match;
}
}
return $closest;
}
Do a linear scan of each number and update two variables and you'll be done.
Python code (performance is O(N), I don't think it's possible to beat O(N)):
def closestNum(numArray, findNum):
diff = infinity # replace with actual infinity value
closestNum = infinity # can be set to any value
for num in numArray:
if((num - findNum) > 0 and (num - findNum) < diff):
diff = num - findNum
closestNum = num
return closestNum
Please add null checks as appropriate.
If you really want the value that's "closest" in distance, even if it's a lesser value, try this, which #Jason gets most of the credit for.
Imagine a scenario when you want the closest number to 38.9 in the following:
$array = array(37.5, 38.5, 39.5);
Most of the solutions here would give you 39.5, when 38.5 is much closer.
This solution would only take the next highest value if what you're looking is in the exact middle between two numbers in the array:
function nearest_value($value, $array) {
if (array_search($value, $array)) {
return $value;
} else {
$array[] = $value;
sort($array);
$key = array_search($value, $array);
if ($key == 0) { return $array[$key+1]; }
if ($key == sizeof($array)-1) { return $array[$key-1]; }
$dist_to_ceil = $array[$key+1]-$value;
$dist_to_floor = $value-$array[$key-1];
if ($dist_to_ceil <= $dist_to_floor) {
return $array[$key+1];
} else {
return $array[$key-1];
}
}
}
What it lacks in elegance, it makes up for in accuracy. Again, much thanks to #Jason.
Try this simple PHP function:
<?php
function nearest($number, $numbers) {
$output = FALSE;
$number = intval($number);
if (is_array($numbers) && count($numbers) >= 1) {
$NDat = array();
foreach ($numbers as $n)
$NDat[abs($number - $n)] = $n;
ksort($NDat);
$NDat = array_values($NDat);
$output = $NDat[0];
}
return $output;
}
echo nearest(90, array(0, 50, 89, 150, 200, 250));
?>
I made a shorter function for that:
function nearestNumber($num, $array) {
if(!in_array($num, $array)) $array[] = $num;
sort($array);
$idx = array_search($num, $array);
if(($array[$idx] -$array[$idx-1]) >= ($array[$idx+1] -$array[$idx])) return $array[$idx+1];
else return $array[$idx-1];
}
Works great in my case: $array = array(128,160,192,224,256,320); $num = 203 :)
It's taking the nearest number and if there's the same distance between two numbers (like 208 for my example), the next highest number is used.
+1 to Jason.
My implementation below, but not as brisk
$array = array(1,2,4,5,7,8,9);
function closest($array, $number) {
$array = array_flip($array);
if(array_key_exists($number, $array)) return $number;
$array[$number] = true;
sort($array);
$rendered = array_slice($array, $number, 2, true);
$rendered = array_keys($rendered);
if(array_key_exists(1, $rendered)) return $rendered[1];
return false;
}
print_r(closest($array, 3));
You could use array_reduce for this, which makes it more functional programming style:
function closest($needle, $haystack) {
return array_reduce($haystack, function($a, $b) use ($needle) {
return abs($needle-$a) < abs($needle-$b) ? $a : $b;
});
}
For the rest, this follows the same principle as the other O(n) solutions.
Here is my solution.
$array=array(10,56,78,17,30);
$num=65;
$diff=$num;
$min=$num;
foreach($array as $a){
if( abs($a-$num)< $diff ){
$diff=abs($a-$num);
$min=$a;
}
}
echo $min;
Say I have an array like this:
$array = array('', '', 'other', '', 'other');
How can I count the number with a given value (in the example blank)?
And do it efficiently? (for about a dozen arrays with hundreds of elements each)
This example times out (over 30 sec):
function without($array) {
$counter = 0;
for($i = 0, $e = count($array); $i < $e; $i++) {
if(empty($array[$i])) {
$counter += 1;
}
}
return $counter;
}
In this case the number of blank elements is 3.
How about using array_count _values to get an array with everything counted for you?
Just an idea, you could use array_keys( $myArray, "" ) using the optional second parameter which specifies a search-value. Then count the result.
$myArray = array( "","","other","","other" );
$length = count( array_keys( $myArray, "" ));
I dont know if this would be faster but it's something to try:
$counter = 0;
foreach($array as $value)
{
if($value === '')
$counter++;
}
echo $counter;
You could also try array_reduce, with a function which would just count the value you are interested in. eg
function is_empty( $v, $w )
{ return empty( $w ) ? ($v + 1) : $v; }
array_reduce( $array, 'is_empty', 0 );
Some benchmarking might tell you if this is faster than array_count_values()
We use array_filter function to find out number of values in array
$array=array('','','other','','other');
$filled_array=array_filter($array);// will return only filled values
$count=count($filled_array);
echo $count;// returns array count
Generally for counting blanks only.
Really depends on use case and speed needed. Personally I like doing things one one line.
Like the chosen response though But you still need a line to extract the data needed though to another variable.
$r = count($x) - count(array_filter($x));
function arrayvaluecount($array) {
$counter = 0;
foreach($array as $val){
list($v)=$val;
if($v){
$counter =$counter+1;
}
}
return $counter;
}
function countarray($array)
{ $count=count($array);
return $count;
}
$test=$array = array('', '', 'other', '', 'other');
echo countarray($test);