I have an array of numbers and some numbers are obviously too big or too small relative to them all. I wonder if there is already some kind of function or algorithm that I can use in order to remove these records from array.
Here is an example of array
8
7
21
1330829238608
6
7
188
8
25
92433
19
6
At the moment all I can think about is just check if number is more than 1k or less than 1k and then do not allow it. But still I get problem since 188 does not belong here either.
Is there any good way that I can get majority of close numbers from this array and produce something like
8
7
6
7
8
6
This is what I have so far
<?php
echo '<pre>';
$startArray = Array(8, 7, 21, 1330829238608, 6, 7, 188, 8, 25, 92433, 19, 6);
print_r($startArray);
for ($i = 0; $i < count($startArray); $i++) {
if ($i != count($startArray) - 1) {
if ($startArray[$i] - 10 <= $startArray[$i + 1]) {
echo $startArray[$i] . '<br />';
}
}
}
Use array_filter:
function filter_callback($var){
return $var < 100 && $var > 2;
}
$array = array(1,1000,23,4453,123,412,321,433,4,6,2,3,5,634,32,432,45,3,4);
$filtered = array_filter($array, "filter_callback");
$arrayData = array(8, 7, 21,
1330829238608,
6, 7, 188, 8, 25,
92433,
19, 6,
);
$min = 7;
$max = 10;
$matches = array_filter( $arrayData,
function($data) use ($min,$max) {
return (($data >= $min) && ($data <= $max));
}
);
var_dump($matches);
I really gotta go but it's an easy one.
create a maximum = closest number to 0 in the array, multiplied by $delta.
any number in the array smaller than the maximum from pct. 1, but if multiplied by $delta is greater than that maximum, becomes maximum if($i<$max && $i*$delta>$max) $max = $i*$delta
trim out all numbers bigger than the current maximum.
Problem is you need a $delta. It's safe to go with 2 for delta, but if you want it adaptable don't ask me how to do it because that's cognitive neuroscience.
This can be optimized but this is what I figured out, works with diff of 20%, you can change it to whatever % you want, of course.
<?php
$startArray = array(8, 7, 21, 1330829238608, 6, 7, 188, 8, 25, 92433, 19, 6);
$groupArray = array();
$startArrayCount = count($startArray);
for ($i = 0; $i < $startArrayCount; $i++) {
// 20% of current value
$valueDiff = ($startArray[$i] / 100) * 20;
// Get minimal and maximal value
$maxValue = ($startArray[$i] + $valueDiff);
$minValue = ($startArray[$i] - $valueDiff);
// Print it out
// echo 'Diff: ' . $valueDiff . '<br />';
// echo 'Max: ' . $maxValue . '<br />';
// echo 'Min: ' . $minValue . '<br />';
$groupArray[$i] = array();
for ($n = 0; $n < $startArrayCount; $n++) {
if ($startArray[$n] <= $maxValue && $startArray[$n] >= $minValue) {
// echo 'TRUE: ' . $startArray[$n] . '<br />';
array_push($groupArray[$i], $startArray[$n]);
}
}
//echo '<hr />';
}
// Getting arrays that have most members in it
$max = count($groupArray[0]);
foreach ($groupArray as $group) {
if (count($group) > $max) {
$max = count($group);
}
}
// Taking all those arrays and combining them in one
$finishArray = array();
foreach ($groupArray as $group) {
if (count($group) == $max) {
foreach ($group as $key) {
array_push($finishArray, $key);
}
}
}
// Combining all values
$total = null;
foreach ($finishArray as $num) {
$total = $total + $num;
}
// Getting average
$average = $total / count($finishArray);
echo $average;
Related
I want to send an integer array and a number to function and function will give me closest element or element sum to my number.
for example: our funtion name is findclosestsum.
findClosestSum([2, 3, 7, 14, 15], 25) --> must give 3,7,15 because sum of this 3 element is exactly 25.
findClosestSum([2, 3, 7, 14, 15], 15) --> must give only 15
findClosestSum([2, 3, 7, 14, 15], 11) --> must give 3,7 because sum=10 and very closer to 11
here is my php code
function findClosestSum($array, $number) {
$result = [];
$minDiff = null;
$arrayCount = count($array);
for ($i = 0; $i < $arrayCount; $i++) {
for ($j = $i + 1; $j < $arrayCount; $j++) {
$sum = $array[$i] + $array[$j];
$diff = abs($number - $sum);
if ($sum == $number) {
return [$array[$i], $array[$j]];
} elseif ($minDiff === null || $diff < $minDiff) {
$minDiff = $diff;
$result = [$array[$i], $array[$j]];
}
}
}
return $result;
}
it returns 7 and 15 for findClosestSum([2, 3, 7, 14, 15], 25). where is my mistake?
For solving this problem in a more productive and precise result, you may need to implement this with graphs.
I have to count the numbers which is divisible by 5.
Here is my code,
$num = array(4, 25, 60, 7, 8);
foreach ($num as $numbers) {
if (($numbers % 5) == 0) {
echo count($numbers);
}
}
Output of above program is 11. But output should be 2. Please give me solution. Thanks in advance.
$nums = array(4, 25, 60, 7, 8);
To only count:
-Basic:
$count = 0;
foreach ($nums as $num) {
if ( $num % 5 == 0 ) $count++;
}
-Playing with types:
$count = 0;
foreach ($nums as $num) {
$count += !($num % 5);
}
$num % 5 returns an integer, !($num % 5) returns a boolean but since it is used as operand with the + operator, false and true act like 0 and 1.
-Functional version using array_reduce:
$count = array_reduce($nums, function($c, $i) { return $c + !($i % 5); });
To filter items, use the well named array_filter:
$result = array_filter($nums, function ($i) { return $i % 5 == 0; });
and count the number of items after if you want:
$count = count($result);
You can use this way also,
function divisibleby5($var){
return $var % 5 == 0;
}
$num = array(4, 25, 60, 7, 8);
echo count(array_filter($num,'divisibleby5');
I think you need to do something more like the following perhaps.
$num = array(4, 25, 60, 7, 8);
$numbers=array();
foreach( $num as $number ) {
if( $number % 5 == 0 ) $numbers[]=$number;
}
echo count( $numbers );
or alternatively using array_walk and a custom callback function
function mod5($item,$key,$arr){
if($item %5==0)$arr[]=$item;
}
array_walk( $num,'mod5',&$numbers);
echo count($numbers);
Here Output is 1 and 1. Not 11 (eleven)
You can try it
echo count($numbers)."<br>";
your solution:
Output will be 2 if you increment count variable value after enter the if condition
<?php
$num = array(4, 25, 60, 7, 8);
$count = 0;
foreach($num as $numbers) {
if (($numbers % 5) == 0) {
$count++;
}
}
echo $count;
?>
in the event you want to print the numbers also
$a=array(); //initialized empty array
$num = array(4, 25, 60, 7, 8);
foreach($num as $numbers){
if(($numbers % 5) == 0){
$a=$numbers; //store values into the array
}
}
echo count($a); // echo the count of the array
echo implode('<br>',$a);
OR if you just need the count
$a=0; //initalize $a
$num = array(4, 25, 60, 7, 8);
foreach($num as $numbers){
if(($numbers % 5) == 0){
$a++; //increment a
}
}
echo $a
I have four variables: $one_flag, $two_flag, $three_flag, and $four_flag. I'm using them as flags inside a for loop because I want to keep track of the last four iterations.
$one_flag = 1;
$two_flag = 0;
$three_flag = 0;
$four_flag = 0;
$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
foreach ($a as $v) {
if ($one_flag){
$first_v = $v;
$one_flag = 0;
$two_flag = 1;
}
if ($two_flag){
$second_v = $v;
$two_flag = 0;
$three_flag = 1;
}
if ($three_flag){
$third_v = $v;
$three_flag = 0;
$four_flag = 1;
}
if ($four_flag){
$fourth_v = $v;
$four_flag = 0;
$first_flag = 1;
}
if ($v == 45){
# tricky part
print "The last three v's were: " . $first_v . ", " . $second_v . ", " . $third_v . "\n";
}
}
Right now it prints The last three v's were 1, 1, 1 but it's supposed to print The last three v's were 45, 44, 27. Also, the problem with the code above is I need to know which flag is equal to 1 (what flag we're currently on) so that I can print the correct statement.
For example, when $v == 45, $first_v is suppose to equal to 27; $second_v is suppose to equal to 44; $fourth_v is suppose to equal to 17; and third_v is suppose equal to 45. I'd need to know $three_flag is equal to 1 in order to print out "The last three were $second_flag, $first_flag, $fourth_flag" in that order.
How can I get my loop to work? How do I keep track of the last four iterations?
EDIT: I misspoke. I actually want to print The last three v's were 44, 27, 17
I suppose that this is a minimal example and that the real program is more complex. Otherwise, you could just get the length of the array and retrieve the last 3 elements based on it.
I'd change the approach as follow:
$f1 = -1; // Last value read
$f2 = -1; // second to last value
$f3 = -1;
$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
foreach ($a as $v) {
$f3 = $f2;
$f2 = $f1;
$f1 = $v;
if ($v == 45){
# tricky part
print "The last three v's were: " . $f1 . ", " . $f2 . ", " . $f3 . "\n";
}
}
I'm using -1 as an indicator that nothing was assigned to the variable. You should adapt this to your context if needed.
The problem lies in your if-statements.
//loop sets $v = 1
//this one is true due to initial parameters, execute
if ($one_flag){
$first_v = $v; //$first_v = 1
$one_flag = 0;
$two_flag = 1; //$two_flag is now TRUE!!!
}
//$two_flag is true, execute immediately!
if ($two_flag){
$second_v = $v; //$second_v = 1
$two_flag = 0;
$three_flag = 1;
}
Although in my reading, that should cause the print to give The last three v's were 45, 45, 45. If you want to keep doing it like this, you will need to use else if.
$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
$track = array();
$num = 3;
foreach ($a as $v){
$track[] = $v;
if (count($track) > $num){
$track = array_slice($track, 1);
}
if ($v == 45){
print_r(array_reverse($track));
}
}
result
Array
(
[0] => 45
[1] => 44
[2] => 27
)
It'd help to know the problem you're trying to solve, but off-hand I'd use a circular array to keep track of the last four. (Edited per your revision):
$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
$previous = array ();
$pCounter = 0;
foreach ($a as $i => $v) {
if (45 === $v) {
print_r(array_reverse($previous));
}
// track the last three using a circular array
$previous[$pCounter] = $v;
$pCounter = ($pCounter + 1) % 3;
}
Results in:
Array
(
[0] => 44
[1] => 27
[2] => 17
)
Try it online.
instead of if use elseif, it will serve your purpose, and change the variable name $first_flag to $one_flag.
$one_flag = 1;
$two_flag = 0;
$three_flag = 0;
$four_flag = 0;
$probe_counter = 1;
$first_v=0;
$second_v=0;
$third_v=0;$fourth_v=0;
$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
foreach ($a as $key => $val) {
if ($one_flag){
$first_v = $val;
$one_flag = 0;
$two_flag = 1;
}
elseif ($two_flag){
$second_v = $val;
$two_flag = 0;
$three_flag = 1;
}
elseif ($three_flag){
$third_v = $val;
$three_flag = 0;
$four_flag = 1;
}
elseif ($four_flag){
$fourth_v = $val;
$four_flag = 0;
$one_flag = 1;
}
if ($val == 45){
# tricky part
echo "The last three v's were: " . $first_v . ", " . $second_v . ", " . $third_v . "<br>";
}
}
Simple question, how do I get every option when dividing a number? For example:
24 by 6 returns 6, 12, 18, 24
24 by 4 returns 4, 8, 12, 16, 20, 24
24 by 5 returns false
I've got a number in my database, for example 2, and my counter, for example 14. That means every time my counter hits the second number, I want to fire my event. So I thought, if I have the solutions 2, 4, 6, etc, and my counter is equal to one of the solutions, I can fire my event.
It's rather trivial to make.
<?php
/**
* #param int $number The beginning number
* #param int $divider The number dividing by
*
* #return array
* #throws Exception In case $number is not divisible by $divider
*/
function get_number_sequence($number, $divider) {
//In case $number is not divisible by $divider, throw an Exception.
if ($number % $divider !== 0) {
throw new Exception("$number is not divisible by $divider");
}
//Return an array from $divider to $number in steps of $divider.
$result = range($divider, $number, $divider);
return $result;
}
/*
* Testing begins
*/
try {
echo "<pre>";
echo implode(", ", get_number_sequence(24, 4)) . PHP_EOL;
echo implode(", ", get_number_sequence(24, 6)) . PHP_EOL;
echo implode(", ", get_number_sequence(24, 5)) . PHP_EOL;
echo "</pre>";
}
catch (Exception $e) {
echo "Invalid: " . $e->getMessage();
}
Some Points
Don't return false if something exceptional happens, use an Exception as shown in the example.
Use the modulus operator to determine if the number is divisible or not.
Return an array, not a string. It's easier to work with.
should be easy
do a modulus on X by Y . If 0 then do a division on X by Y. create a loop which will run from 1 to (division on X by Y) and output Y multiplied by the loop counter
function steps($target,$step) {
if (($target % $step) != 0)
return FALSE;
$steps = range($step,$target,$step);
return $steps;
}
$target = 24;
for ($step = 2; $step < 13; ++$step) {
echo '$step = ',$step,PHP_EOL;
$steps = steps($target,$step);
var_dump($steps);
}
function findQuotients($number, $divider)
{
$arr = array();
if($number % $divider != 0)
{
//return "false";
}
else
{
$loop = $number / $divider;
//$output="";
for($i = 1; $i <= $loop; $i++)
{
//$output .= $i * $divider. " ";
array_push($arr, $i * $divider);
}
}
return $arr;
}
echo print_r(findQuotients(24, 6));
echo print_r(findQuotients(24, 4));
echo print_r(findQuotients(24, 5));
Try this
$number = 24;
$divider = 6;
if($number % $divider != 0 )
{
return false;
}
$div = $number / $divider;
for($i = 1; $i <= $div; $i++)
{
echo $i*$divider;
}
The following snippet will do the trick. It's a simple loop to iterate until $num is <= 0. $num will be subtracted by the divider and each turn the next multiple of $div will be stored as a "divider step".
$num = 24;
$div = 4;
if ($num % $div != 0) {
exit('invalid');
}
$divider = array();
for ($i = 1; $num > 0; $i++) {
$divider[] = ($i * $div);
$num -= $div;
}
echo 'in: ' . $num . '<br />';
echo 'div: ' . $div . '<br />';
echo '<pre>';
print_r($divider);
exit;
based on your description you want to multiply a number and then on a given result you want to white a function:
$num = 6;
$counter = 2;
$solution = 24;
while ($num * $counter) {
$result= $num * $counter;
if ($result = $solution) {
echo $result;
// here would go your event
break;
}
}
This question already has answers here:
PHP get the item in an array that has the most duplicates
(2 answers)
Closed 1 year ago.
I have an array of numbers like this:
$array = array(1,1,1,4,3,1);
How do I get the count of most repeated value?
This should work:
$count=array_count_values($array);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo "The most occuring value is $keys[0][1] with $keys[0][0] occurences."
I think array_count_values function can be useful to you. Look at this manual for details : http://php.net/manual/en/function.array-count-values.php
You can count the number of occurrences of values in an array with array_count_values:
$counts = array_count_values($array);
Then just do a reverse sort on the counts:
arsort($counts);
Then check the top value to get your mode.
$mode = key($counts);
If your array contains strings or integers only you can use array_count_values and arsort:
$array = array(1, 1, 1, 4, 3, 1);
$counts = array_count_values($array);
arsort($counts);
That would leave the most used element as the first one of $counts. You can get the count amount and value afterwards.
It is important to note that if there are several elements with the same amount of occurrences in the original array I can't say for sure which one you will get. Everything depends on the implementations of array_count_values and arsort. You will need to thoroughly test this to prevent bugs afterwards if you need any particular one, don't make any assumptions.
If you need any particular one, you'd may be better off not using arsort and write the reduction loop yourself.
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values, with some useless defaults */
$max = 0;
$max_item = $array[0];
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_item = $value;
}
}
After the foreach loop, $max_item contains the last item that appears the most in the original array as long as array_count_values returns the elements in the order they are found (which appears to be the case based on the example of the documentation). You can get the first item to appear the most in your original array by using a non-strict comparison ($amount >= $max instead of $amount > $max).
You could even get all elements tied for the maximum amount of occurrences this way:
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values */
$max = 0;
$max_items = array();
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_items = array($value);
} elif ($amount = $max) {
$max_items[] = $value;
}
}
$vals = array_count_values($arr);
asort($vals);
//you may need this end($vals);
echo key($vals);
I cant remember if asort sorts asc or desc by default, you can see the comment in the code.
<?php
$arrrand = '$arr = array(';
for ($i = 0; $i < 100000; $i++)
{
$arrrand .= rand(0, 1000) . ',';
}
$arrrand = substr($arrrand, 0, -1);
$arrrand .= ');';
eval($arrrand);
$start1 = microtime();
$count = array_count_values($arr);
$end1 = microtime();
echo $end1 - $start1;
echo '<br>';
$start2 = microtime();
$tmparr = array();
foreach ($arr as $key => $value);
{
if (isset($tmparr[$value]))
{
$tmparr[$value]++;
} else
{
$tmparr[$value] = 1;
}
}
$end2 = microtime();
echo $end2 - $start2;
Here check both solutions:
1 by array_count_values()
and one by hand.
<?php
$input = array(1,2,2,2,8,9);
$output = array();
$maxElement = 0;
for($i=0;$i<count($input);$i++) {
$count = 0;
for ($j = 0; $j < count($input); $j++) {
if ($input[$i] == $input[$j]) {
$count++;
}
}
if($count>$maxElement){
$maxElement = $count;
$a = $input[$i];
}
}
echo $a.' -> '.$maxElement;
The output will be 2 -> 3
$arrays = array(1, 2, 2, 2, 3, 1); // sample array
$count=array_count_values($arrays); // getting repeated value with count
asort($count); // sorting array
$key=key($count);
echo $arrays[$key]; // get most repeated value from array
String S;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
S = in.nextLine();
int count =1;
int max = 1;
char maxChar=S.charAt(0);
for(int i=1; i <S.length(); i++)
{
count = S.charAt(i) == S.charAt(i - 1) ? (count + 1):1;
if(count > max)
{
max = count;
maxChar = S.charAt(i);
}
}
System.out.println("Longest run: "+max+", for the character "+maxChar);
here is the solution
class TestClass {
public $keyVal;
public $keyPlace = 0;
//put your code here
public function maxused_num($array) {
$temp = array();
$tempval = array();
$r = 0;
for ($i = 0; $i <= count($array) - 1; $i++) {
$r = 0;
for ($j = 0; $j <= count($array) - 1; $j++) {
if ($array[$i] == $array[$j]) {
$r = $r + 1;
}
}
$tempval[$i] = $r;
$temp[$i] = $array[$i];
}
//fetch max value
$max = 0;
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] > $max) {
$max = $tempval[$i];
}
}
//get value
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] == $max) {
$this->keyVal = $tempval[$i];
$this->keyPlace = $i;
break;
}
}
// 1.place holder on array $this->keyPlace;
// 2.number of reapeats $this->keyVal;
return $array[$this->keyPlace];
}
}
$catch = new TestClass();
$array = array(1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 1, 2, 3, 1, 1, 2, 5, 7, 1, 9, 0, 11, 22, 1, 1, 22, 22, 35, 66, 1, 1, 1);
echo $catch->maxused_num($array);