perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 325 - Task 1: Consecutive One

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-325/#TASK1
 3 #
 4 # Task 1: Consecutive One
 5 # =======================
 6 #
 7 # You are given a binary array containing only 0 or/and 1.
 8 #
 9 # Write a script to find out the maximum consecutive 1 in the given array.
10 #
11 ## Example 1
12 ##
13 ## Input: @binary = (0, 1, 1, 0, 1, 1, 1)
14 ## Output: 3
15 #
16 #
17 ## Example 2
18 ##
19 ## Input: @binary = (0, 0, 0, 0)
20 ## Output: 0
21 #
22 #
23 ## Example 3
24 ##
25 ## Input: @binary = (1, 0, 1, 0, 1, 1)
26 ## Output: 2
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # We need to keep track of the current consecutive number of 1s and
35 # of the longest streak so far in two variables. For each element
36 # we need to check whether it's a one or zero. In the latter case, we
37 # reset $current to 0, otherwise we add one to $current and if $current
38 # is bigger than the longest streak, we set that variable as well.
39 #
40 
41 use v5.36;
42 
43 consecutive_one(0, 1, 1, 0, 1, 1, 1);
44 consecutive_one(0, 0, 0, 0);
45 consecutive_one(1, 0, 1, 0, 1, 1);
46 
47 sub consecutive_one( @binary ) {
48     say "binary = (" . join(", ", @binary) . ")";
49     my $longest = 0;
50     my $current = 0;
51     foreach my $elem (@binary) {
52         if($elem) {
53             $current++;
54             if($current > $longest) {
55                 $longest = $current;
56             }
57         } else {
58             $current = 0;
59         }
60     }
61     say "Output: $longest";
62 }
63