# Return Cases AND Position at the same time

Posted 8 years ago
3524 Views
|
3 Replies
|
3 Total Likes
|
 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 twiceExample: caseAndPosition=CasePosition[{11,12,13,14},x_/;x>12] It would be great if this returned {{13,14},{{3},{4}}}
3 Replies
Sort By:
Posted 8 years ago
 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 8 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 8 years ago
 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}}