Given a list of integers and a variable containing an integer find the position of the largest number less than the given number. The list is sorted and the given number is not in the list but between two numbers in the list.
For example given list = {8,13,19,35,40,45} and var = 26 one wants to compute the position of 19, which is 3. A simple Select would be a natural thing to try but a Select criteria using a variable does not work. The first code does not work while the second more complicated does.
Is there an easier way to achieve the same result?
var = 22;
list = {8, 13, 19, 35, 40, 45};
Max[Select[list, # &, var]]
-Infinity (* Result *)
This works:
First[Flatten[Position[Sort[AppendTo[list, var]], var]]] - 1
3 (* Result *)
var = 22; list = {8, 13, 19, 35, 40, 45}; Position[list, SelectFirst[list, # > var &]] - 1
$\endgroup$var = 22; list = {8, 13, 19, 35, 40, 45}; FirstPosition[Between[var, ##] & /@ Partition[list, 2, 1], True]
$\endgroup$