Rotasi ganda


28

Deskripsi Tantangan

Siklus semua huruf dari bagian pertama alfabet di satu arah, dan huruf dari bagian kedua alfabet di yang lain. Karakter lain tetap di tempatnya.

Contohnya

1: Halo dunia

Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution

2: codegolf

codegolf
c deg lf
 o   o  

f cde gl
 o   o  

focdeogl

3 .: string kosong

(empty string) //Input
(empty string) //Output

Memasukkan

String yang Anda butuhkan untuk memutar. Mungkin kosong. Tidak mengandung baris baru.

Keluaran

String input yang diputar, membuntuti baris baru
, Dapat ditulis ke layar atau dikembalikan oleh fungsi.

Aturan

  • Tidak ada celah yang diizinkan
  • Ini adalah kode-golf, jadi kode terpendek dalam byte yang menyelesaikan masalah akan menang
  • Program harus mengembalikan solusi yang benar

1
Ingatkan saya, huruf apa yang berasal dari bagian pertama alfabet, huruf apa dari bagian kedua?
user48538

Namun tetap saja, tantangan yang bagus.
user48538

4
Babak pertama: ABCDEFGHIJKLMabcdefghijklm Babak kedua: NOPQRSTUVWXYZnopqrstuvwxyz
Paul Schmitz

Lucu bahwa codegolf menjadi anagram itu sendiri
haskeller bangga

Jawaban:


0

MATL , 29 byte

FT"ttk2Y213:lM@*+)m)1_@^YS9M(

Cobalah online!

Penjelasan

FT        % Push arrray [0 1]
"         % For each
  t       %   Duplicate. Takes input string implicitly in the first iteration
  tk      %   Duplicate and convert to lower case
  2Y2     %   Predefined string: 'ab...yz'
  13:     %   Generate vector [1 2 ... 13]
  lM      %   Push 13 again
  @*      %   Multiply by 0 (first iteration) or 1 (second): gives 0 or 13
  +       %   Add: this leaves [1 2 ... 13] as is in the first iteration and
          %   transforms it into [14 15 ... 26] in the second
  )       %   Index: get those letters from the string 'ab...yz'
  m       %   Ismember: logical index of elements of the input that are in 
          %   that half of the alphabet
  )       %   Apply index to obtain those elements from the input
  1_@^    %   -1 raised to 0 (first iteration) or 1 (second), i.e. 1 or -1
  YS      %   Circular shift by 1 or -1 respectively
  9M      %   Push the logical index of affected input elements again
  (       %   Assign: put the shifted chars in their original positions
          % End for each. Implicitly display

9

Retina , 55 byte

O$i`[a-m](?=.*([a-m]))?
$1
O$i`((?<![n-z].*))?[n-z]
$#1

Cobalah online!

Gunakan dua tahap penyortiran untuk memutar huruf babak pertama dan kedua secara terpisah.


4

05AB1E , 44 43 42 byte

Оn2äø€J2ä©`ŠÃÁUÃÀVv®`yåiY¬?¦VëyåiX¬?¦Uëy?

Penjelasan

Buat daftar huruf alfabet dari kedua kasus. ['Aa','Bb', ..., 'Zz']

Оn2äø€J

Membagi menjadi 2 bagian dan menyimpan salinan di register.

2ä©

Ekstrak surat dari input yang merupakan bagian dari semester 1 alfabet, putar dan toko di X .

`ŠÃÁU

Ekstrak surat dari input yang merupakan bagian dari 2 setengah dari alfabet, putar dan toko di Y .

ÃÀV

Loop utama

v                         # for each char in input
 ®`                       # push the lists of first and second half of the alphabet
   yåi                    # if current char is part of the 2nd half of the alphabet
      Y¬?                 # push the first char of the rotated letters in Y
         ¦V               # and remove that char from Y
           ëyåi           # else if current char is part of the 1st half of the alphabet
               X¬?        # push the first char of the rotated letters in X
                  ¦U      # and remove that char from X
                    ëy?   # else print the current char

Cobalah online!

Catatan: terkemuka The Ðdapat dihilangkan dalam 2sable untuk 41 solusi byte.


4
<s>44</s>masih terlihat seperti 44.
KarlKastor


3

Javascript (ES6), 155 142 138 byte

s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

Sunting: disimpan 3 4 byte dengan menggunakan unshift()(terinspirasi oleh jawaban edc65)

Bagaimana itu bekerja

The RFungsi mengambil metode array sebagai parameter nya m:

R = m => s = s.replace(/[a-z]/gi, c => (c < 'N' | c < 'n' & c > 'Z' ? a : b)[m](c))

Ini pertama kali digunakan dengan pushmetode untuk menyimpan karakter yang diekstraksi dalam a[](bagian pertama dari alfabet) dan b[](bagian kedua dari alfabet). Setelah array ini diputar, R()disebut kali kedua dengan shiftmetode untuk menyuntikkan karakter baru ke string terakhir.

Oleh karena itu sintaks yang sedikit tidak biasa: R`push`dan R`shift`.

Demo

let f =
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

console.log("Hello_world", "=>", f("Hello_world"));
console.log("codegolf", "=>", f("codegolf"));
console.log("HELLO_WORLD", "=>", f("HELLO_WORLD"));


Simpan 1 byte lebih banyak dengan menghindari komaa.unshift(a.pop(b.push(b.shift())))
edc65


2

Python, 211 Bytes

x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
u=filter(y,x)
d=filter(z,x)
r=l=""
for i in x:
 if y(i):r+=u[-1];u=[i]
 else:r+=i
for i in r[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
print l

Yang terbaik yang bisa saya lakukan. Mengambil string dari STDIN dan mencetak hasilnya ke STDOUT.

alternatif dengan 204 Bytes, tetapi sayangnya mencetak baris baru setelah setiap karakter:

x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
f=filter
u=f(y,x)
d=f(z,x)
r=l=""
for i in x[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
for i in l:
 a=i
 if y(i):a=u[-1];u=[i]
 print a

1

Python 2, 149 byte

s=input();g=lambda(a,b):lambda c:a<c.lower()<b
for f in g('`n'),g('m{'):
 t='';u=filter(f,s)[-1:]
 for c in s:
  if f(c):c,u=u,c
  t=c+t
 s=t
print s

2
Tidak yakin siapa yang menurunkan Anda, tetapi saya berhasil kembali dengan meningkatkan. Selamat datang di PPCG! Mungkin Anda bisa menambahkan penjelasan atau ide dari kode Anda ? Saya berasumsi di sini bahwa downvote dilakukan secara otomatis setelah diedit oleh Beta Decay oleh pengguna Komunitas, berdasarkan komentar @Dennis dalam jawaban ini .
Kevin Cruijssen

1

JavaScript (ES6), 144

Menggunakan parseIntbasis 36 untuk memisahkan babak pertama, babak kedua dan lainnya. Untuk karakter apa pun c, saya mengevaluasi y=parseInt(c,36)demikian

  • c '0'..'9' -> y 0..9
  • c 'a'..'m' or 'A'..'M' -> y 10..22
  • c 'n'..'z' or 'N'..'Z' -> y 23..35
  • c any other -> y NaN

Jadi y=parseInt(c,36), x=(y>22)+(y>9)berikan x==1untuk babak pertama, x==2untuk babak kedua dan x==0untuk yang lainnya (sepertiNaN > angka salah)

Langkah pertama: string input dipetakan ke array 0,1 atau 2. Sementara semua karakter string ditambahkan ke 3 array. Pada akhir langkah pertama ini array 1 dan 2 diputar dalam arah yang berlawanan.

Langkah kedua: array yang dipetakan dipindai, membangun kembali string output yang mengambil setiap karakter dari 3 array sementara.

s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop(q.push(q.shift())))).join``

Kurang golf

s=>[...s].map(
  c => a[ y = parseInt(c, 36), x=(y > 22) + (y > 9)].push(c) 
       && x,
  a = [ [], p=[], q=[] ]
).map(
  x => a[x].shift(),  // get the output char from the right temp array
  p.unshift(p.pop()), // rotate p
  q.push(q.shift())   // rotate q opposite direction
).join``

Uji

f=
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop()),q.push(q.shift())).join``

function update() {
  O.textContent=f(I.value);
}

update()
<input id=I oninput='update()' value='Hello, world'>
<pre id=O></pre>


0

Perl. 53 byte

Termasuk +1 untuk -p

Jalankan dengan input pada STDIN:

drotate.pl <<< "Hello_world"

drotate.pl:

#!/usr/bin/perl -p
s%[n-z]%(//g,//g)[1]%ieg;@F=/[a-m]/gi;s//$F[-$.--]/g

0

Python, 142 133 byte

Variasi yang lebih baik pada tema:

import re
def u(s,p):x=re.split('(?i)([%s])'%p,s);x[1::2]=x[3::2]+x[1:2];return ''.join(x)
v=lambda s:u(u(s[::-1],'A-M')[::-1],'N-Z')

ungolfed:

import re
def u(s,p):
    x = re.split('(?i)([%s])'%p,s)  # split returns a list with matches at the odd indices
    x[1::2] = x[3::2]+x[1:2]
    return ''.join(x)

def v(s):
  w = u(s[::-1],'A-M')
  return u(w[::-1],'N-Z')

solusi sebelumnya:

import re
def h(s,p):t=re.findall(p,s);t=t[1:]+t[:1];return re.sub(p,lambda _:t.pop(0),s)
f=lambda s:h(h(s[::-1],'[A-Ma-m]')[::-1],'[N-Zn-z]')

ungolfed:

import re
def h(s,p):                              # moves matched letters toward front
    t=re.findall(p,s)                    # find all letters in s that match p
    t=t[1:]+t[:1]                        # shift the matched letters
    return re.sub(p,lambda _:t.pop(0),s) # replace with shifted letter

def f(s):
    t = h(s[::-1],'[A-Ma-m]')            # move first half letters toward end
    u = h(t[::-1],'[N-Zn-z]')            # move 2nd half letters toward front
    return u

0

Ruby, 89 byte

f=->n,q,s{b=s.scan(q).rotate n;s.gsub(q){b.shift}}
puts f[1,/[n-z]/i,f[-1,/[a-m]/i,gets]]

0

PHP, 189 byte

Cukup sulit untuk bermain golf ... Ini proposal saya:

for($p=preg_replace,$b=$p('#[^a-m]#i','',$a=$argv[1]),$i=strlen($b)-1,$b.=$b,$c=$p('#[^n-z]#i','',$a),$c.=$c;($d=$a[$k++])!=='';)echo strpos(z.$b,$d)?$b[$i++]:(strpos(a.$c,$d)?$c[++$j]:$d);
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.