text:
BrainFlow Interpreter!
BrainFlow
What is BrainFlow?
BrainFlow is an extension of BrainF**k (BFk) with 3 additional commands for added functionality and confusion.
What commands?
In addition to the normal BFk commands, we also have:

^ Jumps to the cell # depending on the value in the cell.
  Ex: If we are at cell # 0 with a value of 4, ^ will jump us to cell # 4.

= Sets the value at the cell to the index of the cell. Ex: If we are at cell # 4 with a value of 0, = will set our value to 4.

& Will set the value at the current cell equal to the value at the cell based on the value in our current cell. (This one's hard to word, so here's an example!) Ex: We are at cell # 33 and our current value at this cell is 7, & will set our current value at cell # 33 to whatever value is in cell # 7.

Optional Challenges
Accomplishing any of the following will apply the specified bonus to your byte count.
Interpreter written in BrainFlow (Can be interpreted by the sample and contains at least one meaningful ^ = or &): Score / 3
Interpreter written in BrainF**k: Score / 2
Doesn't contain any English letters (in either upper or lower case): Score - 20
Doesn't contain any of the BrainFlow / BFk commands in the interpreter itself: Score - 50
Example
An example Java interpreter:
import java.util.Scanner;

public class Interpreter {

    private String exp;

    private int[] values = new int[256];
    private int index = 0;

    private Scanner in;

    public Interpreter(String exp, Scanner in){
        this.exp = exp;
        this.in = in;
    }

    public void run(){
        //Reset index and values
        for(int i = 0; i < values.length; i++){
            values[i] = 0;
        }
        this.index = 0;

        System.out.println("Starting...");
        this.process(this.exp, false);
        System.out.println("\nDone.");
    }

    private void process(String str, boolean loop){
        boolean running = loop;
        do{
            for(int i = 0; i < str.length(); i++){
                switch(str.charAt(i)){
                case '>':increaseIndex();break;
                case '<':decreaseIndex();break;
                case '+':increaseValue();break;
                case '-':decreaseValue();break;
                case '[':
                    String s = str.substring(i);
                    int j = this.getClosingIndex(s);
                    if(this.values[this.index] == 0){
                        i +=j;
                        break;
                    }
                    process(s.substring(1, j), true);
                    i += j;
                    break;
                case '.':
                    int v = this.values[this.index];
                    System.out.print((char)v);
                    break;
                case ',':this.values[this.index] =  this.in.next().charAt(0);break;
                case '^':this.index = this.values[this.index];break;// Jumps to the index specified in the current cell.
                case '=':this.values[index] = this.index;break;// Sets the value at cell #x to x
                case '&':this.values[index] = this.values[this.values[index]];break;// If cell contains X, makes value of current cell equal to value in cell X
                default:
                    //Ignore others
                    break;
                }
            }
            if(this.values[this.index] == 0){
                running = false;
            }
        }while(running);
    }

    private void increaseIndex(){
        if(++this.index >= this.values.length){
            this.index = 0;
        }
    }

    private void decreaseIndex(){
        if(--this.index < 0){
            this.index = this.values.length - 1;
        }
    }

    private void increaseValue(){
        int newVal = this.values[this.index] + 1;
        if(newVal >= this.values.length){
            newVal = 0;
        }
        this.values[this.index] =  newVal;
    }

    private void decreaseValue(){
        int newVal = this.values[this.index] - 1;
        if(newVal < 0){
            newVal = this.values.length - 1;
        }
        this.values[this.index] =  newVal;
    }

    private int getClosingIndex(String str){
        int openings = 0;
        int closings = 0;
        for(int i = 0; i < str.length(); i++){
            char c = str.charAt(i);
            if(c == '['){
                openings++;
            }else if(c == ']'){
                closings++;
            }
            if(openings == closings){
                return i;
            }
        }
        return -1;
    }
}

Not even close to golfed but should provide a good starting point.
Lowest final score wins, where score is number of bytes in your program after the applicable Challenge reductions have been taken into account.
Testing
The following BrainFlow program should print the specified output after reading a '+' char from stdin:
<<,++++[>++++[>++++<-]<-] Set cell #0 to a value dependent on input
>>>+[[-]&>=]+& Set every other cell to that value
[ Start loop
+^ Add one to current value and jump to that cell index
. Print the value at that cell
& Copy value from specified cell
] End loop

Output:
ðñðòñðòðôóòñóñôóðòõóñõðôôóòñööõôöðóöðõðùõñô÷ùõóñöóùñô÷øôøõôòöõóðòöóñ÷ðõôûôòú÷úø÷öùøöùñøðùúðûðþöûñùýøðòñ

Note that the & allows you to essentially create variables in the lower cells then reference them later.
For example if I store my age in the 2nd cell and the month I was born in the 3rd cell, and I am currently in the 64th cell, I can do ++& to retrieve my age or +++& to retrieve the month I was born in. (Assuming of course the 64th cell is at the default value of 0)

I think you mean 'superset', not subset.

@ɐɔıʇǝɥʇuʎs Changed from subset to extension. Thanks for the feedback.

score for being written in brainflow is a bad idea - brainfuck is a subset of brainflow, therefore any brainfuck program is a brainflow program. its like saying a c++ program will score better than a C program. OK, my C program is a C++ program, soo....

@pseudonym117 I'll make it more specific, thanks

for challenge #4, does that mean just literals or in the source code at all?

@pseudonym117 None in the source code at all.

if anyone manages to do that i will be thoroughly impressed. = and , pretty important in every language...

@pseudonym117 That's why its a -50 to your score.

Does it have to be unbounded in both directions or is it okay to not allow negative cell indices?

@IngoBürk It should work the same way BrainF**k does. Decrementing a cell or value when at 0 sets the value to 255. And incrementing when at 255 should set to 0.

Well there are different brainfuck implementations. But we're talking about a wrapping one on both ends here. Got it :)

@IngoBürk Yah, it's the only implementation that makes sense to me, especially since output can only be 0-255.

True, nin-wrapping would cause problems in the new commands. Hadn't thought of that. Thanks!

Why is writing an implementation in Brainfuck have a smaller benefit than writing one in Brainflow? It seems like the former would be more challenging, since it is a smaller language.

@PeterOlson Because I said so. JK, it's because I wanted to give a strong reason to experiment and use the new commands in your interpreter if writing in a Brain[Flow/F**k] language.

Any submission in BFk or BFw would automatically also get the third bonus. In that case, which bonus is applied first?

@MartinBüttner Division bonuses will be applied after subtraction bonuses.

Can we assume a limited size for the array (e.g. the "standard" 30k cell array?).

@Bakuriu There are 255 cells that can hold values up to 255

@spocot According to your description there are at least 255 cells, but you could have an infinite number (although you can only jump to the first 255). Anyway your comment clarifies that you only require exactly 255 cells.

@Bakuriu I can assure you... there are only, at max, 255 cells... The indexes and values wrap around. ex: 255 + 1 = 0

Perl - 233 230 210 182 180 176 174 171 bytes
$/=$,;%d=qw(> $p++ < $p-- + $v[$p]++ - $v[$p]-- , $v[$p]=ord+getc . print+chr+$v[$p] [ while+$v[$p]{ ] } ^ $p=$v[$p] = $v[$p]=$p & $v[$p]=$v[$v[$p]]);eval$d{$_}for<>=~/./g
Simply took an existing BrainFuck interpreter of mine, golfed it, and added the BrainFlow functions.
Update: Completely restructured the program to lose 28 bytes.

Notice that if you were to be fed a string of 300 "+"s, you'd end up with invalid values.  You need to do a %256 sanity check after/while setting many of those values.

I think this does not work with loops ([]). You cannot eval character by character for that.

How the pluses get translated back into parenthesis?

Let's get this party started.
C - 408 384 393 390 380 357 352 bytes (still chipping away)
Compile with gcc on a POSIX compliant system. The first argument is the name of a file containing the Brainflow code to be interpreted. Newlines added to improve readability.
i,p,b[9999],*k=b;unsigned char g[9999],a[30000],*d=a;main(c,v)char**v;
{read(open(v[1],0),g,9999);while(c=g[i++]){c-62||d++;c-60||d--;c-43||
(*d)++;c-45||(*d)--;c-46||putchar(*d);c==44?*d=getchar():0;c==94?d=a+*d:0;
c==61?*d=d-a:0;c==38?*d=a[*d]:0;c==93?i=*(--k):0;if(c==91)if(*d)*k++=i-1;else
while(c=g[i++]){c==91?p++:0;if(c==93)if(p)p--;else break;}}}

And the ungolfed version if you're interested. Let me know if you see any bugs.
int i, depth, buffer[9999], *stack = buffer;
unsigned char c, program[9999], array[30000], *data = array;

main(int argc, char **argv)
{
    read(open(argv[1], 0), program, 9999);

    while(c = program[i++]){
        if (c=='>') data++;
        if (c=='<') data--;
        if (c=='+') (*data)++;
        if (c=='-') (*data)--;
        if (c=='.') putchar(*data);
        if (c==',') *data=getchar();
        if (c=='^') data=array+*data;
        if (c=='=') *data=data-array;
        if (c=='&') *data=array[*data];
        if (c==']') i=*(--stack);
        if (c=='[')
            if (*data) *stack++=i-1;
            else while (c=program[i++]) {
                    if (c=='[') depth++;
                    if (c==']') if (depth) depth--; else break;
            }
    }
}

Updates:

Thanks for the initial feedback which allowed me to knock an extra 24 bytes off.
Sign bug fixed. Added another 9 bytes.
Saved another 3 bytes per es1024's suggestions.
Saved another 10 bytes per more suggestions from es1024.
Just remembered that global variables are initialized to 0. Switched from fread and fopen to read and open. Saved 23 bytes.
Don't need to set null terminator on program because buffer is already initialized to zero. Saved 5 bytes.

I think the if() and the ; could be replaced with ?: and save some characters.

The character literals can be replaced with their ASCII equivalents to save characters.

@Orby It doesn't seem to process input chars correctly. It should convert them to the ascii representation and store them. Other than that it works.

isn't there switch in c? (i don't know c yet)

@proudhaskeller There is a switch statement in C, but it uses more bytes than sequential ifs.

@spocot I don't understand what you mean. getchar() should return the ASCII code for the letter (not the keyboard code). Could you give me an example of a character which it fails to store correctly?

@Orby http://i.imgur.com/rF0FZQ7.png

@spocot What are the contents of test.flo? Just ",."? When I execute ",." I don't encounter any problems. Edit: Oh I see, sorry, you're probably running the test program listed in the problem description. One second, I'll tell you what I get.

@Orby the test program above, your output does not match the test program output

@spocot: Found the culprit. Just a stupid sign bug. All patched up now. You still won't see the extended ASCII characters on the terminal emulator because its dumping raw ASCII instead of Unicode, but the cell values are correct.

You can replace main(int c,char**v){ with main(c,v)char**v;{ and save two bytes, as well as move int i=0,p=0,b[9999],*k=b; to outside the function, and drop the int  to save four bytes. if (c==91) also has an unnecessary space.

@es1024: Moving the integer declaration outside the function won't compile for me on gcc, but the other suggestions work. Thanks!

You can also replace most if not all of the c==[number]?[action]:0; with c-[number]||[action]. (c-[number] is equivalent to c != [number] and if(p)p--; with p&&p--;

@es1024 c-[number]||[action] works in some places, but p&&p-- exhibits different behaviour (though I have no idea why?).

@Orby Ah, the if(p) has an else; that would explain why.

c cannot equal 44 and 94 and 61 etc all at the same time, so rather than c==a?x:0;c==b?y:0 style you could do c==a?x:c==b?y:... ?

@Orby what happens when you actually read 9999 characters? Your program array will be entirely full you won't be sure that the character beyond the input is a \0. Fix: read 9998 chars instead of 9999.

AppleScript 972 670
Mostly golfed although there's no way it will ever win. I don't know why I didn't think about just constructing a script like the perl one did (though it still won't win haha).  This could probably be golfed more by readjusting how the index values a bit better, AppleScript is frustratingly (for this type of stuff) a 1 index language.
Just pass the BrainFlow code in to e().  Note that AppleScript's ASCII commands use MacOSRoman encoding, so while the output will appear different, it is correct looking at its binary representation.  You'll need to take that into account when passing in any upper ASCII characters though on "," commands.
on e(x)
set d to {"", "set b'sitem(i+1)to(b'sitem(i+1)+1)mod 256", "set b'sitem(i+1)to(b'sitem(i+1)+255)mod 256", "set i to(i+1)mod 256", "set i to(i+255)mod 256", "repeat while b'sitem(i+1)≠0", "end", "set o to o&(ASCII character b'sitem(i+1))", "display dialog \"\"default answer\"\"
set b'sitem(i+1)to ASCII number result'stext returned'stext1", "set i to b'sitem(i+1)", "set b'sitem(i+1)to i", "set b'sitem(i+1)to b'sitem(b'sitem(i+1)+1)"}
set s to "set i to 0
set b to{}
repeat 256
set b'send to 0
end
set o to  \"\"
"
repeat with c in x'stext
set s to s&d'sitem((offset of c in "+-><[].,^=&")+1)&"
"
end
set s to s&"return o"
return run script s
end

(because what f***s with your brain more than writing a brainfuck/flow interpreter in another language that f***s with your head way too much?


text:
Interpret /// (pronounced 'slashes')
Because we can't get enough of esoteric language golfs, can we?
///—pronounced slashes—is a fun little language based on the s/// regex-replacement function of Perl fame. It contains only two special characters, slash / and backslash \. You can find a full article on it at the esolangs wiki, but I will reproduce a description of the language below, as well as some examples.
In short, it works by identifying /pattern/repl/rest in the program and making the substitution as many times as possible. No characters are special except / and \: / demarcates patterns and replacements in the program, while \ allows you to insert literal / or \ characters into your code. Notably, these are not regular expressions, just plain string substitutions.
Your challenge is to produce an interpreter for the /// language, as either a program reading STDIN or a function taking a string argument, in as few characters as possible.
You may use any language except for /// itself. You may not use any libraries that interpret ///; you may, however, use regexes, regex libraries, or string-matching libraries.

Execution
There are four states, print, pattern, replacement, and substitution. In every state except substitution:

If the program is empty, execution halts.
Else, if the first character is \, do something with the next character (if present) and remove both from the program.
Else, if the first character is /, remove it, and change to the next state.
Else, do something with the first character and remove it from the program.
Repeat.

The states cycle through print, pattern, replacement, and substitution in order.

In print mode, 'do something' means output the character.
In pattern mode, 'do something' means add the character to the current Pattern.
In replacement mode, 'do something' means add the character to the current Replacement.

In substitution mode, you follow a different set of rules. Repeatedly substitute the first occurrence of the current Pattern with the current Replacement in the program, until no more substitutions are possible. At that point, clear the Pattern and Replacement and return to print mode.
In the program /foo/foobar/foo foo foo, the following happens:
/foo/foobar/foo foo foo
foo foo foo
foobar foo foo
foobarbar foo foo
foobarbarbar foo foo
...

This loops forever and never exits substitution mode. Similarly, if the Pattern is empty, then the first occurrence of the empty string—at the beginning of the program—always matches, so substitution mode loops forever, never halting.

Examples
no

Output: no.
/ world! world!/Hello,/ world! world! world!

Output: Hello, world!.
/foo/Hello, world!//B\/\\R/foo/B/\R

Output: Hello, world!.
a/ab/bbaa/abb

Output: a. Program does not halt.
//

Output: none.
///

Output: none. Program does not halt.
/\\/good/\/

Output: good.
There is also a quine on the wiki you can try.

/-/World//--/Hello//--W/--, w/---! What's not to love? (Try removing dashes from the end)

@Loovjo The \  character escapes any character that follows it, including /, which can later be used as normal. While this doesn't look like much, this makes /// Turing-complete.

I think this is a better explanation of the language than the esolangs wiki article. Will use this info in my /// IDE that I'm making!

APL (133)
{T←''∘{(0=≢⍵)∨'/'=⊃⍵:(⊂⍺),⊂⍵⋄(⍺,N⌷⍵)∇⍵↓⍨N←1+'\'=⊃⍵}⋄⍞N←T⍵⋄p N←T 1↓N⋄r N←T 1↓N⋄''≡N:→⋄∇{⍵≡p:∇r⋄∨/Z←p⍷⍵:∇(r,⍵↓⍨N+≢p),⍨⍵↑⍨N←1-⍨Z⍳1⋄⍵}1↓N}

This is a function that takes the /// code as its right argument.
Ungolfed, with explanation:
slashes←{
   ⍝ a function to split the input string into 'current' and 'next' parts,
   ⍝ and unescape the 'current' bit
   split←''∘{
       ⍝ if the string is empty, or '/' is reached,
       ⍝ return both strings (⍺=accumulator ⍵=unprocessed)
       (0=≢⍵)∨'/'=⊃⍵:(⊂⍺),⊂⍵
       ⍝ otherwise, add current character to accumulator,
       ⍝ skipping over '\'s. (so if '\/' is reached, it skips '\',
       ⍝ adds '/' and then processes the character *after* that.)
       idx←1+'\'=⊃⍵
       (⍺,idx⌷⍵)∇idx↓⍵
   }

   ⍞   next ← split ⍵      ⍝ output stage
   pat next ← split 1↓next ⍝ pattern stage, and eat the '/'
   rpl next ← split 1↓next ⍝ replacement stage, and eat the '/'

   ⍝ if there are no characters left, halt.
   ''≡next:⍬

   ⍝ otherwise, replace and continue.
   ∇{  ⍝ if the input string equals the pattern, return the replacement and loop
       ⍵≡pat:∇rpl

       ⍝ otherwise, find occurences, if there are, replace the first and loop
       ∨/occ←pat⍷⍵:∇(rpl, (idx+≢pat)↓⍵),⍨ (idx←(occ⍳1)-1)↑⍵

       ⍝ if no occurences, return string
       ⍵

   }1↓next
}

"if there are no characters left, halt." Does this work correctly on /// and //foo/ (i.e. loops forever)?

@algorithmshark: yes, in that situation the / would still be left at that point.

J - 181 190 170 char
This was a nightmare. I rewrote it from scratch, twice, because it just kept bugging me. This is a function taking a single string argument, outputting to STDOUT.
(0&$`((2{.{:@>&.>)((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i 5;@}.&,'/';"0;&.>)@.(2<#)@}.[4:1!:2~{:@>@p=.>@{.@[)@((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)i=. ::](^:_)

To explain, I will break it up into subexpressions.
i =. ::](^:_))
parse =: ((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)
print =: 4:1!:2~{:@>@p=.>@{.@[
eval  =: 0&$`((2{.{:@>&.>)sub 5;@}.&,'/';"0;&.>)@.(2<#)@}.
sub   =: ((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i

interp =: (eval [ print) @ parse i

i (short for iterate) is an adverb. It takes a verb argument on the left and returns a verb (f)i, which when applied to an argument, applies f repeatedly to the argument until one of two things happens: it finds a fixed point (y = f y), or it throws an error. The fixed-point behaviour is inherent to ^:_, and ::] does the error handling.
parse tokenizes the input into what I call half-parsed form, and then cuts it up at the unescaped '/'. It binds escaping backslashes to their characters, but doesn't get rid of the backslashes—so we can either revert it or finish it depending on which we want.
The bulk of the interesting work occurs in ;:. This is a sequential-machine interpreter primitive, taking a description of the machine ((0;(0,:~1 0,.2);'\';&<1 0)) on the left and something to parse on the right. This does the tokenizing. I will note that this specific machine actually treats the first character unspecial, even if it's a \ and should bind. I do this for a few reasons: (1) the state table is simpler, so it can be golfed further; (2) we can easily just add a dummy character to the front to dodge the problem; and (3) that dummy-character gets half-parsed at no extra cost, so I can use it to set up for the cutting phase, next.
We also use <;._1 to cut the tokenized result on unescaped / (which is what I choose to be the first char). This is handy for pulling out the output, pattern, and replacement from out/patt/repl/rest all in one step, but unfortunately also cuts up the rest of the program, where we need those / to stay untouched. I splice these back in during eval, because making <;._1 leave them alone ends up costing a lot more.
The fork (eval [ print) executes print on the result from parse for its side-effects, and then runs eval. print is a simple verb that opens up the first box (the one we know for sure is output), finishes parsing it, and sends it to STDOUT. However, we also take the chance to define a utility verb p.
p is defined as >@{.@[, so it takes its left arg (acts like the identity if given only one arg), takes the first item of that (identity when given a scalar), and unboxes it (identity if already unboxed). This will come in very handy in sub.
eval evaluates the remainder of the processed program. If we don't have a full pattern or a full replacement, eval throws it out and just returns an empty list, which terminates evaluation by making ;: (from parse) error out on the next iteration. Else, eval fully parses the pattern and replacement, corrects the remainder of the source, and then passes both to sub. By explosion:
                                              @}.  NB. throw out printed part
                                       @.(2<#)     NB. if we have a pattern and repl:
      2{.                                          NB.  take the first two cuts:
             &.>                                   NB.   in each cut:
         {:@>                                      NB.    drop escaping \ from chars
     (          )                                  NB.  (these are pattern and repl)
                                   &.>             NB.  in each cut:
                                  ;                NB.   revert to source form
                            '/';"0                 NB.  attach a / to each cut
                          &,                       NB.  linearize (/ before each cut)
                     5  }.                         NB.  drop '/pattern/repl/'
                      ;@                           NB.  splice together
    (            sub                  )            NB.  feed these into sub
   `                                               NB. else:
0&$                                                NB.  truncate to an empty list

sub is where one (possibly infinite) round of substitutions happens. Because of the way we set up eval, the source is the right argument, and the pattern and replacement are bundled together in the left. Since the arguments are ordered like this and we know the pattern and replacement don't change within a round of substitutions, we can use another feature of i—the fact that it modifies only the right argument and keeps passing in the same left—to delegate to J the need to worry about keeping track of the state.
There are two spots of trouble, though. The first is that J verbs can have at most two arguments, so we don't have an easy way to access any that are bundled together, like pattern and replacement, here. Through clever use of the p utility we defined, this isn't that big of a problem. In fact, we can access the pattern in one character, just by using p, because of its >@{.@[ definition: the Unbox of the First item of the Left arg. Getting the replacement is tricker, but the shortest way would be p&|., 2 chars shorter than manually getting it out.
The second problem is that i exits on fixed points instead of looping forever, and if the pattern and replacement are equal and you make a substitution, that looks like a fixed point to J. We handle this by entering an infinite loop of negating 1 over and over if we detect they are equal: this is the -i@=`p@.~:~/ portion, replacing p&|..
                                    p    E.]    NB. string search, patt in src
                                      I.@       NB. indices of matches
                                  0{            NB. take the first (error if none)
                               j=.              NB. assign to j for later use
                           #@p+                 NB. add length of pattern
                       ]}.~                     NB. drop that many chars from src
                   /@[                          NB. between patt and repl:
                  ~                             NB.  patt as right arg, repl as left
              @.~:                              NB.  if equal:
        -i@=                                    NB.   loop forever
            `p                                  NB.  else: return repl
 (j{.])                                         NB. first j chars of src
       ,              ,                         NB. append all together
(                                           )i  NB. iterate

This cycle repeats due to the use of i, until something outside of sub errors out. As far as I'm aware, this can only happen when we are out of characters, of when we throw out an incomplete set of pattern-and-replacement.

Fun facts about this golf:

For once, using ;: is shorter than manually iterating through the string.
0{ should have a chance to error out before sub goes into an infinite loop, so this it should work fine if the pattern matches the replacement but never shows up in the remainder of the source. However, this may or may not be unspecified behaviour, since I can't find a citation either way in the docs. Whoopsie.
Keyboard interrupts are processed as spontaneous errors inside running functions. However, due to the nature of i, those errors get trapped too. Depending on when you hit Ctrl+C, you might:

Exit out of the negate-forever loop, error out of the sub loop by trying to concatenate a number to a string, and then go on interpreting /// as if you finished substituting a string with itself an infinite number of times.
Leave sub halfway through and go on interpreting a half-subbed /// expression.
Break out of the interpreter and return an unevaluated /// program to the REPL (not STDOUT, though).

Example usage:
   f=:(0&$`((2{.{:@>&.>)((j{.]),-i@=`p@.~:~/@[,]}.~#@p+j=.0{p I.@E.])i 5;@}.&,'/';"0;&.>)@.(2<#)@}.[4:1!:2~{:@>@p=.>@{.@[)@((0;(0,:~1 0,.2);'\';&<1 0)<;._1@;:'/'&,)i=. ::](^:_)
   f 'no'
no
   f '/ world! world!/Hello,/ world! world! world!'
Hello, world!
   f '/foo/Hello, world!//B\/\\R/foo/B/\R'
Hello, world!
   f '//'  NB. empty string

   f '/\\/good/\/'
good

Wow. I would call this masochistic. +1

When I run this, I get the empty string from every test case. I'm using jqt64, what are you using to run this?

@bcsb1001 I've been using the (64-bit) jconsole binary directly. Checking jqt now, I am getting actually getting intended results except for the /\\/good/\/ test case; debugging tells me the issue is my use of 1!:2&4, since jqt does not have stdin/out. Will investigate. What are your 9!:12'' and 9!:14''?

@algorithmshark My 9!:12'' is 6, and 9!:14'' is j701/2011-01-10/11:25.

Pip, 100 102 bytes
I hadn't ever proven Pip to be Turing-complete (though it's pretty obviously so), and instead of going the usual route of BF I thought /// would be interesting. Once I had the solution, I figured I'd golf it and post it here.
101 bytes of code, +1 for -r flag:
i:gJnf:{a:xW#i&'/NE YPOia.:yQ'\?POiya}W#iI'\Q YPOiOPOiEIyQ'/{p:VfY0s:VfIyQ'/WpNi&YviR:Xp{++y?ps}}E Oy

Here's my ungolfed version with copious comments:
; Use the -r flag to read the /// program from stdin
; Stdin is read into g as a list of lines; join them on newline and assign to c for code
c : gJn

; Loop while c is nonempty
W #c {
 ; Pop the first character of c and yank into y
 Y POc
 ; If y equals "\"
 I yQ'\
  ; Pop c again and output
  O POc
 ; Else if y equals "/"
 EI yQ'/ {
  ; Build up pattern p from empty string
  p : ""
  ; Pop c, yank into y, loop while that is not equal to "/" and c is nonempty
  W #c & '/ NE Y POc {
   ; If y equals "\"
   I yQ'\
    ; Pop c again and add that character to p
    p .: POc
   ; Else, add y to p
   E p .: y
  }

  ; Yank 0 so we can reliably tell whether the /// construct was completed or not
  Y0
  ; Build up substitution s from empty string
  s : ""
  ; Pop c, yank into y, loop while that is not equal to "/" and c is nonempty
  W #c & '/ NE Y POc {
   ; If y equals "\"
   I yQ'\
    ; Pop c again and add that character to s
    s .: POc
   ; Else, add y to s
   E s .: y
  }

  ; If the last value yanked was "/", then we have a complete substitution
  ; If not, the code must have run out; skip this branch, and then the outer loop
  ; will terminate
  I yQ'/ {
   ; While pattern is found in code:
   W pNc {
    ; Set flag so only one replacement gets done
    i : 0
    ; Convert p to a regex; replace it using a callback function: if ++i is 1,
    ; replace with s; otherwise, leave unchanged
    c R: Xp {++i=1 ? s p}
   }
  }
 }
 ; Else, output y
 E Oy
}

Try it online! (Note that TIO doesn't give any output when the program is non-terminating, and it also has a time limit. For larger examples and infinite loops, running Pip from the command line is recommended.)

I think this should be pip + -r, 101 bytes

I believe that you don’t need to count the flag bytes, as that is considered a separate language with the flag.

Perl - 190
$|=1;$/=undef;$_=<>;while($_){($d,$_)=/(.)(.*)/;eval(!$e&&({'/','$a++','\\','$e=1'}->{$d})||('print$d','$b.=$d','$c.=$d')[$a].';$e=0');if($a==3){while($b?s/\Q$b/$c/:s/^/$c/){}$a=0;$b=$c=''}}

Reads /// program from stdin until EOF.

Would an approach along the lines of m/^(.*?)(?<!\\)\/(.*?)(?<!\\)\/(.*?)(?<!\\)\/(.*)$/s--i.e. match output, pattern, and replacement all at once--make for a shorter golf? I don't know any Perl, myself.

I believe this fails with /a/\0/a

C++ 347
Edits:

Thanks to @algorithmshark for lots of help making the original shorter
Thanks to @Adalynn for a good suggestion to save bytes
Thanks to @ceilingcat for many, many very nice pieces of golfing - now even shorter

Here is the code:
#import<bits/stdc++.h>
#define N(x)o[i]);else if(n<x)o[i]==92?
#define O (o[++i]):o[i]==47?n++:
char p[198],*q=p,*s=p+99;int i,t;main(int n,char**m){for(std::string o=m[1];i<=o.size();++i){if(!N(3)putchar O putchar(N(4)*q++=O(*q++=N(5)*s++=O(*s++=o[i]);if(n>4){for(n=2;~(t=o.find(p,i+1));o=o.substr(0,t)+s+&o[t+strlen(p)])s=p+99;bzero(q=p,198);}}}

Try it online!

Can you rewrite if(!o[i]); as if(P to save chars, or am I misunderstanding how #define works?

@algorithmshark how did I miss that?!  if(!P is perfect.  I'll change it.

Every instance of P in main has a space after it, so you can save a character by replacing those spaces with semicolons and removing it from #define. Then, if you can use #defines inside other ones, you can save some more by rewriting N(x) as (92==P instead of o[i]==92 and O likewise.

@algorithmshark you are obviously much better at this than I.  Thanks for the help.

I know this is about four years old, but rewriting N(x) as P;else if(n<x)(P==92? and changing calls to N accordingly could save a few bytes.

@ceilingcat  Each edit seems to make an additional edit more likely...  Thanks very much for all the golfing help.

Cobra - 226
sig Z as String
def f(l='')
    m=Z(do=[l[:1],l=l[1:]][0])
    n as Z=do
        if'/'<>(a=m())>'',return if(a=='\\',m(),a)+n()
        else,return''
    print n()stop
    p,s=n(),n()
    if''<l
        while p in l,l=l[:l.indexOf(p)+1]+s+l[p.length:]
        .f(l)

Python 2 (236), Python 3 (198?)
from __future__ import print_function
def d(i):
 t=0;p=['']*3+[1]
 while i:
  if'/'==i[0]:t+=1
  else:
   if'\\'==i[0]:i=i[1:]
   p[t]+=i[0]
  i=i[1:]
  print(end=p[0]);p[0]=''
  if t>2:
   while p[1]in i:i=i.replace(*p[1:])
   d(i);i=0

Called as d(r"""/foo/Hello, world!//B\/\\R/foo/B/\R""").  The triple quotes are only needed if the /// program contains newlines: otherwise simple quotes are ok.
EDIT: This interpreter now prints stuff as expected (previously it only printed at the very end, cf. comments).  For Python 3, remove the first line (but I don't have Python 3 on my ancient install, so cannot be sure there is no other change).

the interpreter not printing anything until termination is  problematic. writing an infinite loop in /// is possible, so your interpreter fails on non-terminating-but-still-printing-something programs.

@proudhaskeller Fixed.

Actually, this isn't fixed, it doesn't print anything for /a/ab/bbaa/abb.

@BetaDecay /a/ab/bbaa/abb will get stuck in an endless loop without printing anything, because the first substitution is a=>ab. The correct a/ab/bbaa/abb works as advertised.

@BetaDecay: besides the change suggested by algorithmshark, you may need to include the command line option -u to force the output buffer to be unbuffered.

BaCon, 391 387 395 bytes
From the contributions on this page I only got the Python program to work. The others work for some /// samples, or do not work at all. Therefore, I decided to add my version, which is an implementation in BASIC.
To compete in a CodeGolf contest with BASIC is not easy, as BASIC uses long words as statements. The only abbreviation commonly found in BASIC is the '?' sign, which means PRINT.
So the below program may never win, but at least it works with all demonstration code on this Codegolf page and on the Esolangs Wiki. Including all versions of the "99 bottles of beer".
p$=""
r$=""
INPUT i$
WHILE LEN(i$)
t$=LEFT$(i$,1)
i$=MID$(i$,2)
IF NOT(e) THEN
IF t$="\\" THEN
e=1
CONTINUE
ELIF t$="/" THEN
o=IIF(o<2,o+1,0)
IF o>0 THEN CONTINUE
FI
FI
IF o=1 THEN
p$=p$&t$
ELIF o=2 THEN
r$=r$&t$
ELIF o=0 THEN
IF LEN(p$) THEN i$=REPLACE$(i$,p$,r$)
IF NOT(INSTR(t$&i$,"/")) THEN
?t$;
BREAK
ELSE
?LEFT$(i$,INSTR(i$,"/")-1);
i$=MID$(i$,INSTR(i$,"/"))
FI
p$=""
r$=""
FI
e=0
WEND
?i$

Added INPUT statement to get input from user.

What a delicious language!

Ruby, 119 110 bytes
Terminates with exception
r=->s,o=$>{s[k=s[0]]='';k==?/?o==$>?s.gsub!([r[s,''],e=r[s,'']][0]){e}:t=o:o<<(k==?\\?s[0]+s[0]='':k);t||redo}

Try it online!
Terminates cleanly (116 bytes)
r=->s,o=$>{s[k=s[0]||exit]='';k==?/?o==$>?s.gsub!([r[s,''],e=r[s,'']][0]){e}:t=o:o<<(k==?\\?s[0]+s[0]='':k);t||redo}

Try it online!

Python 2/3 (211 bytes)
The following code, based on Bruno Le Floch's answer, is Python 2 and Python 3 compatible.
Moreover, being iterative rather than recursive it does not risk hitting the maximum recursion depth of Python.
def S(c):
 while c:
  B=["","",1]
  for m in 0,1,2:
   while c:
    if"/"==c[0]:c=c[1:];break
    if"\\"==c[0]:c=c[1:]
    if m:B[m-1]+=c[0]
    else:yield c[0]
    c=c[1:]
  while c and B[0]in c:c=c.replace(*B)

Hello and welcome to PPCG. You can golf in(0,1,2) to in 0,1,2 and [""]*2+[1] to ["","",1], resulting in 211 bytes.

I have linked to the referred answer and added the word "bytes". If you disagree with my edit, feel free to roll back.

Thanks Jonathan, your suggestions are very welcome!

source: Stack Exchange

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

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

sort: votes


text:
These Primes of Mine Are Always Solid Lines
Let's create a N×N grid of spaces and underscores that can be used to visually determine if a number is prime. (N may be any positive integer.)
This grid has three simple rules:

The nth column contains the repeated pattern of n - 1 underscores followed by one space. This pattern starts at the first row and is stopped, possibly mid-pattern, at row N. (Rows and columns are 1-indexed.)
The first column is replaced with all underscores instead of all spaces.
If a space occurs somewhere the row index equals the column index it is replaced with an underscore.

Example: N = 10
           1
  1234567890 <-- column indices
 1__________
 2__________
 3__________
 4_ ________
 5__________
 6_  _______
 7__________
 8_ _ ______
 9__ _______
10_ __ _____
 ^ row indices

The indices are just for clarity. The plain grid itself (what your program must output) is:
__________
__________
__________
_ ________
__________
_  _______
__________
_ _ ______
__ _______
_ __ _____

Notice that:

The first column is all underscores.
The second column goes underscore space, underscore space, etc., except for the underscore on row 2.
The third column goes underscore underscore space, underscore underscore space, etc., except for the underscore on row 3.
etc.

Also notice that besides 1, only prime numbered rows have underscores in every column.
Since underscores span the entire font width, each prime numbered row forms a continuous solid line. So checking if a number is prime or not is quite easy visually; just check if its line is solid across all columns. (In fact looking up to the square root of the row index suffices but outputting that grid seems less elegant.)
Program
Write a program that will draw these grids given N via stdin (or closest alternative). Output goes to stdout (or closest alternative) and should only contain spaces, underscores, and newlines, with an optional trailing newline.
The shortest code wins.

I don't get how does it determine prime number

@FilipBartuzi Maybe check out http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

"The nth column contains the repeated pattern of n - 1 underscores followed by one space." So shouldn't column n=1 be all spaces, not all underscores?

@algorithmshark Fixed

It's a good thing those indices don't need to be printed. Was starting to remind me of the punch card one

I must say I don't particularly like the "no trailing newline" requirement. This is very difficult in some languages, downright impossible in others and it only affects programs that print to STDOUT.

@Dennis Really? Why would it be impossible? I've allowed a trailing newline anyway since its presence has little to do with the challenge.

Some languages have limited input/output format since they're not made for "programs" in the usual sense. I'm thinking about Mathematica, Octave, etc. I believe J is one of those languages too, but I'm not actually sure. -- Thanks for changing the requirement. I had to either ask you or leave a comment under every other answer...

The description was hard for me to understand. This is how I would describe it: Start with a grid of N lines of N underscores. For the nth line, make the kth character a space if k is a divisor of m that isn't 1 or m.

CJam, 33 28 27 bytes
q~,:)_f{f{md\1=+'_S?}0'_tN}

Try it online.
How it works
q~        " Read one line from STDIN and evaluate it.                                     ";
,:)       " For “N”, push [ 1 ... N ].                                                    ";
_         " Push a copy.                                                                  ";
f{        " For each “I in [ 1 ... N ], push “I   [ 1 ... N ]”; then:                     ";
  f{      " For each “J in [ 1 ... N ], push “J   I”; then:                               ";
    md\   " Push “J % I   J / I”.                                                         ";
    1=+   " Calculate “J % I + (J / I == 1)”.                                             ";
    '_S?  " Push an underscore if the result is truthy and a space otherwise.             ";
  }       "                                                                               ";
  0'_t    " Replace the first character of the resulting array by an underscore.          ";
  N       " Push a newline.                                                               ";
}         "                                                                               ";

Example run
$ cjam solid-primes.cjam <<< 10
__________
__________
__________
_ ________
__________
_  _______
__________
_ _ ______
__ _______
_ __ _____
$ cjam solid-primes.cjam <<< 100 | md5sum # trailing newline
e4396b316989813dada21141b569ccf9  -

I'll post an explanation when I'm done golfing.

33 bytes and you're not done golfing??

Ruby, 77 73 characters
puts (1..n=gets.to_i).map{|a|?_+(2..n).map{|b|a!=b&&a%b==0? ' ':?_}.join}

Some tricks I used:

The .. operator has almost the lowest precedence of all operators in Ruby, so (1..n=gets.to_i) just works.
Instead of adding an extra a!=1 condition when checking to see if the character should be a space instead of an underscore (since the first row is all underscores), I just started the range from 2 and prepended an extra ?_.
Line A can become line B:
A | a%b==0&&a!=b ? ' ':?_
B | a!=b&&a%b==0? ' ':?_

because I have to have an extra space between b and ? in line A, but that's not needed between 0 and ? in line B. b? is a valid Ruby method, but 0? is not.
puts will automatically join arrays with newlines for you, removing the need for an extra *"\n".

Output for n=100:
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
_ __________________________________________________________________________________________________
____________________________________________________________________________________________________
_  _________________________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ________________________________________________________________________________________________
__ _________________________________________________________________________________________________
_ __ _______________________________________________________________________________________________
____________________________________________________________________________________________________
_   _ ______________________________________________________________________________________________
____________________________________________________________________________________________________
_ ____ _____________________________________________________________________________________________
__ _ _______________________________________________________________________________________________
_ _ ___ ____________________________________________________________________________________________
____________________________________________________________________________________________________
_  __ __ ___________________________________________________________________________________________
____________________________________________________________________________________________________
_ _  ____ __________________________________________________________________________________________
__ ___ _____________________________________________________________________________________________
_ ________ _________________________________________________________________________________________
____________________________________________________________________________________________________
_   _ _ ___ ________________________________________________________________________________________
____ _______________________________________________________________________________________________
_ __________ _______________________________________________________________________________________
__ _____ ___________________________________________________________________________________________
_ _ __ ______ ______________________________________________________________________________________
____________________________________________________________________________________________________
_  _  ___ ____ _____________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ___ _______ ____________________________________________________________________________________
__ _______ _________________________________________________________________________________________
_ ______________ ___________________________________________________________________________________
____ _ _____________________________________________________________________________________________
_   _ __ __ _____ __________________________________________________________________________________
____________________________________________________________________________________________________
_ ________________ _________________________________________________________________________________
__ _________ _______________________________________________________________________________________
_ _  __ _ _________ ________________________________________________________________________________
____________________________________________________________________________________________________
_  __  ______ ______ _______________________________________________________________________________
____________________________________________________________________________________________________
_ _ ______ __________ ______________________________________________________________________________
__ _ ___ _____ _____________________________________________________________________________________
_ ____________________ _____________________________________________________________________________
____________________________________________________________________________________________________
_   _ _ ___ ___ _______ ____________________________________________________________________________
______ _____________________________________________________________________________________________
_ __ ____ ______________ ___________________________________________________________________________
__ _____________ ___________________________________________________________________________________
_ _ ________ ____________ __________________________________________________________________________
____________________________________________________________________________________________________
_  __ __ ________ ________ _________________________________________________________________________
____ _____ _________________________________________________________________________________________
_ _ __  _____ _____________ ________________________________________________________________________
__ _______________ _________________________________________________________________________________
_ __________________________ _______________________________________________________________________
____________________________________________________________________________________________________
_     ___ _ __ ____ _________ ______________________________________________________________________
____________________________________________________________________________________________________
_ ____________________________ _____________________________________________________________________
__ ___ _ ___________ _______________________________________________________________________________
_ _ ___ _______ _______________ ____________________________________________________________________
____ _______ _______________________________________________________________________________________
_  __ ____ __________ __________ ___________________________________________________________________
____________________________________________________________________________________________________
_ _ ____________ ________________ __________________________________________________________________
__ ___________________ _____________________________________________________________________________
_ __ _ __ ___ ____________________ _________________________________________________________________
____________________________________________________________________________________________________
_   _ _  __ _____ _____ ___________ ________________________________________________________________
____________________________________________________________________________________________________
_ __________________________________ _______________________________________________________________
__ _ _________ _________ ___________________________________________________________________________
_ _ ______________ __________________ ______________________________________________________________
______ ___ _________________________________________________________________________________________
_  __ ______ ____________ ____________ _____________________________________________________________
____________________________________________________________________________________________________
_ _  __ _ _____ ___ ___________________ ____________________________________________________________
__ _____ _________________ _________________________________________________________________________
_ ______________________________________ ___________________________________________________________
____________________________________________________________________________________________________
_   _  ____ _ ______ ______ _____________ __________________________________________________________
____ ___________ ___________________________________________________________________________________
_ ________________________________________ _________________________________________________________
__ _________________________ _______________________________________________________________________
_ _ ___ __ __________ _____________________ ________________________________________________________
____________________________________________________________________________________________________
_  _  __  ____ __ ___________ ______________ _______________________________________________________
______ _____ _______________________________________________________________________________________
_ _ __________________ ______________________ ______________________________________________________
__ ___________________________ _____________________________________________________________________
_ ____________________________________________ _____________________________________________________
____ _____________ _________________________________________________________________________________
_   _ _ ___ ___ _______ _______ _______________ ____________________________________________________
____________________________________________________________________________________________________
_ ____ ______ __________________________________ ___________________________________________________
__ _____ _ _____________________ ___________________________________________________________________
_ _  ____ _________ ____ ________________________ __________________________________________________

Now including Extra-Special™ Mega-Colorful Red© Highlight-Magic™® Extended Edition©: (click thumbnail to enlarge)
Ruby with color, 110 characters
puts (1..n=gets.to_i).map{|a|x=(2..n).map{|b|a!=b&&a%b==0? ' ':?_}.join;x.index(' ')??_+x :"\e[41m_#{x}\e[0m"}

That looks like it should be a fractal...

Remove the space within the ternary before the ' '. It probably messes up your syntax highlighter, but it still works properly. Also, a%b<1

*'' will work the same as join, and you can check for a<b instead of a!=b since no factor of a is greater than a. There might also be savings from slicing into a two-character string with the result of some math on a and b instead of using a ternary.

J - 28 char
1('_ '{~0==+&|:1&=+|/~)@:+i.

Explained by explosion:
1(                    )@:+i.  NB. on vector 1..n, do
                   |/~        NB. take the table "column modulo row"
               1&=+           NB. add 1 to column 1
          =                   NB. identity matrix of size 10
            &|:               NB. transpose both tables (now table is row mod col)
           +                  NB. add them
  '_ '{~0=                    NB. space if cell=0 else underscore

What it looks like:
   1('_ '{~0==+&|:1&=+|/~)@:+i.25
_________________________
_________________________
_________________________
_ _______________________
_________________________
_  ______________________
_________________________
_ _ _____________________
__ ______________________
_ __ ____________________
_________________________
_   _ ___________________
_________________________
_ ____ __________________
__ _ ____________________
_ _ ___ _________________
_________________________
_  __ __ ________________
_________________________
_ _  ____ _______________
__ ___ __________________
_ ________ ______________
_________________________
_   _ _ ___ _____________
____ ____________________

Python 2, 76 71
r=range(1,input()+1)
for i in r:print''.join("_ "[i%j<1<j<i]for j in r)

Not sure if it can get any shorter than this... These keywords: range, input and print cost quite a lot.

You can replace i>j>1and i%j<1 with i>j>1>i%j

@Sieg: Cool! It's actually my first time exploiting these concatenated comparisons.

I had written this exact code character-for-character up to var names, including the i%j<1<j<i :-P. So maybe it really doesn't get any shorter.

Actually, I think (not tested) you can do i%j<1. It implies i>=j.

@Sieg: Yes, but we need i>j, not i>=j to avoid blanks on the diagonal.

Alright. I thought that might be the case, but offered it anyways. I'm too lazy to check the specs.

APL (28)
'_ '[(1+(1≠⊢)∧≠∧0=|⍨)/¨⍳2⍴⎕]

Explanation:

⍳2⍴⎕: read a number N and make an N-by-N coordinate matrix
(...)/¨: for each pair of coordinates, apply the following function:

A cell must have a space if:
0=|⍨: y mod x = 0, and
≠: x isn't equal to y, and
1≠⊢: x isn't 1.
1+: Add 1 to the resulting bit matrix because APL arrays start at 1.

'_ '[...]: replace each 1 with an underscore and 2 with a space.

Apparently 28 is the magic golfing number here.

Perl,   69   61
Updated version (thanks, Dennis!)
$n=<>;for$i(1..$n){say"_".join"",map{$i%$_|$i==$_?_:$"}2..$n}

Original version:
$n=<>;for$i(1..$n){say"_".join("",map{$i%$_||$i==$_?"_":" "}(2..$n))}

Neither join nor 2..$n need parentheses. 2. With the -n switch, you can use $_ instead of $n. 3. _ is a valid bareword, so it doesn't need quotes. 4. You can use $" instead of " ". 5. You can use |  instead of ||.

@Dennis — Thanks! I applied a few of those. I didn't do the -n thing because I wanted to keep it a self-contained program and not have to say $^N=1. The use of _ as a bareword worked in the case of $i==_ but didn't work in the case of $i%_ because the parser thought %_ was a hash.

You can keep it self-contained with a shebang (#!/bin/perl -n is usually counted as 1 byte), but that's obviously up to you. I have no idea what $^N=1 does... 2. $i==_ won't work properly; it will test if $i == "_". What I meant is using _ instead of "_", i.e., say _ and $i==$_?_:$".

@Dennis — ohhhh crap, you're right. The edit I made introduced a diagonal line through the matrix. Shame on me for not catching that. Fixed. I see what you mean about _ = "_" now. Unfortunately, it works in the latter case but gives me an error next to the say because it seems to think it's a filehandle.

CJam, 27 bytes
q~:I,{__I?'_*S+I*I<'_t}%zN*

Try it online.
This approach achieves the same byte count as my other answer, but I thought it was worth posting anyway. Instead of marking proper multiples in every row, it does exactly what the specification says.
How it works
q~:I                         " Read an integer I from STDIN.                              ";
    ,{                }%     " For each J ∊ {1,...,I}:                                    ";
          '_*S+              " Push J - 1 underscores followed by a space.                ";
               I*I<          " Repeat the pattern to complete I characters.               ";
       _I?                   " For the first row, replace all spaces with underscores.    ";
      _            '_t       " Replace the Jth character by an underscore.                ";
                        zN*  " Transpose rows and columns; separate with linefeeds.       ";

Example run
$ cjam prime-lines.cjam <<< 10; echo
__________
__________
__________
_ ________
__________
_  _______
__________
_ _ ______
__ _______
_ __ _____
$ cjam prime-lines.cjam <<< 100 | md5sum # no trailing newline
83c7b974e1510f482322456a9dbb461f  -

C, 143
C is obviously not the right choice of language for this. But for completeness, here's one possible way to do it in C. Works for values of n up to 1048575. Reads n from standard input.
#include <stdio.h>
main(){int n,i=0,j;scanf("%d",&n);char x[1<<20];x[n+1]=0;
for(;++i<=n;){for(j=0;++j<=n;)x[j]=i%j|i==j|j==1?95:32;puts(x+1);}}

It is very fast, however.

Runtime for n=1,000,000 (which produces a 1,000,000,000,000-element grid) is approximately 55 minutes on my system.
Runtime for n=1000 (which produes a 1,000,000-element grid) is less than 1/100 second.

The include is not needed for some compilers (e.g., GCC), so you can remove it. 2. Global variables initialize to 0 and default to int, so you can use char x[1<<20];n,i,j;main.... 3. for(scanf("%d",&n);i++<n;) saves two bytes over scanf("%d",&n);for(;++i<=n;).

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


text:
Find the maximum operation
The challenge is to find the maximum number you can get from a list of integer using basic arithmetic operators (addition, substraction, multiplication, unary negation)
Input
A list of integers
Output
The maximum result using every integer in the intput.
The input order doesn't matter, result should be the same.
You do not need to output the full operation, just the result.
Examples
Input : 3 0 1
Output : 4 (3 + 1 + 0)

Input : 3 1 1 2 2
Output : 27 ((2+1)*(2+1)*3))

Input : -1 5 0 6
Output : 36 (6 * (5 - (-1)) +0)

Input : -10 -10 -10
Output : 1000 -((-10) * (-10) * (-10))

Input : 1 1 1 1 1
Output : 6 ((1+1+1)*(1+1))

Rules

Shortest code wins
Standard "loopholes" apply
You may only use + * - operators (addition, multiplication, substraction, unary negation)
The code should work as long as the result can be stored on a 32 bit Integer.
Any overflow behaviour is up to you.

I hope this is clear enough, this is my first Code Golf challenge suggestion.

One of your examples is using an operation which isn't permitted: if unary negation is intended to be in your whitelist then subtraction isn't really necessary.

Editted and added unary negation. Substraction is kept in the whitelist.

Does it have to be a full program or is a function enough?

Full program. Even better if it can be run online, but obviously not mandatory

@INSeed Should i add a way to run online?

@proudhaskeller no this is fine ! :)

C - 224 bytes - Running time O(n)
o=0,w=0,n[55],t,*m=n,*p=n;main(r){for(;scanf("%d",++p);t<3?--p,w+=t/2,o+=t&1:t<*m|m==n?m=p:9)t=*p=abs(*p);t=o<w?o:w;o-=t;w-=t;t+=o/3;for(o%3?o%3-2?t?t--,w+=2:++*m:w++:9;t--;)r*=3;for(r<<=w;--p>n;)r*=*p;printf("%d",r>1?r:o);}

It was amusing to see only exponential-time solutions for a linear-time problem, but I suppose it was the logical way to proceed since there were no bonus points for actually having an algorithm, which is an anagram of logarithm.
After converting negative numbers to positive and discarding zeroes, clearly we are mostly interested in multiplication. We want to maximize the logarithm of the final number.
log(a + b) < log(a) + log(b) except when a = 1 or b = 1, so ones are the only case in which we are interested in adding anything together. In general it is better to add a 1 to  a smaller number, because that causes a bigger increase in logarithm, i.e. a larger percentage increase, than adding 1 to a big number.
There are four possible scenarios, ordered most to least preferable, for utilizing ones:

Adding one to a 2 gives +log .405  [log(3) - log(2)]
Combining ones into threes gives +log .366 per one  [log(3) / 3]
Making a 2 out of ones gives +log .347 per one  [log(2) / 2]
Adding one to a number 3 or higher gives +log .288 or less  [log(4) - log(3)]

The program keeps track of the number of ones, the number of twos, and the minimum number greater than 2, and goes down the list of the most to least preferable ways of using the ones. Finally, it multiplies all the remaining numbers.

Haskell, 126 characters
this is just brute-forcing, with the exception of ignoring the sign of the input and ignoring subtraction and unary negation.
import Data.List
f[x]=abs x::Int
f l=maximum$subsequences l\\[[],l]>>= \p->[f p+f(l\\p),f p*f(l\\p)]
main=interact$show.f.read

this code is extremely slow. the code recursively calculates f on each subsequence of the input four times (except for [] and the input itself). but hey, it's code golf.

SWI-Prolog - 250
Oh boy, I spent way too long on this.
o(A,B,A+B).
o(A,B,A-B).
o(A,B,A*B).
t([],0).
t([A,B|T],D):-t(T,Q),o(A,B,C),o(C,Q,D).
t([A|T],C):-t(T,Q),o(A,Q,C).
a(A):-t(A,B),n(C),B>C,retract(n(C)),assert(n(B)).
m(A):-assert(n(0)),\+p(A),n(R),R2 is R,write(R2).
p(A):-permutation([0|A],B),a(B),0=1.

Called from command line (e.g.):
> swipl -s filename.pl -g "m([1, 1, 1, 1, 1])" -t halt
6

(For no particlar reason, I found it awesome that my golfed function names spell "tomato pot.")
Ungolfed version:
% Possible operations
operation(Left, Right, Left + Right).
operation(Left, Right, Left - Right).
operation(Left, Right, Left * Right).

% Possible ways to transform
transform([], 0).
transform([A, B|T], D) :- transform(T, Q), operation(A, B, C), operation(C, Q, D).
transform([A|T], C) :- transform(T, Q), operation(A, Q, C).

% Throw the given array through every possible transformation and update the max
all_transforms(A) :- transform(A, B), n(C), B>C, retract(n(C)), assert(n(B)).

% Find all the permutations and transformations, then fail and continue execution.
prog(A) :- assert(n(0)), !, permutation([0|A], B), all_transforms(B), fail.

% End the program
finished :- n(R), write(R), nl, R2 is R, write(R2), nl.

% Run the program
main(A) :- ignore(prog(A)), finished.

Explanation:

Take in an array as an argument.
Get all permutations of the array.
Find some arrangement of operators to add to the array. (This is done via dynamic programming, seeing whether it's better if we combine the first two elements or not.)
Check this against our current max value. If it's better, replace it.
Tell the program we failed so that it keeps checking, but then negate that (using ignore or \+) to let the predicate overall return true and continue.
We're given a string of predicates, instead of a number, so assign it using is and then write it.

Scala, 134
print(args.map(Math abs _.toInt)./:(Seq(Array(0)))((l,a)=>l.map(a+:_)++l.flatMap(_.permutations.map{r=>r(0)+=a;r}))map(_.product)max)

Ungolfed & commented:
print(
  args
    .map(Math abs _.toInt)                     // to int, ignoring -
    .foldLeft(Seq(Array(0))){ (list,num) =>    // build up a list of sums of numbers
      list.map(num+:_) ++                      // either add the new number to the list
      list.flatMap(_.permutations.map{ copy =>
        copy(0)+=num                           // or add it to one of the elements
        copy
      })
    }
    .map(_.product) // take the maximum of the the products-of-sums
    .max
)

A slightly different approach, from realizing that the biggest answer can always be expressed as a product of sums.
So close, but a bunch of library stupidity (permutations returns an Iterator instead of a Seq, horrible type inference on empty sequences, Array.update returning Unit) did me in.

Haskell - 295 290 265 246 203 189 182 bytes

Finally works! Also now it is a brute force rather than a dynamic solution.

Thanks to proudhaskeller for some of the golfing tips.
This is probably not a fully golfed solution because I actually suck at golfing, but it is the best I can come up with (and it looks complicated, so I got that going for me):
import Data.List
main=interact$show.g.read
g x=maximum[product$a#b|a<-sequence$replicate(length x-1)[0,1],b<-permutations x]
(a:b)#(c:d:e)|a>0=b#(c+d:e)|0<1=c:b#(d:e)
_#x=x

New test cases:
[1,1,1,2,2]
12

[1,1,3,3,3]
54

[1,1,1,1,1,1,1,1,5,3]
270

Solution explanation:
The main function just gets an input and runs g with it.
g takes the input and returns the maximum of all possible combinations of sums and list orders.
# is the function which calculates the sums in a list like this:
a = [1,0,0,1]
b = [1,1,1,2,2]
a#b = [2,1,4]

this seems like quite a performance-driven solution.

can you please write newlines instead of ; when possible? it doesn't change the byte count but helps the readability troumendously

@proudhaskeller I had no idea how to brute force this so I had to come up with something else :D

my advice for golfing this - 1) inline every function that is used just once (unless it uses pattern matching or guards). 2) you can implement d as d n=[0,2,1]!!n or d n=mod(3-n)3. 3) make o and g take the length of the list instead of taking the list itself, as they only depend on the length (obviously this stands only as long as they aren't inlined). 4) replace otherwise with 0<1. 5) make the last definition of r be r$o x:y. 6) remove the a@ and replace a with x:y. good luck with your golfing!

Your algorithm gives the wrong answer for [3,3,3,2,2,2,1,1,1].  I ran your code, and it returns 216 (the largest result I was able to come up with was 729).

@Brilliand Yes, I realised too, I will see what I can do.

@ThreeFx i see there that you didn't use all my tips, was i not clear enough?

@ThreeFx just realized that you could redefine f this way: f=r.tail.group.sort.map abs.(0:). This works by making sure the list has a 0 by adding 0 to it, and ignoring the first group which must be all zeros instead of using filter(/=0).

@proudhaskeller The problem is that I realised that it is broken and fist of all I want to fix that

@Brilliand Fixed.

Nice use of sequence!

The best i could think of instead of your sequence trick is iterate(>>= \x->[0:x,1:x])!!lengh x but yours is shorter. Nice!

@ThreeFx my tips for this version: make h infix. Use a>0 instead of a==1. You should swap the order of the definitions of h, which allowed you to replace [] with _ and this will enable you to use remove the -1 from lengh x-1, unless i'm mistaken.

@TreeFx shouldn't the example be [2,1,4]?

Python 278 (O(n!))
from itertools import*
def f(n):
 f,n,m=lambda n:[(n,)]+[(x,)+y for x in range(1,n)for y in f(n-x)],map(abs,map(int,n.split())),0
 for p,j in product(permutations(n),f(len(n))):
  i=iter(p)
  m=max(m,reduce(lambda e,p:e*p,(sum(zip(*zip([0]*e,i))[1])for e in j)))
 return m

Explanation

Unary Negate should be judiciously used to convert all negative numbers to positive
Find all possible permutations of the numbers
Using Integer partition to find all power-sets of a given permutation
Find the product of the sums
Return the maximum of the product of the sums

GolfScript (52 chars)
~]0-{abs}%.1-.1,or@,@,-,-1%{!\$.0=3<@+{()}1if+}/{*}*

Online demo
feersum's analysis is pretty good but it can be taken further if the goal is golfing rather than efficiency. In pseudo-code:
filter zeros from input and replace negatives with their absolute value
filter ones to get A[]
count the ones removed to get C
while (C > 0) {
    sort A
    if (A[0] < 3 || C == 1) A[0]++
    else A.append(1)
    C--
}
fold a multiply over A


text:
PNG Pixel Forces

Challenge
A Pixel World is a PNG image where gravitational, electromagnetic, and nuclear forces no longer exist. Special forces known as "pixel forces" are all that remain. We define this force as

Fp->q = a * (p * q) / (r * r) * r̂

F is the pixel force that p exerts on q
a is Adams' constant, defined as  a = 4.2 * 10 ^ 1
p and q are charges on two pixels
r is the distance from p to q
r̂ is the direction of r in radians, measured counterclockwise* from the positive x-axis

*There are infinitely many acceptable values for any given direction. For example, 6.28, 0, -6.28, and -12.57 radians are all equivalent, and would all be accepted.
Three types of pixels exist:

A red pixel holds a charge of positive one
A black pixel holds a charge of negative one
A white pixel holds a charge of zero

The bottom left pixel of pixel world is located at (0, 0). The positive y axis falls up the page, and the positive x axis falls to the right. The total force on a pixel is simply the vector sum of all forces exerted upon that pixel. Like charges repel, and opposite charges attract.
Given a file path to a Pixel World, as well as two integers x and y, output the total force exerted on the pixel at location (x, y) in the format <magnitude>\n<direction>. Output must be accurate to at least 2 decimal places, but you may output more if you want. Direction must be output in radians. The integers x and y are guaranteed to be within the world boundary.
Deliverables
You must include a program, and a command that can be used to run your program. Two examples:

python AbsolutelyPositive.py "C:\Pixtona.png" 50 40
java UltimateAttraction "C:\Jupix.png" 30 30

Example Image
In the image below, there is a black pixel at (100, 104).

Pixars.png

Example Output
This output does not correspond to the above input.

534.19721014
4.32605416

Need help getting started?
I wrote some example code here. I haven't tested it, so use it at your own risk.

Can it be PPM instead of PNG? and typically, images put 0,0 in top left corner, do we have to rotate it?

@user137 Everyone has to handle the PNG image format. I'm considering posting some Java code to get people started. I don't want to start adding optional requirements. The bottom left was selected as (0,0) because this allows us to use a right hand coordinate system and measure radians counterclockwise from the positive x-axis. If we place (0,0) in the top left, and radians would be measured clockwise from the positive x-axis. No matter which way you do it, some standard will unfortunately be broken. Couldn't you just flip the image anyway?

I love the intro picture...

I think the choice for PNG will really hold people back, except those with ready knowledge of Java — which, as far as I know, is the only language with something like ImageIO. C++, for one, doesn't have it.

Nice challenge. PNG is fine IMO. Btw, here are some questions I have while attempting it.

I'm not sure if is it me, but I can't seem to find the black pixel in (99,101) in the image.

Is the example output the answer for the test image?

For the direction, if the angle is < pi degrees clockwise from the +ve x-axis, is negative values (i.e. 0 < Angle < pi) allowed, or must it be (pi < Angle < 2*pi) ?

@bitpwner Whoops, I was way off. The black pixel is at (100, 104). Sorry about that! For reference, the coordinates in Microsoft Paint are (100, 40). Paint indexes from a different corner, but it displays the coordinates of your cursor so I thought it might come in handy. I also checked the embedded image, and Stack Exchange did not resize it, so it is safe to use. As far as radians go, there are infinitely many correct outputs. For example, 2π, 0, and -2π are all equivalent outputs, as they all refer to the same angle. Negative values are fine.

Ah, just about to sleep when saw your comment. I guessed that you take one whole counter-clockwise round as 2π from the output and have adjusted my answer to deal with it.

Python - 355
import sys,Image,math as m
i=Image.open(sys.argv[1])
w,h=i.size
a=i.load()
X,Y=map(int,sys.argv[2:])
t=m.atan2
c=lambda i,j:2*(a[i,j][0]>200)-(a[i,j][1]>200)-1
p=c(X,h-1-Y)
V=H=0
for j in range(h):
 for i in range(w):q=c(i,h-1-j);y=Y-j;x=X-i;r=x*x+y*y;f=r and 42.*p*q/r;V+=m.cos(t(x,y))*f;H+=m.sin(t(x,y))*f
d=t(V,H)
print(V**2+H**2)**.5,[d,m.pi*2+d][d<0]

Ungolfed
import sys
import Image
import math as m

X,Y=map(int,sys.argv[2:]) # The X and Y coordinates of the test pixel

i=Image.open(sys.argv[1]) # Open the image
w,h=i.size # Get the width and height of the image
a=i.load() # Get a pixel access object of the image
V=0 # V = vector sum of Vertical Forces
H=0 # H = vector sum of Horizontal Forces

# Function to calculate the charge of the a pixel at x=i, y=j
def c(i,j):
    global a
    if a[i,j][0]>200: # If Red > 200
        if a[i,j][2]>200: # If Green > 200
            return 0 # We assume that pixel is White
        else:
            return 1 # We assume that pixel is Red
    return -1 # Else, we asusme that pixel is Black

p=c(X,h-1-Y) # Assign the charge of the test pixel to p

for j in range(h): # For every y value...
    for i in range(w): # For every x value...
        q=c(i,h-1-j) # Assign the charge of the current pixel to q
        y=Y-j # The y distance of the test pixel from the current pixel
        x=X-i # The x distance of the test pixel from the current pixel
        rSquared=x*x+y*y # The r-squared distance between the 2 pixels
        f=rSquared and 42.*p*q/rSquared # If rSquared is > 0, calculate the force.
                                        # Otherwise, the force is zero
        V+=m.cos(m.atan2(x,y))*f # Add the Y component of the force to V
        H+=m.sin(m.atan2(x,y))*f # Add the X component of the force to H

d=m.atan2(V,H)
print(V**2+H**2)**.5,[d,m.pi*2+d][d<0]

Some little program used to create tests:
import Image
width  = 100 # Define your own image width
height = 100 # Define your own image height
image = Image.new("RGB", (width, height), "white")
pixels = image.load()
blacks = [(0,0), (1,1)] # Define your own black pixels
reds   = [(0,1), (1,0)] # Define your own red pixels
for x,y in blacks:
    pixels[x,height-1-y] = (0,0,0)
for x,y in reds:
    pixels[x,height-1-y] = (255,0,0)
image.save("y.png") # Save image

Sample tests:

Users-MacBook-Air:pngforces User$ python z3.py y.png 0 0
59.3969696197 0.785398163397

Users-MacBook-Air:pngforces User$ python z3.py y.png 50 50
0.0084 3.92699081699

Users-MacBook-Air:pngforces User$ python z3.py y.png 50 50
0.0084 0.785398163397

Just posting first... If there are any mistakes or issues, drop a comment down below, but will probably take quite some time to respond cuz I am really busy with other stuff.

I love the test program! It's a lot better than zooming in 400% on a little image, making dots by hand, then trying to record the locations of all the little dots. You must be a programmer!


text:
Can you make my terminal less boring?
Terminals are so boring these days. They used to look like this:

Now they're just bland and dull and black-and-white. I want you to write me a program that will make my terminal all colorful again!
Description
Take this example Ruby code:

Most Linux terminals support these escape sequences (\e stands for the escape character), and Windows can support them with ANSICON. Here is the syntax of the specific escape sequence that can change the text or background color of a string:
\e[{{COLOR}}m

where \e stands for the escape character (0x1B in ASCII) and {{COLOR}} is replaced by the number of the color that you want to use (more details on that later). Text that comes after this escape sequence will be formatted as directed, and a value of 0 will reset all formatting.
Your challenge is to take a string specifying some text that may contain color, and output a colorful version of it.
Input / Output
Normal text works just like normal, and is printed literally. For example, the input waffles yields the same output, with no special color.
The syntax for specifying a color is similar to Wikipedia's syntax. For example, to color the words "the color red" in red in the sentence This is the color red!, the input would be:
This is {{red|the color red}}!

Background colors work too. If you wanted black letters on a white background, you would use this:
{{black|white|This text is black on white}}

To get only a background color, omit the foreground:
{{|red|This text has a red background}}

Specification
Two open curly brackets always specify the beginning of a color directive. Two closing curly brackets specify the end. Brackets will always match; there will never be a {{ without a corresponding }}, and a }} will never come before its corresponding {{. These color directives will not be nested, and a {{ will never appear within a color directive.
Within a color directive, there will always be either one or two | symbols. If there is one, the text before it is the foreground color and the text after is the string to show in that color. If there are two, the text before the first one is the foreground color, the text after the first but before the second is the background color, and the text after the second is the string to display. These vertical bars may exist outside of a color directive, and should be printed literally.
The foreground color or background color (but not both) may be empty, in which case you should leave them as the default. The final string (the one to output) will never be empty.
Here are the directions to output text of a certain color:

A color sequence is defined in the "Description" section. For example, a color sequence of 42 would be "\e[42m".
To set a color, print the color sequence of the number determined below:
 Color name   | Color sequence number (foreground / background)
--------------+----------
 black        | 30 / 40
 red          | 31 / 41
 green        | 32 / 42
 yellow       | 33 / 43
 blue         | 34 / 44
 magenta      | 35 / 45
 cyan         | 36 / 46
 lightgray    | 37 / 47
 darkgray     | 90 / 100
 lightred     | 91 / 101
 lightgreen   | 92 / 102
 lightyellow  | 93 / 103
 lightblue    | 94 / 104
 lightmagenta | 95 / 105
 lightcyan    | 96 / 106
 white        | 97 / 107

Color names are case sensitive, and an invalid color name will never be provided. You don't have to handle stuff like RED or lightgrey (spelled with an e).
After you print a color sequence, it will apply for all text following it. To end a color sequence (reset to the default color), output a color sequence of 0 ("\e[0m").

Test case
 {{|yellow|     }}
{{|yellow| }}     {{|yellow| }}
{{|yellow| }} {{red|'}} {{red|'}} {{|yellow| }}
{{|yellow| }} \_/ {{|yellow| }}
{{|yellow| }}     {{|yellow| }}
 {{|yellow|     }}

This should output a smiley face... with evil red eyes.
Rules

You may not use any libraries or functions of your programming language to automatically parse a color. This means that you must be the one to determine what "red" means; you can't have a library automatically do that for you.
This is code-golf, so the shortest code in bytes will win!

It is actually supposed to be a terminal?  Or just a colorful text viewer?  Is it supposed to run commands?

I'm finding it hard to test this. Everything I send to STDOUT using the specified syntax comes in plain text. My bash profile uses a colored prompt, so stealing from that I tried \n\[\e[32m\]\w\n\[\e[0m\]>  (green directory name, plain prompt on next line), but I can't get it to work from a program (tried python and Java so far). Any ideas?

@Geobits Try echo -e "\e[31mtest\e[0m".

That works from bash, but not with a python print. I got it by replacing \e with \033, though.

I think you would enjoy lolcat.

If red is always 31 / 41, how can I be the one to determine what it means?

I think that by you he figuratively means your program (as opposed to a call to a library function), and that he takes determine in the sense of figure out, not as in choose. Ie, it is your program that should handle the mapping: String("red") |-> Integer(31). red is only 31 because he says so, that information needs to be integrated into the program. Although it may be argued exactly what would count as your program - can we use general-purpose String manipulation functions? - don't blatantly cheat/abuse.

Ruby, 205 189 188 186 185 182 174 170 165 161 159 154 bytes
Putting long strings of color names in your code doesn't look nerdy enough.
Down to 170 partly thanks to rubik. Now the scrolling bars are gone!
One obvious and one not so obvious improvement, thanks to the flex answer, without the improvement to it, I wouldn't have revisited this!
Not anymore, I saved 4 bytes with #sum. I didn't intend it, but I just noticed this solution is case-insensitive as well. It happily processes {{RED|Red text}}.
Hex dump:
0000000: 7a3d 2d3e 6a7b 693d 2240 3054 2d44 1547  z=->j{i="@0T-D.G
0000010: 5155 0034 3256 2f46 1749 0b22 2e69 6e64  QU.42V/F.I.".ind
0000020: 6578 2028 415b 6a5d 2e74 6f5f 732e 7375  ex (A[j].to_s.su
0000030: 6d25 3839 292e 6368 723b 692b 3d69 3e39  m%89).chr;i+=i>9
0000040: 3f38 303a 3330 7d0a 243e 3c3c 243c 2e72  ?80:30}.$><<$<.r
0000050: 6561 642e 6773 7562 282f 7b7b 282e 2a3f  ead.gsub(/{{(.*?
0000060: 297d 7d2f 297b 413d 2431 2e73 706c 6974  )}}/){A=$1.split
0000070: 277c 273b 221b 5b25 693b 2569 6d23 7b41  '|';".[%i;%im#{A
0000080: 2e70 6f70 7d1b 5b30 6d22 255b 7a5b 305d  .pop}.[0m"%[z[0]
0000090: 2c31 302b 7a5b 315d 5d7d                 ,10+z[1]]}

You can convert it with xxd -r hex.dump.
The program with all non-printable characters escaped for reference purposes:
z=->j{i="@0T-D\x15GQU\x0042V/F\x17I\v".index (A[j].to_s.sum%89).chr;i+=i>9?80:30}
$><<$<.read.gsub(/{{(.*?)}}/){A=$1.split'|';"\x1b[%i;%im#{A.pop}\x1b[0m"%[z[0],10+z[1]]}

That is one line. Use it like this
ruby colors.rb -W0 < input.txt

The -W0 flag suppresses warnings that would be sent to stderr otherwise. However, the program works fine without any flags.
Output:

Ah, I had the same idea, but you beat me to it! I think you could save a char with base 35, modulus 98 and xor 1. The string would be: '1?IYU_N[(\x0c\x16&",\x1f\x01'. My string is 16 in length though. I see yours is 18, so you probably have to adjust.

Thanks. The two addtional bytes are there to support the color code 39/49, which sets the default back/forground color. But thanks for the tip, I'm currently at work and I'll give it some more thought when I get back home.

Well I observed that the only bases you can use are 35 and 36 (at least Python's int() function cannot go over 36). Then I tried all the combinations for the modulus (from 2 to 10000, but in theory one could widen the search to all of Unicode) and for the xor, which I kept small (1 to 9). Then I considered acceptable results only those which didn't contain duplicate characters.

Yes, that is more or less what I did as well. Originally, I was limiting myself to printable characters, because that gives you less of a headache and looks nicer. But since I am using the byte 0x1e instead of the escape sequence already, I might as well use more non-printable characters. In order to achieve printable characters, I used x.to_i(base)%mod+offset. I then replaced the + with ^, because well, it looks cooler. Other than that, it is unneccessary. Dropping the ^99 and changing << to + saved for more bytes. Thanks for the tip, I wouldn't have noticed otherwise!

Flex (lexer) - 226 197 192 182 168 (or 166)
To get it down to 166, change the \33 to an actual escape character.
 int z;p(i){printf("\33[%dm",i);}
%%
"{{" z=2;
[a-z]*\| if(!z)REJECT;~-yyleng&&p("062q00t03058ns7uo0p90r4"[*(int*)&yytext[yyleng>7?4:0]%131%27]-10*z);z--;
"}}" p(z=0);

Compile and run:
$ flex -o colour.c colour.l
$ gcc -o colour colour.c -lfl
$ ./colour < input

Ruby, 329 bytes.
h={};(y=0..15).each{|i|h[%w(black red green yellow blue magenta cyan lightgray darkgray lightred lightgreen lightyellow lightblue lightmagenta lightcyan white)[i]]=y.map{|j|[30,40].map{|k|k+i%8+i/8*60}}[i]}
loop{puts gets.gsub(/{{.+?}}/){|x|"\e[#{h[(g=x.scan(/[^{}|]+/))[0]][0]}m#{(g[2]? "\e[#{h[g[1]][1]}m":'')}#{g.last}\e[0m"}}

What version of Ruby do I need to run this? I used ruby 2.1.2p95 and it throw error: undefined method 'gsub' for nil:NilClass (NoMethodError) .

Hi @Ray, it works in 2.0.0-p451. I didn't try it in 2.1.2.
Here it works as a script and Here it works in irb.

It works when you enter text manually. If you do ruby colors.rb < input.txt, it will keep looping after all the input has been read. Then gets returns nil, which doesn't possess a #gsub method, thus raising an error. Use $><<$<.read instead of loop{puts gets, it's also shorter ; )

I just tested this script with the smiley face (see question and the image from my post), and there's no yellow border around the smiley?

Python - 351
import re,sys
R=range
E=lambda n,d=0:'\033[%dm'%(T[n]+d)if n else''
def P(m):f,b,t=m.groups();return'%s%s%s\033[0m'%(E(f),E(b,10),t)
x='!red!green!yellow!blue!magenta!cyan'.replace
T=dict(zip(('black'+x('!',' ')+' lightgray darkgray'+x('!',' light')+' white').split(),R(30,38)+R(90,98)))
print re.sub(r'{{(\w+)?\|?(\w+)?\|?(.+?)}}',P,sys.stdin.read())

Python, 561
Reads the text to format from stdin.
import re,sys
def p(f,b,t):
    p=''
    m='\033[%dm'
    if f!=0:p+=m%f
    if b!=0:p+=m%b
    return p+t+m%0
def c(n,b=0):
    s='black:30#red:31#green:32#yellow:33#blue:34#magenta:35#cyan:36#lightgray:37#darkgray:90#lightred:91#lightgreen:92#lightyellow:93#lightblue:94#lightmagenta:95#lightcyan:96#white:97'
    r=0
    for i in s.split('#'):
        (t,c)=i.split(':')
        if t==n:
            r=int(c)
            if b==1:r+=10
    return r
def r(m):
    i=m.groups()
    f=b=0
    if i[0]!='':f=c(i[0])
    if i[1]!=None:b=c(i[1],1)
    return p(f,b,i[2])
print re.sub('{{(\w*)\|(?:(\w*)\|)?([^}]+)}}',r,sys.stdin.read())

It's too verbose to have is not None in a codegolf. You may use !=None, for example.

Also, in def p(f,b,t), your code will throw a ZeroDivisionError. Anything mod 0 is impossible.

@BetaDecay that's not an integer being modulus'ed, that's a string being formatted.

I'm getting invalid syntax errors at re.sub running this

(late comment) Does this 499-byte code work?

if i[0]!='' could be golfed to if i[0]

Cobra - 496
It could almost be a single print statement.
use System.Text.RegularExpressions
class P
    def main
        print Regex.replace(Console.readLine,r'\{\{('+(l=List<of String>(((m=' black red green yellow blue magenta cyan'.split).join(' ')+' lightgray darkgray'+m.join(' light')+' white').split))[1:].join('|')+r')?\|?('+l[1:].join('|')+r')?\|(.*?)\}\}',do(a as Match))
            return if(x=l.indexOf('[a.groups[1]]'),r'\e['+'[if(x>8,x+81,x+29)]m','')+if(y=l.indexOf('[a.groups[2]]'),r'\e['+'[if(y>8,y+91,y+39)]m','')+'[a.groups[3]]'+if(x+y,r'\e[0m','')


text:
Implement an 8 bit adder
The Challenge
Implement a function which accepts two integers whose values range from 0 - 255 and returns the sum of those integers mod 256. You may only use bitwise negation (~), bitwise or (|), bit shifting operators (>>,<<), and assignment (=).
Things you cannot use include (but are not limited to)

Addition, subtraction, multiplication, and division
Loops
Conditional statements
Function calls

Fewest uses of binary or, binary negation, and bit shift operations wins. In the event of a tie, the most popular solution wins. As always, standard loopholes apply.
Here is an example of a simple 2-bit adder. It uses 77 binary negations, 28 binary ors, and 2 bit-shifts for a total score of 107 (this can be seen by running the C preprocessor with gcc -E). It could be made much more efficient by removing the #defines and simplifying the resulting expressions, but I've left them in for clarity.
#include <stdio.h>

#define and(a, b) (~((~a)|(~b)))
#define xor(a, b) (and(~a,b) | and(a,~b))

int adder(int a, int b)
{
    int x, carry;
    x = xor(and(a, 1), and(b, 1));
    carry = and(and(a, 1), and(b, 1));
    carry = xor(xor(and(a, 2), and(b, 2)), (carry << 1));
    x = x | carry;
    return x;
}

int main(int argc, char **argv)
{
    int i, j;
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            if (adder(i, j) != (i + j) % 4) {
                printf("Failed on %d + %d = %d\n", i, j, adder(i, j));
            }
        }
    }
}

Update: Added example and changed scoring critera

why not bitwise "and"?

@Ryan Most people are more familiar with NAND gates than NOR gates :)

does recursion count as a loop?

@Ryan Recursion does count as a loop, though I'm not sure how you'd implement it without a conditional statement.

Is overflow defined or can I just output anything if it overflows?

@Comintern Your solution should wrap around, i.e. 255 + 3 should be equal to 2.

Is x<<3 one operation or three?

@xnor x<<3 is one operation.

Does (ab)using LEA counts as loophole?

@PTwr That would depend on how you use it. If you're using it to perform addition of two registers, then yes.

@Orby then loophole it is. As this problem could be solved with single LEA it would be kinda cheating.

Python, 36 operations
A methods that's logarithmic in the parameter "8"!
def add(a,b):
    H = a&b   #4 for AND
    L = a|b   #1
    NX = H | (~L) #2
    K = NX

    H = H | ~(K | ~(H<<1)) #5
    K = K | (K<<1) #2

    H = H | ~(K | ~(H<<2)) #5
    K = K | (K<<2) #2

    H = H | ~(K | ~(H<<4)) #5

    carry = H<<1 #1

    neg_res = NX ^ carry  #7 for XOR
    res_mod_256 = ~(neg_res|-256) #2
    return res_mod_256

The idea is to figure out which indices overflow and cause carries. Initially, this is just the places where both a andd b have a 1. But since carried bits can cause further overlows, this needs to be determined iteratively.
Rather than overflowing each index into the next one, we speed up the process by moving 1 index, then 2 indices, then 4 indices, being sure to remember places where an overflow happened (H) and where an overflow cannot happen any more (K).

A simpler iterative solution with 47 operations:
def add(a,b):
    H = a&b   #4 for AND
    L = a|b   #1
    NX = H | (~L) #2

    c=H<<1  #1

    for _ in range(6): #6*5
        d = (~c)|NX
        e = ~d
        c = c|(e<<1)

    res = c ^ NX  #7 for XOR

    res_mod_256 = ~(res|-256) #2
    return res_mod_256

Test rig, for anyone who wants to copy it.
errors=[]
for a in range(256):
    for b in range(256):
        res = add(a,b)
        if res!=(a+b)%256: errors+=[(a,b,res)]

print(len(errors),errors[:10])

C - 0
It does use operators outside of ~, |, >>, <<, and =, but I see solutions using casting and comma operators, so I guess the rule isn't too strict provided it isn't using the forbidden operators.
unsigned char sum(unsigned char x, unsigned char y)
{
    static unsigned char z[] = {
        0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
        16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
        32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
        48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
        64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
        80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
        96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
        112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
        128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
        144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
        160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
        176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
        192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
        208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
        224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
        240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
        0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
        16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
        32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
        48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
        64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
        80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
        96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
        112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
        128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
        144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
        160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
        176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
        192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
        208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
        224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
        240,241,242,243,244,245,246,247,248,249,250,251,252,253,254
    };

    return (&z[x])[y];
}

This is obviously a loophole, but +1 for pointing it out.

python, score = 83 80
def g(x,y):
    for i in xrange(7):
        nx = ~x
        ny = ~y
        x,y = ~(x|ny)|~(nx|y), (~(nx|ny))<<1
    x = ~(x|~y)|~(~x|y)
    return ~(~x|256)

Unroll the loop.  It's 10 ops per loop times 7 loops, 7 for the last xor, and 3 to squash the 9th bit at the end.
Implements the equation x+y = x^y + 2*(x&y) by repeating it 8 times.  Each time there is one more zero bit at the bottom of y.

C, Score: 77 60
Golfed just for the hell of it, 206 169 131 bytes:
#define F c=((~(~c|~m))|n)<<1;
a(x,y){int m=(~(x|~y))|~(~x|y),n=~(~x|~y),c;F F F F F F F return (unsigned char)(~(m|~c))|~(~m|c);}

Expanded:
int add(x,y)
{
    int m=(~(x|~y))|~(~x|y);
    int n=~(~x|~y);
    int c = 0;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    return (int)((unsigned char)(~(m|~c))|~(~m|c));
}

Essentially the same solution (mathematically) that @KeithRandall @JuanICarrano came up with, but takes advantage of C's ability to play fast and loose with variable types and pointers to wipe everything after the first 8 bits without using any more operators.
Depends on the endian-ness of the machine and the sizeof() an int and a char, but should be able to be ported to most machine specific applications with the proper pointer math.
EDIT: This is a challenge that C (or other low level languages) will have a distinct upper hand at -- unless somebody comes up with an algorithm that doesn't have to carry.

If you're going to handle the wrap around that way, you could just cast to unsigned char. It's cleaner and more portable.

@Orby - I guess typing out unsigned doesn't come naturally to me in code golf.  You're right of course - updated.

Python - Score 66 64
def xand(a,b):
    return ~(~a|~b) #4

def xxor(a,b):
    return (~(a|~b))|~(~a|b) #7

def s(a,b):
    axb = xxor(a,b)   #7
    ayb = xand(a,b)   #4

    C = 0
    for i in range(1,8):
        C = ((xand(C,axb))|ayb)<<1    #(1+1+4)x7=6x7=42

    return xxor(axb,xand(C,255))    #7 + 4 = 11
    #total: 7+4+42+11 = 64

It is the equation for a ripple adder. C is the carry. It is computed one bit at a time: in each iteration the carry is propagated left.
As pointed out by @Orby, the original version did not make a modular addition. I fixed it and also saved a cycle in the iteration, as the first carry-in is always zero.

Nice job, but your code does not wrap around properly (i.e. s(255,2) returns 257 rather than 1). You can correct this by changing your last line to return ~(~xxor(axb,C)|256)  which adds 3 points.

C++ - score: 113
#define ands(x, y) ~(~x | ~y) << 1
#define xorm(x, y) ~(y | ~(x | y)) | ~(x | ~(x | y))

int add(int x, int y)
{
int x1 = xorm(x, y);
int y1 = ands(x, y);

int x2 = xorm(x1, y1);
int y2 = ands(x1, y1);

int x3 = xorm(x2, y2);
int y3 = ands(x2, y2);

int x4 = xorm(x3, y3);
int y4 = ands(x3, y3);

int x5 = xorm(x4, y4);
int y5 = ands(x4, y4);

int x6 = xorm(x5, y5);
int y6 = ands(x5, y5);

int x7 = xorm(x6, y6);
int y7 = ands(x6, y6);

int x8 = xorm(x7, y7);
int y8 = ands(x7, y7);

return (x8 | y8) % 256;
}

add(1, 255) is returning 128 for me, @Ryan.

@Orby its fixed now

% is not on the list of permitted operators, namely ~, |, >>, and <<. Maybe replace it with ands(x8|y8, 255)>>1?

Actually, ~(~x8 | y8 | 0xFFFFFF00) would do the trick nicely with only 4+ to your score.

But wouldn't making the type byte instead of int would make it overflow automatically?

@proudhaskeller unsigned char, but yes. I hadn't really anticipated this when I considered the challenge. Definitely gives an unfair advantage to C / C++.