4
$\begingroup$

I want to find a function F to represent the positions of identical elements in a list, which means, for example:

  • F[{5,6,5,7}]={{1,3},{2},{4}}
  • F[{5,6,6,5}]={{1,4},{2,3}}
  • F[{5,7,5,5}]={{1,3,4},{2}}
  • F[{5,6,7,8}]={{1},{2},{3},{4}}
  • F[{5,5,5,5}]={{1,2,3,4}}

etc. Is there any function or implementation?

Moreover, I want to use this into an $\underbrace{n\times n\times\cdots\times n}_m$ Table t[n_,m_] (so the dimension $m$ is also an input of t), such that

  • t[[i_1,...,i_m]]=Subscript[x,F[{i_1,...,i_m}]]

where $1\le i_1,\cdots,i_m\le n$. How can I implement it?

Thanks :)

$\endgroup$
4
  • $\begingroup$ What is a "partition situation of a list"? Your example is unclear. Give an explanation as well as examples. $\endgroup$ Jun 22, 2017 at 0:12
  • $\begingroup$ Ohhh.... position situation (not partition situation)! Got it! $\endgroup$ Jun 22, 2017 at 0:32
  • $\begingroup$ Thanks for your edit! Indeed I don't know how to describe it accurately. $\endgroup$
    – Zigzag1263
    Jun 22, 2017 at 19:58
  • $\begingroup$ The first part of this question is a duplicate of How to efficiently find positions of duplicates? $\endgroup$
    – kglr
    Jul 23, 2017 at 14:28

5 Answers 5

13
$\begingroup$

To get the positions of the same elements in a list you can use PositionIndex

f[x_] := Values@PositionIndex[x]

Test:

f[{5,6,5,7}]
f[{5,6,6,5}]

{{1,3},{2},{4}}

{{1,4},{2,3}}

$\endgroup$
2
  • $\begingroup$ To make it more simple, try f=Values@*PositionIndex $\endgroup$
    – Wjx
    Jun 22, 2017 at 0:29
  • $\begingroup$ @Wjx Thanks for the suggestion. $\endgroup$ Jun 22, 2017 at 0:44
2
$\begingroup$

One possibility:

F[list_]:=Values @ GroupBy[
    AssociationThread[Range@Length@list, list],
    Identity,
    Keys
]

Your examples:

F[{5,6,5,7}]
F[{5,6,6,5}]
F[{5,7,5,5}]
F[{5,6,7,8}]
F[{5,5,5,5}]

{{1, 3}, {2}, {4}}

{{1, 4}, {2, 3}}

{{1, 3, 4}, {2}}

{{1}, {2}, {3}, {4}}

{{1, 2, 3, 4}}

$\endgroup$
0
2
$\begingroup$
ClearAll[f]
f[lst_] := GatherBy[Range @ Length @ lst, lst[[#]]&]
(* or  f[lst_] := Values @ GroupBy[Range @ Length @ lst, lst[[#]]&] *)

mat = {{5, 6, 5, 7}, {5, 6, 6, 5}, {5, 7, 5, 5}, {5, 6, 7, 8}, {5, 5, 5, 5}};
Grid[Prepend[{#, f@#} & /@ mat, {"list", "f[list]"}], Dividers -> All] 

enter image description here

Subscript[x, f@#] & /@ mat

enter image description here

$\endgroup$
2
$\begingroup$
Values @ Merge[Flatten] @ MapIndexed[Rule[##] &] @ {5, 7, 5, 5}

{{1, 3, 4}, {2}}

$\endgroup$
1
$\begingroup$
f[k_List] := 
 Flatten[#, 1] &@Position[k, #] & /@ (k // DeleteDuplicates)

mat = {{5, 6, 5, 7}, {5, 6, 6, 5}, {5, 7, 5, 5}, {5, 6, 7, 8}, {5, 5, 
    5, 5}}; (* borrowed *)

{#, f@#} & /@ mat // Grid[#, Alignment -> Left] &

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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