Peter’s blog ✴ Week 117 ✴ 14 June 2021

THE WEEKLY CHALLENGE
Missing row, possible paths

The Perl Camel

Task 1

Missing row

You are given text file with rows numbered 1-15 in random order but there is a catch: one row in missing in the file.

11, Line Eleven
1, Line one
9, Line Nine
13, Line Thirteen
2, Line two
6, Line Six
8, Line Eight
10, Line Ten
7, Line Seven
4, Line Four
14, Line Fourteen
3, Line three
15, Line Fifteen
5, Line Five

Write a script to find the missing row number.

Analysis

Lots of ways to do this, but I created a hash with keys 1 to 15 and then read the file in, deleting the relevant hash element. The remaining element is thus the desired missing number.

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-06-14
use utf8;     # Week 117 - task 1 - Missing row
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

missing_row();

sub missing_row {
    
    my (@rows, %missing, $line, $input);
    
    # initialise
    @rows = @_;
    $missing{$_} = 1 for 1 .. 15;
    
    # scan file
    while ($line = <DATA>) {
        $input .= $line;
        delete $missing{$1} if $line =~ m|^(\d+)|;
    }   
    
    # report
    say qq[\nInput:\n$input];
    say qq[Output: ] . $_  for keys %missing;
}

__DATA__
11, Line Eleven
1, Line one
9, Line Nine
13, Line Thirteen
2, Line two
6, Line Six
8, Line Eight
10, Line Ten
7, Line Seven
4, Line Four
14, Line Fourteen
3, Line three
15, Line Fifteen
5, Line Five

24 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:
11, Line Eleven
1, Line one
9, Line Nine
13, Line Thirteen
2, Line two
6, Line Six
8, Line Eight
10, Line Ten
7, Line Seven
4, Line Four
14, Line Fourteen
3, Line three
15, Line Fifteen
5, Line Five

Output: 12

 

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