http://qs321.pair.com?node_id=1068497


in reply to Hash Uninitialized Values Error

and here's a version that uses recursion and allows duplicate q's:

use strict; use warnings; my @statements = qw( ~c->~f g->b p->f c->~b p->b d->p ); LHCC(parse(@statements)); sub LHCC { my (%all) = @_; my @arguments = sort {@$a <=> @$b} buildArguments(\%all, keys %all +); my $longest = @{$arguments[-1]}; @arguments = map {[join (' => ', @$_), $_->[0], $_->[-1]]} grep {$longest == @$_} @arguments; print " ", join "or ", map {"$_->[0]\n"} @arguments; print "Syllogism(s)\n ", join "and ", map {"$_->[1] => $_->[2]\n"} @arguments; } sub buildArguments { my ($options, @keys) = @_; my @arguments; for my $key (@keys) { next if !exists $options->{$key}; my @qKeys = @{$options->{$key}}; my $remaining = deepCopy($options, $key); my @tails = buildArguments($remaining, @qKeys); push @arguments, [$key, @$_] for @tails; } @arguments = map {[$_]} @keys if ! @arguments; return @arguments; } sub deepCopy { my ($part, @exclude) = @_; my %copy; if ('ARRAY' eq ref $part) { return [map {deepCopy($_)} @$part]; } elsif ('HASH' eq ref $part) { my %copy = map {$_ => deepCopy($part->{$_})} keys %$part; delete $copy{$_} for @exclude; return \%copy; } return $part; } sub parse { my %all; for my $statement (@_) { my ($p, $q) = $statement =~ /(\S+)\s*->\s*(\S+)/; push @{$all{$p}}, $q; $_ = /^~(.*)/ ? $1 : "~$_" for $p, $q; push @{$all{$q}}, $p; } return %all; }

Prints:

d => p => f => c => ~b => ~p => ~d or d => p => b => ~c => ~f => ~p => ~d Syllogism(s) d => ~d and d => ~d

Note that this version has the statement data built in, but replacing @statements with @ARGV allows the command line parsing to be used instead of the test data.

I've switched to using ~ for negation instead of - too.

This version is a little more Perlish than the previous code. Use Perl documentation to look up functions and syntax you've not encountered before. You'll notice I've not bothered to suppress duplicate results - that's left as an exercise for the reader ;).

True laziness is hard work