Largest int from concatenated ints: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 156: Line 156:


[[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each do |c|
[[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each do |c|
p c # prints nicer in Ruby 1.8
puts "#{c}", icsort(c).join
puts icsort(c).join
end</lang>
end</lang>



Revision as of 20:37, 4 April 2013

Task
Largest int from concatenated ints
You are encouraged to solve this task according to the task description, using any language you may know.

Given a set of positive 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 integer.

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}
Possible algorithms
  1. A solution could be found by trying all combinations and return the best.
  2. 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.
  3. Yet another way to solve this is to pad ints to the same size by repeating the digits then sort using these repeated ints as a sort key.

Cf:

C

<lang C>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>

int catcmp(const void *a, const void *b) { char ab[32], ba[32]; sprintf(ab, "%d%d", *(int*)a, *(int*)b); sprintf(ba, "%d%d", *(int*)b, *(int*)a); return strcmp(ba, ab); }

void maxcat(int *a, int len) { int i; qsort(a, len, sizeof(int), catcmp); for (i = 0; i < len; i++) printf("%d", a[i]); putchar('\n'); }

int main(void) { int x[] = {1, 34, 3, 98, 76, 45, 4}; int y[] = {54, 546, 548, 60};

maxcat(x, sizeof(x)/sizeof(x[0])); maxcat(y, sizeof(y)/sizeof(y[0]));

return 0; }</lang>

Output:
998764543431
6054854654

Clojure

<lang Clojure>(defn maxcat [coll]

 (read-string
   (apply str
          (sort (fn [x y]
                  (apply compare
                         (map read-string [(str y x) (str x y)])))
                coll))))

(prn (map maxcat [[1 34 3 98 9 76 45 4] [54 546 548 60]]))</lang>

Output:
(998764543431 6054854654)

Haskell

<lang Haskell>import Data.List (sortBy) import Data.Ord (comparing)

main = print (map maxcat [[1,34,3,98,9,76,45,4], [54,546,548,60]] :: [Integer])

   where sorted = sortBy (flip $ comparing $ cycle)
         maxcat = read . concat . sorted . map show</lang>
Output:
[998764543431,6054854654]

J

Solution: <lang j>maxlen=: [: >./ #&> maxnum=: (0 ". ;)@(\: maxlen $&> ])@(8!:0)</lang> Usage: <lang j> maxnum&> 1 34 3 98 9 76 45 4 ; 54 546 548 60 998764543431 6054854654</lang>

Perl 6

<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

Python: Sort on comparison of concatenated ints method

This also shows one of the few times where cmp= is better than key= on sorted()

<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
   cmp = lambda x,y: (x > y) - (x < y)
   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

Python: Compare repeated string method

<lang python>def maxnumx(x):

   maxlen = len(str(max(x)))
   return .join(sorted((str(n) for n in x), reverse=True,
                         key=lambda i: i*(maxlen // len(i) + 1)))

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 as above.

Python: Try all permutations method

<lang python>from itertools import permutations def maxnumx(x):

   return max(int(.join(n) for n in permutations(str(i) for i in x)))

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 as above.

Ruby

Translation of: Tcl

<lang Ruby>def icsort nums

 nums.sort { |x, y| "#{y}#{x}".to_i <=> "#{x}#{y}".to_i }

end

[[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each do |c|

 p c # prints nicer in Ruby 1.8
 puts icsort(c).join

end</lang>

Output:
[54, 546, 548, 60]
6054854654
[1, 34, 3, 98, 9, 76, 45, 4]
998764543431

Run BASIC

<lang runbasic>a1$ = "1, 34, 3, 98, 9, 76, 45, 4" a2$ = "54,546,548,60"

print "Max Num ";a1$;" = ";maxNum$(a1$) print "Max Num ";a2$;" = ";maxNum$(a2$)

function maxNum$(a1$) while word$(a1$,i+1,",") <> ""

i = i + 1
a$(i) = trim$(word$(a1$,i,","))

wend

s = 1 while s = 1

s = 0
for j = 1 to i -1
 if a$(j)+a$(j+1) < a$(j+1)+a$(j) then
  h$      = a$(j)
  a$(j)   = a$(j+1)
  a$(j+1) = h$
  s       = 1
 end if
next j

wend

for j = 1 to i

maxNum$ = maxNum$ ; a$(j)

next j

end function</lang>Output

Max Num 1, 34, 3, 98, 9, 76, 45, 4 = 998764543431
Max Num 54,546,548,60 = 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)