perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 301 - Task 1: Largest Number

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-301/#TASK1
 3 #
 4 # Task 1: Largest Number
 5 # ======================
 6 #
 7 # You are given a list of positive integers, @ints.
 8 #
 9 # Write a script to arrange all the elements in the given list such that they
10 # form the largest number and return it.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (20, 3)
15 ## Output: 320
16 #
17 ## Example 2
18 ##
19 ## Input: @ints = (3, 30, 34, 5, 9)
20 ## Output: 9534330
21 #
22 ############################################################
23 ##
24 ## discussion
25 ##
26 ############################################################
27 #
28 # Let's play dumb here, just create all possible permutations,
29 # create the number out of each permutation, then keep the maximum
30 # value.
31 
32 use v5.40;
33 use Algorithm::Combinatorics qw(permutations);
34 
35 largest_number(20, 3);
36 largest_number(3, 30, 34, 5, 9);
37 
38 sub largest_number {
39    my @ints = @_;
40    print "Input: (" . join(", ", @ints) . ")\n";
41    my $max = join("", @ints);
42    my $iter = permutations(\@ints);
43    while(my $p = $iter->next) {
44       my $t = join("", @$p);
45       $max = $t if $t > $max;
46    }
47    print "Output: $max\n";
48 }
49