Skip to content

Instantly share code, notes, and snippets.

@masak
Created March 12, 2012 10:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/2021108 to your computer and use it in GitHub Desktop.
Save masak/2021108 to your computer and use it in GitHub Desktop.
Find and show all cycles of a permutation
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};
}
}
@japhb
Copy link

japhb commented Mar 12, 2012

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:

    unless @p == grep /^ \d+ $/, @p;

Or even:

    unless @p == @p.grep: /^ \d+ $/;

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.

@masak
Copy link
Author

masak commented Mar 13, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment