文字列のジグザギフィ


46

印刷可能なASCII文字の空でない文字列を取り込むプログラム(または関数)を作成します。

文字列内の文字のジグザグチェーンを隣接するすべての文字ペアで印刷(またはリターン)します。

  • /通常のASCII順で最初の文字が2番目の文字の前にある場合。例えば

      B
     /
    A
    
  • \最初の文字が通常のASCII順序で2番目の文字の後にある場合。例えば

    B
     \
      A
    
  • -最初の文字と2番目の文字が同じ場合。例えば

    A-A
    

だから、のための出力Programming Puzzles & Code Golfになります

                                                        o    
                                                       / \   
  r                         z-z               o   e   G   l  
 / \                       /   \             / \ / \ /     \ 
P   o   r   m-m   n       u     l   s   &   C   d           f
     \ / \ /   \ / \     /       \ / \ / \ /                 
      g   a     i   g   P         e                          
                     \ /                                     
                                                             

入力文字列に文字が1つしかない場合、出力はその文字になります。

あなたのプログラムが扱うべきである/\、および-すべての他の文字とちょうど同じ。

-\//-- \ //-

      \                      
     / \                     
    -   /-/                  
   /       \                 
 -          ---   \   /-/    
               \ / \ /   \   
                          -  
                           \ 
                             

単一のオプションの末尾の改行を除いて、出力に余分な改行はありません。(上記の例の空の行は、文字列の最後のスペースを保持しているため、無関係ではないことに注意してください。)任意の行の末尾にスペースを配置できます。

バイト単位の最短コードが優先されます。

もう1つの例-入力:

3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

出力:

                          9   9       8   6   6                                                                                                                                                            
                         / \ / \     / \ / \ / \                                                                                                                                                           
            9   6       8   7   3   3   4   2   4     8       9       8-8                                                                                                                                  
           / \ / \     /         \ /             \   / \     / \     /   \                                                                                                                                 
      4   5   2   5   5           2               3-3   3   7   5   2     4   9       9   9-9   7                                                                                                          
     / \ /         \ /                                   \ /     \ /       \ / \     / \ /   \ / \                                                                                                         
3   1   1           3                                     2       0         1   7   6   3     3   5       8                             8   6                                                              
 \ /                                                                             \ /               \     / \                           / \ / \                                                             
  .                                                                               1                 1   5   2   9             9   3   7   1   4   6   8                                                   9
                                                                                                     \ /     \ / \           / \ / \ /         \ / \ / \                                                 / 
                                                                                                      0       0   7   9     5   2   0           0   2   6       9-9               8   5   4             7  
                                                                                                                   \ / \   /                             \     /   \             / \ / \ / \           /   
                                                                                                                    4   4-4                               2   8     8           4   2   3   2     7   6    
                                                                                                                                                           \ /       \         /             \   / \ /     
                                                                                                                                                            0         6   8   3               1-1   0      
                                                                                                                                                                       \ / \ /                             
                                                                                                                                                                        2   0                              

回答:


8

Pyth、69バイト

aY,JhzZVtzaY,@"-\/"K-<NJ>N~JN=+ZKaY,N=+ZK;jbCmX*\ h-e=GSeMYhG-edhGhdY

デモンストレーション。長い入力でも動作しますが、固定幅の出力ボックスではあまり見栄えがよくありません。

まずY、[文字、高さ]タプルのリストを作成します。例[['P', 0], ['/', -1], ['r', -2], ['\\', -1], ['o', 0], ['\\', 1], ['g', 2]]では早いProgramming Puzzles & Code Golfです。

次に、適切な長さのスペースの文字列を作成し、適切な位置に文字を挿入し、転置し、改行で結合して印刷します。


7

ジュリア、297バイト

s->(l=length;d=sign(diff([i for i=s]));J=join([[string(s[i],d[i]>0?:'/':d[i]<0?:'\\':'-')for i=1:l(d)],s[end]]);D=reshape([d d]',2l(d));L=l(J);E=extrema(cumsum(d));b=2sumabs(E)+1;A=fill(" ",L,b);c=b-2E[2];for (i,v)=enumerate(J) A[i,c]="$v";i<l(D)&&(c-=D[i])end;for k=1:b println(join(A'[k,:]))end)

ゴルフをしていない:

function f(s::String)
    # Get the direction for each slash or dash
    # +1 : /, -1 : \, 0 : -
    d = sign(diff([i for i in s]))

    # Interleave the string with the slashes as an array
    t = [string(s[i], d[i] > 0 ? '/' : d[i] < 0 ? '\\' : '-') for i = 1:length(d)]

    # Join the aforementioned array into a string
    J = join([t, s[end]])

    # Interleave D with itself to duplicate each element
    D = reshape(transpose([d d]), 2*length(d))

    # Get the length of the joined string
    L = length(J)

    # Get the maximum and minimum cumulative sum of the differences
    # This determines the upper and lower bounds for the curve
    E = extrema(cumsum(d))

    # Get the total required vertical size for the output curve
    b = 2*sumabs(E) + 1

    # Get the beginning vertical position for the curve
    c = b - 2*E[2]

    # Construct an array of spaces with dimensions corresponding
    # to the curve rotated 90 degrees clockwise
    A = fill(" ", L, b)

    # Fill the array with the curve from top to bottom
    for (i,v) = enumerate(J)
        A[i,c] = "$v"
        i < length(D) && (c -= D[i])
    end

    # Print out the transposed matrix
    for k = 1:b
        println(join(transpose(A)[k,:]))
    end
end

5

Javascript(ES6)、360 331 316 302バイト

これが私の4回目の試みです。

s=>{r=[],c=s[m=w=n=0];for(i in s)(i?(d=s[++i])>c?++n:c>d?--n:n:n)<m&&m--,n>w&&w++,c=d;for(i=0,n=w*2;i<(w-m)*2+1;r[i++]=[...' '.repeat(l=s.length*2-1)]);for(i=0;i<l;i++)i%2?(A=s[C=(i-1)/2])<(B=s[C+1])?r[--n,n--][i]='/':A>B?r[++n,n++][i]='\\':r[n][i]='-':r[n][i]=s[i/2];return r.map(x=>x.join``).join`
`}

他のいくつかほど短くはありませんが、今のところ満足しています。

ああ、あなたはそれをテストしたいですか?さて、ここに行きます:

z=s=>{r=[],c=s[m=w=n=0];for(i in s)(i?(d=s[++i])>c?++n:c>d?--n:n:n)<m&&m--,n>w&&w++,c=d;for(i=0,n=w*2;i<(w-m)*2+1;r[i++]=[...' '.repeat(l=s.length*2-1)]);for(i=0;i<l;i++)i%2?(A=s[C=(i-1)/2])<(B=s[C+1])?r[--n,n--][i]='/':A>B?r[++n,n++][i]='\\':r[n][i]='-':r[n][i]=s[i/2];return r.map(x=>x.join``).join('<br>')};

input=document.getElementById("input");
p=document.getElementById("a");
input.addEventListener("keydown", function(){
  setTimeout(function(){p.innerHTML = "<pre>"+z(input.value)+"</pre>";},10);
})
<form>Type or paste your text here: <input type="text" id="input"/></form>

<h3>Output:</h3>
<p id="a"></p>

楽しんで!

更新:

更新1:さまざまな典型的なテクニックを使用して29バイトをオフにゴルフ。

更新2:垂直方向の文字列の配列を構築し、それらを切り替えることとは対照的に、文字列を最初から水平に構築することにより、さらに15バイトをゴルフオフしました。

更新3:さらに14バイトを保存しました。

より多くのゴ​​ルフネスがすぐに来ます!


あなたは置き換えることにより、バイトを保存することができます'\n'のようなテンプレート文字列で、この
jrich

@UndefinedFunctionええ、私は前にそのトリックを使ったことがありますが、昨夜それを置くのを忘れました。念押し有難う!
ETHproductions

あなたのforループは多くのことを踏み付けすることができます。で必要なコードのブロック全体を無駄にしないでくださいi++。代わりに、ほとんどのforコードをそこで実行します。また、コードの単一行を中括弧で囲む必要もありません。
チャールズではない

また、使用する唯一の方法lは計算するs.length*2-1ことであり、それを2回行うように思われます。代わりにその値を保存しないのはなぜですか?
はないチャールズ

1
@NotthatCharlesヒントをありがとう!修正したアルゴリズムを試してみただけで、まだゴルフに悩まされることはありませんでした。<br>ちょうどそこにそれはHTMLバージョンに表示さそうです。よく見ると、実際のエントリでは代わりにテンプレート文字列を使用しています。また、必須ではありません:「印刷(または返品)...」
ETHproductions

3

Python、393バイト

def z(n,h=[]):
 for j in range(len(n)):h.append(sum(cmp(ord(n[i]),ord(n[i+1]))for i in range(j)))
 h=[j-min(h)for j in h]
 for y in range(max(h)*2+2):
  s=""
  for x in range(len(n)):
   if h[x]*2==y:s+=n[x]
   else:s+=" "
   if x==len(n)-1:continue
   c=" "
   if h[x]<h[x+1]and h[x]*2==y-1:c="\\"
   if h[x]>h[x+1]and h[x]*2==y+1:c="/"
   if h[x]==h[x+1]and h[x]*2==y:c="-"
   s+=c
  print s

として実行: z("Zigzag")


3

JavaScript(ES6)、202

テンプレート文字列を使用します。重要でカウントされているバックティック内の最後の改行を除き、インデントスペースと改行はカウントされません。

通常のメモ:EcmaScript 6準拠のブラウザーでスニペットを実行してテストします(特にMSIEではなくChromeを使用します。Firefoxでテストしたところ、Safari 9が使用できます)。

f=z=>
  [...z].map(c=>
    (d=0,x=w+c,p&&(
      c<p?o[d=1,g='\\ ',r+=2]||o.push(v,v)
      :c>p?(d=-1,g='/ ',r?r-=2:o=[v,v,...o]):x='-'+c,
      o=o.map((o,i)=>o+(i-r?i-r+d?b:g:x),v+=b)
    ),p=c)
  ,v=w=' ',o=[z[p=r=0]],b=w+w)&&o.join`
`

Ungolfed=z=>
(
  v=' ',o=[z[0]],r=0,p='',
  [...z].map(c=>{
    if (p) {
      if (c < p) {
        if (! o[r+=2])
          o.push(v,v)
        o = o.map((o,i)=>o+(i==r ? ' '+c : i==r-1 ? '\\ ' : '  '))
      } else if (c > p) {
        if (r == 0)
          o = [v,v,...o]
        else
          r -= 2
        o = o.map((o,i)=>o+(i==r ? ' '+c : i==r+1 ? '/ ' : '  '))
      } else {
        o = o.map((o,i)=>o+(i==r ? '-'+c : '  '))
      }
      v += '  '
    }
    p = c
  }),
  o.join`\n`
)

out=x=>O.innerHTML+=x+'\n'

test = [
"Programming Puzzles & Code Golf",  
"-\\//-- \\ //- ",  
"3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"]

test.forEach(t=>out(t+"\n"+f(t)))
<pre id=O></pre>


2

CJam、79バイト

l__0=\+2ew::-:g_0\{+_}%);_$0=fm2f*_$W=)S*:E;]z{~\_)"/-\\"=2$@-E\@t@@E\@t}%(;zN*

オンラインで試す

これにより、列ごとに出力が作成され、最後に結果が転置されて、行ごとに出力が取得されます。これは全体的に非常に苦痛でした。

説明:

l__   Get input and create a couple of copies.
0=\+  Prepend copy of first letter, since the following code works only with
      at least two letters.
2ew   Make list with pairs of letters.
::-   Calculate differences between pairs...
:g    ... and the sign of the differences.
_0\   Prepare for calculating partial sums of signs by copying list and
      pushing start value 0.
{     Loop for calculating partial sums.
  +_    Add value to sum, and copy for next iteration.
}%    End of loop for partial sums. We got a list of all positions now.
);    Pop off extra copy of last value.
_$0=  Get smallest value.
fm    Subtract smallest value to get 0-based positions for letters.
2f*   Multiply them by 2, since the offsets between letters are 2.
_$W=  Get largest position.
)     Increment by 1 to get height of result.
S*    Build an empty column.
:E;   Store it in variable E.
]     We got the input string, list of relative offsets, and list of
      absolute positions now. Wrap these 3 lists...
z     ... and transpose to get triplets of [letter offset position].
{     Loop over triplets.
  ~     Unwrap triplet.
  \     Swap offset to front.
  _)    Copy and increment so that offset is in range 0-2.
  "/-\\"  List of connection characters ordered by offset.
  =     Pick out connection character for offset.
  2$@   Get position and copy of offset to top.
  -     Subtract to get position of connection character.
  E     Empty column.
  \@    Shuffle position and character back to top. Yes, this is awkward.
  t     Place connection character in empty line. Done with first column.
  @@    Shuffle letter and position to top.
  E     Empty column.
  \@    Stack shuffling again to get things in the right order.
  t     Place letter in empty line. Done with second column.
}%    End of main loop for triplets.
(;    Pop off first column, which is an extra connector.
z     Transpose the whole thing for output by row.
N*    Join with newlines.

1

Perl 5、230 214

@A=split(//,pop);$y=$m=256;map{$c=ord$_;$d=$c<=>$p;$t=$d>0?'/':$d<0?'\\':'-';$B[$x++][$y-=$d]=$t;$B[$x++][$y-=$d]=$_;$m=$y,if$m>$y;$M=$y,if$M<$y;$p=$c}@A;for$j($m..$M){for$i(1..$x){$s.=$B[$i][$j]||$"}$s.=$/}print$s

テスト

$ perl zigzag.pl "zigge zagge hoi hoi hoi"
z
 \
  i
   \
    g-g
       \
        e   z   g-g       o       o       o
         \ / \ /   \     / \     / \     / \
              a     e   h   i   h   i   h   i
                     \ /     \ /     \ /


$ 

1

K、86

{-1@+((d#\:" "),'1_,/("\\-/"1+e),'x)@\:!|/d:(|/b)+-:b:1_+\,/2#'e:{(x>0)-x<0}@-':6h$x;}  

k){-1@+((d#\:" "),'1_,/("\\-/"1+e),'x)@\:!|/d:(|/b)+-:b:1_+\,/2#'e:{(x>0)-x<0}@-':6h$x;} "Programming Puzzles & Code Golf"
                                                        o
                                                       / \
  r                         z-z               o   e   G   l
 / \                       /   \             / \ / \ /     \
P   o   r   m-m   n       u     l   s   &   C   d           f
     \ / \ /   \ / \     /       \ / \ / \ /
      g   a     i   g   P         e
                     \ /

ゴルフをしていない:

f:{
    dir:{(x>0)-x<0}-':[*a;a:"i"$x];          //directional moves (-1, 0, 1)
    chars:1_,/("\\-/"1+dir),'x;              //array of input string combined with directional indicators
    depths:(|/b)+-:b:1_+\,/2#'dir;           //depth for each char, normalised to start at 0
    -1@+((depths#\:" "),'chars)@\:!|/depths; //Pad each character by the calculated depths, extend each string to a uniform length and transpose
    }

1

ルビー、158

histocratのおかげで6バイト節約されました。ありがとう!

->s,*i{i[x=n=k=(4*m=s=~/$/).times{i<<'  '*m}/2][j=0]=l=s[/./]
$'.chars{|c|i[k-=d=c<=>l][j+1]=%w{- / \\}[d]
i[k-=d][j+=2]=l=c
n,x=[x,n,k].minmax}
puts i[n..x]}

1
を使用してiを空の配列に設定でき->s,*i{ます。あなたが交換した場合とs[0]s[/./]、私はあなたが交換することができると思いますs[1..-1]$'
-histocrat

@histocrat素晴らしい!ありがとう!マルチパラメータラムダ宣言には括弧が必要だと思いましたが、明らかにそれはJSだけです。
チャールズではないチャールズ

0

Numpyを使用したPython:218バイト

numpyをインポートするために19バイトを無駄にする価値があります。

ゴルフ:

from numpy import*
z=zip
r=raw_input()
s=sign(diff(map(ord,r[0]+r)))
c=cumsum(s)
p=2*(max(c)-c)+1
for L in z(*[c.rjust(i).ljust(max(p))for _ in z(z(p+s,array(list('-/\\'))[s]),z(p,r))for i,c in _][1:]):print''.join(L)

ゴルフをしていない:

from numpy import *

letters = raw_input()
#letters = 'Programming Puzzles & Code Golf'
s = sign(diff(map(ord, letters[0] + letters)))
c = cumsum(s)
lines = array(list('-/\\'))[s]

letter_heights = 2 * (max(c) - c) + 1
line_heights = letter_heights + s

columns = [symbol.rjust(height).ljust(max(letter_heights))
    for pair in zip(                    # interleave two lists of (height, symbol) pairs...
        zip(line_heights,   lines),
        zip(letter_heights, letters)
    )
    for height, symbol in pair          # ... and flatten.
][1:]                                   # leave dummy '-' out
for row in zip(*columns):
    print ''.join(row)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.