[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Re: all subsets



In article <Pine.GSO.4.21.0105141926500.357-100000@crusoe.crusoe.net>,
	Jeff Pinyan <jeffp@crusoe.net> writes:
> Wow.  I saw some awesome code today from someone on DALnet #perl:
> 
>   perl -wnle 'split//;for$x(1..1<<@_){print@_[grep $x&1<<$_,0..$#_]}'
> 

they stole it from an ircnet discussion in fact (suo is the author of
that one. I saw him develop it in a number of stages)
(though i think that in fact the original question was in turn stolen from 
the ongoing dalnet discussion)

I ended with (the question was to optimise p,
which should both generate and print print the substrings):

perl -le 'sub p{split//,pop;print@_[grep$j&1<<$_,0..$#_]until$j++>>@_};p("abc")'

Using a different algorithm:

perl -le 'sub p{map$\=~s/.*\n/$&$_$&/g,/./gfor@_;print};p("abc")'

> That prints all subsets of a string (except for "", I believe).  You can
> follow it to see how.
> 
> So I decided I wanted to do that with a regex.
> 
> And I *did*.
> 
>   use re 'eval';
>   $_ = "abcdef";
> 
>   my $pat = join '', map "(?:(.)|.)", 1 .. length;
>   my $str = join '', map "\$$_", 1 .. length;
>   my $print = qq{(?{ print "$str\n" })};
> 
>   /$pat$print(?!)/;
> 
> That was so much fun. :)
> 

We also played with that idea that day. For "real" substrings I came up with:

perl -wle 'sub p{pop=~/.+?(??{print$&})/};p("abc")'

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe