3
$\begingroup$

Consider a toy list

l = {x[2],x[32],x[43],x[56],x[72]};

I would like to find the position of the first element within this list, for which x[y] is such that y>N where N is a positive integer that I will specify. In case if N is bigger than any label of any x[y], then the result should be zero. So for example:

getPos[l,35]

3

getPos[l,60]

5

getPos[l,80]

0

How can I do that in an efficient manner?

$\endgroup$
  • 2
    $\begingroup$ Maybe I don't understand the question but FirstPosition? $\endgroup$ – unlikely Feb 22 '16 at 23:10
  • $\begingroup$ Beware of things like x[n_] := 3; l = {x[2],x[32],x[43],x[56],x[72]}; $\endgroup$ – Dr. belisarius Feb 22 '16 at 23:13
7
$\begingroup$

For default you can use third arg as in

p[n_] := First@FirstPosition[l, x[k_] /; k >= n, {0}]
$\endgroup$
0
$\begingroup$

Thanks to a comment by unlikely here is the solution:

getPos[l_List,myN_Integer]:=FirstPosition[l,x[qq_Integer] /; qq > myN,{0}][[1]]
$\endgroup$
  • 1
    $\begingroup$ Better to use n than N. $\endgroup$ – bbgodfrey Feb 22 '16 at 23:16
  • $\begingroup$ Fixed it to something that starts with a lower case letter. $\endgroup$ – Kagaratsch Feb 22 '16 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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