12
\$\begingroup\$

Given two parameters lane pattern and road length, print an ASCII representation of the lane markings for Roads and Traffic Service to paint the roads.

Example input/output

Input: BTHMLRPHU, 21

I don't care if you take two parameters or concatenate the number onto the end of the string, it's unambiguous.

Input may be taken from STDIN, as a function argument, environment variables, whatever makes sense in your language.

Output:

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

Each character denotes 0.5 metres in width and one kilometre in length.

Specification

Lane markings

For every 10 km stretch of road, markings are painted at kilometres 2, 3, 9 and 10 (from the "top" of the output). Markings are centred in the lane. With the exception of the bike lane and median, all lanes are 3 metres (6 characters) wide.

ASCII diamond and arrow characters are not permitted in lieu of the markings as indicated in the example output.

  • B: Bike lane. B marking. 1.5 metres (3 characters) wide.
  • T: Transit. Diamond marking
  • H: High-occupancy vehicle lane. HOV3 marking
  • L and R: Turning lane. Arrow marking
  • P: Passing lane. Caret markings
  • U: Unrestricted lane. No markings

Separators (in order of precedence)

  • Median: ## (denoted by M in the input string, replaces any other separator including ditch)
  • Ditch (extreme left and extreme right): ! Exclamation mark
  • HOV lanes alternate between x and | every 5 km
  • Normal: |

Constraints

Your function or program must:

  • Print to STDOUT (this means equivalents of System.out.print for Java, console.log for JavaScript, etc.)
  • Be able to print 1 - 9 lanes with 0 - 10 medians
  • Be able to print up to 50 km of roadway (50 lines of output)
  • Not use any standard loopholes
  • Trailing white space is not acceptable with the exception of an optional \n at the end of the output

Largest possible output: 3700 bytes (74 characters * 50 lines).

Smallest possible output: 5 bytes (with input B, 1)

Assumptions

  • No adjacent medians (substring MM will not occur)
  • The second line of markings might be cut off (for example if the length is 9 or 12 km)
  • Lanes may not logically make sense (any order is possible, for example a right turn lane on the left of the road)

This is , so shortest code (in bytes) wins!

\$\endgroup\$
  • 1
    \$\begingroup\$ And there, you loves monospaced fonts \$\endgroup\$ – WayToDoor Aug 20 '15 at 6:53
4
\$\begingroup\$

Ruby, 245

Print the lane divides if relevant, then print the lane.

I don't expect to win.

->(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 choke stderr and split arrays effectively.

263 better way to index array

268 just print each line, don't calculate a canonical version.

330 initial commit

\$\endgroup\$
  • \$\begingroup\$ I wouldn't expect Ruby to win either but if there aren't any other answers within the next week then I guess you win :-P On a second note is there anywhere I can test this without installing Ruby on my computer? \$\endgroup\$ – rink.attendant.6 Aug 21 '15 at 23:55
  • \$\begingroup\$ @rink.attendant.6 ideone.com \$\endgroup\$ – Not that Charles Aug 23 '15 at 2:38
2
\$\begingroup\$

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

Demo

It should work in Firefox and Edge at time of writing, Chrome/Opera require experimental features to be enabled.

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>

\$\endgroup\$
1
\$\begingroup\$

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»

Pretty bad approach, but it works and was fun to make. Can definitely be golfed some more, though.

+1 byte as bug-fix for two adjacent HH lanes.

Try it online.

Explanation:

Step 1: Create all possible lanes with size 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

Step 2: Convert the input-string to indices (which we're going to use to index into the list we created in step 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

Step 3: we use those indices to index into the list of lanes. And then we convert those list of lanes to the correct output, including extending/shortening them to the size of the integer-input:

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

See this 05AB1E tip of mine (sections How to compress strings not part of the dictionary? and How to compress large integers?) to understand why Ž5E is 1289; .•o¤[‹‡• is "tlrpbhmu"; ŽDý is 10201; •δ~¬]• is 1119188999; Ž\nÿ is 19889.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.