Consolidate an Array

33

4

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+" ");
    }
}

Addison Crump

Posted 2016-02-02T17:38:42.120

Reputation: 10 763

Any integer or single digits like the examples? – edc65 – 2016-02-02T21:30:38.847

@edc65 Any integer that your language supports. – Addison Crump – 2016-02-02T21:35:43.277

How can the example be so complex when the shortest answers are 3 characters long? Is Java that much verbose? – A.L – 2016-02-03T00:48:14.790

@A.L in fairness, it is fully ungolfed and a terrible algorithm. – Addison Crump – 2016-02-03T00:50:20.750

7Isn't "There should be no 0s between the non-zero integers." redundant? – Martin Ender – 2016-02-03T09:48:18.567

What if our language only supports one possible value besides the one that delimits the end of the array? – user253751 – 2016-02-04T02:32:08.453

@MartinBüttner Yes, but I put it there to make sure that I was understood (didn't have people shift all the zeroes one to the right or something like that. – Addison Crump – 2016-02-04T07:47:35.197

1@immibis Might not be the right language for this challenge. :P – Addison Crump – 2016-02-04T07:48:10.447

@VoteToClose Did you see my recent answer? This would be a zero-terminated cat program in Boolfuck: ,[;,] - although it's still larger than the Pyth one.

– user253751 – 2016-02-04T09:32:54.007

Answers

31

Pyth, 3 bytes

!DQ

Explanation:

  Q    Input
!D     Sort by logical NOT

Try it here.

lirtosiast

Posted 2016-02-02T17:38:42.120

Reputation: 20 331

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 – 2018-03-28T02:33:27.777

@hakr14 That feature didn't exist 2 years ago. – Dennis – 2018-03-28T16:26:56.850

12

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.

Dennis

Posted 2016-02-02T17:38:42.120

Reputation: 196 637

1Oh hey, modern Jelly can do a 2-byte ¬Þ, even! – Lynn – 2016-09-13T00:42:14.033

10

Octave, 18 bytes

@(A)[A(~~A) A(~A)]

sort() takes too many bytes. I'll just use logical indexing.

Examples on ideone.

beaker

Posted 2016-02-02T17:38:42.120

Reputation: 2 349

Nicely done. +1. – rayryeng - Reinstate Monica – 2016-03-07T17:36:16.163

Wow, works in Matlab too! I didn't know that such indexing is possible – brainkz – 2016-09-13T09:13:30.813

9

R, 29 23 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.

Original answer:

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.

docendo discimus

Posted 2016-02-02T17:38:42.120

Reputation: 211

2x=scan();x[order(!x)] is only 21 bytes long. – Marco Breitig – 2016-02-03T14:44:14.493

@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 – 2016-02-03T15:13:20.277

8

Retina, 15

Simple repeated regex substitution:

+`\b0 (.*)
$1 0

Try it online.

Digital Trauma

Posted 2016-02-02T17:38:42.120

Reputation: 64 644

1I used the same method in my Java answer (if I'm reading this right). :D – Addison Crump – 2016-02-02T20:14:45.057

7

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

Neil

Posted 2016-02-02T17:38:42.120

Reputation: 95 035

6

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 = ''

LOAD_NAME           open
LOAD_CONST          'SourceArray'
CALL_FUNCTION       0,1#  open('SourceArray')
LOAD_ATTR           read
CALL_FUNCTION       0,0#  .read()

LOAD_ATTR           split
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
LOAD_ATTR           pop
LOAD_CONST          0
CALL_FUNCTION       0,1#  list.pop(0)
DUP_TOP
LOAD_CONST          '0'
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 '
LOAD_FAST           no_zeroes
INPLACE_ADD
STORE_FAST          no_zeroes#  no_zeroes = no_zeroes + '0 '
JUMP_ABSOLUTE       13

LOAD_FAST           no_zeroes
PRINT_ITEM          #  print no_zeroes

LOAD_CONST          None
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 = ''
unamed_variable = open('SourceArray').read().split()
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,

Blue

Posted 2016-02-02T17:38:42.120

Reputation: 26 661

Wooow. You cut a ton of time off of that. – Addison Crump – 2016-02-02T19:42:53.687

@VoteToClose that's about 1.5x the speed it ran on my laptop :O Who said Python was that slow? – Blue – 2016-02-02T19:46:36.887

6

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!

Mego

Posted 2016-02-02T17:38:42.120

Reputation: 32 998

It's a bit shorter to use key=0..__eq__ (yes, two dots). – xnor – 2016-02-03T08:28:44.083

@xnor That's neat... How does it work? – Mego – 2016-02-03T08:36:18.183

7

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 – 2016-02-03T08:52:01.123

@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 – 2016-02-03T09:14:18.980

6

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

brainkz

Posted 2016-02-02T17:38:42.120

Reputation: 349

5

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

nimi

Posted 2016-02-02T17:38:42.120

Reputation: 34 639

5

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

sch

Posted 2016-02-02T17:38:42.120

Reputation: 183

4

Javascript, 52 54 51 bytes

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

removed

Posted 2016-02-02T17:38:42.120

Reputation: 2 785

This doesn't work when the input does not contain any zeroes – rink.attendant.6 – 2016-02-02T22:07:33.043

@rink.attendant.6. Thanks, I've updated and still looking for some bytes off :) – removed – 2016-02-02T22:46:03.947

4

Mathematica, 14 bytes

Sort[#,#!=0&]&

alephalpha

Posted 2016-02-02T17:38:42.120

Reputation: 23 988

3Sort[#!=0&] should be enough. – Martin Ender – 2016-02-03T08:21:27.243

4

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

Try it in http://ngn.github.com/apl/web/index.html

Test data: a←1 0 1 2 3 4 0 1 0 0 0 0 1 2 3 4 5

Lobachevsky

Posted 2016-02-02T17:38:42.120

Reputation: 151

1You 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 – 2016-02-03T13:26:37.600

Not so fast. ⍴↑{⍵~0} won't work everywhere, not in APL2000, nor in IBM APL2. – Lobachevsky – 2016-02-07T16:17:53.393

⍴↑{⍵~0} will return an empty vector. ⍴⍴↑{⍵~0} is a (one element vector) zero. – Lobachevsky – 2016-02-08T08:56:45.623

4

Java 7, 78 bytes

void g(int[]a){int c=0;for(int o:a)a[o==0?c:c++]=o;for(;c<a.length;a[c++]=0);}

I'm not sure why the other Java entries are using strings. If you want to filter an integer array, it seems best to use an integer array. This modifies the input in place by keeping two indices, then just filling the remaining slots with zeros.

Marky Markov

Posted 2016-02-02T17:38:42.120

Reputation: 141

Heh, I used it because I felt like it. I think you should be able to declare o with int c=0,o;for(o:a).... You can also convert to Java 8 lambda syntax: a->{int c=0;for(int o:a)a[o==0?c:c++]=o;for(;c<a.length;a[c++]=0);} and state that it expects input as an int array. – Addison Crump – 2016-02-04T20:35:44.660

Wait, scratch the o declaration thingy. But still, java 8 lambda. :D – Addison Crump – 2016-02-04T20:44:45.083

@VoteToClose I thought it had to be self-contained. If I can declare types and stuff elsewhere without counting it, that doesn't seem right. – Marky Markov – 2016-02-04T22:28:06.787

Since this is a function, input is passed to it by a previously executed statement anyways. The lambda can assume an input type, so its essentially the same. – Addison Crump – 2016-02-04T23:00:49.027

3

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.

msh210

Posted 2016-02-02T17:38:42.120

Reputation: 3 094

3

PHP, 73 71 70 52 49 48 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;

MonkeyZeus

Posted 2016-02-02T17:38:42.120

Reputation: 461

1$v==0 can be replaced with !$v, saving you 2 bytes. – Ismael Miguel – 2016-02-02T21:17:34.463

@IsmaelMiguel thanks! – MonkeyZeus – 2016-02-02T21:25:44.893

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 – 2016-02-02T21:41:35.490

2Or foreach($a as$v)$v?print("$v "):$b.="$v ";echo$b; for a more neat way, that looks exactly the same – Ismael Miguel – 2016-02-02T21:49:44.327

1@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 – 2016-02-02T21:54:52.647

@IsmaelMiguel Shaved a few more! – MonkeyZeus – 2016-02-02T22:04:24.777

I would cry as well. Good thing I also practice good coding conventions... Well, as far as Javascript and PHP allow. And I see you keep on improving it! Quite nice the few edges you're cleaning! They were nasty hick-ups I left behind. You deserve more upvotes. – Ismael Miguel – 2016-02-02T22:05:23.417

Sadly, with the last change, your input method to run the code is invalid. However, you can say your code is PHP5.4, since it is now allowed to use POST/GET parameters as input. This allows you to say that your code is PHP4.1 and that you expect that the script is executed through Apache, with the GET key a[]=<value>. This will create your $a array for you. It relies on PHP4.1 directive register_globals that was enabled by default on that version.

– Ismael Miguel – 2016-02-03T09:27:56.607

3

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

coredump

Posted 2016-02-02T17:38:42.120

Reputation: 6 292

3

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.

Digital Trauma

Posted 2016-02-02T17:38:42.120

Reputation: 64 644

@sch Yes, it should be bash - fixed. – Digital Trauma – 2016-02-03T16:24:23.963

@TimmyD yes - thanks for the reminder. – Digital Trauma – 2016-02-03T16:24:40.533

2

JavaScript ES6, 16 bytes

x=>x.sort(t=>!t)

Works on firefox

l4m2

Posted 2016-02-02T17:38:42.120

Reputation: 5 985

2

Ruby, 25 bytes

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

Try it online!

Kirill L.

Posted 2016-02-02T17:38:42.120

Reputation: 6 693

2

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

Luis Mendo

Posted 2016-02-02T17:38:42.120

Reputation: 87 464

2

CJam, 6 bytes

{{!}$}

An anonymous function. Sort using “whether or not an element is zero” as a key.

Lynn

Posted 2016-02-02T17:38:42.120

Reputation: 55 648

2

Seriously, 12 bytes

4,n`Y`M@░)░+

Try it online!

Explanation:

4,n`Y`M@░)░+
4,n           push 4 copies of input
   `Y`M       map logical negate
       @░)    filter (take zeroes) and push to bottom of stack
          ░   filter (take non-zeroes)
           +  append zeroes

Mego

Posted 2016-02-02T17:38:42.120

Reputation: 32 998

2

Swift, 13 bytes

a.sort{$1==0}

scraplesh

Posted 2016-02-02T17:38:42.120

Reputation: 121

2

TeX (Plain format), 160 bytes

Make the 0 character active (that is, make the interpreter process it as a command), then define that command to skip the character and increment a counter. At the end of the string, print as many zeros as were counted.

Save this as zero.tex and give the input through the command line with this command:

pdftex "\def\I{0 1 0 3 2 0 0 8 0 5 0 1 9 4}\input zero"
\def\I{}\newcount\Z\def\L{\loop\advance\Z by-1\ifnum\Z>00 \repeat}
\begingroup\catcode`\013 \def0{\advance\Z by1}
\scantokens\expandafter{\I\empty}\endgroup\L\bye

(Newlines added for clarity)

enter image description here

musarithmia

Posted 2016-02-02T17:38:42.120

Reputation: 531

2

Perl6, 11 bytes

{.sort(!*)}

Produces a Block - which can be called on an array:

{.sort(!*)}.([1,2,0,3]).say

Although it would be more natural (and shorter) to write:

[1,2,0,3].sort(!*).say

How it works: if the perl6 sort routine is called with a block which accepts only one argument, the list elements are sorted according to by($a) cmp by($b). In this case, the block is !*, i.e. a negation of the whatever operator.

I notice that:

  • The example in the question is a class which provides a method, not including boilerplate required to read in
  • The description of the task does not require printing, and, except for the fact that the example prints, implies that an array might be returned

user52889

Posted 2016-02-02T17:38:42.120

Reputation: 211

2

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)

marinus

Posted 2016-02-02T17:38:42.120

Reputation: 30 224

2

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)

TuxCrafting

Posted 2016-02-02T17:38:42.120

Reputation: 4 547

1

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]

Chaos Manor

Posted 2016-02-02T17:38:42.120

Reputation: 521

1

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.

Weijun Zhou

Posted 2016-02-02T17:38:42.120

Reputation: 3 396

1

Pyth, 2 bytes

o!

Test suite

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

hakr14

Posted 2016-02-02T17:38:42.120

Reputation: 1 295

1

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

ngn

Posted 2016-02-02T17:38:42.120

Reputation: 11 449

1

Python 2.7, 31 30 bytes

-1 thanks to dennis

Takes input as array.

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

Khalil

Posted 2016-02-02T17:38:42.120

Reputation: 49

@MuhammadSalman Correct how? The code works, as you can verify in the permalink I left. The function f modifies the array in place. – Dennis – 2018-06-05T18:08:38.233

@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 – 2018-06-05T19:00:46.963

@MuhammadSalman Yes, snippets are disallowed by default. REPL answers are allowed, but they still have to adhere to our defaults for I/O.

– Dennis – 2018-06-06T00:29:57.367

1

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

snail_

Posted 2016-02-02T17:38:42.120

Reputation: 1 982

1

05AB1E, 2 bytes

ΣĀ

Try it online!

Erik the Outgolfer

Posted 2016-02-02T17:38:42.120

Reputation: 38 134

1

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]

Adnan

Posted 2016-02-02T17:38:42.120

Reputation: 41 965

1

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

Addison Crump

Posted 2016-02-02T17:38:42.120

Reputation: 10 763

@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 – 2016-02-02T21:47:17.050

Cool. Space is missing before 0 in last print(). I.e. print("0") should be print(" 0"). Code length is indeed 138 chars. – t0r0X – 2016-02-02T21:49:23.737

@t0r0X I guess that got clipped somehow. ;P – Addison Crump – 2016-02-02T21:50:14.250

1

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}

t0r0X

Posted 2016-02-02T17:38:42.120

Reputation: 153

1

Japt, 8 bytes

Un@!X-!Y

Test it online!

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

ETHproductions

Posted 2016-02-02T17:38:42.120

Reputation: 47 880

1

Clojure/ClojureScript, 18 bytes

#(sort-by zero? %)

MattPutnam

Posted 2016-02-02T17:38:42.120

Reputation: 521

1

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

t0r0X

Posted 2016-02-02T17:38:42.120

Reputation: 153

1Use 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 – 2016-02-02T21:50:55.487

Nah, you take it. c: Keep it in this answer, though. – Addison Crump – 2016-02-02T21:59:44.490

Sorry, I mean to replace the for loop with for(;z!=y.length();)y+=" 0";. – Addison Crump – 2016-02-02T22:01:51.527

You can get rid of ,i=0 now. – Addison Crump – 2016-02-02T22:02:33.007

You can use y=y.replaceAll("( 0)|(0 )","") instead of y=y.replaceAll("0 *","").trim(). – Addison Crump – 2016-02-02T22:16:11.867

Yeah, I realized that after I commented. The suggestion I just put is a byte shorter. :P – Addison Crump – 2016-02-02T22:16:49.140

Shaving another byte: int z=y.length();for(y=y.replaceAll("( 0|0 )","");y.length()<z;)y+=" 0"; – Addison Crump – 2016-02-02T22:28:57.207

And again two. THX for the fun! – t0r0X – 2016-02-02T22:39:41.210

1

Mathematica 33 bytes

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

martin

Posted 2016-02-02T17:38:42.120

Reputation: 1 335

0

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)

12Me21

Posted 2016-02-02T17:38:42.120

Reputation: 6 110

0

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

Addison Crump

Posted 2016-02-02T17:38:42.120

Reputation: 10 763

0

GNU Sed, 25

Score includes +1 for use of -E option.

(Almost) direct port of my Retina answer:

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

Digital Trauma

Posted 2016-02-02T17:38:42.120

Reputation: 64 644

Only GNU sed versions from before this commit (discussion)

– sch – 2016-02-03T12:28:40.493

@sch Dammit - that adds 2 bytes to lots of my sed answers :( – Digital Trauma – 2016-02-03T16:20:12.173

0

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

AdmBorkBork

Posted 2016-02-02T17:38:42.120

Reputation: 41 581

0

sed, 16 bytes

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

it expects a newline delimited stdin input array

mikeserv

Posted 2016-02-02T17:38:42.120

Reputation: 181