Perl Weekly Challenge 280: Twice Appearance

These are some answers to the Week 280, Task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on August 4, 2024, at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

Task 1: Twice Appearance

You are given a string, $str, containing lowercase English letters only.

Write a script to print the first letter that appears twice.

Example 1

Input: $str = "acbddbca"
Output: "d"

Example 2

Input: $str = "abccd"
Output: "c"

Example 3

Input: $str = "abcdabbb"
Output: "a"

Twice Appearance in Raku

I first thought about using a regex, but I feared it might be inefficient (for some input strings, there may be a lot of beacktracking). So I decided it would be better to linearly loop over the letters of the input string and return from the subroutine as soon as we've found a repeated letter. We use the %seen hash to store the letter that we have already visited and return when the visited letter is already in the hash.

sub twice ($in) {
    my %seen;
    for $in.comb -> $let {
        return $let if %seen{$let}:exists;
        %seen{$let} = 1;
    }
}

my @tests = "acbddbca", "abccd", "abcdabbb";
for @tests -> $test {
    printf "%-10s => ", $test;
    say twice $test;
}

This program displays the following output:

$ raku ./twice-appaerance.raku
acbddbca   => d
abccd      => c
abcdabbb   => a

Twice Appearance in Perl

This is a port to Perl of the above Raku program.

use strict;
use warnings;
use feature 'say';

sub twice {
    my %seen;
    for my $let (split //, shift) {
        return $let if exists $seen{$let};
        $seen{$let} = 1;
    }
}

my @tests = ("acbddbca", "abccd", "abcdabbb");
for my $test (@tests) {
    printf "%-10s => ", $test;
    say twice $test;
}

This program displays the following output:

$ perl ./twice-appaerance.pl
acbddbca   => d
abccd      => c
abcdabbb   => a

Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on August 11, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.