Consecutive 1-Bits are Incremented

36

5

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

Luis felipe De jesus Munoz

Posted 2018-06-29T12:59:37.617

Reputation: 9 639

Answers

19

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

Emigna

Posted 2018-06-29T12:59:37.617

Reputation: 50 798

1Oof, better than mine. I would've never thought of this. – Magic Octopus Urn – 2018-06-29T13:25:24.627

3

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

– dr jimbob – 2018-06-30T14:10:43.583

6

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

– Adnan – 2018-06-30T19:00:18.323

18

Haskell, 15 bytes

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.

ბიმო

Posted 2018-06-29T12:59:37.617

Reputation: 15 345

15

Python 2, 36 bytes

c=0
for i in input():c=c*i+i;print c

Try it online!

Erik the Outgolfer

Posted 2018-06-29T12:59:37.617

Reputation: 38 134

14

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

ბიმო

Posted 2018-06-29T12:59:37.617

Reputation: 15 345

12

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

Bubbler

Posted 2018-06-29T12:59:37.617

Reputation: 16 616

Nice usage of the ⊥⍨ trick. – Zacharý – 2018-06-30T18:52:45.617

11

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.

Arnauld

Posted 2018-06-29T12:59:37.617

Reputation: 111 334

10

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!

Galen Ivanov

Posted 2018-06-29T12:59:37.617

Reputation: 13 815

8

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!

Rod

Posted 2018-06-29T12:59:37.617

Reputation: 17 588

1I don't think you need the ,. – Erik the Outgolfer – 2018-06-29T14:13:02.100

@EriktheOutgolfer it looks prettier this way c: – Rod – 2018-06-29T14:20:28.737

1Sorry, but sometimes, in life, you have to make sacrifices. – Erik the Outgolfer – 2018-06-29T14:29:05.373

9RIP , you're not in the code anymore, but you will be forever in my heart – Rod – 2018-06-29T14:45:27.247

6

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

streetster

Posted 2018-06-29T12:59:37.617

Reputation: 3 635

6

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

dylnan

Posted 2018-06-29T12:59:37.617

Reputation: 4 993

5

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

Giuseppe

Posted 2018-06-29T12:59:37.617

Reputation: 21 077

5

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.

Dennis

Posted 2018-06-29T12:59:37.617

Reputation: 196 637

With the group runs quick Erik had suggested this would be three bytes! (If I understood what it would do correctly) – dylnan – 2018-06-29T15:02:58.163

@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. – Erik the Outgolfer – 2018-06-29T15:07:12.207

There could be multiple quicks for the main possible implementations – dylnan – 2018-06-29T15:08:44.300

5

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

Zacharý

Posted 2018-06-29T12:59:37.617

Reputation: 5 710

4

Perl 6, 29 24 18 bytes

-6 bytes thanks to Sean!

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

Try it online!

The inner function could by ($+=1)*=*, but then the anonymous variable would persist across function calls. We get by this by wrapping it in an explicit code block.

Explanation:

*.map:               # Map the array to
      {($+=1)    }   # The anonymous variable incremented
             *=$_    # Multiplied by the element

Jo King

Posted 2018-06-29T12:59:37.617

Reputation: 38 234

I got the same basic approach down to 16 bytes: *.map(($+=1)*=*). This solution has the proviso that the state variable $ persists across calls to the function, so if the final element passed to one call and the first element passed to the next call are both nonzero, then the counting will start with the wrong number. – Sean – 2018-10-31T23:31:21.210

@Sean, Yeah I remember struggling with that when I originally answered. Fortunately I've learned a way around that since then – Jo King – 2018-11-01T00:15:44.340

You can knock one more byte off: *.map:{...}. – Sean – 2018-11-01T00:19:58.833

4

Japt, 7 6 5 bytes

åÏ*°X

Try it


Explanation

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

Shaggy

Posted 2018-06-29T12:59:37.617

Reputation: 24 623

4

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`

Kevin Cruijssen

Posted 2018-06-29T12:59:37.617

Reputation: 67 575

1You can shave it down to 48: a->{int p=0,i=0;for(int b:a)a[i++]=b<1?p=0:++p;} – Tim Seguine – 2018-07-02T14:42:03.787

@TimSeguine Thanks! Now that I see it I can't believe I hadn't thought about it myself. – Kevin Cruijssen – 2018-07-02T14:46:22.140

1I 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];} – Tim Seguine – 2018-07-02T15:08:44.480

4

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

Mr. Xcoder

Posted 2018-06-29T12:59:37.617

Reputation: 39 774

They are monospace... There is a space missing on the first line. – micsthepick – 2018-07-03T07:49:36.530

Look at the edit. It is still misaligned. – Mr. Xcoder – 2018-07-03T07:50:24.990

You must be looking from a mobile device or something - It looks fine to me – micsthepick – 2018-07-03T08:01:50.393

@micsthepick I'm not...

– Mr. Xcoder – 2018-07-03T08:07:13.973

4

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

Phlarx

Posted 2018-06-29T12:59:37.617

Reputation: 1 366

4

C (gcc), 45 44 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.

Matej Mulej

Posted 2018-06-29T12:59:37.617

Reputation: 101

You can save 1 byte: *(a-1)a[-1] – Toby Speight – 2018-07-05T12:52:07.053

Welcome to PPCG! :) – Shaggy – 2018-07-06T09:48:21.850

3

Jelly, 5 bytes

ṛȧ+ɗ\

Try it online!

Erik the Outgolfer

Posted 2018-06-29T12:59:37.617

Reputation: 38 134

3

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.

Laikoni

Posted 2018-06-29T12:59:37.617

Reputation: 23 676

3

Pyth, 6 bytes

m=Z*hZ

Try it here!

How it works

m=Z*hZ – Full program. Q = the evaluated input.
m      – For each integer d in Q.
 =Z    – Assign the variable Z (preinitialised to 0) to...
   *hZ – (Z + 1) * d; (d is implicit at the end).

Mr. Xcoder

Posted 2018-06-29T12:59:37.617

Reputation: 39 774

3

Wanted to get an answer in using regular expressions. There is probably an easier solution which I leave as an exercise for the reader.

PowerShell Core, 86 bytes

Filter F{($_-split"(0)(\B|\b)"|?{$_-ne''}|%{$_-replace'(1+)',(1..$_.Length)})-join' '}

Try it online!

Jeff Freeman

Posted 2018-06-29T12:59:37.617

Reputation: 221

3

C (gcc), 57 52 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.

O.O.Balance

Posted 2018-06-29T12:59:37.617

Reputation: 1 499

Wouldn't it be more accurate to say this is K&R C? – Tim Seguine – 2018-07-01T13:14:33.157

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: https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c

– O.O.Balance – 2018-07-01T14:09:08.850

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. – Tim Seguine – 2018-07-02T12:30:30.327

1Suggest f(a,l,c)int*a;{for(c=0;l--;)c=*a++*=c+1;} – None – 2018-11-01T11:05:55.077

3

alephalpha

Posted 2018-06-29T12:59:37.617

Reputation: 23 988

3

PowerShell, 48 40 25 bytes

Thanks Mazzy for -8
Thanks AdmBorkBork for -15

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

Veskah

Posted 2018-06-29T12:59:37.617

Reputation: 3 580

1Given: 'Output ... can be returned as an string or array' ) I think param($p)$a=@();$p|%{$a+=$i=$_*=++$i};$a is enough. 40 bytes – mazzy – 2018-07-02T12:55:05.730

2

25 bytes by using $args[0] and getting rid of $a -- Try it online!

– AdmBorkBork – 2018-07-06T12:44:44.000

3

QBasic, 60 bytes

INPUT s$
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.

DLosc

Posted 2018-06-29T12:59:37.617

Reputation: 21 213

3

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

Jo King

Posted 2018-06-29T12:59:37.617

Reputation: 38 234

3

Retina, 14 bytes

rv`0|(1)+
$#1¶

Try it online!

Martin Ender

Posted 2018-06-29T12:59:37.617

Reputation: 184 808

3

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!

ErikF

Posted 2018-06-29T12:59:37.617

Reputation: 2 149

3

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

Al R

Posted 2018-06-29T12:59:37.617

Reputation: 81

280 bytes. Check out the SPL tips page for golfing tips. – Jo King – 2018-07-23T01:07:00.667

3

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

Toby Speight

Posted 2018-06-29T12:59:37.617

Reputation: 5 058

3

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.

sundar - Reinstate Monica

Posted 2018-06-29T12:59:37.617

Reputation: 5 296

Do you need D? I removed it and it seems to work fine without it. – Giuseppe – 2018-07-06T17:10:10.813

I had 12 bytes porting my R answer with 4#Y'"@:v!]G* – Giuseppe – 2018-07-06T17:11:52.650

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 - Reinstate Monica – 2018-07-06T18:42:08.507

3

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₀ᵇ+ᵐ.

sundar - Reinstate Monica

Posted 2018-06-29T12:59:37.617

Reputation: 5 296

ḅ{+ℕ₁⟦₁|}ᵐc is 1 byte shorter – Fatalize – 2018-07-30T06:51:00.920

ḅ{a₀ᵇ+ᵐ}ᵐc is 2 bytes shorter and should work, right? – Fatalize – 2018-07-30T06:56:46.687

@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 - Reinstate Monica – 2018-08-03T11:38:41.727

2

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.

Neil

Posted 2018-06-29T12:59:37.617

Reputation: 95 035

2

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

Sok

Posted 2018-06-29T12:59:37.617

Reputation: 5 592

2

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

Kevin

Posted 2018-06-29T12:59:37.617

Reputation: 81

Possible space save in = (. – Jonathan Frech – 2018-06-29T21:52:08.067

2

Brain-Flak, 78 bytes

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

Try it online!

Readable version:

(<>)<>
([])

{

    {}

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

    ([])
    {

        {}(<>)<>
    }

    {}

    ([])

}{}<>

([])

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

James

Posted 2018-06-29T12:59:37.617

Reputation: 54 537

2

Java, 65 bytes

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

Java Gonzar

Posted 2018-06-29T12:59:37.617

Reputation: 173

2

Julia 0.6, 28 bytes

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

Try it online!

sundar - Reinstate Monica

Posted 2018-06-29T12:59:37.617

Reputation: 5 296

2

C++, 46 45 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);}}

bridgerrholt

Posted 2018-06-29T12:59:37.617

Reputation: 51

2

Z80Golf, 12 bytes

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

Try it online! or Run test cases.

I/O format is byte values.

Disassembly

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.

Bubbler

Posted 2018-06-29T12:59:37.617

Reputation: 16 616

1

Jelly, 6 bytes

ŒgJ€F×

Try it online!

Leaky Nun

Posted 2018-06-29T12:59:37.617

Reputation: 45 011

1

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!

wastl

Posted 2018-06-29T12:59:37.617

Reputation: 3 089

1

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.

Xcali

Posted 2018-06-29T12:59:37.617

Reputation: 7 671

Nice again! You can save 2 bytes by dropping the ( ) as the trailing space is just ignored! – Dom Hastings – 2018-07-04T14:39:23.013

@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 – 2018-07-05T16:12:13.183

1

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

            Console.ReadLine();
        }
    }
}

Releases

  • v1.0 - 75 bytes - Initial solution.

Notes

  • None

auhmaan

Posted 2018-06-29T12:59:37.617

Reputation: 906

Since you are already modifying the input, you can change the Func into an Action and drop the return a;. Also, with Java/C# lambdas you don't have to include trailing semi-colon after the function. Your current code becomes: a=>{for(int i=1;i<a.Length;i++)if(a[i-1]>0&a[i]>0)a[i]=a[i-1]+1;} (65 bytes), but you could golf it further (by creating a port of my Java answer) to: a=>{for(int p=0,i=0;i<a.Length;)a[i]=a[i++]<1?p=0:++p;} (55 bytes).

– Kevin Cruijssen – 2018-07-02T06:53:16.253

1

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!

Erik the Outgolfer

Posted 2018-06-29T12:59:37.617

Reputation: 38 134

1

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.

StealthyPanda

Posted 2018-06-29T12:59:37.617

Reputation: 41

2

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!

– Post Rock Garf Hunter – 2018-07-02T16:17:16.833

1

Kotlin, 73 bytes

var i=0
readLine()?.forEach{(it-48).toInt().let{c->i=i*c+c;print("$i ")}}

Try it online!

Kromzem

Posted 2018-06-29T12:59:37.617

Reputation: 31

1

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!

Visckmart

Posted 2018-06-29T12:59:37.617

Reputation: 151

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 – 2018-07-22T08:59:49.300

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 – 2018-07-22T10:05:53.227

@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 – 2018-07-22T14:28:39.677

You can use my code, sure – Jo King – 2018-07-22T21:39:01.960

0

PHP, 41 bytes

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

takes input from command line arguments; prints string.

Run with -r.

Titus

Posted 2018-06-29T12:59:37.617

Reputation: 13 814

0

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.

Annyo

Posted 2018-06-29T12:59:37.617

Reputation: 231

0

Scheme, 91 61 bytes

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

Try it online!

TuxCrafting

Posted 2018-06-29T12:59:37.617

Reputation: 4 547

0

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
}

Meerkat

Posted 2018-06-29T12:59:37.617

Reputation: 371

0

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

clismique

Posted 2018-06-29T12:59:37.617

Reputation: 6 600

0

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

reffu

Posted 2018-06-29T12:59:37.617

Reputation: 1 361