Tampilkan array 2d sebagai tabel ASCII

15

Tugasnya adalah untuk menampilkan tabel ascii untuk array yang diberikan.

Memasukkan

Masukan adalah matriks 2D. Panjang baris matriks sama dengan panjang array. Atau, Anda dapat mengambil input dari matriks 2D dengan baris pertama adalah header. Dimensi luar adalah baris.

Input Contoh:

[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]

Keluaran

Output dari tabel terlihat seperti di bawah ini.

+---------------------+-------------------+------------+------------+------------+------------+
| License             | 2008-05-08        | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2               | 58.69%            | 52.2%      | 42.5%      | 33%        | 23%        |
| GPLv3               | 1.64%             | 4.15%      | 6.5%       | 12%        | 9%         |
| LGPL 2.1            | 11.39%            | 9.84%      | ?          | 6%         | 5%         |
| LGPL 3.0            | ? (<0.64%)        | 0.37%      | ?          | 3%         | 2%         |
| GPL family together | 71.72% (+ <0.64%) | 66.56%     | ?          | 54%        | 39%        |
+---------------------+-------------------+------------+------------+------------+------------+

Setiap sel memiliki tepat satu ruang di sebelah kiri dan setidaknya satu ruang di sebelah kanan, diisi sampai palang sejajar. Namun, setidaknya satu sel hanya memiliki satu ruang di sebelah kanannya.

Uji kasus

Input:
[["Hello", "World", "!!!"],["aa", "bbbbbbbbb", "CcC"], ["Pyth",  "CJam", "GolfScript"]]

Output:
+-------+-----------+------------+
| Hello | World     | !!!        |
+-------+-----------+------------+
| aa    | bbbbbbbbb | CcC        |
| Pyth  | CJam      | GolfScript |
+-------+-----------+------------+

Contoh pengiriman

function ascii_table(array, header) {
    var lengths = array[0].map(function(_, i) {
        var col = array.map(function(row) {
            if (row[i] != undefined) {
                return row[i].length;
            } else {
                return 0;
            }
        });
        return Math.max.apply(Math, col);
    });
    array = array.map(function(row) {
        return '| ' + row.map(function(item, i) {
            var size = item.length;
            if (size < lengths[i]) {
                item += new Array(lengths[i]-size+1).join(' ');
            }
            return item;
        }).join(' | ') + ' |';
    });
    var sep = '+' + lengths.map(function(length) {
        return new Array(length+3).join('-');
    }).join('+') + '+';
    if (header) {
        return sep + '\n' + array[0] + '\n' + sep + '\n' +
            array.slice(1).join('\n') + '\n' + sep;
    } else {
        return sep + '\n' + array.join('\n') + '\n' + sep;
    }
}

Ini adalah , jadi pengiriman dengan jumlah byte paling sedikit menang!

jcubic
sumber
Sepertinya penjawab pertama. Tolong, jangan gunakan contoh-solusi.
Akangka
@ChristianIrwan dihapus.
jcubic
Jangan hapus, saya akan mencoba mencari tahu tantangannya.
Akangka
Anda memiliki cukup reputasi untuk mengobrol. Apakah Anda pikir kita harus berbicara tentang meningkatkan ini di Obrolan? (Sepertinya itu akan menjadi diskusi panjang.)
wizzwizz4
2
Jika kita ingin mengambil input sebagai string tunggal dan bukan array, apakah itu harus dalam format yang sama persis dengan contoh input? Jika demikian, apakah akan ada karakter yang lolos (atau akan ada kutipan dalam input)? Bisakah kita juga berasumsi bahwa tidak ada tanda kurung atau koma di input selain pembatas array? Bagaimana dengan bilah vertikal? Secara umum, apa saja karakter yang valid yang dapat membentuk string dalam tabel?
Gagang Pintu

Jawaban:

3

CJam, 58 byte

Adakah yang tahu trik bermain golf di CJam?

q~z_{:,:e>)}%_{)'-*'++}%'+\+N+@@.{f{Se]"| "\+}}z'|N+f+1$f+
Akangka
sumber
9

vim, 139 138 134

$x0xqq%ls<cr><esc>@qq@q:se nosol|%s/,/\t/g|%s/]/\t./|%!column -t -s'<C-v><Tab>'<cr>qwf";;h<C-v>GI|<esc>@wq@wll<C-v>Gls|<esc>0<C-v>Gs| <esc>:%s/"//g<cr>Yp:s/[^|]/-/g|s/|/+/g<cr>YggpkP

Menerima input dalam bentuk yang ditunjukkan dalam kasus uji. Mungkin atau mungkin tidak valid, karena ini bergantung pada input string tidak pernah yang mengandung ", ,, ], atau |karakter.

Jika input harus mampu mengandung ]s, maka :%s/]/\t./<cr>dapat diganti dengan qe$s<Tab>.<esc>j@eq@euntuk 2 karakter tambahan. Tidak ada cara mudah untuk mengizinkan ",|input.

Harus dijalankan di lingkungan Unix, karena bergantung pada columnalat baris perintah.

Penjelasan sedikit usang (oleh satu revisi, tapi itu hanya sedikit penataan ulang):

:se nosol<cr>    we need this later: G in visual block shouldn't go to BOL
$x0x             delete the surrounding pair of brackets
qq               record a macro
 %ls<cr><esc>    put each element of the big array on its own line
 @qq             recurse
@q               play back the macro until EOF
:%s/,/\t/g<cr>   replace all remaining commas with tabs
:%s/]/\t./<cr>   replace the ] at the end of lines with tabs and a dot
                 we need this for the line at the right edge of the table
:%!column -t     run the whole file through `column' on tabs
 -s'<C-v><Tab>
 '<cr>
qw               record another macro
 f";;            go forward 3 "s--that is, to the next "column"
 h               go back to the middle of the column
 <C-v>GI|<esc>   insert a line behind the cursor from top to bottom
 @wq             recurse
@w               play back until EOF
ll               move right before the line of dots we added earlier
<C-v>Gl          select the dots
s|<esc>          replace with a line (top to bottom)
0<C-v>G          select all the opening brackets
s| <esc>         again, (the leftmost) line
:%s/"//g<cr>     kill all the quotes around the data
Yp               duplicate bottom line
:s/[^|]/-/g<cr>  replace everything that's not a line with a dash
:s/|/+/g<cr>     now replace the lines with plus signs
YggpkP           put the separators before and after the first line

Terima kasih smpl untuk satu byte!

Gagang pintu
sumber
Anda dapat menyimpan byte dengan menggantinya :setdengan :se.
user530873
5

JavaScript (ES6), 210 212 219

Edit 2 byte yang disimpan thx @Neil

a=>(J=(m,j)=>j+m.join(j)+j,a.map(r=>r.map((c,i)=>s[i]>(l=c.length)?0:s[i]=l),s=[]),t=J(s.map(n=>'-'.repeat(n+2)),'+'),z=a.map(r=>J(r.map((c,i)=>' '+c+' '.repeat(s[i]+1-c.length)),'|')),z[0]+=`
`+t,t+J(z,`
`)+t)

UJI

F=a=>(
  J=(m,j)=>j+m.join(j)+j,
  a.map(r=>r.map((c,i)=>s[i]>(l=c.length)?0:s[i]=l),s=[]),
  t=J(s.map(n=>'-'.repeat(n+2)),'+'),
  z=a.map(r=>J(r.map((c,i)=>' '+c+' '.repeat(s[i]+1-c.length)),'|')),
  z[0]+='\n'+t,
  t+J(z,'\n')+t
)  

Z=[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]

O.textContent=F(Z)
<pre id=O></pre>

edc65
sumber
Apakah maksud Anda a=>(?
Neil
(c,i)=>s[i]>(l=c.length)?0:s[i]=lmenghemat dua byte, saya pikir.
Neil
@Neil 1. yes 2.thanks
edc65
@PhiNotPi setuju
edc65
Hah, mengapa komentar itu masuk ke kotak masuk saya?
Neil
2

Python 2, 190

Solusi ini memanfaatkan daftar pemahaman dan ekspresi generator. Ini menerima daftar daftar, dan mengembalikan string dalam format yang diperlukan.

def b(i):
 d=[max(map(len,c))for c in zip(*i)]
 a='+'+''.join('-'*h+'--+'for h in d)
 e=['|'+''.join(' '+f.ljust(h)+' |'for h,f in zip(d,j))for j in i]
 return'\n'.join([a,e[0],a]+e[1:]+[a])

Kode sebelum minifier:

def mktable(data):
    sizes = [max(map(len, column)) for column in zip(*data)]
    divider = '+' + ''.join('-'*size+'--+' for size in sizes)
    lines = ['|' + ''.join(
                ' ' + value.ljust(size) + ' |' for size, value in zip(sizes, row)
                )
                for row in data]
    return '\n'.join([divider, lines[0], divider] + lines[1:] + [divider])

data = [
    ["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],
    ["GPLv2","58.69%","52.2%","42.5%","33%","23%"],
    ["GPLv3","1.64%","4.15%","6.5%","12%","9%"],
    ["LGPL 2.1","11.39%","9.84%","?","6%","5%"],
    ["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],
    ["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]
    ]

table = mktable(data)
print table

yang keluaran:

+---------------------+-------------------+------------+------------+------------+------------+
| License             | 2008-05-08        | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2               | 58.69%            | 52.2%      | 42.5%      | 33%        | 23%        |
| GPLv3               | 1.64%             | 4.15%      | 6.5%       | 12%        | 9%         |
| LGPL 2.1            | 11.39%            | 9.84%      | ?          | 6%         | 5%         |
| LGPL 3.0            | ? (<0.64%)        | 0.37%      | ?          | 3%         | 2%         |
| GPL family together | 71.72% (+ <0.64%) | 66.56%     | ?          | 54%        | 39%        |
+---------------------+-------------------+------------+------------+------------+------------+
Ksatria Logika
sumber
Saya sedih bahwa ini hampir tetapi tidak berhasil:from tabulate import*;a=input();print tabulate(a[1:],a[0],'psql',numalign='left')
quintopia
185 byte: Cobalah secara online!
mdahmoune
1

MATLAB, 244 239 229 226

a=eval(regexprep(input(''),{'], *?[','[[',']]','"'},{';','{','}',''''}));s=size(a);c=repmat(' | ',s(1),1);b=c;for i=1:s(2)
x=char(a{:,i});b=[b x c];end
h=b(1,:);r=h*0+'-';r(h=='|')='+';b=[r;h;r;b(2:end,:);r];disp(b(:,2:end-1))

Penjelasan untuk diikuti.


Kasus cobaan:

Memasukkan:

'[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]'

Keluaran:

+---------------------+-------------------+------------+------------+------------+------------+
| License             | 2008-05-08        | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2               | 58.69%            | 52.2%      | 42.5%      | 33%        | 23%        |
| GPLv3               | 1.64%             | 4.15%      | 6.5%       | 12%        | 9%         |
| LGPL 2.1            | 11.39%            | 9.84%      | ?          | 6%         | 5%         |
| LGPL 3.0            | ? (<0.64%)        | 0.37%      | ?          | 3%         | 2%         |
| GPL family together | 71.72% (+ <0.64%) | 66.56%     | ?          | 54%        | 39%        |
+---------------------+-------------------+------------+------------+------------+------------+
Tom Carpenter
sumber
1

Ruby, 129 126 127 126 karakter

->a{t=?|
a.transpose.map{|c|t+=" %-#{c.map(&:size).max}s |"}
[d=(t%a[0].map{p}).tr('| ','+-'),a.map{|r|t%r}.insert(1,d),d]*$/}

Contoh dijalankan:

2.1.5 :001 > puts ->a{t=?|;a.transpose.map{|c|t+=" %-#{c.map(&:size).max}s |"};[d=(t%a[0].map{p}).tr('| ','+-'),a.map{|r|t%r}.insert(1,d),d]*$/}[[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]]
+---------------------+-------------------+------------+------------+------------+------------+
| License             | 2008-05-08        | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2               | 58.69%            | 52.2%      | 42.5%      | 33%        | 23%        |
| GPLv3               | 1.64%             | 4.15%      | 6.5%       | 12%        | 9%         |
| LGPL 2.1            | 11.39%            | 9.84%      | ?          | 6%         | 5%         |
| LGPL 3.0            | ? (<0.64%)        | 0.37%      | ?          | 3%         | 2%         |
| GPL family together | 71.72% (+ <0.64%) | 66.56%     | ?          | 54%        | 39%        |
+---------------------+-------------------+------------+------------+------------+------------+
manatwork
sumber