Quine/Error Quine Polyglot Your task is simple: Write a program that can be run in two languages. It should be a normal quine (prints its own source code) in language 1, and should be an error quine (generates an error message identical to its own source code) in language 2.

This is code-golf, so the shortest valid submission (in bytes) wins.

Rules:

The languages may be arbitrarily similar. Supersets/similar versions/similar dialects are not disallowed.
The error quine rules are the same as those in Make an Error Quine!.

Befunge-93 (FBBI) / C (tcc), 93 + 62 = 155 bytes

^"
>#001p#"<>:#,_@#1-8*3:-1*57+55-1*79*57:-1:*77**278\-1:*57$p:1: error: declaration expected

Try it online!: Befunge-93, C

Thanks to randomdude999 for noting that the filename requires matching quotes to work.

Must be saved under the filename ^"\n>#001p#"<>:#,_@#1-8*3:-1*57+55-1*79*57:-1:*77**278\-1:*57$p, where \n is a newline. Because of this, the TIO for C doesn't run exactly as intended. Tested to work on Lubuntu.

Explanation (C):

The program fails to compile, and tcc happily outputs the name of the file as part of its error message. There are multiple compilation errors you can get, based on the beginning of the code. ^ at the start gives us a declaration expected, which is short and doesn't contain any problematic characters like ". On the other hand, the gcc and clang developers are very pessimistic and they chose to output multiple errors at once, which is not very nice, so we aren't using their compilers.

Explanation (Befunge-93):

Befunge is convenient for quines in that its code can also be utilised as character data, thanks to the " command, which toggles string mode. At the beginning, we perform some useless stack operations, then issue a p (put command) which places a NUL character at (0, 1). Then we reflect the instruction pointer to the left and begin reading everything as a string. This has to be done to the left, because of the stack's LIFO nature. After wrapping around and reaching the " character again, the string ends. Note that the NUL character replaced the $ character, creating a delimiter midway through the string. We then push 3 numbers onto the stack and jump over the NUL (because it unfortunately hangs the interpreter when run as an instruction). The static part of the error message has to be executed here. Most of its characters are no-ops, but the p command consumes three arguments (hence why we pushed 3 numbers, otherwise part of the string would be eaten here), and : & 1 characters push a total of 4 values to the stack, which we counteract with a p and a $ (pop and discard) instruction. Then, some arithmetic is performed to push the ASCII codes for ^"\n>#001p#" and finally a loop prints out all the values on the stack as characters until it finds a NUL character and terminates.


Mathematica 132 136 127
If Erfc is acceptable, here's my attempt, accurate to 6 places:
t=Table;TableForm[Partition[t[0.5 Erfc[-x/Sqrt[2]],{x,0,3.99,.01}],10],
TableHeadings->{t[k,{k,0,3.9,.1}],t[k,{k,0,.09,.01}]}]


Find the minimal initial values Consider a sequence F of positive integers where F(n) = F(n-1) + F(n-2) for n >= 2.  The Fibonacci sequence is almost one example of this type of sequence for F(0) = 0, F(1) = 1, but it's excluded because of the positive integer requirement.  Any two initial values will yield a different sequence.  For example F(0) = 3, F(1) = 1 produces these terms.

3, 1, 4, 5, 9, 14, 23, 37, 60, 97, ...

Challenge

The task is to find F(0) and F(1) that minimize F(0) + F(1) given some term of a sequence F(n).  Write a function or complete program to complete the task.

Input

Input is a single positive integer, F(n).  It may be accepted as a parameter or from standard input.  Any reasonable representation is allowed, including direct integer or string representations.

Invalid inputs need not be considered.

Output

The output will be two positive integers, F(0) and F(1).  Any reasonable format is acceptable.  Here are some examples of reasonable formats.

Written on separate lines to standard output
Formatted on standard output as a delimited 2-element list
Returned as a tuple or 2-element array of integers from a function

Examples

60  -> [3, 1]
37  -> [3, 1]
13  -> [1, 1]
26  -> [2, 2]
4   -> [2, 1]
5   -> [1, 1]
6   -> [2, 2]
7   -> [2, 1]
12  -> [3, 2]
1   -> [1, 1]

Scoring

This is code golf.  The score is calculated by bytes of source code.

Sandbox

Jelly, 13 bytes

pWạ\Ṛ$</¿€SÞḢ

Try it online!

How it works

pWạ\Ṛ$</¿€SÞḢ  Main link. Argument: n

 W             Wrap; yield [n].
p              Cartesian product; promote the left argument n to [1, ..., n] and take
               the product of [1, ..., n] and n, yielding [[1, n], ..., [n, n]].
         €     Map the link to the left over the pairs [k, n].
        ¿          While...
      </               reducing the pair by less-than yields 1:
  ạ\                       Cumulatively reduce the pair by absolute difference.
    Ṛ                      Reverse the result.
                   In essence, starting with [a, b] := [k, n], we keep executing
                   [a, b] := [b, |a - b|], until the pair is no longer increasing.
          SÞ   Sort the resulting pairs by their sums.
            Ḣ  Head; extract the first pair.


Build a pair of spies that will throw stones into a river Recently at the newly released Puzzling.SE, there was a problem about spies throwing stones into a river that was actually quite challenging:

Two spies must pass each other two secret numbers (one number per spy), unnoticed by their enemies. They have agreed on a method for doing this using only 26 indistinguishable stones in advance.
They meet at a river, where there is a pile of 26 stones. Starting with the first spy, they take turns throwing a group of stones into the river: the first spy throws some number of stones, then the second one, then the first one again...
Each spy must throw at least one stone on his turn, until all the stones are gone.
They observe all throws and diverge when there are no more stones. They keep silence all the time and no information is exchanged except number of stones thrown at each turn.
How can they exchange the numbers successfully if the numbers can be from 1 to M?

Your task is to build a pair of programs, spy1 and spy2, that can solve this problem for the highest possible M.
Your programs will each take a number from 1 to your chosen M as input. Then, spy1 will output a number representing the number of stones it throws into the river, which will be input to spy2 which will also output a number to be input to spy1, and so on until the numbers output add up to 26. At the end of throwing, each program will output the number it believes the other program had, which must match the number that was actually input to the other program.
Your program must work for all possible ordered pairs of numbers (i, j) where both i and j can vary from 1 to M.
The program that works for the largest M will be the winner, with the first answer to be posted breaking a tie. Additionally, I will award a +100 reputation bounty to the first solution that is proven to work for M >= 2286, and +300 to the first solution that is proven to work for M >= 2535.

C#, M = 2535

This implements* the system which I described mathematically on the thread which provoked this contest. I claim the 300 rep bonus. The program self-tests if you run it either without command-line arguments or with --test as a command-line argument; for spy 1, run with --spy1, and for spy 2 with --spy2. In each case it takes the number which I should communicate from stdin, and then does the throws via stdin and stdout.

* Actually, I've found an optimisation which makes a massive difference (from several minutes to generate the decision tree, to less than a second); the tree which it generates is fundamentally the same, but I'm still working on a proof of that. If you want a direct implementation of the system which I described elsewhere, see revision 2, although you might want to backport the extra logging from Main and the better inter-thread comms from TestSpyIO.

If you want a test case which completes in less than a minute, change N to 16 and M to 87.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace CodeGolf
{
    internal class Puzzle625
    {
        public static void Main(string[] args)
        {
            const int N = 26;
            const int M = 2535;

            var root = BuildDecisionTree(N);

            if (args.Length == 0 || args[0] == "--test")
            {
                DateTime startUtc = DateTime.UtcNow;
                Console.WriteLine("Built decision tree in {0}", DateTime.UtcNow - startUtc);
                startUtc = DateTime.UtcNow;

                int ok = 0;
                int fail = 0;
                for (int i = 1; i <= M; i++)
                {
                    for (int j = 1; j <= M; j++)
                    {
                        if (Test(i, j, root)) ok++;
                        else fail++;
                    }
                    double projectedTimeMillis = (DateTime.UtcNow - startUtc).TotalMilliseconds * M / i;
                    Console.WriteLine("Interim result: ok = {0}, fail = {1}, projected test time {2}", ok, fail, TimeSpan.FromMilliseconds(projectedTimeMillis));
                }
                Console.WriteLine("All tested: ok = {0}, fail = {1}, in {2}", ok, fail, DateTime.UtcNow - startUtc);
                Console.ReadKey();
            }
            else if (args[0] == "--spy1")
            {
                new Spy(new ConsoleIO(), root, true).Run();
            }
            else if (args[0] == "--spy2")
            {
                new Spy(new ConsoleIO(), root, false).Run();
            }
            else
            {
                Console.WriteLine("Usage: Puzzle625.exe [--test|--spy1|--spy2]");
            }
        }

        private static bool Test(int i, int j, Node root)
        {
            TestSpyIO io1 = new TestSpyIO("Spy 1");
            TestSpyIO io2 = new TestSpyIO("Spy 2");
            io1.Partner = io2;
            io2.Partner = io1;

            // HACK! Prime the input
            io2.Output(i);
            io1.Output(j);

            Spy spy1 = new Spy(io1, root, true);
            Spy spy2 = new Spy(io2, root, false);

            Thread th1 = new Thread(spy1.Run);
            Thread th2 = new Thread(spy2.Run);
            th1.Start();
            th2.Start();

            th1.Join();
            th2.Join();

            // Check buffer contents. Spy 2 should output spy 1's value, so it's lurking in io1, and vice versa.
            return io1.Input() == i && io2.Input() == j;
        }

        private static Node BuildDecisionTree(int numStones)
        {
            NodeValue[] trees = new NodeValue[] { NodeValue.Trivial };
            for (int k = 2; k <= numStones; k++)
            {
                int[] prev = trees.Select(nv => nv.Y).ToArray();
                List<int> row = new List<int>(prev);
                int cap = prev.Length;
                for (int i = 1; i <= prev[0]; i++)
                {
                    while (prev[cap - 1] < i) cap--;
                    row.Add(cap);
                }

                int[] next = row.OrderByDescending(x => x).ToArray();
                NodeValue[] nextTrees = new NodeValue[next.Length];
                nextTrees[0] = trees.Last().Reverse();
                for (int i = 1; i < next.Length; i++)
                {
                    int cp = next[i] - 1;
                    nextTrees[i] = trees[cp].Combine(trees[i - prev[cp]]);
                }

                trees = nextTrees;
            }

            NodeValue best = trees.MaxElement(v => Math.Min(v.X, v.Y));
            return BuildDecisionTree(numStones, best, new Dictionary<Pair<int, NodeValue>, Node>());
        }

        private static Node BuildDecisionTree(int numStones, NodeValue val, IDictionary<Pair<int, NodeValue>, Node> cache)
        {
            // Base cases
            // NB We might get passed val null with 0 stones, so we hack around that
            if (numStones == 0) return new Node(NodeValue.Trivial, new Node[0]);

            // Cache
            Pair<int, NodeValue> key = new Pair<int, NodeValue>(numStones, val);
            Node node;
            if (cache.TryGetValue(key, out node)) return node;

            // The pair-of-nodes construction is based on a bijection between
            //     $\prod_{i<k} T_i \cup \{(\infty, 0)\}$
            // and
            //     $(T_{k-1} \cup \{(\infty, 0)\}) \times \prod_{i<k-1} T_i \cup \{(\infty, 0)\}$

            // val.Left represents the element of $T_{k-1} \cup \{(\infty, 0)\}$ (using null for the $(\infty, 0)$)
            // and val.Right represents $\prod_{i<k-1} T_i \cup \{(\infty, 0)\}$ by bijection with $T_{k-1} \cup \{(\infty, 0)\}$.
            // so val.Right.Left represents the element of $T_{k-2}$ and so on.
            // The element of $T_{k-i}$ corresponds to throwing $i$ stones.
            Node[] children = new Node[numStones];
            NodeValue current = val;
            for (int i = 0; i < numStones && current != null; i++)
            {
                children[i] = BuildDecisionTree(numStones - (i + 1), current.Left, cache);
                current = current.Right;
            }
            node = new Node(val, children);

            // Cache
            cache[key] = node;
            return node;
        }

        class Pair<TFirst, TSecond>
        {
            public readonly TFirst X;
            public readonly TSecond Y;

            public Pair(TFirst x, TSecond y)
            {
                this.X = x;
                this.Y = y;
            }

            public override string ToString()
            {
                return string.Format("({0}, {1})", X, Y);
            }

            public override bool Equals(object obj)
            {
                Pair<TFirst, TSecond> other = obj as Pair<TFirst, TSecond>;
                return other != null && object.Equals(other.X, this.X) && object.Equals(other.Y, this.Y);
            }

            public override int GetHashCode()
            {
                return X.GetHashCode() + 37 * Y.GetHashCode();
            }
        }

        class NodeValue : Pair<int, int>
        {
            public readonly NodeValue Left;
            public readonly NodeValue Right;

            public static NodeValue Trivial = new NodeValue(1, 1, null, null);

            private NodeValue(int x, int y, NodeValue left, NodeValue right) : base(x, y)
            {
                this.Left = left;
                this.Right = right;
            }

            public NodeValue Reverse()
            {
                return new NodeValue(Y, X, this, null);
            }

            public NodeValue Combine(NodeValue other)
            {
                return new NodeValue(other.X + Y, Math.Min(other.Y, X), this, other);
            }
        }

        class Node
        {
            public readonly NodeValue Value;
            private readonly Node[] _Children;

            public Node this[int n]
            {
                get { return _Children[n]; }
            }

            public int RemainingStones
            {
                get { return _Children.Length; }
            }

            public Node(NodeValue value, IEnumerable<Node> children)
            {
                this.Value = value;
                this._Children = children.ToArray();
            }
        }

        interface SpyIO
        {
            int Input();
            void Output(int i);
        }

        // TODO The inter-thread communication here can almost certainly be much better
        class TestSpyIO : SpyIO
        {
            private object _Lock = new object();
            private int? _Buffer;
            public TestSpyIO Partner;
            public readonly string Name;

            internal TestSpyIO(string name)
            {
                this.Name = name;
            }

            public int Input()
            {
                lock (_Lock)
                {
                    while (!_Buffer.HasValue) Monitor.Wait(_Lock);

                    int rv = _Buffer.Value;
                    _Buffer = null;
                    Monitor.PulseAll(_Lock);
                    return rv;
                }
            }

            public void Output(int i)
            {
                lock (Partner._Lock)
                {
                    while (Partner._Buffer.HasValue) Monitor.Wait(Partner._Lock);
                    Partner._Buffer = i;
                    Monitor.PulseAll(Partner._Lock);
                }
            }
        }

        class ConsoleIO : SpyIO
        {
            public int Input()
            {
                return Convert.ToInt32(Console.ReadLine());
            }

            public void Output(int i)
            {
                Console.WriteLine("{0}", i);
            }
        }

        class Spy
        {
            private readonly SpyIO _IO;
            private Node _Node;
            private bool _MyTurn;

            internal Spy(SpyIO io, Node root, bool isSpy1)
            {
                this._IO = io;
                this._Node = root;
                this._MyTurn = isSpy1;
            }

            internal void Run()
            {
                int myValue = _IO.Input() - 1;
                int hisValue = 1;

                bool myTurn = _MyTurn;
                Node n = _Node;
                while (n.RemainingStones > 0)
                {
                    if (myTurn)
                    {
                        if (myValue >= n.Value.X) throw new Exception("Internal error");
                        for (int i = 0; i < n.RemainingStones; i++)
                        {
                            // n[i] allows me to represent n[i].Y values: 0 to n[i].Y - 1
                            if (myValue < n[i].Value.Y)
                            {
                                _IO.Output(i + 1);
                                n = n[i];
                                break;
                            }
                            else myValue -= n[i].Value.Y;
                        }
                    }
                    else
                    {
                        int thrown = _IO.Input();
                        for (int i = 0; i < thrown - 1; i++)
                        {
                            hisValue += n[i].Value.Y;
                        }
                        n = n[thrown - 1];
                    }

                    myTurn = !myTurn;
                }

                _IO.Output(hisValue);
            }
        }
    }

    static class LinqExt
    {
        // I'm not sure why this isn't built into Linq.
        public static TElement MaxElement<TElement>(this IEnumerable<TElement> e, Func<TElement, int> f)
        {
            int bestValue = int.MinValue;
            TElement best = default(TElement);
            foreach (var elt in e)
            {
                int value = f(elt);
                if (value > bestValue)
                {
                    bestValue = value;
                    best = elt;
                }
            }
            return best;
        }
    }
}

Instructions for Linux users

You'll need mono-csc to compile (on Debian-based systems, it's in the mono-devel package) and mono to run (mono-runtime package). Then the incantations are

mono-csc -out:codegolf31673.exe codegolf31673.cs
mono codegolf31673.exe --test

etc.


Find an Unrelated Number Given 2 non-negative integers as input, output a non-negative integer that cannot be created through any mathematical operators on the 2 inputs.

For example, given inputs 2 and 3, 6, 0, 5, 1, 9, 8, 23, 2 are all invalid outputs.

Operations that must be taken into account are:

Addition        (a + b)
Subtraction     (a - b) and (b - a)
Multiplication  (a * b)
Division        (a / b) and (b / a)
Modulus         (a % b) and (b % a)
Exponentiation  (a ** b) and (b ** a)
Bitwise OR      (a | b)
Bitwise XOR     (a ^ b)
Bitwise AND     (a & b)
Concatenation   (a.toString() + b.toString()) and (b.toString() + a.toString())

In cases where an operation would lead to a non-integer (such as 2 / 3), always floor. So 2 / 3 = 0

Assume any invalid operations (such as dividing by 0) result in 0.

Input

2 non-negative integers.

Standard I/O methods are accepted

You can assume the input will always be within a handleable range for your given language, however remember standard loopholes still apply.

Output

Any non-negative integer that can not be created via any of the above operations on the 2 inputs.

Testcases

Input  -> Invalid outputs
2, 3   -> 0, 1, 2, 3, 5, 6, 8, 9, 23, 32
0, 0   -> 0
17, 46 -> 0, 2, 12, 17, 29, 63, 782, 1746, 4617, 18487710785295216663082172416, 398703807810572411498315063055075847178723756123452198369
6, 6   -> 0, 1, 6, 12, 36, 66, 46656
1, 1   -> 0, 1, 2, 11

Scoring

This is code-golf so fewest bytes wins!

Retina, 3 bytes

.
1

Try it online!

Takes inputs separated by space (or any single non-newline character)

Replaces all digits with 1, and joins the resulting numbers with another 1.

Proof of correctness

Courtesy of Martin Ender

This operation computes a result with one more digit than the number of digits of the two numbers together; the only operation that could produce a result so big is exponentiation.
The result is a repunit (a number whose digits are all 1).
"It is know [sic] [...] that a repunit in base 10 cannot [...] be a perfect power." This means that this result can't be produced by exponentiation either.


Is this quadrilateral tangential? Related: Is this quadrilateral cyclic?

Background

A tangential quadrilateral is a quadrilateral which has an incircle:

Examples include any square, rhombus, or a kite-like shape. Rectangles or parallelograms in general are not tangential.

Task

Given the four vertices of a quadrilateral (as Cartesian coordinates), determine if it is tangential.

Input & output

For input, it is allowed to use any format that unambiguously specifies the four vertices' coordinates (eight real or floating-point numbers). You can assume the following on the input:

The points specify a simple convex quadrilateral, i.e. all internal angles are strictly less than 180 degrees, and the edges meet only at the vertices.
The points are specified in counter-clockwise order (or the other way around if you want).

For output, you can use one of the following:

Truthy/falsy values as defined by your language of choice (swapping the two is allowed), or
Two consistent values for true/false respectively.

It is acceptable if your code produces wrong output due to floating-point inaccuracies.

Test cases

Tangential

(0, 0), (0, 1), (1, 1), (1, 0)  # unit square
(-2, 0), (0, 1), (2, 0), (0, -1)  # rhombus
(1, -2), (-2, -1), (-1, 2), (4, 2)  # kite
(0, 0), (50, 120), (50, 0), (32, -24)  # all four sides different

Not tangential

(0, 0), (0, 1), (2, 1), (2, 0)  # rectangle
(0, 0), (1, 1), (3, 1), (2, 0)  # parallelogram

Scoring & winning criterion

Standard code-golf rules apply. The shortest code in bytes wins.

MATL, 11 10 bytes

5:)d|2e!sd

Input is a vector of four complex numbers. Output is 0 (which is falsy) if tangential, or nonzero (which is truthy) if not tangential.

Try it online! Or verify all test cases.

Explanation

The code computes the difference between sums of lengths of opposite sides. This difference is zero if and only if the quatrilateral is tangential.

5:   % Range [1 2 3 4 5]
)    % Implicit input: complex vector of length 4. Index into it modularly.
     % This repeats the first vertex after the last
d    % Consecutive differences
|    % Absolute value, element-wise
2e   % Reshape as a 2-column matrix, in column-major order
!    % Transpose
s    % Sum of each column. Gives a vector of length 2
d    % Consecutive difference


Primes in Different Bases Challenge:
You are given a base 10 number.  For each base from 10 counting down to base 2:

Take the original input number as a base 10 string, and remove any
digits of the number which are invalid for the base.
Interpret the resulting number string in the that base. If this gives 1 or 0, terminate the whole process.
Output or print its largest prime factor, as decimal number.

The output can be an array of the largest prime factors.
Sample cases:
Input:
987654321

Output:
379721
10593529
1091
179
1493
293
19
7

Alternately:
[379721,10593529,1091,179,1493,293,19,7]

This prints the largest prime factors of \$987654321\$, \$87654321_9 = 42374116_{10}\$, \$7654321_{8} = 2054353_{10}\$, and so on until it reaches \$1_2\$, where it stops.

Pyth, 25 bytes

sfTm>1PiFdC,.u-N`tYKrT1zK

                       z   get input as a string
            .u      rT1    cumulative reduce over [10,9,...,2]
              -N`tY        remove one minus the number (10,9,...) from the input
          C,       K    K  pair each step along the chain with corresponding base
   m                       map over [["987654321", 10],...]:
       iFd                   apply the base-conversion (splat over i)
      P                      prime factorization, smallest to largest
    >1                       take [the last element], or [] if empty (1 or 0)
 fT                        remove the []s from 0s or 1s
s                          join the one-element arrays together

Try it here.


Create a Nonogram Puzzle A nonogram is a two-dimensional logic puzzle that looks something like this (screenshots from the game Pixelo, my favourite nonogram game):

The goal of the game is to figure out what image those numbers are encoding. The rules are simple: A number on a column or row means that somewhere in that column or row, that many boxes are filled in in a row. For example, the bottom row in the above image must have no boxes filled in, while the one above it must have all of its boxes filled. The third row from the bottom has 8 filled boxes, and they will all be in a row.

Two or more numbers for the same column or row mean that there are multiple "runs" of filled boxes, with at least one space between, with those lengths. The order is preserved. For example, there are three filled in boxes on the very right column of the above image, at least one space below them, and then one more filled in box.

Here's that same puzzle, almost completed:

(The Xs aren't important, they're just a hint the player leaves for themself to say "This square is definitely not filled in". Think flags in Minesweeper. They have no rules meaning.)

Hopefully you can see that, for example, the middle columns with hints that say "2 2" have two 2-length runs of filled in boxes.

Your mission, should you choose to accept it, is to write a program or function that will create a puzzle like this. You are given the size of the board as a single integer (5 <= n <= 50) on stdin or as an argument (there's no reason why a nonogram puzzle has to be square, but for this challenge it will be). After that, you will be given a series of 1s and 0s representing filled and unfilled squares in the image, respectively. The first n of them are the top row, then the next row, etc. You will return or print to stdout a board of 2*1 cells (because they look better, and it gives you room for 2-digit hints for a column), all of them empty, with hints corresponding to the input data.

Output Format

Sample

Input:

./nonogram <<< '5 0 1 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 1 0'
                                 OR
      n(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0])

Image:

Output:

           1
         2 1 2
       3 2 1 2 3
     +----------
    3|
  2 2|
1 1 1|
  2 2|
    3|

Input:

./nonogram <<< '15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1'

Image:

Output:

                   1                       1
                 1 1 3       3 5   5 3   3 1
                 7 2 3 2 4 2 3 210 2 3 0 4 215
               +------------------------------
              2|
              1|
              1|
              1|
              1|
            1 1|
        3 3 1 1|
        1 5 1 1|
          3 5 3|
          1 5 1|
          1 3 1|
      1 1 1 1 1|
1 1 1 1 1 1 1 1|
           11 3|
           11 3|

Clarifications

Your output need not be a solvable puzzle. Not all nonograms are solvable, but that isn't your concern. Just output the hints that correspond to the input, whether they make for a good puzzle or not.
A program that takes arguments on the command line is allowed. This is kind of stated above, but it's possible to get the wrong idea. That's what clarifications are for.
Printing a 0 for a row or column that has no filled in boxes is mandatory. I don't say this with words anywhere but it's in the sample data.

GolfScript, 128 characters
~](:k/.{{1,%{,}%.!,+}%}:^~{' ':s*}%.{,}%$-1=:9{s*\+9~)>'|'n}+%\zip^.{,~}%$0=){.~[s]*@+>{s\+-2>}%}+%zip{9)s*\n}%\[9s*'+''--'k*n]\

The input has to be provided on STDIN as space separated numbers.
You can test the example here.
Commented code:
# Parse the input into an 2D array of digits. The width is saved to variable k
~](:k/

# Apply the code block ^ to a copy of this array
.
{                # begin on code block
  {              # for each line
   1,%           #   split at 0s (1, => [0]) (leading, trailing, multiple 0s are
                 #   removed because of operator % instead of /)
   {,}%          #   calculate the length of each run of 1s
   .!,+          #   special case: only zeros, i.e. []
                 #   in this case the ! operator yiels 1, thus [0], else []
  }%             # end for
}:^              # end of code block
~                # apply

# Format row headers
{' ':s*}%        # join numbers with spaces
.{,}%$-1=:9      # calulate the length of the longest row header
                 # and save it to variable <9>
{                # for each row
  s*\+           #   prepend padding spaces
  9~)>           #   and cut at length <9> from the right
  '|'n           #   append '|' and newline
}+%              # end for

# Format column headers
\zip^            # transpose input array and apply the code block ^
                 # i.e. calculate length of runs
.{,~}%$0=)       # determine (negative) length of the longest column header
{                # for each column
  .~[s]*@+       #   prepend enough spaces
  >              #   and cut at common length (from right)
  {s\+-2>}%      #   format each number/empty to 2 chars width
}+%              # end for
zip              # transpose column header into output lines
{9)s*\n}%        # prepend spaces to each line and append newline

# Inject separator line
\[
9s*              # spaces
'+'              # a plus sign
'--'k*           # k (width) number of '--'
n                # newline
]\


Randomly select a character, plinko-style Let's see how good your language of choice is at selective randomness.
Given 4 characters, A, B, C, and D, or a string of 4 characters ABCD as input, output one of the characters with the following probabilities:

A should have a 1/8 (12.5%) chance to be chosen
B should have a 3/8 (37.5%) chance to be chosen
C should have a 2/8 (25%) chance to be chosen
D should have a 2/8 (25%) chance to be chosen

This is in-line with the following Plinko machine layout:
   ^
  ^ ^
 ^ ^ ^
A B \ /
     ^
    C D

Your answer must make a genuine attempt at respecting the probabilities described. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.
Scoring
This is code-golf so fewest bytes in each language wins!

Lean Mean Bean Machine, 55 43 42 bytes
-13 bytes thanks to Alex Varga
  O
  i
  ^
 ^ ^
\ ^ ^
 i / U
 ii
 ^
i U
U

Hope you guys don't mind me answering my own question after only 2 hours, but I highly doubt anybody else was planning on posting an answer in LMBM.
This literally just reflects the Plinko layout shown in the OP, flipped horizontally to cut down on unnecessary whitespace.


multiplication table in javascript This javascript code:
for(x=1;x<6;x++)for(y=1;y<6;y++)console.log((y==1?'\n':'')+x+'*'+y+'='+x*y);

prints the following:

1*1=1
1*2=2
1*3=3
1*4=4
1*5=5

2*1=2
2*2=4
2*3=6
2*4=8
2*5=10

3*1=3
3*2=6
3*3=9
3*4=12
3*5=15

4*1=4
4*2=8
4*3=12
4*4=16
4*5=20

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25

2 questions:

Is there a smaller (in bytes) way to do the same?
What is the smallest code that can do the same without using 2 for statements?

Single for loop, 80 75 72 68 bytes

I will try to make the code smaller too, but as far as single for loop goes:

for(i=5;i<30;)console.log(k=i/5|0,"*",l=i%5+1,"=",k*l,++i%5?"":"\n")

Try it in your console! (Although IE gives the best results)


A Kingdom Hearts VGM challenge I'm a huge video game music fan. One of my favorite OSTs is that from Kingdom Hearts, by Yoko Shimomura.

The challenge

Create a program or function that takes two arguments in any format: an abbreviated Kingdom Hearts game and a boss in that game. It must return the name of the song that plays for that boss. The program should handle any input case, but you can decide what case the output will be. You may assume the input is always valid. Here is a list of all the valid inputs:

Game   Boss                       Song

1      Ansem                      Guardando nel Buio
1      Riku                       Forze de Male
1      Sephiroth                  One Winged Angel
1      Kurt Zisa                  The Deep End
1      Unknown                    Disappeared
2      Organization XIII          The 13th Struggle, Dilemma, Reflection
2      Xemnas I                   A Fight to the Death
2      Xemnas II                  Darkness of the Unknown
2      Sephiroth                  One Winged Angel
2      Lingering Sentiment        Rage Awakened
CoM    Organization XIII          The 13th Struggle
CoM    Marluxia 1                 Graceful Assasin
CoM    Marluxia 2                 Scythe of Petals
CoM    Marluxia 3                 Lord of the Castle
CoM    Riku Replica               The Force in You
CoM    Ansem                      Revenge of Chaos
BBS    Master Xehanort            Black Powder
BBS    Terra vs Master Xehanort   Rage Awakened
BBS    Vanitas                    Enter the Darkness
BBS    Ventus vs Vanitas          The Key
BBS    Vanitas Remnant            Enter the Void
BBS    Terranort                  Dismiss
BBS    Mysterious Figure          Dark Impetus
Coded  Riku                       Riku
Coded  Pete                       Rowdy Rumble
Coded  Maleficent                 Vim and Vigor
Coded  Sora's Heartless           Guardando nel Buio
Coded  Roxas                      The Other Promise
Days   Xion                       Vector to the Heavens
Days   Riku                       Another Side
DDD    Anti Black Coat Nightmare  Dread of Night
DDD    Ansem I                    L'Eminenza Oscura I
DDD    Ansem II                   L'Eminenza Oscura II
DDD    Xemnas                     L'Oscurita dell'Ignoto
DDD    Young Xehanort             L'Impeto Oscuro
DDD    Armored Ventus Nightmare   Eye of Darkness
DDD    Julius                     The Encounter

Scoring

Your score is not your byte count. You do not need to implement the entire list, but you must implement at least 10 items. Your score is byte count / # of items implemented. For instance, say you write a 90-byte program that implements 25 items of the above table. Your score would be 90/25=3.6. Lowest score wins.

Bonus

-1 off your score of you implement an additional item, from Final Fantasy:

Game    Boss        Song

XV      Behemoth    Omnis Lacrima

AND make it so that any other requested bosses from XV return TBD.
-0.5 if your code also takes in the games 1.5 and 2.5, which take the same bosses as 1 and 2 but return the song name followed by (Orchestrated).
Another -0.5 if your program accepts bosses from CoM and Days when given 1.5 and accepts bosses from Coded and BBS when given 2.5. It must return the songs followed by (Orchestrated).

If you know of any other significant bosses I left out, let me know in the comments.

Also, I'm hoping I'm not the only person here who has memorized all of these songs...

Ruby 134 131/10=13.1
->g,b{"Rowdy Rumble|Dread of Night|Riku|One Winged Angel|Rage Awakened|Vim and Vigor|The Key|The 13th Struggle".split(?|)[b.ord%8]}

This is a lambda function, which takes arguments for the game and the boss. The argument for the game is actually ignored by the code, but the OP has clarified that the argument cannot be eliminated.
In fact it only uses the first letter of the boss's name. the ASCII code is taken modulo 8 (this gives the same answer for a given letter, regardless of case) and one of 8 song titles is returned. As two song titles appear twice, this covers a total of 10 elements:
Game   Boss                      Array  Song
                                 index
Coded  Pete                         0   Rowdy Rumble
DDD    Anti Black Coat Nightmare    1   Dread of Night
Coded  Riku                         2   Riku
1      Sephiroth                    3   One Winged Angel
2      Sephiroth                    3   One Winged Angel
2      Lingering Sentiment          4   Rage Awakened
BBS    Terra vs Master Xehanort     4   Rage Awakened
Coded  Maleficent                   5   Vim and Vigor
BBS    Ventus vs Vanitas            6   The Key
CoM    Organization XIII            7   The 13th Struggle

It was a lucky coincidence that the Ascii codes for L and T give the same result modulo 8, so both incidences of Rage Awakened could be covered.
Call the function as in this test program:
f=->g,b{"Rowdy Rumble|Dread of Night|Riku|One Winged Angel|Rage Awakened|Vim and Vigor|The Key|The 13th Struggle".split(?|)[b.ord%8]}
B=gets                  #get boss name from stdin
puts f.call("dummy",B)  #call function, and output return value to stdout


Number Chaining Predicate Problem:
Your task is to decide if in a sequence of numbers, every number contains at least one of the digits of the number that preceded it.
For example, the following should return truthy:
[1, 12, 203, 0, 30]
             ^   ^ Contains a 0
        ^ Contains a 2
    ^ Contains a 1

The following should return falsey:
[1, 32, 23, 34]
    ^ Doesn't contain a 1, therefore false

Your submission can be a function or full program.
Input:
Input can be any reasonable type of sequence. An array of numbers, an array of strings, a delimited string of numbers, etc.
Order matters however, so whatever structure you choose to accept as input obviously must have a definite ordering.
Input can be taken via the stdin or as an argument.
You can assume:

all numbers will be non-negative integers

input will always contain at least 2 numbers

input numbers will not start with a 0

Output:
Output will be a truthy or falsey value (as defined by your language), representing whether or not the above specification is met.
Truthy/falsey values don't need to be consistent between tests.
It can either be output to the stdout or returned.
Test Cases:
True cases:
[1, 1, 1, 11, 111, 11, 1]
[12, 23, 34, 45, 56]
[65, 54, 43, 32, 21]
[123, 29, 9, 59, 55, 52, 2017, 2]
[1234567890, 19, 95, 5012, 23]

False cases:
[1, 2, 3, 4, 5, 1, 11] (2 doesn't contain a 1)
[12, 23, 33, 45] (45 doesn't contain a 3)
[98, 87, 76, 11, 12, 23] (11 doesn't contain a 7 or 6)

This is code-golf, so the least number of bytes wins.

Python 2, 48 bytes

lambda x:reduce(lambda a,b:set(a)&set(b)and b,x)

Try it online!

Print a empty set for False and the last element for True


Most concise way to fold tree structures Background (F#)

Let there be trees:

type Tree<'T> = Node of 'T * Tree<'T> list

Now lets fold them nicely with a function called...

foldTree f:('a -> 'b -> 'c) -> g:('c -> 'b -> 'b) -> a:'b -> t:Tree<'a> -> 'c

...taking two functions f and g, an initial state a and of course a tree structure t. Similar to the well known function fold which operates on lists, this function should "merge" siblings with g and parents with their children with f resulting in an accumulated simple value.

Example (F#)

The tree...

//      1
//     / \
//    2   3
//   / \   \
//  4   5   6

let t = Node (1, [Node (2, [Node (4, []); Node (5, [])]); Node (3, [Node (6, [])])])

...passed to foldTree with the operators for addition and multiplication along with the initial state 1...

let result = foldTree (+) (*) 1 t
        // = (1 + ((2 + ((4 + a) * ((5 + a) * a))) * ((3 + ((6 + a) * a)) * a)))
        // = (1 + ((2 + ((4 + 1) * ((5 + 1) * 1))) * ((3 + ((6 + 1) * 1)) * 1)))

...should return the value 321 to result.

The Challenge

In any programming language, define the function foldTree in the most concise way you can come up with. Fewest number of characters wins.

Haskell, 37 35:

data T a=a:*[T a]

(f%g)z(x:*t)=x`f`foldr(g.(f%g)z)z t

not counting the type definition. With it, 54 52 (shortened by using infix operator, similarly to the answer by proud haskeller, but in a different way).

Ungolfed:

data Tree a = Node a [Tree a]

foldTree :: (a -> b -> c) -> (c -> b -> b) -> b -> Tree a -> c
foldTree f g z (Node x t) = f x $ foldr (g . foldTree f g z) z t
                       -- = f x . foldr g z . map (foldTree f g z) $ t

--      1
--     / \
--    2   3
--   / \   \
--  4   5   6

t = Node 1 [Node 2 [Node 4 [], Node 5 []],
            Node 3 [Node 6 []]]

result = foldTree (+) (*) 1 t   -- ((+)%(*)) 1 t        {-
       = 1 + product [2 + product[ 4 + product[], 5 + product[]],
                      3 + product[ 6 + product[]]]
       = 1 + product [2 + 5*6, 3 + 7]
       = 321                                            -}

   -- product [a,b,c,...,n] = foldr (*) 1 [a,b,c,...,n]
   --     = a * (b * (c * ... (n * 1) ... ))

This is the redtree ("reduce tree") function from John Hughes paper, "Why Functional Programming Matters", where it is presented in a more verbose formulation.


Decode the Dreaded Alphabet Cypher™ This challenge is inspired by one of my other challenges: Pointlessly make your way down the alphabet

That challenge asked you to take a string of text, and for each letter produce a sequence of letters moving down the alphabet to 'a'.

For this challenge I'd like to decode the output of that challenge (minus the line breaks), to find a human-readable string from a much longer human readable string.

Here is some text which has been encoded using the Dreaded Alphabet Cypher™

hgfedcbaedcbalkjihgfedcbalkjihgfedcbaonmlkjihgfedcba wvutsrqponmlkjihgfedcbaonmlkjihgfedcbarqponmlkjihgfedcbalkjihgfedcbadcba

It consists of descending alphabetical sequences, ending in an 'a'. The first character in each of these sequences is a letter in the decoded text. (A space is still a space).

The challenge

Write code to convert a Dreaded Alphabet Cypher™ encoded string into a decoded, human-readable string.
No need to validate if it is a Dreaded Alphabet Cypher™ string, I'm not interested in how it handles invalid input.
Use any language you please.
Please include a link to an online iterpreter.
The input will only consist of lower-case letters and spaces. No upper cases, punctuation etc.
Code golf, try to write short code, standard loopholes etc.

Test Cases

Input:

hgfedcbaedcbalkjihgfedcbalkjihgfedcbaonmlkjihgfedcba wvutsrqponmlkjihgfedcbaonmlkjihgfedcbarqponmlkjihgfedcbalkjihgfedcbadcba

Output:

hello world

Input:

abacbadcbaedcbafedcbagfedcbahgfedcbaihgfedcbajihgfedcbakjihgfedcbalkjihgfedcbamlkjihgfedcbanmlkjihgfedcbaonmlkjihgfedcbaponmlkjihgfedcbaqponmlkjihgfedcbarqponmlkjihgfedcbasrqponmlkjihgfedcbatsrqponmlkjihgfedcbautsrqponmlkjihgfedcbavutsrqponmlkjihgfedcbawvutsrqponmlkjihgfedcbaxwvutsrqponmlkjihgfedcbayxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba

Output:

abcdefghijklmnopqrstuvwxyz

(beware the multiple a's)

Input:

aarqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcba a aarqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcbasrqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcba hgfedcbaasrqponmlkjihgfedcba anmlkjihgfedcba aarqponmlkjihgfedcbadcbavutsrqponmlkjihgfedcbaarqponmlkjihgfedcbakjihgfedcba

Output:

aaron a aaronson has an aardvark

Input:

hgfedcbaaponmlkjihgfedcbaponmlkjihgfedcbayxwvutsrqponmlkjihgfedcba gfedcbaonmlkjihgfedcbalkjihgfedcbafedcbaihgfedcbanmlkjihgfedcbagfedcba

Output (is a secret, shh)

JavaScript (ES9),  37 33  26 bytes
Returns an array of characters.
Either a negative look-behind:

s=>s.match(/(?<![b-z])./g)

Try it online!
Or a positive look-behind:
s=>s.match(/(?<=a| |^)./g)

Try it online!

25 bytes
If the input is guaranteed not to contain leading or double spaces (or we're allowed to remove and collapse them respectively), the positive look-behind can be made 1 byte shorter:

s=>s.match(/(?<=a|\b)./g)

Try it online!


Turn this array into a matrix Take a non-nested array as input. Turn it into a matrix by using the following method:

Let's say my array is [1, 2, 3, 4, 5]

First, I repeat that array 5 times: (the length)

[[1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5]]

Then, I read it along the diagonals:

[[1],
 [2, 1],
 [3, 2, 1],
 [4, 3, 2, 1],
 [5, 4, 3, 2, 1],
 [5, 4, 3, 2],
 [5, 4, 3],
 [5, 4],
 [5]]

I flatten this array and split it into pieces of five (the length):

[[1, 2, 1, 3, 2],
 [1, 4, 3, 2, 1],
 [5, 4, 3, 2, 1],
 [5, 4, 3, 2, 5],
 [4, 3, 5, 4, 5]]

This is code golf. Fewest bytes wins.

Jelly, 11 bytes

WẋLŒDUṙLFsL

Try it online!

Explanation

               Input: array z
WẋL            length(z) copies of z
   ŒD          Diagonals (starting with main diagonal)
     U         Reverse each
      ṙL       Rotate left length(z) places
               (now the top-left diagonal is in front)
        F      Flatten
         sL    Split into chunks of size length(z)


Tips for golfing in Erlang Does anybody have tips for golfing in Erlang? I'm looking for specific things that can be applied to Erlang, not any language. I know we already have tips for Elixir, but that is different.

As usual, please post separate tips in separate answers.

Use the ending conditions

Suppose you have a function reversing a list:

r([H|T])->[T]++r(H);r([])->[].

Since this is the only condition left, this can be golfed into:

r([H|T])->r(T)++[H];r(_)->[].

Or, since this is an identity function:

r([H|T])->r(T)++[H];r(I)->I.

You can also abuse the wild-cards in if statements. E.g.

if A<B->A;true->B end.

This can be golfed into:

if A<B->A;_->B end.


What's this constructed number's starter? A number of programming languages construct large integers through 'concatenating' the digit to the end of the existing number. For example, Labyrinth, or Adapt. By concatenating the digit to the end, I mean that, if the existing number is \$45\$, and the digit is \$7\$, the result number is \$457\:(45 \times 10 + 7)\$.

A constructed number is a number that can be built this way through the use of the multiples of single digit numbers: \$1, 2, 3, 4, 5, 6, 7, 8, 9\$ A.K.A an element in one of these 9 sequences:

$$1, 12, 123, 1234, 12345, \: \dots$$
$$2, 24, 246, 2468, 24690, \: \dots$$
$$3, 36, 369, 3702, 37035, \: \dots$$
$$4, 48, 492, 4936, 49380, \: \dots$$
$$5, 60, 615, 6170, 61725, \: \dots$$
$$6, 72, 738, 7404, 74070, \: \dots$$
$$7, 84, 861, 8638, 86415, \: \dots$$
$$8, 96, 984, 9872, 98760, \: \dots$$
$$9, 108, 1107, 11106, 111105, \: \dots$$

To provide an example of how the sequences are constructed, here's how the sequence for \$a = 3\$ in constructed:

$$\begin{align}
u_1 = && a = && 3 & = 3\\
u_2 = && 10 \times u_1 + 2 \times a = && 30 + 6 & = 36 \\
u_3 = && 10 \times u_2 + 3 \times a = && 360 + 9 & = 369 \\
u_4 = && 10 \times u_3 + 4 \times a = && 3690 + 12 & = 3702 \\
u_5 = && 10 \times u_4 + 5 \times a = && 37020 + 15 & = 37035 \\
u_6 = && 10 \times u_5 + 6 \times a = && 370350 + 18 & = 370368 \\
\end{align}$$
$$\vdots$$
$$\begin{align}
u_{33} = && 10 \times u_{32} + 33 \times a = && 37\dots260 + 99 & = 37\dots359 \\
u_{34} = && 10 \times u_{33} + 34 \times a = && 37\dots359 + 102 & = 37\dots3692
\end{align}$$
$$\vdots$$

\$u_{33}\$ and \$u_{34}\$ included to demonstrate when \$n \times a \ge 100\$. A lot of digits dotted out for space.

It may still not be clear how these sequences are constructed, so here are two different ways to understand them:

Each sequence starts from the single digit. The next term is found by taking the next multiple of that digit, multiplying the previous term by \$10\$ and adding the multiple. In sequence terms:

$$u_n = 10 \times u_{n-1} + n \times a,  \: \: u_1 = a$$

where \$a\$ is a single digit (\$1\$ through \$9\$)

Each of the \$9\$ elements at any point in the sequence (take \$n = 3\$ for instance) are the multiples of \$123\dots\$ from \$1\$ to \$9\$, where \$123\dots\$ is constructed by \$u_{n+1} = 10 \times u_n + n\$ \$(1, 12, 123, \dots, 123456789, 1234567900, 12345679011, \dots)\$

So the first values are \$1 \times 1, 2, 3, \dots, 8, 9\$, the second are \$12 \times 1, 2, 3, \dots, 8, 9\$, the third \$123 \times 1, 2, 3, \dots, 8, 9\$, etc.

Your task is to take a constructed number as input and to output the initial digit used to construct it. You can assume the input will always be a constructed number, and will be greater than \$0\$. It may be a single digit, which maps back to itself.

You may take input in any reasonable manner, including as a list of digits, as a string etc. It is acceptable (though not recommended) to take input in unary, or any other base of your choosing.

This is a code-golf so the shortest code wins!

Test cases

       u_n        => a
 37035            => 3
 6172839506165    => 5
 5                => 5
 246913580244     => 2
 987654312        => 8
 61728395061720   => 5
 1111104          => 9
 11111103         => 9
 111111102        => 9
 2469134          => 2
 98760            => 8
 8641975308641962 => 7

or as two lists:

[37035, 6172839506165, 5, 246913580244, 987654312, 61728395061720, 1111104, 11111103, 111111102, 2469134, 98760, 8641975308641962]
[3, 5, 5, 2, 8, 5, 9, 9, 9, 2, 8, 7]

When I posted this challenge, I didn't realise it could be simplified so much by the method used in Grimmy's answer, and so therefore would be very interested in answers that take a more mathematical approach to solving this, rather than a 'digit' trick (Obviously all valid answers are equally valid, just what I'd be interested in seeing).

05AB1E, 7 5 4 bytes

>9*н

Try it online!

>            # input + 1
 9*          # * 9
   н         # take the first digit

The \$(n-1)^{th}\$ term of the sequence starting with \$a\$ is \$\sum _{i=1}^{n-1} a \times i \times 10^{i-1} = a \times \frac{(10^n - 1) / 9 - n}{9}\$. Multiply that by \$9\$ and add \$a\times n\$, and you get \$a \times \frac{10^n - 1}{9}\$, aka the digit \$a\$ repeated \$n\$ times. Turns out adding \$9\$ instead of \$a\times n\$ works for \$n=1\$, and for bigger \$n\$ the linear difference is negligible next to the exponential growth.


Is this uniquely concatenable? In this challenge about prefix code, we learnt that prefix codes are uniquely concatenable.

That means, they can be joined together without separator, and without ambiguity.

For example, since [1,2,45] is a prefix code, I can join them together without separator as such: 1245245112145, and there will be no ambiguity.

However the converse is not always true.

For example, [3,34] is not a prefix code. However, I can do the same: 3333434334333, and there will be no ambiguity. You would just need a smarter parser.

However, [1,11] is not uniquely concatenable, because 1111 can be interpreted in 5 ways.

Goal

Your task is to write a program/function that takes a list of strings (ASCII) as input, and determine if they are uniquely concatenable.

Details

Duplicate counts as false.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

True:

[12,21,112]
[12,112,1112]
[3,4,35]
[2,3,352]

False:

[1,1]
[1,2,112]
[1,23,4,12,34]
[1,2,35,4,123,58,8]

05AB1E, 15 bytes
On the phone, so explanation will have to follow later. Code:
gF¹N>ã})€`€JDÚQ

Uses CP-1252 encoding. Try it online!.
Takes too much memory for the last test case, so that might not work...


Hello world with a twist Your goal: to write a piece of code that will result in the classic result of "Hello, world!" being printed to STDOUT or equivalent.

Rules: Code must be entirely in printing ASCII. All code must be functional - removal of any single counting character must change the result or cause the code to not function. All variables must be used after assignment. Character and String literals must be necessary to the output - that is, replacement of any character literal or any character within a string literal with another character must be capable of changing the result (and not via the effect of escape sequence - replacing character with backslash or equivalent)

(NOTE: Final rule was edited in)

Scoring: This is where it gets interesting. Highest score wins as determined by number of characters, as per typical code-bowling rules. But repeated use of characters will result in point deductions. Specifically...

Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not result in a deduction).
Repeated use of basic punctuation ([!?.-,":';]) - including the brackets - will result in a deduction of 2 points per repeat.
Repeated use of other ASCII characters {`~@#$%^&*_+=|\/><} - including the curly brackets - will result in a deduction of 4 points per repeat.
Repeated use of spaces, tabs, and newlines will result in a deduction of 1 point per repeat. That is, only the first use of a space, tab, or newline will count towards your total.

Note: comments do not count towards total, although the characters marking the start/end of a comment do. For instance, in C/C++, If you have /* This is a comment */, then it will count two slashes and two asterisks, but nothing between them.

Some examples (note: using Julia as sample language)...

print("Hello, world!");

Total visible characters: 22
Contains Space: +1
Repeated alphanumerics: -12 for llor
Repeated punctuation: -2 for "
Final score: 22+1-12-2 = 9

print("Hel",char(108),"o, wor",0x108,"d!"); # 0x108 makes a Uint8 that prints as ASCII

Total characters: 43 (does not count any characters after #, which is the comment character)
Contains Space: +1
Repeated alphanumerics: -18 for rr1008
Repeated punctuation: -24 for ()""""",,,,,
Final score: 43+1-24-18 = 2

xy=STDOUT
m="Hello, world!"
print(xy,m);

Total visible characters: 37
Contains Newline: +1
Contains Space: +1
Repeated alphanumerics: -18 for xyllor
Repeated punctuation: -4 for ",
Repeated other ASCII: -4 for =
Final score: 37+1+1-18-4-4 = 13

A couple of invalid pieces of code...

x=2;print("Hello,world!")

Problem: x is assigned, but not used.

print("Hello,"*" world!")

Problem: * is unnecessary, result will be the same without it.

k=1
if k>0
  print("Hello, world!")
else
  print("abcghjmquvxyzABCDEFGIJKLMNOPQRSTUVWXYZ_+*-&|")
end

Problem: The second print command will not run. Also, removing characters in quote in second print command will not change output.

x="Hello, world!";
print(x)

Problem: removal of newline will not change result or cause error (in Julia, semicolon is only necessary if multiple commands are on the same line, otherwise just suppresses return value).

print("Hellos\b, world!")

Problem: s character does not affect result, as it gets erased by \b. This is acceptable if done through code ("Hello",char(100),"\b, world!"), but cannot be done via string literals or character literals.

Convenient score-calculator - http://jsfiddle.net/4t7qG/2/ - thanks to Doorknob

Perl - 96
(Pretty good, given the theoretical max 97 score)
s{}[Hel0o, w3$=d!];y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(
    6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)+print

(Note that second line starts with an actual \t tab character)
The code is 98 characters long and contains every ascii char exactly once, plus an extra -.
98 - 2 = 96
There are no string literals here, but removal of any single character breaks the program.
Deobfuscation
There are 3 statements in this program (well, actually 2 but I abused + as some kind of statement separator)

s{}[Hel0o, w3$=d!]
This is a very stretched case of the sed operator. It is more commonly written as s/a/b/, or s:a:b:, but perl allows much more fantasy here: s(a)(b) s(a)^b^ s(a)[b], and even s qaqbq.
It replaces an empty string (inside {}) with Hel0o w360d! (inside []) ($= interpolates to 60 by default). Because of the lack of an ~= operator, it operates on $_.

y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)
This is also a very stretched case, but of a tr operator, which is also called y (y< >( )).
Let's look at the replacement table:
" # %&'*.124578:?@BCDEFGIJKLMNOQ    /-9
\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cA  k-u
I have moved some characters around so that existing string is not broken. The only actually working part here is /-9 -> k-u. It replaces 0 with l, 3 with o, and 6 with r.
Again because of lack of the ~= operator, it operates on $_
So now we have the complete phrase in the $_ variable.

print
Lack of arguments makes it print just the $_ variable.


Piano Chords on White Keys Backstory [which is not true]

A piano is set up like this:

However, on my piano, all of the black keys are broken!

I still want to be able to play some chords on my broken piano though.

In music, a chord is a group of notes that are played together. To allow for input of chords, I will first define what a semitone is.

What is a semitone?

A semitone is the smallest distance in Western music. If you look at the top part of the piano, you see that you can usually move from a black key to a white key, or vice versa; however, between B and C and E and F there is no black key.

What is a chord?

For the purposes of this challenge, we define a chord as a bunch of notes with a certain number of semitones between them. For example, let's take a took at a 4-3-3 chord starting on C (for music people, this is a V7 chord in F major). We start at C. We count up 4 semitones: C#, D, D#, E. The next note is E, and we count 3 semitones up after that: F, F#, G. The next note is G, and we count 3 semitones up after that: G#, A, Bb. So, we get C-E-G-Bb. Yay! But wait... Bb is a black key and those are broken... However, if we start from G, we get G-B-D-F! Yay!

Input

Input is given as a list of integers in any reasonable format. This represents the chord as described above.

Output

Output should be a list of notes on which I can start to only need to use white keys. This can also just be a string of all of the up to 7 notes because all of the keynames will be one character. You must be able to handle having an empty output as well.

Test Cases

input -> output // comments
4 3 -> C F G // this is a major triad
3 4 -> D E A // this is a minor triad
4 3 3 -> G // this is the major-minor seventh chord
3 3 3 -> [empty output] // this is the diminished-diminished seventh chord. All of them use black keys
4 4 -> [empty output] // this is an augmented triad
3 3 -> B // this is a diminished triad
1 -> B E // this is just a minor second
11 -> C F // this is just a major seventh

Other specs

Standard Loopholes forbidden
You may assume that the input has at least one integer
You may assume that all of the integers are non-negative and less than 12 (because the piano repeats every 12 notes)
Output may be in any order

Winning Criteria

The shortest valid submission as of April 15th will be accepted.

MATL, 31 bytes
Thanks to Jonathan Allan for a correction.
'BAGFEDC'"GYs12X\110BQX@YSYsm?@

Try it online! Or verify all test cases.
Explanation
The pattern 2 2 1 2 2 2 1 specifies the intervals between consecutive white keys. The program uses a loop that applies all cyclic shifts to this basic pattern, in order to test each key as a potential lowest note of the input chord. For each shift, the cumulative sum of the pattern is obtained. For example, for B as potential lowest note, the pattern has been shifted to 1 2 2 1 2 2 2 and its cumulative sum is 1 3 5 6 8 10 12.
Now, to see if this can support a 4 3 3 chord we compute the cumulative sum of the chord intervals, which is 4 7 10; reduce it via 1-based modulo 12 (an interval of 14 would give 2); and check if those numbers are all members of the allowed values 1 3 5 6 8 10 12. That's not the case in this example. Had it been the case, we would output the letter B.
The correspondence between cyclic shifts and output letters is defined by the string 'BAGFEDC'. This indicates that 'B' (first character) corresponds to a cyclic shift by 1; 'A' (second character) corresponds to a cyclic shift by 2 etc.
'BAGFEDC'  % Push this string
"          % For each character from the string
  G        %   Push input array
  Ys       %   Cumulative sum
  12X\     %   1-based modulo 12, element-wise (1,12,13,14 respectively give 1,12,1,2)
  110BQ    %   Push 110, convert to binary, add 1 element-wise: gives [2 2 1 2 2 2 1]
  X@       %   Push current iteration index, starting at 1
  YS       %   Cyclic shift to the right by that amount
  Ys       %   Cumulative sum
  m        %   Ismember. Gives an array of true of false entries
  ?        %   If all true
    @      %     Push current character
           %   End (implicit)
           % End (implicit)
           % Display (implicit)


Witness My Challenge (Tetris Puzzle) Introduction

In the game   The Witness (possible spoilers ahead) there is a group of puzzles that involve drawing a Tetris piece with your line while making sure that the symbol for the Tetris piece your currently drawing stays contained within the shape you've drawn.

For the image above the drawing works because the L-shaped and upside down L-shaped Tetris pieces, occupying the positions (1,2)(2,2)(3,2)(3,3) and (1,1)(1,0)(2,0)(3,0) respectively, and the icons, located at (3,0) and (3,3), are contained within the white line.

Challenge

Your goal is to draw the solution line such that it contains all Tetris pieces as well as their respective symbols. The solution line may not contain anymore squares than that which is required (i.e. you must contain the sum of the number of squares making up each Tetris piece). Each solution will begin in the bottom left and end in the top right. Lastly, this is code-golf, so the shortest solution (in bytes) wins.

Representation

Each of these puzzles use a HxW grid of squares to construct your Tetris pieces and have some space for you to draw lines in between them. The representation is best understood by example. For the above image the representation would be

===========
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
===========

and the solution would be

===========
|*********|
|*X X X X |
|*******  |
| X X X*X |
|  *** *  |
| X*X*X*X |
|  * * ***|
| X*X*X X*|
|*** *****|
===========

where each square is represented by an X and the solution is drawn using a line of *s. The number of lines for each puzzle is 2*H+3 and the number of characters for each line is 2*W+3.

Input

The first n lines will give you the Tetris piece followed by the location of the corresponding symbol for that Tetris piece. The format is as follows:

(i1,j1)(i2,j2)...(ik,jk)->(p,q)

where (ik,jk) is the kth coordinate pair of the Tetris piece
(the left coordinate increases as you move down, the right coordinate increases as you move right) and (p,q) is the location of the corresponding symbol. The origin of each Tetris piece is the top left square (i.e. the top left square is (0,0)).

Example 1:

X
X
XX

would be

(0,0)(1,0)(2,0)(2,1)

Example 2:

XX
X
X

would be

(0,0)(1,0)(2,0)(0,1)

Example 3:

X  X
X  X

would be

(0,0)(1,0)(0,3)(1,3)

The next 2*H+3 lines will consist of the puzzle's grid.

Output

Output the puzzle grid with the solution line drawn in.

Examples

Example Input 1

(0,0)(0,1)->(2,1)
(0,0)(0,1)->(0,1)
(0,0)->(0,2)
=========
|       |
| X X X |
|       |
| X X X |
|       |
| X X X |
|       |
=========

Example Output 1

=========
|*******|
|*X X X |
|*******|
| X X X*|
|***** *|
|*X X*X*|
|*   ***|
=========

Example Input 2

(0,0)(0,1)(0,2)(1,2)(2,2)->(0,0)
(0,0)(1,0)(0,3)(1,3)->(2,1)
(0,0)(1,0)(2,0)->(1,3)
===========
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
===========

Example Output 2

===========
|      ***|
| X X X*X |
|      ***|
| X X X X*|
|        *|
| X X X X*|
|*** *****|
|*X*X*X X |
|* ***    |
===========

Example Input 3

(0,0)(1,0)(2,0)->(1,0)
(0,0)(1,0)(2,0)->(1,6)
(0,0)(0,1)(0,2)->(1,3)
=================
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
=================

Example Output 3

=================
|***         ***|
|*X*X X X X X*X |
|* *******   *  |
|*X X X X*X X*X |
|* *******   *  |
|*X*X X X X X*X |
|* ***********  |
=================

Clarifications

It is assumed that for any given input there is a solution.
If there are multiple solutions just print one.

Python, 992

Takes input from stdin and prints the solution.   Note that SE has turned my tab characters into four spaces - anything indented beyond one space should be a tab.

It shouldn't be too hard to beat this, but I thought I'd post it since no one else had posted a solution.

L=len
R=range
j=[(-1,0),(1,0),(0,-1),(0,1)]
P=lambda y,x,q:(y,x)==(0,w)and[q+[(y,x)]]or sum([P(y+e,x+d,q+[(y,x)])for e,d in j if not(y+e,x+d)in q and 0<=x+d<=w and 0<=y+e<=h],[])
def C(q,y,x,v):
 if(y,x)in v:return
 v.add((y,x))
 for e,d in j:
    Y,X=y+e,x+d;a,b=[(y+(e+s*d+1)/2,x+(d+s*e+1)/2)for s in[-1,1]]
    if 0<=X<w and 0<=Y<h and not(a in q and b in q and abs(q.index(a)-q.index(b))==1):C(q,Y,X,v)
def G(s,c):
 if not s:return not c
 for y,x in r:
    p=set((Y+y,X+x)for Y,X in s[0])
    if c&p==p and G(s[1:],c-p):return 1
def B(q):
 for y,x in r:
    c=set();C(q,y,x,c);s=[h for(w,h)in p if w in c]
    if s and not G(s,c):return 1
h,p,g=0,[],[]
try:
 while 1:
    s=raw_input()
    if'('in s:l,o=s.split('->');p.append(map(eval,[o,'('+l.replace(')','),')+')']))
    else:g.append(list(s))
except:h=L(g)/2-1;w=L(g[0])/2-1
r=[(x/w,x%w)for x in R(w*h)]
for s in P(h,0,[]):
 if not B(s):break
for(a,b),(c,d)in zip(s,s[1:]):g[1+2*a][1+2*b]=g[1+a+c][1+b+d]=g[1+2*c][1+2*d]='*'
print'\n'.join(''.join(r)for r in g)

Quick rundown of how it works:

P finds all possible paths.

C finds all the squares that are connected to a given square.

G determines whether or not a set of shapes fit exactly in a set of squares.

B determines whether or not a path is bad by checking each connected set of squares and checking if their shapes fit.

Examples

input:

(0,0)(0,1)->(2,1)
(0,0)(0,1)->(0,1)
(0,0)->(0,2)
=========
|       |
| X X X |
|       |
| X X X |
|       |
| X X X |
|       |
=========

output (all tetris pieces are grouped into the top-right):

=========
|***   *|
|*X*X X*|
|* *   *|
|*X*X X*|
|* * ***|
|*X*X*X |
|* ***  |
=========

input:

(0,0)(0,1)(0,2)(1,2)(2,2)->(0,0)
(0,0)(1,0)(0,3)(1,3)->(2,1)
(0,0)(1,0)(2,0)->(1,3)
===========
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
===========

output (this is the only one that's the same as the example solution):

===========
|      ***|
| X X X*X |
|      ***|
| X X X X*|
|        *|
| X X X X*|
|*** *****|
|*X*X*X X |
|* ***    |
===========

input:

(0,0)(1,0)(2,0)->(1,0)
(0,0)(1,0)(2,0)->(1,6)
(0,0)(0,1)(0,2)->(1,3)
=================
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
=================

output (rightmost 2 pieces are grouped together):

=================
|*** *** *******|
|*X*X*X*X*X X X |
|* * * * *******|
|*X*X*X*X X X X*|
|* * * * *******|
|*X*X*X*X*X X X |
|* *** ***      |
=================


Calculator that adds char values Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

Input
Hello World!

Output
1085

Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.
So I leave it as a bonus thing aswell.
The calculator should be run as written, so no need to modify before compiling or interpreting.

Bonus

Thanks to Synthetica, here is one more bonus,

  The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(

Have fun coding :)

Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

GolfScript, 4 characters

{+}*

Simply uses the fold operator (*) to add up all the characters.

If it has to work with the empty string, 9 chars:

{{+}*}0if

Thanks to @PeterTaylor for providing an alternative 6-char version that works with empty string:

0\{+}/


Counting Grains of Rice Consider these 10 images of various amounts of uncooked grains of white rice.
THESE ARE ONLY THUMBNAILS. Click an image to view it at full size.
A:
B:
C:
D:
E:
F:
G:
H:
I:
J:
Grain Counts: A: 3, B: 5, C: 12, D: 25, E: 50, F: 83, G: 120, H:150, I: 151, J: 200
Notice that...

The grains may touch each other but they never overlap. The layout of grains is never more than one grain high.
The images have different dimensions but the scale of the rice in all of them is consistent because the camera and background were stationary.
The grains never go out of bounds or touch the image boundaries.
The background is always the same consistent shade of yellowish-white.
Small and large grains are counted alike as one grain each.

These 5 points are guarantees for all images of this sort.
Challenge
Write a program that takes in such images and, as accurately as possible, counts the number of grains of rice.
Your program should take the filename of the image and print the number of grains it calculates. Your program must work for at least one of these image file formats: JPEG, Bitmap, PNG, GIF, TIFF (right now the images are all JPEGs).
You may use image processing and computer vision libraries.
You may not hardcode the outputs of the 10 example images. Your algorithm should be applicable to all similar rice-grain images. It should be able to run in less than 5 minutes on a decent modern computer if the image area is less than 2000*2000 pixels and there are fewer than 300 grains of rice.
Scoring
For each of the 10 images take the absolute value of the actual number of grains minus the number of grains your program predicts. Sum these absolute values to get your score. The lowest score wins. A score of 0 is perfect.
In case of ties the highest voted answer wins. I may test your program on additional images to verify its validity and accuracy.

Python, Score: 24 16
This solution, like Falko's one, is based on measuring the "foreground" area and dividing it by the average grain area.
In fact, what this program tries to detect is the background, not so much as the foreground.
Using the fact that rice grains never touch the image boundary, the program starts by flood-filling white at the top-left corner.
The flood-fill algorithm paints adjacent pixels if the difference between theirs and the current pixel's brightness is within a certain threshold, thus adjusting to gradual change in the background color.
At the end of this stage, the image might look something like this:

As you can see, it does a pretty good job at detecting the background, but it leaves out any areas that are "trapped" between the grains.
We handle these areas by estimating the background brightness at each pixel and painting all equal-or-brighter pixels.
This estimation works like so:
during the flood-fill stage, we calculate the average background brightness for each row and each column.
The estimated background brightness at each pixel is the average of the row and column brightness at that pixel.
This produces something like this:

EDIT:
Finally, the area of each continuous foreground (i.e. non-white) region is divided by the average, precalculated, grain area, giving us an estimate of the grain count in the said region. The sum of these quantities is the result.
Initially, we did the same thing for the entire foreground area as a whole, but this approach is, literally, more fine-grained.

from sys import argv; from PIL import Image

# Init
I = Image.open(argv[1]); W, H = I.size; A = W * H
D = [sum(c) for c in I.getdata()]
Bh = [0] * H; Ch = [0] * H
Bv = [0] * W; Cv = [0] * W

# Flood-fill
Background = 3 * 255 + 1; S = [0]
while S:
    i = S.pop(); c = D[i]
    if c != Background:
        D[i] = Background
        Bh[i / W] += c; Ch[i / W] += 1
        Bv[i % W] += c; Cv[i % W] += 1
        S += [(i + o) % A for o in [1, -1, W, -W] if abs(D[(i + o) % A] - c) < 10]

# Eliminate "trapped" areas
for i in xrange(H): Bh[i] /= float(max(Ch[i], 1))
for i in xrange(W): Bv[i] /= float(max(Cv[i], 1))
for i in xrange(A):
    a = (Bh[i / W] + Bv[i % W]) / 2
    if D[i] >= a: D[i] = Background

# Estimate grain count
Foreground = -1; avg_grain_area = 3038.38; grain_count = 0
for i in xrange(A):
    if Foreground < D[i] < Background:
        S = [i]; area = 0
        while S:
            j = S.pop() % A
            if Foreground < D[j] < Background:
                D[j] = Foreground; area += 1
                S += [j - 1, j + 1, j - W, j + W]
        grain_count += int(round(area / avg_grain_area))

# Output
print grain_count

Takes the input filename through the comand line.
Results
      Actual  Estimate  Abs. Error
A         3         3           0
B         5         5           0
C        12        12           0
D        25        25           0
E        50        48           2
F        83        83           0
G       120       116           4
H       150       145           5
I       151       156           5
J       200       200           0
                        ----------
                Total:         16


Inscriptio Labyrinthica In the burial place of King Silo of Asturias there is an inscription that reads SILO PRINCEPS FECIT (King Silo made this).

The first letter is found in the very middle, and from there one reads by going in any non-diagonal direction radiating outward.  The final letter is found on all four corners.  In this challenge, you'll generalize the process to make them.

Input

A string (or equivalent), and an integer.  You may make the following assumptions about the input:

The string will have an odd length.
The integer will be an odd number between 1 and one less than twice the length of the string.

Output

An inscriptio labyrinthica for the string, using the integer for the height or width (see models for height examples).  Output should be each letter with no spaces, line break as default to your system/language.

Test cases

Note that an input of 1 or (length * 2 - 1) will result in a horizontal or vertical palindrome.

 Input: FOO, 3    Input: BAR, 1    Input: BAR, 3    Input: BAR, 5

Output: OOO      Output: RABAR    Output: RAR       Output: R
        OFO                               ABA               A
        OOO                               RAR               B
                                                            A
                                                            R

 Input: ABCDE, 5   Input: ABCDE, 3   Input: *<>v^, 5

Output: EDCDE     Output: EDCBCDE           ^v>v^
        DCBCD             DCBABCD           v><>v
        CBABC             EDCBCDE           ><*<>
        DCBCD                               v><>v
        EDCDE                               ^v>v^

Scoring

This is code-golf so shortest answer in bytes wins.  Standard loopholes forbidden.

J, 27 bytes

([{~]+/&(|@i:)#@[-1+])-:@<:

Try it online!

An example will clarify the high-level approach.

Consider 'ABCDE' f 3

We notice that what we seek is simply the "cross addition" table of 1 0 1 and 3 2 1 0 1 2 3, which looks like this:

4 3 2 1 2 3 4
3 2 1 0 1 2 3
4 3 2 1 2 3 4

We then pull those indexes from the original string: [{~.

All the rest of the code is just boring arithmetic and the use of i: to construct the arguments 1 0 1 and 3 2 1 0 1 2 3.


Go and make it starry In this contest you have to write a program, that accepts a black and white pixel image, and tries to alter it, such that the white shape forms star domain, with as few changes as possible.
Allowed changes are turning white pixels into black ones and turning black pixels into white ones.
The output must again consist of the same image but this time with all the changes and with a/the center marked. The pixels that were changed from white to black must be displayed in blue, the ones that were changed from black to white must be displayed in yellow, and at least one center pixel must be displayed in red. (Exact colours are up to you.) The program must ouput the specified image as well as the total number of changes that were made.
Definitions
Star Domain
The set of white pixels of the image represent a star domain if (and only if) there is (at least) one center pixel. The center pixel is one of the white pixels that can be conneced by a straight line to all of the other white pixels such that the line only traverses white pixels. (The center pixel is therefore not necessarily unique.)
Straight line between two pixels
Given two pixel (start and end, both red in the illustration below), the straigth line between the two pixels consists of all the pixels, that touch the (mathematical, yellow in the illustration below) line that leads from the center of the first pixel to the center of the last pixel. A pixel is not touching the line if it only touches it by a corner, so for a pixel to belong to the pixel line the (mathematical, yellow) line has to cross the pixel in question with a nonzero length. (If it only touches the corner point this is considered as length zero). Consider the following examples:

Example
The first image should represent an example testcase 'input' and the two other images represent two valid possible outputs for the given example:

The yellow areas (formerly black) count to the 'white' domain as well, while the blue areas (formerly white) count to the 'black' part outside of the domain, and the red dot each time represents one possible center pixel.
Test Cases
The follwoing test cases are png's with each a size of 256 x 256 pixels.

Scoring
Please run your program with the following test cases and include the output (image / number of changes) in your answer. I will make a leaderboard for each test case. Your score will be the sum of each ranking in the leaderboard -the lower the score the better. Standard loopholes apply. It is not allowed to make the program recognize those test cases and run a special case for them. (It is not allowed to precompute and save the optimal center pixels for each of those test cases.) The program should work for any images.
Leaderboard
Name        | Score | 1     - rk | 2     - rk | 3     - rk | 4     - rk | 5     - rk | 5     - rk | Total Changes
------------+-------+------------+------------+------------+------------+------------+------------+--------------
Maltysen    |    11 | 28688 -  2 | 24208 -  2 | 24248 -  1 |  7103 -  2 | 11097 -  2 | 13019 -  2 | 108363
TheBestOne  |     7 | 0     -  1 | 13698 -  1 | 24269 -  2 |   103 -  1 |  5344 -  1 |  4456 -  1 |  47867

Java 8, 47,867 changes total.

Uses the average of the image as the center point. It then draws all possible rays to the center and gives it the best radius to color. It then colors all invalid points black.

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MakeItStarry {

    private static final int RGB_RED = Color.RED.getRGB();
    static int[][] originalImage;

    static final int WHITE = 0;
    static final int BLACK = 1;
    static final int RGB_WHITE = Color.WHITE.getRGB();
    static final int RGB_BLACK = Color.BLACK.getRGB();
    static final int RGB_BLUE = Color.BLUE.getRGB();
    static final int RGB_YELLOW = Color.YELLOW.getRGB();

    public static void main(String[] args) throws Exception{
        originalImage = convert(ImageIO.read(new File(args[0])));
        Point center = findCenter(originalImage);
        int[][] nextImage = starry(originalImage, center);
        BufferedImage result = difference(originalImage, nextImage);
        result.setRGB(center.x, center.y, RGB_RED);
        String fileType;
        String fileName;
        if (args[1].split("\\.").length > 1){
            fileType = args[1].split("\\.")[1];
            fileName = args[1];
        } else {
            fileType = "PNG";
            fileName = args[1] + ".PNG";
        }
        ImageIO.write(result, fileType, new File(fileName));
        System.out.println(cost);
    }

    static int cost;

    private static BufferedImage difference(int[][] image1, int[][] image2) {
        cost = 0;
        int height = image1[0].length;
        int width = image1.length;
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++){
            for (int y = 0; y < width; y++){
                if (image1[x][y] == image2[x][y]){
                    if (image1[x][y] == WHITE){
                        result.setRGB(x, y, RGB_WHITE);
                    } else {
                        result.setRGB(x, y, RGB_BLACK);
                    }
                } else {
                    cost++;
                    if (image1[x][y] == WHITE){
                        result.setRGB(x, y, RGB_BLUE);
                    } else {
                        result.setRGB(x, y, RGB_YELLOW);
                    }
                }
            }
        }
        return result;
    }

    private static int[][] starry(int[][] image, Point center) {
        int width = image.length;
        int height = image[0].length;
        int[][] result = new int[width][height];
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                result[x][y] = BLACK;
            }
        }
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++) {
                Point endPoint = new Point(x, y, image);
                List<Point> line = Point.lineTo(center, endPoint, image);
                List<Point> newLine = starRay(line);
                newLine.stream().filter(point -> result[point.x][point.y] == BLACK).forEach(point -> {
                    result[point.x][point.y] = point.color;
                });
            }
        }
        int distance = 0;
        while (distance < height || distance < width){//This removes pixels that can't see the center.
            for (int x = Math.max(center.x - distance,0); x < center.x + distance && x < width; x++){
                for (int y = Math.max(center.y - distance, 0); y < center.y + distance && y < height; y++){
                    Point point = new Point(x, y, result);
                    if (Point.distance(center, point) != distance){
                        continue;
                    }
                    if (point.color == WHITE){
                        List<Point> line = Point.lineTo(center, point, result);
                        for (Point p : line){
                            if (p.color == BLACK){
                                point.color = BLACK;
                                break;
                            }
                        }
                        result[point.x][point.y] = point.color;
                    }
                }
            }//All white pixels can technically see the center but only if looking from the edge.
            distance++;
        }
        return result;
    }

    private static List<Point> starRay(List<Point> line) {
        int numOfWhites = 0;
        int farthestGoodPoint = 0;
        int blackCost = 0;
        int whiteCost = 0;
        for (int i = 0; i < line.size(); i++){
            if (line.get(i).color == WHITE){
                numOfWhites++;
                whiteCost++;
                if (numOfWhites + whiteCost > blackCost){
                    blackCost = 0;
                    whiteCost = 0;
                    farthestGoodPoint = i;
                }
            } else {
                blackCost++;
                numOfWhites = 0;
            }
        }
        List<Point> result = new ArrayList<>();
        for (int i = 0; i < line.size(); i++){
            Point p = line.get(i);
            if (i <= farthestGoodPoint){
                result.add(new Point(p.x, p.y, WHITE));
            } else {
                result.add(new Point(p.x, p.y, BLACK));
            }
        }
        return result;
    }

    private static Point findCenter(int[][] image) {
        double totalx = 0;
        double totaly = 0;
        int counter = 0;
        int width = image.length;
        int height = image[0].length;
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                if (image[x][y] == WHITE){
                    totalx += x;
                    totaly += y;
                    counter++;
                }
            }
        }
        return new Point((int)(totalx/counter), (int)(totaly/counter), image);
    }

    private static int[][] convert(BufferedImage image) {
        int width = image.getWidth();
        int height  = image.getHeight();
        int[][] result = new int[width][height];
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                if (image.getRGB(x, y) == RGB_WHITE){
                    result[x][y] = WHITE;
                } else {
                    result[x][y] = BLACK;
                }
            }
        }
        return result;
    }

    private static class Point {

        public int color;
        public int y;
        public int x;

        public Point(int x, int y, int[][] image) {
            this.x = x;
            this.y = y;
            this.color = image[x][y];
        }

        public Point(int x, int y, int color) {
            this.x = x;
            this.y = y;
            this.color = color;
        }

        public static List<Point> lineTo(Point point1, Point point2, int[][] image) {
            List<Point> result = new ArrayList<>();
            boolean reversed = false;
            if (point1.x > point2.x){
                Point buffer = point1;
                point1 = point2;
                point2 = buffer;
                reversed = !reversed;
            }
            int rise = point1.y - point2.y;
            int run = point1.x - point2.x;
            if (run == 0){
                if (point1.y > point2.y){
                    Point buffer = point1;
                    point1 = point2;
                    point2 = buffer;
                    reversed = !reversed;
                }
                int x = point1.x;
                for (int y = point1.y; y <= point2.y; y++){
                    result.add(new Point(x, y, image));
                }
                if (reversed){
                    return reversed(result);
                }
                return result;
            }
            if (rise == 0){
                if (point1.x > point2.x){
                    Point buffer = point1;
                    point1 = point2;
                    point2 = buffer;
                    reversed = !reversed;
                }
                int y = point1.y;
                for (int x = point1.x; x <= point2.x; x++){
                    result.add(new Point(x, y, image));
                }
                if (reversed){
                    return reversed(result);
                }
                return result;
            }
            int gcd = gcd(rise, run);
            rise /= gcd;
            run /= gcd;
            double slope = (rise + 0.0) / run;
            if (Math.abs(rise) >= Math.abs(run)){
                if (point1.y > point2.y){
                    Point buffer = point1;
                    point1 = point2;
                    point2 = buffer;
                    reversed = !reversed;
                }
                double x = point1.x;
                for (double y = point1.y + .5; y <= point2.y; y++){
                    int px = (int) Math.round(x);
                    if (Math.abs(Math.abs(px - x) - .5) < Math.abs(1.0 / (rise * 4))){
                        x += 1/slope;
                        continue;
                    }
                    result.add(new Point(px, (int) Math.round(y - .5), image));
                    result.add(new Point(px, (int) Math.round(y + .5), image));
                    x += 1/slope;
                }
                if (reversed){
                    return reversed(result);
                }
                return result;
            } else {
                if (point1.x > point2.x){
                    Point buffer = point1;
                    point1 = point2;
                    point2 = buffer;
                    reversed = !reversed;
                }
                double y = point1.y;
                for (double x = point1.x + .5; x <= point2.x; x++){
                    int py = (int) Math.round(y);
                    if (Math.abs(Math.abs(py - y) - .5) < Math.abs(1.0 / (run * 4))) {
                        y += slope;
                        continue;
                    }
                    result.add(new Point((int) Math.round(x - .5), py, image));
                    result.add(new Point((int) Math.round(x + .5), py, image));
                    y += slope;
                }
                if (reversed){
                    return reversed(result);
                }
                return result;
            }
        }

        private static List<Point> reversed(List<Point> points) {
            List<Point> result = new ArrayList<>();
            for (int i = points.size() - 1; i >= 0; i--){
                result.add(points.get(i));
            }
            return result;
        }

        private static int gcd(int num1, int num2) {
            if (num1 < 0 && num2 < 0){
                return -gcd(-num1, -num2);
            }
            if (num1 < 0){
                return gcd(-num1, num2);
            }
            if (num2 < 0){
                return gcd(num1, -num2);
            }
            if (num2 > num1){
                return gcd(num2, num1);
            }
            if (num2 == 0){
                return num1;
            }
            return gcd(num2, num1 % num2);
        }

        @Override
        public String toString(){
            return x + " " + y;
        }

        public static int distance(Point point1, Point point2) {
            return Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y);
        }
    }
}

Results

Image 1 - 0 changes, Image 2 - 13,698 changes

Image 3 - 24,269 changes, Image 4 - 103 changes

Image 5 - 5,344 changes, Image 6 - 4,456 changes

Without invalid pixels removed, 42,782 changes total

Green pixels are the first layer of invalid pixels.

Image 1 - 0 changes, Image 2- 9,889 changes

Image 3 - 24,268 changes, Image 4 - 103 changes

Image 5 - 4,471 changes, Image 6- 4,050 changes

All white pixels in all the pictures can have a line drawn to them from the center pixel if the line does not have to originate/end at the centers but rather anywhere on the pixel.

args[0] contains input file name.

args[1] contains output file name.

Prints to stdout number of changes.