41
\$\begingroup\$

The task is simple: consolidate an array of ints. Consolidating this array consists of the following:

  • All instances of 0 need to be moved to the end of the array.
  • There should be no 0s between the non-zero integers.
  • All non-zero indices should retain their order.

Challenge

Consolidate an array in the least amount of bytes.

You are consolidating an array of random length with a size up to your language's max with random integers. Input may be any natural way for your language.

Examples

Input

0 5 8 8 3 5 1 6 8 4 0 3 7 5 6 4 4 7 5 6 7 4 4 9 1 0 5 7 9 3 0 2 2 4 3 0 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 0 5 0 6 0 3

Output

5 8 8 3 5 1 6 8 4 3 7 5 6 4 4 7 5 6 7 4 4 9 1 5 7 9 3 2 2 4 3 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 5 6 3 0 0 0 0 0 0 0 0

Input

-1 -7 -6 5 1 -5 -2 7 -3 -8 0 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 0 -5 -7 3 8 1 1 3 -3 -2 -2 0 -7 0 -4 8 6 -3 6 0 5 3 2 2 2 -2 -7 -3 9 -1 6 0 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 0 3 3 7 -1 -5 1 -3 4 -7 0 3 2 -2 7 -3 0 0 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7

Output

-1 -7 -6 5 1 -5 -2 7 -3 -8 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 -5 -7 3 8 1 1 3 -3 -2 -2 -7 -4 8 6 -3 6 5 3 2 2 2 -2 -7 -3 9 -1 6 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 3 3 7 -1 -5 1 -3 4 -7 3 2 -2 7 -3 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7 0 0 0 0 0 0 0 0 0 0

Example Code (Java)

public class Consolidate {
    public static void main(String[] args) throws Exception {
        int[] toConsolidate = new int[args.length];
        for (int i=0; i<args.length; i++){
            toConsolidate[i]=Integer.parseInt(args[i]);
        }
        for (int i=0; i<toConsolidate.length; i++) {
            for (int k=0; k<toConsolidate.length-1; k++) {
                if (toConsolidate[k] == 0){
                    toConsolidate[k] = toConsolidate[k+1];
                    toConsolidate[k+1] = 0;
                }
            }
        }
        for (int i:toConsolidate)
            System.out.print(i+" ");
    }
}
\$\endgroup\$
9
  • \$\begingroup\$ Any integer or single digits like the examples? \$\endgroup\$
    – edc65
    Commented Feb 2, 2016 at 21:30
  • \$\begingroup\$ @edc65 Any integer that your language supports. \$\endgroup\$ Commented Feb 2, 2016 at 21:35
  • 1
    \$\begingroup\$ @A.L in fairness, it is fully ungolfed and a terrible algorithm. \$\endgroup\$ Commented Feb 3, 2016 at 0:50
  • 8
    \$\begingroup\$ Isn't "There should be no 0s between the non-zero integers." redundant? \$\endgroup\$ Commented Feb 3, 2016 at 9:48
  • 2
    \$\begingroup\$ @immibis Might not be the right language for this challenge. :P \$\endgroup\$ Commented Feb 4, 2016 at 7:48

67 Answers 67

2
\$\begingroup\$

J, 4 bytes

/:0=

Explanation:

/:      NB. upward sort on
  0=    NB. equality to zero

The sort function in J is guaranteed to be stable by the specification.

Alternative solution, 6 bytes:

#{.*#+

 

   *#+  NB. replicate each item by its sign (removing zeroes)
#{.     NB. take as many items from this as the original list had
        NB.  (taking more items than there are in a list results in extra zeroes)
\$\endgroup\$
0
2
\$\begingroup\$

Straw, 30 29 bytes

<:([^0 ])()/,0()/ +,+( +) /}>

Use the CP437 encoding

Explanation

<:([^0 ])()/,0()/ +,+( +) /}>
<                             Take input
 :                            Duplicate
  ([^0 ])()/                  Remove every character that is not a 0 or a space
            ,                 Swap the two items on the top of the stack
             0()/             Remove every 0 on the top of the stack
                  +           Push a space and concatenate
                   ,          Swap
                    +         Concatenate
                     ( +) /   Remove duplicate spaces
                           }  Get the 'tail' of the string
                            > Output

Try it online! (The added code is to test all test cases)

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

Ruby, 25 bytes

->a{a-[0]+[0]*a.count(0)}

Try it online!

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

K (ngn/k), 7 bytes

{x@<~x}

Try it online!

{ } anonymous function with argument x

~ "not" - turn 0s into 1s, and everything else into 0s

< return the permutation for a stable ascending sort

@ indexing

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

Brachylog, 6 bytes

{0∨>}ᵒ

Try it online!

Other languages' "sort by logical negation" approach doesn't work here, because 1. Brachylog doesn't even have a concept of a Boolean and 2. applies the default sort to elements that produce the same output to the given predicate, rather than preserving their order. Although, if the output is unbound but constrained... this happens.

{   }ᵒ    Sort the input by:
 0        this element is 0
  ∨       and the output is whatever, or whatever
   >      is greater than the output.

The very first solution I attempted was simply >ᵒ, which didn't rearrange anything at all, and when it came time to include that as an aside in my explanation of my original solution, I found I couldn't quite explain the circumstances, which led me to this.

The original, which is not without its own share of magic to begin with:

Brachylog, 10 bytes

~b{ȧ>≜}ᵍcb

Try it online!

I arrived at this solution by trying the longer ~b{ȧ>≜}ᵍ↔ck, only to discover that ... I actually don't know how this works. Not a clue. Somehow, the unbound variable created by ~b always ends up non-zero, causing the group of non-zero items to appear before the group of zeroes, as intended (since groups are sorted by first appearance of their earliest elements).

~b{ȧṡ}ᵍ↔ck has the same length, and works on the same principle, but involves only more understandable behaviors of CLP(FD)-- checks the case where its input and output are zero first, so the unbound variable created by ~b simply ends up being zero:

~b            Un-behead the input, i.e. append something.
  {  }ᵍ       Group the elements by
    ṡ         sign of
   ȧ          absolute value.
       ↔      Reverse the groups, so that the one containing the first element is last,
        c     concatenate them,
         k    and remove the last element (the "something" from ~b).
\$\endgroup\$
2
\$\begingroup\$

x86 machine code, 17 bytes

Hexdump:

57 8b fa 33 c0 86 02 42 84 c0 74 01 aa e2 f4 5f
c3

A fastcall function: receives pointer to array in edx and its length in ecx.

Disassembled code:

    doit:
00D815D0 57                   push        edi  
00D815D1 8B FA                mov         edi,edx  
    myloop:
00D815D3 33 C0                xor         eax,eax  
00D815D5 86 02                xchg        al,byte ptr [edx]  
00D815D7 42                   inc         edx  
00D815D8 84 C0                test        al,al  
00D815DA 74 01                je          myskip (0D815DDh)  
00D815DC AA                   stos        byte ptr es:[edi]  
    myskip:
00D815DD E2 F4                loop        doit+3h (0D815D3h)  
00D815DF 5F                   pop         edi  
00D815E0 C3                   ret  
\$\endgroup\$
2
\$\begingroup\$

ArnoldC, 3752 bytes

Input is a 16 bit positive integer, where the first digit is disregarded. Wrote my own 'power' function, but I used the stock standard example for modulo function as per the ArnoldC website. e.g. If you want to consolidate the array [3,1,0,2] you would do so as per the example below:

IT'S SHOWTIME
HEY CHRISTMAS TREE out
YOU SET US UP 0
GET YOUR ASS TO MARS out
DO IT NOW consolidate 13102
TALK TO THE HAND out
YOU HAVE BEEN TERMINATED

LISTEN TO ME VERY CAREFULLY consolidate
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE ZeroCount
YOU SET US UP 0
HEY CHRISTMAS TREE NewNumber
YOU SET US UP 0
HEY CHRISTMAS TREE Modulus
YOU SET US UP 10
HEY CHRISTMAS TREE Power
YOU SET US UP 0
HEY CHRISTMAS TREE Decimal
YOU SET US UP 0
HEY CHRISTMAS TREE Digits
YOU SET US UP 0
GET YOUR ASS TO MARS Digits
DO IT NOW modulo n Modulus
HEY CHRISTMAS TREE Loop
YOU SET US UP 1
HEY CHRISTMAS TREE Cond1
YOU SET US UP 1
HEY CHRISTMAS TREE Cond2
YOU SET US UP 1
HEY CHRISTMAS TREE Val1
YOU SET US UP 0
HEY CHRISTMAS TREE Val2
YOU SET US UP 0
HEY CHRISTMAS TREE Val3
YOU SET US UP 0
HEY CHRISTMAS TREE FinalZeros
YOU SET US UP 1
GET TO THE CHOPPER Loop
HERE IS MY INVITATION n
LET OFF SOME STEAM BENNET Digits
ENOUGH TALK
GET TO THE CHOPPER Cond1
HERE IS MY INVITATION Modulus
HE HAD TO SPLIT 100
LET OFF SOME STEAM BENNET Digits
HE HAD TO SPLIT 10
CONSIDER THAT A DIVORCE Digits
YOU ARE NOT YOU YOU ARE ME 0
ENOUGH TALK
STICK AROUND Loop
BECAUSE I'M GOING TO SAY PLEASE Cond1
GET TO THE CHOPPER ZeroCount
HERE IS MY INVITATION ZeroCount
GET UP 1
ENOUGH TALK
BULLSHIT
GET YOUR ASS TO MARS Val1
DO IT NOW pow 10 Power
GET TO THE CHOPPER Val1
HERE IS MY INVITATION Digits
HE HAD TO SPLIT Val1
ENOUGH TALK
GET YOUR ASS TO MARS Val2
DO IT NOW pow 10 Decimal
GET TO THE CHOPPER Val1
HERE IS MY INVITATION Val1
YOU'RE FIRED Val2
ENOUGH TALK
GET TO THE CHOPPER NewNumber
HERE IS MY INVITATION NewNumber
GET UP Val1
ENOUGH TALK
GET TO THE CHOPPER Decimal
HERE IS MY INVITATION Decimal
GET UP 1
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER Modulus
HERE IS MY INVITATION Modulus
YOU'RE FIRED 10
ENOUGH TALK
GET TO THE CHOPPER Power
HERE IS MY INVITATION Power
GET UP 1
ENOUGH TALK
GET YOUR ASS TO MARS Digits
DO IT NOW modulo n Modulus
GET TO THE CHOPPER Val3
HERE IS MY INVITATION Digits
HE HAD TO SPLIT 10
ENOUGH TALK
GET TO THE CHOPPER Cond1
HERE IS MY INVITATION Modulus
HE HAD TO SPLIT 100
LET OFF SOME STEAM BENNET Val3
ENOUGH TALK
GET TO THE CHOPPER Cond2
HERE IS MY INVITATION Digits
YOU ARE NOT YOU YOU ARE ME 0
ENOUGH TALK
GET TO THE CHOPPER Cond1
HERE IS MY INVITATION Cond1
CONSIDER THAT A DIVORCE Cond2
ENOUGH TALK
GET TO THE CHOPPER Loop
HERE IS MY INVITATION n
LET OFF SOME STEAM BENNET Digits
ENOUGH TALK
CHILL
GET YOUR ASS TO MARS FinalZeros
DO IT NOW pow 10 ZeroCount
GET TO THE CHOPPER NewNumber
HERE IS MY INVITATION NewNumber
YOU'RE FIRED FinalZeros
ENOUGH TALK
I'LL BE BACK NewNumber
HASTA LA VISTA, BABY


LISTEN TO ME VERY CAREFULLY pow
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE base
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE exponent
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE result
YOU SET US UP 1
STICK AROUND exponent
GET TO THE CHOPPER result
HERE IS MY INVITATION base
YOU'RE FIRED result
ENOUGH TALK
GET TO THE CHOPPER exponent
HERE IS MY INVITATION exponent
GET DOWN 1
ENOUGH TALK
CHILL
I'LL BE BACK result
HASTA LA VISTA, BABY

LISTEN TO ME VERY CAREFULLY modulo
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE dividend
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE divisor
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE quotient
YOU SET US UP 0
HEY CHRISTMAS TREE remainder
YOU SET US UP 0
HEY CHRISTMAS TREE product
YOU SET US UP 0
GET TO THE CHOPPER quotient
HERE IS MY INVITATION dividend
HE HAD TO SPLIT divisor
ENOUGH TALK
GET TO THE CHOPPER product
HERE IS MY INVITATION divisor
YOU'RE FIRED quotient
ENOUGH TALK
GET TO THE CHOPPER remainder
HERE IS MY INVITATION dividend
GET DOWN product
ENOUGH TALK
I'LL BE BACK remainder
HASTA LA VISTA, BABY

Try it online!

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

Julia, 22 bytes

l->[l[l.!=0];l[l.==0]]

Try it online!

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

Thunno 2, 2 bytes

Þ~

Attempt This Online!

Sort the input (Þ) by logical NOT (~).

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

05AB1E, 15 14 bytes

Code:

ED0¢r0KR`rFZ}|

Explanation:

E               # Evaluate input
 D              # Duplicate top of the stack
  0¢            # Count zeroes
    r           # Reverse stack
     0K         # Delete all zeroes
       R        # Reverse top of the stack
        `       # Flatten
         r      # Reverse stack
          FZ}   # For N in range(amount zeroes): push zero
             |  # Print full stack

Uses CP-1252 encoding. Takes an array like this:

[0, 5, 8, 8, 3, 5, 1, 6, 8, 4, 0, 3, 7, 5, 6, 4, 4, 7, 5, 6, 7, 4, 4, 9, 1, 0, 5, 7, 9, 3, 0, 2, 2, 4, 3, 0, 4, 8, 7, 3, 1, 4, 7, 5, 1, 2, 1, 8, 7, 8, 7, 7, 2, 6, 3, 1, 2, 8, 5, 1, 4, 2, 0, 5, 0, 6, 0, 3]
\$\endgroup\$
1
\$\begingroup\$

Groovy, 28 chars

Given input array i, e.g. def i = [ 0, 5, -1, 3... ], the following delivers the solution:

i.findAll{it}+i.findAll{!it}
\$\endgroup\$
1
\$\begingroup\$

Japt, 8 bytes

Un@!X-!Y

Test it online!

Joining the "sort by logical NOT" party, as that's literally all it is.

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

Java, 131 138 136 bytes

Thanks to @t0r0X for pointing out a flaw in my code! (and @Mego for pointing out how to fix it!)

void x(String y){int z=y.length(),i=0;System.out.print(y=y.replaceAll("( 0)|(0 )",""));for(;i<z-y.length();i+=2)System.out.print(" 0");}

Expects input as a string in the format "1 2 3 4 5 0 6 0 7 8 9".

\$\endgroup\$
3
  • \$\begingroup\$ @t0r0X I don't think so; do you mean that it's missing a space after the 0? or it looks like 00? \$\endgroup\$ Commented Feb 2, 2016 at 21:47
  • \$\begingroup\$ Cool. Space is missing before 0 in last print(). I.e. print("0") should be print(" 0"). Code length is indeed 138 chars. \$\endgroup\$
    – t0r0X
    Commented Feb 2, 2016 at 21:49
  • \$\begingroup\$ @t0r0X I guess that got clipped somehow. ;P \$\endgroup\$ Commented Feb 2, 2016 at 21:50
1
\$\begingroup\$

Java 8, 84 99 chars

Now even shorter than ever... based on previous answer and suggestions by @VoteToClose ;-)

y->{int z=y.length();for(y=y.replaceAll(" 0|0 ","");y.length()<z;)y+=" 0";return y;}

Java <= 7 version, 99 chars:

String x(String y){int z=y.length();for(y=y.replaceAll(" 0|0 ","");y.length()<z;)y+=" 0";return y;}
\$\endgroup\$
8
  • 1
    \$\begingroup\$ Use Java 8 lambda syntax: y->{int z=y.length(),i=0;y=y.replaceAll("0 *","").trim();for(int n=y.length();i<z-n;i+=2)y+=" 0";return y;} \$\endgroup\$ Commented Feb 2, 2016 at 21:50
  • \$\begingroup\$ Nah, you take it. c: Keep it in this answer, though. \$\endgroup\$ Commented Feb 2, 2016 at 21:59
  • \$\begingroup\$ Sorry, I mean to replace the for loop with for(;z!=y.length();)y+=" 0";. \$\endgroup\$ Commented Feb 2, 2016 at 22:01
  • \$\begingroup\$ You can get rid of ,i=0 now. \$\endgroup\$ Commented Feb 2, 2016 at 22:02
  • \$\begingroup\$ You can use y=y.replaceAll("( 0)|(0 )","") instead of y=y.replaceAll("0 *","").trim(). \$\endgroup\$ Commented Feb 2, 2016 at 22:16
1
\$\begingroup\$

Mathematica 33 bytes

DeleteCases[#,0]~Join~Cases[#,0]&
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 31 bytes

param($a)($a|?{$_})+($a|?{!$_})

Takes input $a, then does a Where-Object (the ?) for all elements that are true (i.e., not zero), and joins that with another Where-Object for all elements that are false (i.e., zero).

\$\endgroup\$
2
  • \$\begingroup\$ You can make it even shorter by using splatting Try it online! \$\endgroup\$
    – Julian
    Commented Mar 3, 2021 at 4:19
  • \$\begingroup\$ And using the -ne and -eq operators Try it online! \$\endgroup\$
    – Julian
    Commented Mar 3, 2021 at 20:21
1
\$\begingroup\$

8th, 75 bytes

First create an array with elements not equal to zero. Then append all found zeros to resulting array.

SED (Stack Effect Diagram) is a -- a

Code

0 swap ( not if n:1+ false else true then ) a:filter ( 0 a:push ) rot times

Example

ok> [0, -3, 7, 0 ,0 , 14, -1] 0 swap ( not if n:1+ false else true then ) a:filter ( 0 a:push ) rot times .
[-3,7,14,-1,0,0,0]
\$\endgroup\$
1
\$\begingroup\$

Stax, 4 bytes

{!oJ

Run and debug it

Sort using x!=0 as the key.

5 bytes

╦╤∩öµ

Run and debug it

Filter out zeros and pad to input length.

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

Pyth, 2 bytes

o!

Test suite

Python 3 translation:
print(sorted(eval(input()),key=lambda x:not x))
\$\endgroup\$
1
\$\begingroup\$

Tcl, 47 bytes

proc D L {proc S x\ y {expr !$x}
lsort -c S $L}

Try it online!

Tcl, 47 bytes

proc S x\ y {expr !$x}
proc D L {lsort -c S $L}

Try it online!


Tcl, 53 bytes

proc D L {lsort -c [list apply {x\ y {expr !$x}}] $L}

Try it online!

Tcl, 55 bytes

proc S x\ y {expr abs($x)<!$x}
proc D L {lsort -c S $L}

Try it online!


Tcl, 61 bytes

proc D L {lsort -c [list apply {x\ y {expr abs($x)<!$x}}] $L}

Try it online!

Tcl, 70 bytes

proc D L {concat [lsearch -al -inl -not $L 0] [lsearch -al -inl $L 0]}

Try it online!

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

Python 2.7, 31 30 bytes

-1 thanks to dennis

Takes input as array.

def f(i):i.sort(key=0..__eq__)
\$\endgroup\$
3
  • \$\begingroup\$ @MuhammadSalman Correct how? The code works, as you can verify in the permalink I left. The function f modifies the array in place. \$\endgroup\$
    – Dennis
    Commented Jun 5, 2018 at 18:08
  • \$\begingroup\$ @Dennis : not that, I know it works, what I meant was whether this comment : "You cannot provide snippet as answer" was correct or not ? \$\endgroup\$ Commented Jun 5, 2018 at 19:00
  • \$\begingroup\$ @MuhammadSalman Yes, snippets are disallowed by default. REPL answers are allowed, but they still have to adhere to our defaults for I/O. \$\endgroup\$
    – Dennis
    Commented Jun 6, 2018 at 0:29
1
\$\begingroup\$

Kotlin, 44 bytes

{i:List<Int>->i.sortedBy{if(it==0)1 else 0}}

Try it online!

Explanation

{ i: List<Int> ->             // lambda taking a List<Int> i
    i.sortedBy {              // sort List by the result of function
        if(it == 0) 1 else 0  // if item is 0 return 1 else 0
    }                         // this will sort i ascending
}                             // while leaving 0s at the end
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 2 bytes

ΣĀ

Try it online!

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

Factor, 29 bytes

[ [ sgn abs ] inv-sort-with ]

Try it online!

Inverse sort with key function 0 -> 0, not 0 -> 1.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Interestingly [ [ 0 = ] partition prepend ] has the same byte count. \$\endgroup\$
    – Bubbler
    Commented May 31, 2021 at 23:54
  • \$\begingroup\$ @Bubbler Nice. All the same, your solution runs an order of magnitude faster. On an array of 100,000 items on my machine, sorting takes around ~40ms in the listener, but partitioning takes ~4ms. \$\endgroup\$
    – chunes
    Commented Jun 1, 2021 at 0:31
1
\$\begingroup\$

Japt, 3 bytes

ñ¶T

Try it

ñ¶T     :Implicit input of array
ñ       :Sort by
 ¶      :Is equal to
  T     :0
\$\endgroup\$
1
\$\begingroup\$

Batch 93 bytes

Input is provided as arguments when running the script in windows cmd.exe

:l
@(Set/A1/%1 2>nul&&Set .=%.%%1 ||set t=%t%%1 )
@If not %1.==. Shift&Goto:l
@Echo %.%%t%

Explainer:

 @Set/A1/%1                   Attempt to Provoke divide by 0 error
 2>nul                        Redirect STDERR to nul
    &&                        If not 0
      Set .=%.% %1            Append to '.' list
    ||                        Else
      'Set t=%t%%1 '          Append to 't'rail list
 @If not %1.==. Shift&Goto:l  If argument remains, Shift Argument, repeat loop
 @Echo %.%%t%                 Output

Note:

@     Suppress command Echo
\$\endgroup\$
1
\$\begingroup\$

Raku, 10 bytes

*.sort(!*)

Try it online!

An anonymous function that calls sort on its argument, where the sort-by function is !*, another anonymous function that boolean-inverts its argument.

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

Desmos, 19 bytes

f(x)=sort(x,0^{xx})

Try it on Desmos!

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

Erlang 86 bytes

f(L)->M=lists:filter(fun(E)->E /= 0 end,L),M++lists:duplicate(length(L)-length(M),0).
\$\endgroup\$
1
\$\begingroup\$

Go, 111 bytes, using golang.org/x/exp/slices

import."golang.org/x/exp/slices"
func f(I[]int)[]int{SortStableFunc(I,func(a,b int)bool{return b==0});return I}

Attempt This Online!

Go, 199 bytes, using sort

import."sort"
type L[]int
func(l L)Len()int{return len(l)}
func(l L)Less(i,j int)bool{return l[j]==0}
func(l L)Swap(i,j int){l[i],l[j]=l[j],l[i]}
func f(I[]int)[]int{l:=L(I);Stable(l);return[]int(l)}

Attempt This Online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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