Doppia rotazione


28

Descrizione della sfida

Scorri tutte le lettere della prima parte dell'alfabeto in una direzione e le lettere della seconda metà dell'alfabeto nell'altra. Altri personaggi rimangono al loro posto.

Esempi

1: Ciao mondo

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 .: stringa vuota

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

Ingresso

Stringa che devi ruotare. Potrebbe essere vuoto Non contiene newline.

Produzione

Stringa di input ruotata, trascinamento della nuova riga consentita
Può essere scritta sullo schermo o restituita da una funzione.

Regole

  • Non sono ammesse scappatoie
  • Questo è code-golf, quindi vince il codice più breve in byte che risolve il problema
  • Il programma deve restituire la soluzione corretta

1
Ricordami, quali lettere sono della prima metà dell'alfabeto, quali lettere sono della seconda?
user48538

Ma comunque, una bella sfida.
user48538

4
Primo tempo: ABCDEFGHIJKLMabcdefghijklm Secondo tempo: NOPQRSTUVWXYZnopqrstuvwxyz
Paul Schmitz

Divertente che codegolf diventi un anagramma di se stesso
orgoglioso haskeller il

Risposte:


0

MATL , 29 byte

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

Provalo online!

Spiegazione

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

Provalo online!

Utilizza due fasi di ordinamento per ruotare le lettere della prima e della seconda metà separatamente.


4

05AB1E , 44 43 42 byte

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

Spiegazione

Genera un elenco delle lettere dell'alfabeto di entrambi i casi. ['Aa','Bb', ..., 'Zz']

Оn2äø€J

Dividi in 2 parti e archivia una copia nel registro.

2ä©

Estrarre le lettere di input che sono una parte del 1 ° semestre dell'alfabeto, ruotarlo e conservare in X .

`ŠÃÁU

Estrarre le lettere provenienti dall'ingresso che fanno parte della 2a metà dell'alfabeto, ruotarla e conservare in Y .

ÃÀV

Anello principale

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

Provalo online!

Nota: il lead Ðpuò essere omesso in 2sable per una soluzione da 41 byte.


4
<s>44</s>sembra ancora 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)

Modifica: salvato 3 4 byte utilizzando unshift()(ispirato alla risposta di edc65)

Come funziona

La Rfunzione utilizza un metodo array come parametro m:

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

Viene prima utilizzato con il pushmetodo per memorizzare i caratteri estratti in a[](prima metà dell'alfabeto) e b[](seconda metà dell'alfabeto). Una volta che questi array sono stati ruotati, R()viene chiamato una seconda volta con il shiftmetodo per iniettare i nuovi caratteri nella stringa finale.

Da qui la sintassi leggermente insolita: R`push`e R`shift`.

dimostrazione

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


Salva un altro byte evitando una virgolaa.unshift(a.pop(b.push(b.shift())))
edc65


2

Python, 211 byte

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

Il meglio che potrei fare. Prende la stringa da STDIN e stampa il risultato su STDOUT.

alternativa con 204 byte, ma sfortunatamente stampa una nuova riga dopo ogni carattere:

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
Non sono sicuro di chi ti ha votato per il downgrade, ma ho fatto di nuovo 0 aumentando il voto. Benvenuti in PPCG! Forse potresti aggiungere una spiegazione o un ideone al tuo codice ? Sto assumendo qui che il downvote sia stato fatto automaticamente dopo la modifica da Decadimento Beta da parte dell'utente della Community, sulla base del commento di @Dennis in questa risposta .
Kevin Cruijssen,

1

JavaScript (ES6), 144

Usando la parseIntbase 36 per separare la prima metà, la seconda metà e l'altra. Per ogni personaggio c, lo valuto y=parseInt(c,36)così

  • 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

Quindi y=parseInt(c,36), x=(y>22)+(y>9)x==1per la prima metà, x==2per la seconda metà e x==0per qualsiasi altro (poiché NaN> qualsiasi numero è falso)

Primo passo: la stringa di input viene mappata su un array di 0,1 o 2. Nel frattempo tutti i caratteri di stringa vengono aggiunti a 3 array. Al termine di questo primo passaggio, l'array 1 e 2 vengono ruotati in direzioni opposte.

Secondo passaggio: la matrice mappata viene scansionata, ricostruendo una stringa di output che prende ogni carattere dalle 3 matrici temporanee.

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

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

Test

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

Include +1 per -p

Esegui con l'input su 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

Una migliore variazione sul 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')

soluzione precedente:

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

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

Abbastanza difficile da golf ... Ecco la mia proposta:

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);
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.