Mostrar matriz 2d como tabla ASCII

15

La tarea es mostrar una tabla ascii para una matriz dada.

Entrada

La entrada es una matriz 2D. La longitud de la fila de la matriz es la misma que la longitud de una matriz. Alternativamente, puede tomar la entrada de una matriz 2D con la primera fila es un encabezado. La dimensión exterior es la fila.

Entrada de ejemplo:

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

Salida

El resultado de una tabla se ve a continuación.

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

Cada celda tiene exactamente un espacio a la izquierda y al menos un espacio a la derecha, rellenado hasta que las barras estén alineadas. Sin embargo, al menos una celda tiene solo un espacio a su derecha.

Casos de prueba

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

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

Presentación de ejemplo

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

Este es el , por lo que gana el envío con la menor cantidad de bytes.

jcubic
fuente
Parece el primer respondedor. Por favor, no use ejemplo de solución.
Akangka
@ChristianIrwan eliminado.
jcubic
No elimines, intentaré resolver el desafío.
Akangka
Tienes suficiente reputación para estar en el chat. ¿Crees que deberíamos hablar sobre mejorar esto en el chat? (Parece que se convertirá en una discusión extendida.)
wizzwizz4
2
Si queremos tomar la entrada como una sola cadena en lugar de una matriz, ¿tiene que estar exactamente en el mismo formato que las entradas de ejemplo? Si es así, ¿alguna vez habrá caracteres escapados (o alguna vez habrá comillas en la entrada)? ¿Podemos suponer también que no hay corchetes o comas en la entrada que no sean los delimitadores de matriz? ¿Qué pasa con las barras verticales? En general, ¿cuáles son los caracteres válidos que pueden formar las cadenas de la tabla?
Pomo de la puerta

Respuestas:

3

CJam, 58 bytes

Alguien sabe truco de golf en CJam?

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

Acepta entradas en la forma que se muestra en los casos de prueba. Puede o no ser válido, ya que esto depende de la cadena de entrada no contiene ningún ", ,, ], o |caracteres.

Si la entrada tiene que poder contener ]s, entonces :%s/]/\t./<cr>se puede reemplazar qe$s<Tab>.<esc>j@eq@epor 2 caracteres adicionales. No hay una manera fácil de permitir ",|la entrada.

Debe ejecutarse en un entorno Unix, ya que depende de la columnherramienta de línea de comandos.

Explicación ligeramente desactualizada (por una revisión, pero eso fue solo un poco de reorganización):

: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

Gracias smpl por un byte!

Pomo de la puerta
fuente
Puede guardar un byte reemplazándolo :setcon :se.
user530873
5

JavaScript (ES6), 210212219

Editar 2 bytes guardados gracias a @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)

PRUEBA

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
fuente
Quiso decir a=>(?
Neil
(c,i)=>s[i]>(l=c.length)?0:s[i]=lte ahorra dos bytes, creo.
Neil
@Neil 1. sí 2.gracias
edc65
@PhiNotPi estuvo de acuerdo
edc65
¿Por qué ese comentario llegó a mi bandeja de entrada?
Neil
2

Pitón 2, 190

Esta solución hace uso de comprensiones de listas y expresiones generadoras. Acepta una lista de listas y devuelve una cadena en el formato requerido.

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

El código antes del minificador:

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

que salidas:

+---------------------+-------------------+------------+------------+------------+------------+
| 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%        |
+---------------------+-------------------+------------+------------+------------+------------+
Caballero Lógico
fuente
Me entristeció que esto casi no funcionó:from tabulate import*;a=input();print tabulate(a[1:],a[0],'psql',numalign='left')
quintopia
185 bytes: ¡ Pruébelo en línea!
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))

Explicación a seguir.


Caso de prueba:

Entrada:

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

Salida:

+---------------------+-------------------+------------+------------+------------+------------+
| 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
fuente
1

Rubí, 129 126 127 126 caracteres

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

Ejecución de muestra:

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%        |
+---------------------+-------------------+------------+------------+------------+------------+
hombre trabajando
fuente