in reply to Search a database for every permutation of a list of words
#! /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 ) ;
|
|---|