43
\$\begingroup\$

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

\$\endgroup\$
0

69 Answers 69

3
\$\begingroup\$

Retina, 14 bytes

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Wouldn't it be more accurate to say this is K&R C? \$\endgroup\$ Commented Jul 1, 2018 at 13:14
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Jul 1, 2018 at 14:09
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jul 2, 2018 at 12:30
  • 1
    \$\begingroup\$ Suggest f(a,l,c)int*a;{for(c=0;l--;)c=*a++*=c+1;} \$\endgroup\$
    – user77406
    Commented Nov 1, 2018 at 11:05
3
\$\begingroup\$

Java, 65 bytes

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Do you need D? I removed it and it seems to work fine without it. \$\endgroup\$
    – Giuseppe
    Commented Jul 6, 2018 at 17:10
  • \$\begingroup\$ I had 12 bytes porting my R answer with 4#Y'"@:v!]G* \$\endgroup\$
    – Giuseppe
    Commented Jul 6, 2018 at 17:11
  • \$\begingroup\$ 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. :) \$\endgroup\$
    – Sundar R
    Commented Jul 6, 2018 at 18:42
3
\$\begingroup\$

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});
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$ Commented Aug 17, 2021 at 13:38
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ there is \$\endgroup\$
    – lyxal
    Commented Mar 9, 2023 at 1:22
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

K (ngn/k), 11 9 bytes

(*/+\|,)\

Try it online!

-2 bytes thanks to ovs

\$\endgroup\$
5
  • \$\begingroup\$ Shorter with a lambda but tacit is fun. \$\endgroup\$
    – doug
    Commented Mar 10, 2023 at 21:31
  • \$\begingroup\$ Isn't 1+\/ just +\ ? \$\endgroup\$
    – ovs
    Commented Mar 11, 2023 at 9:12
  • \$\begingroup\$ That seems to hang for me. I that turns it into converge on sum scan which is monadic. \$\endgroup\$
    – doug
    Commented Mar 12, 2023 at 3:37
  • \$\begingroup\$ (*/+\|,)\ \$\endgroup\$
    – ovs
    Commented Mar 12, 2023 at 8:33
  • \$\begingroup\$ Oh, sorry. I misread what you wrote. \$\endgroup\$
    – doug
    Commented Mar 12, 2023 at 9:14
2
\$\begingroup\$

Jelly, 6 bytes

ŒgJ€F×

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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))))))
\$\endgroup\$
1
  • \$\begingroup\$ Possible space save in = (. \$\endgroup\$ Commented Jun 29, 2018 at 21:52
2
\$\begingroup\$

Brain-Flak, 78 bytes

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

Try it online!

Readable version:

(<>)<>
([])

{

    {}

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

    ([])
    {

        {}(<>)<>
    }

    {}

    ([])

}{}<>

([])

{
    {}({}<>)<>([])
}<>{}
\$\endgroup\$
2
\$\begingroup\$

Julia 0.6, 28 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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);}}
\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
0
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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

enter image description here

\$\endgroup\$
2
\$\begingroup\$

BQN, 6 bytes

(×+⊢)`

Try it at BQN online!

Explanation

Port of Dominic van Essen's Nibbles answer.

(×+⊢)`
(    )`  Left scan on this function:
  +       Add
   ⊢      each element to
 ×        the product of the element and the previous intermediate value
\$\endgroup\$
2
\$\begingroup\$

KamilaLisp v0.2, 14 (APL SBCS)

$(⍀.←[+ * #1])

Equivalent to $(scanl1[+ * #1]).

\$\endgroup\$
2
\$\begingroup\$

Thunno 2 S, 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)
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
0
1
\$\begingroup\$

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
\$\endgroup\$
1
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ 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! \$\endgroup\$
    – Wheat Wizard
    Commented Jul 2, 2018 at 16:17
1
\$\begingroup\$

Kotlin, 73 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

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

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!

\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$
    – Jo King
    Commented Jul 22, 2018 at 8:59
  • \$\begingroup\$ 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 \$\endgroup\$
    – Jo King
    Commented Jul 22, 2018 at 10:05
  • \$\begingroup\$ @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? \$\endgroup\$
    – Visckmart
    Commented Jul 22, 2018 at 14:28
  • \$\begingroup\$ You can use my code, sure \$\endgroup\$
    – Jo King
    Commented Jul 22, 2018 at 21:39
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.