Registros ASCII básicos


36

Título alternativo: Registre sua sentença de prisão na parede

Dado um número n, as contagens de saída agrupadas nos tradicionais 5 por grupo e 50 por linha.


Exemplos

1

|
|
|
|

4

||||
||||
||||
||||

5

|||/
||/|
|/||
/|||

6

|||/ |
||/| |
|/|| |
/||| |

50.

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

51

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

|
|
|
|

256

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /||| 

|||/ |
||/| |
|/|| |
/||| |

Regras

  • 5 registros por grupo, 50 registros totais por linha.
  • Os quatro primeiros registros são verticais, o quinto registro cruza todos os outros registros.
    • Cada um dos quatro primeiros consiste em 4 |caracteres verticais .
    • O quinto registro final abrange todos os quatro do primeiro, com um /caractere na diagonal.
  • Cada grupo deve ser separado por um espaço, cada linha uma nova linha em branco.
  • As restrições nsão: 0 <= n <= 1000(por simplicidade).
  • Os espaços à direita e as novas linhas são bons, os anteriores não.
  • Isso é , menor número de bytes ganhos.

Avaliado por ~ 4 pessoas na sandbox .


PS divertido pouco pouco, o número médio de contagens por fila na prisão era de 50, daí o alt. título.



Grande desafio, complexo e simples.
ATaco13

@ATaco Eu realmente quero encontrar a solução que agrega as barras no "quadro geral" e leva em conta que o padrão da barra pode ser inferido por linha (essa é a vitória fácil).
Magic Octopus Urn

2
Obrigado obrigado por fazê-las barras para frente em vez de barras para trás.
totallyhuman

1
@totallyhuman Oh deus, o cara na imagem que eu postei faz ... QUE UNIVERSO É ESTE? São os ursos de Bernstein mais uma vez ... A moeda caiu sobre cara ou coroa para decidir a eleição mais recente dos EUA ?!
Magic Octopus Urn

Respostas:


11

Carvão , 30 25 bytes

FN«J﹪ι⁵⁰×⁵÷ι⁵⁰¿﹪⊕ι⁵↓⁴«←↙⁴

Experimente online! Link é a versão detalhada do código. Explicação:

 N                          Input number
F «                         Loop over implicit range
     ι     ι                Loop index
      ⁵⁰    ⁵⁰              Literal 50
    ﹪                       Modulo
          ÷                 Integer divide
         ⁵                  Literal 5
        ×                   Multiply
   J                        Jump to column, row
                 ι          Loop index
                ⊕           Incremented
                  ⁵         Literal 5
               ﹪            Modulo
              ¿             If
                   ↓⁴       Print 4 `|`s downwards
                     «      Implicit else
                      ←     Move left
                       ↙⁴   Print 4 `/`s down and left

6

Funky , 156 132 133 bytes

n=>{k=n=>((l="|"::rep)(3-i)+"/"+l(i)+" ")::rep(n)p=print L=f=>fori=0i<4i++p(f())forc=0c<n//50c++{L@k(10);p()}L@k((m=n%50)//5)+l(m%5)}

Experimente online!


1
Funky é um ... E agora? Interessante. Nunca vi esse idioma em nenhum dos meus desafios antes.
Magic Octopus Urn

1
@MagicOctopusUrn Provavelmente porque eu escrevi: P
ATaco 13/11

1
Uma linguagem baseada em JavaScript? Perigoso. Mas tudo bem, eu amo o perigo.
Urna Mágica de Polvo

1
fori=0i<4i++p(f())forc=0c<n//50c++o que é esta besta profana tomando o nome de sintaxe
totallyhuman



5

Geléia , 37 bytes

:5[“|||/”]ẋ;”|ẋ⁸%5¤¤W¤ṙ€4Ḷ¤s⁵Z€G€j⁾¶¶

Experimente online!

Explicação

:5[“|||/”]ẋ;”|ẋ⁸%5¤¤W¤ṙ€4Ḷ¤s⁵Z€G€j⁾¶¶  Main Link
:5                                     Floordiv by 5
  [“|||/”]ẋ                            Repeat ["|||/"] by this number
           ;                           Append
            ”|ẋ    ¤                   "|" repeated by
               ⁸%5¤                    The argument modulo 5
                    W¤                 Then wrapped to prevent weirdness
                      ṙ€               Rotate each tally segment by
                        4Ḷ¤            (each) [0, 1, 2, 3]
                           s⁵          Slice into pieces of length 10 (to get 50 per row)
                             Z€        Transpose each
                               G€      Convert each into a grid
                                 j⁾¶¶  Join these grids by a double newline

wheee isso é muito longo


@FrownyFrog corrigido, obrigado!
HyperNeutrino

4

Casca , 29 bytes

J;øṀṪṙŀ4C10§:oR"|||/"÷5oR'|%5

Experimente online!

Sinto que o primeiro 5é redundante, mas removê-lo gera um erro de tipo ...

Explicação

J;øṀṪṙŀ4C10§:oR"|||/"÷5oR'|%5  Implicit input, an integer n.
                       oR'|    Repeat the character '|'
                           %5  n mod 5 times.
             oR"|||/"          Repeat the string "|||/"
                     ÷5        n/5 times.
           §:                  Tack the '|'-string to the end of that list.
        C10                    Cut the list of strings into pieces of length 10.
   Ṁ                           For each piece,
    Ṫ ŀ4                       for each k in [0,1,2,3],
     ṙ                         rotate each string k steps to the left
                               and collect the results into a list.
                               Now we have a list of lists of lists of strings.
J;ø                            Join them with the list [[]].
                               Implicitly join each list of strings by spaces,
                               then join the resulting list of strings by newlines,
                               and print the result.

4

SOGL V0.12 , 33 bytes

ā.{┐4∙F5\?X1w⁄3-14╚╬5@}┼FM»\?O¶oā

Experimente aqui!

Golfe em um telefone é difícil ..

Explicação:

ā                                  push an empty array
 .{                                repeat input times
   ┐4∙                               push a 4 tall line
      F5\?            }              if the counter (1-indexed) divides by 5
          X                            pop that vertical line
           1w⁄                         get the width of the main array
              3-                       subtract 3 from that width - X position
                1                      push 1 - Y position
                 4╚                    push a 4 long diagonal
                   ╬5                  place that in the main array at [width-3; 1]
                     @                 push a space - for the below to add spacing
                       ┼             append horizontally
                        FM»\?        if the counter divides by 50
                             O         output the main array
                              ¶o       output a newline
                                ā      push a new array
                                       (note that the outputting here doesn't disable
                                       implicit outputting)

4

JavaScript (ES6), 139 137 bytes

n=>eval('s="";for(i=0;i++<=n/50;s+=N)for(j=5;--j;s+=N=`\n`)for(k=0;k<(x=(y=n-i*50)<0?50+y:50);)s+=++k%5?k%5-j|k>5*(x/5|0)?"|":"/":" ";s')

Retorna uma string com uma nova linha à direita quando nnão é múltiplo de 50 e uma com várias novas linhas à direita quando n é múltiplo de 50.

Ungolfed

n=>{
    s=""
    for(i=0; i++ <= n/50; s+=N)
        for(j=5; --j; s+=N=`\n`)
            for(k=0; k < (x = (y = n-i*50) < 0 ? 50+y : 50);)
                s += ++k%5 ?
                    k%5-j|k>5*(x/5|0) ?
                        "|"
                    : "/"
                : " "
    return s
}

Snippet de teste

Não evalsolução, 150 bytes

n=>(A=(v,m)=>j=>[...Array(v).keys()].map(m).join(j))(n/50+1|0,i=>A(4,j=>A(x=(y=n+~i*50)<0?50+y:50,k=>++k%5?k%5-4+j|k>5*(x/5|0)?"|":"/":" ")``)`
`)`

`

Possivelmente capaz de jogar mais este, mas o evalmétodo tem sido mais curto até agora.


Levei 10 minutos sólidos para trabalhar com a versão não-destruída e entendê-la. = ^ P Você tem alguns truques legais lá.
DLosc

certeza que você pode fazer para (i = 0; i ++ <n / 50; s + = N) o que economiza um caractere
DanielIndie

@DanielIndie Isso falha porque o loop externo é executado algumas vezes: Experimente online!
Justin Mariner

4

J , 50 48 45 35 33 bytes

_50|:\'|/ '{~[{.(|.2,=i.4)$~]-5|]

Experimente online!

                (    =i.4)          Identity matrix of size 4.
                (  2,    )          Prepend a row of 2s.
                (|.      )          Upside down.
                          $~        Take __ rows.
                            ]-5|]   Input rounded down to a multiple of 5.
             [{.                    Pad with rows of zeroes to [input] rows.
      '|/ '{~                       Get the characters.
_50|:\                              Transpose and fit to width.

Eu amo a idéia de usar infixos para esta parte4,&' '\7$'|||/'
Jonah

@Jonah ele tinha que ir :(
FrownyFrog

3

C (gcc), 170 bytes

char*s="|||/ \0||/| \0|/|| \0/||| \0";h;k;g(x){for(h=0;h<5;h++){for(k=x;k>4;k-=5)printf(s+6*h);for(;k&&h-4;k--)printf("|");putchar(10);}}f(x){for(;x>49;x-=50)g(50);g(x);}

Experimente online!

fé uma função que pega um número inteiro não negativo ( x) e imprime quantos registros, agrupados conforme especificado, em stdout

gé uma função auxiliar que imprime xcontagens, agrupadas por 5, sem dividir linhas.

fchama g(50)e diminui xem 50 até que seja menor que 50; depois, chama g(x)para imprimir os registros restantes em uma linha.

sé um char*tal que, como cadeias, sé a primeira linha de um pacote, s+6é a segunda, s+12é a terceira e s+18é a quarta e s+24é uma cadeia vazia.

g(x)imprime pacotes e diminui x em 5 até x ser menor que 5 e depois imprime xcontagens únicas.



2

Python 2 , 142 bytes

n=input()
while n>0:print"\n".join("".join("|/ "[2*(j%5>3)+(n/(5*(j/5+1))and 3-i==j%5)]for j in range(min(50,n)))for i in range(4)),"\n";n-=50

Experimente online!


1
142 bytes em 18 minutos? Não é ruim :).
Magic Octopus Urn

3
Tem que trabalho rápido quando você realmente deveria ter ido para a cama uma hora atrás
Halvard Hummel

Quick ~= Quality;). Bom trabalho.
Magic Octopus Urn

3
Errr ... isso pode ser mal interpretado. Dizendo que você fez um trabalho de qualidade rápido ... Não é o contrário.
Magic Octopus Urn




2

PHP, 138 141 + 1 bytes

provavelmente não é a solução mais curta possível

for(;0<$z=50+min($n=$x=$y=0,$argn-=50);print"
")while($n++<$z||!$x=+(3<$y+=$n=print"
"))echo"/| "[$n%5?($y+$x++)%4<3|$n%5+$y<4|$z-$z%5<$n:2];

Execute como pipe -nRou experimente online .


Arrumado! Mas a partir da segunda linha de contagem dos registros não são completamente cruzados.
SpazzMarticus

Ao executar o exemplo "tente online" a partir do 5.5, localmente 5.6.31 e 7.1.9.
SpazzMarticus

1
$xé indefinido apenas no primeiro loop, isso atrapalha a produção para um registro maior que 54. Fixo, mas não jogado
SpazzMarticus

@SpazzMarticus fixed
Titus

Legal! Foi minha primeira vez depurando código de golfe, você me deu um tempo difícil! :) Eu acho que estou viciado!
SpazzMarticus

2

Python, 129 113 112 bytes

f=lambda n:n>50and f(50)+"\n\n"+f(n-50)or"\n".join(("|||/|||"[k:k+4]+" ")*(n//5)+" "+"|"*(n%5)for k in range(4))

Explicação

def p(n):
  if n > 50:
    return p(50) + "\n\n" + p(n-50) # Handle 50-groups recursively
  else:
    # For each of the 4 lines:
    rows = []
    for row in range(4):
      #  - Build the "|||/"-blocks by slicing the correct part of "|||/|||".
      #  - Do that n/5 times
      #  - Then add "|" n%5 times
      rows += [("|||/|||"[row:row+4]+" ")*(n//5) + " " + "|"*(n%5)]

    # Join the four rows together
    return "\n".join(rows)

Funciona em Python 2 e 3.

Experimente online



1

Ruby , 100 bytes

->n{(n/-50*-4).times{|i|j=[n-i/4*50,50].min
$><<("|||/|||"[i%4,4]+" ")*(j/5)+?|*(j%5)+$/*(1+i%4/3)}}

Comentado

->n{(n/-50*-4).times{|i|              #Calculate rows of tallies (Ruby rounds division towards negative infinity. Multiply by 4 lines per tally and iterate through them.)
  j=[n-i/4*50,50].min                 #Number of strokes printed in current row is either the number remaining, or 50, whichever is less
    $><<("|||/|||"[i%4,4]+" ")*(j/5)+ #Send to stdout the correct 4 chars selected from "|||/|||" plus a space, j/5 times (rounded down, which eliminates odd strokes.) 
    ?|*(j%5)+                         #If there are any odd strokes, add them to the output
    $/*(1+i%4/3)                      #followed by a newline (2 for the final line of each row of tallies.)
  }
}

Experimente online!


1

Pip , 47 46 bytes

Wa-:yP('|X4.sRA3-_'/M,4)X(YMN[a50])/5.'|Xy%5.n

Experimente online!

Explicação

        Implicit: a is 1st cmdline arg, y is "", s is space, n is newline
W       While loop:
 a-:y   Each iteration, subtract y from a and check if a is still nonzero
        (Since "" is 0 in numeric contexts, this does nothing the first time through)
     P  Print the following:

('|X4.sRA3-_'/M,4)X(YMN[a50])/5.'|Xy%5.n
              M                           Map this function to each number in
               ,4                         range(4):
 '|X4                                      String of four pipe characters
     .s                                    Concatenate a space
       RA                                  Replace the character at index
         3-_                                (3 minus function argument)
            '/                              with forward slash

                                          We now have a list of four strings representing
                                           the rows of a group of 5 tally marks; the
                                           following operations apply to the list
                                           element-wise:

                       [a50]              List of a (number of remaining tallies) and 50
                     MN                   Get the min (number of tallies on this row)
                    Y                     Yank it into y
                   (        )/5           Divide by 5 (number of groups on this row)
(                )X                       String-multiply by that amount
                                   y%5    Number of leftover tallies on this row
                                '|X       String-multiply that many pipes
                               .          Concatenate
                                      .n  Concatenate a newline

A lista resultante será mais ou menos assim:

["|||/ ||\n" "||/| ||\n" "|/|| ||\n" "/||| ||\n"]

Por padrão, P concatena o conteúdo da lista e os gera com uma nova linha à direita. Assim, temos

|||/ ||
||/| ||
|/|| ||
/||| ||

com duas novas linhas à direita (uma do conteúdo da lista e uma adicionada por P). Se houver outra linha a ser impressa, isso fornecerá a linha em branco necessária no meio.




0

05AB1E , 28 bytes

5‰"|||/"¬‚×J4ôTôεε3Ý._}ø»¶«,

Experimente online.

Explicação:

5              # Divmod the (implicit) input-integer by 5
                #  i.e. 111 → [22,1]
  "|||/"        # Push string "|||/"
        ¬       # Push its first character (without popping the string itself): "|"
               # Pair them together: ["|||/","|"]
          ×     # Repeat it based on the divmod
                #  i.e. [22,1] → ["|||/|||/|||/...|||/|||/|||/","|"]
           J    # Join everything together to a single string
                #  → "|||/|||/|||/...|||/|||/|||/|"
            4ô  # Which is then split into block of size 4
                #  → ["|||/","|||/","|||/",...,"|||/","|||/","|||/","|"]
Tô              # Then split this list into sublists of size 10
                #  → ["|||/","|||/","|||/",...],[...,"|||/"],["|||/","|||/","|"]]
  ε             # For-each over the sublists:
   ε            #  Map over the strings in the sublist:
    3Ý          #   Push list [0,1,2,3]
      ._        #   For each: rotate the string that many times
                #    ("|||/" → ["|||/","||/|","|/||","/|||"])
              #  After the map: zip/transpose; swapping rows/columns
     »          #  Join each inner list by spaces, and then the strings by newlines
      ¶«        #  Append a newline to each string
        ,       #  And print with trailing newline

¶«,é claro que existem algumas alternativas possíveis de bytes iguais, como ,¶?ou ,õ,.



Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.