text:
Calculate a check digit using the Damm algorithm
There are popular check digit algorithms such as Luhn and then there are good ones, for example the Damm algorithm. The only possible reason behind the popularity of algorithms such as Luhn is that there exist code golfed implementations of them. This means that we as a community have the power to change the world by providing golfed implementations of better algorithms.
So this challenge is to change the world by writing a function or a complete program in your language of choice that calculates a check digit using the Damm algorithm. The answer with the smallest number of characters (not bytes) will be chosen as a winner in a few weeks. Note that all helping functions and the declaration of the operation table must be included in the character count. In case of a tie the most popular answer will be chosen.
This algorithm revolves around an operation table that must be a weakly totally anti-symmetric quasigroup of order 10. The operation table that can be found in the Wikipedia article about the Damm algorithm is the one which is to be used in this challenge. For completeness sake I will reproduce it below:
    |   0   1   2   3   4   5   6   7   8   9
----+----------------------------------------
0   |   0   3   1   7   5   9   8   6   4   2
1   |   7   0   9   2   1   5   4   8   6   3
2   |   4   2   0   6   8   7   1   3   5   9
3   |   1   7   5   0   9   8   3   4   2   6
4   |   6   1   2   3   0   4   5   9   7   8
5   |   3   6   7   4   2   0   9   5   8   1
6   |   5   8   6   9   7   2   0   1   3   4
7   |   8   9   4   5   3   6   2   0   1   7
8   |   9   4   3   8   6   1   7   2   0   5
9   |   2   5   8   1   4   3   6   7   9   0

In short (for details see the Wikipedia article) the algorithm works as follows:

You start with a list of digits to be processed and an interim digit which is set to 0.
For every digit in the list you calculate a new interim digit by using the digit as the column index and the previous interim digit as the row index.
The final interim digit is the check digit. If you are validating a number that already has an added check digit the final interim digit is 0 if the number is valid.

Your program or function must accept a string that can contain any characters except null, but it should only concern itself with the digits in the string. It must either print (if a program) or return (if a function) the original string with the calculated check digit appended. If you chose to write a program the program may either accept the input as an argument or as standard input. If the input string is empty or doesn't contain any digits you must return or append a zero.
Some examples:
Input       |   Output
------------+-------------
42          |   427
427         |   4270
2 to 2      |   2 to 29
23 42 76-   |   23 42 76-5
-           |   -0

I look forward to seeing the Piet entries claiming the win.

Pyth, 49 characters
+z`u@sm>+0jCdT_6"Ľ쵥"+*TGvH:z"\D"k0

Contains god knows what characters, so here's a Python3 program to generate the above program accurately on your machine:
N = 317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790
M = 1000000
l = []
while N:
    l.insert(0, N % M)
    N //= M

n = "".join(chr(c) for c in l)

s = '+z`u@sm>+0jCdT_6"' + n + '"+*TGvH:z"\D"k0'

with open("golf.pyth", "wb") as f:
    f.write(s.encode("utf-8"))

print("Program length is {} characters.".format(len(s)))

Explanation:
+z`                                     Output the input followed by a
                                        stringified...
   u                         :z"\D"k0   Reduction starting with 0 of digits
                                        in input...
    @                  +*TGvH           Indexing ... by 10*prev + int(next).
     sm         "ZALGO"                 Sum all digits created by ... over the
                                        unicode garbage.
       >+0     6                        Prepend 0 if needed to...
          jCdT_                         Codepoint converted to sequence of
                                        digits.

CJam, 54 characters
q_o{A,s&},{~0"끼´慜䪝膞䝮芜㮜ꡞ靓渏縰蒆㣉倔쵶"2G#bAb+A/T==:T;}/T

There is one unprintable character in there, so you might want to use the permalink below.
Test it here.
Explanation
The interim digit is being tracked in  T, which CJam initialises to 0.
q_o                                  "Read STDIN, duplicate it and print it.";
   {A,s&},                           "Filter out all non-digit characters.";
          {                     }/   "For each digit character.";
           ~                         "Eval to get the digit itself.";
            0                        "Push a zero.";
             "..."2G#b               "Push that long string and interpret the character
                                      codes as the digits of a base-2^16 number.";
                      Ab+            "Get base-10 digits and prepend the 0.";
                         A/          "Split into rows of 10.";
                           T=        "Select row based on interim digit.";
                             =       "Select column based on current digit.";
                              :T;    "Store in T and discard.";
                                   T "Push the interim digit to be printed.";

Python 3, 149 141 138 characters
import re
l=""
for c in"ĽᝢႮ⏿ዿၮ∉᜝Ꮺൢ៫ǋẜ᳼╭᛭ᰡඡᆸߡⓞ᠜ȍ῏᪆":l+="%04d"%ord(c)
def D(b):
 a="0"
 for i in re.sub("\D","",b):a=l[int(a+i)]
 return b+a

Examples:
 Input | Output
-------+--------
    42 | 427
   427 | 4270
2 to 2 | 2 to 29
   123 | 1234
  1234 | 12340
     - | -0

Thanks to @MegaTom and @Sieg for helping to remove a total of 11 characters

10*int(a)+int(i) is int(a+i), is it not?

Good point! Thank you, that saves 5 chars.

For followed by a single statement doesn't need a newline in between. (-3)

Ruby, 149 characters
i="0";t="0#{'2uleblnnz0nbpv3kqkaufbjqebm57jdj6ubaba1mc2fyucqff69tbllrcvw393li'.to_i 36}";puts(gets.chomp.each_char{|c|i=(c=~/\d/?t[(i+c).to_i]:i)}+i)

Tested on repl.it

J, 117 bytes
Contains only printable ascii. (I had a hard time with J and unicode.) Generates the transition table from the permutation-indices of the rows.
3 :'y,":(((_4(87)&#:inv\40-~a.i.''(3/3+wGf*Dl:(zaW+Hhw*(1p+;~.,y>m-<MZ)JCs'')A.i.10){~<@,~)/|.0,(#~10>])(1":i.10)i.y'

Usage:
   damm=.3 :'y,":(((_4(87)&#:inv\40-~a.i.''(3/3+wGf*Dl:(zaW+Hhw*(1p+;~.,y>m-<MZ)JCs'')A.i.10){~<@,~)/|.0,(#~10>])(1":i.10)i.y'

   damm '23 42 76-'
23 42 76-5

   damm ''
0

Try it online here.

Haskell, 131 characters
import Data.Char
f n=n++(show$foldl(\x y->read[('0':(show.ord=<<"౧⚈ક×ዿၮ∉ɏᵕₖ᧔İɕSʢ凞㷽ᰡ衎텴䘗↩倭῏᪆"))!!(x*10+y)])0[read[i]|i<-n,isDigit i])

Test run:
> mapM_ (putStrLn.f) ["42", "427", "2 to 2", "23 42 76-", "-"]
427
4270
2 to 29
23 42 76-5
-0

k, 36 characters
/ declare quasi-group
M:"H"$'"0317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790"

/ declare function
  f:{x,$0{M y+10*x}/"H"$'x@&x in .Q.n}

/ get length of function
  #$f
36

/ execute function against test input
  .q.show f@'{x!x}("42";"427";"2 to 2";"23 42 76-";,"-")
"42"       | "427"
"427"      | "4270"
"2 to 2"   | "2 to 29"
"23 42 76-"| "23 42 76-5"
,"-"       | "-0"

q, 40 characters (equivalent implementation to k)
 f:{x,string 0{M y+10*x}/"H"$'x inter .Q.n}

I must say I admire the use of a questionable loop-hole in the rules, but I really do must clarify the rules to enforce the inclusion of the declaration of the quasi-group and the declaration of any kind of helping function in the character count.


text:
Brainf*** subprograms with unique outputs
You should write a 100-byte long brainfuck (BF) program.
One character will removed from it in every possible way the resulting 100 new (99-byte long) programs.  E.g. for the program ++.>. the 5 subprograms are +.>., +.>., ++>., ++.. and ++.> .
Your score will be the number of unique outputs the 100 programs generate. Higher score is better.
Details

Your programs will be terminated after outputting the first character.
Invalid or non-terminating programs and programs generating empty outputs are not counted towards the score.
The BF cells are 8 bit wrapping ones. (255+1=0, 0-1=255)
Your program is given no input. If you use , in the code it set's the current cell to 0.
There are no cells on the left side of the starting position. E.g. <. is invalid but .< is valid as the execution is terminated at .. The tape is unbounded in the other direction.
Programs with unbalanced brackets ([ and ]) are invalid.
Your original program can be shorter than 100 bytes as it's easy to extend it to 100 bytes without changing the score.
Your original program doesn't have to be valid BF code.

You can use this python3 program (ideone link) to determine the score of your answer. (For long-running programs you may need to modify the maxstep variable.)
Example
(For simplicity this program is shorter than 100 bytes.)
Solution: ++,+[-]+><.-,-.

Score: 3

Explanation:

Subprogram     => Output

+,+[-]+><.-,-. => 1
+,+[-]+><.-,-. => 1
+++[-]+><.-,-. => 1
++,[-]+><.-,-. => 1
++,+-]+><.-,-. => None
++,+[]+><.-,-. => None
++,+[-+><.-,-. => None
++,+[-]><.-,-. => 0
++,+[-]+<.-,-. => None
++,+[-]+>.-,-. => 0
++,+[-]+><-,-. => 255
++,+[-]+><.,-. => 1
++,+[-]+><.--. => 1
++,+[-]+><.-,. => 1
++,+[-]+><.-,- => 1

Unique outputs are [0, 1, 255]
Score is 3 for ++,+[-]+><.-,-. (length = 15)

In case of a tie the winner is the one with the shorter code. (Your program can be shorter than 100 bytes as stated in the Details section.) If the codes are equal length the winner is the earlier poster.
Bonus puzzle: without the bolded restriction can you find a program with score 100?

I solved the bonus puzzle; the answer is (censored).

@AJMansfield Could you edit your comment so others could think about the puzzle too? E.g change your solution to a http://pastebin.com/ link which contains the answer.

Hmm. I wrote a genetic optimizer for this question to try to find micro-improvements to existing answers, but it's not too successful so far. They're getting stuck at 79 and 43 respectively. Ah well—it was worth a shot!

Score: 35 41 69 78 79 83
(Remove the newline.)
-->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>->+>-
>+>->+>->+>->+>->+>->+>->+>->+>++[>[-<+++>]<<++]>.

Try it online!
I'm not sure exactly why it works...
Score: 79
X->>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>
+>+>+>+>+>+>+>+>+>+>+>+[>[-<+>>+<]+>[-<+>]<<<+]>>.

Try it online!
It was supposed to sum 2*mem[i]*i and add the number of cells (+const) where the addresses are counted from the right to the left. The multiplier 2 and number of cells can make removing + and > having different parity.
It indeed worked like that in the 69 points version. But the latest version broke that and got something else by coincidence. It calculates sum(mem[i]*i+i+1) and removing + and > does almost the same, except for the sum(i) which has a difference of the number of cells, which is also the number of different output for either removing + and >.
For the bonus:

 +.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.

Note: if you test this with the provided scorer program make sure to increase the maxstep value (in def evaluate(r,maxstep=20000):) as some subprograms run for a long time.

Score can actually be increased to 79 by replacing ->+>+> ... with ->,>+> ...

@BrainSteel I just changed it to a no-op.

Score: 37 43
+>-,->,+-><->-[>---+-+<[--->>+><,+>>>++<><<<+<[>--]]><><+-+>+<<+<><+++<[[<[---->-<-]>++>],>,]<,]<+-.

EDIT: Now my program allows some square brackets. Not going to win any prizes with it, but that's what I get for making some weighted RNGs do the busy work for me.
This was generated by a program I wrote in C.
For every Nth character removed, here are the outputs:
N = 0 => 158
N = 1 => 158
N = 2 => 158
N = 3 => 187
N = 4 => 129
N = 5 => 100
N = 6 => 158
N = 7 => 13
N = 8 => 1
N = 9 => 211
N = 10 => 129
N = 11 => 1
N = 12 => 57
N = 13 => 255
N = 14 => Mismatched Braces
N = 15 => 59
N = 16 => 11
N = 17 => 11
N = 18 => 11
N = 19 => 117
N = 20 => 11
N = 21 => 117
N = 22 => 166
N = 23 => Mismatched Braces
N = 24 => 206
N = 25 => 206
N = 26 => 206
N = 27 => 147
N = 28 => 147
N = 29 => 158
N = 30 => 148
N = 31 => 188
N = 32 => 51
N = 33 => 17
N = 34 => 84
N = 35 => 84
N = 36 => 84
N = 37 => 158
N = 38 => 158
N = 39 => 94
N = 40 => 46
N = 41 => 94
N = 42 => 94
N = 43 => 94
N = 44 => 17
N = 45 => 196
N = 46 => Mismatched Braces
N = 47 => 149
N = 48 => No Termination
N = 49 => No Termination
N = 50 => Mismatched Braces
N = 51 => Mismatched Braces
N = 52 => 45
N = 53 => 77
N = 54 => 45
N = 55 => 77
N = 56 => 50
N = 57 => 209
N = 58 => 50
N = 59 => 251
N = 60 => 249
N = 61 => 99
N = 62 => 99
N = 63 => 117
N = 64 => 89
N = 65 => 207
N = 66 => 89
N = 67 => 115
N = 68 => 115
N = 69 => 115
N = 70 => 95
N = 71 => Mismatched Braces
N = 72 => Mismatched Braces
N = 73 => 104
N = 74 => Mismatched Braces
N = 75 => No Termination
N = 76 => No Termination
N = 77 => No Termination
N = 78 => No Termination
N = 79 => Left Overflow
N = 80 => 3
N = 81 => 2
N = 82 => No Termination
N = 83 => Mismatched Braces
N = 84 => No Termination
N = 85 => 133
N = 86 => 133
N = 87 => 0
N = 88 => Mismatched Braces
N = 89 => 158
N = 90 => 0
N = 91 => 4
N = 92 => Mismatched Braces
N = 93 => 0
N = 94 => 158
N = 95 => Mismatched Braces
N = 96 => 0
N = 97 => 157
N = 98 => 159
N = 99 => None

There are a total of 37 unique outputs, which are (in numerical order):
0, 1, 2, 3, 4, 11, 13, 17, 45, 46, 50, 51, 57, 59, 77, 84, 89, 94, 95, 99,
100, 104, 115, 117, 129, 133, 147, 148, 149, 157, 158, 159, 166, 187, 188,
196, 206, 207, 209, 211, 249, 251, 255

I am 90% 100% certain this solution is not optimal, but proving that may be exceedingly difficult. There are a few things that are clear. Having no . symbols until the last character seems to be the way to go, and square brackets ([]) seem to be rather useless. I did a little bit of thinking here, which I'd like to outline:
Let L be the length of the code in bytes (in the challenge, 100), and n be the number of unique outputs of the sub programs.
For L=3, there are several optimal solutions of the form +-., where n=2 (in this case, the outputs are 1 and 255 for +. and -., respectively.) This puts the best ratio for L = 3 at n/L = 66.67%. Note that this ratio cannot be beaten for at least L<10.
For L=10, the solutions are simple enough to bruteforce it. Here are all the best solutions, at n = 6:
++>-->+<+. => 6
++>-->+<+. => 6
+++>->+<+. => 6
--->->+<+. => 6
++>---><+. => 6
+++>--><+. => 6
-->++>-<-. => 6
+++>+>-<-. => 6
--->+>-<-. => 6
-->+++><-. => 6
--->++><-. => 6

Which yields a score ratio of n/L = 60%.
As L->infinity, it is clear that the ratio must approach 0, since there only 255 possible outputs for a potentially infinite L.
The ratio does NOT, however, decrease uniformly. It is not possible to construct a solution for n=6, L=9, so the best possible ratio for L=9 is 5/9 = 55.56% < 60%.
This begs the question, how quickly, and in what matter, does the ratio descend? For L = 100, and at 10^9 checks/second, it would take several orders of magnitude longer than the lifetime of the universe to bruteforce an optimal solution. Is there an elegant way to go about this? I very much doubt that it is down to 37% for L = 100.
The ratio actually increases, up to L=100. View other answers to confirm.
I'd love to hear your evaluations of the above. I could be was atrociously wrong, after all.

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:
How to recover from DDOS'ed internet
The internet has failed.  DDoS attacks are now rampant and widespread.  It is up to you to take control and repair the internet.
Each bot will control 20 nodes in this network.  Every node is either active or safe, has an owner, and has a strength, which starts at 2. Every active node is connected to all other active nodes.
Each turn, you will receive a list of all active nodes with their strength.  For each of the active nodes that you own, you either:

Designate an active node you want to transfer your entire strength to, or
Save and increase its strength

Then the following happens in order:

A Node choosing to save its strength will increase its strength by 1.
All nodes choosing to transfer their strength will simultaneously transfer their entire strength to the new node.
If a node was transferred strength from an enemy node, an attack will ensue.  If an enemy owner collectively transfers more strength than the original owner (and all other attackers), then that enemy becomes the new owner.  The strength of that node then becomes the strength of the attacker.  If there is a tie for strength, then the owner will be chosen randomly.
All nodes left without any strength will be considered safe, and gives 1 point to the owner.

After 100 games of 100 turns, the owner with the most safe nodes across all games wins. EDIT: I changed it from 2000 to 100 turns, as it ended up that the last 1900 turns were useless
IO
You will be passed the list of active nodes (via command line args) like the following:
F20 F4 E7 E2 E20 F2

F designates that the node is a friendly node, and E designates that the node is an enemy.
For each of your friendly nodes, you should return an action (via STDOUT) like the following:
0,0 1,3 5,0

The above would mean that you want to increase your strength of the first node, use your second node to attack the fourth node, and your last node will transfer its strength the first node (and if nobody attacks it, it will become a safe node).
After returning, your program should quit.
Scoreboard

accumulator got 3240 points
classy got 2370 points
dumbot got 2262 points
random_bot got 1603 points
smarter_random_bot got 1319 points
steady_bot got 1097 points

The controller can be found here: https://github.com/nathanmerrill/NetAttack

The controller contradicts with the specification: "If an enemy owner collectively transfers more strength than the original owner...". Currently it's equal or more.

@randomra: in the spec it says: If there is a tie for strength, then the owner will be chosen randomly

@NathanMerrill I assumed if the attackers tie.

The last remaining node is stuck waiting until the end of the game, right? There's no way for him to run away?

@acbabis correct, but I actually test for that and end the game prematurely at that point.

Accumulator, Python
Let's get this party started! My submission should work both on Python 2 and Python 3.
import sys

inputs = [(i, x[0], int(x[1:])) for (i, x) in enumerate(sys.argv[1].split())]

own_nodes = sorted([(s,i) for (i,o,s) in inputs if o == 'F'])
targets = sorted([(s,i) for (i,o,s) in inputs if o == 'E'])

if targets:
    t_copy = targets[:]
    out = ""
    total_str = 0
    attackers = []
    for (s,i) in own_nodes:
        attackers += [i]
        if t_copy:
            total_str += s
            if t_copy[0][0] < total_str - 1:
                j = max([j for j in range(len(t_copy)) if t_copy[j][0] < total_str - 1])
                out += " ".join([str(k) + "," + str(t_copy[j][1]) for k in attackers]) + " "
                attackers = []
                total_str = 0
                t_copy = t_copy[:j] + t_copy[j+1:]
    if attackers:
        if t_copy:
            out += " ".join([str(k) + "," + str(t_copy[0][1]) for k in attackers])
        else:
            out += " ".join([str(k) + "," + str(attackers[0]) for k in attackers])
else:
    out = " ".join([str(i) + "," + str(own_nodes[0][1]) for (s,i) in own_nodes])

print(out.rstrip())
sys.stdout.flush()

The idea is really simple.
I start enumerating my nodes in ascending order of strength, keeping a running sum of the strengths.
When the sum exceeds the strength of the weakest enemy node (+1 for a possible increase), I attack that node and remove it from the pool, reset the sum, and continue.
At the end, if the strongest nodes can't find anyone to attack, they'll collect more strength.
EDIT: Accumulator is now a bit smarter.
Instead of always attacking the weakest enemy node, it accumulates the strength until it could do so, and then attacks the strongest free node it can with that strength.
Also, if there are still enemies left at the end, any unassigned nodes will attack the weakest remaining enemy, just in case it decides to transfer its strength away.

Classy, Python3
import random, sys
f,e,p=[],[],[]
for si,s in enumerate(sys.argv[1].split()):
    if s[0]=='F': f+=[(int(s[1:]),si)]
    else: e+=[(int(s[1:]),si)]
f=sorted(f,key=lambda t:t[0]);r=4
f1,f2,f3=f[:len(f)//r],f[len(f)//r:len(f)//r*2],f[len(f)//r*2:]
for fa in f3:
    ea=[t for t in e if t[0]<fa[0]]
    p+=[(fa[1],random.choice(ea)[1])] if ea else [(fa[1],fa[1])]
for fd,fs in zip(f1,reversed(f2)):
    p+=[(fs[1],fd[1])]
    p+=[(fd[1],fd[1])]
if len(e)==0: p=[(fe[1],0) for fe in f]
for t in p: print(t[0],',',t[1],' ',sep='',end='')
sys.stdout.flush()

The bot splits its own nodes into 3 categories based on strength and each node acts according to its category.

Each strong node attacks a random enemy node which it can beat.
Each middle node supports it's weak node pair.
Each weak node supports itself.

Result against Accumulator and the two sample bots:
smarter_random_bot got 1301 points
random_bot got 1841 points
Accumulator got 2178 points
Classy got 2580 points

SteadyBot, Node.js
(new Promise(function(resolve, reject) {
    var input = process.argv[2];
    if(input) {
        resolve(input);
    } else {
        process.stdin.once('data', function(data){
            resolve(data.toString());
        });
    }
})).then(function(input) {
    return input.trim().split(' ');
}).then(function(nodes) {
    var friends = [], enemies = [];
    nodes.forEach(function(value, index) {
        var data = { index: index, strength: parseInt(value.substring(1)) };
        if(value[0] === 'F') {
            friends.push(data);
        } else {
            enemies.push(data);
        }
    });

    function weaknessCompare(a, b) {
        return (a.strength > b.strength) ? -1 : ((a.strength < b.strength) ? 1 : 0);
    }

    friends.sort(weaknessCompare);
    enemies.sort(weaknessCompare);

    if(enemies.length === 0) {
        friends.forEach(function(friend) {
            friend.target = 0;
        });
    } else {
        if(friends.length > 0) {
            var strongest = friends[0];
            for(var i = 0; i < enemies.length; i++) {
                var enemy = enemies[i];
                if(enemy.strength + 1 < strongest.strength) {
                    strongest.target = enemy.index;
                    break;
                }
            };
        }
        if(friends.length > 1) {
            friends[1].target = friends[friends.length - 1].index;
        }
    }

    console.log(friends.map(function(friend) {
        return friend.index + ',' +
                (typeof friend.target === 'number' ? friend.target : friend.index);
    }).join(' '));
});

Assumes enemies won't reinforce large nodes: Largest friendly node attacks strongest enemy it can beat under this assumption.
Assumes that weakest target will be attacked: Second largest friendly node moves to weakest friendly node each round.
Wants lots of free strength: Other nodes wait.

I'm unsure why, but this bot isn't returning properly (it prints an empty string).   The other nodejs bot works, so I'd recommend taking a look at it.  I should also mention that I just installed nodejs, and while I know javascript, I may be missing something specific to nodejs.

Thanks for the heads-up. When I do node SteadyBot.js F20 F4 E7 E2 E20 F2, it works for me. Could you please tell me the input for which it is failing?

@NathanMerrill I rewrote it to also work with stdin. Hope that fixes it. cat  F20 F4 E7 E2 E20 F2 | node SteadyBot.js

@acbabis Input is given as one big argument.

@acbabis randomra is correct.  You are going to get 1 big argument, the list (unless, you get the call as well like C++, in which case, you will get 2).

@NathanMerrill I fixed the problem and successfully ran it with your controller after adding a node steadyBot.js command.txt file. Thanks for your help.

Dumbot, Nodejs
var input = process.argv.splice(2);
var regexp = new RegExp(" ", "gm");
input = String(input).split(regexp);
var nodes = [];
var targets = [];
for(var i = 0; i < input.length; i++){
    if(input[i].charAt(0) == "F")
        nodes.push(i);
    else
        targets.push(i);
}
var result = "";
var length = nodes.length;
for(var i = 0; i < length; i++){
    if(targets.length>0)
        result += nodes.shift() + "," + targets.shift() + " ";
    else
        result += nodes.shift() + ",0 ";
}
console.log(result);

The bot will attack without any thinking or strategy. The main goal is to ensure a lot of safe node right at the beginning. Be aware that this bot make an infinite loop with accumulator.

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


text:
Infinite Labyrinths
Background
You are the apprentice of a powerful wizard, and your master is currently developing a spell for creating an inter-dimensional labyrinth to trap his enemies in.
He wants you to program his steam-powered computer to analyze the possible layouts.
Programming this diabolical machine is highly dangerous, so you'll want to keep the code as short as possible.
Input
Your input is a two-dimensional grid of periods . and hashes #, signifying empty space and walls, given as a newline-delimited string.
There will always be at least one . and one #, and you can decide whether there is a trailing newline or not.
This grid is the blueprint of an infinite labyrinth, which is made by aligning infinitely many copies of the grid next to each other.
The labyrinth is divided into cavities, which are connected components of empty spaces (diagonally adjacent spaces are not connected).
For example, the grid
##.####
...##..
#..#..#
####..#
##...##

results in the following labyrinth (continued infinitely in all directions):
##.######.######.####
...##.....##.....##..
#..#..##..#..##..#..#
####..#####..#####..#
##...####...####...##
##.######.######.####
...##.....##.....##..
#..#..##..#..##..#..#
####..#####..#####..#
##...####...####...##
##.######.######.####
...##.....##.....##..
#..#..##..#..##..#..#
####..#####..#####..#
##...####...####...##

This particular labyrinth contains a cavity of infinite area.
On the other hand, this blueprint results in a labyrinth with only finite cavities:
##.####
##..###
####...
..####.
#..####

Output
Your output shall be a truthy value if the labyrinth contains an infinite cavity, and a falsy value if not.
Note that the labyrinth may contain both finite and infinite cavities; in that case, the output shall be truthy.
Rules
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Additional Test Cases
Infinite cavities:
.#

#.#
...
#.#

#.###.#.###.#
#.#...#...#.#
#.#.#####.#.#
..#.#...#.#..
###.#.#.#.###
#...#.#.#...#
#.###.#.###.#

##.###
#..###
..##..
###..#
##..##

..#..#..#..#..#..#
.#..#..#..#..#..#.
#..#..#..#..#..#..

#.####.###.###.####
#...#..#...###..###
###.#..#.######..##
....####.#######...
###..###...########
##########.##....##
..###......##.##...
#.........##..#####
###########..###..#
#...........####..#
#.###########.##..#
#.##....##.....####
#.####.###.###.####

Finite cavities:
###
#.#
###

.#
#.

####
.#..
####

#.#.#
..#..
#####
..#..
#.#.#

#.#.#.#.#.#
..#...#.#..
###.###.###
..#.#......
#.#.#######
#.#.......#
#.#######.#
#.#.....#.#
#.#.#.#.#.#

##....#####
.#..#...##.
.##.#..#...
..###.###..
#..##.#####
#...##....#
#.#.#####.#
###..####.#
....####...
###...#####

###....##.#########
####...##....#...##
..####.#######.###.
....##..........##.
###..#####.#..##...
####..#..#....#..##
..###.####.#.#..##.
..###...#....#.#...
..####..##.###...##
#.####.##..#####.##
####...##.#####..##

###########
........#..
#########.#
..........#
.##########
.#.........
##.########
...#.......

Is there a trailing newline character?

@FUZxxl That's up to you.

Can the infinite labyrinth be a straight line that goes to infinity.

@Neil I'm not sure what you mean. The first and second infinite examples have infinite lines, but there is at least one . and one # in the input.

Nice challenge, more difficult than it seems

Can we receive input as a matrix of characters instead of a string with newlines?

I have an interesting solution that runs in O(n² m²) where n and m are the dimensions of the array. Let's see if it works.

@FUZxxl In this challenge, it must be a newline-delimited string. Looking forward to your solution!

JavaScript (ES6), 235 253
Same method used by @mac. For each free cell, I try a recursive fill, marking used cells with the coordinate I am using (that can be outside the orginal template). If during the fill I arrive to a cell already marked having a different coordinate, I am in an infinite path.
The quirky way of handling the modulo in JS it's quite annoying.
L=g=>(
  g=g.split('\n').map(r=>[...r]),
  w=g[0].length,h=g.length,
  F=(x,y,t=((x%w)+w)%w,u=((y%h)+h)%h,v=g[u][t],k=0+[x,y])=>
    v<'.'?0:v>'.'?v!=k
    :[0,2,-3,5].some(n=>F(x+(n&3)-1,y+(n>>2)),g[u][t]=k),
  g.some((r,y)=>r.some((c,x)=>c=='.'&&F(x,y)))
)

Test In Firefox / FireBug console
Infinite
['##.###\n#..###\n..##..\n###..#\n##..##'
,'#.#\n...\n#.#'
,'#.###.#.###.#\n#.#...#...#.#\n#.#.#####.#.#\n..#.#...#.#..\n###.#.#.#.###\n#...#.#.#...#\n#.###.#.###.#'
,'##.###\n#..###\n..##..\n###..#\n##..##'
,'#.####.###.###.####\n#...#..#...###..###\n###.#..#.######..##\n....####.#######...\n###..###...########\n##########.##....##\n..###......##.##...\n#.........##..#####\n###########..###..#\n#...........####..#\n#.###########.##..#\n#.##....##.....####\n#.####.###.###.####'
].forEach(g=>console.log(g,L(g)))

Output
"##.###
#..###
..##..
###..#
##..##" true

"#.#
...
#.#" true

"#.###.#.###.#
#.#...#...#.#
#.#.#####.#.#
..#.#...#.#..
###.#.#.#.###
#...#.#.#...#
#.###.#.###.#" true

"##.###
#..###
..##..
###..#
##..##" true

"#.####.###.###.####
#...#..#...###..###
###.#..#.######..##
....####.#######...
###..###...########
##########.##....##
..###......##.##...
#.........##..#####
###########..###..#
#...........####..#
#.###########.##..#
#.##....##.....####
#.####.###.###.####" true

Finite
['###\n#.#\n###', '.#\n#.', '####\n.#..\n####'
,'#.#.#\n..#..\n#####\n..#..\n#.#.#'
,'#.#.#.#.#.#\n..#...#.#..\n###.###.###\n..#.#......\n#.#.#######\n#.#.......#\n#.#######.#\n#.#.....#.#\n#.#.#.#.#.#'
,'##....#####\n.#..#...##.\n.##.#..#...\n..###.###..\n#..##.#####\n#...##....#\n#.#.#####.#\n###..####.#\n....####...\n###...#####'
,'###....##.#########\n####...##....#...##\n..####.#######.###.\n....##..........##.\n###..#####.#..##...\n####..#..#....#..##\n..###.####.#.#..##.\n..###...#....#.#...\n..####..##.###...##\n#.####.##..#####.##\n####...##.#####..##'
].forEach(g=>console.log(g,L(g)))

Output
"###
#.#
###" false

".#
#." false

"####
.#..
####" false

"#.#.#
..#..
#####
..#..
#.#.#" false

"#.#.#.#.#.#
..#...#.#..
###.###.###
..#.#......
#.#.#######
#.#.......#
#.#######.#
#.#.....#.#
#.#.#.#.#.#" false

"##....#####
.#..#...##.
.##.#..#...
..###.###..
#..##.#####
#...##....#
#.#.#####.#
###..####.#
....####...
###...#####" false

"###....##.#########
####...##....#...##
..####.#######.###.
....##..........##.
###..#####.#..##...
####..#..#....#..##
..###.####.#.#..##.
..###...#....#.#...
..####..##.###...##
#.####.##..#####.##
####...##.#####..##" false

Yeah, daft modulo was a pain in C# as well, but I think I've found a way to make good use of it in my working copy with the directional code (I'll only re-post if I can get a 10% reduction or better): (j%4-1)%2 gives a nice repeating pattern.

I believe unnamed functions are permissible, and, thus, unless thfunction includes a call to itself (it would appear not to) it is permissible to not count the L= towards the byte count.

@SuperJedi224 you're probably right, but it's short enough as is after all

C# - 423 375 bytes
Complete C# program, accepts input via STDIN, outputs "True" or "False" to STDOUT as appropriate.
I could not bare to leave that Linq in there... thankfully its removal paid off! It now keeps track of seen and visited cells in an array (given it only ever looks at a finite number of them anyway). I also re-wrote the directional code, removing the need for a Lambda, and generally making the code more impossible to understand (but with substantial byte savings).
using C=System.Console;struct P{int x,y;static void Main(){int w=0,W,k=0,o,i,j;P t;string D="",L;for(;(L=C.ReadLine())!=null;D+=L)w=L.Length;for(i=W=D.Length;i-->0&k<W;){k=1;P[]F=new P[W];for(F[j=0].x=i%w+W*W,F[0].y=i/w+W*W;D[i]>35&j<k;)for(t=F[j++],o=1;o<5&k<W;t.y+=(o++&2)-1){t.x+=o&2;if(D[--t.x%w+t.y%(W/w)*w]>35&System.Array.IndexOf(F,t)<0)F[k++]=t;}}C.WriteLine(k>=W);}}

It is a breadth-first (not that this matters) search which just carries on until it either gets stuck in a finite cavern, or it decides the cavern is big enough that it must be infinitely large (when it has as many cells as the original rectangle, this means there must be a path from one cell to itself somewhere else, which we can continue to follow forever).
Untrimmed code:
using C=System.Console;

struct P
{
    int x,y;

    static void Main()
    {
        int w=0, // w is the width
        W, // W is the length of the whole thing
        k=0, // k is visited count
        o, // o is offset, or something (gives -1,0 0,-1 +1,0 0,+1 t offset pattern)
        i, // i is the start cell we are checking currently
        j; // j is the F index of the cell we are looking at

        P t; // t is the cell at offset from the cell we are looking at

        string D="", // D is the map
        L;

        for(;(L=C.ReadLine())!=null; // read a line, while we can
            D+=L) // add the line to the map
            w=L.Length; // record the width

        for(i=W=D.Length;i-->0&k<W;) // for each cell
        {
            k=1;

            P[]F=new P[W]; // F is the list of visited cells,

            for(F[j=0].x=i%w+W*W,F[0].y=i/w+W*W; // there are reasons (broken modulo)
                D[i]>35&j<k;) // for each cell we've visited, until we've run out
                for(t=F[j++], // get the current cell
                    o=1; // o is just a counter which we use to kick t about
                    o<5& // 4 counts
                    k<W; // make sure we havn't filled F
                    t.y+=(o++&2)-1) // kick and nudge y, inc o
                {
                    t.x+=o&2; // kick x
                    if(D[--t.x%w+t.y%(W/w)*w]>35 // nudge x, it's a dot
                       &System.Array.IndexOf(F,t)<0) // and we've not seen it before
                        F[k++]=t; // then add it
                }
        }

        C.WriteLine(k>=W); // result is whether we visited lots of cells
    }
}

Probably the first time I've seen a C# answer as the top vote getter here.

Main() in struct, now thats cute.

Python 2 - 258 210 244 bytes
Recursively check paths, if stack overflow return 1 (truthy) else return None (falsey).
import sys
def k(s):
 a=len(s);m=[[c=='.'for c in b]*999for b in s.split('\n')]*999;sys.setrecursionlimit(a)
 for x in range(a*a):
  try:p(m,x/a,x%a)
  except:return 1
def p(m,x,y):
 if m[x][y]:m[x][y]=0;map(p,[m]*4,[x,x,x+1,x-1],[y+1,y-1,y,y])

You can save some bytes by using ; for the lines in p, as you'll get them on the same line with the if.

"If stack overflow return true" - I like that recursion end condition :)

I'm not convinced this is a valid approach. Using stack overflows to detect an "infinite" region will produce false positives. The problem spec doesn't state any limitations on input ranges but something like a 300x300 labyrinth doesn't seem unreasonable and could enclose very long finite paths.

Almost all finite mazes would also cause a stack overflow. This is not a valid program.

@johne Updated so the recursion limit is on the order of the size of the labyrinths. Added 34 bytes unfortunately but it should be correct now (at least as correct as a hack like this can be).

Python 2 - 297 286 275 bytes
Picks an arbitrary "open" cell to begin a flood fill from. Labyrinth is infinite if during the fill we re-visit a cell we've already visited, but it has a different coordinate to the previous visit. If the flood fill fills the entire region without finding such a cell, try a different region. If such a region can't be found, the labyrinth is finite.
Takes file to process on command line, returns exit code 1 for infinite, and 0 for finite.
Returns correct results for all test cases.
import sys
e=enumerate
C=dict([((i,j),1)for i,l in e(open(sys.argv[1]))for j,k in e(l)if'.'==k])
while C:
 d={}
 def f(r,c):
  n=(r%(i+1),c%j)
  if n in d:return(r,c)!=d[n]
  if C.pop(n,0):d[n]=(r,c);return any(map(f,[r-1,r,r+1,r],[c,c+1,c,c-1]))
 if f(*C.keys()[0]):exit(1)

You can't assume that some any cell will be a member of an infinite cavern, you can easily have both infinite and finite caverns.

@VisualMelon: sorry, the description isn't entirely correct. The code does actually check every possible region of interconnected cells, not just one (as is currently implied). That's what the final while loop is for - selecting regions to check while there are still any unchecked cells left.


text:
DoIt Java Style
Given string X, convert it to Java Style string, as defined below:

Strings may only contain numbers and letters(signs are not allowed)
Strings must not start with numbers
Strings must start with Capital letter
Strings may not contain two capital letters in a raw.

As for conversion you may perform the next actions

Replace capital letter with lower case letter and vise versa.
Remove character

A good conversion is defined as follow:
Minimum actions been performed while achieving the next goals:

all the sequences of capital letters only kept the first letter as capital.
if a letter has a character in place before it, and the character is not a letter nor a number, then the letter becomes capital.
in case that after a good conversion there is a contradiction with the style, good conversion will be applied again on the result of previous conversion.
If there is more then one way to apply good conversion, than conversion A is considered to be better then conversion B if conversion A has more capital letters then B.

Input:

String x

Output:

Best conversion Java Style String

I/O examples
X                Output

'ab<>c'          'AbC'
'a<>b<>c'        'Abc' // conversion been applied twice. ABC -> Abc
'a<>bc'          'Abc' // conversion been applied twice. ABc -> Abc
'HI<>man'        'HiMan'
''               ''
'its**cOOL'      'ItsCool'
'28and*2fun'     'And2fun' // conversion been applied twice. and2fun -> And2fun

In this example strings been wrapped with '' sign.
Criteria

The shortest program wins, as determined by the number of bytes of source code.

What about underscores? Java allows underscores in names.

@Ilya_Gazman Yes, but AbC does not contain two capitals in a row.

@Doorknob i was afraid it will be to confusing so I did not allow it. My definition is to fallow.

Would 28and*2Fun (note the capital F) become And2Fun? Also would its**coOL (one lowercase o) become ItsCoOl?

@MartinBüttner yes for both of them

Without more detail about the interactions between the rules, they seem to contradict each other and some of the test cases. E.g. 'minimum actions been performed' would imply that no letter should be converted to a capital except the first one (required for conformance with the rules for valid output). May I point you at the sandbox?

Isn't HI<>man supposed to be HiMaN instead of HiMan

@CoolGuy no, there is no reason to convert the last latter to capital.

@PeterTaylor I edit it, so now there is no more contradictions

We can infer from your examples that we are meant to convert to upper case, then remove non-alphanumeric characters in that order but you do not state this explicitly.  Can you add this, please?

@Alchymist I believe that the instructions are clear as they are, please prove your point by providing an example to input that do not work with the rules.

@Ilya_Gazman you state that the only actions you can take are to convert the case of characters and to delete characters but you do not specify that these have to be in a specific order.  Then your 'good conversion' instructions do not state when to delete characters either.
By your example A2+b -> A2+B -> A2B (deletion occurs after capitalisation).  However equally valid is A2+b -> A2b (deletion occurs before capitalisation).

@Alchymist the good conversion speaks about the final result, based on the input. If your input is a2+b, than b is expected to become capital in the final output. In your second example you are doing legal string manipulations and then applying the conversion, in this case the conversion is not valid.

@Ilya_Gazman.  Your instructions do not state when deletions should happen.  Unless you specify that then my second example is valid according to your instructions, even if it is not what you intended.  A2b is a Java style string according to your definition.
This could just be a language problem as I suspect English is not your first language.  However both I and Peter Taylor find the current rules difficult to follow.  It might be useful if you just try restating the instructions in other words.

@Alchymist how about now?

@Ilya_Gazman.  I think it works, although it would still be simpler to explicitly state when to delete non-alphanumeric characters.

Java 551 490 bytes
public class A{public static void main(String...a){String b="";for(int i=0;i<2;i++){String[]c=a[0].split("[^a-zA-Z0-9]");if(c[0].length()>0&&Character.isDigit(c[0].charAt(0)))c[0]=c[0].replaceFirst("[0-9]+","");b="";for(String d:c){boolean e=false;String f="";byte[]g=d.getBytes();for(byte h:g){if(e){if(Character.isLowerCase(h))e=false;else h+='a'-'A';}else if(!Character.isLowerCase(h))e=true;f+=(char)h;}d=f;if(d.length()>0)b+=StringUtils.capitalize(d);}a[0]=b;}System.out.println(b);}}

Ungolfed Code:
public class A{
    public static void main(String...args){
        String input = args[0];

        String className = "";
        for (int i = 0; i < 2; i++) {
            String[] names = input.split("[^a-zA-Z0-9]");
            if(names[0].length() > 0 && Character.isDigit(names[0].charAt(0))){
                names[0] = names[0].replaceFirst("[0-9]+", "");
            }
            className = "";
            for (String value : names) {
                boolean toLowerCase = false;
                String newValue = "";
                byte[] bytes = value.getBytes();
                for (byte aByte : bytes) {
                    if(toLowerCase){
                        if (Character.isLowerCase(aByte)){
                            toLowerCase = false;
                        }
                        else{
                            aByte += 'a' - 'A';
                        }
                    }
                    else if (!Character.isLowerCase(aByte)){
                        toLowerCase = true;
                    }
                    newValue += (char)aByte;
                }

                value = newValue;
                if(value.length() > 0){
                    className += StringUtils.capitalize(value);
                }
            }
            input = className;
        }

        System.out.println(className);

    }
}

Haskell 316 bytes
Not fully golfed, may spend time to golf a bit more if others come and join the game.
import Data.Char
data T = C | S | X
conv t [] = []
conv t (c:cs)
  |isLower c = case t of X -> toUpper c : conv C cs; _ -> c : conv S cs
  |isUpper c = case t of C -> toLower c : conv X cs; _ -> c : conv C cs
  |isDigit c = c : conv S cs
  |otherwise = conv X cs
main = interact $ conv X . dropWhile isDigit . conv X

The C, S, X, data = T = C | S | X stands for Capital, Small, Other.


text:
Draw a Random Walk with Slashes
Write a program or function that takes in a positive integer N (via stdin/command line/function arg) and prints or returns a string representation of a two dimensional random walk that is N steps long, drawn out of slashes: / \ (plus spaces and newlines for spacing).
A 2D random walk starts at the origin of an infinite integer lattice. Then N times repeatedly, a cardinal direction (up, down, left, right) is chosen uniformly at random and the walker moves one unit in that direction. The resulting path taken is the random walk.
Here is a random walk for N = 6. Notice that it traverses back on itself when it reaches (-1, 3).

To draw this with slashes we essentially need to rotate the entire thing 45° clockwise. The axes and start and end points are not drawn in the slash version.
/
\
 \
 /\

A more complex walk like this (N = 20, though there's no way to tell):

Would become this:
     /
/\/ /\
\/\/
/\/
\/

Your program needs to generate these type of slash versions of random walks. You must randomly choose each new direction the walk takes, so every running of the program for a certain N will almost definitely produce a different walk. (Pseudorandomness is fine.)
There should never be any empty lines above or below the lowest and highest slashes (except for one optional trailing newline), and there should never be empty columns of spaces before or after the leftmost and rightmost slashes.
So for N = 1, the output is always / or \, but never something like:

 /

Trailing spaces are allowed as long as they don't go past the column of the rightmost slash.
The submission with the fewest bytes wins. Here's a handy byte counter.

so it's possible (although rare) that the output could be a single slash even when N = 20?

@DaveAlger Sure. Though if your program does that a lot I'd expect something is very wrong.

Pyth, 74 bytes
K0VQJO2=GO2 XH,-ZJ-KG@"\/"xJG-=ZtyJ-=KtyG;=YmrhSdheSdCHjbclhYsmh@XkH\ k.xY

An even more optimized translation of Uri Zarfaty's answer.

I've got a better Pyth solution: "\  - of course, there's no randomness, but it's a valid walk every time!

@theonlygusti Then I have an ever better solution: \.

Don't get it...

@theonlygusti Backslash in Pyth starts a 1 character constant. Oh wait, nevermind, isn't shorter xD

Python 2, 300 285 257 246 236 bytes

Something to kick things off. It should be possible to shrink this down further. Thanks @Maltysen for shaving 10 bytes.
from random import*
N=input()
x=y=0;G={}
exec'n=randrange(4);l=n<2;u=n&1;G[(x-l,y-u)]="\\/"[l^u];x-=2*l-1;y-=2*u-1;'*N
f=lambda i:range(min(x[i]for x in G),max(x[i]for x in G)+1)
for i in f(0):print"".join(G.get((i,j)," ")for j in f(1))

Generates the walk output into a dictionary G of visited (x,y) tuples, updating our location as we go. Each random step n is both either u/d (u) and l/r (l).

Neat. N = 100000, font size 1.

You can save a lot with "".join at the j in f(1) loop and printing directly.

PHP 5.5 - 209 bytes

<?for(;$X[]=$x+=1-2*$l,$Y[]=$y+=1-2*$u,$i++<$argv[1];){$m[$y-$u=$n&1][$x-$l=($n=rand(0,3))<2]='\\/'[$u^$l];}for($y=min($Y);$y<max($Y);$y++){for($x=min($X);$x<max($X);$x++)$s.=$m[$y][$x]?:' ';$s.="\n";}echo$s;

Ungolfed:
<?
for (; $X[] = $x += 1 - 2 * $l, $Y[] = $y += 1 - 2 * $u, $i++ < $argv[1];) {
    $m[$y - $u = $n & 1][$x - $l = ($n = rand(0, 3)) < 2] = '\\/'[$u ^ $l];
}
for ($y = min($Y); $y < max($Y); $y++) {
    for ($x = min($X); $x < max($X); $x++) {
        $s .= $m[$y][$x] ? : ' ';
    }
    $s .= "\n";
}
echo $s;

Began working on a PHP answer from scratch, but the final code too much resembled the work of @Uri Zarfaty so I really did not have the nerve to to post it. Ended up porting said answer with a few modifications instead. Pushes x/y values into $X and $Y arrays to determine min/max in output loop.
Usage:
php golf.php 200

Pyth - 89
This is basically a translation on Uri Zarfaty's answer, though I did make some optimizations.
KZVQJO4=G<J2=b.&J1 XH,-KG-Zb@"\\/".|Gb-=KtyG-=Ztyb)LrhSm@dbHheSm@kbHFNy0jkm?@H,Nb},NbHdy1

Explanation coming soon.
Try it here.


text:
■ or ■+■ or ■+■+■ or ■+■+■+■
Sum of squares
Goal: Write a given natural number as sum of squares. Thanks to Lagrange, Fermat and Legendre we know that you can write any positive integer as sum of (one), two, three, or maximal four squares of integers.
Your task is to write a program/function which takes a natural number via stdin/argument and outputs/returns a list of one to four numbers, where the sum of the squares of those numbers equals the input number. But you have to find the shortest possible example, that means if you can write a number as three squares, you may not output the four squares version.
Examples:
1 : 1
2 : 1,1
3 : 1,1,1
4 : 2
5 : 1,2
6 : 1,1,2
127 : 1,3,6,9
163 : 1,9,9
1234 : 3,35
1248 : 8,20,28

I think this will have different answers from the other question because there's no time limit so brute force is possible.

Between the lack of a time constraint and the minimality of the number of squares I think it's borderline okay to keep, but I'm not sure what others think.

I just read the linked question in detail, (I did not find it before, because I was looking for 'sum of squares' and similar keywords), I'm gonna close this question if nobody opposes.

JavaScript: 141
function x(i){var a=0,b,c,d;for(;a<i;a++)for(b=0;b<i;b++)for(c=0;c<i;c++)for(d=0;d<i;d++)if(a*a+b*b+c*c+d*d==i){console.log(a,b,c,d);return}}

Your function does not return the 'shortest' example. E.g. for the input 11 your function returns [0,1,1,3] where the shortest answer would be [1,1,3].

I assume the zeros returned don't count, as they don't contribute to the sum.

Does it always produce the shortest, ignoring 0s?

yes, by brute force.


text:
Remove single line and multiline comments from string
Goal
Using the programming language of your choice, write the shortest program to eliminate comments from a string representing a C program.

Input
The string can be taken as any form of input, but it may also be taken as a variable.

Instructions
Two different kinds of comments are to be removed:

multiline comments, starting with /* and ending with */
single line comments, starting with // and ending with Linux-style line breaks (LF, \n)

Comments within strings are not to be deleted. For the purpose of this challenge, you only need to consider "-delimited strings. In particular, you can ignore the possibility of '-delimited character literals. You may also ignore trigraphs and line continuations (/\<LF>*...).

Examples
Input:
#include <stdio.h>

int main(int argc, char** argv)
{
    // this comment will be removed
    if (argc > 1) {
        printf("Too many arguments.\n");   // this too will be removed
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");
    // but not this
    printf("just \"ano//ther\" test.");
    return 0;
}

Output:
#include <stdio.h>

int main(int argc, char** argv)
{

    if (argc > 1) {
        printf("Too many arguments.\n");
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");

    printf("just \"ano//ther\" test.");
    return 0;
}

Input:
/*
    this shall disappear
*/
#include <string>
int main(int argc, char** argv)
{
    string foo = ""/*remove that!**/;
    // Remove /* this
    int butNotThis = 42;
    // But do */ remove this
    int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
    return 0;//just a comment
}/*end of the file has been reached.*/

Output:
#include <string>
int main(int argc, char** argv)
{
    string foo = "";

    int butNotThis = 42;

    int bar = 4 * 3;
    return 0;
}

From where that printf("\"/* This will stay too */\"\n"); appeared in the should become code?

Oops, sorry... it was just a typo. Thanks for noticing!

Do whitespaces count? There are 4 spaces in front of // this comment will be removed which just disappeared. Any rule for that?

I don't know any of the listed languages that well, so some kind of a self-contained spec would be nice, together with more examples.

@manatwork: whitespace removal is not mandatory

@MartinBüttner & Zgarb: the comments to be removed are the ones described in the instruction section.

@MartinBüttner: trigraph management is not necessary

Not to mention issues around things like JavaScript's regex literals.

Are we allowed to assume that the file ends in a newline?

How about line continuation? It is going to mess up many of the answers here.

Retina, 35 + 1 + 2 = 38 bytes
This program consists of two files, hence I've included a 1-byte penalty for the second file.
//.*|/\*[\s\S]*?\*/|("(\\.|[^"])*")

$1

This is a simple regex replacement, using the .NET flavour (although this would work the same in most other flavours).
The idea is to match both comments and strings, but only write the match back if it was a string. By matching the strings explicitly, they are skipped when searching for comments.

This works surprisingly well in PHP: https://regex101.com/r/kB5kA4/1

@IsmaelMiguel Yes, I didn't use anything feature specific. The only reason I picked .NET is because Retina allows me to write regex-only programs without any overhead of calling something like preg_replace.

I'm aware of that. You've used it quite a lot before. If I'm correct, it was created by you. It was for the curious. And also, you now have a test-suite where you can test whatever changes come into this question (I predict many)

Nice! This regular expression even works with other programming languages (when slashes are escaped).

I used your regex technique to improve a third party library I work with: Dojo Toolkit

This is also working in Java, thank you

Shell + coreutils + gcc compiler collection, 31 bytes
This answer may seem a bit loopholey, but I didn't see anything specifically banning it in the question.
Rather than using clumsy regular expressions, why not use the tool that was built for the job.  It should have no problem giving correct results:
cpp -fpreprocessed -o- -|sed 1d

Takes input from STDIN and output to STDOUT.  Normally ccp will do all preprocessing (header files, macro expansion, comment removal, etc), but with the -fpreprocessed option, it will skip most of the steps, but it will still remove comments.  In addition, cpp adds a line like # 1 "<stdin>" to the beginning of the output, so the sed is there to delete it.

"-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi". might you be able to save some bytes by saving the file in something like a.i instead of using the flag?

@MartinBüttner Yes, I noticed that in the manual too.  So I would expect something like cat>i.i;cpp -o- i.i|sed 1d to be equivalent.  But full preprocessing ensues (e.g. full contents of stdio.h are inserted).  Possible gcc bug???  Well perhaps I'll check the cpp source when I get a mo'.

You can remove the |sed 1d if you add the -P option. Note that (as allowed by the question), as it expects pre-processed code, it won't handle trigraphs or line continuations properly.

I am getting problems with this code. It spews out "# 234" with varying numbers after the hashtag, here and there.

Java 365
String a(String s){String o="";int m=1;for(int i=0;i<s.length();i++){String u=s.substring(i,Math.min(i+2,s.length()));char c=s.charAt(i);switch(m){case 1:m=u.equals("/*")?5:u.equals("//")?4:c=='"'?3:1;break;case 3:m=c=='"'?1:c=='\\'?2:3;break;case 2:m=3;break;case 4:m=c=='\n'?1:4;continue;case 5:m=u.equals("*/")?1:5;i+=m==1?1:0;continue;}o+=m<4?c:"";}return o;}}

Ungolfed
public static final int DEFAULT = 1;
public static final int ESCAPE = 2;
public static final int STRING = 3;
public static final int ONE_LINE_COMMENT = 4;
public static final int MULTI_LINE_COMMENT = 5;

String clear(String s) {
    String out = "";
    int mod = DEFAULT;
    for (int i = 0; i < s.length(); i++) {
        String substring = s.substring(i, Math.min(i + 2 , s.length()));
        char c = s.charAt(i);
        switch (mod) {
            case DEFAULT: // default
                mod = substring.equals("/*") ? MULTI_LINE_COMMENT : substring.equals("//") ? ONE_LINE_COMMENT : c == '"' ? STRING : DEFAULT;
                break;
            case STRING: // string
                mod = c == '"' ? DEFAULT : c == '\\' ? ESCAPE : STRING;
                break;
            case ESCAPE: // string
                mod = STRING;
                break;
            case ONE_LINE_COMMENT: // one line comment
                mod = c == '\n' ? DEFAULT : ONE_LINE_COMMENT;
                continue;
            case MULTI_LINE_COMMENT: // multi line comment
                mod = substring.equals("*/") ? DEFAULT : MULTI_LINE_COMMENT;
                i += mod == DEFAULT ? 1 : 0;
                continue;
        }
        out += mod < 4 ? c : "";
    }

    return out;
}

Python2 - 163 134 bytes
import re
def f(s):
 for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
 print s

As you can see here, the regex consists of 2 alternating capturing groups. The first one captures all the quoted strings. The second one all the comments.
All we need to do, is removing everything captured by the 2nd group.
Example:

Python 2.7.9 (default, Dec 11 2014, 04:42:00)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> def f(s):
...  for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
...  print s
...
>>> code = r'''#include <stdio.h>
...
... int main(int argc, char** argv)
... {
...     // this comment will be removed
...     if (argc > 1) {
...         printf("Too many arguments.\n");   // this too will be removed
...         return 1;
...     }
...     printf("Please vist http://this.will.not.be.removed.com\n");
...     printf("/* This will stay */\n");
...     printf("\"/* This will stay too */\"\n");
...     printf("//and so will this\\");
...     // but not this
...     printf("just \"ano//ther\" test.");
...     return 0;
... }
... /*
...     this shall disappear
... */
... #include <string>
... int main(int argc, char** argv)
... {
...     string foo = ""/*remove that!**/;
...     // Remove /* this
...     int butNotThis = 42;
...     // But do */ remove this
...     int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
...     return 0;//just a comment
... }/*end of the file has been reached.*/'''
>>> f(code)
#include <stdio.h>

int main(int argc, char** argv)
{

    if (argc > 1) {
        printf("Too many arguments.\n");
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");

    printf("just \"ano//ther\" test.");
    return 0;
}

#include <string>
int main(int argc, char** argv)
{
    string foo = "";

    int butNotThis = 42;

    int bar = 4 * 3;
    return 0;
}

Rebol - 151
f: func[t][Q:{"}W: complement charset Q parse t[any[[Q any["\\"|"\"Q | W]Q]|[a:[["//"to[lf | end]]|["/*"thru"*/"]]b:(remove/part a b):a skip]| skip]]t]

Ungolfed + some annotations:
f: func [t] [
    Q: {"}
    W: complement charset Q     ;; any char thats not a double quote

    ; rule to parse t (c program) - it can be ANY of
    ;     1. string
    ;     2. OR comment (if so then remove)
    ;     3. OR pass thru

    parse t [
        any [
            ;; 1. String rule
            [Q any ["\\" | "\" Q | W] Q]

            ;; 2. OR comments rule
            | [
                a:  ;; mark beginning of match
                [
                    ;;    // comment    OR  /* comment */
                    ["//" to [lf | end]] | ["/*" thru "*/"]
                ]
                b:  ;; mark end of match
                (remove/part a b) :a skip   ;; remove comment
            ]

            ;; 3. OR allow thru (so not a String or Comment)
            | skip
        ]
    ]

    t
]

PHP
Converting @Martin Ender's answer for php:
$str = preg_replace_callback('/\/\/.*|\/\*[\s\S]*?\*\/|("(\\.|[^"])*")/m',
  function($matches){
     if(\is_array($matches) && (\count($matches) > 1)){
        return $matches[1];
     }else{
        return '';
     }
  }, $str);

now $str has lost single- and multi-line comments.
This is useful for stripping comments in JSON data before feeding to json_decode().

Maybe you could reduce the bytes count by using a ternary operator?

C# (262 chars):
From this very good SO answer:
string a(string i){return Regex.Replace(i, @"/\*(.*?)\*/|//(.*?)\r?\n|""((\\[^\n]|[^""\n])*)""|@(""[^""]*"")+", m => { var v = m.Value; if (v.StartsWith("/*") || v.StartsWith("//")) return v.StartsWith("//") ? "\r\n" : ""; return v; }, RegexOptions.Singleline);

JS (ES6), 47 chars (wip)
DEMO: http://codepen.io/anon/pen/dPEMro
a=b=>b.replace(/(\/\*[^]*?\*\/|\/\/.*)\n?/g,"")

Inspired by my codegolfed minifiers: http://xem.github.io/miniMinifier/
doesn't handle comments in strings yet...
I'm curious to see if it's possible to achieve that in JS regexes.

If this answer doesn't meet the requirements, it should either be fixed or deleted.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳


text:
Remove boxes under preservation of shape
This challenge is specific to languages of the APL family. Although it might be solvable in other languages, please do not expect this to be easy as it depends on some specific concepts of this language family.
Many array oriented languages have the concept of a box (also called enclosure). A box encapsulates an array, hiding its shape. Here is an example of a boxed array:
┌─┬───────┬─────┐
│0│1 2 3 4│0 1 2│
│ │       │3 4 5│
└─┴───────┴─────┘

This array was generated from the J sentence 0 ; 1 2 3 4 ; i. 2 3 and contains three boxes, the first containing the scalar 0, the second containing a vector of shape 4, and the third containing a matrix of shape 2 3.
Some arrays of boxes look like they are plain arrays broken apart by boxes:
┌─┬───────────┐
│0│1 2 3 4    │
├─┼───────────┤
│5│ 9 10 11 12│
│6│13 14 15 16│
│7│17 18 19 20│
│8│21 22 23 24│
└─┴───────────┘

The previous array was generated from the J expression 2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4.
Your goal in this challenge is to take an array like that and remove the boxes separating the subarrays from one another. For instance, the previous array would be transformed into
0  1  2  3  4
5  9 10 11 12
6 13 14 15 16
7 17 18 19 20
8 21 22 23 24

Submit a solution as a monadic verb / function. The verb must work on arrays of arbitrary rank. You may assume that the shapes of the boxed arrays fit, that is, boxed subarrays adjacent on an axis have to have the same dimensions in all but that axis. Behaviour is undefined if they don't.
This challenge is code golf. The submission compromising the least amount of characters wins.

Which languages are considered part of the APL family?

@AlexA. Languages like APL, J, and K.

@randomra An array of boxes such that the arrays in the boxes if concatenated along the respective axes would form one large array. Imagine each boxed subarray to be a cuboid or rectangle and you put these together as specified by the boxes' positions to get a large cuboid or rectangle.

@randomra Your input would be considered invalid as the subarrays are not directly concatenable along the axes they would be concatenated.

Number of dimensions for the boxed array?

@randomra Arbitrary.

In the interest of making this less language-specific, why not provide the example also using simple nested array notation for other languages?

@MartinBüttner That would require a notation that can distinguish nested arrays from multi-dimensional arrays.

@FUZxxl Why? The first two levels would be treated as a 2D array of boxes, and the (up to 2) levels below that would be the normal arrays. Or could you actually have arbitrarily many dimensions of either in the challenge? If so, your own example is by far not enough and you should include at least 1D and 3D examples as well.

@MartinBüttner It's supposed to work with n-dimensional arrays of boxes where each box contains an array of arbitrary dimension as long as the constraints are met.

"You may assume that the shapes of the boxed arrays fit, that is, boxed subarrays adjacent on an axis have to have the same dimensions in all but that axis." So doesn't that mean 2 2$0;1 2 3 4;(,.5 6 7 8);9+i.4 4 is undefined behaviour? 1 2 3 4 doesn't have the same dimensions as 0 or 9+i.4 4 because the ranks don't even match.

@algorithmshark If one subarray has lesser rank than another, add leading axes with a dimension of one each until the ranks are equal.

@FUZxxl Do you have a nice solution for the question? (Couldn't ping/reach you in chat.)

@randomra No. I have some ideas involving ;"1 and transposing the matrices until we're out of boxes.

@FUZxxl I feel like you need dynamic rank (which doesn't exist AFAIK). (Hence my "code-generator" hack.) Would be interested to see how can you resolve that issue (or is it exist at all).

@randomra Rank can be an arbitrary noun, does not need to be a constant.

@FUZxxl Can't ping you in chat (because you haven't been there for some time) but (<@(<;.1)~1,.2#:@i.@^<:@#) 'abc' works for partitioning. (And I would like to see your solution for this challenge. :))

J, 73 chars
f=.3 :0
>".'z',~,(',"','&.>/',~":)"*1+i.#$z=.(,$~$,~1#~(#$y)-#@$)&.>y
)

Usage and tests:
   a=.2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4

   f a
0  1  2  3  4
5  9 10 11 12
6 13 14 15 16
7 17 18 19 20
8 21 22 23 24

   f a,:a  NB. rank 3 test
0  1  2  3  4
5  9 10 11 12
6 13 14 15 16
7 17 18 19 20
8 21 22 23 24

0  1  2  3  4
5  9 10 11 12
6 13 14 15 16
7 17 18 19 20
8 21 22 23 24

Golfing and explanation coming tomorrow.

Your solutions looks like you took a sledgehammer to the problem and beat it with brute force until it ceased to exist.

@FUZxxl Exactly. Interested in nice solutions.

J, 39
f=:([:;(([:(;"1@|:)(;/&> ::]))&.>)@<"1)

Usage and tests
a=.2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4
   f a
0  1  2  3  4
5  9 10 11 12
6 13 14 15 16
7 17 18 19 20
8 21 22 23 24

Is the name for v really needed? This csn be shortened I think.

good point. shortened

You can leave out some parentheses: [:;([:;"1@|:;/&> ::])&.>@<"1 it's not needed to assign the verb to a name either.

This looks a little bit like it would only work with two-dimensional test-cases.


text:
Write an evil April Fools file scanner
This is inspired by my python-ideas "new module loader" prank.
Your task is to write a cat-like program that does the following:

Read the file on disk labeled files. Assume it exists. No error handling necessary.
The file contains a list of files separated by newlines. The file names may contain spaces. Print the file name and the contents to the screen like so:
<<<<myfile.txt
file contents here

<<<<another file.txt
those file contents here

Also store the file name some sort of array/list.
Pick a random file name from the array and print:
fatal error: ?
with file myfile
executing 'rm -rf /'

replacing myfile with the randomly picked file name.
Loop forever.

The program flow would be something like this:
file = open 'files'
all files = empty list
for filename in file
    print "<<<<" + filename
    contents = read contents of filename
    print contents
    add filename to all files
bad file = random filename in all files
print "fatal error: ?"
print "with file " + bad file
print "executing 'rf -rf /'"
while true do
end

Shortest entry wins.

Typo in the pseudocode. Shouldn't rf -rf be rm -rf?

Personally I think this toes the line of malicious code, which is off topic here. Maybe I'm just a little too jumpy when I see rm -fr / appear in any code.

Pyth - 77
Can probably be golfed a lot more.
#FN'"files"+*\>4Njb'NaYN)"fatal error: ?"+"with file "OY"executing 'rm -rf /'

Won't work on the online interpreter because it doesn't allow unsafe operations.
#                         Infinite loop
 FN                       For N in
  '"files"                Read file files as list of lines
  +                       Concat
   *\>4                   4 >'s
   N                      File name
  jb                      Join by newlines
   'N                     Readfile as list of lines
  aYN                     Append N to empty list
  )                       Close for loop
 "fatal error: ?"         Print message
 +                        Concatenation
  "with file "            Message
  OY                      Random choice of file list
 "executing 'rm -rf /'    Message with implicit closing quote


text:
Find a mirror configuration to match laser destinations
UPDATED SCORING: As this challenge is more difficult than I anticipated, I have adjusted the scoring. A program that can solve a single mirror input is a valid answer. More sophisticated programs get a bonus to their score.
There have been several puzzles on PPCG to find a laser path in a box of
mirrors. In this puzzle, you need to create a box of mirrors to match a number
of laser destinations.
You are given a box and a specifications where lasers are to enter and exit.
Your program needs to place exactly N double-sided mirrors in the box to meet
the specification. The mirrors must be angled at 45 degrees but can be forward
sloping or back sloping.
Input
Your program should accept a box grid via STDIN, command line argument, or file
in the following format examples:
+--G--+     +abcde+
G     |     f/////d
|    /|     a//   c
+-----+     f     |
            +-b-e-+

The letter pairs ([a-zA-Z] may be used) indicate the input/output of up to 52 lasers.
Inside the box will be N / mirrors. The box dimensions will be
3 <= W,H <= 200. The box is made of +|- characters. There may be any number of
  mirrors in the box including zero.
Output
The output should match the input, except the / characters may be moved and/or
changed into \ characters.  Your program should send a correct mirror box
string to STDOUT or a file, trailing new line optional. If no placement of
mirrors can meet the input specification, output Impossible\n. Examples of
possible solutions:
+--G--+     +abcde+
G  /  |     f \ \ d
|     |     a/ \  c
+-----+     f / //|
            +-b-e-+

Testing example
Input:
+abcdefghijklmnopqrstuvwxyA-+
|///////////////            |
|///////////////            |
|                           |
+-Abcdefghijklmnopqrstuvwxya+

Example output:
+abcdefghijklmnopqrstuvwxyA-+
|\                         \|
|/                        / |
|\\\\\\\\\\\\\\\\\\\\\\\\\\ |
+-Abcdefghijklmnopqrstuvwxya+

Scoring (UPDATED)
This is code-golf with bonuses. You should nominate with your answer how many mirrors your program can solve (N). Your score is the length of your program in bytes divided by N. This allows people to enter with a simple program, but rewards more ambition programmers with a bonus.
Standard loopholes disallowed.

This sounds like a hard problem, regardless of golfing.

Hint: brute force is not an option; it will take you 3 universe ages at 10k options per second for the larger example.

@sanchises I think it will take a great deal longer, as any mirror can be flipped, so I think you need a * 2^30 component in there as well

Extra hint: You will need to exploit properties of the puzzle to prune your search space. You might also using combinations of partial solutions or hillclimbing from partial solutions that are close to a complete solution. It is now valid to answer with simpler solutions, so programs that solve one or two mirror puzzles are welcome too.

C# - 897 862 bytes
Found a serious bug with it putting mirrors in places that they can't be. Now it works, hopefully! Also did some light golfing, couldn't leave the while loop in there... shameful.
Complete program, takes input from STDIN, outputs to STDOUT.
This was a lot of fun, it copes fine with the 7 by 5 problem (and when you remove one of the mirrors, making it impossible), took about 1 hour to solve the 30 by 5.
using Q=System.Console;class P{static int w,L;static string S(char[]M,int t,int r,int i,int d,int[]B){var s="";if(r<0)return s;M=(char[])M.Clone();B=(int[])B.Clone();B[i]=1;for(i+=d;M[t]<48|t==i;i=t+(d=t<w?w:t>L-w?-w:t%w<1?1:-1))if(++t>=L){for(i=0;++i<L&r>0;)if(B[i]<1&M[i]<33){M[i]='.';r--;}return r<1?new string(M):s;}int c=M[i];if(c>32)s=c>47|c<46?s=c==M[t]?S(M,t,r,t,0,B):s:S(M,t,r,i,c<47?w/d:-w/d,B);else if((s=S(M,t,r,i,d,B))==""&B[i]<1){M[i]='.';s=S(M,t,r-1,i,w/d,B);if(s==""){M[i]='/';s=S(M,t,r-1,i,-w/d,B);}}return s;}static void Main(){string a,A="",R=A;for(;(a=Q.ReadLine())!=null;A+=a)L+=(w=a.Length);var G=A.ToCharArray();int r=0,i=L;for(;i>0;G[i]=G[i]=='|'?',':G[i])if(G[--i]==47|G[i]==92){r++;G[i]=' ';}a=S(G,0,r,1,w,new int[L]);if(a=="")R="Impossible\n";else for(;i<L;i+=w)R+=a.Substring(i,w)+"\n";Q.Write(R.Replace(".","\\").Replace(",","|"));}}

7 by 5 Example:
+abcde+
f/////d
a//   c
f     |
+-b-e-+

+abcde+
f   \ d
a/  //c
f/ \ /|
+-b-e-+

Impossible version:
+abcde+
f ////d
a//   c
f     |
+-b-e-+

Impossible

Something different (the program doesn't look at the original mirror layout):
+a----+
|//// |
|/////|
|/////|
+----a+

+a----+
| /\\\|
|\\\\\|
|\\/\\|
+----a+

30 by 5 solution:
+abcdefghijklmnopqrstuvwxyA-+
| \\\\\\\\\\\\\\\\\\\\\\\\ \|
| /                       //|
|\                         \|
+-Abcdefghijklmnopqrstuvwxya+

It looks at each laser source in turn, and builds a valid route for it (if it can), and then moves onto the next. It's a pretty simple depth-first search, which has to know which laser source (target) it's looking at, how many mirrors it remain for it to place, the current cell it's "at", the direction it's moving in, and each cell it's visited already (so that it doesn't put a mirror somewhere it's already been). The last 3 are used for assembling the path for the current target, and at reset when the target changes. Once it's got all the lasers linked up, it goes ahead and fills in any gaps it doesn't need left empty (another reason it needs to know everywhere it's visited).
When it's building routes, it favours going "forward" over inserting a mirror, and when it does, it favours a "\" mirror - this is best seen in the "something different" example above, where it skips the first cell below the top-most 'a', then continually fills out a "\" if it can find a solution with one, otherwise a "/" (naturally, if skipping the first cell resulted in it being unable to find a solution, then it would back-track and try putting a mirror there instead).
using Q=System.Console;

class P
{
    static int w,L;

    // M is cur grid
    // t is target edge thing (0->L)
    // r is mirrors remaining
    // i is pos
    // d is dir
    static string S(char[]M,int t,int r,int i,int d,int[]B)
    {
        var s="";

        if(r<0) // no mirrors left
            return s;

        // clone everything
        M=(char[])M.Clone();
        B=(int[])B.Clone();

        B[i]=1; // can't write to this

        for(i+=d; // move i
            M[t]<48|t==i; // only if target is something sensible (increment if i==t)
            i=t+(d=t<w?w:t>L-w?-w:t%w<1?1:-1)) // reflect, should be fine for w=3
            if(++t>=L) // run off the end
            {
                for(i=0;++i<L&r>0;) // don't need I any more (count through everything)
                    if(B[i]<1&M[i]<33) // not been here & it's open space
                    {
                        M[i]='.'; // doesn't matter
                        r--;
                    }
                return r<1?new string(M):s; // none remaining ? victory : defeat
            }

        int c=M[i];
        if(c>32) // not boring
            s=c>47|c<46? // hit edge
                s=c==M[t]? // hit the correct thing
                    S(M,t,r,t,0,B): // i+0=t, tells it to increment t
                    s
            :S(M,t,r,i,c<47?w/d:-w/d,B); // mirror
        else // boring
            if((s=S(M,t,r,i,d,B))==""&B[i]<1) // fwd
            {
                M[i]='.'; // use . instead of \
                s=S(M,t,r-1,i,w/d,B); // \
                if(s=="")
                {
                    M[i]='/';
                    s=S(M,t,r-1,i,-w/d,B); // /
                }
            }

        return s;
    }

    static void Main()
    {
        string a,A="",R=A; // R is free
        for(;(a=Q.ReadLine())!=null;A+=a) // read input
            L+=(w=a.Length); // note width, accumulate length

        var G=A.ToCharArray();

        int r=0,i=L; // count mirrors (I refuse to make these static)
        for(;i>0; // end on i=0
            G[i]=G[i]=='|'?',':G[i]) // replace | with ,
            if(G[--i]==47|G[i]==92) // remove and count mirrors
            {
                r++;
                G[i]=' '; // storing G[i] doesn't seem to save anything
            }

        // search
        a=S(G,0,r,1,w,new int[L]);

        if(a=="") // defeat
            R="Impossible\n";
        else // victory
            for(;i<L;i+=w) // for each line
                R+=a.Substring(i,w)+"\n";

        Q.Write(R.Replace(".","\\").Replace(",","|")); // swap back | and \
    }
}

Nice solution. According to the new scoring system you score at least 917/7 = 131.

Python, 671 654 bytes
Not a solution, but an attempt, read below.
import random as R
def V(F):
 for S,_x,_y in (F[0],0,1),(F[-1],0,-1),([L[0] for L in F],1,0),([L[-1] for L in F],-1,0):
  for i,C in enumerate(S):
   if not C in '+-|':
    x=_x;y=_y
    if not x: X=i;Y=y
    elif not y: Y=i;X=x
    while F[Y][X] != C:
     if F[Y][X]=='\\':x,y=y,x
     if F[Y][X]=='/':a=x+y;x,y=x-a,y-a
     X+=x;Y+=y
     try:
      if F[Y][X] in '+-|':return False
     except:
      return False
 return True
F=open(input()).read().split('\n')
while 1:
 _=[F[0]]+['\n'.join([L[0]+''.join([R.choice(' \\/')for i in range(len(F[0])-2)])+L[-1] for L in F[1:-1]])]+[F[-1]]
 if V(_):
  for l in _: print l
  break

I did not golf this to the max, since I'm not satisfied with the solution.
V validates a given solution by walking the field F for each character C it finds on the sideline. Solutions are generated at random. It's ugly, it works for entry1, but takes a Lot of time for the other entries. Since it randomly tries solutions, I don't consider this to be an actual solution for the given problem; but it might help others.
Run:
echo "entry1.txt" | python script.py

With the new scoring system, this is a valid solution but does not score a divisor bonus (unless it can solve problems with 2 or more mirrors). I think you could optimise this by pruning out invalid configurations earlier (eg: each column or row with a letter on the edge must have at least one mirror - unless matching letters are opposite each other).