La strada da percorrere


12

Dati due parametri della corsia e della lunghezza della strada , stampare una rappresentazione ASCII delle indicazioni di corsia per Strade e Traffic Service per dipingere le strade.

Esempio di input / output

Ingresso:, BTHMLRPHU 21

Non mi importa se prendi due parametri o concateni il numero alla fine della stringa, è inequivocabile.

L'input può essere preso da STDIN, come argomento di funzione, variabili d'ambiente, qualunque cosa abbia senso nella tua lingua.

Produzione:

!   |      x      ##      |      |      x      x      !
! B |  /\  x HOV3 ##  <-  |  ->  |  ^^  x HOV3 x      !
! B |  \/  x HOV3 ##   |  |  |   |  ^^  x HOV3 x      !
!   |      x      ##      |      |      x      x      !
!   |      x      ##      |      |      x      x      !
!   |      |      ##      |      |      |      |      !
!   |      |      ##      |      |      |      |      !
!   |      |      ##      |      |      |      |      !
! B |  /\  | HOV3 ##  <-  |  ->  |  ^^  | HOV3 |      !
! B |  \/  | HOV3 ##   |  |  |   |  ^^  | HOV3 |      !
!   |      x      ##      |      |      x      x      !
! B |  /\  x HOV3 ##  <-  |  ->  |  ^^  x HOV3 x      !
! B |  \/  x HOV3 ##   |  |  |   |  ^^  x HOV3 x      !
!   |      x      ##      |      |      x      x      !
!   |      x      ##      |      |      x      x      !
!   |      |      ##      |      |      |      |      !
!   |      |      ##      |      |      |      |      !
!   |      |      ##      |      |      |      |      !
! B |  /\  | HOV3 ##  <-  |  ->  |  ^^  | HOV3 |      !
! B |  \/  | HOV3 ##   |  |  |   |  ^^  | HOV3 |      !
!   |      x      ##      |      |      x      x      !

Ogni personaggio indica 0,5 metri di larghezza e un chilometro di lunghezza.

specificazione

Segnaletica di corsia

Per ogni tratto di strada di 10 km, i segni sono dipinti ai chilometri 2, 3, 9 e 10 (dalla "cima" dell'uscita). I segni sono centrati nella corsia. Ad eccezione della pista ciclabile e della mediana, tutte le corsie sono larghe 3 metri (6 caratteri).

I caratteri di diamante e freccia ASCII non sono consentiti al posto dei segni come indicato nell'output di esempio.

  • B: Corsia per le bici. Bmarcatura. 1,5 metri (3 caratteri) di larghezza.
  • T: Transito. Marcatura a diamante
  • H: Corsia per veicoli ad alta occupazione. HOV3marcatura
  • Le R: svolta corsia. Freccia
  • P: Passaggio corsia. Marcature del cursore
  • U: Corsia libera. Nessun segno

Separatori (in ordine di precedenza)

  • Mediana: ##(indicato da Mnella stringa di input, sostituisce qualsiasi altro separatore incluso fosso)
  • Ditch (estrema sinistra ed estrema destra): !punto esclamativo
  • Le corsie HOV si alternano tra xe |ogni 5 km
  • Normale: |

vincoli

La tua funzione o programma deve:

  • Stampa su STDOUT (ciò significa equivalenti di System.out.printper Java, console.logper JavaScript, ecc.)
  • Essere in grado di stampare 1 - 9 corsie con 0 - 10 mediane
  • Essere in grado di stampare fino a 50 km di carreggiata (50 linee di uscita)
  • Non utilizzare scappatoie standard
  • Lo spazio bianco finale non è accettabile ad eccezione di un facoltativo \nalla fine dell'output

Output massimo possibile: 3700 byte (74 caratteri * 50 righe).

Output più piccolo possibile: 5 byte (con input B, 1)

ipotesi

  • Nessuna mediana adiacente ( MMnon si verificherà la sottostringa )
  • La seconda linea di marcature potrebbe essere tagliata (ad esempio se la lunghezza è di 9 o 12 km)
  • Le corsie potrebbero non avere un senso logico (è possibile qualsiasi ordine, ad esempio una corsia di svolta a destra a sinistra della strada)

Questo è , quindi vince il codice più breve (in byte)!


1
E lì,
adori i

Risposte:


4

Ruby, 245

Stampa la corsia divide se pertinente, quindi stampa la corsia.

Non mi aspetto di vincere.

->(n,i){i.times{|d,t|*e=''
g=e+%w{HOV3 ^^ B}
n.chars{|c|$><<(c==?M?'##':!t ??!:(t+c)[?H]&&d%10<5??x:?|)if(M=t!=?M)
$><<((e+[(%w{/\\ <- ->}+g)[v='TLRUHPB'.index(c)],(%w{\\/ \ | |\ }+g)[v]]+e*4)*2)[d%10].center(v>5?3:6)if(t=c)!=?M}
puts M ? e:?!}}

changelog

245 soffocare stderr e dividere gli array in modo efficace.

263 modo migliore per indicizzare l'array

268 basta stampare ogni riga, non calcolare una versione canonica.

330 commit iniziale


Non mi aspetterei che Ruby vincesse, ma se non ci fossero altre risposte entro la prossima settimana, immagino tu vinca :-P In una seconda nota c'è un posto dove posso provarlo senza installare Ruby sul mio computer?
rink.attendant.6

@ rink.attendant.6 ideone.com
Non che Charles il

2

JavaScript (ES6), 316 byte

f=(x,n)=>{for(i=0;n>i++;){b=!(r=i%10)|r==3;y=[...`! ${[...x].join` | `} !`[o='replace'](/[\W] ?M [\W]?/g,'##')].map(c=>~(q='LPRTU'.indexOf(c))?` ${'<- |^^^^->| /\\\\/    '.substr(4*q+2*b,2)} `:c=='H'?'HOV3':c).join``;y=r&&r<6?y[o](/\| H/g,'x H')[o](/3 \|/g,'3 x'):y;console.log(b|r==2|r==9?y:y[o](/[^!\|x#]/g,' '))}}

dimostrazione

Dovrebbe funzionare su Firefox e Edge al momento della scrittura, Chrome / Opera richiede l'abilitazione di funzionalità sperimentali.

console.log = x => O.innerHTML += x + '\n';

f = (x, n) => {
  for (i = 0; n > i++;) {
    b = !(r = i % 10) | r == 3;
    y = [...
      `! ${[...x].join` | `} !` [o = 'replace'](/[\W] ?M [\W]?/g, '##')
    ].map(c => ~(q = 'LPRTU'.indexOf(c)) ? ` ${'<- |^^^^->| /\\\\/    '.substr(4*q+2*b,2)} ` : c == 'H' ? 'HOV3' : c).join ``;
    y = r && r < 6 ? y[o](/\| H/g, 'x H')[o](/3 \|/g, '3 x') : y;
    console.log(b | r == 2 | r == 9 ? y : y[o](/[^!\|x#]/g, ' '))
  }
}

// Snippet stuff
var demo = () => {
  O.innerHTML = '';
  document.forms[0].checkValidity() && f(document.getElementById('P').value, document.getElementById('N').valueAsNumber);
};

document.getElementById('P').addEventListener('change', demo);
document.getElementById('N').addEventListener('change', demo);

demo();
<form action='#'>
  <p>
    <label>Lane pattern:
      <input type=text pattern=^M?([BHLPRTU]M?)+$ maxlength=19 required id=P value=MLTPUMHUTBR>
    </label>
  </p>
  <p>
    <label>Kilometres:
      <input type=number id=N min=1 value=21 max=50 step=1 required>
    </label>
  </p>
  <pre><output id=O></output></pre>
</form>


1

05AB1E , 175 174 175 byte

ðTиDU'|TиX'BŽ5ES©ǝX„\/TbSDVè®ǝ€ºX4×"HOV3"®ǝX'<18SǝX„|-Yè®ǝøJDí'<'>:X'^®ǝ2×'#Tи2×'x5и'|5и«'!Tи)I.•o¤[‹‡•uŽDýSтì€ûŽe1ª904ûª8ª₄«ª‡•δ~¬]•2ôDí«Ž
ÿT∍S:ð.ø8ðì‚8:1ðì‚ð:SðT:èεI∍}øJ»

Approccio piuttosto negativo, ma funziona ed è stato divertente da realizzare. Si può sicuramente giocare ancora un po 'a golf.

+1 byte come correzione di bug per due HHcorsie adiacenti .

Provalo online.

Spiegazione:

Passaggio 1: crea tutte le corsie possibili con dimensione 10:

ðTи               # Push a space character, repeated 10 times as list
   DU             # And store a copy in variable `X`
'|Tи             '# Push "|", repeated 10 times as list
X                 # Push the list of spaces of variable `X`
 'B              '# Push a "B"
   Ž5E            # Push compressed integer 1289
      S           # Converted to a list of digits: [1,2,8,9]
       ©          # Store it in variable `®` (without popping)
        ǝ         # Replace the spaces in the pushed `X` with the "B" at these (0-based)
                  # indices
X                 # Push `X` again
 \/              # Push string "\/"
    TbS           # Push 10, converted to binary, as list: [1,0,1,0]
       DV         # Store a copy in variable `Y`
         è        # Index each into this string: ["/","\","/","\"]
          ®       # Push list `®` again ([1,2,8,9])
           ǝ      # And replace the spaces with these characters
            €º    # And then mirror each line (" "→"  "; "/"→"/\"; "\"→"\/")
X                 # Push `X` again
 4×               # Extend each space to four spaces
   "HOV3"         # Push string "HOV3"
         ®ǝ       # And replace the spaces with this string at the indices of `®` again
X                 # Push `X` again
 '<              '# Push string "<"
   18S            # Push 18 as list: [1,8]
      ǝ           # Replace the spaces with "<" at those indices
       X          # Push `X` yet again
        „-|       # Push string "-|"
           Yè     # Use list `Y` ([1,0,1,0]) to index into this string: ["-","|","-","|"]
             ®ǝ   # And replace the spaces at the indices of `®` again
               ø  # Then zip-pair the two lists together
                J # And join each pair of characters to a string
Dí                # Create a copy and reverse each string
  '<'>:           # And replace all "<" with ">"
X'^®ǝ            '# Push `X` with the spaces at indices `®` replaced with "^" 
     2×           # Extend each character to size 2
'#Tи             '# Push "#", repeated 10 times as list
    2×            # And extend each character to size 2
'x5и             '# Push "x" repeated 5 times as list
    '|5и         '# Push "|" repeated 5 times as list
        «         # And merge the lists together
'!Tи             '# Push "!", repeated 10 times as list
)                 # And finally wrap all lists of the stack into one big list of lanes

Passaggio 2: converti la stringa di input in indici (che utilizzeremo per indicizzare nell'elenco che abbiamo creato nel passaggio 1):

I                 # Push the input-string
 .•o¤[‹‡•         # Push compressed string "tlrpbhmu"
         u        # And uppercase it
ŽDý               # Push compressed integer 3567
   S              # Converted to a list of digits: [3,5,6,7]
    тì            # Prepend each with "100": ["1003","1005","1006","1007"]
      €û          # And palindromize each: ["1003001","1005001","1006001","1007001"]
Že1               # Push compressed integer 10201
   ª              # And append it to the list
904ûª             # Push 904 palindromized to "90409", and also append it to the list
8ª                # Append 8 to the list
₄Â                # Push 1000, and bifurcate it (short for Duplicate & Reverse copy)
  «               # Merge them together: "10000001"
   ª              # And also append it to the list
                 # Now transliterate all uppercase characters in the input to these numbers
•δ~¬]•            # Push compressed integer 1119188999
      2ô          # Split into parts of size 2: [11,19,18,89,99]
        Dí        # Create a copy, and reverse each item: [11,91,81,98,99]
          «       # And merge the lists together: [11,19,18,89,99,11,91,81,98,99]
Ž\nÿ              # Push compressed integer 19889
    T            # Extended to size 10: 1988919889
      S           # As a list of digits: [1,9,8,8,9,1,9,8,8,9]
:                 # Replace all [11,19,18,89,99,11,91,81,98,99] with [1,9,8,8,9,1,9,8,8,9]
                  # in the converted string
ð.ø               # Surround the string with spaces
8ðì               # Push 8 with a prepended space: " 8"
   ‚             # Bifurcate and pair: [" 8","8 "]
     8:           # And replace all those for 8 in the string
1ðì‚ð:           # Do the same for [" 1","1 "] → " "
S                 # Convert the string to a list of characters (digits and space)
 ðT:              # Replace the spaces for 10

Passaggio 3: utilizziamo tali indici per indicizzare l'elenco delle corsie. E poi convertiamo quell'elenco di corsie nell'output corretto, incluso l'estensione / accorciamento di loro alla dimensione dell'input intero:

è                 # Index the indices in the integer-list into the lanes-list
 ε                # Map over each lane
  I               #  Push the second integer-input
                 #  Extend/shorten each 10-sized lane to this input-size
                # After the map: zip/transpose; swapping rows/columns
   J              # Join inner list together to a single string
    »             # And then join each string by newlines
                  # (after which the result is output implicitly)

Vedere questo 05AB1E punta del mio (sezioni Come stringhe di comprimere che non fanno parte del dizionario? E Come comprimere grandi numeri interi? ) Per capire perché Ž5Eè 1289; .•o¤[‹‡•è "tlrpbhmu"; ŽDýè 10201; •δ~¬]•è 1119188999; Ž\nÿlo è 19889.

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.