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

49 Answers 49

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\$

Clojure/ClojureScript, 18 bytes

#(sort-by zero? %)
\$\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\$
  • \$\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\$ – Addison Crump Feb 2 '16 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 Feb 2 '16 at 21:49
  • \$\begingroup\$ @t0r0X I guess that got clipped somehow. ;P \$\endgroup\$ – Addison Crump Feb 2 '16 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\$
  • 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\$ – Addison Crump Feb 2 '16 at 21:50
  • \$\begingroup\$ Nah, you take it. c: Keep it in this answer, though. \$\endgroup\$ – Addison Crump Feb 2 '16 at 21:59
  • \$\begingroup\$ Sorry, I mean to replace the for loop with for(;z!=y.length();)y+=" 0";. \$\endgroup\$ – Addison Crump Feb 2 '16 at 22:01
  • \$\begingroup\$ You can get rid of ,i=0 now. \$\endgroup\$ – Addison Crump Feb 2 '16 at 22:02
  • \$\begingroup\$ You can use y=y.replaceAll("( 0)|(0 )","") instead of y=y.replaceAll("0 *","").trim(). \$\endgroup\$ – Addison Crump Feb 2 '16 at 22:16
1
\$\begingroup\$

Mathematica 33 bytes

DeleteCases[#,0]~Join~Cases[#,0]&
\$\endgroup\$
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\$

Python 2.7, 31 30 bytes

-1 thanks to dennis

Takes input as array.

def f(i):i.sort(key=0..__eq__)
\$\endgroup\$
  • \$\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 Jun 5 '18 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\$ – Muhammad Salman Jun 5 '18 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 Jun 6 '18 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\$

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\$
0
\$\begingroup\$

GNU Sed, 25

Score includes +1 for use of -E option.

(Almost) direct port of my Retina answer:

:
s/\b0 ([^0].*)/\1 0/
t
\$\endgroup\$
  • \$\begingroup\$ Only GNU sed versions from before this commit (discussion) \$\endgroup\$ – sch Feb 3 '16 at 12:28
  • \$\begingroup\$ @sch Dammit - that adds 2 bytes to lots of my sed answers :( \$\endgroup\$ – Digital Trauma Feb 3 '16 at 16:20
0
\$\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\$
0
\$\begingroup\$

sed, 16 bytes

$G
/[^0]/b
G
h
d

it expects a newline delimited stdin input array

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

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! **

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

SmileBASIC, 77 64 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)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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