On 6/9/09 Tue Jun 9, 2009 1:24 AM, "Dave Tang" <d.t...@imb.uq.edu.au> scribbled:
> Hello, > > I have a problem, which I have put into an analogy. > > Suppose a parent has 11 children. These children like chocolate. If 9 or > more of the 11 children from the same parent like a particular chocolate, > the parent will like the chocolate. I want to find out what types of > chocolate each parent likes. > > I have a file listing each child's preference of chocolate (which can be >> = 1). There are +45,000 parents, each parent has 11 children and there > are +100,000 different types of chocolate. > > I guess I could parse the file and store the results in something like this > > $listOfParent{$parentOne}{$childOne} = @chocolate; More precisely, $listOfParent{$parentOne}{$childOne} = [ @chocolate ]; since hash elements must be scalars. > ... > $listOfParent{$parentOne}{$childN} = @chocolate; > ... > $listOfParent{$parentN}{$childN} = @chocolate; > > Then > > my %result = (); > foreach my $parent (keys %listOfParent){ foreach my $parent (keys %$listOfParent) { (note: $listOfParent and %listOfParent are two different variables) > my $chocolate = ''; > foreach my $child (keys %{$listOfParent}{$parent}){ foreach my $child ( keys %{$listOfParent->{$parent}} ) { (note: $listOfParent{$parent} is an element of %listOfParent, not an element of the hash referenced by $listOfParent) > foreach ($listOfParent{$parent}{$child}){ foreach ( $listOfParent->{$parent}->{$child} ) { > $chocolate = $_; > if (exists $result{$parent}{$chocolate}){ > $result{$parent}{$chocolate}++; > } else { > $result{$parent}{$chocolate} = '1'; > } You can replace the above 5 lines with just this: $result{$parent}->{$chocolate}++; as Perl will treat an undef value as zero in an increment operation. > } > } > } > > Then go through %result and print out the >=9. Is there a better way of > doing this? If you don't care about the names of the parents and children, you could use an array of arrays instead of a hash-of-hashes to store the preference data. Arrays will use a little less memory storage than hashes, and access will be a little faster. If, however, you already have your hashes created for other purposes, then converting to arrays will probably not help. A little whitespace sprinkled into your source code makes it more readable, which is always a good thing when you are looking for help. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/