#! /usr/bin/perl use strict ; use Algorithm::Permute ; use Data::Dumper ; my @words_raw = qw/ receding hairline bald / ; # First, check for & remove duplicate words in the list. my @words = () ; { my %wc = () ; foreach ( @words_raw ) { push @words, $_ unless $wc{$_}++ ; } } # Cardinality of powerset of @words = 2**n, # where n = |@words|. my $cardinality = 2 ** @words ; my $places = ( log( $cardinality ) / log( 2 ) ) ; # Generate binary templates for all subsets of @words. my $fmt_str = "%0${places}b" ; my @set_templates = map { sprintf $fmt_str, $_ } ( 0 .. $cardinality - 1 ) ; my @power_set = () ; # Replace the template values with the contents of @words. # This will form the power set of @words. foreach ( @set_templates ) { my @flags = split // ; my @temp_set = () ; for ( my $i = 0 ; $i < @flags ; $i++ ) { push @temp_set, $words[$i] if $flags[$i] ; } push @power_set, \@temp_set ; } my @all_iterations = () ; # Drop the empty set from the power set (it's irrelevant # in the context of a search engine. shift @power_set ; # Find the set of possible permutations for each set in # the power set of @words. foreach my $set ( @power_set ) { my $p = new Algorithm::Permute $set ; while ( my @res = $p->next ) { push @all_iterations, join ' ', @res ; } } # Voila! print Dumper( \@all_iterations ) ;

_______________
D a m n D i r t y A p e
Home Node | Email

In reply to Re: Search a database for every permutation of a list of words by DamnDirtyApe
in thread Search a database for every permutation of a list of words by jfrancis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.