Code
<?php
$array = array("1", "2", "3", "4", "5", "6", "7", "8", "100");
$max = $temp = 0;
$min = $temp = 0;
//This loop is to get max and min value from array
for ($i = 0 ; $i < count($array); $i++) {
if ($i == 0) {
$max = $temp = $array[$i];
}
if ($i > 0) {
if ($array[$i] > $temp) {
$max = $array[$i];
}
}
if ($i == 0) {
$min = $temp = $array[$i];
}
if ($i < 0) {
if ($array[$i] < $temp) {
$min = $array[$i];
}
}
}
echo "Max Number = $max <br>";
echo "Min Number = $min";
?>
The above code only calculates one minimum and one maximum number from the array. I need it to calculate 3 maximum and 3 minimum numbers.
I can't use pre-made functions and can't use more than one for loop so kindly suggest me customization within the above code.
This looks neat to me.
<?php
$array = array("1", "2", "3", "4", "5", "6", "7", "8", "100");
$n1 = $n2 = $n3 = 1000 ; // some high number
$m1 = $m2 = $m3 = 0 ;
//This loop is to get max and min value from array
for ($i = 0 ; $i < count($array); $i++) {
$x = $array[$i] ;
//min
if ($x <= $n1){
$n3 = $n2 ;
$n2 = $n1 ;
$n1 = $x ;
} elseif ($x < $n2){
$n3 = $n2;
$n2 = $x;
} elseif ($x < $n3){
$n3 = $x;
}
//max
if ($x >= $m1){
$m3 = $m2 ;
$m2 = $m1 ;
$m1 = $x ;
} elseif ($x > $m2){
$m3 = $m2;
$m2 = $x;
} elseif ($x > $m3){
$m3 = $x;
}
}
echo "Min Number = $n1 $n2 $n3<br>";
echo "Max Number = $m1 $m2 $m3";
?>
Output:
Min Number = 1 2 3
Max Number = 100 8 7
This code is working properly
<?php
$array = array("1", "2", "3", "4", "5", "6", "7", "8", "100");
$max1 =$max2 =$max3= -999999999999999; // highest possible number
$min3 = $min2= $min1 = 9999999999999999; // lowest possible number
for ($i = 0 ; $i < count($array); $i++) {
$x = $array[$i] ;
//to get the max 3 numbers
if($x>= $max1)
{
$max3 = $max2;
$max2 = $max1;
$max1 = $x;
}
else if ($x> $max2)
{
$max3 = $max2;
$max2 = $x;
}
else if ($x> $max3)
{
$max3 = $x;
}
// to get the min 3 numbers
if($x<=$min3 && $x>$min2 )
{
$min3 = $x;
}
else if ($x<$min2 && $x>$min1)
{
$min3 = $min2;
$min2 = $x;
}
else if ( $x<$min1)
{
$min3 = $min2;
$min2 = $min1;
$min1 = $x;
}
}
echo "Max Number = $max1 , $max2 , $max3 <br>";
echo "Min Number = $min1 , $min2 , $min3";
?>
The output is
Max Number = 100 , 8 , 7
Min Number = 1 , 2 , 3
There are better ways and more efficient than that but which requires 2 loops and u don't want that !
You can handle this using if statements
Checking for the max/min number works when you find another min/max value other than the previous one while looping. This is the algorithm that you use
Lets assume that your min=5
and after looping the current index value is 3, so you will have to make min=3
What about assigning 5 to min2 for example?
Three variables min1, min2, min3, and nested if statements
I know it's not the best way. But have you tried this?
You just need to reverse sort the array and then slice the first three indexes. You could express it as a function:
function topThree(Array $arr) {
// Sort the array in reverse
rsort($arr);
// Return the first three indexes (top three)
return array_slice($arr, 2);
}
See rsort and array_slice
Edit: Okay this works
/**
* Sorts an array of numeric values from largest to
* smallest and returns the three highest values.
*
* #param Array $arr An array of numeric values.
* #return Array $srt The three highest values in $arr.
*/
function topThree(Array $arr) {
$srt = [];
foreach($arr as $key => $val) {
if(!$key) {
$srt[] = $val;
} else if ($val < $srt[0]) {
array_unshift($srt, $val);
} else if ($val > $srt[count($srt)-1]) {
array_push($srt, $val);
} else {
for( $i=1; $i<count($srt); $i++) {
if($val < $srt[$i]) {
array_splice( $srt, $i, 0, $val );
break;
}
}
}
}
$max = array_slice($srt, -3, 3);
$min = array_slice($srt, 0, 3);
return ["min" => $min, "max" => $max];
}
// "Test"
for($i=0; $i<20;$i++){
$arr[]=rand(-100,100);
}
print_r($arr);
print_r(topThree($arr));
If $val's the first $key $val's added to $sort.
If $val's less than $sort[0] $val's added to the start of $sort.
If $val's greater than $sort[length], then $val's added to the end of $sort.
Otherwise, we check every $val against every other $sort value. When we find a $sort[$i] value greater than $val, we splice the array with $val at $i.
Make sense?
Related
I have the following code:
<?php
echo "<p>Exercise 5:</p>";
echo "Numbers: ";
$random = 0;
while ($random < 10) {
$rand = rand(2, 80);
echo "$rand";
$random = $random + 1;
if ($random < 10) {
echo ", ";
};
}
echo "<br><br>Min value: <br>";
echo "Max value: <br>";
echo "Average value: <br>";
?>
How can I calculate the min, max and average value of the 10 numbers?
$min = min($rand) doesn't work...
$max = max($rand) doesn't work either...
$rand is a single value, minimum of a single value is irrelevant. Min takes an array as parameter (or several values), so save your values in an array, e.g. like this.
$array = array();
while($random < 10) {
$rand = rand(2, 80);
$array[] = $rand;
$random++; // short for random = random + 1
}
echo min($array);
Works also with max.
Moreover, average = sum / count, you have array_sum and count function in PHP, I let you figure out how to do that.
Edit: Augustin is right about division by zero. Consider adding a condition when making a division by a variable.
One solutions thinking in division by zero could be:
$random = 0;
$numbers = array();
while ($random < 10) {
$rand = rand(2, 80);
echo "$rand";
$numbers[] = $rand;
$random ++;
}
$min = min($numbers);
$max = max($numbers);
if($totalNumbers = count($numbers) > 0) {
$average = array_sum($numbers) / count($numbers);
}else{
$average = 0;
}
echo "<br><br>Min value: $min <br>";
echo "Max value: $max <br>";
echo "Average value: $average <br>";
I don't understand why min or max doesn't work, but in this case, you could make a custom max min function:
function customMaxMin($numbers)
{
$max = 0;
$min = 0;
foreach ($numbers as $number) {
$max = $number;
$min = $number;
if ($max > $number) {
$max = $number;
}
if ($min < $number) {
$min = $number;
}
}
return array('max' => $max, 'min' => $min);
}
Conditions:
Starting digit should not be 0
Succeeding digits should be greater than preceding numbers.
The last digit can be 0
The middle digit should not be 0
We have succeeded in satisfying the first two conditions but because of the contradiction between second and third condition, I am not able to get the expected output.
For example,
The input 1234 gives output:
123
124
134
234
For the digits 12340, the output should be:
123
124
134
234
120
120
140
230
240
340
But it isn't working with what I have done.
The code:
<?
function pc_permute($items, $perms = array( )) {
if (empty($items)) {
$return = array($perms);
} else {
$return = array();
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$return = array_merge($return, pc_permute($newitems, $newperms));
}
}
return $return;
}
// example
$chars = array('1', '2', '3','4','0');
$output = pc_permute($chars);
$a=count($output);
for ($i = 0; $i<count($output);$i++) {
for ($j = 0; $j < 3;$j++){
$c[$i] = $c[$i].$output[$i][$j];
}
}
$arr = array_unique($c);
$last = end(array_keys($arr));
$n=0;
for($i = 0;$i <= $last;$i++) {
if(!empty($arr[$i])){
$temp = $arr[$i];
$d = str_split($temp);
$e = end(array_keys($d));
$flag = 0;
for($j = 0;$j < (count($d)-1); $j++) {
if(($d[$j] < $d[$j+1] && $d[0] != 0)) {
$flag = 1;
}
else {
$flag = 0;
break;
}
}
if($flag == 1) {
echo $temp;
echo "<br>";
$n++;
}
}
}
?>
You should deviate the following steps for your program based on the rules:
Due to rule 2 you can remove duplicates
Due to rule 2 you can sort the input
Due to rule 1, 3 and 4 you can move 0 to the end of the array, if present
If that is respected you can then iterate over the input array with three foreach loops, that permutate the succeeding numbers with the preceding ones. Because it is sorted in the correct order all rules will be respected automatically.
The comments explain what is done in each step.
$input = [0, 3, 1, 2, 2, 4];
$results = [];
//Remove duplicates, necessary for rule 2
$input = array_unique($input);
//Sort Numbers, necessary for rule 2
sort($input);
// Mark 0 as the greates number, so it can only appear at the end. Necessary for rule 1, 3 and 4
if ($input[0] === 0) {
$input[] = array_shift($input);
}
$inputCount = count($input);
for( $i = 0; $i < $inputCount - 2; $i++) {
for ($j = $i + 1; $j < $inputCount - 1; $j++) {
for ($k = $j + 1; $k < $inputCount; $k++) {
$results[] = $input[$i] . $input[$j] . $input[$k];
}
}
}
foreach ($results as $result) {
echo $result . '<br>';
}
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;
I want to generate 10 numbers with each ranging from (1 to 5) but can only duplicate after 2 elements
for example 5 3 1 4 2 5(can be duplicated here) 2 (cannot be duplicate here since it occur before 1 element) ...etc.
I have this code in php working but its performance is awful since it sometimes exceeds the maximum 30 seconds execution time.
<?php
function contain($prevItems, $number) {
if (count($prevItems) == 3)
{
array_shift($prevItems);
}
for ($k=0; $k<count($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,5);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,5);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,5);
}
$prevItems[$i] = $num[$i]; //append into the array
}
print_r($num);
?>
Edit:
I have also tried this method, its performance is good but it duplicates elements
<?php
$evalAccurance = array();
$count = 0;
while ( $count < 11)
{
$random = rand(1, 5);
if (in_array($random, $evalAccurance))
{
$p = $random;
for ($k = $p ; $k <5; $k++)
{
$random = $random++;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
if (in_array($random, $evalAccurance))
{
for ($k = $p ; $k >0; $k--)
{
$random = $random--;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
}
}
$evalAccurance[] = $random;
if (count ($evalAccurance) == 4)
array_shift($evalAccurance);
print_r ($evalAccurance);
$count++;
}
?>
One way you could do this:
// pass to function current array of numbers
function randomNumber($ar){
// create a random number from 1 to 5
$num = rand(1,5);
// check backwards 3 elements for same number, if none found return it
if(!in_array($num, array_slice($ar, -3, 3, true))){
return $num;
} else {
// else recall function with same array of numbers
return randomNumber($ar);
}
}
$array = array();
// loop 10 numbers and call randomNumber with current set of results.
for($i=1; $i<=10; $i++){
$array[] = randomNumber($array);
}
print_r($array);
Using PHP SPLQueue:
$queue = new SplQueue();
$values = array(1, 2, 3, 4, 5);
$container = array();
for ($i = 0; $i < 10; $i++) {
$value = give_random($values, $queue);
$container[] = $value;
if ($queue->offsetExists(1) AND $queue->offsetExists(0)) {
$queue->dequeue();
}
$queue->enqueue($value);
}
function give_random(&$values, &$queue) {
$picked_value = $values[array_rand($values)];
if ($queue->offsetExists(1)) {
if ($picked_value == $queue->offsetGet(1)) {
$picked_value = give_random($values, $queue);
}
}
if ($queue->offsetExists(0)) {
if ($picked_value == $queue->offsetGet(0)) {
$picked_value = give_random($values, $queue);
}
}
return $picked_value;
}
print_r($container);
It could be neater, but you can figure what's going on.
Cheers.
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);