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].
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 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
}
let's say I have these two arrays:
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
As you can see, my arrays have different lengths. What I'm trying to do is to input these array values into an HTML table with the first column containing the values coming from $array1 and the second column containing the values coming from $array2. So, in this case right here, I should have a table of 10 rows (because $array2 contains 10 elements) and 2 columns (because I have 2 arrays). Also, I cannot know in advance which array is going to have more elements than the other (so, $array1 could be bigger than $array2, they could also have equal sizes). So, depending on which array has more elements, the number of rows in my table should adjust accordingly.
Any idea please?
Thank you
$array2 = array(6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
$array1 = array(1, 2, 3, 4, 5);
$a=count($array1);
$b=count($array2);
echo "<table border=1><tr><th>Array1</th><th>Array2</th></tr>";
if($a > $b)
{
for($i=0;$i<$a;$i++)
{
echo "<tr><td>".$array1[$i]."</td>";
echo "<td>".$array2[$i]."</td></tr>";
}
}
if($b > $a)
{
for($i=0;$i<$b;$i++)
{
echo "<tr><td>".$array1[$i]."</td>";
echo "<td>".$array2[$i]."</td></tr>";
}
}
echo "</table>";
Try thinking of some thing like below
this will give you atleast an idea of how to iterate them.
$array = array($array1,$arry2);
for($i = 0; $i < $array.length; $i++)
{
$rows = $array[$i];
for($j=0; $j< $rows.length; $rows++){
}
}
i hope you can figure out the logic required from this . in case it doesnt work out post comment and we will walk through
This works but, is it reliable? Will it always work since the MAINarray is containing ANOTHERarray which contains 2 values and min should work in MAINarray and find lowest value in its subarays.
$a[0]=array(0=>522,1=>'Truck');
$a[1]=array(0=>230,1=>'Bear');
$a[2]=array(0=>13,1=>'Feather');
$a[3]=array(0=>40,1=>'Rabit');
$z=min($a);$y=max($a);
echo "The easiest is ".$z[1]." with only ".$z[0]." pounds!<br>";
echo "The heaviest is ".$y[1]." with ".$y[0]." pounds!";
What you say?
Yes, it is reliable. It's safe to assume that min(array(1, 2, ..., n)) is equivalent to min(1, 2, ..., n), and the documentation specifically covers how min compares multiple arrays:
// With multiple arrays, min compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
My understanding of how min works with your type of input is:
Only consider the arrays with the fewest number of items.
Compare the first elements
If there is a tie, compare the next element of each array. Repeat step.
e.g.:
array(
array(1, "A"),
array(2), // min
)
array(
array(1, "A"), // min
array(2, "A"),
)
array(
array(1, "Z"),
array(1, "A"), // min
)
I don't have a source for that information, but it's how I remember it working.
I’m not sure if this always works. In case of doubt just implement the function yourself:
function extremes($array, $key=0) {
if (count($array) === 0) return null;
$min = $max = null;
foreach ($array as &$val) {
if (!isset($val[$key])) continue;
if ($min > $val[$key]) $min = $val[$key];
else if ($max < $val[$key]) $max = $val[$key];
}
return array($min, $max);
}
$a = array(array(522, 'Truck'), array(230, 'Bear'), array(13, 'Feather'), array(40, 'Rabit'));
list($z, $y) = extremes($a);
The only evidence I could find to say it was intended to be able to use an array of arrays to compare is this bug report to improve the php docs. http://bugs.php.net/bug.php?id=50607
Although, it's quite unlikely for them to remove this functionality because of the way it has to compare arrays already by going into them recursively. The arguments list itself when using the function normally would be an array because there is no finite number of arguments.
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.