The weekly challenge 368 - Task 1: Make it Bigger
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-368/#TASK1 3 # 4 # Task 1: Make it Bigger 5 # ====================== 6 # 7 # You are given a given a string number and a character digit. 8 # 9 # Write a script to remove exactly one occurrence of the given character digit 10 # from the given string number, resulting the decimal form is maximised. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "15456", $char = "5" 15 ## Output: "1546" 16 ## 17 ## Removing the second "5" is better because the digit following it (6) is 18 ## greater than 5. In the first case, 5 was followed by 4 (a decrease), 19 ## which makes the resulting number smaller. 20 # 21 ## Example 2 22 ## 23 ## Input: $str = "7332", $char = "3" 24 ## Output: "732" 25 # 26 ## Example 3 27 ## 28 ## Input: $str = "2231", $char = "2" 29 ## Output: "231" 30 ## 31 ## Removing either "2" results in the same string here. By removing a "2", 32 ## we allow the "3" to move up into a higher decimal place. 33 # 34 ## Example 4 35 ## 36 ## Input: $str = "543251", $char = "5" 37 ## Output: "54321" 38 ## 39 ## If we remove the first "5", the number starts with 4. If we remove the 40 ## second "5", the number still starts with 5. Keeping the largest possible 41 ## digit in the highest place value is almost always the priority. 42 # 43 ## Example 5 44 ## 45 ## Input: $str = "1921", $char = "1" 46 ## Output: "921" 47 # 48 ############################################################ 49 ## 50 ## discussion 51 ## 52 ############################################################ 53 # 54 # Simplicity beats complexity: Just create all possible variations of numbers 55 # by removing each possible occurrence of $char and remember the biggest one 56 # of those. 57 58 use v5.36; 59 60 make_it_bigger("15456", "5"); 61 make_it_bigger("7332", "3"); 62 make_it_bigger("2231", "2"); 63 make_it_bigger("543251", "5"); 64 make_it_bigger("1921", "1"); 65 66 sub make_it_bigger($str, $char) { 67 say "Input: \"$str\", \"$char\""; 68 my @chars = split //, $str; 69 my $best = 0; 70 foreach my $index (0..$#chars) { 71 if($chars[$index] eq $char) { 72 my $tmp = join("", @chars[0..$index-1]) . join("", @chars[$index+1..$#chars]); 73 $best = $tmp if $tmp > $best; 74 } 75 } 76 say "Output: $best"; 77 }