# Halve the falses

Given a non-empty array of 0 and 1, halve the lengths of the runs of 0.

# Input

An array of 0 and 1. Acceptable format:

• Real array in your language
• Linefeed-separated string of 0 and 1
• Contiguous string of 0 and 1
• Any other reasonable format

For example, the following three inputs are all acceptable:

• [1, 0, 0, 1]
• "1\n0\n0\n1" (where \n is a linefeed U+000A)
• "1001"

You may assume that the runs of 0 will have even length.

# Output

An array of 0 and 1, in the acceptable formats above.

# Testcases

input ↦ output
[1,0,0,1,0,0,1] ↦ [1,0,1,0,1]
[1,1,0,0,1,1,0,0,1] ↦ [1,1,0,1,1,0,1]
[1,1,0,0,1,1,1,0,0,1,1] ↦ [1,1,0,1,1,1,0,1,1]
[1,1,1] ↦ [1,1,1]
[0,0,1] ↦ [0,1]
[0,0] ↦ [0]
[1,1,1,0,0,0,0,1,1,1,1,0,0,1,0,0,1,1,0,0,1,1,1,1,0,0,1,0,0] ↦ [1,1,1,0,0,1,1,1,1,0,1,0,1,1,0,1,1,1,1,0,1,0]


# Scoring

This is . Shortest answer in bytes wins.

Standard loopholes apply.

• In the last testcase, don't the runs of zeroes not have even length? May 3, 2017 at 11:26
• @OldBunny2800 Read the test case carefully; the 0-runs have lengths 4, 2, 2, 2, 2, and 2. May 3, 2017 at 12:21
• Can we take true and false instead of 1 and 0? May 3, 2017 at 18:13
• @Cyoce which language? May 3, 2017 at 18:15
• @LeakyNun Ruby, which considers 0 to be truthy. May 3, 2017 at 18:16

## Retina, 4 bytes

00
0


Try it online!

• This one will be hard to beat.
May 3, 2017 at 10:15
• @Adám I'd say impossible to beat. May 3, 2017 at 11:13
Jun 27, 2017 at 10:07

# 05AB1E, 5 bytes

00¤.:


Try it online!

Explanation

00     # push 00
¤    # tail, pushes 0
.:  # replace

• That was easy; why didn't I think of that? May 3, 2017 at 7:09
• 00 is weird behavior... May 3, 2017 at 10:45
• @EriktheOutgolfer: Sequential digits are concatenated to form a number, so 11 is eleven and not 1,1. A side effect of that is that 00 becomes 00 instead of 0,0 :) May 3, 2017 at 10:48
• @Emigna I'd have expected it to become 0 or 0 0 instead, but whatever. May 3, 2017 at 10:56

f(0:0:r)=0:f r
f(x:r)=x:f r
f e=e


Try it online! Usage: f[1,1,0,0,1,1,0,0,1]. Iterates over the list and replaces two consecutive zeros by one zero.

• I feel that this can be forked to Prolog May 3, 2017 at 7:20

# C (gcc), 35 bytes

f(char*s){while(*s)putchar(*s),*s++-48?:s++;}


48 is the ascii code of '0'

better version 43 bytes as suggested by Neil

f(char*s){while(*s)putchar(*s),s+=2-*s%2;}


another one 40 byte this time (again as suggested by Neil & VisualMelon) :)

f(char*s){for(;*s;s+=50-*s)putchar(*s);}


and then 35 bytes thanks to Khaled.K

f(char*s){*s&&f(s+50-putchar(*s));}


Try it online!

• Would s+=2-*s%2 work?
– Neil
May 3, 2017 at 9:40
• If I've counted correctly I think for(;*s;s+=2-*s%2)putchar(*s); saves another byte.
– Neil
May 3, 2017 at 10:06
• What would be wrong with s+=50-*s? Not done C for ages and don't want to embarrass myself by invoking undefined behaviour (coming from C# where there is none) May 3, 2017 at 13:55
• Looking at the putchar docs, can you do f(char*s){for(;*s;s+=50-putchar(*s));} ? May 3, 2017 at 15:04
• You can save 5 bytes by making it recursive f(char*s){*s&&f(s+50-putchar(*s));} May 3, 2017 at 16:19

# sed, 8 bytes

s/00/0/g


Try it online!

• @boboquack Doesn't work, since it would always replace a run of 0s with 0. May 3, 2017 at 11:02
• @EriktheOutgolfer No, it does just halve the length of runs of 0's: tio.run/##K05N@f@/WN/AQN9AP/3/fwMwAAA Jan 17 at 15:15

# Octave, 22 bytes

@(s)strrep(s,'00','0')


Verify all test cases here.

This is an anonymous function taking a string on the format '1001000011' as input, and replaces two consecutive zeros with a single zero.

f(h:t)=h:f(drop(1-h)t)
f e=e


Try it online!

Recursively takes the first element, dropping the second one if the first one is zero, until the list of empty. If the first entry is h, then the first 1-h are dropped from the remainder.

# Java, 50 bytes

String f(String s){return s.replaceAll("00","0");}


Try Online

• A very good input choice! By the way, if you're interested in switching to a Java 8+ solution, you could use a lambda: s->s.replaceAll("00","0"). Dec 12, 2017 at 6:05
• Even better, use replace instead of replaceAll to save 3 bytes Apr 17, 2019 at 17:08
• @BenjaminUrquhart replace will only replace the first occurrence Apr 21, 2019 at 8:49
• @Khaled.K in javascript, yes. In java, it replaces all occurrences Apr 21, 2019 at 12:39
• @BenjaminUrquhart is indeed correct, both replace and replaceAll replace all occurrences. The difference is that replaceAll supports regex. To replace the first occurrence there is the replaceFirst method (also supporting regex). I personally think Java's replace is the worst-named method there is in Java. Better would be if replace was called replaceAll and replaceAll was called replaceAllWithRegex or something along those lines.. :/ Jan 14 at 16:32

# Japt, 7 6 5 bytes

d'0²0


Try it online!

Simply replaces each run of two zeroes in the input by one zero. Uses string input (i.e. "1001001").

• Nice! You don't even need the ' I think May 3, 2017 at 11:22
• Ooh, you can save another byte by replacing "00" with '0² :-) May 3, 2017 at 12:21
• Well, that's weird. Thanks though!
– Luke
May 3, 2017 at 13:14

## Alice, 13 bytes

/oe00/
@iS0e\


Try it online!

### Explanation

/.../
@...\


This is a simple template for linear programs which operate entirely in Ordinal mode. The initial / reflects the IP to move south east and then it bounces diagonally up and down through the code until the mirrors at the end. Those simply offset the position by one so that on the way back the IP traverses the remaining cells. Reading the code in this zigzag fashion it becomes:

ie00e0So@


This is a simple string substitution:

i   Read all input.
e   Push an empty string.
00  Append two zeros to create the string "00".
e   Push an empty string.
0   Append a zero to create the string "0".
S   Substitute all occurrences of "00" in the input with "0".
o   Output the result.
@   Terminate the program.


There are a few other ways to push the two strings, e.g. '00'0 or e000t, but I haven't found anything that beats 5 bytes there (and I'd have to shave off two bytes to be able to shorten the program).

• Looks like you fell in love with Alice recently... May 3, 2017 at 7:55
• @LeakyNun Please don't tell my wife... May 3, 2017 at 10:40
• @MartinEnder I'm gonna tell that to Mrs. Ender! May 3, 2017 at 11:02

# Jelly, 8 bytes

ṣ1j1,1m2


Try it online!

Possibly other answers in languages without a .replace() or similar could use this trick.

Explanation

ṣ1j1,1m2 - (duplicates the 1s, then halves all lengths)
ṣ1       - split by the element 1
j1,1   - join the elements with the two-element list 1,1
m2 - get every second element


# V, 4 bytes

òf0x


Try it online!

ò    ' Recursively (until we error)
f0  ' Go to the next zero (errors when there are no zeros left)
x ' Delete it


# sed, 8 6 bytes

n;/0/d


Try it online!

Takes a linefeed-separated string of 0 and 1.

n skips a line, and /0/d deletes a line if it has a zero in it. This has the net effect of deleting every 0 on an even-numbered line. Since any even-length contiguous list of 0 has the same number of even-numbered and odd-numbered lines, this has the effect of halving the length of every run of 0.

# Prolog (SWI), 42 bytes

[0,0|T]*[0|R]:-T*R.
[H|T]*[H|R]:-T*R.
H*H.


Try it online!

• A prolog answer, but not what I expected... May 3, 2017 at 8:26
• Nice trick to use the * operator. May 3, 2017 at 8:28

<?=strtr($argn,["00"=>0]);  simply replace all 00 by 0. # Lua, 33 bytes print((io.read():gsub("00","0")))  Takes a string via input and condenses double zeros. Easy. # Perl 5, 7+1(-p flag)=8 bytes <>if/0/  Takes input as newline separated numbers. Skips the next line if it sees a zero. # Alice, 12 10 bytes 2 bytes saved thanks to Martin Ender i.h%.7%$io


Try it online!

### Explanation

This is a 1-D code operating in cardinal mode, so it's easy to follow its flow:

i                   Read a byte from input (pushes -1 on EOF)
.h                 Duplicate it and add 1 to the copy
%                Compute n%(n+1). This will exit with an error on n==-1
and return n for any non-negative n.
.7%             Duplicate the input again and compute its value modulo 7
This returns 6 for '0' (unicode value 48) and 0 for '1'
(unicode value 49)
\$i           If this last result was not 0, input another number.
This ignores every other '0' in the input
and moves to the following number (another '0')
o          Output the last byte read

At the end, wrap back to the beginning of the line

• You can actually save two more bytes with i.h%... May 4, 2017 at 20:25
• @MartinEnder you're an evil person, going around teaching people to play dirty... :D
– Leo
May 5, 2017 at 10:09

# Jelly, 4 bytes

¹‘ƭƇ


Try it online!

## Explanation

¹‘ƭƇ   Main monadic link
Ƈ   Filter by
ƭ      Every time this is called, switch between
¹          doing nothing and


# Husk, 4 bytes

fG=¹


Try it online!

How?
The Husk scanl command (G) applies a function to each element of a list and the result-so-far. The initial result-so-far is set to the first element.

In this case, used with the eq (=) function, it checks whether each element is equal to the result-so-far. For runs of 1, this will always output 1 (truthy). Now, the first of any run of 0s will be 0 (falsy), of course; then, the next result will be 1 (since 0 is equal to the result-so-far), and then 0, and so on, alternating 0s at odd positions in the run and 1s at even positions, until the end of the run. Since there are always an even number of 0s in each run, then last result-so-far must be 1: so, when we enter the next run of 1s, the first result will be 1 (truthy) again, and so on...

So: runs of 0s get alternating 0 and 1, and runs of 1s always get 1, and we just need to filter (f) the input list (¹) by this.

# Java, 131 123 bytes

int[]f(int[]a){int c=0,i=0,l=a.length;for(int x:a)c+=1-x;int[]r=new int[l-c/2];for(c=0;c<l;c+=2-a[c])r[i++]=a[c];return r;}


Try it online!

# JavaScript (ES6), 26 21 bytes

Takes the input as a string and returns a string.

s=>s.replace(/00/g,0)


## Try It

f=
s=>s.replace(/00/g,0)
console.log(f("1001001")) // "10101"
console.log(f("110011001")) // "1101101"
console.log(f("11001110011")) // "110111011"
console.log(f("111")) // "111"
console.log(f("001")) // "01"
console.log(f("00")) // "0"
console.log(f("11100001111001001100111100100")) // "1110011110101101111010"
<input id=i><pre id=o>

# Mathematica, 24 bytes

StringReplace["00"->"0"]


A function that expects a string of "0"s and "1"s and returns a similar string. Self-explanatory syntax. Mathematica has lots of transformation builtins; the key is to use one that transforms every relevant subexpression (unlike /.) but only passes through the expression once (unlike //.).

# MATL, 5 bytes

FFOZt


Try it online!

### Explanation

This is similar to Stewie Griffin's Octave answer:

FF     % Push [0 0]
O      % Push 0
Zt     % Implicitly take input. Replace [0 0] by 0. Implicitly display


# 8 bytes

vy~f2L)(


This avoids the string/array replacement builtin.

Try it online!

### Explanation

Consider input [1,0,0,1,0,0,1] as an example:

v      % Concatenate stack (which is empty): pushes []
% STACK: []
y      % Implicit input. Duplicate from below
% STACK: [1,0,0,1,0,0,1], [], [1,0,0,1,0,0,1]
~f     % Negate, find: gives indices of zeros
% STACK: [1,0,0,1,0,0,1], [], [2,3,5,6]
2L     % Push [2,2,1i]. As an index, this is interpreted as 2:2:end
% STACK: [1,0,0,1,0,0,1], [], [2,3,5,6], [2,2,1i]
)      % Reference indexing. This selects the even-indexed entries
% STACK: [1,0,0,1,0,0,1], [], [3,6]
(      % Assignment indexing. This deletes the specified entries
% (assigns them the empty array). Implicitly display
% STACK: [1,0,1,0,1]


# Pip, 5 bytes

aR00i


Takes a string of 0s and 1s. Try it online!

### Explanation

Beating Jelly? Inconceivable!

a      Take the first command-line argument
R     and replace
00   00 (an integer literal, so it doesn't need quotes)
i  with i (variable preinitialized to 0)
Autoprint

• Not beating Jelly anymore ;) Feb 15, 2021 at 22:38

# R, 21 bytes

function(n)n[n+1:0>0]


Try it online!

• Ah, this better leverages the fact that runs of zero are even length! Very nice. Jan 14 at 13:25

# Brachylog, 10 bytes

ḅ{cẹ|ḍh}ᵐc


Try it online!

Not sure this is optimal yet…

### Explanation

This exploits the bug that c on a list of integers that has leading zeroes will fail.

ḅ               Blocks; group consecutive equal elements together
{     }ᵐ       Map on each block:
c               It is possible to concatenate the block into an int (i.e. it contains 1s)
ẹ              Split it again into a list of 1s
|             Else
ḍh           Dichotomize and take the head
c      Concatenate the blocks into a single list

• How is that a bug? May 3, 2017 at 7:44
• @LeakyNun We should be able to concatenate [0,0,4,2] into 42. Leading zeroes make it fail right now because it's here to prevent infinite leading zeroes when the Input is a variable, but here the Input is fully grounded so that limitation shouldn't exist. May 3, 2017 at 7:46
• Would you write a Prolog answer? May 3, 2017 at 7:50

# Python (list I/O), 36 bytes

f=lambda l:l and l[:1]+f(l[2-l[0]:])


Try it online!

Recursively takes the first element, then removes the remaining one if the first one was zero.

38 bytes:

lambda l:eval(l.replace('0, 0','0'))


Try it online This takes a Python list and outputs a Python list by doing replacement on its string representation. String I/O would allow a more direct and shorter solution, such as

lambda s:s.replace('00','0')


for '1001' format.

• The first answer with format specified, nice. May 3, 2017 at 7:59
• String I/O is allowed. lambda s:s.replace('00','0') should be fine. May 3, 2017 at 10:49

# ///, 11 bytes

/00/a//a/0/<input goes here>


Try it online!

Fun fact: /00/0/<input> won't work, because it reduces 0000 to 0. Hence the a-substitute.

# APL (Dyalog), 9 bytes

'00'⎕R'0'


Try it online!

• It says DOMAIN ERROR: I-Beam function 7160 has been withdrawn Aug 14, 2020 at 14:50