Created
March 12, 2012 10:43
-
-
Save masak/2021108 to your computer and use it in GitHub Desktop.
Find and show all cycles of a permutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
sub MAIN(*@p) { | |
die "Arguments need to be integers" | |
unless all(@p) ~~ /^ \d+ $/; | |
die "Arguments need to be 1..N in some order" | |
unless sort(@p) ~~ [1..@p]; | |
say "($_)" for sort *.[0], gather for @p -> $e { | |
next if (state %handled).exists($e); | |
my @cycle = @p[$e - 1], { @p[$_ - 1] } ... $e; | |
@cycle .= rotate(first { @cycle[$_] == @cycle.min }, ^@cycle); | |
take [@cycle]; | |
++«%handled{@cycle}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe line 5 is incorrect (it merely checks if all of the grep results have true values, which is not the intent there). Perhaps:
Or even:
Which makes it more clear that you're asking if the count of @p is the same as the count of the matching subset of @p.