Related
I already have solution. But i think it will be more optimizable. So please provide me a solution for it. And remember that don't use predefined function of php. Like max() function.
i know there are so many ways to find it but i want best and better solution. Because my array contains more than 1 lakh records and it's taking lot of time. Or sometime site will be down.
My code :
<?php
$array = array('1', '15', '2','10',4);
echo "<pre>";
print_r($array);
echo "<pre>";
$max = 0;
$s_max=0;
for($i=0; $i<count($array); $i++)
{
$a = $array[$i];
$tmax = $max;
$ts_max = $s_max;
if($a > $tmax && $a > $ts_max)
{
$max = $a;
if($tmax > $ts_max) {
$s_max = $tmax;
} else {
$s_max = $ts_max;
}
} else if($tmax > $a && $tmax > $ts_max)
{
$max = $tmax;
if($a > $ts_max) {
$s_max = $a;
} else {
$s_max = $ts_max;
}
} else if($ts_max > $a && $ts_max > $tmax)
{
$max = $ts_max;
if($a > $tmax)
{
$s_max = $a;
} else {
$s_max = $tmax;
}
}
}
echo "Max=".$max;
echo "<br />";
echo "S_max=".$s_max;
echo "<br />";
?>
<?php
$array = array('200', '15','69','122','50','201');
$max_1 = $max_2 = 0;
for ($i=0; $i<count($array); $i++) {
if ($array[$i] > $max_1) {
$max_2 = $max_1;
$max_1 = $array[$i];
} else if ($array[$i] > $max_2 && $array[$i] != $max_2) {
$max_2 = $array[$i];
}
}
echo "Max=".$max_1;
echo "<br />";
echo "Smax 2=".$max_2;
See this solution.
<?php
$numbers = array_unique(array(1,15,2,10,4));
// rsort : sorts an array in reverse order (highest to lowest).
rsort($numbers);
echo 'Highest is -'.$numbers[0].', Second highest is -'.$numbers[1];
// O/P: Highest is -15, Second highest is -10
?>
I didn't check your solution, but in terms of complexity it's IMO optimal. If the array has no more structural information (like it's sorted) there's no way to skip entries. I.e. the best solution is in O(n) which your solution is.
This is a perfect and shortest code to find out the second largest value from the array. The below code will always return values in case the array contains only a value.
Example 1.
$arr = [5, 8, 1, 9, 24, 14, 36, 25, 78, 15, 37];
asort($arr);
$secondLargestVal = $arr[count($arr)-1];
//this will return 37
Example 2.
$arr = [5];
asort($arr);
$secondLargestVal = $arr[count($arr)-1];
//this will return 5
You can also use techniques in sorting like Bubble sort
function bubble_Sort($my_array )
{
do
{
$swapped = false;
for( $i = 0, $c = count( $my_array ) - 1; $i < $c; $i++ )
{
if( $my_array[$i] > $my_array[$i + 1] )
{
list( $my_array[$i + 1], $my_array[$i] ) =
array( $my_array[$i], $my_array[$i + 1] );
$swapped = true;
}
}
}
while( $swapped );
return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "Original Array :\n";
echo implode(', ',$test_array );
echo "\nSorted Array\n:";
echo implode(', ',bubble_Sort($test_array)). PHP_EOL;
Original Array :
3, 0, 2, 5, -1, 4, 1
Sorted Array :
-1, 0, 1, 2, 3, 4, 5
Flow explanation
$array = array(80,250,30,40,90,10,50,60,50); // 250 2-times
$max = $max2 = 0;
foreach ($array as $key =>$val) {
if ($max < $val) {
$max2 = $max;
$max = $val;
} elseif ($max2 < $val && $max != $val) {
$max2 = $val;
}
}
echo "Highest Value is : " . $max . "<br/>"; //output: 250
echo "Second highest value is : " . $max2 . "<br/>"; //output: 90
The answer given by "Kanishka Panamaldeniya" is fine for highest value but will fail on second highest value i.e. if array has 2-similar highest value, then it will showing both Highest and second highest value same. I have sorted out it by adding one more level comparsion and it works fine.
$array = array(50,250,30,250,40,70,10,50); // 250 2-times
$max=$max2=0;
for ($i = 0; $i < count($array); $i++) {
if ($array[$i] > $max) {
$max2 = $max;
$max = $array[$i];
} else if (($array[$i] > $max2) && ($array[$i] != $max)) {
$max2 = $array[$i];
}
}
echo "Highest Value is : " . $max . "<br/>"; //output : 250
echo "Second highest value is : " . $max2 . "<br/>"; //output : 70
This code will return second max value from array
$array = array(80,250,30,250,40,90,10,50,60,50); // 250 2-times
$max=$max2=0;
for ($i = 0; $i < count($array); $i++) {
if($i == 0) {
$max2 = $array[$i];
}
if($array[$i] > $max) {
$max = $array[$i];
}
if($max > $array[$i] && $array[$i] > $max2) {
$max2 = $array[$i];
}
}
echo "Highest Value is : " . $max . "<br/>"; //output : 250
echo "Second highest value is : " . $max2 . "<br/>"; //output : 90
Two way find the second highest salary
1. Sort the data in Descending order
2. get array first value
3. Check the condition already comments
$array = [2,3,6,11,17,14,19];
$max = $array[0];
$count = count($array);
for($i=0; $i<$count;$i++)
{
for($j=$i+1;$j<$count;$j++)
{
if($array[$i] < $array[$j])
{
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
}
First Method
//echo $array[1]; // Second highest value
$second ='';
for($k=0;$k<2;$k++)
{
if($array[$k] >$max)
{
$second = $array[$k];
}
}
echo $second; // Second method
Without using MAX function. Here.
$arr = [3,4,-5,-3,1,0,4,4,4];
rsort($arr); // SORT ARRAY IN DESCENDING ORDER
$largest = $arr[0]; // IN DESCENDING ORDER THE LARGEST ELEMENT IS ALWAYS THE FIRST ELEMENT
$secondLargest = 0;
foreach($arr as $val){
$secondLargest = $val; // KEEP UPDATING THE VARIABLE WITH THE VALUE UNTIL IT RECEIVES THE FIRST ELEMENT WHICH IS DIFFERENT FROM THE LARGEST VALUE
if($val != $arr[0]){
break; // BREAK OUT OF THE LOOP AS SOON AS THE VALUE IS DIFFERENT THAN THE LARGEST ELEMENT
}
}
echo $secondLargest;
My task is to create a function named 'maximum' that will find the max in a given set of numbers. My function should return the max number.
Requirement:
My function should not use 'sizeof' or 'count' function that counts the number of elements in the array.
How will I do that? This is my PHP function:
function maximum($array){
$elements = count($array);
$max = $array[0];
for($a=1; $a < $elements; $a++){
if ($max < $array[$a]){
$max = $array[$a];
}
}
return $max;
}
Using built-in function:
$max = max($array);
Using foreach:
$max = 0;
foreach ( $array as $item ) {
if ( $max<$item ) {
$max = $item;
}
}
Using sorting function:
rsort($array);
$max = array_shift($array);
or
sort($array);
$max = array_pop($array);
$max = $array[0];
foreach ($array as $value) {
if ($max < $value){
$max = $value;
}
}
you could do this by max()
echo max($array);
function maximum($array) {
$max = 0;
foreach($array as $value) { // get every value of array
if($max < $value) // if value of array is bigger then last one
$max = $value; // put it into $max
}
return $max;
}
Let's say I have this array
$number = [2,1,4,3,6,2];
First pair the elements on an array by two's and find their difference
so this is the output in the first requirement
$diff[] = [1,1,4];
Second sum all the difference
this is the final output
$sum[] = [6];
Conditions:
the array size is always even
the first element in a pair is always greater than the second one, so their is no negative difference
What I've done so far is just counting the size of an array then after that I don't know how to pair them by two's. T_T
Is this possible in php? Is there a built in function to do it?
One line:
$number = [2,1,4,3,6,2];
$total = array_sum(array_map(function ($array) {
return current($array) - next($array);
}, array_chunk($number, 2)));
echo $total;
This should work fine:
<?
$number = array(2,1,4,3,6,2);
for($i=0;$i<count($number); $i+=2){
$dif[] = $number[$i] - $number[$i+1];
}
print_r($dif);
$sum = 0;
foreach ($dif as $item){
$sum += $item;
}
echo 'SUM = '.$sum;
?>
Working CODE
If you want all the different stages kept,
$numbers = [2,1,4,3,6,2];
$diff = [];
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$diff[] = $numbers[$i]-$numbers[$i+1];
}
$sum = array_sum($diff);
Else, to just get the total and bypass the diff array:
$numbers = [2,1,4,3,6,2];
$total = 0;
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$total += $numbers[$i]-$numbers[$i+1];
}
I have got this far it gives the required solution.
$arr = array(2,1,4,3,6,2);
$temp = 0;
$diff = array();
foreach ($arr as $key => $value) {
if($key % 2 == 0) {
$temp = $value;
}
else {
$diff[] = $temp - $value;
}
}
print_R($diff);
print 'Total :' . array_sum($diff);
Note : Please update if any one knows any pre-defined function than can sorten this code.
Please check and see if this works for you.
<?php
$sum=0;
$number = array(2,1,4,3,6,2);
for ($i=0;$i<=count($number);$i++) {
if ($i%2 == 1 ) {
$sum = $sum + $number[$i-1] - $number[$i];
}
}
print $sum;
?>
Well with your conditions in mind I came to the following
$number = [2,1,4,3,6,2];
$total = 0;
for($i = 0; $i < count($number); $i+=2) {
$total += $number[$i] - $number[$i + 1];
}
Try this one:
$number = array(2,1,4,3,6,2);
$diff = array();
$v3 = 0;
$i=1;
foreach($number as $val){
if ($i % 2 !== 0) {
$v1 = $val;
}
if ($i % 2 === 0) {
$v2 = $val;
$diff[] = $v1-$v2;
$v3+= $v1-$v2;
}
$i++;
}
print $v3;//total value
print_r($diff); //diff value array
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);
How could I echo 5 elements randomly from an array of about 20?
Thanks.
Does this work?
$values = array_rand($input, 5);
Or, as a more flexible function
function randomValues($input, $num = 5) {
return array_rand($input, $num);
}
//usage
$array = range('a', 'z');
//prints 5 random characters from the alphabet
print_R(randomValues($array));
for($i=0; $i++; $i < 5)
{
echo $array[rand(0, count($array)-1);
}
or
for($i=0; $i++; $i < 5)
{
echo array_rand($array);
}
or
array_map("echo", array_rand($array, 5));
$n = number of random numbers to return in the array
$min = minimum number
$max = maximum number
function uniqueRand($n, $min = 0, $max = null)
{
if($max === null)
$max = getrandmax();
$array = range($min, $max);
$return = array();
$keys = array_rand($array, $n);
foreach($keys as $key)
$return[] = $array[$key];
return $return;
}
$randNums = uniqueRand(5, 0, count($array)-1);
for($i=0; $i++; $i < 5)
{
echo $array[$randNums[i]);
}