aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWalt Mankowski <waltman@pobox.com>2020-08-17 20:03:09 -0400
committerWalt Mankowski <waltman@pobox.com>2020-08-17 20:03:09 -0400
commitfe25e16220e9e1b20432555ee201fc6da121058d (patch)
treec77e8b594f7e9bee398319d25a161ab4238af370
parente77f5b4c2fd92595000fb92dde051534a1ff299b (diff)
downloadperlweeklychallenge-club-fe25e16220e9e1b20432555ee201fc6da121058d.tar.gz
perlweeklychallenge-club-fe25e16220e9e1b20432555ee201fc6da121058d.tar.bz2
perlweeklychallenge-club-fe25e16220e9e1b20432555ee201fc6da121058d.zip
perl solution for challenge 74 task 2
-rw-r--r--challenge-074/walt-mankowski/perl/ch-2.pl60
1 files changed, 60 insertions, 0 deletions
diff --git a/challenge-074/walt-mankowski/perl/ch-2.pl b/challenge-074/walt-mankowski/perl/ch-2.pl
new file mode 100644
index 0000000000..01a73a12cd
--- /dev/null
+++ b/challenge-074/walt-mankowski/perl/ch-2.pl
@@ -0,0 +1,60 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use feature qw(:5.32);
+use experimental qw(signatures);
+
+# TASK #2 › FNR Character
+# Submitted by: Mohammad S Anwar
+#
+# You are given a string $S.
+#
+# Write a script to print the series of first non-repeating character
+# (left -> right) for the given string. Print # if none found.
+#
+# Example 1
+# Input: $S = ‘ababc’
+# Output: ‘abb#c’
+# Pass 1: “a”, the FNR character is ‘a’
+# Pass 2: “ab”, the FNR character is ‘b’
+# Pass 3: “aba”, the FNR character is ‘b’
+# Pass 4: “abab”, no FNR found, hence ‘#’
+# Pass 5: “ababc” the FNR character is ‘c’
+#
+# Example 2
+# Input: $S = ‘xyzzyx’
+# Output: ‘xyzyx#’
+# Pass 1: “x”, the FNR character is “x”
+# Pass 2: “xy”, the FNR character is “y”
+# Pass 3: “xyz”, the FNR character is “z”
+# Pass 4: “xyzz”, the FNR character is “y”
+# Pass 5: “xyzzy”, the FNR character is “x”
+# Pass 6: “xyzzyx”, no FNR found, hence ‘#’
+
+my $s = $ARGV[0];
+my @c = split //, $s;
+my %seen;
+my @nr;
+my @out;
+
+for my $c (@c) {
+ # have we seen $c before?
+ unless (defined $seen{$c}) {
+ # add $c to @nr
+ $seen{$c} = 1;
+ push @nr, $c;
+ } else {
+ # remove $c from @nr
+ for my $i (0..$#nr) {
+ if ($nr[$i] eq $c) {
+ splice @nr, $i, 1;
+ last;
+ }
+ }
+ }
+
+ # now the FNR is either the last element of @nr, or #
+ push @out, @nr ? $nr[-1] : '#';
+}
+
+say join '', @out;