Largest int from concatenated ints: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Python}}: translation to Perl6)
m (→‎{{header|Perl 6}}: minor rewrite)
Line 15: Line 15:
}
}


say maxnum <1 34 3 98 9 76 45 4>;
say maxnum .[] for
[<1 34 3 98 9 76 45 4>],
say maxnum <54 546 548 60>;</lang>
[<54 546 548 60>];</lang>
{{out}}
{{out}}
<pre>998764543431
<pre>998764543431

Revision as of 21:39, 3 April 2013

Largest int from concatenated ints is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Given a set of integers, the task is to write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this number.

Use the following two sets of integers as tests and show your program output here.

  • {1, 34, 3, 98, 9, 76, 45, 4}
  • {54, 546, 548, 60}

Note: A solution could be to try all combinations and return the best. Another way to solve this is to note that in the best arrangement, for any two adjacent original integers X and Y, the concatenation X followed by Y will be numerically greater than or equal to the concatenation Y followed by X.

Perl 6

Translation of: Python

<lang Perl 6>sub maxnum(@x) {

   [~] sort -> $x, $y { $x~$y <=> $y~$x }, @x

}

say maxnum .[] for [<1 34 3 98 9 76 45 4>], [<54 546 548 60>];</lang>

Output:
998764543431
6054854654

Python

<lang python>try:

   cmp     # Python 2 OK or NameError in Python 3
   def maxnum(x):
       return .join(sorted((str(n) for n in x),
                             cmp=lambda x,y:cmp(int(y+x), int(x+y))))

except NameError:

   # Python 3
   from functools import cmp_to_key
   def cmp(x, y):
       return -1 if x<y else ( 0 if x==y else 1)
   def maxnum(x):
       return .join(sorted((str(n) for n in x),
                             key=cmp_to_key(lambda x,y:cmp(int(y+x), int(x+y)))))

for numbers in [(1, 34, 3, 98, 9, 76, 45, 4), (54, 546, 548, 60):

   print('Numbers: %r\n  Largest integer: %15s' % (numbers, maxnum(numbers)))</lang>
Output:
Numbers: (1, 34, 3, 98, 9, 76, 45, 4)
  Largest integer:    998764543431
Numbers: (54, 546, 548, 60)
  Largest integer:      6054854654

Tcl

<lang tcl>proc intcatsort {nums} {

   lsort -command {apply {{x y} {expr {"$y$x" - "$x$y"}}}} $nums

}</lang> Demonstrating: <lang tcl>foreach collection {

   {1 34 3 98 9 76 45 4}
   {54 546 548 60}

} {

   set sorted [intcatsort $collection]
   puts "\[$collection\] => \[$sorted\]  (concatenated: [join $sorted ""])"

}</lang>

Output:
[1 34 3 98 9 76 45 4] => [9 98 76 45 4 34 3 1]  (concatenated: 998764543431)
[54 546 548 60] => [60 548 546 54]  (concatenated: 6054854654)