perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 304 - Task 1: Arrange Binary

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-304/#TASK1
 3 #
 4 # Task 1: Arrange Binary
 5 # ======================
 6 #
 7 # You are given a list of binary digits (0 and 1) and a positive integer, $n.
 8 #
 9 # Write a script to return true if you can re-arrange the list by replacing at
10 # least $n digits with 1 in the given list so that no two consecutive digits
11 # are 1 otherwise return false.
12 #
13 ## Example 1
14 ##
15 ## Input: @digits = (1, 0, 0, 0, 1), $n = 1
16 ## Output: true
17 ##
18 ## Re-arranged list: (1, 0, 1, 0, 1)
19 #
20 ## Example 2
21 ##
22 ## Input: @digits = (1, 0, 0, 0, 1), $n = 2
23 ## Output: false
24 #
25 ############################################################
26 ##
27 ## discussion
28 ##
29 ############################################################
30 #
31 # We can simply turn the list of binary digits into a string.
32 # Then we can:
33 # - change 00 at the beginning of the string into 10
34 # - change 00 at the end of the string into 01
35 # - change the first 000 into 010
36 # If none of these replacements is possible, but we still have more
37 # digits to change from 0 into 1, then we can't change any 0 into 1
38 # without having at least two 1's in a row.
39 
40 use strict;
41 use warnings;
42 
43 arrange_binary(1, 1, 0, 0, 0, 1);
44 arrange_binary(2, 1, 0, 0, 0, 1);
45 
46 sub arrange_binary {
47    my ($n, @digits) = @_;
48    my $str = join("",@digits);
49    while($n >= 1) {
50       $str =~ s/^00/^10/ and $n-- and next;
51       $str =~ s/00$/01/ and $n-- and next;
52       $str =~ s/000/010/ and $n-- and next;
53       return print "Output: false\n";
54    }
55    print "Output: true\n";
56 }