Pattern decoding

后端 未结 3 1885
情话喂你
情话喂你 2021-01-16 03:02

I need a little help in the following. I have this kind of datafile:

0 0    # <--- Group 1 -- 1 house (0) and 1 room (0)

0 0    # <--- Group 2 -- 2 ho         


        
3条回答
  •  臣服心动
    2021-01-16 03:12

    Perl solution. It converts the input into this format:

    1|0
    2|1 2
    3|2
    4|0 0 0 0
    5|0
    6|0
    

    The first column is group number, in second column there are number of rooms (minus one) of all its houses, sorted. To search for group with two different houses with 2 and 3 rooms, you can just grep '|1 2$', to search for groups with just one house with one room, grep '|0$'

    #!/usr/bin/perl
    #-*- cperl -*-
    
    #use Data::Dumper;
    
    use warnings;
    use strict;
    
    sub report {
        print join ' ', sort {$a <=> $b} @_;
        print "\n";
    }
    
    my $group = 1;
    my @last = (0);
    print '1|';
    my @houses = ();
    while (<>) {
        if (/^$/) { # group end
            report(@houses, $last[1]);
            undef @houses;
            print ++$group, '|';
            @last = (0);
        } else {
            my @tuple = split;
            if ($tuple[0] != $last[0]) { # new house
                push @houses, $last[1];
            }
            @last = @tuple;
        }
    }
    
    report(@houses, $last[1]);
    

    It is based on the fact that for each house, only the last line is important.

提交回复
热议问题