perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 374 - Task 2: Largest Same-digits Number

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-374/#TASK2
 3 #
 4 # Task 2: Largest Same-digits Number
 5 # ==================================
 6 #
 7 # You are given a string containing 0-9 digits only.
 8 #
 9 # Write a script to return the largest number with all digits the same in the
10 # given string.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "6777133339"
15 ## Output: 3333
16 #
17 ## Example 2
18 ##
19 ## Input: $str = "1200034"
20 ## Output: 4
21 #
22 ## Example 3
23 ##
24 ## Input: $str = "44221155"
25 ## Output: 55
26 #
27 ## Example 4
28 ##
29 ## Input: $str = "88888"
30 ## Output: 88888
31 #
32 ## Example 5
33 ##
34 ## Input: $str = "11122233"
35 ## Output: 222
36 #
37 ############################################################
38 ##
39 ## discussion
40 ##
41 ############################################################
42 #
43 # We create all substrings of all the same digits, then we sort
44 # this list and return the largest number from it.
45 
46 use v5.36;
47 
48 largest_same_digits_number("6777133339");
49 largest_same_digits_number("1200034");
50 largest_same_digits_number("44221155");
51 largest_same_digits_number("88888");
52 largest_same_digits_number("11122233");
53 
54 sub largest_same_digits_number($str) {
55     say "Input: \"$str\"";
56     my @numbers = ();
57     while(length($str)) {
58         my $c = substr($str,0,1);
59         $str =~ s/^($c*)//;
60         push @numbers, $1;
61     }
62     my @sorted = sort {$b <=> $a} @numbers;
63     say "Output: " . shift @sorted;
64 }