text:
Insta-Name... Just Add Coder!
In the English language, a surefire way to make a pronounceable nonsense letter combination is to make it entirely out of consonant-vowel pairs, e.g., Wu ko pa ha, or, Me fa ro, consonant first, followed by vowel.
Challenge:
Write a program or function that will, given a user-specified number of letters, create a random name using this principle. It's that simple.
Input:
An integer greater than or equal to 2 which designates the required number of letters in the output. Input can be taken from STDIN, command line arguments, or function arguments.
Output:
A string of the given length containing randomly selected consonant-vowel pairs. It can be printed to STDOUT or closest alternative or returned in the case of a function.
Rules:

Each consonant of the English alphabet should have equal probability of being selected for the first character of each pair, and each vowel of the English alphabet should have equal probability of being selected for the second character of each pair.
Letter pairs may be repeated.
Since this is a name, the first letter must be capitalized.
If the input is odd, a randomly selected letter pair in the name should have y or h appended to the end. The choice of y or h should be random as well.
Standard loopholes are not permitted.
Smallest code in bytes wins.

Letter definitions:
Consonants:
bcdfghjklmnpqrstvwxyz

Vowels:
aeiou

Example I/O:
Input: 6
Output: Mefaro

Input: 9
Output: Wukohpaha

Enjoy!

And by the way, welcome to Programming Puzzles and Code Golf.SE :)

I think my new format is more clear. Is it? @trichoplax

I post all my potential questions in the sandbox where they can get plenty of feedback before posting here. It makes things easier - I recommend it for future questions.

Thanks, @alex, Since this is my first question, I now know some  good technique on how to use this site. I have learned a lot, and I hope my next question will be better!

I'll try my best to clear everything up with no major edits on my next question

Thanks for everyone who as helped me make this question the best it can be, I didn't know sandbox was a thing, but will use it in the future. the edits are great@AlexA.

How come an input of 9 gives Wukohpaha and not Wukopahah?

an input of 9 should give Wukopahah, @ASCIIThenANSI, I fixed that minor error

@ASCIIThenANSI Per rule #4, a randomly selected letter pair will get a y or h. In that example, it was ko that got the h, not ha. jman: If that's not what you had in mind, better modify the rules quick before more answers start coming in!

@AlexA. Ah, OK. I saw it as "getting appended to the end of the word".

I changed my edit back. I like your way better, Alex.

Pyth, 33 bytes
rsXOtQmO*-GJ"aeiou"J/Q2*%Q2O"hy"4

Demonstration.

JavaScript ES6, 187 180 168 bytes
f=l=>{r=m=>Math.random()*m|0
d=l%2&&r(--l/2)*2+1
for(s='';l--;s+=s?a:a.toUpperCase())a=l%2?'bcdfghjklmnpqrstvwxyz'[r(21)]:'aeiou'[r(5)]+(l==d-1?'hy'[r(2)]:'')
return s}

Edit: I switched from using regex replace to a simple for loop, which improved the length considerably. Ungolfed code and test UI below. Input a negative number at your own risk because it makes an infinite loop. (Thanks to unclemeat for pointing that out.)

f=function(l){
  // Function to return a random integer between 0 and m-1 inclusive
  r=function(m){
    return Math.random()*m|0
  }
  // d is the position the h or y will be added
  // l is decremented only if l is odd so an extra consonant won't be added to the end
  d=l%2&&r(--l/2)*2+1

  for(s='';l--;){
    a=l%2?'bcdfghjklmnpqrstvwxyz'[r(21)]:'aeiou'[r(5)]+(l==d-1?'hy'[r(2)]:'')
    // If `s` is empty (i.e. this is the first leter), make it uppercase
    s+=s?a:a.toUpperCase()
  }
  return s
}

run=function(){ip=parseInt(document.getElementById('input').value);if(ip<2)return alert('Input must be greater than one.');document.getElementById('output').innerHTML=f(ip)};document.getElementById('run').onclick=run;run()
<input type="number" id="input" value="7" min="2" /><button id="run">Run</button>

Note: Do not put a negative number into the test UI..

SWI-Prolog, 286 285 bytes
a(I):-a(I,[]).
a(I,R):-(I=1,r(1,K),nth0(K,`hy`,V),length(R,L),random(1,L,W),nth0(W,[O:P|Q],V:0xFEFF,R);I=0,[O:P|Q]=R),N is O-32,p([N:P|Q]);r(5,A),nth0(A,`aeiou`,X),r(21,B),nth0(B,`bcdfghjklmnpqrstvwxyz`,Y),J is I-2,a(J,[Y:X|R]).
p([A:B|R]):-put(A),put(B),p(R);!.
r(I,R):-random(0,I,R).

Example: a(13). outputs Leqihsekeqira.
Note: You might need to replace the ` with " if you have an old version of SWI-Prolog.

Pyth, 52 42 bytes
V/Q2=k++kO-GJ"aeiou"OJ;rs.SXZck2*%Q2O"hy"4

You can try it in the online compiler here.
Thanks to Jakube for golfing it down further, NinjaBearMonkey for clarifying the challenge, and issacg for creating Pyth and inadvertently teaching me about X.
This program randomly selects a consonant and a vowel to fill the string, adds 'h' or 'y' to one pair if the input is odd, then capitalizes the first character. Here is the breakdown:
V/Q2                                              For N in range(1, input/2):
    =k                                            Set k to:
        k                                         k (defaults to ""),
       + O G                                      plus a random letter from the alphabet...
          - J"aeiou"                              without the vowels,
      +             OJ                            plus a random vowel
                      ;                           End the loop
                             ck2                  Chop k into strings of length 2
                           XZ                     Append to the first string:
                                    O"hy"         'h' or 'y' picked at random,
                                *%Q2              repeated input mod 2 times
                         .S                       Shuffle the strings
                        s                         Convert them back to a single string
                       r                 4        Capitalize and print the string

It seems inefficient to append 'h' or 'y' to the first consonant-vowel pair and then scramble the list. I tried appending to a random pair but the code was always longer than this.

Pyth, and the coders who know it, always amaze me.

Just a few tricks: rX1 capitalizes X. t is the same thing as _P_.

You can remove the assignment to J, since you use J only once.

I think this adds h or y to the end, not a randomly selected pair.

@Jakube Thanks once again for your help!

@NinjaBearMonkey You're right, it does add y or h to the end of the word, not a random letter pair. I had misread the rules and will fix it shortly.

Perl, 253 238 bytes
@c=split"","bcdfghjklmnpqrstvwxyz";@v=split"","aeiou";@t=();chomp($n=<>);for(1..$n/2){$l=$c[$$=rand(21)];if($_<2){$l=uc$l};push@t,$l.$v[$$=rand(5)]};$x=0;$y=int(rand(@t));for(@t){print;if($x==$y&&$n%2>0){print qw(h y)[int(rand(1))]};$x++}

I can probably golf it further, but this should do for now.
Changes:

Saved 10 bytes by myself, and 5 thanks to Alex A.

Julia, 141 bytes
n->(R=rand;r=isodd(n)?R(1:n÷2):0;ucfirst(join([string("bcdfghjklmnpqrstvwxyz"[R(1:21)],"aeiou"[R(1:5)],i==r?"yh"[R(1:2)]:"")for i=1:n÷2])))

This creates an unnamed lambda function that accepts an integer as input and returns a string. it takes advantage of the fact that strings in Julia can be indexed and referenced like character arrays. To call it, give it a name, e.g. f=n->....
Ungolfed + explanation:
function f(n)
    # There will be n÷2 consonant-vowel pairs
    p = n ÷ 2

    # Determine which pair will get a y or h, if any
    r = isodd(n) ? rand(1:p) : 0

    # Consonants and vowels
    c = "bcdfghjklmnpqrstvwxyz"
    v = "aeiou"

    # Randomly select letters for pairs, appending y or h as needed
    s = [string(c[rand(1:21)], v[rand(1:5)], i == r ? "yh"[rand(1:2)] : "") for i in 1:p]

    # Join s into a string and convert the first letter to uppercase
    ucfirst(join(s))
end

Examples:
julia> f(9)
"Luyvunize"

julia> f(2)
"Fe"

julia> f(16)
"Pahonapipesafuze"

Python 2, 148 169 156
from random import*
I=input()
R=choice
i=I/2
S=[R('hybcdfgjklmnpqrstvwxz')+R('aeiou')for _ in[0]*i]
if I%2:S[R(range(i))]+=R('hy')
print ''.join(S).title()

Edit: Realized it didn't capitalize the first letter. Ill see if I can golf it back down tomorrow.
Edit 2: Remembered .title but I think that will be it.

If only strings supported item assignment...

Marbelous, 203 bytes
}0}0@1
>>^0&1
--=0@1FF
??&0}0&0
&1
qqqqqq\\\\
//\\pppppp
:p
0000
?K\\?4..}2
<G++<4+5=0\/}0
<B++<3+5?111>1!!
<6++<2+3Mult-2
<3++<1+3+7}2{<
++//mm//mm--
mm..{1..{2{>
{0
:q
}2{2}0
pppppp{0{1
-W
:m
}061
{0{0

Test it out here (online interpreter). Input via arguments. Libraries and cylindrical boards must be enabled.
Commented/readable version:
}0 }0 @1 .. .. # 1st column: generate a number from 0 to length/2-1, wait on &1
>> ^0 &1 .. .. # 2nd column: check bottom bit; if zero activate &1, otherwise &0
-- =0 @1 FF .. # FF (wait on &0): if no h/y, set counter to 255 (0xFF)
?? &0 }0 &0 .. # Send copy of full length to :q
&1 .. .. .. ..
qq qq qq \\ \\ # Call :q with counter and length
// \\ pp pp pp # Output of :q falls into :p, which is called repeatedly until done

:p                      # prints a consonant/vowel pair, and h/y if needed
00 00 .. .. .. .. .. .. # two zeros, to be passed into ?K and ?4
?K \\ ?4 .. }2 .. .. .. # pass through ?K (0-20 = consonants) and ?4 (0-4 = vowels)
<G ++ <4 +5 =0 \/ }0 .. # 1st/2nd column: add 1-4 to skip vowels
<B ++ <3 +5 ?1 11 >1 !! # 3rd/4th column: add 3/6/11/16 to create nth vowel
<6 ++ <2 +3 Mu lt -2 .. # 5th/6th column: if counter is 0, generate either h or y
<3 ++ <1 +3 +7 }2 {< .. # 7th/8th column: if length left to print is 0-1, terminate
++ // mm // mm -- .. .. # mm: add 'a'. 1st/2nd start at 'b' (++)
                        #              5th/6th start at 'h' (+7)
mm .. {1 .. {2 {> .. .. # output consonant, vowel, h/y to {0, {1, {2
{0 .. .. .. .. .. .. .. # left input (length left): -2 + output to left
                        # right input (counter until print h/y): -1 + output to right

:q             # calls :p, but with the first letter capitalized
}2 {2 }0 .. .. # {2 is an unused output which prevents exit when all outputs are filled
pp pp pp {0 {1 # call :p, and forward return outputs to MB to start loop
-W .. .. .. .. # subtract W (0x20) from the first letter = capitalize it

:m    # add 0x61 ('a')
}0 61
{0 {0 # input + 0x61 is returned

This is roughly equivalent to the following pseudocode (random(a,b) generates numbers between a and b inclusive):
main(length)
    if length & 0x01 == 0 then
        counter, length_left = q(0xFF, , length)
    else
        counter, length_left = q(random(0, (length >> 1) - 1), , length)
    end
    while true do
        length_left, counter, consonant, vowel, hy = p(length_left, , counter)
        print consonant, vowel, hy
    end
p(length_left, , counter)
    if length_left <= 1 then terminate_program end
    consonant = random(0, 20)
    switch consonant
        case >16: ++consonant
        case >11: ++consonant
        case >6:  ++consonant
        case >3:  ++consonant
    ++consonant
    consonant = m(consonant)
    vowel = random(0, 4)
    switch vowel
        case >4: vowel += 5
        case >3: vowel += 5
        case >2: vowel += 3
        case >1: vowel += 3
    vowel = m(vowel)
    if counter == 0 then
        hy = random(0, 1) * 0x11
        hy += 7
        hy = m(hy)
    return length_left - 2, counter - 1, consonant, vowel, hy
q(counter, , length_left)
    length_left, counter, consonant, vowel, hy = p(length_left, , counter)
    print consonant - 0x20, vowel, hy
    return counter, length_left
m(number)
    return number + 'a'

SmileBASIC 2 (Petit Computer), 197 177 bytes
CONTEMPORARY EDIT MAY 2018: This was my first submission ever, nearly 3 years ago! My skills have improved a lot since then; -20 just from minor adjustments.
It starts with a prompt (it's left blank to save bytes, so it's just a ?) where you put in the length (stored in variable L).
C$="bcdfgjklmnpqrstvwxzhyaeiou"INPUT L
J=0 OR L/2K=-1IF L%2THEN K=RND(J)
FOR I=0TO J-1?CHR$(ASC(MID$(C$,RND(21),1))-32*!I)+MID$(C$,RND(5)+21,1)+MID$(C$,RND(2)+19,1)*(K==I);
NEXT

I'm sure participating with an obscure BASIC language is gonna get me nothing but weird looks, but I managed to make it pretty small for BASIC. It takes advantage of SB's weird quirks (like conditionals evaluating to 1 or 0 since there's no boolean type) to eliminate as many bytes as I possibly could have when I wrote this at 3AM.

Ruby, 119 bytes
13 bytes for capitalizing...
->n{z=(0...n/2).map{([*(?a..?z)]-v=%w[a e i o u]).sample+v.sample}
n.odd?&&z[rand n/2]+='yh'[rand 2]
(z*'').capitalize}

Usage:
f=
->n{z=(0...n/2).map{([*(?a..?z)]-v=%w[a e i o u]).sample+v.sample}
n.odd?&&z[rand n/2]+='yh'[rand 2]
(z*'').capitalize}

2.upto(20) do |i|
  puts f[i]
end

Output:
Qo
Gah
Gilu
Baygu
Tevaba
Rohyori
Jigupadi
Diguvareh
Bidifenaji
Xohsuyileze
Depixoyizili
Boqizurejupiy
Buhuboketedasa
Vuwuhojetayduno
Forigikedawojawe
Qacetihxiheciyaju
Zoqigafukedugusoku
Bavuhlarofetucebapi
Zusiraxoxureqimavugo

Ruby, 316 238 216 chars
v=%w{a e i o u};c=[];(?a..?z).map{|i|v.include?(i)||c.push i};combos=[];c.map{|i| v.map{|j| combos.push i+j}};i=gets.to_i;o="";(i/2).times{o+=combos.sample};if i%2==1;(rand(4)==1?o+=?y:o+=?h); end; puts o.capitalize;

Odd number combos end in h or y.
Thanks to @blutorange for a complete dictionary of ruby golfing tips.
Whoa, I shortened my code by 100 chars.

The extra combos are unnecessary. I think some of the whitespace in there is unnecessary as well. Maybe take a look at some tips for golfing in Ruby to help shorten your code. Also, does this take input?

Yes, it takes input, the extra combos were neccessary for extra points before the question got redone, and I thought they would still work. j was a typo.

Just a few tricks with ruby: for i in ?a..?z;...;end can be replaced with (?a..?z).map{...}; The then after if is optional. v.include?(i)||c.push(i) is short for unless v.include?(i);c.push(i). Use c<<i for c.push(i). c.map{} is shorter than c.each{}. i%2==1?1:2 is short for if i%2==1;1;else;2;end. The print "Enter..." is not needed in codegolf ; )

C, 219 characters
Seems to work, I'm still new to this.
char o[]="aeiouqwrtypsdfghjklzxcvbnm";n,i=0;main(int h,char**v){n=atol(v[1]);srand(time(0));h=n%2;for(;i<n-n%2;i+=2)printf("%c%c%c",o[rand()%21+5]-(i?0:32),o[rand()%5],(rand()%(n-1)<(i+2)&h)?h=0,'h'+(rand()%2?17:0):0);}

You need rand()%(n-1-i)<2 instead of rand()%(n-1)<(i+2) to get a uniform distribution, unless you generate this random number only once and save it somewhere.

Is each character a byte, or how many bytes it it?

@jman294 Because the ASCII alphabet uses 8 bits per character, a character is one byte. You only really need to use bytes if you are using non-ASCII characters like `` which uses more than one byte.

R, 166 bytes
Takes input from STDIN and outputs to STDOUT.
l=letters;s=sample;n=scan();v=c(1,5,9,15,21);o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));o[1]=toupper(o[1]);cat(o,sep='')

Explanation
# Alias letters and sample
l=letters;
s=sample;
# Get input
n=scan();
# Vowel positions
v=c(1,5,9,15,21);
# Create a matrix with a row of
# consonants and a row of vowels
o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));
# If odd paste either h or y to a vowel
if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));
# Upper case first letter
o[1]=toupper(o[1]);
# Output
cat(o,sep='')

Some tests
> l=letters;s=sample;n=scan();v=c(1,5,9,15,21);o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));o[1]=toupper(o[1]);cat(o,sep='')
1: 13
2:
Read 1 item
Vetigiysurale
> l=letters;s=sample;n=scan();v=c(1,5,9,15,21);o=rbind(s(l[-v],i<-n/2),s(l[v],i,T));if(n%%2)o[a]=paste0(o[a<-s(i,1)*2],s(c('h','y'),1));o[1]=toupper(o[1]);cat(o,sep='')
1: 12
2:
Read 1 item
Mucowepideko

K5, 131 bytes
{r:(`c$-32+c@1?#c),{*d@1?#d:(v;(c::(`c$97+!26)^v::"aeiou"))@2!x}'1+1_!x;$[x=p:2*_x%2;r;,/(*w),("yh"@1?2),*|w:(0,2+2**1?_(#r)%2)_r]}

This will NOT work on Kona or kdb+; you need to use a K5 interpreter like oK.
Live demo. (Try setting the 5 at the end to a different number to try different inputs.)

Perl 5, 112 bytes
@;=map{(grep aeiou!~$_,a..z)[rand 21].(a,e,i,o,u)[rand 5]}1..$_/2;$_%2?$;[rand@;].=time%2?h:'y':0;$_=$"^join"",@

Try it online!


text:
Brainf**k to Unary and Back
A language that is very useful in restricted source and other such challenges is Unary, a brainfuck derivative in which programs are written in with only one character. Your job is to write a program to convert programs from brainfuck to unary and a program to do the opposite, both programs in the same language. Your score will be the sum of the lengths of the two programs.
How do you convert from brainfuck to Unary?

First convert your brainfuck code to binary according to this table:

Brainfuck
Binary

>
000

<
001

+
010

-
011

.
100

,
101

[
110

]
111

Now concatenate the code into one giant binary number in order of the code.

Prepend a 1 to the string to ensure a unique binary number.

Convert from a binary number to a unary number using any character.

Example:
+.

would become
000000000000000000000000000000000000000000000000000000000000000000000000000000000000

which is 84 zeroes.

brainfuck → Unary specification:

Since the resulting programs will be impossibly huge, print not the actual program but merely the length of the resulting program.
Take the brainfuck program as a string through stdin, function arg, etc and output the length.
The program will always be valid and have only those 8 chars in it.

Unary → brainfuck specification:

You will have to implement the reverse of the above algorithm.
Again because of the huge sizes in question, the input will be a number describing the length of the Unary code.
Same I/O rules as always.
The program will always be valid and have only those 8 chars in it.

Test Cases

Hello World:
++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+.

becomes:
239234107117088762456728667968602154633390994619022073954825877681363348343524058579165785448174718768772358485472231582844556848101441556`

Fibonacci:
++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++>++++++++++++++++>>+<<[>>>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[<+>-]>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<.>.>>[>>+<<-]>[>+<<+>-]>[<+>-]<<<-]<<++...

becomes:
13067995222095367150854793937817629722033205198624522624687536186118993888926522550140580142585590431635487113180955099384652678100247403485397450658564826143160529351955621991895221530908461364045400531236124980271740502887704217664044858614821622360156740992393765239123681327824577149595724956207165558106099868913919959549896553103116795519592552089266360725543244154867904980260

This is code-golf so the shortest code in bytes wins!
Anyone up for a solution in Unary? ;P

A more appropriate title would probably be "Brainfuck to Golunar and Back"

@Sp3000 good point, but I think that most people haven't really heard of it that one (myself included).

@Maltysen I don't think your test cases are correct. For instance, the leading digits of the first number in binary are 10101010101010, when they should be 1010010010010

@isaacg sorry, got them off a website that was using a different translation mechanism, will fix.

Can we convert them to a program which isn't exactly equal, but does exactly the same thing?

Presumably you want the length in decimal right? Because otherwise, the binary representation of the Brainfuck program pretty much is a number describing the length of the program in Unary. (Though you have to prepend a 1 to it first.)

Since this is a pure [tag:code-golf] it seems meaningless to submit an unary answer?

Pyth, 17 + 17 = 34 bytes
BF -> Unary, 17 bytes
i+1xL"><+-.,[]"z8

Unary -> BF, 17 bytes
s@L"><+-.,[]"tjQ8

brainfuck, 563 335 318 316 296 + 529 373 366 336 = 632 bytes
Since this was obviously missing a solution in a related language, here is the solution in brainfuck and Golunar. I couldn't post an answer in unary, because that would need a few fantasticatillion times more memory than there are atoms in the universe ^^
The "back" routine won't check if the Golunar/Unary code is valid. If the bit count mod 3 != 1 then it will run into an endless loop printing a lot of ">"s.
Thanks to Nitrodon for helping me getting below 300 chars for the bf to unary code
brainfuck to unary
->+>>>>,[>+++[>+++++<-]>[<+<---->>-]<<--[<+>++[<<+>>>[<+>-]<[<->++[<<<+>->+>-[<->--[<<+>>>+++++++++[<----->-]<[<+>--]]]]]]]>[-]>>,]<<<<+[<+]>[>]->+[<]>+[[->+]->[->[<++>-[<++>-[<++>-[<++>-[<-------->>[-]++<-[<++>-]]]]]]<[>+<-]+>>]<<[<<]>[<]>-[[->+]->>+<[<<]>[<]]>+]>[>>]<<[+++++++[>++++++<-]>.<<<]

Try it online!
and back
->>,[<++++++[>--------<-]+>>>>>>,]>->-<<<+[-<+]>[[->[->+<[->->+>]<[<<<]>]<+>>>[-<<+>>]<[>>>>++++++++++<<<<-]>>>]>>>+[->+]>-<+[-<+]-<[>>+[->+]-<++[-<+]-<[-]]<<<<<<[<<<<<]>>>>>>[<<]<[->>>]>>]>>>+[->+]<-<+[-[<++>-]<[<++>-]>+++[>+++++<-]>[<+<++++>>-]<<++<[>--<-[>>[<->-]<--<-[>++<-[>+<-[>--<-[>+[>+<-]>[<++>-]<+<-[>++<-]]]]]]]>.[-]>[-]<<<+]

Try it online!
Golunar/unary-digits, 509 303 288 286 268 + 478 337 331 304 = 572 bytes
brainfuck to unary
2845581296974449674357817038179762273623136917867627972159702240227366875240878616687779429553529795902322625321040063298921498529640547483869509829184440577052825434462245755576011912505085065586076069824710351537537205287083477698633592357950165322060367940923703887

and back
3775574485023133646619269732540391678811443648964274086227256847322821618228135493733703990523803451383315165001915937932498966394771849173263120467073642011339214182483748816052890450078070151307011943625602391238338941712116968736593594971620990210178757280976709140113340322124688909388916094040773207

Source codes
brainfuck to unary
[
unary:
><+-.,[]
01234567

62 > 62
60 < -2
45 - 15
43 + 2
44 , 1
46 . 2
91 [ 45
93 ] 2

tape (while reading input): Left tape end marker/LTE, [binary data], input, 15, (15 multiplicator)
tape (while base conversion): LTE, [binary data], Value Start/VS, [decimal digits]

decimal digits: digit used/DU, value
]

-                       set LTE
>+                      set leading 1
>>>>,[                  while input
  >+++[>+++++<-]        set 15 (multiplicator)
  >[<+<---->>-]         set 15 and decrease input by 60

                    check for greater than
                        set current bits = 000 (greater than)
  <<--[                 if input != 62 try next char

                    check for less than
  <+>                   set current bits = 001 (less than)
  ++[                   if input != 60 try next char

                    check for minus
  <<+>>                 set current bits = 011 (minus)
  >[<+>-]<[             if input != 45 try next char

                    check for plus
  <->                   set current bits = 010 (plus)
  ++[                   if input != 43 try next char

                    check for comma
  <<<+>->+>             set current bits = 101 (comma)
  -[                    if input != 44 try next char

                    check for dot
  <->                   set current bits = 100 (dot)
  --[                   if input != 46 try next char

                    check for left bracket
  <<+>>                set current bits = 110 (left bracket)
  >+++++++++[<----->-]<[   if input != 91 go to next char

                    use right bracket
  <+>                   set current bits = 111 (right bracket)
  --                    decrease input by 2 / should be 0 now

  ]]]]]]]               close all ifs
  >[-]>>                delete 15 if still existant
  ,                     input next character
]
<<<<+[<+]>[>]           add one to each bit and delete LTE (for shorter search routine)

                    Start of binary to decimal routine

-                       set value start marker (VS)
>+                      set digit used marker (DU)
[<]                     go to LTE

                    binary to decimal loop: use "double and add algorithm" to calculate the digits of the decimal value
>+[                     if not on VS then
  [->+]-                restore current bit value and go to VS
  >                     go to first DU
  [                     digit doubling loop
    ->                  remove DU and go to corresponding digit
    [
      <++>-             decrement current value and add 2 to temp value four times
      [
        <++>-
        [
          <++>-
          [
            <++>-
            [                   if value was greater than 4 then
              <---- ----        subtract 8 from temp
              >>[-]++           set next digit temp = 2 (DU plus 1)
              <-                decrement current digit
              [<++>-]           set temp = remaining value * 2
            ]
          ]
        ]
      ]
    ]
    <[>+<-]             set current digit = temp
    +                   set DU
    >>                  go to next digit
  ]                     end of digit doubling loop
  <<[<<]>[<]>           go to current bit
  -[                    if bit is 2 (used plus 1)
    [->+]-              delete bit and go to VS
    >>+                 increment least significant digit
    <[<<]>[<]           go to current bit
  ]
  >+                    if not on VS then repeat
]                   end of binary to decimal loop

>[>>]<                  go to most significant digit
<[                  printing loop: for each DU print corresponding value
  +++++++[>++++++<-]>.  add 48 to value (ASCII 0) and print
  <<<                   go to next DU
]

and back
[
tape: left tape end marker/LTE(-1), [digits], digit end marker/DE(0), carry, SB(-1), [binary data], 60, 15
digits: digit used marker/DU(1), digit, remainder, solution, 0
        else]                                    [exit else, exit if
binary data: value (, else, exit if, exit else)
]

                    input decimal value
->>                     set LTE
,[                      while input
  <++++++[>--------<-]  decrease input by 48
  +                     set DU
  >>>>> >,              input next digit
]
>->-                    set start of bits (SB) and first CCB
<<<+[-<+]>              delete LTE and go to first DU

                    division loop: calculate the remainders of the input divided by 2 repeatedly to get the (inverted) bits
[
                        divide each digit by 2
  [                     for each DU
    -                   delete DU (for exit if)
    >                   go to digit
    [->+<               dec digit / set remainder
      [->->+>]          if digit gt 0: dec digit / del remainder / inc solution / goto 0
                        pointer: (value(0) remainder is set) or (0 solution gt 1)
      <[<<<]            go to DU
      >                 go to digit
    ]
    <+                  set DU
    >>>[-<<+>>]         move solution to digit
    <[                  if remainder
      >>>>              go to next digit
      +++++ +++++       add 10 to digit/carry
      <<<<-             go back and delete remainder
    ]
    >>>                 go to next DU
  ]

                    append new bit
  >>>+[->+]             go to and delete CCB
  >-                    set new CCB
  <+[-<+]-<             go to carry
  [                     if carry
    >>+[->+]-<+         set last bit
    +[-<+]-<[-]         go to and clear carry
  ]

                    check if first digit became 0 / neccessary to check if value has been completely processed
  < <<<<<[<<<<<]>>>>>   go to first DU
  >[                    if digit gt 0
    <<                  go to exit if
  ]<[                   else
    -                   delete DU
    >>>                 go to exit else of next digit
  ]
  >>                    go to DU / DE if all digits processed
]                   end of division loop

                    decode binary values
>>>+[->+]               go to and delete CCB (after last bit)
<-                      delete leading 1
<                       go to first bit

                    Start of bit decoder
[
unary:
><+-.,[]
01234567

62 > 62
60 < -2
43 + -17
45 - 2
46 . 1
44 , -2
91 [ 47
93 ] 2

tape: start of bytes marker/SB(-1), [binary data], 60(print char/PC), 15
]

+[-                     while not SB

                    Set least significant to octal value of three bits
  [<++>-]               if first bit set add 2 to second bit
  <[<++>-]              for each second bit add 2 to third bit

  >+++[>+++++<-]        multiplier 15
  >[<+<++++>>-]         setup table 60 15

                    run through the 8 possibilities

                    0 greater than
  <<++                  set PC = 62 (greater than)
  <[                    if value gt 0 go to next char

                    1 less than
  >--                   set PC = 60 (less than)
  <-[                   if value gt 1 go to next char

                    2 plus
  >>[<->-]<--           set PC = 43 (plus)
  <-[                   if value gt 1 go to next char

                    3 minus
  >++                   set PC = 45 (minus)
  <-[                   if value gt 1 go to next char

                    4 dot
  >+                    set PC = 46 (dot)
  <-[                   if value gt 1 go to next char

                    5 comma
  >--                   set PC = 44 (comma)
  <-[                   if value gt 1 go to next char

                    6 left bracket
  >+[>+<-]>[<++>-]<+    set PC = 91 (left bracket) (inc (45) / double (90) / inc (91))
  <-[                   if value gt 1 go to next char

                    7 right bracket
  >++                   set PC = 93 (right bracket)
  <-                    decrease value the last time to exit if

  ]]]]]]]               close all ifs
  >.[-]                 print char and clear PC
  >[-]                  clear 15 if still existant

  <<<                   go to next bits
  +                     repeat if not SB
]

When converting to Unary, you can subtract the 60 directly from the input cell instead of putting it in its own cell first, saving 16 bytes.  A further 4 bytes can be saved by not creating the 45 immediately (thus compacting the tape layout even further).
Additionally, it is slightly golfier to check the input bytes in the order 01325467.

The alternative I meant was to create the 45 while you're adding 15 to the input cell.

Python 2, 80 79 63 55 + 86 64 = 119 Bytes
Thanks to Sp3000 for his numerous suggestions, saving a lot of bytes.
Brainfuck to Unary, 78 77 61 53 + 2 = 55 bytes
Added two bytes to account for surrounding "s on input.
print int(`[1]+map("><+-.,[]".find,input())`[1::3],8)

Unary to Brainfuck, 86 64 bytes
print''.join("><+-.,[]"[int(i)]for i in oct(input())[2:]if'L'>i)

Check it out on ideone here.

47 bytes for Unary -> Brainfuck

CJam, 35 bytes
Brainfuck to Unary, 17 bytes
1r"><+-.,[]"f#+8b

Try it online.
How it works
 r                e# Read a whitespace-separated token from STDIN.
            f     e# For each character in the token:
  "><+-.,[]" #    e#     Find its index in this string.
1             +   e# Prepend a 1 to the results.
               8b e# Convert to integer, using base 8 conversion.

Unary to Brainfuck, 18 bytes
ri8b"><+-.,[]"f=1>

Try it online.
How it works
r                  e# Read a whitespace separated token from STDIN.
 i                 e# Interpret as integer.
  8b               e# Convert to array using base 8 conversion.
              f    e# For each digit:
    "><+-.,[]" =   e#     Select the corresponding character from the string.
                1> e# Discard the first character.

Bash + coreutils, 39 + 47 = 86
b2u.sh:
dc -e8i1`tr '<>+-.,[]' 0-7`p|tr -dc 0-9

u2b.sh:
dc -e8o?p|tr -dc 0-9|tr 0-7 '<>+-.,[]'|cut -c2-

Test output:
$ echo "++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+." | ./b2u.sh
239234206933197750788456456928845900180965531636435002144714670872282710109774487453364223333807054152602699434658684117337034763550216789
$ echo 239234206933197750788456456928845900180965531636435002144714670872282710109774487453364223333807054152602699434658684117337034763550216789 | ./u2b.sh
++++++[>++++++++++++<-[>.>++++++++++[>++++++++++<-[>+.+++++++..+++.>++++[>+++++++++++<-[>.<+++[>----<-[>.<<<<<+++[>+++++<-[>.>>.+++.------.--------.>>+.
$

tr -dc 0-9  (and in code golf you can assume that ? is fine unescaped)

Japt, 13 + 13 = 26 bytes
Brainfuck to Unary
i< n"><+-.,[]

Try it!
Explanation:
i<               :Insert a "<" at the start of the string (representing 1)
   n             :Convert string to decimal by interpreting as:
    "><+-.,[]    : A base 8 number represented by the 8 characters of BF

Unary to Brainfuck
s"><+-.,[]" Å

Try it!
Explanation:
s                :Convert decimal to string representation of:
 "><+-.,[]"      : Base 8 using the BF characters to represent the 8 digits
            Å    :Remove the extra "<" at the front

Notes
I can't find the meta post, but if my memory serves correctly answers are allowed to limit I/O to numbers that their language can support, as long as they implement an algorithm that would work if the language starts supporting larger numbers. That is the case here, Japt's ability to treat a string as "base n using these n characters for the digits" can only use the number data type on the other side of the operation, and thus the test cases won't actually run successfully; the output of the first program and the input of the second program will coerce the number to one which can be represented as a number, rather than using the actual number. For numbers which can be perfectly represented by Japt's number data type these programs will work as desired, and if the number data type changes to support larger numbers then these programs will start supporting those numbers as well.

05AB1E, 33 (17 + 16) bytes
Brainfuck to Unary-length:
"><+-.,[]"sSk1š8β

Try it online or verify all test cases.
Explanation:
"><+-.,[]"           # Push string "><+-.,[]"
          s          # Swap to take the (implicit) input
           S         # Convert it to a list of characters
            k        # Check for each the index in the string
             1š      # Prepend a 1 to the list of indices
               8β    # Convert the list to Base-8 (and output implicitly)

Unary-length to Brainfuck
8в¦"><+-.,[]"sèJ

Try it online or verify all test cases.
Explanation:
8в                  # Convert the (implicit) input-list from Base-8 to Base-10
  ¦                 # Remove the first 1
   "><+-.,[]"       # Push string "><+-.,[]"
             s      # Swap the list and string on the stack
              è     # Index each integer into this string
               J    # Join everything together (and output implicitly)

Dart, 77 + 142 = 219 bytes
f(s)=>BigInt.parse('1'+s.split('').map('><+-.,[]'.indexOf).join(''),radix:8);

F(n)=>BigInt.parse(n).toRadixString(8).split('').map((s)=>'><+-.,[]'.substring(int.parse(s),int.parse(s)+1)).join('').toString().substring(1);

Try it online!

C (gcc), 254 bytes
#include"gmp.h"
f(i,o)char*i,*o;{mpz_t l;char*c="><+-.,[]";if(*i>47&*i<58)for(mpz_init_set_str(l,i,0),mpz_get_str(o,8,l);*o;*o++=o[1]?c[o[1]-48]:0);else for(mpz_init_set_si(l,1);mpz_get_str(o,10,l),*i;mpz_mul_si(l,l,8),mpz_add_ui(l,l,strchr(c,*i++)-c));}

Try it online!
Determines which direction to go based on input (i), stores the result in the passed buffer (o). Note that some compilers allow saving of 4 bytes based on the implementation-defined ordering of the o++. In these cases the provided solution will truncate an extra character off of the Unary->BF conversion and the o[1]'s can all be replaced by *o to recover behaviour.

The language should be "C (gcc) + GMP" here

Also, is this shorter as one program than as 2? And I'd also recommend putting #include <string.h> in the footer instead of the header to show it works without that import. Also wouldn't C++ be shorter because of its operator overloading? :P

Also not important, but I'd change every si to ui maybe

*i>47&*i<58 -> *i%48<10?

also mpz_init_set_str -> mpz_set_str

Thunno 2, 17 + 15 = 32 bytes
"><+-.,[]"$€Ȯ1Ƥ8ḋ

Try it online! (Brainfuck -> Unary)
8Bḣ"><+-.,[]"si

Try it online! (Unary -> Brainfuck)
Explanation
"><+-.,[]"$€Ȯ1Ƥ8ḋ  # Implicit input
"><+-.,[]"         # Push the string
          $€Ȯ      # Index of each character in the input
             1Ƥ    # Prepend a 1
               8ḋ  # Convert from base 8
                   # Implicit output

8Bḣ"><+-.,[]"si  # Implicit input
8B               # Convert to base 8
  ḣ              # Remove the leading 1
   "><+-.,[]"si  # Index into the string
                 # Implicit output

source: Stack Exchange

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

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

sort: votes


text:
Which Friends characters were really the best friends?
The six main cast members of the American sitcom Friends all agreed that they would be paid the same salary throughout the run of the series (after season 2, at least). But that doesn't mean that they all had the same amount of air time or that they all interacted on screen with each other the same amount.
In this challenge, you'll write a program that could help determine which Friends friends were really the best.
Setup
Consider watching an episode or scene of Friends and noting down exactly who is on screen during each camera shot and for how long.
We'll abbreviate each character's name:

C is for Chandler
J is for Joey
M is for Monica
P is for Phoebe
R is for Rachel
S is for Ross

Then for every camera shot (or every time a character enters/exits the shot), we'll list who was on screen. For example:
504 CRS
200 J
345 MP
980
2000 CJMPRS

This is saying that:

For 504ms, Chandler, Rachel, and Ross were on screen.
Then for 200ms, Joey was.
Then for 345ms, Monica and Phoebe were.
Then for 980ms, none of the 6 main characters were on screen.
Then for 2 seconds, all of them were.

(This is not from an actual clip, I made it up.)
Note that the following would be equivalent:
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS

To analyze which combinations of characters had the most screen time, we look at all 64 possible subsets of the 6 characters and total up the screen time they had. If everyone in a subset appears on screen during a camera shot, even if there are more characters than just the ones in the subset, the time for that camera shot is added to that subset's total screen time.
There's an exception for the empty subset - only the scenes with none of the 6 main characters are counted.
So the analysis of the example above would be:
980
2504 C
2200 J
2345 M
2345 P
2504 R
2504 S
2000 CJ
2000 CM
2000 CP
2504 CR
2504 CS
2000 JM
2000 JP
2000 JR
2000 JS
2345 MP
2000 MR
2000 MS
2000 PR
2000 PS
2504 RS
2000 CJM
2000 CJP
2000 CJR
2000 CJS
2000 CMP
2000 CMR
2000 CMS
2000 CPR
2000 CPS
2504 CRS
2000 JMP
2000 JMR
2000 JMS
2000 JPR
2000 JPS
2000 JRS
2000 MPR
2000 MPS
2000 MRS
2000 PRS
2000 CJMP
2000 CJMR
2000 CJMS
2000 CJPR
2000 CJPS
2000 CJRS
2000 CMPR
2000 CMPS
2000 CMRS
2000 CPRS
2000 JMPR
2000 JMPS
2000 JMRS
2000 JPRS
2000 MPRS
2000 CJMPR
2000 CJMPS
2000 CJMRS
2000 CJPRS
2000 CMPRS
2000 JMPRS
2000 CJMPRS

We can see that J (just Joey) had 2200ms of screen time because he had 200 by himself and 2000 with everyone.
Challenge
Write a program that takes in a string or text file such as
504 CRS
200 J
345 MP
980
2000 CJMPRS

where each line has the form [time in ms] [characters on screen], and outputs the total amount of time that each of the 64 subsets of the 6 characters spent on the screen, where each line has the form [total time in ms for subset] [characters in subset] (just as above).
The input can be taken as a string to stdin, the command line, or a function, or it can be the name of a text file that contains the data.

The milliseconds numbers will always be positive integers.
The character letters will always be in the order CJMPRS (alphabetical).
You can optionally assume there is a trailing space when there are no characters in the scene (e.g. 980 ).
You can optionally assume there is a trailing newline.
The input will have at least 1 line and may have arbitrarily many.

The output should be printed or returned or written to another text file as a 64 line string.

The lines may be in any order.
The character letters do not need to be in the CJMPRS order.
Subsets with 0ms total time do need to be listed.
There may optionally be a trailing space after the empty subset total.
There may optionally be a trailing newline.

(This problem can of course be generalized to more characters, but we'll stick with the 6 CJMPRS Friends characters.)
The shortest code in bytes wins.
Note that I actually enjoy Friends and don't think some characters are more important than the others. The statistics would be interesting though. ;)

Do we get a bounty if we post an analysis of the series? ;)

I may or may not have seen every episode dozens of times and own all 10 seasons...

@AlexA. I may or may not know what you are talking about...

The empty set is a special case — it doesn't obey the "even if there are more characters than just the ones in the subset" rule, or else it would score 4029 in the example (the total amount of time that at least no one is on screen), and not 980.

@hobbs That's correct. It looks like people understood that from the example but I've added a note to be sure.

@BetaDecay Quite possibly, actually!

Pyth, 37 bytes
Vy"CJMPRS"++smvhdf?q@eTNNN!eTcR\ .zdN

Try it online: Demonstration
Explanation:
  "CJMPRS"                             string with all friends
 y                                     create all subsets
V                                      for loop, N iterates over ^:
                                 .z      all input lines
                             cR\         split each line at spaces
                 f                       filter for lines T, which satisfy:
                  ?      N                 if N != "":
                   q@eTNN                    intersection(T[1],N) == N
                                           else:
                          !eT                T[1] == ""
             m                           map each of the remaining d to:
              vhd                          eval(d[0]) (extract times)
            s                            sum
           +                       d     + " "
          +                         N    + N
                                         implicitly print

It's hardly even worth trying when I write one line of my solution and it's already longer than the whole Pyth answer :-P

@hobbs That's the downside of mixed language competitions. But don't be intimidated, solutions in other languages usually receive more votes. Just look at the Haskell-Solution.

36% shorter and made me realize I had a bug in my code...

It's rather unfortunate that cM uses the .* map expansion. Perhaps an exception should be made for c as I can't imagine someone wanting to use it like that in a map

This gives 0 on the top line in the example output instead of 980.

@Calvin'sHobbies Pyth changed the order of parameters of ? recently. So q@eTNN and N have to been switched. Here's a link to an updated version: Link

Haskell, 187 bytes
f=g.(>>=(q.words)).lines
g t=p"CJMPRS">>=(\k->show(sum.map snd$filter((==k).fst)t)++' ':k++"\n")
q[n]=[("",read n)]
q[n,s]=[(k,read n)|k<-tail$p s]
p s=map concat$sequence[[[],[c]]|c<-s]

f is a function that takes the input, as a single multi-line string, and returns the multi-line output as single string. Probably plenty left to golf here.
λ: putStr test1
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS

λ: putStr $ f test1
980
2504 S
2504 R
2504 RS
2345 P
2000 PS
2000 PR
2000 PRS
2345 M
2000 MS
2000 MR
2000 MRS
2345 MP
2000 MPS
2000 MPR
2000 MPRS
2200 J
2000 JS
2000 JR
2000 JRS
2000 JP
2000 JPS
2000 JPR
2000 JPRS
2000 JM
2000 JMS
2000 JMR
2000 JMRS
2000 JMP
2000 JMPS
2000 JMPR
2000 JMPRS
2504 C
2504 CS
2504 CR
2504 CRS
2000 CP
2000 CPS
2000 CPR
2000 CPRS
2000 CM
2000 CMS
2000 CMR
2000 CMRS
2000 CMP
2000 CMPS
2000 CMPR
2000 CMPRS
2000 CJ
2000 CJS
2000 CJR
2000 CJRS
2000 CJP
2000 CJPS
2000 CJPR
2000 CJPRS
2000 CJM
2000 CJMS
2000 CJMR
2000 CJMRS
2000 CJMP
2000 CJMPS
2000 CJMPR
2000 CJMPRS

SWI-Prolog, 381 bytes
s([E|T],[F|N]):-E=F,(N=[];s(T,N));s(T,[F|N]).
a(A):-split_string(A," \n","",B),w(B,[],C),setof(L,s(`CJMPRS`,L),M),x(C,[` `|M]).
w([A,B|T],R,Z):-number_string(N,A),(B="",C=` `;string_codes(B,C)),X=[[N,C]|R],(T=[],Z=X;w(T,X,Z)).
x(A,[M|T]):-y(M,A,0,R),atom_codes(S,M),writef("%t %w\n",[R,S]),(T=[];x(A,T)).
y(_,[],R,R).
y(M,[[A,B]|T],R,Z):-subset(M,B),S is R+A,y(M,T,S,Z);y(M,T,R,Z).

This expects to be run as:
a("504 CRS
200 J
345 MP
980
2000 CJMPRS").

Note that you might need to replace every ` to " and every " to ' if you have an old version of SWI-Prolog.
I could shave off 100+ bytes if I didn't have to use a String as an input.

Haskell, 150 136 bytes
import Data.List
f=(subsequences"CJMPRS">>=).g
g l c=show(sum[read x|(x,y)<-map(span(/=' '))$lines l,c\\y==[],c/=[]||c==y])++' ':c++"\n"

Usage example:
*Main> putStr $ f "504 CRS\n1 J\n199 J\n345 MP\n980\n2000 CJMPRS"
980
2504 C
2200 J
2000 CJ
2345 M
2000 CM
2000 JM
2000 CJM
2345 P
2000 CP
2000 JP
2000 CJP
2345 MP
2000 CMP
2000 JMP
2000 CJMP
2504 R
2504 CR
2000 JR
2000 CJR
2000 MR
2000 CMR
2000 JMR
2000 CJMR
2000 PR
2000 CPR
2000 JPR
2000 CJPR
2000 MPR
2000 CMPR
2000 JMPR
2000 CJMPR
2504 S
2504 CS
2000 JS
2000 CJS
2000 MS
2000 CMS
2000 JMS
2000 CJMS
2000 PS
2000 CPS
2000 JPS
2000 CJPS
2000 MPS
2000 CMPS
2000 JMPS
2000 CJMPS
2504 RS
2504 CRS
2000 JRS
2000 CJRS
2000 MRS
2000 CMRS
2000 JMRS
2000 CJMRS
2000 PRS
2000 CPRS
2000 JPRS
2000 CJPRS
2000 MPRS
2000 CMPRS
2000 JMPRS
2000 CJMPRS

Different approach than @MtnViewMark's answer: For all combinations c of the characters find the lines of the input string where the difference of c and the list from the lines y is empty (take care of the special case where no character is on screen (e.g. 980) -> c must be not empty or c == y). Extract the number and sum.

CJam, 67 58 bytes
"CJMPRS"6m*_.&:$_&qN/_{_el=},:~1bpf{{1$\-!},Sf/0f=:i1bS\N}

Try it online in the CJam interpreter.

Perl 5 (5.10+), 128 bytes
2 bytes per line of output. use feature "say" not included in the byte count.
@_=<>;for$i(0..63){@c=qw(C J M P R S)[grep$i&(1<<$_),0..5];
$r=@c?join".*","",@c:'$';$t=0;for(@_){$t+=$1 if/(.*) $r/}say"$t ",@c}

Un-golfed:
# Read the input into an array of lines.
my @lines = <>;
# For every 6-bit number:
for my $i (0 .. 63) {
    # Select the elements of the list that correspond to 1-bits in $i
    my @indices = grep { $i & (1 << $_) } 0 .. 5;
    my @characters = ('C', 'J', 'M', 'P', 'R', 'S')[@indices];

    # Build a regex that matches a string that contains all of @characters
    # in order... unless @characters is empty, then build a regex that matches
    # end-of-line.
    my $regex = @characters
      ? join ".*", ("", @c)
      : '$';

    my $time = 0;
    # For each line in the input...
    for my $line (@lines) {
        # If it contains the requisite characters...
        if ($line =~ /(.*) $regex/) {
            # Add to the time total
            $time += $1;
        }
    }

    # And print the subset and the total time.
    say "$time ", @characters;
}

K, 95
{(+/'{x[1]@&min'y in/:*x}[|"I \n"0:x]'b)!b:" ",?,/{x{,/y{x,/:y@&y>max x}\:x}[d]/d:"CJMPRS"}

Takes a string like "504 CRS\n200 J\n345 MP\n980  \n2000 CJMPRS"
k){(+/'{x[1]@&min'y in/:*x}[|"I \n"0:x]'b)!b:" ",?,/{x{,/y{x,/:y@&y>max x}\:x}[d]/d:"CJMPRS"}["504 CRS\n200 J\n345 MP\n980  \n2000 CJMPRS"]
980 | " "
2504| "C"
2200| "J"
2345| "M"
2345| "P"
2504| "R"
2504| "S"
2000| "CJ"
2000| "CM"
2000| "CP"
2504| "CR"
2504| "CS"
2000| "JM"
2000| "JP"
2000| "JR"
2000| "JS"
2345| "MP"
2000| "MR"
2000| "MS"
2000| "PR"
2000| "PS"
2504| "RS"
2000| "CJM"
2000| "CJP"
2000| "CJR"
2000| "CJS"
2000| "CMP"
2000| "CMR"
2000| "CMS"
2000| "CPR"
2000| "CPS"
2504| "CRS"
2000| "JMP"
2000| "JMR"
2000| "JMS"
2000| "JPR"
2000| "JPS"
2000| "JRS"
2000| "MPR"
2000| "MPS"
2000| "MRS"
2000| "PRS"
2000| "CJMP"
2000| "CJMR"
2000| "CJMS"
2000| "CJPR"
2000| "CJPS"
2000| "CJRS"
2000| "CMPR"
2000| "CMPS"
2000| "CMRS"
2000| "CPRS"
2000| "JMPR"
2000| "JMPS"
2000| "JMRS"
2000| "JPRS"
2000| "MPRS"
2000| "CJMPR"
2000| "CJMPS"
2000| "CJMRS"
2000| "CJPRS"
2000| "CMPRS"
2000| "JMPRS"
2000| "CJMPRS"

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


text:
Go south, east and north, come to the same place
There is that famous riddle:

A bear walks 1 km south, 1 km east and 1 km north, and comes to the place it started from. What color is the bear?

This one is very old, so I'll generalize it:

A bear walks x km south, y km east and x km north, and comes to the place it started from. This bear thinks that the North Pole is boring, so it never goes there. Which latitude did it start and end at?

Assume that the bear is an idealized point, and the Earth is a perfect sphere with 10000 km distance from the pole to the equator (however, you can use a more accurate model if it's easier for some reason).
Write a program or a subroutine that receives the two numbers x and y, and prints or returns the latitude.
Fine points:

Input with at least 3 decimal places of precision should be supported
Input is in the range (0...99999), bounds not inclusive
If the situation is physically impossible, print an empty string or a message, or return an impossible value (like 91 or NaN - or, in fact, 90 - since 90 is an impossible value)
You should print the most northern (maximal) latitude that satisfies the conditions, except the North Pole. If the North Pole is the only solution, see above.
Output precision should be like IEEE single precison or better (24 bits or 7 decimal digits of precision).
If the output is printed, use decimal notation (e.g. -89.99 for a point near the South Pole) . If the output is returned, use floating-point or fixed-point notation.

Shortest code in bytes wins.

Am I missing something, or is this only possible if going y km east makes the bear return to the same place by doing an integer number of laps around?

@xnor That is correct, I believe.

I feel like this is really an algebra/geometry problem, and once you solve it, it will be straightforward to code it in a mathematical language.

So if y = 0 and x < 20000 are you expecting the largest representable number smaller than 90? What if that then gets formatted to 90 by the printf or equivalent? And what intermediate precision and accuracy is required?

@PeterTaylor I disallowed zero specifically to avoid this problem

@xnor I feel there should be some cases (like when solving a cubic equation - is the discriminant negative? what about reusing the code that calculates it in the code that calculates the roots?) and opportunities for golfing; didn't solve it so cannot say for sure.

@PeterTaylor Regarding intermediate calculations - ideally, I'd say "use whatever is necessary to make the output accurate enough". However, it's difficult to verify floating-point precision in all situations, and this question is not about FP accuracy. So just use whatever feels right.

CJam, 62 chars
{4e4/:Y\9e-3*:X90-P180/:Q*mc/XY2$m](/mCQ/+_90<\@XY@m[)/mCQ/-?}

This is a block (subroutine) which takes x y on the stack and leaves the solution on the stack.
Online demo
I'm interpreting the spec to allow returning 90 as an "impossible value" if there is no other solution. If that interpretation is disallowed, I think the best fix would be
{4e4/:Y\9e-3*:X90-P180/:Q*mc/[XY2$m](/mCQ/+\XY@m[)/mCQ/--91]{90<}=}

I have no idea how it works (magic, I guess), but it seems to include all the edge cases!


text:
Find the maximum determinant for each size Toeplitz matrix
For a fixed n, consider the n by n Toeplitz matrices with entries which are either 0 or 1.  The aim is to find maximum determinant over all such Toeplitz matrices.
Task
For each n from 1 upwards, output the maximum determinant over all n by n Toeplitz matrices with entries which are either 0 or 1. There should be one output per n which should have the maximum determinant and also an example matrix that reaches it.
Score
Your score is the largest n your code gets to in 2 minutes on my computer.  To clarify a little, your code can run for 2 minutes in total, this is not 2 minutes per n.
Tie breaker
If two entries get the same n score then the winning entry will be the one that gets to the highest n in the shortest time on my machine. If the two best entries are equal on this criterion too then the winner will be the answer submitted first.
Languages and libraries
You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.
My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.
Small answers
For n = 1..10 the outputs should be 1,1,2,3,5,9,32,56,125,315
This sequence is not in OEIS and so the winning entry also gets to propose a new entry there.
Entries so far

n=10 n=11 by Vioz in Python
n=9 by Tyilo in C
n=12 by Legendre in J
n=10 by Tensibai in R
n=14 by SteelRaven in C++
n=14 by RetoKoradi in C++

@AlexA. You are right and I have apologised. Luckily the two problems are very similar so he should easily be able to modify his code.

The solution by @Vioz comes up with a sequence that starts with 1, 1, 2, 3, 5, 9, 32. So the value for n=5 is different from what you list. Since all other values match, it looks like the solution is probably correct, and this is just a typo in the question?

@RetoKoradi Thank you. Fixed.

Here are 10 possible binary Toeplitz matrices with maximum determinants for n = 1..10: https://ghostbin.com/paste/axkpa

Does our code need to prove that we have the matrix with the greatest determinant (e.g. by checking all of them), or can we just have an algorithm that generates a matrix with greatest determinant without proving it's optimal?

@ThomasKwa Well a proof is fine even it is cleverer than checking all possibilities. But I am not sure exactly what you meant.

Say I have a hill-climbing algorithm that tries to optimize for greatest determinant, which correctly finds a matrix with greatest determinant for n=1..15 but gives a matrix with suboptimal determinant for n>15. Would that be a valid submission for n=15?

@ThomasKwa That's a tricky one as someone else would have to write code to verify your answers!  I would love to see such a hill climbing answer but I don't think I can award a win to it sadly.

@Tyilo How high does it get?

Here's a better version of the Mathematica one: Print["1: 1"];Do[m=Max@Table[d=IntegerDigits[c,2,2*n-1];Det[ToeplitzMatrix@@(Prepend@First@d/@Partition[Drop[d,1],n-1])],{c,0,2^(2*n-1)-1}];Print[n,": ",m],{n,2,100}] It only gets to 9 in 2 minutes, so it's actually worse than my C version. (To actually run it you have to remove the ̣ by stackexchange.)

@Lembik I can get to 11 in 2 mins with: Print["1: 1"];Quiet@Do[m=Max@Table[d=IntegerDigits[c,2,2*n-1];Tr[First@LUDecomposition[ToeplitzMatrix@@(Prepend@First@d/@Partition[Drop[d,1],n-1])],Times],{c,0,2^(2*n-1)-1}];Print[n,": ",m],{n,2,10}]

As an observation that may help others but I can't verify beyond 14.  It appears respective means of the top row and the first column of the Toeplitz matrix are always 0.4 <= m <= 0.6 for the maximum determinant.

I notice that all the matrices with the highest determinants have a 1 in the main diagonal. I figure it would be considered cheating to hardwire that?

@RetoKoradi The max is sometimes reached with 0s in the main diagonal, e.g. for n=3 there is [0,1,1;1,0,1;1,1,0], and the next one occurs for n=6. I checked that for n=1..12 there is always at least one matrix with 1s in the main diagonal that reaches the max, but that's not the same as what you wrote.

@MitchSchwartz The best solution my code got for n=17 has 0 in the main diagonal. I did not check if there are tied solutions that have a 1 diagonal. So yes, assuming that the main diagonal is 1 would not work for very long.

One thing I find fascinating when looking at the numbers is that some results are powers of 2. So far, I got powers of 2 for n=1, 2, 3, 7, 15. Except for n=2, these are all values of n that are of the form 2^k-1. I know it's risky to draw conclusions from a few values. But the value for n=15 being exactly 2^17 is almost too good to be a coincidence. I wonder if there's some kind of pattern.

@RetoKoradi "So yes, assuming that the main diagonal is 1 would not work for very long." does not follow logically from "The best solution my code got for n=17 has 0 in the main diagonal. I did not check if there are tied solutions that have a 1 diagonal."

@MitchSchwartz Not strictly, yes. But at least it shoots down the initial idea that only matrices with diagonal 1 are worth trying. I guess your counter-example for n=3 was sufficient. I should probably extend my code to keep track of ties if we want to know for sure. :) Well, at least for the sizes it can complete, which should be up to n=20 in a weekend run.

@RetoKoradi It is always worth comparing to https://oeis.org/A003432 . For n = 15 the max for general (0,1) matrices is also 2^17   and this is a much more widely studied question..

@MitchSchwartz My code output 927472 (which is smaller than the maximum) for n=17 with the main diagonal = 1.

C++ with pthreads
This gets to n=14 in just under 1 minute on my machine. But since that's just a 2-core laptop, I hope that the 8-core test machine can finish n=15 in under 2 minutes. It takes about 4:20 minutes on my machine.
I was really hoping to come up with something more efficient. There has got to be a way to calculate the determinate of a binary matrix more efficiently. I wanted to come up with some kind of dynamic programming approach that counts the +1 and -1 terms in the determinant calculation. But it just hasn't quite come together so far.
Since the bounty is about to expire, I implemented the standard brute force approach:

Loop over all possible Toeplitz matrices.
Skip one of the two in each transposed matrix pair. Since the matrix is described by bitmask values, this is simple to do by skipping all values where the reverse of the bitmask is smaller than the bitmask itself.
The determinate is calculated with a text book LR decomposition. Except for some minor performance tuning, the main improvement I made to the algorithm from my college numerical methods book is that I use a simpler pivot strategy.
Parallelization is done with pthreads. Just using regular spacing for the values processed by each thread caused very bad load balancing, so I introduced some swizzling.

I tested this on Mac OS, but I used similar code on Ubuntu before, so I hope this will compile and run without a hitch:

Save the code in a file with a .cpp extension, e.g. optim.cpp.
Compile with gcc -Ofast optim.cpp -lpthread -lstdc++.
Run with time ./a.out 14 8. The first argument is the maximum n. 14 should finish in under 2 minutes for sure, but it would be great if you could try 15 as well. The second argument is the number of threads. Using the same value as the number of cores of the machine is normally a good start, but trying some variations could potentially improve the times.

Let me know if you have any problems building or running the code.
#include <stdint.h>
#include <pthread.h>
#include <cstdlib>
#include <iostream>

static int NMax = 14;
static int ThreadCount = 4;

static pthread_mutex_t ThreadMutex;
static pthread_cond_t ThreadCond;
static int BarrierCount = 0;

static float* MaxDetA;
static uint32_t* MaxDescrA;

static inline float absVal(float val)
{
    return val < 0.0f ? -val : val;
}

static uint32_t reverse(int n, uint32_t descr)
{
    uint32_t descrRev = 0;
    for (int iBit = 0; iBit < 2 * n - 1; ++iBit)
    {
        descrRev <<= 1;
        descrRev |= descr & 1;
        descr >>= 1;
    }

    return descrRev;
}

static void buildMat(int n, float mat[], uint32_t descr)
{
    int iDiag;
    for (iDiag = 1 - n; iDiag < 0; ++iDiag)
    {
        float val = static_cast<float>(descr & 1);
        descr >>= 1;
        for (int iRow = 0; iRow < n + iDiag; ++iRow)
        {
            mat[iRow * (n + 1) - iDiag] = val;
        }
    }

    for ( ; iDiag < n; ++iDiag)
    {
        float val = static_cast<float>(descr & 1);
        descr >>= 1;
        for (int iCol = 0; iCol < n - iDiag; ++iCol)
        {
            mat[iCol * (n + 1) + iDiag * n] = val;
        }
    }
}

static float determinant(int n, float mat[])
{
    float det = 1.0f;
    for (int k = 0; k < n - 1; ++k)
    {
        float maxVal = 0.0f;
        int pk = 0;
        for (int i = k; i < n; ++i)
        {
            float q = absVal(mat[i * n + k]);
            if (q > maxVal)
            {
                maxVal = q;
                pk = i;
            }
        }

        if (pk != k)
        {
            det = -det;
            for (int j = 0; j < n; ++j)
            {
                float t = mat[k * n + j];
                mat[k * n + j] = mat[pk * n + j];
                mat[pk * n + j] = t;
            }
        }

        float s = mat[k * n + k];
        det *= s;

        s = 1.0f / s;
        for (int i = k + 1; i < n; ++i)
        {
            mat[i * n + k] *= s;
            for (int j = k + 1; j < n; ++j)
            {
                mat[i * n + j] -= mat[i * n + k] * mat[k * n + j];
            }
        }
    }

    det *= mat[n * n - 1];

    return det;
}

static void threadBarrier()
{
    pthread_mutex_lock(&ThreadMutex);

    ++BarrierCount;
    if (BarrierCount <= ThreadCount)
    {
        pthread_cond_wait(&ThreadCond, &ThreadMutex);
    }
    else
    {
        pthread_cond_broadcast(&ThreadCond);
        BarrierCount = 0;
    }

    pthread_mutex_unlock(&ThreadMutex);
}

static void* threadFunc(void* pData)
{
    int* pThreadIdx = static_cast<int*>(pData);
    int threadIdx = *pThreadIdx;

    float* mat = new float[NMax * NMax];

    for (int n = 1; n <= NMax; ++n)
    {
        uint32_t descrRange(1u << (2 * n - 1));
        float maxDet = 0.0f;
        uint32_t maxDescr = 0;

        uint32_t descrInc = threadIdx;
        for (uint32_t descrBase = 0;
             descrBase + descrInc < descrRange;
             descrBase += ThreadCount)
        {
            uint32_t descr = descrBase + descrInc;
            descrInc = (descrInc + 1) % ThreadCount;

            if (reverse(n, descr) > descr)
            {
                continue;
            }

            buildMat(n, mat, descr);
            float det = determinant(n, mat);
            if (det > maxDet)
            {
                maxDet = det;
                maxDescr = descr;
            }
        }

        MaxDetA[threadIdx] = maxDet;
        MaxDescrA[threadIdx] = maxDescr;

        threadBarrier();
        // Let main thread output results.
        threadBarrier();
    }

    delete[] mat;

    return 0;
}

static void printMat(int n, float mat[])
{
    for (int iRow = 0; iRow < n; ++iRow)
    {
        for (int iCol = 0; iCol < n; ++iCol)
        {
            std::cout << " " << mat[iRow * n + iCol];
        }
        std::cout << std::endl;
    }

    std::cout << std::endl;
}

int main(int argc, char* argv[])
{
    if (argc > 1)
    {
        NMax = atoi(argv[1]);
        if (NMax > 16)
        {
            NMax = 16;
        }
    }

    if (argc > 2)
    {
        ThreadCount = atoi(argv[2]);
    }

    MaxDetA = new float[ThreadCount];
    MaxDescrA = new uint32_t[ThreadCount];

    pthread_mutex_init(&ThreadMutex, 0);
    pthread_cond_init(&ThreadCond, 0);

    int* threadIdxA = new int[ThreadCount];
    pthread_t* threadA = new pthread_t[ThreadCount];

    for (int iThread = 0; iThread < ThreadCount; ++iThread)
    {
        threadIdxA[iThread] = iThread;
        pthread_create(threadA + iThread, 0, threadFunc, threadIdxA + iThread);
    }

    float* mat = new float[NMax * NMax];

    for (int n = 1; n <= NMax; ++n)
    {
        threadBarrier();

        float maxDet = 0.0f;
        uint32_t maxDescr = 0;

        for (int iThread = 0; iThread < ThreadCount; ++iThread)
        {
            if (MaxDetA[iThread] > maxDet)
            {
                maxDet = MaxDetA[iThread];
                maxDescr = MaxDescrA[iThread];
            }
        }

        std::cout << "n = " << n << " det = " << maxDet << std::endl;
        buildMat(n, mat, maxDescr);
        printMat(n, mat);

        threadBarrier();
    }

    delete[] mat;

    delete[] MaxDetA;
    delete[] MaxDescrA;

    delete[] threadIdxA;
    delete[] threadA;

    return 0;
}

There's an interesting way of calculating the determinant of an integer matrix using only integer arithmetic: LU decomposition in some finite field (basically mod a large prime). I don't know if this would be faster.

@ThomasKwa That would probably still be O(n^3)? It might be helpful for larger matrices where floating point precision would otherwise become an issue. I didn't really look for literature. Well, I did a quick search, and found a paper about calculating determinants of Toeplitz matrices. But there were too many open questions for me to commit the time to try and implement it.

BTW, the killer here is really the exponential complexity for enumerating all matrices. But I don't even have the vaguest idea how to calculate the largest determinant without enumerating all of them. I thought about possibilities to at least cut out some unproductive values, but I got nothing on getting it down to polynomial complexity.

This is pretty amazing. Sadly it takes about 3 minutes for n = 15 however.  I was going to try it with n = 18, just for fun but I see you set a max of 16 in the code. Is there any reasons for that?

@Lembik This version of the code uses a 32-bit value for the bitmask, and it needs 2*n-1 bits for describing the matrix. I actually didn't compare if it's any slower with a 64-bit value. Probably wouldn't make much of a difference. However, at some point I think it will need double instead of float for the matrix to get the necessary precision. And I definitely expect that to slow it down. I initially started writing the code with generic types, but it looked kind of awkward. Since it was not going to go above 16 for this challenge, I hardwired the smaller types.

One cheap trick you can do is stop early if you get to the max for any 0,1 matrix from the OEIS.  Surprisingly this does happen sometimes.  In any case, if you can compute the values up to n=18 say it would be a great new OEIS entry in my view.

Just literally changing float to double didn't do it. Would you mind making a version that works for n = 18 by any chance, please?

http://paste.ubuntu.com/11909953/ is the modified version but it just gives 0 for n = 17.

@Lembik I'll try and take a look at it later today. I changed it to handle larger sizes for your other related challenge yesterday. Couldn't beat the highest scores for n=30 so far, my heuristics are stuck below 5*10^13.

@Lembik See http://paste.ubuntu.com/11915546 for code and http://paste.ubuntu.com/11915532 for results up to n=19.

@RetoKoradi Thank you. So amazingly all the values found by the simple hill climbing are optimal up to n = 19 it seems!

@Lembik The results up to n=20 are at http://paste.ubuntu.com/11949738. They now list all the tied solutions, including attributes to quickly see the value of the diagonal and whether they are circulant. All of the maxima for m=18,19,20 are circulant matrices. Please double check the determinants before publishing them anywhere.

J
Update: Improved code to search over half the values. Now calculates n=12 comfortably within 120 seconds (down from 217s to 60s).
You will need the latest version of J installed.
#!/usr/bin/jconsole

dim =: -:@>:@#
take =: i.@dim
rotstack =: |."0 1~ take
toep =: (dim (|."1 @: {."1) rotstack)"1
det =: -/ . * @: toep
ps =: 3 : ',/(0 1 ,"0 1/ ,.y)'
canonical =: #. >: [: #. |. " 1

lss =: 3 : 0
  shape =. (2^y), y
  shape $ ,>{;/(y,2)$0 1
)

ls =: (canonical@:lss) # lss
ans =: >./ @: det @: ls @: <: @: +:

display =: 3 : 0
echo 'n = ';y;'the answer is';ans y
)
display"0 (1 + i.13)
exit''

Run this and kill when two minutes are up. My results (MBP 2014 - 16GB of RAM):
┌────┬─┬─────────────┬─┐
│n = │1│the answer is│1│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │2│the answer is│1│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │3│the answer is│2│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │4│the answer is│3│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │5│the answer is│5│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │6│the answer is│9│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬──┐
│n = │7│the answer is│32│
└────┴─┴─────────────┴──┘
┌────┬─┬─────────────┬──┐
│n = │8│the answer is│56│
└────┴─┴─────────────┴──┘
┌────┬─┬─────────────┬───┐
│n = │9│the answer is│125│
└────┴─┴─────────────┴───┘
┌────┬──┬─────────────┬───┐
│n = │10│the answer is│315│
└────┴──┴─────────────┴───┘
┌────┬──┬─────────────┬────┐
│n = │11│the answer is│1458│
└────┴──┴─────────────┴────┘
┌────┬──┬─────────────┬────┐
│n = │12│the answer is│2673│
└────┴──┴─────────────┴────┘

Total run time = 61.83s.

Just for fun
┌────┬──┬─────────────┬────┐
│n = │13│the answer is│8118│
└────┴──┴─────────────┴────┘

This took approximately 210 seconds on its own.

Note to testers: n = 12 requires roughly 18 GiB of memory.

This is a very nice improvement. The output is slightly buggy however. For me using  j64-804 it outputs n =1 twice so it is out by one for ever more.

@Lembik Ah that's right. I just updated the code; could you try running again? Thanks! (I have set it to calculate up to n=13. You can change the 13 in the second-to-last line to have it calculate up whatever you wish.)

I ran it again and it still gets to 12.

@Lembik Hmm .. are you saying it gets to 12 within the time limit and gets to 13 some time after that (which is what I expect), or that it never gets to 13 (i.e. program halts after 12)?

@Legendre The former.

@Lembik Ah yes, that is to be expected. Calculating up to n=13 takes about 7 minutes on my Macbook Pro. (The n=13 itself is like ~4 minutes). Until I think of a better algorithm, n=12 is the best I can manage in the time allotted :)

C++
Bruteforce with use of OpenMP for parallelization and simple optimization to avoid evaluation of determinant for transposed matrices.
$ lscpu
...
Model name:            Intel(R) Core(TM) i5-2410M CPU @ 2.30GHz
...
$ g++ -O2 toepl.cpp -fopenmp
$ timeout 2m ./a.out
1 1
2 1
3 2
4 3
5 5
6 9
7 32
8 56
9 125
10 315
11 1458
12 2673
13 8118
14 22386

#include <cmath>

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

void updateReverses(vector < int > & reverses) {
  int reversesCnt = reverses.size();
  for(int i = 0; i < reversesCnt; ++i){
    reverses[i] <<= 1;
    reverses.push_back(reverses[i] | 1);
  }
}

const double eps = 1e-9;

double determinant(vector < vector < double > > & matrix) {
  int n = matrix.size();
  double det = 1;
  if(n == 1) return matrix[0][0];
  for(int i = 0; i < n; ++i){
    int p = i;
    for(int j = i + 1; j < n; ++j)
      if(fabs(matrix[j][i]) > fabs(matrix[p][i]))
        p = j;
    if(fabs(matrix[p][i]) < eps)
      return 0;
    matrix[i].swap(matrix[p]);
    if(i != p) det *= -1;
    det *= matrix[i][i];
    matrix[i][i] = 1. / matrix[i][i];
    for(int j = i + 1; j < n; ++j)
      matrix[i][j] *= matrix[i][i];
    for(int j = i + 1; j < n; ++j){
      if(fabs(matrix[j][i]) < eps) continue;
      for(int k = i + 1; k < n; ++k)
        matrix[j][k] -= matrix[i][k] * matrix[j][i];
    }
  }
  return det;
}

int main() {
  vector < int > reverses(1, 0);
  reverses.reserve(1 << 30);
  updateReverses(reverses);
  for(int n = 1;; ++n){
    double res = 0;
    int topMask = 1 << (2 * n - 1);
    vector < vector < double > > matrix(n, vector < double > (n));
#pragma omp parallel for reduction(max:res) firstprivate(matrix) schedule(dynamic,1<<10)
    for(int mask = 0; mask < topMask; ++mask){
      if(mask < reverses[mask]) continue;
      for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
          matrix[i][j] = (mask >> (i - j + n - 1)) & 1;
      res = max(res, determinant(matrix));
    }
    cout << n << ' ' << res << endl;
    updateReverses(reverses);
    updateReverses(reverses);
  }
}

Looks like you may soon be making your first OEIS entry unless someone comes up with a clever idea :)

Python 2
This is a very straightforward solution, and probably won't win the contest. But hey, it works!
I'll give a quick overview of what exactly is happening.

I first generate every possible starting row for n. For example, when n=2, this will generate an array length 2n+1, where each row is length 2n-1. It would look like this: [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]].
Then, for each of those possible starting rows, I rotate it n times and slice off the first n items to generate the appropriate matrix, and use scipy to calculate the determinant, all while keeping track of the maximum value. At the end of this, I simply print out the maximum, increment n by 1, and keep going until 10 minutes has passed.

To run this, you will need scipy installed.
Edit 1: Changed how initial rows were built by using itertools.product instead, thanks Sp3000!
Edit 2: Removed storage of possible starting rows for a minimal improvement in speed.
Edit 3: Changed to scipy to have more control over how det worked.
from scipy import linalg
from collections import deque
from time import time
from itertools import product

c=1
t=time()
while 1:
    m=0
    for d in product(range(2),repeat=2*c-1):
        a=deque(d)
        l=[d[0:c]]
        for x in xrange(c-1):
            a.rotate(1)
            l+=[list(a)[0:c]]
        m=max(m,linalg.det(l,overwrite_a=True,check_finite=False))
    print m,'in',time()-t,'s'
    c+=1

Here's some sample output on my home machine (i7-4510U, 8GB RAM):
1.0 in 0.0460000038147 s
1.0 in 0.0520000457764 s
2.0 in 0.0579998493195 s
3.0 in 0.0659999847412 s
5.0 in 0.0829999446869 s
9.0 in 0.134999990463 s
32.0 in 0.362999916077 s
56.0 in 1.28399991989 s
125.0 in 5.34999990463 s
315.0 in 27.6089999676 s
1458.0 in 117.513000011 s

Thank you but I think you have answered an old version of the question I am afraid. It is now about Toeplitz matrices and the time limit is 2 minutes.

I see so much golfed Python on this site that I often forget that for general purposes it's actually a readable language.

This could probably be sped up significantly, because it doesn't take advantage of the fact that it's a binary matrix.

@ThomasKwa If I'm honest, I have no idea how to take advantage of that :P

Quote from numpy documentation: "The determinant is computed via LU factorization using the LAPACK routine z/dgetrf." I looked at dgetrf, and it says it uses double precision; depending on OP's GPU single precision could be faster.

Makes it to 11 now on my machine!

R
You'll have to install R and the packages listed with install.packages("package_name")
Didn't get under 2 mins on my machine with this version (I've to try with a parallel modification)
library(pracma)
library(stringr)
library(R.utils)
library(microbenchmark)

f <- function(n) {
  #If n is 1, return 1 to avoid code complexity on this special case
  if(n==1) { return(1) }
  # Generate matrices and get their determinants
  dets <- sapply(strsplit(intToBin( 0:(2^n - 1)), ""), function(x) {
              sapply( strsplit( intToBin( 0:(2^(n-1) - 1) ), ""),
                    function(y) {
                      det(Toeplitz(x,c(x[1],y)))
                    })

              })
  #Get the maximum determinant and return it
  res <- max(abs(dets))
  return(res)
}

Call and output:
> sapply(1:10,f)
 [1]   1   1   2   3   5   9  32  56 125 315

Benchmark on my machine:
> microbenchmark(sapply(1:10,f),times=1L)
Unit: seconds
            expr      min       lq     mean   median       uq      max neval
 sapply(1:10, f) 66.35315 66.35315 66.35315 66.35315 66.35315 66.35315     1

For information, for a 1:11 range, it takes 285 seconds.

C
Compile with:
$ clang -Ofast 52851.c -o 52851

Run with:
$ ./52851

Can output the maximum determinant for n = 1..10 in ~115 seconds on my computer.
The program is just getting the determinant every possible binary Toeplitz matrix of size n, however every determinant of matrices of size 5x5 or smaller will be cached using memoization.
At first I wrongly assumed that every submatrix of a Toeplitz matrix will also be a Toeplitz matrix, so I only needed to memoize 2^(2n-1) values instead of 2^(n^2) for each n. I made the program before realizing my mistake, so this submission is just a fix of that program.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <string.h>

#define ELEMENTS(x) (sizeof(x) / sizeof(*x))

int *dets[6];

void print_matrix(int n, int c) {
    for(int row = 0; row < n; row++) {
        for(int col = 0; col < n; col++) {
            int j = n - 1 - row + col;
            int val = !!(c & (1 << j));
            printf("%d ", val);
        }
        puts("");
    }
}

int det(int n, uint8_t *m) {
    if(n == 1) {
        return m[0];
    }

    int i = 0;

    if(n < ELEMENTS(dets)) {
        for(int j = 0; j < n * n; j++) {
            i *= 2;
            i += m[j];
        }

        int v = dets[n][i];
        if(v != INT_MIN) {
            return v;
        }
    }

    int v = 0;

    uint8_t *sub = malloc((n - 1) * (n - 1));

    for(int removed = 0; removed < n; removed++) {
        if(m[removed]) {
            uint8_t *p = sub;
            for(int row = 1; row < n; row++) {
                for(int col = 0; col < n; col++) {
                    if(col == removed) {
                        continue;
                    }

                    *p = m[col + row * n];

                    p++;
                }
            }

            v += (removed % 2 == 0? 1: -1) * det(n - 1, sub);
        }
    }

    free(sub);

    if(n < ELEMENTS(dets)) {
        dets[n][i] = v;
    }
    return v;
}

int main(void) {
    for(int i = 2; i < ELEMENTS(dets); i++) {
        int combinations = 1 << (i * i);
        dets[i] = malloc(combinations * sizeof(**dets));
        for(int j = 0; j < combinations; j++) {
            dets[i][j] = INT_MIN;
        }
    }

    puts("1: 1");

    for(int n = 2; n < 65; n++) {
        int vars = 2 * n - 1;
        size_t combinations = 1 << vars;

        int best = -1;
        int max = -1;

        uint8_t *sub = malloc((n - 1) * (n - 1));

        for(int c = 0; c < combinations; c++) {
            int d = 0;
            for(int i = 0; i < n; i++) {
                if(c & (1 << (n - 1 + i))) {
                    uint8_t *p = sub;
                    for(int row = 1; row < n; row++) {
                        for(int col = 0; col < n; col++) {
                            if(col == i) {
                                continue;
                            }

                            int j = n - 1 - row + col;
                            *p = !!(c & (1 << j));

                            p++;
                        }
                    }
                    d += (i % 2 == 0? 1: -1) * det(n - 1, sub);
                }
            }

            if(d > max) {
                max = d;
                best = c;
            }
        }

        free(sub);

        printf("%d: %d\n", n, max);
        //print_matrix(n, best);
    }

    return 0;
}

It looks like you're calculating the determinant using expansion by minors; this has O(n!) complexity, so you may be better off using a different algorithm.

@ThomasKwa I didn't know that there were faster algorithms, so yeah this solution is pretty bad.

You may want to look into using LU Decomposition to find the determinant of a matrix.  It's O(n^3), I believe, though can be made faster with some interesting algorithms. I believe most of the builtins used here generally use a variant of decomposition to perform determinants.

@BrainSteel, yeah I looked at it, but I might as well go for a O(n^2) algorithm if I'm updating my answer.

According to a casual Wikipedia search, the determinant of a Toeplitz matrix can be determined in O(n^2). But I think the bottleneck of the problem is searching among the O(4^n) many 0-1 n by n matrices.

@Legendre Maybe writing O(n^2) code to compute the determinant of a Toeplitz matrix could be a PPCG challenge on its own?

@Lembik I digged around the literature some more. It seems that even the O(n^2) algorithm (there are better ones) is a serious algorithm --- not hard to code up per se, but not something that is easily "golfable".

@Legendre Right. There should be a way to pose serious coding challenges which aren't related to golf on PPCG though.

PARI/GP, n=11
This is brute force but taking advantage of det(A^T) = det(A). I'm only posting it to demonstrate how easy it is to skip transposes. The lowest bit of b1 holds the top left cell, and the other bits hold the rest of the top row. b2 holds the rest of the left column. We simply enforce b2 <= (b1>>1).
{ for(n=1,11,
    res=0;
    for(b1=0,2^n-1,
      for(b2=0,b1>>1,
        res=max(res,matdet(matrix(n,n,i,j,bittest(if(i>j,b2>>(i-j-1),b1>>(j-i)),0))));
      )
    );
    print(n" "res);
  )
}

Regarding computing Toeplitz determinants in O(n^2) time: In my limited research, I've kept running into a requirement that all leading principal minors must be nonzero in order for the algorithms to work, which is a major obstacle for this task. Feel free to give me pointers if you know more about this than I do.

Did you see this paper? http://www.scienpress.com/upload/JAMB/Vol%201_1_4.pdf . It wasn't clear to me what the complexity is. There seemed to be quite a lot of terms for the n=5 example.

@RetoKoradi Yes I saw that. It seems the complexity is not polynomial, considering that e.g. e_{k+1} has 4 times the number of components as e_k. There are many omissions in the paper. An invertible matrix has an LU decomposition iff all leading principal minors are nonzero. (Notice the denominators, e.g. a_0 -- implicitly they are guaranteed to be nonzero.) Uniqueness comes from L being unit triangular. The author also didn't mention numerical stability. In case the link becomes unavailable, the paper is "On Calculating the Determinants of Toeplitz Matrices" by Hsuan-Chu Li (2011).

Rust, \$n \leq 14 \$ in 2 min on my laptop
src/main.rs
use std::time::{Instant, Duration};
use rulinalg::matrix::Matrix;

fn bit_get(n: u32, i: u32) -> f64 {
    ((n >> i) & 1) as f64
}

fn main() {
    let start = Instant::now();
    let max_duration = Duration::from_secs(120); // 2 minutes

    let mut n = 1;

    while start.elapsed() < max_duration {
        let mut res = 0f64;
        for b1 in 0..(1 << n) {
            for b2 in 0..=(b1 / 2) {
                let values: Vec<f64> = (0..n)
                    .flat_map(|r| (0..n)
                        .map(move |c| if r > c {
                            bit_get(b2, r as u32 - c as u32 - 1)
                        } else {
                            bit_get(b1 as u32, c as u32 - r as u32)
                        }))
                    .collect();
                let matrix = Matrix::new(n as usize, n as usize, values);
                let det = matrix.det();
                res = res.max(det);
            }
        }
        println!("{} {}", n, res);
        n += 1;
    }
}

Cargo.toml
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ndarray = "0.15"
ndarray-linalg = "0.13"
rulinalg = "0.4"

Build and running
# win10 environment

$ set Copt-level=3
$ set Clto=fat
$ set Ctarget-cpu=native
$ cargo build --release
$ target\release\rust_hello.exe
1 1
2 1
3 2
4 3
5 5
6 9
7 32
8 56
9 125
10 315
11 1458
12 2673
13 8117.999999999997  # roughly 8118
14 22386.000000000007 # roughly 22386

Any chance for 13?

@Simd I have updated the Rust code, now $n \leq 14 $ in 2 min on my laptop.

Mathematica
So slow. It can be optimized more.
Try it online!
Clear["Global`*"];
Table[res = 0;
 For[b1 = 0, b1 <= 2^n - 1, b1++,
  For[b2 = 0, b2 <= Floor[b1/2], b2++,
   matrix =
    Array[If[#1 > #2, BitGet[b2, #1 - #2 - 1],
       BitGet[b1, #2 - #1]] &, {n, n}, 0];
   res = Max[res, Det[matrix]];]];
 Print[n, " ", res], {n, 1, 11}]

1,1,2,3,5,9,32,56,125,315,1458

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