29
2
The task
Write a program or function whose input is a list/array X of integers, and whose output is a list of sets of integers Y, such that for each element e in each set Y[i], X[e] = i, and such that the total number of elements in the sets in Y equals the number of elements in X.
(This is basically the same operation as reversing a hashtable/dictionary, except applied to arrays instead.)
Examples
These examples assume 1-based indexing, but you can use 0-based indexing instead if you prefer.
X Y
[4] [{},{},{},{1}]
[1,2,3] [{1},{2},{3}]
[2,2,2] [{},{1,2,3}]
[5,5,6,6] [{},{},{},{},{1,2},{3,4}]
[6,6,5,5] [{},{},{},{},{3,4},{1,2}]
Clarifications
- You may represent a set as a list, if you wish. If you do so, the order of its elements does not matter, but you may not repeat elements.
- You can use any reasonable unambiguous I/O format; for example, you could separate elements of a set with spaces, and the sets themselves with newlines.
- Y should be finitely long, and at least long enough to have all elements of X as array indexes. It may, however, be longer than the maximal element of X (the extra elements would be empty sets).
- The elements of X will all be valid array indices, i.e. non-negative integers if you use 0-based indexing, or positive integers if you use 1-based indexing.
Victory condition
As a code-golf challenge, shorter is better.
Related. In the Sandbox post (now deleted, but you can view it if you have the reputation), we decided it probably wasn't a duplicate, but feel free to vote to close if you disagree. – None – 2017-05-09T22:04:58.957
Does "the order of its elements does not matter" mean that the outputs of
[5,5,6,6]
and[6,6,5,5]
can be identical? – Leaky Nun – 2017-05-10T01:44:34.4731@LeakyNun The order of the elements of the sets in the output list doesn't matter. So
[5,5,6,6]
and[6,6,5,5]
can't have identical output, but the output for[5,5,6,6]
could also have been, e.g.,[{},{},{},{},{2,1},{4,3}]
. – ngenisis – 2017-05-10T02:51:50.660Is there an assumable max value of an index in X? Also can empty sets have a 0 in them instead of being actually empty? For example would
[{0},{0},{0},{0},{1,2},{3,4}]
be valid output for[5,5,6,6]
? – Skidsdev – 2017-05-10T09:45:11.130@Mayube: No to the first answer (although if you're using a language which has limited range on integers, you can write the program as though integers could be unboundedly large, and not worry about it breaking if someone gives you an out-of-range integer as input). With respect to the second question, that's an unambiguous (if weird) syntax when you're using 1-based indexing, so yes in that case (obviously, no if you're using 0-based indexing because then the 0 would mean someting else.) – None – 2017-05-11T11:33:14.213