2
\$\begingroup\$

This question already has an answer here:

I'm new here. I tried seeing if this challenge was introduced before. Found a close call one counting the number of cycles, but didn;t find one for listing them. So I'm writing this one. Sorry if I'm repeating...

Anyway, I'm looking for the shortest function to return all close cycles in a shuffled list of indices. For good order's sake let's start counting with 0 as the first index. A cycle uses the value in a certain position as the index for its next one. Repeating this process creates a closed cycle. Exhausting all indices in the original list eventually organize it into few such close chains. And this organization is what we're after here.

In this challenge the order between chains is not important. The order within a chain should be kept as in the original, but it can be cyclically shifted (i.e. [5, 1, 4], [1, 4, 5] and [4, 5, 1] are all equivalent).

The input list is guaranteed to contain all the integers from 0 to n and only them.

This is code-golf - i.e. looking for the most compact implementation.

Few examples:

[4, 8, 0, 6, 7, 5, 2, 3, 9, 1] --> [[0, 4, 7, 3, 6, 2], [1, 8, 9], [5]]

[8, 1, 4, 2, 9, 6, 7, 5, 0, 3] --> [[0, 8], [1], [2, 4, 9, 3], [5, 6, 7]]

[3, 4, 0, 1, 2, 9, 5, 8, 6, 7] --> [[0, 3, 1, 4, 2], [5, 9, 7, 8, 6]]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] --> [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0] -->  [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] --> [[0, 9], [1, 8], [2, 7], [3, 6], [4, 5]]
\$\endgroup\$

marked as duplicate by Nathan Merrill, Blue, FryAmTheEggman, Leaky Nun, Suever Jul 18 '16 at 19:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • \$\begingroup\$ I feel like this is a duplicate, but even if it isn't, nice first challenge! \$\endgroup\$ – Nathan Merrill Jul 18 '16 at 19:05

Browse other questions tagged or ask your own question.