Message Boards Message Boards

1
|
3858 Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Return Cases AND Position at the same time

This has always bugged me about the WL. You often want the Case and Position of some criteria. It's always a two step process. Am I missing something? I could write a function to do both, but that seems like double the overhead since it'll still have to loop through the criteria twice

Example:

caseAndPosition=CasePosition[{11,12,13,14},x_/;x>12]

It would be great if this returned {{13,14},{{3},{4}}}

POSTED BY: Eric Smith
3 Replies

Thanks guys, I'll keep these in mind next time I'm worried about speed. It seems like a useful option to have, and I was wondering if I had missed anything with the built-in functions. MapIndex is probably the closest built-in function. Simply getting the part though as David suggested is also straightforward. Just trying to decrease key strokes. Thanks again.

POSTED BY: Eric Smith
Posted 9 years ago

This also works:

In[1]:= casePosition[list_, pat_] := Module[{positions, elements},
  positions = Position[list, pat];
  elements = Part[list, #] & /@ positions;
  {elements, positions}
  ]

In[2]:= (* elements and their indices occupy the same level in the \
returned structure *)
casePosition[{11, 12, 13, 14}, x_ /; x > 12]

Out[2]= {{{13}, {14}}, {{3}, {4}}}

In[3]:= (* duplicated elements are reported separately *)
casePosition[{11, 13, 12, 13, 14}, x_ /; x > 12]

Out[3]= {{{13}, {13}, {14}}, {{2}, {4}, {5}}}

In[4]:= (* it could of course return exactly what you prescribed *)
casePosition[list_, pat_] := Module[{positions, elements},
  positions = Position[list, pat];
  elements = Part[list, #] & /@ positions;
  {elements // Flatten, positions}
  ]

In[5]:= (* elements and their indices occupy the same level in the \
returned structure *)
casePosition[{11, 12, 13, 14}, x_ /; x > 12]

Out[5]= {{13, 14}, {{3}, {4}}}

In[6]:= (* duplicated elements are reported separately *)
casePosition[{11, 13, 12, 13, 14}, x_ /; x > 12]

Out[6]= {{13, 13, 14}, {{2}, {4}, {5}}}
POSTED BY: David Keith

I think it could be done with MapIndexed. For example:

In[38]:= g[a_, {b_}] := If[a > 12, {a, b}, Nothing]

In[39]:= MapIndexed[g, {11, 12, 13, 14}]

Out[39]= {{13, 3}, {14, 4}}
POSTED BY: Frank Kampas
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract