El zigzag siempre amplificador


24

Escriba un programa o función que tome un entero positivo N y genere los primeros N números de este patrón de zigzag amplificador, usando solo las líneas necesarias:

                                         26
                                       25  27                                      .
         10                          24      28                                  .
        9  11                      23          29                              .
 2     8     12                  22              30                          44
1 3   7        13              21                  31                      43
   4 6           14          20                      32                  42
    5              15      19                          33              41
                     16  18                              34          40
                       17                                  35      39
                                                             36  38
                                                               37

Entonces, si N es 1la salida es

1

Si N es 2, la salida es

 2
1

Si N es 3la salida es

 2
1 3

Si N es 4la salida es

 2
1 3
   4

Si N es 10la salida es

         10
        9
 2     8
1 3   7
   4 6
    5

Si N es 19la salida es

         10
        9  11
 2     8     12
1 3   7        13
   4 6           14
    5              15      19
                     16  18
                       17

y así.

Notas

  • Cada pico o valle del zigzag alcanza su punto una línea más lejos de la línea con el 1mismo que el pico o valle anterior.

  • N no se limita a 44. El zigzag crece en el mismo patrón y se debe admitir N más grande.

  • Los números con varios dígitos solo deben "tocarse" en sus esquinas, como se muestra. Asegúrese de que esto funcione cuando N sea 100y superior.

  • No debe haber líneas vacías (o solo espacio) en la salida, excepto una nueva línea final opcional.

  • Cualquier línea puede tener cualquier cantidad de espacios finales.

Tanteo

El código más corto en bytes gana. Tiebreaker es la respuesta anterior.


¿Cuál es el máximo N posible?
— Julie Pelletier

@JuliePelletier En teoría no hay ninguno, pero puede suponer que será inferior a 2 ^ 16.
— Aficiones de Calvin

¿Se permite el uso de caracteres de control o estamos limitados a espacios de dígitos y saltos de línea?
— Dennis

2
@ Dennis Digamos que no. Solo dígitos / espacios / líneas nuevas.
— Aficiones de Calvin

1
Alguien debería enviar eso al OEIS en ese formato como una broma.
— DanTheMan

Respuestas:


10

Jalea , 41 37 29 bytes

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷

Pruébalo en línea!

Cómo funciona

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷  Main link. Argument: n (integer)

R                              Range; yield [1, ..., n].
 D                             Decimal; yield A =: [[1], ..., [1, 0], ...].
  µ                            Begin a new, monadic chain. Argument: A
   Ḍ                           Undecimal; convert back to falt range.
    ’                          Decrement to yield [0, ..., n-1].
     ½Ċ                        Take the square root and round up (ceil).
       -*                      Elevate -1 to each rounded square root.
         _\                    Cumulatively reduce by subtraction.
                               This yields [1, 2, 1, 0, -1, 0, ...], i.e., the
                               vertical positions of the digits in A.
             L€                Compute the length of each list in A.
           x                   Repeat the nth position l times, where l is the
                               nth length.
            ©                  Copy the result to the register.
               Ṣ               Sort.
                .ị             At-index 0.5; yield the last and first element,
                               which correspond to the highest and lowest position.
                  ạ€®          Take the absolute difference of each position in the
                               register and the extrema.
                               This yields the number of spaces above and below
                               the integers in r as a list of pairs.
                     ⁶ẋ        Replace each difference with that many spaces.
                         F     Flatten the list A.
                       j"      Join the nth pair of strings of spacing, separating
                               by the nth digit in flat A.
                          Z    Zip/transpose the result.
                           j⁷  Join, separating by linefeeds.

2
¿Por qué no hacer una función en su idioma (Jelly) que pueda hacer eso en unos pocos caracteres mientras lo hace?
— Julie Pelletier

19
@JuliePelletier El arte de escribir un buen lenguaje de golf consiste en crear un conjunto de instrucciones (y una semántica de sintaxis / lenguaje) que le permitan escribir soluciones cortas para tantas tareas diferentes como sea posible, no se trata de poder resolver una muy específica y desafío artificial en un solo byte. Un buen lenguaje de golf tiende a ser realmente muy poderoso y expresivo, en lugar de ser una colección de elementos incorporados que son inútiles para cualquier cosa que no sea la función específica que calculan.
— Martin Ender

@JuliePelletier Y también iría en contra de las reglas de PPCG SE
— Bálint

8

PHP, 211 177 164 163 bytes

Predecir los picos con $ny aumentar la matriz dinámicamente en cualquier dirección, utilizando ($x, $y)el cursor de salida.

Los números están alineados str_pad()y el resultado final es el implode()de esa matriz de cadenas ( $g).

for($x=0,$d=-1,$h=$n=2,$y=$a=1;$a<=$argv[1];$y+=$d){$g[$y]=str_pad($g[$y],$x).$a;$x+=strlen($a);if($a++==$n){$h+=2;$n+=$h-1;$d*=-1;}}ksort($g);echo implode(~õ,$g);

¡Pruébalo en línea!

Actualización: eliminó 34 bytes al deshacerse del array_pad () innecesario. Actualización2: siguió los consejos de @ insertusernamehere para acortarlo un poco más. Actualización 3: siguió el consejo de @ Lynn de guardar un byte más con ~ õ que impone el uso del juego de caracteres LATIN-1. (no disponible en el emulador PHP en línea, por lo que no está incluido allí)


Solo una pregunta sobre este código. ¿No tiene que inicializar la matriz $ g antes de acceder a un elemento específico? Quiero decir, ¿darle una longitud o insertar las filas? No tengo mucha experiencia con PHP, así que me parece raro ... Gracias.
— Yotam Salmon

No. Una vez que defina $arr = [];, puede consultar $arr[anything]. Algunos casos generarán avisos, pero estos se ignoran aquí. Tenga en cuenta que leer cosas como esta probablemente no lo ayudará mucho a aprender un idioma. Sin embargo, su comentario me hizo darme cuenta de que podría acortarlo, ya que inicialmente pensé que necesitaría rellenar mi matriz, pero no lo hago. :)
— Julie Pelletier

Jaja contento de ayudar;) Me acabo de dar cuenta de que en PHP una matriz y un diccionario se inicializan de la misma manera y son completamente iguales cuando se mira la sintaxis (¡¿Por qué, PHP ?!)
— Yotam Salmon

Algunas mejoras menores - 164 bytes : for($x=0,$d=-1,$h=$n=2,$y=$a=1;$a<=$argv[1];$y+=$d){$g[$y]=str_pad($g[$y],$x).$a;$x+=strlen($a);if($a++==$n){$h+=2;$n+=$h-1;$d*=-1;}}ksort($g);echo implode("⏎",$g);(Reemplace ⏎ con una nueva línea real.)
— insertusernamehere aquí

Creo que si configura su codificación correcta (Latin-1, no UTF-8), ~ões una alternativa de dos bytes a "⏎".
— Lynn

8

Pyth, 60 53 52 46 42 39 38 36 34 32 31 bytes

39: Ahora está a la par con la versión de Jelly corregida por errores , ¡y he superado la versión competitiva de Dennis!

38: ¡He superado a Dennis!

36: ¡He superado a Dennis nuevamente!

34: ¡Incluso más bajo que su versión corregida!

31: 32 -> 31 gracias a Dennis.

J1K.u+N=J_WsI@Y2JtQZjsM.t.e ++ *] * dl`hkabhSK`hk *] * dl`hkabeSKKd 
J1K.u+N=J_WsI@Y2JtQZjsM.t.eX *] * dl`hkhaeSKhSKabhSKhkKd 
J1K.u + N=J_WsI@Y2JtQZ=-RhSKKjsM.t.eX *] * dl`hkheSKbhkKd 
J1K.u+N=J_WsI@Y2JtQQj-#dsMC.eX *] * dl`hkheSKbhkK 
J1j- # dsMC.eX * # dsMC.eX * + Qbhkm = + Z = J_WsI @ td2J 
J1j- # dsMCmX *] *; l`hdyQ + Q = + Z = J_WsI @ td2Jhd 
J1j- # dsMCmX *] *; l`hdyQ + Q = + Z = J_WsI @ td2Jh 
J1j - # dsMCmX *] *; l`hdyQ + Q = + Z = @ _ BJsI @ td2h 
j- # dsMCmX *] *; l`hdyQ + Q = + Zsty% s @ td2 2h 
j- # dsMCmX *] *; l `hdyQ + Q = + Z @ _B1.E @ d2h 
JQj- # dsMCmX *] *; l`hdyQ = + J @ _B1.E @ d2h 
JyQj- # dsMCmX *] *; l`hdJ = + Q @ _B1. E @ d2h 
j- # dsMCmX *] *; l`hdyQ = + Q @ _B1.E @ d2h
j- # dsMCmX *] *; l`hdyQ=+Q^_1.E@d2h

Pruébalo en línea!

Cómo funciona

j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2h      input: Q
j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2hdQ    implicit filling arguments

       m                        Q    for each number d from 0 to Q-1:
                           @d2           yield the square root of d.
                         .E              yield its ceiling.
                      ^_1                raise -1 to that power. this
                                         yields the desired direction.
                   =+Q                   increment Q by this amount.

               hd                        yield d+1.
              `                          yield its string representation.
             l                           yield its length.
           *;                            repeat " " for that number of times
          ]                              yield a list containing the string above.
         *       yQ                      repeat the list for Q*2 times.
                                         the Q has changed, but Q*2 is
                                         an overshoot that is high
                                         enough, so we don't have to
                                         worry about it.

        X                                in that list, replace the
                                         element with index being the
                                         number generated above
                              hd         with d+1.

      C                              transpose the resulting array.
    sM                               flatten each element.
 -#d                                 remove lines containing only spaces.
                                     (filter on truthiness of set difference with space)
j                                    join by newlines.

2
" 39: a la par con Jelly "; " 38: ¡He superado a Dennis! " Durante unas horas lo hiciste, pero parece que a @Dennis no le gusta que le peguen en el golf de código: Jelly 37 bytes ;)
— Kevin Cruijssen

1
@KevinCruijssen Hecho.
— Leaky Nun

¡Agradable! xD M̶a̶y̶b̶e̶ Tengo una imaginación salvaje, pero ahora imagino que has mirado y mirado con frustración durante horas hasta que finalmente encontraste esta solución más corta, y ahora @Dennis se despertará casualmente y acortará su código nuevamente. (Jk, ¡espero que te quedes debajo de Dennis!)
— Kevin Cruijssen

@KevinCruijssen Tada! Ahora es más bajo que la versión con corrección de errores.
— Leaky Nun

5

MATLAB, 148 bytes

n=input('');k=fix(n^.5);m=0;w=1;d=-1;for l=1:n;s=num2str(l);m(k+1,w:w+nnz(s)-1)=s;w=w+nnz(s);k=k+d;d=d*(-1)^(l^.5==fix(l^.5));end;[m(any(m,2),:),'']

Tenga en cuenta que faltan espacios en Octave, ya que MATLAB imprime el carácter indexado 0como un espacio, mientras que octave simplemente omite ese carácter.

Explicación:

n=input('');
k=fix(n^.5);                    %caculate starting height
m=0;w=1;d=-1;                   %initialize counters and output matrix
for l=1:n;
    s=num2str(l);
    m(k+1,w:w+nnz(s)-1)=s;      %insert current index as a string
    w=w+nnz(s);                 %current horizontal position
    k=k+d;                      %current vertical position
    d=d*(-1)^(l^.5==fix(l^.5)); %if we reached a square number, change direction
end
[m(any(m,2),:),'']              %delete all zero rows

3

Haskell, 144 142 bytes

g n|k<-take n$scanl(+)0$[1..]>>= \x->(-1)^x<$[2..2*x]=unlines[[1..n]>>= \x->show x#(k!!(x-1)==y)|y<-[minimum k..maximum k]]
s#g|g=s|1<2=' '<$s

Ejemplo de uso:

*Main> putStr $ g 19
         10                  
        9  11                
 2     8     12              
1 3   7        13            
   4 6           14          
    5              15      19
                     16  18  
                       17    

Cómo funciona:

s#g|g=s|1<2=' '<$s              -- # is a helper function that expects a string s
                                -- and a boolean g. It returns s if g is True, else
                                -- as many spaces as there a characters in s 

k<-take n$                      -- bind k to the first n elements of
 [1..]>>= \x->(-1)^x<$[2..2*x]  -- 2*x-1 copies of (-1)^x for each x in [1,2,3,...]
                                -- i.e. [-1, 1,1,1, -1,-1,-1,-1,-1, 1,1,1,1,1,1,1..]
 scanl(+)0                      -- build partial sums, starting with 0
                                -- i.e. [0,-1,0,1,2,1,0,-1,-2,-3,-2,-1...]
                                -- -> k is the list of y coordinates for the
                                --    numbers 1,2,3,...

 [  |y<-[minimum k..maximum k]] -- for all y coordinates in k 
      \x->show x#(k!!(x-1)==y)  -- map the # function
  [1..n]>>=                     -- over [1..n] (the x coordinates)
                                -- where # is called with
                                --  s -> a string representation of x 
                                --  g -> True if k at index x equals the current y
unlines                         -- join with newlines

Editar: ¡Gracias @Lynn por dos bytes!


2

JavaScript (ES6), 213 bytes

with(Math)n=>(a=[...Array(n)].map((_,i)=>n-=1+sqrt(--i)&1||-1).map((e,_,a)=>e-min(...a))).map((e,i)=>r[e][i]=++i,r=[...Array(1+max(...a))].map(_=>a.map((_,i)=>` `.repeat(1+log10(++i)))))&&r.map(a=>a.join``).join`\n`

Donde \nrepresenta un carácter de nueva línea literal. Explicación:

with(Math)                          Bring functions into scope
 n=>                                Accepts one parameter
  (a=                               Intermediate result variable
   [...Array(n)].map(               For each number 0..n-1
    (_,i)=>n-=                      Accumulate index for each number
     1+sqrt(--i)&1||-1              Calculate the direction
    ).map((e,_,a)=>e-min(...a))     Scale the smallest index to zero
  ).map((e,i)=>r[e][i]=++i,         Overwrite the padding with 1..n
   r=[...Array(1+max(...a))].map(   Calculate number of lines
    _=>a.map((_,i)=>                For each number 1..n
     ` `.repeat(1+log10(++i)))))    Calculate the padding needed
  &&r.map(a=>a.join``).join`\n`     Join everything together

Para acortarlo, pow(-1,ceil(sqrt(i)))lo reescribo porque, sqrt(i-1)&1||-1sin embargo, esto no funciona, i=0así que para solucionarlo, agrego 1, pero luego voltea el signo del resultado, por lo que termino con n-=.


heyyy tienes una insignia de oro! ¡buen trabajo! y santo fuma, casi tienes tanta reputación como yo. ¡sigue así!
— Conor O'Brien

1
@ CᴏɴᴏʀO'Bʀɪᴇɴ Eso es "simplemente" la insignia de Fanatic. ¡Aparentemente estoy muy cerca de obtener la insignia de etiqueta de golf con código de oro!
— Neil

doble santo fuma Necesito ponerme en movimiento XD
— Conor O'Brien

1

Python 2, 137 bytes

l={}
i=x=y=n=v=0
exec"v+=1;l[y]=l.get(y,'').ljust(x)+`v`;x+=len(`v`);i=-~i%-~n;y+=n%4-1;n+=2>>i*2;"*input()
for k in sorted(l):print l[k]

Ver el resultado en ideone .


Hm ... No sigue y sigue y sigue y sigue.
— Zizouz212

@ Zizouz212 Sí, ideone solo tiene una salida fija y rompe automáticamente las líneas que son demasiado largas.
— flawr
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.