perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 282 - Task 1: Good Integer

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-282/#TASK1
 3 #
 4 # Task 1: Good Integer
 5 # ====================
 6 #
 7 # You are given a positive integer, $int, having 3 or more digits.
 8 #
 9 # Write a script to return the Good Integer in the given integer or -1 if none found.
10 #
11 ### A good integer is exactly three consecutive matching digits.
12 #
13 ## Example 1
14 ##
15 ## Input: $int = 12344456
16 ## Output: "444"
17 #
18 ## Example 2
19 ##
20 ## Input: $int = 1233334
21 ## Output: -1
22 #
23 ## Example 3
24 ##
25 ## Input: $int = 10020003
26 ## Output: "000"
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # We just walk the digits, taking note of the previous digit
35 # and how often it occured already. If the current digit is
36 # different from the previous one and we have seen the
37 # previous digit exactly 3 times, we return that digit
38 # 3 times. If we reached the end of $int, we just have to check
39 # whether the last digit was seen 3 times as well.
40 
41 use strict;
42 use warnings;
43 
44 good_integer(12344456);
45 good_integer(1233334);
46 good_integer(10020003);
47 
48 sub good_integer {
49    my $int = shift;
50    print "Input: $int\n";
51    my $prev_digit = "";
52    my $seen = 0;
53    foreach my $digit (split //, $int) {
54       if($prev_digit eq $digit) {
55          $seen++;
56       } elsif ($seen == 3) {
57          return print "Output: $prev_digit$prev_digit$prev_digit\n";
58       } else {
59          $prev_digit = $digit;
60          $seen = 1;
61       }
62    }
63    if($seen == 3) {
64       return print "Output: $prev_digit$prev_digit$prev_digit\n";
65    }
66    print "Output: -1\n";
67 }