Separate alphabets and numbers

15

2

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.

SibiCoder

Posted 2016-05-25T10:20:05.953

Reputation: 259

"all the numbers has to be moved left side but numerical values has to be pasted o right side" ?!?!?! – Leaky Nun – 2016-05-25T10:28:32.023

numbers to leftside and alphabets to right side in each line? Please post a couple of test cases complete with output and including several lines. Also, by numbers do you mean digits or sets of contiguous digits considered as a unit? In the latter case, can the number contain minus sign, decimal point, exponential notation? Voting to close as unclear. I'll remove my vote when clarified – Luis Mendo – 2016-05-25T10:40:52.260

I will update it. I am new here :) – SibiCoder – 2016-05-25T11:09:11.913

4

@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

– Luis Mendo – 2016-05-25T11:15:00.603

In the first output line there is a space missing before the last comma. Also, you should include commas in spec, item 4) – Luis Mendo – 2016-05-25T11:49:58.677

1Using alphabet to mean letter is, I believe, a distinctive of Indian English. – TRiG – 2016-05-25T14:35:50.137

Sorry if this is obvious but I am new here. Does this need to be a function or a program? – AstroDan – 2016-05-25T15:25:45.160

2@AstroDan Both are allowed by default. – Adnan – 2016-05-25T15:26:49.397

@AstroDan Welcome to the site! I hope you have a lot of fun here. :) – James – 2016-05-25T16:54:03.697

2Seems pretty clear now. @close-voters - do you think you can retract your votes now? – Digital Trauma – 2016-05-25T17:44:07.187

@DigitalTrauma, I think the test cases contradict the spec, which requires the alphabetic letters to be moved to the end of the line. The four (out of five) test cases which have punctuation don't respect that requirement. – Peter Taylor – 2016-05-25T20:27:58.370

@PeterTaylor I would say Rule #2 (and the absence of other rules in the same template) clarifies this over what the introductory paragraph says. But perhaps I'm over-relying on the absence of other rules bit. – Digital Trauma – 2016-05-25T20:52:25.537

What happened to the space after like in the first line of the example? – msh210 – 2016-05-25T22:17:04.920

@PeterTaylor Couldn't we just edit the test cases? It's pretty obvious where they're unclear. – James – 2016-05-26T02:58:11.060

1Fixed the first test case, since it was most likely nothing more than a typo. I am voting to reopen this post. – Bassdrop Cumberwubwubwub – 2016-05-26T08:44:34.047

Answers

11

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.

Martin Ender

Posted 2016-05-25T10:20:05.953

Reputation: 184 808

9

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

Emigna

Posted 2016-05-25T10:20:05.953

Reputation: 50 798

8

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='')

Lynn

Posted 2016-05-25T10:20:05.953

Reputation: 55 648

Another variant of the same length: while 1:print(*sorted(input(),key=lambda x:-('/'<x<':')),sep='') – Byte Commander – 2016-05-25T14:13:09.660

5

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

Dom Hastings

Posted 2016-05-25T10:20:05.953

Reputation: 16 415

1It's cool to see a non-golfing language be competitive, even against golfing languages. – James – 2016-05-25T16:55:00.680

@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!

– Dom Hastings – 2016-05-25T20:08:59.427

5

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

RenderSettings

Posted 2016-05-25T10:20:05.953

Reputation: 620

1God, I will never not upvote Hoon. ♥ – Lynn – 2016-05-25T13:51:49.650

4

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

Luis Mendo

Posted 2016-05-25T10:20:05.953

Reputation: 87 464

4

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

James

Posted 2016-05-25T10:20:05.953

Reputation: 54 537

4I'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 – James – 2016-05-25T15:35:31.053

3

CJam, 9 13 16 bytes

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

There isn't f$...

This 13 bytes version nearly works:

{l{A,s-,}$N}h

jimmy23013

Posted 2016-05-25T10:20:05.953

Reputation: 34 042

3

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

Leaky Nun

Posted 2016-05-25T10:20:05.953

Reputation: 45 011

You don't need the U because maps automatically cast integers to ranges. – FryAmTheEggman – 2016-05-25T15:54:33.400

Oh, thanks for reminding! – Leaky Nun – 2016-05-25T19:11:57.237

3

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>

Bassdrop Cumberwubwubwub

Posted 2016-05-25T10:20:05.953

Reputation: 5 707

3

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.

AdmBorkBork

Posted 2016-05-25T10:20:05.953

Reputation: 41 581

3

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.

Maltysen

Posted 2016-05-25T10:20:05.953

Reputation: 25 023

2

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!

Leaky Nun

Posted 2016-05-25T10:20:05.953

Reputation: 45 011

1Please update your code. Numbers may come in between words. If yours is updated, then its fine. – SibiCoder – 2016-05-25T11:19:54.543

2

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

Kevin Cruijssen

Posted 2016-05-25T10:20:05.953

Reputation: 67 575

2

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.

AstroDan

Posted 2016-05-25T10:20:05.953

Reputation: 171

2

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.

Digital Trauma

Posted 2016-05-25T10:20:05.953

Reputation: 64 644

2

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.

Nick Mertin

Posted 2016-05-25T10:20:05.953

Reputation: 161

Similar but slightly shorter : string.Join("", s.Where(c => char.IsDigit(c)).Concat(s.Where(c => !char.IsDigit(c)))); – Marc – 2016-05-26T20:22:30.943

@Marc wow, I've been using this language for 5 years and I didn't know char.IsDigit existed... – Nick Mertin – 2016-05-28T03:31:45.883

2

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 ;

fede s.

Posted 2016-05-25T10:20:05.953

Reputation: 945

2

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.

John Red

Posted 2016-05-25T10:20:05.953

Reputation: 151

1

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.

Toby Speight

Posted 2016-05-25T10:20:05.953

Reputation: 5 058

1

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!

Toby Speight

Posted 2016-05-25T10:20:05.953

Reputation: 5 058

1

Japt v2, 14 12 bytes

-2 bytes thanks to ETHproductions

®o\d +Zr\d}R

Run it

Oliver

Posted 2016-05-25T10:20:05.953

Reputation: 7 160

1

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

Stewie Griffin

Posted 2016-05-25T10:20:05.953

Reputation: 43 471

Input can be multiline; see (updated) challenge – Luis Mendo – 2016-05-25T11:54:45.647

1

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.

mark

Posted 2016-05-25T10:20:05.953

Reputation: 251

1

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 ¤

Jeto

Posted 2016-05-25T10:20:05.953

Reputation: 1 601

1

APL, 28 chars

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

lstefano

Posted 2016-05-25T10:20:05.953

Reputation: 850

1

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,"

sudee

Posted 2016-05-25T10:20:05.953

Reputation: 551

0

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!

gggg

Posted 2016-05-25T10:20:05.953

Reputation: 1 715

0

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

mypetlion

Posted 2016-05-25T10:20:05.953

Reputation: 702

0

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!

gastropner

Posted 2016-05-25T10:20:05.953

Reputation: 3 264

0

Jelly, 10 bytes

Ỵðf;ḟµ€ØDY

Try it online!

Erik the Outgolfer

Posted 2016-05-25T10:20:05.953

Reputation: 38 134

0

K4, 21 bytes

Solution:

{x(&a),&~a:x in .Q.n}

Example:

q)k){x(&a),&~a:x in .Q.n}"The text might con4tain chara29cters s2huffled like hlep or dfeintino or even"
"4292The text might contain characters shuffled like hlep or dfeintino or even"

Explanation:

{x(&a),&~a:x in .Q.n} / the solution
{                   } / lambda function, implicit arg x
                .Q.n  / list "0123456789"
           x in       / true/false for each character of x
         a:           / save as variable a
        ~             / negate (so non numerics)
       &              / indices where true
      ,               / joined with
  (&a)                / indices where true
 x                    / index into x at these indices

Bonus:

23 byte implementation in K (oK):

{x(&a),&~a:x in 48+!10}

Try it online!

streetster

Posted 2016-05-25T10:20:05.953

Reputation: 3 635

0

ReRegex, 25 bytes

([^\n\d])(\d)/$2$1/#input

Try it online!

ATaco

Posted 2016-05-25T10:20:05.953

Reputation: 7 898