# Consolidate an Array

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+" ");
}
}
• Any integer or single digits like the examples? – edc65 Feb 2 '16 at 21:30
• @edc65 Any integer that your language supports. – Addison Crump Feb 2 '16 at 21:35
• How can the example be so complex when the shortest answers are 3 characters long? Is Java that much verbose? – A.L Feb 3 '16 at 0:48
• Isn't "There should be no 0s between the non-zero integers." redundant? – Martin Ender Feb 3 '16 at 9:48
• @immibis Might not be the right language for this challenge. :P – Addison Crump Feb 4 '16 at 7:48

# 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}


# Japt, 8 bytes

Un@!X-!Y


Test it online!

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

# Clojure/ClojureScript, 18 bytes

#(sort-by zero? %)


# Java, 131138 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".

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

# 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;}

• 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;} – Addison Crump Feb 2 '16 at 21:50
• Nah, you take it. c: Keep it in this answer, though. – Addison Crump Feb 2 '16 at 21:59
• Sorry, I mean to replace the for loop with for(;z!=y.length();)y+=" 0";. – Addison Crump Feb 2 '16 at 22:01
• You can get rid of ,i=0 now. – Addison Crump Feb 2 '16 at 22:02
• You can use y=y.replaceAll("( 0)|(0 )","") instead of y=y.replaceAll("0 *","").trim(). – Addison Crump Feb 2 '16 at 22:16

# Mathematica 33 bytes

DeleteCases[#,0]~Join~Cases[#,0]&


# 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]


# 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.

## Pyth, 2 bytes

o!


Test suite

Python 3 translation:
print(sorted(eval(input()),key=lambda x:not x))


## Python 2.7, 31 30 bytes

-1 thanks to dennis

Takes input as array.

def f(i):i.sort(key=0..__eq__)

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

# 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


# 05AB1E, 2 bytes

ΣĀ


Try it online!

# 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

# GNU Sed, 25

Score includes +1 for use of -E option.

(Almost) direct port of my Retina answer:

:
s/\b0 ([^0].*)/\1 0/
t

• Only GNU sed versions from before this commit (discussion) – sch Feb 3 '16 at 12:28
• @sch Dammit - that adds 2 bytes to lots of my sed answers :( – Digital Trauma Feb 3 '16 at 16:20

## 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).

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!

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!

# SmileBASIC, 7764 62 bytes

DEF C A
DIM B[LEN(A)]ARYOP 2,B,A,A
ARYOP 6,B,B,2,1SORT B,A
END


Modifies input array in-place.

## Explanation

DEF CONSOLIDATE ARRAY
DIM B[LEN(ARRAY)] 'create another array of the same length
ARYOP #AOPMUL,B,ARRAY,ARRAY 'square each element in ARRAY and store the result in B
ARYOP #AOPCLP,B,B,2,1 'clamp each element in B to be "between" 2 (min) and 1 (max)
SORT B,ARRAY 'sort A and B, using B
END


ARYOP is a function that does simple operations to entire arrays at once.

My goal is to convert all 0s into one value, and every other number into another value. It is important that 0 turns into a HIGHER value than the other numbers, so they will be placed at the end during sorting.

(It would be simpler to convert non-zero numbers to 1, and leave 0 unchanged, but this doesn't work. There is a RSORT function, but it actually just sorts the array and reverses it, so it would not leave the order of other numbers unchanged.)

First, the negative numbers need to be made positive. The simplest way to do this is by squaring them. The result is stored in B.

Next, these values are clamped into the range [2,1]. Technically this is an invalid range, but it works due to the way clamping is implemented.

if (number >= start)
number = start
else if (number <= end)
number = end


Notice that it checks >= rather than >, and that if the first check happens, the second is skipped.

For example:
0 is not greater than or equal to 1, but it is smaller than 2, so it is set to 2.
1 IS greater than or equal to 1, so it is set to 1.
(The second check is skipped, even though 1 is smaller than 2)
2 is greater than or equal to 1, so it is set to 1.
etc.

### So now, we have converted all 0s into 2s, and every other number into a 1.

We can now use SORT to sort the input array by our modified array. This will put all the 0s at the end, and leave the nonzero numbers in the same order (SORT uses a stable sorting algorithm)