Matriz con 1 a L (n), en todas las n columnas

18

Desafío:

Tome una lista, L que contenga enteros positivos como entrada:

3 5 2 1 6

y crea una matriz donde la enésima columna contiene el vector 1: L (n) , donde las filas más cortas se rellenan con ceros.

Casos de prueba:

3   5   2   1   6
-----------------
1   1   1   1   1
2   2   2   0   2
3   3   0   0   3
0   4   0   0   4
0   5   0   0   5
0   0   0   0   6

1
-
1

1   2   3   4   3   2   1
-------------------------
1   1   1   1   1   1   1
0   2   2   2   2   2   0
0   0   3   3   3   0   0
0   0   0   4   0   0   0

Reglas:

  • Formatos opcionales de entrada y salida.
    • La lista de listas es un formato de salida aceptable
  • La matriz debe ser lo más pequeña posible (no puede rellenarla con más ceros de los necesarios)
  • El código más corto en cada idioma gana
  • Las explicaciones son altamente recomendables
Stewie Griffin
fuente
¿Podemos distribuir los rangos horizontalmente en su lugar?
Sr. Xcoder
No, deberían ser verticales. Si usa un idioma donde las palabras horizontal / vertical no tienen ningún significado, entonces es opcional. (Podría ser relevante para idiomas donde las listas de listas no están asociadas con direcciones horizontales / verticales)
Stewie Griffin
1
@StewieGriffin ¿Qué lenguaje sensato no asocia dimensiones con listas anidadas?
Erik the Outgolfer
44
@EriktheOutgolfer, ¿Cuántos idiomas locos se usan en este sitio?
Stewie Griffin
2
@EriktheOutgolfer R para uno no ve las matrices como una lista anidada, sino más bien una larga lista, que se ajusta en hileras.
JAD

Respuestas:

18

R , 40 38 bytes

function(l)outer(m<-1:max(l),l,"<=")*m

Pruébalo en línea!

Explicación:

outeraplica su tercer argumento (la función) a todas las combinaciones de elementos de sus dos primeros argumentos, generando una matriz de TRUEy FALSEdonde cada columna tiene TRUEdonde 1:max(l)es menor o igual que el elemento correspondiente de l, por ejemplo, donde l=c(3,5,2,1,6):

      [,1]  [,2]  [,3]  [,4] [,5]
[1,]  TRUE  TRUE  TRUE  TRUE TRUE
[2,]  TRUE  TRUE  TRUE FALSE TRUE
[3,]  TRUE  TRUE FALSE FALSE TRUE
[4,] FALSE  TRUE FALSE FALSE TRUE
[5,] FALSE  TRUE FALSE FALSE TRUE
[6,] FALSE FALSE FALSE FALSE TRUE

Luego, suponiendo que la matriz resultante es A, entonces A*m-> A[i,j]=A[i,j]*ique coaccionaTRUE a 1 y FALSEa 0, produciendo el resultado deseado.

Giuseppe
fuente
Creo que - se puede ahorrar 2 bytes, reemplazando function(l)conl=scan();
AndriusZ
@AndriusZ pero luego tendría que envolver todo en una printpara que perdiera esos bytes.
Giuseppe
Creo que no necesitas envolverlo todo - TOI
AndriusZ
2
@AndriusZ definitivamente hemos hablado de esto antes. La única respuesta a esta meta pregunta da una penalización de +4 por usar source(...,echo=TRUE)y leer stdin como un programa completo, si tiene una sugerencia alternativa, sopesar allí, pero hasta donde sé, eso es lo más cerca que tenemos a un consenso de R sobre programas completos y se destaca por el momento.
Giuseppe
Tarde al juego: guarde dos bytes usando [este consejo] ( codegolf.stackexchange.com/a/111578/80010 )
JayCe
7

MATL , 8 bytes

"@:]Xho!

Pruébalo en línea!

Explicación

"      % Implicit input, L. For each k in L
  @    %   Push k
  :    %   Range [1 2 ... k]
]      % End
Xh     % Collect all stack contents in a cell array
o      % Convert to double matrix. The content of each cell is
       % right-padded with zeros if needed
!      % Transpose. Implicitly display
Luis Mendo
fuente
5

Mathematica, 20 bytes

PadRight@Range@#&

Contiene U + F3C7 ( Transposefunción incorporada de Mathematica )

Pruébalo en Wolfram Sandbox

Uso

PadRight@Range@#&[{3, 5, 2, 1, 6}]
{
 {1, 1, 1, 1, 1},
 {2, 2, 2, 0, 2},
 {3, 3, 0, 0, 3},
 {0, 4, 0, 0, 4},
 {0, 5, 0, 0, 5},
 {0, 0, 0, 0, 6}
}

Explicación

PadRight@Range@#&

         Range@#    (* Generate {1..n} for all elements of input *)
PadRight@           (* Right-pad 0s so that all lists are equal length *)
                   (* Transpose the result *)
JungHwan Min
fuente
@downvoters ¿por qué los votos negativos? ¿Podrían explicarlo?
JungHwan Min
No voté en contra, pero sospecho que es porque le falta la firma de la función o una entrada de argumentos, ¡lo que hace que su fragmento de código no sea un cuadro negro!
sergiol
5

Octava , 26 bytes

@(x)((y=1:max(x))'<=x).*y'

Función anónima que ingresa un vector de fila y genera una matriz.

Pruébalo en línea!

Explicación

Considere la entrada x = [3 5 2 1 6]. Este es un vector de fila de tamaño 1 × 5.

1:max(x)da el vector fila [1 2 3 4 5 6], que se asigna a la variable y.

La transposición de eso, es decir, el vector de columna [1; 2; 3; 4; 5; 6], se <=compara (elemento-sabio con difusión) con la entrada [3 5 2 1 6]. El resultado es la matriz 6 × 5

[1 1 1 1 1;
 1 1 1 0 1;
 1 1 0 0 1;
 0 1 0 0 1;
 0 1 0 0 1;
 0 0 0 0 1]

Finalmente, multiplicando (elemento-sabio con difusión) por el vector de columna [1; 2; 3; 4; 5; 6], obtenido como ytranspuesto, da el resultado deseado:

[1 1 1 1 1;
 2 2 2 0 2;
 3 3 0 0 3;
 0 4 0 0 4;
 0 5 0 0 5;
 0 0 0 0 6]
Luis Mendo
fuente
1
Esperaba ver una presentación de MATLAB / Octave. Implementé esto sin pensarlo, por lo que probablemente tenía más de 40 bytes. Muy buena solución :)
Stewie Griffin
3

Cáscara , 4 bytes

Devuelve una lista de listas

T0mḣ

Pruébalo en línea!

Explicación

  m    Map over the input
   ḣ   Range from 1 to n
T0     Transpose, padding with 0s
H.PWiz
fuente
3

Pyth , 6 bytes

.tSMQZ

Pruébalo aquí! o Verifique todos los casos de prueba (con letra bonita)!


Explicación

.tSMQZ: programa completo.

  SMQ: obtenga los rangos unarios inclusivos para cada uno.
.t - Transposición, relleno con copias de ...
     Z - ... Cero.
         - Impresión implícita.

Una versión de transposición no incorporada sería :

mm*hd<dkQeS

Esto funciona de la siguiente manera:

mm*hd<dkQeS   - Full program.

m        eS   - Map over [0, max(input)) with a variable d.
 m      Q     - Map over the input with a variable k.
   hd         - d + 1.
  *           - Multiplied by 1 if...
     <dk      - ... d is smaller than k, else 0.
              - Output implicitly.
Sr. Xcoder
fuente
3

Jalea , 3 bytes

Rz0

Pruébalo en línea!

Explicación

Rz0  Input: array A
R    Range, vectorizes to each integer
 z0  Transpose and fill with 0
millas
fuente
3

En realidad , 17 bytes

;M╗♂R⌠╜;0@α(+H⌡M┬

Pruébalo en línea!

Explicación:

;M╗♂R⌠╜;0@α(+H⌡M┬
;M╗                store the maximal element (M) of the input in register 0
   ♂R              range(1, n+1) for each n in input
     ⌠╜;0@α(+H⌡M   for each range:
      ╜;0@α          push a list containing M 0s
           (+        append to range
             H       take first M elements
                ┬  transpose
Mego
fuente
Sí, en realidad necesita zip con soporte de relleno ...
Erik the Outgolfer
2

Pyke , 3 bytes

Esto usa la nueva característica de Pyke, codificaciones hexadecimales ... ¡La mejor parte es que vinculamos a Jelly! Bytes sin procesar:

4D 53 AC

Pruébalo aquí!

El equivalente ASCII-Pyke sería de 4 bytes :

MS.,

¿Cómo?

4D 53 AC - Programa completo.

4D - Mapa.
   53 - Gama inclusiva.
      AC - Transponer con ceros.
           - Salida implícita.

-------------------------------------

MS., - Programa completo.

M - Mapa.
 S - Gama inclusiva.
  ., - Transponer con ceros.
       - Salida implícita.

Aquí hay una versión impresa bonita con ASCII, y aquí hay una con codificaciones hexadecimales.

Sr. Xcoder
fuente
2

Perl 6 , 39 bytes

{zip (1 X..$_).map:{|@_,|(0 xx.max-1)}}

Intentalo

Expandido:

{                # bare block lambda with implicit parameter 「$_」

  zip

    (1 X.. $_)   # turn each input into a Range that starts with 1

    .map:        # map each of those Ranges using the following code

    {            # bare block lambda with implicit parameter 「@_」 
                 # (「@_」 takes precedence over 「$_」 when it is seen)

      |@_,       # slip the input into a new list

      |(         # slip this into the list

        0        # a 「0」
        xx       # list repeated by

          .max   # the max of 「$_」 (implicit method call)
          - 1    # minus 1 (so that zip doesn't add an extra row)
      )
    }
}

Tenga en cuenta que ziptermina una vez que se agota la lista de entrada más corta.

Brad Gilbert b2gills
fuente
2

C # , 136 bytes


Datos

  • Entrada Int32[] i Una matriz de entradas
  • Salida Int32[,] Una matriz bidimensional.

Golfed

i=>{int m=System.Linq.Enumerable.Max(i),l=i.Length,x,y;var o=new int[m,l];for(y=0;y<m;y++)for(x=0;x<l;)o[y,x]=i[x++]>y?y+1:0;return o;};

Sin golf

i => {
    int
        m = System.Linq.Enumerable.Max( i ),
        l = i.Length,
        x, y;

    var o = new int[ m, l ];

    for( y = 0; y < m; y++ )
        for( x = 0; x < l; )
            o[ y, x ] = i[ x++ ] > y ? y + 1 : 0;

    return o;
};

Legible sin golf

// Take an array of Int32
i => {

    // Store the max value of the array, the length and declare some vars to save some bytes
    int
        m = System.Linq.Enumerable.Max( i ),
        l = i.Length,
        x, y;

    // Create the bidimensional array to output
    var o = new int[ m, l ];

    // Cycle line by line...
    for( y = 0; y < m; y++ )

        // ... and column by column...
        for( x = 0; x < l; )

            // And set the value of the line in the array if it's lower than the the value at the index of the input array
            o[ y, x ] = i[ x++ ] > y ? y + 1 : 0;

    // Return the bidimentional array.
    return o;
};

Código completo

using System;
using System.Collections.Generic;

namespace TestBench {
    public class Program {
        // Methods
        static void Main( string[] args ) {
            Func<Int32[], Int32[,]> f = i => {
                int
                    m = System.Linq.Enumerable.Max( i ),
                    l = i.Length,
                    x, y;
                var o = new int[ m, l ];
                for( y = 0; y < m; y++ )
                    for( x = 0; x < l; )
                        o[ y, x ] = i[ x++ ] > y ? y + 1 : 0;
                return o;
            };

            List<Int32[]>
                testCases = new List<Int32[]>() {
                    new[] { 1, 2, 5, 6, 4 },
                    new[] { 3, 5, 2, 1, 6 },
                    new[] { 1, 2, 3, 4, 3, 2, 1 },
                };

            foreach( Int32[] testCase in testCases ) {
                Console.WriteLine( " INPUT: " );
                PrintArray( testCase );

                Console.WriteLine( "OUTPUT: " );
                PrintMatrix( f( testCase ) );
            }

            Console.ReadLine();
        }

        public static void PrintArray<TSource>( TSource[] array ) {
            PrintArray( array, o => o.ToString() );
        }
        public static void PrintArray<TSource>( TSource[] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 index = 0; index < array.Length; index++ ) {
                output.Add( valueFetcher( array[ index ] ) );
            }

            Console.WriteLine( $"[ {String.Join( ", ", output )} ]" );
        }

        public static void PrintMatrix<TSource>( TSource[,] array ) {
            PrintMatrix( array, o => o.ToString() );
        }
        public static void PrintMatrix<TSource>( TSource[,] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 xIndex = 0; xIndex < array.GetLength( 0 ); xIndex++ ) {
                List<String>
                    inner = new List<String>();

                for( Int32 yIndex = 0; yIndex < array.GetLength( 1 ); yIndex++ ) {
                    inner.Add( valueFetcher( array[ xIndex, yIndex ] ) );
                }

                output.Add( $"[ {String.Join( ", ", inner )} ]" );
            }

            Console.WriteLine( $"[\n   {String.Join( ",\n   ", output )}\n]" );
        }
    }
}

Lanzamientos

  • v1.0 -136 bytes - Solución inicial.

Notas

  • Ninguna
auhmaan
fuente
1

C (gcc) , 142 bytes

i,j,k;main(c,v)char**v;{for(;++i<c;k=k<*v[i]?*v[i]:k)printf("%c ",*v[i]);for(i=48;puts(""),i++<k;)for(j=1;j<c;)printf("%c ",i<=*v[j++]?i:48);}

Pruébalo en línea!

cleblanc
fuente
1

Java 10, 115 bytes

a->{int l=a.length,m=0;for(int j:a)m=j>m?j:m;var r=new int[m][l];for(;l-->0;)for(m=0;m<a[l];r[m][l]=++m);return r;}

Explicación:

Pruébalo en línea.

a->{                  // Method with integer-array parameter and integer-matrix return-type
  int l=a.length,     //  Length of the array
      m=0;            //  Largest integer in the array, 0 for now
  for(int j:a)        //  Loop over the array
    m=j>m?            //   If the current item is larger than `m`:
       j              //    Set `m` to this item as new max
      :               //   Else:
       m;             //    Leave `m` the same
  var r=new int[m][l];//  Result-matrix of size `m` by `l`, filled with zeroes by default
  for(;l-->0;)        //  Loop over the columns
    for(m=0;m<a[l];   //   Inner loop over the rows
      r[m][l]=++m);   //    Set the cell at position `m,l` to `m+1`
  return r;}          //  Return the result-matrix
Kevin Cruijssen
fuente
0

Protón , 38 bytes

a=>[[i<j?-~i:0for j:a]for i:0..max(a)]

Pruébalo en línea!

Hiperneutrino
fuente
Déjame adivinar, ¿el error es el espacio después?
caird coinheringaahing
@cairdcoinheringaahing Sí. El signo de interrogación consumirá el carácter después de él para asegurarse de que no sea otro signo de interrogación, pero olvidé compensar el carácter adicional que resulta en que se omita.
HyperNeutrino
Parece que tienes un tirón, ahora puedes eliminar el aviso :)
Erik the Outgolfer