4

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 :)

user64494
  • 26,149
  • 4
  • 27
  • 56
Zigzag1263
  • 63
  • 3

5 Answers5

13

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}}

Anjan Kumar
  • 4,979
  • 1
  • 15
  • 28
2

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}}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
2
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

kglr
  • 394,356
  • 18
  • 477
  • 896
2
Values @ Merge[Flatten] @ MapIndexed[Rule[##] &] @ {5, 7, 5, 5}

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

eldo
  • 67,911
  • 5
  • 60
  • 168
1
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

Syed
  • 52,495
  • 4
  • 30
  • 85