5
$\begingroup$

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 *)
$\endgroup$
2
  • $\begingroup$ var = 22; list = {8, 13, 19, 35, 40, 45}; Position[list, SelectFirst[list, # > var &]] - 1 $\endgroup$
    – cvgmt
    Commented Nov 10 at 8:50
  • $\begingroup$ Or var = 22; list = {8, 13, 19, 35, 40, 45}; FirstPosition[Between[var, ##] & /@ Partition[list, 2, 1], True] $\endgroup$
    – cvgmt
    Commented Nov 10 at 8:53

4 Answers 4

5
$\begingroup$
var = 22;
list = {8, 13, 19, 35, 40, 45};
SplitBy[list, # > var &] // First // Length

3

$\endgroup$
5
$\begingroup$
list = {8, 13, 19, 35, 40, 45};
var = 22;

Using LengthWhile:

LengthWhile[list, # < var &]

3

Or using PositionIndex and KeySelect:

Last@KeySelect[PositionIndex[list], # < var &]

{3}

$\endgroup$
4
$\begingroup$
var = 22;
list = {8, 13, 19, 35, 40, 45};

Catch[Do[If[list[[i]] > var, Throw[i - 1]], {i, Length[list]}]]

(* 3 *) 
$\endgroup$
4
$\begingroup$
list = {8, 13, 19, 35, 40, 45};
var = 22;

Length@Position[list, _?(# <= var &), All]
First[-1 + FirstPosition[list, n_ /; n > var, 1]]
CountsBy[# > var &][list][False]
DeleteCases[list, _?(# > var &)] // Length
Boole[Thread[# > var &@list]] // Count[0]
Count[1]@UnitStep[var - list]
GatherBy[list, # <= var &] // First // Length
Length@MaximalBy[list, # <= var &]

3

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.