I have an array let say $array = array(2, 1, 8, 3, 6, 0, 10, 10)and I want to get second largest value of that array.
Which sorting/searching technique will be best & how could I use it?
I'd just remove the duplicates from your array (using array_unique) and then use rsort (which uses Quicksort) with the SORT_NUMERIC flag to sort numerically from highest to lowest:
$array = array(2, 1, 8, 3, 6, 0, 10, 10);
$unique_array = array_unique($array);
rsort($unique_array, SORT_NUMERIC);
$second_highest = $unique_array[1]; // will be 8
The PHP manual has a comparison of sorting techniques.
Something like this?
$array = array(2, 1, 8, 3, 6, 0, 10, 10);
rsort($array);
echo $array[1]; // 10
this reverse sorts the array and then outputs the second element.
Edit: if you want the second highest unique value, just add an array_unique call:
$array = array(2, 1, 8, 3, 6, 0, 10, 10);
$array = array_unique($array);
rsort($array);
echo $array[1]; // 8
you could use rsort, but it will do a lot of additional operations which are not needed (quick sort has O(logn) complexity).
It might be a lot faster if you pass the array only in one pass like this (O(n)):
$largest=$array[0];
$secondLargest=null; //none present, by default
foreach($array as $value)
if($value>$largest)
{
$secondLargest=$largest;
$largest=$value;
}
it will be significantly faster on large arrays, but it is only good when you want the first, second, maybe third largest element. In all other cases it would be more reasonable to sort the array and take the N'th largest element dynamically.
Related
Can someone help me for my College Exam. I tried to search but Im totally newbie in php and Im still studying
Here's what i want, Can you give me some Idea or function so that I can arrange an array of positive integers to form the largest numerical string?
For Example:
$arrnew = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert(getLargestNumStr($arrnew) == 98765432110, 'Basic test 9-8-7-6-5-4-3-2-1-10');
Hope you can help me.
This is a nice problem, this could be solved by this observation:
let's consider two elements in the array x and y, so assume that for the two numbers created by appending these two elements: xy > yx => in the final result, x will always be in front of y, otherwise, we could easily create a larger number by swapping the position of x and y in the result.
=> We could simply create a custom sort based on this observation, when compare two number x and y.
Give a try with below code if it solve your problem...
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$text='';
foreach($array as $arr){
$text.=$arr;
}
$string = str_split($text, "1");
$new_text = implode(",", $string);
$output=explode(",",$new_text);
rsort($output);
$final = '';
foreach($output as $out){
$final.=$out;
}
echo $final;
Try sorting the array in descending order with something like arsort() and concatinate the Array-elements to a string. This should give you the highest possible number.
Try this
$arrnew = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arsort($arrnew);
$str = str_replace(',','',join(',',$arrnew));
$arr1 = str_split($str);
arsort($arr1);
print_r($arr1);
echo implode('',$arr1);
Demo
I want to merge 2 arrays together that have a different number of elements, using the keys from one and the values from another where/if the keys match. The array that contains the desired values may have less elements in it although I would like to retain the resulting empty keys from the original array. For example:
//Array that contains keys I would like to retain
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
//Array that contains values I'd like to use
$arr2 = array(01=>123, 03=>123, 05=>123, 07=>123, 09=>123, 11=>123);
//The desired result with some valueless elements
$results = array(01=>123, 02, 03=>123, 04, 05=>123, 06, 07=>123, 08, 09=>123, 10, 11=>123, 12);
As you can see the results array retains 12 elements but only applies values to where the keys from the 2 arrays match.
I have tried $results = array_intersect_key($arr1 + $arr2, $arr2); among other PHP functions as well as:
for ($i=1; $i < count($arr1); $i++) {
if (isset($arr2[$i])) {
$arr3[] = $arr2[$i];
} else {
$arr3[] = $arr1[$i];
}
}
print_r($arr3);
No luck as yet.
Thanks in advance!
For arrays like this
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
$arr2 = array(1=>123, 3=>123, 5=>123, 7=>123, 9=>123, 11=>123);
this should work.
foreach ($arr1 as $key) {
$results[$key] = isset($arr2[$key]) ? $arr2[$key] : null;
}
or using some other PHP functions:
$results = array_replace(array_fill_keys($arr1, null), $arr2);
//Array that contains keys I would like to retain
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
//Array that contains values I'd like to use
$arr2 = array(1=>123, 3=>123, 5=>123, 7=>123, 9=>123, 11=>123);
$result = array_fill_keys(
$arr1,
null
);
array_walk(
$result,
function(&$value, $key) use($arr2) {
$value = (isset($arr2[$key])) ? $arr2[$key] : null;
}
);
var_dump($result);
First set your $arr1's values to false to retain just the keys:
$arr1 = array_fill_keys(array_keys($arr1), false); Or if you're generating $arr1 yourself, define it as such to start with: $arr1 = Array(false, false, false, false /* etc. */);
Now use the array union operator:
$result = $arr2 + $arr1;
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays — from the docs: http://php.net/manual/en/language.operators.array.php)
Then if required sort the array by key: ksort($array);
I am having doubt implementing this algorithm in PHP. I have few address bounds( or ranges ). The size of the address bound vary ( as shown in the image). Now, I have a key element. I need to find, which address bound, does the key element lie.
I am currently using multiple if statements to compare, add the bound length. I am sure, there is a better way to do it. Any idea how it can be implemented.
I am not looking for code( even though it helps :) ). Just the idea on how it can be implemented, would be helpful .
A way to do the job, is to define a 2-dimensional array, which contains the bounds:
<?php
$bounds = array();
$bounds[0] = array(1, 1, 1);
$bounds[1] = array(1, 1, 1, 1, 1);
$bounds[2] = array(1, 1, 1);
// ...
?>
And an other array which contains the index of the bound depending on the key:
<?php
$indexes = array(0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2,
3, 3, 3, 3,
4);
?>
Then, assuming $key = 10, $bounds[$indexes[$key]] refers to $bounds[2] which is array(1, 1, 1);
Here you are duplicating data but this is a O(1) algorithm.
An other way (the best if you don't manipulate a ton of data), without duplicating data (but O(n) complexity), is to go through the $bounds array:
<?php
for($key = 10, $i = 0; $key >= 0; $key -= count($bounds[$i]), ++$i);
?>
Here, $bounds[$i-1] refers to $bounds[2].
I have 2 arrays to compare and find if there is at least a single value in common.
This works just fine:
$arr1 = array(1, 2, 3, 4, 5);
$arr2 = array(2, 3, 4, 5, 6);
if (array_intersect($arr1, $arr2)) {
// good, at least one match found
}
However, the question is performance. It doesn't make sense to continue looping thru the arrays after the first match was found. Is there a native PHP function or a useful snippet to achieve this?
Will a combination of foreach() and in_array() do the trick?
How about this?
foreach ($arr1 as $key => $val) {
if (in_array($val, $arr2)){
// do something, maybe return so you wouldn't need break
break;
}
}
Just compare the first value?
$arr1 = array(1, 2, 3, 4, 5);
$arr2 = array(2, 3, 4, 5, 6);
if (array_intersect($arr1, $arr2)[0]) {
// good, at least one match found
}
I have an array that has values like 1, 5, 6, 9, 11, 45, 56, etc. What I'm trying to do is to randomly one value, perhaps 6. Then I want to pick a random value excluding 6 (so no doubles). Then a random value excluding the last two, all from inside an array. Any help? I'm trying to do this without while loops but if they are necessary then so be it.
I suggest the following:
# pick a random key in your array
$rand_key = array_rand($your_array);
# extract the corresponding value
$rand_value = $your_array[$rand_key];
# remove the key-value pair from the array
unset($your_array[$rand_key]);
See: array_rand, unset.
Shuffle the array first and then use it as a stack:
$a = array(1, 5, 6, 9, 11, 45, 56);
shuffle($a);
// now you can have your picks:
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
...
I would probably shuffle the array and get the first/last x value