15
\$\begingroup\$

This question already has an answer here:

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

\$\endgroup\$

marked as duplicate by caird coinheringaahing, Laikoni, Sriotchilism O'Zaic code-golf Oct 12 '17 at 22:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

24 Answers 24

6
\$\begingroup\$

05AB1E, 3 bytes

œJà

Try it online!

\$\endgroup\$
9
\$\begingroup\$

Python 2, 85 80 77 72 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

\$\endgroup\$
5
\$\begingroup\$

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!

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – aka.nice Oct 13 '17 at 1:11
4
\$\begingroup\$

Ohm v2, 4 bytes

ψJì↑

Explanation:

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Fails for 7, 78; output should be 787 but this returns 778. \$\endgroup\$ – Neil Oct 13 '17 at 8:00
  • \$\begingroup\$ @Neil Whoops, thanks. Fixed at +0 bytes. \$\endgroup\$ – ETHproductions Oct 13 '17 at 13:08
  • \$\begingroup\$ Now fails for 7, 776; output should be 7776 but this returns 7767. \$\endgroup\$ – Neil Oct 13 '17 at 14:24
  • \$\begingroup\$ '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' \$\endgroup\$ – Nahuel Fouilleul Oct 18 '17 at 13:50
  • \$\begingroup\$ @NahuelFouilleul thanks, fixed at +0 bytes. I promise it's finally fixed this time, for real... \$\endgroup\$ – ETHproductions Oct 18 '17 at 21:35
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Octave / MATLAB, 65 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Java (OpenJDK 8), 113 220 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!

\$\endgroup\$
  • \$\begingroup\$ what about l->l.stream().sorted((i,j)->(j+""+i).compareTo(i+""+j)).forEach(i->System.out.print(i)) \$\endgroup\$ – Nahuel Fouilleul Oct 12 '17 at 13:36
  • 1
    \$\begingroup\$ 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() \$\endgroup\$ – Nahuel Fouilleul Oct 12 '17 at 13:52
2
\$\begingroup\$

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"
\$\endgroup\$
2
\$\begingroup\$

Japt, 13 7 bytes

á m¬ñ Ì

Try it here.

-6 thanks to ETHproductions.

\$\endgroup\$
  • \$\begingroup\$ Don't think you'll need the ms if you change ®r+} to \$\endgroup\$ – ETHproductions Oct 12 '17 at 14:37
  • \$\begingroup\$ @ETHproductions Oh so there is such a builtin :p \$\endgroup\$ – Erik the Outgolfer Oct 12 '17 at 17:22
  • \$\begingroup\$ A built-in to join an array on the empty string? Of course :P \$\endgroup\$ – ETHproductions Oct 12 '17 at 17:25
  • \$\begingroup\$ @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 \$\endgroup\$ – Erik the Outgolfer Oct 12 '17 at 17:25
2
\$\begingroup\$

Ruby, 48 41 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"
\$\endgroup\$
  • \$\begingroup\$ 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" \$\endgroup\$ – Neil Slater Oct 12 '17 at 16:12
  • \$\begingroup\$ you can also output it as a String, which s generally readable like an int \$\endgroup\$ – 0x45 Oct 12 '17 at 16:18
  • 1
    \$\begingroup\$ You can also use the f.([50, 2, 1, 9]) syntax to call lambdas. \$\endgroup\$ – Jonah Oct 12 '17 at 17:25
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Gaia, 4 bytes

f$¦⌉

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 27 bytes

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

TIO

\$\endgroup\$
1
\$\begingroup\$

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()}
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Doesn't work for inputs of 7 and 78. \$\endgroup\$ – Neil Oct 13 '17 at 8:01
  • \$\begingroup\$ 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') \$\endgroup\$ – Nahuel Fouilleul Oct 13 '17 at 8:14
  • \$\begingroup\$ fixed using bash builtins instead of coreutils \$\endgroup\$ – Nahuel Fouilleul Oct 18 '17 at 13:19
1
\$\begingroup\$

Python 2, 90 86 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.

\$\endgroup\$
  • \$\begingroup\$ IIRC you don't need any of your square brackets as max and join can take generators, which should save you four bytes \$\endgroup\$ – FlipTack Oct 12 '17 at 19:08
  • \$\begingroup\$ 80 bytes. \$\endgroup\$ – totallyhuman Oct 17 '17 at 10:14
0
\$\begingroup\$

Mathematica, 57 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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). \$\endgroup\$ – phroureo Oct 12 '17 at 23:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.