aboutsummaryrefslogtreecommitdiff
path: root/challenge-180
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-08-29 14:09:24 +0200
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-09-02 17:41:42 +0200
commit4b1eae555995a19f8eca3313f6a5657fc53b2952 (patch)
treea8c7c9c65308abb576613a9a9c75d08010e9d52a /challenge-180
parent08e116e40ba3cff85f73e507cbf7895e5ab9f755 (diff)
downloadperlweeklychallenge-club-4b1eae555995a19f8eca3313f6a5657fc53b2952.tar.gz
perlweeklychallenge-club-4b1eae555995a19f8eca3313f6a5657fc53b2952.tar.bz2
perlweeklychallenge-club-4b1eae555995a19f8eca3313f6a5657fc53b2952.zip
Solution to task 1
Diffstat (limited to 'challenge-180')
-rwxr-xr-xchallenge-180/jo-37/perl/ch-1.pl64
1 files changed, 64 insertions, 0 deletions
diff --git a/challenge-180/jo-37/perl/ch-1.pl b/challenge-180/jo-37/perl/ch-1.pl
new file mode 100755
index 0000000000..7187cfbfbb
--- /dev/null
+++ b/challenge-180/jo-37/perl/ch-1.pl
@@ -0,0 +1,64 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use experimental 'signatures';
+
+our ($tests, $examples);
+
+run_tests() if $tests || $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [-tests] [STR]
+
+-examples
+ run the examples from the challenge
+
+-tests
+ run some tests
+
+STR
+ string to be examined
+
+EOS
+
+
+### Input and Output
+
+say first_uniq(shift);
+
+
+### Implementation
+
+sub first_uniq ($str) {
+ # Count each character's occurrences.
+ my %cnt;
+ $cnt{$_}++ for split //, $str;
+ # Return the index of the first unique character.
+ $cnt{substr $str, $_, 1} == 1 && return $_ for 0 .. length($str) - 1;
+ # If there is no unique character in the string:
+ -1;
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+
+ is first_uniq('Perl Weekly Challenge'), 0, 'example 1';
+ is first_uniq('Long Live Perl'), 1, 'example 2';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+
+ is first_uniq('aa'), -1, 'no unique character';
+ is first_uniq(''), -1, 'empty string';
+ is first_uniq('aa0'), 2, 'find zero';
+ }
+
+ done_testing;
+ exit;
+}