text:
Leibniz golf in C#
I'm starting with golf code. But im only do C# so I know wont be a breaking record, but I want give it a try. Leibniz
Challenge is here
The first line contains the number of test cases (N) which is less than 100. Each additional line is a test case for a positive integer value (T) less than 10^7.
I format the code to easy the reading, removing spaces I reduce it to 210 chars.
The best code submit for this problem is 54 char, but For C# lenguaje the best is 172 chars.
My guess is should remove reading the N, but couldn't make it stop properly.
using System;
class S
{
    static void Main()
    {
        int n=Convert.ToInt32(Console.ReadLine()),i=0;
        for (;i++<n;)
        {
            double r=0,t=Convert.ToInt32(Console.ReadLine()),j=0;
            for(;j<t;)
                r+=(1-j%2*2)/(2*j+++1);
            Console.WriteLine(r);
        }
    }
}

NOTE
Mono C# compiler 3.2.8.0 .NET 4.0 CLR
So using C=System.Console doesn't work.

This isn't an appropriate question for this site. Questions here are challenges for people to compete on (and a few other things like language tips). If you need help, submit your code as an answer to the challenge, and ask for help in the comments of your answer.

@Sparr this is an old challenge, you can see this question was already here for Python. http://codegolf.stackexchange.com/questions/10716/solve-the-codesprint4-leibniz-code-golf-challenge-in-python-in-66-characters , and is +2 years old, same challenge I just ask for a diferent lenguaje. Im not trying to get any prize, just trying to learn.

@Sparr Asking for golfing advice is definitely on topic, and has been officially for almost a year. Also see the help centre.

It's not clear to me whether you want help golfing the code in the question or solving the Hacker Rank challenge. The code in the question doesn't meet the spec for the Hacker Rank challenge. Consider e.g. that the correct output for 100000 is 0.785395663397448.

@PeterTaylor My request is for help golfing the code, especially the first FOR and try reading the number of cases. But you are right for that case doesn't work. As I say in the description Im new with this and I considere my program correct because pass the test case. Didnt consider have to try all the cases by myself. Do you think this is because a wrong data type, or is something wrong with my code logic?

It's a logic problem. One of the basic rules of applied numerical analysis is that when adding a list you should process the numbers in order of increasing absolute value.

So should I run the calculation in inverse order?

@PeterTaylor, I invert the order of calculation and for 100000 now i got 0.785400663372449 need to polish a litle bit more.

As I suggested in a comment on VisualMelon's answer, the second for loop is being underutilised. By changing some variable scopes it's possible to use the fors in such a way that we save one set of curly brackets and one variable, and perform the sum in the correct order, fixing the bug in the supplied code.
Golfed:
using C=System.Console;class S{static void Main(){for(double n=int.Parse(C.ReadLine()),r,t;n-->0;C.WriteLine(r))for(r=0,t=2*int.Parse(C.ReadLine());t>0;t--)r-=(1-t%4)/--t;}}

Online demo
Ungolfed:
using C = System.Console;
class S {
    static void Main() {
        for (double n=int.Parse(C.ReadLine()), r, t; n-- > 0; C.WriteLine(r))
            for (r=0, t=2*int.Parse(C.ReadLine()); t>0; t--)
                r -= (1-t%4) / --t;
    }
}

I've heard that a double can perfectly represent an Int32, but I never quite believed it (too lazy to find a good source more than anything else), I was holding back on suggesting collapsing t/j as well, this is considerably better than my job.

A double can perfectly represent any integer up to 2^51 or 2^52 (can't quite remember offhand and don't feel like looking it up).

Setting all variables and printing result in the same for very cleaver. But you lose me on the second for. You move the 2* to t assignment and then you have t-- and --t. I think i will have to run it step by step to see what is doing.

Couple of simple things that apply in lots of places:

You've got a free semi-colon in your first for loop which you can make use of
You keep track of i against n, but you as you never use the value of n, you can use it as the counter itself.
As someone else said, you can use int.Parse (or double.Parse) instead of the Convert namespace/class/whatever it is - this makes your using System directive less helpful, and you are better of using the classic using C=System.Console (unless C# 6 has come out, I can't say I'm sure, in which case you can using System.Console directly)
There is an unneeded space after the first for (not sure if you'd accounted for this or not)

I haven't tested this code, but hopefully it will at least help:
using C=System.Console; // 3

class S
{
    static void Main()
    {
        for(int n=int.Parse(C.ReadLine()); // 1, 3, 4
            n-->0;) // 2
        {
            double r=0,t=int.Parse(C.ReadLine()),j=0; // 3
            for(;j<t;)
                r+=(1-j%2*2)/(2*j+++1);
            C.WriteLine(r); // 3
        }
    }
}

Is it possible that the shorter C# solution disregards the first line, and just assumes the input is clean? May well be cheaper to do that if it is allowed.
This is just a quick reply, I might have a better bash at this tomorrow when I have less going on.

Point 1 applies to the second for loop too.

@PeterTaylor unfortunately it doesn't seem to pay to move the doubles outside of the for loop, and you need access to r below (which you don't have if you define it in the for loop initial expression)

Yes, That part I try putting the variable inside the loop and couldnt access outside.

Looks like I cant use using C=System.Console; Say `System.Console' is a type not a namespace

There's no reason why n can't be a double... See my answer.

@JuanCarlosOropeza that's irritating, I wonder if it's an ancient version of C# or something (or maybe it's mono and it does more than reject perfectly valid uses of goto). In that case, I have a one-byte longer version without it (I'll write this up properly some other time): using System;class S{static void Main(){Func<int>L=()=>int.Parse(Console.ReadLine());for(int n=L();n-->0;){double r=0,t=L(),j=0;for(;j<t;)r+=(1-j%2*2)/(2*j+++1);Console.WriteLine(r);}}

You are right Mono C# compiler 3.2.8.0 .NET 4.0 CLR. But dont worry about it, I learn a lot. Thanks

Instead of Convert.ToInt32, use int.Parse; it saves a few characters.
Unless you really need a double, use a float; it's one char shorter than double.

Thanks, I was using Math.power() that is why I need double, but i replace it for r+=(1-j%2*2), so no need it anymore.

I went back to double, Need 15 decimals precision. :(

172 Characters
The permanent version of the challenge can be found here. I have the shortest solution for C#, which is 172 characters.
Golfed
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n,j;;){for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;){s+=(j%2<1?1:-1)/(2*j+++1);}R.WriteLine(s);}}}

Ungolfed
using R=System.Console;
class C
{
    static void Main()
    {
        R.ReadLine();
        for(double s,n,j;;)
        {
            for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)
            {
                s+=(j%2<1?1:-1)/(2*j+++1);
            }
            R.WriteLine(s);
        }
    }
}

It does error out on the last loop, but it's after outputting all test cases.
Edit
Seeing it ungolfed like this, just realized I can inline the for loop.
170 characters
Golfed
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n,j;;){for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)s+=(j%2<1?1:-1)/(2*j+++1);R.WriteLine(s);}}}

Ungolfed
using R=System.Console;
class C
{
    static void Main()
    {
        R.ReadLine();
        for(double s,n,j;;)
        {
            for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)
                s+=(j%2<1?1:-1)/(2*j+++1);
            R.WriteLine(s);
        }
    }
}

Edit 2
@PeterTaylor's answer has some fantastic logic. Cleaned it up a bit, and I'm still using exceptions for control flow.
155 characters
Golfed
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n;;R.WriteLine(s))for(s=0,n=2*int.Parse(R.ReadLine());n>0;n--)s-=(1-n%4)/--n;}}

Ungolfed
using R = System.Console;
class C
{
    static void Main()
    {
        R.ReadLine();
        for(double s, n;; R.WriteLine(s))
            for(s = 0, n = 2 * int.Parse(R.ReadLine()); n > 0; n--)
                s -= (1 - n % 4) / --n;
    }
}

I really wish I could get rid of the extra ReadLine().


text:
Binary Images of Triangle Counts
My challenges tend to be a little bit hard and unattractive. So here something easy and fun.
Alcuin's sequence
Alcuin's sequence A(n) is defined by counting triangles. A(n) is the number of triangles with integer sides and perimeter n. This sequence is called after Alcuin of York.
The first few elements of this sequence, starting with n = 0 are:
0, 0, 0, 1, 0, 1, 1, 2, 1, 3, 2, 4, 3, 5, 4, 7, 5, 8, 7, 10, 8, ...

For instance A(9) = 3, because the only triangles with integer sides and perimeter 9 are 1 - 4 - 4, 3 - 3 - 3 and 2 - 3 - 4. You can see the 3 valid triangles down below.

There are some quite interesting pattern in this sequence. For instance A(2*k) = A(2*k - 3).
For more information, see A005044 on OEIS.
Challenge
But your challenge is about the binary representation of these numbers. If we convert each sequence number to it's binary representation, put them in column vectors and line them up, it creates a quite interesting binary picture.
In the following picture you can see the binary representation of the sequence numbers A(0), A(1), ..., A(149). In the first column you can see the binary representation of A(1), in the second column the representation of A(1), and so on.

You can see some sort of repeating pattern in this picture. It even looks kinda like fractals, if you look for instance at the image with the sequence numbers A(600), A(601), ..., A(899).

Your job is to generate such an image. Your function, your script will receive two integer 0 <= m < n, and it has to generate the binary image of Alcuin's sequence A(m), A(m+1), A(m+2), ..., A(n-2), A(n-1). So the input 0, 150 generates the first picture, the input 600, 900 the second picture.
You can use any popular graphics format you want. Let's say every format that can be converted to png using image.online-convert.com. Alternatively, you may display the image on screen. No leading white rows are allowed!
This is code-golf. So the shortest code (in bytes) wins.

Eh, I was interested in doing this challenge until I got to the part about creating a binary image. It seems like an extraneous step. I don't feel like learning a library for image creation in Python, and I expect that if I did, there wouldn't be much to golf.

@xnor: Then use some simple image format like PBM.

Is it white=1 and black=0 or the other way around?

@Maltysen white=0 and black=1. So the other way. A(0) produces a white column, A(9)=3 produces a white column with 2 black pixel at the bottom.

Is A(2*k) = A(2*k - 3) a typo? Wouldn't that mean that the sequence would be periodic with period 3?

@MartinBüttner Nope, k has to be an integer. Therefore A(6) = A(3) but A(6) != A(9). But be aware that this little fact has nothing to do with the challenge at all.

@Jakube Oh, I see. That makes sense.

Are you sure the first image is correct? It has 0,0,0,1,0,2 while the list at the beginning of the question says 0,0,0,1,0,1.

@Maltysen Your right. Had a little bug in my own program. Replaced them with correct images now.

Should the "pixels" be 1 pixel sized and rectangular?

J (52 45 (Codepage 437))
This would be allowed (I think)
[:|:' █'{~[:#:[:([:<.48%~*:+24+6*]*2|])(}.i.)

Hex dump
(Nothing special really, the black square is DB16 or 21910 in codepage 437.)
0000: 5b 3a 7c 3a 27 20 db 27 7b 7e 5b 3a 23 3a 5b 3a   [:|:' .'{~[:#:[:
0010: 28 5b 3a 3c 2e 34 38 25 7e 2a 3a 2b 32 34 2b 36   ([:<.48%~*:+24+6
0020: 2a 5d 2a 32 7c 5d 29 28 7d 2e 69 2e 29            *]*2|])(}.i.)

Usage
This outputs as follows (The code tags mess it up by adding space between the lines):
   A=:[:|:' █'{~[:#:[:([:<.48%~*:+24+6*]*2|])(}.i.)
   0 A 100
                                                                             █ █████████████████████
                                                     █ ██████████████████████ █              █ █████
                                     █ ██████████████ █          █ ██████████ █      █ ██████ █
                         █ ██████████ █      █ ██████ █    █ ████ █    █ ████ █  █ ██ █  █ ██ █  █ █
                 █ ██████ █    █ ████ █  █ ██ █  █ ██ █  █  █  █  █  █  ██ ██ ██  ██  ██  ██  ██  ██
           █ ████ █  █ ██ █  █  █  █  ██  ██  ██  ██  ██  █  █  █  █ ██ █  █ ████ █
       █ ██ █  █  ██  ██  ██  █  █ ██ █                █ ██ █  █  ██  ██  ██  █  █ ██ █
   █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █
   2000 A 2100
████████████████████████████████████████████████████████████████████████████████████████████████████

████████████████████████████████████████████████████████████████████████████████████████████████████
                                                                             █ █████████████████████
                             █ ██████████████████████████████████████████████ █
     █ ██████████████████████ █                      █ ██████████████████████ █
█████ █          █ ██████████ █          █ ██████████ █          █ ██████████ █          █ █████████
 ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ███
█  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █
██  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █ ██ ██ █
 █ ██ ██ ██ ██ ██ █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  ██ ██ ██ ██ ██  █  █
  ██ ██ ██  █  █  ██ ██ ██  █  █  █  █  █  █  █  █  █  █  █  █  █  █ ██ ██ ██ █  █  █  █ ██ █  █ ██
 █ ██ █  █ ██ █  █ ██ █  █ ██ █  █  █  █  █  █  █  █  █  █  ██ ██ ██  █  █  ██  ██ ██ ██  ██  ██  ██
  ██  ██  ██  ██  ██  ██  ██  ██ ██ ██  █  █  █  █  █  █ ██ █  █ ██ █  █ ████ █    █ ██████ █
█ █                        █ ████ █  █ ██ █  █  █  █  ██  ██  ██  ██  ██  █  █  █  █ ██ █  █ ████ █
 █ ██ █                █ ██ █  █  ██  ██  ██  █  █ ██ █                █ ██ █  █  ██  ██  ██  █  █ █
██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██

In the standard J console, there is no spacing between lines, so I call the rule 'Alternatively, you may display the image on screen.' (Nowhere did it say that this image had to be represented as a sensible image format internally)
EDIT: Jconsole (as opposed to JQT) uses codepage 437 as a default, and DOES render the rectangles correctly when using them from a string.

Mathematica, 126 122 121 89 bytes
Image[1-Thread@IntegerDigits[l=Round[(#+3#~Mod~2)^2/48]&/@Range@##,2,⌈2~Log~Max@l⌉]]&

This defines an unnamed function taking the two integers as parameters and displaying the image on screen. It plots each square as a single pixel, but if you like you can actually zoom in.
I'm now using an explicit formula given in the OEIS article (first one in the Mathematica section, thanks to David Carraher for pointing that out). It's also blazingly fast now.
Here is the indented code with a few comments:
Image[1-Thread@IntegerDigits[   (* 3. Convert each number to padded binary, transpose
                                      invert colours, and render as Image. *)
    l = Round[
      (#+3#~Mod~2)^2/48
    ] & /@ Range@##,            (* 1. Turn input into a range and get the Alcuin
                                      number for each element. *)
    2,
    ⌈2~Log~Max@l⌉               (* 2. Determine the maximum number of binary digits. *)
]] &

Here is the output for 0, 600:

Just about the same size (because left and right ceiling must be spelled out): Image[1 -     Thread@IntegerDigits[      l = Round[If[EvenQ[#], #^2, (# + 3)^2]/48] & /@ Range@##,       2, \[LeftCeiling]2~Log~Max@l\[RightCeiling]]] &

@DavidCarraher Thanks, I golfed it a bit further. :) (Should have checked the OEIS article.)

CJam (56 55 53 chars) / GolfScript (64 chars)
CJam:
"P1"q~,>{_1&3*+_*24+48/}%_:e>2b,\2_$#f+2fbz(,@@:~~]N*

GolfScript:
"P1"\~,>{.1&3*+.*24+48/}%.$-1=2base,\{2.$?+2base}%zip(,@@{~}/]n*

Both produce output in NetPBM format, and they're essentially ports of each other.
Dissection
CJam                 GolfScript           Explanation

"P1"                 "P1"\                NetPBM header
q~,>                 ~,>                  Create array [m .. n-1]
{_1&3*+_*24+48/}%    {.1&3*+.*24+48/}%    Map the sequence calculation
_:e>2b,\             .$-1=2base,\         Compute image height H as highest bit
                                          in largest number in sequence
2_$#f+2fb            {2.$?+2base}%        Map sequence to bits, ensuring that
                                          each gives H bits by adding 2^H
z(,@@                zip(,@@              Transpose and pull off dummy row to use
                                          its length as the "width" in the header
:~~                  {~}/                 Flatten double array and dump on stack
]N*                  ]n*                  Separate everything with whitespace

Thanks to Optimizer for CJam 56 -> 53.

Any reason you don't have "P1" at the beginning and thus save 1 byte by avoiding the \ ?

@Optimizer, too used to thinking in GS.

Not quite: the height needs to appear in the output. But there's still a saving to be made with the map shortening.

51: 'PoXq~{_1&3*+_*24+48/}%>_:e>2b,\2_$#f+2fbz(,@@]e_N*

Pyth - 101 60 59
Outputs a .pbm. Can likely be golfed more.
Km.B/++24*dd**6%d2d48rvzQJCm+*\0-eSmlkKlddK"P1"lhJlJjbmjbdJ

Highly ungolfed because I will be translating to Pyth.
Explanation coming next. Right now look at the equivalent Python code.
It uses the OEIS algorithm to calculate the sequence and then it converts to binary, pads the numbers, does a matrix rotation, and formats it into a pbm image. Since I'm not using brute force, it is incredibly fast.
         K=
 m          rvzQ      Map from eval input to eval input
  .B                  Binary rep
   /      48          Divided by 48
    ++                Triple sum
     24               Of 24,
     *dd              Square of d
     **               Triple product
      6               6
      %d2             Modulo d%2
      d               Var d
J                     Set J=
 C                    Matrix rotation from columns of row to rows of columns
  m           K       Map K (This does padding)
   +                  String concat
    *                 String repeat
     \0               "0"
     -     ld         Subtract the length of the column from
      eS              The max
       mlkK           Of all the column lengths
    d                 The column
"P1"                  Print header "P1"
l                     Length of
 hJ                   First row
lJ                    Number of columns
jb                    Join by linebreaks
 m  J                 Map on to J
  jb                  Joined columns by linb
   d

Here is the 600,900 example:

Try it here online.

R - 127 125
I'm not sure if this complies with the rules totally.  It doesn't output an image to a file, but it does create a raster and plot it to an output device.
I found the same formula as Martin, but here.
It uses an unnamed function.
require(raster);function(m,n)plot(raster(mapply(function(n)rev(as.integer(intToBits(round((n+n%%2*3)^2/48)))),m:n),0,n,0,32))

Run as follows
require(raster);(function(m,n)plot(raster(mapply(function(n)rev(as.integer(intToBits(round((n+n%%2*3)^2/48)))),m:n),0,n,0,32)))(0,600)

Produces the following plot

You can drop 7 bytes by not attaching raster to the namespace, since raster() is the only thing in there specific to that package. Instead just do raster::raster(...).

@AlexA. Thanks, will make that edit

@AlexA. Unfortunately I just tried it and it errors out for me.  I suspect that it's because raster requires sp as well.  I'll see if I can track it down.

Bummer. Sorry to have led you astray.

Python 2 + PIL, 255 184
My first version used PIL in order to show an image :
i,R,B=input,range,lambda x:bin((x*x+6*x*(x%2)+24)/48)[2:]
def F(k,v):i.load()[k]=v
a,b=i(),i();h=len(B(b));from PIL import Image;i=Image.new('P',(b-a,h))
[F((x-a,y),int(B(x).zfill(h)[y])) for x in R(a,b) for y in R(h)]
i.putpalette([255]*3+[0]*3)
i.show()

The new version just produces a b&w PPM image on stdout :
i,R,B=input,range,lambda x:bin((x*x+6*x*(x%2)+24)/48)[2:]
def p(s):print s
a,b=i(),i();h=len(B(b));p('P1 %i %i'%(b-a,h))
[p(' '.join([B(x).zfill(h)[y] for x in R(a,b)])) for y in R(h)]

Some character saves for the PPM version: You don't need a space before for. You can avoid parens around x%2 by changing the order to x%2*.... It's shorter not to define print as a function and just use two nested for loops, using print ..., to avoid newlines and a blank print to start a new line. A trick to force binary expansions to have length h without zfill is to add 2**h, then extract the last h digits.

JAVASCRIPT - 291
Code:
(function(a,b,c){c.width=b;t=c.getContext('2d');t.strokeStyle='black';for(i=a;i<=b;i++){g=(Math.floor(((i*i)+6*i*(i%2)+24)/48)>>>0).toString(2);l=g.length;for(j=0;j<l;j++){if(g[l-1-j]=='1'){t.rect(i-a,j,1,1);t.fill();}}}document.body.appendChild(c);})(0,300,document.createElement('canvas'))

Explanation:
(function (a, b, c) {
    //setting canvas width
    c.width = b;
    //get context 2d of canvas
    t = c.getContext('2d');
    //setting storke style.
    t.strokeStyle = 'black';
    //looping from a to b
    for (i = a; i <= b; i++) {
        //calculating A(i) and converting it to a binary string
        g = (Math.floor(((i * i) + 6 * i * (i % 2) + 24) / 48) >>> 0).toString(2);
        //looping through that string
        for (j = 0; j < g.length; j++) {
            //since canvas is upside down and the first digit is actually the last digit:
            if (g[g.length - 1 - j] == '1') {
                //we create the 1 by 1 rect
                t.rect(i - a, j, 1, 1);
                //we draw the rect
                t.fill();
            }
        }
    }
    //we append everything to the body
    document.body.appendChild(c);
    //parameters are put here
})(0, 300, document.createElement('canvas'))

Result:
Yes the result is upside down, but that's because 0,0 on a js canvas is top left. :3

Demo:
Demo on jsfiddle

APL (Dyalog Extended), 26 25 24 bytes
' ⎕'[⊤⌊12÷⍨6+×⍨⊥⊖0 2⊤…⎕]

Try it online!
Takes the inputs in reverse(-1 byte).
-1 byte from Bubbler(.5+12÷⍨ → 12÷⍨6+)
Generates the sequence in the same way as the existing J solution, except Bubbler shortened it with some math explained here.
Uses '⎕' as the display character. If '█' is required, then it becomes 27 bytes(does look nicer with it).
Explanation
' ⎕'[⊤⌊12÷⍨6+×⍨⊥⊖0 2⊤…⎕]
                      ⎕  take the second and first inputs
                     …   create an inclusive range between them
                 0 2⊤    encode into parts of 0 & 2
                ⊖        reverse the columns
               ⊥         decode from base 2
                         (this calculates (n+3×(n%2))/2)
             ×⍨          square that
      ⌊12÷⍨6+            divide by 12, round to the nearest integer
     ⊤                   encode in base 2
                         (this gives a binary matrix witht the required graph)
' ⎕'[                  ] convert 0s to ' ' and 1s to '⎕'

.5+12÷⍨ → 12÷⍨6+

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Road-Length Encoding
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 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.

Let me ask by example, is either of these a valid output?  https://gist.github.com/orlp/0e0eae16d6e1fcda5e9b

@orlp Neither is.

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

JavaScript (ES6), 114
Using  template strings, the 5 linefeeds are significant and thus 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

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/

K (ngn/k), 46 bytes
Created on the APL Farm with lots of input from chrispsn.
{++(,/(.x@y)#'"-="x_y#="PNP";"_")@3\466}`c$!58

Try it online!

k9 2021.03.27, 53 52 bytes
-1 byte thanks to chrispsn!
++"_  ",|"_ ",,,/{.[x]#*"-="y#="PNP"}/'-2^(~=':64>)^

Try it online on kparc.io!

Nice! Possible -1 byte: (="PNP")y => y#="PNP"

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

k9 2021.03.27, 72 bytes
" -=_"{++(3;0;0;mod[x]+2*~x;0;3)}@{y*x+y}\&?`P=!/`i`n$+-2^{9<a|-a:-':x}^

J (69 59 55 52 bytes)
-14 bytes thanks to Raul Miller and ovs on The APL Farm Discord.
-3 bytes by removing noun assigments
6$'_',4$'','',:'\d+.'(".@}:$'-= '#~'PNP'={:)rxapply]

Attempt This Online
Explanation
'\d.+'(...)rxapply]: For every match of pattern \d+, apply the function...
".@}:$'-= '#~'PNP'={:, a Fork/3-Train.

'-= '#~'PNP'={:: The right tine of the Fork. {: takes the last element ('N' or 'P'), and checks it's     equality against 'PNP', then uses the resulting boolean mask to select from '-= '. 'P' gets 1 0 1 so it  selects '- ', and N gets 0 1 0 and selects '='.
".@}:": The left tine of the Fork. }: drops the last element, keeping the digit(s) as a sting. The string is converted to a integer with "., the Execute operator.
$: The Reshape operator reshapes the right arg by the left arg

The expression so far has produced the mid line, eg. ====- - =========- - - -=-==- , which I will refer to as m  below.
,: Itemize m (ie. Puts it in an array, changing the shape from 30 to 1 30)
4$'','' Prepend 2 blank rows (arrays are rectangular, so the 2 chars get padded to the width of m) and then reshape by 4. Since there are 3 rows, reshape cycles to reuse the first row, adding another blank line.
6$'_', Prepends a _ char (which again gets padded to the width of m) then reshapes to 6. Again, since there's  5 rows, reshaping cycles back to the first item in the array (ie. the top line) which is appended to the array, producing the final result.

K (ngn/k), 71 69 68 64 69 68 65 bytes
{++"_  ",|"_ ",+" =-"@+/1(~<\2=)\-78+*'&.'!/|+0N 2#(&~=':58<x)_x}

Try it online!
-2 superfluous parens
-1 shuffling
-4 borrowing a parsing idea from ovs
+5 I actually prefer using "-" for the embankment, but what evs.
-1 woo hoo!
-4 bye bye beloved Bubbler train...

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.

@mbomb007 It didn't change the count :/ I can't get it below 169 atm

Putting p+=['='*v,('- '*v)[:v]][_[-1]=='P'] at the end of the previous line with a preceding semicolon saves one byte.

Also, using Python 2 instead saves 1 byte on the print.

@mbomb007 added them in :) I have a feeling python 2 it may be even shorter... But I'm not sure.

05AB1E, 35 34 bytes
.γa}2ôε`„PN…- =2ä‡s∍}J©¶ĆìĆ'_®∍DŠ»

Try it online or verify all test cases.
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)

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[1],$m,2);
$o='';
foreach($m as $p)
    $o.=str_replace('--','- ',str_repeat($p[2]<'P'?'=':'-',$p[1]));
$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'--','- '.

Vyxal L, 180 bitsv1, 22.5 bytes
⁽aḊyC½`- =`½$İ$⌊Ẏ∑ƛ4↳Ǔ\_pǏ

Try it Online!
  Ḋ                        # Group by...
⁽a                         # Is it an uppercase letter?
   y                       # Uninterleave - split into [numbers, chars]
    C½                     # Charcodes / 2 - N -> 39, P -> 40
            $İ             # Index into...
      `- =`½               # ["- ", "="]
                Ẏ          # Extend to length
              $⌊           # numbers
                 ∑         # Concatenate into a single string
                  ƛ        # For each character
                   4↳      # Prepend three spaces
                     Ǔ     # Move a space to the end
                      \_p  # Prepend a _
                         Ǐ # Append the _
                           # L flag transposes and joins the whole thing

Since when did we start scoring in bits (presumably or the charcodes)? Does this mean I can claim my solution is 205 bits, or 25.625 bytes?

@Shaggy Vyxal can use a custom range coding encoding (see the link in the header)

@Shaggy since the start of may - that's when vyncode was added (a fractional byte encoding/compression system).

Pip, 46 40 bytes
-6 bytes thanks in part to emanresu A
a^:CXUYP'_X$+aPnP{bHa}MPaR'N'=R'P"- "n.y

Attempt This Online!
Explanation
a^:CXU
a      ; Command-line argument
 ^:    ; Split by this separator and assign back to a:
    XU ;   Built-in regex `[A-Z]` (uppercase letters)
   C   ;   Wrapped in capturing group
       ; Splitting by a regex wrapped in a capturing group has the effect of keeping
       ; the matches of the regex in the result list, so this gives a list of
       ; alternating numbers and letters (with a stray empty string at the end)

YP'_X$+a
       a ; The new value of a, calculated above
     $+  ; Fold on addition (sum, treating letters as 0)
  '_X    ; String of underscores of that length
YP       ; Print, with trailing newline, and also yank into y variable

Pn ; Print newline, with trailing newline

P{bHa}MPaR'N'=R'P"- "
        a             ; In the list a,
         R'N'=        ; Replace "N" with "="
              R'P"- " ; Replace "P" with "- "
      MP              ; Map this function to each pair of consecutive values in
                      ; the list (either number & string or string & number):
 {bHa}                ;   Take (a) characters from the start of (b)
                      ;   If (a) is a string, it is treated as 0
                      ;   If (a) is longer than the length of (b), (b) is repeated
                      ;   till it is long enough
                      ; We end up with a list of strings that make up the correct
                      ; center line, interspersed with a bunch of empty strings
P                     ; Print that list, joined together

n.y ; Print a newline concatenated with y (the underscore string from earlier)

here's a 44

@emanresuA Ooh, great idea with MP! Combining it with a thought I had about cyclical indexing this morning, I got it down to 40.

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
pattern representation of the road
_________________________

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

_________________________

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

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:
______________________________

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

______________________________

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[1];*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]);}

More readable:
main(l,v,k,n,x,s,c)
    char*s,**v,c;
{
    for(l=6;l--;puts(s))
        for(s=v[1];*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

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

Japt v2.0a0, 30 29 28 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.

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!

Lua, 123 122 bytes
p=print s=(...):gsub('(%d+)(.)',load'a,b=...return({N="=",P="- "})[b]:rep(a):sub(1,a)')r=('_'):rep(#s)p(r)p'\n'p(s)p()p(r)

Try it online!
Ungolfed Version:
p=print
s=(...):gsub('(%d+)(.)',                       --For each number/letter pair
function(a,b)                                  --Number in a, letter in b
    return({N="=",P="- "})[b]:rep(a):sub(1,a)  --Replace each number/letter pair
                                               --with respective pattern
end)
r=('_'):rep(#s)                                --Create edges of road
p(r)p'\n'p(s)p()p(r)                           --Print road

PowerShell, 158 bytes
$f='';($_|sls "\d*\w"-a|% m*).value|%{$n=($_|sls "\d+"-a|% m*).value;if($n-eq$null){$n=1};switch($_[-1]){N{$f+='='*$n}P{$f+=-join(1..$n|%{(' ','-')[$_%2]})}}}

Ungolfed
$args|%{

    # empty string for adding road later
    $finalString=''

    # breaks every pair apart and selects the value (N4, P4, etc.)
    ($_|sls "\d*\w"-a|% m*).value|%{

        # selects just the number
        $num = ($_|sls "\d+"-a|% m*).value

        # for those pairs that don't have a number associated
        if($num -eq $null){$num = 1}

        # switch depending on the char
        switch($_[-1]){

            # nothing to do with N so append to finalString var
            N{
                $finalString += '=' * $num
            }

            # for loop to determine the alternating of the road pattern
            P{
                $finalString += -join (1..$num | %{(' ','-')[$_%2]})
            }
        }
    }

    # formats string for desired output
    "{0}`n`n`n{1}`n`n{0}" -f $("_"*$finalString.length),$finalString
}

Try it online!

Retina 0.8.2, 46 bytes
\d+N
$*=
\d+P
$*-
--
-
.+
$.0$*_¶¶¶$0¶¶$.0$*_

Try it online!
Explanation
\d+N
$*=

Match digits followed by N; treating the digits as a number, replace the match with that many =.
\d+P
$*-

Same, but with P and -.
--
-

Replace any two consecutive dashes with dash-space.
.+
$.0$*_¶¶¶$0¶¶$.0$*_

Replace the whole string with:

Get the length of the whole match ($.0) and make a string of that many underscores ($*_)
Three newlines (¶¶¶)
The original match ($0)
Two more newlines (¶¶)
The same underscores code again

Scala, 163 bytes
(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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Area of an ASCII polygon
You should write a program or function which receives a string representing an ascii-art polygon as input and outputs ot returns the area of the polygon.
The input is a string consisting of the characters _ / \ L V space and newline defining a simple polygon (which means no extra segments, no self-touch and no self-intersect).
The area of a single character cell is 2

_ splits the cell into sizes 0 and 2
\ splits the cell into sizes 1 and 1
/ splits the cell into sizes 1 and 1
L splits the cell into sizes 0 and 2
V splits the cell into sizes 1 and 1 (The two sides of the V will always be on the same side of the polygon so they are treated together in the listing.)

Every character connects the two corners of its character cell which you expect (e.g. top left and top right in case of V).
An example with area of 7 (1+2+1 in the second row and 1+1+1 in the third one):
 _
/ \
V\/

Input

Input will form a rectangle, i.e. there will be the same number of characters between newlines.
There can be extra whitespace on any side of the polygon.
Trailing newline is optional.

Output

A single positive integer, the area of the polygon.

Examples
Outputs are after the last row of their inputs.
  _
  V

1

/L
\/

3

    /VV\
    L  /
     L/
14

  ____/\
  \    /
/\/   /
\____/

32

   /V\
  /   \__
  \     /
/\/   /V
L____/

45

This is code-golf so the shortest entry wins.

your third example should be 14

@Optimizer Thanks,  corrected.

Is the lack of ^  intentionally?

@RobAu Yes, that doesn't look good enough.

CJam, 48 43 29 bytes
qN-{i_9%2%U!^:U;J%D%1U2*?}%:+

Update: Golfed a lot using maths and the state*2 trick from orlp's answer.
How it works (Outdated, updating soon)
We split the input on newline and then for each part we maintain a counter of occurrences of boundary characters L\/. This counter % 2 will tell us which of the two partitions amounts to choose for all of the characters. Then we find the index of each character in the string L _. \/V will give -1 referring to the last element in an array. After getting the index, we use 4558Zb2/ to create the array [[2 0] [0 2] [0 2] [1 1]] and then choose the correct of the count using the counter.
qN/0f{                                  }      e# Split the input on newline and for each
      \{                             }/        e# swap the 0 to back and for each char in
                                               e# the line, run this loop
        _"L _"#                                e# Copy the char and get index of it in
                                               e# this string "L _"
               4558Zb                          e# This is basically 4558 3base
                                               e# which comes to be [2 0 0 2 0 2 1 1]
                     2/=                       e# Group into pairs of 2 and choose the
                                               e# correct one.
                        2$=                    e# Based on the counter, choose the correct
                                               e# partition amount
                           @@"\/L"&,+          e# Increment the counter if the char is one
                                               e# of \, / and L
                                       ;       e# Pop the counter after each line loop
                                         :+    e# Sum all the numbers to get area

Try it online here

Pyth, 47 46 45 36 30
FNs.zx=Z}N"\/L"aY|}N"\/V"yZ;sY

Explanation:
FNs.z            For every character in input, except newlines...
  x=Z}N"\/L"     Swap state if /, \, or L.
  aY|}N"\/V"yZ;  Append 1 if /, \, or V, else 2 times the state to Y.
sY               Sum Y and print.

We have two states, "in the polygon", and "out of the polygon". The following characters each do the following when reading them from top-left to bottom-right:
/ \     swap state, add one to area
V                   add one to area
_ space             if in polygon, add two to area
L       swap state, if in polygon, add two to area

Note that "add one to area" and "if in polygon, add two to area" are mutually exclusive.

I'm really confused on how x= works. Is this documented somewhere?

@Jakube It's augmented assignment.

@Jakube It's like += or *= or whatever. In this case x is being used as xor, so it's exactly the same as Python's ^=.

Retina, 293 + 15 = 308 314 385 bytes
;`\s
_
;`\\
/
;`.+
o$0iio
;+`(o(?=/.*(i)|L.*(ii)|V.*(io)|_)|i(?=/.*(io)|L.*(o)|_.*(ii)|V.*(i))).
$1$2$3$4$5$6$7$8
;`o
<empty>
;`ii$
#:0123456789
;+`^(?=i)(i*)\1{9}(?=#.*(0)|i#.*(1)|ii#.*(2)|iii#.*(3)|iiii#.*(4)|iiiii#.*(5)|iiiiii#.*(6)|iiiiiii#.*(7)|iiiiiiii#.*(8)|iiiiiiiii#.*(9))
$1#$2$3$4$5$6$7$8$9$10$11
:.*|\D
<empty>

Each line goes in a separate file, so I've added 13 to the byte count. Alternatively, you can put that all in a single file as is and use the -s flag. The <empty> stand for actually empty files or lines.
Unfortunately, I need 187 bytes just to convert the result from unary to decimal. I guess I really should implement this some time soon.
Explanation
Retina is a regex-based language (which I wrote exactly for being able to do stuff like this with regex). Each pair of files/lines defines a replacement stage, with the first line being the pattern and the second line the replacement string. Patterns can be preceded by a `-delimited configuration string, which may contain the usual regex modifiers, as well as some Retina-specific options. For the above program, the relevant options are ;, which suppresses output of that stage and +, which applies the replacement in a loop until the result stops changing.
The idea of the solution is to count each line separately, because we can always decide by the characters already encountered whether we're inside or outside the polygon. This also means I can join the entire thing into a single line, because going the beginning and end of a line are always outside the polygon. We can also note that _ and space are completely identical for a line sweep algorithm, as well as \ and /. So as a first step I replace all newlines and spaces by _ and all \ by / to simplify some code later on.
I'm keeping track of the current inside/outside state with the characters i and o, while also using the is to tally the area. To do so I start by prepending an o to the joined line to mark that we're outside the polygon. I'm also adding an iio to the very end of the input, which I'll use as a lookup to generate new characters.
Then, the first large replacement simply replaces an i or o followed by one of /V_L with the next set of characters, thereby flooding and tallying the entire thing. The replacement table looks as follows, where the columns correspond to the last character in that line and the rows to the next character (where S is for space and <> for an empty string). I've included all characters of the input to show the equivalences I've already made use of:
     i     o

/    io    i
\    io    i
L    o     ii
V    i     io
_    ii    <>
S    ii    <>

Note that the final character then always indicates whether after the character we're inside or outside the polygon, while the number of is corresponds to the area that needs to be added to the polygon. As an example here are the results of the first four iterations on the last example input (this was generated by an old version which actually flooded each line separately, but the principle is still the same):
o   /V\
o  /   \___
o  L     _/
o/\/   /V
oL__ _/
o   V

o  /V\
o /   \___
o L     _/
oi\/   /V
oii__ _/
o  V

o /V\
o/   \___
oL     _/
oiio/   /V
oiiii_ _/
o V

o/V\
oi   \___
oii     _/
oiioi   /V
oiiiiii _/
oV

oiV\
oiii  \___
oiiii    _/
oiioiii  /V
oiiiiiiii_/
oio

Lastly, I just get rid of all the os and the line breaks by removing everything that matches [^i], and the remainder is the decimal-to-unary conversion which is rather boring.

GNU sed, 290 + 1
The + 1 is to account for the -r switch passed to sed.  Comments and additional whitespace not counted in the score.
I haven't looked in great detail, but I think this is probably similar to Martin's Retina answer:
:                      # label to start processing next (or first) line
s/[0-9]//g             # remove the count of colons from previous lines
H                      # append the current line to the hold space
g                      # copy the hold space to the pattern space
y^_\\^ /^              # Replace '_' with ' ' and replace '\' with '/'
s/(\n| +$)//g          # strip newlines and trailing space
:o                     # start of "outside loop"
s/(^|:) *V/\1:/        # replace leading spaces and "V" with ":"
to                     #   if the above matches, stay outside
s/(^|:) *[|/]/\1:/     # replace leading spaces and "|" or "/" with ":"
ti                     #   if the above matches, go inside
s/(^|:) *L/\1::/       # replace leading spaces and "L" with "::"
:i                     # start of "inside" loop
s/: /:::/              # replace space with "::"
ti                     #   if the above matches, stay inside
s/:V/::/               # replace "V" with ":"
ti                     #   if the above matches, stay inside
s/:[|/]/::/            # replace "|" or "/" with ":"
to                     #    if the above matches, go outside
s/:L/:/                # remove "L"
to                     #    if the above matches, go outside
h                      # copy current string of colons to hold buffer
:b                     # start of colon count loop
s/:{10}/</g            # standard sed "arithmetic" to get string length
s/<([0-9]*)$/<0\1/
s/:{9}/9/
s/:{8}/8/
s/:{7}/7/
s/:{6}/6/
s/:{5}/5/
s/::::/4/
s/:::/3/
s/::/2/
s/:/1/
s/</:/g
tb                     # once arithmetic done, pattern buffer contains string length
N                      # append newline and next line to pattern buffer
b                      # loop back to process next line

Overview

Replace each unit of area with a colon :
Count the number of colons

Notes

sed is line oriented so needs some work to process multiple lines at once.  The N command does this by appending a newline then the next line to the current pattern space.  The difficulty with N is that once it gets to the input stream EOF, it quits sed completely without any option to do further processing.  To get around this, we count the current set of colons at the end of each line, just before reading in the next line.

Output:
$ echo '   /V\
  /   \__
  \     /
/\/   /V
L____/' |sed -rf polyarea.sed
45
$

Perl, 65 58 bytes
map{map{$b^=2*y,/\\L,,;$a+=y,/\\V,,||$b}split//}<>;print$a

Toggle $b between 0 and 2 upon seeing / \ or L.
Add 1 to $a upon seeing / \ or V.
Add $b to $a upon seeing anything else.

Nice solution, Perl is surprisingly compact.

Input processing can be simplified for some more gains: $/=\1;$-^=2*y,/\\L,,,$a+=y,/\\V,,||$-for<>;print$a

C, 93 96 108 bytes
Edit: Took into account suggestions in the comments, converted the while into a single-statement for loop, and removed the "i" variable entirely.
int s,t;main(c,v)char**v;{for(;c=*v[1]++;t+=s+(c>46^!(c%19)^s))s^=c>13^c%9>4;printf("%d",t);}

Original post:
This looked like a fun and simple enough problem to finally get me to create an account here.
main(c,v)char**v;{int i,t,s;i=t=s=0;while(c=v[1][i++]){s^=c>13^c%9>4;t+=s+(c>46^!(c%19)^s);}printf("%d",t);}

The polygon text should be passed as the first command-line argument; this should work with or without any amount of newlines / whitespace.
This just reads in the polygon one character at a time, s switches whether currently in or outside of the polygon on '/', 'L', or '\', and t increases by 1 on '/', 'V', and '\', or by 2 if inside / 0 if outside on 'L', '_', space and newline.
This is my first time trying my hand at any sort of "golfing" (or C, to the extent it differs from C++), so any criticisms are appreciated!

Welcome and good job! You may be able to skip the i=t=s=0; I think C initializes all ints to 0 anyway. Also, see if you can turn the while loop into a for loop; that often saves a few bytes.

Using the idea of the for loop above I think you can do something like this: ...int i,t,s;for(i=t=s=0;c=v[1][i++];t+=s+(c>46^!(c%19)^s))s^=c>13^c%9>4;... which should save 4 bytes; one {, one } and two ;

Also as mentioned above, apparently global variables are automatically set to 0, so if int i,t,v; was to be put in front of main instead of inside we could get rid of i=t=s=0 altogether saving another 7 bytes.

POSIX sed, 245 244
POSIX sed, no extensions or extended regexps.  Input is limited to the maximum hold space size of sed - POSIX mandates at least 8192; GNU manages more.  This version assumes that there will be no blank lines before or after the shape; an extra 10 bytes of code, indicated in the expansion, can accommodate that if it's a requirement (original question doesn't specify).
H
/^\([L\\]_*\/\|V\| \)*$/!d
x
s/[_ ]/  /g
s/^/!/
s/$/!/
:g
s/\([^V]\)V/V\1/
tg
y/V/ /
s/L/!  /g
s,[/\\], ! ,g
s/![^!]*!//g
:d
/ /{
s/     /v/g
s/vv/x/g
/[ v]/!s/\b/0/2
s/  /b/g
s/bb/4/
s/b /3/
s/v /6/
s/vb/7/
s/v3/8/
s/v4/9/
y/ bvx/125 /
td
}

Expanded and annotated
#!/bin/sed -f

# If leading blank lines may exist, then delete them
# (and add 8 bytes to score)
#/^ *$/d

# Collect input into hold space until we reach the end of the figure
# The end is where all pieces look like \___/ or V
H
/^\([L\\]_*\/\|V\| \)*$/!d

x

# Space and underscore each count as two units
s/[_ ]/  /g

# Add an edge at the beginning and end, so we can delete matching pairs
s/^/!/
s/$/!/
# Move all the V's to the beginning and convert each
# to a single unit of area
:gather
s/\([^V]\)V/V\1/
tgather
y/V/ /

# L is a boundary to left of cell; / and \ in middle
s/L/!  /g
s,[/\\], ! ,g

# Strip out all the bits of outer region
s/![^!]*!//g

# Now, we have a space for each unit of area, and no other characters
# remaining (spaces are convenient because we will use \b to match
# where they end).  To count the spaces, we use roman numerals v and x
# to match five and ten, respectively.  We also match two (and call
# that 'b').  At the end of the loop, tens are turned back into spaces
# again.
:digit
/ /{
s/     /v/g
s/vv/x/g
/[ v]/!s/\b/0/2
s/  /b/g
s/bb/4/
s/b /3/
s/v /6/
s/vb/7/
s/v3/8/
s/v4/9/
y/ bvx/125 /
tdigit
}

# If trailing blank lines may exist, then stop now
# (and add 2 bytes to score)
#q

C, 84 bytes
a;i;f(char*s){for(;*s;a+=strchr("\\/V",*s++)?1:i+i)i^=!strchr("\nV_ ",*s);return a;}

We switch sides whenever we see \, / or L; we always add one for \\, / or V, but add 2 (if inside) or 0 (if outside) for space, newline, L or _.
The variables a and i are assumed to be zero on entry - they must be reset if the function is to be called more than once.
Ungolfed:
int a;                          /* total area */
int i;                          /* which side; 0=outside */
int f(char*s)
{
    while (*s) {
        i ^= !strchr("\nV_ ",*s);
        a += strchr("\\/V",*s++) ? 1 : i+i;
    }
    return a;
}

Test program:
#include <stdio.h>
int main()
{
    char* s;
    s = "  _  \n"
        "  V  \n";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "/L\n"
        "\\/\n";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "    /VV\\\n"
        "    L  /\n"
        "     L/";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "  ____/\\ \n"
        "  \\    /\n"
        "/\\/   /\n"
        "\\____/";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "   /V\\\n"
        "  /   \\__ \n"
        "  \\     /\n"
        "/\\/   /V\n"
        "L____/";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    return 0;
}


text:
Find Patterns in Strings
In this challence, your task is to locate substrings with a given structure.
Input
Your input shall be two non-empty alphanumeric strings, a pattern p and a text t.
The idea is that each character of p represents a contiguous non-empty substring of t which occur next to each other, and p represents their concatenation.
Identical characters correspond to identical substrings; for example, the pattern aa represents any non-empty square (a string obtained by concatenating a shorter string to itself).
Thus the pattern aa can match the substring byebye, with each a matching bye.
Output
If the text t contains a substring that p matches, then your output shall be that substring, with colons : inserted between the strings that correspond to characters of p.
For example, if we have t = byebyenow and p = aa, then bye:bye is an acceptable output.
There may be several choices for the matching substring, but you shall only output one of them.
If t does not contain a matching substring, your output shall be a sad face :(.
Rules and Clarifications
Different characters of p can correspond to identical substrings, so p = aba can match the string AAA.
Note that the characters must correspond to non-empty strings; in particular, if p is longer than t, the output must be :(.
You can write a full program or a function, and you can also change the order of the two inputs.
The lowest byte count wins, and standard loopholes are disallowed.
Test Cases
Given in the format pattern text -> output.
Note that other acceptable outputs may exist.
a Not -> N
aa Not -> :(
abcd Not -> :(
aaa rerere -> re:re:re
xx ABAAAB -> A:A
MMM ABABBAABBAABBA -> ABBA:ABBA:ABBA
x33x 10100110011001 -> 10:1001:1001:10
abcacb 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> c:a0aa:0c:c:0c:a0aa
abccab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> a:a:0c0:0c0:a:a
abcbcab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> :(
abcbdcab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> 00:c:ca0aa0c:c:0:ca0aa0c:00:c

The powerset of all substrings? Why not!

@orlp It's only O(2^((n * (n + 1))/2)) :P

What does a digit in the pattern string signify?

@feersum It is a character, so it is essentially the same as any other character.

@ThreeFx I'm unsure because the first paragraph refers only to "letters" in the pattern.

@feersum In Rules "different characters of p can ..."

@feersum Digits are simply handled as characters. I've replaced "letters" with "characters" in the spec.

Anything I come up with will be horribly inefficient...

@mbomb007 Efficiency is of little concern here. My reference implementation runs in exponential time. :P

Python, 207 bytes
import re
h=lambda x:"a"+str(ord(x))
def g(a,b):
 c,d="",set()
 for e in a:
  c+=["(?P<"+h(e)+">.+)","(?P="+h(e)+")"][e in d]
  d.add(e)
 f=re.search(c,b)
 return f and":".join(f.group(h(e))for e in a)or":("

Call with g(pattern, string)
Uses the re module to do most of the work.

JavaScript (SpiderMonkey) (ES5.1), 198 bytes
Since ES6 was released in June 2015, I post the ES5.1 version of the code together with the ES6 equivalent, but declare ES5.1 version as the main answer.
Greedy match, so the first case returns "Not" instead of "N".
function(a,b){c=[o="indexOf"];r=a.split("");return(m=RegExp(r.map(function(i){return(e=c[o](i))>0?"\\"+e:(c.push(i),"(.+)")}).join("")).exec(b))?r.map(function(x){return m[c[o](x)]}).join(":"):":("}

Try it online!
JavaScript (Node.js) (ES6), 141 bytes
a=>b=>(c=[o="indexOf"],r=[...a],m=RegExp(r.map(i=>(e=c[o](i))>0?"\\"+e:(c.push(i),"(.+)")).join``).exec(b))?r.map(x=>m[c[o](x)]).join`:`:":("

Try it online!
Takes the arguments in currying syntax: f(a)(b)
Explanation (and ungolfed):
function matchPattern(a, b) {                   // Main function
 var c = ["indexOf"];                           // Array used for the capturing groups
 var r = [...a];                                // Split the pattern first
 var m = RegExp(r.map(function(i) {             // Create the regex
  var e = c.indexOf(i);                         // Check if the character is found before
  if (e > 0)                                    // If so
   return "\\" + e;                             // Append the back reference to the regex
  else {                                        // If not
   c.push(i);                                   // Append the character to the array
   return "(.+)";                               // Append a capturing group to the regex
  }
 }).join("")).exec(b);                          // Execute the regex
 if (m != null)                                 // If the pattern matches the string
  return r.map(function(x) {                    // Replace each letter
   return m[c.indexOf(x)];                      // With the corresponding substring
  }).join(":");                                 // And join them with ":"
 else                                           // If there is no match
  return ":(";                                  // Return ":("
}

Brachylog, 35 bytes
sᵗ~cᵗXlᵛ∧Xzdz≠ʰ∧Xt~ṇ{Ḷ∧":"|}ᵐ.∨":("

Try it online!
On not-quite-small inputs, very slow. I-haven't-actually-done-the-sixth-test-case-but-not-for-lack-of-trying slow. (Probably owing to brute-forcing every partition of every substring, starting with the largest, and then checking if it's a match.) Takes input as a list [pattern,string].
Condensed and divided explanation:
sᵗ~cᵗX
X is the pattern paired with a partition of a substring of the input string.
lᵛ
The pattern and the partition have the same number of elements.
Xzdz≠ʰ
No two unique pattern char, matched substring pairs share a pattern character. That is, no pattern character maps to multiple substrings, although multiple pattern characters may map to one substring.
Xt~ṇ{Ḷ∧":"|}ᵐ.∨":("
The output is the elements of the partition joined by colons, unless something couldn't be done, in which case it's :( instead.
Monolithic explanation:
                                       The input
 ᵗ  ᵗ                                  with its last element replaced with
  ~c                                   a list which concatenates to
s                                      a substring of it
     X                                 is X,
       ᵛ                               the elements of which all have the same
      l                                length.
        ∧                              And,
         X                             X
          z                            zipped
           d                           with duplicate pairs removed
            z                          and zipped back
              ʰ                        has a first element
             ≠                         with no duplicate values.
               ∧                       Furthermore,
                 t                     the last element of
                X                      X
                  ~ṇ                   with its elements joined by newlines
                    {      }ᵐ          where each character of the joined string
                     Ḷ                 is a newline
                      ∧                and
                          |            is replaced with
                       ":"             a colon
                          |            or is passed through unchanged
                             .         is the output.
                              ∨        If doing any part of that is impossible,
                                       the output is
                               ":("    ":(".

It's been more than an hour and it still hasn't done the sixth test case... maybe it actually doesn't work? It's using more than its share of processor...

Okay, either I underestimated the time complexity of using multiple layers of hard brute force, or this is broken in some way, because it still hasn't done the sixth test case

I've shut it down now because if it takes three hours I'm not sure how much longer I'm willing to wait

Can shave three off with z₂, but bumping this with an edit doesn't seem appropriate.


text:
Like a quine, but not
Very simple, write a program that at first glance appears to be a quine, but is not. Upon running, the program actually prints the source to a real quine, obviously distinct from the original program in some way, preferably creative, but since this is a popularity contest, the answer with the most upvotes wins.
Standard Loopholes which are no longer funny are forbidden.

Can I allow requiring specific input in my answer, or does my program have to work regardless of input?

I think it has to work regardless of the input.

Why does this question have so many dislikes?

@loovjo I have no idea. Vague? Open ended?

I'm voting to close this question as off-topic because it's an [underhanded] challenge, which was on-topic a year ago, but is now off-topic by community consensus.

CJam
{"_~"}_~

Well, whether this looks like a real quine to you depends on whether you're used to CJam or GolfScript, but anyway, it looks like and prints the standard quine:
{"_~"}_~

Wait, isn't that the same thing?

 Nope, there's a space at the end of the first code. I believe the same thing would work in almost any language with almost any quine.

Test it here.

CJam. What can it do? Everything, apparently...

H9+
"Hello, world!"

It's easy: In H9+, anything other than H, 9, or + is ignored, and therefore, this is a quine. Or is it?

 Nope. H actually outputs Hello, world!, with no quotes.

Python
s="s=%r\nprint(s%%s)"
print(s%s)

Explanation:

 The output actually has single quotes instead of double quotes.

Try it here

Mathematica
This one can be quite tricky to newer users.
Function[Print[StringJoin[ToString[FullForm[#0]], "[];"]]][];

Explanation:

 Some people might not notice the #0 as not being part of the FullForm. In the output, it is replaced with Slot[0]. Everything else is the same.

Haskell
Recursion can be tricky at times.
let s = "let s = " ++ show s ++ " in putStrLn s" in putStrLn s

 This actually outputs the same as 's = "let s = " ++ show s in putStrLn s', namely 'let s = "let s = \"let s = \\\"let s = \\\\\\\"let s = \\\\\\\\\\\\\\\"let s = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"...'

 Basically, Haskell is trying to let s be equal to itself, with let s = appended to it, and escaping the string.

 Obviously, in order to escape " you need \", and in order to escape \ you get \\, which is how the long stream of backslashes is formed.


text:
Testing if a number is a square
Write a GOLF assembly program that given a 64-bit unsigned integer in register n puts a non-zero value into register s if n is a square, otherwise 0 into s.
Your GOLF binary (after assembling) must fit in 4096 bytes.

Your program will be scored using the following Python3 program (which must be put inside the GOLF directory):
import random, sys, assemble, golf, decimal

def is_square(n):
    nd = decimal.Decimal(n)
    with decimal.localcontext() as ctx:
        ctx.prec = n.bit_length() + 1
        i = int(nd.sqrt())
        return i*i == n

with open(sys.argv[1]) as in_file:
    binary, debug = assemble.assemble(in_file)

score = 0
random.seed(0)
for i in range(1000):
    cpu = golf.GolfCPU(binary)

    if random.randrange(16) == 0: n = random.randrange(2**32)**2
    else:                         n = random.randrange(2**64)

    cpu.regs["n"] = n
    cpu.run()
    if bool(cpu.regs["s"]) != is_square(n):
        raise RuntimeError("Incorrect result for: {}".format(n))
    score += cpu.cycle_count
    print("Score so far ({}/1000): {}".format(i+1, score))

print("Score: ", score)

Make sure to update GOLF to the latest version with git pull. Run the score program using python3 score.py your_source.golf.
It uses a static seed to generate a set of numbers of which roughly 1/16 is square. Optimization towards this set of numbers is against the spirit of the question, I may change the seed at any point. Your program must work for any non-negative 64-bit input number, not just these.
Lowest score wins.

Because GOLF is very new I'll include some pointers here. You should read the  GOLF specification with all instructions and cycle costs. In the Github repository example programs can be found.
For manual testing, compile your program to a binary by running python3 assemble.py your_source.golf. Then run your program using python3 golf.py -p s your_source.bin n=42, this should start the program with n set to 42, and prints register s and the cycle count after exiting. See all the values of the register contents at program exit with the -d flag - use --help to see all flags.

I unrolled a 32-iteration loop to save ~64 operations per test. That's probably outside the spirit of the challenge. Maybe this would work better as speed divided by codesize?

@Sparr Loop unrolling is allowed, as long as your binary fits in 4096 bytes. Do you feel this limit is too high? I'm willing to lower it.

@Sparr Your binary right now is 1.3k, but I think that 32-iteration loop unrolling is a bit much. How does a binary limit of 1024 bytes sound?

Warning to all contestants! Update your GOLF interpreter with git pull. I found a bug in the leftshift operand where it didn't properly wrap.

I'm not sure. 1024 would only require me to loop once; I'd still save ~62 ops per test by the unrolling.
I suspect someone might also put that much space to good use as a lookup table. I've seen some algorithms that want 2-8k of lookup tables for 32 bit square roots.

all the existing solutions, including mine before unrolling, fit in much much less space than that. How big is yours?

Is there a way to get access to math (in particular, math.sqrt) to programmatically generate a lookup table in the data section?  Right now I have a string of 3k octal escapes pasted in my file...

@2012rcampion No, but you can use x ** 0.5 to do square roots.

Score: 22120 (3414 bytes)
My solution uses a 3kB lookup table to seed a Newton's method solver that runs for zero to three iterations depending on the result's size.
    lookup_table = bytes(int((16*n)**0.5) for n in range(2**10, 2**12))

    # use orlp's mod-64 trick
    and b, n, 0b111111
    shl v, 0xc840c04048404040, b
    le q, v, 0
    jz not_square, q
    jz is_square, n

    # x will be a shifted copy of n used to index the lookup table.
    # We want it shifted (by a multiple of two) so that the two most
    # significant bits are not both zero and no overflow occurs.
    # The size of n in bit *pairs* (minus 8) is stored in b.
    mov b, 24
    mov x, n
    and c, x, 0xFFFFFFFF00000000
    jnz skip32, c
    shl x, x, 32
    sub b, b, 16
skip32:
    and c, x, 0xFFFF000000000000
    jnz skip16, c
    shl x, x, 16
    sub b, b, 8
skip16:
    and c, x, 0xFF00000000000000
    jnz skip8, c
    shl x, x, 8
    sub b, b, 4
skip8:
    and c, x, 0xF000000000000000
    jnz skip4, c
    shl x, x, 4
    sub b, b, 2
skip4:
    and c, x, 0xC000000000000000
    jnz skip2, c
    shl x, x, 2
    sub b, b, 1
skip2:

    # now we shift x so it's only 12 bits long (the size of our lookup table)
    shr x, x, 52

    # and we store the lookup table value in x
    add x, x, data(lookup_table)
    sub x, x, 2**10
    lbu x, x

    # now we shift x back to the proper size
    shl x, x, b

    # x is now an intial estimate for Newton's method.
    # Since our lookup table is 12 bits, x has at least 6 bits of accuracy
    # So if b <= -2, we're done; else do an iteration of newton
    leq c, b, -2
    jnz end_newton, c
    divu q, r, n, x
    add x, x, q
    shr x, x, 1

    # We now have 12 bits of accuracy; compare b <= 4
    leq c, b, 4
    jnz end_newton, c
    divu q, r, n, x
    add x, x, q
    shr x, x, 1

    # 24 bits, b <= 16
    leq c, b, 16
    jnz end_newton, c
    divu q, r, n, x
    add x, x, q
    shr x, x, 1

    # 48 bits, we're done!

end_newton:

    # x is the (integer) square root of n: test x*x == n
    mulu x, h, x, x
    cmp s, n, x
    halt 0

is_square:
    mov s, 1

not_square:
    halt 0

Score: 27462
About time I'd compete in a GOLF challenge :D
    # First we look at the last 6 bits of the number. These bits must be
    # one of the following:
    #
    #     0x00, 0x01, 0x04, 0x09, 0x10, 0x11,
    #     0x19, 0x21, 0x24, 0x29, 0x31, 0x39
    #
    # That's 12/64, or a ~80% reduction in composites!
    #
    # Conveniently, a 64 bit number can hold 2**6 binary values. So we can
    # use a single integer as a lookup table, by shifting. After shifting
    # we check if the top bit is set by doing a signed comparison to 0.

    and b, n, 0b111111
    shl v, 0xc840c04048404040, b
    le q, v, 0
    jz no, q
    jz yes, n

    # Hacker's Delight algorithm - Newton-Raphson.
    mov c, 1
    sub x, n, 1
    geu q, x, 2**32-1
    jz skip32, q
    add c, c, 16
    shr x, x, 32
skip32:
    geu q, x, 2**16-1
    jz skip16, q
    add c, c, 8
    shr x, x, 16
skip16:
    geu q, x, 2**8-1
    jz skip8, q
    add c, c, 4
    shr x, x, 8
skip8:
    geu q, x, 2**4-1
    jz skip4, q
    add c, c, 2
    shr x, x, 4
skip4:
    geu q, x, 2**2-1
    add c, c, q

    shl g, 1, c
    shr t, n, c
    add t, t, g
    shr h, t, 1

    leu q, h, g
    jz newton_loop_done, q
newton_loop:
    mov g, h
    divu t, r, n, g
    add t, t, g
    shr h, t, 1
    leu q, h, g
    jnz newton_loop, q
newton_loop_done:

    mulu u, h, g, g
    cmp s, u, n
    halt 0
yes:
    mov s, 1
no:
    halt 0

If I steal your lookup idea then my score drops from 161558 to 47289. Your algorithm still wins.

Have you tried unrolling the newton loop? How many iterations does it need, for the worst case?

@Sparr Yes, it's not faster to unroll because there's high variance in number of iterations.

does it ever complete in zero or one iterations? what's the max?

The lookup table idea was also in the answer http://stackoverflow.com/a/18686659/4339987.

Score: 161558 227038 259038 260038 263068
I took the fastest integer square root algorithm I could find and return whether its remainder is zero.
# based on http://www.cc.utah.edu/~nahaj/factoring/isqrt.c.html
# converted to GOLF assembly for http://codegolf.stackexchange.com/questions/49356/testing-if-a-number-is-a-square

# unrolled for speed, original source commented out at bottom
start:
    or u, t, 1 << 62
    shr t, t, 1
    gequ v, n, u
    jz nope62, v
    sub n, n, u
    or t, t, 1 << 62
    nope62:

    or u, t, 1 << 60
    shr t, t, 1
    gequ v, n, u
    jz nope60, v
    sub n, n, u
    or t, t, 1 << 60
    nope60:

    or u, t, 1 << 58
    shr t, t, 1
    gequ v, n, u
    jz nope58, v
    sub n, n, u
    or t, t, 1 << 58
    nope58:

    or u, t, 1 << 56
    shr t, t, 1
    gequ v, n, u
    jz nope56, v
    sub n, n, u
    or t, t, 1 << 56
    nope56:

    or u, t, 1 << 54
    shr t, t, 1
    gequ v, n, u
    jz nope54, v
    sub n, n, u
    or t, t, 1 << 54
    nope54:

    or u, t, 1 << 52
    shr t, t, 1
    gequ v, n, u
    jz nope52, v
    sub n, n, u
    or t, t, 1 << 52
    nope52:

    or u, t, 1 << 50
    shr t, t, 1
    gequ v, n, u
    jz nope50, v
    sub n, n, u
    or t, t, 1 << 50
    nope50:

    or u, t, 1 << 48
    shr t, t, 1
    gequ v, n, u
    jz nope48, v
    sub n, n, u
    or t, t, 1 << 48
    nope48:

    or u, t, 1 << 46
    shr t, t, 1
    gequ v, n, u
    jz nope46, v
    sub n, n, u
    or t, t, 1 << 46
    nope46:

    or u, t, 1 << 44
    shr t, t, 1
    gequ v, n, u
    jz nope44, v
    sub n, n, u
    or t, t, 1 << 44
    nope44:

    or u, t, 1 << 42
    shr t, t, 1
    gequ v, n, u
    jz nope42, v
    sub n, n, u
    or t, t, 1 << 42
    nope42:

    or u, t, 1 << 40
    shr t, t, 1
    gequ v, n, u
    jz nope40, v
    sub n, n, u
    or t, t, 1 << 40
    nope40:

    or u, t, 1 << 38
    shr t, t, 1
    gequ v, n, u
    jz nope38, v
    sub n, n, u
    or t, t, 1 << 38
    nope38:

    or u, t, 1 << 36
    shr t, t, 1
    gequ v, n, u
    jz nope36, v
    sub n, n, u
    or t, t, 1 << 36
    nope36:

    or u, t, 1 << 34
    shr t, t, 1
    gequ v, n, u
    jz nope34, v
    sub n, n, u
    or t, t, 1 << 34
    nope34:

    or u, t, 1 << 32
    shr t, t, 1
    gequ v, n, u
    jz nope32, v
    sub n, n, u
    or t, t, 1 << 32
    nope32:

    or u, t, 1 << 30
    shr t, t, 1
    gequ v, n, u
    jz nope30, v
    sub n, n, u
    or t, t, 1 << 30
    nope30:

    or u, t, 1 << 28
    shr t, t, 1
    gequ v, n, u
    jz nope28, v
    sub n, n, u
    or t, t, 1 << 28
    nope28:

    or u, t, 1 << 26
    shr t, t, 1
    gequ v, n, u
    jz nope26, v
    sub n, n, u
    or t, t, 1 << 26
    nope26:

    or u, t, 1 << 24
    shr t, t, 1
    gequ v, n, u
    jz nope24, v
    sub n, n, u
    or t, t, 1 << 24
    nope24:

    or u, t, 1 << 22
    shr t, t, 1
    gequ v, n, u
    jz nope22, v
    sub n, n, u
    or t, t, 1 << 22
    nope22:

    or u, t, 1 << 20
    shr t, t, 1
    gequ v, n, u
    jz nope20, v
    sub n, n, u
    or t, t, 1 << 20
    nope20:

    or u, t, 1 << 18
    shr t, t, 1
    gequ v, n, u
    jz nope18, v
    sub n, n, u
    or t, t, 1 << 18
    nope18:

    or u, t, 1 << 16
    shr t, t, 1
    gequ v, n, u
    jz nope16, v
    sub n, n, u
    or t, t, 1 << 16
    nope16:

    or u, t, 1 << 14
    shr t, t, 1
    gequ v, n, u
    jz nope14, v
    sub n, n, u
    or t, t, 1 << 14
    nope14:

    or u, t, 1 << 12
    shr t, t, 1
    gequ v, n, u
    jz nope12, v
    sub n, n, u
    or t, t, 1 << 12
    nope12:

    or u, t, 1 << 10
    shr t, t, 1
    gequ v, n, u
    jz nope10, v
    sub n, n, u
    or t, t, 1 << 10
    nope10:

    or u, t, 1 << 8
    shr t, t, 1
    gequ v, n, u
    jz nope8, v
    sub n, n, u
    or t, t, 1 << 8
    nope8:

    or u, t, 1 << 6
    shr t, t, 1
    gequ v, n, u
    jz nope6, v
    sub n, n, u
    or t, t, 1 << 6
    nope6:

    or u, t, 1 << 4
    shr t, t, 1
    gequ v, n, u
    jz nope4, v
    sub n, n, u
    or t, t, 1 << 4
    nope4:

    or u, t, 1 << 2
    shr t, t, 1
    gequ v, n, u
    jz nope2, v
    sub n, n, u
    or t, t, 1 << 2
    nope2:

    or u, t, 1 << 0
    shr t, t, 1
    gequ v, n, u
    jz nope0, v
    sub n, n, u
    nope0:

end:
    not s, n        # return !remainder
    halt 0

# before unrolling...
#
# start:
#     mov b, 1 << 62  # squaredbit = 01000000...
# loop:               # do {
#     or u, b, t      #   u = squaredbit | root
#     shr t, t, 1     #   root >>= 1
#     gequ v, n, u    #   if remainder >= u:
#     jz nope, v
#     sub n, n, u     #       remainder = remainder - u
#     or t, t, b      #       root = root | squaredbit
# nope:
#     shr b, b, 2     #   squaredbit >>= 2
#     jnz loop, b      # } while (squaredbit > 0)
# end:
#     not s, n        # return !remainder
#     halt 0

EDIT 1: removed squaring test, return !remainder directly, save 3 ops per test
EDIT 2: use n as the remainder directly, save 1 op per test
EDIT 3: simplified the loop condition, save 32 ops per test
EDIT 4: unrolled the loop, save about 65 ops per test

You can use full Python expressions in instructions, so you can write 0x4000000000000000 as 1 << 62 :)

Score: 344493
Does a simple binary search within the interval [1, 4294967296) to approximate sqrt(n), then checks if n is a perfect square.
mov b, 4294967296
mov c, -1

lesser:
    add a, c, 1

start:
    leu k, a, b
    jz end, k

    add c, a, b
    shr c, c, 1

    mulu d, e, c, c

    leu e, d, n
    jnz lesser, e
    mov b, c
    jmp start

end:
    mulu d, e, b, b
    cmp s, d, n

    halt 0

Nice starting answer! Do you have any feedback on programming in GOLF assembly, the tools I made for GOLF, or the challenge? This type of challenge is very new, and I'm eager to hear feedback :)

Your answer is bugged for n = 0 sadly, 0 is 0 squared :)

@orlp fixed for n = 0. Also, I'd suggest adding an instruction to print a register's value mid-execution, which could make debugging GOLF programs easier.

I'm not going to add such an instruction (that would mean challenges have to add extra rules about disallowed debugging instructions), instead I have interactive debugging planned, with breakpoints and viewing all register contents.

you could maybe speed this up by weighting your binary search to land somewhere other than the midpoint. the geometric mean of the two values perhaps?