The smallest greater and
the shortest slice
Weekly challenge 189 — 31 October 2022
Week 189: 31 Oct 2022
You are given an array of characters (a..z) and a target character.
Write a script to find out the smallest character in the given array lexicographically greater than the target character.
Example 1 Input: @array = qw/e m u g/, $target = 'b' Output: e Example 2 Input: @array = qw/d c e f/, $target = 'a' Output: c Example 3 Input: @array = qw/j a r/, $target = 'o' Output: r Example 4 Input: @array = qw/d c a f/, $target = 'a' Output: c Example 5 Input: @array = qw/t g a l/, $target = 'v' Output: v
The best way to approach this seems to me to sort the array, and then look for the first character in the sorted array which is alphabetically after the target character (noting that the target character may occur more than once).
This works for all of Mohammad's examples except the last, where the array is 't, g, a, l' and the target character is 'v'. For that I would say there is no answer, though Mohammad's example says the answer is 'v', which isn't in the array.
#!/usr/bin/perl # Peter Campbell Smith - 2022-10-31 # PWC 189 task 1 use v5.28; use utf8; use warnings; binmode(STDOUT, ':utf8'); my (@tests, $test, @array, $target, $k, @x); @x = split('', 'thequickbrownfoxjumpsoverthelazydog'); @tests = ([qw/e m u g/], 'b', [qw/d c e f/], 'a', [qw/j a r/], 'o', [qw/d c a f/], 'a', [qw/t g a l/], 'v', \@x, 'm'); # loop over tests TEST: while ($tests[0]) { # get inputs @array = @{ shift @tests }; $target = shift @tests; say qq[\nInput: \@array = qw/] . join(' ', @array) . qq[/, \$target = '$target']; # sort the array and get the first character > $target for $k (sort @array) { next unless ($k gt $target); say qq[Output: $k]; next TEST; } say qq[Output: none]; }
Input: @array = qw/e m u g/, $target = 'b' Output: e Input: @array = qw/d c e f/, $target = 'a' Output: c Input: @array = qw/j a r/, $target = 'o' Output: r Input: @array = qw/d c a f/, $target = 'a' Output: c Input: @array = qw/t g a l/, $target = 'v' Output: none Input: @array = qw/t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g/, $target = 'm' Output: n
Any content of this website which has been created by Peter Campbell Smith is in the public domain