Mappa altimetrica delle scatole


22

Dai un'occhiata a questo diagramma di arte ascii di varie scatole:

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

Ogni casella è formata da caratteri di tubo per le parti verticali ( |), trattini per le parti orizzontali ( -) e vantaggi per gli angoli ( +).

Il diagramma mostra anche le caselle all'interno di altre caselle. Chiameremo il numero di scatole che una scatola è contenuta all'interno del relativo livello . Ecco di nuovo il diagramma con il livello di ogni casella annotato:

+--------------------------------------------------------------+
|                                                              |
|   +-------------------------------+          +-------+       |
|   |                               |          |       |       |
|   |                               |          |   1   |       |
|   |     +----------------+        |          |       |       |
|   |     |                |        |    0     +-------+       |
|   |     |        2       |   1    |                          |
|   |     |                |        |          +-------+       |
|   |     +----------------+        |          |       |       |
|   |                               |          |   1   |       |
|   |                               |          |       |       |
|   +-------------------------------+          +-------+       |
|                                                              |
+--------------------------------------------------------------+

Il tuo programma prenderà un diagramma a scatole simile a quello in alto come input. Come output, il tuo programma dovrebbe generare il diagramma a scatole con:

  • La casella sul livello 0 deve essere riempita con il carattere #(NB: ci sarà sempre una sola casella sul livello 0);
  • Le caselle sul livello 1 devono essere riempite con il personaggio =;
  • Le caselle sul livello 2 devono essere riempite con il personaggio -;
  • Le caselle sul livello 3 devono essere riempite con il personaggio .;
  • Le caselle di livello 4 e superiore non devono essere riempite.

Ecco come dovrebbe apparire l'output dell'input di esempio:

+--------------------------------------------------------------+
|##############################################################|
|###+-------------------------------+##########+-------+#######|
|###|===============================|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###|=====+----------------+========|##########|=======|#######|
|###|=====|----------------|========|##########+-------+#######|
|###|=====|----------------|========|##########################|
|###|=====|----------------|========|##########+-------+#######|
|###|=====+----------------+========|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###+-------------------------------+##########+-------+#######|
|##############################################################|
+--------------------------------------------------------------+

Ecco un altro input e output che mostra i livelli 3, 4 e 5. Nota le linee orizzontali in alto che sono molto vicine tra loro. In questi casi non c'è abbastanza spazio per riempire i personaggi lì.

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

L'output:

+-----------------------------------------------------------------------+
|#####+--------------------------------------------------------------+##|
|#####|======+-----------------------------------------------------+=|##|
|#####|======|---------+-----------------------------------------+-|=|##|
|#####|======|---------|...........+---------------------------+.|-|=|##|
|#####|======|---------|...........|         +-------------+   |.|-|=|##|
|#####|======|---------|...........|         |             |   |.|-|=|##|
|#####|======|---------|...........|         +-------------+   |.|-|=|##|
|#####|======|---------|...........+---------------------------+.|-|=|##|
|#####|======|---------|.........................................|-|=|##|
|#####|======|---------+-----------------------------------------+-|=|##|
|#####|======|-----------------------------------------------------|=|##|
|#####|======|-----------------------------------------------------|=|##|
|#####|======+-----------------------------------------------------+=|##|
|#####|==============================================================|##|
|#####+--------------------------------------------------------------+##|
|#######################################################################|
|#######################################################################|
|#######################################################################|
+-----------------------------------------------------------------------+

Un altro input, questa volta anche con le linee verticali vicine tra loro:

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

L'output:

+-------------+
|+-----------+|
||===========||
||===========||
||===========||
|+-----------+|
+-------------+

Note aggiuntive

  • Ci possono essere spazi bianchi attorno alla scatola più esterna.
  • Le scatole non possono avere una larghezza interna o un'altezza di 0 (quindi avranno sempre un po 'di spazio al loro interno)
  • Le caselle sullo stesso livello possono toccarsi.

Risposte:


3

Rubino 163 164

w=l=-1
x=$<.map{|l|w=l.size;l}.join
b=[]
x.size.times{|i|c=x[i]
x[i..i+1]=='+-'&&(x[i+w]!=?|?b-=[i%w]:b<<i%w)
c>?z&&l+=b&[i%w]!=[]?1:-1
$><<(c==' '&&'#=-.'[l]||c)}

Prova online: test case n. 1 , test case n . 2 .

Il programma non golfato:

  # read all lines from STDIN
  input = $<.map{|l|l}.join
  width = input.index(?\n)+1

  box_left_margins = []
  current_layer = -1

  input.size.times{|i|
    c = input[i]

    if c == ?+ && input[i+1] == ?-
      #we're at a box's left margin
      if input[i+width] == ?|
        # we're at the box's top - mark this index as a left margin
        box_left_margins << i%width
      else
        # we're at the box's bottom - this index is no longer a left margin
        box_left_margins-=[i%width]
      end
    end

    if c == ?|
      if box_left_margins.include? (i%width)
        current_layer += 1
      else
        current_layer -= 1
      end
    end

    if c == ' '
      $><< ('#=-.'[current_layer]||' ')
    else
      $><<c
    end
  }

2

Java, 476 466 byte

import java.util.*;class H{public static void main(String[]a){Scanner p=new Scanner(System.in);char[]l=p.nextLine().toCharArray(),d={'#','=','-','.'};int s=l.length,b,i;int[]m=new int[s];String o=new String(l);for(;;){o+='\n';l=p.nextLine().toCharArray();if(l[0]=='+')break;o+='|';b=0;for(i=1;i<s;++i){char c=l[i];switch(c){case' ':c=b>3?' ':d[b];break;case'+':m[i]=l[i-1]=='-'?-++m[i]:- --m[i];break;case'|':b+=m[i];}o+=c;}}o+=new String(l);System.out.println(o);}}

Questo legge la prima riga per determinare la larghezza (s) della casella più esterna. Con questo mantiene una serie di lunghezze s. Questo array memorizza da sinistra a destra dove iniziano e finiscono le caselle e viene inizializzato con 0s. Memorizza anche l'altezza della scatola.

Il programma legge l'input riga per riga e controlla i seguenti caratteri:

  • '+' è, come sappiamo, il bordo di una scatola. Se il carattere di input a sinistra è un '-', è la fine del riquadro, altrimenti è l'inizio. L'array marker viene aggiornato come segue:
    • Se il marker in questo indice è 0, imposta il valore su 1 (inizio) o -1 (fine).
    • Altrimenti imposta il valore su 0. (Abbiamo raggiunto il fondo del riquadro, non è più importante)
  • '|' cambia l'altezza della casella corrente dal marker nell'indice corrente.
  • '' Ogni carattere viene generato così com'era, ad eccezione degli spazi vuoti, che vengono sostituiti in base all'altezza della casella corrente.

Modifica: grazie a TheNumberOne per il suggerimento. Ho anche sostituito while (true) con for (;;).


1
È possibile sostituire import java.util.Scannerconimport java.util.*
TheNumberOne il

2

CJam, 114 111 108 104 103 102 98 byte

q"-+":R/Ws*N/z{_,{"|1"/Bs*}*}%z{_,,{_I=S&{_I>_1sf&s,\"|+"f&s,m5e<" #=2."=I\t}&}fI}%N*Ws/R*Cs"|-"er

Provalo online nell'interprete CJam .

Come funziona

q               e# Read all input from STDIN.
"-+":R/Ws*      e# Replace each "-+" with "-1".
N/z             e# Split at linefeeds and zip. Pushes the array of columns.
{               e# For each column:
  _,            e#   Push its length.
  {             e#   Do that many times:
    "|1"/Bs*    e#   Replace each "|1" with "11".
  }*            e#
}%              e#
z               e# Transpose. Goes back to array of rows.
{               e# For each row:
  _,,           e#   Push the array of its indexes.
  {             e#   For each index I:
    _I=         e#     Get the Ith character of the row.
    S&{         e#     If it is a space:
      _I>       e#       Get the characters after the Ith.
      _1sf&s,   e#       Count how many characters are 1's.
      \"|+"f&s, e#       Count how many are |'s or +'s.
      m5e<      e#       Subtract and truncate at 5.
      " #=2."=  e#       Retrieve the corresponding character.
      I\t       e#       Replace the Ith character of the row with that one.
    }&          e#
  }fI           e#
}%              e#
N*              e# Join the rows, separating by linefeeds.
Ws/R*           e# Turn "-1"s back to "-+"s.
Cs"|-"er        e# Turn 1's and 2's into |'s and -'s.

2

JavaScript ( ES6 ) 156

Esegui lo snippet in Firefox per testarlo

F=b=>(
  r=b.split(/\n/),q=[n=0],
  r.map((r,i)=>(
    [...r].map((c,p)=>c=='+'?(q[p]=r[p-1]=='-'?-1:1,c):c<'!'?' #=-.'[n]||' ':((n+=q[p]|0),c)).join(''))
  ).join('\n')
)

// TEST

o=x=>O.innerHTML += x+'\n\n'


;[`+--------------------------------------------------------------+
|                                                              |
|   +-------------------------------+          +-------+       |
|   |                               |          |       |       |
|   |                               |          |       |       |
|   |     +----------------+        |          |       |       |
|   |     |                |        |          +-------+       |
|   |     |                |        |                          |
|   |     |                |        |          +-------+       |
|   |     +----------------+        |          |       |       |
|   |                               |          |       |       |
|   |                               |          |       |       |
|   +-------------------------------+          +-------+       |
|                                                              |
+--------------------------------------------------------------+`
,`+-----------------------------------------------------------------------+
|     +--------------------------------------------------------------+  |
|     |      +-----------------------------------------------------+ |  |
|     |      |         +-----------------------------------------+ | |  |
|     |      |         |           +---------------------------+ | | |  |
|     |      |         |           |         +-------------+   | | | |  |
|     |      |         |           |         |             |   | | | |  |
|     |      |         |           |         +-------------+   | | | |  |
|     |      |         |           +---------------------------+ | | |  |
|     |      |         |                                         | | |  |
|     |      |         +-----------------------------------------+ | |  |
|     |      |                                                     | |  |
|     |      |                                                     | |  |
|     |      +-----------------------------------------------------+ |  |
|     |                                                              |  |
|     +--------------------------------------------------------------+  |
|                                                                       |
|                                                                       |
|                                                                       |
+-----------------------------------------------------------------------+`
,`+-------------+
|+-----------+|
||           ||
||           ||
||           ||
|+-----------+|
+-------------+`  
].forEach(t=>o(t+'\n'+F(t)+'\n'))
pre { font-size:10px;}
<pre id=O></pre>


1

CJam, 76 74 byte

q:Q"-+":R/Ws*{_"| "#"]_QN#~%'|m0='+=2*(U+:U+~; \"#=-.\"+U5e<= "S/=~}%Ws/R*

Provalo online nell'interprete CJam .

Come funziona

q:Q        e# Read all input from STDIN and save it in the variable Q.
"-+":R/Ws* e# Replace each "-+" with "-1".
           e# This allows us to easily keep track of right corners.
{          e# For each charcter in the modified input:
  _"| "#   e#   Push its index in the string (0 for '|', 1 for ' ', -1 otherwise).

  "]_QN#~%'|m0='+=2*(U+:U+~; \"#=-.\"+U5e<= "S/

           e#   Split the pushed string at spaces, which results in three chunks:

           e#     ]        Turn the entire stack into a string.
           e#     _QN#     Compute the first index of a linefeed (row length).
           e#     ~%       Retrieve every previous character in the current column,
           e#              starting with the last.
           e#     '|m0=    Get the first character that is not a vertical bar.
           e#     '+=2*(   Push 1 if it's a plus sign and -1 otherwise.
           e#     U+:U     Add to U (initially 0) to keep track of the layer.
           e#     +~;      Add U to the string (casts to Array), dump and discard U.

           e#     "#=-."+  Concatenate this string with the space on the stack.
           e#     U5e<     Truncate U at 5.
           e#     =        Retrieve the corresponding character to replace the space.

           e#     (empty)

  =~       e#   Select and execute the proper chunk.
}%         e#
Ws/R*      e# Replace each "-1" with "-+".

1

APL (Dyalog Unicode) , 50 byte SBCS

s[⊃¨0~¨⍨a5|5⌊+⍀+\(⊢ׯ1*+⍀++\)5=a←⎕⍳⍨s' #=-.+|']

Provalo online!

s←' #=-.+|' assegnare una stringa alla variabile s

input valutato, deve essere una matrice di caratteri

⎕⍳⍨ssostituisci ogni elemento di con il suo indice ins

a← assegnato a a

5=restituisce una matrice booleana di dove +sono a( s[5]è '+')

(⊢ׯ1*+⍀++\)questo è un treno di funzioni:

  • +\ matrice di somme parziali per riga

  • + più

  • +⍀ matrice di somme parziali per colonna

  • ¯1* uno negativo alla potenza di - trasforma le probabilità in ¯1 e le pari in 1

  • ⊢× moltiplicare per l'argomento del treno: azzerare tutto tranne gli angoli delle scatole

+⍀+\ somme parziali per colonna di somme parziali per riga

5⌊ minimo di quello e 5

5| modulo 5

a,¨accoppia gli elementi di ae della matrice corrente

0~¨⍨ rimuove 0 dalle coppie

⊃¨ prima di tutto ciò che resta

s[ ] usa ogni elemento come indice in s



@EriktheOutgolfer Non c'è bisogno di preoccuparsi, la risposta è corretta :) L'espressione che prepara l'argomento (mescola le righe di input non elaborate in una matrice) dovrebbe invertirlo perché ↑⍞⍞...⍞valuta da destra a sinistra. Per il primo esempio non ha avuto importanza e ho dimenticato di menzionarlo.
ngn,


@EriktheOutgolfer ah, vedo ... Adesso eliminerò la risposta e la riparerò più tardi. Grazie.
ngn,

dovrebbe essere corretto ora
ngn

0

> <> , 118 115 87 byte

]0{i:0(?;:"-"=?\:"+"=?\:" "=?\$3l$g+}:ob(?
~$?:g2.10p1+4f:<p3l+10/.16@:$/>.!0"#"$
 #=-.

Provalo online!

Se uno dei simboli non era un, -questo potrebbe essere più breve di 6 byte. Eh, lo ha comunque reso un po ' più piccolo

Come funziona:

] Resets the stack
 0{ Pushes a 0 and rotates the stack
    If the stack is empty, this initialises 0 as the counter
    Otherwise it adds an extra 0 to the stack and pushes the counter to the top
   i:0(?; Gets input and ends if it is EOF
         :"-"=?\ If the inputted character is a -
         p1+4f:< Put a - at cell (19, 1)
      .10        And skip to the end of this line

         :"+"=?\ Else if the inputted character is +
            ?10/ Generate either -1 or 1, depending on what was last put into cell (19,1)
                 The question mark represents cell (19,1), which is either + or -
         p3l     Put this number on (3, length of the stack)
.10p1+4f:<       Repeat the exact same code as with the -, except we put a + at cell (19,1)
         :" "=?\ Else if the character is a space
            @:$/ Create a copy of the counter
         .16     Skip to cell (1,6)
      g2         Get the cell (2, counter) (the  #=-.)
   ~$?           If that cell is a zero, pop it, leaving the initial space. 
                 Else pop the space, leaving the fetched character
        Else if the character is a | or a newline
        $3l$g+   Get the cell at (3, length of the stack) and add it to the counter
    For everything but the last else, we are at the end of the second line
       >.!0"#"$ Skip to the 35th instruction on the first line

 } Push the counter to the bottom of the stack
  :o Output the current character
    b(? If the character is smaller than 11 (a newline)
 ]          Skip the clear stack at the start of the line
 Repeat this until EOF

0

C (gcc) , 190 179 byte

-11 byte grazie a ceilingcat

Non riesce se sizeof (int)> 9, ma puoi consolarti nel fatto che il tuo computer proviene dal futuro.

l;*H,*h,d;f(S){h=H=calloc(l=index(S,10)-S,9);for(char*s=S;*s;s++)h=*s^10?h:H-1,d=*s-43?d:s!=S&s[-1]==45|s-S>l&s[~l]=='|'?-1:1,*h+=*s^45?0:d,h+=write(1,*s^32|*h>4?s:" #=-."+*h,1);}

Provalo online!

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.