From a7f00d154e8da2292e87aaf2dcb08a32b55c135f Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Wed, 4 Mar 2020 21:57:29 +0100 Subject: Use enum instead of bitmask literals, remove the nested hash Singles can be represented by another bitmask value if we ignore it when checking for left and right boundaries. --- challenge-050/e-choroba/perl/ch-1.pl | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/challenge-050/e-choroba/perl/ch-1.pl b/challenge-050/e-choroba/perl/ch-1.pl index ccd05e335b..436d44f96c 100755 --- a/challenge-050/e-choroba/perl/ch-1.pl +++ b/challenge-050/e-choroba/perl/ch-1.pl @@ -4,27 +4,27 @@ use strict; { package MyInterval; + use enum 'BITMASK:' => qw( LEFT RIGHT SINGLE ); + sub new { bless {}, shift } sub insert { my ($self, $from, $to) = @_; - $self->{$from} ||= 0, undef $self->{same}{$from}, return - if $from == $to; - $self->{$from} |= 1; - $self->{$_} = 3 for $from + 1 .. $to - 1; - $self->{$to} |= 2; + $self->{$from} |= SINGLE, return if $from == $to; + $self->{$from} |= LEFT; + $self->{$_} = LEFT | RIGHT for $from + 1 .. $to - 1; + $self->{$to} |= RIGHT; } sub out { my ($self) = @_; my @r; - my $same = $self->{same}; - for my $k (sort { $a <=> $b } grep $_ ne 'same', keys %$self) { - if ($self->{$k} == 1) { + for my $k (sort { $a <=> $b } grep 'same' ne $_, keys %$self) { + if (($self->{$k} & (LEFT | RIGHT)) == LEFT) { push @r, [$k]; - } elsif ($self->{$k} == 2) { + } elsif (($self->{$k} & (LEFT | RIGHT)) == RIGHT) { push @{ $r[-1] }, $k - } elsif ((! @r || 1 != @{ $r[-1] }) && exists $same->{$k}) { + } elsif ((! @r || 1 != @{ $r[-1] }) && ($self->{$k} == SINGLE)) { push @r, [$k, $k]; } } -- cgit