Costruisci scale ASCII


28

Dato un input di due numeri interi n e m , genera una scala ASCII di lunghezza n e dimensione m .

Questa è una scala ASCII di lunghezza 3 e dimensione 3:

o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

Questa è una scala ASCII di lunghezza 5 e dimensione 1:

o-o
| |
+-+
| |
+-+
| |
+-+
| |
+-+
| |
o-o

Questa è una scala ASCII di lunghezza 2 e dimensione 5:

o-----o
|     |
|     |
|     |
|     |
|     |
+-----+
|     |
|     |
|     |
|     |
|     |
o-----o

Essere specifici:

  • La lunghezza ( n ) rappresenta il numero di quadrati di cui è composta la scala.

  • La dimensione ( m ) rappresenta la larghezza e l'altezza dell'interno di - cioè, senza contare i "bordi" - ogni quadrato.

  • Ogni quadrato è costituito dall'area interna piena di spazi, circondata da -s in alto e in basso, |s a sinistra e a destra e +s in tutti e quattro gli angoli.

  • I bordi tra i quadrati si uniscono, quindi due linee di seguito si +--...--+uniscono in una.

  • Gli angoli dell'intera scala vengono sostituiti con il personaggio o.

  • È possibile facoltativamente generare una nuova riga finale.

La lunghezza della scala ( n ) sarà sempre ≥ 2 e la dimensione ( m ) sarà sempre ≥ 1.

L'input può essere preso come una stringa separata da spazi bianchi / virgola, una matrice / lista / ecc. O due funzioni / riga di comando / ecc. argomenti. Gli argomenti possono essere presi in qualunque ordine sia il più conveniente / più golfistico.

Dato che si tratta di , vince il codice più breve in byte.

Suggerimento: gli esempi sopra riportati possono essere utilizzati anche come casi di test.


Dobbiamo prima prendere la lunghezza, poi le dimensioni?
RK.

@RK. Puoi prenderli nell'ordine che preferisci.
Maniglia della porta

1
Può esserci una newline leader ?
Conor O'Brien,

1
@ CᴏɴᴏʀO'Bʀɪᴇɴ Uhh ... non ci vado per quello.
Maniglia della porta

1
Va bene: P Ne è valsa la pena.
Conor O'Brien,

Risposte:


4

Pyth, 34 byte

.NjjNm*QTvz*2YjC:M++J"+|o"m"- -"QJ

Suite di test

Accetta gli argomenti newline separati su STDIN.

Utilizza una funzione di supporto :, che costruisce ogni tipo di stringa verticale da tre caratteri, quindi si replica all'occorrenza, traspone e si unisce su newline.


11

Ruby, 71

->m,n{h=0;(?o+?+*(n-1)+?o).chars{|c|puts [?|+' '*m+?|]*h,c+?-*m+c;h=m}}

non golfato nel programma di test

f=->m,n{
  h=0                             #The number of | above the 1st rung is 0
  (?o+?+*(n-1)+?o).chars{|c|      #Make a string of all the rung ends o++...++o and iterate through it
    puts [?|+' '*m+?|]*h,         #draw h vertical segments |  ...  |
      c+?-*m+c                    #and a rung with the correct ends
    h=m                           #The number of | above all rungs except the 1st is m
  }
}


f[gets.to_i,gets.to_i]

Sembra che ci siano problemi minori con la versione golf: bisogno ;dopo h=0, bisogno spazio dopo puts. Ma il tuo punteggio cresce solo con 1 personaggio in quanto c'è uno spazio extra prima puts.
arte

@manatwork oops, grazie, risolto. Non so come sia successo, devo aver giocato a golf e non averlo seguito.
Level River St

9

CJam, 43 42 byte

Non sono irritato dal punteggio. Ma io non sono Dennis, vero?

q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$

L'input è di 2 elementi separati da spazio. Prima la lunghezza

2 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

Spiegazione

q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$
q~                                         e# read input
  :Z;                                      e# Record the size in Z and discard
     '-'o{[\Z*1$N]}:X~                     e# Create the initial line (and final). also creates a shorcut to do this later
           \                               e# Capture two arguments
            Z*                             e# The separator is repeated size times
              1$                           e# Repeat the first argument
                N                          e# Add newline
                                           e# X is a function to create line in a ladder
                      ['-_'+X\'|XZ*]       e# Design the repeating part
                                    @*     e# Repeat the pattern n times
                                      1>   e# Discard the initial
                                        1$ e# Since the final line is same than the initial, we just write it.
                                           e# Implicit printing

1
Mi piace che tu l'abbia formulato come una domanda. "Non sono Dennis ... vero?"
undergroundmonorail,

7

JavaScript (ES6), 89

... ripeti, ripeti, ripeti ...

(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

Test

F=(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

// Less golfed
U=(n,m)=>
{
  var R=x=>x.repeat(m),
      a=R(' '),
      b=R(`|${a}|\n`);
      c=R('-'),
      d=`o${c}o\n`;
  m=n-1;
  return d+R(b+`+${c}+\n`)+b+d
}

function test() {
  var i=I.value.match(/\d+/g)
  if (i) O.textContent=F(+i[0],+i[1])
  console.log(i,I.value)
}  
 
test()
N,M: <input id=I value="3,5" oninput=test()>
<pre id=O></pre>


Non sapevo che document.getElementById('elem').potesse essere sostituito da elem.! +1 per questo, ma per favore, potresti indicare alcuni documenti su questo?
F. Hauri,

2
@ F.Hauri funziona in quasi tutti i browser, ma dovrebbe essere evitato (tranne quando si codifica per divertimento). Info e link stackoverflow.com/questions/3434278/...
edc65

6

C #, 1412 byte

... Il mio primo tentativo di CodeGolf, probabilmente non vincerà, ma funziona, quindi eccoci qui:

using System;

namespace Ascii_Ladders
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            int m = 0;

            Console.Write("Please enter Height: ");
            n = int.Parse(Console.ReadLine());
            Console.Write("Please Enter Width: ");
            m = int.Parse(Console.ReadLine());

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                Console.Write("-");
            }
            Console.WriteLine("o");

            for (int k = 0; k < n; k++)
            {
                for (int i = 0; i < m; i++)
                {
                    Console.Write("|");
                    for (int j = 0; j < m; j++)
                    {
                        Console.Write(" ");
                    }
                    Console.WriteLine("|");
                }
                if (k != n - 1)
                {
                    Console.Write("+");
                    for (int i = 0; i < m; i++)
                    {
                        Console.Write("-");
                    }
                    Console.WriteLine("+");
                }
            }

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                 Console.Write("-");
            }
            Console.WriteLine("o");

            Console.ReadKey();
        }
    }
}

9
Benvenuto in Programmazione di puzzle e codice golf! Hai un sacco di spazi nel tuo codice che puoi rimuovere per accorciare il tuo codice, se desideri maggiori informazioni sul golf del tuo codice, puoi dare un'occhiata a Suggerimenti per giocare a golf in C # .
Downgoat,

Sono d'accordo con @ Doᴡɴɢᴏᴀᴛ qui. Sono stato potenzialmente in grado di giocare a golf a soli 533 byte . Ma potrebbe essere migliore. (Avviso: non programma in C #.)
user48538

Sono arrivato al 314 conusing System;class P{static int m;static void Main(){int n = int.Parse(Console.ReadLine());m = int.Parse(Console.ReadLine());M('o','-');for(int k=0;k<n;k++){for(int i=0;i<m;i++){M('|',' ');}if(k!=n-1){M('+','-');}}M('o','-');Console.ReadKey();}static void M(char x,char y){Console.WriteLine(x+new string(y,m)+x);}}
RedLaser il

3
Mancavano pochi spazi così 310 conusing System;class P{static int m;static void Main(){int n=int.Parse(Console.ReadLine());m=int.Parse(Console.ReadLine());M('o','-');for(int k=0;k<n;k++){for(int i=0;i<m;i++){M('|',' ');}if(k!=n-1){M('+','-');}}M('o','-');Console.ReadKey();}static void M(char x,char y){Console.WriteLine(x+new string(y,m)+x);}}
RedLaser

2
Giù a 270, senza cambiamenti di approccio utilizzato: using C=System.Console;class P{static void Main(){int i,k,n=int.Parse(C.ReadLine()),m=int.Parse(C.ReadLine());System.Action<char,char> M=(x,y)=>C.WriteLine(x+new string(y,m)+x);M('o','-');for(k=0;k<n;k++){for(i=0;i<m;i++){M('|',' ');}if(k<n-1){M('+','-');}}M('o','-');}}. C'è molto più potenziale qui, però, semplicemente cambiando un po 'come fare le cose.
Joey,

6

Julia, 87 byte

f(n,m)=(g(x)=(b=x[1:1])x[2:2]^m*b*"\n";(t=g("o-"))join([g("| ")^m for i=1:n],g("+-"))t)

Questa è una funzione che accetta due numeri interi e restituisce una stringa.

Ungolfed:

function f(n::Int, m::Int)
    # Create a function g that takes a string of two characters and
    # constructs a line consisting of the first character, m of the
    # second, and the first again, followed by a newline.
    g(x) = (b = x[1:1]) * x[2:2]^m * b * "\n"

    # Assign t to be the top and bottom lines. Construct an array
    # of length n where each element is a string containing the
    # length-m segment of the interior. Join the array with the
    # ladder rung line. Concatenate all of this and return.
    return (t = g("o-")) * join([g("| ")^m for i = 1:n], g("+-")) * t
end

5

pb - 147 byte

^t[B]>>[B]vw[T!0]{b[43]<[X]b[43]>w[B=0]{b[45]>}v[X-1]w[B=0]{b[124]^}v[X]t[T-1]}t[111]b[T]<w[X!0]{b[45]<}b[T]w[Y!0]{w[B!0]{^}b[124]^}b[T]^>>[B]vb[T]

Questo è il tipo di sfida a cui, per diritto, pb dovrebbe essere davvero bravo. Disegnare semplici immagini con personaggi è esattamente ciò per cui è stato progettato pb. Ahimè, credo sia solo un linguaggio volgare.

Accetta prima la lunghezza dell'input, seguita dalla dimensione. Accetta l'input sotto forma di valori byte, ad esempio:python -c 'print(chr(5) + chr(7))' | ./pbi.py ladder.pb

Guarda, un'animazione divertente!

Con commenti:

^t[B]            # Save length to T
>>[B]v           # Go to X=size+1, Y=0

w[T!0]{          # While T is not 0:
    b[43]            # Write a '+'
    <[X]b[43]        # Write a '+' on the left side as well
    >w[B=0]{b[45]>}  # Travel back to the right '+', writing '-' on the way
    v[X-1]           # Go down by X-1 (== size)
    w[B=0]{b[124]^}  # Travel back up to the '+', writing '|' on the way
    v[X]             # Go down by X (== size + 1, location of next '+')
    t[T-1]           # Decerement T
}

t[111]           # Save 'o' to T (it's used 4 times so putting it
                 # in a variable saves bytes)

b[T]             # Write an 'o' (bottom right)

<w[X!0]{         # While not on X=0:
    b[45]<           # Travel left, writing '-' on the way
}

b[T]             # Write an 'o' (bottom left)

w[Y!0]{          # While not on Y=0:
    w[B!0]{^}        # Skip nonempty spaces
    b[124]           # Write a '|'
    ^                # Travel up
}

b[T]             # Write an 'o' (top left, replaces existing '+')

^>>[B]v          # Go back to where the size is saved and go to X=size+1, Y=0

b[T]             # Write an 'o' (top right, replaces existing '+')

5

Bash puro, 132 130 128 127 byte

Sì, potrei eliminare un altro byte sostituendo l'ultimo ${p% *}, ma preferisco questo:

p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"

Campione:

ladders() {
    p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
    a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"
}

ladders 3 4
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

ladders 2 1
o--o
|  |
|  |
o--o

4

Haskell, 100 97 byte

l#s=unlines$t:m++[t]where _:m=[1..l]>>["+"!"-"]++("|"!" "<$u);t="o"!"-";o!i=o++(u>>i)++o;u=[1..s]

Esempio di utilizzo:

*Main> putStr $ 4 # 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

Come funziona:

l#s=unlines$t:m++[t]         -- concat top line, middle part and end line
                             -- with newlines between every line
  where                      -- where
  _:m=                       -- the middle part is all but the first line of
     [1..l]>>                -- l times
         ["+"!"-"]           --    a plus-dashes-plus line
         ++("|"!" "<$u)      --    followed by s times a bar-spaces-bar line

  t="o"!"-"                  -- very first and last line
  o!i=o++(u>>i)++o           -- helper to build a line
  u=[1..s]

Modifica: @Christian Irwan ha trovato 3 byte. Grazie!


Patternmatching per -1 score m=init$[1..l]>>("|"!" "<$u)++["+"!"-"]=>(_:m)=[1..l]>>["+"!"-"]++("|"!" "<$u)
Akangka

Sorprendentemente _:m=[1..l]>>["+"!"-"]++("|"!" "<$u)funziona
Akangka il

@ChristianIrwan: ben individuato! Grazie!
nimi,

3

brainfuck - 334 byte

,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-]<----[>---<----]--[>[+>>]<<[<<]>++++++]>[+.>>]-[<+>---]<+++++++>>--[<+>++++++]->---[<------->+]++++++++++[<++<]+++++[>[++++++>>]<<[<<]>-]>[-]>.-<<----[>>+++<<----]--[>+<--]>---<<<<++++++++++.,[>[>+>+<<-]>[<+>-]>[<<<<[>>>>>>[.>>]<<[<<]>>-]>>>>>[.>>]<<[<<]>-]<<<<+>-]>>>>[-]----[>---<----]>+.[>]<<<<<[.<<]

Mi aspettavo che questo fosse molto più breve.

Questo crea una "stringa" che assomiglia | (...) |e una che assomiglia +----(...)----+, stampando ognuna come necessario, con un involucro speciale per la os in alto e in basso.

Richiede un interprete che utilizza celle a 8 bit e consente di spostarsi a sinistra dalla cella 0 (sia in celle negative che in loop). Nella mia esperienza, queste sono le impostazioni predefinite più comuni.

Con commenti:

,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-] Get m from input; make a copy
                      Turn it into m cells containing 1 with empty cells between

<----[>---<----]      Put 67 at the beginning (again with an empty cell between)

--[>[+>>]<<[<<]>++++++]  Add 43 to every nonempty cell

>[+.>>]               Add 1 to each cell and print it

-[<+>---]<+++++++    Put 92 after the last 45 (no empty cell!)

>>--[<+>++++++]      Put 43 immediately after the 92

->---[<------->+]    Put 234 after 43

++++++++++           And 10 after that

[<++<]             Add two to the 234; 92; the empty spaces; and left of the 111

+++++[>[++++++>>]<<[<<]>-] Add 30 to each 2; the 94; and the 236

>[-]>.-<<----[>>+++<<----] Erase leftmost 32; Print 111; subtract 68 from it

--[>+<--]>---        Put 124 where the 32 was

<<<<++++++++++.,     Print a newline; override the cell with n from input

[                    n times:

  >[>+>+<<-]>[<+>-]    Make a copy of m

  >[                   m times:

    <<<<                 Look for a flag at a specific cell

    [                    If it's there:

      >>>>>>[.>>]          Go to the 43; print it and every second cell after

      <<[<<]>>-            Clear the flag

    ]

    >>>>>[.>>]           Go to the 124; print it and every second cell after

    <<[<<]>              Go back to the copy of m

  -]

  <<<<+>               Plant the flag

-]

>>>>

[-]----[>---<----]>+ Erase the 124; add 68 to 43

.[>]                 Print it; then head to the end

<<<<<[.<<] Go to the last 45; print it; then print every second cell to the left


2

Jolf, 36 byte

Provalo qui!

ρpi,a+2J+2J"o-| "j"o(.+)o
o.+o'+$1+

Spiegazione

ρpi,a+2J+2J"o-| "j"o(.+)o\no.+o'+$1+
 pi              j                   repeat vertically j times
   ,a+2J+2J"o-| "                    a box with dimensions 2+J
ρ                 "o(.+)p\np.+o'     replace with regex
                                +$1+ with the -...-

2

Perl, 98 byte

($n,$m)=@ARGV;print$h="o"."-"x$m."o\n",((("|".(" "x$m)."|\n")x$m.$h)x$n)=~s{o(-+)o(?=\n.)}{+$1+}gr

1
Un'eccellente prima risposta. Ma non vedo alcun +segno nel tuo codice, hai considerato che i gradini intermedi hanno +segni ad ogni estremità?
Level River St

Grazie per il commento formulato molto bene: ho completamente distanziato i segni più! Mi è costato anche un po 'di spazio; sto ancora pensando a come posso accorciarlo ... oltre a omettere ($n,$m)=@ARGV;e supporre che siano già impostati - non sono sicuro che sia nello spirito o no. Dovrò cercarlo.
ZILjr,

Salvo quanto diversamente specificato nella domanda, la regola è qui meta.codegolf.stackexchange.com/a/2422/15599 . Non puoi semplicemente supporre che le variabili siano impostate, ma puoi scrivere una funzione invece di un programma, se ciò aiuta. Non faccio Perl ma presumo che potrebbe salvarti il @ARGV. Inoltre, quando rispondi a qualcuno ricorda di includere @username in modo da ricevere un avviso. Non ho bisogno di farlo in quanto questo è il tuo post.
Level River St

1

C, 122 byte

f(int m,int n,char*s){int i=0,w=3+m++;for(;i<w*m*n+w;++i)*s++=i%w>m?10:" |-+-o"[!(i/w%m)*2+!(i%w%m)+!(i/w%(m*n))*2];*s=0;}

Provalo online .


1

Tcl, 187 byte

lassign $argv n w
set c 0
while { $c < [expr {($w * $n) + ($n + 2)}]} {if {[expr {$c % ($n + 1)}] == 0} {puts "o[string repeat "-" $w ]o"} else {puts "|[string repeat " " $w ]|"}
incr c}

Questo codice viene creato per essere inserito in un file con argomenti immessi nella riga di comando. fornire il numero di scatole e la larghezza in quell'ordine.


1

PHP, 81 byte

Prevede 2 argomenti, passati quando si chiama direttamente il comando PHP. Il primo è la dimensione e il secondo è il numero di passaggi.

$R=str_repeat;echo$P="o{$R('-',$W=$argv[1])}o
",$R("|{$R(' ',$W)}|
$P",$argv[2]);

Potrebbe richiedere alcuni miglioramenti.


0

Python 2, 94 byte

def F(n,m):a,b,c,d='o|+-';r=[a+d*m+a]+([b+' '*m+b]*m+[c+d*m+c])*n;r[-1]=r[0];print'\n'.join(r)

'Ungolfed':

def F(n,m):
 # 'o---o'
 r = ['o'+'-'*m+'o']
 # ('|   |'*m+'+---+') n times
 r += (['|'+' '*m+'|']*m+['+'+'-'*m+'+'])*n
 # replace last +---+ with o---o
 r[-1] = r[0]
 print '\n'.join(r)


0

Pip -l , 35 byte

(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o

Provalo online!

Spiegazione

(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o
                                     a is length, b is size, s is space (implicit)
   sXb                               String containing b spaces
      RLa                            List containing a copies of that string
         JW'-                        Join on "-" and wrap the result in "-" as well
  Y                                  Necessary for operator precedence reasons
 ^                                   Split into a list of characters
(            )Xb                     String-repeat each character in the list b times
                                     This list represents the central columns of the ladder

                    '|Xb             String containing b pipe characters
                        RLa          List containing a copies of that string
                           J'+       Join on "+"
                   (          )WR'o  Wrap in "o"
                  ^                  Split into a list of characters
                                     This list represents the outer columns of the ladder

                WR                   Wrap the left list in the right list, vectorizing

Alcune altre versioni

Ho provato molti approcci diversi cercando di catturare Pyth ...

[Y'-XbWR'o;@>(sXbWR'|RLbPE'-XbWR'+RL:a)y]  41
Y^(t**b.1*:t**bX--a.1)" --"@yXbWR"|o+"@y   40
Y'|XbRLaJ'+YyWR'o;Z:sXbRLaJW'-RLbPEyAEy    39
t**:b(" |-o-+"<>2)@_@^t.1M$*Y[ttXa-1].1    39
J*Z:sXbRLaJW'-RLbWR:^('|XbRLaJ'+)WR'o      37
Y^$*Y[t**:btXa-1].1" --"@yXbWR"|o+"@y      37

Mi piacciono particolarmente t**bquelli che usano la matematica per generare il modello verticale della scala:

        b           Size; e.g. 3
    t               Preset variable for 10
     **:            Set t to t**b (e.g. 1000)
           a        Length; e.g. 3
            -1      2
         tX         String-repeat (the new value of) t 2 times: 10001000
   [          ]     Put t and the above into a list: [1000; 10001000]
               .1   Append 1 to both of them: [10001; 100010001]
$*(              )  Fold on multiplication: 1000200020001

Il 1000200020001può quindi essere utilizzato per generare i modelli o|||+|||+|||oe - - - -che compongono la scala. Sfortunatamente, questo approccio non è stato più breve dell'approccio join / wrap.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.