Mathematica Asked on June 4, 2021
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.
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} *)
Correct answer by flinty on June 4, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP