text:
Can you cast the spell?
In Magic: the Gathering, mages (known as "planeswalkers") battle each other by casting spells. Spells cost mana. Five colors of mana exist: White, Blue, Black, Red, and Green, represented as {W}, {U}, {B}, {R}, and {G}, respectively.
A spell's cost is slightly more complex. The cost can be any combination of the following:

One or more colors
One or more colorless, represented as {X}, where X is a positive integer
One or more hybrids, represented as {Y/Z}, where Y and Z are either a color (represented by one of the five letters) or colorless, represented by a positive integer

The following rules apply when attempting to cast a spell:

A color in a cost must be satisfied by one mana of that color
A colorless cost {X} may be satisfied by X mana of any color
A hybrid cost {Y/Z} may be satisfied by satisfying either Y or Z

Note that braces are not nested
Y and Z are not hybrid

Write a program or function that, given a pool of mana and a cost, prints or returns true (or some truthy value) if and only if the mana in that pool can satisfy the cost, else false (or some falsy value).
A mana pool is a non-empty string of the format:
Color1,Color2,Color3,...,Colorn-1,Colorn
A cost is a non-empty string of the format:
Cost1,Cost2,Cost3,...,Costn-1,Costn
Examples
In the format Pool Cost -> ExpectedOutput (with a space between Pool and Cost):
{R},{R},{G},{B},{R} {4},{R} -> True
{G},{G},{G},{G},{W},{W},{W} {2/W},{2/U},{2/B},{2/R},{2/G} -> False
{G},{G},{R} {R/G},{G/B},{B/R} -> True
{R},{R},{R},{G} {1},{G},{2/G}-> True
{R} {R},{R},{R},{R},{R} -> False
{W},{R},{R} {2/W},{W/B} -> True
{U},{U} {1} -> True
{W},{R},{G} {1},{2} -> True

Is it possible to have colorless mana in the pool?

@nutki In the real game, yes. In the challenge, no. Only the five colors defined in the challenge exist for the purposes of the challenge.

I've been away from magic too long. Hybrid costs?!?

@Sparr They were introduced in Ravnica, back in 2005

@murgatroid99 I quit when 6E came out. None of my friends were willing to adapt to the new rules :(

Pyth, 55 53 52 50 bytes
FN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`Hd\,#=sN)I!.-NhK1B)E0

Try it online: Demonstration or Test harness
Notice that the time and memory complexity is really bad. So the second example doesn't work. I allocates about 1.6 GB of Ram before it crashes on my machine.
Explanation
The explanation is for the 53 solution. The only difference is, that the initial parsing happens in the middle instead of the beginning.
Kc-rz0"{}"dFN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`H\,#=sN)I!.-NhK1B)E0

So here's the initial parsing.
Kc-rz0`Hd
   rz0     convert input() to lowercase
  -   `H   remove all curly brackets (`H = "{}")
 c      d  split at the space
K          assign to K

So the input "{W},{R},{R} {2/W},{W/B}" gets converted into ['w,r,r', '2/w,w/b'].
m               ceK\,    map each cost d of the costs split by "," to:
 s                         the sum of
  m         cd\/           map each value k of cost split by "/" to:
    k                        k
   ? }kG                     if k in "abcdef...xyz" else
        ^Gvk                 Cartesian product with "abc...yz" of int(k) repeats

So what does this do? The cost input '2/w,w/b' gets converted into:
[['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w'], 'wb']

Every string in ['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w'] satisfies {2/W} and every char in 'wb' satisfies {w/b}.
Now we generate the Cartesian product of these lists (or strings) and see, if any combination can be produced with the mana-pool.
FN*F...              )      for N in Cartesian product of ...:
       #   )                   while 1:
        =sN                      N = sum(N)
                               this flattens N
            I!.-NhK            if not (subtract mana pool from N):
                   1             print 1 (True)
                    B            break
                      E      else:
                       0       print 0 (False)

truthy and falsy values are allowed, not just True and False.

You can save a character by inling the assignment to K. Put Kc-rz0"{}") where K is first used, and remove the initial assignment to K.

@isaacg Oh, should have seen that. Thanks.

@Rainbolt You accepted a non-working solution. Well it worked when I posted it, but Pyth changed a lot. I updated it and also saved 2 more bytes.

@Jakube Thanks, but this answer needs to work using an interpreter that was available at the time the challenge was posted, not some new updated interpreter.

Actually, after looking through some other old Pyth answers, it looks like editing after the fact has become acceptable practice. Seems cheaty to me, but whatever.

Python 2.7, 412 characters
import re,collections as C
r,C=re.findall,C.Counter
def g(m,h,c,v):
 try:return t(m,h,c+int(v))
 except:
  if m[v]:return t(m-C({v:1}),h,c)
def t(m,h,c):return any(g(m,h[1:],c,v)for v in h[0].split('/'))if h else sum(m.values())>=c
def f(m,c):m=C(r(r'\w',m));c=[filter(None, x)for x in zip(*r(r'(\w+/\w+)|(\d+)|(\w)',c))];m.subtract(C(c[2]));print all(x>=0 for x in m.values())*t(m,c[0],sum(int(x)for x in c[1]))

The function f is the one that does the check. It takes the mana pool and cost as string arguments, and prints 1 when the mana satisfies the cost and 0 otherwise. For example, f('{R},{R},{G},{B},{R}', '{4},{R}') prints 1.
Ungolfed, it basically looks like this
import re
from collections import Counter
def helper(mana, hybrids, colorless, option):
  try:
    option = int(option) # See if option is an integer
    # For colorless hybrid, just add the value to the colorless amount
    # to check at the end.
    return check_hybrids(mana, hybrids, colorless + option)
  except ValueError: # Option is a mana letter
    # For colored hybrid costs, check if any of that color is
    # available, then try to pay the rest of the cost with 1 less
    # of that color.
    if mana[option] >= 0:
      return check_hybrids(mana - Counter({option: 1}), hybrids, colorless)
    else:
      return False
def check_hybrids(mana, hybrids, colorless):
  '''Check whether the given mana pool can pay the given hybrid costs and colorless costs'''
  if hybrids:
    # For each option in the first hybrid cost, check whether the
    # rest of the cost can be paid after paying that cost
    return any(helper(mana, hybrids[1:], colorless, option) for option in hybrids[0].split('/'))
  else:
    # When there are no remaining hybrid costs, if there is enough
    # remaining mana to pay the colorless costs, we have success
    return sum(m.values()) > colorless
def can_cast(mana_str, cost_str):
  mana = Counter(re.findall(r'\w', mana_str))
  # transpose to get separate lists of hybrid, colorless, and colored symbols
  cost = zip(*re.findall(r'(\w+/\w+)|(\d+)|(\w)',cost_str))
  cost = [filter(None, sublist) for sublist in cost] # Remove unfound symbols
  mana.subtract(Counter(cost[2]))
  # After subtracting the single-colored cost from the mana pool, if
  # anything in the mana pool is negative, we didn't have enough to
  # pay for that color.
  if any(x <=0 for x in mana.values()):
    return False
  return check_hybrids(mana, cost[0], sum(int(x)for x in cost[1]))


text:
Pythy Finite Ordinals
Write a program in any language that takes a single natural number n as input and generates a Pyth program that, in turn, produces, using nested lists, the nested set given by S(n), where:

S(0) = ∅
S(n+1) = S(n) ∪ {S(n)}

S(n) giving the set representation of the corresponding ordinal number.
Using the list representation required by this question, this gives (as the final output from the generated Pyth program):
0->[]
1->[[]]
2->[[],[[]]]
3->[[],[[]],[[],[[]]]]

Etc.
Again, the challenge is to write a program in another language for generating the corresponding Pyth program.
This is code golf, so shortest full program wins.

Are the spaces in the output optional?

The spaces in the final output (from the pyth program) are optional.

The generating program takes the input though, the generated result isn't allowed to take any.

It'd be trivial to append something like J<input> at the front.

Pyth, 11 10 bytes
"u+G]G"z\]

"Answers must be at least 30 characters."

source: Stack Exchange

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

sort: votes


text:
Books on a Shelf
I have some books and a bookshelf. I would like to put as many books on the shelf as possible but I have a rule. All dimensions of the books (height, width and depth) should form a non-increasing sequence on the shelf.
This means every books has to be at least as high as the ones after it on the self. The same goes for the width and depth. You can not rotate the books to swap their height, width and depth.
You should write a program or function which given the dimensions of all the books as input outputs or returns the maximal number of books I can put on the shelf.
Input

A list of triplets of positive integers where each triplet defines a book's height, width and depth.
There will be at least one triplet in the input list.
Two books can have the same lengths along any number of dimensions.

Output

A single positive integer, the maximal number of books that fit on the shelf obeying the rule.

Time complexity
Your algorithm should have a worst-case time complexity polynomial in the number of books. This means that for example the following time complexities are all valid: O(N^3), O(log(N)*N^2), O(N) and the following ones are invalid: O(2^N), O(N!), O(N^N).
Examples
Input => Output
(1, 1, 1) =>  1

(5, 2, 5), (1, 3, 5) =>  1

(5, 2, 5), (1, 2, 5) =>  2

(2, 2, 2), (2, 2, 2), (2, 2, 2), (1, 3, 6) =>  3

(1, 2, 5), (1, 3, 5), (1, 2, 8), (1, 2, 5), (7, 7, 7) =>  4

(5, 19, 3), (9, 4, 16), (15, 16, 13), (7, 4, 16), (1, 13, 14), (20, 1, 15), (9, 8, 19), (4, 11, 1) =>  3

(1, 1, 18), (1, 13, 7), (14, 1, 17), (8, 15, 16), (18, 8, 12), (8, 8, 15), (10, 1, 14), (18, 4, 6), (10, 4, 11), (17, 14, 17), (7, 10, 10), (19, 16, 17), (13, 19, 2), (16, 8, 13), (14, 6, 12), (18, 12, 3) =>  5

This is code golf so the shortest entry wins.
A related interesting book sorting challenge: Book Stack Sort.

Do you mean it should form a decreasing sequence? That's what you get if each book is at least as high as the book after it, unless every book is the same height.

@mbomb007 Right, changed "non-decreasing" to "non-increasing".

Python 3: 436 bytes
At first I saw this as the NP-complete problem of finding the longest simple path in a directed graph with cycles. However, every cycle in the graph (actually a complete subgraph) can be represented as a single vertex. In other words, treat identical books as one book, to be placed on the shelf as a unit. We can then construct a directed acyclic graph where a->b means b could follow a on the shelf. Finally, we find the maximum height of the out tree(s) using a recursive method.
import sys
b=[]
n={}
r=[]
for L in sys.stdin.readlines():z=[int(x)for x in L.split()];r+=[z];z in b or b+=[z]
def l(a,b):return a[0]<=b[0]and a[1]<=b[1]and a[2]<=b[2]
R=range(len(b))
for i in R:
    n[i]=[]
    for j in R:i!=j and l(b[i],b[j])and n[i]+=[j]
def L(t):
    global v;best=0
    if t in v:
            return v[t]
    for s in n[t]:best=max(best,L(s)+1)
    v[t]=best+r.count(b[t])-1;return best
m=0
for i in R:v={};m=max(L(i)+1,m)
print(m)

This is a nice solution, but it isn't really golfed yet. I'll upvote once it is.

Pyth, 40 bytes
KYleolNe.eaK+e+]])olNf.A.eg@YbZeT<Kk]YSQ

Not fast, but it is polynomial.
Python3 equivalent:
def num_books(l):
    l = sorted(l)
    s = []
    for i, Y in enumerate(l):
        s.append(max([T for T in s[:i]
                      if all(Y[e] >= t for e, t in enumerate(T[-1]))] + [[]],
                     key=len) + [Y])
    return max(len(u) for u in s)

The Python 3 version is 177 bytes with the obvious golfs. Just an fyi.

Python 2, 231 bytes
Try it here
My program currently gets the last two examples wrong. Can someone help me fix it, please? Thanks.
I sort the list all of the 6 possible permutation orders of the 3 dimensions, then see what the longest continuous ordering relation is in the list, then find the max of those.
Also, I know if can be golfed a lot more, but I couldn't figure out if I could use reduce to do this. Simply put, this way was the easiest to make in a reasonable time without my brain exploding.
from operator import*
from itertools import*
def f(t):
    m=1
    for l in(sorted(t,key=itemgetter(*o))for o in permutations(range(3))):
        c=1
        for k in range(len(l)-1):
            c+=all(i<=j for i,j in zip(l[k],l[k+1]))
        m=max(m,c)
    print m

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


text:
Shortest Identifying Substring

This challenge is inspired by dmenu, the program I use to launch other programs on my Linux box. To start, for example, GIMP, I simply hit the keyboard shortcut I have assigned to dmenu, type "gimp" and hit enter. However, I don't have to type the whole name. On my machine, if I type "gim", that's enough. Here's how dmenu decides which program to launch when you hit enter1:

Find all program names that contain the input as a substring.
Sort this list alphabetically.
Take the items in the list that begin with the input, and (preserving their order) put them at the beginning.
Launch the first2 program in the list.

While this is usually quite convenient, it is sometimes annoying. For example, on my computer I have chromedriver and chromium. I never want to launch chromedriver, but it's earlier alphabetically than chromium is. If I start typing at the beginning of the word, like I naturally want to do, I have to type six characters to specify that I mean the latter.
However, we don't need to start typing at the beginning of the word! chromium is, alphabetically, the first program name containing the substring iu. I have no programs that start with iu. Therefore, I only need to type those two characters to unambiguously specify which program I want.
For this challenge, your program or function will receive at least two lines of input. No line will contain any whitespace characters (other than the newline, obviously) and the first line is guaranteed to be repeated somewhere in the remaining input. Your program or function will output (stdout, return, etc.) the shortest string that, using dmenu's rules, would find that first line in all the rest. If there are two or more that are tied for shortest, you may output whichever you like.
Examples
In:
bbbb
aaaa
bbbb
cccc

Out:
b

In:
bc
bc
aaaa
bbc

Out:
bc

1: I don't actually know this to be the case, but in my experience it seems to work this way.
2: When actually using dmenu, you can hit left and right to choose different items in the list, but that's irrelevant for this challenge.

For example 1, unless I'm misunderstanding things, shouldn't the output be b?

@isaacg Yep, I changed the test and didn't fix the output. mb

Pyth, 22 21 bytes
hfqzho>xNT0Sf}TY.z.:z

isaacg and me got the same 21 solution more or less at the same time. So he deleted his solution.
Try it online: Pyth Compiler/Executor
Explanation
                         implicit:  z = first input line
                                   .z = all other input lines
 f                .:z   filter all substrings T of z, which satisfy:
            f   .z        filter .z for lines Y, which satisfy:
             }TY            T in Y
           S              sort these lines alphabetically
     o                    order these lines N by:
      >xNT0                 (index of T in N) > 0
                          (sorting in Pyth is stable, so this brings the lines,
                           which start with T, to the beginning
                           without messing up the alphabetically order)
  qzh                     z == first element of ...
h                       print first elment

hfqzho!!xNTSf}TY.z.:z


text:
Valid snakes on a plane
Inspired by one of Vi Hart's videos (which are a treasure trove full of potential challenge ideas)
A snake is made up of segments of same length and the connection between each segment can be straight or make a 90° turn.
We can encode such a snake (up to a rotation, which depends on the initial direction) by writing down a slither, the direction of turns (Straight/Left/Right) it takes. This one, starting in the top left and pointing to the right
-+    +--+    SR    RSSR
 |  +-+  |     S  RSL  S
 +--+  --+     LSSL  SSR

Would be represented by the slither SRSLSSLRLRSSRSRSS
And of course a planar snake cannot intersect itself (like in SSSSLLLSS), that would result in a horrible pixelated Game Over.
Your task is to determine whether a slither is valid or not (results in at least one self-intersection)
Input
A string made from letters SLR with 2 < length < 10000
Output
Something Truthy if it is a valid slither and something Falsey if its not.
Test cases
__Valid__
SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS
SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR (A hilbert curve)
RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR
SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS (Spiral)
SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS (bigger, squigglier spiral)
LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL

__Invalid__
SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR
SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR
SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS
SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS
LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS

You can draw the slithers here (R and L are flipped, but it doesnt affect validity)

Does input have to be done in the program or can it be read from a file?

Should SRRR be True or False? It connects but doesn't intersect itself.

touching snakes challenge NSFW?

if you draw SRRR on a graph paper with one square per segment then it would overlap and is therefore invalid, simply RRR however, would occupy exactly a 2x2 square without overlaps (just like in the classic game)

Similar but not a duplicate (due to different objective and different construction rules).

+1 for Vi Hart :)

"if you draw SRRR on a graph paper with one square per segment then it would overlap and is therefore invalid"  This doesn't make sense to me.  Based on the description, the turns are directional changes,  not positional ones.  So SRR would result in a single segment, which should be valid.

I gotta say it took me an embarrassingly long time to figure out the pun you were making with "snakes on a plane"

Pyth, 22 20 bytes
ql{m+=Z*=T^.j)hCdzlz

Try it yourself or run the testsuite.
Note the ASCII values of SRL, respectively 83, 76, 82. I abuse the fact that:

i 83 + 1 = 1
i 76 + 1 = i
i 82 + 1 = -i

From here I just keep a variable for the current position and current direction. For every character I multiply the current direction with the above complex number, then add it to the current position.
At the end I check if all the visited positions are unique.

SRRR = true????

@Ewan On closer inspection - I'm not sure if that should be false or not. The head and tail connect, but do not intersect.

what about SRRRS?

@Ewan Same story - connection but no intersection. The question isn't clear what should be returned for these.

hmm I can see why SRRR is true but surely SRRRS is def false? both Ss are at the same x,y coord?

@Ewan They touch but do not intersect.

how do you define intersection? line 1 : SR line 2 RR : last S would be placed on same square as first S = interesection?

@Ewan Intersection is when two lines cross, not when they touch. See this: http://i.imgur.com/GXi4XMr.png

how would you draw SRRR?

@Ewan As a square.

Yes, i see where you are coming from now.

JavaScript (ES6), 84 89
Run snippet in Firefox to test.
Some notes:

the snake moves inside the f array. Unvisited cells have value undefined. On first visit, the tilde operator change it to -1 that is a truthy. Eventually, on a second visit the value change to 0 that is falsy and the every loop terminates returning false.
in JS, array elements with non canonic indices (not numeric or negative) are somehow 'hidden', but they do exist. Here I use negative indices with no problem.

F=s=>[...s].every(c=>f[p+=[1,1e5,-1,-1e5][d=d+{R:1,L:3,S:0}[c]&3]]=~f[p],d=p=0,f=[])

//TEST
$('#S').on('keyup mouseup change', Draw);

function Draw(){
  var s = S.value.toUpperCase();
  if (!s) {
    C.width = C.height = 0;
    return
  }
  C.width = 600;
  C.height = 400;

  var ctx = C.getContext("2d");
  var px, py, int=0;

  ctx.strokeStyle = '#008';
  ctx.lineWidth = 2;
  ctx.translate(300,200);
  ctx.beginPath();
  ctx.moveTo(0,0);

  [...s].forEach(c=>{
    (f[p+=[1,1e4,-1,-1e4][d=d+{R:1,L:3,S:0}[c]&3]]=~f[p])
    ? 1
    : (++int)
    if (int==1) ctx.stroke(), ctx.strokeStyle = '#800', ctx.beginPath(), ctx.moveTo(10*px,10*py);

    py = (p / 1e4 | 0) - 5e3;
    px = (p % 1e4) -5e3
    ctx.lineTo(10*px, 10*py);
  }, d=0,p=50005000,f=[]);
  ctx.stroke();

}

valid=["SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS",
"SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR",
"RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR",
"SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS",
"SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS",
"LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL"];
invalid=["SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR",
"SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR",
"SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS",
"SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS",
"LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"];

V.innerHTML=valid.map(s=>F(s)+' '+s).join('\n')
I.innerHTML=invalid.map(s=>F(s)+' '+s).join('\n')

Type to check and draw <input id=S>
(better full page)

<canvas id=C width=1 height=1 ></canvas>

Valid

Invalid

TI-BASIC, 49 56 53 51 bytes
abs(e^(i)-cumSum(i^cumSum(seq(inString("SL",sub(Ans,X,1))-1,X,1,length(Ans→X
SortA(∟X
min(ΔList(∟X

Similar to orlp's method, this creates a list of all points in the complex plane visited by the snake, starting at the origin. If the list has no duplicate elements, the code returns some positive value. Note that on a string of more than 999 elements, the calculator will be unable to generate a sufficiently long list, and will error.
EDIT: Saved two bytes at the cost of ugliness as no two lattice points on the complex plane can be the same distance away from e^i.

CJam, 30 bytes
q{iF%U+:U[XWe4W1e4]=T+:T}%__&=

Explanation to follow soon.
Try it online here or run the whole suite.

Damn, that was fast. I didnt even think of an algorithm to solve it myself yet.

SRRRS = true???

@Ewan umm, are we assuming that 0 is initially filled up and counts ?

I guess I am interpreting it like a game of snake, where moves take up blocks of space. and some of you guys are interpreting it as a zero width line

@Ewan My question is a bit different though. When we have a single move, say S, does it mean that the snake has already occupied both (0,0) and (1,0) ?

If you are using lines then can you 'occupy' any coord?

As i said, my question is not in the terms of line vs block. So lets assume, for sake of my question, these are all blocks.

Ruby 87 89
F=->s{d=[1,w=1e4,-1,-w]
v=[w]+s.chars.map{|c|w+=d.rotate!(c<?R?-1:c>?R?0:1)[0]}
v==v&v}

Online test: http://ideone.com/pepeW2
Ungolfed version:
F = -> input {
  # Coordinates are expressed using one number,
  # that is computed using the formula `y + x*max_x`.
  # Assume max horizontal field width (max_x) to be 10000,
  # since that's the max length of the input.
  position = max_x = 1e4

  # These are possible directions to move to (coordinate deltas).
  # The current direction is always the first in the array.
  directions = [1,max_x,-1,-max_x]

  visited = [position]

  visited += input.chars.map{|c|
    # adjust current direction...
    directions.rotate! case c
    when ?L
      -1
    when ?R
      1
    when ?S
      0
    end

    # ...and move there
    position += directions[0]
  }

  # Return `true` if `visited` only contains distinct elements, `false` otherwise
  visited == visited & visited
}

Golfscript 48 49 50
[10.4?:z-10z~)]z*z@{'R L S'?@>(@+.`n}%n/@;\;..&=

Expects the string to exist on the stack and returns either 0 or 1.
You can try it online with tests for valid and invalid snakes.
This is basically the same idea as in my Ruby answer. Just the direction array is dealt with differently, because AFAIK Golfscript does not have an arary rotate function. In this case, I build a sufficiently large directions array, by multiplying it 10000 times and then trimming from its start 0, 1, or 3 elements, depending on the current command (S, R, or L). The current "direction" to move to is always the first item in the array.
Here it is with comments:
# Build the direction array and set current position
[1 10000:z-1z~)]z*z

@{
  # For each character in the input:

  # set current direction by cutting 0, 1 or 3 elements
  # from the beginning of the directions array
  'SR L'?
  @>

  # move to current direction
  .0=@+.

  # format as number and addd newline
  `n
}%

# split by newlines
n/

# cleanup
@;\;

# return 1 if array contains distinct elements, 0 otherwise
..&=

Edit:
Saved 1 char by modifying how the "directions" array is consumed.
Edit:
saved 1 char by moving increments of 10 instead of 1 to make use of the ? (power) syntax.


text:
Calculate the first n perfect numbers
Write a program that calculates the first n perfect numbers. A perfect number is one where the sum of the factors is the original number. For example, 6 is a perfect number because 1+2+3=6. No non standard libraries.The standard loopholes are forbidden.

Please clarify: What is a non-standard library? Also, how should output be given?

Related.

Pyth - 27 25 bytes
Extremely super slow brute force approach.
K2W<ZQ~K1IqKsf!%KTr1KK~Z1

Trial division to factor, then while loop till length of perfect numbers is enough.
Try it here online.

Does prime factorization using P speed anything up?

@orlp possibly, but we want all factors, not primes.

I'm aware, but you can compute the sigma function from the factorization.

Pyth, 25 bytes
J1W<lYQy=JI!tPKtyJaY*JK;Y

Tests whether Mersenne numbers are prime. If so, it generates the corresponding perfect number. Can find the first 8 perfect numbers in under a second.
Note: Only generates even perfect numbers. However, since it has been proven that any odd perfect number is greater than 10^1500, this algorithm is correct on inputs up to 14.
Demonstration.

This answer will skip odd perfect numbers.

CJam, 24 bytes
1{{2*_(mp!}g__(*2/p}ri*;

Try it online.
Makes use of the Euclid–Euler theorem:
An even number P is perfect iff P = 2 ** (N - 1) * (2 ** N - 1) where 2 ** N - 1 is prime.
Disclaimer
If there are odd perfect numbers, this code will fail to generate them. However, there are no known odd perfect numbers.
How it works
1                        e# A := 1
 {                 }ri*  e# do int(input()) times:
  {       }g             e#   do:
   2*                    e#     A *= 2
     _(                  e#     M := A - 1
       mp!               e#   while(prime(P))
            __(2/        e#   P := A * (A - 1) / 2
                 p       e#   print(P)
                       ; e# discard(A)


text:
Add or subtract numbers to find the smallest non-negative integer
Given a positive integer, n, along with n non-negative integers, write a program or function that prints or returns the smallest non-negative integer that can be obtained by additions and subtractions between those numbers. You must use all of the input numbers.
The winner is the algorithm with the smallest big O time complexity. Ties will be broken by shortest code, in bytes. Please post your time complexity and your byte count along with your submission.
Examples
Input: 5 14 16 20 10 2
Output: 2
Two is the smallest number that can be obtained by adding or subtracting the given numbers, as shown by 16 + 14 - 20 - 10 + 2 = 2.
Input: 4 1 1 1 1
Output: 0
Input: 1 0
Output: 0
Input: 3 100 50 49
Output: 1

What is 'fastest'?

It's the fastest algorithm

The tag suggests that it's the smallest big O time complexity. Is that what you are intending?

Yes, the challenge is to find the smallest big O complexity algorithm

Seems like grading by big O complexity will result in lots of many-way ties. How will these be resolved? Am I correct in assuming that every number in the input must be used exactly once?

I was thinking about that. It can't be execution time, so it should be the length of the code

Can you add a couple more examples?

This is the optimzation version of the partition problem, which is NP-hard, so you won't be getting any polynomial-time algorithms.

There's two parameters at play here: the number of numbers, and their sizes. Different algorithms could make tradeoffs in the two. How will they be compared? (The complexity-theory default is to consider the bit-length of the input.)


text:
Draw An ASCII Double Helix
Write a program that takes in an integer N via stdin or the command line.
If N is 0, the single letter O must be printed to stdout.

If N is positive, this horizontal ASCII art double helix, drawn N segments wide, must be printed.
If N is 1, the output is:
 /\
O  O
 \/

If N is 2, the output is:
 /\ /\
O  /  O
 \/ \/

If N is 3, the output is:
 /\ /\ /\
O  /  /  O
 \/ \/ \/

If N is 4, the output is:
 /\ /\ /\ /\
O  /  /  /  O
 \/ \/ \/ \/

The pattern continues in the exact same way for larger N. Note that forward slash (/) must be used in all places the helixes cross, except for the O ends.

If N is negative, this vertical ASCII art double helix, drawn -N segments tall, must be printed.
If N is -1, the output is:
 O
/ \
\ /
 O

If N is -2, the output is:
 O
/ \
\ /
 \
/ \
\ /
 O

If N is -3, the output is:
 O
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 O

If N is -4, the output is:
 O
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 O

The pattern continues in the exact same way for smaller N. Note that backward slashes (\) must be used in all places the helixes cross, except for the O ends.
Details

Instead of a program, you may write a function that takes N as an integer and prints the result normally or returns it as a string.
The output for any N may optionally contain a trailing newline.
Any line of output for any N may optionally contain 4 or fewer trailing spaces.
There should never be any leading space that aren't part of the specified pattern.
The shortest code in bytes wins.

Brilliant Question!

it seems to me that for n=0, it might be convenient to print <spc>O<spc>  or \nO\n. Is unnecesary leading whitespace allowed?

print "." Zoom in to see helix. *nodnod*

@steveverrill That may have been helpful but there are so many answers now I don't want to change the rule. I've clarified that leading spaces not part of the pattern are not allowed.

CJam, 56 55 53 52 50 bytes
S'O:Ori:X0>"\/"=" / \\\ / "+Xz*1>O]s3/X"z"<~N*X\O?

Look at that size! The main culprits are N = 0 special case and the \ instead of / in the vertical helix.
Here is how it works:
S'O:O                                  e# Put a space on stack. Now put char O on stack
                                       e# and assign it to variable O. This is not really
                                       e# helping in golfing as using 'O everywhere is
                                       e# same number of bytes
     ri:X                              e# Read input as in integer and store it in X
         0>"\/"=                       e# If X is greater than 0, choose /, otherwise \
                " / \\\ / "            e# Put this string on stack
                           +           e# Append to chosen \ or /
                            Xz*        e# Repeat it abs(X) times
1>                                     e# Remove the first character from repeated string
  O]                                   e# Put char O on stack, wrap everything in an array
                                       e# and convert it to string.
    3/                                 e# Split the string into parts of length 3
      X"z"<~                           e# If X is positive, transpose the array to get a
                                       e# horizontal helix, otherwise it would be vertical
            N*                         e# Join the parts with newline
              X\O?                     e# If X was 0, then pick char O instead of this
                                       e# final joined string.

The code is divided into three parts:

The part X0>"\/"=" / \\\ / "+ gives either "/ / \\\ / " or "\ / \\\ / " which is crucial as the helix is simply made up of alternate "/ \" and "\ /" joined by either " / " or " \ ". For instance, if you consider input to be 2, then your final repeated string would be "/ / \\ / / / \\ / " (without escaping). This obviously has extra /  at the beginning and an extra space at the ending.
Second part is to correct the above string with additional things and split. For an input 2, the desired final string without newlines would be " O / \\\ / / / \\\ / O", but after the above point, we only have "/ / \\\ / / / \\\ / ". So we remove the first character, add a space and 'O at the beginning and another 'O at the end. Then we finally split it into parts of 3
Finally, we decide whether to transpose this split string for a vertical helix or not; Join the parts by newlines; And choose between this and a single character 'O (for input 0 case)

Try it online here

JavaScript(ES6), 126 132 133

A=n=>(F=(f,j='')=>f+(j+f).repeat(n-1),n>0?F(' /\\')+`
o${F('  ','/')}o
`+F(' \\/'):(n=-n)?` o${F(`
/ \\
\\ /
`,' \\')} o`:'o')

// Test
for(i=0;i<10;i++)
  P.innerHTML = P.innerHTML + A(i)+'\n\n\n',
  N.innerHTML = N.innerHTML + A(-i)+'\n\n\n'
pre {
  font-size: 10px;
  line-height: 9px;
}

Positive	Negative

Using templated string, newlines count.
More readable
A=n=>(
  F=(f,j='')=>f+(j+f).repeat(n-1),
  n > 0 ? F(' /\\') + '\no' + F('  ','/') + 'o\n'+F(' \\/')
  : (n=-n) ? ' o' + F('\n/ \\\n\\ /\n',' \\')'+' o':'o'
)

And i thought I'm good with JS ... what is n=>( doing? I've never seen nor used that operator before.

@YUNOWORK it's an ES6 feature for creating a function, It's still available only on FireFox. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

That's some cool stuff, should look into ES6 too soon. Thanks for clarifying!

Pyth, 52 bytes
M[Jj"/\\"*hGdjP*G+*2dH*2\O_J)?jb?gQ\/>Q0msdCg_Q\\Q\O

Demonstration.
Explanation:
The first section, M[Jj"/\\"*hGdjP*G+*2dH*2\O_J), defines a function, g, which takes two inputs. The first input, G, is the number of repetions to use. This is the absolute value of the input. The second input, H, is the character to place at the center of the spirals.
The function returns a 3 element list, which consists of the 3 lines of the positive spiral, and the 3 columns of the negative spiral.
The first element is defined by Jj"/\\"*hGd. *hGd is the string of G+1 spaces. j"/\\"*hGd joins that string with "/\" as the delimeter. The J at the beginning saves the resultant value for future use.
The second element is jP*G+*2dH*2\O. We start with +*2dH. This is two spaces followed by the input character. Then, we repeat that string G times with *G. Then, we remove its final character with P. Finally, we surround this string with two O characters, with j ... *2\O.
The third element is generated with _J. This is simply the reverse of the first line.
The latter section, ?jb?gQ\/>Q0msdCg_Q\\Q\O selects between three different posibilities, positive, negative and zero. The first if-then conditions on Q, the input. The second conditions on >Q0, whether the input is positive.
If Q is zero, \O, the character O, is printed.
If Q is nonzero, we join the result of the second ternary on newlines and print it, with jb. If Q is positive, the list joined and printed is gQ\/, g(Q,"/").
If Q is negative, the list joined and printed is msdCg_Q\\. We start with g_Q\\, which is g(-Q,"\"). Then we transpose the rows and columns with C. msd turns the resultant tuples of characters into strings, ready to be joined on newlines and printed.

Python 2, 118
n=input()
a=[' O '[n==0:]]+['/ \\','\\ /','  /\\ '[n<0::2]]*abs(n)
a[-1]=a[0]
for x in[a,zip(*a)][n>0]:print''.join(x)

Creates the vertical double helix from a list of strings and transposes it to get the horizontal one. I'm sure it could be improved.

Nice work. One thing: it should be a capital letter "O" rather than the number 0.

@AlexA. Thanks - I completely missed that.

Java, 500 488 bytes
My first try, and unfortunately it is 10* longer than the current leader :(. Anyone have any tips (other than use a different language)?
import java.util.*;class t{public static void main(String[] args){Scanner sc=new Scanner(System.in);int n=Integer.parseInt(sc.nextLine());if(n>0){for(int i=0;i<n;i++)System.out.print(" /\\");o("");System.out.print('o');for(int i=0;i<n-1;i++)System.out.print("  /");o("  o");for(int i=0;i<n;i++)System.out.print(" \\/");}else if(n<0){o(" o ");for(int i=0;i<-n-1;i++){o("/ \\");o("\\ /");o(" \\ ");}o("/ \\");o("\\ /");o(" o ");}else o("o");}static void o(String s){System.out.println(s);}}

Welcome to PPCG! It's not important that you're a factor 10 off a golfing language like CJam with Java. ;) The joy is in trying to beat answers in the same language, or languages of similar verbosity, and learning new quirks of your language. I'm not that familiar with golfing in Java, but you can certainly save some bytes with a shorter class name and consistently 1-letter variable names. Also, can't you just import System.* or something to save writing System each time?

Indeed he can, import static java.lang.System.*;, or he could save the standard output stream as a variable (though, I don't know if it'd save or hinder in this case, haven't checked).

+1 for Java. You can get rid of the sc variable since it is only called once. Shaves off 14 bytes.

I know it's been almost three years, but quite a few things can be golfed: class M{public static void main(String[]a){int n=new Integer(new java.util.Scanner(System.in).next()),i=n;if(n>0){for(;i-->0;)o(" /\\");o("\no");for(i=n;i-->1;)o("  /");o("  o\n");for(i=0;i++<n;)o(" \\/");}else if(n<0){o(" o \n");for(i=0;i++<~n;)o("/ \\\n\\ /\n \\ \n");o("/ \\\n\\ /\n o \n");}else o("o\n");}static<T>void o(T s){System.out.print(s);}} (352 bytes) Try it online.

In addition, a function is allowed for this challenge, so it can be 251 bytes when using a Java 8+ lambda: n->{int i=n;if(n>0){for(;i-->0;)o(" /\\");o("\no");for(i=n;i-->1;)o("  /");o("  o\n");for(i=0;i++<n;)o(" \\/");}else if(n<0){o(" o \n");for(i=0;i++<~n;)o("/ \\\n\\ /\n \\ \n");o("/ \\\n\\ /\n o \n");}else o("o\n");};<T>void o(T s){System.out.print(s);} Try it online.

Haskell, 156 bytes
h 0="O"
h n|n>0=' ':c n "/\\ "++"\nO"++c(n-1)"  /"++"  O\n "++c n "\\/ "
   |0<1=" O\n/ \\\n"++c(-n-1)"\\ /\n \\\n/ \\\n"++"\\ /\n O"
c x=concat.replicate x

You can then write it as:
*Main> putStrLn $ h 1
 /\
O  O
 \/
*Main> putStrLn $ h 0
O
*Main> putStrLn $ h (-1)
 O
/ \
\ /
 O
*Main> putStrLn $ h 3
 /\ /\ /\
O  /  /  O
 \/ \/ \/
*Main> putStrLn $ h (-3)
 O
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 O
*Main>

You can write 1<2 or something like that instead of True, and save a byte.

@marinus: updated, many thanks.

C#, 242 241 238 230 222 219 Bytes
Spurred on by Martin's comment, here's my first attempt at something like this:
string h(int n){int x=0;string p="",r=n==0?"O":p;if(n>0){for(;x++<n;){r+=" /\\";p+=" \\/";}r+="\nO  ";for(;x-->2;)r+="/  ";r+="O\n"+p;}else if(n<0){r+=@" O
/ \
";for(--x;x-->n;)r+=@"\ /
 \
/ \
";r+=@"\ /
 O";}return r;}

More readably:
string h(int n)
{
    int x = 0;
    string p = "",
            r = n==0 ? "O" : p;
    if (n > 0) {
        for (; x++ < n;) {
            r += " /\\";
            p += " \\/";
        }
        r += "\nO  ";
        for (; x-- > 2;) r += "/  ";
        r += "O\n" + p;
    }
    else if(n<0) {
        r += @" O
/ \
";
        for (--x; x-- > n;) r += @"\ /
 \
/ \
";
        r += @"\ /
 O";
    }
    return r;
}

C# 199 197 196 bytes
string f(int n){var u=n<0;int m=u?-n:n;string a="",b=" O ";for(;m-->0;)b+="\n/ \\\n\\ /\n "+(m==0?"O ":u?"\\ ":"/ ");for(;++m<3;)a+=string.Concat(b.Split('\n').Select(s=>s[m]))+"\n";return u?b:a;}

Ungolfed version:
    string f(int n)
    {
        var u = n < 0;
        int m = u ? -n : n;
        string a = "", b = " O ";
        for (; m-- > 0; ) b += "\n/ \\\n\\ /\n " + (m == 0 ? "O " : u ? "\\ " : "/ ");
        for (; ++m < 3;) a += string.Concat(b.Split('\n').Select(s => s[m])) + "\n";
        return u ? b : a;
    }

The idea is to build the horizontal display from the vertical display by rendering the transposed matrix of characters.

Nice - I hadn't had a chance to try a transposition answer in C# yet.  Note that you have the "" and "/" the wrong way round for the crossovers, and you can save a few bytes by changing for(;m>0;--m) to for(;m-->0;) in both loops

This string: "\n/ \\\n\\ /\n " could also be shortened as per the methods in my answer - ie use @"...", where each "\" becomes "" and each "\n" becomes an actual newline

Right, I introduced the variable u to shorten the solution, but forgot to invert the test of the crossovers. Thanks for the idea of shortening the loop condition (though I can't shorten the second loop since m is then equal to 0 and I use it as index). For the newline trick, it doesn't work under windows because the b.Split('\n') should be changed to b.Split('\n','\r') which costs 5 characters and saves only 3.

Ah fair enough - I guess I hadn't noticed because I wasn't splitting anything.  I also just spotted you could switch bool u for var u for another whole byte :)

Since your version didn't use any var, I didn't want to get an undue advantage. :)

haha - I couldn't use it for my strings, as I was initialising them at the same time - you can't use var when you do that (you wouldn't be able to do it for a and b here)

Fine, here you go, "var".

Python 3, 118 bytes
x=int(input())
print("O"if x==0else" /\\"*x+"\nO "+" / "*(x-1)+" O\n"+" \\/"*x if x>0else(" O"+"\n/ \\\n\\ /\n \\"*-x)[:-1]+"O")

My first ever code golf submission, so it may not be at all impressive.
Just uses Python's ... if ... else ... ternary operator to separate the three scenarios. That gives a string made of repeating some smaller strings a certain number of times to print.

Julia, 229 bytes
Oh man, this is way, way too big. It's the longest answer so far by a large margin. I could probably save a lot by returning the string rather than printing it, or by avoiding the matrix approach altogether. I'll experiment with that later.
n->(if n==0 println("O")else m=abs(n);A=B=reshape(split(" / "*(n>0?"/":"\\")*" \\\\ /",""),(3,3));E=[" ";"O";" "];if m>1for i=2:m B=hcat(B,A)end end;B[:,1]=E;B=hcat(B,E);C=n>0?B:B';for i=1:size(C,1) println(join(C[i,:]))end end)

This creates a lambda function that takes a single integer and prints the appropriately formatted double helix. To call it, give it a name, e.g. f=n->(...).
Ungolfed + explanation:
function f(n)
    if n == 0
        println("O")
    else
        m = abs(n)

        # Split the string into a 3x3 matrix with a slash on the left,
        # or a backslash for n < 0
        A = B = reshape(split(" / " * (n > 0 ? "/" : "\\") * " \\\\ /", ""), (3, 3))

        # We can get the O lines where needed by appending this
        E = [" "; "O"; " "]

        # Grow the helix by abs(n)
        if m > 1
            for i = 2:m
                B = hcat(B, A)
            end
        end

        # Exchange the first column for E
        B[:,1] = E

        # Add E onto the right
        B = hcat(B, E)

        # If n is negative, we actually want the transpose
        C = n > 0 ? B : B'

        # Print the rows of C
        for i = 1:size(C, 1)
            println(join(C[i,:]))
        end
    end
end

A couple examples:
julia> f(1)
 /\
O  O
 \/

julia> f(-2)
 O
/ \
\ /
 \
/ \
\ /
 O

Python 3, 135 bytes
n=int(input());m=abs(n)-1;print({n:" O\n/ \\\n"+m*"\ /\n \\\n/ \\\n"+"\\ /\n O",m+1:n*" /\\"+"\nO"+"  /"*m+"  O\n"+" \/"*n,0:"O"}[n])

Try it online here

Perl, 91 97
Transposing proved to be too expensive in the end.
#!perl -n
print/-/?"\0\23"^" \\
/ \\
\\ /
"x-$_." O":-$_?" /\\"x$_.("*`"^" / "x$_." O
"." \\/"x$_):O

Previous solution:
#!perl -n
$".="`"^"/
\\ /
/ \\
 "x abs.O;print/-/?$"=~y!/\\!\\/!r:/^0/?O:map{($"=~/^.{$_}(.)/mg,$/)}2,1,0

Test me.

This is really sweet. You can save two more bytes by replacing /^0/?O:etc with $_?etc:O

@alexander-brett this would require no EOL on input, because "0\n" evaluates to true.

You can probably get away with requiring no EOL on stdin :) also, you can save 4 with $".="\23"^"\\  / \\ \\ /  "x abs."O ";print/-/?$":/^0/?O:map{reverse$/,$"=~/(.).{$_}$/mg}0..2

@alexander-brett, this produces backslashes in the center line for positive numbers, which is incorrect, right?

Oh man, that's what I get far playing fast and loose. You're absolutely right. Also, did I mention I really really like this array-transpose idea.

Scheme, 379 bytes
My first attempt at code golf and, unfortunately, one of the longest ones. :(
(define (h i) (define a string-append) (define (k n p q s e) (cond ((= i n) (p s (k (q n 1) p q s e))) ((= 0 n) e) (else (p `("\\ /" ,(if (> i 0) " / " " \\") "/ \\") (k (q n 1) p q s e))))) (if (= i 0) "O\n" (apply a (map (lambda (s) (a s "\n")) (if (> i 0) (k i (lambda (x y) (map a x y)) - '(" /" "O " " \\") '("\\" " O" "/")) (k i append + '(" O" "/ \\") '("\\ /" " O")))))))

Ungolfified:
(define (h i)
  (define a string-append)

  (define (k n p q s e)
    (cond ((= i n) (p s (k (q n 1) p q s e)))
          ((= 0 n) e)
          (else (p `("\\ /" ,(if (> i 0) " / " " \\") "/ \\")
                   (k (q n 1) p q s e)))))

  (if (= i 0) "O\n"
      (apply a (map (lambda (s) (a s "\n"))
                    (if (> i 0)
                        (k i (lambda (x y) (map a x y)) -
                           '(" /" "O " " \\")
                           '("\\" " O" "/"))
                        (k i append +
                           '(" O" "/ \\")
                           '("\\ /" " O")))))))

Java, 282
My first approach, with particularly nice variable names:
class H{public static void main(String[]_){int N=Integer.parseInt(_[0]),í=N;String ì="/ \\\n\\ /\n",I=" o \n",i="",l=I;for(;í-->0;)i+=" /\\";i+="\no";for(í=N;í-->1;)i+="  /";i+="  o\n";for(í=N;í-->0;)i+=" \\/";for(í=1;í++<-N;)l+=ì+" \\ \n";System.out.println(N<0?l+ì+I:N>0?i:"o");}}

I have no idea why I am doing this. Must be some recreational thing.

Java, 317
My first code golf attempt.
public class t{public static void main(String[]e){int n=Integer.parseInt(e[0]);String s=new String(new char[n==0?0:(n>0?n:-n)-1]),u="\0";System.out.print(n==0?"O":n>0?s.replace(u," /\\")+" /\\\nO"+s.replace(u,"  /")+"  O\n"+s.replace(u," \\/")+" \\/":" O \n/ \\\n"+s.replace(u,"\\ /\n \\ \n/ \\\n")+"\\ /\n O \n");}}

Groovy, 142 134 129 125 120 118
a=args[0]as int;b="\n/ \\\n\\ /\n ";print!a?"O":a>0?" /\\"*a+"\nO  ${"/  "*(a-1)}O\n"+" \\/"*a:" O$b${"\\$b"*(1-a)}O"

Finally tied with python 2!

Python 3, 165 bytes
x,a,b,c,d=int(input())-1,'\ /',' / ','/ \\','\ /\n \\\n/ \\\n'
print([[' O\n/ \\\n'+d*abs(x+2)+'\ /\n O',' /'+a*x+'\\\nO '+b*x+' O\n \\'+c*x+'/'],'OO'][x==-1][x>-1])

Try it online here.

Perl, 193 197 187 180 166 163B
1 byte penalty for -n commandline switch. Run with echo 1|perl -M5.10.0 -n scratch.pl:
$_*=3;$s=($m=abs)==$_;$_?map{say if$_=join'',map{(map[/./g]," O ",(('/ \\', '\\ /',$s?' / ':' \\ ')x$m)[0..$m-2]," O")[$s?$_:$j][$s?$j:$_]}0..$m;$j++}0..$m:say'O'

With whitespace:
$_ *= 3;
$s = ($m = abs) == $_;
$_ ? map{
      say if $_=join '', map {
       ( map[/./g],
          " O ",
          (('/ \\', '\\ /',$s?' / ':' \\ ') x $m)[0..$m-2],
          " O"
        )[$s ? $_ : $j][$s ? $j : $_]
       }0..$m;
      $j++
    } 0..$m
  : say 'O'

Is it conventional that -M5.10.0 does not contribute to your byte count?  say is handy for code golf …

@TheSuitIsBlackNot said that it was (in the top comment http://codegolf.stackexchange.com/a/49762/19039 on) - I assume it's because it's a language version.

R, 228 201
n=scan();z=cat;f=`for`;if(!n)z("O");if(n>0){f(i,1:n,z(" /\\"));z("\nO  ");if(n>1)f(i,2:n,z("/  "));z("O\n");f(i,1:n,z(" \\/"))};if(n<0){z(" O\n");f(i,-n:1,{z("/ \\\n\\ /\n ");if(i>1)z("\\\n")});z("O")}

My first attempt at code golf. I think it works but it is not subtle.
n=scan(); # enter number here
z=cat;
if(!n) z("O\n");
if(n>0){
  z(" ");
  for(i in 1:n) z("/\\ ");
  z("\nO");
  if(n>1){
    for(i in 2:n) z("  /")
  };
  z("  O\n ");
  for(i in 1:n) z("\\/ ")
};
if(n<0){
  z(" O \n");
  for(i in -n:1){
    z("/ \\\n\\ /");
    if(i>1) z("\n \\\n")
  };
z("\n O ")
}

PHP, 341
$s='';$n=$argv[1];$l=PHP_EOL;if($n>0){for($i=0;$i<$n;$i++)$s.=" /\\";$s.=$l;for($i=0;$i<$n;$i++){if($i==0)$s.='o';if($i<$n-1)$s.='  /';if($i==$n-1)$s.='  o';}$s.=$l;for($i=0;$i<$n;$i++)$s.=" \\/";}else{$n=abs($n);for($i=0;$i<$n;$i++){if($i== 0)$s.=' o '.$l;$s.="/ \\".$l."\\ /".$l;if($i < $n-1)$s.=' \\ '.$l;if($i==$n-1)$s.=' o '.$l;}}echo $s;

Ungolfed version
$s = '';
$n = $argv[1];
echo PHP_EOL;
if($n > 0)
{
    for($i=0;$i<$n;$i++)
    {
        $s.=" /\\";
    }
    $s.=PHP_EOL;

    for($i=0;$i<$n;$i++)
    {
        if($i==0) {
            $s.='o';
        }
        if($i < $n-1) {
            $s.='  /';
        }
        if( $i == $n-1)
        {
            $s.='  o';
        }
    }
    $s.=PHP_EOL;

    for($i=0;$i<$n;$i++)
    {
        $s.=" \\/";
    }
} else
{
    $n = abs($n);
    for($i=0;$i<$n;$i++)
    {
        if($i == 0) {
            $s.=' o '.PHP_EOL;
        }
        $s.="/ \\".PHP_EOL."\\ /".PHP_EOL;
        if($i < $n-1) {
            $s.=' \\ '.PHP_EOL;
        }
        if( $i == $n-1) {
            $s.=' o '.PHP_EOL;
        }
    }
}

echo $s;

JAVA 377 384 bytes
class F{public static void main(String[] a){int n=Integer.parseInt(a[0]);if(n>0){for(int i=0;i<n;i++)p(" /\\");p("\n");for(int i=0;i<n;i++){if(i==0)if(n>1)p("O  ");else p("O  O");else if(i==n-1)p("/  O");else p("/  ");}p("\n");for(int i=0;i<n;i++){p(" \\/");}}else{p(" O\n");for(int i=0;i<Math.abs(n);i++){p("/ \\\n\\ /\n O\n");}}}static void p(String s){System.out.print(s);}}

C++ 269 262 258
#include <string>
#include <iostream>
int main(){int i,j;std::cin>>i;std::string s,u,t;if(i>0){for(j=i;j;j--){s+=" /\\";t+="/  ";u+=" \\/";}t[0]='O';t+="O";s=s+'\n'+t+'\n'+u;}else{for(j=i;j;j++)s+=" \\\n/ \\\n\\ /\n";s[1]='O';s+=" O";}std::cout<<(i==0?"O":s);}

Canvas, 33 32 30 bytes
 /¶O：╴⤢╷\ /¶ \×＋；↔＋──╴０＜？↷｝╴‽O

Try it here!
Explanation:
 /¶O:                           push " /\¶O" twice
     ╴⤢╷                        push the absolute value of the input, -1
        \ /¶ /×                 repeat "\ /¶ /" horizontally that many times
               ＋                append that horizontally to one of the first strings
                ;               and get the other, reverse it
                 ↔+             and then append it to the result of above. Now the top part of the helix is done
                   ──           vertically palindromize with no mirroring (works because of a misake - it just doesn't overlap smartly)
                     ╴0<? }     if the input is less than 0
                         ↷        rotate clockwise the whole thing
                           ╴‽   if the input is falsy (aka 0)
                             O    push O; implicitly output the top of stack

Charcoal, 28 24 22 bytes
↙OＦ↔θ/¶\¶ \¶↗‖ＢO¿›Ｎ⁰⟲Ｔ

Try it online! Link is to verbose version of code. Explanation:
↙O

Print the top O, and leave the cursor one space down and left.
Ｆ↔θ/¶\¶ \¶

Print the strings /, \ and  \ and repeat for the absolute number value of the input.
↗

Move back over the last \.
‖Ｂ

Reflect to create the right-hand side of the helix. I do this here because otherwise the ↗ would not parse unambiguously.
O

Overwrite the last \ with an O.
¿›Ｎ⁰⟲Ｔ

If the input was positive then rotate the canvas.

C, 189 bytes
char*h="6Er66 e66Ee 6rE66",*v="6e6 E6r r6E 6r6 6e6",*z="e",*u;b,m,w,c,p;f(n){b=n<0;u=b?v:n?h:z;for(m=b?4:1,w=n*(b?-3:3);u[p];p+=++c%((w+2)*m)==w*m?m:p%(6*m)==m*4?-m*3:0)putchar(u[p++]-22);}

With whitespace and newlines:
char *h="6Er66 e66Ee 6rE66",
     *v="6e6 E6r r6E 6r6 6e6",
     *z="e",
     *u;
b, m, w, c, p;
f(n) {
    b = n < 0;
    u = b ? v : n ? h : z;
    for (m = b ? 4 : 1, w = n * (b ? - 3 : 3);
         u[p];
         p += ++c % ((w + 2) * m) == w * m ? m : p % (6 * m ) == m * 4 ? - m * 3 : 0)
        putchar(u[p++] - 22);
 }

Some notes about the approach:

Stores the pattern in character arrays. They are shifted by 22 characters to avoid needing a bunch of backslashes to escape special characters.
Uses separate patterns for horizontal, vertical, and zero. I initially considered using one single pattern, and just traversing it differently for positive and negative values. I didn't implement it, but I had a feeling that it would make the logic quite a bit more complicated. Particularly since the central slash has the opposite direction for the two cases. And the tables are not that large, so this seemed more promising.
The code is mainly just index calculations, with logic to decide when it's done and when the pattern loops. Much of the math is there so that it works for both cases with their different dimensions and repetition rules.

C++, 352
Not at all the shortest answer, but the first in C++ so far :)
#include <iostream>
int main(int argc, char* argv[]){int a=argv[0][0]-'0';if(a==0){printf("o");}else if(a>0){for(int i =0; i < a;i++){printf(" /\\");}printf("\no");for(int i=0;i<a-1;i++){printf("  /");}printf("  o\n");for(int i=0;ia+1;i--){printf("/ \\\n\\ /\n");}printf(" o");};}

Here it is in C++ Shell with whitespace to test

perl 156
$==pop;print$=>0?' /\\'x$=.$/:'',$=>0?'O'.'  /'x$=."\bO
":'',$=>0?' \\/'x$=:'';print$=<0?" O":'';print"
/ \\
\\ /
 \\" for$=..-1;print$=<0?"\bO":!$=?"O":''

Pretty straight forward attempt, my second golf.
I think newlines count as 1 byte right?
Now to figure out how to join all those ternaries together.. I have a lot of room for improvement with those :''; everywhere.

Perl, 184 bytes
$n=pop;$p=$n>0;$_=' \ /'x(1+abs$n*3);$n=$p?$n*4+1:3;$_=join'
',/.{$n}/g;$r=$p?'.':'.*
';s/($r$r)$r($r)/$1$2/g;$p and s/^\S|\S$/O/gm or s/^ \S $|(?<=^ )\S|\S $/O/g;y~\\/~/\\~if$p;print;

I thought this was going to be a lot shorter! There are probably some simple things I can do to save a few bytes. It's been five years since I've programmed seriously in Perl!

PHP, 155
$n=$argv[1];$r='str_repeat';$k="/ \\\n\\ /\n";echo$n>0?" /{$r('\ /',$n-1)}\\\nO{$r('  /',$n-1)}  O\n \\{$r('/ \\',$n-1)}/":" O\n{$r("$k \\\n",-$n-1)}$k O";

C (gcc), 161 160 bytes
Now more compliant than ever! Thanks to @EriktheOutgolfer for making it so.
#define g(n)for(i=n;i--;)printf(
i;f(n){if(n<0){puts(" O");g(-n)"/ \\\n\\ /\n%2c\n",i?92:79);}else{g(n)" /\\");g(1)"\nO"+!n);g(n)i?"  /":"  O\n");g(n)" \\/");}}

Try it online!

You can save a byte by making the Os uppercase. However, I think this answer is invalid (There should never be any leading space that aren't part of the specified pattern.)

@EriktheOutgolfer Ah, yes. Not sure why I added unnecessary spaces there. Also, thanks for pointing out the Os are capital, since I completely missed that.

J, 67 59 55 51 bytes
(<&0|:' O '(0},[)(3,~3*|)$' / \\'({~,7$[)0,*) ::'O'

Try it online!

SOGL V0.12, 37 bytes
 O¶/”▓:.θH{"⌠λ5⁸‘▓+};↕№+╬⁷.0>?I↔}.‽ O

Try it Here!

Ruby, 118 138 bytes
->i{print i<0?" O ":" /\\"*i+"\n"*(1-0**i),i<0?("\n/ \\\n\\ /\n \\"*-i)[0..-3]:i==0&&"O"||"O "+" / "*(i-1)+" O\n",i<0?" O ":" \\/"*i+"\n"}

Basically a if-else statement on all the 3 parts of the helixes :)
Try it online!
Any tips to get it even smaller would be greatly appericated!
Edit: Silly me forgot to remove all the parantheses, and didnt see the requirement of "O" if 0

Vyxal, 45 bytes
ȧDk/ðp*ð+⅛\/w$‹ẋf\Op\OJṄððdV⅛k\ðp*⅛¾?0<ßÞTvṅ⁋

Try it Online!
Transposing the input yields the vertical version :)

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


text:
Is This a Real Tree?
You should write a program or function which receives a string as input and outputs or returns if the input is an ASCII tree.
  _
\/  /
 \_/
  |
  |

ASCII trees consist of characters / \ | _ spaces and newlines.
The non-whitespace characters connect two edge points of their cells by a line segment:

/ connects the bottom left and top right corners
\ connects the bottom right and top left corners
| connects the middle points of the bottom edge and top edge
_ connects the bottom left and bottom right corners and the middle point of the bottom edge

(Note that this means that | can only connect with | or _ but not with / or \.)
An ASCII picture is called a tree if the following rules apply:

Exactly one point (the root) of exactly one character touches to the bottom edge of the last row.
You can reach any point of any line segment by:

starting from the root
using only the line segments
never going into a downward direction (not even sideways downward)

Input

A string consisting of the characters / \ | _ space and newline containing at least one non-whitespace character.
You can choose of two input format:

No unnecessary whitespace around the tree (as seen in the examples).
No unnecessary whitespace around the tree (as seen in the examples) except spaces on the right side of the rows to make all rows the same length.

Trailing newline is optional.

Output

A consistent truthy value if the input is an ascii tree.
A consistent falsy value if the input isn't an ascii tree.

Examples
Valid trees:
|

  _
\/  /
 \_/
  |
  |

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

 \___/
 /   \
 \___/
   |
   |

   __/
 _/
/

____
  \  ___
 \ \/
  \/\_____/
 \/  \/
  \__/
    |
    |

Invalid trees (with extra explanations which are not parts of the inputs):
\/
 \_______/
  \__   /
   | \_/    <- reachable only on with downward route
   |

_           <- multiple roots

\/          <- multiple root characters

/\          <- multiple roots

|           <- unreachable part

|

 __/
/           <- unreachable parts
|

\____/
 |  |       <- multiple roots

_\__/       <- unreachable parts (_ and \ don't connect to each other)
|

This is code-golf so the shortest entry wins.

PMA/Snails, 99 93
Prints 1 if it satisfies the "tree" definition or 0 if not. The rectangular space-padded form of input is preferred, although it costs only one byte (using the F option) to convert the ragged version to a space-filled rectangle, which was useful in testing.
&
\ |{(\_|\|)d=\||(\\a7|\/d|\_da7)=\\|(\\d|\/a5|\_da5)=\/|(\_lr|\|d|\/l|\\r)=\_},^_!(r.,^ )d~

Ungolfed, outdated version (for my personal viewing pleasure) :
F&
\ |
{
  \_ (lr=\_|da5=\/|da7=\\|d=\|) | \/ (l=\_|a5=\/|d=\\) |
    \\ (r=\_|a7=\\|d=\/) | \|d=(\_|\|)
},
^_ !(r.,^ ) d~

This turns out to be fairly well suited to the current language features. Unfortunately, I had to spend a few hours chasing down a reference counting bug before it could work.
The & option means that the match must succeed at every character. From each non-space starting point it checks for a downward path to the bottom. Making a finite state machine with a regex is luckily much shorter by using assertions, here = ... . At the bottom row, it checks that there are no non-space characters to the right.

Mathematica, 345 300 bytes
Still quite long, but I guess it's a start...
(s=StringSplit;v=Reverse;#=="|"||#=="\\"||#=="/"&[""<>s@#]&&(g={};i=0;(c={i,++j};d={i,j+1/2};e=2d-c;g=Join[g,Switch[#,"|",{d->{1,0}+d},"/",{c->c+1},"\\",{e->{i+1,j}},"_",{c->d,d->e,e->c},_,{}]])&/@Characters[++i;j=0;#]&/@{##};Sort@VertexOutComponent[Graph@g,g[[1,1]]]==Union@@List@@@g)&@@v@s[#,"
"])&

Here is a slightly ungolfed version:
(
  s = StringSplit;
  v = Reverse;
  # == "|" || # == "\\" || # == "/" &[
      "" <> s@#
      ] && (
      g = {};
      i = 0;
      (
           c = {i, ++j};
           d = {i, j + 1/2};
           e = 2 d - c;
           g = Join[g, Switch[#,
              "|", {d -> {1, 0} + d},
              "/", {c -> c + 1},
              "\\", {e -> {i + 1, j}},
              "_", {c -> d, d -> e, e -> c},
              _, {}
              ]]
           ) & /@ Characters[
          ++i;
          j = 0;
          #
          ] & /@ {##};
      Sort@VertexOutComponent[Graph@g, g[[1, 1]]] ==
       Union @@ List @@@ g
      ) & @@ v@s[#, "\n"]
) &

This defines an unnamed function which takes the string as input and returns True or False.
The basic idea is first to check that there's a single root, and then to build an actual (directed) Graph object to check if all vertices can be reached from the root. Here is how we build the graph:
Imagine an integer grid overlaid onto the ASCII art, where integer coordinates correspond to the corners of the character cells. Then on each of the cells there are six relevant points that can be connected. Here is an example, where I've also labelled the points a to f:
     |                 |
     |                 |
---(2,3)---(2.5,3)---(3,2)---
     | d      e      f |
     |                 |
     |                 |
     |                 |
     |                 |
     |                 |
     |                 |
     | a      b      c |
---(2,2)---(2.5,2)---(3,2)---
     |                 |
     |                 |

So we can build a graph whose vertices are these half-integer coordinates, and whose edges are determined by the non-space characters in the input. | connects b to e, / connects a to f and \ connects c to d. Note that these must be directed edges to ensure that we're never moving downwards while traversing the graph later. For _ we can go either way, so in theory we need four edges a -> b, b -> a, b -> c, c -> b. However, we can notice that all that matters is that there's a cycle containing all three vertices, so we can shorten this to three edges: a -> b, b -> c, c -> a.
Building this graph is quite simple in Mathematica, because any object can act as a vertex, so I can actually build a graph whose vertices are the coordinate pairs.
Finally, we check that every vertex can be reached from the root. The root's coordinate is easily found as the very first vertex we added to the graph. Then the shortest way I have found to check if all vertices can be reached is to check if the VertexOutComponent of the root (i.e. the set of all vertices reachable from the root) is identical to the set of all vertices in the graph.

300 bytes may be long, but exactly 300 is so satisfying!

Ruby 226 227 228
->i{w=i.index(?\n)+1
t=[i.index(/[^ _] *\n\z/)]
a=->x,c{(i[x]==c||i[x]==?_)&&t<<x}
((x=t.pop)&&(s=x-w;c=i[x])<?0?(a[s+1,?/];a[s,?\\]):c<?]?(a[s-1,?\\];a[s,?/]):c<?`?(a[x-1,?\\];a[x+1,?/]):a[s,?|]
i[x]=' ')while t!=[]
!i[/\S/]}

Online test: http://ideone.com/Z7TLTt
The program does the following:

searches for a root (a \, /, or | on the last row)
starting from that root, climb the tree using the rules and replacing every visited char with a space
at the end, see if our string is fully composed of whitespace (meaning a valid tree), or not (invalid tree; not all pieces have been "visited")

Here it is ungolfed:
F =-> input {
  row_size = input.index(?\n)+1

  root_coord = input.index /[^ _] *\n\z/

  # coordinates to process
  todo = [root_coord]

  add_todo = -> coord, char{
    if input[coord] == char || input[coord] == ?_
      todo << coord
    end
  }

  while todo.any?
    x = todo.pop

    next unless x # exit quickly if no root present

    case input[x]
    when ?|
      add_todo[x - row_size, ?|]
    when ?_
      add_todo[x - 1, ?\\]
      add_todo[x + 1, ?/]
    when ?/
      add_todo[x - row_size + 1, ?/]
      add_todo[x - row_size, ?\\]
    when ?\\
      add_todo[x - row_size - 1, ?\\]
      add_todo[x - row_size, ?/]
    end
    input[x]=' '
  end
  input.strip < ?*
}


text:
List Sophie Germain primes
The Question
A Sophie Germain prime is a prime \$p\$ such that \$2p+1\$ is prime as well. For example, 11 is a Sophie Germain prime because 23 is prime as well. Write the shortest program to calculate Sophie Germain primes in ascending order
Rules

The Sophie Germain primes must be generated by your program, not from an external source.
Your program must calculate all Sophie Germain primes under \$2^{32}-1\$
You must print each distinct Sophie Germain prime your program finds.
The person with the lowest score wins

Scoring

2 points per byte of your code
-10 if you can show a prime generated by your program greater than \$2^{32}-1\$

Comments are not for extended discussion; this conversation has been moved to chat.

Pyth, 19 bytes * 2 - 10 = 28
Note that the online compiler/executor doesn't show output because it's an infinite loop.
K1#~K1I&!tPK!tPhyKK

Explained:
K1                      K=1
  #                     While true:
   ~K1                  K+=1
      I                 If
       &                logical AND
        !tPK            K is prime
            !tPhyK      2*K+1 is prime (y is double, h is +1)
                  K     Print K

PZ doesn't return a truthy or falsy value. It returns the prime factorization of Z. Testing for prime is !tPZ, which checks if the prime factorization only contains one factor.

Yes. Now it works. !tP mistakes 0 and 1 to be prime though, since their prime factorization only contains 1 factor. Easy fix is to replace all Z by K and assign K2 at the beginning.

Some other golfs: assign K1 instead of K2, and swap the if and the increment. This way you can remove the ). And +1*K2 is the same thing as hyK.

Ah, I had just read about those on the tutorial page. Does it work for you on https://pyth.herokuapp.com/?code=K2%23I%26!tPK!tPhyKK)~K1&debug=0

The online compiler doesn't show a result, because the program is stuck in an infinite loop. And the website shows only output, after the program finishes. I've tested the code using the offline compiler. It works.

Swapping if-condition-print and incrementing-K saves still 1 byte: K1#~K1I&!tPK!tPhyKK

CJam
For 17 chars we get full enumeration up to 2^32:
G8#,{_mp*2*)mp},`

For 4 chars more, we get a range just large enough to include an SG prime greater than 2^32:
G8#K_*+,{_mp*2*)mp},`

since 4294967681 = 2^32 + 385 < 2^32 + 400.
Of course, we could equally extend the range for free as
C9#,{_mp*2*)mp},`

This means you can submit it without the bonus for 17 characters or with the bonus for 21 characters

@user3502615, or with the bonus for 17 characters. Although it's debatable whether the SG prime I list was actually generated "by my program", since I don't have a powerful enough computer to run it that far.

I, treats I as a signed 32-bit integer, so the maximum value for I is 2 ** 31 - 1.

@Dennis, is that a documented property of the language or an implementation quirk of the Java implementation?

It's not documented, but the behavior is consistent for both the Java and the online interpreter.

Husk, 16 8 7 * 2 - 10 = 4
-8 12 thanks to @Jo King
fȯṗ→Dİp

Try it online!
A list of all natural numbers that are Sophie Germain primes. I hope it's valid, because it doesn't terminate when you try to show the entire list, but Husk lazily evaluates it, so you can just take the required amount.
fȯṗ→Dİp
f         Filter
     İp   the prime numbers
    D     that, when doubled
   →      and incremented by 1
 ȯṗ       are prime

Another way to do it, also 7 bytes:
fṗm÷2İp

I had this exact same program, but it didn't display anything(like you have said), so I wrote an APL answer.

05AB1E, 7 bytes, score = 4
Thanks to @ovs for -1 byte!
∞ʒx>‚pP

(Technically) Prints an infinite list of Sophie Germain primes! (Hence, score is subtracted by 10)
Try it online!
How?
∞ʒ        # For each natural number 'p'...
  x>‚     # Pair p with 2p + 1 (The ‚ is not a comma, it is a weird sort of quotation)
     p    # Are they both prime?
      P   # Then multiply the boolean values! (And implicitly print if the product is 1)

∞ʒx>‚pP for 7 bytes.

∞<Øʒ·>p for an alternative 7-byter. Too bad 2 is truthy, otherwise the < could have been removed.

This is ‚ SINGLE LOW-9 QUOTATION MARK, not , COMMA. This can be really confusing, but the first pairs up two numbers while the latter prints to STDOUT

@ovs Just figured that out... :P

Pyth - 2 * 16 bytes - 10 = 22
Uses the customary method of prime checking in Pyth with the !tP and applies it both to the number and its safe-prime, with a little trick to check both at once. Goes up to 10^10, so I'm going for the bonus.
f!+tPTtPhyTr2^TT

Explanation coming soon.
f          r2^TT     Filter from 2 till 10^10
 !                   Logical not to detect empty lists
  +                  List concatenation
   tP                All but the firs element of the prime factorization
    T                The filter element
   tP                All but the firs element of the prime factorization
    hyT              2n+1

Try under 1000 online.

This takes a machine with about 40 GB of RAM memory. Quite efficient ;-)

I don't think you can claim the - 10 unless you have actually successfully run the code?

@orlp no, I asked OP and he said making the range smaller and simulating the whole program would be sufficient: http://chat.stackexchange.com/transcript/message/21585393#21585393

APL (Dyalog Extended), 10 - ⍨ 2 × 27 = 44
f←{⎕←⍵⍴⍨⌽∧\1⍭⍵,1+2×⍵⋄∇⍵+1}1+⊢

Try it online!
Made with some golfing help and general APL help from dzaima.
Explanation
{⎕←⍵⍴⍨⌽∧\1⍭⍵,1+2×⍵⋄∇⍵+1}1+⊢
                        1+⊢ add 1 to the input (initially, 1)
             1+2×⍵          double and increment it
         1⍭⍵,               prepend the primality check(1 or 0)
       ∧\                   and scan with LCM
   ⍵⍴⍨⌽                     reverse & reshape using self
                            (if test is falsy, then this results in ⍬)
 ⎕←                         and display it with newline

Vyxal, 6 bytes, score 2
Þp:d›↔

Try it Online!
     ↔ # Union of...
Þp     # Primes
  :d›  # Primes * 2 + 1

-10 score because it prints an infinite list.

Nekomata, 4 bytes, score -2
Ƥ←½Q

Attempt This Online!
Ƥ←½Q
Ƥ          Non-deterministically choose a prime number
 ←         Decrement
  ½        Divide by 2
   Q       Check if result is a prime

By default, Nekomata prints all possible results.

CJam, 34 (2 * 22 - 10)
C9#{ImpI2*)mp&{Ip}&}fI

Prints all Sophie Germain primes under 12 ** 9, which includes 4294967681 > 2 ** 32.
I estimate that this will take roughly 8 hours on my machine. I'll run it tonight.

Python 3, 124 123 bytes
i=3
q=[2]
while 1:
 p=1
 for x in range(2,round(i**.5)+1):p=min(p,i%x)
 if p:
  q+=[i];s=(i-1)/2
  if s in q:print(s)
 i+=2

How does it work?
i=3                                 # Start at 3
q=[2]                               # Create list with first prime (2), to be list of primes.
while 1:                            # Loop forever
 p=1                                # Set p to 1 (true)
 for x in range(2,round(i**0.5)+1): # Loop from 2 to the number's square root. x is the loop value
     p=min(p,i%x)                   # Set p to the min of itself and the modulo of
                                    # the number being tested and loop value (x).
                                    # If p is 0 at the end, a modulo was 0, so it isn't prime.
 if p:                              # Check if p is 0
  q+=[i]                            # Add the current number (we know is prime) to list of primes (q)
  s=(i-1)/2                         # Generate s, the number that you would double and add 1 to make a prime.

  if s in q:print(s)                # If (i-1)/2 is a prime (in the list), then that prime satifies
                                    # the condition 2p+1 is prime because i is 2p+1, and i is prime
 i+=2                               # Increment by 2 (no even numbers are prime, except 2)

Try it online here.

My computer says it is has generated 0.023283 % of all the Sophie Germain primes below 2^32.
When it's finished, I'll post it on pastebin if there are enough lines. You can use it to check you've got them all.

.5 is shorter than 0.5

Haskell, 2*54-10 = 98 132
i a=all((>0).rem a)[2..a-1]
p=[n|n<-[2..],i n,i$2*n+1]

i is a prime check. p takes all numbers n where both n and 2*x+1 are prime. p is an infinite list.
Edit: better way for checking if 2*n+1 is prime.

Julia, 2*49 - 10 = 88
p=primes(2^33)
print(p[map(n->isprime(2n+1),p)])

Prints them in list format, [2,3,5,11,...]. If that format, using the primes function, or waiting until all the computation is done to print isn't acceptable, this prints them one per line as it runs.
isprime=f
for i=1:2^33;f(i)&&f(2i+1)&&println(i)end

It's a little longer, 52 chars. Both compute all the Sophie Germain primes up to 2^33, so they should get the 10 point discount.

Ruby, 61*2 - 10 = 112
require'prime';Prime.each(1.0/0)do|n|p Prime.prime?(n*2+1)end

It would take forever to print out all values up to 2**32
Edit
Shaved off a few bytes substituting Float::INFINITY for 1.0/0

Perl, 2*57-10 = 104
use ntheory":all";forprimes{say if is_prime(2*$_+1)}2**33

2
3
5
11
...
8589934091
8589934271

42 seconds to 2^32, 1m26s to 2^33.  Will run 50% faster if 2*$_+1 is written as 1+$_<<1 but that's one more byte.
The module also installs primes.pl which has lots of filters including one for Sophie-Germain primes.  So: primes.pl --so 2**33 (20 bytes)

PARI/GP, 46 * 2 - 10 = 82
forprime(p=2,2^33,if(isprime(2*p+1),print(p)))

Python 3, 2 * 64 bytes - 10 = 118
n=1
while 1:n+=1;all((n-~n)*n%k for k in range(2,n))>0!=print(n)

Try it online!
It turns out a normal prime test is shorter.

Python 3, 2 * 67 bytes - 10 = 124
P=k=1
d=[]
while 1:P*=k*k;k+=1;P%k*k//2in d!=print(k//2);d+=P%k*[k]

Try it online!
This uses Wilson's theorem to generate a list of primes. When k is prime and k//2 is prime as well (in d), this prints k//2.
This can be done a little more memory efficient by not collecting a list of primes but rather doing two prime tests at once at the cost of 4 bytes:
P=k=1
m=3;R=4
while 1:P*=k*k;k+=1;R*=m*m*-~m*-~m;m+=2;P%k*R%m>0!=print(k)

Try it online!

Stax, 14 bytes
ü♀σJàx╧☺▼∟╓X≥╣

Run and debug it

PowerShell Core, 85 bytes, score 170
2
for($i=2){if((&($p={param($a)+!(2..($a-1)|?{!($a%$_)})})(++$i))*(&$p(2*$i+1))){$i}}

Try it online!
A bit faster, but longer for 93 bytes
for($i=2){if((&($p={param($a)for($u=1;++$u-$a){$k+=!($a%$u)}+!$k})(++$i))*(&$p(2*$i+1))){$i}}

Jelly, 10 bytes => score 10
ȷ10ÆRḤ‘ẒƊƇ

Generates primes up to 10^10 > 2^32.
Try it online! (TIO link is to a shorter version that generates only up to 1000, so it doesn't time out)

Pyt, 11 bytes, score 12
9ᴇřᵽĐ2*⁺ṗ*ž

Try it online!
9ᴇřᵽ    generates the first 1,000,000,000 primes (there are 203,280,221 primes less than 2^32)
Đ2*⁺    calculates 2*p+1 for each prime
ṗ       is each 2*p+1 prime
*       multiply the two lists one element at a time
ž       remove all zeroes from list; implicit print

Thunno, \$ 20 \log_{256}(96) \approx \$ 16.46 bytes, score \$ \approx \$ 22.92
[xNx2*1+N&?xZK((x1+X

Explanation
[                     # while True:
 xN                   #  x is prime?
   x2*1+N             #  x*2+1 is prime?
         &?           #  if both are true:
           xZK        #   print x
              ((      #  endif
                x1+X  #  x=x+1

Screenshot

Stax, 10 bytes, score 10
2*10=20 score, -10 because it prints infinitely.
▓i☼=ö│╪¥♠p

Run and debug it
This is a PackedStax program, which unpacks to the following:
VIfc|psH^|pI

Run and debug it
Explanation
  f         # filter from 1 to...
VI          # infinity by..
   |p       # is prime
          I # and
  c  sH^    # 2*p+1
        |p  # is prime

Ruby -rprime, 34 bytes, score 58
Prints infinitely and should be able to exceed 2**32 due to native support for large numbers, although I haven't bothered to actually wait around to check.
Prime.each{p _1 if(2*_1+1).prime?}

Attempt This Online! (with a timeout)

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


text:
Scientist Seals Stranded upon an Iceberg
Introduction
A family of seals are stranded upon an iceberg in the Arctic Circle. There is a radio transmitter located on the iceberg which the seals can use to call for help. However, only the daddy seal knows how to operate the radio transmitter. And worse, the ice is very slippery this time of year, so the seals will slide uncontrollably until they hit another seal or slide off the edge of the iceberg, making it very difficult for the daddy seal to reach the radio transmitter. Luckily, one of the seals is a computer scientist, so she decides to write a program to figure out how to manoeuvre the daddy seal to the radio transmitter. As there is not much space on the ice to write a program, she decides to make the program use as little bytes as possible.
Input Description
The seal's program will take input in from STDIN, command line arguments, or user input functions (such as raw_input()). It cannot be preinitialised in a variable (e.g. "This program expects the input in a variable x").
The first line of the input consists of two comma separated integers in the form
A,B

Following that is B lines consisting of A characters each. Each line can only contain characters out of the following:

.: The cold, cold, ocean. The map will always have this as a border.
#: A part of the iceberg.
a...z: A seal that is not the daddy seal on the iceberg.
D: The daddy seal on the iceberg.
*: The radio transmitter.

(Note that the daddy seal is always notated with an uppercase D. A lowercase d is simply a regular seal.)
Output Description
According to the following rules regarding how the seals can move, output a list of instructions for the seals on how they should move to get the daddy seal to the radio transmitter.

Rule: All seals can move up (U), down (D), left (L), and right (R). They cannot slide diagonally.
Rule: Upon moving, a seal will continue to move in the same direction until it collides with another seal or falls into the sea.

If a seal collides with another seal, it will stop moving. The seal it collided with will not move.
If a seal falls into the sea, it will drown and disappear from the map. That is, it does not act as a collider for other seals and it cannot be moved again.

Rule: Two seals cannot move at the same time, neither can a seal be moved while another one is still moving. The next seal can only be moved once the previous seal has stopped moving.
Rule: There is no restriction regarding moving a seal multiple times, or the number of seals that drown.
Rule: A correct solution will have the daddy seal end at the radio transmitter. The daddy seal cannot simply pass the transmitter while sliding.

The output will consist of several lines, each in the form
A,B

Where A is the seal to move (D for the daddy seal, a...z for others), and B is the direction to move the seal (either U, D, L, or R). Note that you do not need to find the shortest route. Any route that gets the daddy seal to the goal is an acceptable output.
Example Inputs and Outputs
Input:
25,5
.........................
.#######################.
.####D#############*k###.
.#######################.
.........................

Output:
D,R

Input:
9,7
.........
.a#####b.
.#####d#.
.##l*###.
.###m#p#.
.#D#.#c#.
.........

Output (one possible output out of many):
m,R
b,L
D,U
D,R
D,D
D,L

Input:
26,5
..........................
.###..................###.
.l*##########v#########D#.
.###..................###.
..........................

Output (one possible output out of many):
v,D
D,L

If you have any other questions, please ask in the comments.

Will all inputs have a valid solution? If not, what is expected output/behavior?

@Geobits All inputs will have a valid solution. Inputs without solutions are considered invalid and your program can do whatever with them.

Is it permissible to end the program by throwing an exception?

@Dlosc It can throw an exception on invalid inputs. For valid inputs, as long as it outputs a solution before throwing the exception it's fine.

What happens if a non-daddy seal hits the radio transmitter? Will it stop, or move through it?

I remember pokemon has this kind of puzzle, awesome

For a javascript answer, a function with a multi line string parameter could go? Like F("9,7\n.........\n.a#####b.\n.#####d#.\n.##l*###.\n.###m#p#.\n.#D#.#c#.\n.........")

@RetoKoradi All seals will move through the radio transmitter.

This means that the baby seals can also stop on the transmitter? Say if you have part of a row a###*b, and you make the move a,R. If the transmitter does not stop a, but b does, this now becomes ####ab. The consequence is that if you only have the text representation of the configuration, the transmitter is now invisible, since it's covered by a. So you pretty much have to find the transmitter position in the initial configuration, and separately remember what it is.

@RetoKoradi Correct.

That invalidates my solution. :(

Test case with baby seal sliding over transmitter: 8,5 ........ .##c###. .a#*#D#. .##b###. ........

Except for the part about falling into the ocean, you've reinvented the board game Ricochet Robots.

Python 3, 520 bytes
R=range
g=[list(input())for i in R(int(input().split(',')[1]))]
f=set(sum(g,[]))-set(".#*")
L=8
def P(p,g):
 if len(p)>L:return
 for s in f:
  c=sum(y.index(s)for y in g if s in y)
  if c<1:continue
  r,=[n for n in R(len(g))if s in g[n]]
  for d in R(4):
   m=p+s+",%s\n"%"LURD"[d];G=[y[:]for y in g];o="#";i,j=I,J=r,c
   while"#"==o:G[i][j]="#";G[I][J]=s;i,j=I,J;I,J=i+d%2*(d-2),j+(~d%-2&d-1);o=G[I][J]
   if"."==o:G[i][j]="#"
   if"D"==s:
    if"."==o:continue
    if"*"==o:print(m);1/0
   P(m,G)
while 1:P("",g);L+=4

I may do a more detailed explanation later if people want, but basically this runs a depth-first search with iterative deepening on the state space of possible moves. If a move causes the daddy seal to fall off, it is immediately rejected. If the daddy ends up next to the transmitter, the sequence of moves is printed, and the program divides by zero to force an exit.
I can make the code run significantly faster by adding if G!=g: at the beginning of the second-last line, for 8 extra bytes--this rejects moves that don't change anything, such as k,L in the first test case.
The runtime varies noticeably from one run to the next, even with the same input--evidently a result of the fact that I pick the next seal to move by iterating over a set, which is an unordered type. I timed the second test case at 5 minutes 30 seconds, though it didn't seem that long the first time I ran it. With the optimization mentioned above, it's more like 40 seconds.

Interestingly in Python 2 it should give the same order each time. I think they changed Python 3 to give randomized hashes on each run for the same objects to avoid certain exploits: "Hash randomization is enabled by default. Set the PYTHONHASHSEED environment variable to 0 to disable hash randomization. See also the object.hash() method."

JavaScript (ES6) 322 334 323
Edit2 Added animation in the snippet
Edit Bug fix, remember initial posiiton of '*', so I find it even when a seal slide over it and erase it.
Implemented as a function with the input string as parameter (probably invalid but waiting for a clarification). Output via popup.
The problem with multiline string input in JavaScript is that prompt does not manage it well.
As for the algorithm: a BFS, should find an optimal solution.
I keep a queue of game status in variable l, the status beeing the character grid g and the sequence of moves so far s. Besides, there is a set of grids obtained so far in variable k, to avoid exploring the same grid again and again.
The main loop is

dequeue a game status
try all possibile moves, enqueue the status after each valid move (IIF the resulting grid is not already present)
if solution found then exit the loop

F=s=>{
  o=~s.match(/\d+/),g=[...z=s.replace(/.*/,'')];
  for(l=[[g,'']],k=[];[g,s]=l.shift(),!g.some((c,p)=>
      c>'A'&&[-1,1,o,-o].some((d,j)=>{
        t=s+' '+[c,'LRUD'[j]];
        for(q=p;(u=g[q+d])<'.';)q+=d;
        return(c<'a'&z[q]=='*')||
        c>'D'|u>'.'&&!(
          f=[...g],u=='.'?0:f[q]=c,f[p]='#',
          k[h=f.map(v=>v>'D'?0:v)]||(k[h]=l.push([f,t]))
        )
      })
    ););
  alert(t)
}

Run Snippet to test in FireFox

F=s=>{
  o=~s.match(/\d+/),g=[...z=s.replace(/.*/,'')];
  for(l=[[g,k=[]]];[g,s]=l.shift(),!g.some((c,p)=>
      c>'A'&&[-1,1,o,-o].some((d,j)=>{
        t=s+' '+[c,'LRUD'[j]];
        for(q=p;(u=g[q+d])<'.';)q+=d;
        return(c<'a'&z[q]=='*')||
        c>'D'|u>'.'&&!(
          f=[...g],u=='.'?0:f[q]=c,f[p]='#',
          k[h=f.map(v=>v>'D'?0:v)]||(k[h]=l.push([f,t]))
        )
      })
    ););
  return t
}

$('.T td').each(function(i,td) { $('.R td').eq(i).text(F($(td).text())) });

$(".R").on('click','td',function(){
  var i = $(this).index();
  var $td = $('.T td').eq(i);
  var t = $td.text().trim();
  animate($td, $td.text().trim(), $('.R td').eq(i).text().trim());
});

$('#GO').on('click',function() {
  var s = T0.value, h=F(s)
  console.log(s)
  $('#R0').text(h);
  animate($('#A'), s,h);
});

function animate($out, s, h){
  o=~s.match(/\d+/),g=[...s.replace(/.*/,'')];

  fr=[g.join('')];
  h.replace(/.,(.)/g, (c,d)=>{
    i = g.indexOf(c=c[0]);
    d = [-1,1,o,-o]['LRUD'.search(d)]
    for(;g[i+d]<'.';i+=d)
    {
      g[i]='#',z=[...g],g[i+d]=c,z[i+d]=''+c+'', fr.push(z.join(''))
    }
    if(g[i+d]=='.')
    {
      g[i]='#', fr.push(g.join(''))
    }
  })

  var fa = ()=>{
    var f=fr.shift();
    f ? $out.html(f) : (
      clearInterval(i),
      $out.text(s),
      $out.toggleClass('Anim')
  )};
  $out.toggleClass('Anim');
  fa();
  var i=setInterval(fa, 500);
}
td { vertical-align: top; font-family: monospace; white-space: pre; }
textarea { width: 99%;  height:10em;}
pre { margin: 0; }
.R td { background: #fdc; padding: 6px 0; }
.R td:hover { background: #ffc }
.T td { background: #ddf}
B { color: red }
.T td.Anim, td.Anim { background: #ffc; }

    Predefined tests

    25,5
.........................
.#######################.
.####D#############*k###.
.#######################.
.........................
    9,7
.........
.a#####b.
.#####d#.
.##l*###.
.###m#p#.
.#D#.#c#.
.........
26,5
..........................
.###..................###.
.l*##########v#########D#.
.###..................###.
..........................
8,5
........
.##c###.
.a#*#D#.
.##b###.
........

Click on solution text to start animation

Your test

<textarea id=T0></textarea>

    Find solution and animate <button id=GO>go</button>

C++, 628 bytes
Well, this didn't turn out very short:
#include <set>
#include <iostream>
using namespace std;struct R{string b,m;bool operator<(R r)const{return b<r.b;}};int w,h,t,j,k,z=1;char c,f;set<R> p,q;int m(R r,int x,int d,char a){for(j=x,c=r.b[x];(f=r.b[j+=d])==35;);if(c-68||f-46){r.b[x]=35;if(f-46)r.b[j-d]=c;r.m+=c;r.m+=44;r.m+=a;r.m+=10;if(c==68&j-d==t){cout<<r.m;z=0;}if(p.count(r)+q.count(r)==0){q.insert(r);}}}int main(){cin>>w>>c>>h>>c;R r;string l;for(;k++<h;){getline(cin,l);r.b+=l;}t=r.b.find(42);r.b[t]=35;q.insert(r);for(;z;){r=*q.begin();q.erase(q.begin());p.insert(r);for(k=0;z&&k<w*h;++k){if(r.b[k]>64){m(r,k,-1,76);m(r,k,1,82);m(r,k,-w,85);m(r,k,w,68);}}}}

I chose C++ because I wanted to use the data structures (set, string), but it's inherently quite verbose. The solution does reasonably well on performance, solving test 2 in a little over 2 seconds on a MacBook Pro, even though it's not optimized for runtime.
Code before starting to eliminate whitespace and some other length reduction:
#include <set>
#include <iostream>

using namespace std;

struct R {
    string b, m;
    bool operator<(R r) const {return b < r.b; }
};

int w, h, t;
set<R> p, q;
bool z = true;

void m(R r, int k, int d, char a) {
    int j = k;
    char s = r.b[k], f;
    for (; (f = r.b[j += d]) == 35;);
    if (s - 68 || f - 46) {
        r.b[k] = 35;
        if (f - 46) {
            r.b[j - d] = s;
        }
        r.m += s;
        r.m += 44;
        r.m += a;
        r.m += 10;
        if (s == 68 && j - d == t) {
            cout << r.m;
            z = false;
        }
        if (p.count(r) + q.count(r) == 0) {
            q.insert(r);
        }
    }
}

int main() {
    char c;
    cin >> w >> c >> h >> c;
    string b, l;
    int k;
    for (k = 0; k < h; ++k) {
        getline(cin, l);
        b += l;
    }

    t = b.find(42);
    b[t] = 35;

    R r;
    r.b = b;
    q.insert(r);

    for ( ; z; ) {
        r = *q.begin();
        q.erase(q.begin());
        p.insert(r);

        for (k = 0; z && k < w * h; ++k) {
            c = r.b[k];
            if (c > 64) {
                m(r, k, -1, 76);
                m(r, k, 1, 82);
                m(r, k, -w, 85);
                m(r, k, w, 68);
            }
        }
    }

    return 0;
}

The core idea behind the algorithm is that two sets are maintained:

q is the set of configurations that are pending processing.
p is the set of configurations that have been processed.

The algorithm starts with the initial configuration in q. In every step, a configuration is popped from q, added to p, all possible seal movements are generated, and the resulting new configurations inserted into q.
Test run:
bash-3.2$ ./a.out <test1
D,R
bash-3.2$ time ./a.out <test2
p,U
c,U
p,R
c,L
m,L
b,L
a,L
D,U
b,L
D,R
D,D
D,L

real    0m2.267s
user    0m2.262s
sys 0m0.003s
bash-3.2$ ./a.out <test3
v,U
D,L
bash-3.2$

Using a queue instead of set for 'q', you can find shorter solutions in less time (my solution for test 2 is 6 steps).

@edc65 Yes, I was initially surprised at the number of moves there. I did walk through it to confirm that it's a valid solution. Using a FIFO for q would certainly be better in that sense. The reason I used a set was that I wanted to avoid entering the same entry multiple times. But I started having second thoughts once I saw the outcome.

Performance wise, you should use a queue AND a set to avoid repetitions. But put in the set a modified version of the grid, as each baby seal is interchangeable.