Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: generating permutations

by Anonymous Monk
on Mar 29, 2017 at 20:36 UTC ( [id://1186434] : note . print w/replies, xml ) Need Help??


in reply to Re: generating permutations
in thread generating permutations

Thanks, again. With a few extra print statements, I am able to see exactly what it is doing.

A quick (I hope) follow up. How would I do a more general list - say all the permutations of (apple, banana, orange), or numbers that go into double digits?

Replies are listed 'Best First'.
Re^3: generating permutations
by BrowserUk (Patriarch) on Mar 29, 2017 at 21:21 UTC

    Try this. It's a re-casting of the Python algorithm to operate on arrays:

    #! perl -slw use strict; sub permute3 { my( $in, $pre ) = ( @_, [] ); return print join '-', @$pre unless @$in; permute3( [ @{ $in }[ 0 .. $_-1, $_+1 .. $#$in ] ], [ @$pre, $in->[ $_ ] ] ) for 0 .. $#$in; } permute3( [ qw[ apple banana orange ] ] );; __END__ C:\test>junk36 apple-banana-orange apple-orange-banana banana-apple-orange banana-orange-apple orange-apple-banana orange-banana-apple

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re^3: generating permutations
by tybalt89 (Monsignor) on Mar 31, 2017 at 22:35 UTC

    Here's a version that uses a separate array to mark when a item is used instead of building and destroying anon arrays.

    #!/usr/bin/perl # http://perlmonks.org/?node_id=1186402 use strict; use warnings; my @items = qw( apple banana orange ); my @used; sub permute { @_ == @items and return print "@_\n"; $used[$_]++ || permute(@_, $items[$_]), $used[$_]-- for 0 .. $#items +; } permute();