Afficher le tableau 2D en tant que table ASCII

15

La tâche consiste à afficher la table ascii pour un tableau donné.

Contribution

L'entrée est une matrice 2D. La longueur de ligne de la matrice est identique à la longueur d'un tableau. Alternativement, vous pouvez saisir une matrice 2D dont la première ligne est un en-tête. La dimension extérieure est la ligne.

Exemple d'entrée:

[["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%"]]

Production

La sortie d'un tableau ressemble à ci-dessous.

+---------------------+-------------------+------------+------------+------------+------------+
| 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%        |
+---------------------+-------------------+------------+------------+------------+------------+

Chaque cellule a exactement un espace à gauche et au moins un espace à droite, rembourré jusqu'à ce que les barres soient alignées. Cependant, au moins une cellule n'a qu'un seul espace à sa droite.

Cas de test

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

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

Exemple de soumission

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;
    }
}

C'est du , donc la soumission avec le moins d'octets gagne!

jcubic
la source
On dirait le premier répondeur. Veuillez ne pas utiliser d'exemple de solution.
Akangka
@ChristianIrwan supprimé.
jcubic
Ne supprimez pas, je vais essayer de comprendre le défi.
Akangka
Vous avez assez de réputation pour discuter. Pensez-vous que nous devrions parler d'améliorer cela sur le chat? (Il semble que cela deviendra une discussion approfondie.)
wizzwizz4
2
Si nous voulons prendre l'entrée comme une chaîne unique au lieu d'un tableau, doit-elle être exactement au même format que les entrées d'exemple? Si oui, y aura-t-il jamais des caractères échappés (ou y aura-t-il jamais des guillemets dans l'entrée)? Pouvons-nous également supposer qu'il n'y a pas de crochets ou de virgules dans l'entrée autre que les délimiteurs de tableau? Et les barres verticales? En général, quels sont les caractères valides pouvant constituer les chaînes du tableau?
Poignée de porte

Réponses:

3

CJam, 58 octets

Quelqu'un sait truc de golf à CJam?

q~z_{:,:e>)}%_{)'-*'++}%'+\+N+@@.{f{Se]"| "\+}}z'|N+f+1$f+
Akangka
la source
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

Accepte les entrées sous la forme indiquée dans les cas de test. Ou non être valide, car cela repose sur la chaîne d'entrée ne contenant pas ", ,, ]ou |caractères.

Si l'entrée doit pouvoir contenir ]s, elle :%s/]/\t./<cr>peut être remplacée par qe$s<Tab>.<esc>j@eq@epour 2 caractères supplémentaires. Il n'y a pas de moyen facile de permettre ",|l'entrée.

Doit être exécuté dans un environnement Unix, car il repose sur l' columnoutil de ligne de commande.

Explication légèrement dépassée (par une révision, mais c'était juste un peu de réorganisation):

: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

Merci smpl pour un octet!

Poignée de porte
la source
Vous pouvez enregistrer un octet en le remplaçant :setpar :se.
user530873
5

JavaScript (ES6), 210 212 219

Modifier 2 octets enregistrés 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)

TESTER

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
la source
Vous vouliez dire a=>(?
Neil
(c,i)=>s[i]>(l=c.length)?0:s[i]=lvous fait gagner deux octets, je pense.
Neil
@Neil 1. oui 2.merci
edc65
@PhiNotPi a accepté
edc65
Huh, pourquoi ce commentaire a-t-il frappé ma boîte de réception?
Neil
2

Python 2, 190

Cette solution utilise des compréhensions de liste et des expressions de générateur. Il accepte une liste de listes et renvoie une chaîne au format requis.

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])

Le code avant le minifieur:

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

qui génère:

+---------------------+-------------------+------------+------------+------------+------------+
| 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%        |
+---------------------+-------------------+------------+------------+------------+------------+
Logic Knight
la source
J'étais triste que cela ait presque mais pas tout à fait fonctionné:from tabulate import*;a=input();print tabulate(a[1:],a[0],'psql',numalign='left')
quintopie
185 octets: essayez-le en ligne!
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))

Explication à suivre.


Cas de test:

Contribution:

'[["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%"]]'

Production:

+---------------------+-------------------+------------+------------+------------+------------+
| 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
la source
1

Ruby, 129 126 127 126 caractères

->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]*$/}

Exemple d'exécution:

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%        |
+---------------------+-------------------+------------+------------+------------+------------+
homme au travail
la source