Largest int from concatenated ints

From Rosetta Code
Revision as of 20:27, 3 April 2013 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.

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