15
\$\begingroup\$

A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line.

Rules:

  1. Numbers are plain integers; so no decimal point, and no negative/positive signs.
  2. Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order.
  3. Numbers may occur in between words.
  4. The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots.
  5. The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner.

Example Text:

A word can have any number of text like 433884,
but all the numb89ers has to be moved left side 
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Expected output:

433884A word can have any number of text like ,
89but all the numbers has to be moved left side 
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.
\$\endgroup\$
  • 4
    \$\begingroup\$ @SibiCoder Welcome aboard then! You might want to use the sandbox next time. It's used for posting challenges before doing it here. That way you can get feedback from other users and improve the challenge \$\endgroup\$ – Luis Mendo May 25 '16 at 11:15
  • 1
    \$\begingroup\$ Using alphabet to mean letter is, I believe, a distinctive of Indian English. \$\endgroup\$ – TRiG May 25 '16 at 14:35
  • 2
    \$\begingroup\$ @AstroDan Both are allowed by default. \$\endgroup\$ – Adnan May 25 '16 at 15:26
  • 2
    \$\begingroup\$ Seems pretty clear now. @close-voters - do you think you can retract your votes now? \$\endgroup\$ – Digital Trauma May 25 '16 at 17:44
  • 1
    \$\begingroup\$ Fixed the first test case, since it was most likely nothing more than a typo. I am voting to reopen this post. \$\endgroup\$ – Bassdrop Cumberwubwubwub May 26 '16 at 8:44

33 Answers 33

11
\$\begingroup\$

Retina, 14 bytes

O%$`\d|(.)
$#1

Try it online!

Explanation

O introduces a sorting stage. % tells Retina to apply the transformation to each line separately. $ tells it to sort the matches by the result of the specified substitution.

The regex itself is \d|(.) which either matches a digit, or anything else which is captured into group 1. This is substituted with $#1 which is the number of captures of group 1. That is, the sorting key for digits is 0 and the sorting key for everything else is 1. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right.

\$\endgroup\$
9
\$\begingroup\$

05AB1E, 14 10 bytes

Code:

|vyþyyþ-¶J

Explanation:

|                 # push all lines in input as array of strings
 v                # for each line in array
  yþ              # push only digits from line
    yyþ-          # push line without digits
        ¶         # push newline char
         J        # join as string
                  # end loop and print explicitly

Example Input:

A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless words co43mbined togeth81er.

Example Output:

433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
4381meaningless words combined together.

Try it online

\$\endgroup\$
8
\$\begingroup\$

Python 3, 64 bytes

Three equivalent solutions! I can’t pick.

while 1:print(*sorted(input(),key=lambda x:-x.isdigit()),sep='')
while 1:print(*sorted(input(),key=lambda x:x<'0'or'9'<x),sep='')
while 1:print(*sorted(input(),key=str.isdigit,reverse=1),sep='')
\$\endgroup\$
  • \$\begingroup\$ Another variant of the same length: while 1:print(*sorted(input(),key=lambda x:-('/'<x<':')),sep='') \$\endgroup\$ – Byte Commander May 25 '16 at 14:13
5
\$\begingroup\$

Perl, 17 bytes

16 bytes code + 1 switch

s/\d/!print$&/ge

Requires -p.

Usage

perl -pe 's/\d/!print$&/ge' <<< 'a1b2c3d4e5f6'
123456abcdef

Alternatively:

print/\d/g,/\D/g

Requires -n.

Usage

perl -ne 'print/\d/g,/\D/g' <<< 'a1b2c3d4e5f6'
123456abcdef
\$\endgroup\$
  • 1
    \$\begingroup\$ It's cool to see a non-golfing language be competitive, even against golfing languages. \$\endgroup\$ – DJMcMayhem May 25 '16 at 16:55
  • \$\begingroup\$ @DrGreenEggsandHamDJ I'm glad you liked it! I don't add many answers but I quite liked the solution of this one! Also I'm sure some people would classify Perl as a golfing language, since its described as write only! \$\endgroup\$ – Dom Hastings May 25 '16 at 20:08
5
\$\begingroup\$

Hoon, 92 83 bytes

|*
*
(turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))

++lore splits a multi-line cord into a (list cord), (trip +<) turns it into a tape. ++skid seperates a list in two: one side where the function returns yes, one side where it returns no. Our function tries to parse the character with ++nud (numeric) and checks if it parses fully, and then we weld the two lists back together into a tape.

> %.
  '''
  A word can have any number of text like 433884,
  but all the numb89ers has to be moved left side 
  but alph6abetical va9lues has to be pas46ted on right side.
  The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
  meaningless1 words co43mbined togeth81er.
  '''
  |*
  *
  (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))
<<
  "433884A word can have any number of text like ,"
  "89but all the numbers has to be moved left side "
  "6946but alphabetical values has to be pasted on right side."
  "4292The text might contain characters shuffled like hlep or dfeintino or even"
  "14381meaningless words combined together."
>>
\$\endgroup\$
  • 1
    \$\begingroup\$ God, I will never not upvote Hoon. ♥ \$\endgroup\$ – Lynn May 25 '16 at 13:51
4
\$\begingroup\$

MATL, 13 12 bytes

`jt4Y2m&)hDT

Exits with an error (allowed by default), producing the correct output.

Try it online!

Explanation

`          T    % infinite loop
 j              % input one line as a string
  t             % duplicate
   4Y2          % predefined literal: '0123456789'
      m         % true for elements of string that are digits, false for the rest
       &)       % two-output indexing: push digits, then non-digits
         h      % concatenate the two strings
          D     % display
\$\endgroup\$
4
\$\begingroup\$

V, 12 bytes

òí¨Ä©¨ä©/²±
​

V, is an unfinished, 2D string based golfing language. Although it is unfinished, this program works as of commit 45, which was published last night, making this a competing answer. (Most of my previous V answers were non-competing.)

Note, the trailing newline is necessary, although this is due to a bug.

Try it online!

Explanation:

ò            #Recursively, do:
 í           #Substitute on every line
  ¨Ä©¨ä©/²±  #The following regex. 

¨Ä©¨ä©/²± expands into the vim regex:

:%s/\(\D\)\(\d\)/\2\1

which is a non-digit (\D) followed by a digit (\d), and swap them.

Since this is filled with gross unicode characters, here is a reversible hexdump:

00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a            ......../...
\$\endgroup\$
  • 4
    \$\begingroup\$ I'm really proud of this answer. With some more work on the language, this could easily be 4-5 bytes shorter, but it's cool to see the features I've been working on actually be useful. This would not have worked a day ago. =D \$\endgroup\$ – DJMcMayhem May 25 '16 at 15:35
3
\$\begingroup\$

Javascript ES6, 40 bytes

a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

Tried several other solutions, but couldn't get it smaller than this.
My first try was a=>[...a.match(/\d/g),...a.match(/\D/g)].join`` but that's 5 bytes longer

Try it here

f=
a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

a.innerHTML='<pre>'+
  ['A word can have any number of text like 433884,',
 'but all the numb89ers has to be moved left side',
 'but alph6abetical va9lues has to be pas46ted on right side.',
 'The text might con4tain chara29cters s2huffled like hlep or dfeintino or even',
 'meaningless words co43mbined togeth81er.'].map(b=>f(b)).join('<br>')+'</pre>'
<div id=a>

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

CJam, 9 13 16 bytes

qN/{{A,s-,}$}%N*

There isn't f$...

This 13 bytes version nearly works:

{l{A,s-,}$N}h
\$\endgroup\$
3
\$\begingroup\$

PowerShell v2+, 55 bytes

$args[0]-split"`n"|%{($_-replace'\D')+($_-replace'\d')}

Due to the need to support multi-line input, we have to encapsulate our -replace statements with a loop and -split on newlines. Otherwise basically equivalent to the JavaScript solution.

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

Pyth - 11 bytes

Don't like my grouping test. Takes input as list of lines, tell me if that's not ok.

jms_.g}k`MT

Try it online here.

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

Pyth, 16 15 bytes

1 byte thanks to @FryAmTheEggman.

jms+@J`MTd-dJ.z

Try it online!

Sample input:

A word can have any number of text like 433884,
but all the numb89ers has to be moved left side 
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Sample output:

433884A word can have any number of text like ,
89but all the numbers has to be moved left side 
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

How it works

jms+@J`MTd-dJ.z

 m           .z    for each line (d):
         d           yield d (the line)
     J                 assign J to
        T              [0,1,2,3,...,9]
      `M               with each number converted to string
    @                intersect with J
   +                 append:
          -dJ          filter d for characters not in J
  s                  convert to one string
j                  join by newline
\$\endgroup\$
  • \$\begingroup\$ You don't need the U because maps automatically cast integers to ranges. \$\endgroup\$ – FryAmTheEggman May 25 '16 at 15:54
  • \$\begingroup\$ Oh, thanks for reminding! \$\endgroup\$ – Leaky Nun May 25 '16 at 19:11
2
\$\begingroup\$

Retina, 16 bytes

Stable bubble sort.

%+`(\D)(\d)
$2$1

Sample input:

A word can have any number of text like 433884,
but all the numb89ers has to be moved left side 
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Sample output:

433884A word can have any number of text like ,
89but all the numbers has to be moved left side 
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Please update your code. Numbers may come in between words. If yours is updated, then its fine. \$\endgroup\$ – SibiCoder May 25 '16 at 11:19
2
\$\begingroup\$

C#, 59 bytes

I=>Regex.Replace(I,"[^0-9]","")+Regex.Replace(I,@"\d+","");

A simple C# lambda function using regex.

Sample output

433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.
\$\endgroup\$
2
\$\begingroup\$

C# (LINQ), 110 bytes

s=>string.join("",s.Where(c=>"0123456789".Contains(c).Concat(s.SelectMany(c=>new[]{c}.Except("0123456789"))));

Not the shortest solution, by far, but I thought this would be a good use of LINQ.

\$\endgroup\$
  • \$\begingroup\$ Similar but slightly shorter : string.Join("", s.Where(c => char.IsDigit(c)).Concat(s.Where(c => !char.IsDigit(c)))); \$\endgroup\$ – Marc May 26 '16 at 20:22
  • \$\begingroup\$ @Marc wow, I've been using this language for 5 years and I didn't know char.IsDigit existed... \$\endgroup\$ – Nick Mertin May 28 '16 at 3:31
2
\$\begingroup\$

Factor 61

[ "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ]

It's a naive approach.

"\n"split splits the string on top of the stack into lines. Then, for each line:

  1. [ digit? ] partition splits each line into digits-only and non-digits-only
  2. [ write ] bi@ outputs both, and nl prints a newline.

PS:

As a word 90 bytes (71 if you replace the-factorish-long-name with 1 letter):

: numbers-to-the-front ( s -- ) "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ;
\$\endgroup\$
2
\$\begingroup\$

Pyth, 14 bytes

FG.zo_:N"\d"0G

Try it online!

Explanation:

FG             : For every G in ...
  .z           : the-list-where-lines-of-input-are-stored ...
               : (implicitly print)
    o        G : sorted G ...
     _N        : where, a negative key is given ...
       :"\d"0  : to the individual character if it is a digit

The logic of the solution is the same as in Lynn's answer.

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

Java 8, 130 126 86 bytes

a->{for(String s:a)System.out.println(s.replaceAll("\\D","")+s.replaceAll("\\d",""));}

-4 bytes converting Java 7 to 8 and removing an unused character
-40 bytes converting program to function and changing [^\\d] to \\D

Explanation:

Try it here.

a->{                             // Method with String-array parameter and no return-type
  for(String s:a)                //  Loop over the array
    System.out.println(          //   Print with a trailing new-line:
      s.replaceAll("\\D","")     //    All digits,
      +s.replaceAll("\\d",""));  //    plus all non-digits
\$\endgroup\$
2
\$\begingroup\$

GNU Sed, 28

Score includes +1 for -r option to sed.

:
s/([^0-9])([0-9])/\2\1/
t

Repeatedly switches one non-number character followed by one number character until no more substitutions are made.

Sadly sed regexes don't have \d or \D, so these have to be written out longhand.

Ideone.

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

Octave, 37 32 bytes

@(s)disp([s(x=s>47&s<58),s(~x)])

ans('The text might con4tain chara29cters s2huffled like hlep or dfeintino or even')
4292The text might contain characters shuffled like hlep or dfeintino or even
\$\endgroup\$
  • \$\begingroup\$ Input can be multiline; see (updated) challenge \$\endgroup\$ – Luis Mendo May 25 '16 at 11:54
1
\$\begingroup\$

Clojure, 113 bytes

(fn[s](map(fn[x](println(apply str(sort-by #(when-not(Character/isDigit %)1)x))))(clojure.string/split-lines s)))

Sorts digits to the beginning of the line.

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

Oracle SQL 11.2, 131 bytes

The lines in the input string are separated by '¤'. That way it is not necessary to create a table to use as the input.

A word can have any number of text like 433884,¤but all the numb89ers has to be moved left side ¤but alph6abetical va9lues has to be pas46ted on right side.¤The text might con4tain chara29cters s2huffled like hlep or dfeintino or even¤meaningless1 words co43mbined togeth81er.

Query :

SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'));

Un-golfed

SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||  -- Every number
       REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')     -- Every character not a number   
FROM   XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))  -- Split on ¤
\$\endgroup\$
1
\$\begingroup\$

APL, 28 chars

{⍵[⍋(~⍵∊⎕D)++\¯1⌽⍵=⎕UCS 13]}
\$\endgroup\$
1
\$\begingroup\$

Haskell, 60 bytes

import Data.List;g(n,l)=n++l;f=g.partition(`elem`['0'..'9'])

Usage

f "A word can have any number of text like 433884,"
\$\endgroup\$
1
\$\begingroup\$

Sed, 35 bytes

h
s/[0-9]//g
x
s/[^0-9]//g
G
s/\n//

This makes a copy of the line, removes digits from one copy and letters from the other, before recombining them.

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

Bash, 42 bytes

read a&&echo "${a//[^0-9]}${a//[0-9]}"&&$0

Be warned that this recursive implementation forks a new process for each line of input!

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

Japt v2, 14 12 bytes

-2 bytes thanks to ETHproductions

®o\d +Zr\d}R

Run it

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

Julia 0.6, 77 bytes

x->(l=r="";for c=x
c=='\n'?(println(l*r);l=r=""):'/'<c<':'?(l*=c):(r*=c)
end)

Anonymous function taking a string and printing output. Loops over characters, adding them to the left l or right r buffers until it finds a newline, then it prints and empties buffers. Lots of potential useful constructs like sort, filter and logical indexing (indexing with an array of boolean values) don't work on Strings.

Try it online!

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

Vim, 30 keystrokes

qr:%s/\v(\D+)(\d+)/\2\1/<Enter>@rq@r

Record a search and replace action that moves digits to the left of non-digits. Call the macro recursively until an exception is thrown by the pattern not being found (when there are no more digits to the right of any non-digits).

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

C (gcc), 106 bytes

g(s,x)char*s;{for(;*s;s++)isdigit(*s)^x&&putchar(*s);}f(s,n)char**s;{for(;n--;puts(""))g(*s,0),g(*s++,1);}

Try it online!

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