62
\$\begingroup\$

In this challenge, your task is to decipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each encountered digit N (0 to 9) must be replaced with the character which is N+1 positions before it.

Example

The input string "Prog2am0in6" would be decoded this way:

example

Hence, the expected output is "Programming".

Clarifications and rules

  • The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty.
  • The original deciphered string is guaranteed not to contain any digit.
  • Once a character has been decoded, it may in turn be referenced by a subsequent digit. For instance, "alp2c1" should be decoded as "alpaca".
  • References will never wrap around the string: only previous characters can be referenced.
  • You can write either a full program or a function, which either prints or outputs the result.
  • This is code golf, so the shortest answer in bytes wins.
  • Standard loopholes are forbidden.

Test cases

Input : abcd
Output: abcd

Input : a000
Output: aaaa

Input : ban111
Output: banana

Input : Hel0o W2r5d!
Output: Hello World!

Input : this 222a19e52
Output: this is a test

Input : golfin5 3s24o0d4f3r3y3u
Output: golfing is good for you

Input : Prog2am0in6 Puz0les7&1Cod74G4lf
Output: Programming Puzzles & Code Golf

Input : Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.
Output: Replicants are like any other machine. They're either a benefit or a hazard.
\$\endgroup\$
4
  • \$\begingroup\$ Can we receive the input as an array of single character strings? Can we assume that the number will never be greater than 9? \$\endgroup\$ Apr 7, 2017 at 13:29
  • \$\begingroup\$ @fəˈnɛtɪk Regarding the input format: I'd say no, unless this is the only acceptable format for your language. We're dealing with single digits rather than numbers. So yes: it's guaranteed to be <= 9 but you may encounter several digits in a row. \$\endgroup\$
    – Arnauld
    Apr 7, 2017 at 13:38
  • \$\begingroup\$ Would 1bbab be a valid input (with expected output of abbab)? In other words, can the references wrap around the string? \$\endgroup\$
    – Luke
    Apr 7, 2017 at 13:41
  • \$\begingroup\$ @Luke Good point. No, 1bbab is not valid. I've added a clarification about that. \$\endgroup\$
    – Arnauld
    Apr 7, 2017 at 13:48

37 Answers 37

13
\$\begingroup\$

Java 7, 81 80 bytes

void a(char[]a){for(int i=0;++i<a.length;)if(a[i]>47&a[i]<58)a[i]=a[i-a[i]+47];}

Try it online!

Saved 1 byte thanks to Anders Tornblad. The first character cannot be a digit so it doesn't need to be checked meaning we can preincrement before checking our terminate condition.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Since the first char could never contain a digit, you don't have to check it. Therefore, your loop can be for(int i=0;++i<a.length;){ instead, saving one char. \$\endgroup\$ Apr 10, 2017 at 10:35
12
\$\begingroup\$

Jelly, 9 7 bytes

~ịṭṭµ@/

Try it online!

How it works

~ịṭṭµ@/  Main link. Argument: s

    µ    Combine the four links to the left into a chain (arity unknown).
     @   Swap the chains arguments. This makes it dyadic.
      /  Reduce s by the chain with swapped arguments. It will be called with
         right argument r (the result of the previous call, initially the first 
         character) and left argument c (the next character of s).
~            Bitwise NOT of c. This maps a digit 'd' to ~d = -(d+1), but all 
             non-digit characters 'D' to 0.
  ṭ          Tack; append c to r.
 ị           Index; select the character of the result to the right at the
             index from the result to the left. Indexing is 1-based and modular,
             so 0 is the last character, -1 the second to last, etc.
   ṭ         Tack; append the resulting character to r.    
\$\endgroup\$
12
\$\begingroup\$

Haskell, 55 bytes

o#c|c>'/',c<':'=o!!read[c]:o|1<2=c:o
reverse.foldl(#)[]

Usage example: reverse.foldl(#)[] $ "Prog2am0in6 Puz0les7&1Cod74G4lf" -> "Programming Puzzles & Code Golf". Try it online!

Reduce the string to a reverse copy of itself with the numbers replaced by the corresponding chars. "reverse", because this way we have easy access to the string so far when indexing the numbers. Reverse it again.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Wow, I have written this exact solution but I was slow in posting it :) Well, at least now I know it was a good one, +1 \$\endgroup\$
    – Leo
    Apr 7, 2017 at 15:20
11
\$\begingroup\$

C, 46 bytes

f(char*s){for(;*s++;)*s=s[(*s-52)/6?0:47-*s];}

Try it online!


C,  52   49  48 bytes

Thanks to @l4m2 for saving a byte!

f(char*s){for(;*s++;)*s>47&*s<58?*s=s[47-*s]:0;}

Edits the input string directly.

Try it online!

Alternative 50-byte version:

f(char*s){for(;*s++;)*s=abs(*s-57)>9?*s:s[47-*s];}

Recursive version, 48 bytes:

f(char*s){*s>47&*s<58?*s=s[47-*s]:0;*s++&&f(s);}
\$\endgroup\$
0
9
\$\begingroup\$

05AB1E, 11 bytes

vydiÂyèëy}J

Try it online!

Explanation

v            # for each character y in input
 ydi         # if y is a digit
    Â        #    push a reversed copy of the string we've built up so far
     yè      #    push the character at index y in the reversed string
       ë     # else
        y    #    push y
         }   # end if
          J  # join stack to a single string
             # output top of the stack at the end of the loop
\$\endgroup\$
2
  • \$\begingroup\$ I really need to check to see if you've already answered more often before starting. \$\endgroup\$ Apr 10, 2017 at 18:12
  • \$\begingroup\$ @carusocomputing: You could still think up some better trick than I've used ;) \$\endgroup\$
    – Emigna
    Apr 10, 2017 at 18:14
7
\$\begingroup\$

JavaScript (ES6), 59 53 bytes

f=x=>/\d/.test(x)?f(x.replace(/\d/,(m,o)=>x[o+~m])):x

Saved 7 bytes thanks to fəˈnɛtɪk.

f=x=>/\d/.test(x)?f(x.replace(/\d/,(m,o)=>x[o+~m])):x

console.log(f("Prog2am0in6"));
console.log(f("abcd"));
console.log(f("a000"));
console.log(f("ban111"));
console.log(f("Hel0o W2r5d!"));
console.log(f("this 222a19e52"));
console.log(f("golfin5 3s24o0d4f3r3y3u"));
console.log(f("Prog2am0in6 Puz0les7&1Cod74G4lf"));
console.log(f("Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d."));

\$\endgroup\$
8
  • \$\begingroup\$ .charAt(...) can be replaced with [...] for savings of 7 bytes \$\endgroup\$ Apr 7, 2017 at 13:56
  • \$\begingroup\$ x.charAt(...) is equivalent to x[...] \$\endgroup\$ Apr 7, 2017 at 14:44
  • \$\begingroup\$ @fəˈnɛtɪk Yep, I thought I tried that before but it threw an error. Thanks! \$\endgroup\$
    – Tom
    Apr 7, 2017 at 14:45
  • 1
    \$\begingroup\$ o-m-1 can be replaced with o+~m. \$\endgroup\$
    – Neil
    Apr 7, 2017 at 16:15
  • 2
    \$\begingroup\$ Because f is called recursively, the character count of the program must include the f= part, so this is 54 bytes, not 52. \$\endgroup\$ Apr 7, 2017 at 18:19
5
\$\begingroup\$

Retina, 37 bytes

Byte count assumes ISO 8859-1 encoding.

\d
$*«»
r1+`(?<=(.)(?<-2>.)*)(«)*»
$1

Try it online!

Explanation

\d
$*«»

Replace each digit d with d «s, followed by one ». We need the latter a) to be able to recognised positions where d = 0 and b) as a separator between adjacent digits.

r1+`(?<=(.)(?<-2>.)*)(«)*»
$1

Repeatedly (+) match the regex on the first line from right to left (r) and then replace the left-most match (1) with the substitution on the second line.

The regex itself matches one of our now unary digits and counts the number of «s in group 2. The lookbehind then matches d characters with (?<-2>.)* before capturing the referred-to character in group 1. The string of «s and » is then replaced with the captured character.

\$\endgroup\$
5
\$\begingroup\$

MATL, 21 19 17 16 bytes

"@t4Y2m?UQ$y]]&h

Try it at MATL Online!

Explanation

        % Implicitly grab input as a string
"       % For each character in the input
  @     % Push that character to the stack
  t     % Make a copy of it
  4Y2   % Push the pre-defined array '0123456789' to the stack
  m     % Check if the current character is part of this array (a digit)
  ?     % If it is
    UQ  % Convert it to a number and add 1 (N)
    $y  % Make a copy of the element N-deep in the stack. MATL uses one-based indexing
        % So 1$y is the element at the top of the stack, 2$y is the next one down, etc.
  ]     % End of if statement
        % Non-digit characters remain on the stack as-is
]       % End of for loop
&h      % Horizontally concatenate the entire stack to form a string
        % Implicitly display the result
\$\endgroup\$
4
  • \$\begingroup\$ Nice use of $y in the new version! \$\endgroup\$
    – Luis Mendo
    Apr 7, 2017 at 15:11
  • \$\begingroup\$ @LuisMendo Thanks! Yea stack-based languages are a good fit for this challenge \$\endgroup\$
    – Suever
    Apr 7, 2017 at 15:13
  • \$\begingroup\$ @LuisMendo Unfortunately this could have been shortened even more if U only worked for digits. Unfortunately 'e'U yields exp(1) otherwise I could have gotten rid of the 4Y2 stuff \$\endgroup\$
    – Suever
    Apr 7, 2017 at 15:14
  • \$\begingroup\$ Another of those Octave things... \$\endgroup\$
    – Luis Mendo
    Apr 7, 2017 at 15:16
4
\$\begingroup\$

JavaScript (ES6), 51 bytes

f=
s=>s.replace(/\d/g,(c,i)=>a[i]=a[i+=~c]||s[i],a=[])
<input oninput=o.textContent=f(this.value)><pre id=o>

a is used to store the replaced digits to deal with digits referring to other digits.

\$\endgroup\$
1
  • \$\begingroup\$ ``` s=>s.replace(a=/\d/g,(c,i)=>a[i]=a[i+=~c]||s[i]) ``` \$\endgroup\$
    – l4m2
    Apr 23, 2018 at 10:24
3
\$\begingroup\$

Perl 5, 34 bytes

33 bytes of code + -p flag.

s/\d/substr$_,-$&-1+pos,1/e&&redo

Try it online!

s/\d/.../e replace the first digit by ... evaluated as Perl code. (with ... being substr$_,-$&-1+pos,1 in that case. substr$_,-$&-1+pos,1 returns the substring of $_ of length 1 at index -$&-1+pos, where $& is the number just matched, and pos is the index of the start of the match. We just need to redo if the replace was successful in order to replace every digit. (and the result is implicitly printed thanks to -p flag).


Old approach, 47 bytes:

44 bytes of code + -F flag.

map{$F[$i]=$F[$i-$_-1]if/\d/;++$i}@F;print@F

Try it online!

Quite straight forward actually. -F flag splits the inputs on each character into @F. map{...}@F iterates through @F (ie. every character of the input). If the character if a digit (/\d/), then we replace it by the character at index $i-$_-1. The $i is the current index variable (that we maintain by incrementing at each character seen).

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

JavaScript ES6, 61 59 bytes

Thanks @Luke for golfing off 8 bytes

x=>[...x].map((p,i,a)=>a[i]=/\d/.test(p)?a[i-1-p]:p).join``

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ x.split`` could also be [...x], [0-9] could be \d, together saving 6B \$\endgroup\$
    – Luke
    Apr 7, 2017 at 13:43
  • \$\begingroup\$ Currently has an error somewhere so going to fix that first \$\endgroup\$ Apr 7, 2017 at 13:44
  • \$\begingroup\$ x=>[...x].map((p,i,a)=>+p+1?a[i-1-p]:p).join`` for 46 bytes \$\endgroup\$
    – Luke
    Apr 7, 2017 at 14:05
  • \$\begingroup\$ Fails for spaces +" " gives 0 which causes it to grab the previous character \$\endgroup\$ Apr 7, 2017 at 14:12
  • \$\begingroup\$ x=>[...x].map((p,i,a)=>a[i]=1+p>9?a[i-1-p]:p).join`` \$\endgroup\$
    – l4m2
    Apr 23, 2018 at 10:17
3
\$\begingroup\$

05AB1E, 27 17 bytes

vyDdiU)DRXèU`X}}J

Try it online!

vy             }  # For each character
  Dd              #   Push is_number
    i         }   #   If it is
     U            #     Save save it
      )DR         #     Wrap the (reversed) stack into an array
         Xè       #     Get the character at the saved index
           U`X    #     Flatten the whole stack
                J # Join 
\$\endgroup\$
2
\$\begingroup\$

CJam, 13 bytes

q{_A,s#)$\;}/

Online demo.

This solution uses CJam's built-in "copy n-th item on the stack" operator $ to implement the decoding. It starts by reading the input (with q) and then looping over the characters from the input string and dumping them onto the stack (with {}/). However, inside the loop body it also duplicates each character after it has been put on the stack (with _) and checks if it's a digit by looking up its position with # in the string "0123456789", conveniently represented as A,s.

The result of this lookup is either the digit's numeric value or, if the character is not a digit, -1. The ) operator then increments that value by one, and $ replaces it with the character current at that many positions below the top of the stack. Finally, \; just removes the copy of the current input character that we made with _ from the stack, as it's no longer needed.

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

Befunge-98, 45 43 bytes

::::#@~\1p:1g::'9`!\'/`*j;'/--1g\1p\1g#;,1+

Try it online!

The idea:

  1. For each char in the input string,
    1. Write it to line 2
    2. If it is not a number, just output it
    3. Otherwise, look up the correct value, rewrite it, then output it
::::            ; There's a counter on the stack, duplicate it 4 times  ;
    #@~         ; Get the next char of input, exiting if there is none  ;
       \1p      ; At the location (counter, 1), write the input char    ;
          :1g   ; Re-obtain the char. Stack is now [counter * 4, input] ;

::                ; Stack: [counter * 4, input * 3]      ;
  '9`!\'/`*       ; If !(input > '9') and (input > '/')  ;
                  ; IE If ('0' <= input && input <= '9') ;
           j;...; ; Then execute the ...                 ;

; Stack: [counter * 4, input] ;
; The ... branch:             ;

'/-             ; input -> int. (input -= '/')             ;
   -            ; counter - int(input) - 1                 ;
                ; Stack: [counter * 3, lookupPosition ]    ;
    1g          ; Get the char that we want to find        ;
      \1p\1g#   ; Overwrite the current char (not the old) ;

; Both branches: ;
,1+             ; Print the number and increment the counter ;

I wasn't able to get this version shorter, but this one is 44 bytes:

s #@~\3p:3g::'9`!\'/`*j;'/--3g#;:10g3p,1+:::

Thought I'd share it because of the neat trick with s - but storing the counter on the stack leads to that 1 char improvement

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

Python 2, 59 bytes

s=''
for c in input():s+=c['/'<c<':':]or s[~int(c)]
print s

Try it online!

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

Python 2, 75 71 bytes

s='';j=-1
for i in input():s+=s[j-int(i)]if'/'<i<':'else i;j+=1
print s

Try it Online!

Edit: Fixed for ascii values between 32-47 ; Fixed for double decoding (eg. "alp2c1" to "alpaca")

\$\endgroup\$
7
  • 1
    \$\begingroup\$ @Arnauld Nope. Sorry, i didn't read the spec closely enough. WIll modify shortly \$\endgroup\$ Apr 7, 2017 at 14:14
  • \$\begingroup\$ It seems there is a bug. for 'Prog2am0in6 Puz0les7&1Cod74G4lf' your program prints Programming Puzzles &7Code1Golf! I tried with both TIO links shared! \$\endgroup\$ Apr 7, 2017 at 14:53
  • \$\begingroup\$ @KeerthanaPrabhakaran Thanks! Fixed at the cost of 0 bytes! (My alternate solution didn't make the cut though) \$\endgroup\$ Apr 7, 2017 at 15:01
  • \$\begingroup\$ Thats a great approach! \$\endgroup\$ Apr 7, 2017 at 15:08
  • \$\begingroup\$ Can you explain '/'<i<':'. I know it's testing if it's a number but how does it work? \$\endgroup\$
    – user43124
    Apr 7, 2017 at 17:22
2
\$\begingroup\$

PHP 7.1 67 59 bytes

while(_&$c=$argn[$i++])$t.=($c^"0")<"
"?$t[~+$c]:$c;echo$t;

Takes input from STDIN; run as pipe with -nR or try it online.

  • _&$c=$s[$i++] loop through string (_&$c will result in something that is not "0"; so the only character that can break the loop is the empty string = end of input)
  • $c^"0" toggle bits 5 and 6 in the ascii code
  • <"\n" check if result is < chr(10)
  • if so, it is a digit: print previous character by index (and copy to current index)
  • else print this character

Thanks @Christoph for saving 12%

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I know this is an old answer but: Negative string offsets ! (and that $s=$argn ... ?) for(;_&$c=$argn[$i++];)$t.=($c^"0")<"\n"?$t[~+$c]:$c;echo$t; \$\endgroup\$
    – Christoph
    Apr 23, 2018 at 12:13
2
\$\begingroup\$

APL (Dyalog Classic), 25 23 bytes

-2 bytes thanks to @FrownyFrog

((⊂⌷⊢)⍣≡⍳∘≢-11|⎕d∘⍳)⊃¨⊂

Try it online!

uses ⎕io←1

( below stands for an intermediate value in the evaluation)

⎕d is the string '0123456789'

⎕d⍳⍵ finds the (1-based in this case) indices of 's chars in ⎕d; for a non-digit the index is 11

11|⍵ is modulo - the 11s become 0s

≢⍵ is the length of

⍳≢⍵ is 1 2 ... till ≢⍵

so, (⍳≢⍵)-11|⎕d⍳⍵ gives us a vector i of the indices where we should look to get the resulting characters; however some of those indices may redirect to yet other (smaller) indices. To compute the transitive closure (i.e. the effective indices), we index the vector into itself (⊂⌷⊢, a train equivalent to (⊂i)⌷i or i[i]) and repeat that until it stabilises (⍣≡ is known as the fixed point operator).

finally we index into the original string: (...)⊃¨⊂

\$\endgroup\$
2
  • \$\begingroup\$ How would it look as a train? \$\endgroup\$
    – FrownyFrog
    Apr 25, 2018 at 1:24
  • \$\begingroup\$ @FrownyFrog indeed, shorter \$\endgroup\$
    – ngn
    Apr 25, 2018 at 6:13
2
\$\begingroup\$

Vim macro/keystrokes, 49 29 bytes

^M represent the return character (0x0A, 1 byte).

qaqqa/\d^Myl@=@"+1^Mhylnvp@aq@a

Explanation

qaq                                 clear register a
   qa                               record into a
     /\d^M                          move the cursor to the next digit
          yl                        yank the digit
            @=@"+1^Mh               move the cursor left that number of characters plus one
                     yl             yank the char
                       n            go back to the digit
                        vp          replace the digit with the yanked char
                          @a        recursive call will execute until the search for a digit fails
                            q       stop recording
                             @a     run the macro
\$\endgroup\$
1
\$\begingroup\$

Python 2,83 80 bytes

r=input()
for i in r:
 if'/'<i<':':r=r.replace(i,r[r.find(i)+~int(i)],1)
print r

Try it online!

  • saved 3 bytes but checking ascii instead of is digit! Thanks to math_junkie!
\$\endgroup\$
1
\$\begingroup\$

Japt, 24 bytes

£Xn >J?U=UhYUgJ+Y-X):PÃU

Try it online!

Explanation:

£Xn >J?U=UhYUgJ+Y-X):PÃU
£                     Ã    Iterate through the input (implicit U) 
                             X becomes the iterative item, Y becomes the index
 Xn                          Try parseInt(X)
    >J                       > -1
                               In this case, this checks if X is a digit
      ?                      If true:
       U=                      Set U to 
         UhY                     U with the char at index Y set to:     
            UgJ+Y-X               The index at -1+Y-X
                   ):        Else:
                     P         variable P (just a no-op in this case)
                       U   Finally, return U
        
\$\endgroup\$
1
\$\begingroup\$

Ruby, 56 46 bytes

->s{i=0;s[i]=s[i+~s[i].to_i]while i=s=~/\d/;s}

Try it online!

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

Python 2, 58 bytes

lambda s:reduce(lambda t,c:t+(c+t)['/'<c<':'and~int(c)],s)

This is essentially a port of my Jelly answer, plus the digit check from @xnor's Python answer.

Try it online!

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

Röda, 51 bytes

f a{x=0;a|{|y|a[x]=a[x+47-ord(y)]if[y=~`\d`];x++}_}

Try it online!

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

JavaScript ES6, 54 bytes

f=r=>[...r].reduce((a,s,i)=>a+(/\d/.test(s)?a[i+~s]:s))

f=r=>[...r].reduce((a,s,i)=>a+(/\d/.test(s)?a[i+~s]:s))

console.log(f("Prog2am0in6"));
console.log(f("abcd"));
console.log(f("a000"));
console.log(f("ban111"));
console.log(f("Hel0o W2r5d!"));
console.log(f("this 222a19e52"));
console.log(f("golfin5 3s24o0d4f3r3y3u"));
console.log(f("Prog2am0in6 Puz0les7&1Cod74G4lf"));
console.log(f("Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d."));

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! If you don't need your function name for recursive calls, unnamed functions are valid, so you can save two bytes on the f=. \$\endgroup\$ Apr 10, 2017 at 21:39
1
\$\begingroup\$

><> (Fish), 108 bytes (= 9 x 12 grid)

01-r>:0(\
"/"&::;?/
)?\v    \
":/v!?(":
")\ :>:"0
 !?\
${/  \ -1
&>\ ~{:&$
\ \ :"0"=
/\- 1}$/?
:v&//}~/~
 \o}\&$/ 

Try it here to see the fish swimming around.

  • Append -1 to the input stack then reverse the stack.
  • Loop: If top value is -1 then end (we've cycled through all characters). Otherwise:
  • Put the top character in the register; check to see whether it's in the range "0" to "9". If so:
    • rotate the stack the appropriate number of places
    • get the character being pointed to
    • rotate back and replace the number with the character from the register
  • Output; resume loop.
\$\endgroup\$
1
\$\begingroup\$

8086 machine code, 35 bytes

00000000  be 82 00 ac 98 50 2c 30  3c 09 77 0c 4e 89 f7 4e  |.....P,0<.w.N..N|
00000010  29 c6 58 ac aa 89 fe 50  5a b4 02 cd 21 80 fa 0d  |).X....PZ...!...|
00000020  75 e1 c3                                          |u..|
00000023
\$\endgroup\$
1
\$\begingroup\$

oK, 39 bytes

{x{x[y 0]:x@-/y}/(!#x),'0|{x*11>x}x-47}

Try it online!

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

Japt v2.0a0, 16 bytes

r\d@=hYUgY-°X¹gY

Try it


Explanation

                     :Implicit input of string U
r                    :Replace
 \d                  :  RegEx /\d/g
   @                 :  Pass each match X at index Y through a function
     hY              :    Set the character at index Y in U
       UgY-°X        :    To the character at index Y-++X
    =        ¹       :    Reassign to U
              gY     :    Get the character at index Y
\$\endgroup\$
1
\$\begingroup\$

J, 20 bytes

{~[:{~^:_#\-2+_1".,.

Try it online

                  ,.  Each character on a separate row
              _1".    Convert to numbers, replacing non-numbers with -1
                         (it becomes one row again)
            2+        Add 2.
         #\           Prefix lengths (range 1..length)
           -          Subtract
  [:{~^:_             Index into itself as long as it changes the result
{~                    Index into the original string

Credit to ngn for the inspiration.

22 bytes

(],,{~1{._1-_1".[)/@|.

This is a port of the Jelly answer.

                    |. The string backwards, because reduce is right-to-left.
            _1".[      The next character as a number (d), -1 if it's not a number,
                          and a space character produces an empty array.
         _1-           -1-d
      1{.              Take 1. If we have a nothing
                          at this point, that makes it a 0.
   ,                   Prepend the next character to the result of the previous call.
    {~                 Select the character. 0 is the first, _2 is second to last.
 ],                    Append the result.

In both solutions the version that TIO uses interprets a single . as the number 0, so the last test fails. Older versions (≤7) seem to work correctly.

Try it online!

\$\endgroup\$
0

Your Answer

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

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