1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-202/#TASK1
 3 #
 4 # You are given an array of integers.
 5 #
 6 # Write a script to print 1 if there are THREE consecutive odds in the given array otherwise print 0.
 7 #
 8 ## Example 1
 9 ##
10 ## Input: @array = (1,5,3,6)
11 ## Output: 1
12 #
13 ## Example 2
14 ##
15 ## Input: @array = (2,6,3,5)
16 ## Output: 0
17 #
18 ## Example 3
19 ##
20 ## Input: @array = (1,2,3,4)
21 ## Output: 0
22 #
23 ## Example 4
24 ##
25 ## Input: @array = (2,3,5,7)
26 ## Output: 1
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # basically we need to walk the array from left to right and
35 # count consecutive odds
36 # The way the task is set this doesn't mean there need to be
37 # EXACT 3 consecutive odds, but AT LEAST 3 consecutive odds,
38 # which makes the solution even easier, as we can short-curcuit
39 # the execution once we found 3 consecutive odds
40 
41 use strict;
42 use warnings;
43 use feature 'say';
44 
45 my @examples = (
46    [1,5,3,6],
47    [2,6,3,5],
48    [1,2,3,4],
49    [2,3,5,7],
50    [1,2,3,4,5,7,9,11]
51 );
52 
53 foreach my $array (@examples) {
54    check_three_consecutive_odds(@$array);
55 }
56 
57 
58 sub check_three_consecutive_odds {
59    my @array = @_;
60    my $consecutive_odds = 0;
61    foreach my $elem (@array) {
62       if($elem % 2) {
63          # odd number
64          $consecutive_odds++;
65          if($consecutive_odds >= 3) {
66             # we have at least 3 consecutive odds, so
67             # we're finished
68             say "(" . join(", ", @array) . ") has output 1";
69             return;
70          }
71       } else {
72          # even number, start over at 0
73          $consecutive_odds = 0;
74       }
75    }
76    # we didn't find 3 consecutive odds anywhere
77    say "(" . join(", ", @array) . ") has output 0";
78 }
79