ASCIIアートテーブルをUTF-8テーブルに変換する


13

ドキュメントやコメントなどを書くとき、ASCIIテーブルを作成するのが大好きです。彼らは通常かなりきれいに見えますが、特にUTF-8 / Unicodeにはボックス描画文字が含まれているため、私はいつももっと良く見えると感じています。ただし、これらの文字は使用するのが非常に面倒であり、挿入するにはいくつかのキーを押す必要があります。あなたのタスク?ASCIIテーブルをUTF-8 / Unicodeに自動的に変換できるプログラムまたは関数を作成します。

この課題はサンドボックス化されました

チャレンジ

入力文字列としてASCIIテーブルを指定するプログラムを作成し、Unicode / UTF-8ボックス描画文字で再描画されたテーブルを出力します。具体的には、表の一部である文字は次のように翻訳する必要があります。

(Unicode, 3 bytes each in UTF-8)
- to ─ (\u2500)
| to │ (\u2502)
= to ═ (\u2550)

and + to one of:
   ┌ (\u250C), ┐ (\u2510), └ (\u2514), ┘ (\u2518),
   ├ (\u251C), ┤ (\u2524), ┬ (\u252C), ┴ (\u2534),
   ┼ (\u253C)
or, if '=' on either side:
   ╒ (\u2552), ╕ (\u2555), ╘ (\u2558), ╛ (\u255D),
   ╞ (\u255E), ╡ (\u2561), ╤ (\u2564), ╧ (\u2567),
   ╪ (\u256A)

詳細

I / O:

  • デフォルトのI / Oが許可されます
  • テーブルを文字列として、またはテーブルを含むファイルへのパスを含む、妥当な形式で入力を取得できます。
  • ファイルに出力し、ファイル名を追加の引数として使用できます。
    • ただし、入力ファイルを変更することはできません。(将来の編集を容易にするために保持する必要があります)

入力:

  • 入力のすべての行がで同じ長さになるようにパディングされていると仮定できます。
  • 改行の後の最初の文字が表の境界の一部であると想定することはできません(空白である可能性があるため)。
  • (テーブルの一部である)すべての文字-=|が正確に2文字に接続されている場合、入力は有効なテーブルと見なされ、+に接続され、少なくとも1文字に水平および垂直の両方に接続され。
  • プログラムは、有効な入力でエラーを生成しない場合があります。
  • 入力が有効でない場合、動作は未定義であり、出力を生成できます。
  • 入力には、ボックス描画文字を含むUTF-8文字を含めることができます。

出力:

  • -=|+テーブルの一部ではない文字は、そのままにしておく必要あります。
  • 同様に、他の文字はそのままにしておく必要があります。
  • 単一の先頭および/または末尾の改行が許可されます。

その他:

  • 通常どおり、標準の抜け穴は禁止されています。
  • 優先言語にこの問題を解決する組み込み機能がある場合は、使用しないでください。
    • これは、追加なしでこのチャレンジに対して有効な提出となるプログラム、関数、サブルーチン、または命令を意味します。
  • このチャレンジで必要な各文字は、UTF-8でエンコードされている場合は3バイトです。

接続されたキャラクター

次の場合、キャラクターは別のキャラクターに接続されます。

  • それは|直接の上または下である+、または|
  • それは-前または後に、直接です+-
  • それは=前または後に、直接です+=
  • それは+、上または下、|または+、または、直前または直後-=または+です。

文字は、表の一部である任意の文字に接続されている場合、表の一部と見なされます。定義では+、入力の最初はテーブルの一部です。

コピー&ペースト可能なバージョンとしてここで利用可能な例。

 Input:                    Output:
+------------------+      ┌──────────────────┐
|   Hello+World!   |      │   Hello+World!   │
+==================+      ╞══════════════════╡
| This is+my first |  ->  │ This is+my first │
|+-+ code|golf  +-+|      │+-+ code|golf  +-+│
|+-+chall|enge! +-+|      │+-+chall|enge! +-+│
+------------------+      └──────────────────┘

     +===+===+===+             ╒═══╤═══╤═══╕
     | 1 | 2 | 3 |             │ 1 │ 2 │ 3 │
 +---+===+===+===+         ┌───╪═══╪═══╪═══╡
 | 1 | 1 | 2 | 3 |         │ 1 │ 1 │ 2 │ 3 │
 +---+---+---+---+    ->   ├───┼───┼───┼───┤
 | 2 | 2 | 4 | 6 |         │ 2 │ 2 │ 4 │ 6 │
 +---+---+---+---+         ├───┼───┼───┼───┤
 |-3 |-3 |-6 |-9 |         │-3 │-3 │-6 │-9 │
 +===+---+---+---+         ╘═══╧───┴───┴───┘

      +-----+         ->      <Undefined>

      +-----+         ->      ┌─────┐
      +-----+                 └─────┘

+-----------------+
|  Hello, World!  |
| This is invalid |   ->      <Undefined>
|      input      |
 -----------------+

       ++++                      ┌┬┬┐
       ++++           ->         ├┼┼┤
       ++++                      └┴┴┘

       +--+
       ++++           ->      <Undefined>
       +--+

最後に...

これはであるため、最小バイト数が優先されます。ハッピーゴルフ!


最初の例では、連続した+-+抜粋が接続されたテーブルを形成するとは見なされないのはなぜですか?
再帰的

多分16ビット関数が1バイトを使用して╡を表す場合、バイトカウントはどうですか?
l4m2

@recursive最初のHello Worldテーブルを意味する場合、テーブル内のテキストは変更されないままである必要があるため、内部テーブルはテーブルを形成するとは見なされず、外部テーブルの境界の一部とは見なされません。

最初の+----+例を意味する場合、角の方向があいまいになるためです。

1
ああ、「可能な限り最も外側のテーブルを拡張するために接続しない限り、テーブル内にテーブルがない」という要件により、これは非常に難しくなります。
ジョナサンアラン

回答:


2

Python 3、392 281バイト

それをかなりゴルフし、反復的な解決策の代わりに再帰的な解決策に変換しました:

def h(a):
 def g(i):
  k=-3;d=a[i]=='=';z[i]=''
  for p,j,r in zip((1,2,4,8),(i+1,i+w,i-1,i-w),('+-=','+|')*2):
   if 0<=j<len(a)and{a[i],a[j]}<={*r}:k+=p;d|=a[j]=='=';z[j]and g(j)
  z[i]="┌╒!!─═┐╕┬╤@@└╘││├╞┘╛┴╧┤╡┼╪"[2*k+d]
 w=a.find('\n')+1;z=[*a];g(a.find('+'))
 return''.join(z)

改行で区切られた同じ長さの行の文字列を受け取り、同じ形式の文字列を返します。無効な入力で例外をスローする場合があります。

以前のソリューション:

def h(a):
 i=a.find('+');q=[i];w=a.find('\n')+1;z=[*a]
 while q:
  i=q.pop();c=a[i];k=-5
  for p,j in enumerate((i+1,i-1,i+w,i-w)):
   r='++-|='[p>1::2]
   if 0<=j<len(a)and a[i]in r and a[j]in r:
    k+=1<<p;q+=[j][:z[j]<'─']
  z[i]='│'if c>'='else'─═'[a[i]>'-']if c>'+'else"┌╒┐╕┬╤@@└╘┘╛┴╧##├╞┤╡┼╪$$"['='in a[abs(i-1):i+2]::2][k]
 return''.join(z)

ゴルフされていないバージョン:

def h(a):
    i = a.find('+')         # find index of first '+'. It is first node
    q = [i]                 # in the queue of indexes to convert to unicode
    w = a.find('\n')+1      # width of the table
    z = [*a]                # strings are immutable, so copy it to a list

    while q:                # while the queue isn't empty
        i=q.pop()           # get the next index to process
        c=a[i]              # and the associated character

        k=-5                # 'k' is the index into the unicode string, U.  The way they
                            # are encoded, the first unicode value is at index 5. 

                 # directions  E   W   S   N
        for p,j in enumerate((i+1,i-1,i+w,i-w)):  # j is the index of an adjacent cell

            # r='++-|='[p>1::2] is equivalent to:
            if p > 1:
                r = '+|'    # compatible symbols for vertical connections
            else:
                r = '+-='   # compatible symbols for horizontal connections

            # if adjacent cell index is valid and the characters are compatible
            if 0 <= j < len(a) and a[i] in r and a[j] in r:
                k += 1<<p                 # update the unicode symbol index

                # q += [j][:z[j]<'─'] is equivalent to:
                if z[j] < '-':            # if the adjacent cell hasn't been converted already
                    q.append(j)           #  append it's index to the queue

            if c > '=':
                z[i] = '│'                # replace a '|' with a '│'

            elif c > '+':
                z[i] = '─═'[a[i]>'-']     # replace a '-' or '=' with '─' or '═' respectively 

            else:                                      # it's a '+'
                U = "┌╒┐╕┬╤@@└╘┘╛┴╧##├╞┤╡┼╪$$"         # even indexes are single horizontal line, 
                                                       # double horizontal lines are at odd indexes

                z[i] = U['='in a[abs(i-1):i+2]::2][k]  # '='in a[abs(i-1):i+2] is true if there is an '=' to the left or right
                                                       # so this selects the odd chars from U
                                                       #  then [k] selects the correct char

 return''.join(z)

3

Pythonの3914 898 827 823 594 587 569 540 469バイト

編集:戦略が大幅に変更され、隣人のビットフィールドが作成されました(デッドポッサムの回答と同様)。以前のバージョンは下に残しました。

H='─│═-|=└╘++++┌╒├╞++┘╛++┴╧┐╕┤╡┬╤┼╪'
def n(l):
 def j(r,c,t=0):O=(0,r-1,c),(1,r,c+1),(2,r+1,c),(3,r,c-1);v=f(r,c);b=t|any(f(Y,X)=='='for i,Y,X in O);l[r][c]={'+':H[b+2*sum((f(Y,X)in H)<<x for x,Y,X in O)],**dict(zip(H[3:6],H))}.get(v,v);[f(Y,X)!=';'and v in'+++-|='[i%2::2]and j(Y,X,v=='=')for i,Y,X in O]
 for i,I in enumerate(l):
  if'+'in I:f=lambda r,c:l[r][c]if len(l)>r>=0and 0<=c<len(l[r])else';';j(i,I.index('+'));break

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

入力は、文字のリストのリストの形式であり、その場で修正されます。見つかった最初の+からの再帰。

x=range
C='┌┐└┘','╒╕╘╛'
D='┬┤┴├','╤╡╧╞'
A='┼╪'
H,V,T='─│═'
J={'-':H,'|':V,'=':T}
K=C[1]+D[1]+A[1]+'='+T
E=('+|','+-=')*2
F=['+|'+V,'+-='+H+T]*2
O=(0,-1,0),(1,0,1),(2,1,0),(3,0,-1)
for i in x(4):
 for j in{0,1,2,3}-{i}:F[i+2&3]+=D[0][j]+D[1][j]
 h=C[0][i]+C[1][i];F[i&2]+=h;F[3-2*(i&1)]+=h
def n(l):
 for i,I in enumerate(l):
  if'+'in I:r=i;c=I.index('+');break
 else:return l
 def f(r,c):
  try:assert c>=0 and r>=0;return l[r][c]
  except:return'\0'
 def j(r,c):
  v=f(r,c)
  l[r][c]=J.get(v,v)
  if v=='+':
   X=[f(r+Y,c+X)for i,Y,X in O];B=any(x in K for x in X);X=[X[x]in F[x]for x in x(4)];L=sum(X)
   if L in(2,3,4):l[r][c]=D[B][X.index(False)]if L==3 else C[B][X[0]*2+X[3]]if L==2 else A[B]
  for i,Y,X in O:
   if v in E[i]and f(r+Y,c+X)in E[i]:j(r+Y,c+X)
 j(r,c);return l

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

ここに、私が持っていないバージョンに最も近いものがあります:

def tr(s):
    t='┌┐└┘','╒╕╘╛'
    t2='┬┤┴├','╤╡╧╞'
    A = '┼','╪'
    H,V,T = '─│═'
    Th = ''.join(x[1]for x in (t,t2,A))+'='+T
    ps = ['+|'+V, '+-='+H+T, '+|'+V, '+-='+H+T]
    ps2 = ('+|', '+-=')*2
    for i in range(4):
        for j in {0,1,2,3}-{i}:
            ps[(i+2)%4] += t2[0][j]+t2[1][j]
        h=t[0][i] + t[1][i]
        ps[i & 2] += h
        ps[3 - 2 * (i & 1)] += h

    l = [list(x) for x in s.split('\n')]
    r = 0
    for i,I in enumerate(l):
        if'+'in I:
            r=i;c=I.index('+')
            break
    def g(r,c): return l[r][c]
    def G(r,c):
        if r >= 0 and r < len(l) and c >= 0 and c < len(l[r]):
            return g(r,c)
        return '\0'
    def process(r,c):
        v = g(r,c)
        if v == '-': l[r][c] = H
        elif v == '|': l[r][c] = V
        elif v == '=': l[r][c] = T
        elif v == '+':
            all=[G(r-1,c),G(r,c+1),G(r+1,c),G(r,c-1)]
            bold=any(x in Th for x in all)
            for i in range(4):all[i] = all[i] in ps[i]
            N,E,S,W=all
            tt=sum(all)
            if tt == 3:
                l[r][c]=t2[bold][all.index(False)]
            elif tt == 2:
                l[r][c]=t[bold][N*2+W]
            elif tt == 4:
                l[r][c]=A[bold]
            else: return
        for i,(dy,dx) in enumerate(((-1,0),(0,1),(1,0),(0,-1))):
            if v in ps2[i] and G(r+dy,c+dx) in ps2[i]:
                process(r+dy,c+dx)
    process(r,c)
    return l

9バイト(814まで)を保存するためのマイナーな改善 bit.ly/2NOu7HF
mypetlion

別の9バイト(805は、現在バイト)のためのいくつかのよりbit.ly/2pYom0x
mypetlion

763まで:bit.ly/2OxErsJ
mypetlion

1

JavaScript、311 307バイト

X=>(O=[...X],P=(I,j=0,_=0)=>!P[I]&&(P[I]=1,['-─1','|│','=═1'].map(([a,b,n=X.indexOf('\n')+1])=>[-n,+n].map(n=>{for(i=I;X[i+=n]==a;)O[i]=b
if(X[i]=='+')j|=[1,2,4,8,I-i>1&&17,i-I>1&&18][_],P(i)
_++})),O[I]='┘└┴ ┐┌┬ ┤├┼     ╛╘╧ ╕╒╤ ╡╞╪'[j-5]),P(X.indexOf`+`),O.join``)

説明

最初に見つかった+ジャンクションから開始して、プログラムはすべての方向で他のジャンクションへのパスを見つけようとし、そのまま置換を実行します。見つかった方向と「二重境界」状態をビットマップに保存し、適切な接合文字を決定します。

// Take an input string X
f = X => {
    // Copy the input string into an array so characters can be overwritten and eventually output
    O = [...X]

    // Define a function that processes a junction ("+" symbol) at index I in the input string X:
    P = I => {
        // Make a bitmap to keep track of the direction coming out of the junction and double borders
        // Bits from right to left: west, east, north, south, double border
        // E.g. a double-bordered south/east junction corresponds to the binary number 11010 ("╒")
        let j = 0

        // A counter
        let _ = 0

        // Ensure this junction hasn't already been processed
        if(!P[I]){
            P[I] = 1,

            // We'll walk away from the junction in each of the four directions, then west and east again to check for double borders
            // i.e. walk along `a`, replace with `b`, move index `i` by `n`
            // 1st pass: walk along "-", replace with "─", move index by 1
            // 2nd pass: walk along "|", replace with "│", move index by the width of the input (plus 1 for the newline) to traverse vertically
            // 3rd pass: walk along "=", replace with "═", move index by 1
            ['-─1','|│','=═1'].map(([a, b, n = X.indexOf('\n') + 1])=>
                // We'll walk in the negative and positive directions for each pass
                [-n,+n].map(n=>{
                    // Start the walk
                    i=I
                    // Keep walking (incrementing by n) as long as we're on a "path" character, "a"
                    while(i += n, X[i] == a)
                        // Replace the corresponding character in the output with "b"
                        O[i] = b

                    // Upon reaching another junction at index i:
                    if(X[i] == '+'){
                        // OR the bitmap according to the direction we walked
                        j |= [
                            // Pass 1: Horizontal
                            1, // west
                            2, // east

                            // Pass 2: Vertical
                            4, // north
                            8, // south

                            // Pass 3: Double Horizontal (only if we've walked more than 1 step)
                            I-i > 1 && 17, // west, double border
                            i-I > 1 && 18 // east, double border
                        ][_]

                        // Process the junction we walked to
                        P(i)
                    }
                    _++
                })
            )

            // Finally, replace the "+" with a proper junction character based on the bitmap value
            O[I] = '     ┘└┴ ┐┌┬ ┤├┼     ╛╘╧ ╕╒╤ ╡╞╪'[j]
        }
    }

    // Process the first junction to kick off the recursion
    P(X.indexOf`+`)

    // Return our modified character array as a joined string
    return O.join``
}

修正済み-バイト数ではなく、文字数を確認する必要がありました。
-darrylyeo

1

Python 3、599バイト

私はPython 3でのゴルフはあまり得意ではありませんが、(残念なことに)Python 2ではUTF-8文字の通常の出力を得ることができませんでした。

ここでの唯一の興味深いトリックは、+変換を決定することだと思います。
4ビットアドレスを使用して、考えられるすべてのバリアントをエンコードしました。アドレスの各ビットは、neightbourセルへの接続に似ています。0-接続なし、1-接続。
1111is
0011is
etc
接続の一部の構成は無効であり、ダミー値に置き換えられます。'012┐45┌┬8┘0┤└┴├┼'

neightbourセルにが含まれている場合=、2番目のリストが二重線で使用されます。

['012┐45┌┬8┘0┤└┴├┼','012╕45╒╤8╛0╡╘╧╞╪']['='in r]

ここでアドレスが結合されます。

r=''.join([str(int(V(y,x)))+W(y,x)for y,x in[(Y-1,X),(Y,X+1),(Y+1,X),(Y,X-1)]])

r文字列の長さ8が含まれます。2文字ごとに1/0で、実際にはneightbour文字です。
例:1+0y1-1|
これは、前に示したように置換のリストを選択するために使用されます。そして、アドレスに契約しました:int(r[0::2],2)

このラムダは、セル座標が有効であり、セルのcharが「+-| =」のいずれかであることを確認するために使用されました

V=lambda y,x:~0<x<len(I[0])and~0<y<len(I)and I[y][x]in'+-|='

このラムダは、セルからcharを受け取るために使用されました。' '座標が無効かどうかを返します。(間違いなくゴルフで離れることができます)

W=lambda y,x:V(y,x)and I[y][x]or' '

再帰の条件。ゴルフもできるかもしれません。

if Z in'+-=':F(Y,X+1);F(Y,X-1)
if Z in'+|':F(Y-1,X);F(Y+1,X)

I=eval(input())
J=[i[:]for i in I]
V=lambda y,x:~0<x<len(I[0])and~0<y<len(I)and I[y][x]in'+-|='
W=lambda y,x:V(y,x)and I[y][x]or' '
def F(Y,X):
 if V(Y,X)and I[Y][X]==J[Y][X]:
  Z=I[Y][X]
  if','>Z:
   r=''.join([str(int(V(y,x)))+W(y,x)for y,x in[(Y-1,X),(Y,X+1),(Y+1,X),(Y,X-1)]])
   J[Y][X]=['012┐45┌┬8┘0┤└┴├┼','012╕45╒╤8╛0╡╘╧╞╪']['='in r][int(r[0::2],2)]
  else:J[Y][X]=dict(zip('|-=','│─═'))[Z]
  if Z in'+-=':F(Y,X+1);F(Y,X-1)
  if Z in'+|':F(Y-1,X);F(Y+1,X)
e=enumerate
F(*[(y,x)for y,r in e(I)for x,c in e(r)if'+'==c][0])
for r in J:print(''.join(r))

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

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.