3
$\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$
  • $\begingroup$ What is a "partition situation of a list"? Your example is unclear. Give an explanation as well as examples. $\endgroup$ – David G. Stork Jun 22 '17 at 0:12
  • $\begingroup$ Ohhh.... position situation (not partition situation)! Got it! $\endgroup$ – David G. Stork Jun 22 '17 at 0:32
  • $\begingroup$ Thanks for your edit! Indeed I don't know how to describe it accurately. $\endgroup$ – Zigzag1263 Jun 22 '17 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 '17 at 14:28
7
$\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}}

| improve this answer | |
$\endgroup$
  • $\begingroup$ To make it more simple, try f=Values@*PositionIndex $\endgroup$ – Wjx Jun 22 '17 at 0:29
  • $\begingroup$ @Wjx Thanks for the suggestion. $\endgroup$ – Anjan Kumar Jun 22 '17 at 0:44
1
$\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}}

| improve this answer | |
$\endgroup$
0
$\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

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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