Richard Lee wrote:
> " It should include '1 2 3' because '1 2 3', '1 2 4', '1 2 7', '1 2 8',
> '1 2 9' = '1 2'(the common number from the list) + anynumber. "
> as any of them contains 1 and 2 and I don't understand why '1 2 3' was
> picked.
My interpretation: Because it's the first element of those with 1 and 2
in them. In other words, the order in which the elements appear in
@datas is important for the result.
> Also can someone explain to me in detail what Gunnar Hjalmarsson's
> solution is doing?
>
> ------------ code of Gunnar's ----------------
>
> my $numbers_wanted = 2;
> my ( @datawanted, @numbers );
>
> LOOP: foreach ( @datas ) {
> my @test = split;
> foreach my $num ( @numbers ) {
> next LOOP if grep( $num->{$_}, @test ) >= $numbers_wanted;
> }
> push @datawanted, $_;
> push @numbers, { map { $_ => 1 } @test };
> }
>
> print "$_\n" for @datawanted;
It iterates over @datas and stores some of the elements in @datawanted
based on (my interpretation of) the OP's criteria. There is nothing
mysterious with the code; everything can be looked up in the Perl docs.
@numbers is a help variable where the numbers in previously stored
elements are made conveniently accessible for lookups. The expression
map { $_ => 1 } @test
creates a key/value list where the elements of @test are the keys (see
"perldoc -f map"), and
push @numbers, { map { $_ => 1 } @test };
makes the list an anonymous hash and adds a reference to that hash to
@numbers.
grep() is used in scalar context to compare the elements with previously
stored elements and test against the OP's criteria.
perldoc -f grep
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
Thread Previous
|
Thread Next