# 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

# Perl 5, 26 bytes

23 plus three for -an (-E is free)

say for sort{!$a-!$b}@F


Thanks to Dennis for reminding me of -a, saving two bytes.

# Jelly, 3 bytes

¬Ụị


Sorts the list by the logical NOT of its values. Try it online!

### How it works

¬Ụị    Main link. Input: A (list)

¬      Compute the logical NOT of each element of A.
Ụ     Grade up; sort the resulting list's indices by their corresponding values.
ị    Retrieve the elements of A at that indices.

• Oh hey, modern Jelly can do a 2-byte ¬Þ, even! – Lynn Sep 13 '16 at 0:42

# R, 2923 21 bytes

As noted by MarcoBreitig, we can shorten it to 21 bytes if we don't need to provide it as a function:

x=scan();x[order(!x)]


Previous versions:

function(x)x[order(!x)]


The function takes a vector as input and orders by the logical vector that results from negating the input.

function(x)c(x[x!=0],x[x==0])


The function takes a vector as input and the concatenates (c()) the non-zero values and then the zero-values.

• x=scan();x[order(!x)] is only 21 bytes long. – Marco Breitig Feb 3 '16 at 14:44
• @MarcoBreitig, that's right. I thought it should be a function (and initially, the requirement was a "full-fledged program"). Will update my answer – docendo discimus Feb 3 '16 at 15:13

# 05AB1E, 15 14 bytes

Code:

ED0¢r0KRrFZ}|


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]


## Pyth, 3 bytes

!DQ


Explanation:

  Q    Input
!D     Sort by logical NOT


Try it here.

• Q can be implicit at the end of any Pyth script (assuming it's outside of a lambda, which this is), making this 2 bytes. – hakr14 Mar 28 '18 at 2:33
• @hakr14 That feature didn't exist 2 years ago. – Dennis Mar 28 '18 at 16:26

# MATL, 7 bytes

t~FT#S)


Try it online!

t      % input array. Duplicate
~      % logical negate: nonzero values become false, zeros become true
FT#S   % sort (false, then true) and output a vector with the indices of the sorting
)      % apply that vector of indices to original array


# Python byte code (2.7.9), 252 bytes, 33 opcodes, 0.0228 seconds

This was build when the contest was still a contest

Opens a file in the current directory called 'SourceArray' for use

LOAD_CONST          ''
STORE_FAST          no_zeroes#  no_zeroes = ''

CALL_FUNCTION       0,1#  open('SourceArray')

CALL_FUNCTION       0,0#  .split()

DUP_TOP
DUP_TOP             #Start if
BUILD_LIST          0
COMPARE_OP          ==
POP_JUMP_IF_TRUE    35#  if list == [], GOTO 35
CALL_FUNCTION       0,1#  list.pop(0)
DUP_TOP
COMPARE_OP          ==
POP_JUMP_IF_TRUE    28#  if list.pop(0) == '0', GOTO 28
PRINT_ITEM          #  print list.pop(0)
JUMP_ABSOLUTE       13

POP_TOP
LOAD_CONST          '0%_'#  '0 '
STORE_FAST          no_zeroes#  no_zeroes = no_zeroes + '0 '
JUMP_ABSOLUTE       13

PRINT_ITEM          #  print no_zeroes

RETURN_VALUE


The co_code (The actual codey bit)

'd\x01\x00}\x00\x00\te\x00\x00\x83\x00\x00\tj\x01\x00\x83\x00\x00\t\x04\x04g\x00\x00k\x02\x00sG\x00j\x02\x00d\x02\x00\x83\x01\x00\x04d\x03\x00k\x02\x00s8\x00Gq\x15\x00\t\x01d\x04\x00|\x00\x007}\x00\x00q\x15\x00\t|\x00\x00G\td\x00\x00S'


Or a .pyc file version 03F3

03 F3 0D 0A 40 FD B0 56 63 00 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 73 59 00 00 00 64 01 00 7D 00 00 09 65 00 00 64 02 00 83 01 00 6A 01 00 83 00 00 09 6A 02 00 83 00 00 09 04 04 67 00 00 6B 02 00 73 50 00 6A 03 00 64 03 00 83 01 00 04 64 04 00 6B 02 00 73 41 00 47 71 1E 00 09 01 64 05 00 7C 00 00 37 7D 00 00 71 1E 00 09 7C 00 00 47 09 64 00 00 53 28 06 00 00 00 4E 74 00 00 00 00 74 0B 00 00 00 53 6F 75 72 63 65 41 72 72 61 79 69 00 00 00 00 74 01 00 00 00 30 73 02 00 00 00 30 20 28 04 00 00 00 74 04 00 00 00 6F 70 65 6E 74 04 00 00 00 72 65 61 64 74 05 00 00 00 73 70 6C 69 74 74 03 00 00 00 70 6F 70 28 01 00 00 00 74 09 00 00 00 6E 6F 5F 7A 65 72 6F 65 73 28 00 00 00 00 28 00 00 00 00 74 09 00 00 00 70 79 6B 65 5F 63 6F 64 65 52 08 00 00 00 01 00 00 00 52 00 00 00 00


You can try to compile my source code yourself using my library on github. I just posted a commit to it that allowed comments so I hope this is still competing as far as goes ;)

Roughly equivalent to

no_zeroes = ''
while unamed_variable != []:
unamed_variable_2 = unamed_variable.pop()
if unamed_variable_2 == '0':
no_zeroes += '0 '
else:
print unamed_variable_2,
print no_zeroes,

• Wooow. You cut a ton of time off of that. – Addison Crump Feb 2 '16 at 19:42
• @VoteToClose that's about 1.5x the speed it ran on my laptop :O Who said Python was that slow? – Blue Feb 2 '16 at 19:46

## Haskell, 26 bytes

f x=filter(/=0)x++[0|0<-x]


Take all non-zero numbers followed by all zeros. Filtering constants (here: 0) is quite short when using a list comprehension: [0|0<-x].

# Javascript, 5254 51 bytes

s=>s.replace(/\b0 /g,x=>++i&&'',i=0)+' 0'.repeat(i)

• This doesn't work when the input does not contain any zeroes – rink.attendant.6 Feb 2 '16 at 22:07
• @rink.attendant.6. Thanks, I've updated and still looking for some bytes off :) – removed Feb 2 '16 at 22:46

## ES6, 23 bytes

a=>a.sort((x,y)=>!x-!y)


It used to be the case that sort wasn't stable, in which case you needed 41 bytes:

a=>a.filter(x=>x).concat(a.filter(x=>!x))


{{!}$}  An anonymous function. Sort using “whether or not an element is zero” as a key. # 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 # Vitsy, 18 bytes lDv\[}D(X]lv-i*\0r l Get length of stack Dv Duplicate and grab for later \[ ] Do everything in the loop that many times. } Rotate the stack right. D(X If the item is 0, delete it. lv-i* Get the value of original length - current length. \0 Push that many zeroes. r Reverse the stack. This leaves the sorted array on the stack. ** Note that this no longer works for the current version! ** # PHP, 737170524948 46 bytes - BIG thanks to Ismael Miguel // Assuming$a = array(4,8,6,1,0,8,0,0,0,0,0,-4,'-5',-1,564,0);

// Produces a notice-level error
foreach($a as$v)$v?print"$v ":$b.="0 ";echo$b;

• $v==0 can be replaced with !$v, saving you 2 bytes. – Ismael Miguel Feb 2 '16 at 21:17
• @IsmaelMiguel thanks! – MonkeyZeus Feb 2 '16 at 21:25
• You're welcome. I see you did manage to cut a byte. Try this: foreach($argv as$v)$v?$f.=" $v":$b.=" $v";echo$f.$b;. It is.... some bytes, I don't know... – Ismael Miguel Feb 2 '16 at 21:41 • Or foreach($a as$v)$v?print("$v "):$b.="$v ";echo$b; for a more neat way, that looks exactly the same – Ismael Miguel Feb 2 '16 at 21:49
• @IsmaelMiguel Nice! I would cry if I ever had to pick up someone else's project and found this level of code-golfing lol – MonkeyZeus Feb 2 '16 at 21:54

# Retina, 15

Simple repeated regex substitution:

+\b0 (.*)
$1 0  Try it online. • I used the same method in my Java answer (if I'm reading this right). :D – Addison Crump Feb 2 '16 at 20:14 # 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 # 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 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 # Common Lisp, 46 bytes (lambda(a)(stable-sort a(lambda(_ b)(= 0 b))))  Sort the array so that for each couple (a,b), we have a < b if b is zero. When neither a < b or b < a, the sort is stable: the original order between elements is retained. I also tried with adjust-array and remove, but this was too long: (lambda(a)(adjust-array(remove 0 a)(length a):initial-element 0))  # Octave, 18 bytes @(A)[A(~~A) A(~A)]  sort() takes too many bytes. I'll just use logical indexing. Examples on ideone. • Nicely done. +1. – rayryeng Mar 7 '16 at 17:36 • Wow, works in Matlab too! I didn't know that such indexing is possible – brainkz Sep 13 '16 at 9:13 # Bash + GNU utilities, 23 grep -v ^0 a grep ^0 a  Assumes input is newline-separated entries in a file called a. Score includes +1 for this filename. • @sch Yes, it should be bash - fixed. – Digital Trauma Feb 3 '16 at 16:24 • @TimmyD yes - thanks for the reminder. – Digital Trauma Feb 3 '16 at 16:24 # Mathematica 33 bytes DeleteCases[#,0]~Join~Cases[#,0]&  # Mathematica, 14 bytes Sort[#,#!=0&]&  • Sort[#!=0&] should be enough. – Martin Ender Feb 3 '16 at 8:21 ## Python, 32 bytes lambda x:sorted(x,key=0..__eq__)  Takes argument as any iterable (list, tuple, etc.). Thanks to @xnor for teaching me a new trick! • It's a bit shorter to use key=0..__eq__ (yes, two dots). – xnor Feb 3 '16 at 8:28 • @xnor That's neat... How does it work? – Mego Feb 3 '16 at 8:36 • Most Python objects have an equality method, so for example "abc".__eq__("abc")==True. It's what's called when you do "abc"==. For reasons, Python integers don't have it but floats do, and since 0. == 0, we can substitute its equality operator., which is 0..__eq__. – xnor Feb 3 '16 at 8:52 • @xnor ahh, I knew about the .__eq__ method, but the double dots were confusing me. I didn't catch that the first one was the decimal point in a float literal. – Mego Feb 3 '16 at 9:14 ## Seriously, 12 bytes 4,nYM@░)░+  Try it online! Explanation: 4,nYM@░)░+ 4,n push 4 copies of input YM map logical negate @░) filter (take zeroes) and push to bottom of stack ░ filter (take non-zeroes) + append zeroes  # Matlab: 21 bytes @(a)[a(a~=0),a(a==0)]  Prints nonzero elements first, then concatenates with zero elements @(a)____ create an anonymous function with one input argument a [___,___] concatenates horizontally vectors inside brackets, separated by commas a(a~=0) returns vector with all nonzero elements of vector a a(a==0) returns vector with all zero elements of vector a # APL: 8 bytes (⍴a)↑a~0  a~0 remove zeros from a (read "a without 0") (⍴a) original length of a (read "shape of a") ↑ pad a without zeros to a's original length Test data: a←1 0 1 2 3 4 0 1 0 0 0 0 1 2 3 4 5 • You should either write a full program and read the input from stdin, or write a function and read the input from its parameters. But you can use ⍴↑{⍵~0} and that's even shorter. – jimmy23013 Feb 3 '16 at 13:26 • Not so fast. ⍴↑{⍵~0} won't work everywhere, not in APL2000, nor in IBM APL2. – Lobachevsky Feb 7 '16 at 16:17 • ⍴↑{⍵~0} will return an empty vector. ⍴⍴↑{⍵~0} is a (one element vector) zero. – Lobachevsky Feb 8 '16 at 8:56 # Zsh, 22 bytes (input passed as arguments to the script/function ($@ aka $argv array), output on stdout as space separated list, newline terminated) <<<${@:#0}\ ${(M)@:#0}  • <<< string: here-string here passed as stdin to the $NULLCMD command (cat by default).
• ${@:#0} $@ except elements being 0.
• \${(M)@:#0} reverse of the above

That assumes (like several other answers here) that zeroes in the input are all expressed as 0 (no 00 nor 0x0 nor 36#0`).