Doublez quelques diamants


25

Problème

Étant donné un entier positif noùn < 100

Sortez un motif de diamant comme suit:

Contribution n=1

/\/\
\/\/

Entrée n=2:

 /\      /\
//\\/\/\//\\
\\//\/\/\\//
 \/      \/

Entrée n=3:

  /\                /\
 //\\  /\      /\  //\\
///\\\//\\/\/\//\\///\\\
\\\///\\//\/\/\\//\\\///
 \\//  \/      \/  \\//
  \/                \/

Entrée n=4:

   /\                              /\
  //\\    /\                /\    //\\
 ///\\\  //\\  /\      /\  //\\  ///\\\
////\\\\///\\\//\\/\/\//\\///\\\////\\\\
\\\\////\\\///\\//\/\/\\//\\\///\\\\////
 \\\///  \\//  \/      \/  \\//  \\\///
  \\//    \/                \/    \\//
   \/                              \/

Etc.

Règles

  • Programme et fonction autorisés.
  • Espace de fin autorisé.
  • Espaces en tête sur les lignes sans /ou \autorisés.
  • Traitements et sauts de ligne autorisés.
  • Code le plus court en octets gagnant

C'est probablement assez lié


2
@carusocomputing Vous hallucinez en ce moment ...
— Erik the Outgolfer


1
@dzaima dans le bac à sable avec!
— Magic Octopus Urn

1
@carusocomputing Bien sûr, mais je dois d'abord comprendre pourquoi et comment cela s'est produit: p
— dzaima

Réponses:


12

SOGL V0.12 , 24 octets

ā.∫ā;∫ \*+}ø┼↔±╬¡;øΚ┼}╬³

Essayez-le ici!

Explication:

ā                         push an empty array (the main canvas)
 .∫                  }    iterate over the input, pushing 1-indexed iteration
   ā;                       push an empty array below the iteration
     ∫    }                 iterate over the iteration counter
       \*                     push current iteration amount of slashes
         +                    append those to the 2nd array
           ø┼               append nothing (so it'd space the array to a square)
             ↔±             reverse horizontally (swapping slashes)
               έ           quad-palindromize with 0 overlap and swapping characters as required
                 ;          get the canvas ontop
                  øΚ        prepend to it an empty line (so the now bigger romb would be one up)
                    ┼       append horizontally the canvas to the current romb
                      ╬³  palindromize horizontally with no overlap and swapping characters

2
Wow, ╬c'est une commande malade.
— Magic Octopus Urn

@carusocomputing Un ajout assez récent aussi. dossier pertinent . Reste à savoir quoi faire avec les 190 caractères restants
— dzaima

Wow, vous avez donc 190 commandes gratuites dans SOGOL et vous pouvez déjà jouer au golf efficacement?
— Magic Octopus Urn

1
@carusocomputing Je voulais dire 190 commandes gratuites pour ╬lol
— dzaima

2
@carusocomputing Mais comme fait amusant, (environ) 90/256 caractères ne sont pas implémentés et 61/256 n'ont aucune documentation
— dzaima

7

Fusain , 30 27 octets

F⁺¹N«Fι«F⁴«↙⁻ικ↑⟲T»←»Mι←»‖M

Essayez-le en ligne! Le lien est vers la version détaillée du code. Explication: les primitives de dessin du fusain ne peuvent pas tout à fait dessiner un diamant, car les mouvements diagonaux restent sur des carrés de la même parité. Modifier: La nouvelle solution consiste à dessiner un côté d'un diamant, puis à faire pivoter la toile entière prête à dessiner le côté suivant, permettant à un diamant d'être dessiné en boucle. Cette boucle est ensuite contenue dans une boucle pour dessiner tous les diamants intérieurs pour chaque diamant. La boucle la plus à l'extérieur attire tous les diamants les uns à côté des autres. Enfin, l'image est reflétée.

Notez que Charcoal a depuis été étendu et qu'un autre octet pourrait être enregistré en utilisant Increment.


Où sont les mouvements de 0,5 caractère lorsque vous en avez besoin :(
— CalculatorFeline

6

APL (Dyalog) , 70 69 66 octets

B←{'/\ '['\/'⍳⍺⍺⍵]}
C←⊢,⌽B
C(⊢⍪⊖B)⊃,/{C⊖A↑⊖' /'[⍵≤∘.+⍨⍳⍵+1]}¨⌽⍳A←⎕

Essayez-le en ligne!

Suppose ⎕IO←0, qui est standard sur de nombreux systèmes, donc le programme est indexé 0.

Il s'agit d'un tradfn qui accepte les données via STDIN.

Explication

(légèrement dépassé)

Notez qu'il ⍺s'agit de l'argument gauche, de ⍵l'argument droit et de ⍺⍺l'opérateur gauche.

Best une fonction qui aide à refléter les diamants. Il prend la chaîne comme argument de droite et la fonction inverse comme gauche (tout Bcomme un opérateur).

B←{'/\ '['\/'⍳⍺⍺⍵]}
              ⍺⍺⍵            Apply ⍺⍺ on ⍵
         '\/'⍳               Find the index of the reflected string in '\/' (if the character is not found in `'\/'`, then return an index out of the bounds of the string, ie `2` if the character is a space)
   '/\ '[        ]           Use these indexes on '/\ ' to reflect the '/\' characters

Et maintenant, nous allons à la partie principale du programme.

A←⎕              Assign the input to variable A
⍳                Create a range 0 .. A-1
⌽                Reverse it so that it becomes A-1 .. 0
¨                For each element do (the right argument is the element):
 ⍳⍵+1             Create a range 0 .. ⍵
 ∘.+⍨             Create an addition table using the range to result in a matrix like so:
                   0+0 0+1 0+2 .. 0+⍵
                   1+0 1+1 1+2 .. 1+⍵
                   2+0 2+1 2+2 .. 2+⍵
                   ...
                   ⍵+0 ⍵+1 ⍵+2 .. ⍵+⍵
 ⍵≤              The elements of the matrix that are greater than or equal to the ⍵,
                 this creates a triangle matrix that looks like this:
                   0 0 .. 0 1
                   0 0 .. 1 1
                   ..
                   1 1 .. 1 1
 ' /'[...]       Index it in ' /' to get a character matrix
                 (ie replace 0s with spaces and 1s with '/'s)
 ⊖               Flip this vertically
 A↑              Pad the top spaces

Cela est nécessaire pour garantir que tous les triangles créés pour chaque élément de la plage ⌽⍳Aont la même hauteur afin de pouvoir ensuite être concaténés les uns avec les autres.

 ⊖               Flip the matrix vertically again to go back to the original state
 (⊢,  )          Concatenate it with
    ⌽B           itself, but flipped horizontally
,/              Concatenate all triangles formed by the range operator
⊃               The resulting matrix is nested, so this operator "un-nests" it

La partie supérieure gauche du motif est maintenant terminée. Il ne reste plus qu'à le retourner verticalement puis horizontalement.

(⊢⍪⊖B)          Concatenate the resulting matrix with itself but flipped vertically
                (the vertically flipped matrix is concatenated below of the original matrix)
                Now the left part of the pattern is complete
(⊢,⌽B)         Concatenate the resulting matrix with itself flipped horizontally

Et c'est tout! La sortie est une matrice de caractères avec /\s et remplie d'espaces.


6

05AB1E , 47 43 41 35 34 33 32 octets

'/×ηηvy∞.C.Bø€∞¹NαGð.ø}})øíJ.B»∞

Essayez-le en ligne!

(-4 octets grâce à @Emigna qui a suggéré 3 améliorations)


Cette explication concernait la version précédente, il y a eu quelques itérations depuis lors.

>                                          # [2]
 '/×                                       # ['//']
    η                                      # ['/','//']
     €η                                    # [['/'], ['/', '//']]
       vy                    }             # {For each element...}
         ∞                                 # Mirror horizontally.
          ¶¡                               # Split mirror on newlines.
            N£                             # Shave each diamond down a layer.
              .C                           # Horizontal center.
                .B                         # Pad for the transpose.
                  ø                        # Transpose.
                   €∞                      # Mirror each (vertically).
                     ¹NαFð.ø}              # Pad each list for transpose (verticaly).
                              )            # Wrap back to list...
                               €.B         # Pad each horizontally.
                                  ¦        # Remove the random numbers?
                                   ø       # Back to horizontal...
                                    €R     # Reverse to get correct order.
                                      J    # Join, no spaces.
                                       »   # Join newlines.
                                        ∞  # Final horizontal mirror.

Il y a des espaces entre vos diamants
— LiefdeWen

@LiefdeWen est- ce correct? Avec des sauts de ligne finaux et précédents?
— Magic Octopus Urn

Vous pouvez utiliser des préfixes ηau lieu de suffixes car ils sont identiques pour cette chaîne.
— Emigna

N£est le même ¨qu'ici et l' €Rest í.
— Emigna

@Emigna J'ai joué au golf en partie, mais merci! Vous allez essayer une réponse de 33 octets 100% différente: P?
— Magic Octopus Urn

5

CJam , 65 63 octets

q~_,:)_W%\+f{_2*S*a@2$-*\_,f{)'/*\Se[_W%'/'\er+}_W%Wf%+1$++}zN*

Essayez-le en ligne!

Explication

Dans cette explication, je ferai référence au numéro d'entrée comme n.

q~        e# Read and eval the input (push n to the stack).
_,        e# Copy it an get the range [0 .. n-1].
:)        e# Increment each element to get [1 .. n].
_W%       e# Copy it and reverse it.
\+        e# Prepend the reverse to the original range, resulting in [n n-1 .. 1 1 .. n-1 n].
f{        e# Map over each number x in the range using n as an extra parameter:
 _2*S*a   e#  Push a string containing n*2 spaces, and wrap it in an array.
 @2$-     e#  Push n-x.
 *        e#  Repeat the space string from before n-x times.
 \        e#  Bring x back to the top.
 _,       e#  Copy it and get the range [0 .. x-1].
 f{       e#  Map over each number y in this range, using x as an extra parameter:
  )       e#   Increment y.
  '/*     e#   Repeat '/' y times.
  \Se[    e#   Pad the resulting string to length x by adding spaces to the left.
  _W%     e#   Copy the result and reverse it.
  '/'\er  e#   Replace '/' with '\' in that.
  +       e#   Concatenate to the other string. This forms one row of one diamond.
 }        e#  (end map, now we have the top half of a diamond of size x)
 _W%      e#  Copy the half-diamond and reverse it.
 Wf%      e#  Reverse each row.
 +        e#  Concatenate to the top half. Now we have a full diamond of size x.
 1$++     e#  Put the spaces from before at the beginning and end. This is to pad the top
          e#  and bottom of the smaller diamonds.
}         e# (end map)
z         e# Transpose.
N*        e# Join with newlines. Implicit output.

Par curiosité, pourquoi e#dans l'explication?
— Magic Octopus Urn

1
@carusocomputing C'est un commentaire, vous pouvez donc exécuter l'explication elle-même. Pas vraiment nécessaire mais ¯ \ _ (ツ) _ / ¯
— Business Cat

1
@carusocomputing #n'est pas un commentaire dans CJam - sourceforge.net/p/cjam/wiki/Basic%20operators/#number-sign - même si c'est dans de nombreuses autres langues. Étant donné que CJam est un langage de golf, toutes les commandes à un caractère sont utilisées pour des fonctionnalités adaptées au golf. Les commentaires ne sont utiles que pour le code non golfé, il utilise donc une séquence de 2 caractères, libérant ainsi la séquence d'un caractère pour autre chose
— Joe

3

Python 2 , 152 147 143 140 140 octets

-1 octet grâce à musicman523

n=input()
r=range(n)
r+=r[::-1]
for x,i in enumerate(r):a,b='/\\\/'[i<x::2];s=' '*(n+~i);print''.join((s+a*n)[:n-j]+(b*-~i+s)[j:]for j in r)

Essayez-le en ligne!

Cela fonctionne en coupant les colonnes intérieures du plus grand diamant pour en faire des plus petites, en utilisant [0,..,n,n,..,0]pour contrôler la quantité de colonnes à supprimer.


Vous pouvez obtenir un octet bon marché en changeant r=r+enr+=
— musicman523

3

Pyth, 35 32 octets

j.tsm+Jm.[yQS*"\/"k\ Sd_M_Js__BS

Suite de tests

Fait pour voir comment mes approches et celles de @ LeakyNun différeraient.


3

Dyalog APL, 46

{⊃,/⍵∘{'/ \'[2+((-⍪⊖)⌽,-)(-⍺)↑∘.≥⍨⍳⍵]}¨(⌽,⊢)⍳⍵}

Bienvenue chez PPCG et belle première réponse! Vu que c'est un DFN, j'ai ajouté le {}à votre réponse car ils doivent être inclus.
— Kritixi Lithos


En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.