復号化機能

Sep 21 2020

暗号化された文字列を受け取り、特定のルールに従って復号化してから印刷するプログラムを作成する必要があります。復号化は、2つの操作を実行することによって発生します。

サンプル入力引数1(暗号化された文字列)

HGJILKBADCFE

操作1:

文字列の前半を後半と交換すると、次のようになります。

BADCFEHGJILK

操作2:

文字1を2、3を4に交換するなど、2文字ごとに交換します。これにより、復号化された文字列が残ります。

ABCDEFGHIJKL

ガイドライン:

  • 入力引数1には大文字のみが含まれます

  • 入力引数1の長さは2〜100文字になります

  • 入力引数1の長さは常に偶数になります

  • できれば、入力はコマンドラインから取得されます(以下のように)。

  • 別のテストケースMPORQTSVUXWZYBADCFEHGJILKNは入力であり、出力はABCDEFGHIJKLMNOPQRSTUVWXYZ

私の試み

import sys
_,a=sys.argv
b=len(a)//2
s=a[b:]+a[:b]
print(''.join(x+y for x,y in zip(s[1::2],s[::2])))

回答

5 Jonah Sep 21 2020 at 10:59

J、15バイト

[:,_2|.\-:@#|.]

オンラインでお試しください!

式の簡単な実装。


もう少し興味深いのは(Jゴルフには役立ちませんが、別の言語には役立つかもしれません)、アルゴリズムがスキャン合計で解けることです。

  1. リストの長さまで繰り返されて、最初に1続いて-1 3、を取り-1 3ます。
  2. そのリストを合計してスキャンします。
  3. リストの長さの半分の数字を回転させます。
  4. それらの番号に従ってオリジナルを並べ替えます。

Jのデモについては、TIOを参照してください。

5 Dingus Sep 21 2020 at 10:26

Ruby -p、4847バイト

$_=$_[l= ~/$//2,l]+$_[0,l];gsub /(.)(.)/,'\2\1'

オンラインでお試しください!

操作1は$_、(入力を含む事前定義されたグローバル変数)を同じ長さの2つの部分文字列に分割することによって処理されます。~/$/入力の長さを示します。次にgsub /(.)(.)/,'\2\1'、文字の各ペアを交換して、操作2を完了します。(-pフラグがある場合gsub、レシーバーがない場合は暗黙的に作用し$_ます。)

5 Lyxal Sep 21 2020 at 11:36

05AB1E、13の12バイト

D2äRJ2ι`s.ιJ

オンラインでお試しください!

-1別の答えで見た@Kevinによるゴルフのヒントのおかげで

説明

D2äRJ2ι`s.ιJ
  • 入力を複製します(D)
  • 2つのチャンクに分割します(2ä)
  • リストを逆にして、1つの文字列に結合します(RJ)
  • 2文字ごとにその文字列のインターリーブを解除します(2ι)
  • インターリーブされていない文字列からすべてのアイテムをスタックにプッシュします( `` `)
  • それらのアイテムをインターリーブします(.ι)
  • そして、結果のリストに参加します(J)
5 Graham Sep 21 2020 at 14:15

APL + WIN、24の22バイト

-JoKingのおかげで2バイト

文字列の入力を求めるプロンプト:

,⌽n⍴⊖(⌽n←⌽2,.5×⍴s)⍴s←⎕

オンラインでお試しください!DyalogClassicの礼儀

5 DominicvanEssen Sep 21 2020 at 14:48

R、78の 80 79バイト

編集:バグスポッティングのためのDingusのおかげで+2バイト、pajonkのおかげで-1バイト

n=nchar(s<-scan(,''));o=1:n;cat(substring(s,p<-(o+n/2-2+2*o%%2)%%n+1,p),sep='')

オンラインでお試しください!

Rコンソールからの入力(Rワークスペースの「コマンドライン」と見なすことができます)。
Rは、Rscriptヘルパーフロントエンドを使用して(非R)シェルから呼び出すこともできます。これにより、コマンドライン引数が呼び出しの直後に続くようになります。この場合、変更されたプログラムは87バイトで、を使用して呼び出すことができますRscript decrypt.r HGJILKBADCFE。

デコードされた文字の位置を計算し、再配置された文字列を出力します。

コメント:

 n=nchar(                   # n = number of characters in...
         s<-scan(,''));     # s = the input.
 o=1:n;                     # o = sequence from 1 to n
 p=                         # p = positions of decoded characters:
   (o+n/2-1                 #   - reverse the first & second halves of o
                            #     by adding n/2-1
                            #     (will be fixed with final modulo below) 
         +2*o%%2-1)         #   - then add 2 at every odd position
                            #     and subtract 1 from all, so in effect
                            #     adding to odds & subtracting from evens
                   %%n      #   - all modulo n
                      +1    #   - add 1 to get 1-based indices
 cat(                       # output:
   substring(s,p,p),sep='') #   characters of s from positions p to p
3 HyperNeutrino Sep 21 2020 at 09:44

ゼリー、7バイト

ŒHṚFs2U

オンラインでお試しください!

同等に7バイト、ṙLH$s2U。

説明

ŒHṚFs2U  Main Link
ŒH       Split into two halves of similar length
  Ṛ      Reverse the order (swap the two halves)
   F     Flatten back into a single string
    s2   Slice into chunks of length 2
      U  Reverse each chunk
         Output is implicitly as one string

他の1ṙによってotatesそれ$(H文字列ののALF Length)、次に挑戦の第二部のために同じことを行います。

3 Sisyphus Sep 21 2020 at 12:10

Python 3、75バイト

要求どおり:コマンドラインからの入力、STDOUTへの出力。

import sys
_,s=sys.argv
i=1
while s[i:]:print(end=s[i-len(s)//2]);i+=3|i%-2

オンラインでお試しください!


Python 2、52バイト

関数を使用できる場合:

f=lambda s,i=1:s[i:]and s[i-len(s)/2]+f(s,i+3-i%2*4)

オンラインでお試しください!


これらすべての考え方は、\のインデックスが$i\$長さの文字列の '番目の出力文字\$n\$ は:

$$ i - \frac{n}{2} + (-1)^i $$

通常のPythonインデックスセマンティクスに従います。これを繰り返し書き直すと、\$i\$'番目の出力文字は次のとおりです。

$$ a_i - \frac{n}{2} \text{ where } a_0 = 1 \text{ and } a_i = a_{i-1} + 3 - 4(i\%2) $$

特定の優先順位を持つ短いものは次のとおりです。

$$ a_i - \frac{n}{2} \text{ where } a_0 = 1 \text{ and } a_i = a_{i-1} + 3|(i\%-2) $$

3 xnor Sep 21 2020 at 17:11

Python 2、50バイト

f=lambda s,i=0:s[i:]and s[(i^1)-len(s)/2]+f(s,i+1)

オンラインでお試しください!

アイデアを借りシーシュポス、i出力の番目の文字は、インデックスの文字で(i^1)-len(s)/2入力します。ここでは、i^1とのXORである1最後のビットを反転させ、およびスワップので、偶数/奇数のペアは0<->1、2<->3、4<->5、...

これは同じ長さの非再帰的な代替手段ですが、許可されているかどうかはわかりませんが、文字のリストが出力されます。

lambda s:[s[(i^1)-len(s)/2]for i in range(len(s))]

オンラインでお試しください!

3 Noodle9 Sep 21 2020 at 19:57

C(GCC) 、73の 72 70バイト

Dominic vanEssenのおかげで2バイト節約できました!!!

i;l;f(char*s){for(i=1;(l=strlen(s))/i;)putchar(s[(i+l/2-++i%2*2)%l]);}

オンラインでお試しください!

文字列を入力し、復号化を出力します。

説明

インデックスをマップします(\から開始$0\$最後まで)、入力文字列の\$s\$長さの\$l\$、上に移動して正しい場所に移動します\$\frac{l}{2}+1\$場所と戻る\$2\$奇数インデックスの場合。これを使用して\$\mod{l}\$\の正しいインデックスを与える$s\$ 次の出力文字用。

3 nununoisy Sep 21 2020 at 23:39

JavaScriptの(Node.jsの)、 71の 65バイト

s=>(s.slice(l=s.length/2)+s.slice(0,l)).replace(/(.)(.)/g,'$2$1')

オンラインでお試しください!

@Shaggyのおかげで6バイト節約できました。

元の71バイトのソリューション:

s=>(l=>s.slice(l)+s.slice(0,l))(s.length/2).replace(/(\w)(\w)/g,'$2$1')

ここでは非常に単純なものです-sliceとにかく呼び出しを囲む必要があるため、内部関数を使用しました-これにより4バイトが節約されます。

2 xash Sep 21 2020 at 16:34

Brachylog、8バイト

ḍ↔cġ₂↔ᵐc

オンラインでお試しください!

使い方

ḍ↔cġ₂↔ᵐc
ḍ        split in two halves
 ↔       reverse
  c      join
   ġ₂    group with length two
     ↔ᵐ  reverse each
       c join 
1 aidan0626 Sep 21 2020 at 10:08

Python 3、91バイト

a=input();x=len(a)//2;b=a[x:]+a[:x];c=''
for i in range(0,len(b),2):c+=b[i+1]+b[i]
print(c)

オンラインでお試しください!

1 Razetime Sep 21 2020 at 11:05

ピップ、21バイト

RV_M(JRV(a<>#a/2)<>2)

オンラインでお試しください!

説明

RV_M(JRV(a<>#a/2)<>2)
        (a<>#a/2)     split input into parts of size length/2
     JRV              reverse the list, and join it to string
                 <>2  split the joined string into parts of size 2
RV_M                  reverse each of those parts
                      implicit output
1 ErikF Sep 21 2020 at 13:45

C(gcc)、78 76 7874バイト

-4のceilingcatに感謝します!

編集:演算子の優先順位の問題を回避するために、ORの代わりに加算を使用するように戻しました。

この関数は、文字列を分割するのではなく、文字列の途中から開始し、処理された文字列全体をラップします。1文字おきに反転するには、インデックスがカウンターの1の位置を反転します。

f(s,i,j)char*s;{for(i=strlen(s),j=0;write(1,s+(i/2+j++/2*2+j%2)%i,j<i););}

オンラインでお試しください!

プログラムが絶対にコマンドラインから取得する必要がある場合:82バイト

main(i,s,j)char**s;{for(i=strlen(*++s),j=0;write(1,*s+(i/2+j++/2*2+j%2)%i,j<i););}

オンラインでお試しください!

1 Razetime Sep 21 2020 at 17:16

Stax、10バイト

ü♠yαæ♠╟«ºñ

実行してデバッグする

なんて素晴らしいオンライン通訳。

リンクは、解凍されたバージョンのコードへのリンクです。

説明

;%h/r$2/Frp ; copy input % get it's length h halve it / split input into parts of that size r reverse $      join to string
      2/    split into parts of size 2
        F   for each element in the resulting array:
         rp reverse, and print without newline.
1 GalenIvanov Sep 21 2020 at 17:48

K(ngn / k)、17バイト

,/|'0N 2#,/|2 0N#

オンラインでお試しください!

1 GalenIvanov Sep 21 2020 at 18:41

因数分解、89バイト

: d ( s -- s ) halves swap [ >array ] bi@ append 2 group [ reverse ] map concat >string ;

オンラインでお試しください!

1 Giuseppe Sep 21 2020 at 21:50

R、64の63バイト

m=matrix;intToUtf8(m(m(utf8ToInt(scan(,"")),,2)[,2:1],2)[2:1,])

オンラインでお試しください!

1バイトをゴルフしたドミニク・ファン・エッセンとは異なるアプローチを取りました。マトリックスの再形成/索引付けを使用して、反転を実行します。

ゴルフなし:

s <- utf8ToInt(scan(,""))		# read input and convert to a list of byte values
m <- matrix(s,,2)			# convert to a Nx2 matrix, filling down by columns
m <- m[,2:1]				# reverse the columns of the matrix (flip the halves)
m <- matrix(m,2)			# convert to an Nx2 matrix, filling down by the columns
m <- m[2:1,]				# reverse the rows (swap adjacent characters)
intToUtf8(m)				# convert back to string
1 nununoisy Sep 23 2020 at 03:28

bash + sed、57バイト

コマンドライン引数として入力を受け取ります。

<<<"${1:${#1}/2}${1:0:${#1}/2}" sed 's/\(.\)\(.\)/\2\1/g'

オンラインでお試しください!

Mintable Sep 21 2020 at 15:44

バーレスク、17バイト

iRsa2./!!2co)<-++

オンラインでお試しください!

説明:

iR               # Generate all rotations of the input string
  sa             # Duplicate and get length (which equals string length)
    2./          # Divide by two
       !!        # And grab the string that's been rotated that many times
         2co     # Split the rotated string into chunks of two
            <-   # Reverse each chunk
              ++ # Join together and implicitly output
Shaggy Sep 21 2020 at 15:48

Japt -P、9バイト

éUÊz)ò mw

それを試してみてください

éUÊz)ò mw     :Implicit input of string U
é             :Rotate right by
 UÊ           :  Length of U
   z          :  Floor divided by 2
    )         :End rotate
     ò        :Partitions of length 2
       m      :Map
        w     :  Reverse
              :Implicitly join and output
Neil Sep 21 2020 at 16:49

チャコール、13バイト

⭆⪪⪫⮌⪪θ⊘Lθω²⮌ι

オンラインでお試しください!リンクは、コードの詳細バージョンへのリンクです。説明:

        θ       Input string
       L        Length
      ⊘         Halved
    ⪪θ          Split input string into substrings of this length
   ⮌            Reverse
  ⪫      ω      Join together
 ⪪        ²     Split into substrings of length 2
⭆               Map over substrings and join
            ι   Current substring
           ⮌    Reversed
                Implicitly print
Neil Sep 21 2020 at 17:00

Retina 0.8.2、36バイト

((.)+?)((?<-2>.)+)$ $3$1 (.)(.) $2$1

オンラインでお試しください!説明:最初のステージでは、.NETバランシング・グループを使用して$1、同じ数の文字をに一致させながら、できるだけ少ない文字に一致させ$3ます。$#2に一致する各文字の増分とに一致する$1各文字の$3減分がゼロ未満に減ることはできないため$1、文字列の終わりに到達できるように、文字列の前半を強制的に消費します。次に、第2段階では、隣接する文字のペアを反転します。(ASCIIアートもあります。)

KevinCruijssen Sep 21 2020 at 17:08

MathGolf、10バイト

h½/xy2/mx~

オンラインでお試しください。

説明:

h           # Get the length of the (implicit) input-string (without popping)
            #  i.e. "HGJILKBADCFE" → "HGJILKBADCFE" and 12
 ½          # Halve this length
            #  → "HGJILKBADCFE" and 6
  /         # Split the string into parts of that size
            #  → ["HGJILK","BADCFE"]
   x        # Reverse this pair
            #  → ["BADCFE","HGJILK"]
    y       # Join it back together to a string
            #  → "BADCFEHGJILK"
     2/     # Split it into parts of size 2
            #  → ["BA","DC","FE","HG","JI","LK"]
       m    # Map over each pair:
        x   #  Reverse the pair
            #  → ["AB","CD","EF","GH","IJ","KL"]
         ~  # Pop and push all strings separated to the stack
            #  → "AB", "CD", "EF", "GH", "IJ", and "KL"
            # (after which the entire stack joined together is output implicitly)
            #  → "ABCDEFGHIJKL"
GalenIvanov Sep 21 2020 at 17:29

赤、89バイト

func[s][move/part s tail s(length? s)/ 2
rejoin collect[foreach[b a]s[keep rejoin[a b]]]]

オンラインでお試しください!

valsaysReinstateMonica Sep 21 2020 at 22:52

Lua、67バイト

a=...b=#a//2print(((a:sub(b+1)..a:sub(1,b)):gsub('(.)(.)','%2%1')))

オンラインでお試しください!

まず、sub関数を使用して文字列を2つに切断し、逆の順序で連結して戻します。次に、gsub文字のペアを交換するために使用されます。

att Sep 22 2020 at 05:54

Wolfram言語(Mathematica)、6451バイト

#[[#+UnitStep@#&@Array[#+(-1)^#&,L=Tr[1^#],-L/2]]]&

オンラインでお試しください!

SisyphusのPythonソリューションの移植

EsolangingFruit Sep 22 2020 at 14:26

CJam、13バイト

q2/::\_,2//:\

オンラインでお試しください!

NahuelFouilleul Sep 22 2020 at 17:07

Perl 5、40 -pFバイト

for$p("."x(@F/2),"."){s/($p)($p)/$2$1/g}

オンラインでお試しください!

JosiahRyanW Sep 30 2020 at 18:31

詩的、472バイト

DECODING THINGS:A BRIEFING
o,o,hello!i am agent Q
nah,Q`s chosen by an infamous phoney
a misprint!oh,sorry!am i sorry
i am agent J.W,tech/A.I hacker
i see a piece o code,i am trying at a means on how i decode it
what i am doing:i am laying all A-Z clearly along a pathway
midway,put in zeros(O,O)cause J.W needs it to split em
i shift em in tandem,i get B,A
lastly,if it leaves you a letter,it is moved
o,then i am doing A-Z again,it is taken to a shift
ah ha!spying is EZ

オンラインでお試しください!