Peter
Peter Campbell Smith

Counting the stars

Weekly challenge 280 — 29 July 2024

Week 280: 29 Jul 2024

Task 1

Task — Twice appearance

You are given a string, $str, containing lowercase English letters only. Write a script to print the first letter that appears twice.

Examples


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

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

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

Analysis

I feel sure there's a neat way to do this with an exciting regular expression, but my solution is to iterate along the letters in the string, $a, and check whether:

$str =~ m|$a.*$a|;

... and if it does, we have the answer.

Try it 

Try running the script with any input:



example: challenge

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2024-07-29
use utf8;     # Week 280 - task 1 - Twice appearance
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

twice_appearance('acbddbca');
twice_appearance('abccd');
twice_appearance('abcdabbb');
twice_appearance('aabcdef');
twice_appearance('abcdeff');
twice_appearance('soporific');

sub twice_appearance {
    
    my ($str, $j, $a);
    $str = shift;
    
    # iterate along string
    for $j (0 .. length($str) - 1) {
        $a = substr($str, $j, 1);
        
        # check if this letter appears twice
        last if $str =~ m|$a.*$a|;
        $a = '';
    }
    printf(qq[\nInput:  \@str = '%s'\n], $str);
    printf(qq[Output: '%s'\n], $a);
}

Output


Input:  @str  = 'acbddbca'
Output: 'a'

Input:  @str = 'abccd'
Output: 'c'

Input:  @str = 'abcdabbb'
Output: 'a'

Input:  @str = 'aabcdef'
Output: 'a'

Input:  @str = 'abcdeff'
Output: 'f'

Input:  @str = 'soporific'
Output: 'o'

 

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