| Bytes | Lang | Time | Link |
|---|---|---|---|
| 005 | Japt | 240822T195419Z | Shaggy |
| 043 | JavaScript Node.js | 240822T235932Z | l4m2 |
| 007 | Uiua | 240822T185703Z | noodle p |
| 735 | Nibbles | 240822T142611Z | Dominic |
| 058 | tinylisp 2 | 240821T200618Z | DLosc |
| 039 | Arturo | 230220T203701Z | chunes |
| 004 | Vyxal | 221105T233108Z | tybocopp |
| 022 | Raku | 210417T220125Z | Sean |
| 020 | APL Dyalog Unicode | 210411T004342Z | Andrew O |
| 005 | 05AB1E | 210412T162734Z | Makonede |
| 090 | C gcc | 210411T005158Z | l4m2 |
| 010 | K ngn/k | 210410T155513Z | coltim |
| 004 | Husk | 210410T150622Z | Dominic |
| nan | 161227T155028Z | Quentin | |
| 023 | Wonder | 161227T142622Z | Mama Fun |
| 037 | Clojure | 161226T222712Z | NikoNyrh |
| 126 | Java | 160524T045555Z | Hopefull |
| 022 | Perl | 160427T091742Z | Toby Spe |
| nan | 160427T091500Z | auhmaan | |
| 045 | Haskell | 160425T201824Z | xnor |
| 123 | Oracle SQL 11.2 | 160426T155421Z | Jeto |
| 131 | C# | 160426T143409Z | downrep_ |
| 008 | Jolf | 160425T181010Z | Conor O& |
| 030 | Julia | 160426T021628Z | Alex A. |
| 022 | Actually | 160426T051618Z | user4594 |
| 179 | Java | 160426T045633Z | 1232 |
| 103 | F# | 160426T022502Z | David Co |
| 035 | Factor | 160425T201840Z | cat |
| 030 | Mathematica | 160425T175540Z | feersum |
| 052 | Perl 5 | 160425T200139Z | msh210 |
| 050 | Python | 160425T193454Z | 1232 |
| 046 | Haskell | 160425T193453Z | nimi |
| 044 | Clojure/ClojureScript | 160425T191530Z | MattPutn |
| 005 | Jelly | 160425T190615Z | Dennis |
| 2524 | Retina | 160425T182751Z | FryAmThe |
| 018 | J | 160425T180218Z | Conor O& |
| 049 | JavaScript ES6 | 160425T182209Z | user8165 |
| 015 | Retina | 160425T183323Z | Martin E |
| 006 | 05AB1E | 160425T175155Z | Adnan |
| 005 | IPOS | 160425T175848Z | Denker |
| 045 | PowerShell v2+ | 160425T181914Z | AdmBorkB |
| 008 | Pyke | 160425T180809Z | Blue |
| 029 | Ruby | 160425T180134Z | Doorknob |
| 008 | Pyth | 160425T175057Z | FryAmThe |
Japt, 5 bytes
I/O as a digit array.
óm cw
óm cw :Implicit input of array
ó :Partition between pairs that return falsey (0) when
m : Reduced by minimum
c :Flat map
w : Reverse
Uiua, 7 bytes
⍜⊜□⍚⇌⊸±
Try it online: Uiua pad
Under taking the boxed chunks of where the sign of each number is one, reverse each box.
Nibbles, 7 nibbles (3.5 bytes)
\+\`=$/
\+\`=$/ # full program
\+\`=$/$$ # with implicit variables shown
`=$ # split the input into chunks
# by the result of
/$$ # dividing each element by itself
# (so: nonzero/nonzero == 1,
# and zero/zero == 0)
\ # reverse the order of the chunks,
+ # flatten,
\ # and reverse
tinylisp 2, 58 bytes
(d R(\(D(A))(?(! D)A(?(h D)(R(t D)(c(h D)A))(, A(c 0(R(t D
Ungolfed/explanation
Define reverse-runs as a function that takes a list of digits and optionally an accumulator. If the accumulator argument is not provided, it defaults to nil.
(def reverse-runs
(lambda (digits (accum))
Base case: if digits is empty, return whatever is in the accumulator:
(if (not digits)
accum
Otherwise, if the next digit is truthy (non-zero), prepend it to the accumulator and recurse:
(if (head digits)
(reverse-runs
(tail digits)
(cons (head digits) accum))
Otherwise, the next digit is zero; prepend the accumulator and a 0 to a recursive call with an empty accumulator:
(concat accum
(cons 0
(reverse-runs
(tail digits))))))))
Vyxal, 4 bytes
0ẆRṅ
Takes input as a string instead. If that's not allowed then the Ṡ flag can be added.
Explanation:
0 # Push the literal digit 0
Ẇ # Split and keep delimiter
R # Reverse each one
ṅ # Join by nothing
Raku, 22 bytes
{S:g[<-[0]>+]=$/.flip}
Basic regex solution. <-[0]> matches any nonzero character (it's Raku's version of the classic [^0]), and $/.flip reverses each sequence.
APL (Dyalog Unicode), 20 bytes
('[1-9]+'⎕R{⌽⍵.Match})
It's just a simple regular expression with an anonymous function.
'[1-9]+' ⍝ a regex pattern
⎕R ⍝ the replace operator
{⌽⍵.Match} ⍝ an anonymous function that recieves a regex namespace (object). ⌽ reverses the string.
05AB1E, 5 bytes
0¡í0ý
0¡í0ý # full program
ý # join...
# implicit input...
¡ # split by...
0 # literal...
¡ # s...
í # with each element reversed...
ý # by...
0 # literal...
ý # s
# implicit output
C (gcc), 90 bytes
char*t;f(char*s){*s>48&&putchar(*s,f(s+1),++t);}g(char*s){for(t=s;f(t),*t;putchar(*t++));}
K (ngn/k), 10 bytes
"0"/|'"0"\
Similar to many of the other approaches; takes (implicit) input as a string of digits:
"0"\split input on0s|'reverse each chunk"0"/join with0s
Husk, 4 bytes
ṁ↔ġ¬
Try it online! or verify all test cases
Input is a list of digits.
ġroups all adjacent runs of nonzero (¬=NOT) digits, then ṁaps the 'reverse a list' (↔=REV) function across all groups, concatenating the result.
C, 105 bytes
#define x(o)for(p=s;*s&&'0'o*s;++s);for(r=s;r-->p;putchar(*r));
f(s,p,r)char*s,*p,*r;{x(^)x(==)*s&&f(s);}
Call f with the list of digits as a nul-terminated string, and it will print the correct output.
Ungolfed and explained:
f(s,p,r)
char*s,*p,*r; // K&R style to avoid repeating `char`
{
// x(^)x(==) expands to...
// Find the next zero digit
for(p = s; *s && '0' ^ *s; ++s)
;
// Print that run backwards
for(r = s; r-- > p; putchar(*r))
;
// Find the next non-zero digit
for(p = s; *s && '0' == *s; ++s)
;
// Print that run backwards (no difference, it's all zeros)
for(r = s; r-- > p; putchar(*r))
;
// If there's more string, recurse
*s && f(s);
}
Wonder, 23 bytes
rstr[`[^0]*`g;'><"".rev
Usage:
(rstr[`[^0]*`g;'><"".rev)1230123
Reverses all parts of the input that match the global regex [^0]*.
Clojure, 37 bytes
#(mapcat reverse(partition-by #{0}%))
Uses #{0} instead of pos? (save 1 byte by concatenating with %) and using mapcat instead of (flatten(map. Still longer than Factor.
Java, 126
a->{String r="",t[]=a.split("0");for(String s:t){r+=new StringBuilder(s).reverse()+"0";}return r.substring(0, r.length()-1);}
Perl, 22 bytes
Including +1 for -p option:
s/[^0]+/reverse$&/eg
This is a pretty trivial substitution - sorry to be so boring. Note that if your input is newline-terminated (e.g. using perl -pe 's/[^0]+/reverse$&/eg' <<<21000543 in Bash), it will catch the newline with the digits - use echo -n or printf to avoid that. Alternatively, for a cost of one additional byte, change the character class to [1-9], and you can provide many inputs, one per line.
C#, 133 bytes
Golfed
String m(String s){for(int i=0,p=i;i<s.Length;i++){if(s[i]=='0'){p=i+1;}else{s=s.Insert(p,s[i].ToString()).Remove(i+1,1);}}return s;}
Ungolfed
String m( String s ) {
// i = Index on the String
// p = Pointer of the last '0' found
for (int i = 0, p = i; i < s.Length; i++) {
if (s[ i ] == '0') {
// Move the 'p' pointer to the index after this '0'
p = i + 1;
} else {
// Insert the Char at the Index location to the Pointer location
// and remove the one at the Index Location + 1,
// since the String was incremented by one char due to the 'Insert()'.
s = s.Insert( p, s[ i ].ToString() )
.Remove( i + 1, 1 );
}
}
return s;
}
Full code
using System;
using System.Collections.Generic;
namespace Namespace {
class Program {
static void Main( String[] args ) {
List<String> ls = new List<String>() {
"4",
"00",
"123",
"0010",
"12000345",
"18161604",
"95883007414830",
"010230456078912",
"357509902003550",
"2492882377675046",
"03026302053000357099"
};
foreach (String s in ls) {
String f = m( s );
Console.WriteLine( String.Format( "{0,30}", s.Replace( "0", "0 " ) ) );
Console.WriteLine( String.Format( "{0,30}", f.Replace( "0", "0 " ) ) );
Console.WriteLine( "" );
}
Console.ReadLine();
}
static String m( String s ) {
for (Int32 i = 0, p = i; i < s.Length; i++) {
if (s[ i ] == '0') {
p = i + 1;
} else {
s = s.Insert( p, s[ i ].ToString() ).Remove( i + 1, 1 );
}
}
return s;
}
}
}
Haskell, 45 bytes
r%(0:t)=r++0:[]%t
r%(h:t)=(h:r)%t
r%_=r
([]%)
Recursively accumulates the reversed chunk so far in r, prepending it when a 0 is reached. When the remaining string is empty, it also discharges r.
The first two repeat some code, but I didn't find a shorter way to combine them (45 and 47 bytes):
r%(h:t)|h<1=r++h:[]%t|1>0=(h:r)%t
r%_=r
([]%)
r%l|0:t<-l=r++0:[]%t|h:t<-l=(h:r)%t
r%_=r
([]%)
Oracle SQL 11.2, 131 123 bytes
Abusing XML functions.
SELECT LISTAGG(REVERSE(COLUMN_VALUE||''))WITHIN GROUP(ORDER BY rownum)FROM XMLTABLE(('"'||REPLACE(:1,'0','","0","')||'"'));
C#, 131 bytes ##
solution flawed!
string j(string i){foreach(var s in i.Split('0'))if(s!="")i=i.Replace(s,new string(s.ToCharArray().Reverse().ToArray()));return i;}
ungolfed:
string j(string input)
{
string[] a = input.Split('0');
foreach (string s in a)
{
if (s!="")
input=input.Replace(s, new string(s.ToCharArray().Reverse().ToArray()));
}
return input;
}
Jolf, 8 bytes
RΜGi0λ_0
Explanation
RΜGi0λ_0
Gi0 split input on zeroes
Μ λ_ map over reversal as a lambda
R 0 join by zeroes
The code explanation looks sort of like a lambda if you squint.
An equivalent 8-byte answer:
RΜGi0΅O0
Same thing, but it uses ΅O (string mirror lambda) instead.
Julia, 30 bytes
s->replace(s,r"[^0]+",reverse)
This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.
The replace function provides the ability to replace matches of a regular expression with the result of a function applied to each match. In this case we can get nonzeros using [^0]+ and replace those runs with the result of the reverse function applied to the matched text.
Actually, 22 bytes
k"a%sa"%'0@s♂R'0j#pXdX
This actually made me notice that there's a bug in the split command - it doesn't preserve empty splits. As a workaround, I surround the input string with as before doing the split, reverse, and join, then remove the as at the end. Input is taken as a string, output is a list of single-character strings.
Explanation:
k"a%sa"%'0@s♂R'0j#pXdX
k"a%sa"% surround input with "a" characters
'0@s split on 0
♂R reverse each piece
'0j join on 0
#pXdX listify, remove first and last element (the "a"s)
Java, 179 bytes(with import)
import java.util.*;static void r(String s){StringJoiner x= new StringJoiner("0");for(String a:s.split("0",s.length())){x.add(new StringBuilder(a).reverse());}System.out.print(x);}
Takes in a string input and splits the characters by zero then adds them back by calling the add method on the StringJoiner class.
F#, 103 bytes
let f x=x="";x.Split '0'|>Array.map(fun s->System.String(s|>Seq.toArray|>Array.rev))|>String.concat "0"
Factor, 35 bytes
Beating Pyfon and Clojure, booyah!
[ "0"split [ reverse ] map "0"join ]
This anonymous function is a literal translation of this Python answer.
It's quite simple, just split the string on zeroes, reverse every element of the resulting array, and join all the elements (including zero-length strings) with "0".
Here's an example of it running on all test cases:
IN: scratchpad auto-use {
"4"
"00"
"123"
"0010"
"12000345"
"18161604"
"95883007414830"
"010230456078912"
"357509902003550"
"2492882377675046"
"03026302053000357099"
}
[
"0" split [ reverse ] map "0" join
]
map .
{
"4"
"00"
"321"
"0010"
"21000543"
"61618104"
"38859003841470"
"010320654021987"
"575309902005530"
"5767732882942064"
"03036202035000753099"
}
"00120" -> { "" "" "12" "" } -> { "" "" "21" "" } -> "00210"
Mathematica, 30 bytes
Join@@Reverse/@#~SplitBy~Sign&
e.g. Join@@Reverse/@#~SplitBy~Sign&[{1,2,3,0,0,5,9,0}] = {3, 2, 1, 0, 0, 9, 5, 0}
Perl 5, 52 bytes
A subroutine:
{$_=pop;y/0/ /;map$i.=reverse,split/\b/;$i=~y/ /0/r}
Python, 58 50 bytes
lambda x:"0".join([n[::-1] for n in x.split("0")])
Takes in a string x and splits on the zeros and reverses each element in the split and adds a zero and returns the this minus last zero.
Haskell, 46 bytes
import Data.Lists
(reverse=<<).split(oneOf"0")
Usage example: (reverse=<<).split(oneOf"0") $ "0123004500678090"-> "0321005400876090".
Sadly the split function requires the expensive import. Split the input list at every 0, e.g. split(oneOf"0") "0120030" -> ["","0","12","0","","0","3","0",""], reverse each chunk and concatenate into a single string.
Clojure/ClojureScript, 44 chars
#(flatten(map reverse(partition-by pos? %)))
Same solution as others, just more verbose thanks to long function names. Wasn't going to post it because of that, but it beats some other answers so why not?
Works on any sequence type. In ClojureScript, this also works on strings since strings are processable as lists of characters, which are really just 1-length strings, which coerce to numbers for things like pos?.
Retina, 25 24
O^$#`[^0](?=(.*?0)*)
$#1
Saved 1 byte thanks to Martin!
Sort the nonzero digits by the number of zeros that follow the digit, in reverse order.
See Martin's solution for a clever use of per-line mode to get a shorter program!
J, 20 18 bytes
0}:@;@(<@|.;.1)@,]
Thanks to Zgarb for helping with this! Takes a space-separated list as a right argument.
-2 bytes thanks to Zgarb!
JavaScript (ES6), 50 49 bytes
String version:
s=>s.replace(/[^0]+/g,r=>[...r].reverse().join``)
Saved a byte thanks to @Kevin Lau!
Array version (60 bytes):
a=>a.map((n,i)=>n?a[z-i+[...a,0].indexOf(0,i)]:(z=i,0),z=-1)
Retina, 15 bytes
S`0
O%^$`.
¶
0
Try it online! (Slightly modified to run all test cases at once.)
Explanation
S`0
Split the input around 0s that is, put each (possibly empty) run of non-zero digits on its own line.
O%^$`.
This reverses each line, by:
- Applying the stage to each line individually with
%. - Matching each character individually with
.. - Sorting it by the result of the substitution (
$) with the empty string (the empty second line). I.e. it doesn't sort at all, since all sort values are identical. - Then reverses the order of the sorted characters.
Finally:
¶
0
Turn the linefeeds back into 0s.
05AB1E, 6 bytes
Code:
0¡€R0ý
Explanation:
0¡ # Split on zeros
€R # For each item in the array, reverse it
0ý # Join by zeros
Uses CP-1252 encoding. Try it online!.
IPOS, 5 bytes
'0!r%
% splits the input string on zeroes, applies the command r (reverse) to every substring and joins the result back on zeroes.
PowerShell v2+, 45 bytes
($args-split0|%{-join$_[$_.length..0]})-join0
Abusing the implicit casting like there's no tomorrow. Likely can't get much shorter, as there's no builtin for reverse that's shorter than this indexing trick.
Explanation
An example of how this works -- suppose 123045 was the input $args. After the -split on 0, the pipeline would contain an array (123,45). The first loop with |%{...} has the current element $_ equal to 123, which is then implicitly cast as a string, then reversed with the [] indexing. That makes it ('3','2','1') as a char-array. The loop's -join puts that back into a string "321" and leaves it on the pipeline. The next (last) loop iteration reverses the input to "54". So now our pipeline is "321", "54". That's encapsulated in parens () so it's reformed into an array, and re-joined back together with zeros to produce the resultant output string "321054". That's left on the pipeline and output to the console is implicit.
If there are subsequent zeros in the original input, the array would be populated with null elements, so there are the correct number of zeros on the output. For example, 1230045-split0 turns into (123,,45) and things continue as above.
Pyke, 8 bytes
\0cm_\0J
Explanation:
\0c - input().split("0")
m_ - map(reversed, ^)
\0J - "0".join(^)
Ruby, 29 bytes
->x{x.gsub /[^0]*/,&:reverse}