Largest int from concatenated ints: Difference between revisions

m
Added Easylang
m (→‎Version 4: minor improvement)
m (Added Easylang)
 
(61 intermediate revisions by 31 users not shown)
Line 20:
*   [http://stackoverflow.com/questions/14532105/constructing-the-largest-number-possible-by-rearranging-a-list/14539943#14539943 Constructing the largest number possible by rearranging a list]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F maxnum(x)
V maxlen = String(max(x)).len
R sorted(x.map(v -> String(v)), key' i -> i * (@maxlen * 2 I/ i.len), reverse' 1B).join(‘’)
 
L(numbers) [[212, 21221], [1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]]
print("Numbers: #.\n Largest integer: #15".format(numbers, maxnum(numbers)))</syntaxhighlight>
 
{{out}}
<pre>
Numbers: [212, 21221]
Largest integer: 21221221
Numbers: [1, 34, 3, 98, 9, 76, 45, 4]
Largest integer: 998764543431
Numbers: [54, 546, 548, 60]
Largest integer: 6054854654
</pre>
 
=={{header|Ada}}==
Line 25 ⟶ 45:
The algorithmic idea is to apply a twisted comparison function:
 
<langsyntaxhighlight Adalang="ada">function Order(Left, Right: Natural) return Boolean is
( (Img(Left) & Img(Right)) > (Img(Right) & Img(Left)) );</langsyntaxhighlight>
This function converts the parameters Left and Right to strings and returns True if (Left before Right)
exceeds (Right before Left). It needs Ada 2012 -- the code for older versions of Ada would be more verbose.
Line 32 ⟶ 52:
The rest is straightforward: Run your favourite sorting subprogram that allows to use the function "Order" instead of standard comparison operators ("<" or ">" or so) and print the results:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Containers.Generic_Array_Sort;
 
procedure Largest_Int_From_List is
Line 63 ⟶ 83:
Print_Sorted((1, 34, 3, 98, 9, 76, 45, 4));
Print_Sorted((54, 546, 548, 60));
end Largest_Int_From_List;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">largest(...)
<lang aime>void
largest(...)
{
integer i;
index x;
for (, integer e in xcall(list).__list) {
i = count();
x[999999999 - 9.times(b_, data(), e).b_size(9).atoi] = e;
while (i) {
data b;
call_n(9, b_, b, $(i -= 1));
b_size(b, 9);
x[999999999 - atoi(b_string(b))] = $i;
}
i_wcallx.ucall(x, o_form, 1, 1o_, "~"0);
o_newline();
}
 
 
integer
main(void)
{
largest(1, 34, 3, 98, 9, 76, 45, 4);
largest(54, 546, 548, 60);
return 0;
}</langsyntaxhighlight>
works for input up to 999999999.
{{Out}}
Line 97 ⟶ 109:
=={{header|ALGOL 68}}==
Using method 2 - first sorting into first digit order and then comparing concatenated pairs.
<langsyntaxhighlight lang="algol68">BEGIN
# returns the integer value of s #
OP TOINT = ( STRING s)INT:
Line 165 ⟶ 177:
print( ( newline ) )
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 171 ⟶ 183:
6054854654
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">largestConcInt: function [arr]->
max map permutate arr 's [
to :integer join map s => [to :string]
]
 
loop [[1 34 3 98 9 76 45 4] [54 546 548 60]] 'a ->
print largestConcInt a</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">LargestConcatenatedInts(var){
StringReplace, var, A_LoopField,%A_Space%,, all
Sort, var, D`, fConcSort
Line 183 ⟶ 204:
m := a . b , n := b . a
return m < n ? 1 : m > n ? -1 : 0
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">d =
(
1, 34, 3, 98, 9, 76, 45, 4
Line 191 ⟶ 212:
)
loop, parse, d, `n
MsgBox % LargestConcatenatedInts(A_LoopField)</langsyntaxhighlight>
{{out}}
<pre>998764543431
Line 199 ⟶ 220:
=={{header|AWK}}==
{{works with|gawk|4.0}}
<langsyntaxhighlight lang="awk">
function cmp(i1, v1, i2, v2, u1, u2) {
u1 = v1""v2;
Line 219 ⟶ 240:
print largest_int_from_concatenated_ints(X)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>998764543431
Line 225 ⟶ 246:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM Nums%(10)
Nums%()=1,34,3,98,9,76,45,4
PRINT FNlargestint(8)
Line 245 ⟶ 266:
l$+=STR$Nums%(i%)
NEXT
=l$</langsyntaxhighlight>
{{out}}
<pre>998764543431
Line 251 ⟶ 272:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( maxnum
= A Z F C
. !arg:#
Line 268 ⟶ 289:
& out$(str$(maxnum$(1 34 3 98 9 76 45 4)))
& out$(str$(maxnum$(54 546 548 60)))
);</langsyntaxhighlight>
{{out}}
<pre>998764543431
Line 274 ⟶ 295:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 304 ⟶ 325:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
<pre>998764543431
6054854654</pre>
 
=={{header|C++}}==
<lang cpp>#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>
 
std::string findLargestConcat ( std::vector< int > & mynumbers ) {
std::vector<std::string> concatnumbers ;
std::sort ( mynumbers.begin( ) , mynumbers.end( ) ) ;
do {
std::ostringstream numberstream ;
for ( int i : mynumbers )
numberstream << i ;
concatnumbers.push_back( numberstream.str( ) ) ;
} while ( std::next_permutation( mynumbers.begin( ) ,
mynumbers.end( ) )) ;
return *( std::max_element( concatnumbers.begin( ) ,
concatnumbers.end( ) ) ) ;
}
 
int main( ) {
std::vector<int> mynumbers = { 98, 76 , 45 , 34, 9 , 4 , 3 , 1 } ;
std::vector<int> othernumbers = { 54 , 546 , 548 , 60 } ;
std::cout << "The largest concatenated int is " <<
findLargestConcat( mynumbers ) << " !\n" ;
std::cout << "And here it is " << findLargestConcat( othernumbers )
<< " !\n" ;
return 0 ;
}</lang>
 
{{out}}
<pre>The largest concatenated int is 998764543431 !
And here it is 6054854654 !</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 380 ⟶ 366:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
<pre>The largest possible integer from set 1 is: 998764543431
The largest possible integer from set 2 is: 6054854654</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>
 
std::string findLargestConcat ( std::vector< int > & mynumbers ) {
std::vector<std::string> concatnumbers ;
std::sort ( mynumbers.begin( ) , mynumbers.end( ) ) ;
do {
std::ostringstream numberstream ;
for ( int i : mynumbers )
numberstream << i ;
concatnumbers.push_back( numberstream.str( ) ) ;
} while ( std::next_permutation( mynumbers.begin( ) ,
mynumbers.end( ) )) ;
return *( std::max_element( concatnumbers.begin( ) ,
concatnumbers.end( ) ) ) ;
}
 
int main( ) {
std::vector<int> mynumbers = { 98, 76 , 45 , 34, 9 , 4 , 3 , 1 } ;
std::vector<int> othernumbers = { 54 , 546 , 548 , 60 } ;
std::cout << "The largest concatenated int is " <<
findLargestConcat( mynumbers ) << " !\n" ;
std::cout << "And here it is " << findLargestConcat( othernumbers )
<< " !\n" ;
return 0 ;
}</syntaxhighlight>
 
{{out}}
<pre>The largest concatenated int is 998764543431 !
And here it is 6054854654 !</pre>
 
=={{header|Ceylon}}==
{{trans|Kotlin}}
{{works with|Ceylon|1.23.13}}
<langsyntaxhighlight lang="ceylon">shared void run2run() {
function intConcatenationComparercomparator(Integer x, Integer y) {
assert (existsis Integer xy = parseIntegerInteger.parse(x.string + y.string),
existsis Integer yx = parseIntegerInteger.parse(y.string + x.string));
return yx <=> xy;
}
function biggestConcatenation({Integer*} ints) => "".join(ints.sort(intConcatenationComparercomparator));
value test1 = {1, 34, 3, 98, 9, 76, 45, 4};
print(biggestConcatenation(test1));
value test2 = {54, 546, 548, 60};
value test2 = {54, 546, 548, 60};
print("``biggestConcatenation(*test1)`` and ``biggestConcatenation(*test2)``");
print(biggestConcatenation(test2));
}</lang>
}</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(defn maxcat [coll]
(read-string
(apply str
Line 414 ⟶ 436:
coll))))
 
(prn (map maxcat [[1 34 3 98 9 76 45 4] [54 546 548 60]]))</langsyntaxhighlight>
 
{{out}}
Line 422 ⟶ 444:
=== Sort by two-by-two comparison of largest concatenated result ===
 
<langsyntaxhighlight lang="lisp">
(defun int-concat (ints)
(read-from-string (format nil "~{~a~}" ints)))
Line 431 ⟶ 453:
(defun make-largest-int (ints)
(int-concat (sort ints #'by-biggest-result)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 445 ⟶ 467:
=== Variation around the sort with padded most significant digit ===
 
<langsyntaxhighlight lang="lisp">
;; Sort criteria is by most significant digit with least digits used as a tie
;; breaker
Line 471 ⟶ 493:
#'largest-msd-with-less-digits)))
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 481 ⟶ 503:
=={{header|D}}==
The three algorithms. Uses the second module from the Permutations Task.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.conv, std.array, permutations2;
 
auto maxCat1(in int[] arr) pure @safe {
Line 501 ⟶ 523:
const lists = [[1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]];
[&maxCat1, &maxCat2, &maxCat3].map!(cat => lists.map!cat).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[["998764543431", "6054854654"], ["998764543431", "6054854654"], ["998764543431", "6054854654"]]</pre>
 
=={{header|Delphi}}==
See [https://www.rosettacode.org/wiki/Largest_int_from_concatenated_ints#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight>
func con a b .
t = 10
while b >= t
t *= 10
.
return a * t + b
.
func$ max a[] .
n = len a[]
for i to n - 1
for j = i + 1 to n
if con a[i] a[j] < con a[j] a[i]
swap a[i] a[j]
.
.
.
for v in a[]
r$ &= v
.
return r$
.
print max [ 1 34 3 98 9 76 45 4 ]
print max [ 54 546 548 60 ]
</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def largest_int(list) do
sorted = Enum.sort(list, fn x,y -> "#{x}#{y}" >= "#{y}#{x}" end)
Line 514 ⟶ 571:
 
IO.inspect RC.largest_int [1, 34, 3, 98, 9, 76, 45, 4]
IO.inspect RC.largest_int [54, 546, 548, 60]</langsyntaxhighlight>
 
{{out}}
Line 523 ⟶ 580:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( largest_int_from_concatenated ).
 
Line 535 ⟶ 592:
task() ->
[io:fwrite("Largest ~p from ~p~n", [ints(X), X]) || X <- [[1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]]].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 542 ⟶ 599:
Largest 6054854654 from [54,546,548,60]
</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Form largest integer which is a permutation from a list of integers. Nigel Galloway: March 21st., 2018
let fN g = List.map (string) g |> List.sortWith(fun n g->if n+g<g+n then 1 else -1) |> System.String.Concat
</syntaxhighlight>
{{out}}
<pre>
fN [1; 34; 3; 98; 9; 76; 45; 4] -> "998764543431"
fN [54; 546; 548; 60] -> "6054854654"
</pre>
 
=={{header|Factor}}==
Using algorithm 3:
<syntaxhighlight lang="factor">USING: assocs io kernel math qw sequences sorting ;
IN: rosetta-code.largest-int
 
: pad ( target seq -- padded )
2dup length / swap <repetition> concat swap head ;
: largest-int ( seq -- )
dup dup [ length ] map supremum ! find longest length so we know how much to pad
[ swap pad ] curry map ! pad the integers
<enum> sort-values ! sort the padded integers
keys ! find the original indices of the sorted integers
swap nths ! order non-padded integers according to their sorted order
reverse concat print ;
qw{ 1 34 3 98 9 76 45 4 } qw{ 54 546 548 60 } [ largest-int ] bi@</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
Or alternatively, a translation of F#.
{{trans|F#}}
<syntaxhighlight lang="factor">USING: kernel math.order qw sequences sorting ;
 
: fn ( seq -- str )
[ 2dup swap [ append ] 2bi@ after? +lt+ +gt+ ? ] sort concat ;</syntaxhighlight>
{{out}}
<pre>
qw{ 1 34 3 98 9 76 45 4 } qw{ 54 546 548 60 } [ fn ] bi@
 
--- Data stack:
"998764543431"
"6054854654"</pre>
 
=={{header|Fortran}}==
Line 552 ⟶ 657:
The sorting of the text array was to be by the notorious BubbleSort, taking advantage of the fact that each pass delivers the maximum value of the unsorted portion to its final position: the output could thereby be produced as the sort worked. Rather than mess about with early termination (no element being swapped) or attention to the bounds within which swapping took place, attention concentrated upon the comparison. Because of the left-alignment of the texts, a simple comparison seemed sufficient until I thought of unequal text lengths and then the following example. Suppose there are two numbers, 5, and one of 54, 55, or 56 as the other. Via normal comparisons, the 5 would always be first (because short texts are considered expanded with trailing spaces when compared against longer texts, and a space precedes every digit) however the biggest ordering is 5 54 for the first case but 56 5 for the last. This possibility is not exemplified in the specified trial sets. So, a more complex comparison is required. One could of course write a suitable function and consider the issue there but instead the comparison forms the compound text in the same manner as the result will be, in the two ways AB and BA, and looks to see which yields the bigger sequence. This need only be done for unequal length text pairs.
 
The source is F77 style, except for the declaration of XLAT(N), the use of <N> in the FORMAT statements instead of some large constant or similar, and the ability to declare an array via constants as in <code>(/"5","54"/)</code> rather than mess about declaring arrays and initialising them separately. The <code>I0</code> format code to convert a number (an actual number) into a digit string aligned leftwards in a CHARACTER variable of sufficient size is also a F90 introduction, though the B6700 compiler allowed a code <code>J</code> instead. This last is to demonstrate usage of actual numbers for those unpersuaded by the argument for ambiguity that allows for texts. If the <code>I0</code> format code is unavailable then <code>I9</code> (or some suitable size) could be used, followed by <code>text = ADJUSTL(text)</code>, except that this became an intrinsic function only in F90, so perhaps you will have to write a simple alignment routine. <langsyntaxhighlight Fortranlang="fortran"> SUBROUTINE SWAP(A,B) !Why can't the compiler supply these!
INTEGER A,B,T
T = B
Line 624 ⟶ 729:
END DO !Thus, the numbers are aligned left in the text field.
CALL BIGUP(T1,10)
END </langsyntaxhighlight>
Output: the Fortran compiler ignores spaces when reading fortran source, so, hard-core fortranners should have no difficulty doing likewise for the output...
<pre>
Line 645 ⟶ 750:
Biggest:9 8 7 6 5 4 3 2 1 10
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">'#define versionMAXDIGITS 17-01-20168
' compile with: fbc -s console
 
function catint( a as string, b as string ) as uinteger
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
return valint(a+b)
' But we have to define them for older versions.
end function
#Ifndef TRUE ' if TRUE is not defined then
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
 
function grt( a as string, b as string ) as boolean
Dim As Integer array()
return catint(a, b)>catint(b, a)
end function
 
sub shellsort( a() as string )
Function largest(array() As Integer) As String
'quick and dirty shellsort, not the focus of this exercise
dim as uinteger gap = ubound(a), i, j, n=ubound(a)
dim as string temp
do
gap = int(gap / 2.2)
for i=gap to n
temp = a(i)
j=i
while j>=gap andalso grt( a(j-gap), temp )
a(j) = a(j - gap)
j -= gap
wend
a(j) = temp
next i
loop until gap = 1
end sub
 
sub sort_and_print( a() as string )
Dim As Integer lb = LBound(array), ub = UBound(array)
Dimdim Asas Integeruinteger i, flag
Dimdim Asas Stringstring a_str(lboutstring To= ub),tmp""
shellsort(a())
for i=0 to ubound(a)
outstring = a(i)+outstring
next i
print outstring
end sub
 
dim as string set1(8) = {"1", "34", "3", "98", "9", "76", "45", "4"}
For i = lb To ub
dim as string set2(4) = {"54", "546", "548", "60"}
a_str(i) = Left(Str(array(i)) & String(14, " "), 14)
Next
 
sort_and_print(set1())
Do
sort_and_print(set2())</syntaxhighlight>
flag = TRUE
{{out}}
For i = lb To ub - 1
<pre>998764543431
If a_str(i) < a_str(i+1) Then
6054854654
Swap a_str(i), a_str(i +1)
</pre>
flag = FALSE
End If
Next
If flag = TRUE Then Exit Do
Loop
 
=={{header|Frink}}==
For i = lb To ub
<syntaxhighlight lang="frink">a = [[1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]]
tmp += Trim(a_str(i))
f = {|p| parseInt[join["",p]] }
Next
for s = a
 
println[max[map[f, s.lexicographicPermute[]]]]</syntaxhighlight>
Return tmp
 
End Function
 
' ------=< MAIN >=------
 
Data 1, 34, 3, 98, 9, 76, 45, 4, -999
Data 54, 546, 548, 60, -999
Data -999
 
Dim As Integer i, x
 
Do
ReDim array(1 To 1)
i = 1
Do
Read x
If x = -999 Then Exit Do
If i > 1 Then
ReDim Preserve array(1 To i)
End If
array(i) = x
i += 1
Loop
If i = 1 Then Exit Do
Print "Largest concatenated int from {";
For i = lBound(array) To UBound(array)
Print Str(array(i));
If i = UBound(array) Then
Print "} = "; largest(array())
Else
Print ",";
End If
Next
Loop
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre>
<pre>Largest concatenated int from {1,34,3,98,9,76,45,4} = 989764543431
998764543431
Largest concatenated int from {54,546,548,60} = 6054854654</pre>
6054854654
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=4169e7641f29ff0ae1dd202b459e60ce Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">'Largest int from concatenated ints
 
Public Sub Main()
Line 777 ⟶ 860:
Print Val(sList.Join("")) 'Join all items in sList together and print
 
End</langsyntaxhighlight>
Output:
<pre>
Line 785 ⟶ 868:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">// Variation of method 3. Repeat digits to at least the size of the longest,
// then sort as strings.
package main
 
import (
"fmt"
"math/big"
"sort"
"strconv"
"strings"
)
 
type c struct {
i int
s, rs string
}
 
type cc []*c
 
func (c cc) Len() int { return len(c) }
func (c cc) Less(i, j int) bool { return c[j].rs < c[i].rs }
func (c cc) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
 
// Function required by task. Takes a list of integers, returns big int.
func li(is ...int) *big.Int {
ps := make(cc, len(is))
ss := make([]c, len(is))
ml := 0
for j, i := range is {
p := &ss[j]
ps[j] = p
p.i = i
p.s = strconv.Itoa(i)
if len(p.s) > ml {
ml = len(p.s)
}
}
for _, p := range ps {
p.rs = strings.Repeat(p.s, (ml+len(p.s)-1)/len(p.s))
}
sort.Sort(ps)
s := make([]string, len(ps))
for i, p := range ps {
s[i] = p.s
}
b, _ := new(big.Int).SetString(strings.Join(s, ""), 10)
return b
}
 
func main() {
fmt.Println(li(1, 34, 3, 98, 9, 76, 45, 4))
fmt.Println(li(54, 546, 548, 60))
}</lang>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
=={{header|Go}}==
<lang go>// Variation of method 3. Repeat digits to at least the size of the longest,
// then sort as strings.
package main
Line 897 ⟶ 920:
fmt.Println(li(1, 34, 3, 98, 9, 76, 45, 4))
fmt.Println(li(54, 546, 548, 60))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 905 ⟶ 928:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def largestInt = { c -> c.sort { v2, v1 -> "$v1$v2" <=> "$v2$v1" }.join('') as BigInteger }</langsyntaxhighlight>
Testing:
<langsyntaxhighlight lang="groovy">assert largestInt([1, 34, 3, 98, 9, 76, 45, 4]) == 998764543431
assert largestInt([54, 546, 548, 60]) == 6054854654</langsyntaxhighlight>
 
=={{header|Haskell}}==
===Compare repeated string method===
<langsyntaxhighlight Haskelllang="haskell">import Data.List (sortBy)
import Data.Ord (comparing)
 
Line 921 ⟶ 944:
in sortBy (flip $ comparing pad) xs
 
maxcat = read . concat . sorted . map show</langsyntaxhighlight>
 
{{out}}
Line 927 ⟶ 950:
 
Since repeating numerical string "1234" is the same as taking all the digits of 1234/9999 after the decimal point, the following does essentially the same as above:
<langsyntaxhighlight lang="haskell">import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Ratio ((%))
Line 937 ⟶ 960:
map (\a->(a, head $ dropWhile (<a) nines))
 
main = mapM_ (print.maxcat) [[1,34,3,98,9,76,45,4], [54,546,548,60]]</langsyntaxhighlight>
 
===Sort on comparison of concatenated ints method===
<langsyntaxhighlight Haskelllang="haskell">import Data.List (sortBy)
 
main = print (map maxcat [[1,34,3,98,9,76,45,4], [54,546,548,60]] :: [Integer])
where sorted = sortBy (\a b -> compare (b++a) (a++b))
maxcat = read . concat . sorted . map show</langsyntaxhighlight>
 
;Output as above.
 
===Try all permutations method===
<langsyntaxhighlight Haskelllang="haskell">import Data.List (permutations)
 
main :: IO ()
main =
print
(maxcat <$> [[1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]] :: [Integer])
where
maxcat = read . maximum . fmap (concatMap show <$>) . permutations</langsyntaxhighlight>
 
;Output as above.
Line 964 ⟶ 988:
lifting.
 
<langsyntaxhighlight lang="unicon">import Collections # For the Heap (dense priority queue) class
 
procedure main(a)
Line 977 ⟶ 1,001:
procedure cmp(a,b)
return (a||b) > (b||a)
end</langsyntaxhighlight>
 
Sample runs:
Line 989 ⟶ 1,013:
 
=={{header|J}}==
Here we use the "pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key" approach:
'''Solution:'''
<langsyntaxhighlight lang="j">maxlen=: [: >./ #&>
maxnum=: (0 ". ;)@(\: maxlen $&> ])@(8!:0)</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> maxnum&> 1 34 3 98 9 76 45 4 ; 54 546 548 60
998764543431 6054854654</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,000 ⟶ 1,025:
This example sets up a comparator to order the numbers using <code>Collections.sort</code> as described in method #3 (padding and reverse sorting).
It was also necessary to make a join method to meet the output requirements.
<langsyntaxhighlight lang="java5">import java.util.*;
 
public class IntConcat {
Line 1,041 ⟶ 1,066:
System.out.println(join(ints2));
}
}</langsyntaxhighlight>
{{works with|Java|1.8+}}
<langsyntaxhighlight lang="java5">import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Line 1,090 ⟶ 1,115:
);
}
}</langsyntaxhighlight>
{{out}}
<pre>998764543431
6054854654</pre>
 
=={{header|JavaScript}}==
 
===ES5===
 
<langsyntaxhighlight JavaScriptlang="javascript"> (function () {
'use strict';
 
Line 1,124 ⟶ 1,150:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,133 ⟶ 1,159:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">var maxCombine = (a) => +(a.sort((x, y) => +("" + y + x) - +("" + x + y)).join(''));
 
// test & output
Line 1,139 ⟶ 1,165:
[1, 34, 3, 98, 9, 76, 45, 4],
[54, 546, 548, 60]
].map(maxCombine));</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,145 ⟶ 1,171:
==== Padding ====
''For jq versions greater than 1.4, it may be necessary to change "sort_by" to "sort".''
<langsyntaxhighlight lang="jq">def largest_int:
 
def pad(n): . + (n - length) * .[length-1:];
Line 1,158 ⟶ 1,184:
([1, 34, 3, 98, 9, 76, 45, 4],
[54, 546, 548, 60]) | largest_int
</syntaxhighlight>
</lang>
{{Out}}
$ /usr/local/bin/jq -n -M -r -f Largest_int_from_concatenated_ints.jq
Line 1,166 ⟶ 1,192:
====Custom Sort====
The following uses [[Sort_using_a_custom_comparator#jq| quicksort/1]]:
<langsyntaxhighlight lang="jq">def largest_int:
map(tostring)
| quicksort( .[0] + .[1] < .[1] + .[0] )
| reverse | join("") ;</langsyntaxhighlight>
 
=={{header|Julia}}==
Perhaps algorithm 3 is more efficient, but algorithm 2 is decent and very easy to implement in Julia. So this solution uses algorithm 2.
 
<lang Julia>
<syntaxhighlight lang="julia">function maxconcat{T<:Integer}(aarr::ArrayVector{T,1<:Integer})
b = mapsort(string.(arr); lt=(x, ay) -> x * y < y * x, rev=true) |> join
breturn =try sortparse(bInt, lt=(x,yb)->x*y <catch y*xparse(BigInt, rev=trueb) end
b = join(b, "")
try
b = parseint(b)
catch
b = parseint(BigInt, b)
end
end
 
tests = {([1, 34, 3, 98, 9, 76, 45, 4],
[54, 546, 548, 60],
[1, 34, 3, 98, 9, 76, 45, 4, 54, 546, 548, 60]})
 
for tarr in tests
println("MaxconcatingMax concatenating in $arr:\n -> ", tmaxconcat(arr))
end</syntaxhighlight>
println(" ", maxconcat(t))
</lang>
 
{{out}}
<pre>Max concatenating in [1, 34, 3, 98, 9, 76, 45, 4]:
<pre>
-> 998764543431
Maxconcating [1,34,3,98,9,76,45,4]
Max concatenating in [54, 546, 548, 60]:
998764543431
-> 6054854654
Maxconcating [54,546,548,60]
Max concatenating in [1, 34, 3, 98, 9, 76, 45, 4, 54, 546, 548, 60]:
6054854654
-> 9987660548546544543431</pre>
Maxconcating [1,34,3,98,9,76,45,4,54,546,548,60]
9987660548546544543431
</pre>
 
=={{header|Kotlin}}==
{{trans|C#}}
<syntaxhighlight lang="kotlin">import kotlin.Comparator
{{works with|Kotlin|1.0b4}}
<lang scala>import java.util.Comparator
 
fun main(args: Array<String>) {
val comparator = Comparator<Int> { x, y -> "$x$y".compareTo("$y$x") }
val xy = (x.toString() + y).toInt()
val yx = (y.toString() + x).toInt()
xy.compareTo(yx)
}
 
fun findLargestSequence(array: IntArray): String {
return array.sortedWith(comparator).reversed()).mapjoinToString("") { it.toString() }.joinToString("")
}
 
for (array in listOf(
val source1 = intArrayOf(1, 34, 3, 98, 9, 76, 45, 4)
intArrayOf(1, 34, 3, 98, 9, 76, 45, 4),
println(findLargestSequence(source1))
intArrayOf(54, 546, 548, 60),
 
)) {
val source2 = intArrayOf(54, 546, 548, 60)
println("%s -> %s".format(array.contentToString(), findLargestSequence(source2array)))
}
}</lang>
}</syntaxhighlight>
{{Out}}
<pre>
998764543431
[1, 34, 3, 98, 9, 76, 45, 4] -> 998764543431
6054854654
[54, 546, 548, 60] -> 6054854654
</pre>
 
=={{header|Lua}}==
 
{{trans|Python}}
<langsyntaxhighlight Lualang="lua">function icsort(numbers)
table.sort(numbers,function(x,y) return (x..y) > (y..x) end)
return numbers
Line 1,242 ⟶ 1,257:
table.concat(numbers,","),table.concat(icsort(numbers))
))
end</langsyntaxhighlight>
{{out}}
<pre>Numbers: {1,34,3,98,9,76,45,4}
Line 1,249 ⟶ 1,264:
Largest integer: 6054854654</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">makeLargestInt[list_] := Module[{sortedlist},
sortedlist = Sort[list, Order[ToString[#1] <> ToString[#2], ToString[#2] <> ToString[#1]] < 0 &];
Map[ToString, sortedlist] // StringJoin // FromDigits
Line 1,256 ⟶ 1,271:
(* testing with two examples *)
makeLargestInt[{1, 34, 3, 98, 9, 76, 45, 4}]
makeLargestInt[{54, 546, 548, 60}]</langsyntaxhighlight>
{{out}}
<pre>998764543431
6054854654</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that decompose a number into a list of its digits using conversions between numbers and strings */
decompose_n_s(n):=block(
string(n),
charlist(%%),
map(eval_string,%%))$
 
/* Function that orders the list obtained by decompose_n_ according to ordergreat and then orders the result to reached what is needed to solve the problem */
largest_from_list(lst):=(
sort(map(decompose_n_s,lst),ordergreatp),
sort(%%,lambda([a,b],if last(a)>last(b) then rest(b,-1)=a else rest(a,-1)=b)),
map(string,flatten(%%)),
simplode(%%),
eval_string(%%));
 
/* Test cases */
test1: [1, 34, 3, 98, 9, 76, 45, 4]$
test2: [54, 546, 548, 60]$
largest_from_list(test1);
largest_from_list(test2);
</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
=={{header|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">(quote cons "" join) :s+
('string map (over over swap s+ 's+ dip <) sort "" join int) :fn
 
(1 34 3 98 9 76 45 4) fn puts!
(54 546 548 60) fn puts!</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,311 ⟶ 1,365:
end il
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,319 ⟶ 1,373:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import algorithm, sequtils, strutils, futuresugar
 
proc maxNum(x: seq[int]): string =
var c = x.mapIt(string, $it)
c.sort((x, y) => cmp(y&x, x&y))
c.join()
 
echo maxNum(@[1, 34, 3, 98, 9, 76, 45, 4])
echo maxNum(@[54, 546, 548, 60])</langsyntaxhighlight>
 
{{out}}
<pre>998764543431
Line 1,333 ⟶ 1,388:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let myCompare a b = compare (b ^ a) (a ^ b)
let icsort nums = String.concat "" (List.sort myCompare (List.map string_of_int nums))</langsyntaxhighlight>
 
;testing
Line 1,347 ⟶ 1,402:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: largestInt map(#asString) sortWith(#[ 2dup + -rot swap + > ]) sum asInteger ;</langsyntaxhighlight>
 
{{out}}
Line 1,354 ⟶ 1,409:
[998764543431, 6054854654]
</pre>
 
=={{header|PARI/GP}}==
Sorts then joins. Most of the noise comes from converting a vector of integers into a concatenated integer: <code>eval(concat(apply(n->Str(n),v)))</code>. Note that the short form <code>eval(concat(apply(Str,v)))</code> is not valid here because <code>Str</code> is variadic.
 
<syntaxhighlight lang="parigp">large(v)=eval(concat(apply(n->Str(n),vecsort(v,(x,y)->eval(Str(y,x,"-",x,y))))));
large([1, 34, 3, 98, 9, 76, 45, 4])
large([54, 546, 548, 60])</syntaxhighlight>
{{out}}
<pre>%1 = 998764543431
%2 = 6054854654</pre>
 
=={{header|Pascal}}==
tested with freepascal.Used a more extreme example 3.
===algorithm 3===
<langsyntaxhighlight lang="pascal">const
base = 10;
MaxDigitCnt = 11;
Line 1,449 ⟶ 1,514:
var
i,l : integer;
s : stringAnsiString;
begin
{ the easy way
Line 1,496 ⟶ 1,561:
InsertData(tmpData[i],source3[i]);
HighestInt(tmpData);
end.</langsyntaxhighlight>
{{out}}
<pre>998764543431
Line 1,505 ⟶ 1,570:
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints#Compare_repeated_string_method
 
<langsyntaxhighlight lang="pascal">const
base = 10;
MaxDigitCnt = 11;
Line 1,630 ⟶ 1,695:
InsertData(tmpData[i],source3[i]);
HighestInt(tmpData);
end.</langsyntaxhighlight>
{{out}}
<pre>9987645434310
6054854654
602121212122210></pre>
 
=={{header|PARI/GP}}==
Sorts then joins. Most of the noise comes from converting a vector of integers into a concatenated integer: <code>eval(concat(apply(n->Str(n),v)))</code>. Note that the short form <code>eval(concat(apply(Str,v)))</code> is not valid here because <code>Str</code> is variadic.
 
<lang parigp>large(v)=eval(concat(apply(n->Str(n),vecsort(v,(x,y)->eval(Str(y,x,"-",x,y))))));
large([1, 34, 3, 98, 9, 76, 45, 4])
large([54, 546, 548, 60])</lang>
{{out}}
<pre>%1 = 998764543431
%2 = 6054854654</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub maxnum {
join '', sort { "$b$a" cmp "$a$b" } @_
}
 
print maxnum(1, 34, 3, 98, 9, 76, 45, 4), "\n";
print maxnum(54, 546, 548, 60), "\n";</langsyntaxhighlight>
{{out}}
<pre>998764543431
6054854654</pre>
 
=={{header|Perl 6}}==
<lang perl6>sub maxnum(*@x) {
[~] @x.sort: -> $a, $b { $b ~ $a leg $a ~ $b }
}
 
say maxnum <1 34 3 98 9 76 45 4>;
say maxnum <54 546 548 60>;</lang>
{{out}}
<pre>998764543431
Line 1,669 ⟶ 1,713:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function catcmp(string a, string b)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return compare(b&a,a&b)
<span style="color: #008080;">function</span> <span style="color: #000000;">catcmp</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">compare</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">&</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">&</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function method2(sequence s)
for i=1 to length(s) do
<span style="color: #008080;">function</span> <span style="color: #000000;">method2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
s[i] = sprintf("%d",s[i])
<span style="color: #008080;">return</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">catcmp</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">)),</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
s = custom_sort(routine_id("catcmp"),s)
return join(s,"")
<span style="color: #0000FF;">?</span><span style="color: #000000;">method2</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">34</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">98</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">76</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">})</span>
end function
<span style="color: #0000FF;">?</span><span style="color: #000000;">method2</span><span style="color: #0000FF;">({</span><span style="color: #000000;">54</span><span style="color: #0000FF;">,</span><span style="color: #000000;">546</span><span style="color: #0000FF;">,</span><span style="color: #000000;">548</span><span style="color: #0000FF;">,</span><span style="color: #000000;">60</span><span style="color: #0000FF;">})</span>
 
<!--</syntaxhighlight>-->
? method2({1,34,3,98,9,76,45,4})
? method2({54,546,548,60})</lang>
{{out}}
<pre>
Line 1,690 ⟶ 1,733:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function maxnum($nums) {
usort($nums, function ($x, $y) { return strcmp("$y$x", "$x$y"); });
return implode('', $nums);
Line 1,696 ⟶ 1,739:
 
echo maxnum(array(1, 34, 3, 98, 9, 76, 45, 4)), "\n";
echo maxnum(array(54, 546, 548, 60)), "\n";</langsyntaxhighlight>
{{out}}
<pre>998764543431
6054854654</pre>
 
=={{header|Picat}}==
On the simpler cases, four methods are tested: 2 using permutations and 2 with different sorting methods.
 
===permutation/2===
<syntaxhighlight lang="picat">s_perm1(L, Num) =>
permutation(L,P),
Num = [I.to_string() : I in P].flatten().to_integer().</syntaxhighlight>
 
 
===Using permutations/1===
<syntaxhighlight lang="picat">s_perm2(L, Num) =>
Perms = permutations(L),
Num = max([ [I.to_string() : I in P].flatten().to_integer() : P in Perms]).</syntaxhighlight>
 
===Sort on concatenated numbers===
<syntaxhighlight lang="picat">s_sort_conc(L,Num) =>
Num = [to_string(I) : I in qsort(L,f3)].join('').to_integer().
 
% sort function for s_sort_conc/2
f3(N1,N2) =>
N1S = N1.to_string(),
N2S = N2.to_string(),
(N1S ++ N2S).to_integer() >= (N2S ++ N1S).to_integer().
 
% qsort(List, SortFunction)
% returns a sorted list according to the sort function SortFunction.
qsort([],_F) = [].
qsort([H|T],F) = qsort([E : E in T, call(F,E,H)], F)
++ [H] ++
qsort([E : E in T, not call(F,E,H)],F).</syntaxhighlight>
 
===Extend each element to the largest length===
<syntaxhighlight lang="picat">s_extend(L,Num) =>
LS = [I.to_string() : I in L],
MaxLen = 2*max([I.length : I in LS]),
L2 = [],
foreach(I in LS)
I2 = I,
% extend to a larger length
while(I2.length < MaxLen)
I2 := I2 ++ I
end,
% keep info of the original number
L2 := L2 ++ [[I2,I]]
end,
Num = [I[2] : I in qsort(L2,f4)].join('').to_integer().
 
% sort function for s_extend/2
f4(N1,N2) => N1[1].to_integer() >= N2[1].to_integer().</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">import util.
 
go =>
Ls = [[1, 34, 3, 98, 9, 76, 45, 4],
[54, 546, 548, 60],
[97, 9, 13, 979],
[9, 1, 95, 17, 5]
],
foreach(L in Ls)
test(L)
end,
nl.
 
% Test all implementations
test(L) =>
println(l=L),
 
maxof_inc(s_perm1(L,Num1), Num1),
println(s_perm1=Num1),
 
s_perm2(L,Num2),
println(s_perm2=Num2),
 
s_sort_conc(L,Num3),
println(s_sort_conc=Num3),
 
s_extend(L,Num4),
println(s_extent=Num4),
nl.</syntaxhighlight>
 
{{out}}
<pre>l = [1,34,3,98,9,76,45,4]
s_perm1 = 998764543431
s_perm2 = 998764543431
s_sort_conc = 998764543431
s_extend = 998764543431
 
l = [54,546,548,60]
s_perm1 = 6054854654
s_perm2 = 6054854654
s_sort_conc = 6054854654
s_extend = 6054854654
 
l = [97,9,13,979]
s_perm1 = 99799713
s_perm2 = 99799713
s_sort_conc = 99799713
s_extend = 99799713
 
l = [9,1,95,17,5]
s_perm1 = 9955171
s_perm2 = 9955171
s_sort_conc = 9955171
s_extend = 9955171</pre>
 
===Testing larger instance===
Test a larger instance: 2000 random numbers between 1 and 100; about 5800 digits. The two permutation variants (<code>s_perm1</code> and <code>s_perm2</code>) takes too long on larger N, say N > 9.
<syntaxhighlight lang="picat">go2 =>
garbage_collect(100_000_000),
_ = random2(),
N = 2000,
println(nums=N),
L = [random(1,1000) : _ in 1..N],
S = join([I.to_string : I in L],''),
println(str_len=S.len),
 
nl,
println("s_sort_conc:"),
time(s_sort_conc(L,_Num3)),
 
println("s_extend:"),
time(s_extend(L,_Num4)),
 
nl.</syntaxhighlight>
 
{{out}}
<pre>nums = 2000
str_len = 5805
 
s_sort_conc:
 
CPU time 0.54 seconds.
 
s_extend:
 
CPU time 0.526 seconds.</pre>
 
=={{header|PicoLisp}}==
Line 1,708 ⟶ 1,890:
unique lists (as the comparison of identical numbers would not terminate), so a
better solution might involve additional checks.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l") # For 'permute'</langsyntaxhighlight>
===Algorithm 1===
<langsyntaxhighlight PicoLisplang="picolisp">(for L '((1 34 3 98 9 76 45 4) (54 546 548 60))
(prinl (maxi format (permute L))) )</langsyntaxhighlight>
===Algorithm 2===
<langsyntaxhighlight PicoLisplang="picolisp">(for L '((1 34 3 98 9 76 45 4) (54 546 548 60))
(prinl
(sort L
Line 1,719 ⟶ 1,901:
(>
(format (pack A B))
(format (pack B A)) ) ) ) ) )</langsyntaxhighlight>
===Algorithm 3===
<langsyntaxhighlight PicoLisplang="picolisp">(for L '((1 34 3 98 9 76 45 4) (54 546 548 60))
(prinl
(flip
(by '((N) (apply circ (chop N))) sort L) ) ) )</langsyntaxhighlight>
{{out}} in all three cases:
<pre>998764543431
Line 1,730 ⟶ 1,912:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
/* Largest catenation of integers 16 October 2013 */
/* Sort using method 2, comparing pairs of adjacent integers. */
Line 1,761 ⟶ 1,943:
end largest_integer;
end Largest;
</syntaxhighlight>
</lang>
<pre>
54 546 548 60
Line 1,773 ⟶ 1,955:
{{works with|PowerShell|2}}
Using algorithm 3
<langsyntaxhighlight PowerShelllang="powershell">Function Get-LargestConcatenation ( [int[]]$Integers )
{
# Get the length of the largest integer
Line 1,789 ⟶ 1,971:
return $Integer
}</langsyntaxhighlight>
<langsyntaxhighlight PowerShelllang="powershell">Get-LargestConcatenation 1, 34, 3, 98, 9, 76, 45, 4
Get-LargestConcatenation 54, 546, 548, 60
Get-LargestConcatenation 54, 546, 548, 60, 54, 546, 548, 60</langsyntaxhighlight>
{{out}}
<pre>998764543431
Line 1,801 ⟶ 1,983:
Works with SWI-Prolog 6.5.3.
===All permutations method===
<langsyntaxhighlight Prologlang="prolog">largest_int_v1(In, Out) :-
maplist(name, In, LC),
aggregate(max(V), get_int(LC, V), Out).
Line 1,810 ⟶ 1,992:
append(P, LV),
name(V, LV).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- largest_int_v1([1, 34, 3, 98, 9, 76, 45, 4], Out).
Line 1,821 ⟶ 2,003:
 
===Method 2===
<langsyntaxhighlight Prologlang="prolog">largest_int_v2(In, Out) :-
maplist(name, In, LC),
predsort(my_sort,LC, LCS),
Line 1,856 ⟶ 2,038:
my_sort(R, [H1, H1 | T], [H1]) :-
my_sort(R, [H1 | T], [H1]) .
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,870 ⟶ 2,052:
This also shows one of the few times where cmp= is better than key= on sorted()
 
<langsyntaxhighlight lang="python">try:
cmp # Python 2 OK or NameError in Python 3
def maxnum(x):
Line 1,884 ⟶ 2,066:
key=cmp_to_key(lambda x,y:cmp(y+x, 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)))</langsyntaxhighlight>
 
{{out}}
Line 1,894 ⟶ 2,076:
 
===Python: Compare repeated string method===
<langsyntaxhighlight lang="python">def maxnum(x):
maxlen = len(str(max(x)))
return ''.join(sorted((str(v) for v in x), reverse=True,
Line 1,900 ⟶ 2,082:
 
for numbers in [(212, 21221), (1, 34, 3, 98, 9, 76, 45, 4), (54, 546, 548, 60)]:
print('Numbers: %r\n Largest integer: %15s' % (numbers, maxnum(numbers)))</langsyntaxhighlight>
 
{{out}}
Line 1,911 ⟶ 2,093:
 
{{works with|Python|2.6+}}
<langsyntaxhighlight lang="python">from fractions import Fraction
from math import log10
 
Line 1,919 ⟶ 2,101:
 
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)))</langsyntaxhighlight>
 
;Output as first Python example, above.
 
===Python: Try all permutations method===
<langsyntaxhighlight lang="python">from itertools import permutations
def maxnum(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)))</langsyntaxhighlight>
 
;Output as above.
 
=={{header|Quackery}}==
 
===With a string of space separated sequences of digits===
 
<syntaxhighlight lang="quackery">[ sortwith
[ 2dup swap join
dip join $< ]
[] swap witheach join ] is largest-int ( [ --> $ )
 
$ '1 34 3 98 9 76 45 4' nest$ largest-int echo$ cr
$ '54 546 548 60' nest$ largest-int echo$</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
===With a nest of numbers===
 
<syntaxhighlight lang="quackery"> [ number$ dip number$ join $->n drop ] is conc ( n n --> n )
 
[ 2dup conc unrot swap conc < ] is conc> ( n n --> b )
 
[ sortwith conc>
$ "" swap
witheach [ number$ join ]
$->n drop ] is task ( [ --> n )
 
' [ [ 1 34 3 98 9 76 45 4 ]
[ 54 546 548 60 ] ]
 
witheach [ task echo cr ] </syntaxhighlight>
 
{{out}}
 
<pre>998764543431
6054854654</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">Largest_int_from_concat_ints <- function(vec){
#recursive function for computing all permutations
perm <- function(vec) {
n <- length(vec)
if (n == 1)
return(vec)
else {
x <- NULL
for (i in 1:n){
x <- rbind(x, cbind(vec[i], perm(vec[-i])))
}
return(x)
}
}
permutations <- perm(vec)
concat <- as.numeric(apply(permutations, 1, paste, collapse = ""))
return(max(concat))
}
 
#Verify
Largest_int_from_concat_ints(c(54, 546, 548, 60))
Largest_int_from_concat_ints(c(1, 34, 3, 98, 9, 76, 45, 4))
Largest_int_from_concat_ints(c(93, 4, 89, 21, 73))
</syntaxhighlight>
 
{{out}}
<pre>
[1] 6054854654
[1] 998764543431
[1] 938973421
</pre>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (largest-int ns)
Line 1,941 ⟶ 2,196:
(map largest-int '((1 34 3 98 9 76 45 4) (54 546 548 60)))
;; -> '(998764543431 6054854654)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub maxnum(*@x) {
[~] @x.sort: -> $a, $b { $b ~ $a leg $a ~ $b }
}
 
say maxnum <1 34 3 98 9 76 45 4>;
say maxnum <54 546 548 60>;</syntaxhighlight>
{{out}}
<pre>998764543431
6054854654</pre>
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red []
 
foreach seq [[1 34 3 98 9 76 45 4] [54 546 548 60]] [
print rejoin sort/compare seq function [a b] [ (rejoin [a b]) > rejoin [b a] ]
]
</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654</pre>
=={{header|REXX}}==
The algorithm used is based on exact comparisons (left to right) &nbsp; with &nbsp; ''right digit fill'' &nbsp; of the &nbsp; ''left digit''.
Line 1,950 ⟶ 2,227:
<br>verify that the numbers are indeed integers &nbsp; (and it also normalizes the integers).
 
The absolute value is used for negative numbers. &nbsp; No sorting of the numbers is required for the 1<sup>st</sup> two examples.
The &nbsp; '''numeric digits''' &nbsp; (the number of decimal digits for the precision) &nbsp; is automatically adjusted for any sized integer.
<br>The absolute value is used for negative numbers.
 
===simple integers===
<langsyntaxhighlight lang="rexx">/*REXX program constructs the largest integer from an integer list using concatenation.*/
@.=.; @.1 = '{ 1, 34, 3, 98, 9, 76, 45, 4}' 4 /*the 1st integer list to be used. */
@.2 = '{ 54, 546, 548, 60}' /* " 2nd " " " " " */
@.3 = '{ 4, 45, 54, 5}' /* " 3rd " " " " " */
w=0 /* [↓] process all the integer lists.*/
do j=1 while @.j\==.; $= z= space(@.j) /*keep truckin' until lists exhausted. */
z w=spacemax( translate(@.jw, , '])},{length(['z) ); $= /*performobtain scrubbingmaximum onwidth theto integeralign listoutput.*/
do while z\=''; idx= 1; big= norm(1) /*keep examining the list until done.*/
_=length( space(z, 0) ) + 2 /*determine largest possibility + extra*/
do k=2 to words(z); #= norm(k) /*obtain an a number from the list. */
if _>digits() then numeric digits _ /*use enough decimal digits for maximum*/
L= max(length(big), length(#) ) /*get [↓] examinethe eachmaximum numberlength inof the listinteger*/
do while if z\=='';left(#, L, left(#, 1) ) index<<=1 left(big, L, left(big, 1) ) /*keep examining the list until then done.*/iterate
big=isOK( word(z,#; 1) ) idx= k /*assumewe thatfound firsta integernew isbiggie biggest.(and the index)*/
end /*k*/ /* [] checkfind themax restconcatenated ofinteger. the integers.*/
do kz=2 to wordsdelword(z);, #=isOK(word(zidx,k) 1) /*obtaindelete anthis anmaximum integer from the list. */
L$=max(length( $ || big), length(#) ) /*getappend " " " the maximum length───► of the$. integer*/
end if left(#, L, left(#, 1)/*while )z*/ <<= left(big, L, left(big, 1) ) then iterate /* [↑] process all integers in a list.*/
say 'largest concatenatated integer from ' left( space(@.j), w) " is ─────► " $
big=#; index=k /*we found a new biggie (and the index)*/
end end /*kj*/ /* [↑] findprocess each maxlist concatenatedof integerintegers. */
exit 0 /*stick a fork in it, we're all done. */
 
z=space( delword(z, index, 1) ) /*delete this maximum integer from list*/
$=$ || big /*append " " " ───► $. */
end /*while z*/ /* [↑] process all integers in a list.*/
 
say right($, digits()) ' max for: ' @.j /*show the maximum integer and the list*/
end /*j*/ /* [↑] process each list of integers. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isOKnorm: parse arg ?i; if#= datatypeword(?z,'W' i); thener= return'***error***'; if absleft(?)/#, 1)=="-" then #= /*normalizesubstr(#, the integer.*/2)
say; sayif \datatype(#,'***error*** number W') then do; ? say er # "isn't an integer."; exit 13; sayend; return exit 13#/1</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) integer lists:}}
<pre>
998764543431largest concatenatated maxinteger for:from {1, 34, 3, 98, 9, 76, 45, 4} is ─────► 998764543431
largest concatenatated integer from 54 546 548 60 is ─────► 6054854654
6054854654 max for: {54, 546, 548, 60}
largest concatenatated integer from 4 45 54 5 is ─────► 554454
554454 max for: { 4, 45, 54, 5}
</pre>
 
Line 1,994 ⟶ 2,262:
<br>large enough to express that number as an integer without the exponent.
 
The default for REXX is &nbsp; '''9''' &nbsp; decimal digits., &nbsp; but the &nbsp; '''norm''' &nbsp; function automatically uses enough decimal digits to
<br>express the number as an integer.
 
This REXX version can handle any sized integer &nbsp; (most REXXes can handle up to around eight million decimal
<br>digits, &nbsp; but displaying the result would be problematic for results wider than the display area).
<langsyntaxhighlight lang="rexx">/*REXX program constructs the largest integer from an integer list using concatenation.*/
@.=.; @.1 = '{ 1, 34, 3, 98, 9, 76, 45, 4}' 4 /*the 1st integer list to be used. */
@.2 = '{ 54, 546, 548, 60}' /* " 2nd " " " " " */
@.3 = '{ 4, 45, 54, 5}' /* " 3rd " " " " " */
@.4 = '{ 4, 45, 54, 5, 6.6e77}' /* " 4th " " " " " */
w= 0 /* [↓] process all the integer lists.*/
do j=1 while @.j\==.; $z= space(@.j) /*keep truckin' until lists exhausted. */
z w=spacemax( translate(@.jw, , '])},{length(['z) ); $= /*performobtain scrubbingmaximum onwidth theto integeralign listoutput.*/
do while z\=''; idx=1; big= norm(1) /*keep examining the list until done.*/
_=length( space(z, 0) ) + 2 /*determine largest integer possibility*/
do k=2 to words(z); #= norm(k) /*obtain an a number from the list. */
if _>digits() then numeric digits _ /*use enough decimal digits for maximum*/
L= max(length(big), length(#) ) /*get [↓] examinethe eachmaximum numberlength inof the listinteger*/
do while if z\=='';left(#, L, left(#, 1) ) p<<=uPow(1) left(big, L, left(big, 1) /*keep examining the) list until then done.*/iterate
if p\ big==0#; then numeric digits p idx= k /*#we hasfound biga exponent?new biggie Then(and adjustthe digsindex)*/
big=isOK(y); index=1 end /*k*/ /*assume that[↑] first integerfind ismax biggestconcatenated integer. */
z= delword(z, idx, 1) /*delete [↓] check thethis restmaximum ofinteger thefrom integers.list*/
$= $ || big do k=2 to words(z); p=uPow(k) /*obtainappend an a number" from the list. " " ───► $. */
end /*while z*/ if p\==0 then numeric digits p + Lm +3 /*# has[↑] bigprocess exponent?all integers Thenin adjusta digslist.*/
say 'largest concatenatated integer from #=isOK(y)' left( space(@.j), w) " is " /*obtain an an integer from the list. */$
end /*j*/ L=max(length(big), length(#) ) /*get the[↑] process maximumeach lengthlist of theintegers. integer*/
if left(#, L, left(#, 1) ) <<= left(big, L, left(big, 1) ) then iterate
big=#; index=k /*we found a new biggie (and the index)*/
end /*k*/ /* [↑] find max concatenated integer. */
 
z=space( delword(z, index, 1) ) /*delete this maximum integer from list*/
$=$ || big /*append " " " ───► $. */
end /*while z*/ /* [↑] process all integers in a list.*/
 
say right($, digits()) ' max for: ' @.j /*show the maximum integer and the list*/
end /*j*/ /* [↑] process each list of integers. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
norm: arg i; #= word(z, i); er= '***error***'; if left(#, 1)=="-" then #= substr(#, 2)
isOK: parse arg ?; if datatype(?,'W') then return abs(?)/1 /*normalize the integer.*/
say;if \datatype(#, 'N') say '***error***then signal numberer13 ' ? "isn't an integer."; say; exit/*go and 13tell err msg.*/
else #= # / 1 /*a #, so normalize it*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
uPow: y=word(z, arg(1) ); if pos('E',#)>0 then do; upperparse yvar # mant "E" pow /*extract a number from the list. /*Has exponent? Expand*/
if \datatype(y, 'N') then return 0 /*isn't a number, let isOK handle it. numeric digits pow + length(mand) /*expand digs, adjust#*/
if pos('E', y)==0 then return 0 /*Has the number an exponent? No, ret.*/end
if datatype(#, 'W') then return # / 1
parse var y mant 'E' pow; Lm=length(mant) /*get mantissa's length and exponent. */
er13: say er # "isn't an integer."; exit 13</syntaxhighlight>
if pow +Lm <=digits() then return 0 /*is number smaller than current digs? */
return pow + Lm /*use a new NUMERIC DIGITS pow + Lm */</lang>
{{out|output|text=&nbsp; when using the default (internal) integer lists:}}
 
<pre>
(Output shown at three-quarter size.)
998764543431 max for: {1, 34, 3, 98, 9, 76, 45, 4}
 
6054854654 max for: {54, 546, 548, 60}
<pre style="font-size:75%">
554454 max for: { 4, 45, 54, 5}
largest concatenatated integer from 1 34 3 98 9 76 45 4 is 998764543431
660000000000000000000000000000000000000000000000000000000000000000000000000000554454 max for: { 4, 45, 54, 5, 6.6e77}
largest concatenatated integer from 54 546 548 60 is 6054854654
largest concatenatated integer from 4 45 54 5 is 554454
largest concatenatated integer from 4 45 54 5 6.6e77 is 660000000000000000000000000000000000000000000000000000000000000000000000000000554454
</pre>
 
===Alternate Version===
Inspired by the previous versions.
<syntaxhighlight lang="text">/*REXX program constructs the largest integer from an integer list using concatenation.*/
l.=''; l.1 = '1 34 3 98 9 76 45 4' /*the 1st integer list to be used. */
l.2 = '54 546 548 60' /* " 2nd " " " " " */
Line 2,103 ⟶ 2,364:
result=result||big /*append " " " ---? $. */
end /*while z*/ /* [?] process all integers in a list.*/
Return result</langsyntaxhighlight>
{{out}}
<pre>1 34 3 98 9 76 45 4 -> 998764543431
Line 2,113 ⟶ 2,374:
===Version 4===
{{trans|NetRexx}}
<langsyntaxhighlight lang="rexx">/*REXX program constructs the largest integer from an integer list using concatenation.*/
l.=''; l.1 = '1 34 3 98 9 76 45 4' /*the 1st integer list to be used. */
l.2 = '54 546 548 60' /* " 2nd " " " " " */
Line 2,119 ⟶ 2,380:
l.4 = ' 4 45 54 5 6.6e77' /* " 4th " " " " " */
l.5 = ' 3 3 .2' /* " 5th " " " " " */
l.6 = ' 4 45 54 5 6.6e1001' /* " 4th6th " " " " " */
l.7 = ' 10e9999999994.0000 45 54 5.00' /* " 4th7th " " " " " */
l.8 = ' 10e999999999 5' /* " 8th " " " " " */
l_length=0
Do li=1 By 1 While l.li<>''
Line 2,138 ⟶ 2,400:
z=z int
End
Say left(space(l.li),l_length) '->' zz=largeint(z)
If length(zz)<60 Then
Say left(space(l.li),l_length) '->' zz
Else
Say left(space(l.li),l_length) '->' left(zz,5)'...'right(zz,5)
End
Exit
Line 2,146 ⟶ 2,412:
Parse Arg z
If Datatype(z,'W') Then
Return z+0/1
Else Do
If Datatype(z,'NUM') Then Do
Line 2,154 ⟶ 2,420:
Numeric Digits dig
If Datatype(z,'W') Then
Return z+0/1
End
msg='cannot convert it to an integer'
Line 2,160 ⟶ 2,426:
End
Else Do
msg='not a number (maybe larger than 1e999999999what this REXX can handle)'
Return '?'
End
Line 2,188 ⟶ 2,454:
list=list w.ww
End
Return space(list,0)</syntaxhighlight>
</lang>
{{out}}
<pre>1 34 3 98 9 76 45 4 -> 998764543431
54 546 548 60 -> 6054854654
4 45 54 5 -> 554454
4 45 54 5 6.6e77 -> 66000000000000000000000000000000000000000000000000000000000000000000000000000055445466000...54454
3 3 .2 -> ** invalid ** bad list item: .2 cannot convert it to an integer
4 45 54 5 6.6e1001 -> 66000...54454
4 45 54 5 6.6e1001 -> 660000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000554454
4.0000 45 54 5.00 -> 554454
10e999999999 5 -> ** invalid ** bad list item: 10e999999999 not a number (maybe larger than 1e999999999)</pre>
10e999999999 5 -> ** invalid ** bad list item: 10e999999999 not a number (larger than what this REXX can handle)</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nums=[1,34,3,98,9,76,45,4]
see largestInt(8) + nl
Line 2,225 ⟶ 2,491:
next
return l
</syntaxhighlight>
</lang>
Output:
<pre>
998764543431
6054854654
</pre>
 
=={{header|RPL}}==
We use here the second algorithm, easily derived from the SORT program given in [[Sorting algorithms/Bubble sort#RPL|Sorting algorithms/Bubble sort]].
{{works with|HP|28}}
≪ LIST→ → len
≪ 1 len '''START'''
→STR len ROLL '''END'''
len 1 '''FOR''' n
1 n 1 - '''START'''
'''IF''' DUP2 + LAST SWAP + < '''THEN''' SWAP '''END'''
n ROLLD
'''NEXT''' n ROLLD
-1 '''STEP'''
2 len '''START''' + '''END''' STR→
≫ ≫ ‘<span style="color:blue">MKBIG</span>’ STO
 
{212 21221} <span style="color:blue">MKBIG</span>
{1 34 3 98 9 76 45 4} <span style="color:blue">MKBIG</span>
{54 546 548 60} <span style="color:blue">MKBIG</span>
{{out}}
<pre>
3: 21221221
2: 998764543431
1: 6054854654
</pre>
 
Line 2,237 ⟶ 2,528:
{{trans|Tcl}}
 
<langsyntaxhighlight Rubylang="ruby">def icsort nums
nums.sort { |x, y| "#{y}#{x}" <=> "#{x}#{y}" }
end
Line 2,244 ⟶ 2,535:
p c # prints nicer in Ruby 1.8
puts icsort(c).join
end</langsyntaxhighlight>
 
{{out}}
Line 2,254 ⟶ 2,545:
 
===Compare repeated string method===
<langsyntaxhighlight lang="ruby">def icsort nums
maxlen = nums.max.to_s.length
nums.map{ |x| x.to_s }.sort_by { |x| x * (maxlen * 2 / x.length) }.reverse
Line 2,262 ⟶ 2,553:
p c # prints nicer in Ruby 1.8
puts icsort(c).join
end</langsyntaxhighlight>
 
;Output as above.
 
<langsyntaxhighlight lang="ruby">require 'rational' #Only needed in Ruby < 1.9
 
def icsort nums
Line 2,275 ⟶ 2,566:
p c # prints nicer in Ruby 1.8
puts icsort(c).join
end</langsyntaxhighlight>
 
;Output as above.
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a1$ = "1, 34, 3, 98, 9, 76, 45, 4"
a2$ = "54,546,548,60"
 
Line 2,308 ⟶ 2,599:
maxNum$ = maxNum$ ; a$(j)
next j
end function</langsyntaxhighlight>
{{out}}
<pre>Max Num 1, 34, 3, 98, 9, 76, 45, 4 = 998764543431
Max Num 54,546,548,60 = 6054854654</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn maxcat(a: &mut [u32]) {
a.sort_by(|x, y| {
let xy = format!("{}{}", x, y);
let yx = format!("{}{}", y, x);
xy.cmp(&yx).reverse()
});
for x in a {
print!("{}", x);
}
println!();
}
fn main() {
maxcat(&mut [1, 34, 3, 98, 9, 76, 45, 4]);
maxcat(&mut [54, 546, 548, 60]);
}</syntaxhighlight>
{{out}}
<pre>998764543431
6054854654</pre>
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">define catcmp(a, b)
{
a = string(a);
Line 2,333 ⟶ 2,644:
print("max of series 1 is " + maxcat([1, 34, 3, 98, 9, 76, 45, 4]));
print("max of series 2 is " + maxcat([54, 546, 548, 60]));
</syntaxhighlight>
</lang>
{{out}}
<pre>"max of series 1 is 998764543431"
Line 2,341 ⟶ 2,652:
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">object LIFCI extends App {
 
def lifci(list: List[Long]) = list.permutations.map(_.mkString).max
Line 2,347 ⟶ 2,658:
println(lifci(List(1, 34, 3, 98, 9, 76, 45, 4)))
println(lifci(List(54, 546, 548, 60)))
}</langsyntaxhighlight>
 
{{out}}
Line 2,356 ⟶ 2,667:
 
=={{header|Scheme}}==
<langsyntaxhighlight Schemelang="scheme">(define (cat . nums) (apply string-append (map number->string nums)))
 
(define (my-compare a b) (string>? (cat a b) (cat b a)))
 
(map (lambda (xs) (string->number (apply cat (sort xs my-compare))))
'((1 34 3 98 9 76 45 4) (54 546 548 60)))</langsyntaxhighlight>
{{output}}
<pre>
Line 2,369 ⟶ 2,680:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func maxnum(nums) {
nums.sort {|x,y| "#{y}#{x}" <=> "#{x}#{y}" };
}
Line 2,375 ⟶ 2,686:
[[54, 546, 548, 60], [1, 34, 3, 98, 9, 76, 45, 4]].each { |c|
say maxnum(c).join.to_num;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,381 ⟶ 2,692:
998764543431
</pre>
 
=={{header|Smalltalk}}==
Version 1) sort by padded print strings:
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">#(
(54 546 548 60)
(1 34 3 98 9 76 45 4)
) do:[:ints |
|resultString|
 
"sort ints by padded strings (sort a copy - literals are immudatble),
then collect their strings, then concatenate"
resultString :=
((ints copy sort:[:a :b |
|pad|
pad := (a integerLog10) max:(b integerLog10).
(a printString paddedTo:pad with:$0) > (b printString paddedTo:pad with:$0)])
collect:#printString) asStringWith:''.
Stdout printCR: resultString.
].</syntaxhighlight>
Version 2) alternative: sort by concatenated pair's strings:
<syntaxhighlight lang="smalltalk">#(
(54 546 548 60)
(1 34 3 98 9 76 45 4)
) do:[:ints |
|resultString|
 
resultString :=
((ints copy sort:[:a :b | e'{a}{b}' > e'{b}{a}']) "(1)"
collect:#printString) asStringWith:''.
Stdout printCR: resultString.
].</syntaxhighlight>
Note &sup1; replace "e'{a}{b}'" by "(a printString,b printString)" in dialects, which do not support embedded expression strings.
 
Version 3) no need to collect the resultString; simply print the sorted list (ok, if printing is all we want):
<syntaxhighlight lang="smalltalk">#(
(54 546 548 60)
(1 34 3 98 9 76 45 4)
) do:[:ints |
(ints copy sort:[:a :b | e'{a}{b}' > e'{b}{a}'])
do:[:eachNr | eachNr printOn:Stdout].
Stdout cr.
]</syntaxhighlight>
 
Version 4) no need to generate any intermediate strings; the following will do as well:
<syntaxhighlight lang="smalltalk">#(
(54 546 548 60)
(1 34 3 98 9 76 45 4)
) do:[:ints |
(ints copy sortByApplying:[:i | i log10 fractionPart]) reverseDo:#print.
Stdout cr.
]</syntaxhighlight>
{{out}}
<pre>6054854654
989764543431</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc intcatsort {nums} {
lsort -command {apply {{x y} {expr {"$y$x" - "$x$y"}}}} $nums
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">foreach collection {
{1 34 3 98 9 76 45 4}
{54 546 548 60}
Line 2,393 ⟶ 2,759:
set sorted [intcatsort $collection]
puts "\[$collection\] => \[$sorted\] (concatenated: [join $sorted ""])"
}</langsyntaxhighlight>
{{out}}
<pre>
[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)
</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
 
MainModule: {
_start: (lambda
(for ar in [[98, 76, 45, 34, 9, 4, 3, 1], [54, 546, 548, 60]] do
(sort ar (λ l Int() r Int() (ret (> Int(String(l r)) Int(String(r l))))))
(lout (join ar "")))
)
}</syntaxhighlight>
{{out}}
<pre>
998764543431
6054854654
</pre>
 
=={{header|VBScript}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="vb">
<lang vb>
Function largestint(list)
nums = Split(list,",")
Line 2,427 ⟶ 2,809:
WScript.StdOut.Write largestint(WScript.Arguments(0))
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,440 ⟶ 2,822:
=={{header|Vim Script}}==
This solution is intended to be run as an Ex command within a buffer containing the integers to be processed, one per line.
<langsyntaxhighlight Vimlang="vim">%s/\(.\+\)/\1\1/ | sort! | %s/\(.\+\)\1\n/\1/</langsyntaxhighlight>
 
;Demonstration
 
<langsyntaxhighlight Bashlang="bash">$ paste -s nums
1 34 3 98 9 76 45 4
$ vim -S icsort.vim nums
998764543431</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "./sort" for Sort
 
var cmp = Fn.new { |x, y|
var xy = Num.fromString(x.toString + y.toString)
var yx = Num.fromString(y.toString + x.toString)
return (xy - yx).sign
}
 
var findLargestSequence = Fn.new { |a|
var b = Sort.merge(a, cmp)
return b[-1..0].join()
}
 
var arrays = [
[1, 34, 3, 98, 9, 76, 45, 4],
[54, 546, 548, 60]
]
for (a in arrays) {
System.print("%(a) -> %(findLargestSequence.call(a))")
}</syntaxhighlight>
 
{{out}}
<pre>
[1, 34, 3, 98, 9, 76, 45, 4] -> 998764543431
[54, 546, 548, 60] -> 6054854654
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn bigCI(ns){
ns.apply("toString").sort(fcn(a,b){ (a+b)>(b+a) }).concat();
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">bigCI(T(1, 34, 3, 98, 9, 76, 45, 4)).println();
bigCI(T(54, 546, 548, 60)).println();</langsyntaxhighlight>
{{out}}
<pre>
1,995

edits