Peter’s blog ✴ Week 180 ✴ 29 August 2022

THE WEEKLY CHALLENGE
Uniquely trimmed

The Perl Camel

Task 1

First unique character

You are given a string, $s. Write a script to find out the first unique character in the given string and print its index (0-based).

Examples


Example 1
Input: $s = "Perl Weekly Challenge"
Output: 0 as 'P' is the first unique character

Example 2
Input: $s = "Long Live Perl"
Output: 1 as 'o' is the first unique character

Analysis

I had high hopes for:

$s =~ m|^(.*?)(.)([^\2]*)$|
which says:
  • zero or more characters, followed by
  • one character (the answer), followed by
  • any number of characters that aren't the answer.

But it doesn't work, and I'm not sure why.

So I settled for cycling through the characters and searching for a further occurrence of each; when none is found, we have the answer.

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:



example: spam, spam, spam or spam

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2022-08-29
use utf8;     # Week 180 - task 1 - First unique character
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

first_unique_character('Perl Weekly Challenge');
first_unique_character('Long Live Perl');
first_unique_character('Cheer Cheer Cheer');

sub first_unique_character {
    
    my ($str, $j, $char);
    
    $str = shift;
    say qq[\nInput:  \$s = '$str'];
    
    # loop over characters
    for $j (0 .. length($str) - 1) {
        $char = substr($str, $j, 1);
        
        # no good if it recurs
        next if $str =~ m|^(.*)$char.*$char.*$|;
        
        # found the answer
        say qq[Output: $j (character = '$char')];
        return;
    }
    
    # no non-repeating character
    say qq[Output: -1];
}

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

Output from script


Input:  $s = 'Perl Weekly Challenge'
Output: 0 (character = 'P')

Input:  $s = 'Long Live Perl'
Output: 1 (character = 'o')

Input:  $s = 'Cheer Cheer Cheer'
Output: -1

 

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