이중 회전


28

도전 설명

알파벳의 첫 번째 부분의 모든 문자를 한 방향으로 순환하고 알파벳의 후반의 문자를 다른 방향으로 순환하십시오. 다른 캐릭터는 그대로 남아 있습니다.

1 : 안녕하세요 세계

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
c deg lf
 o   o  

f cde gl
 o   o  

focdeogl

3 .: 빈 문자열

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

입력

회전해야하는 문자열입니다. 비어있을 수 있습니다. 줄 바꿈이 포함되어 있지 않습니다.

산출

회전 된 입력 문자열, 후행 줄 바꾸기 허용
화면에 쓰거나 함수에 의해 반환 될 수 있습니다.

규칙

  • 허점 없음
  • 이것은 코드 골프이므로 문제를 해결하는 가장 짧은 바이트 코드
  • 프로그램이 올바른 솔루션을 반환해야합니다

1
알파벳의 전반부에서 어떤 문자가 있는지, 두 번째 문자에서 어떤 문자가 있습니까?
user48538

그러나 여전히 좋은 도전입니다.
user48538

4
전반 : ABCDEFGHIJKLMabcdefghijklm 후반 : NOPQRSTUVWXYZnopqrstuvwxyz
Paul Schmitz

코드 골프 자체의 아나그램이 된 것은 재미있다
자랑스런 Haskeller

답변:


0

MATL , 29 바이트

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

온라인으로 사용해보십시오!

설명

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


4

05AB1E , 44 43 42 바이트

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

설명

두 경우 모두 알파벳 문자 목록을 생성하십시오. ['Aa','Bb', ..., 'Zz']

Оn2äø€J

두 부분으로 나누고 사본을 레지스터에 저장하십시오.

2ä©

알파벳의 전반부의 일부인 입력에서 문자를 추출하고 회전하여 X에 저장하십시오 .

`ŠÃÁU

알파벳의 후반부에 속하는 입력에서 문자를 추출하고 회전하여 Y에 저장하십시오 .

ÃÀV

메인 루프

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

온라인으로 사용해보십시오!

주 : 주요한는 Ð생략 될 수 2sable A에 대한 41 바이트 용액.


4
<s>44</s>여전히 44처럼 보인다.
KarlKastor


3

자바 (ES6) 155 142 138 바이트

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)

편집 : 사용하여 3 4 바이트 저장 unshift()(edc65의 답변에서 영감을 얻음)

작동 원리

R함수는 배열 메소드를 매개 변수로 사용합니다 m.

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

push추출 된 문자를 a[](알파벳의 첫 번째 절반) 및 b[](알파벳의 두 번째 절반 ) 에 저장 하는 방법 과 함께 사용됩니다 . 이러한 배열이 회전되면 마지막 문자열에 새 문자를 삽입하는 방법으로 R()두 번째로 호출 shift됩니다.

따라서 약간 특이한 구문 : R`push`R`shift`.

데모

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"));


쉼표를 사용하지 않고 1 바이트 더 절약a.unshift(a.pop(b.push(b.shift())))
edc65


2

파이썬, 211 바이트

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

내가 할 수있는 최선. STDIN에서 문자열을 가져 와서 결과를 STDOUT에 인쇄합니다.

204 바이트의 대안이지만 각 문자 다음에 줄 바꿈을 불행히도 인쇄합니다.

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

파이썬 2, 149 바이트

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
누가 당신을 다운 보트했는지는 모르겠지만, 나는 업 보팅으로 다시 0을 만들었습니다. PPCG에 오신 것을 환영합니다! 아마도 코드에 대한 설명이나 아이디어를 추가 할 수 있습니까? 나는 이 답변 에서 @Dennis 의 의견에 따라 커뮤니티 사용자 가 Beta Decay에 의해 편집 한 후 downvote가 자동으로 수행되었다고 가정합니다 .
Kevin Cruijssen

1

자바 스크립트 (ES6), 144

parseInt기초 36을 사용하여 전반, 후반 및 기타를 분리합니다. 모든 문자를 들면 c, 나는 평가 y=parseInt(c,36)그래서

  • 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

그래서 y=parseInt(c,36), x=(y>22)+(y>9)x==1, 전반기 x==2후반과 x==0(임의의 다른 대해 NaN> 개수가 false)

첫 번째 단계 : 입력 문자열이 0, 1 또는 2의 배열에 매핑됩니다. 한편 모든 문자열 문자는 3 개의 배열에 추가되었습니다. 이 제 1 단계의 끝에서, 어레이 1 및 2는 반대 방향으로 회전된다.

두 번째 단계 : 매핑 된 배열을 스캔하여 3 개의 임시 배열에서 각 문자를 가져 오는 출력 문자열을 다시 작성합니다.

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

덜 골프

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

테스트

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

펄. 53 바이트

에 +1 포함 -p

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

파이썬 142 133 바이트

주제에 대한 더 나은 변형 :

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

언 골프 :

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

이전 솔루션 :

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

언 골프 :

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

루비, 89 바이트

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 바이트

골프하기가 매우 어렵다 ... 여기 내 제안이있다 :

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);
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.