Calculate mean of a range of XML Elements in PHP - php

I'm trying to calculate the mean of a range of XML elements in PHP, but haven't found any solution yet.
Here are the XML elements.
<root>
<quoteDay>
<date>2018-02-26</date>
<close>1586,96</close>
</quoteDay>
<quoteDay>
<date>2018-02-23</date>
<close>1577,11</close>
</quoteDay>
<quoteDay>
<date>2018-02-22</date>
<close>1565,5</close>
</quoteDay>
</root>
Here is the PHP code:
<?php
$xml = simplexml_load_file("file.xml") or die("Error: Cannot create object");
$id = -1;
$total[] = 0;
foreach ($xml->root as $root) {
foreach ($root->quoteDay as $quoteDay) {
$id ++;
$total[] += $root->quoteDay[$id]->close;
$close = number_format(round($quoteDay->close,0));
echo $quoteDay->date; echo $close; echo $total[$id+1];
}
}
?>
So, for each quoteDay, I would like to return the date, close and a moving average.
Date 2018-02-26 would return the mean of "close" for 2018-02-26 and 2018-02-23 = (1586,96+1577,11)/2.
Mean for 2018-02-23 would return (1577,11+1565,5)/2.
I've, as you can see, tried to sum a cumulative total sum for each element, but for some reason I can't understand it won't work.
How can I accomplish calculating a moving average for the elements?

In order to achieve your result you need to do a couple of things:
simplexml_load_file() already gives you the root, so there's no need for your first loop
The $total array is not necessary
Your XML has , as decimal separators, but PHP uses ., so you need to replace them in order to do math and not lose the decimals (here I cast to float which can make you lose precision, look into bcmath to avoid that)
I assume that for the first day, when there's no previous, the moving average is the day's value
So, your code would look like this:
<?php
$xml = simplexml_load_file("a.xml") or die("Error: Cannot create object");
$id = 0;
foreach ($xml->quoteDay as $quoteDay) {
echo "Moving average for ".$quoteDay->date.":".PHP_EOL;
$current = (float) str_replace(",", ".", $quoteDay->close);
$previous = $xml->quoteDay[$id + 1]
? (float) str_replace(",", ".", $xml->quoteDay[$id + 1]->close)
: $current;
$movingMean = ($current + $previous) / 2;
echo $movingMean.PHP_EOL;
echo PHP_EOL;
$id++;
}
Demo
Result
Moving average for 2018-02-26:
1582.035
Moving average for 2018-02-23:
1571.305
Moving average for 2018-02-22:
1565.5
To generalize it to $daysInMovingMean days, use a for loop to get the days up to the days needed, stopping earlier if necessary (i.e. no more days left):
$xml = simplexml_load_file("a.xml") or die("Error: Cannot create object");
$id = 0;
$daysInMovingMean = 3;
foreach ($xml->quoteDay as $quoteDay) {
echo "Moving average for ".$quoteDay->date.":".PHP_EOL;
$sum = 0;
for ($days = 0; $days < $daysInMovingMean; $days++) {
if (!$xml->quoteDay[$id + $days]) break;
$sum += (float) str_replace(",", ".", $xml->quoteDay[$id + $days]->close);
}
$sumovingMean = $sum / $days;
echo $sumovingMean.PHP_EOL;
echo PHP_EOL;
$id++;
}
Notice that in this example you get the same results as before if you set $daysInMovingMean = 2;
Demo

Related

compare driving distance from JSON array

I'm using googledistancematrix api for calculating distance from login user to all my fields of db. That's my controller code.
$field_list = Field::all();
for ($i=0; $i < count($field_list); $i++)
{
$destination = $field_list[$i]['latitude'] . "," . $field_list[$i]['longitude'];
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destination&mode=driving&sensor=false";
$json = file_get_contents($details);
$details = json_decode($json, TRUE);
if (count($details['destination_addresses']) > 0 )
{
$distance = $details['rows'][0]['elements'][0]['duration']['text'];
$field_list[$i]->distance = $distance;
}
}
By this i'm getting following response:
https://jsoneditoronline.org/?id=a35cedef327244ceb19ed35a2a4c8ddf
But i want to show only those fields whose distance < or = 30 mins.
Thanks
It's a simple matter to convert the time to seconds using strtotime() as follows:
$time=strtotime($details['rows'][0]['elements'][0]['duration']['text']);
if (($time-time()>1800) {
// ignore this element, probably in loop so do a continue
}
This is based on using your example line above which is only for a single element. You would need to wrap it with a loop and perform the calculation for each element.
You can use strtotime
$min = strtotime("30 mins");
$val = strtotime("0 hours 10 mins");
echo $min <= $val? "yes":"no";
(here if you want to test it)
in your case
if (count($details['destination_addresses']) > 0 ){
$min = strtotime("30 mins");
$distance = $details['rows'][0]['elements'][0]['duration']['text'];
if($min <= strtotime($distance)){
//do your logic
}
}

How to compare 2 numeric strings

I have 2 strings like this
$s1="32.56.86.90.23";
$s2="11.25.32.90.10";
I need to compare $s1 and $s2 and find if there are 2 or more numbers in common.
I am using this way
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo "YES"; } else {echo "no"; }
Since I need millions values of $s1 and $s2 and the code above seems to be slow, do you know alternative way to execute the work faster ?
I tested it with the following code, one million times, less than 2 seconds on my 3 years old laptop.
Loop 1M times takes no time, most time is used for displaying.
Comment off the display, 1M loops, 0.816432 seconds
Saved the results into a file, ~13.564MB, 0.731708 seconds
ob_start();
$t1 = microtime();
for($i=1; $i<=1000000; $i++) {
$s1="32.56.86.90.23";
$s2="10.25.30.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo $i . " YES<br>"; } else {echo $i . " no<br>"; }
}
$out = ob_get_contents();
ob_end_clean();
var_dump($out);
echo '<p>'.(microtime() - $t1).'</p>';
Try this.
$s1="32.56.86.90.23";
$s2="11.23.32.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
//assuming $s1_ar and $s2_ar both has unique values if not please make them unique
$result_array = array();
$hasMatch = 0;
for($i = 0; $i < count($s1_ar) && $i < count($s2_ar); $i++){
if(!isset($result_array[$s1_ar[$i]])){
$result_array[$s1_ar[$i]] = 1;
}else{
$result_array[$s1_ar[$i]]++;
}
if(!isset($result_array[$s2_ar[$i]])){
$result_array[$s2_ar[$i]] = 1;
}else{
$result_array[$s2_ar[$i]]++;
}
}
foreach($result_array as $result){
if($result >=2) $hasMatch++;
}
if($hasMatch >= 2)
echo "YES";
else
echo "NO";
I think it will solve your purpose.
Looking at: php array_intersect() efficiency
There's mention that array_intersect_key may be more efficient. But really it would be nice to have data and versions to compare results.
$s1 = "2.3.5.7.9.11.13.17";
$s2 = "2.3.4.5.6";
$s1 = array_flip(explode('.', $s1));
$s2 = array_flip(explode('.', $s2));
echo count(array_intersect_key($s1, $s2))>=2 ? 'yes' : 'no';
Output:
yes
I thought of a way to solve this in a 2*n complexity:
We loop one list and create an associative array from it's elements (LIST c) then we loop the second list and look up if the list c contains such an index/key ( c[element] ).
This shall be very light weighted :
$commons = 0;
$s1_fliped = array_flip($s1_ar)
foreach($s2_ar as $s2_el){
if ( isset($s1_fliped[$s2_el]) ){
$commons ++;
}
if($commons >=2) break;
});

Random generator returning endless duplicates

I am trying to create a random string which will be used as a short reference number. I have spent the last couple of days trying to get this to work but it seems to get to around 32766 records and then it continues with endless duplicates. I need at minimum 200,000 variations.
The code below is a very simple mockup to explain what happens. The code should be syntaxed according to 1a-x1y2z (example) which should give a lot more results than 32k
I have a feeling it may be related to memory but not sure. Any ideas?
<?php
function createReference() {
$num = rand(1, 9);
$alpha = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 1);
$char = '0123456789abcdefghijklmnopqrstuvwxyz';
$charLength = strlen($char);
$rand = '';
for ($i = 0; $i < 6; $i++) {
$rand .= $char[rand(0, $charLength - 1)];
}
return $num . $alpha . "-" . $rand;
}
$codes = [];
for ($i = 1; $i <= 200000; $i++) {
$code = createReference();
while (in_array($code, $codes) == true) {
echo 'Duplicate: ' . $code . '<br />';
$code = createReference();
}
$codes[] = $code;
echo $i . ": " . $code . "<br />";
}
exit;
?>
UPDATE
So I am beginning to wonder if this is not something with our WAMP setup (Bitnami) as our local machine gets to exactly 1024 records before it starts duplicating. By removing 1 character from the string above (instead of 6 in the for loop I make it 5) it gets to exactly 32768 records.
I uploaded the script to our centos server and had no duplicates.
What in our enviroment could cause such a behaviour?
The code looks overly complex to me. Let's assume for the moment you really want to create n unique strings each based on a single random value (rand/mt_rand/something between INT_MIN,INT_MAX).
You can start by decoupling the generation of the random values from the encoding (there seems to be nothing in the code that makes a string dependant on any previous state - excpt for the uniqueness). Comparing integers is quite a bit faster than comparing arbitrary strings.
mt_rand() returns anything between INT_MIN and INT_MAX, using 32bit integers (could be 64bit as well, depends on how php has been compiled) that gives ~232 elements. You want to pick 200k, let's make it 400k, that's ~ a 1/10000 of the value range. It's therefore reasonable to assume everything goes well with the uniqueness...and then check at a later time. and add more values if a collision occured. Again much faster than checking in_array in each iteration of the loop.
Once you have enough values, you can encode/convert them to a format you wish. I don't know whether the <digit><character>-<something> format is mandatory but assume it is not -> base_convert()
<?php
function unqiueRandomValues($n) {
$values = array();
while( count($values) < $n ) {
for($i=count($values);$i<$n; $i++) {
$values[] = mt_rand();
}
$values = array_unique($values);
}
return $values;
}
function createReferences($n) {
return array_map(
function($e) {
return base_convert($e, 10, 36);
},
unqiueRandomValues($n)
);
}
$start = microtime(true);
$references = createReferences(400000);
$end = microtime(true);
echo count($references), ' ', count(array_unique($references)), ' ', $end-$start, ' ', $references[0];
prints e.g. 400000 400000 3.3981630802155 f3plox on my i7-4770. (The $end-$start part is constantly between 3.2 and 3.4)
Using base_convert() there can be strings like li10, which can be quite annoying to decipher if you have to manually type the string.

PHP - Nest a for loop a variable number of times

I'm a beginner with PHP (and programming in general).
To test what I've learned so far I wrote this code, which prints all the possibile combinations of a set number of dice with a certain number of faces. (you'll find the code at the end).
What I want to do is dynamically change the number of nested for loops according to the $dicenumber variable. Right now it can only process 3 dice, since the code is:
for ($d1=1; $d1 <= $d1value ; $d1++) {
for ($d2=1; $d2 <= $d2value ; $d2++) {
for ($d3=1; $d3 <= $d3value ; $d3++) {
array_push(${sum.($d1+$d2+$d3)}, "$d1"."$d2"."$d3");
}
}
}
But I want to change it so that, for example, if $dicenumber were 2, it would produce something like:
for ($d1=1; $d1 <= $d1value ; $d1++) {
for ($d2=1; $d2 <= $d2value ; $d2++) {
array_push(${sum.($d1+$d2)}, "$d1"."$d2");
}
}
I want the code to process for whatever number $dicenumber may be, without limits. Looking around, it seems like I have to add some kind of recursive code, but I don't know how to do that. Any tips? Also, any feedback on what I did wrong in general, would be extremely helpful! thanks!
<?php
//defines the number and type of dice
$dicenumber = 3;
$dtype = 6;
//defines the maximum value of every die
for ($i=1; $i <=$dicenumber ; $i++) {
${d.$i.value} = $dtype;
}
//defines and array for each possible sum resulting from the roll of the given number of dice.
for ($i=$dicenumber; $i <= ($dtype*$dicenumber) ; $i++) {
${sum.$i} = array();
}
//the troublesome piece of code I want to change
for ($d1=1; $d1 <= $d1value ; $d1++) {
for ($d2=1; $d2 <= $d2value ; $d2++) {
for ($d3=1; $d3 <= $d3value ; $d3++) {
array_push(${sum.($d1+$d2+$d3)}, "$d1"."$d2"."$d3");
}
}
}
//prints all the possible roll combinations, each line lists combination that share the same sum
for ($i=$dicenumber; $i <= ($dtype*$dicenumber); $i++) {
print join(" ", ${sum.$i})."<br />";
}
?>
Here we have a two-function process. The first function, buildArrays, creates arrays in the proper format to feed into the second function, allCombinations. So, for this example with 3 d6's in play, buildArrays will produce an array equivalent to this:
$data = array(
array(1, 2, 3, 4, 5, 6),
array(1, 2, 3, 4, 5, 6),
array(1, 2, 3, 4, 5, 6));
I will warn you that as you increase the number of dice and the number of sides, the number of possible combinations increases exponentially! This means that you could place a very large demand on the server, and both timeout and max memory limits will quickly come into play. The arrays generated could be very, very large and quickly consume more than the max memory limit. That said, here we go:
function buildArrays($dicenumber, $dtype){
for ($i = 0; $i<$dicenumber; $i++){
$tmp = array();
for ($j = 1; $j<=$dtype; $j++){
$tmp[] = $j;
}
$data[$i] = $tmp;
}
return $data;
}
function allCombinations($data){
$result = array(array()); //this is crucial, dark magic.
foreach ($data as $key => $array) {
$new_result = array();
foreach ($result as $old_element){
foreach ($array as $element){
if ($key == 0){
$new_result[] = $element;
} else {
$new_result[] = $old_element.$element;
}
}
$result = $new_result;
}
}
return $result;
}
//set variables
$dicenumber = 3;
$dtype = 6;
//set_time_limit(0); //You may need to uncomment this for large values.
//call functions
$data = buildArrays($dicenumber, $dtype);
$results = allCombinations($data);
//print out the results
foreach ($results as $result){
echo $result."<br/>";
}
N.B. This answer is a variant of the cartesian product code
If you have learned functions, you can do a recursive call and keep track of what dicenumber you're on, then increment it each call to the function (and end the loop once you've hit your #).
understanding basic recursion

How to reduce lists of ranges?

Given a list of ranges ie: 1-3,5,6-4,31,9,19,10,25-20
how can i reduce it to 1-6,9-10,19-25,31 ?
Here is what i've done so far, it seems a little bit complicated, so
is there any simpler/clever method to do this.
$in = '1-3,5,6-4,31,9,19,10,25-20';
// Explode the list in ranges
$rs = explode(',', $in);
$tmp = array();
// for each range of the list
foreach($rs as $r) {
// find the start and end date of the range
if (preg_match('/(\d+)-(\d+)/', $r, $m)) {
$start = $m[1];
$end = $m[2];
} else {
// If only one date
$start = $end = $r;
}
// flag each date in an array
foreach(range($start,$end) as $i) {
$tmp[$i] = 1;
}
}
$str = '';
$prev = 999;
// for each date of a month (1-31)
for($i=1; $i<32; $i++) {
// is this date flaged ?
if (isset($tmp[$i])) {
// is output string empty ?
if ($str == '') {
$str = $i;
} else {
// if the previous date is less than the current minus 1
if ($i-1 > $prev) {
// build the new range
$str .= '-'.$prev.','.$i;
}
}
$prev = $i;
}
}
// build the last range
if ($i-1 > $prev) {
$str .= '-'.$prev;
}
echo "str=$str\n";
NB: it must run under php 5.1.6 (i can't upgrade).
FYI : the numbers represent days of month so they are limited to 1-31.
Edit:
From a given range of dates (1-3,6,7-8), i'd like obtain another list (1-3,6-8) where all the ranges are recalculated and ordered.
Perhaps not the most efficient, but shouldn't be too bad with the limited range of values you're working with:
$in = '1-3,5,6-4,31,9,19,10,25-20';
$inSets = explode(',',$in);
$outSets = array();
foreach($inSets as $inSet) {
list($start,$end) = explode('-',$inSet.'-'.$inSet);
$outSets = array_merge($outSets,range($start,$end));
}
$outSets = array_unique($outSets);
sort($outSets);
$newSets = array();
$start = $outSets[0];
$end = -1;
foreach($outSets as $outSet) {
if ($outSet == $end+1) {
$end = $outSet;
} else {
if ($start == $end) {
$newSets[] = $start;
} elseif($end > 0) {
$newSets[] = $start.'-'.$end;
}
$start = $end = $outSet;
}
}
if ($start == $end) {
$newSets[] = $start;
} else {
$newSets[] = $start.'-'.$end;
}
var_dump($newSets);
echo '<br />';
You just have to search your data to get what you want. Split the input on the delimiter, in your case ','. Then sort it somehow, this safes you searching left from the current position. Take you first element, check whether it's a range and use the highest number in this range (3 out of 1-3 range or 3 if 3 is a single element) for further comparisions. Then take the 2nd element in your list and check if it's a direct successor of the last element. If yes combine the 1st and 2nd elements/range to a new range. Repeat.
Edit: I'm not sure about PHP but a regular expression is a bit overkill for this problem. Just look for a '-' in your exploded array, then you know it's a range. Sorting the exp. array safes you the backtracking, the stuff you are doing with $prev. You could also explode every element in the exploded array on '-' and check if the resulting array has a size > 1 to learn whether an element is a range or not.
Looking at the problem from an algorithmic stand-point, let's consider the limitations that you've put on the problem. All numbers will be from 1-31. The list is a collection of "ranges", each of which is defined by two numbers (start and end). There is no rule for whether start will be more, less than, or equal to end.
Since we have an arbitrarily large list of ranges but a definite means of sorting/organizing these, a divide and conquer strategy may yield the best complexity.
At first I typed out a very long and careful explanation of how I created each step in this algorithm (the dividing portion, the conquering potion, optimizations, etc.) however the explanation got extremely long. To shorten it, here's the final answer:
<?php
$ranges = "1-3,5,6-4,31,9,19,10,25-20";
$range_array = explode(',', $ranges);
$include = array();
foreach($range_array as $range){
list($start, $end) = explode('-', $range.'-'.$range); //"1-3-1-3" or "5-5"
$include = array_merge($include, range($start, $end));
}
$include = array_unique($include);
sort($include);
$new_ranges = array();
$start = $include[0];
$count = $start;
// And begin the simple conquer algorithm
for( $i = 1; $i < count($include); $i++ ){
if( $include[$i] != ($count++) ){
if($start == $count-1){
$new_ranges[] = $start;
} else {
$new_ranges[] = $start."-".$count-1;
}
$start = $include[$i];
$count = $start;
}
}
$new_ranges = implode(',', $new_ranges);
?>
This should (theoretically) work on arrays of arbitrary length for any positive integers. Negative integers would get tripped up since - is our delimiter for the range.

Categories