# I am greater than you! [duplicate]

Write a function or program that given a list of non negative integers, arranges them such that they form the largest possible number.

INPUT

[50, 2, 1, 9]


OUTPUT

95021


INPUT

0


OUTPUT

0


INPUT (Interesting one)

[7, 76]


OUTPUT

776


RULES

• standard loopholes apply.
• Depending on your language you can use int(32) / int(64) or any other numeric datatype. (Please append the chosen type to your answer)
• take a list as Input
• you choose the behavior on empty input

GL

• Can we return a list rather than a number? [9,50,2,1] for instance? Commented Oct 12, 2017 at 12:27
• No, a "plain" number has to be returned., like in the example.
– 0x45
Commented Oct 12, 2017 at 15:00
• Is there any reason why it must be a plain number and not a list? Commented Oct 12, 2017 at 15:34
• Because in my understanding a list can't be read as a number. Concatenating is also the task.
– 0x45
Commented Oct 12, 2017 at 15:36
• – nimi
Commented Oct 12, 2017 at 16:49

# Python 2, 85807772 70 bytes

lambda l:''.join(sorted(map(str,l),key=lambda i:i+i[-1]*max(l))[::-1])


Try it online!

Sorts the numbers lexicographically, but each number is padded with its last digit.

This means that 'shorter' numbers (string-wise) can be larger than 'longer' numbers:

Example:

Input: [76, 7]

Each number gets padded with its last digit: ['76666..','7777..']

Sorted (descending): ['7777..',76666..'], which gives [7, 76]

Joining the result gives: 776

# 05AB1E, 3 bytes

œJà


Try it online!

# Jelly, 4 bytes

Œ!VṀ


## Explanation

       Input: list [1, 4, 5, 21, 4]
Œ!     Generate all permutations of input list
V    Eval those lists as Jelly code: every sublist is joined and interpreted as int
Ṁ   Pick the highest


Try it online!

# Brachylog, 5 bytes

pᶠcᵐ⌉


Try it online!

### Explanation

pᶠ       Find all permutations of the list
cᵐ     Concatenate each permutation into an integer
⌉    Take the biggest one


## JavaScript (ES6), 40 bytes

a=>a.sort((a,b)=>+b+a-(+a+b)).join


Sorts the numbers by their ordering when concatenated, and joins the result.

• I like those ugly concatenations, it works in Squeak Smalltalk too [:x|(x sort:[:a :b|'',a,b>('',b,a)])join+0]the final +0 is for answering an Integer and avoiding quotes Commented Oct 13, 2017 at 1:11

# Ohm v2, 4 bytes

ψJì↑


Explanation:

ψ      All possible permutations
J     join sublists
ì    convert to int
↑   get maximum


Try it online!

# Japt, 8 bytes

ñ!îL w q


Test it online!

Look ma, no permutation built-in!

### Explanation

ñ           Sort the input as if each item
!îL          were repeated to 100 chars. (!îL -> LîX for each item X, L = 100)
w      Reverse.
q    Join into a single string.
Implicit: output result of last expression


Repeating each item to length 100 works because while '7' < '76', '7777...' > '7676...', and no number could possibly be length 100 when converted to a string.

• Fails for 7, 78; output should be 787 but this returns 778.
– Neil
Commented Oct 13, 2017 at 8:00
• @Neil Whoops, thanks. Fixed at +0 bytes. Commented Oct 13, 2017 at 13:08
• Now fails for 7, 776; output should be 7776 but this returns 7767.
– Neil
Commented Oct 13, 2017 at 14:24
• '78' is before '7', '76' after '7' and, '7' and '77' can be in any order , more generally when a number start with sequence of another wrapped the digit which comes after must be compared to the next number in shorter: for example '7625' comes before '762575' but '76257625762' before '7625' Commented Oct 18, 2017 at 13:50
• @NahuelFouilleul thanks, fixed at +0 bytes. I promise it's finally fixed this time, for real... Commented Oct 18, 2017 at 21:35

# Actually, 11 bytes

;l@╨⌠εj≈⌡MM


Try it online!

Explanation:

;l@╨⌠εj≈⌡MM
;l@╨         all permutations of input
⌠εj≈⌡M   concatenate each permutation
M  maximum


# Pyth, 9 bytes

eSmsjkd.p


Try it here!

or:

eSsMjLk.p
jkeojkN.p


• .p - Generate all the permutations.

• msjkd - Map on the above with the following function that takes d as a variable:

• jkd - Concatenate the integers into a single string.

• s - Convert to integer.

• S - Sort the input.

• e - Get the last element.

# Octave / MATLAB, 65 bytes

@(x)max(cellfun(@(s)str2num(s(s>32)),cellstr(num2str(perms(x)))))


Try it online!

# Java (OpenJDK 8), 113220 87 bytes

l->l.stream().map(i->""+i).sorted((i,j)->(j+i).compareTo(i+j)).reduce((i,j)->i+j).get()


Try it online!

• what about l->l.stream().sorted((i,j)->(j+""+i).compareTo(i+""+j)).forEach(i->System.out.print(i)) Commented Oct 12, 2017 at 13:36
• should be a function rather than a consumer l->l.stream().map(i->""+i).sorted((i,j)->(j+i).compareTo(i+j)).reduce((i,j)->i+j).get() Commented Oct 12, 2017 at 13:52

# K (oK), 18 bytes

Solution:

,/x@>(|/#:'x)#'x:$ Try it online! Examples: > ,/x@>(|/#:'x)#'x:$50 2 1 9
"95021"
> ,/x@>(|/#:'x)#'x:$7 76 "776"  Explanation: ,/x@>(|/#:'x)#'x:$ / the solution
$/ convert to string, 50 2 1 9 -> "50","2","1","9" x: / store in x ( ) / do this together #:'x / count (#:) each (') x, "50","2","1","9" -> 2 1 1 1 |/ / max over, 2 1 1 1 -> 2, #' / take each parallel, 2#'"50","2","1","9" -> "50","22","11","99" > / return sorted indices (descending), "50","22","11","99" -> 3 0 1 2 x@ / apply these indices to x, "50","2","1","9" -> "9","50","2","1" ,/ / flatten, "9","50","2","1" -> "95021"  # Japt, 13 7 bytes á m¬ñ Ì  Try it here. -6 thanks to ETHproductions. • Don't think you'll need the ms if you change ®r+} to m¬ Commented Oct 12, 2017 at 14:37 • @ETHproductions Oh so there is such a builtin :p Commented Oct 12, 2017 at 17:22 • A built-in to join an array on the empty string? Of course :P Commented Oct 12, 2017 at 17:25 • @ETHproductions yeah I was referring to q I thought it surprisingly didn't exist but japt isn't that insane so as not to include it :p Commented Oct 12, 2017 at 17:25 ## Ruby, 4841 36 bytes Similar implementation to others, generates all permutations and takes the max. Shame that "permutation" needs to be spelled out in full . . . f=->l{l.permutation.map(&:join).max}  Calling it: f.call([50, 2, 1, 9]) => "95021" f.call([7, 76]) => "776"  Or f.([50, 2, 1, 9]) => "95021"  • I have assumed that the output has to be an integer in the given language - I can drop the .to_i at the end and save 5 bytes if this is not the case. However OP has stated output should be a "plain number" Commented Oct 12, 2017 at 16:12 • you can also output it as a String, which s generally readable like an int – 0x45 Commented Oct 12, 2017 at 16:18 • You can also use the f.([50, 2, 1, 9]) syntax to call lambdas. Commented Oct 12, 2017 at 17:25 # C#, 113 Bytes It's not very short, but hey, it's still C# we're talking about. int F(List<int>n)=>n.Max(i=>{var l=new List<int>(n);l.Remove(i);return int.Parse(""+i+(l.Count>0?""+F(l):""));});  Formatted: int F (List<int>n) => n.Max (i => { var l = new List<int> (n); l.Remove (i); return int.Parse ("" + i + (l.Count > 0 ? "" + F (l) : "")); });  It simply recursively tries all possible permutations of the input and returns the largest one. It uses a 32 Bit integer as input and output numerical datatype. If anybody has an idea on how to improve this solution, feel free to comment. # Gaia, 4 bytes f$¦⌉


Try it online!

# Perl 5, 27 bytes

join"",sort{"$b$a"cmp$a.$b}


TIO

# Groovy, 41 bytes

{it.permutations().max{it.join()}.join()}


If commands were 3 bytes in groovy instead of a full word I halve the size lol:

{it.p().max{it.j()}.j()}


# J, 29 25 bytes

[:>./-.&' '&.":"1@(A.~i.@!@#)

[:>./,&.":/"1@(A.~i.@!@#)

• -.&' '&.":"1 smashes a list of numbers together to produce a single number. -. is "set minus" and ": is format, so ": turns, eg, the list 7 76 into the single string (aka list of chars) into '7 76', and -.&' ' removes the spaces from that string. Since ": was applied using Under &. the inverse is automatically applied at the end, turning the single string-now-without-spaces back into a number.
• ,&.":/"1 smashes a list of numbers together to produce a single number.
• (A.~i.@!@#) all permutations of the list
• >./ maximum of

Try it online!

# MATLAB/Octave, 65 62 bytes

@(n)max(str2num(sprintf([repmat('%d',size(n)) 10],perms(n)')))


Try it online!

Anonymous function which takes an array as an input, and spits out an integer representing the largest number that can be made.

Permutations are found, then the result is formatted to a 2D array where each line contains only the digits from the values in a given permutation in order. This is done by sprintf with enough %d markers to absorb the whole permutation. The result is then converted back to an array of integers where each line becomes its own value. The maximum from this array is returned.

• Save 3 bytes using size(n) instead of 1,numel(n) in the repmat() call

Note: This was developed completely independently from the other Octave answer.

# bash, 96 bytes

f(){ local l g p=$1;shift&&{ for i;{ (($i$p>$p$i))&&l+=\$i||g+=\ $i;};echo$(f $l)$p$(f$g);};}


Try It Online

• Doesn't work for inputs of 7 and 78.
– Neil
Commented Oct 13, 2017 at 8:01
• indeed, from ETHproductions solution (to append 'a' so that '7' > '76') doesn't work because shorter numbers always placed after number which begins with same sequence however it doesn't work for all numbers : '7' > '76', '7' > '77', '7' > '78' but (should be '7' < '76', '7' = '77' and '7' < '78') Commented Oct 13, 2017 at 8:14
• fixed using bash builtins instead of coreutils Commented Oct 18, 2017 at 13:19

# Python 2, 9086 80 bytes

lambda l:max("".join(map(str,x))for x in permutations(l))
from itertools import*


Try it online!

-4 bytes thanks to FlipTack

-6 bytes thanks to i cri everytim

I believe this can be golfed a ton, but I don't really know how. Stupid type conversions added a ton of bytes.

• IIRC you don't need any of your square brackets as max and join can take generators, which should save you four bytes Commented Oct 12, 2017 at 19:08
• 80 bytes. Commented Oct 17, 2017 at 10:14

# Mathematica, 57 bytes

Max[FromDigits[Join@@IntegerDigits/@#]&/@Permutations@#]&


Try it online!

# Matlab, 135 53 bytes

New Solution:

a=input('')
b=sprintf('%d', a)
c=sort(b,'descend')


Explanation: It takes a user matrix input, then separates it into digits, and finally orders those digits from greatest to least.

Old Solution:

a=input('');
b=sprintf('%d',a) - '0';
c=[];b=sort(b,'descend');
for i=1:size(b,2)
c(i)=b(i);
end
for y=1:size(c,2)
e(y)=num2str(c(y))
end


Explanation: First it takes a user input, then separates all of the numbers into individual digits. The %d in sprintf essentially converts the numbers in the string, which is necessary for sorting into each digit (afaik). I tried simply doing num2str(a) but that leaves a space between each number. From there, it is just a matter of sorting and arranging the numbers with proper formatting. The actual code has a lower byte count because it has no semi-colons and everything on one line.

• I think that this might not work (based on the description your provided) because he doesn't want the individual DIGITS ordered (for example, if I'm understanding right, you would return 95210 and split up the 50 from the example, when the user requested that it return 95021). Commented Oct 12, 2017 at 23:01