Peter’s blog ✴ Week 181 ✴ 5 September 2022

THE WEEKLY CHALLENGE
Sorted text and hot days

The Perl Camel

Task 2

Hot day

You are given file with daily temperature record in random order. Write a script to find out the days that were hotter than the previous day.

Examples

Example
Input File: (temperature.txt)
2022-08-01, 20
2022-08-09, 10
2022-08-03, 19
2022-08-06, 24
2022-08-05, 22
2022-08-10, 28
2022-08-07, 20
2022-08-04, 18
2022-08-08, 21
2022-08-02, 25
Output:
2022-08-02
2022-08-05
2022-08-06
2022-08-08
2022-08-10

Analysis

The obvious way to do this is to read the the data into an array such that $input{$date} = $temp, and then with for $date (sort keys @input) we can print the desired output in a single line of code.

Perl Weekly’s review

from PW issue 581

Short and sweet, logical reasoning. Nice attempt.

This review may cover either or both challenges for this week.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:


Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-09-05
# PWC 181 task 2

use v5.28;
use utf8;
use warnings;

my ($line, %input, $day, $yesterday);

# read the data into %input such that $input{date} = temp
while ($line = <DATA>) {
    $input{$1} = $2 if $line =~ m|(.+), (\d+)|;
}

# check each day against the previous one
$yesterday = 99;
for $day (sort keys %input) {
    say qq[$day was hotter ($input{$day}) than the previous day ($yesterday)] if $input{$day} > $yesterday;
    $yesterday = $input{$day};
}

__DATA__
2022-08-01, 20
2022-08-09, 10
2022-08-03, 19
2022-08-06, 24
2022-08-05, 22
2022-08-10, 28
2022-08-07, 20
2022-08-04, 18
2022-08-08, 21
2022-08-02, 25

21 lines of code

Output from script


2022-08-02 was hotter (25) than the previous day (20)
2022-08-05 was hotter (22) than the previous day (18)
2022-08-06 was hotter (24) than the previous day (22)
2022-08-08 was hotter (21) than the previous day (20)
2022-08-10 was hotter (28) than the previous day (10)

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain