# 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

## Retina, 14 bytes

rv0|(1)+
$#1¶  Try it online! # C (gcc), 5752 51 bytes f(a,l,c,i)int*a;{for(c=i=0;i<l;)a[i++]=c=a[i]*-~c;}  Port of Arnauld's JavaScript answer, modifies the array in-place. Try it online here. • Wouldn't it be more accurate to say this is K&R C? Commented Jul 1, 2018 at 13:14 • Possibly, but that would be true of a lot of answers. I'm no expert, but it's entirely possible it's not even valid K&R C. The thing is, we don't really care about the language standards on this site. If gcc allows you to mix K&R C with more modern stuff, then it's valid C for the purposes of golfing because gcc will compile it. See also: codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c Commented Jul 1, 2018 at 14:09 • I didn't realize until searching just now that C11 still supports the old identifier list function syntax, so nevermind. But your point holds regardless. Commented Jul 2, 2018 at 12:30 • Suggest f(a,l,c)int*a;{for(c=0;l--;)c=*a++*=c+1;} – user77406 Commented Nov 1, 2018 at 11:05 ## Java, 65 bytes void a(int[]q){for(int i=1;i<q.length;i++)q[i]+=q[i]>0?q[i-1]:0;} # 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. Commented Jul 6, 2018 at 17:10 • I had 12 bytes porting my R answer with 4#Y'"@:v!]G* Commented Jul 6, 2018 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. :) Commented Jul 6, 2018 at 18:42 ## Zig, 65 bytes fn f(b:[]u8)[]u8{for(b)|_,i|{if(i>0)b[i]+=b[i-1]*b[i];}return b;}  Expanded version fn f(b:[]u8) []u8 { // Foreach loop where only index is used. for(b) |_,i| { // First value is always going to be 0 or 1, if(i > 0) // b[1] will either be 0 or 1, // so this is basically an if statement // that we can use to reset the count. b[i] += b[i-1] * b[i]; } return b; }  I would add a Try it online!, but their compiler seems to lack some crucial language features. (Language still being in development and all that) And I am not going to attempt to make it compatible through trial and error. But you can copy paste this into Zig playground (Confirmed to work as of writing this post) const std = @import("std"); fn f(b:[]u8)[]u8{for(b)|_,i|{if(i>0)b[i]+=b[i-1]*b[i];}return b;} pub fn main() anyerror!void { var bits = [_]u8{0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1}; var array = f(bits[0..]); try std.io.getStdOut().writer().print("{any}\n", .{array}); }  • Welcome to Code Golf, and nice first answer! Commented Aug 17, 2021 at 13:38 # Vyxal, 4 bytes Ġv¦f  Try it Online! -6 thanks to Lyxal. Ġ # Group consecutive identical elements v¦ # Take the cumulative sum of each f # Flatten the result  • there is Commented Mar 9, 2023 at 1:22 # Thunno, $$\ 6 \log_{256}(96) \approx \$$ 4.94 bytes zy.z(S  Attempt This Online! #### Explanation zy # Group by consecutive . # Apply to each: z( # Cumulative sums S # Flatten  # K (ngn/k), 11 9 bytes (*/+\|,)\  Try it online! -2 bytes thanks to ovs • Shorter with a lambda but tacit is fun. – doug Commented Mar 10, 2023 at 21:31 • Isn't 1+\/ just +\ ? – ovs Commented Mar 11, 2023 at 9:12 • That seems to hang for me. I that turns it into converge on sum scan which is monadic. – doug Commented Mar 12, 2023 at 3:37 • (*/+\|,)\  – ovs Commented Mar 12, 2023 at 8:33 • Oh, sorry. I misread what you wrote. – doug Commented Mar 12, 2023 at 9:14 # Jelly, 6 bytes ŒgJ€F×  Try it online! # 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 = (. Commented Jun 29, 2018 at 21:52 # Brain-Flak, 78 bytes (<>)<>([]){{}{{}<>(({})())<>}([]){{}(<>)<>}{}([])}{}<>([]){{}({}<>)<>([])}<>{}  Try it online! Readable version: (<>)<> ([]) { {} { {}<>(({})())<> } ([]) { {}(<>)<> } {} ([]) }{}<> ([]) { {}({}<>)<>([]) }<>{}  # 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);}}  # 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! # Arturo, 22 bytes $=>[0map&=>[<=&*<=1+]]


Try it

$=>[ ; a function, assign input to & 0 ; push 0 map&=>[ ; map over input, assign current elt to & 1+ ; increment tos <= ; dup &* ; multiply by current elt <= ; dup ] ; end map ] ; end function  # TI-Basic, 25 bytes Prompt B For(I,1,dim(⁻B ⁻B(I)(Ans+1 Disp Ans End  Input is taken as a list. Output is as numbers separated by newlines. # Nibbles, 2.5 bytes (5 nibbles) =$+*  =$+* # full function =\$+*$@$    # (with implicit arguments shown):
=\          # scan from left over
$# input # with function: + # add$    #   each element
#   to
*       #   product of
$# each element # and @ # result so far  # BQN, 6 bytes (×+⊢)  Try it at BQN online! ### Explanation (×+⊢) ( ) Left scan on this function: + Add ⊢ each element to × the product of the element and the previous intermediate value  # KamilaLisp v0.2, 14 (APL SBCS) $(⍀.←[+ * #1])


Equivalent to $(scanl1[+ * #1]). # Thunno 2S, 4 bytes ġıż×  Attempt This Online! #### Explanation ġıż× # Implicit input ġ # Group consecutive items ı # Map over this list of lists: ż # Push [1..length] without popping × # Multiply the two lists elementwise # Implicit output, summed (flattened)  # 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

# Dodos, 152 bytes

	_ 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! Commented Jul 2, 2018 at 16:17

# Kotlin, 73 bytes

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! Commented Jul 4, 2018 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. Commented Jul 5, 2018 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
Commented Jul 22, 2018 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
Commented Jul 22, 2018 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? Commented Jul 22, 2018 at 14:28
• You can use my code, sure
– Jo King
Commented Jul 22, 2018 at 21:39

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