The weekly challenge 217 - Task 2: Max Number
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-217/#TASK2 3 # 4 # Task 2: Max Number 5 # ================== 6 # 7 # You are given a list of positive integers. 8 # 9 # Write a script to concatenate the integers to form the highest possible value. 10 # 11 ## Example 1: 12 ## 13 ## Input: @list = (1, 23) 14 ## Output: 231 15 # 16 ## Example 2: 17 ## 18 ## Input: @list = (10, 3, 2) 19 ## Output: 3210 20 # 21 ## Example 3: 22 ## 23 ## Input: @list = (31, 2, 4, 10) 24 ## Output: 431210 25 # 26 ## Example 4: 27 ## 28 ## Input: @list = (5, 11, 4, 1, 2) 29 ## Output: 542111 30 # 31 ## Example 5: 32 ## 33 ## Input: @list = (1, 10) 34 ## Output: 110 35 # 36 ############################################################ 37 ## 38 ## discussion 39 ## 40 ############################################################ 41 # 42 # We simply create all possible permutations of the input list. 43 # Each permutation represents one possible value, so we just 44 # pick the highest value. 45 46 use strict; 47 use warnings; 48 49 max_number(1, 23); 50 max_number(10, 3, 2); 51 max_number(31, 2, 4, 10); 52 max_number(5, 11, 4, 1, 2); 53 max_number(1, 10); 54 55 sub max_number { 56 my @list = @_; 57 print "Input: (" . join(", ", @list) . ")\n"; 58 print "Output: " . get_max(@list) . "\n"; 59 } 60 61 sub get_max { 62 my @list = @_; 63 return "" unless @list; 64 my $max = 0; 65 foreach my $index (0..$#list) { 66 my @rest = (); 67 @rest = @list[0..$index-1] if $index > 0; 68 push @rest, @list[$index+1..$#list] if $index < $#list; 69 my $current = $list[$index] . get_max(@rest); 70 $max = $current if $current > $max; 71 } 72 return $max; 73 } 74