In the United States, the two opposing directions of traffic on a road are separated by a dashed yellow line if passing is allowed and two solid yellow lines if passing is not allowed. (Just one side can be dashed to allow passing on that side, and yellow lines can mean other things like center or reversible lanes, but we aren't concerned with any of those cases.)

Write a program that takes in a run-length encoded string of P for passing and N for no passing, and prints an ASCII version of the corresponding road. Except for the center line, the road always has the same pattern, which can be easily inferred from the examples below.

There will be a positive decimal number before each P and N in the input string. This number defines the length of the passing or no passing region of the current part of the road.

### Examples

An input of 12N would produce 12 columns of no passing road (center line all =):

____________

============

____________


An input of 12P would produce 12 columns of passing road (center line -  repeating):

____________

- - - - - -

____________


Passing and no passing can then be combined, e.g. 4N4P9N7P1N1P2N2P would produce:

______________________________

====- - =========- - - -=-==-

______________________________


These are 4 no passing columns, then 4 passing, then 9 no passing, etc.

Note that a passing zone always starts with a dash (-) on the leftmost side, not a space ( ). This is required.

### Details

• The input will never have two N zones or two P zones in a row. e.g. 4P5P will never occur.
• You don't need to support letters without a leading positive number. Plain P will always be 1P, plain N will always be 1N.
• There may be trailing spaces as long as they do not extend beyond the final column of the road. There may be one optional trailing newline.
• Instead of a program, you may write a function that takes in the run-length encoded string and prints or returns the ASCII road.
• Takes input in any standard way (stdin, command line, function arg).

The shortest code in bytes wins. Tiebreaker is earlier post.

• Does the road have to be asymmetrical, or is it allowed to print 4 spaces of road on each side of the line?
– orlp
Apr 27 '15 at 13:09
• @orlp If you're asking if the road can be wider than 5 rows, then no. If you're asking if space characters can be put in the empty lines above or below the center line, then yes as long as they hold with detail bullet 3. Apr 27 '15 at 14:36
• Let me ask by example, is either of these a valid output? gist.github.com/orlp/0e0eae16d6e1fcda5e9b
– orlp
Apr 27 '15 at 14:43
• @orlp Neither is. Apr 27 '15 at 14:47

# JavaScript (ES6), 114

Using template strings, the 5 linefeeds are significant are must be counted.

f=s=>(b=(s=s.replace(/(\d+)(.)/g,(x,n,b)=>(b<'P'?'=':'- ').repeat(n).slice(0,n))).replace(/./g,'_'))+

${s} +b  # CJam, 38 bytes "_ - _":N3'=t:P;q~]2/e~z' *"--"/"- "*  How it works We first assign the correct road column to variables N and P and then simply evaluate the input string. This leaves a pair of the length and the column on stack. We group them up, run an RLD on it to get the full columns, transpose to join them and then finally, convert the continuous -- to - . :_ - _":N e# This is the no passing column. We assign it to N 3'=t:P e# Replace the '-' in N with '=" and assign it to P q~]2/ e# Read the input, evaluate it and then group it in pairs e~ e# Run a run-length-decoder on the pairs z' * e# Transpose and join with new lines. "--"/ e# Split on two continuous occurrence of - "- "* e# Join by an alternate "- "  Try it online here # rs, 252 chars Although this might not count because I added the convergence operator as a ripoff of Martin Büttner's Retina an hour ago...I'm not really here to compete anyway. It's just fun making a regex-based solution for this. (\d+\D)/#\1 +(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)(?=\d*\D)/\1\1\1\1\1\1\1\1\1\1\2\3\4\5\6\7\8\9\10# \d(?=\d*#N)/= (^|(?<=\D))\d(?=\d*#P)/- +(?<=-)\d\d(?=\d*#P)/ - (?<=-)\d(?=\d*#P)/ #\D/ ((?:(=|-| ))+)/A\1\n\n\n\1\n\nA\1\n +(A_*)(.)/\1_ A/  I got line 2 from Martin's Retina answer for Programming Languages Through the Years. ## Explanation (\d+\D)/#\1 +(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)(?=\d*\D)/\1\1\1\1\1\1\1\1\1\1\2\3\4\5\6\7\8\9\10#  This does lots of magic. See the answer I linked above for more info. Basically, with the input 4N4P9N7P1N1P2N2P, this will be the result: 4444#N4444#P999999999#N7777777#P1#N1#P22#N22#P  Next: \d(?=\d*#N)/=  This replaces the numbers preceding the no-passing symbol (N) with the equal signs. The result with the previous input: ====#N4444#P=========#N7777777#P=#N1#P==#N22#P  This: (^|(?<=\D))\d(?=\d*#P)/-  replaces the first number preceding a passing symbol (P) with the first dash. The result: ====#N-444#P=========#N-777777#P=#N-#P==#N-2#P  The next two lines continue the same pattern: +(?<=-)\d\d(?=\d*#P)/ - (?<=-)\d(?=\d*#P)/  The first line replaces the rest of the line with the dash-space pattern. The second one handles an odd number; it replaces the last dash followed by a single integer (such as -5) with a dash-space (-). Now, the output is: ====#N- - #P=========#N- - - -#P=#N-#P==#N- #P  Now things are starting to fall into place. The next line: #\D/  just removes the #N and #P. ((?:(=|-| ))+)/A\1\n\n\n\1\n\nA\1\n +(A_*)(.)/\1_  set up the underscores on the top and bottom to give: A______________________________ ====- - =========- - - -=-==- A______________________________  Lastly, we remove the A: A/  ## Python 2, 136 bytes Surprisingly, importing re seems to be actually worthwhile here. import re s="" for x,y in re.findall("(\d+)(.)",input()):s+=(("- ","==")[y=="N"]*int(x))[:int(x)] t="_"*len(s);print t+"\n"*3+s+"\n"*2+t  # Python 3, 169 168 bytes. (167 with Python 2) p,s='',str.split for _ in s('N '.join(s('P '.join(s(input(),'P')),'N'))): v=int(_[:-1]);p+=['='*v,('- '*v)[:v]][_[-1]=='P'] l=len(p) u='_'*l print(u+'\n'*3+p+'\n\n'+u)  Fairly ungolfed: p='' for i in'N '.join('P '.join(input().split('P')).split('N')).split(): v=int(i[:-1]) # Get the number from the input section if i[-1]=='N': # Check the letter (last char) from the input section p+=('='*v) # Repeat = the number from input (v) else: p+=('- '*v)[:v] #Repeat -  v times, then take first v chars (half) l=len(p) #Get the length of the final line markings print('_'*l+'\n\n\n'+p+'\n\n'+'_'*l)  print('_'*l # Print _ repeated the length of p +'\n\n\n' # 3 new lines +p+ # print out p (the markings) '\n\n' # 2 new lines +'_'*l) # Print _ repeated the length of p  for i in 'N '.join( 'P '.join( input().split('P')) .split('N')) .split(): # Split the input into items of list at P # Join together with P and ' ' # Split at N... # Join with N and ' ' # Split at space # Loop through produced list  Try it online here. • You forgot to update your byte count. Apr 27 '15 at 20:15 • @mbomb007 It didn't change the count :/ I can't get it below 169 atm – Tim Apr 27 '15 at 20:16 • Putting p+=['='*v,('- '*v)[:v]][_[-1]=='P'] at the end of the previous line with a preceding semicolon saves one byte. Apr 27 '15 at 20:18 • Also, using Python 2 instead saves 1 byte on the print. Apr 27 '15 at 20:25 • @mbomb007 added them in :) I have a feeling python 2 it may be even shorter... But I'm not sure. – Tim Apr 27 '15 at 20:26 # Haskell, 165 bytes k 'N'="=" k _="- " d c=c>'/'&&c<':' p[]=[] p s=take(read$takeWhile d s)(cycle$k a)++p r where(a:r)=dropWhile d s f s=unlines[q,"\n",p s,"",q]where q=map(\x->'_')$p s


Example run (f returns a string, so for better display print it):

*Main> putStr $f "4N4P9N7P1N1P2N2P" ______________________________ ====- - =========- - - -=-==- ______________________________  How it works: p returns the middle line by recursively parsing the input string and concatenating the given number of symbols found by the lookup function k. The main function f joins a five element list with newlines, consisting of the top line (every char of the middle line replaced by _), a newline, the middle line, an empty line and the bottom line (same as top). # PHP, 187 bytes preg_match_all('/(\d+)(\w)/',$argv,$m,2);$o='';
foreach($m as$p)
$o.=str_replace('--','- ',str_repeat($p<'P'?'=':'-',$p));$a=preg_replace('/./','_',$o); echo("$a\n\n\n$o\n\n$a\n");


The code can stay on a single line; it is displayed here on multiple lines to be more readable (the whitespaces and newlines used for formatting were not counted).

Two bytes can be saved by not printing the trailing newline. Five more bytes can be saved by using real newline characters on the echo():

echo("$a$o

$a");  Six additional bytes can be saved by omitting the initialization of $o ($o='';) but this will trigger a notice. The notice can be suppressed by running the script using the command line: $ php -d error_reporting=0 <script_name> 4N4P9N7P1N1P2N2P


These brings it to 174 bytes.

# Ruby, 137 135 bytes

Not the shortest I could come up with, but close to the nicest. Partly borrowed from Optimizer's answer.

require'scanf'
N='_  = _'
P='_  - _'
a=[]
scanf('%d%c'){|l,t|a+=[eval(t).chars]*l}
puts (a.shift.zip(*a).map(&:join)*?\n).gsub'--','- '


Ungolfed:

require 'scanf'

N = '_  = _'
P = '_  - _'
columns = [] # array of columns
# scan stdin for a number followed by a single char
scanf('%d%c') do |length, type|
columns += [eval(type).chars] * length
done

# Convert to an array of rows, and join into a string
rows = columns.shift.zip(*columns).map(&:join)
str = rows * "\n" # join lines

# Replace '--' by '- ' and print
puts str.gsub(/--/, '- ')

• You should be able to improve this by 2 bytes (and beat the python 2 answer) by changing the last line to (a.shift.zip(*a).map(&:join)*?\n).gsub'--','- '. May 2 '15 at 22:26

# 05AB1E, 35 34 bytes

.γa}2ôε„PN…- =2ä‡s∍}J©¶ĆìĆ'_®∍DŠ»


Explanation:

.γ                # Consecutive group the (implicit) input by:
a               #  Check if the character is a letter
}2ô            # After the group by: split it into parts of size 2
ε                 # Map each pair of integer + letter to:
#  Pop and push them separated to the stack
„PN             #  Push string "PN"
…- =         #  Push string "- ="
2ä       #  Split it into 2 parts: ["- ","="]
‡      #  Transliterate the "P" to "- " and "N" to "="
s     #  Swap to take the integer value
∍    #  Extend (or shorten) the string to that length
}J  # After the map: join all parts together to a single string
© # And store it in variable ® (without popping)
¶                 # Push a newline character "\n"
Ć                # Double it "\n\n"
ì               # Prepend it in front of the string
Ć              # Enclose the string, appending it's own first character
'_               '# Push string "_"
®∍              # Extend it to a size equal to the length of string ®
D             # Duplicate it
Š            # Triple swap the three values on the stack from a,b,c to c,a,b
»           # Join the values on the stack with newline delimiter
# (after which the result is output implicitly)


# Ruby, 94 bytes

Borrows the gsub'--','- ' idea from 14mRh4X0r's answer. I think that answer is more interesting, though, although this is shorter.

f=->x{n=?_*x.gsub!(/(\d+)(.)/){($2==?P??-:?=)*$1.to_i}.size
"#{n}

#{x.gsub'--','- '}

#{n}"}


Testing:

f=->x{n=?_*x.gsub!(/(\d+)(.)/){($2==?P??-:?=)*$1.to_i}.size
"#{n}

#{x.gsub'--','- '}

#{n}"}

puts f['4N4P9N7P1N1P2N2P']


Produces:

______________________________

====- - =========- - - -=-==-

______________________________


let me include my matlab version

## MATLAB (267 b)

function d=p(V,a),j=numel(V)-1;if (a==0),d=0;return; end,d=(V(a)-48+10*p(V,a-1))*(V(a)<64);fprintf('%c%.*s%c%.*s',(a>=j)*10,(a==j|a==1)*eval(strcat(regexprep(V,'[NP]','+'),48)),ones(99)*'_',(a<3)*10,(V(a+1)>64)*d,repmat((V(a+1)==78)*'=='+(V(a+1)==80)*'- ',[1 99]));end


## input

An ascii-formatted string tailed by a space (since there is no end of chain '\0' in matlab

example V='12N13P '

## output

_________________________

============- - - - - - -

_________________________


## function

the function must be called from its tail-1 (the empty character is removed)

example : p(V,numel(V)-1)

## Simulation

try it online here

# R, 132 bytes

Not greatly happy with this, but it was a bit of fun to do:) Tried to get rid of the multiple gsubs, but my efforts were in vain. I suspect there's a much better way to do this.

cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')))))),substring(a,1,1)),sep='')

• scan gets the strings from STDIN and grabs the 4th one. Note that the empty lines require a space (or something) in them for scan to carry on getting the input.

"====- - =========- - - -=-==- "

• It replaces the =s with Ns, the - and with Ps.

"NNNNPPPPNNNNNNNNNPPPPPPPNPNNPP"

• Then it inserts a space between each NP and PN

"NNNN PPPP NNNNNNNNN PPPPPPP N P NN PP"

• The scan splits the string on spaces

"NNNN" "PPPP" "NNNNNNNNN" "PPPPPPP" "N" "P" "NN" "PP"

• The string length is then bound(rbind) with the first character of each string

4 4 9 7 1 1 2 2
"N" "P" "N" "P" "N" "P" "N" "P"

• The array is then output using cat.

Test run

cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')))))),substring(a,1,1)),sep='')
1: ____________
2:
3:
4: ============
5:
6: ____________
7:
12N
>
> cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')))))),substring(a,1,1)),sep='')
1: ____________
2:
3:
4: - - - - - -
5:
6: ____________
7:
12P
> cat(rbind(nchar(a<-scan(,'',t=gsub('PN','P N',gsub('NP','N P',chartr('- =','PPN',scan(,'',sep='|')))))),substring(a,1,1)),sep='')
1: ______________________________
2:
3:
4: ====- - =========- - - -=-==-
5:
6: ______________________________
7:
4N4P9N7P1N1P2N2P


# C, 155 153 bytes

−2 bytes thanks to ceilingcat

l=6;main(k,v,n,x,s,c)char*s,**v,c;{for(;l--;puts(s))for(s=v;*s;s+=k)for(x=sscanf(s,"%d%c%n",&n,&c,&k);n--;)putchar(" -=_"[l%5?l^2?0:c^78?++x&1:2:3]);}


main(l,v,k,n,x,s,c)
char*s,**v,c;
{
for(l=6;l--;puts(s))
for(s=v;*s;s+=k)
for(x=sscanf(s,"%d%c%n",&n,&c,&k);n--;)
putchar(l%5?l^2?32:c^78?++x&1?45:32:61:95);
}


The outer loop counts lines from 5 to 0.

The middle loop iterates over parts of the encoded string:

4N4P9N7P1N1P2N2P
4P9N7P1N1P2N2P
9N7P1N1P2N2P
7P1N1P2N2P
1N1P2N2P
1P2N2P
2N2P
2P
string is empty - exit


The inner loop decodes a part, like, 7P, and iterates the needed number of times (e.g. 7).

Each iteration prints one char. The value of the char is described by the code " -=_"[l%5?l^2?0:c^78?++x&1:2:3]:

• If line number is 5 or 0, print _
• Otherwise, if line number is not equal to 2, print a space
• Otherwise, if the symbol is 'N', print =
• Otherwise, increase x by 1 (it was initialized to 2 by sscanf)
• If odd, print -, else print a space

# Japt v2.0a0, 302928 29 bytes

Takes input in lowercase, prepend v<space> for +2 bytes if that's not allowed. Had to sacrifice a byte to fix a bug with inputs that contained a 0 :\

ò!Í®n îZèÍg"- ="òÃ¬yÈû4 Ôû6'_


Try it

ò!Í®n îZèÍg"- ="òÃ¬yÈû4 Ôû6'_     :Implicit input of string
ò!Í                               :Partition into the run length groups we need (See more detailed explanation below)
®                              :Map each Z
n                             :   Convert to integer (the letter at the end is ignored)
î                           :   Repeat and slice to that length
Zè                         :     Count the occurrences in Z of
Í                        :     "n" (see below for the why)
g                       :     Index into
"- ="ò                 :     Partitions of "- =" of length 2
Ã                :End map
¬               :Join
y              :Transpose
È             :Pass each row through the following function and transpose back
û4           :   Centre pad with spaces to length 4
Ô         :   Reverse ('cause centre padding is right-biased)
û6'_     :   Centre pad with "_" to length 6


OK, I finally (think I) figured out how the partitioning is working! First the basics: The ò method partitions string between pairs of characters (X & Y) that return a truthy value when run through the method that's passed as an argument. We're using Í here, which is the shortcut for n2<space>. The space is used to close the ò method and the n and the 2 being split into two separate arguments, with the second being ignored as ò only expects one argument. That means that we're currently testing XnY but, by adding the !, the elements get flipped giving us YnX.

And now for the trickery: The possible combinations we can have (where L=[np] & D=[0-9]) are DnL, LnD & DnD and, in all cases, both elements are strings, which is important. The n attempts to convert Y to an integer, run X on it as a method and convert it back to a string, with the following possible outcomes:

• Dnp squares the integer resulting in a non-empty string, which is truthy, creating a partition.
• Dnn negates the integer resulting in a non-empty string, which is truthy, creating a partition.
• DnD & LnD, for some reason that I can't figure out, both result in 0, which is falsey, so no partition is created.

Hopefully, that all made some sort of sense but, if it helps, here's a handy table.

And, as a final note: the Í works exactly the same way as above when passed to the è method, which only expects a single string argument.

• +1 for not understanding what your code is doing at all. Oct 30 '20 at 12:56
• Figured it out, @Razetime; see updated explanation. My confusion was coming from the ! causing the n method to behave differently when passed to the ò method, barring just flipping the arguments. I eventually had to build a huge truth table of all the things that could possibly be happening to help me figure it out! Oct 30 '20 at 16:45

(s:String)=>{val r=(("\\d+(P|N)"r) findAllIn(s) map(r=>{val l=r.init.toInt;if(r.last=='N')"="*l else ("- "*l).take(l)})).mkString;val k="_"*r.length;s"$k\n\n\n$r\n\n$k"}  First try, might be golfed some more. # Perl 5-pl, 64 bytes y/PN/-=/;s/\d+(.)/$1x$&/ge;s/--/- /g;$_=($t=y//_/cr)."$_

$t"  Try it online! # APL (Dyalog Extended), 89 bytes {,⌿{⍪(⌽,2∘↓∘⊢)⍵,' _'}¨⍪⍎¯1↓('\d+'⎕R{'(',⍵.Match})('[P]' '[N]'⎕R'⍴''- ''),' '⍴''=''),')⍵}  Try it online! A huge, clunky solution with a lot of regex and ⍎. ## Explanation ('[P]' '[N]'⎕R'⍴''- ''),' '⍴''=''),')⍵ Replace N with code for producing '=' and P for producing '- ' with a closing bracket ('\d+'⎕R{'(',⍵.Match}) prepend an opening bracket to each digit ('\d+'⎕R{'(',⍵.Match}) ⍎¯1↓ drop the last character, and execute (gives the road markings) ⍪ table it ⍵,' _'}¨ add two spaces and underscore for each marking ⍪(⌽,2∘↓∘⊢) Palindromize that, table it ,⌿ join all the columns into a single road # Vyxal, 44 bytes \d+[NP]λṫC₃- ==½$i$I*½h;øṙ:L\_*…¤…,$,¤,…


Try it Online!

Uses regex.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8269404,"math_prob":0.93473834,"size":2058,"snap":"2021-43-2021-49","text_gpt3_token_len":485,"char_repetition_ratio":0.16212268,"word_repetition_ratio":0.010958904,"special_character_ratio":0.29446065,"punctuation_ratio":0.1056701,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9908361,"pos_list":[0,1,2],"im_url_duplicate_count":[null,8,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-11-28T08:55:43Z\",\"WARC-Record-ID\":\"<urn:uuid:7da2e340-2876-4dd4-b0d3-fabcb7ecd922>\",\"Content-Length\":\"328613\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:689c18a5-8ba5-4358-9ebd-149456c1ac3c>\",\"WARC-Concurrent-To\":\"<urn:uuid:883b17ce-7a6e-4ce3-bda1-48126f1b63e9>\",\"WARC-IP-Address\":\"151.101.1.69\",\"WARC-Target-URI\":\"https://codegolf.stackexchange.com/questions/49307/road-length-encoding?noredirect=1\",\"WARC-Payload-Digest\":\"sha1:CU2W77FMYCODEQJFZH5JN7SCIXVGG337\",\"WARC-Block-Digest\":\"sha1:7MMYMMEKX6CYPHNRXFIJ4YF7RVAG5PZM\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-49/CC-MAIN-2021-49_segments_1637964358480.10_warc_CC-MAIN-20211128073830-20211128103830-00071.warc.gz\"}"}