perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 350 - Task 1: Good Substrings

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-350/#TASK1
 3 #
 4 # Task 1: Good Substrings
 5 # =======================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script to return the number of good substrings of length three in the
10 # given string.
11 #
12 ### A string is good if there are no repeated characters.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "abcaefg"
17 ## Output: 5
18 ##
19 ## Good substrings of length 3: abc, bca, cae, aef and efg
20 #
21 #
22 ## Example 2
23 ##
24 ## Input: $str = "xyzzabc"
25 ## Output: 3
26 ##
27 ## Good substrings of length 3: "xyz", "zab" and "abc"
28 #
29 #
30 ## Example 3
31 ##
32 ## Input: $str = "aababc"
33 ## Output: 1
34 ##
35 ## Good substrings of length 3: "abc"
36 #
37 #
38 ## Example 4
39 ##
40 ## Input: $str = "qwerty"
41 ## Output: 4
42 ##
43 ## Good substrings of length 3: "qwe", "wer", "ert" and "rty"
44 #
45 #
46 ## Example 5
47 ##
48 ## Input: $str = "zzzaaa"
49 ## Output: 0
50 #
51 ############################################################
52 ##
53 ## discussion
54 ##
55 ############################################################
56 #
57 # We check all substrings of length 3 in the string and count the
58 # good substrings, which we return in the end.
59 
60 use v5.36;
61 
62 good_substrings("abcaefg");
63 good_substrings("xyzzabc");
64 good_substrings("aababc");
65 good_substrings("qwerty");
66 good_substrings("zzzaaa");
67 
68 sub good_substrings($str) {
69     say "Input: \"$str\"";
70     my $good = 0;
71     foreach my $index (0..length($str)-3) {
72         $good++ if is_good(substr($str,$index,3));
73     }
74     say "Output: $good";
75 }
76 
77 sub is_good($str) {
78     my @chars = split //,$str;
79     return 0 if $chars[0] eq $chars[1] or $chars[1] eq $chars[2] or $chars[0] eq $chars[2];
80     return 1;
81 }