Pisahkan huruf dan angka


15

Paragraf teks memiliki angka dan huruf alfabet tercampur. Tugas Anda adalah untuk memisahkan angka ke sisi kiri dan huruf alfabet ke sisi kanan dalam urutan yang sama dari setiap baris.

Aturan:

  1. Angka adalah bilangan bulat; jadi tidak ada titik desimal, dan tidak ada tanda negatif / positif.
  2. Angka mungkin berdekatan atau tidak, tetapi apa pun masalahnya, mereka harus didorong ke kiri dalam urutan yang sama.
  3. Angka dapat terjadi di antara kata-kata.
  4. Teks ini hanya berisi huruf dan angka alfabet ASCII, beserta spasi, garis bawah, koma, dan titik.
  5. Orang yang melakukan ini dengan penekanan tombol minimum (seperti makro vim) atau paling sedikit jumlah byte dalam kasus scripting adalah pemenangnya.

Teks Contoh:

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.

Output yang diharapkan:

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.

4
@SibiCoder Selamat datang! Anda mungkin ingin menggunakan kotak pasir lain kali. Ini digunakan untuk memposting tantangan sebelum melakukannya di sini. Dengan begitu Anda bisa mendapatkan umpan balik dari pengguna lain dan meningkatkan tantangan
Luis Mendo

1
Saya percaya, menggunakan alfabet untuk huruf berarti adalah ciri khas bahasa Inggris India.
TRiG

2
@AstroDan Keduanya diizinkan secara default.
Adnan

2
Tampak cukup jelas sekarang. @ close-voters - apakah Anda pikir Anda dapat menarik kembali suara Anda sekarang?
Trauma Digital

1
Memperbaiki kasus uji pertama, karena kemungkinan besar tidak lebih dari kesalahan ketik. Saya memberikan suara untuk membuka kembali posting ini.
Bassdrop Cumberwubwubwub

Jawaban:


11

Retina , 14 byte

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

Cobalah online!

Penjelasan

Omemperkenalkan tahap penyortiran. %memberitahu Retina untuk menerapkan transformasi ke setiap baris secara terpisah. $memintanya untuk mengurutkan pertandingan berdasarkan hasil penggantian yang ditentukan.

Regex itu sendiri adalah \d|(.)yang cocok dengan digit, atau apa pun yang ditangkap dalam grup 1. Ini diganti dengan $#1yang merupakan jumlah tangkapan kelompok 1. Yaitu, kunci penyortiran untuk digit adalah 0dan kunci penyortiran untuk semua yang lain adalah 1. Karena pengurutan di Retina stabil, ini hanya memindahkan angka ke kiri dan yang lainnya ke kanan.


9

05AB1E, 14 10 byte

Kode:

|vyþyyþ-¶J

Penjelasan:

|                 # 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

Input Contoh:

Sebuah kata dapat memiliki sejumlah teks seperti 433884,
tetapi semua angka harus dipindahkan ke sisi kiri
tetapi huruf abjad abjad harus dipasangkan di sisi kanan.
Teks itu mungkin mengandung karakter yang teracak seperti hlep atau dfeintino atau bahkan
kata-kata yang tidak bermakna yang digabungkan bersama.

Contoh Output:

433884A kata dapat memiliki sejumlah teks seperti,
89 tetapi semua angka harus dipindahkan sisi kiri
6946 tetapi nilai-nilai alfabet harus ditempelkan di sisi kanan.
4292Teks ini mungkin berisi karakter yang dikocok seperti hlep atau dfeintino atau genap
kata-kata tak berarti yang digabungkan bersama.

Cobalah online


8

Python 3, 64 byte

Tiga solusi setara! Saya tidak bisa memilih.

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

Another variant of the same length: while 1:print(*sorted(input(),key=lambda x:-('/'<x<':')),sep='')
Byte Commander

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

1
It's cool to see a non-golfing language be competitive, even against golfing languages.
DJMcMayhem

@DrGreenEggsandHamDJ Saya senang Anda menyukainya! Saya tidak menambahkan banyak jawaban tetapi saya cukup menyukai solusi yang satu ini! Juga saya yakin beberapa orang akan mengklasifikasikan Perl sebagai bahasa golf, karena itu digambarkan sebagai menulis saja !
Dom Hastings

5

Hoon , 92 83 byte

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

++loremembelah kabel multi-line menjadi (list cord), (trip +<)mengubahnya menjadi pita. ++skidmemisahkan daftar menjadi dua: satu sisi di mana fungsi mengembalikan ya, satu sisi di mana ia mengembalikan tidak. Fungsi kami mencoba mem-parsing karakter dengan ++nud(numerik) dan memeriksa apakah ia mem-parsing sepenuhnya, dan kemudian kami mengelas kedua daftar kembali bersama menjadi rekaman.

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

1
God, I will never not upvote Hoon. ♥
Lynn

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

4

V, 12 bytes

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

V, adalah bahasa golf berbasis string 2D yang belum selesai. Meskipun belum selesai, program ini bekerja pada commit 45 , yang diterbitkan tadi malam, menjadikan ini sebagai jawaban yang bersaing. (Sebagian besar jawaban V saya sebelumnya tidak bersaing.)

Perhatikan, baris baru yang tertinggal diperlukan, meskipun ini disebabkan oleh bug.

Cobalah online!

Penjelasan:

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

¨Ä©¨ä©/²± meluas ke vim regex:

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

yang merupakan non-digit (\D)diikuti oleh digit(\d) , dan tukar mereka.

Karena ini diisi dengan karakter unicode kotor, berikut adalah hexdump yang dapat dibalik:

00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a            ......../...

4
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
DJMcMayhem

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


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

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.



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

You don't need the U because maps automatically cast integers to ranges.
FryAmTheEggman

Oh, thanks for reminding!
Leaky Nun

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!


1
Please update your code. Numbers may come in between words. If yours is updated, then its fine.
SibiCoder

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.

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.


Similar but slightly shorter : string.Join("", s.Where(c => char.IsDigit(c)).Concat(s.Where(c => !char.IsDigit(c))));
Marc

@Marc wow, I've been using this language for 5 years and I didn't know char.IsDigit existed...
Nick Mertin

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 ;

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.


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

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.


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

Input can be multiline; see (updated) challenge
Luis Mendo

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.


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 433884but all the numb89ers has to be moved left side ¤but alph6abetical va9lues has to be pas46ted on right sideThe 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 ¤

1

APL, 28 chars

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

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

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.


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!



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!


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


Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.