# 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

# 05AB1E, 4 bytes

γ€ƶ˜


Try it online! or as a Test Suit

Explanation

γ      # split input into groups of consecutive equal elements
€ƶ    # multiply each number in each sublist by its 1-based index in the sublist
˜   # flatten

• Oof, better than mine. I would've never thought of this. Commented Jun 29, 2018 at 13:25
• I'm not 100% familiar with codegolf byte-counting rules (and googling only found this post which didn't come to a conclusion). While your answer is 4 characters shouldn't it at least be 8 bytes (e.g., utf-16-be without BOM 03 B3 20 AC 01 B6 02 DC) or 9 bytes (utf-8: CE B3 E2 82 AC C6 B6 CB 9C) or 10 bytes (e.g., UTF-16 including the 2 byte BOM) in any non-toy encoding? (Yes, one could construct a toy 8-bit encoding similar to iso-8859 encodings with these 4 symbols represented as 1-byte, but that seems like cheating.) Commented Jun 30, 2018 at 14:10
• @drjimbob Yes, good question. The code can actually be converted to a binary file using the 05AB1E code page. For example, γ€ƶ˜ would be represented as 04 80 8F 98. The code page primarily exists to make writing code easier. To run this 4-byte file, you would need to run the interpreter with the --osabie flag. Commented Jun 30, 2018 at 19:00

scanl1$(*).succ  Try it online! ### Explanation/Ungolfed scanl1 iterates from left over a list using a function which takes the last result and the current element generating a new list with the results, leaving empty lists and singletons "unmodified". (*).succ is the equivalent of \x y-> (x+1)*y Using that function together with scanl1 only works because the increasing sequences (1,2,3,..) start with 1 and either have no preceding element (in which case it's the first element in the list which won't be "modified") or they have a leading 0. # Python 2, 36 bytes c=0 for i in input():c=c*i+i;print c  Try it online! # Husk, 5 4 3 bytes ṁ∫g  Try it online! ### Explanation ṁ∫g -- full function, example input: [1,1,1,0,1] g -- group: [[1,1],[0],[1]] ṁ -- map the following and concatenate result (example with [1,1,1]) ∫ -- | cumulative sum: [1,2,3] -- : [1,2,3,0,1]  Edit history -1 byte by using scanl1 over zipWith -1 byte by porting Dennis's solution # APL (Dyalog Unicode), 5 bytes ⊥⍨¨,\  Try it online! ### How it works ⊥⍨¨,\ ,\ ⍝ Convert to lists of first n elements ⊥⍨¨ ⍝ Map "Count trailing ones" to each list  • Nice usage of the ⊥⍨ trick. Commented Jun 30, 2018 at 18:52 # JavaScript (ES6), 22 bytes Takes input as an array. a=>a.map(s=n=>s=n*-~s)  Try it online! The shorter a=>a.map(n=>a=n*-~a) (20 bytes) would unfortunately fail on [1] because of coercion of singleton arrays to the integer they're holding. # J, 4 bytes #.~\  A port of Bubbler's APL solution Try it online! # J, 8 bytes i.&0@|.\  ## How? It's simply the distance to the preceding 0  \ for each prefix |. reverse it @ and i.&0 find the index of the first 0  Try it online! # Python 2, 39 38 bytes -1 byte thanks to Erik the Outgolfer i=1 for x in input():i*=x;print i;i+=1  Try it online! • I don't think you need the ,. Commented Jun 29, 2018 at 14:13 • @EriktheOutgolfer it looks prettier this way c: – Rod Commented Jun 29, 2018 at 14:20 • Sorry, but sometimes, in life, you have to make sacrifices. Commented Jun 29, 2018 at 14:29 • RIP , you're not in the code anymore, but you will be forever in my heart – Rod Commented Jun 29, 2018 at 14:45 # Jelly, 4 bytes ‘×¥\  Try it online! ‘×¥\ \ Accumulate the input with: ¥ The dyad ‘ Increment the left element × Multiply by the second element (1 or 0) The result always begins with the first element unchanged  # Jelly, 4 bytes ŒgÄF  Try it online! ### How it works ŒgÄF Main link. Argument: A (bit array) Œg Group adjacent, identical bits. Ä Accumulate; take the cumulative sum of each chunk. F Flatten.  • With the group runs quick Erik had suggested this would be three bytes! (If I understood what it would do correctly) Commented Jun 29, 2018 at 15:02 • @dylnan The problem is that it's hard to decide on a behavior for such a quick. :( That's why the quick is still in hiatus. Commented Jun 29, 2018 at 15:07 • There could be multiple quicks for the main possible implementations Commented Jun 29, 2018 at 15:08 # R, 46 31 bytes function(a)sequence(rle(a)$l)*a


Try it online!

sequence, which "mainly exists in reverence to the very early history of R", is quite handy here.

function(a)                       # function, taking a vector as argument
rle(a)$l # take the lengths of the run-length encoding sequence( ) # and generate the list [1:x for x in lengths] *a # multiply by a to maintain 0s, and return  # K (oK), 11 8 bytes Solution: {y*1+x}\  Try it online! Explanation: Iterate over the list. Increment accumulator, multiply by current item (which resets accumulator if item is 0): {y*1+x}\ / the solution { }\ / iterate (\) over lambda function x / accumulator 1+ / add 1 y* / multiply by current item  # TIS, 68 + 33 = 101 bytes Code (68 bytes): @0 MOV UP ACC SUB 47 MOV ACC ANY @1 ADD 1 JRO UP SUB ACC MOV ACC ANY  Layout (33 bytes): 2 1 CC I0 ASCII - O0 NUMERIC - 32  Try it online! Explanation: | Input 0 | Input is given in ASCII (0 is 48, 1 is 49) +--------+------+ | Node 0 | | This node prepares the input data +--------+ | | MOV UP ACC | Read in a character | SUB 47 | Subtract 47 to map [48, 49] to [1, 2] | MOV ACC ANY | Send the 1 or 2 to the next node | | Implicitly wrap back to top of node +--------+------+ | Node 1 | | This node does the incrementing/printing +--------+ | | ADD 1 | Increment counter (starts at zero) | JRO UP | Get value from above, and jump forward that many lines (skip next line or not) | SUB ACC | Reset counter to zero (if input was zero) | MOV ACC ANY | Send the counter value downward to be printed | | Implicitly wrap back to top of node +---------------+ | Output 0 | Output is space-delimited numeric values  # C (gcc), 4544 38 bytes f(a,i)int*a;{while(--i)*++a*=-~a[-1];}  Try it online! Save one byte thanks to Toby Speight! Save 6 bytes by using *= and a smarter while condition. • You can save 1 byte: *(a-1)a[-1] Commented Jul 5, 2018 at 12:52 • Welcome to PPCG! :) Commented Jul 6, 2018 at 9:48 # RAD, 8 bytes (⊢×1+⊣)⍂  Try it online! ## How? • (⊢×1+⊣), if the right argument is 0, return 0, otherwise increment the left argument • ⍂, LTR Scan ((A f B) f C instead of A f (B f C)) , apply this across the array # Jelly, 5 bytes ṛȧ+ɗ\  Try it online! # Haskell, 19 bytes scanl1$((*)=<<).(+)


Try it online!

Explanation: The code is equivalent to scanl1(\b a->(b+a)*a), where b is the current bit and a is the accumulator. scanl1 takes a list, instantiates the first list element as accumulator, and folds over the list and collects the intermediate values in a new list.

Edit: BMO beat me by a few seconds and 4 bytes.

# Wolfram Language (Mathematica), 16 bytes

FoldList[+###2&]


Try it online!

# Japt, 76 5 bytes

åÏ*°X


Try it

## Explanation

åÏ        :Cumulatively reduce
°X     :  Increment the current total (initially 0)
*       :  Multiply by the current element


# Java 8, 55 48 bytes

a->{int p=0,i=0;for(int v:a)a[i++]=v<1?p=0:++p;}


Modifies the input-array instead of returning a new one to save bytes.

-7 bytes thanks to @TimSeguine.

Try it online.

Explanation:

a->{             // Method with integer-array parameter and no return-type
int p=0,       //  Previous integer, starting at 0
i=0;       //  Index-integer, starting at 0
for(int v:a)   //  Loop over the values of the input-array:
a[i++]=v<1?  //   If the current value is 0:
p=0    //    Reset the previous integer to 0
:       //   Else:
++p;}  //    Increase p by 1 first with ++p
//    and set the current item to this new value of p

• You can shave it down to 48: a->{int p=0,i=0;for(int b:a)a[i++]=b<1?p=0:++p;} Commented Jul 2, 2018 at 14:42
• @TimSeguine Thanks! Now that I see it I can't believe I hadn't thought about it myself. Commented Jul 2, 2018 at 14:46
• I was able to get rid of p, but it is the same size :( a->{int i=0;for(int v:a)a[i]+=v*i++<1?0:a[i-2];} Commented Jul 2, 2018 at 15:08

## Shakespeare, 365 bytes

I.Ajax,.Ford,.Act I:.Scene I:.[enter Ajax and Ford]Ajax:Open mind!Scene V:.Ford:Am I nicer than the sum of a big red old cute hard cat a big red old cute joy?Ford:If so,you is the sum of thyself a son!Ford:If not,you is zero!Ford:Open heart!Ajax:you is a big red old cute hard cat.Ajax:Speak mind!Ajax:Open mind!Ford:Am I nicer than zero?Ajax:If so, let us Scene V.


try it here

## less golfed version

I.Ajax,.Ford,.
Act I:.
Scene I:.
[enter Ajax and Ford]
Ajax:Open mind!
Scene V:.
Ford:Am I nicer than the sum of a big red old cute hard cat a big red old cute joy?     <- smallest way to 48 (ascii "0") I could think of
Ford:If so,you is the sum of thyself a son!
Ford:If not,you is zero!
Ford:Open heart!
Ajax:you is a big red old cute hard cat.    <- get value of 32 or space
Ajax:Speak mind!                            <- then output it
Ajax:Open mind!
Ford:Am I nicer than zero?
Ajax:If so, let us Scene V.                 <- loop through inputs


# Gaia, 5 bytes

ẋ+⊣¦_


Try it online!

### Explanation

ẋ+⊣¦_     Full program
ẋ         Split into chunks of equal adjacent values.
¦_     And for each chunk, flattening the result afterwards...
+⊣       Reduce it cumulatively on + (addition); aka cumulative sums


Ugh, I thought SE code fonts were monospace....

• They are monospace... There is a space missing on the first line. Commented Jul 3, 2018 at 7:49
• Look at the edit. It is still misaligned. Commented Jul 3, 2018 at 7:50
• You must be looking from a mobile device or something - It looks fine to me Commented Jul 3, 2018 at 8:01
• @micsthepick I'm not... Commented Jul 3, 2018 at 8:07

# C++, 47 bytes

[](int*a,int*b){for(int c=0;a!=b;)c=*a++*=1+c;}


A lambda that modifies an array in place, given start and end pointers.

Try it online! (requires Javascript)

Generic version at 55 bytes (this works for any container with elements of arithmetic type):

[](auto a,auto b){for(auto c=*a-*a;a!=b;)c=*a++*=1+c;};


# 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 Commented Jul 30, 2018 at 6:51
• ḅ{a₀ᵇ+ᵐ}ᵐc is 2 bytes shorter and should work, right? Commented Jul 30, 2018 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! Commented Aug 3, 2018 at 11:38

# Perl 6, 29 24 18 bytes

-6 bytes thanks to Sean!

*.map:{($+=1)*=$_}


Try it online!

FOR i=1TO LEN(s$) b=MID$(s$,i)>="1 v=-b*v-b ?v NEXT  Takes the input as a string; gives the output as numbers separated by newlines. ### Explanation We read the string s$ and loop i from 1 up to its length.

MID$(s$,i) gets the substring from character i (1-indexed) to the end of the string. If this starts with a 1, it will be lexicographically >= the string "1"; if it starts with a 0, it will not be. So b gets 0 if the character at index i is 0, or -1 if the character is 1.

Next, we update the current value v. If we just read a 0, we want v to become 0; otherwise, we want to increment v by one. In other words, v = (-b) * (v+1); simplifying the math gives the shorter expression seen in the code. Finally, we print v and loop.

# Brain-Flak, 60 bytes

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


Try it online!

# Explanation:

([]){  For each element in the input
{}
<>(())<>  Push a one to the other stack
{ If the element is one,
{}<>({}({}))(<>)  Add the one to a copy of the previous number in the series
}{}  Pop the element
([])}  End loop
{}<>   Pop extra zero
{({}[()]<>)<>}<>   And reverse the output stack, subtracting one from each element