Last active
April 27, 2021 03:53
-
-
Save harmlessprince/25f6bf8b23557c9582a02500043545c6 to your computer and use it in GitHub Desktop.
This function returns start and end position of of given value in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function FindStartEnd($array, $val) | |
{ | |
$type = gettype($array); | |
try { | |
if (!$array) { | |
throw new Exception("Expects parameter 1 to be array and should contain at least one value"); | |
} | |
if (!is_numeric($val)) { | |
throw new Exception("Second value passed must be a number"); | |
} | |
if(sort($array)){ | |
$indexes = array_keys($array, $val); | |
if (!$indexes) { | |
return [-1, -1]; | |
} | |
return [min($indexes), max($indexes)]; | |
} | |
throw new Exception("expects parameter 1 to be array, $type given"); | |
} catch (Exception $e) { | |
echo 'Error: ' . $e->getMessage() . "\n"; | |
} | |
} | |
print_r(FindStartEnd([0,8,-2,5,0], 0)); |
Thank you very much and look forward to coming Friday.
By the way, the link is broken, I am getting a 404 error.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really commendable effort @harmlessprince, I like this solution a lot better even though it is still dependent on the performance of
array_keys
andcount
functions.I have written a blog post here sharing my solution to this problem - a solution that avoids having to sort the array. Please read through and let me know what you think.
Thank you for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.