From 16aea00999acf68f2adaaa40c35d7b6b0b531b86 Mon Sep 17 00:00:00 2001 From: Jörg Sommrey <28217714+jo-37@users.noreply.github.com> Date: Wed, 29 Mar 2023 17:40:50 +0200 Subject: Challenge 039 task 1 --- challenge-039/jo-37/perl/ch-1.pl | 102 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100755 challenge-039/jo-37/perl/ch-1.pl diff --git a/challenge-039/jo-37/perl/ch-1.pl b/challenge-039/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..5b28a33207 --- /dev/null +++ b/challenge-039/jo-37/perl/ch-1.pl @@ -0,0 +1,102 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use DateTime::Duration; +use DateTime::Format::Strptime; +use List::UtilsBy 'sort_by'; +use experimental 'signatures'; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <in_units('minutes'); + + +### Implementation + +# Converting the guestbook into a list of events. Each event consists +# of a time and the change in number of guests, i.e. the IN-time with an +# increment of one and the OUT-time with a decrement of one. Processing +# the events in timed order reveals the number of guests before and +# after each event. When coming from zero, the switch-on time is +# recorded and when going to zero the swich-on duration is cumulated. + +sub light_duration ($fh) { + my @events; + my $parser = DateTime::Format::Strptime->new(pattern => '%H:%M'); + # Convert guestbook entries to events. + while (<$fh>) { + /^.*?\s+IN:\s*(\d{2}:\d{2})\s+OUT:\s*(\d{2}:\d{2})$/i or next; + push @events, [$parser->parse_datetime($1), 1], + [$parser->parse_datetime($2), -1]; + } + my $light_dur = DateTime::Duration->new; + my $guests = 0; + my $starttime; + # Process events in timed order. + for my $event (sort_by {$_->[0]} @events) { + $starttime = $event->[0] unless $guests; + $guests += $event->[1]; + $light_dur += $event->[0] - $starttime unless $guests; + } + + $light_dur; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + my $guestbook = <in_units('minutes'), 110, 'task 1'; + } + + SKIP: { + skip "tests" unless $tests; + + my $guestbook = <in_units('minutes'), 180, 'two segments'; + } + + done_testing; + exit; +} -- cgit