0
$\begingroup$

I want following imaginary feature : PositionOf

Example1)

In[1]  Cases[{3,5,1,7,2,8,9,7,5,6}, x_ /; x > 4 :> PositionOf[x]]

Out[1]  {2,4,6,7,8,9,10}

Above code extracts elements bigger than 4 (x_ /; x > 4),
{5,7,8,9,7,5,6}
and produce their position :> PositionOf[x]:
{2,4,6,7,8,9,10}

Example2)

In[2]  Cases[{3,5,1,7,2,8,9,7,5,6}, x_ /; x + PositionOf[x] == 14]

Out[2]  {8,5}

Above code extracts every element x such that x + its position is 14 (x_ /;x + PositionOf[x] == 14) In the list, 8 is 6th, and 5 is 9th. 8+6 = 5+9 = 14. So the output is {8,5}.

There is a code that works for example 1 :

Flatten[Position[{3,5,1,7,2,8,9,7,5,6}, x_ /; x > 4 ]]

also for example 2 by indexing method (using Range,Length,Transpose,Part.)

But I am curious that PositionOf[x] like feature is ever possible. If there is no such thing, a slight variation is also welcomed.

$\endgroup$
1
  • $\begingroup$ Position already has this capability for your first example: Flatten[Position[{3, 5, 1, 7, 2, 8, 9, 7, 5, 6}, x_ /; x > 4]] returns {2,4,6,7,8,9,10} $\endgroup$ – flinty Apr 13 at 15:31
3
$\begingroup$

Example 1 already addressed in the comments as position can already handle this.

Example 2 is addressed below:

With[{list = {3, 5, 1, 7, 2, 8, 9, 7, 5, 6}},
  Select[14 == Plus @@ # &][Thread[{list, Range@Length@list}]]
 ][[All, 1]]
(* returns : {8, 5} *)

Another way using ResourceFunction["PositionCases"]:

PositionCases = ResourceFunction["PositionCases"];
PositionCases[{3, 5, 1, 7, 2, 8, 9, 7, 5, 6}, 
 PositionPattern[pos_, x_] /; pos != {} && First[pos] + x == 14]
(* returns : {8, 5} *)
$\endgroup$
1
  • $\begingroup$ Source notebook for PositionCases in resource center, is beyond my level. Anyway thank you. $\endgroup$ – imida k Apr 14 at 9:16

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.