text:
Implement multiplication by a constant with addition and bit shifts
While looking at the ARM instruction set, you notice that the ADD instruction has the so-called "Flexible second operand", which can be abused for quick multiplication. For example, the following instruction multiplies register r1 by 17 (shifting it left by 4 bits and adding to itself):
ADD r1, r1, r1, LSL #4
; LSL means "logical shift left"

The subtraction instruction has that feature too. So multiplication by 15 is also easy to implement:
RSB r1, r1, r1, LSL #4
; RSB means "reverse subtract", i.e. subtract r1 from (r1 << 4)

So this is an excellent optimization opportunity! Certainly, when you write in a C program x *= 15, the compiler will translate that to some inefficient code, while you could replace it by x = (x << 4) - x, and then the compiler will generate better code!
Quickly, you come up with the following cunning plan:

Write a program or a subroutine, in any language, that receives one parameter m, and outputs a C optimizing macro, like the following (for m = 15):
#define XYZZY15(x) (((x) << 4) - (x))

or (which is the same)
#define XYZZY15(x) (-(x) + ((x) << 4))

???
Profit!

Notes:

The macro's name is essential: magic requires it.
Parentheses around x and the whole expression are required: ancient C arcana cannot be taken lightly.
You can assume m is between 2 and 65535.
The input and output can be passed through function parameters, stdin/stdout or in any other customary way.
In C, addition and subtraction have tighter precedence than bit shift <<; use parentheses to clarify order of calculations. More parentheses than necessary is OK.
It is absolutely vital that the C expression be optimal, so e.g. x+x+x is not acceptable, because (x<<1)+x is better.
Expressions x + x and x << 1 are equivalent, because both require one ARM instruction to calculate. Also, (x << 1) + (x << 2) (multiplication by 6) requires two instructions, and cannot be improved.
You are amazed to discover that the compiler detects that (x << 0) is the same as x, so x + (x << 0) is an acceptable expression. However, there is no chance the compiler does any other optimizations on your expression.
Even though multiplication by 17 can be implemented in one instruction, multiplication by 17*17 cannot be implemented in two instructions, because there is no C expression to reflect that:
#define XYZZY289(x) x + (x << 4) + (x + (x << 4) << 4) // 3 operations; optimal

In other words, the compiler doesn't do common sub-expression elimination. Maybe you will fix that bug in version 2...

This is code-golf: the shortest code wins (but it must be correct, i.e. produce correct and optimal expressions for all m)
Please also give example outputs for m = 2, 10, 100, 14043 and 65535 (there is no requirement on the length of the expression - it can contain extra parentheses, whitespace and shift left by 0 bits, if that makes your code simpler).

For some 2 <= m <= 65535, there will be a worst case value where the number of bitshifts is a maximum.  Is it guaranteed that even for this worst case that it will be more efficient to do this many shifts instead of one multiplication?

Define “optimal.” I count two operations in both x+x+x and (x<<1)+x.

@FUZxxl: ARM can do as a single instruction x+(y<<k), x-(y<<k), and (y<<k)-x (for registers x,y and any constant k).  So there is only one operation in your second example.

It's not currently clear to me whether output which uses sub-macros is required or not. Please add a worked example for something like m = 24 where that would make a difference.

Does the compiler do common subexpression elimination?  If I have ((x<<8)+1)+(((x<<8)+1)<<5), is that 3 ops, or 2?

@PeterTaylor, I think 24 is just (x+(x<<1))<<3

@KeithRandall, that's not a multiplication. Did you mean ((x<<8)+x)+(((x<<8)+x)<<5)? That can be done in 2 steps ADD r1, r1, r1, LSL #8 and ADD r1, r1, r1, LSL #5

@DigitalTrauma This is just a code-golf challenge; the explanation on performance optimization is just for fun. Compilers do this type of optimization since long ago (but don't tell anyone - it's secret!). Suppose the text starts like You tear a leaf from the calendar - today is 8.9.89...

@PeterTaylor Sub-macros are not required and not allowed. I added an example for 289.

@gnibbler, yes, my example should have been 27. Essentially it's the same question as Keith's.

I don't think it's right to not optimise 17*17 etc. Why can't you write it in C as x = (x << 4) + x; x = (x << 4) + x

Can you provide a sample for m = 11?  As I understand the question, there is no possible XYZZY11 macro. I assume I'm missing something.

@gnibbler I guess your suggestion will require some sort of BFS. The rules as stated allow both BFS and bit-fiddling - more flexibility in algorithm choice is better. I agree that utilizing common sub-expressions is "more optimized", but let's leave that for version 2.0 (if at all).

@MattNoonan #define XYZZY11(x) x + (x<<1) + (x<<3) or #define XYZZY11(x) -x + (x<<2) + (x<<3) or #define XYZZY11(x) -x + ((x + (x<<1)) << 2) (but one should add the required additional parentheses)

@anatolyg Ah, so we can write expressions which would utilize more than one register? Great!

Python - 414 393 331
This is my entry, which finds the least possible addition/subtraction operations, and subsequently evaluates to a C expression. Not sure it is optimal as multiplication of subexpressions may offer less operations.
import itertools as l
def w(N,s=''):
 for k,v in enumerate(min([t for t in l.product((1,0,-1),repeat=len(bin(N))-1)if sum([v*2**k for k,v in enumerate(t)])==N],key=lambda t:sum(abs(k)for k in t))):
  if v!=0:s+='{:+d}'.format(v)[0];s+='((x)<<{})'.format(k)if k>0 else'(x)'
 return '#define XYZZY{}(x) ({})'.format(N,s.lstrip('+'))

For the cases 2, 10, 100, 14043, 65535:
#define XYZZY2 (((x)<<1))
#define XYZZY10 (((x)<<1)+((x)<<3))
#define XYZZY100 (((x)<<2)+((x)<<5)+((x)<<6))
#define XYZZY14043 (-(x)-((x)<<2)-((x)<<5)-((x)<<8)-((x)<<11)+((x)<<14))
#define XYZZY65535(x) (-(x)+((x)<<16))

The final 65535 took around 11 minutes to compute. Suggestions for improvement (also speedwise) are welcome :-). Thanks to mbomb007 and plg for golfing improvements.

Change your 2nd line to this: a=lambda t:sum(abs(k)for k in t) to save some bytes. Omit any spaces you can, such as every space before an IF, except where the previous non-whitespace character is a letter. e.g. '+' if -> '+'if and you can do s[0] != '+' else -> s[0]!='+'else

This IS code-golf after all.

The return can be written: return '#define XYZZY{}(x) ({})'.format(N,s.lstrip('+')). And abs(v) > 0 is equivalent to v != 0. Calling sorted on g's current definition can also save a char (also you should make g a generator -- replace the angle brackets with parentheses). Also you can define e=enumerate, and inline a into sorted.

Also you can apply what @mbomb007 said to [...]0 else: [...]0else is fine.

r is unused. L and g can be inlined. Your now inlined g can be written in terms of min instead of sorted()[0]. As r is gone,  s=''\n can be added as a param: def w(N,s=''):. After all these changes I'm down to 342, and I'm sure there are other things to do.

@plg 0else only works with Python 3.

Python 508
Slightly more characters than my other answer, but this code runs in roughly one second for all cases 2, 10, 100, 14043, 65535.
def l(n,k=0,o=0):
 while 1:
  if k==0:
   for j in range(1,n):
    yield(j,);yield(-j,)
   k+=1
  else:
   for j in range(1,n):
    for u in l(j,k-1,1):
     yield(j,)+u;yield(-j,)+u
   k+=1
  if o:break
r=lambda t:sum((1,-1)[k<0]*2**(abs(k)-1)for k in t)
def w(N,s=''):
 g = loop(len(bin(N)))
 while 1:
  a = g.next()
  if r(a)==N:
   for k in a:
    s+='{:+d}'.format(k)[0];s+='((x)<<{})'.format(abs(k-1)) if abs(k)>1 else'(x)'
   return '#define XYZZY{}(x) ({})'.format(N,s.lstrip('+'))""")


text:
ASCII topology pt 1: Can I count on you?
I have a serious problem. I have some text files where I keep my very important numbers -- all of the important ones! And twos, and threes..
These numbers were so important that I couldn't entrust them to those newfangled decimal or binary number systems. I kept each number encoded in unary, as so:
            +--+
            |  |
+---+  +----+  |
|   |  |       |
+---+  +-------+
   ~/two.txt

Simple and reliable: two ASCII loops for the number 2. Unfortunately, these things tend to get tangled up over time and now I have a hard time figuring out how many loops are in each file. Here are some examples that I worked out by hand:
One:
   +---+
   |   |
+--+   |
|      |
+--+   |
   |   |
   |   |
   |   |
+--+   +--+
|         |
+---------+

Three:
+---------+
| +-----+ |
| | +-+ | |
| | | | | |
| | +-+ | |
| +-----+ |
+---------+

Four:
  +--------------+
  |  +--+  +--+  |
  |  |  |  |  |  |
+-|-----|-----|----+
| |  |  |  |  |  | |
| +--+  +--+  +--+ |
+------------------+

              +------------+
              |            |
        +-----+  +-----+   |
        |        |     |   |
  +-----|-----------+  |   |
  |     |  +--+  |  |  |   |
  +-+   +--|--|--+  +---------+
    |      |  +-+      |   |  |
    +------+    |      |   |  |
                +-------+  |  |
                       ||  |  |
                       |+-----+
                       |   |
                       +---+

Five:
+--------+  +--------+  +--------+
|        |  |        |  |        |
|     +--|-----+  +--|-----+     |
|     |  |  |  |  |  |  |  |     |
+-----|--+  +-----|--+  +--------+
      |        |  |        |
      +--------+  +--------+

Can you help me count my loops?
Here are the rules:

Since I store everything in ASCII-encoded unary, space efficiency is very important to me. Therefore, this is code golf. The smallest program in bytes wins.
Loops are drawn with the characters +, -, |. Every corner in the loop is drawn unambiguously: exactly one of the characters above and below the +
will be |, and exactly one to the right or left will be -.  Two + marks
are never adjacent.
Strands may pass over and under each other. When strands cross, you'll be able to see the "under" strand immediately on both sides of the "over" strand.
Your program should take a string representation of the loop (either from stdin or as a function parameter) and produce a number (either to stdout or as a return value).
Line lengths may not be uniform in the loop drawing and there may be trailing spaces on each line.
You may assume that there is at least one loop in the input.

I'm counting on you!

Can one of the sides of an 'under strand' be a +?

@feersum: No, the two edges attached to the + will always be visible.

@Martin: I'm afraid not. My storage space is really at a premium, so I can't spare all those extra spaces.

I think you should add this (pastebin) as a test case unless I'm missing something and it's not valid input. There are 6 loops; I only tested it online with the SnakeEx solution and it outputs 12.

Each corner has got a | and -. Or does that mean, out of the 4 adjacent characters, 2 need to be - and |, and the other 2 spaces? Wouldn't that invalidate the current example for four?

Colored version of the loops as it might be hard to see: http://imgur.com/sf87vsn

Perhaps you should explicitly forbid or allow loops that cross themselves (eg http://pastebin.com/5RLZuULG) Currently, they are detected by the ruby solution, but not by the SnakeEx solution.

@blutorange Yes, self crossings absolutely are allowed. I can't believe I forgot to add an example like that! Your colored example is also valid.

Possible sequel of knot or not?

SnakeEx - 98 bytes with Javascript, 44 without
This looked like a good problem to try my language from the Fortnightly Challenge on:
m:({e<>PE}\-[|\-]*<T>\+|[|\-]*<T>)+`\+
e:\+

The best place to try this out is my online interpreter.
SnakeEx matches patterns in text by using "snakes" that move around the text matching regexes. The code reads kind of like a regex, except:

The <T> instruction. That is a direction command that branches the snake left and right from its current direction.
{e<>PE} is like a subroutine call. It that spawns a snake with definition e moving forward (<>) and with parameters P (piggyback - the spawning snake follows the new snake) and E (exclusive - don't match anything that's already been matched). This exclusive check is the only thing that stops the snake from looping infinitely.
The prefix ` at the end indicates that what follows should be matched only if it has already been matched, which we can use to force the loop to close.

Because SnakeEx is like regex and doesn't technically output the results as desired by itself, I guess we need to wrap it in some Javascript calling the interpreter:
function e(s){return snakeEx.run('m:({e<>PE}\\-[|\\-]*<T>\\+|[|\\-]*<T>)+`\\+\ne:\\+',s,1).length}

Edit: fixed it up to work with blutorange's additional test cases

+1 I really like this, perhaps because I can try it online and get the loops highlighted. But you might want to check these two test cases: 1, 2

@blutorange Good catch. I added a slightly hacky fix for self-crossing loops.  I'll have to think about test case 1 a bit more, though.

That's the easy one to fix, just replace [^ ] with [|\-] ;)

Hah, it took me a long time to figure out why that was the case. Good call.

This is awesome!

C# - 338 388 433 bytes
Saved a bunch of bytes by changing to a 1-dimensional array.
using C=System.Console;using System.Linq;class P{static void Main(){var D=C.In.ReadToEnd().Split('\n');int z,w=D.Max(m=>m.Length)+1,d,c=0;var E=D.SelectMany(l=>l.PadRight(w)).ToList();for(z=E.Count;z-->1;)if(E[z-1]==43)for(d=1,c++;E[z+=d%2<1?w*d-w:d-2]>32;)if(E[z]<44){E[z]=' ';d=d%2>0?z<w||E[z-w]<99?2:0:E[z+1]!=45?1:3;}C.WriteLine(c);}}

First it reads in the input, and makes it nice and rectangular, with a " " border so we don't have to do any bounds checking on the horizontal (cheaper to do the checking on the vertical than to put in the extra line). Then it looks back through the rectangle, so it always hits a right-bottom corner. When it hits one of these, it directs itself up, following any +s it meets, and clearing them as it goes (with a space). It stops following when it meets a space. Tested on the five given examples.
using C=System.Console;
using System.Linq;

class P
{
    static void Main()
    {
        // read in
        var D=C.In.ReadToEnd().Split('\n');

        int z, // z is position in E
        w=D.Max(m=>m.Length)+1, // w is width
        d, // d is direction of travel (1 == horizontal?, 2 == down/right?)
        c=0; // c is loop count

        // make all the lines the same length
        var E=D.SelectMany(l=>l.PadRight(w)).ToList(); // say no to horizontal bounds checking

        // consume +s
        for(z=E.Count;z-->1;)
            if(E[z-1]==43) // right-most lower-most +
                for(d=1,c++; // go left, increment counter
                    E[z+=d%2<1?w*d-w:d-2]>32 // move z, then check we havn't hit a space (when we do, z is basiclly z - 1)
                    ;)
                    if(E[z]<44) // +
                    {
                        E[z]=' '; // toodles

                        d=
                            d%2>0? // currently horizontal, must go vertical
                                z<w||E[z-w]<99?2 // can't go up, must go down
                                :0 // can go up, go up
                            : // currently vertical, must go horizontal
                                E[z+1]!=45?1 // can't go right, must go left
                                :3 // can go right, go right
                            ;
                    }

        // output result
        C.WriteLine(c);
    }
}

Wow. That's impressive :o

Slip, 51 41 + 2 = 43 bytes
$a(`+`-[^ +]*`+(<|>)`|[^ +]*`+#(<|>))+?$A

(Now updated to work with @blutorange's test case at a major cost)
Since @BMac used SnakeEx for this challenge, I thought I'd try and use my 2D pattern-matching language submission, Slip. But because Slip didn't have the features necessary to solve this problem, I've been adding them in over the past few days. In other words, this submission is not eligible to win.
Run with the n flag for number of matches, e.g.
py -3 slip.py regex.txt input.txt n

Try it online.

Explanation
Due to the plethora of new features in this submission, this is a good opportunity to showcase them.
$a                Set custom anchor at current position
(
  `+`-            Match '+-'
  [^ +]*          Match any number of '|' or '-'
  `+              Match a '+'
  (<|>)           Either turn left or turn right
  `|              Match a '|'
  [^ +]*          Match any number of '|' or '-'
  `+              Match a '+'
  #               Prevent next match from moving the match pointer (doubling up on '+')
  (<|>)           Either turn left or turn right
)
+?                Do the above at least once, matching lazily
$A                Make sure we're back where we started

Slip tries to match starting from every position, and only returns unique matches. Note that we use [^ +] — while using [-|] would theoretically save two bytes, unescaped - at the beginning/end of character classes is not yet implemented in Slip.

@blutorange three also has +s which aren't one -, one | and 2 spaces, so I'm assuming it's not a mistake

Ruby 295
F=->i{l=i.lines
g={}
l.size.times{|y|i.size.times{|x|l[y][x]==?+&&g[[y,x]]=[[y,x]]}}
c=->a,b{w=g[b]+g[a];w.map{|x|g[x]=w}}
k=g.keys
k.product(k).map{|n,o|
r,p=n
s,q=o
((r==s&&p<q&&l[r][p...q]=~/^\+-[|-]*$/)||(p==q&&r<s&&l[r...s].map{|l|l[p]||c}.join=~/^\+\|[|-]*$/))&&c[n,o]}
g.values.uniq.size}

Try it online: http://ideone.com/kIKELi (I added a #to_a call on the first line, because ideone.com uses Ruby 1.9.3, which does not support #size for Enumerables. In Ruby 2.1.5+ the code runs OK.)
The approach is the following:

make a list of all the + signs in the input and consider each of them a distinct shape
find horizontal and vertical lines that link two + signs and combine their shapes into one
in the end, the number of distinct shapes matches the result

Here's a more readable version:
def ascii_topology_count(input)
  lines = input.lines
  max_length = lines.map(&:size).max

  # hash in which the keys are corners ("+"s), represented by their [y, x] coords
  # and the values are arrays of corners, representing all corners in that group
  corner_groups = {}

  lines.size.times { |y|
    max_length.times { |x|
      if lines[y][x] == ?+
        corner_groups[[y, x]] = [[y, x]]
      end
    }
  }

  # function that combines the groups of two different corners
  # into only one group
  combine_groups =-> c1, c2 {
    g1 = corner_groups[c1]
    g2 = corner_groups[c2]

    g2 += g1
    corner_groups[c1] = g2
    g2.map{|x| corner_groups[x] = g2}
  }

  corner_groups.keys.product(corner_groups.keys).map{|c1, c2|
    y1,x1=c1
    y2,x2=c2
    if y1 == y2 && x1 < x2
      # test horizontal edge
      t = lines[y1][x1...x2]
      if t =~ /^\+-[|-]*$/
        # p "#{c1}, #{c2}, [H] #{t}"
        combine_groups[c1, c2]

      end
    end

    if x1 == x2 && y1 < y2
      # test vertical edge
      t=lines[y1...y2].map{|l|l[x1]||' '}.join

      if t =~ /^\+\|[|-]*$/
        # p "#{c1}, #{c2}, [V] #{t}"
        combine_groups[c1, c2]
      end
    end
  }

  corner_groups.values.uniq.count
end

JavaScript (ES6) 190 197 202 215 235 289 570
Edit Single dimension array instead of 2 dimension, max row size 999 chars (but can be more at no cost, e.g. 1e5 instead of 999)
Edit Added animated code snippet, see below
F=s=>[...s.replace(/.+/g,r=>r+Array(e-r.length),e=999)]
  .map((c,x,z,d=1,f='-',g='|')=>{
    if(c=='+')
      for(++n;z[x+=d]!='+'||([f,g,e,d]=[g,f,d,z[x-e]==g?-e:z[x+e]==g&&e],d);)
        z[x]=z[x]==g&&g
  },n=0)|n

Ungolfed first try
f=s=>
{
  cnt=0
  s = (1+s+1).split(/[1\n]/)

  for(;x=-1, y=s.findIndex(r=>~(x=r.indexOf('+-'))), x>=0;++cnt)
  {
    //console.log(y+' '+x+' '+s.join('\n'))
    dx = 1
    for(;dx;)
    {
      a=s[y-1],b=s[y+1],
      r=[...s[y]]
      for(r[x]=' ';(c=r[x+=dx])!='+';)
      {
        if (c=='-')
          if((a[x]||b[x])=='|')r[x]='|';
          else r[x]=' ';
      }

      if(a[x]=='|')dy=-1;
      else if(b[x]=='|')dy=1;
      else dy=0
      r[x]=' '
      s[y]=r.join('')
      if (dy) {
        for(;y+=dy,r=[...s[y]],(c=r[x])!='+'&c!=' ';)
        {
          if (c=='|')
            if((r[x-1]||r[x+1])=='-')r[x]='-';
            else r[x]=' ';
          s[y]=r.join('')
        }
        if(r[x-1]=='-')dx=-1;
        else if(r[x+1]=='-')dx=1;
        else dx=0;
      }
    }
  }
  return cnt
}

Animated snippet

F=s=>[...s.replace(/.+/g,r=>r+Array(e-r.length),e=999)].map((c,x,z,d=1,f='-',g='|')=>{if(c=='+')for(++n;z[x+=d]!='+'||([f,g,e,d]=[g,f,d,z[x-e]==g?-e:z[x+e]==g&&e],d);)z[x]=z[x]==g&&g,steps.push(z.map(c=>c?c!=','?c:'':0).join(''))},n=0)|n

function go(){var g=grid.value;steps=[];Num.value=F(g);a=_=>{g=steps.shift();if(g){grid.value=g;setTimeout(a, 100)}};a()}
textarea { width: 500px;  height: 500px; }
input {width: 80px}
Better viewed full page
Input (paste input text - enlarge if needed)<button onclick="go()">Process</button>Loop count:<input readonly id=Num />
<textarea id=grid></textarea>

Test In Firefox/FireBug console

F('\
  +--------------+\n\
  |  +--+  +--+  |\n\
  |  |  |  |  |  |\n\
+-|-----|-----|----+\n\
| |  |  |  |  |  | |\n\
| +--+  +--+  +--+ |\n\
+------------------+\n\
\n\
              +------------+\n\
              |            |\n\
        +-----+  +-----+   |\n\
        |        |     |   |\n\
  +-----|-----------+  |   |\n\
  |     |  +--+  |  |  |   |\n\
  +-+   +--|--|--+  +---------+\n\
    |      |  +-+      |   |  |\n\
    +------+    |      |   |  |\n\
                +-------+  |  |\n\
                       ||  |  |\n\
                       |+-----+\n\
                       |   |\n\
                       +---+')

4

F('\
+--------+  +--------+  +--------+\n\
|        |  |        |  |        |\n\
|     +--|-----+  +--|-----+     |\n\
|     |  |  |  |  |  |  |  |     |\n\
+-----|--+  +-----|--+  +--------+\n\
      |        |  |        |\n\
      +--------+  +--------+')

5

Surely you'd save some bytes by single-lining the golfed version? You can also just create an anonymous function (I think that's within the rules of codegolf)

@theonlygusti the golfed version is counted as single-line (no newlines and indentation spaces are counted).With an anonymous function I save 2 bytes, negligible saving ...

Ruby, 178 187 199 212
Better ruby version, creates a function F. Now with more delicious interpreter warnings constantly.
b=->n{Q[I]=?~
d=Q[I+n]==(n>1??|:?-)?1:-1
loop{I+=d*n
b[n>1?1:N]if Q[I]==?+
Q[I]<?~?4:break}}
F=->s{N=s.size;Q=s+?\n
Q.gsub!(/^.*$/){$&.ljust N-1}
(0..N).find{!(I=Q=~/\+/)||b[1]}}

Test it online: ideone
Basically, function b starts at any +, recursively goes through the loop, setting all + to u. Thus one loop gets removed each time b is called. Function F just tries how often we need to call b until there aren't any loops remaining.

Python 2 - 390
Takes a string with newlines from stdin. It's a pretty simple method golfed a fair bit, but I'm sure not as much as it could be considering how long it is.
s=raw_input().split('\n');L=len
def R(x,y):
 b=p,q=x,y;u=v=f=0
 while b!=(p,q)or not f:
    p+=u;q+=v;f=u+v;c=s[q][p]
    if'+'==c:u,v=[(i,j)for i,j in{(-1,0),(1,0),(0,-1),(0,1)}-{(-u,-v)}if 0<=q+j<L(s)and 0<=p+i<L(s[q+j])and s[q+j][p+i]in['-+','|+'][j]][0];s[q]=s[q][:p]+' '+s[q][p+1:]
    if c+s[q+v][p+u]in'-|-':p+=u;q+=v
print L([R(x,y)for y in range(L(s))for x in range(L(s[y]))if'+'==s[y][x]])

Python 2 - 346 bytes
Implemented as a function c that takes the file data as input and returns the number of loops.
First, the function decomposes the data to a mapping of loop element locations to the element type at that location (e.g. {(0,0): '+'}). Then, it uses two mutually-recursive internal functions. The first removes a loop segment from the mapping and decides which locations to check for the subsequent segment. The second checks what kind of loop element is in the selected locations and, if it is compatible with what is expected, calls the first to remove the newly found section.
e=enumerate
def c(d):
 D={(i,j):k for i,l in e(d.split('\n'))for j,k in e(l)if k in'+-|'}
 def f(r,c,R,C,t):
  if D.get((r,c),t)!=t:g(r,c)
  elif D.get((R,C),t)!=t:g(R,C)
 def g(r,c):
  t=D.pop((r,c))
  if t!='|':f(r,c-1,r,c-2,'|');f(r,c+1,r,c+2,'|')
  if t!='-':f(r-1,c,r-2,c,'-');f(r+1,c,r+2,c,'-')
 n=0
 while D:g(*D.keys()[0]);n+=1
 return n

source: Stack Exchange

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

sort: votes


text:
Very Simple Triangles
Write a program or function that takes in a positive integer (via stdin, command line, or function arg) and prints or returns a string of that many of these small triangles tiled together, alternating which way they point:
 /\
/__\

This sole triangle is the output if the input is 1.
If the input is 2, the output is
  ____
 /\  /
/__\/

If the input is 3, the output is
  ____
 /\  /\
/__\/__\

If the input is 4, the output is
  ________
 /\  /\  /
/__\/__\/

And so on. Your program must support inputs up to 216 - 1 = 65535.
Details

The leftmost triangle always points upwards.
There may be trailing spaces but there may not be unnecessary leading spaces.
There may be an optional trailing newline.
Note that for 1 the output is two lines long but otherwise it's three. This is required.
The shortest submission in bytes wins.

Pyth, 44 42
ItQpdd*\_*4/Q2)jbms<*dQhQ,c" /\ "2,\/"__\\

The first line:
ItQpdd*\_*4/Q2)
ItQ           )    If the input is not 1
   pdd             Print two spaces
      *\_*4/Q2     Then groups of 4 underscores, repeated input/2 times.

The other two lines are generated by noticing that the second line consists of " /" and "\ " alternating input + 1 times, and the third line consists of "/" and "__\" alternated in the same fashion.

striked out 44 is still normal 44 :(

42. Of course!

42 ?  We have a winner!! O.o lol

@Optimizer: I find it endlessly amusing that your sadness over the appearance of 44 has received more votes than the question or this answer.

3 bytes - doubling with y is the same as *4/2

@Maltysen *4/1 2 = 0, y1 = 2. / is floored, which is necessary behavior.

Just got 10 answers deep in the crossed out 44 chain

@AlexA. I find it endlessly amusing that your amusement over Optimizer's sadness over the appearance of 44 has received more votes than the question or this answer.

@isaacg Unfortunately false now

@Quintec Fortunately true again!

SQL, 182 175 173 187 bytes
Not that this'll ever be the shortest, but it's still amusing to try to minimize sql ;) lol
I did this in Oracle 11, however, these should be basic SQL.
[edit] as pointed out, I didn't apply the when input = 1 rule - only show 2 lines. can't think of a better way to do it, however, I did save a couple bytes by modifying the v logic ;) adding 2 ahead of time saves a couple bytes by not having to repeat it later [/edit]
select decode(&i,1,'',rpad('  ',v,'____')||z)||rpad(' /',v,'\  /')||decode(y,1,'\')||z||rpad('/',v-1,'__\/')||decode(y,1,'__\')from(select 2+floor(&i/2)*4v,mod(&i,2)y,chr(10)z from dual);

[edit1] removed some unnecessary spaces[/edit1]
[edit2] changed &&i to just &i.  It cuts down 2 chars, but forces user to input the # of triangles twice ... :P I realized my "good coding habits" using &&i were costing be 2 bytes!! The horror!! [/edit2]
Explanation
(note: I use &&1 in this explanation so it only prompts once, the &1 above saves code space, but prompts multiple times ;) )
 select  -- line 1
     decode(&&1,1,'',   -- don't need line 1 if input is 1
     rpad('  ',v,'____') || z ) || -- every pair of triangles
     -- line 2
     rpad(' /',v,'\  /') ||  -- every pair of triangles
          decode(y,1,'\') || z || -- add the final triangle, input: 1,3,5 etc.
     -- line 3
     rpad('/',v-1,'__\/') ||  -- every pair of triangles
          decode(y,1,'__\')   -- add the final triangle, input: 1,3,5 etc.
from (select 2+floor(&&i/2)*4 v,   -- common multiplier. 4 extra chars for every triangle pair
             mod(&&i,2) y,  -- Flag for the final triangle (odd inputs, 1,3,5, etc)
             chr(10) z  -- CR, here to save space.
        from dual);

Output
  SQL> accept i
  1
  SQL> /

   /\
  /__\

  SQL> accept i
  2
  SQL> /

    ____
   /\  /
  /__\/

  SQL> accept i
  3
  SQL> /

    ____
   /\  /\
  /__\/__\

  SQL> accept i
  12
  SQL> /

    ________________________
   /\  /\  /\  /\  /\  /\  /
  /__\/__\/__\/__\/__\/__\/

  SQL>

Would it work to remove the space after from? If so that'll save you a byte.

oh good lord .. that's nuts . just tried it .. and then "went to town" stripping out what spaces I could ... O.o  This sucker's unreadable now .. but it works still ;) lol  (I can NOT believe the aliases still work like that .. O.o  hehe )

I'm sooo confused on the upvotes! O.o It's nowhere near the smallest size .. yet .. upvotes!  O.o  wow.

Upvotes typically denote that people like your submission because it's creative, the language used is uncommon, or any number of reasons. In my experience it's uncommon for the shortest code golf answer to also be the highest voted. So while this may not be the shortest answer, the community has deemed it a good one. :)

@Alex .. cool, gravy :)  (i'm gonna have to try this in Excel next ... lol )

Line 1 should probably be decode(&&i,1,'',rpad('  ',2+v,'____') || z) ||.

@freekvd: why? that'll make it longer, and as it is, the rpad will chunk it back appropriately. It needs 2 leading spaces .. always, for any "i" > 0. (and for i = 1, the spaces are "visible", so doesn't matter .. ;) )

Because for i=1 it has to be 2 lines long instead of 3. It says so in the challenge details.

add .. didn't notice that before .. thx ... let me rethink that. :)

@freekvd: Thx for catching that - fixed (I hope) .. :)

Python 2, 89 88 87 85 83 named / 81 unnamed
f=lambda n:1%n*("  "+n/2*4*"_"+"\n")+(" /\ "*n)[:2+2*n]+"\n"+("/__\\"*n)[:n-~n+n%2]

(Thanks to @orlp for a byte, and @xnor for another three)
This is a function which takes in an int n and returns the triangles as a string using the row-by-row approach.
e.g. print f(10) gives
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

For the first row, instead of (n>1)* we use 1%n*, since 1%n is 0 if n == 1 and 1 if n > 1.

You can shave off a character, turning " /\\ " into " /\ ".

Doesn't this lambda work in Python 3 also?

@mbomb007 There's a floor division in there

@orlp Allow me now, to add further confusion, but deleting my comment ;)

I'm suspicious of the "\n".join() for 3 items, even if the list is used to conditionally remove the first element. Perhaps something like b*(x+"\n")+y+"\n"+z is shorter?

Ah, the good old 1%n. For the 2*n-~(n%2), I think it can be n-~n+n%2.

JavaScript (ES6), 101 109
Way too long
f=(n,z=a=>a.repeat(n/2))=>(n>1?'  '+z('____')+'\n ':' ')+z('/\\  ',w=' /'[++n&1]+'\n')+w+z('/__\\')+w

Explanation
Using fat arrow for function definition. Moreover no {} block: the function body is a single expression that is the return value. f=(a,b,c)=>expr is equivalent to
function f(a,b,c)
{
  return expr;
}

Inside a single expression you can not use statements like if or var, but

parameters with default values can be used as local variables
conditional expressions ?: work well instead of if else
you can add more subexpressions using the comma operator or even better as unused parameter to functions. In this case the assignment of w is the second (unused) parameter to the function z

We can rewrite the f function as
f = function(n) {
  var z = function(a) { // use current value of n (that changes)
    return a.repeat(n/2);
  };
  var result;
  if (n > 1) {
    result = '  ' + z('____') + '\n '; // top row if more than 1 triangle
  else
    result = ' '; // else just the blank
  ++n; // increase n, so invert even/odd
  w = ' /'[n&1]+'\n'; //  blank if n is now even, else '/' if n is now odd
  // the next rows will end in "/\" or "\  /" based on n even/odd
  result +=  z('/\\  ') + w; // offset by the blank char added before
  result += z('/__\\') + w;
  return result;
}

Test in Firefox/FireBug console
console.log(f(1),f(2),f(3),f(4),f(9))

Output
 /\
/__\

  ____
 /\  /
/__\/

  ____
 /\  /\
/__\/__\

  ________
 /\  /\  /
/__\/__\/

  ________________
 /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\

Nicely done! I spent far too long yesterday looking to shorten it and at best managed to reproduce the 109 in different ways. -8 is quite the jump.

Cool. Could you post an explanation? I don't fully understand the use of w

@BadHorse explanation added (really, this time)

Out of interest I tried to do it without trailing spaces and came up with n=>(n>1?'  '+'____'.repeat(n/2)+'\n':'')+' /\\ '.repeat(n).slice(0,n*2+2-n%2)+'\n'+'/__\\'.repeat(n).slice(0,n*2+1+n%2) for 119 (deliberately not using template strings etc. to match your answer).

Haskell 155 153 139 131 Bytes
I found a slightly different approach that turned out to be shorter than my original method. My original attempt is preserved below. As with before, golfing tips are appreciated.
m n=unlines.dropWhile(=="  ").z["  "," /","/"].foldr1 z$map t[1..n]
t n|odd n=["","\\","__\\"]
t _=["____","  /","/"]
z=zipWith(++)

Thanks to Nimi for the golfing tips.

Previous Attempt 197 179 Bytes
t n=putStr.unlines.dropWhile(all(==' ')).z(flip(++))(if odd n then["","\\","__\\"]else repeat"").z(++)["  "," /","/"].map(take(4*div n 2).cycle)$["____","\\  /","__\\/"]
z=zipWith

Some hints for golfing: (mod n 2)==0 is even n or better use odd n and swap the then and else part. concat.take(div n 2).repeat is take(4*div n 2).cycle because all list elements are of length 4. Assign short names to functions with long names, e.g. z=zipWith - then use z. You can kick out a few spaces ...repeat""else[....

@nimi Thanks for your hints! Using them, I was able to golf my original solution to 179 bytes. By reconsidering my approach, I was also able to reduce my solution to 155 Bytes.

Hints, part II: foldr z["","",""] is foldr1 z, because the list to fold is never empty. Instead of all(==' ')  you can use =="  " (<- two spaces in-between), because it is used to remove the empty line in case of n = 1 and here the first line is "  ". The first definition of t can be written in a single line: t n|odd....

CJam, 55 53 51 bytes
SSri:I2/4*'_*N]I1>*" /\ "I*I)2*<N"/__\\"I*I2*)I2%+<

I tried porting my Python answer and it turned out to be shorter than the other CJams.
Permalink.

CJam, 73 68 63 62 60 bytes
This definitely needs some golfing...
S2*l~:I2/'_4**N]I(g*S"\\  /"'\{I2md@*@@*'/\@}:F~N"__\\/"_W<F

Test it here.
Explanation
"Print the first line:";
S2*l~:I2/'_4**N]I(g*

S2*                  "Push a string with 2 spaces.";
   l~:I              "Read and eval the input, store it in I.";
       2/            "Divide by two to get the number of top segments.";
         '_4**       "Push '____' and repeat it by the number of segments.";
              N]     "Push a newline and wrap everything in an array.";
                I(g* "Get sign(I-1) and repeat the array that often. This is a no-op
                      for I > 1 but otherwise empties the array.";

"Print the other two lines. The basic idea is to define block which takes as arguments
 a repeatable 4-character string as well as another string which only gets printed for
 even I.";
S"\\  /"'\{I2md@*@@*'/\@}:F~N"__\\/"_W<F

S                                        "Push a space.";
 "\\__/"'\                               "Push the string '\__/' and the character \.";
          {             }:F~             "Store this block in F and evaluate it.";
           I2md                          "Get I/2 and I%2 using divmod.";
               @*                        "Pull up the second argument and repeat it I%2
                                          times. This turns it into an empty string for
                                          even I.";
                 @@                      "Pull up I/2 and the 4-character string.";
                   *                     "Repeat the string I/2 times.";
                    '/\@                 "Push a / and reorder the three line parts.";
                            N            "Push a newline.";
                             "__\\/"_W<F "Call F again, with '__\/' and '__\'.";

Julia, 115 bytes
n->(m=n÷2;p=println;k=n%2>0?m+1:m;e=m<k?"":"/";t=" /\\ ";b="/__\\";if n>1 p("  "*"_"^4m)end;p(t^k*" "*e);p(b^k*e))

This creates an unnamed function which accepts an integer and prints the triangles. To call it, give it a name, e.g. f=n->(...).
Ungolfed + explanation:
function f(n)

    m = n ÷ 2                    # Number of upside down triangles
    p = println                  # Store println function to save space
    k = n % 2 > 0 ? m + 1 : m    # Number of right side up triangles
    e = m < k ? "" : "/"         # n even? End lines with a /

    # Top of the triangle
    t = " /\\ "

    # Bottom of the triangle
    b = "/__\\"

    # Print the bottoms of any upside down triangles
    # * performs string concatenation
    # ^ performs string repetition
    if n > 1
        println("  " * "_"^4m)
    end

    # Print the triangle tops (these have two trailing spaces
    # if the last triangle isn't upside down)
    println(t^k * " " * e)

    # Print the triangle bottoms
    println(b^k * e)
end

Example output:
julia> for i = 1:10 f(i) end
 /\
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\
/__\/__\
  ________
 /\  /\  /
/__\/__\/
  ________
 /\  /\  /\
/__\/__\/__\
  ____________
 /\  /\  /\  /
/__\/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ________________
 /\  /\  /\  /\  /
/__\/__\/__\/__\/
  ________________
 /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

I'm pretty bummed that this is so long. I'm sure there are golfing opportunities aplenty but they aren't clear to me at the moment. Let me know if you have any suggestions or if you'd like any further explanation!

CJam, 68 62 60 bytes
As far as I can see, this is a completely different approach than the other CJam solution. This can be golfed a lot.
"/__\\ /\\"4/]ri:R(['/"  /"'_4*"__\\"'\L]3/R*<+zR1>SS+*\W%N*

Try it online here

C#, 257183 bytes
void C(int t){int i;var n="\r\n";var s="  "+string.Join("____",new string[1+t/2])+n;for(i=0;i++<=t;)s+=i%2<1?"\\ ":" /";s+=n;for(i=0;i++<=t;)s+=i%2<1?"__\\":"/";Console.WriteLine(s);}

Edit: Thanks to the tips from @VisualMelon, saved 74 bytes.
I know it's far from the best language to golf in, but I'm mostly interested in learning about the various nuances of C#, rather than winning the competition.
This is basically a port of this Pyth answer.
I'm thinking the for loops could be golfed further, but I'm not quite sure how, given the tertiary statements embedded within them.
Example (1, 2, 3, 10):
 /\
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\
/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

Ungolfed:
void C2(int t)
{
    int i;
    var n="\r\n";
    var s="  "+string.Join("____",new string[1+t/2])+n;
    for(i=0;i++<=t;)
        s+=i%2<1?"\\ ":" /";
    s+=n;
    for(i=0;i++<=t;)
        s+=i%2<1?"__\\":"/";
    Console.WriteLine(s);
}

While StringBuilders are fast and lovely, if you want a low byte count, s+= is your friend. Indeed, you're for loops can be made a bit more compact. The joy/horror of the ++ and -- operators means you can do most of the work in the conditional check for(i=0;i++<=t;) (this checks if i is less than or equal to t then increments it). You'd do well to define the int i outside the for loop, and reuse it, and since you can guarantee that i will never be negative, i%2==0 can be swapped for i%2<1. With these changes, a sub 200byte score is easily attained.

Also, I suspect you wrote this up in LINQPad or similar, because access to Enumerable usually requires a using System.Linq directive, and I think it's generally intended that such clauses are included. However, in this instance the only LINQ can be replaced with var s="  "+string.Join("____",new string[1+t/2])+n; which contains no LINQ, and is shorter than the current code ;) It joins lots of null strings together with what we really care about, "" (the 1+t/2 being because we need another null string to fit another "" before). The variable n is declared as "\r\n".

Great tips! I forgot that Enumerable would need System.Linq, I barely pay attention these days. The for loop tip is handy!

A bit late, but you could save 4 bytes by using Console.Write instead of Console.WriteLine

C# 190
void f(int n){string s=(n>1)?"\n  ":"",t=" /",u = "/";bool b=true;int m=n;while(m-->0){s+=(n>1&&b&&m>0)?"____":"";t+=b?"\\":"  /";u+=b?"__\\":"/";b=!b;}Console.Write("{0}\n{1}\n{2}",s,t,u);}

Ungolfed
void f(int n)
{
string s = (n > 1) ? "\n  " : "", t = " /", u = "/";
bool b = true;
int m = n;
while(m-->0)
{
s += (n > 1 && b && m>0) ? "____" : "";
t += b ? "\\" : "  /";
u += b ? "__\\" : "/";
b = !b;
}
Console.Write("{0}\n{1}\n{2}",s,t,u);
}

Nice work! Note that it is never better to use a whileloop, rather use a for loop. In this case you can save 2 bytes by including the definition of m in the for loop initialisation, and b=!bin the last thing whatever it's called. You can also make savings by replacing string and bool with var. You also don't need the "()" around n>1 clauses, and in the s+= clause you can use the non-short circuiting & rather than && as there are no side-effects or dereferences to go wrong. Finally, 1>0 is shorter than true ;)

Java, 185
String f(int n){int i;String s="";if(n>1){s="  ";for(i=0;i<n/2;i++)s+="____";s+='\n';}for(i=0;i<=n;)s+=i++%2<1?" /":"\\ ";s+='\n';for(i=0;i<=n;i++)s+=i%2<1?i<n?"/_":"/":"_\\";return s;}

Explanation
String f(int n) {
    int i;
    String s = "";
    if (n > 1) {
        s = "  ";
        for (i = 0; i < n / 2; i++) {
            s += "____";
        }
        s += '\n';
    }
    for (i = 0; i <= n; i++) {
        s += i % 2 < 1 ? " /" : "\\ ";
    }
    s += '\n';
    for (i = 0; i <= n; i++) {
        s += i % 2 < 1 ? i < n ? "/_" : "/" : "_\\";
    }
    return s;
}

C# - 151 146 141 138
Inspired by @bacchusbeale's answer
string f(int n){string t="\n",s=n>1?"  "+new string('_',n/2*4)+t:"";for(var b=n<0;n-->=0;t+=b?"__\\":"/",b=!b)s+=b?"\\ ":" /";return s+t;}

Ungolfed
    string f(int n)
    {
        string t = "\n", s = n > 1 ? "  " + new string('_', n / 2 * 4) + t : "";
        for (var b = n < 0; n-- >= 0; t += b ? "__\\" : "/", b = !b)
            s += b ? "\\ " : " /";
        return s + t;
    }

Nice, not sure how I missed this before commenting on the other answers! That overload of new String is a new one to me! You seem to have missed your t="" from the golfed version, though a better thing to do would be initialize t as "\n". You can save a couple of bytes by appending to t where you flip b, saving the "{}" on the for-loop: t+=(b=!b)?"/":"__\\".

@tis you can save a couple more if you define t before s and add t to the string rather than "\n" ;)

C89, 150
r(p,q,n)int*p,*q;{n?printf(p),r(q,p,n-1):puts(p);}main(c,v)int**v;{c=atoi(v[1]);if(c>1)printf("  "),r("","____",c-1);r(" /","\\ ",c);r("/","__\\",c);}

An ungolfed version:
r(p, q, n) char *p, *q; {
    if(n > 0) {
        printf(p);
        r(q, p, n-1); /* swap p and q */
    } else {
        puts(p);
    }
}

main(c, v) char**v; {
    c = atoi(v[1]);
    if(c>1) {
        printf("  ");
        r("", "____", c - 1);
    }
    r(" /", "\\ ", c);
    r("/", "__\\", c);
}

The output:
$ seq 1 3 10 | xargs -n1 ./triangles
 /\
/__\
  ________
 /\  /\  /
/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

The stack overflows if I enter 65535 (but not if you compile with -O3!), but theoretically it should work ;-)
edit: program now fulfills the requirement that only two lines should be outputted if 1 is passed to the program
edit 2: use int* instead of char*

You could declare main as main(c,v)**v; if that works.

I was wondering if you could save something by  having c or n as a global variable, so you don't have to pass that parameter to r(). I don't think your answer complies with Note that for 1 the output is two lines long but otherwise it's three. This is required.

@FUZxxl unfortunately this doesn't work :-( error: expected declaration specifiers before ‘*’ token main(c,v)**v;{

@steveverrill fixed it, but I needed to lenghten the code. Couldn't find a solution with a global n or c that's shorter either.

@MarcDefiant Were you able to pass an int**?

@FUZxxl thank you, that worked!

Go, 156 144
func f(n int){a,b,c:="  ","","";for i:=0;i<=n;i++{if i<n/2{a+="____"};if i%2<1{b+=" /";c+="/"}else{b+=`\ `;c+=`__\`}};print(a+"\n"+b+"\n"+c)}

Ungolfed:
func f(n int) {
    a, b, c := "  ", "", ""   // Initialize 3 accumulators
    for i := 0; i <= n; i++ { // For each required triangle
        if i < n/2 {          // Yay integer math
            a += "____"
        }
        if i%2 < 1 {          // Even, uneven, (are we drawing up or downslope?)
            b += " /"
            c += "/"
        } else {
            b += `\ `
            c += `__\`
        }
    }
    print(a + "\n" + b + "\n" + c)
}

The only real trick here (and it isn't even a good one) is using 3 accumulators so I can condense the solution down to 1 loop.
The code can be run here: http://play.golang.org/p/urEO1kIjKv

simply use c += `__\`  instead of the if i<n{c+="_"}

@MarcDefiant Updated, thanks

Bash, 166 127 125 119 105 bytes
printf -v l %$[$1/2]s;(($1%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r

In a function:
triangle() {
    printf -v l %$[$1/2]s;(($1%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r
}

With some presentations:
for i in {1..5} 10 31;do
    paste -d\  <(
        figlet -fsmall $i |
             sed 's/^/         /;s/^ *\(.\{10\}\)$/\1  /;$d'
    ) <(triangle $i)
  done

May render (if you have figlet installed):
        _
       / |    /\
       | |   /__\
       |_|
      ___      ____
     |_  )    /\  /
      / /    /__\/
     /___|
      ____     ____
     |__ /    /\  /\
      |_ \   /__\/__\
     |___/
     _ _       ________
    | | |     /\  /\  /
    |_  _|   /__\/__\/
      |_|
      ___      ________
     | __|    /\  /\  /\
     |__ \   /__\/__\/__\
     |___/
   _  __       ____________________
  / |/  \     /\  /\  /\  /\  /\  /
  | | () |   /__\/__\/__\/__\/__\/
  |_|\__/
    _____      ____________________________________________________________
   |__ / |    /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
    |_ \ |   /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
   |___/_|

Save 2 chars if input from variable instead of $1: 103
printf -v l %$[i/2]s;((i%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r

Into the loop:
for i in {1..3} {31..34};do
    [ $i == 31 ] && figlet -fsmall ...
    paste -d\  <(
        figlet -fsmall $i |
            sed 's/^/         /;s/^ *\(.\{10\}\)$/\1   /;$d'
    ) <(
        printf -v l %$[i/2]s;((i%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r
    )
  done

Will render (approx) same:
        _
       / |     /\
       | |    /__\
       |_|
      ___       ____
     |_  )     /\  /
      / /     /__\/
     /___|
      ____      ____
     |__ /     /\  /\
      |_ \    /__\/__\
     |___/

 _ _ _
(_|_|_)

    _____       ____________________________________________________________
   |__ / |     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
    |_ \ |    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
   |___/_|
  _______       ________________________________________________________________
 |__ /_  )     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /
  |_ \/ /     /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/
 |___/___|
  ________      ________________________________________________________________
 |__ /__ /     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
  |_ \|_ \    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
 |___/___/
 _____ _        ____________________________________________________________________
|__ / | |      /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /
 |_ \_  _|    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/
|___/ |_|

You should post a question about a figlet implementation codegolf!

><> (Fish), 215 183 156 bytes
Edit: Notepad++ was giving me 5 extra bytes due to CR, so modified count accordingly
Slightly more golfed, but it is my first fish program so far >_< The requirement to not have a blank first line for 1 triangle doubled the size of the program.
99+0{:}1=?.~~"  "oo:2,:1%-v
-1  oooo  "____"  v!?  )0:/!
" /"oa~~.?=1}:{24~/:oo
v!?)0:-1o"\"v!?)0:/!-1ooo"  /"
/v   ~o"/"oa/!
!\:0)?!;"\__"ooo1-:0)?!;"/"o1-

Can test at http://fishlanguage.com/ (Int on initial stack for length)
Explanation:
       Start with initial stack as input number
99+0   Push 18 and 0 to the top of the stack
{:}    Shift the stack to the left (wraps), copy the top value, and shift it back to the left (i.e. copy bottom of stack to the top)
1=     Check to see if the top of the stack is equal to 1, pushes 1 for true, 0 for false
?.     If top of stack is zero, skip the ., otherwise jumps to x,y coordinates on top of stack (18,0). This skips the next 8 instructions
~~     Pop the top 2 values from the stack (if they're not popped by the jump)
"  "   Push the string literal "  " onto the stack
oo     Pop the top two values of stack and output them as characters
:2,    Copy top value of stack, ad divide by 2
:1%-   Since ><> uses float division, and doesn't have >= notation, remove the decimal part (if exists)
v      Redirect pointer down
/      Redirect pointer left
:0)    Copy top of stack, and see if its greater than 0 (1 for true, 0 for false)
?!v    If top of stack is non-zero, then ! is executed, which skips the next instruction (redirect), otherwise, code is redirected
"____" Push the literal "____" to the stack
oooo   Pop the top four values of stack and output them as characters
1-     Decrement the top of the stack by 1
!/     Ignore the redirect action.
       When the loop gets to 0, it goes to next line, and gets redirected to the left.
~      Pops the top of the stack (0 counter)
42     Pushes 4 and 2 to the stack
{:}    As before, copies the bottom of the stack to the top
1=?.   Also as before, if the initial value is 1, jump to (2,4) (skipping next 4 instructions
~~     Pop 2 values from stack if these instructions haven't been skipped
ao     Push 10 onto the stack and output it as a character (LF)
"/ "oo Push the literal "/ " onto the stack and output it
://    Copies the top of the stack then redirects to the line below, which then redirects to the left
:0)    Copies top of the stack and compares if its greater than 0
?!v    If it is, redirect to next line
"\"o   Push "\" to stack, then output it as a character
1-     Decrement top value of stack
:0)?!v If loop is not greater than 0, redirect to next line
       Either mode of redirect will loop to the left, and (potentially) skip the far right redirect because of the !
ao     Push 10 to stack and output it as a character (LF)
"/"o~  Push "/" to stack, then output it as a character. Pop top value of stack (the 0 from previous loop)
v      Redirects to next line, which then redirects to the right
:0)?!; If the top of the stack is not greater than 0, terminate (;)
"\__"  Pushes "\__" to the stack
ooo    Outputs top 3 stack values as characters ("__\")
1-     Decrement top of stack by 1
:0)?!; If the top of the stack is not greater than 0, terminate (;)
"/"o   Push "/" to top of stack then output it as a character
1-     Decrement top of stack by 1
!\     Ignore the redirect

Nice interpreter! Did you make that yourself?

Not even slightly. :P I used it extensively to teach myself the language...and to debug. I just saw the language floating around and thought it was very interesting (also want to try Marbles).

perl 109 108 106
$i=<>;$t=join$/,$i-1?"  "."_"x($i/2)x4:(),$m.=(" /")[$_&1]||"\\ ",$b.=("/")[$_&1]||"__\\"for 0..$i;print$t

I think this is alright for my first golf, I used Vynce's section for the first line, with the rest of my code to get past the new line problem with 1 triangle.
Now to see if I can shorten it :)
Edit: Whitespace
Edit 2: replaced "\n" with $/
1:
 /\
/__\

4:
  ________
 /\  /\  /
/__\/__\/

C++ stdlib, 194 bytes
string f(int n){char* p[]={"____"," /\\ ","/__\\"};int x[]={(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},i,j;string s=n>1?"  ":"";for (i=n>1?0:1;i<3;s+=++i<3?"\n":"")for (j=0;j<x[i];)s+=p[i][j++%4];return s;}

Test program:
#include <string>
#include <iostream>

using namespace std;

string f(int n)
{
    char* p[]={"____"," /\\ ","/__\\"};
    int x[]={(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},i,j;
    string s=n>1?"  ":"";
    for (i=n>1?0:1;i<3;s+=++i<3?"\n":"")
        for (j=0;j<x[i];)
            s+=p[i][j++%4];
    return s;
}

int main(int argc, char* argv[])
{
    cout << f(10);
    return 0;
}

Charcoal, 27 bytes
ＦＥＮ﹪ι²«Ｐ×⁴_↗⊗¬ι↓Ｐ↘²↘⊗ι↑Ｐ↗⊗ι

Try it online! Link is to verbose version of code. Explanation:
ＦＥＮ﹪ι²«

Generate a list of alternating bits of length n and loop over them.
Ｐ×⁴_

Draw ____ without moving the cursor.
↗⊗¬ι↓

On the first and every other triangle, draw the left / side.
Ｐ↘²

Draw the \ side without moving the cursor.
↘⊗ι↑

On the second and every other triangle, draw the left \ side again to move the cursor.
Ｐ↗⊗ι

On the second and every other triangle, draw the right / side, without moving the cursor.

Answers no longer have to be marked as non-competing anymore

PowerShell, 116 95 bytes
Big thanks to Mazzy and ASCII-Only for saving 21 bytes

param($n)@("  "+"_"*4*($x=$n-shr1))[$n-eq1]
" /"+"\  /"*$x+"\"*($a=$n%2)
"/"+"__\/"*$x+"__\"*$a

Try it online!
Not allowing an empty line for n = 1 ate up like 14 10 bytes. This solution is pretty brain dead now much more clever with a minimal amount of repeated code. Banker's Rounding is still the actual devil.

Is an empty line not allowed???

@ASCII-only Read the 4th bullet point from the OP.

damnit

here we go

102 on yours

@ASCII-only Breaks on x = 3 The string replace is how you bypass banker's rounding

@mazzy you can't generate a first line, otherwise it'd be 102

100?

close, but not quite 100

96 bytes. Try it online!

Let us continue this discussion in chat.

Prolog, 126 bytes
A+B:-writef(A,B).
$N:-(N>1,"  %r\n"+['____',N//2];!),(0is N/\1,T='/';T='')," %r%w\n"+['/\\  ',N/2,T],"%r%w\n"+['/__\\',N/2,T].

Invoke like $3.
More readable:
triangle(N):-
    (   N > 1
    ->  writef("  %r\n", ['____', N//2])
    ;   true
    ),
    (   0 is N mod 2
    ->  T = '/'
    ;   T = ''
    ),
    writef(" %r%w\n", ['/\\  ', N/2, T]),
    writef("%r%w\n", ['/__\\', N/2, T]).

Example:
?- findall(N,between(1,10,N),NN), maplist($, NN), !.
 /\
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\
/__\/__\
  ________
 /\  /\  /
/__\/__\/
  ________
 /\  /\  /\
/__\/__\/__\
  ____________
 /\  /\  /\  /
/__\/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ________________
 /\  /\  /\  /\  /
/__\/__\/__\/__\/
  ________________
 /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/
NN = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].

C, 368 Bytes
void p(char* c){printf(c);}
int x(int s,int f){int t=0,p=s;for(int i=0;i<f;i++){if(p==1){t++;p=0;}else{p=1;}}return t;}
int main(int argc,char* argv[]){int t=atoi(argv[1]);if(t>1){p("  ");for(int i=0;i<x(0,t);i++)
{p("____");}p("\n");}for(int i=0;i<x(1,t);i++){p(" /\\ ");}if(t%2==0){p(" /");}p("\n");
for(int i=0;i<x(1,t);i++){p("/__\\");}if(t%2==0){p("/");}p("\n");}

It's more if you count the #include statements, but it compiled on gcc, albeit with warnings, without them. I know it's not the shortest by far, but I still like that I did it in C.

The macro #define p(c)printf(c) is shorter than your function. You can omit return types on functions (they default to int). You can also define function in C89 style like this main(c,v)char**v;{}. That is short for int main(int c, char** v){}

Perl (simple) 131 125 120
fairly straightforward first pass:
$i=<>;print join"\n",$i-1?"  "."_"x(4*int($i/2)):(),join("",map{(" /","\\ ")[$_%2]}0..$i),join"",map{("/","__\\")[$_%2]}0..$i

oh who needs explicit int?
$i=<>;print join"\n",$i-1?"  "."_"x($i/2)x4:(),join("",map{(" /","\\ ")[$_%2]}0..$i),join"",map{("/","__\\")[$_%2]}0..$i

C#: 1 line LINQ, 198 bytes
string f(int n){return(n>1?"  ":"")+string.Join("\n",new[]{"____"," /\\ ","/__\\"}.Zip(new[]{(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},(s,l)=>string.Join(s,new string[n+1]).Substring(0,l)).Where(x=>x.Any()));}

Retina, 88 bytes
K`  ____¶ /\  /¶/__\/
%`....$
$+*$&
%`(.+)\1$
$1
(  (____)*)__(¶.*)  /(¶.*)/
$1$3$4
G`\S

Try it online! Explanation:
K`  ____¶ /\  /¶/__\/

Replace the input with a pair of triangles.
%`....$
$+*$&

Multiply the triangles by the original input.
%`(.+)\1$
$1

Divide the triangles by 2.
(  (____)*)__(¶.*)  /(¶.*)/
$1$3$4

Remove the left-over half triangle.
G`\S

Remove the first line if it is now blank.

Perl 6, 83 bytes
{~["  {'____'x$_/2-.5}
"x($_>2),'/\  'x$_/2~($!='/'x$_%2),"
"~'/__\\'x$_/2~$!]}o*+1

Try it online!
Anonymous code block that takes a number and returns a string.

C (gcc), 117 115 bytes
-2 thanks to ceilingcat.
All those parentheses suggest something less clunky is surely possible.
f(n,i,j){for(j=3-1/n;j--;puts("/"+(n%2|j>1)))for(i=0;i<n+(j<2)>>1;)printf("  %.4s"+2-j*!i++,"/__\\/\\  ____"+j*4);}

Try it online!

this might be a start for something less clunky. might.

05AB1E, 37 bytes
≠iðð'_I2÷4*×J}„ /„\ ‚I>∍J'/…__\‚I>∍J»

Try it online or verify the first 10 outputs.
Explanation:
≠i            } # If the (implicit) input is NOT 1:
                #   i.e. 1 → 0 (falsey)
                #   i.e. 5 → 1 (truthy)
  ðð            #  Push two spaces "  "
    '_         '#  Push string "_"
      I         #  Push the input
       2÷       #  Integer-divide it by 2
                #   i.e. 5 → 2
         4*     #  And then multiply it by 4
                #   i.e. 2 → 8
           ×    #  Repeat the "_" that many times
                #   i.e. "_" and 8 → "________"
            J   #  Join everything on the stack together to a single string
                #   i.e. "  ________"
„ /             # Push string " /"
   „\           # Push string "\ "
     ‚          # Pair them together: [" /","\ "]
      I>        # Push the input+1
        ∍       # Extend the list to that size
                #  i.e. [" /","\ "] and 2 → [" /","\ "]
                #  i.e. [" /","\ "] and 6 → [" /","\ "," /","\ "," /","\ "]
         J      # Join the list together to a single string
                #  i.e. [" /","\ "] → " /\ "
                #  i.e. [" /","\ "," /","\ "," /","\ "] → " /\  /\  /\ "
'/             '# Push string "/"
  …__\          # Push string "__\"
      ‚         # Pair them together: ["/","__\"]
       I>       # Push the input+1
         ∍      # Extend the list to that size
                #  i.e. ["/","__\"] and 2 → ["/","__\"]
                #  i.e. ["/","__\"] and 6 → ["/","__\","/","__\","/","__\"]
          J     # Join the list together to a single string
                #  i.e. ["/","__\"] → "/__\"
                #  i.e. ["/","__\","/","__\","/","__\"] → "/__\/__\/__\"
»               # Join the entire stack with a newline delimiter
                #  i.e. " /\ " and "/__\" → " /\ \n/__\"
                #  i.e. "  ________", " /\  /\  /\ " and "/__\/__\/__\"
                #   → "  ________\n /\  /\  /\ \n/__\/__\/__\"
                # (and output the result implicitly)

Java 11, 122 bytes
n->(n>1?"  "+"_".repeat(n/2*4)+"\n":"")+" /\\ ".repeat(n).substring(0,++n*2)+"\n"+"/__\\".repeat(n).substring(0,n/2*4+n%2)

Try it online.
Explanation:
n->                   // Method with integer parameter and String return-type
  (n>1?               //  If the input is larger than 1:
    "  "              //   Return two spaces
    +"_".repeat(      //   Appended with "_" repeated the following amount of times:
          n/2         //    The input integer-divided by 2
             *4)      //    And then multiplied by 4
    +"\n"             //   Appended with a newline
   :                  //  Else:
    "")               //   Return nothing
  +" /\\ ".repeat(n)  //  Appended with " /\ " repeated the input amount of times
    .substring(0,     //   After which we only leave the first `x` characters, where `x` is:
      ++n             //    Increase the input by 1 first with `++n`
         *2)          //    And then multiply it by 2
                      //     i.e. For input 1, `x` becomes 4 here
                      //     i.e. For input 6, `x` becomes 14 here
  +"\n"               //  Appended with a newline
  +"/__\\".repeat(n)  //  Appended with "/__\" repeated the input amount of times
    .substring(0,     //   After which we only leave the first `y` characters, where `y` is:
      n/2             //    The input+1 integer-divided by 2
         *4           //    Then multiplied by 4
           +n%2)      //    And then the input+1 modulo-2 added
                      //     i.e. For input 1, `y` becomes 4 here
                      //     i.e. For input 6, `y` becomes 13 here

MathGolf, 35 bytes
½û__∞* ∞qpÿ /\ *k∞⌠<p)½ÿ/__\*k¥┬'/*

Try it online!
Explanation
The program is split into 3 parts, ½û__∞* ∞qp, ÿ /\ *k∞⌠<p, and )½ÿ/__\*k¥┬'/*. One part for each line of the output.
First part
½           Halve input to integer
 û__∞       Push "__" and double
     *      Repeat string (input//2 times)
       ∞    Push space character and double
        qp  Print the spaces first, then the underscores

Second part
ÿ /\ *      Push " /\ " and repeat it <input> times
      k∞    Push input and double it
        ⌠   Increment by two
         <p Slice the string to get the first (<input>*2 + 2) characters and print

Third part
)½              Increment input by 1 and halve it to integer
  ÿ/__\*        Repeat "/__\" that many times
        k¥┬     Check if input is divisible by 2
           '/*  Repeat "/" either zero or one times based on input

C# (.NET Core), 151 bytes
Without LINQ - 3 string array.
Like most of these, this fails if the integer goes over the  max char count per line for stdout.
p=>{var s=new string[3]{ "  ","",""};for(var j=0;j< p;){if(j++%2<1){s[1]+=j==p-1?@" /":@" /\ ";s[2]+=j==p-1?@"/":@"/__\";}else s[0]+="____";}return s;}

Try it online!

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

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


text:
Convert a string to its Rövarspråket equivalent
Rövarspråket
Rövarspråket is a word game played by Swedish children, from the books about Kalle Blomkvist by Astrid Lindgren.
The basic rules are as follows (from Wikipedia):

Every consonant (spelling matters, not pronunciation) is doubled, and
an o is inserted in-between.
Vowels are left intact.

A few examples:

"hello" -> "hohelollolo"
"Min svävare är full med ål" -> "MoMinon sosvovävovarore äror fofulollol momedod ålol"

Swedish consonants are the same as the English ones, so the program should work with both Swedish and English entries.
The letter "y" is taken as a consonant in this case - as most of the time it is.

Your Task:
Write a program to convert a string of Swedish letters, inputted through a function or through stdin, into its Rövarspråket equivalent.  Shortest answer in bytes wins!

@MartinBüttner Clarified my question further - it should work with Swedish (as it is a Swedish word-game).

What is the meaning of alphabetical entries ?

@Optimizer A string of only alphabetical characters.  Sorry, I worded it badly, I'll edit

do you mean English alphabets a-zA-Z ?

@Optimizer It should work with Swedish - however the consonants are the same in both Swedish and English.  Will clarify question.

ah, i see . . . .

In the case of a function, should the output be returned or printed to stdout/closest alternative?

How should we treat non letters? At least spaces show up in the second example.

On a side note: 'Y' is considered a vowel in Swedish

Retina, 14 + 5 = 19 bytes
Retina is a language that is essentially just .NET regex with as little overhead as possible. The code for this program consists of two files:
i`[b-z-[eiou]]

$0o$0

This reads the input on STDIN and prints the output to STDOUT.
If you call the files pattern.rgx and replacement.rpl, you can run the program simply like
echo "hello" | ./Retina pattern.rgx replacement.rpl

Explanation
This is pretty straightforward, but let me add some explanation anyway (mostly about how Retina works). If Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.
Retina can be configured (which includes RegexOptions and other options) by prepending the regex with ` and a configuration string. In this case I'm only giving it i which is the normal regex modifier for case insensitivity.
As for the regex itself, it uses .NET's character class subtraction to match any consonant in the ASCII range. The replacement then just writes the match back twice with an o in between.

Are you missing an a in your vowel character class?

@BrianGordon No, I'm starting the character class from b, so I don't need to subtract a.

Interesting, I've never seen nested, subtractive character ranges before. Is that just a .NET thing?

I feel like you need to count at least one character for the delimiting between the two files. that would be a semicolon or newline in another language. it's the space between the filenames if you want to get picky about where the character comes from in this language.

@Sparr yes, that's the policy now, but that policy is newer than this challenge/answer. For reference (In fact, if you look at the time stamps, you can see that I pushed for the policy because of this answer, but applying rules like that throughout the site retroactively doesn't make much sense.)

@MartinBüttner sure, but it doesn't have to be policy to be right.

Using Unix KSH  27 28 32 27 bytes  (or 21 if we only count inside sed command)
Thanks to the suggestions of others :) Appreciated.
.. I got down to this:
sed 's/[^AEIOUÅÄÖ ]/&o&/ig'

(allowed for spaces and Swedish characters)
echo "hello" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
hohelollolo
echo "HELLO" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
HoHELoLLoLO
echo "QuIcKlY Now" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
QoQuIcocKoKlolYoY NoNowow

the i modifier to the s command

Also, I think it is allowable to claim your answer is a sed program, and just count the bytes between the single quotes

I was trying to add it .. but it wouldn't work ... any ideas ?  (tried: "-i" "-I", tried "/Ig", "/gI" .. etc .. nothing worked :(

s/[^AEIOU]/&o&/ig seems to work.. for single words at least... you'll need to exclude spaces as well

what Unix shell are you in? I'm using KSH: and getting command garbled

bash, though the shell shouldn't matter, so long as your sed program is in single quotes

Also watch out for the swedish vowels ö, å, etc - these need excluding too.  Might be better to use a whitelist of just the consonants s/[BCDFGHJ-NP-TV-Z]/&o&/ig

I've setup a chat room .. can we continue there ?  same name as this thread ;)

I don't think I have the GNU extension on my system :(

Let us continue this discussion in chat.

I would make it 'sed' and use "s/[^AEIOUÅÄÖ ]/&o&/ig", which covers Swedish vowels and spaces for 25 bytes.

@swstephe ... cool, thanks .. was trying to do the not vowels, but wasn't sure of the swedish chars :)

CJam, 32 30 bytes
q{_eu'[,66>"EIOU"-#)g{'o1$}*}/

This is a full program reading from STDIN and printing to STDOUT. It works for arbitrary Unicode input and treats the following 42 characters as consonants:
BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz

Test it here.
Explanation
q                              "Slurp STDIN.";
 {                          }/ "For each character...";
  _eu                          "Duplicate and convert to upper case.";
     '[,66>                    "Get a string from B to Z using range and slice.";
           "EIOU"-             "Remove the remaining four vowels.";
                  #            "Find the position of the character in this string or
                                -1 if the character can't be found.";
                   )g          "Increment, take signum, which gives 1 for consonants,
                                and 0 otherwise.";
                     {    }*   "Repeat this block that many times, i.e. do nothing for
                                non-consonants.";
                      'o       "Push an 'o'.";
                        1$     "Copy the current character.";

JavaScript, 59 57 55 44 bytes
s=>s.replace(/(?![eiou])[b-z]/gi,"$&o$&")

Thanks to Masterzagh for reminding me that a function would be acceptable as well, and for his regex tip regarding backreferences without capturing!
Longer version with input/output:
alert(prompt().replace(/(?![eiou])[b-z]/gi,"$&o$&"));

Displays a prompt box to enter the string, then shows a dialog containing the Rövarspråket output. The code uses a regex to double the consonants and insert os.

"Write a program to convert a string of Swedish letters, inputted through a function or through stdin", You can make it s=>alert(s.replace(/(?![eiou])([b-z])/gi,"$1o$1"));

And since it wasn't asked to output, you don't need the alert either.

One more thing, you can backreference without capturing. Basically do s=>s.replace(/(?![eiou])[b-z]/gi,"$&o$&"), since $& means current match you can remove the parenthesis that capture your letter and while you're at it save another byte by removing the semicolon at the end.

@Masterzagh That's cool, thanks again!

Julia, 46 44 bytes
t->replace(t,r"(?![eiou])[b-z]"i,s->s*"o"*s)

This creates an anonymous function that takes a single string input and prints the Rövarspråket equivalent. To call it, give it a name, e.g. f=t->....
Not much has really been golfed here, other than spaces after the commas in replace().
Here we're using 3 arguments in the replace() function: the input string, the regular expression for identifying substrings, and a replacement. Julia denotes regular expression patterns by r"...". Adding i to the end makes it case insensitive. This particular regex matches consonants. If a function is used for the replacement, the output is that function applied to each matched substring. The function we're using here takes a string s and returns sos, since * performs string concatenation in Julia. Thus the end result is the input string with each consonant doubled with an "o" between.
Examples:
julia> f("Min svävare är full med ål")
"MoMinon sosvovävovarore äror fofulollol momedod ålol"

julia> f("hello")
"hohelollolo"

julia> f("Rövarspråket")
"RoRövovarorsospoproråkoketot"

Note that this will be 9 bytes longer if we have to print the result rather than return it. Awaiting confirmation from the OP.

Edit: Saved 2 bytes thanks to Martin Büttner!

Mathematica, 84 73 72 bytes
StringReplace[#,a:RegularExpression@"(?i)[BCDFGHJ-NP-TV-Z]":>a<>"o"<>a]&

Explanation:

RegularExpression@"(?i)[BCDFGHJ-NP-TV-Z]" is a regex matching all consonants case-insensitively.
a:*..*:>a<>"o"<>a creates a delayed rule to bind those consonants to a, and replace it with and o surrounded by itself.
Finally, StringReplace[#,*..*]& creates a pure function applying that rule to every matching letter in its argument.

@MartinBüttner Thanks! Still new to Mathematica golfing...

@MartinBüttner Was going to do that anyways but got distracted by some notifications :P

Haskell, 81 bytes
x n|elem n"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"=[n,'o',n]|1<2=[n]
f=(>>=x)

Usage: f "Hello there!" -> "HoHelollolo tothoherore!".
I cannot cleverly construct the list of consonants without expensive imports. Even turning the letter to check to lowercase needs more bytes than simply listing both upper and lowercase consonants.

Java 8, 45
Use as a lambda function. Uses regular expression.
a->a.replaceAll("(?i)[b-z&&[^eiou]]","$0o$0")

Try here

"Write a program to..." This looks more like a function to me.

PowerShell - 35 bytes
Just to show that PowerShell can compete in these sometimes too, and with the regex shamelessly stolen from Martin Büttner's Retina answer:
%{$_-replace'[b-z-[eiou]]','$0o$0'}

accepts string input from stdin

Python, 61
I couldn't get a character class union or subtraction to work, and so I don't think Python has that feature. I had to use a negative lookahead instead.
import re;f=lambda s:re.sub('(?i)(?![eiou])([b-z])',r'\1o\1',s)

Run it here: http://repl.it/fQ5
Link to the inverse: https://codegolf.stackexchange.com/a/48182/34718

C 106
Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter
x;main(c){for(;read(0,&c,1);printf("%s%s%s"+x*2,&c,x+"o",&c))x=c<66|c>122|c>90&c<98||index("EIOUeiou",c);}

Try it online!

How does the local variable c get declared?

@wjl global variables in C are zero initialized. Local variables are on the stack and are not initialized. See http://stackoverflow.com/questions/3553559/how-are-local-and-global-variables-initialized-by-default   Variables with out a type default to int and since printf works on chars the code might have endian issues - I will check tomorrow.

Yes, I understand default initialization. I was just trying to nicely point out that this code does not compile since c isn't declared at all, e.g. out.c:2:18: error: ‘c’ undeclared (first use in this function).

@wjl I guess it depends on the compiler.  It compiles and runs at ideone.com http://ideone.com/s7M5mZ when you choose C - any idea what the difference is?

Looks like a bug with ideone's compiler. If you fix the newline between c[2];main (necessary because #define doesn't end at a semicolon) it gives similar errors to GCC. Anyway, no big deal, it's still a fun code-golf, but you might actually need a few more characters to make this valid C. =)

@wjl I can't get ideone.com to fail to compile it by adding newlines.  With gcc on my own box it compiles fine (with warnings)  My version of gcc is: gcc (i686-posix-sjlj-rev0, Built by MinGW-W64 project) 4.9.2
Maybe it is a bug in gcc too?

@wjl Ok, I agree it is not valid C.  I can't get it to compile on my RS6000 because it doesn't like the ternary operator having two different types.  Of course it is xlc version 6 - a compiler from 2003.  I guess to make it valid C that would pass any compiler I would need to change it massively.

Perl, 33 Bytes
This answer is mostly regex-only, with a small amount of extra code to perform I/O.
$_=<>;s/[^aeiou\W]/$&o$&/gi;print

It's been a while since I've used Perl regexes, so this can probably be improved.
$_=<>;                              This takes input from STDIN `<>` and stores
                                    it into the default variable $_
      s/          /     /gi;        This is a case-(i)nsentive, (g)lobal,
                                    (s)ubstitution regex.  Since no other
                                    variable is specified, it is applied to
                                    the default variable $_.
        [^aeiou\W]                  This matches any single character that
                                    is a consonant, by using a double-
                                    negative ^\W to match only alphanumeric
                                    characters excluding vowels.  Accented
                                    vowels are not considered alphanumeric
                                    by Perl.
                   $&o$&            This forms the replacement.  $& contains the
                                    match (the consonant), so this replaces each
                                    consonant with two copies of itself with
                                    an 'o' in between.
                            print   This prints the result.  With no arguments,
                                    it prints $_ by default.

Won't [^aeiou] still match å and other non-ASCII vowels?

@AlexA. I already noticed the problem.  It was a zero-character fix (\s to \W).

+1, most thorough explanation for Perl code I have seen on this site.

Windows Batch, 235 bytes
@echo off
setlocal enabledelayedexpansion
set d=qwrtypsdfghjklzxcvbnm
set #=%1
:x
if defined # (
for /l %%i in (0,1,20)do (
set m=!d:~%%i,1!
if /i !m!==%#:~0,1% set g=!g!!m!o)
set g=!g!%#:~0,1%
set #=%#:~1%
goto x)
echo %g%

Usage:
script.bat hello

Output:
hohelollolo

You might be wondering why I didnt set d to "aoui", checking for not-equals requires breaking out of a loop. Not everything that should work, does work, in batch. The script handles 1 word of characters [as they appear on your keyboard]. All spaces and newlines that are still present are required for the script to run.
Windows XP or higher, required. Not tested in Windows 8 and above.

05AB1E, 16 15 13 bytes
-2 bytes thanks to Kevin Cruijssen
žNDu«SD'o«€Ć‡

Try it online!

.š can be u (to uppercase) to save a byte. And nice answer!

I just had the feeling 13 bytes was possible.. Took me a bit to find it, though: žNDu«SD'o«€Ć‡

haha, I was searching for "capital" instead of upper, thanks for the improvements @KevinCruijssen

K, 38 chars
f:{,/(1+2*~(_x)in"aeiouåäö ")#'x,'"o"}

-1 f"Min svävare är full med ål";
MoMinon sosvovävovarore äror fofulollol momedod ålol

K, 31 bytes
,/{(x,"o",x;x)9>" aeiouåäö"?x}'

A straightforward solution seems fairly competitive given that K lacks regexes. Select between the "XoX" form and "X" form based on whether each character was found in a lookup table of ignored vowels and join the resulting lists.
You can try it in your browser using oK:
http://johnearnest.github.io/ok/index.html?run=%20%2C%2F%7B(x%2C%22o%22%2Cx%3Bx)9%3E%22%20aeiouåäö%22%3Fx%7D'%22Min%20svävare%20är%20full%20med%20ål%22

(Unfortunately I can't provide a clickable link because stack overflow doesn't appear to allow accented characters in URLs)

Pyth - 28 bytes
This is works in the obvious way by generating the consonants list on the fly using set-wise difference.
FNzpk+N?+\oN}rNZ-{G{"aeiou"k

Explanation coming soon.
Try it here.

You can save 4 bits by removing 4 chars and replacing one char with another one.

Clip 10, 30
gx"((?i)[b-z&&[^eiou]])""$1o$1

Basic regex substitution.

Pyth, 25 24 23
sm+d*+\od}rd0-G"aeoui"z

Run it here.

One char of your solution is redundant.

Golfscript, 35 bytes
{."aeiouåäö\n "?-1={."o"\}{}if}%

Expects the input to be on the stack. With input (50 bytes):
"#{STDIN.gets}"{."aeiouåäö\n "?-1={."o"\}{}if}%

Works with the swedish vovels å, ä and ö.

input is always on stack on GS

Sed (on command line), 28 bytes
sed 's/\([^aeiou]\)/\1o\1/g'

Either pipe the text in or type it direct. Just the sed code on its own is 22 bytes.

This also duplicates spaces and chars like ä.

JavaScript 43
Thanks to @Masterzagh for saving on function syntax.
x=>x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&")

JavaScript 62
function E(x){return x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&")}

Your function can be in the form of an anonymous arrow function like x=>x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&").
Arrow functions work like this name=(arg1, arg2)=>{code}. () are not needed if there's only one argument and {} are not needed if there's only one line of code. Return is also not needed if the one line returns something.

And I forgot to say. You don't need to give it a name to solve the problem which only asked you to create a function.

R, 45 chars
gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)

Simple regex. Reads from stdin. i=T stands for ignore.case=TRUE (thanks to partial matching of argument names), which makes gsub case insensitive.
Usage:
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
Min svävare är full med ål
[1] "MoMinon sosvovävovarore äror fofulollol momedod ålol"
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
hello
[1] "hohelollolo"
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
hElLo
[1] "hohElolLoLo"

<>< (Fish), 64 bytes
>" oieauåäöOIEAUÅÄÖ"0i:1+?!;01.
 :&=?\     l?!v&
^[0o&<&o"o"o:&<

It's not the shortest answer but I enjoy the challenge of programming in <><
Try it out here

golflua, 36 bytes
B=I.r():g("[^aeiou%W ]","%1o%1")w(B)

Simple pattern-matching: take stdin, then find the non-vowels (%W takes care of non-alphanumeric chars) & insert an o between the two replacements. Sadly, doing all this within the write (i.e., w(I.r():g(....))) also output the count of insertions, though it saved 3 chars. A Lua equivalent would be
line = io.read()
rovar = line:gsub("[^aeiou%W ]","%1o%1")
print(rovar)

REXX, 107 bytes
parse arg s
v='aeiouåäö '
o=
do until s=''
  parse var s l 2 s
  if verify(l,v)>0 then l=l'o'l
  o=o||l
  end
say o

"MoMinon sosvovävovarore äror fofulollol momedod ålol"

Japt v2.0a0, 7 bytes
r\c_+io

Try it

Haskell, 75 bytes
x n|elem n[x|x<-['B'..'z'],notElem x"EIOUaeiou"]=[n,'o',n]|1<2=[n]
f=(>>=x)

This is a slight improvement on nimi's answer (unfortunately I can't comment yet) which uses a "clever" way to generate a list of consonants ([x|x<-['B'..'z'],notElem x"EIOUaeiou"]) that saves 6 bytes over just listing them out.
In this case ['B'..'z'] expands to "BCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz".
While some non-letter characters are included in the list of consonants, these don't include any punctuation or spaces so it should work for any regular sentence.
Usage: f "Hello there!" -> "HoHelollolo tothoherore!".


text:
Implement a Variable Length Hash
My friend and I have this game that we play with words. It is a fun pastime and it involves "canceling out" letters in a word until there is nothing left. I am really tired of him being so much faster than me at it, so it is your job to implement it and let me finally beat him. Obviously, since I have to make the program as easy to hide as possible, it has to be small as possible.
How does this game work?
The game is a pretty simple algorithm. It reduces a alphabetical string until it can't be reduced any further, thus making it a sort of hash. The actual game that we humans do is very hard to implement, but it can be simplified into the following algorithm:
You start by folding the alphabet in half and lining up the two pieces like such:
a b c d e f g h i j k l m
z y x w v u t s r p q o n

Then, starting from the middle, you assign the positive integers to the top half and the negative to the bottom:
a  b  c  d  e f g h i j k l m
13 12 11 10 9 8 7 6 5 4 3 2 1

z   y   x   w   v  u  t  s  r  p  q  o  n
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Then you take your string (we will be using hello world) and ignoring any non-alphabetical characters, translate it:
h e l l  o w   o  r  l d
6 9 2 2 -2 -10 -2 -5 2 10

Then you sum the letter values. The ones that lined up in the earlier diagram (e.g. d and w, l and o) will cancel out, while the others will add up.
sum(6 9 2 2 -2 -10 -2 -5 2 10 )=12

12 is the number for b, so the hash of hello world is b
For a word that completely cancels out (e.g. love), you output the "0 character": -. Note that in the input, - will still be disregarded. It only matters in the output.
If the number's magnitude is larger than 13, then you start doubling up on the a's and the z's You basically take as many a's or z's fit into the number and take whatever is left into the last letter like so:
code golf: 43.

Fits 3 a's and has 4 left over:
aaa 4: j
result: aaaj

Hint: This part is basically divmod except that it rounds toward zero, not -infinity (e.g. -43 would become 3 z's and and a -4 which is p so zzzp).
Note: the dash does not come if the a's or z's fit in perfectly, only if it is exactly 0.
Clarifications:

The hash is case insensitive
Standard Loopholes are not allowed
I/O can be in any format that isn't too outlandish, stdin, stdout, command-line arg, function, etc.
This is code-golf so shortest size in bytes wins.

Examples:
hello world  -->  b

love  -->  -

this is an example -->  aak

hello *&*(&(*&%& world  -->  b

good bye --> ae

root users --> zzs

love is empty...

Pyth, 79 78 77 65 61 58
J+\-GK+0fTr13_14=ZsX@JzJKMe,pk*G/H13%H13@JxK?g\aZ>Z0_g\z_Z

You can use @Jz instead of f}YJz There's probably more, but I must sleep now. Good luck ;)

@FryAmTheEggman Cool, I wasn't aware of the intersection of @!

CJam, 46 bytes
Try it online, or try the test suite online.
lel{'n-_W>+_zE<*}%:+{_De<C~e>___0>-'n+'-?o-}h;

Explanation
The algorithm works how you might expect: read the input, convert to lowercase, map each character to a value, sum the values, and print characters and adjust the sum accordingly until the sum is zero. Probably the most interesting optimization (although it only saves two bytes) is that negated character mappings are used instead, as this avoids swapping subtraction arguments to correct the sign when computing the mapped value and avoids swapping again when mapping back to a letter due to the subtraction of a negated value being replaceable by addition.
lel             "Read a line of input and convert all letters to lowercase.";
{               "Map each character:";
  'n-_W>+         "Map each character to its negated value by subtracting 'n'
                   and incrementing if the result is nonnegative.";
  _zE<*           "If the value is out of the letter range, use 0 instead.";
}%
:+              "Compute the sum of the mapped character values.";
{               "Do...";
  _De<C~e>        "Compute the sum clamped to the letter range.";
  __              "If the clamped sum is nonzero, ...";
  _0>-'n+         "... then produce the clamped sum mapped back to a letter by
                     decrementing if it is positive and adding 'n', ...";
  '-              "... else produce '-'.";
  ?
  o               "Output the character produced above.";
  -               "Subtract the clamped sum out of the sum.";
}h              "... while the sum is nonzero.";
;               "Clean up.";

Clip 10, 87
Fr+`m[y?cAyg#Ay-v,-RRZ]0]}m.U`[Fx?x?<x0,:-/xR'z*m'm%xR!!%xR],:/xR'a*m'n%xR!!%xR]]'-[R13

R, 258 bytes
function(s){a=13;r=data.frame;z=strsplit(gsub("[^a-z]","",tolower(s)),"")[[1]];d=r(l=rev(letters),h=c(-1*a:1,1:a));m=merge(r(l=z),d);n=sum(m$h);q=abs(n);v=rep(ifelse(n>0,"a","z"),q%/%a);paste0(paste(v,collapse=""),d$l[d$h==sign(n)*q%%a],ifelse(n==0,"-",""))}

This has to be the grossest R code ever. I figured R might be a decent choice since it has a vector of all letters "a" through "z" as a built-in global variable. But it turns out the rest is a mess.
Ungolfed + explanation:
function(s) {
    a <- 13              # Store the value associated with a
    r <- data.frame      # Store the `data.frame` function

    # Split the input into a vector, ignoring case and non-letters
    z <- strsplit(gsub("[^a-z]", "", tolower(s)), "")[[1]]

    # Create a data frame where the first column is the letters
    # z through a and the second is the associated scores
    d <- data.frame(l=reverse(letters), h=c(-1*a:1, 1:a))

    # Merge the split vector with the data frame of scores
    m <- merge(data.frame(l=z), d)

    # Get the total score for the input
    n <- sum(m$h)
    q <- abs(n)

    # Pad the output with a or z as necessary
    v <- rep(ifelse(n > 0, "a", "z"), q %/% a)

    # Collapse the vector of a's or z's into a string
    out1 <- paste(v, collapse="")

    # Look up the letter associated with remainder
    out2 <- d$l[d$h == sign(n)*q%%a]

    # If n = 0, we still want a dash
    out3 <- ifelse(n == 0, "-", "")

    # Return the concatenation of all pieces of the output
    paste0(out1, out2, out3)
}

This creates an unnamed function object that accepts a string as input and returns the associated hash value. To call it, give it a name, e.g. f=function(s){...}.
Examples:
> f("this is an example")
[1] "aak"

> f("root users")
[1] "zzs"

> f("love")
[1] "-"

> f("People like grapes.")
[1] "aaag"

Try it online!
Questions? I'll happily provide any further explanation. Suggestions? Suggestions are more than welcome!

Haskell, 171 bytes
import Data.Char
m=13
l=zip['a'..'z'][-i|i<-[-m..m],i/=0]
p 0="-"
p n|n>m='a':p(n-m)|n<(-m)='z':p(n+m)|1<2=[c|(c,i)<-l,i==n]
f n=p$sum[y|Just y<-[lookup(toLower x)l|x<-n]]

Test run:
> map f ["hello world", "love", "this is an example", "hello *&*(&(*&%& world", "good bye", "root users"]
["b","-","aak","b","ae","zzs"]

How it works: l is a lookup table from letters to the corresponding value. Lookup all characters from the input string and discard those not found. Sum the resulting list. Depending on the sum p prints - or maybe first some as or zs and finally (reverse-)lookups the letter from l.

R - 200
function(s){l=letters
N=setNames
x=strsplit(tolower(s),'')[[1]]
n=(13:-13)[-14]
v=sum(N(n,l)[x[x%in%l]])
o=''
while(v){d=min(max(v,-13),13)
o=paste0(o,N(l,n)[as.character(d)])
v=v-d}
if(o=='')o='-'
o}

+1, definitely better than my R answer. Nice work!


text:
Decode a Rövarspråket string
This question is the inverse of this one by James Williams.

Rövarspråket
Rövarspråket is a word game played by Swedish children, from the books about Kalle Blomkvist by Astrid Lindgren.
The basic rules used during encoding are as follows (from Wikipedia):

Every consonant (spelling matters, not pronunciation) was doubled, and
an o was inserted in-between.
Vowels were left intact.

A few examples of decoding:

"hohelollolo" -> "hello"
"MoMinon sosvovävovarore äror fofulollol momedod ålol" -> "Min svävare är full med ål"

Swedish consonants are the same as the English ones, so the program should work with both Swedish and English entries.
The letter "y" is taken as a consonant in this case - as most of the time it is.

Your Task:
Write a program to convert a Rövarspråket string of Swedish letters, inputted through a function or through stdin, into its decoded equivalent.  Shortest answer in bytes wins!

Are uppercase letters treated the same way as their lowercase counterparts? e.g. does HOHELOLLOLO become HELLO?

In the case of a function, should results be returned, printed to stdout/closest alternative, or either?

@AlexA. I think any of those are fine.

@MartinBüttner Oops, no, caught me. It should indeed be HoHELoLLoLO.

@Sp3000 Sorry, I was mistaken, the os in the middle must be lowercase. So HOHELOLLOLO is not a valid input. If the input is invalid your program is allowed to do whatever, it will only be tested for valid inputs.

Wouldn't HOHELOLLOLO then return itself because there are no lowercase o?

Retina, 19 + 2 = 21 bytes
Retina strikes again! The code for this program consists of two files:
i`([b-z-[eiou]])o.

$1

This reads the input on STDIN and prints the output to STDOUT.
If you call the files pattern.rgx and replacement.rpl, you can run the program simply like
echo "hohelollolo" | ./Retina pattern.rgx replacement.rpl

Explanation
As for the previous answer, if Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.
Retina can be configured (which includes RegexOptions and other options) by prepending the regex with ` and a configuration string. In this case I'm only giving it i which is the normal regex modifier for case insensitivity.
The pattern itself is a bit more interesting this time. It still uses .NET's character class subtraction to match any consonant in the ASCII range, but then it also matches the following o as well as the character after it (i.e. the copy of the consonant). The replacement then just writes the captured consonant back.
You might be wondering why this is not ambiguous in a case like lololol -> lol. The trick is that matches cannot overlap and are always found from left-to-right. So whenever I encounter a consonant, I include the next two character in the match and replace all of them - the search continues after this. It's quite easy to convince yourself that this kind of greedy algorithm will always decode the input correctly. In fact the pattern could even have been
i`([b-z-[eiou]])..

Julia, 61 43 bytes
t->replace(t,r"(?![eiou])[b-z]o."i,s->s[1])

This creates an anonymous function which accepts a string as input and returns the inverse Rövarspråket transformation of the string. It's the exact inverse of my Julia answer to the Rövarspråket challenge. To call it, give it a name, e.g. f=t->....
The replace() function is doing all of the work here. The first argument is the input string, the second is a regular expression pattern (which in Julia is given as a string preceded by r), and the third is the replacement.
For the regex, we're matching all pairs of consonants separated by an "o". For the replacement, we're taking the match and extracting only the first character, which is the consonant.
Examples:
julia> f("hohelollolo")
"hello"

julia> f("MoMinon sosvovävovarore äror fofulollol momedod ålol")
"Min svävare är full med ål"

Questions? Just let me know. Suggestions? Very welcome as always!

Edit: Saved 18 bytes thanks to Martin Büttner!

@MartinBüttner: Has anyone told you recently that you're awesome?

I've read something on meta. ;) (And +1 for using Julia!)

Btw, you can save two more bytes by mimicking character class subtraction with a lookahead: (?![eiou])[b-z]o. (I think this also goes for a lot of answers on the original challenge.)

@MartinBüttner: I think meta did a good job of getting the point across. :) And thanks for the support! I've been using Julia for a couple years and I try to use it around PPCG whenever I can. It's a good way to learn new things. Also, thanks once again!!

Sed, 13, 15, 16, 28
s/\([^äöåaeiou]\)o\1/\1/g

Run it like this:
echo MoMinon sosvovävovarore äror fofulollol momedod ålol | sed 's/\([^äöåaeiou]\)o\1/\1/g'

Output:
Min svävare är full med ål

I would consider -r part of the bytecount, just like a Python solution has to count re.sub.

Your solution fails for ooo, which incorrectly gets decoded to o. It should stay ooo.

@Thor: No Swedish words have to contain "ooo" for "o" to be invalid output because the Rövarspråket-transformed words aren't constrained to be actual Swedish words.

orlp and AlexA: You are correct, I will use a non-vowel group instead.

Java, 47
Use as a lambda function. Works the exact same way as Martin's answer.
a->a.replaceAll("(?i)([b-z&&[^eiou]])o.","$1");

Try here

Pyth, 27
VzJ:zZhZpkJ~Zhy}rJ0-G"aeoui

JavaScript (ES6), 46
This turns out to be some language-specific sintax around a regexp.
ES6 is quite short. Too bad we miss subtraction
F=s=>s.replace(/([b-df-hj-np-tv-z])../gi,'$1')

Mathematica, 36 bytes
Roughly uses the strategy in my previous answer.
StringReplace[#,a_~~"o"|"O"~~a_:>a]&

Explanation:

"o"|"O" matches the lettter O insensitively.
a_~~*..*~~a_:>a matches any character a followed by an O followed by a again, and replaces it with a.
Finally, StringReplace[#,*..*]& creates a pure function applying that rule to every matching sequence in its argument.

PHP - 65 66
$s=$argv[1];echo preg_replace("/([^aeiou])o([^aeiou])/i","$1",$s);

I don't think this is going to work correctly with ä, ö and å or upper case vowels.

It works for upper case, But yes not for other characters you mentions. It strictly for english only alphabets.

@MartinBüttner, You comment is correct. I copied another version do not have case insensitive (/i) modifier. However my code is still run on local with out this modifier for some unknown reasons. Still i added a "i". One more byte.

Python, 61
The inverse is conveniently is the same length as the original.
import re;g=lambda s:re.sub('(?i)(?![eiou])([b-z])o.',r'\1',s)

Or alternatively:
import re;g=lambda s:re.sub('(?i)(?![eiou])([b-z])o.','\\1',s)

Run it here: http://repl.it/f3N

JavaScript 65
function R(x){return x.replace(/([bcdfghj-np-tv-z])o\1/gi, "$1")}

JavaScript ES6, 108 bytes
F=s=>{
  for(n='',i=0;i<s.length;n+=c)c=s[i],i+=~'bcdfghjklmnpqrstvwxyz'.indexOf(c.toLowerCase())?3:1
  return n
}

To make this interesting, I tried to do this entirely without regular expressions, which is why it is so long. It works by iterating over the string, copying each letter over to a new string. If it encounters a consonant, it skips the next two letters, which would be o + that letter. Use the snippet for a GUI alert and ES5.

F=function(s){for(n='',i=0;i<s.length;n+=c)c=s[i],i+=~'bcdfghjklmnpqrstvwxyz'.indexOf(c.toLowerCase())?3:1
return n}

alert(F('hohelollolo')+'\n'+F('MoMinon sosvovävovarore äror fofulollol momedod ålol'))

QuadR, 15 bytes
([^aeiou])o.
\1

Try it online!
PCRE Replace…
([^aeiou])o. non-vowel (and call this the first capturing group), "o", any character
 with…
\1 the first capturing group