I'm trying to output [device_id] of the least frequent [device_ip_isp] from this array.
Also, If the array only has two SharedDevice Object available, and having different [device_ip_isp], it should output the 2nd SharedDevice Object's [device_id]
array (
0 =>
SharedDevice::__set_state(array(
'device_no' => 1,
'device_id' => '82',
'device_ip_isp' => 'Verizon Fios',
)),
1 =>
SharedDevice::__set_state(array(
'device_no' => 2,
'device_id' => '201',
'device_ip_isp' => 'Spectrum',
)),
2 =>
SharedDevice::__set_state(array(
'device_no' => 3,
'device_id' => '312',
'device_ip_isp' => 'Verizon Fios',
)),
3 =>
SharedDevice::__set_state(array(
'device_no' => 4,
'device_id' => '9715',
'device_ip_isp' => 'Verizon Fios',
)),
4 =>
SharedDevice::__set_state(array(
'device_no' => 5,
'device_id' => '11190',
'device_ip_isp' => 'Verizon Fios',
)),
)
The output should be 201 because "Spectrum" is the least frequent.
I tried the following and had issues:
I'm not sure how I can sort the object variables before comparing to find the least frequent.
/*
$user->getUser_devices() will output the array shown above.
*/
leastFrequent($user->getUser_devices(), 5);
function leastFrequent($arr, $n){
// find the min frequency
// using linear traversal
$min_count = $n + 1;
$res = -1;
$curr_count = 1;
for ($i = 1; $i < $n; $i++) {
if ($arr[$i]['device_ip_isp'] == $arr[$i - 1]['device_ip_isp']) {
$curr_count++;
} else {
if ($curr_count < $min_count) {
$min_count = $curr_count;
$res = $arr[$i - 1]['device_id'];
}
$curr_count = 1;
}
}
// If last element is
// least frequent
if ($curr_count < $min_count) {
$min_count = $curr_count;
$res = $arr[$n - 1]['device_id'];
}
return $arr[$n]$res['device_id'];
}
Ok, below is the explanation of the snippet inside out.
array_column to get all the device_ip_isp values in a single array.
array_count_values to get the frequency of each value.
array_reverse to reverse the count frequency array since you need the latest share device ID incase of count collision for a minimum count value.
min to get the lowest value among all the frequency counts.
array_search to get the key of the first frequency min element.
In the end, we reverse the input array to immediate return the device IP the moment we find the key from the above step matching the current device_ip_isp.
Snippet:
<?php
function getLeastFrequentElement($arr){
$freqs = array_reverse(array_count_values(array_column($arr, 'device_ip_isp')));
$deviceIPISP = array_search(min($freqs), $freqs);
foreach(array_reverse($arr) as $sharedDevice){
if($sharedDevice->device_ip_isp === $deviceIPISP){
return $sharedDevice->device_id;
}
}
throw new Exception("No shared object found!");
}
echo getLeastFrequentElement($arr);
Online Demo
Related
The job to be done is show the price of postage per KG. So starting at 1KG, I want to increase by 0.50 for every KG.
I tried doing it like this which doesn't seem to work for me:
$shipping_second_class = array (
array ('weight' => range(1,5), 'cost' => range(1,3, 0.50))
);
foreach ($shipping_second_class as $shipping_second_class) {
echo('weight '.$shipping_second_class['weight'].' costs £'.$shipping_second_class['cost'].'<br/>');
}
That doesn't seem to work. What I'm trying to do in a way that's easier to maintain is something like this, but with less code:
$shipping_second_class = array (
array ('weight' => '1', 'cost' => '1'),
array ('weight' => '2', 'cost' => '1.5'),
array ('weight' => '3', 'cost' => '2'),
array ('weight' => '4', 'cost' => '2.5'),
array ('weight' => '5', 'cost' => '3'),
);
foreach ($shipping_second_class as $shipping_second_class) {
echo('weight '.$shipping_second_class['weight'].' costs £'.$shipping_second_class['cost'].'<br/>');
}
Another simple way
$per_kg_extra_cost = 0.5;
foreach (range(0, 4) as $shipping) {
$cost = 1 + ( $shipping * $per_kg_extra_cost );
$weight = ++$shipping;
echo '<pre>';
echo 'Weight: '. $weight . ' cost : ' .$cost;
}
Here's one way to do this:
$shipping_second_class = array (
array ('weight' => 1, 'cost' => 1)
);
for($x = 2; $x < 6; $x++){
$newdata = ['weight' => $x, 'cost' => 0.5 + $x * 0.5];
array_push($shipping_second_class, $newdata);
}
foreach ($shipping_second_class as $s) {
echo('weight '.$s['weight'].' costs £'.$s['cost'].'<br/>');
}
Essentially, you need to add to the array after it's been called rather than initialize it fully filled. You start with the array at 1 value (you could modify this code to start with an empty array) and it expands from there. If you need to add more to the array, just increase the 6 to (Desired Number) + 1 in the for loop.
I'm not sure if there is a way to add to the array in the manner you do in the first block of code.
Here is a simple way to do it:
$key = -1;
$interval = 0.5;
$shipping_second_class = array_map(function($v) use (&$key,$interval) {
$key++;
return ["weight"=>$v,"cost"=>(1 + ($interval * $key))];
},range(1,5));
echo json_encode($shipping_second_class);
You can change the $interval variable if you need to change the way it increments cost
This is the input:
$deals = array(
array('deal' => '1', 'deal_date' => '2017-02-13', 'amount' => '400'),
array('deal' => '2', 'deal_date' => '2017-04-17', 'amount' => '8900'),
array('deal' => '3', 'deal_date' => '2017-04-23', 'amount' => '1000'),
array('deal' => '4', 'deal_date' => '2017-06-02', 'amount' => '2400'),
array('deal' => '5', 'deal_date' => '2017-07-05', 'amount' => '10500'),
);
I am searching for a subset of exactly N elements where the sum of the 'amount' properties is greater then or equal to X and the elements have the lowest 'deal_date' property possible.
If there is no subset that fits the rules:
$subset = false;
So for N=2 and X=10000, I get this output:
$subset = array(
array('deal' => '2', 'deal_date' => '2017-04-17', 'amount' => '8900'),
array('deal' => '4', 'deal_date' => '2017-06-02', 'amount' => '2400'),
);
for N=3 and X=12000:
$subset = array(
array('deal' => '2', 'deal_date' => '2017-04-17', 'amount' => '8900'),
array('deal' => '3', 'deal_date' => '2017-04-23', 'amount' => '1000'),
array('deal' => '4', 'deal_date' => '2017-06-02', 'amount' => '2400'),
);
My current idea entails creating an array that contains arrays of the list of deals in every conceivable order. Then I scan through those for my list of deals that fit the criteria but then I have a list of deals and I am unsure how to determine the 'earliest'.
I'm also looking for the algorithm with the lowest time complexity.
Any ideas would be appreciated.
It is not simple but roughly this
There will be a better way.
The approximate source is
$calculate = 0;
$end_case = array();
$sum = 10000;
// first amount 10000 over value array remove
foreach($deals as $key => $val){
if($val['amount']>=$sum)unset($deals[$key]);
}
// second Obtaining data
foreach($deals as $key => $val){
foreach($deals as $k => $v){
// same deal excetpion
if($val['deal']==$v['deal']) continue;
$calc = deal_sum($val['amount'],$v['amount']);
if($calc>=$sum){
echo "#".$v['deal']." => ".$val['amount']."+".$v['amount']." = ".$calc."\n";
array_push($end_case,$v['deal']);
}
print_r($end_case);
}
}
function deal_sum($source,$destination){
$result = $source+$destination;
return $result;
}
You should keep in mind the time complexity of your algorithm, otherwise large input sets will take forever.
Algorithm for N:
Returns array() of the first $number_of_deals_to_combine deals from
$deals ordered by 'deal_date', that have at least $threshold or
greater combined amounts or false if no such combination is found.
Uses a rolling window of $number_of_deals_to_combine elements
excluding deals that have too small 'amount'.
function combine_deals($deals, $threshold, $number_of_deals_to_combine){
$return = false;
//are there enough deals to combine?
if(count($deals) >= $number_of_deals_to_combine){
//are deals sorted by date? sort them
usort($deals,function($a, $b){return strnatcmp($a['deal_date'],$b['deal_date']);});
//find out if there is a possible solution, by adding up the biggest deals
$amounts = array_map('intval',array_column($deals,'amount'));
rsort($amounts); //sort descending
if(array_sum(array_slice($amounts, 0, $number_of_deals_to_combine)) >= $threshold){
//find the smallest possible number that is part of a solution
$min_limit = $threshold - array_sum(array_slice($amounts, 0, $number_of_deals_to_combine - 1));
//rolling window
$combined = array();
foreach($deals as $deal){
if(intval($deal['amount']) < $min_limit){continue;} //this deal is not part of any solution
$combined[] = $deal;
//keep the number of deals constant
if(count($combined) > $number_of_deals_to_combine){
$combined = array_slice($combined, count($combined) - $number_of_deals_to_combine);
}
//there are enough deals to test
if(count($combined) == $number_of_deals_to_combine){
$amount = array_sum(array_map('intval',array_column($combined, 'amount')));
if($amount >= $threshold){
$return = $combined;
break;
}
}
}
}
}
return $return;
}
$threshold = 10000;
$number_of_deals_to_combine = 2;
$result = combine_deals($deals, $threshold, $number_of_deals_to_combine);
Are the amount fields always integers? If not, replace all intval with floatval everywhere.
So I'm trying to make an array for stat growths in a fake rpg. It looks like this.
// base array
// $base: starting base stats
// $growth: growth rate per rng
$growths = array(
'HP' => array (70 => 20),
'STR' => array (50 => 7),
'MAG' => array (35 => 2),
'SKL' => array (45 => 6),
'SPD' => array (50 => 8),
'LCK' => array (55 => 5),
'DEF' => array (45 => 6),
'RES' => array (15 => 4),
);
//rng calculator
for ($x = 0; $x <= 20; $x++) {
foreach ($growths as $stat_name => $info) {
$roll = rand(0,100);
foreach ($info as $growth => $base) {
if ($roll <= $growth) {
$info[$growth] = ++$base;
print "(UP!) ";
}
echo "$stat_name: $base<br/ >";
}
}
}
My only issue is that the new $base value after the rng calculator refuses to store in the original array. Am I doing something wrong, or do I just need to rebuild the array from scratch and try something else? Any help would be appreciated!
In your first foreach loop, you assign the key of $growths to $stat_name and the value to $info. These are temporary variables. If you change them, the original array is not affected.
// This won't work because $info is temporary.
$info[$growth] = ++$base;
Instead, simply refer to the original array:
// Do this instead.
$growths[$stat_name][$growth] = ++$base;
use reference
just use foreach ($growths as $stat_name => &$info) to replace conrresponding line in your code.
I am comparing each element of array with every other element of array and if two elements have the same source/target, target/source I merge the inner array with employees e.g.
0=> source - 3 target - 4 officers => 0 - 'Aberdeen Asset Management PLC'
1=> source - 3 target - 4 officers => 0 - 'whatever'
it would be merged to
0=> source - 3 target - 4 officers => 0 - 'Aberdeen Asset Management PLC', 1 - 'whatever'
Here is how the data looks like:
My code is really inefficient with 1000 on more rows to go through the execution takes about 90 seconds which is unacceptable for this sort of thing.
foreach ($edges as $i => &$edge) {
for ($j = $i + 1; $j < count($edges); $j++) {
if ($edge['source'] == $edges[$j]['source'] && $edge['target'] == $edges[$j]['target']) {
foreach ($edges[$j]['officers'] as $officer) {
array_push($edge['officers'], $officer);
}
array_splice($edges, $j, 1);
}
}
}
The solution using array_search, array_keys, array_slice and array_merge functions:
// an exemplary array
$edges = [
0 => ['source' => 3, 'target' => 4, 'officers' => ['Aberdeen Asset Management PLC']],
1 => ['source' => 3, 'target' => 4, 'officers' => ['whatever']],
3 => ['source' => 4, 'target' => 7, 'officers' => ['Jason']],
4 => ['source' => 4, 'target' => 5, 'officers' => ['John']],
5 => ['source' => 4, 'target' => 7, 'officers' => ['Bourne']]
];
foreach ($edges as $k => &$v) {
$next_slice = array_slice($edges, array_search($k, array_keys($edges)) + 1);
foreach ($next_slice as $key => $item) {
if ($item['source'] == $v['source'] && $item['target'] == $v['target']) {
$v['officers'] = array_merge($v['officers'], $item['officers']);
unset($edges[$k + $key + 1]);
}
}
}
print_r($edges);
DEMO link
I think you should do this (updated):
// we will have new array with officers
$new_items = array();
foreach ($edges as $edge) {
// create unique keys for `source-target` and `target-source` pairs
$source_target = $edge['source'] . ':' . $edge['target'];
$target_source = $edge['target'] . ':' . $edge['source'];
// check if unique keys exists in `new_items`
if (!isset($new_items[$source_target]) && !isset($new_items[$target_source])) {
// if unique key doesn't exist - create a new one
$new_items[$source_target] = $edge;
} elseif (isset($new_items[$source_target])) {
// if unique key exists `$source_target` - add an officer to it
$new_items[$source_target]['officers'][] = $edge['officers'][0];
} else {
// if unique key exists `$target_source` - add an officer to it
$new_items[$target_source]['officers'][] = $edge['officers'][0];
}
}
// for returning to numeric indexes use `array_values`
$new_items = array_values($new_items);
How can I sort an array with some posts from a bank account?
I need to sort by three fields: date, amount, accumulated amount
ie.
date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)
btw. the date field is an UNIX timestamp
array(
array(
'time' => 1200000000,
'amount' => 500,
'accum_amount' => 500
),
array(
'time' => 1200000000,
'amount' => 150,
'accum_amount' => 725
),
array(
'time' => 1200000000,
'amount' => 100,
'accum_amount' => 600
),
array(
'time' => 1300000000,
'amount' => 200,
'accum_amount' => 925
),
array(
'time' => 1300000000,
'amount' => -25,
'accum_amount' => 900
),
array(
'time' => 1200000000,
'amount' => -25,
'accum_amount' => 575
)
)
Change your array structure to something like:
$tmp = array(
time => array(1200000000, 1200000000, 1200000000, ...),
amount => array(500, 150, 100, ...),
accum_amount => array(500, 725, 600, ...),
)
and then use array_multisort for sorting (http://php.net/manual/en/function.array-multisort.php) like:
array_multisort($tmp['time'], SORT_ASC, $tmp['amount'], SORT_DESC, $tmp['accum_amount'], SORT_ASC);
It's not very intuitive, but it should work.
Of course you can write a helper function to map the new sorting order on other array structure.
Example:
function mySort($array, $sort) {
$tmp = array();
foreach ($array as $row) {
foreach ($row as $field => $value) {
if (!isset($tmp[$field])) {
$tmp[$field] = array();
}
$tmp[$field][] = $value;
}
}
$params = array();
foreach ($sort as $field => $direction) {
$params[] = $tmp[$field];
$params[] = $direction;
}
$keys = array_keys($array);
$params[] =& $keys;
call_user_func_array('array_multisort', $params);
$result = array();
foreach ($keys as $key) {
$result[$key] = $array[$key];
}
return $result;
}
Call:
$data = mySort($data, array(
'time' => SORT_ASC,
'amount' => SORT_ASC,
'accum_amount' => SORT_ASC
));
function usort() is made for this purpose:
usort($data, "my_sort");
function my_sort($row1, $row2) {
if ($row1['time']<$row2['time']) return -1;
if ($row1['time']>$row2['time']) return 1;
if ($row1['amount']<$row2['amount']) return -1;
if ($row1['amount']>$row2['amount']) return 1;
if ($row1['accum_amount']<$row2['accum_amount']) return -1;
if ($row1['accum_amount']>$row2['accum_amount']) return 1;
return 0;
}
Your example isnt really clear what you want. You don't describe it this way, but from example it appears you want to sort by date increasing, then accum_amount increasing, then amount (increasing?)
You just have to write a comparison function and pass it to uasort along with your array
$comp = function($a,$b)
{
if ($a['date'] != $b['date'])
return $a['date'] - $b['date'];
else if ($a['accum_amount'] != $b['accum_amount'])
return $a['accum_amount'] - $b['accum_amount'];
return $a['amount'] - $b['amount'];
}
uasort($arr, $comp);
You might find a function like this helpful. It will create the comparison function when given an array, in order of importance, of the keys to compare by. (All ascending, support for descending would necessarily complicate it a good deal)
$compMakerAsc = function($l)
{
return function($a, $b) use ($l)
{
foreach($l as $k)
{
if ($a[$k] != $b[$k])
return $a[$k] - $b[$k];
//OR return ($a[$k] > $b[$k]) ? 1 : -1;
}
return 0;
}
$myComp = $compMakerAsc('date', 'accum_amount', 'amount');
$uasort($arr, $myComp);
$key = 'accum_amount';
function sortme($a, $b)
{
global $key;
if ($a[$key] == $b[$key]) {
return 0;
}
return ($a[$key] < $b[$key]) ? -1 : 1;
}
usort($array, "sortme");
perhaps this should help. Bad thing, have to define global variable. Complete code!!!
$array = array(
array(
'time' => 1200000000,
'amount' => 500,
'accum_amount' => 500
),
array(
'time' => 1200000000,
'amount' => 150,
'accum_amount' => 725
),
array(
'time' => 1200000000,
'amount' => 100,
'accum_amount' => 600
),
array(
'time' => 1300000000,
'amount' => 200,
'accum_amount' => 925
),
array(
'time' => 1300000000,
'amount' => -25,
'accum_amount' => 900
),
array(
'time' => 1200000000,
'amount' => -25,
'accum_amount' => 575
)
);
$key = 'accum_amount';
function sortme($a, $b)
{
global $key;
if ($a[$key] == $b[$key]) {
return 0;
}
return ($a[$key] < $b[$key]) ? -1 : 1;
}
usort($array, "sortme");
echo "<pre>";
print_r($array);
echo "</pre>";
Let's combine this from the comments
the query is just as simple as SELECT time, amount, accum_amount FROM table
with this requirement from the original question:
I need to sort by three fields: date, amount, accumulated amount
Now, there were no requirements stated as to whether the sort is ascending or not. Let's assume ascending.
SELECT time, amount, accum_amount
FROM table
ORDER BY time ASC, amount ASC, accum_amount ASC
This will give us all of the data first sorted by time. When the time is identical, it will sort second by amount, lowest first and highest last. When the time and amount are identical, it will sort third by the accumulated amount, again sorted lowest first, highest last.
Changing the order of operations with the sort is as simple as swapping around the list in the ORDER BY clause. Going from largest to smallest is as easy as switching from ASC to DESC.
Note how relatively easy this method is in comparison to sorting in PHP. Whenever you can, let your database give you pre-sorted results.
Because I need to leave the site for a few hours, I'm just going to type this up real quick. I'm operating right now under the assumption that you want to recalculate the accumulated value.
Our query is now:
SELECT time, amount
FROM table
ORDER BY time ASC, amount DESC
We'll be a friendly bank and perform all deposits (increases in amount) first, then all debits (decreases in amount) last, processing the largest debits later than the smaller debits.
Given $data is our array:
$running_total = 0;
foreach($data as $index => $row) {
$data[$index]['accum_amount'] = $running_total + $row['amount'];
$running_total = $data[$index]['accum_amount'];
}
This should successfully rebuild the accum_amount list, given the business rules I have outlined above.
I have found another way to do it before the data is put into the db