text:
Shrink your language's character set
We often get restricted-source questions here on PPCG that favour submitting solutions using only a subset of characters (sufficiently so that there's a tag printable-ascii that identifies a particular subset of those challenges). Wouldn't it be nice if we could automatically cut languages down to a subset of their normal character set?
As an example, JavaScript is sometimes translated into a subset known as JSFuck which contains only the characters []()!+. In this challenge, you're aiming to write the equivalent of a JavaScript to JSFuck translator, but without the language restriction: you're compiling a language of your choice down to a subset of its characters (well, bytes, in order to avoid dubious corner cases).
Clarifications and detailed specification

Call the program you submit program A. The input to program A will be a string representing a program (program B). Its output must also be a string representing a program (program C). Program B will be in the same language as program A (there are no restrictions on how your program reacts to invalid input). Program C must also be a program in that language, and have the same behaviour in all cases as program B (i.e. if program C is given input X, it will produce the same probability distribution of outputs as program A does).
You may assume that in the case where programs A and B are distinct, program B does not access any files from disk. (In particular, you may assume it does not attempt to read its own source code from disk.).
Although part of the scoring is based on a single test case (program A itself), your program must work for any input (in the sense of complying with the specification above; that is, any valid program B must lead to a corresponding output for program C). Optimizing specifically for the test case given is allowed (and might or might not be helpful).
A cat implementation is technically speaking a valid answer to this question (as the subsetting of characters is part of the scoring criterion, not the validity criterion), but the scoring is designed so that such a program is unlikely to win. Just as solutions to code-golf competitions should make at least an attempt to minimize the number of bytes, solutions to this competition should make at least an attempt to minimize score. (Note that in some languages, cat may genuinely work best because the character sets are already small or impossible to shave down further. These solutions are valid, but ideally wouldn't be upvoted.)
You can accept the strings used for your input and output via any reasonable method.
Because languages with no computational ability might potentially lead to trivial solutions due to there being few possible programs to consider, this competition is open only to entries written in programming languages.

Victory condition
Let S be the set of bytes that can appear in the outputs C of your program (that is: for any valid input B, if the corresponding output C can potentially contain a byte, then that byte must be an element of S). Let c be the number of elements in S.
Now, let Q be the result of running your program on itself (i.e. the output C produced when A and B are the same program). Let b be the number of bytes in Q. (In order to minimize b and thus your score, you'll want to keep your program short, as in code-golf, but also the size of your program's output short, as in metagolf.)
Your score for this code-challenge is:
(b+1000)×loge(c+1)
The winner is the entry with the lowest score. (If there's a tie for first place, the lowest c among the tied entries will win; if there's still a tie for first place, the earliest entry among the entries tied for first will win.) Even if you can't win, though, you're encouraged to show off interesting answers (perhaps answers with a particularly low c, or in a language other people haven't attempted yet).

Agreed that they're similar. The other challenge has a broken victory condition, though (it has a vaguely worded ban on languages which is the only thing preventing Unary scoring 1). Actually, that challenge probably needs to be closed as unclear.

To those who closed as 'unclear what you're asking', what exactly is unclear? I found the challenge plenty clear.

@orlp, with the link added to the actual JSFuck page this becomes clear (well actually still a bit muddy on JSFuck's property to seemly be able to run in normal JS, is that required too?) to me. But this is a duplication issue now it seems.

Brainfuck, (1000 + 133) * loge(8+1) ~= 2489
Requires an interpreter that has wrapping 8-byte unsigned cells and produces 0 or doesn't change the cell on EOF.
,[>>>--[>-<++++++]>>->->->-------------->-->>>-[++[>]<<->+]--[<]<<<[->+>>+<<<]+>>>>[<[->+<]+>[<-]<[->>[[-]>]-[+<-]+>.>]>>>]-[[+]<-],]

A proper brainfuck interpreter ignores any character except []<>+-,., so we minify the character set by keeping only those characters.
For example, giving this as input to the above program produces the above program:
,[>>>
prepare array
--[>-<++++++]>>->->->-------------->-->>>-[++[>]<<->+]--
[<]<<<[->+>>+<<<]+>>>
while number to the right of i
>[
    <[->+<] move sum of both to the right
    +>[<-]<[ if sum == 0
        clear everything to the right
        ->>[[-]>]
        move to the left until we hit 1
        -[+<-]
        output i and move past to stop loop
        +>.>
    ]
    >>>
]
-[[+]<-]
,]

source: Stack Exchange

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

sort: votes


text:
Score a hand of Cribbage!
Goal:
Given a hand of 5 cards, determine its value in the game Cribbage.
Input a string through any reasonable means. You can assume the string will always be in this format:
[Card Value][Card Face],[Card Value][Card Face],[Card Value][Card Face],[Card Value][Card Face],[Card Value][Card Face]

Valid Card Values:
A,2,3,4,5,6,7,8,9,10,J,Q,K

Valid Card Faces:
H,D,S,C

Examples:
5H,6D,9C,KC,JH
AH,AD,AS,AC,2H

Rules:
Each item in the list is a card. Score the cards based on the following rules:
- Any card with the same value as another is worth 2 points.

- A "run" of at least 3 cards, that is, cards that have sequential values are worth the same amount of points as there are cards. (A run of 4 cards is worth 4 points). Aces are worth 1, and JQK are all worth 10.

- Cards whose values add up to 15 or 31 are worth 2 points. You may use any amount of cards for this.

- You may use any card over and over to form different combinations. If you have three cards of the value, you may count 3 separate pairs. However, if you have 4 cards forming a run, you may not count 2 runs of 3, only a run of 4.

- The output of the program is the sum of the points.

Examples
Input: "2C,10D,10H,AD,9C"
// 10D and 10H is a pair -> 2 points
// 2C, 9C, 10D, and 10H sum to 31 -> 2 points
Output: 4

Input: "10D,AH,JS,9H,QC"
// 9H, 10D, JS, and QC is a run of 4 -> 4 points
Output: 4

Input: "AH,AD,AS,AC,3C"
// AH and AD, AH and AS, AH and AC, AD and AS, AD and AC, and AS and AC are all pairs -> 12 points.
Output: 12

This is an interesting challenge, but I'm afraid it's already been done before.

How did you not see that listed under "possible duplicates" when you typed in the question?

I love the game and can understand why this is a great challenge. Unfortunately it is most definitely a dupe as I looked at doing the same. Why don't you post it in the sandbox and maybe we can work on a variation which is not a dupe and provides an interesting challenge? I have a couple of ideas.

and by the way, you missed out 1 for the Jack if it is the same suit as the turnover card and also points for the flush if all are the same suit (must be 5 if in the box/crib) :-)

and "Cards whose values add up to 15 or 31 are worth 2 points" is not strictly correct. 31 only counts when you are pegging, not in the hand.

@DJMcMayhem I previosly wrote the entire game in Java then ported to Javascript. Would be interested in seeing what golfing languages can really do with this. Would you support a variation on the theme after some time in the sandbox?

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


text:
Composite Factorization
This is similar to prime factorization, where you find the smallest prime factors of a number (i.e. 8 = 2 x 2 x 2). But this time, you are to return an array/list of the smallest composite factors of any given positive integer n. If n is prime, simply return an empty list.
Examples:

Prime:
n = 2
Result: []

Composite and Positive:
n = 4
Result: [4]

n = 32
Result: [4, 8]

n = 64
Result: [4, 4, 4]

n = 96
Result: [4, 4, 6]

Rules:

The product of the factors in the list must equal the input
Standard loopholes are banned
An array/list must be returned or printed (i.e. [4])
Your program must be able to return the same results for the same numbers seen in the examples above
The factors in the array/list can be strings so [4] and ["4"] are both equally valid
A prime number is any positive integer whose only possible factors are itself and 1. 4 returns [4] but is not prime since 2 is also a factor.
A composite number for this challenge any positive integer that has 3 or more factors (including 1) like 4, whose factors are 1, 2, and 4.

Clarifications:

Given a number such as 108, there are some possibilities such as [9, 12] or [4, 27]. The first integer is to be the smallest composite integer possible (excluding 1 unless mandatory) thus the array returned should be [4, 27] since 4 < 9.
All factors after the first factor need to be as small as possible as well. Take the example of 96. Instead of simply [4, 24], 24 can still be factored down to 4 and 6 thus the solution is [4, 4, 6].

Winning Criteria:
Shortest code wins since this is code-golf.

As an important test case you seemed to have missed, I assume the result for 32 is [4,8] (the first way I came up with fails that case).

Also, I think if you made the challenge simply undefined for non-positive integers then the question would have less of "how many characters is if-then-else in your language?"

@walpen Will edit momentarily

Should maybe add a test case like 42, where first composite factor is less than remaining single-prime factor (which just tripped up my attempt).

05AB1E, 8 bytes
Òā¨ÉÅ¡P¦

Try it online!
Explanation:
            # implicit input (example: 72)
Ò           # prime factorization ([2, 2, 2, 3, 3])
 ā          # indices ([1, 2, 3, 4, 5])
  ¨         # drop the last element ([1, 2, 3, 4])
   É        # is odd ([1, 0, 1, 0])
    Å¡      # split on 1s ([[], [2, 2], [2, 3, 3]])
      P     # product ([1, 4, 18])
       ¦    # drop the first element ([4, 18])
            # implicit output

Note that this correctly returns [] for prime inputs.

Jelly, 12 bytes
»0Æf×Ṫ$-¦×2/

Try it online!
How it works
»0Æf×Ṫ$-¦×2/  Main link. Argument: n

»0            Take the maximum of n and 0.
              Jelly's prime factorization does weird things for negative numbers.
  Æf          Take the prime factorization of the maximum.
        ¦     Conditional application:
    ×Ṫ$         Pop the last element of the array and and multiply all elements
                of the remaining array with it.
       -        Replace the element at index -1 with the corresponding element in
                the result.
              This effectively multiplies the last two elements of the array.
         ×2/  Multiply the factors in non-overlapping pairs. If the last element
              does not have a partner, leave it unmodified.

Haskell 150
Pretty basic answer but:
r n=p n$n-1
p 1 _=[]
p n 1=[n]
p n m
 |n`mod`m==0=p(n`div`m)(m-1)++r m
 |1>0=p n$m-1
i[x,y,z]=[x*y*z]
i(x:y:z)=x*y:i z
i _=[]
c n
 |n>0=i.r$n
 |1>0=[]

Works very straightforwardly: find all the prime factors of the input (the p function) in a way that produces them sorted ascending, and multiply them by twos (with the exception of multiplying three together if there are an odd number, to handle cases like 32 that prime factor into [2,2,2,2,2]. Example usage c 2880 = [4, 4, 4, 45].
Bonus fun
As a massively ineffecient prime generator: primes = filter (> 1) . zipWith (-) [2..] $ map (product . c) [1..].

JavaScript ES6 112

c=n=>{with(a=[]){for(i=k=1;i++<n;)for(;1^n%i;n/=i)push(++k%2?pop()*i:i);k%2||push(pop()*pop());return k<3?[]:a}}

test=k=>{console.log("n = "+k);console.log(c(k))};
test(-1);
test(0);
test(2);
test(4);
test(64);
test(96);
test(32);

Haskell, 106 104 101 bytes
c x=2/=sum[1|0<-mod x<$>[1..x]]
(x:r)%n|c x,mod n x<1,d<-div n x,c d=x:g d|1<3=r%n
e%n=e
g n=[4..n]%n

Try it online!
Less golfed and explanation:
c x = 2 /= sum[1|0<-map(mod x)[1..x]] -- counts number of divisors of x and returns true for all non-primes

g n = f [4..n] n            -- call f with a list of factor candidates and n

f []    n = []              -- if there are no factor candidates, return the empty list
f (x:r) n                   -- for the factor candidate x ...
    | c x,                  --    check if x is composite
      (d,m) <- divMod n x,  --    set d = n div x and m = n mod x
      m < 1,                --    n is divided by x if m = 0
      c d                   --    check that d is composite or 1
    = x : f (x:r) d         -- if all those checks are true append x to the list and determine the composites for d
    | otherwise = f r n     -- otherwise check the next candidate

Javascript (ES6), 94 bytes
n=>{for(a=[],d=2,l=q=0;n>1;)n%d?d++:(n/=d,q&&(a[l++]=q*d),q=q?0:d);q&&l&&(a[l-1]*=q);return a}

Ungolfed:
n=>{ //function declaration
  for(
    a=[], //the list
    d=2, //current factor
    l= //next index of the list
    q=0; //stored factor
    n>1; //while n>1
  )
    n%d? //if the factor is not a factor of current n
      d++ //go to next factor
      :( //else
        n/=d, //remove the factor
        q&& //if a factor is stored,
          (a[l++]=q*d), //add multiple of the saved factor and current factor
        q=q?0:d //store factor if it doesn't exist
      ); //end else
   //implicit for loop close
  q&& //if there is remaining factor
    l&& //if the input is not a prime
      (a[l-1]*=q); //place the factor in the last element in the list
  return a //return the list
} //end function

Perl 6, 83 bytes
my&f=->\n {my \p=min grep {n%%$_&!is-prime $_|n/$_},2..^n;Inf>p??flat p,f n/p!![n]}

Note: uses the is-prime builtin
Try it online!

78 bytes

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


text:
A bit, a nibble or byte?
Inspired by this challenge
Given an integer in the range 0 <= n < 2**64, output the minimum sized container it can fit in out of

bit: 1
nibble: 4
byte: 8
short: 16
int: 32
long: 64

Testcases:
0 -> 1
1 -> 1
2 -> 4
15 -> 4
16 -> 8
123 -> 8
260 -> 16
131313 -> 32
34359750709 -> 64

This is code-golf, so the shortest answer in bytes wins.

This would be considerably easier if 2 was an output too...

@ETHproductions It would but alas, it isn't (it took me far to long to write an algorithm that did it)

I wish I understood the problem. ... wait, all it wants is the amount of bits needed to contain the number, rounded to the next fundamental structure?

@z0rberg's basically find the smallest container that the number will fit in out of the ones given.

Thanks! I realized it when I wrote the comment and edited it too late. I guess I need a rubber duck to talk to...

@Daniel the answers here take a completely different approach to the other question. When I say 'inspired by' it does not mean 'duplicate of'. No answers could be trivially modified to be valid for this question

AFAIK if it had all integers, the answer would be ceil(log2(n))

05AB1E, 10 bytes
bg.²îD1Q+o

Explanation
bg         Push the length of the binary representation of input without leading zeros
  .²î      Push x = ceil(log2(length))
     D1Q+  Add 1 if x == 1 or add 0 otherwise
         o Push pow(2,x) and implicitly display it

Try it online!

Python, 39 bytes
f=lambda n:4**(n>1)*(n<16)or 2*f(n**.5)

Counts how many times one must take the square root for n to be below 16, with some special-casing to avoid outputs of 2.
If 2 were included, we could do
f=lambda n:n<2or 2*f(n**.5)

with True for 1.

41 bytes:
f=lambda n,i=1:i*(2**i>n)or f(n,i<<1+i%2)

Repeatedly doubles the exponent i until 2**i>n. Skips from i=1 to i=4 by shifting an additional bit when i is odd.
Alt 45 bytes:
f=lambda n,i=4:4**(n>1)*(2**i>n)or 2*f(n,i*2)

It never ceases to amaze me how you can come up with so many solutions for a problem. Basically as a programmer I have learned to find a solution to a problem and work with it until it works. Guess I still have a lot to learn about golf! Respect.

@xnor, how does your first answer output 1 when the square root of 0 or 1 is always 1 (infinite recursiveness in or 2*f(n**.5))?

@dfernan I believe the part after the or is only evaluated if the part before evaluates to something falsy (zero). For n=0, and for n=1, n>1 evaluates to False, which is treated as zero in a numeric expression, and n<16 evaluates to True, which is treated as one in a numeric expression. So 4**(n>1)*(n<16) is 1.

@trichoplax, that is right. Thanks for the explanation.

J, 19 bytes
Monadic verb taking the number on the right and spitting out the container size. There are a couple of equivalent ways of writing it so I've included both.
2^2(>.+1=>.)@^.#@#:
2^s+1=s=.2>.@^.#@#:

Explained by explosion:
2^2(>.+1=>.)@^.#@#: NB. takes one argument on the right...
                 #: NB. write it in binary
               #@   NB. length (i.e. how many bits did that take?)
  2          ^.     NB. log base 2 of that
   (>.     )@       NB. ceiling
      +1=>.         NB. +1 if needed (since no container is two bits wide)
2^                  NB. base 2 exponential

What's cool is we see two different ways of taking log base 2 in J. The first is the obvious 2^., which is a numerical logarithm. The second is #@#:, which can be read as "length of base-2 representation". This is almost equivalent to one-plus-floor-of-log-base-2, except that #:0 is the one-element list 0, which is exactly what we want. This beats 1+2<.@^.1&>. by 8 bytes.
In use at the REPL:
   f =: 2^2(>.+1=>.)@^.#@#:
   f 131313
32
   f 34359750709
64
   (,.f"0) 0 1 2 15 16 123 260
  0  1
  1  1
  2  4
 15  4
 16  8
123  8
260 16

Old, overly clever 20 byte solution.
2&^.(>.+1=>.&.)@#@#: NB. takes one argument on the right...
                #@#: NB. how many bits
2&^.                 NB. log base 2 of that
     >.              NB. ceiling
       +1=>.         NB. +1 if needed (since no container is two bits wide)
    (       &.)      NB. undo log base 2

Python, 53 50 49 bytes
lambda n:[w for w in[1,4,8,16,32,64]if n<2**w][0]

lambda n:[w for w in[1,4,8,16,32,64]if n<2**w][0] is one byte shorter

Was just about to post something similar. +1

Mathematica, 44 39 38 bytes
Thanks @orlp for 5 bytes and @MartinEnder for 1 byte.
FirstCase[{1,4,8,16,32,64},x_/;2^x>#]&

Finds the first the elements in the list {1, 4, 8, 16, 32, 64} such that 2^number is greater than the input.

Pip, 19 bytes
(a<2**_FI2**,7RM2i)

Try it online!
How it works
                     a is 1st cmdline arg, i is 0 (implicit)
         2**,7       Construct powers of 2 from 0 to 6 [1 2 4 8 16 32 64]
              RM2    Remove 2
       FI            Filter for elements for which:
 a<2**_                a is less than 2 to that element
(                i)  Get 0th item of resulting list and autoprint

JavaScript (ES7), 35 bytes
n=>[1,4,8,16,32,64].find(b=>2**b>n)

A recursive version such as f=(n,b=1)=>2**b>n&&b-2?b:f(n,b*2) should be slightly shorter.

Mathematica, 46 43 38 bytes
Thanks to JungHwan Min and Martin Ender for saving 3 bytes! Thanks to ngenisis for a big 5-byte savings!
2^⌈Log2@BitLength@#⌉/.{2->4,0->1}&

Unnamed function taking a nonnegative integer as input and returning a positive integer. BitLength@# computes the number of bits in the input, and then 2^⌈Log2@...⌉ computes the smallest power of 2 that's at least as large as the number of bits. Finally, /.{2->4,0->1} takes care of the special case that there's no "niblit" between bit and nybble, and also fixes the answer for the weird input 0.

Save 3 bytes by using BitLength@# instead of ⌊1+Log2@#⌋. Then instead of replacing ∞ with 1 you can replace 0, saving another 2 bytes and you're tied for first.

This can actually be done entirely with BitLength. See my answer

Julia, 40 bytes
n->filter(x->n<big(2)^x,[1;2.^(2:6)])[1]

This is an anonymous function that generates an array of the powers of 2 from 0 to 6, excluding 2, and filters it to only those elements x such that 2x is greater than the input. The first such element is the answer. Unfortunately this requires promoting 2 to a BigInt to avoid overflow on x = 64.
This is actually quite similar to orlp's Python answer, though I didn't see it before concocting this approach.
Try it online!

Perl 6, 30 bytes
{first 1+<*>$_,1,4,8,16,32,64}

+< is Perl 6's left bit shift operator, which many other languages call <<.

Haskell, 31 bytes
f n=[2^i|i<-0:[2..],2^2^i>n]!!0

32-byte alt:
f n|n<2=1|n<16=4|1>0=2*f(sqrt n)

Java, 143 bytes.
int f(long a){a=Long.toBinaryString(a).length();if(a<2)return 1;if(a<5)return 4;if(a<9)return 8;if(a<17)return 16;if(a<33)return 32;return 64;}

I know I can make this shorter, Io do it when I'm at a computer.

save 50 bytes:  return a<2?1:a<5?4:a<9?8:a<17?16:a<33?32:64;

@Mindwin I know, but I'm traveling and won't have access to a computer for a while. I'll get around to it.

Does the score make it a... love byte?

Haskell, 43 bytes
f x=head$filter((>x).(2^))$[1,4,8,16,32,64]

Java 8, 65 55 bytes
This is a lambda expression which takes a long and returns an int. Never golfed in Java before, so this should be easily beatable:
x->{int i=1;while(Math.pow(2,i)<=x)i<<=1+i%2;return i;}

Try it online!

For 47 bytes, we could have:
x->{int i=1;while(1L<<i<=x)i<<=1+i%2;return i;}

However, 1L<<i overflows for return values larger than 32, so this fails for the final testcase.

This returns 4 when tested with 16 when it is supposed to return 8. Also you can still golf this solution by removing the brackets around i<<=1+i%2; since without {}s, the while loop will only execute the next line

@KritixiLithos should be fixed now - sorry, my Java's gone rusty...

Ruby, 39 36 bytes
->n{2**[0,*2..6].find{|p|2**2**p>n}}

Thanks G B for helping golf

Should also work without parentheses. Also, the list could be 0,2,3,4,5,6 and using 1<<2**p.

... because then you could use 0,*2..6.

Stacked, 34 30 bytes
@n 1 2 6|>2\^,:n 2 log>keep 0#

or
{!1 2 6|>2\^,:n 2 log>keep 0#}

The first takes input on the TOS and leaves output on TOS; the second is a function. Try it here!
Explanation
@n 1 2 6|>2\^,:n 2 log>keep 0#
@n                               set TOS to `n`
   1 2 6|>2\^,                   equiv. [1, ...2 ** range(2, 6)]
              :                  duplicate it
               n                 push `n`
                 2 log           log base-2
                      >          element-wise `>`
                       keep      keep only truthy values
                            0#   yield the first element

Here's an example of it working on the repl:
> 8    (* input *)
(8)
> @n 1 2 6|>2\^,:n 2 log>keep 0#    (* function *)
(4)
>    (* output *)
(4)

Test cases
> {!1 2 6|>2\^,:n 2 log>keep 0#} @:f
()
> (0 1 2 15 16 123 260 131313 34359750709) $f map
((1 1 4 4 8 8 16 32 64))
>

Or, as a full program:
{!1 2 6|>2\^,:n 2 log>keep 0#} @:f

(0 1 2 15 16 123 260 131313 34359750709) $f map

out

bash, 49 bytes 48 bytes
for((y=1;$[y==2|$1>=1<<y];$[y*=2])){ :;};echo $y

or
for((y=1;$[y==2|$1>=1<<y];)){ y=$[y*2];};echo $y

Save in a script and pass the number to be tested as an argument.
Edit: Replaced || with |, which works because the arguments are always 0 or 1.
Note: This works for integers up to the largest positive integer that your version of bash can handle. If I have time, I'll modify it to work up to 2^64-1 in versions of bash that use 32-bit signed arithmetic.
In the meantime, here's a 64-byte solution that works for arbitrarily large numbers (in any bash version):
for((x=`dc<<<2o$1n|wc -c`;$[x==2||x&(x-1)];$[x++])){ :;};echo $x

Racket 45 bytes
(findf(λ(x)(>(expt 2 x)m))'(1 4 8 16 32 64))

Ungolfed:
(define (f m)
  (findf (λ (x) (> (expt 2 x) m))          ; find first function
         '(1 4 8 16 32 64)))

Other versions:
(define (f1 m)
  (for/last ((i '(1 4 8 16 32 64))         ; using for loop, taking last item
             #:final (> (expt 2 i) m))     ; no further loops if this is true
    i))

and using string length:
(define (f2 m)
  (for/last
      ((i '(1 4 8 16 32 64))
       #:final (<= (string-length
                    (number->string m 2))  ; convert number to binary string
                   i))
    i))

Testing:
(f 0)
(f 1)
(f 2)
(f 15)
(f 16)
(f 123)
(f 260)
(f 131313)
(f 34359750709)

Output:
1
1
4
4
8
8
16
32
64

Mathematica, 30 bytes
2^(f=BitLength)[f@#-1]/. 2->4&

Explanation:
Let N be the set of nonnegative integers. Define two functions on N, BitLength and NextPower as follows:
BitLength(n) := min {x in N : 2^x - 1 >= n}
NextPower(n) := 2^(min {x in N : 2^x >= n})

This solution essentially calculates NextPower(BitLength(n)) given an integer n >= 0. For n > 0, we can see that NextPower(n) = 2^BitLength(n-1), so NextPower(BitLength(n)) = 2^BitLength(BitLength(n)-1).
Now the Mathematica BitLength built-in agrees with the definition I gave for n >= 0. For n < 0, BitLength[n] == BitLength[BitNot[n]] == BitLength[-1-n], so BitLength[-1] == BitLength[0] == 0. Thus we get the desired answer of 1 for n==0.
Since we skip straight from bit to nibble, we have to replace answers of 2 with 4.

Nicely constructed! (Shame that the space is necessary.)

Thunno, \$ 13 \log_{256}(96) \approx \$ 10.70 bytes
bL2AYZmD1=+2@

Attempt This Online!
Port of Osable's 05AB1E answer.
Explanation
bL2AYZmD1=+2@  # Implicit input
bL             # Length of binary representation
  2AY          # Log base 2 of above
     Zm        # Ceil of above
        1=     # Equals one?
       D  +    # If true, add one; else, pass
           2@  # Two to the power of above
               # Implicit output

PHP, 49 46 44 bytes
echo(2**ceil(log(log(1+$argn,2),2))-2?:2)+2;

Run like this:
echo 16 | php -R 'echo(2**ceil(log(log(1+$argv[1],2),2))-2?:2)+2;';echo

Explanation
echo                       # Output the result of the expression
  (
    2**                    # 2 to the power
      ceil(log(            # The ceiling of the power of 2 of bitsize
        log(1+$argn,2),    # Number of bits needed
        2
      ))
      - 2 ?:               # Subtract 2 (will be added back again)
      2;                   # If that results in 0, result in 2 (+2=4).
  ) + 2                    # Add 2.

Tweaks

Saved 3 bytes by getting rid of the $r= assignment
Saved 2 bytes by using -R to make $argn available

Octave, 40 36 31 29 bytes
Simple anonymous function. It is assumed that the input value is an integer - see the caveat at the end.
@(a)(b=2.^[0 2:6])(a<2.^b)(1)

The code works as follows:

First an array of the allowed bit lengths (1,4,8,16,32,64) is created and saved to b.

Next we find the number of bits required to store the input number a by comparing with the maximum size of each container in b to see which are big enough.

We then use the resulting index vector to extract the container size from b again.

Finally we take the first element in the resulting array which will be the smallest container possible.

You can try it online here.
Simply run the following code, and then do ans(x).

The only caveat with this is that double precision is used for constants by default which means that it only works with numbers up to the highest value representable by a double precision float that is less than 2^64.
This can be fixed by ensuring that the number that is supplied to the function is an integer rather than a double. This can be achieved by calling the function for example with: ans(uint64(x)).

CJam, 18 bytes
2ri2b,2mLm]_({)}|#

Try it online!
Explanation
2                   Push 2
 ri                 Read an integer from input
   2b,              Get the length of its binary representation
      2mLm]         Take the ceiling of the base-2 log of the length
           _(       Duplicate it and decrement it
             {)}|   Pop the top element, if it's 0, increment the next element
                     Effectively, if ceil(log2(input)) was 1, it's incremented to 2,
                     otherwise it stays the same.
                 #  Raise 2 to that power

Vyxal, 9 bytes
ʀ~‹E≬E?>c

Try it Online!
This took a lot of experimenting to get to 9 bytes. Like at least 20 minutes of trying and trying.
Explained
ʀ~‹E≬E?>c
ʀ          # The range [0, input]
 ~‹        # With 1 removed (filter by decrement, could also be 1o, but that's not as stylish)
   E       # with 2 raised to the power of each item. This creates a list of [1, 4, ...]
    ≬   c  # get the first item of that where
     E     #   2 to the power of the item
      ?>   #   is greater than the input

8 with M flag

Pyke, 13 bytes
7Zm@2-#2R^<)h

Try it here!
7Zm@          -   [set_bit(0, i) for i in range(7)] <- create powers of 2
    2-        -  ^.remove(2)
      #    )h - filter(^, V)[0]
       2R^    -   2 ** i
          <   -  input < ^

C, 71 52 bytes
i;f(long long n){for(i=1;n>>i;i*=2);return i-2?i:4;}

Wouldn't an input of (1<<15)+1 or more break this because of the signed behavior of long long? The type you really want is uint64_t which necessitates #include <stdint.h> which is still a loser compared to unsigned long long! Headers are the bane of golfing in c.

@dmckee I guess it could break it, but it seems to work at least on my computer. Haven't found an example which wouldn't work. I thought of using unsigned long long or uint64_t, but since it seems to work with long long I went with it.

QBIC, 27 bytes
:~a<2|_Xq]{~a<2^t|_Xt\t=t*2

Explanation
:        Get cmd line parameter N, call it 'a'
~a<2     IF 'a' is 0 or 1 (edge case)
|_Xq]    THEN quit, printing 1 ('q' is auto-initialised to 1). ']' is END-IF
{        DO - infinite loop
    2^t  't' is our current number of bits, QBIC sets t=4 at the start of the program.
         2^t gives the maximum number storable in t bytes.
 ~a<     IF the input fits within that number,
|_Xt     THEN quit printing this 't'
\t=t*2   ELSE jump to the next bracket (which are spaced a factor 2 apart, from 4 up)
         DO-loop is auto-closed by QBIC.

PHP, 43 bytes
for(;1<<2**$i++<=$argn;);echo 2**$i-=$i!=2;

Run with echo <number> | php -R '<code>'.
loops $i up until 2**(2**$i) is larger than input. (Tweak: << instead of ** to eliminate parens)
After the loop, $i is one too high; so it gets a decrement before calculating the output
- but not for $i==2.


text:
Optimal cheating at BINGO
You're sick of other players smugly announcing "BINGO" and walking triumphantly past you to claim their prize. This time it will be different. You bribed the caller to give you the BINGO calls ahead of time, in the order they will be called. Now you just need to create a BINGO board that will win as early as possible for those calls, guaranteeing you a win (or an unlikely tie).
Given a delimited string or list of the calls in order, in typical BINGO format (letters included, e.g. B9 or G68, see the rules for more info), output a matrix or 2D list representing an optimal BINGO board for those calls. Assume input will always be valid.
BINGO Rules:

5x5 board
A "BINGO" is when your card has 5 numbers in a row from the numbers that have been called so far.
The center square is free (automatically counted towards a BINGO), and may be represented by whitespace, an empty list, -1, or 0.
The 5 columns are represented by the letters B,I,N,G,O, respectively.
The first column may contain the numbers 1-15, the second 16-30, ..., and the fifth 61-75.
The letters and numbers taken for input may optionally be delimited (by something that makes sense, like a , or space) or taken as a tuple of a character and a number.
Output requires only numbers in each place in the matrix.
Squares that will not contribute to your early BINGO must be valid, but do not have to be optimal.
This is code-golf, shortest code wins

Examples:
I'm using this input format for the examples, because it's shorter. See the section above for acceptable input/output formats.
O61 B2 N36 G47 I16 N35 I21 O64 G48 O73 I30 N33 I17 N43 G46 O72 I19 O71 B14 B7 G50 B1 I22 B8 N40 B13 B6 N37 O70 G55 G58 G52 B3 B4 N34 I28 I29 O65 B11 G51 I23 G56 G59 I27 I25 G54 O66 N45 O67 O75 N42 O62 N31 N38 N41 G57 N39 B9 G60 I20 N32 B15 O63 N44 B10 I26 O68 G53 I18 B12 O69 G49 B5 O74 I24

Possible Output (this has a horizontal BINGO in 3rd row. A diagonal is also possible.):
[[11,25,42,53,68],
 [ 6,22,32,57,62],
 [ 2,16, 0,47,61],
 [ 3,17,37,59,75],
 [ 9,19,41,46,70]]

N42 N34 O66 N40 B6 O65 O63 N41 B3 G54 N45 I16 O67 N31 I28 B2 B14 G51 N36 N33 I23 B11 I17 I27 N44 I24 O75 N38 G50 G58 B12 O62 I18 B5 O74 G60 I26 B8 I22 N35 B1 B4 G53 O73 G52 O68 B10 O70 I30 G59 N43 N39 B9 G46 G55 O64 O61 I29 G56 G48 G49 I19 G57 N37 O72 I25 N32 B13 B7 B15 O71 I21 I20 O69 G47

Must be a vertical BINGO in 3rd (N) column (because 4 N's came before one of each B,I,G,O):
[[11,25,42,53,63],
 [ 2,22,34,57,65],
 [ 6,16, 0,47,66],
 [ 3,17,41,54,75],
 [ 9,19,40,46,70]]

You say that the letters are included. What do they mean?

@muddyfish Under BINGO rules: The 5 columns are represented by the letters B,I,N,G,O, respectively.

Mathematica, 302 bytes
(b=Prepend;i=1;n=15#&@@#-15+Range@5&;g=#~b~{N,0};o={#2,#3,#,##4}&@@#&;While[(l=Length@Union[t=(k=Take)[#&@@@g,i]])<5&&Max[#2&@@@Tally@t]<5,i++];If[l<5,m=#&@@Commonest@t;If[m===#,o[g~k~i/.{m,x_}->x/.{_,_}->Nothing],n@#2]&,o@DeleteDuplicates@b[n@#2,<|#->#2&@@@Reverse@g|>@#]~k~5&]~MapIndexed~{B,I,N,G,O})&

Unnamed function taking as its argument a list of ordered pairs, such as {{N,42},{N,34},{O,66},{N,40},...} (note that the first element in each ordered pair is not a string but rather a naked symbol), and returning a 2D list of integers, where the sublists represent columns (not rows) of the bingo board.
Output for the first test case:
{{1,3,2,4,5},{17,18,16,19,20},{31,32,0,33,34},{46,48,47,49,50},{62,63,61,64,65}}

In general, when the earliest possible bingo occurs because of a number called in each of the B/I/G/O rows, then those numbers will be in the center row; each column will otherwise contain the four smallest possible numbers (taking the already used number into account). For example, if the first test case is changed so that the second number called is B12 rather than B2, then the first column of the output board will be {1,2,12,3,4}.
Output for the second test case:
{{1,2,3,4,5},{16,17,18,19,20},{42,34,0,40,41},{46,47,48,49,50},{61,62,63,64,65}}

In general, when the earliest possible bingo occurs because of five numbers called in a single column (or four called in the N column), then the remaining four columns contain their five smallest possible numbers in order.
If the second test case is changed from {{N,42},{N,34},{O,66},{N,40},...} to {{O,72},{O,74},{O,66},{N,40},...} (only the first two entries changed), then the output is:
{{1,2,3,4,5},{16,17,18,19,20},{31,32,33,34,35},{46,47,48,49,50},{74,66,72,65,63}}

Somewhat ungolfed version:
(b=Prepend;i=1;n=15First[#]-15+Range[5]&;g=b[#,{N,0}];o={#2,#3,#,##4}&@@#&;
While[
    (l=Length[Union[t=(k=Take)[Apply[#&,g,{1}],i]]])<5
  &&
    Max[Apply[#2&,Tally[t],{1}]]<5,
  i++];
MapIndexed[
  If[l<5,
    m=First[Commonest[t]];If[m===#,o[k[g,i]/.{m,x_}->x/.{_,_}->Nothing],n[#2]]&,
    k[
      o[DeleteDuplicates[b[n[#2],Association[Apply[#->#2&,Reverse[g],{1}]][#]]]]
    ,5]&
  ],{B,I,N,G,O}
])&

The first line is mostly definitions to shorten the code, although g prepends the center square {N,0} to the input to simplify the bingo-finding. (The n function gives the smallest five legal bingo numbers in the #th column, 1-indexed. The o function takes a 5-tuple and moves the first element so that it's third.)
The While loop in lines 2-6 finds the smallest initial segment of the input that contains a bingo. (The third line tests for one-in-each-column bingos, while the fifth line tests for single-column bingos).
For any function F, the operator MapIndexed[F,{B,I,N,G,O}] (starting in line 7) produces the 5-tuple {F{B,1},F{I,2},F{N,3},F{G,4},F{O,5}} (well, technically it's {F{B,{1}},...}); we apply a function F that creates a bingo-board column out of its two arguments. That function, however, depends on which type of bingo was found: line 8 is true when we have a single-column bingo, in which case the function (line 9) uses the relevant input numbers in the bingo column and default numbers in the other columns. In the other case, the function (lines 10-12) uses the relevant input numbers in the center of each column and default numbers elsewhere.

What, no built-in Bingo function?

—wait, built-in Bingo isn't disallowed?

JavaScript (ES6) 372 Bytes
Can probably still be golfed a bit, but I don't see how. Suggestions are much appreciated ;)
A=a=>[1,2,3,4,5].map(x=>x+15*a),F=a=>{b=[[],[],[i=0],[],[]],a.replace(/[^0-9 ]/g,"").split` `.some(x=>{b[--x/15|(c=0)].push(++x);return b.some((x,i)=>(d=x.length)>4||d==1&i-2&&++c>3)});for(e=[A(0),A(1),A(2),A(3),A(4)];i<5;a=b[i][0],b[i][0]=b[i][2],b[i++][2]=a)for(j=0;j<5&b[i].length<5;j++)b[i][j]<i*15+5?e[i].splice(e[i].indexOf(b[i][j]),1):b[i][j]=e[i].shift();return b}


text:
Ruby on Rails (or Trackety Track)
You are Ruby, a railway engineer. Your task is to lay track in any given valley such that it visits every station (M). The amount of track laid is not important, but it must be laid in one continuous path which starts and ends at the valley entrance/exit point (>) and does not, at any point cross itself. There are a few other constraints: mountains(^) are impassable so you must go around them, rivers(~) must be crossed using a bridge(X), and the edge of the valley (#) is also impassable.
The Rules of the Track
If track is not laid properly there will be derailments and nobody wants that, so here are the rules over track placement.
There are four kinds of track: - | / \.
Here's how each one may be combined with the others:
Allowed combinations from - (in the centre of each example):
#####  #####  #####  #####  #####  #####  #####
#   #  #   #  #\  #  #   #  #  /#  #\ /#  #   #
#---#  # --#  # --#  #-- #  #-- #  # - #  # - #
#   #  #/  #  #   #  #  \#  #   #  #   #  #/ \#
#####  #####  #####  #####  #####  #####  #####

- may never be combined with |. This is too sharp a turn for the trains to make safely.
Allowed combinations from / (in the centre of each example):
#####  #####  #####  #####  #####  #####  #####
#  /#  #  -#  #  |#  #  /#  #  /#  #  -#  #  |#
# / #  # / #  # / #  # / #  # / #  # / #  # / #
#/  #  #/  #  #/  #  #|  #  #-  #  #|  #  #-  #
#####  #####  #####  #####  #####  #####  #####

\ may never be combined with /. This is too sharp a turn for the trains to make safely.
Allowed combinations from \ (in the centre of each example):
#####  #####  #####  #####  #####  #####  #####
#\  #  #-  #  #|  #  #\  #  #\  #  #-  #  #|  #
# \ #  # \ #  # \ #  # \ #  # \ #  # \ #  # \ #
#  \#  #  \#  #  \#  #  |#  #  -#  #  |#  #  -#
#####  #####  #####  #####  #####  #####  #####

Allowed combinations from | (in the centre of each example):
#####  #####  #####  #####  #####  #####  #####
# | #  #\  #  #  /#  # | #  # | #  #  /#  #\  #
# | #  # | #  # | #  # | #  # | #  # | #  # | #
# | #  # | #  # | #  #/  #  #  \#  #  \#  #/  #
#####  #####  #####  #####  #####  #####  #####

Tracks may combine with the stations, bridges and valley entrance/exit in the following ways:
#####  #####  #####
#\|/#  #\|/#  #/  #
#-M-#  #-X-#  >-  #
#/|\#  #/|\#  #\  #
#####  #####  #####

Stations have turn-tables, so it's permissible to leave a station at a sharp angle (though not back the way you came - you wouldn't want to crash into the next scheduled train coming the other way!).
Bridges are for crossing rivers so you must exit the bridge on the opposite side of the river that you entered it.
Input
Input will be via STDIN for programs or a function argument for functions. If your function needs a name in order for me to run it on my input then that name declaration should be included in the byte count.
The input will be a single string with line-breaks. Each line within your input will always be the same length as the others, giving you a rectangular input. The edge of the input will always be solid and impassable (#) except for the point of entry. Any given input will have at least one valid answer.
Output
Your output should be returned as a single string with line-breaks from a function, or printed/echoed to the screen for full programs.
The output should be the same as the input but with the track characters added.
Scoring
Winner will be the shortest code in bytes.
Test cases
###########
#    M    #
#   ^     #
>  ^^  M  #
#    ^    #
#~~~~~~~~~#
# M       #
#     ^^  #
#        M#
###########

#################
#               #
#   M         M #
#       ^       #
#        ^ M    #
#~~~~~~~^       #
#               #
#   ^           #
#   M^          #
#    ^          #
> ^^^          M#
#               #
#        M      #
#################

###############
# M   ~       #
#     ~       #
>     ~    M  #
#     ~       #
#     ~       #
#     ~       #
###############

Possible solutions to test cases
###########
# ---M    #
#/  ^ \   #
>  ^^  M  #
#\   ^ |  #
#~X~~~~X~~#
# M     \ #
#  \  ^^ |#
#   -----M#
###########

#################
#               #
#   M---------M #
#   |   ^    /  #
#  /     ^ M-   #
#~X~~~~~^  |    #
# |         \   #
#  \^        \  #
# --M^        \ #
#/   ^         |#
> ^^^          M#
#\            / #
# -------M----  #
#################

###############
# M   ~       #
#/ \  ~       #
>   --X----M  #
#\    ~    |  #
# \   ~   /   #
#  ---X---    #
###############

Finally! This challenge has been in the Sandbox forever!

@mbomb007 Not quite, there were 4 months between this site starting and the question being posted in the sandbox ;-)

I can't wait to see someone solve this one using Ruby on Rails

Are rivers always horizontal only?

@briantist No. They are in both the examples, but they could be in any direction.

@Gareth can they have turns? Can they be wider than one cell?

@MartinEnder Turns - yes. Wider than 1 cell - no.

Oh boy. Are there any time/memory constraints; Can we just brute-force it?

@Blacksilver No strict constraints, but if I can't run it to completion on the two test inputs I won't be able to upvote or accept the answer.

I just realized brute-force is a terrible idea since the possible solutions is n^4 for a valley with n spaces. Maybe if I limit it to possible connections from there... n^3ish, not as bad

To clear up the confuzzlement, I've added another test case to show vertical rivers.

wait - What if we need to move just one space vertically while going horizontally?

@Blacksilver Yes, I had to change my test inputs after updating the question in the sandbox for that reason. Assume that any given input will have at least one valid answer.

@LliwTelracs I think I see what you mean - the crossing on the right in my test solution is too close to the valley edge. I'll alter that test case now.

@LliwTelracs I don't see the mistake in the second test solution though?

@LliwTelracs No, they don't have to be.

Would I be correct in saying that you can only turn up to 45 degrees when going across a bridge? Or are you able to turn up to 90 degrees?

@LliwTelracs You can turn up to 90 degrees when crossing a bridge.

So do bridges act like normal rails except that you can only exit in a straight line from them? It might help if you gave all the individual examples for a bridge with a diagonal entry and a bridge with a vertical entry.

@LliwTelracs The only rule with a bridge is that you must exit on the opposite side of the river.

If the rivers can end at any given point, what is the opposite side of the river at the end of a river.

@LliwTelracs Okay, I see what you're getting at. At the end of a river imagine that the line formed by the last two river characters stretches off into infinity. You need to exit the bridge on the opposite side of that imaginary line.

Can rivers fork?

@LliwTelracs For this question, no.

My head hurts. I have been working on this and it is so hard

@DownChristopher I can help - but would you share the bounty if you do so?

Forget shortest code -- Let's just get something that WORKS first...... this is like the next GoL Tetris challenge...

Can you place bridges over land? (Question about Abusing Rules)

@HyperNeutrino More like: the WAY AHEAD OF TIME GoL Tetris challenge.

@HyperNeutrino No, you can only use bridges over rivers.

@SIGSEGV Good point. This was sandboxed really early, right?

@HyperNeutrino Correct.

Valley entrances hurts my head badly :(

..I just want to put T(Teleporter) around the stations to teleport the train from one station to another

Can input be taken "like this"?

@HyperNeutrino I'm not sure what you mean. Are you asking if the input can be embeded in the code? If so, then no. It would need to be from STDIN or from a function argument (though there's nothing to stop you doing embedding it whilst you are developing an answer).

@HyperNeutrino Just asking- Did you just attempt to put bridges literally everywhere

@SIGSEGV Maybe... Well I mean I didn't make code to do that because I knew OP wouldn't allow it :P

@Gareth I'm wondering if I can take input with quotes around it (the single string)

@HyperNeutrino If you want to add quotes around the string I have no objection to that.

Introducing bogorail

@SIGSEGV for sure. If we get it working I made a chat here it ended up on sci-fi SE as that is my main.

Python 2, 3990 3430 4412 4313 bytes
This is a basically an A* with a ugly heuristic and an ugly getChildren method. To run the 3 test cases consecutively takes 6.5s on my machine. The function f is the solution here. It takes the map as a string and returns the solved map as a string.
from itertools import*
import sys
from Queue import*
A,B,C,D,E,F,G=">|\\/-MX";H=range;I=permutations;J=set;K=abs;L=len
class M:
	@staticmethod
	def T(a):return a in">|\\/-MX"
	@staticmethod
	def C(a,b,c,d,x,y,e):
		if not M.T(d)or not M.T(e):return 0
		if e in"MX"and d in"MX"and e!=d:return 1
		if d==A:return x>0 and(e==D and y==-1 or e==E and y==0 or e==C and y==1)
		if d==F:return e==C and K(x+y)==2 or e==D and x+y==0 or e==B and x==0 or e==E and y==0
		if d==G:
			if b!=0!=c and K(b-x)+K(c-y)==1:return 0
			return e==C and K(x+y)==2 or e==D and x+y==0 or e==B and x==0 or e==E and y==0
		if e!=""and e in"MX>"and a!=""and a in"MX>":return M.C("",0,0,a,-b,-c,d)and M.C("",0,0,e,-x,-y,d)
		elif e!=""and e in"MX>"and a!="":return M.C("",0,0,d,b,c,a)and M.C("",0,0,e,-x,-y,d)
		elif e!=""and e in"MX>"and a=="":return M.C("",0,0,e,-x,-y,d)
		elif a!=""and a in"MX>":return M.C("",0,0,a,-b,-c,d)and M.C("",0,0,d,x,y,e)
		f=[[E,-1,0,E,1,0,E],[D,-1,1,E,1,0,E],[C,-1,-1,E,1,0,E],[E,-1,0,E,1,1,C],[E,-1,0,E,1,-1,D],[C,-1,-1,E,1,-1,D],[D,-1,1,E,1,1,C],[D,-1,1,D,1,-1,D],[D,-1,1,D,1,-1,E],[D,-1,1,D,1,-1,B],[B,-1,1,D,1,-1,D],[E,-1,1,D,1,-1,D],[B,-1,1,D,1,-1,E],[E,-1,1,D,1,-1,B],[C,-1,-1,C,1,1,C],[C,-1,-1,C,1,1,E],[C,-1,-1,C,1,1,B],[B,-1,-1,C,1,1,C],[E,-1,-1,C,1,1,C],[B,-1,-1,C,1,1,E],[E,-1,-1,C,1,1,B],[B,0,-1,B,0,1,B],[C,-1,-1,B,0,1,B],[D,1,-1,B,0,1,B],[B,0,-1,B,-1,1,D],[B,0,-1,B,1,1,C],[D,1,-1,B,1,1,C],[C,-1,-1,B,-1,1,D]];g=0;h=[a,b,c,d,x,y,e];j=[0,3][a==""]
		for k in f:
			l=1;m=1;n=[k[6],k[4],k[5],k[3],k[1],k[2],k[0]]
			for i in H(j,L(k)):
				if k[i]!=h[i]:l=0
				if n[i]!=h[i]:m=0
			if l or m:g=1
		return g
	def __init__(s,a):s.m=[list(x)for x in a.split("\n")]
	def __str__(s):return"\n".join(["".join(x)for x in s.m])
	def A(s):return str(s)
	def B(s):return L(s.m[0])
	def D(s):return L(s.m)
	def E(s):
		a=[]
		for y in H(1,s.D()-1):
			for x in H(1,s.B()-1):
				if s.J(x,y)==F and L(s.H(x,y, F))==0:a+=[(x,y)]
		return a
	def F(s):
		for y in H(s.D()):
			for x in H(s.B()):
				if s.J(x,y)==A:return(x,y)
	def G(s):
		a=0
		for y in H(0,s.D()-1):
			for x in H(0,s.B()-1):
				b=s.J(x,y)
				c=L(s.H(x,y,b))
				if b==A:
					if c==0:a=(x,y)
					c=0
				if c==1:return(x,y)
		if a!=0:
			return a
		raise ValueError()
	def J(s,x,y):return s.m[y][x]
	def K(s,x,y,b):
		a=[[i for i in row]for row in s.m];a[y][x]=b
		return"\n".join("".join(x)for x in a)
	def H(s,x,y,c):
		d=[];e=[]
		for a,b in J(I([-1,-1,0,1,1],2)):
			g=s.J(x+a,y+b)
			if M.T(g)and M.C("",0,0,c,a,b,g):e+=[[g,a,b]]
		if L(e)==1:return[e[0][0]]
		if L(e)==0:return[]
		for g,h in I(e,2):
			i,j,k=g;l,m,n=h;o=x + m;p=y + n
			if M.C(i,j,k,c,m,n,l):
				if l==F:
					if L(s.H(o,p,l))>=1:d+=[l]
				else:d+=[l]
		return d
	def I(s,x,y,a,b):
		if a==0 or b==0:return 0
		a=s.J(x+a,y);b=s.J(x,y+b)
		return(M.T(a)or a==F)and(M.T(b)or b==F)
class P:
	@staticmethod
	def A(x0,y0,x1,y1):return K(x0-x1)+4*K(y0-y1)
	def __init__(s,a,p,t=0,g=0):
		s.a=[];s.b=p;s.c=a;s.d=[a];s.e=t;s.f=g
		if p:s.d=p.d[:];s.d+=[a];s.e=p.e;s.f=p.f
		s.g=M(a);s.h=s.B()
	def __str__(s):return s.g.A()
	def B(s):
		a=0;b=1;c=0
		try:c=s.g.G()
		except:a=1
		d=s.g.E();e=s.g.F();g=[]
		if L(d)==0 and not a:g=P.A(c[0],c[1],e[0],e[1])+b
		elif L(d)==0 and a:return 0
		elif c:
			h,i=c
			for j in combinations(d,L(d)):
				k=0
				for x,y in j:k+=P.A(h,i,x,y);h,i=x,y
				g+=[k]
			g=min(g);g+=s.g.B()+s.g.D()+b
		else:return sys.maxint
		if g<1:return 0
		return g
	def C(s):
		try:a=s.g.G()
		except:s.a=[];return
		b=s.g.J(a[0],a[1]);c=("",0,0);e=(0,0)
		for x,y in J(I([-1,-1,0,1,1],2)):
			g,h=a[0]+x,a[1]+y;i=s.g.J(g,h)
			if M.T(i)and M.C("",0,0,i,x,y,b):c=(i,x,y)
			if i=="~":e=(x,y)
		for x,y in J(I([-1,-1,0,1,1],2)):
			g,h=a[0]+x,a[1]+y;i=s.g.J(g,h)
			if not(i in"^#"or M.T(i)):
				for j in"-|\\/":
					if i=="~":
						j=G
						if c[0]==G:continue
					if c[0]==G and K(e[0])==1 and y==c[1]:continue
					if c[0]==G and K(e[1])==1 and x==c[0]:continue
					k=s.g.H(g,h,j);l=L(k)
					if(l==1 or l==2 and A in k)and M.C(c[0],c[1],c[2],b,x,y,j)and not s.g.I(a[0],a[1],x,y):
						try:s.a+=[P(s.g.K(g,h,j),s)]
						except:pass
def f(x):
	d=[];a=[];b=PriorityQueue();b.put((0,P(x,0)))
	while not d and b.qsize():
		c=b.get()[1];c.C();a+=[c.c]
		for e in c.a:
			if e.c not in a:
				if not e.h:d=e.d
				b.put((e.h,e))
	return d[-1]

Try it online!
Test Cases
Test 1

###########
# ---M    #
#/  ^ \   #
>  ^^  M  #
#\   ^ |  #
#~X~~~~X~~#
# M    |  #
#  \  ^^\ #
#   -----M#
###########

Test 2

#################
#               #
#   M---------M #
#  /    ^    /  #
# |      ^ M-   #
#~X~~~~~^   \   #
# |          |  #
#  \^        |  #
# --M^       |  #
#/   ^-       \ #
> ^^^/ \       M#
#\  /   \     / #
# --     M----  #
#################

Test 3

###############
# M   ~       #
#/ \  ~       #
>   --X----M  #
#\    ~   /   #
# ----X---    #
#     ~       #
###############

Source Code
A* State + A* Solver Class
I actually golfed these out of my solution. But they exist in my 'readable' version. The State class is generic and meant to be implemented. The Solver class takes a start state and then follows that states heuristic getDist.
from Queue import PriorityQueue

# A* State
class State(object):
    # The type of value should be a primative
    def __init__(self, value, parent, start=0, goal=0):
        self.children = []
        self.parent = parent
        self.value = value
        self.dist = 0
        if parent:
            self.path = parent.path[:]
            self.path.append(value)
            self.start = parent.start
            self.goal = parent.goal
        else:
            self.path = [value]
            self.start = start
            self.goal = goal

    # Implement a heuristic for calculating the distance from this state to the goal
    def getDist(self):
        pass

    # Implement a way to create children for this state
    def createChildren(self):
        pass

# A* Solver
# Note: if maxmin = 1: Solver tries to minimize the distance
#       if maxmin = -1: Solver tries to maximize the distance
class AStar_Solver:
    def __init__(self,startState,maxmin=1):
        self.path = []
        self.visitedQueue = []
        self.priorityQueue = PriorityQueue()
        self.priorityQueue.put((0,startState))
        self.startState = startState
        self.maxmin = maxmin
        self.count = 0

    # Create a png of the string 'qPop'
    def imager(self,qPop):
        # Imager(qPop,str(self.count).rjust(5,"0")+".png")
        # print str(qPop)+"\n"
        self.count += 1

    # Solve the puzzle
    def solve(self):
        while(not self.path and self.priorityQueue.qsize()):
            closestChild = self.priorityQueue.get()[1]
            self.imager(str(closestChild))
            closestChild.createChildren()
            self.visitedQueue.append(closestChild.value)
            for child in closestChild.children:
                if child.value not in self.visitedQueue:
                    if not child.dist:
                        self.imager(str(child))
                        self.path = child.path
                        break
                    self.priorityQueue.put((self.maxmin*child.dist,child))
        if not self.path:
            print "Goal was not reachable"
        return self.path

State Class
This is the implementation of the A* state class. The most important method here is getDist, it is the heuristic for determining how close self is to the goal. It is basically the minimum distance to visit all the remaining destinations and get back to start.
from A_Star import State,AStar_Solver
from Ruby_Map import Map
from itertools import combinations, permutations
import sys

# A state class designed to work with A*
class State_Pathfinder(State):

    # This is deprecated
    @staticmethod
    def toValue(location):
        return str(location[0])+","+str(location[1])

    # Calculate the weighted distance between 2 points.
    # Not sure why the deltaY is more weighted. My theory
    # is that it is because the starting point is always
    # on a side. So vertical space is most precious?
    @staticmethod
    def distance(x0,y0,x1,y1):
        # return (abs(x0-x1)**2+abs(y0-y1)**2)**.5
        return 1*abs(x0-x1)+4*abs(y0-y1)

    def __init__(self, maps, parent, value=0, start=0, goal=0):
        super(State_Pathfinder,self).__init__(maps,parent,start,goal)
        self.map = Map(maps)
        self.dist = self.getDist()
        if not value:
            location = self.map.getLocation()
            self.value = maps
            self.path = [self.value]

    def __str__(self):
        return self.map.getDisplay()

    # The heuristic function that tells us
    # how far we are from the goal
    def getDist(self):
        blownup = False
        WEIGHT = 1
        location = None
        try:
            location = self.map.getLocation()
        except ValueError as e:
            blownup = True
        destinations = self.map.getDestinations()
        goal = self.map.getGoal()
        dist = []
        if len(destinations) == 0 and not blownup:
            dist = State_Pathfinder.distance(location[0],location[1],goal[0],goal[1])+WEIGHT
        elif len(destinations) == 0 and blownup:
            return 0
        elif location:
            oldX,oldY = location
            for path in combinations(destinations,len(destinations)):
                length = 0
                for pair in path:
                    x,y = pair
                    length += State_Pathfinder.distance(oldX,oldY,x,y)
                    oldX,oldY = x,y
                dist.append(length)
            dist = min(dist)
            dist += self.map.getWidth()+self.map.getHeight()+WEIGHT
        else:
            return sys.maxint
        if dist<1:
            return 0
        return dist

    # Creates all possible (legal) child states of this state
    def createChildren(self):
        if not self.children:
            try:
                location = self.map.getLocation()
            except:
                self.children = []
                return
            track = self.map.get(location[0],location[1])
            intrack = ("",0,0)
            river = (0,0)
            for x,y in set(permutations([-1,-1,0,1,1],2)):
                realX,realY = location[0]+x,location[1]+y
                adjacent = self.map.get(realX,realY)
                if Map.isTrack(adjacent) and Map.isConnected("",0,0,adjacent,x,y,track):
                    intrack = (adjacent,x,y)
                if adjacent=="~":
                    river = (x,y)
            for x,y in set(permutations([-1,-1,0,1,1],2)):
                realX,realY = location[0]+x,location[1]+y
                adjacent = self.map.get(realX,realY)
                if not Map.isBlocking(adjacent) and not adjacent in "M":
                    for outtrack in "-|\\/":
                        if adjacent=="~":
                            outtrack="X"
                            if intrack[0]=="X":continue
                        if intrack[0]=="X" and abs(river[0])==1 and y==intrack[1]:continue
                        if intrack[0]=="X" and abs(river[1])==1 and x==intrack[0]:continue
                        connections = self.map.getConnections(realX,realY,outtrack)
                        hoppin = len(connections)
                        connected = Map.isConnected(intrack[0],intrack[1],intrack[2],track,x,y,outtrack)
                        blocked = self.map.isBlocked(location[0],location[1],x,y)
                        if (hoppin==1 or hoppin==2 and ">" in connections) and connected and not blocked:
                            try:
                                maps = self.map.set(realX,realY,outtrack)
                                value = State_Pathfinder.toValue((realX,realY))
                                child = State_Pathfinder(maps,self,value)
                                self.children.append(child)
                            except ValueError as e:
                                print "Bad kid"
                                print e

# The solution function. Takes a map string
# and returns a map string.
def f(mapX):
    a = AStar_Solver(State_Pathfinder(mapX,0))
    a.solve()
    print a.path[-1]

if __name__ == "__main__":

    map1 = """###########
#    M    #
#   ^     #
>  ^^  M  #
#    ^    #
#~~~~~~~~~#
# M       #
#     ^^  #
#        M#
###########"""

    map2 = """#################
#               #
#   M         M #
#       ^       #
#        ^ M    #
#~~~~~~~^       #
#               #
#   ^           #
#   M^          #
#    ^          #
> ^^^          M#
#               #
#        M      #
#################"""

    map3 = """###############
# M   ~       #
#     ~       #
>     ~    M  #
#     ~       #
#     ~       #
#     ~       #
###############"""

    f(map3)
    f(map2)
    f(map1)

Map Class
This class stores and processes the map. The isConnected method is probably the most important piece. It tests to see if 2 pieces of track are connected.
from itertools import permutations,combinations

# A map class designed to hold string map
# the specification is found here:
# http://codegolf.stackexchange.com/questions/104965/ruby-on-rails-or-trackety-track
class Map(object):

    # Is 'track' part of the railroad?
    @staticmethod
    def isTrack(track):
        return track in ">|\\/-MX"

    # Can I not build on this terrian?
    @staticmethod
    def isBlocking(terrian):
        return terrian in "^#" or (Map.isTrack(terrian) and not terrian=="M")

    # Are these 3 consecuative tracks connected in a legal fashion?
    @staticmethod
    def isConnected(inTerrian,relativeXin,relativeYin,centerTerrian,relativeXout,relativeYout,outTerrian):
        tin = inTerrian
        xin = relativeXin
        yin = relativeYin
        x = relativeXout
        y = relativeYout
        tout = outTerrian
        center = centerTerrian

        if not Map.isTrack(center) or not Map.isTrack(tout):
            return False

        if tout in "MX" and center in "MX" and tout!=center:
            return True

        if center == ">":
            return x>0 and (\
                tout == "/" and y == -1 or \
                tout == "-" and y == 0 or \
                tout == "\\" and y == 1 \
                )

        if center == "M":
            return tout == "\\" and abs(x+y) == 2 or \
                tout == "/" and x+y == 0 or \
                tout == "|" and x == 0 or \
                tout == "-" and y == 0

        if center == "X":
            if xin!=0!=yin and abs(xin-x)+abs(yin-y) == 1:
                return False
            return tout == "\\" and abs(x+y) == 2 or \
                tout == "/" and x+y == 0 or \
                tout == "|" and x == 0 or \
                tout == "-" and y == 0

        if tout!="" and tout in "MX>" and tin!="" and tin in "MX>":
            return Map.isConnected("",0,0,tin,-xin,-yin,center) and Map.isConnected("",0,0,tout,-x,-y,center)
        elif tout!="" and tout in "MX>" and tin!="":
            return Map.isConnected("",0,0,center,xin,yin,tin) and Map.isConnected("",0,0,tout,-x,-y,center)
        elif tout!="" and tout in "MX>" and tin=="":
            return Map.isConnected("",0,0,tout,-x,-y,center)
        elif tin!="" and tin in "MX>":
            return Map.isConnected("",0,0,tin,-xin,-yin,center) and Map.isConnected("",0,0,center,x,y,tout)

        allowed = [ \
            ["-",-1,0,"-",1,0,"-"], \
            ["/",-1,1,"-",1,0,"-"], \
            ["\\",-1,-1,"-",1,0,"-"], \
            ["-",-1,0,"-",1,1,"\\"], \
            ["-",-1,0,"-",1,-1,"/"], \
            ["\\",-1,-1,"-",1,-1,"/"], \
            ["/",-1,1,"-",1,1,"\\"], \

            ["/",-1,1,"/",1,-1,"/"], \
            ["/",-1,1,"/",1,-1,"-"], \
            ["/",-1,1,"/",1,-1,"|"], \
            ["|",-1,1,"/",1,-1,"/"], \
            ["-",-1,1,"/",1,-1,"/"], \
            ["|",-1,1,"/",1,-1,"-"], \
            ["-",-1,1,"/",1,-1,"|"], \

            ["\\",-1,-1,"\\",1,1,"\\"], \
            ["\\",-1,-1,"\\",1,1,"-"], \
            ["\\",-1,-1,"\\",1,1,"|"], \
            ["|",-1,-1,"\\",1,1,"\\"], \
            ["-",-1,-1,"\\",1,1,"\\"], \
            ["|",-1,-1,"\\",1,1,"-"], \
            ["-",-1,-1,"\\",1,1,"|"], \

            ["|",0,-1,"|",0,1,"|"], \
            ["\\",-1,-1,"|",0,1,"|"], \
            ["/",1,-1,"|",0,1,"|"], \
            ["|",0,-1,"|",-1,1,"/"], \
            ["|",0,-1,"|",1,1,"\\"], \
            ["/",1,-1,"|",1,1,"\\"], \
            ["\\",-1,-1,"|",-1,1,"/"] \
        ]

        passing = False
        forward = [tin,xin,yin,center,x,y,tout]
        start = [0,3][tin==""]

        for allow in allowed:
            maybeF = True
            maybeB = True
            backallowed = [allow[6],allow[4],allow[5],allow[3],allow[1],allow[2],allow[0]]
            for i in range(start,len(allow)):
                if allow[i]!=forward[i] and str(forward[i])not in"*":
                    maybeF = False
                if backallowed[i]!=forward[i] and str(forward[i])not in"*":
                    maybeB = False
            if maybeF or maybeB:
                passing = True
        return passing

    def __init__(self,mapString):
        self.indexableMap = [list(x) for x in mapString.split("\n")]

    def __str__(self):
         return "\n".join(["".join(x) for x in self.indexableMap])

    # Get the string representation of this map
    def getDisplay(self):
        return self.__str__()

    # Get map width
    def getWidth(self):
        return len(self.indexableMap[0])

    # Get map height
    def getHeight(self):
        return len(self.indexableMap)

    # Get unvisited destinations
    def getDestinations(self):
        destinations = []
        for y in xrange(1,self.getHeight()-1):
            for x in xrange(1,self.getWidth()-1):
                sigma = 2
                if self.get(x,y)=="M":
                    sigma = len(self.getConnections(x,y,"M"))
                    if sigma==0:
                        destinations.append((x,y))
        return destinations

    # Get the x,y of the goal (endpoint)
    def getGoal(self):
        for y in xrange(self.getHeight()):
            for x in xrange(self.getWidth()):
                if self.get(x,y)==">":
                    return (x,y)

    # Get the x,y of the current location
    def getLocation(self):
        location = None
        for y in xrange(0,self.getHeight()-1):
            for x in xrange(0,self.getWidth()-1):
                track = self.get(x,y)
                sigma = len(self.getConnections(x,y,track))
                if track == ">":
                    if sigma==0:
                        location = (x,y)
                    sigma = 0
                if sigma == 1:
                    return (x,y)
        if location != None:
            return location
        raise ValueError('No location found in map\n'+self.getDisplay())

    # Get the terrian at x,y
    def get(self,x,y):
        return self.indexableMap[y][x]

    # Set the terrain at x,y
    # (non-destructive)
    def set(self,x,y,value):
        newMap = [[i for i in row] for row in self.indexableMap]
        newMap[y][x] = value
        return "\n".join(["".join(x) for x in newMap])

    # Get the track connectioning to a piece of track at x,y
    def getConnections(self,x,y,track):
        connections = []
        tracks = []
        for a,b in set(permutations([-1,-1,0,1,1],2)):
            outtrack = self.get(x+a,y+b)
            if Map.isTrack(outtrack) and Map.isConnected("",0,0,track,a,b,outtrack):
                tracks+=[[outtrack,a,b]]
        if len(tracks)==1:return [tracks[0][0]]
        if len(tracks)==0:return []

        for inner,outer in permutations(tracks,2):
            intrack,relXin,relYin = inner
            other,relX,relY = outer
            ex = x + relX
            ey = y + relY
            if Map.isConnected(intrack,relXin,relYin,track,relX,relY,other):
                if other == "M":
                    if len(self.getConnections(ex,ey,other))>=1:
                        connections.append(other)
                else:
                    connections.append(other)
        return connections

    # Is could a piece of track at x,y build in
    # the direct of relX,relY?
    def isBlocked(self,x,y,relX,relY):
        if relX==0 or relY==0:
            return False
        side1 = self.get(x+relX,y)
        side2 = self.get(x,y+relY)
        return (Map.isTrack(side1) or side1=="M")  and (Map.isTrack(side2) or side2=="M")

Updates

-560 [17-03-31] A bunch of basic regex golfing
+982 [17-03-31] Fixed illegal track laying. Thanks @fəˈnɛtɪk!
-99  [17-03-31] Utilized ;s

Change some variable names for moar golf ;)

You should be able to golf this more by using a combination of spaces and tabs for indentation

The two lines starting with elif e!=""and e in"MX>" could be combined into a single line with a ternary if else. Also, some of your defs could be lambdas. Like def A(s):return str(s) can be A=lambda s:str(s), or if you change from __str__ to __repr__, you can use  A=lambda s:\s`, at which point, it's not even be worth having A` as its own function, since it requires parentheses to call. Just use backticks instead.

The code attempts illegal moves when it builds bridges. I can't say for certain this is an issue because it ends the test cases with valid paths.

What! I had no idea this was made. I was trying to do this and never finished but good job!


text:
Construct a Gaussian Matrix
Gaussian blur is a method used for blurring images smoothly. It involves creating a matrix which will be used by convolving it with the pixels of an image. In this challenge, your task is to construct that matrix used in Gaussian blur. You will take an input r which will be the radius of the blur and an input σ which will be the standard deviation in order to construct a matrix with dimensions (2 r + 1 × 2 r + 1). Each value in that matrix will have an (x, y) value that depends on its absolute distance in each direction from the center and will be used to compute G(x, y) where the formula G is:
$$G(x,y)=\frac{1}{2 \cdot \pi \cdot \sigma ^ 2} e ^ {-\frac{x^2+y^2}{2\cdot \sigma ^2}} $$
For example, if r = 2, we want to generate a 5 x 5 matrix. First, the matrix of (x, y) values is
(2, 2) (1, 2) (0, 2) (1, 2) (2, 2)
(2, 1) (1, 1) (0, 1) (1, 1) (2, 1)
(2, 0) (1, 0) (0, 0) (1, 0) (2, 0)
(2, 1) (1, 1) (0, 1) (1, 1) (2, 1)
(2, 2) (1, 2) (0, 2) (1, 2) (2, 2)

Then, let σ = 1.5 and apply G to each (x, y)
0.0119552 0.0232856 0.0290802 0.0232856 0.0119552
0.0232856 0.0453542 0.0566406 0.0453542 0.0232856
0.0290802 0.0566406 0.0707355 0.0566406 0.0290802
0.0232856 0.0453542 0.0566406 0.0453542 0.0232856
0.0119552 0.0232856 0.0290802 0.0232856 0.0119552

Normally in image blurring, this matrix would be normalized by taking the sum of all the values in that matrix and dividing by it. For this challenge, that is not needed and the raw values calculated by the formula is what the output should be.
Rules

This is code-golf so the shortest code wins.
The input r will be a nonnegative integer and σ will be a positive real number.
The output must represent a matrix. It can be formatted as a 2d array, a string representing a 2d array, or something similar.
Floating-point inaccuracies will not be counted against you.

Test Cases
(r, σ) = (0, 0.25)
2.54648

(1, 7)
0.00318244 0.00321509 0.00318244
0.00321509 0.00324806 0.00321509
0.00318244 0.00321509 0.00318244

(3, 2.5)
0.00603332 0.00900065 0.0114421  0.012395 0.0114421 0.00900065 0.00603332
0.00900065  0.0134274 0.0170696 0.0184912 0.0170696  0.0134274 0.00900065
 0.0114421  0.0170696 0.0216997  0.023507 0.0216997  0.0170696  0.0114421
  0.012395  0.0184912  0.023507 0.0254648  0.023507  0.0184912   0.012395
 0.0114421  0.0170696 0.0216997  0.023507 0.0216997  0.0170696  0.0114421
0.00900065  0.0134274 0.0170696 0.0184912 0.0170696  0.0134274 0.00900065
0.00603332 0.00900065 0.0114421  0.012395 0.0114421 0.00900065 0.00603332

(4, 3.33)
0.00339074 0.00464913 0.00582484 0.00666854 0.00697611 0.00666854 0.00582484 0.00464913 0.00339074
0.00464913 0.00637454 0.00798657  0.0091434 0.00956511  0.0091434 0.00798657 0.00637454 0.00464913
0.00582484 0.00798657  0.0100063  0.0114556   0.011984  0.0114556  0.0100063 0.00798657 0.00582484
0.00666854  0.0091434  0.0114556   0.013115  0.0137198   0.013115  0.0114556  0.0091434 0.00666854
0.00697611 0.00956511   0.011984  0.0137198  0.0143526  0.0137198   0.011984 0.00956511 0.00697611
0.00666854  0.0091434  0.0114556   0.013115  0.0137198   0.013115  0.0114556  0.0091434 0.00666854
0.00582484 0.00798657  0.0100063  0.0114556   0.011984  0.0114556  0.0100063 0.00798657 0.00582484
0.00464913 0.00637454 0.00798657  0.0091434 0.00956511  0.0091434 0.00798657 0.00637454 0.00464913
0.00339074 0.00464913 0.00582484 0.00666854 0.00697611 0.00666854 0.00582484 0.00464913 0.00339074

How accurate do we need pi and e to be?

@xnor Good question. If your language allows, you may assume that those values are already stored in a variable or something similar. If not, you may use values to two decimal places making pi = 3.14 and e = 2.72 where you can count each of those values as a single byte. Of course, inaccuracies in the final answer will not be counted against you again.

Does the output have to be a decimal number, or could it be exact numbers with constants in them?

@JungHwanMin The exact numbers, such as those in Mathematica, are fine.

@miles I think it would be easier if you just mandated a certain precision (e.g. 3 decimal places).

Mathematica, 60 54 50 bytes
Thanks @GregMartin for 4 bytes!
Array[s=2#2^2;E^(-{##}.{##}/s)/π/s&,1+2{#,#},-#]&

Takes r and sigma as input, returns the matrix (exact numbers).
Built-in version (58 bytes)
GaussianMatrix[{##},Standardized->1<0,Method->"Gaussian"]&

Of course, Mathematica has a built-in for this, too, but it's too long.

You can replace -l by -# at the end (Array will thread that over both dimensions for you); that takes away the need to define l, saving 4 bytes.

MATL, 20 bytes
_G&:U&+iUE/_Ze5MYP*/

Try it online!
Explanation
_     % Take input r implicitly. Negate
G     % Push r again
&:    % Binary range: [-r -r+1 ... r]
U     % Square, elementwise
&+    % Matrix of all pairwise additions
i     % Take input σ
U     % Square
E     % Multiply by 2. Gives 2σ^2
/     % Divide
_     % Negate
Ze    % Exponential
5M    % Push 2σ^2 again
YP    % Push pi
*     % Multiply
/     % Divide. Display implicitly

Octave, 45 bytes
@(r,s)exp((x=-(-r:r).^2/2/s^2)+x')/2/s^2/pi

Octave, 49 bytes
@(r,q)1./((Q=2*q^2)*pi*e.^(((x=(-r:r).^2)+x')/Q))

Try It Online!

Python, 88 bytes
lambda r,s:[[.5/3.14/s/s/2.72**((x*x+y*y)/2/s/s)for x in range(-r,r+1)]for y in range(-r,r+1)]

Uses the rule where you may hardcode 3.14 and 2.72 at 1 byte cost each.

Perl 6, 71 bytes
->\r,\σ{map ->\y{map ->\x{exp((x*x+y*y)/-2/σ/σ)/2/pi/σ/σ},-r..r},-r..r}

Technically this may be more than 71 bytes if encoded and saved to a file, but I couldn't resist naming the "sigma" input with an actual Greek sigma.  It could be renamed to any plain-ASCII letter if one wanted.

SAS Macro Language, 296 bytes
Probably a much more efficient way to do this but it works :)
This code prints out the resulting dataset.
%macro G(r,s);%let l=%eval(2*&r+1);%let pi=%sysfunc(constant(pi));data w;array a[*] t1-t&l;%do i=-&r %to &r;%do j=-&r %to &r;%let t=%sysfunc(sum(&j,&r,1));a[&t]=%sysevalf(1/(2*&pi*&s**2)*%sysfunc(exp(-(%sysfunc(abs(&j))**2+%sysfunc(abs(&i))**2)/(2*&s**2))));%end;output;%end;proc print;run;%mend;

Haskell, 59 bytes
r#s|i<-[-r..r]=[[exp(-(x*x+y*y)/2/s/s)/2/pi/s/s|x<-i]|y<-i]

Usage example:
1#7

[[3.1824449424224664e-3,3.2150851187016326e-3,3.1824449424224664e-3],
 [3.2150851187016326e-3,3.2480600630999047e-3,3.2150851187016326e-3],
 [3.1824449424224664e-3,3.2150851187016326e-3,3.1824449424224664e-3]]

Python 2.7, 167 bytes
A very simple solution:
from __future__ import division;from math import*;r,s=input();s*=2*s;R=range(-r,r+1);print"\n".join("\t".join(str(pow(e,-(x*x+y*y)/s)/(pi*s))[:9]for x in R)for y in R)

Try it here!
Ungolfed:
from __future__ import division
from math import *
r,s = input()                         # Take input
s *= 2*s                              # Set s = 2*s^2; simplifies the expression
R = range(-r,r+1)                     # Range object; used twice

                                   # G(x,y)             # Stripped
print "\n".join("\t".join(str(pow(e,-(x*x + y*y)/s)/(pi*s))[:9] for x in R) for y in R)

from __future__ import division, really?

JavaScript (Node.js), 260 229 212 208 bytes
(r,σ)=>{t=[];z=[];σ*=σ;b=r*-1;y=r;a=2*r++;while(y!=b-1){x=b;while(r>x){z.push(x,y);x++}y--}for(i=0;i<z.length;i+=2){x=z[i];y=z[i+1];t.push(1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)))}return t}

Attempt This Online!
How?
(r,σ)=>{t=[];z=[];σ*=σ;b=r*-1;y=r;a=2*r++;while(y!=b-1){x=b;while(r>x){z.push(x,y);x++}y--}for(i=0;i<z.length;i+=2){x=z[i];y=z[i+1];t.push(1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)))}return t} : main function
        t=[];z=[]; : Define empty arrays
                  σ*=σ; : set σ to σ squared
                       a=2*r+1;b=r*-1;y=r; : set variables for looping
                                          while(y!=b-1){ : open while loop for y's
                                                        x=b; : reset x value
                                                            while(r+1>x){ : open while loop for x's
                                                                         z.push(x,y); : push xy values to array z
                                                                                x++} : increment x and close loop
                                                                                y--} : decrement y and close loop
                                                                                for(i=0;i<z.length;i+=2){ : open for loop based off length of array z
                                                                                x=s(z[i]);y=s(z[i+1]); : retrieve x and y values from z
                                                                                t.push(....)} : push results to array t +closes for loop
                                                                                1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)) : Gaussian function
                                                                                return t} : returns the results and closes the main function

J, 39 bytes
{{(^-a%~1#.*:>{@(,&<)~i:x)%o.a=.+:*:y}}

Attempt This Online!
{{(^-a%~1#.*:>{@(,&<)~i:x)%o.a=.+:*:y}}
{{                                   }} NB. direct definition
                           o.a=.+:*:y   NB. π * (a = 2σ²)
  (^-a%~1#.*:>{@(,&<)~i:x)              NB. computes the eʸ portion
                      i:x               NB. range [-n..n]
              {@(,&<)~                  NB. cartesian product, creates a grid of boxed pairs
             >                          NB. unbox
           *:                           NB. square the pairs
        1#.                             NB. sum¹ the pairs
     a%~                                NB. divide each sum by a, x f~ y -> y f x
    -                                   NB. negate
   ^                                    NB. eʸ
                          %             NB. division

See common use 3 for sum¹. The DD allows a non-tacit definition, which helps implement the function directly, but I am working on refactoring this.

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


text:
print "Hello, World!"
Yes, really.  Print it with a hardware printer  to create a hard copy.
Send the necessary commands/data to your printer such that the following text is printed on a piece of paper:

Hello, World!

You may use any local- or network-connected printer that is available to you.
If your printer allows, you should use 8pt or greater text in black ink on white paper.
The text should appear on its own line.  It may be left or right positioned as you wish.
Digital photographic/video/GIF evidence of submissions will be helpful.
If your hardware cannot do paper, but allows other exotic hardcopy production such as 3D printing, CNC machining, or printing at the atomic level, then I will happy to accept such interesting submissions.

To clarify, the question asks "Send the necessary commands/data to your printer".  The implication of this is that no further user input should be required.  Opening a print dialog is not sufficient.  Existing answers that do this as of 10:48am PST 31st Dec 2016 will be grandfathered (but not upvoted by me).

Please supply address to which we can send submissions for verification.

@steenbergh Yep - good point - Digital photographic/video/GIF evidence of submissions should be good enough.

It's worth noting that many older printers use custom command sets. Most of these print ASCII characters literally, so if you have access to one of the printers in question (or can just claim that you do), sending Hello, World! to the printer port should be enough.

I could swear that I tried print("Hello, World!") in the Firefox console once and it opened the print dialogue (useless because I wasn't connected to a printer in any way), but now it just returns the string...

are xditview, distiller, cups-pdf and other printer simulators considered cheating?

@Jasen Those are fine for testing, so long as your answer will work with a real printer with no modification

@ETHproductions in chrome doing <script>print("Hello, World!")</script>  does open the print dialog, but without the actual text on it.

Can submissions open a print dialog box that has to be submitted before the text is printed? Some languages (e.g. JavaScript) can't compete otherwise.

@ETHproductions No, I want complete automation without additional user input.

After I read the title, I thought the question was about Python 2. :-(

Too bad we still don't have postscript answer :-(

Bash, 21 19 bytes
lp<<<Hello,\ World!

And there it is.
2 bytes saved thanks to Dennis!

+1 Valid as a script.  Works fine on my Mac.  If you want to run it directly at the command-line you'll need to change the double-quotes to single-quotes.

why not have banner to make ot look pretty

@juggernaut1996 where? Not if I have to print something out again

PowerShell, 18 bytes
'Hello, World!'|lp

Try it online!

Not sure the point of the TIO link.  +1 anyway.

@DigitalTrauma I thought it was funny; and it generates the post for me. You can also look at the debug output just to see that it's trying (and failing) to spool the job. :-p

@DigitalTrauma If you put your address in the input field, TIO will mail you the result.

@Dennis if I had money to burn I'd submit an answer that uses an API-to-print service. Alas...

QBIC, 11 bytes
'LPRINT `_h

Almost forgot I built a 'Hello, World!' command into QBIC...
'          Starts a code literal. This used to be "$", finally changed it.
 LPRINT `  Feeds everything from ` to the next ` directly to QBasic.
           In this case, "LPRINT" and a space
_h         Yields "Hello, World!"

Tested and found working identical to my QBasic answer:

um.. so what's that link? Is it a language invented by you?

@eis Yes, I made QBIC. The link is a Google Drive folder with all the code in it - I suck at GitHub... It's an interpreter atop of QBasic (QBIC stands for Quick Basic's Interpreter for Codegolf) and it runs in DosBox. Check out the Showcase-thread for some examples (or just open my profile's answers-page, 75% is in QBIC). WIP, so syntax and tokens occasionally get shifted.

The OP used a capital "W" to avoid builtin "hello world" (see also).: building your own builtin command for the job is not code golfing, or you could make it "0 bytes" with a builtin default behavior for that.

@Cœur: that hardly works nowadays, most newer golfing languages use the capital W precisely because it's standard on PPCG, and it's highly likely that the command was added with no knowledge of this particular challenge (just a guess that more "Hello, World!" challenges would be submitted in the future)

@Cœur Welcome to PPCG! You may be surprised to learn that you're not the first person to whom that particular concern has occurred. Here's a good place to start reading: http://meta.codegolf.stackexchange.com/q/4867/11261 And further, people who enjoy code golfing spend a lot of time thinking about loopholes: http://meta.codegolf.stackexchange.com/q/1061/11261

Batch, 22 bytes
echo Hello, World!>prn

This redirects the output of the echo command to the device file PRN, meaning that it's sent directly to the default printer (usually LPT1).
I neither have a DOS machine nor a printer, so I'm afraid I can't test this right now, but I'm fairly certain I've done this back in the day. It doesn't work on Windows XP or later.

This reminds of when I tried to create a file called con and was unable to. Ah, the joy of DOS device files...

NT (and presumable XP etc) can be configured to print this way using the "net" command.  iirc "net use lpt1: something"

Python 2.7, 43 bytes
import os;os.system("lp<<<'Hello, World!'")

Not very interesting, though. Here's a more interesting one:
import zlib,base64,os;os.system("s=$'%s';lp<<<\"$s\""%zlib.decompress(base64.decodestring("eNqVkk1qxDAMha/yupNgwNfoDboReDPdhQRmrcNXP3bixA3tGEMesj/r5wXoq+YysUemI0BWlYgV\npTyAEDKEQSDucxLxJaj6gUVKE8BFsH2TIOM5iMyrcTIL3YnMqCH4X0TLONTwF3H04Z0XuRPeR3Wi\nxDOi1EZY7gUTWFa8s+z5kTgcnK3sBtbZQRtCt5LPDlrliKouDh5DYz07KB6COuETUL/YRthGxHqZ\nbjyWBAU8EFk6z350Yt97Dol65hxUow9i3zr8YGxFS61nB4szPqvDnS7CU/nFwYLIYczn97JsD3xt\nr+X5wT/ARNN3\n")))

Seems a bit too long? Perhaps it's a bit overcomplicated.... :P

Mod Note edited the competitive submission to the top for clarity.

HTML + Javascript, 37 34 bytes
<body onload=print()>Hello, World!

Tested in Safari:

Thanks to @jimmy23013 for some savings.

This appears just to open the print dialog box and not actually send the job to the printer without further manual intervention

Minor nitpick, the W in world should be capitalized.

@DigitalTrauma JS cannot do that

Also, you can shave 9 bytes off by omitting </script>.

Are you sure, @EriktheOutgolfer? Firefox and Chrome evaluates the script code only when the closing tag is met.

@manatwork Oh, I can't remember well, I just recalled from ≥1 year ago.

Yeah I tried leaving off the </script> and it didn't work.

-3 bytes: <body onload=print()>Hello, World!

@jimmy23013 Nice! I thought there might be some trick like that but I couldn't quite think what.

hello + lp + tr, 9 15 bytes
hello|tr w W|lp

I originally had
hello|lp

But it had the wrong capitalisation on the w
hello is GNU hello from the Debian package hello

hello prints a lowercase w, as is the custom on most programming sites. (I'm not quite sure how the uppercase W became standard on PPCG.)

@ais523 I think uppercase W is standard here precisely to avoid built ins like this.

If the capitalization is wrong, I'm afraid this is invalid.

Thanks for your comments, I will delete this answer tomorrow.

How about hello|tr w W|lp?

ZX Spectrum BASIC, 16 bytes
LPRINT "Hello, World!"

LPRINT is a 1-byte keyword in ZX Spectrum BASIC, having codepoint 224.

can you show a photo of the hardcopy.

@Jasen In theory I still have the kit around, but it would be a bit of a palaver to dig it out and hook it up to an old enough TV. Sorry about that.

you could probably type that command "blind".

MATLAB, 40 37 36 bytes
Printing text is not something you'd normally do in Matlab, but it can be done.
title 'Hello, World!'
axis off;print

I saved 3 bytes thanks to Tom Carpenter (use title instead of text(0,0,. I saved an additional 2 bytes by substiting title('Hello, World!') with title 'Hello, World!' followed by a newline instead of a semicolon.
title adds a title to a figure. If a figure is not yet open, it will be created.
axis off is used to get rid of the frame and axes, so that the text appears alone.
print prints the current figure to the default printer if no input arguments are given.
I printed this (successfully according to the dialog box) on my default printer at the office. I can retrieve it there and prove it but you'll have to wait two weeks. After changing the default to a pdf-printer, this is the output:

^^ Not the correct image anymore.

QBasic, 21 bytes
LPRINT"Hello, World!"

LPRINT sends text directly to the printer. Unfortunately untested, DosBox doesn't natively support NET USE, so I can't reroute LPT1: to NovaPDF.
The problems I have...
UPDATE: Tested it in QB64. Resulting PDF opened in Microsoft Edge. Looks like this:

8086 machine code, 28 bytes
00000000  be 0f 01 b9 0d 00 31 d2  ac 98 cd 17 e2 fa c3 48  |......1........H|
00000010  65 6c 6c 6f 2c 20 57 6f  72 6c 64 21              |ello, World!|
0000001c

Uses the standard int 0x17 BIOS call. I don't have my dot-matrix printer set up right now so this code is untested.
How it works:
            |   org 0x100
            |   use16
be 0f 01    |       mov si, msg         ; source pointer = msg
b9 0d 00    |       mov cx, 13          ; counter = length of msg
31 d2       |       xor dx, dx          ; clear dx
ac          |   @@: lodsb               ; al = *si++
98          |       cbw                 ; sign-extend al->ax (simply clears ah)
cd 17       |       int 0x17            ; send char in al to printer dx
e2 fa       |       loop @b             ; loop while (cx-- > 0)
c3          |       ret
48 65 6c    |   msg db "Hello, World!"
6c 6f 2c    |
20 57 6f    |
72 6c 64    |
21          |

Sure, just added it.

Now we're talking!

Absurdly late reply, but a byte can be saved by using cwd after cbw instead of xor dx, dx.

Stuck + Batch, 5 bytes
Inspired by this answer an empty stuck program prints "Hello, World!".

Have a printer connected to your computers LPT1 port
Create an empty stuck file to be interpreted (filename a)
Run the stuck interpretter on the empty file and pipe the result to LPT1

Code
stuck a>LPT1

If you're using multiple languages, you also need to count the glue that connects them together as part of your byte count. I'd count this as 15 for the Batch program, plus 0 due to the need for a 0-byte external file.

Can you show distinctly the Windows batch script, and explicitly the command used to call Stuck and pass the result to the printer? By explicitly I mean something like stuck empty > LPT1. BTW if this uses a REPL I believe the consensus is that should be clearly stated (I believe it's to minimise confusion exactly like this).

@ais523 I conquer - I should count the glue, and because of that, raised it from 5 bytes to 12

You can save a byte here by redirecting to PRN instead of LPT1.

IMO you need to add 1 byte for the 1 byte filename.

Assuming your default printer is set to LPT1, this can be 4 bytes with stuck stk>PRN.

@Makonede Don't edit people's code in order to fix it, leave a comment pointing out the problem and potentially suggesting a fix

OK, well the problem here is this will print Usage: python stuck.py program.stk. Thankfully though, after looking through the source code, naming the file stk and then running it with stuck stk>PRN will print out Hello, World!

Java, 330 bytes
Golfed:
import java.awt.print.*;void f()throws Throwable{PrinterJob job=PrinterJob.getPrinterJob();job.setPrintable(new Printable(){public int print(java.awt.Graphics g,PageFormat f,int i){if(i==0){((java.awt.Graphics2D)g).translate(f.getImageableX(),f.getImageableY());g.drawString("Hello, World!",0,90);}return i>0?1:0;}});job.print();}

Ungolfed (import plus function only):
import java.awt.print.*;

void f() throws Throwable {
  PrinterJob job = PrinterJob.getPrinterJob();
  job.setPrintable(new Printable() {
    public int print(java.awt.Graphics g, PageFormat f, int i) {
      if (i == 0) {
        ((java.awt.Graphics2D) g).translate(f.getImageableX(), f.getImageableY());
        g.drawString("Hello, World!", 0, 90);
      }
      return i > NO_SUCH_PAGE ? 1 : PAGE_EXISTS;
    }
  });
  job.print();
}

Java is not a great golfing language, and certain does an exceptionally poor job golfing anything hardware-related, printing included.
While testing this program, I set my PDF printer as the default. It worked, but also sent a print job to my laser printer containing 87,792 pages of "Hello, World!" I pulled the paper tray and canceled the job, then retested. It did not happen again. Thanks, Windows 10.

-7 bytes by changing 3x job to j, and i==0 to i<1.

GFA-Basic, 22 bytes
Only tested on an Atari ST emulator with the parallel port redirected to a file. It should work on the Windows version of GFA-Basic (which is free), but this is untested.
LPRINT "Hello, World!"

Note: This turns out to be identical to the QBasic syntax.

JavaScript, 37 36 bytes
print(document.write`Hello, World!`)

Saved 15 bytes thanks to @manatwork and @xem!

No need to explicitly specify window: document.write('Hello, World!');print(). Or even shorter: print(document.write('Hello, World!')).

with ES6 you can even do:  document.write\Hello, world!` ` (more info here: http://xem.github.io/articles/#webspeech)

Does it print without confirmation? No? Well too bad, it's invalid.

@CalculatorFeline Why the hostility? If you read the footnote of the challenge you'd see "...Existing answers that do this as of 10:48am PST 31st Dec 2016 will be grandfathered...".

Oh. I missed that part.

Mathematica, 29 bytes
NotebookPrint@"Hello, World!"

c#, 259 250 bytes
using System.Drawing;using System.Drawing.Printing;struct p{static void Main(){var p=new PrintDocument();p.PrintPage+=(s,e)=>e.Graphics.DrawString("Hello,World!",new Font("Arial",12),new SolidBrush(Color.Black),new Rectangle(0,0,999,99));p.Print();}}

Example output

Batch, 32 bytes
echo Hello, World!>t
notepad/P t

Should work on all versions of windows with no manual intervention required.

APL (Dyalog), 50 bytes
Of course we could shell out and use a Batch/Bash solution, but let us instead create a real print job:
{'X.'⎕WC'Text' 'Hello, World!'⍵⊣'X'⎕WC'Printer'}⍳2

⎕WC is Windows Create object
First we create a printer object (a print job) called 'X', then (⊣) in that ('X.') we create a text object at ⍵ the argument of the anonymous function {…}. The argument is ⍳2, which gives the first two integers (1 2) and means 1%  from the top and 2% from the left. When the anonymous function terminates, all its local variables (X) are destroyed, which signals to Windows that the print job is ready to be printed:

Ruby, 55 bytes
IO.write(?l,"Hello, World!");`lpr<<?l`

For Mac and Linux, your default printer must be set at localhost:631.
For Windows, you need to add an lpr port in your printer settings.

No need to write to file; you can just send the string to lp directly: \lp<<<Hello,\ World!``

I figured everyone was doing that, so I just used lpr. Thanks for the advice.

Admittedly it is boring. There are a few ways to golf your version: File.write -> IO.write, you can remove mode:?w, and you can use backticks instead of system.

Racket 35 bytes
(system("echo 'Hello World!'\|lp"))

ZPL (Zebra Programming Language), 25 bytes
Code:
^XA^FDHello, World!^XZ~PS

Try it online!
Explanation:
^XA                        # Start Format
    ^FDHello, World!       # Field Data "Hello, World!"
^XZ                        # End Format

~PS                        # Print Start

Python 3 (Win32), 114 bytes
I used the win32api library to do this.
import win32api;open('h.txt', 'w').write('Hello, World!');win32api.ShellExecute(0, 'print', 'h.txt', None, '.', 0)

Lua, 34 32 bytes
os.execute"lp<<<'Hello, World!'"

Welcome to Code Golf, and nice first answer! Be sure to check out Tips for golfing in Lua for further help on golfing your answers.

Thanks for the tips! Managed to scrape off 2 bytes from my original answer :)

HP‑41C series, 44 Bytes
Because this program uses accumulated printer output (ACA), the printer’s print mode must be set to man (manual).
In trace or norm (normal) mode the print buffer is printed prematuraly, thus not producing the desired result.
This preparation cannot be programmed.
01♦LBL⸆P           5 Bytes    global label requires 4 + n Bytes
02 ⸆H              2 Bytes    set alpha register to the string "H"
03 ACA             2 Bytes    accumulate alpha register contents
04 ⸆ELLO,          6 Bytes    overwrite alpha register again
05 SF 13           2 Bytes    sets lower case flag
06 ACA             2 Bytes    accumulate α‑register and translate to lowercase
07 ⸆ W             3 Bytes
08 CF 13           2 Bytes    disable lowercase translation
09 ACA             2 Bytes
10 ⸆ORLD           5 Bytes    exclamation point cannot be entered via keyboard
11 33              2 Bytes    put character code for `!` into `X` register
12 XTOA            2 Bytes    append character identified by `X` to α‑register
13 SF 13           2 Bytes
14 ACA             2 Bytes
15 PRBUF           2 Bytes    print contents of printer buffer and clear it
16 END             3 Bytes

−1 B:
You can use the command ADV (1 Byte) instead of PRBUF (2 Bytes).
The print buffer procedure starts printing from the left‑hand margin.
The advance procedure prints the buffer right justified.
−2 B:
The END command allows inspecting the program’s size via catalog 1 and forms a barrier for local label search.
A RTN (1 Byte) does not have said characteristics.
Let’s see the program in action:
Note, the video actually shows a program with a couple ADV inserted before the END.
PS: Yeehaw! This is my 100th (programming challenge answer) post!

HTML (33)
Hello, World!<svg onload=print()>

(Prompts a print window in the browser, doesn't print directly)

Is there a reason the tag has to be <svg> specifically, or would any tag work? (Many tags have shorter names.)

afaik, only svg, img (with a valid src), iframe and body have an onload event triggered when the page is loaded. img without src triggers an onerror event. all in all, the shortest we've found is svg onload=...

The challenge asks for upper case W (not that it changes your byte count).

JavaScript + HTML, 20 bytes

print()
Hello, World!

This just opens the print dialog.   Further manual intervention is required to actually print.  Please see the note at the bottom of the question.

C#, 174 bytes
namespace System.Drawing.Printing{_=>{var p=new PrintDocument();p.PrintPage+=(s,e)=>e.Graphics.DrawString("Hello, World!",new Font("Onyx",9),Brushes.Black,0,0);p.Print();};}

Full/Formatted version:
namespace System.Drawing.Printing
{
    class P
    {
        static void Main(string[] args)
        {
            Action<float> f = _ =>
            {
                var p = new PrintDocument();
                p.PrintPage += (s, e) =>
                    e.Graphics.DrawString("Hello, World!", new Font("Onyx", 9), Brushes.Black, 0, 0);
                p.Print();
            };

            f(0);
        }
    }
}

Javascript, 36 bytes
print(document.write`Hello, World!`)

This just opens the print dialog.   Further manual intervention is required to actually print.  Please see the note at the bottom of the question.