-1

So given this array:

$stack = [ 100, 200, 300, 400, 500, 600, 700 ]

What is the best way, given some arbitrary number, for example $needle = 78, to find 'nearest' number from the stack. In this case it would be 100.

I have algorithm in mind, where I loop through all numbers, and do determine it eventually.

But this for some reason feels, like it has some nice one liner solution that I am just not aware of. So is my feeling correct, is there such one liner?

galdikas
  • 1,609
  • 5
  • 19
  • 43
  • Do you have any constraints? Such as, "`$stack` is always sorted" or "all numbers that end in `00`"? If not, then iterating and remembering the closest is the best there is. – Amadan Dec 05 '18 at 05:39
  • Asking about a "best way" is very broad, with no single *right* answer. If you have a problem with what you've coded, please edit your question to show what you've tried, issues/errors you're running into, etc. But as written, there's no code, just an ask for the community to solve this for you. And, unfortunately, that's off-topic for Stack Overflow. – David Makogon Dec 05 '18 at 05:40
  • 1
    There is no one-liner solution (regardless if the array is or isn't pre-sorted). The amount of code you need, however, is quite small though. Check this out: https://stackoverflow.com/questions/5464919/find-a-matching-or-closest-value-in-an-array – Javier Larroulet Dec 05 '18 at 05:41
  • Yeah I had something like what you reference in mind. I just thought that maybe there is some standart function available for this. Thanks everyone! :) – galdikas Dec 05 '18 at 05:48
  • To follow the "letter" of the question you could always do something like `$result = array_reduce($stack, function($carry, $item) use ($needle) { return abs($carry-$needle) < abs($item-$needle) ? $carry : $item; });` but readability wise it's pretty horrible compared to a straight forward function (and you'd need a pretty wide screen to have it fit one line :))) ) – Joachim Isaksson Dec 05 '18 at 07:00
  • Possible duplicate of [Find a matching or closest value in an array](https://stackoverflow.com/questions/5464919/find-a-matching-or-closest-value-in-an-array) – Matt Raines Dec 05 '18 at 09:01

1 Answers1

0

Simply create a function to check for value e.g.:

function findClose($needle, $stack) {
   $close= null;
   foreach ($arr as $value) {
     if ($close == null) {
          $close = $value;
     }

     if ( !is_null( $close ) && abs($value - $close) > abs($value - $search)) {
       $close= $value;
     }
  }
  return $close;
}

and call this function with your value.

echo findClose(160, $stack);

will give you the result you want.

Hope it helps.

kshitij
  • 642
  • 9
  • 17