The weekly challenge 387 - Task 1: Rearrange Binary String
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-387/#TASK1 3 # 4 # Task 1: Rearrange Binary String 5 # =============================== 6 # 7 # You are given a binary string string. 8 # 9 # Write a script to re-arrange the given binary string that all occurrences of 10 # “01” are simultaneously replaced with “10” until no occurrences of “01” 11 # exist. Finally return the total steps needed. 12 # 13 ## Example 1 14 ## 15 ## Input: $str = "111000" 16 ## Output: 0 17 ## 18 ## The string already has all 1s on the left and 0s on the right. 19 ## There are no occurrences of "01", so zero step needed. 20 # 21 ## Example 2 22 ## 23 ## Input: $str = "00011" 24 ## Output: 4 25 ## 26 ## Step 1: "00101" 27 ## Step 2: "01010" 28 ## Step 3: "10100" 29 ## Step 4: "11000" 30 # 31 ## Example 3 32 ## 33 ## Input: $str = "01011" 34 ## Output: 3 35 ## 36 ## Step 1: "10101" 37 ## Step 2: "11010" 38 ## Step 3: "11100" 39 # 40 ## Example 4 41 ## 42 ## Input: $str = "010101" 43 ## Output: 3 44 ## 45 ## Step 1: "101010" 46 ## Step 2: "110100" 47 ## Step 3: "111000" 48 # 49 ## Example 5 50 ## 51 ## Input: $str = "00001" 52 ## Output: 4 53 ## 54 ## Step 1: "00010" 55 ## Step 2: "00100" 56 ## Step 3: "01000" 57 ## Step 4: "10000" 58 # 59 ############################################################ 60 ## 61 ## discussion 62 ## 63 ############################################################ 64 # 65 # While the string still contains "01" as a substring, replace 66 # all "01" for "10". Count how many steps were taken. 67 68 use v5.36; 69 70 rearrange_binary_string("111000"); 71 rearrange_binary_string("00011"); 72 rearrange_binary_string("01011"); 73 rearrange_binary_string("010101"); 74 rearrange_binary_string("00001"); 75 76 sub rearrange_binary_string($str) { 77 say "Input: \"$str\""; 78 my $count = 0; 79 while($str =~ m/01/) { 80 $str =~ s/01/10/g; 81 $count++; 82 } 83 say "Output: $count"; 84 }