# Consecutive 1-Bits are Incremented

Given a pattern (string or array format) of Bits : [0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]

The tasks is to replace any number of consecutive 1-Bits with an ascending number sequence starting at 1.

Input

• Pattern (can be received as an string or array) Example:
• String: 1001011010110101001
• Array: [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1]

Output

• Ascending number sequence (can be returned as an string or array) Example:
• String: 1 0 0 1 0 1 2 0 1 0 1 2 0 1 0 1 0 0 1
• Array: [1, 0, 0, 1, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 0, 1, 0, 0, 1]

Rules

• (only apply for strings) Input wont contain spaces between 1 and 0
• Assume Input length > 0
• (only apply for strings) Output is separated by space (use any other separator if you need as long as is not a number or a letter from the alphabet)

Example:

Given [0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]
Output [0,1,2,3,0,1,2,0,0,0,1,2,3,4,5,6]

--------------------------------------------------------------------------

Given 0110101111101011011111101011111111
Output 0 1 2 0 1 0 1 2 3 4 5 0 1 0 1 2 0 1 2 3 4 5 6 0 1 0 1 2 3 4 5 6 7 8

---------------------------------------------------------------------------

Given 11111111111101
Output 1 2 3 4 5 6 7 8 9 10 11 12 0 1

Winning criteria: Codegolf

# MATL, 11 10 bytes

0w"@+@*t]x

Try it online!

(-1 byte thanks to Giuseppe)

The obvious "accumulate y(x+y) over the array" approach.

### 16 bytes

n:G~f!-tO<YYw(X<

Try it online!

Longer, more matrix-y approach: get the overall index, broadcast-subtract the indices of all zeros, and take the difference from the index of the nearest zero.

• Do you need D? I removed it and it seems to work fine without it. – Giuseppe Jul 6 '18 at 17:10
• I had 12 bytes porting my R answer with 4#Y'"@:v!]G* – Giuseppe Jul 6 '18 at 17:11
• Indeed I don't, the values will just accumulate in the stack in order. Thanks! (And your R answer's RLE approach is what I too started with, but soon got confused and lost. :) – sundar - Remember Monica Jul 6 '18 at 18:42

# Brachylog, 12 10 bytes

ḅ{a₀ᵇ+ᵐ}ᵐc

Try it online!

(-2 bytes thanks to @Fatalize.)

ḅ             % split input into "blocks" of equal value
{     }ᵐ     % map this predicate on each such block:
a₀ᵇ            % Find all prefixes (initial subsequences) of the block
%  Returns them in increasing order of length
+ᵐ          % Sum the values in each subsequence
% This results in each block being replaced by its cumulative sum values
c    % concatenate the results back into a single array

~c{≤₁a₀ᵇ+ᵐ}ᵐc is temptingly just out of reach at 13 bytes, but I haven't been able to find a shorter way of doing cumulative sum than the 5 byte a₀ᵇ+ᵐ.

• ḅ{+ℕ₁⟦₁|}ᵐc is 1 byte shorter – Fatalize Jul 30 '18 at 6:51
• ḅ{a₀ᵇ+ᵐ}ᵐc is 2 bytes shorter and should work, right? – Fatalize Jul 30 '18 at 6:56
• @Fatalize Yep. I was an idiot, I even mentioned the cumulative sum idea for the alternate solution, but didn't apply it to this one. Thanks! – sundar - Remember Monica Aug 3 '18 at 11:38

# C (gcc), 52 51 bytes

Thanks to ceilingcat for the suggestion.

c;f(char*i){for(;*i;printf("%d ",c=~c*(48-*i++)));}

Try it online!

# PowerShell, 4840 25 bytes

Thanks Mazzy for -8

$args[0]|%{($i=$_*=++$i)}

Try it online!

Takes input as an array numbers. Uses the self-assigning, multiply trick other answers are using and updates everything with a very gross assignment. It then wraps this whole thing in parens to push it to output.

• Given: 'Output ... can be returned as an string or array' ) I think param($p)$a=@();$p|%{$a+=$i=$_*=++$i};$a is enough. 40 bytes – mazzy Jul 2 '18 at 12:55
• 25 bytes by using $args[0] and getting rid of$a -- Try it online! – AdmBorkBork Jul 6 '18 at 12:44

# Retina 0.8.2, 15 bytes

.(?<=(1*))
$.1 Try it online! Link includes test cases. Alternative version, also 15 bytes: .(?<=(1)*)$#1

Try it online! Link includes test cases Explanation:

.

Match the 0s and 1s.

(?<=(1*))
(?<=(1)*)

Count the number of 1s from the current digit backwards. The first one counts by capturing the run of 1s as a subtring, while the second one counts the number of times the 1 was captured.

$.1$#1

Replace the digit with the number of 1s, either via the length of the capture or by the number of captures as appropriate.

# Pyth, 9 bytes

t.u*YhNQZ

Verify all the test cases

t.u*YhNQZ   Implicit: Q=eval(input())

.u    QZ   Cumulative reduce over Q, starting value 0
hN       Increment the current value
*Y         Multiply by the next value
t           Remove 1st element of list, implicit print

# racket, 107 bytes

(λ(i)(let c((x i)(z 0))(if(empty? x)'()(if(= (car x)1)(cons(+ 1 z)(c(cdr x)(+ 1 z)))(cons 0(c(cdr x)0))))))
• Possible space save in = (. – Jonathan Frech Jun 29 '18 at 21:52

# Brain-Flak, 78 bytes

(<>)<>([]){{}{{}<>(({})())<>}([]){{}(<>)<>}{}([])}{}<>([]){{}({}<>)<>([])}<>{}

Try it online!

(<>)<>
([])

{

{}

{
{}<>(({})())<>
}

([])
{

{}(<>)<>
}

{}

([])

}{}<>

([])

{
{}({}<>)<>([])
}<>{}

## Java, 65 bytes

void a(int[]q){for(int i=1;i<q.length;i++)q[i]+=q[i]>0?q[i-1]:0;}

# Julia 0.6, 28 bytes

t->(x=0;[(x=(x+y)y)for y=t])

Try it online!

# C++, 4645 41 bytes

Generic lambda, any int container.

[](auto&a){int p=0;for(int&i:a)p=i*=p+i;}

Saved a byte with the *= operator, saved 4 bytes by removing unneeded braces and parenthesis.

Note: The p+i part can be replaced with p+1 or ++p, I'm not sure why I did p+i but it wouldn't save any bytes to change it.

Old:

[](auto&a){int p=0;for(int&i:a){p=i=i*(p+i);}}

# Z80Golf, 12 bytes

00000000: cd03 8030 0176 b928 0180 47d5            ...0.v.(..G.

I/O format is byte values.

start:
call $8003 ; cd 03 80 ; a = getchar() jr nc, skip ; 30 01 ; if not EOF, skip halt ; 76 ; terminate program skip: cp c ; b9 ; compare a and 0 jr z, skip2 ; 28 01 ; if a == 0, skip add b ; 80 ; a += b skip2: ld b, a ; 47 ; b = a push de ; d5 ; call putchar with return address 0 The final push de pushes the address 0 to the stack, so when putchar returns, PC goes back to the start of the program. # Jelly, 6 bytes ŒgJ€F× Try it online! # Python 2, 52 46 bytes f=lambda x,y=1:x and[y*x[0]]+f(x[1:],y*x[0]+1) Saved 6 bytes thanks to Jo King and Rod! # C# (Visual C# Interactive Compiler), 75 bytes Golfed Try it online! a=>{for(int i=1;i<a.Length;i++)if(a[i-1]>0&a[i]>0)a[i]=a[i-1]+1;return a;}; Ungolfed a => { for( int i = 1; i < a.Length; i++ ) if( a[ i - 1 ] > 0 & a[ i ] > 0 ) a[ i ] = a[ i - 1 ] + 1; return a; }; Full code using System; namespace Namespace { class Program { static void Main( String[] args ) { Func<Int32[], Int32[]> f = a => { for( int i = 1; i < a.Length; i++ ) if( a[ i - 1 ] > 0 & a[ i ] > 0 ) a[ i ] = a[ i - 1 ] + 1; return a; }; List<Int32[]> testCases = new List<Int32[]>() { new Int32[] { 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 }, new Int32[] { 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, new Int32[] { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 }, }; foreach( Int32[] testCase in testCases ) { Console.WriteLine($"{{ {String.Join(", ", testCase)} }}\n{f( testCase )}" );
}

}
}
}

Releases

• v1.0 - 75 bytes - Initial solution.

Notes

• None

_ b _ F >
b
dab
t
dot
(
t b
t
X
X dip
<
b X (
/
<
< b
0
t 0 b
>

0
.
dip <
< b
t b
x
x .
H
b b x >
b
G
t H /
b b
F
<
F G
_
_ b
<

Try it online!

# Python 2.7, 217 Bytes

def f(d):
c = 0
r = []
for e in d:
if e == 1:
r.append(1 + c)
c += 1
else:
c = 0
r.append(0)
return r

I'm new so.

• Welcome to the site. You can save bytes here by removing whitespace around operators, and using ; instead of newlines for indentation. You can also save bytes by using += instead of append. Lastly instead of appending 1+c and then incrementing c you can increment c first and then append it. Here's a link with all those edits made. Anyway hope you have fun here! – Wheat Wizard Jul 2 '18 at 16:17

var i=0
readLine()?.forEach{(it-48).toInt().let{c->i=i*c+c;print("$i ")}} Try it online! # Perl 5-p, 22 20 bytes -2 bytes thanks to @DomHastings s/./$i=$&*++$i.$"/ge Try it online! Method: Replace each character with itself multiplied by the incremented value of$i, then store that value back in $i. Thus,$i starts at 0 (undef) and gets reset to 0 every time the character in the bit string is a 0.

Finally, append a space to the result of the above step to make the output format correct.

• Nice again! You can save 2 bytes by dropping the ( ) as the trailing space is just ignored! – Dom Hastings Jul 4 '18 at 14:39
• @Abigail In some languages, that may be the case, but in Perl, ++ has a higher precedence than either = or * and will always execute first. – Xcali Jul 5 '18 at 16:12

# Lua, 63 54 bytes

function f(j)for i=2,#j do j[i]=j[i]*(j[i-1]+1)end end

Written by Jo King. Try it online!

### Explanation

function f(j) -- declares the function 'f' that will receive a variable 'j' (we know it's a table)
for i=2,#j do -- from 2 to the number of elements in j
j[i]=j[i]*(j[i-1]+1) -- change the current element of j to itself
(j[i-1]+1) -- multiplied by the one before it plus one
end
end

Original (invalid) in expanded form:

for i=2,#input do -- a loop that goes from 2 to the number of elements in the input table
if input[i] == 0 then -- if the element at 'i' is 0
input[i] = 0 -- then keep it as 0
else
input[i] = input[i-1]+1 -- change it to the element that comes before + 1
end
end

Feel free to ask or suggest anything!

• The input can't be a pre-declared variable, otherwise this is an incomplete snippet. Your submission can be either a full program taking input from STDIN or equivalent, or a function. – Jo King Jul 22 '18 at 8:59
• Here's a 54 byte function that modifies its argument in-place. For more standards, you can check out the Standard I/O methods for submissions – Jo King Jul 22 '18 at 10:05
• @JoKing oh thank you for the correction, now I think I got how it works. But what do I do? Remove the post or edit it with your code? – Visckmart Jul 22 '18 at 14:28
• You can use my code, sure – Jo King Jul 22 '18 at 21:39

# PHP, 41 bytes

while(~$c=$argv[++$i])echo$k=++$k*$c," ";

takes input from command line arguments; prints string.

Run with -r.

# C++ (gcc), 37 bytes

[](auto&a){for(int&i:a)i*=*(&i-1)+1;}

Try it online!

A lambda function which works with any int container supporting range-based for loops.

# Scheme, 91 61 bytes

(lambda(l)(define x 0)(map(lambda(n)(set! x(* n(+ 1 x)))x)l))

Try it online!

# C# (.NET Core), 74 70 bytes

a=>{int i=0;var s="";foreach(var c in a)s+=(i=c/49*-~i)+" ";return s;}

Try it online!

-4 bytes: changed format of foreach loop (thanks to recursive)

Ungolfed:

a => {
int i = 0;              // initialize i to 0
var s = "";             // initialize s
foreach(var c in a)     // for each character in a
s +=                    // append to s:
( i =                   // i, where i is:
c / 49                  // ascii representation of c divided by 49 (identifies 0 or 1)
* -~i )             // multiplied by the negative bitwise complement of i (essentially, one more than current i)
+ " ";                      // a space
return s;               // output s to console
}
• Found 4 bytes to shave. tio.run/… – recursive Nov 1 '18 at 18:54

# Clojure, 62 bytes

#(map-indexed(fn[i n](*(+(.indexOf(reverse(take i %))0)1)n))%)

Use as follows:

(println #(...) [0 1 1 1 0 1])

where #(...) is the answer (anonymous function).

# Forth (gforth), 48 bytes

: f 0 tuck do 1+ over i + c@ '0 - * dup . loop ;

Try it online!

### Code Explanation

: f                \ start a new word definition
0 tuck           \ set up a loop and also stick a 0 on the stack to use as a counter
do               \ loop from 0 to string-length - 1
1+             \ add 1 to counter
over i +       \ get the address of the next character
c@             \ get the ascii value for that character
'0 -           \ subtract ascii 0 (48) from the value
*              \ multiply counter by the result (change counter to 0 if char is '0')
dup .          \ print the current sequence
loop             \ end the loop
;                  \ end word definition