36
\$\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\$

56 Answers 56

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

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

\$\endgroup\$
  • \$\begingroup\$ ḅ{+ℕ₁⟦₁|}ᵐc is 1 byte shorter \$\endgroup\$ – Fatalize Jul 30 '18 at 6:51
  • \$\begingroup\$ ḅ{a₀ᵇ+ᵐ}ᵐc is 2 bytes shorter and should work, right? \$\endgroup\$ – Fatalize Jul 30 '18 at 6:56
  • \$\begingroup\$ @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! \$\endgroup\$ – sundar Aug 3 '18 at 11:38
3
\$\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\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Given: 'Output ... can be returned as an string or array' ) I think param($p)$a=@();$p|%{$a+=$i=$_*=++$i};$a is enough. 40 bytes \$\endgroup\$ – mazzy Jul 2 '18 at 12:55
  • 2
    \$\begingroup\$ 25 bytes by using $args[0] and getting rid of $a -- Try it online! \$\endgroup\$ – AdmBorkBork Jul 6 '18 at 12:44
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\$
  • \$\begingroup\$ Possible space save in = (. \$\endgroup\$ – Jonathan Frech Jun 29 '18 at 21:52
2
\$\begingroup\$

Brain-Flak, 78 bytes

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

Try it online!

Readable version:

(<>)<>
([])

{

    {}

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

    ([])
    {

        {}(<>)<>
    }

    {}

    ([])

}{}<>

([])

{
    {}({}<>)<>([])
}<>{}
\$\endgroup\$
2
\$\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\$
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\$

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.

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

Jelly, 6 bytes

ŒgJ€F×

Try it online!

\$\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\$
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
\$\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\$
  • 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\$ – Sriotchilism O'Zaic Jul 2 '18 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\$
  • \$\begingroup\$ Nice again! You can save 2 bytes by dropping the ( ) as the trailing space is just ignored! \$\endgroup\$ – Dom Hastings Jul 4 '18 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 Jul 5 '18 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\$
  • \$\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 Jul 22 '18 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 Jul 22 '18 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 Jul 22 '18 at 14:28
  • \$\begingroup\$ You can use my code, sure \$\endgroup\$ – Jo King Jul 22 '18 at 21:39
0
\$\begingroup\$

PHP, 41 bytes

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

takes input from command line arguments; prints string.

Run with -r.

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

Scheme, 91 61 bytes

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

Try it online!

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

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
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Found 4 bytes to shave. tio.run/… \$\endgroup\$ – recursive Nov 1 '18 at 18:54
0
\$\begingroup\$

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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