Pintura de carreteras por delante

12

Dado el patrón de carril de dos parámetros y la longitud del camino , imprima una representación ASCII de las marcas del carril para que el Servicio de Caminos y Tráfico pueda pintar los caminos.

Ejemplo de entrada / salida

Entrada: BTHMLRPHU 21

No me importa si toma dos parámetros o concatena el número al final de la cadena, no es ambiguo.

La entrada puede tomarse de STDIN, como argumento de función, variables de entorno, lo que tenga sentido en su idioma.

Salida:

!   |      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      !

Cada carácter denota 0,5 metros de ancho y un kilómetro de longitud.

Especificación

Marcas de carril

Por cada tramo de carretera de 10 km, las marcas se pintan en los kilómetros 2, 3, 9 y 10 (desde la "parte superior" de la salida). Las marcas se centran en el carril. Con la excepción del carril bici y la mediana, todos los carriles tienen 3 metros (6 caracteres) de ancho.

Los caracteres ASCII de diamante y flecha no están permitidos en lugar de las marcas como se indica en el resultado del ejemplo.

  • B: Carril de bicicletas. Bcalificación. 1.5 metros (3 caracteres) de ancho.
  • T: Tránsito. Marcado de diamantes
  • H: Carril de vehículos de alta ocupación. HOV3calificación
  • Ly R: Carril de giro. Marca de flecha
  • P: Pasando el carril. Marcas de cuidado
  • U: Carril sin restricciones. Sin marcas

Separadores (en orden de precedencia)

  • Mediana: ##(denotado por Men la cadena de entrada, reemplaza cualquier otro separador, incluida la zanja)
  • Zanja (extrema izquierda y extrema derecha): !signo de exclamación
  • HOV carriles alternan entre xy |cada 5 kilómetros
  • Normal: |

Restricciones

Su función o programa debe:

  • Imprimir en STDOUT (esto significa equivalentes System.out.printpara Java, console.logJavaScript, etc.)
  • Poder imprimir de 1 a 9 carriles con 0 a 10 medianas
  • Ser capaz de imprimir hasta 50 km de carretera (50 líneas de salida)
  • No usar ninguna laguna estándar
  • El espacio en blanco \nal final no es aceptable con la excepción de un opcional al final de la salida

Salida más grande posible: 3700 bytes (74 caracteres * 50 líneas).

Salida más pequeña posible: 5 bytes (con entrada B, 1)

Supuestos

  • No hay medianas adyacentes ( MMno se producirá una subcadena )
  • La segunda línea de marcas podría cortarse (por ejemplo, si la longitud es de 9 o 12 km)
  • Los carriles pueden no tener sentido lógicamente (cualquier orden es posible, por ejemplo, un carril de giro a la derecha a la izquierda de la carretera)

Este es el , por lo que gana el código más corto (en bytes).

rink.attendant.6
fuente
1
Y allí, te encantan las fuentes monoespaciadas
WayToDoor

Respuestas:

4

Rubí, 245

Imprima el carril se divide si es relevante, luego imprima el carril.

No espero ganar.

->(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:?!}}

Registro de cambios

245 estrangulador stderr y matrices divididas de manera efectiva.

263 mejor manera de indexar la matriz

268 solo imprime cada línea, no calcules una versión canónica.

330 confirmación inicial

No es que Charles
fuente
Tampoco esperaría que Ruby ganara, pero si no hay otras respuestas dentro de la próxima semana, entonces supongo que usted gana :-P En una segunda nota, ¿hay algún lugar donde pueda probar esto sin instalar Ruby en mi computadora?
rink.attendant.6
@ rink.attendant.6 ideone.com
No es que Charles el
2

JavaScript (ES6), 316 bytes

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,' '))}}

Manifestación

Debería funcionar en Firefox y Edge al momento de escribir, Chrome / Opera requiere que se habiliten características experimentales.

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>

rink.attendant.6
fuente
1

05AB1E , 175 174 175 bytes

ð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»

Un enfoque bastante malo, pero funciona y fue divertido de hacer. Sin embargo, definitivamente se puede jugar un poco más.

+1 byte como corrección de errores para dos HHcarriles adyacentes .

Pruébalo en línea.

Explicación:

Paso 1: Cree todos los carriles posibles con el tamaño 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

Paso 2: Convierta la cadena de entrada en índices (que vamos a usar para indexar en la lista que creamos en el paso 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

Paso 3: usamos esos índices para indexar en la lista de carriles. Y luego convertimos esa lista de carriles a la salida correcta, incluyendo extenderlos / acortarlos al tamaño de la entrada entera:

è                 # 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)

Ver este consejo 05AB1E mío (secciones Cómo comprimir cadenas que no forman parte del diccionario? Y cómo comprimir grandes números enteros? ) Para entender por qué Ž5Ees 1289; .•o¤[‹‡•es "tlrpbhmu"; ŽDýes 10201; •δ~¬]•es 1119188999; Ž\nÿes 19889.

Kevin Cruijssen
fuente