Peter Campbell Smith

Strings and sequences

Weekly challenge 224 — 3 July 2023

Week 224 - 3 Jul 2023

Task 1

Task — Special notes

You are given two strings, $source and $target. Write a script to find out if using the characters (only once) from source, a target string can be created.


This is rather similar to week 221's Good strings challenge and I have tackled it in a similar way:

  • Create a hash %letters, where $letters{$char} is the frequency with which $char appears in $source.
  • Loop over the characters ($char) in $target. If $letters{$char} > 0 we decrement it and continue to the the next $char,
  • but if $letters{$char} is 0, we can immediately conclude that the result is false.
  • If there are no more letters in $target then the result is true.

Try it 

$source (eg: good):

$target (eg: dog):



use v5.16;    # The Weekly Challenge - 2023-07-03
use utf8;     # Week 224 task 1 - Special notes
use strict;   # Peter Campbell Smith
use warnings; # Blog:

special_notes('abc', 'xyz');
special_notes('scriptinglanguage', 'perl');
special_notes('aabbcc', 'abc');
special_notes('gorge', 'george');
special_notes('fornowisthetimeforallgoodpeopletocometotheaidofthebaby', 'hyperbolicparaboloid');

sub special_notes {
    my ($source, $target, $letter, %letters, $good);
    ($source, $target) = @_;
    # split $source into individual letters
    for $letter (split('', $source)) {
        $letters{$letter} ++;
    # check if $target has any letters not in $source
    $good = 'true';
    for $letter (split('', $target)) {
        if ($letters{$letter}) {
            $letters{$letter} --;
        } else {
            $good = 'false ';
    # show answer
    say qq[\nInput:  \$source = '$source'\n        \$target = '$target'];
    say qq[Output: $good];


Input:  $source = 'abc'
        $target = 'xyz'
Output: false

Input:  $source = 'scriptinglanguage'
        $target = 'perl'
Output: true

Input:  $source = 'aabbcc'
        $target = 'abc'
Output: true

Input:  $source = 'gorge'
        $target = 'george'
Output: false

Input:  $source = 'fornowisthetimeforallgoodpeopletocometotheaidofthebaby'
        $target = 'hyperbolicparaboloid'
Output: true