¡Hazme una cerca!

15

Desafío

Este es un desafío simple. Dados dos enteros positivos w y hcrear una cerca ASCII con un ancho wy una altura de h. La cerca debe construirse usando las siguientes reglas:

  • El +personaje representará una publicación.
  • El -personaje se usará para representar el ancho de la cerca.
  • El |será usado para representar la altura de la cerca.
  • Después de que se- hayan generado exactamente tres caracteres, se debe generar un +carácter después. Excluyendo las cuatro esquinas, cualquier otra vez que envíe un resultado no será válido. Puede seguir esta regla desde la izquierda o la derecha (ver ejemplos), pero debe ser coherente.+
  • Después de que| se hayan emitido exactamente dos caracteres, se debe generar un +carácter después. Excluyendo las cuatro esquinas, cualquier otra vez que envíe un resultado no será válido. Puede seguir esta regla desde la parte superior o inferior (ver ejemplos), pero debe ser coherente.+
  • Cada cerca tendrá exactamente cuatro esquinas, y cada esquina estará representada con un +.

En otras palabras: en cada tres -caracteres, debe generar un +. Y en cada dos |caracteres, debe generar un +.

Puede suponer que la cerca siempre será un rectángulo, y que ambos wy hnunca serán mayores 100o menores que1 . Se permite el espacio en blanco al final y / o al final.

Ejemplos / Casos de prueba

w = 1
h = 1

+-+ 
| |
+-+


w = 3
h = 2

+---+
|   |
|   |
+---+


w = 5
h = 7

+---+--+ or +--+---+
|      |    |      |
|      |    +      +
+      +    |      |
|      |    |      |
|      |    +      +
+      +    |      |
|      |    |      |
|      |    +      +
+      +    |      |
|      |    |      |
+---+--+    +--+---+

w = 10
h = 5

+---+---+---+-+  or +-+---+---+---+
|             |     |             |
|             |     +             +
+             +     |             |
|             |     |             |
|             |     +             +
+             +     |             |
|             |     |             |
+---+---+---+-+     +-+---+---+---+


w = 4
h = 4

+---+-+ or +-+---+
|     |    |     |
|     |    |     |
+     +    +     +
|     |    |     |
|     |    |     |
+---+-+    +-+---+

Reglas

Christian Dean
fuente
relacionado
vroomfondel
3
¿Estoy en lo cierto al entender que no puede haber dos +toques?
xnor
@xnor Sí, eso es correcto.
Christian Dean
3
Gran primer desafío, por cierto.
xnor
1
@LeakyNun Tu derecho. Ese es un caso que no tenía en mente al hacer mis reglas. Agregué una regla para indicar por qué +-+-+-+-+-+no es válido. Perdón por la confusion.
Christian Dean

Respuestas:

9

C, 131 bytes

#define L for(i=0,j=w;j;)putchar(i++%4?--j,45:43);puts("+")
f(w,h,i,j,c){L;for(j=1;h;printf("%c%*c\n",c,i,c))c=j++%3?--h,124:43;L;}

Pruébalo en línea!

Explicación:

// The first and the last line are always similar, so let's use a macro
// to avoid code duplication.
#define L

// Let's initialize 'i' and 'j'. 'i' will be used to keep track of which
// character ('+' or '-') we should print, whereas 'j' starts from the
// input width and the loop terminates when 'j' reaches zero.
for(i=0,j=w;j;)

// We post-increment 'i' and take a modulo 4 of its previous value.
// If i%4 == 0, we print '+' (ASCII 43), otherwise we decrement 'j'
// and print '-' (ASCII 45).
putchar(i++%4?--j,45:43);

// After the loop we print one more '+' and newline.
puts("+")

// The function declaration which takes the two input parameters, and
// also declares three integer variables. These three variables could
// also be declared as global variables with the same bytecount.
f(w,h,i,j,c)

// The start of the function body. We use the macro 'L' to print the 
// first line along with a newline.
{L;

// This loop prints all the lines between the first and the last. 'j'
// keeps track of when we should output a '+' instead of a '|'. 'h',
// which is the input parameter for height, serves as a terminator
// for the loop as it reaches zero.
for(j=1;h;<stuff missing from here>)

// We post-increment 'j' and check if its previous value is divisible
// by three, and if it isn't, we decrement 'h' and assign 124 (ASCII
// value for '|') to 'c'. Otherwise we assign '+' (ASCII 43) to 'c'.
c=j++%3?--h,124:43;

// The following is inside the 'increment' part of the 'for' loop.
// We print the character corresponding to the value of 'c', then
// the same character again, but padded with i-1  spaces before it 
// ('i' hasn't been touched since the first loop, so it still stores
// the length of the first line), then a newline.
printf("%c%*c\n",c,i,c)

// Lastly we print the first line again using the same macro 'L'.
L;}
Steadybox
fuente
5

Python 3 , 140 137 128 119 106 105 bytes

def f(w,h):a=~-w//3-~w;b=("+---"*w)[:a]+'+';print(b,*[i+' '*~-a+i for i in"||+"*h][:h+~-h//2],b,sep='\n')

Pruébalo en línea!

GarethPW
fuente
2
Ahora es más largo pero el problema se ha solucionado.
GarethPW
1
Puede guardar un byte eliminando el espacio entre iny [w+1+(w-1)//3]]en la última parte.
Christian Dean
1
Bienvenido a PPCG! También puedes eliminar el espacio '\n') for. Además, puede cambiar (w-1)a lo ~-wque le permite eliminar los paréntesis, ya que los operadores unarios tienen mayor prioridad que los binarios. Lo mismo para (h-1)-> ~-hy (a-1)-> ~-a. Pruébelo en línea - 128 bytes
musicman523
1
Además, dado que toda su salida está impresa, def f(w,h)tiene la misma longitud que lambda w,h, pero le permite usar varias líneas si eso le ayuda a seguir
jugando a
1
a=~-w//3-~w;guardar 1 byte
Felipe Nardi Batista
4

Mathematica, 165 bytes

v=Column;d[w_,y_,m_,n_]:=Table[If[Mod[i,y]==0&&i!=w,m,n],{i,w}];(a="+"<>d[#,3,"-+","-"]<>"+";b=v@d[#2,2,"|\n+","|"];v[{a,Row[{b,""<>Table[" ",#+Floor[#/3]],b}],a}])&
J42161217
fuente
4

Pipa , 38 bytes

37 bytes de código, +1 para -nbandera.

Ph:'-Xa<>3JW'+PsX#h-2WR:'|Xb<>2J'+^xh

Toma ancho y alto como argumentos de línea de comandos. Pruébalo en línea!

Explicación

                         a,b are cmdline args; s is space; x is empty string (implicit)
Ph:'-Xa<>3JW'+
   '-Xa                  String of hyphens of length a
       <>3               grouped into substrings of (maximum) length 3
          JW'+           Join on +, also wrapping the result in +
 h:                      Assign that string to h (mnemonic: "header")
P                        and print it (with newline)

PsX#h-2WR:'|Xb<>2J'+^xh
          '|Xb           String of pipes of length b
              <>2        grouped into substrings of (maximum) length 2
                 J'+     joined on +
                    ^x   and split on empty string (i.e. converted to list of chars)
 sX#h-2                  String of len(h)-2 spaces
       WR:               Wrap the spaces with the list of chars
                         Note 1: WR operates itemwise on lists, so the result is a list,
                          each item of which consists of the spaces wrapped in an item
                          from the list of chars
                         Note 2: the : compute-and-assign meta-operator is here abused
                          to give WR: lower precedence than J and ^ and avoid parentheses
P                        Print that list, newline-separated (-n flag)
                      h  Autoprint the header a second time as the footer
DLosc
fuente
4

Carbón, 47 45 40 bytes

F⁴«¿﹪ι³FIη↓⁺×+¬﹪κ²|FIθ⁺×+¬﹪κ³-P+¿⁼ι¹J⁰¦⁰

Explicación: funciona dibujando los -s / |s de cada lado por turno, insertando +s cuando sea necesario y luego terminando con a +. Después de dibujar los lados superior y derecho, salta de nuevo al inicio para dibujarlos en orden inverso, dibujando efectivamente los lados izquierdo y inferior. No sé si se permite la simetría rotacional, pero si es así, entonces para 27 25 bytes:

F⁴«FI⎇﹪ι²ηθ⁺×+¬﹪κ⁻³﹪ι²-⟲T

Lleve la idea anterior al extremo dibujando el lado superior, girando hacia la izquierda, dibujando el lado derecho, girando nuevamente y luego repitiendo para dibujar los lados inferior e izquierdo al revés.

Neil
fuente
1
@LeakyNun La última vez que vencí a Pyth fue para Doblar algunos diamantes, e incluso entonces fue solo más corto.
Neil
4

JavaScript (ES6), 133 132 bytes

w=>h=>(a="-".repeat(w).replace(/--?-?/g,"+$&")+`+`)+(`
|`.padEnd(a.length)+`|`).repeat(h).replace(/(\|( +)\|\n)\1/g,`$&+$2+
`)+`
`+a

Toma de entrada en la sintaxis currificación: f(width)(height).

Fragmento de prueba

f=
w=>h=>(a="-".repeat(w).replace(/--?-?/g,"+$&")+`+`)+(`
|`.padEnd(a.length)+`|`).repeat(h).replace(/(\|( +)\|\n)\1/g,`$&+$2+
`)+`
`+a
O.innerHTML=f(W.value=5)(H.value=10)
<div oninput="O.innerHTML=f(+W.value)(+H.value)">
W <input id=W type=number min=1> H <input id=H type=number min=1>
</div>
<pre id=O>

Justin Mariner
fuente
2

Java (OpenJDK 8) , 178 177 bytes

w->h->{int i=0;String t="",m,r;for(;i<w;)t+=i++%3<1?"+-":"-";r=t+="+\n";m=t.format("|%"+(t.length()-3)+"s|\n","");for(i=0;i<h;)r+=i++%2<1&i>1?m.replace("|","+")+m:m;return r+t;}

Pruébalo en línea!

-1 byte gracias a @KevinCruijssen

Olivier Grégoire
fuente
Puede guardar un byte al cursar los parámetros: w->h-> Pruébelo aquí.
Kevin Cruijssen
Sí, constantemente me olvido del curry ... No es algo que me parezca natural: s
Olivier Grégoire
1

Carbón , 47 45 37 bytes

A…+---÷⁺²×⁴N³αA…+||÷⁺¹×³N²βPα↓βα+↖↑⮌β

Pruébalo en línea!

  • 2 bytes guardados después de jugar con los signos en la creación de la cadena.
  • 8 bytes guardados gracias a Neil, quien ideó una forma mucho más simple de calcular la longitud de las cercas.

Un enfoque diferente al de @ Neil : primero creo las cadenas αyβ contengo los caracteres en los bordes horizontal y vertical, utilizando el Rangeoperador que crea una repetición de una cadena hasta que se alcanza una longitud determinada. Luego los imprimo en el orden correcto:

  • Imprima α sin mover el cursor.
  • Imprima β hacia abajo.
  • Imprimir α.
  • Imprime un "+".
  • Mueve el cursor hacia arriba y hacia la izquierda.
  • Imprima β hacia arriba, invertido.

Enlace a una versión detallada .

Charlie
fuente
1
Gracias por recordarme Range, ¡eso ahorra 3 bytes en mi segundo enfoque!
Neil
@Neil, eso es bueno porque te acabo de superar y no puedo creerlo. :-)
Charlie
1
Mejor aún, me las arreglé para optimizar sus expresiones, el ahorro de 8 bytes: A…+---÷⁺²×⁴N³αA…+||÷⁺¹×³N²βPα↓βα+↖↑⮌β.
Neil
@Neil Wow. Tal optimización. Muy carbón.
Charlie
0

05AB1E , 58 bytes

D3/ó+DU'-×'+.ø©'|DXú«²D2/ó+.D®»'-4×D'+3ǝ.:¶¡ø'|3×D'+2ǝ.:ø»

Pruébalo en línea!

Más duro en 05AB1E de lo que pensaba.

Urna de pulpo mágico
fuente