Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: generating permutations

by BrowserUk (Patriarch)
on Mar 29, 2017 at 19:00 UTC ( [id://1186421] : note . print w/replies, xml ) Need Help??


in reply to generating permutations

Here's a brute force conversion of the python code you posted:

#! perl -slw use strict; sub permute { my( $in, $pre ) = ( @_, '' ); if( not length $in ) { print $pre; } else { for my $i ( 0 .. length( $in ) - 1 ) { permute( substr( $in, 0, $i ) . substr( $in, $i+1 ), $pre . substr( $in, $i, 1 ) ); } } } permute( '12345' );;

Ask if anything is unclear.


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.

Replies are listed 'Best First'.
Re^2: generating permutations
by Anonymous Monk on Mar 29, 2017 at 20:36 UTC
    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?

      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.

      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();