29
\$\begingroup\$

Challenge

Given a string of any length which contains only digits from 0 to 9, replace each consecutive run of the digit 0 with its length.

Test Cases

  1. 12345003620004401234523623441
  2. 123450036200044123452362344
  3. 00000000000012
  4. 01234567891123456789
  5. 12345678901234567891
  6. 123456789123456789
  7. 01020300405011121324151

Note

The shortest answer in bytes wins as per rules

\$\endgroup\$
2
  • 3
    \$\begingroup\$ What is a run of \$10\$ 0s replaced with? 11? \$\endgroup\$
    – Noodle9
    Commented Dec 21, 2022 at 12:28
  • 1
    \$\begingroup\$ Not OP, but I think it will be replaced with 10 as no modifications to the output were also needed, as most answers suggest \$\endgroup\$ Commented Dec 21, 2022 at 12:45

48 Answers 48

1
2
2
\$\begingroup\$

PHP, 110 96 94 86 bytes

try{for(;;)if(!~~$c=fgetc(STDIN))$x++;else{echo$x?:"",$c;$x=0;}}finally{echo$x?$x:"";}

Try it online!

Takes input via STDIN, outputs via STDOUT.

\$\endgroup\$
4
  • \$\begingroup\$ if the string ends in 0s, it just removes them: Try it online! \$\endgroup\$
    – naffetS
    Commented Dec 27, 2022 at 0:29
  • \$\begingroup\$ here's 59 based on what you curerntly have though, to give you a good base: Try it online! \$\endgroup\$
    – naffetS
    Commented Dec 27, 2022 at 0:46
  • \$\begingroup\$ no it doesn't fix it, i just golfed your current code down. Try it online! that should end in a 3 \$\endgroup\$
    – naffetS
    Commented Dec 27, 2022 at 0:52
  • \$\begingroup\$ @Steffan fixed, thanks \$\endgroup\$ Commented Dec 31, 2022 at 21:02
1
\$\begingroup\$

Charcoal, 20 bytes

⭆⪪⁻⪫⪪SI⁰_0_×_²_∨№ι0ι

Try it online! Link is to verbose version of code. Explanation:

     S                  Input string
    ⪪                   Split on
       ⁰                Literal integer `0`
      I                 Cast to string
   ⪫                    Join with
        _0_             Literal string `_0_`
  ⁻                     Remove matching substrings
            _           Literal string `_`
           ×            Repeated
             ²          Twice
 ⪪                      Split on
              _         Literal string `_`
⭆                       Map over pieces and join
                №       Count of
                  0     Literal string `0`
                 ι      In current piece
               ∨        Logical Or
                   ι    Current piece

String separators are only needed between consecutive strings so the code has been tweaked to avoid them to reduce the byte count. ⭆S∨Iι_0_ also works instead of ⪫⪪SI⁰_0_ for the same byte count.

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

Dart (2.18.4), 63 bytes

r(s)=>s.replaceAllMapped(RegExp('0+'),(m)=>'${m.end-m.start}');
String replaceZerosWithTheirConsecutiveCounts(String src) {
  return src.replaceAllMapped(
    RegExp('0+'),
    (Match match) => '${match.end - match.start}',
  );
}
\$\endgroup\$
1
\$\begingroup\$

J, 16 bytes

'0+'":@#rxapply]

Attempt This Online!

Fairly simple regex solution:

'0+' ":@#rxapply ]
'0+'     rxapply ]    apply to all relevant patterns in the input
        #             length
     ":@              casted to string

J, 47 bytes

' '-.~[:,(1,2~:/\'0'&=)([`(":@#)@.('0'&e.));.1]

Attempt This Online!

Horrendously long non-regex solution. This is the only way I could really think of approaching this, since, afaik, J doesn't have a builtin for grouping according to a boolean matrix or similar.

\$\endgroup\$
1
  • \$\begingroup\$ +1 for rxapply. re: non-regex, yeah, J performs badly here, I got a 40: [:;]<`(<@":@#)@.('0'&e.);.1~1,2~:/\'0'&= \$\endgroup\$
    – Jonah
    Commented Dec 23, 2022 at 0:30
1
\$\begingroup\$

Nibbles, 7 6 bytes (12 nibbles)

+.`=$$?`r$@,
  `=$           # chunk the input by
     $          # itself,
 .              # now map over each chunk:
      ?         #   if
       `r$      #   its value as an integer is nonzero
          @     #     return itself
                #   otherwise
           ,    #     return its length
+               # finally, join it all together

enter image description here

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

Mathematica (13.1) 54 bytes

StringReplace[string,x:"0"..:>ToString@StringLength@x]
\$\endgroup\$
1
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 86 bytes

	I =INPUT
R	I ARB . L SPAN(0) . X REM . I	:F(O)
	O =O L SIZE(X)	:(R)
O	OUTPUT =O I
END

Try it online!

	I =INPUT				;* read input
R	I 					;* Match in I:
	  ARB . L				;*	ARBitrary characters (save as Left part of string) up to
		  SPAN(0) . X			;*	1 or more 0s (save as X)
			      REM . I		;*	REMaining characters (save as I)
					:F(O)	;* On no match, goto O
	O =O L SIZE(X)	:(R)			;* Append L and # of 0s to O and goto R
O	OUTPUT =O I				;* Output O and any remaining characters of I that didn't match
END
\$\endgroup\$
1
\$\begingroup\$

Bash --extglob, 57 bytes

j=$1;for w in ${1//[1-9]/ };{ j=${j/+(0)/${#w}};}
echo $j

Try it Online!

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

Pyth, 11 bytes

sm`|vedhdr8

Try it online!

Explanation

sm`|vedhdr8Q    # implicitly add Q to the end
                # implicitly assign Q = eval(input())
         r8Q    # length encode Q
s               # concatenate together
 m              # map over lambda d
  `             # convert to string
   |            # short circuiting or
    ved         # evaluate the second element of d
       hd       # or take the first element of d
\$\endgroup\$
1
\$\begingroup\$

Lua 68 bytes

s=io.read("*a")for i=#s,1,-1 do s=s:gsub(("0"):rep(i),i)end print(s)
\$\endgroup\$
2
  • \$\begingroup\$ 46 bytes \$\endgroup\$
    – Jo King
    Commented Dec 23, 2022 at 13:33
  • \$\begingroup\$ 42 bytes \$\endgroup\$
    – bluswimmer
    Commented Apr 13, 2023 at 11:50
1
\$\begingroup\$

Python 3, 120 119 bytes

def f(s):
    c=0;r=''
    for d in s:
        if d=='0':c+=1
        else:r+=f'{c if c!=0 else""}'+d;c=0
    return r+f'{c if c!=0 else""}'

Try it online!

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

Arturo, 55 bytes

$=>[chunk&=>[&]|map'g->(`0`=g\0)?->size g->join g|join]

Try it

$=>[                   ; a function, assign input to &
    chunk&=>[&]        ; split input into blocks of equal, contiguous chars
    |                  ; then
    map'g->            ; map over each block and assign current elt to g
        (`0`=g\0)?     ; is the first element of g the character `0`?
        ->size g       ; then map g to the length of g
        ->join g       ; otherwise, map g to its joined string
    |                  ; then
    join               ; join the block of strings and numbers to a string
]                      ; end function
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 71 bytes

Solution without using regexp

s=>s.split(0).map(c=>c?(a?a:"")+(a=1,c):(++a,""),a=0).join``+(--a?a:"")

Try it online!

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

PowerShell, 94 bytes

$r='';$_|sls '0+|[1-9]+'-a|% m*|%{$v=$_.value;('$r+=$v','$r+=$_.length')[$v-match"0+"]|iex};$r

Ungolfed

$args|%{
    
    # empty string to append to
    $r=''
    
    # '0+|[1-9]+' will match full string but split by zeroes and non-zeroes
    $_ | sls '0+|[1-9]+' -a | % m*| %{
        
        # value is the matched string 
        $v=$_.value

        # true = 1; false = 0; shorter than an if statement
        # iex will execute the command in quotes
        ('$r+=$v','$r+=$_.length')[$v-match"0+"] | iex
    }
    
    # prints the results
    $r
}

Try it online!

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

Nekomata, 10 bytes

ĉᵐ{ᵉĜ#Mĝ}j

Attempt This Online!

Nekomata is still bad at string challenges.

ĉᵐ{ᵉĜ#Mĝ}j
ĉ               Split into groups of identical characters
 ᵐ{     }       For each group:
   ᵉ  M           Max of the following two:
    Ĝ               Convert string to number
     #              Length
       ĝ          Convert number to string
         j      Join

Using the fact that the length of a positive integer is always less than or equal to the integer itself.

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

Pxem, 11 + 52 = 63 bytes

.c.w.n\0.a.s

Filename

\1.rL.w.i.c0.x.t.e.c.-.m.oXX\1.a.c!.x.s\1.+XX\1.a\1.+.a.e

Try it online!

What I have golfed

  1. EOF case out of the loop
  2. How subroutine works

Pxem, 13 + 58 = 71 bytes

.s.c.w.n\0.a.s

Filename

\1.rL.w.i.c\1.+\1.y.e.d.a.c0.x.e.o.s\1.rXX1.a.c1.z.s\1.+XX0.a.a

Try it online!

How I golfed

  1. Push zero by \1.r instead of aa.%.
  2. Put number of zeros at bottom then digit or EOF above.

Pxem, 16 + 61 = 77 bytes

.c.w.naa.%.a.s.s

Filename

aa.%.t.w.i.c\1.y.m.e.d.a.c0.x.m.e.m.-.t.oXX1.a1.z\1.m.+.tXX.a.a

Try it online!

Explained

Filename.

aa.%.t      Store 0 to register because it is initialized with null.
.w          Loop
  .i          Push getchar
  .c\1.y      If EOF
    .m.e.d      Push register, call subroutine, exit
  .a
  .c0.x       If top is greater than 48
    .m.e        Push register, call subroutine
    .m.-.t      Reset register to 0
    .o          putchar pop
  XX1.a         Push 49
  1.z         If pop is NOT 49 
    \1.m.+.t    Increment register
  XX.a
.a          End loop

Content as subroutine. Different space with filename, when return stack is concatenated to caller's stack.

.c.w    If top is not zero
  .n      print popped value as numeric integer
aa.%.a
.s.s    Clean up
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I enjoyed reading the story of Pxem - very creative! \$\endgroup\$
    – roblogic
    Commented Jun 22 at 2:32
0
\$\begingroup\$

Haskell, 76 bytes

import Data.List
r s=concat[case t!!0 of '0'->show$length t;_->t|t<-group s]

Try it online!

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

awk

(gawk-specific)

gawk 'ORS=RT?length(RT):_' RS=0+
1234523623441
123452362344
12
1123456789
1234567891
123456789
11121324151
\$\endgroup\$
1
  • \$\begingroup\$ It's not printing the last digit. If you change it to 'ORS=RT?length(RT):$_' RS=0+ you get the digit back, but a trailing one on a new line. \$\endgroup\$
    – xrs
    Commented Dec 5 at 15:13
1
2

Your Answer

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