Faites-le exploser!

33

Prenez une matrice d’entiers positifs en entrée et faites-la exploser!


Pour exploser une matrice, il suffit d’ajouter des zéros autour de chaque élément, y compris les bordures extérieures.

Les formats d'entrée / sortie sont optionnels comme toujours!

Cas de test:

1
-----
0 0 0
0 1 0
0 0 0
--------------

1 4
5 2
-----
0 0 0 0 0
0 1 0 4 0
0 0 0 0 0
0 5 0 2 0
0 0 0 0 0
--------------

1 4 7
-----
0 0 0 0 0 0 0
0 1 0 4 0 7 0
0 0 0 0 0 0 0
--------------

6
4
2
-----
0 0 0
0 6 0
0 0 0
0 4 0
0 0 0
0 2 0
0 0 0
Stewie Griffin
la source

Réponses:

59

Langage de script Operation Flashpoint , 182 octets

f={t=_this;c=count(t select 0);e=[0];i=0;while{i<c*2}do{e=e+[0];i=i+1};m=[e];i=0;while{i<count t}do{r=+e;j=0;while{j<c}do{r set[j*2+1,(t select i)select j];j=j+1};m=m+[r,e];i=i+1};m}

Ungolfed:

f=
{
  // _this is the input matrix. Let's give it a shorter name to save bytes.
  t = _this;
  c = count (t select 0);

  // Create a row of c*2+1 zeros, where c is the number of columns in the
  // original matrix.
  e = [0];
  i = 0;
  while {i < c*2} do
  {
    e = e + [0];
    i = i + 1
  };

  m = [e]; // The exploded matrix, which starts with a row of zeros.
  i = 0;
  while {i < count t} do
  {
    // Make a copy of the row of zeros, and add to its every other column 
    // the values from the corresponding row of the original matrix.
    r = +e;
    j = 0;
    while {j < c} do
    {
      r set [j*2+1, (t select i) select j];
      j = j + 1
    };

    // Add the new row and a row of zeroes to the exploded matrix.
    m = m + [r, e];
    i = i + 1
  };

  // The last expression is returned.
  m
}

Appeler avec:

hint format["%1\n\n%2\n\n%3\n\n%4",
    [[1]] call f,
    [[1, 4], [5, 2]] call f,
    [[1, 4, 7]] call f,
    [[6],[4],[2]] call f];

Sortie:

Dans l'esprit du challenge:

Steadybox
la source
6
Inconnu; homme; mille.
MooseBoys
2
Maintenant, je suis confus
Grajdeanu Alex.
@MrGrj La commande fait littéralement exploser quelque chose
1
+1 pour le deuxième gif " Dans l’esprit du challenge "! :)
Kevin Cruijssen le
10

Gelée ,  12 à  11 octets

-1 octet grâce à Erik l'Outgolfer (inutile d'utiliser des arguments échangés pour une jointure)

j00,0jµ€Z$⁺

Essayez-le en ligne! Ou voir une suite de tests .

Un lien monadique acceptant et renvoyant des listes de listes.

Comment?

j00,0jµ€Z$⁺ - Link: list of lists, m
          ⁺ - perform the link to the left twice in succession:
         $  -   last two links as a monad
      µ€    -     perform the chain to the left for €ach row in the current matrix:
j0          -       join with zeros                [a,b,...,z] -> [a,0,b,0,...,0,z]
  0,0       -       zero paired with zero = [0,0]
     j      -       join                     [a,0,b,0,...,0,z] -> [0,a,0,b,0,...,0,z,0]
        Z   -     and then transpose the resulting matrix
Jonathan Allan
la source
Vous pouvez enregistrer un octet:j00,0jµ€Z$⁺
Erik the Outgolfer
Oh, bien sûr, merci!
Jonathan Allan
6

MATL , 12 octets

FTXdX*0JQt&(

L'entrée est une matrice avec un ;séparateur de lignes.

Essayez-le en ligne!

Explication

FT     % Push [0 1]
Xd     % Matrix with that diagonal: gives [0 0; 0 1]
X*     % Implicit input. Kronecker product
0      % Push 0
JQt    % Push 1+j (interpreted as "end+1" index) twice
&(     % Write a 0 at (end+1, end+1), extending the matrix. Implicit display
Luis Mendo
la source
5

Japt , 18 octets

Ov"y ®î íZ c p0Ã"²

Testez-le en ligne! (Utilise le -Qdrapeau pour que la sortie soit plus facile à comprendre.)

Semblable à la réponse de gelée, mais beaucoup plus longtemps ...

Explication

La partie externe du code est juste une solution de contournement pour simuler celle de Jelly :

  "             "²   Repeat this string twice.
Ov                   Evaluate it as Japt.

Le code lui-même est:

y ®   î íZ c p0Ã
y mZ{Zî íZ c p0}   Ungolfed
y                  Transpose rows and columns.
  mZ{          }   Map each row Z by this function:
     Zî              Fill Z with (no argument = zeroes).
        íZ           Pair each item in the result with the corresponding item in Z.
           c         Flatten into a single array.
             p0      Append another 0.

Répété deux fois, ce processus donne le résultat souhaité. Le résultat est implicitement imprimé.

ETHproductions
la source
5

Coque , 12 octets

₁₁
Tm»o:0:;0

Prend et retourne un tableau entier 2D. Essayez-le en ligne!

Explication

Même idée que dans beaucoup d'autres réponses: ajoutez des zéros à chaque ligne et transposez-les deux fois. L'opération de ligne est implémentée avec un pli.

₁₁         Main function: apply first helper function twice
Tm»o:0:;0  First helper function.
 m         Map over rows:
  »         Fold over row:
   o         Composition of
      :       prepend new value and
    :0        prepend zero,
       ;0    starting from [0].
            This inserts 0s between and around elements.
T          Then transpose.
Zgarb
la source
5

Mathematica, 39 octets

r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r

Essayez-le au bac à sable Wolfram! Appelez ça comme " r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r@{{1,2},{3,4}}".

Comme beaucoup d'autres réponses, cela fonctionne en transposant et en décalant les zéros dans chaque ligne, puis en répétant la même chose. Inspiré par la réponse de Jonathan Allan sur la gelée en particulier, mais uniquement parce que je suis tombé sur cette réponse en premier.

Pas un arbre
la source
4

Dyalog APL, 24 octets

4 octets enregistrés grâce à @ZacharyT

5 octets enregistrés grâce à @KritixiLithos

{{⍵↑⍨-1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵}

Essayez-le en ligne!

Uriel
la source
Tu n'as pas besoin de parens autour du 1,1,⍴⍵, hein?
Zacharý
Je reçois ceci: {{⍵↑⍨-1 1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵}à 26
Kritixi Lithos
@KritixiLithos belle utilisation de 1 1+!
Uriel
Le tableau orienté APL, alors 1+fonctionnerait?
Zacharý
@ZacharyT Je viens de me rendre compte qu'après avoir vu votre réponse ...
Kritixi Lithos
3

Python 3 , 104 101 97 93 86 octets

  • @Zachary T enregistré 3 octets: variable inutilisée wsupprimée et un espace indésirable
  • @Zachary T a sauvegardé encore 4 octets: [a,b]comme a,blors de l'ajout à une liste
  • @nore sauvé 4 octets: utilisation du slicing
  • @Zachary T et @ovs ont contribué à la sauvegarde de 7 octets: compression des instructions dans la boucle for
def f(a):
 m=[(2*len(a[0])+1)*[0]]
 for i in a:r=m[0][:];r[1::2]=i;m+=r,m[0]
 return m

Essayez-le en ligne!

fonctionnaire
la source
1
Vous pouvez supprimer wet sauvegarder 2 octets: repl.it/JBPE
Zacharý
1
Oh, vous avez un espace inutile après la lignem+=[r,w]
Zacharý
1
Aussi, pouvez-vous économiser 4 octets en changeant de [j,0]destination j,0ou de [r,m[0]destination r,m[0]?
Zacharý
1
Vous pouvez enregistrer 4 autres octets en utilisant des tranches de tableau .
plus de
1
Vous pouvez enregistrer trois octets en convertissant en python2 et en modifiant l’ forindentation de la boucle en un seul onglet.
Zacharý
3

Python 3, 118 octets

def a(b):
    z='00'*len(b[0])+'0'
    r=z+'\n'
    for c in b:
        e='0'
        for d in c:e+=str(d)+'0'
        r+=e+'\n'+z+'\n'
    return r

Première fois au golf! Pas le meilleur, mais je suis assez fier si je peux le dire moi-même!

  • -17 octets de commentaires de blé
  • -4 octets à partir de la deuxième ligne pour la boucle
Liren
la source
Bonjour et bienvenue sur le site. Vous semblez avoir beaucoup d'espaces blancs ici. Par exemple, certains de vos +=et =sont entourés d'espaces, qui peuvent être supprimés. De plus, faire +=deux fois de suite pourrait être simplifié en une seule déclaration, par exemplee+=str(d)+'0'
Wheat Wizard
@ WheatWizard: Merci et merci. Enregistré 17 octets :)
Liren
Je remarque maintenant que vous pouvez réduire votre forboucle interne sur une seule ligne for d in c:e+=str(d)+'0', mais vous pouvez également utiliser une carte de jointure (str, d)) + '0' , in which case it becomes pointless to define e ' .
Wheat Wizard
1
Ah, je viens de penser à cela moi-même! Hmm, je devrais apprendre ce que .join et map () est le premier, je suppose. Je reviendrai!
Liren
1
Vous pouvez mettre les définitions de zet rsur la même ligne (avec un ;entre elles), en sauvegardant un octet d'indentation.
nore
3

R, 65 octets

Merci à Jarko Dubbeldam et Giuseppe pour leurs précieux commentaires!

Code

f=function(x){a=dim(x);y=array(0,2*a+1);y[2*1:a[1],2*1:a[2]]=x;y}

L'entrée pour la fonction doit être une matrice ou un tableau à deux dimensions.

Tester

f(matrix(1))
f(matrix(c(1,5,4,2),2))
f(matrix(c(1,4,7),1))
f(matrix(c(6,4,2)))

Sortie

> f(matrix(1))
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    1    0
[3,]    0    0    0
> f(matrix(c(1,5,4,2),2))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    1    0    4    0
[3,]    0    0    0    0    0
[4,]    0    5    0    2    0
[5,]    0    0    0    0    0
> f(matrix(c(1,4,7),1))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0    0    0    0    0    0    0
[2,]    0    1    0    4    0    7    0
[3,]    0    0    0    0    0    0    0
> f(matrix(c(6,4,2)))
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    6    0
[3,]    0    0    0
[4,]    0    4    0
[5,]    0    0    0
[6,]    0    2    0
[7,]    0    0    0
Djhurio
la source
En un coup d'œil, je pense que l'utilisation a=dim(x)*2+1au lieu de nrowet ncolserait mieux. Vous pourriez alors faire y=matrix(0);dim(y)=aet 2*1:a[1],2*1:a[2].
JAD
1
En fait, ce y=array(0,a)serait encore plus court.
JAD
1
Je pense que vous pouvez supprimer les parenthèses autour des indices, c'est-à-dire 2*1:a[1]parce :que leur priorité est supérieure à celle de*
Giuseppe
2

Mathematica, 55 octets

(a=ArrayFlatten)@{o={0,0},{0,a@Map[{{#,0},o}&,#,{2}]}}&
Alephalpha
la source
3
o={0,0}peut être réduit ào=0{,}
JungHwan Min
2

PHP , 98 octets

Entrée sous forme de tableau 2D, sortie sous forme de chaîne

<?foreach($_GET as$v)echo$r=str_pad(0,(count($v)*2+1)*2-1," 0"),"
0 ".join(" 0 ",$v)." 0
";echo$r;

Essayez-le en ligne!

PHP , 116 octets

Entrée et sortie sous forme de tableau 2D

<?foreach($_GET as$v){$r[]=array_fill(0,count($v)*2+1,0);$r[]=str_split("0".join(0,$v)."0");}$r[]=$r[0];print_r($r);

Essayez-le en ligne!

Jörg Hülsermann
la source
2

Clojure, 91 octets

#(for[h[(/ 2)]i(range(- h)(count %)h)](for[j(range(- h)(count(% 0))h)](get(get % i[])j 0)))

Itère sur les plages par demi-pas.

NikoNyrh
la source
2

Python 2 , 64 octets

lambda l:map(g,*map(g,*l))
g=lambda*l:sum([[x,0]for x in l],[0])

Essayez-le en ligne!

La fonction gsépare l'entrée entre les zéros. La fonction principale transpose l'entrée lors de l'application g, puis recommence. Peut-être y a-t-il un moyen d'éviter la répétition dans la fonction principale.

Xnor
la source
2

JavaScript (ES6), 73 72 octets

a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g)

Formaté et commenté

Insérer des zéros horizontalement et verticalement est une opération très similaire. L'idée ici est d'utiliser la même fonction g () pour les deux étapes.

a =>                            // a = input array
  (g = a =>                     // g = function that takes an array 'a',
    (                           //     builds a new array 'r' where
      r = [b],                  //     'b' is inserted at the beginning
      a.map(v => r.push(v, b)), //     and every two positions,
      b = 0,                    //     sets b = 0 for the next calls
      r                         //     and returns this new array
  ))(a, b = a[0].map(_ => 0))   // we first call 'g' on 'a' with b = row of zeros
  .map(g)                       // we then call 'g' on each row of the new array with b = 0

Cas de test

Arnauld
la source
2

Charbon de bois , 49 octets

A⪪θ;αA””βF⁺¹×²L§α⁰A⁺β⁰βA⁺β¶βFα«βA0δFιA⁺δ⁺κ⁰δ⁺䶻β

Essayez-le en ligne!

L'entrée est une simple chaîne séparant les lignes par un point-virgule.

Charlie
la source
1
Le charbon de bois moderne peut faire cela en 24 octets: ≔E⪪θ;⪫00⪫ι0θFθ⟦⭆ι0ι⟧⭆⊟θ0mais même en évitant StringMap, je pense toujours que cela peut être fait en 27 octets.
Neil
Oh, et quelques conseils généraux: il existe une variable prédéfinie pour la chaîne vide et vous pouvez créer une chaîne de zéros d'une longueur donnée à l'aide de Times ou de Mold.
Neil
2

C ++ 17 + Modules, 192 octets

Entrée sous forme de rangées de chaînes de cin , Sortie vers cout

import std.core;int main(){using namespace std;int i;auto&x=cout;string s;while(getline(cin,s)){for(int j=i=s.length()*2+1;j--;)x<<0;x<<'\n';for(auto c:s)x<<'0'<<c;x<<"0\n";}for(;i--;)x<<'0';}
Robert Andrzejuk
la source
2

C # , 146 octets


Les données

  • Input Int32[,] m La matrice à exploser
  • Sortie Int32[,] La matrice éclatée

Golfé

(int[,] m)=>{int X=m.GetLength(0),Y=m.GetLength(1),x,y;var n=new int[X*2+1,Y*2+1];for(x=0;x<X;x++)for(y=0;y<Y;y++)n[x*2+1,y*2+1]=m[x,y];return n;}

Ungolfed

( int[,] m ) => {
    int
        X = m.GetLength( 0 ),
        Y = m.GetLength( 1 ),
        x, y;

    var
        n = new int[ X * 2 + 1, Y * 2 + 1 ];

    for( x = 0; x < X; x++ )
        for( y = 0; y < Y; y++ )
            n[ x * 2 + 1, y * 2 + 1 ] = m[ x, y ];

    return n;
}

Ungolfed lisible

// Takes an matrix of Int32 objects
( int[,] m ) => {
    // To lessen the byte count, store the matrix size
    int
        X = m.GetLength( 0 ),
        Y = m.GetLength( 1 ),
        x, y;

    // Create the new matrix, with the new size
    var
        n = new int[ X * 2 + 1, Y * 2 + 1 ];

    // Cycle through the matrix, and fill the spots
    for( x = 0; x < X; x++ )
        for( y = 0; y < Y; y++ )
            n[ x * 2 + 1, y * 2 + 1 ] = m[ x, y ];

    // Return the exploded matrix
    return n;
}

Code complet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestBench {
    public static class Program {
        private static Func<Int32[,], Int32[,]> f = ( int[,] m ) => {
            int
                X = m.GetLength( 0 ),
                Y = m.GetLength( 1 ),
                x, y,

                a = X * 2 + 1,
                b = Y * 2 + 1;

            var
                n = new int[ a, b ];

            for( x = 0; x < X; x++ )
                for( y = 0; y < Y; y++ )
                    n[ a, b ] = m[ x, y ];

            return n;
        };

        public static Int32[,] Run( Int32[,] matrix ) {
            Int32[,]
                result = f( matrix );

            Console.WriteLine( "Input" );
            PrintMatrix( matrix );

            Console.WriteLine( "Output" );
            PrintMatrix( result );

            Console.WriteLine("\n\n");

            return result;
        }

        public static void RunTests() {
            Run( new int[,] { { 1 } } );
            Run( new int[,] { { 1, 3, 5 } } );
            Run( new int[,] { { 1 }, { 3 }, { 5 } } );
            Run( new int[,] { { 1, 3, 5 }, { 1, 3, 5 }, { 1, 3, 5 } } );
        }

        static void Main( string[] args ) {
            RunTests();

            Console.ReadLine();
        }

        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]" );
        }
    }
}

Communiqués

  • v1.0 - 146 bytes- Solution initiale.

Remarques

  • Aucun
auhmaan
la source
Vous n’avez pas besoin de la valeur (int[,] m)=>, m=>c’est suffisant si vous déclarez mêtre un int-tableau 2D int. En outre, vous pouvez changer ,x,pour ,x=0,et se débarrasser de x=0dans l'initialisation en boucle pour -1 octet. Et vous pouvez retirer y++de la boucle intérieure en changeant =m[x,y];d' =m[x,y++];un montant supplémentaire -1 octet. Mais +1 de moi, et si je crée un port de votre réponse, il est également plus court que ma réponse Java actuelle. :)
Kevin Cruijssen le
1

Dyalog APL, 24 octets

{{⍵↑⍨¯1-⍴⍵}⊃⍪/,/2 2∘↑¨⍵}

Toutes les améliorations sont les bienvenues et souhaitées!

Zacharý
la source
1

JavaScript (ES6), 80 78 octets

a=>[...a,...a,a[0]].map((b,i)=>[...b,...b,0].map((_,j)=>i&j&1&&a[i>>1][j>>1]))
Neil
la source
1

APL (Dyalog) , 22 octets

Invite la matrice, retourne la matrice jointe.

{⍺⍀⍵\a}/⍴∘0 1¨1+2×⍴a←⎕

Essayez-le en ligne!

a←⎕ invite pour la matrice et attribuer à un

 les dimensions d' un (lignes, colonnes)

 multiplier par deux

1+ ajoute un

⍴∘0 1¨ utiliser chacun de r Eshape (cyclique) les nombres zéro et un

{}/ Réduire en insérant la fonction anonyme suivante entre les deux nombres:

⍵\a développer * les colonnes de a en fonction du bon argument

⍺⍀a développer * les lignes de cela selon l'argument de gauche

* 0 insère une colonne / ligne de zéros, 1 insère une colonne / ligne de données d'origine

Adam
la source
1

Java 8, 183 166 162 129 octets

m->{int a=m.length,b=m[0].length,x=0,y,r[][]=new int[a*2+1][b*2+1];for(;x<a;x++)for(y=0;y<b;r[x*2+1][y*2+1]=m[x][y++]);return r;}

Entrée et sortie en tant que int[][].

-33 octets en créant un port de la réponse C # de @auhmaan .

Explication:

Essayez ici.

m->{                                // Method with 2D integer-array as parameter and return-type
  int a=m.length,                   //  Current height
      b=m[0].length,                //  Current width
      x=0,y,                        //  Two temp integers
      r[][]=new int[a*2+1][b*2+1];  //  New 2D integer-array with correct size
  for(;x<a;x++)                     //  Loop (1) over the height
    for(y=0;y<b;                    //   Inner loop (2) over the width
      r[x*2+1][y*2+1]=m[x][y++]     //    Fill the new array with the input digits
    );                              //   End of inner loop (2)
                                    //  End of loop (1) (implicit / single-line body)
  return r;                         //  Return result 2D integer-array
}                                   // End of method
Kevin Cruijssen
la source
0

05AB1E , 22 octets

"vy0ý0.ø})"©.V€Sø®.Vø»

Essayez-le en ligne!


Utilise réellement le même morceau de code 2x, je peux donc le stocker en tant que chaîne et utiliser Eval pour -10 octets.

Urne Magique De Pieuvre
la source