text:
Calculate a probability exactly and quickly
[This is a partner question to Calculate a probability exactly ]
This task is about writing code to compute a probability exactly and quickly. The output should be a precise probability written as a fraction in its most reduced form. That is it should never output 4/8 but rather 1/2.
For some positive integer n, consider a uniformly random string of 1s and -1s of length n and call it A. Now concatenate to A its first value. That is A[1] = A[n+1] if indexing from 1.  A now has length n+1. Now also consider a second random string of length n whose first n values are -1, 0, or 1 with probability 1/4,1/2, 1/4 each and call it B.
Now consider the inner product of A[1,...,n] and B and the inner product of A[2,...,n+1] and B.
For example, consider n=3. Possible values for A and B could be A = [-1,1,1,-1] and B=[0,1,-1]. In this case the two inner products are 0 and 2.
Your code must output the probability that both inner products are zero.
Copying the table produced by Martin Büttner we have the following sample results.
n   P(n)
1   1/2
2   3/8
3   7/32
4   89/512
5   269/2048
6   903/8192
7   3035/32768
8   169801/2097152

Languages and libraries
You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.
The task
Your code must start with n=1 and give the correct output for each increasing n on a separate line. It should stop after 10 seconds.
The score
The score is simply the highest n reached before your code stops after 10 seconds when run on my computer.  If there is a tie, the winner be the one to get to the highest score quickest.
Table of entries

n = 64 in Python. Version 1 by Mitch Schwartz
n = 106 in Python.  Version June 11 2015 by  Mitch Schwartz
n = 151 in C++. Port of Mitch Schwartz's answer by kirbyfan64sos
n = 165 in Python. Version June 11 2015 the "pruning" version by Mitch Schwartz with  N_MAX = 165.
n = 945 in Python by Min_25 using an exact formula. Amazing!
n = 1228 in Python by Mitch Schwartz using another exact formula (based on Min_25's previous answer).
n = 2761 in Python by Mitch Schwartz using a faster implementation of the same exact formula.
n = 3250 in Python using Pypy by Mitch Schwartz using the same implementation. This score needs pypy MitchSchwartz-faster.py |tail to avoid console scrolling overhead.

I wonder if a numpy solution would run faster than Boost C++?

@qwr I think numpy, numba and cython would all be interesting as they keep within the Python family.

I'd love to see more of these fastest-code problems

@qwr it's my favourite sort of question... Thank you! The challenge is to find one that doesn't just involve coding exactly the same algorithm in the lowest level language you can find.

Are you writing the results to the console or to a file? Using pypy and writing to a file seems the fastest for me. The console slows the process considerably.

@gnibbler Thank you! I updated the fastest score following your suggestion.  I did find that pypy slowed down the dynamic programming approaches however.

Python
A closed-form formula of p(n) is

An exponential generating function of p(n) is

where I_0(x) is the modified Bessel function of the first kind.
Edit on 2015-06-11:
- updated the Python code.
Edit on 2015-06-13:
- added a proof of the above formula.
- fixed the time_limit.
- added a PARI/GP code.
Python
def solve():
  # straightforward implementation

  from time import time
  from itertools import count

  def binom(n, r):
    return facts[n] // (facts[r] * facts[n - r])

  def p(N):
    ans = 0
    for i in range(1 + N // 2):
      t = binom(2 * (N - 2 * i), N - 2 * i)
      t *= binom(N, 2 * i)
      t *= binom(4 * i, 2 * i)
      ans += t
    e = (ans & -ans).bit_length() - 1
    numer = ans >> e
    denom = 1 << (3 * N - 1 - e)
    return numer, denom

  facts = [1]
  time_limit = 10.0 + time()

  for i in count(1):
    facts.append(facts[-1] * (2 * i - 1))
    facts.append(facts[-1] * (2 * i))

    n, d = p(i)

    if time() > time_limit:
      break

    print("%d %d/%d" % (i, n, d))

solve()

PARI/GP
p(n) = polcoeff( (exp(x/2) + 1) * besseli(0, x/4) ^ 2, n) * n!;

Proof:
This problem is similar to a 2-dimensional (restricted) random walk problem.
If A[i] = A[i+1], we can move from (x, y) to (x+1, y+1) [1 way], (x, y) [2 ways] or (x-1, y-1) [1 way].
If A[i] != A[i+1], we can move from (x, y) to (x-1, y+1) [1 way], (x, y) [2 ways] or (x+1, y-1) [1 way].
Let a(n, m) = [x^m]((x+1)^n + (x-1)^n), b(n) = [x^n](1+x)^{2n} and c(n) be the number of ways to move from (0, 0) to (0, 0) with n steps.
Then, c(n) = \sum_{i=0}^n a(n, i) * b(i) * b(n-i).
Since p(n) = c(n) / 8^n, we can get the above closed-form formula.

This is .. well.. amazing! How on earth did you compute the exact formula?

Wow! Closed form is always neat!

I bet if you port this answer to C++, you can get a higher value of n.

@Lembik : I added a (rough) proof.

@qwr : Thanks. I think so, too !

@mbomb007 : Yes. But, it is an implementation task rather than a computing task. So, I would not code it in C++.

Thank you for the proof! I look forward to fully understanding it.

I think I understand your proof now except I don't see where the "wrap-around" part is dealt with. Would you mind explaining that please? Also, do you think the same method can get a closed form solution for j =2 at http://codegolf.stackexchange.com/questions/51624/probabilities-how-high-can-you-go ? I just added a bounty there as well in case it's of interest.

@Lembik Sorry, what does [the "wrap-around" part] mean ? About j >= 2, I think it is difficult to obtain a simple formula. For j = 1, a random walk is linearly independent, but not for j >= 2.

I just worked out how you solve the "wrap around" part. What I meant by that was that A[1] = A[n+1] .  I see your point about the lack of independence as well for j >= 2. (Do you see my chat posts when I add  @Min_25?)

@Lembik Thank you. Yes, I can see them.

Python
Note: Congratulations to Min_25 for finding a closed-form solution!
Thanks for the interesting problem! It can be solved using DP, although I am not currently feeling very motivated to optimise for speed to get a higher score. It could be nice for golf.
The code reached N=39 within 10 seconds on this old laptop running Python 2.7.5.
from time import*
from fractions import*
from collections import*

X={(1,0,0,0):1,(-1,0,0,0):1}

T=time()
N=0

while 1:
    Y=defaultdict(lambda:0)
    n=d=0
    for a,b,s,t in X:
        c=X[(a,b,s,t)]
        for A in ( (1,-1) if N else [a] ):
            for B in 1,0,0,-1:
                n+=c*(s+A*B==0==t+A*b+a*B)
                d+=c
                Y[(a,B,s+A*B,t+A*b)]+=c
    if time()>T+10: break
    N+=1
    print N,Fraction(n,d)
    X=Y

For tuple (a,b,s,t): a is the first element of A, b is the last element of B, s is the inner product of A[:-1] and B, and t is the inner product of A[1:-1] and B[:-1], using Python slice notation. My code does not store the arrays A or B anywhere, so I use those letters to refer to the next elements to be added to A and B, respectively. This variable naming choice makes the explanation a little awkward, but allows for a nice-looking A*b+a*B in the code itself. Note that the element being added to A is the penultimate one, since the last element is always the same as the first. I have used Martin Büttner's trick of including 0 twice in B candidates in order to get the proper probability distribution. The dictionary X (which is named Y for N+1) keeps track of the count of all possible arrays according to the value of the tuple. The variables n and d stand for numerator and denominator, which is why I renamed the n of the problem statement as N.
The key part of the logic is that you can update from N to N+1 using just the values in the tuple. The two inner products specified in the question are given by s+A*B and t+A*b+a*B. This is clear if you examine the definitions a bit; note that [A,a] and [b,B] are the last two elements of arrays A and B respectively.
Note that s and t are small and bounded according to N, and for a fast implementation in a fast language we could avoid dictionaries in favor of arrays.
It may be possible to take advantage of symmetry considering values differing only in sign; I have not looked into that.
Remark 1: The size of the dictionary grows quadratically in N, where size means number of key-value pairs.
Remark 2: If we set an upper bound on N, then we can prune tuples for which N_MAX - N <= |s| and similarly for t. This could be done by specifying an absorbing state, or implicitly with a variable to hold the count of pruned states (which would need to be multiplied by 8 at each iteration).
Update: This version is faster:
from time import*
from fractions import*
from collections import*

N_MAX=115

def main():
    T=time()

    N=1
    Y={(1,0,0,0):1,(1,1,1,0):1}
    n=1
    thresh=N_MAX

    while time() <= T+10:
        print('%d %s'%(N,Fraction(n,8**N/4)))

        N+=1
        X=Y
        Y=defaultdict(lambda:0)
        n=0

        if thresh<2:
            print('reached MAX_N with %.2f seconds remaining'%(T+10-time()))
            return

        for a,b,s,t in X:
            if not abs(s)<thresh>=abs(t):
                continue

            c=X[(a,b,s,t)]

            # 1,1

            if not s+1 and not t+b+a: n+=c
            Y[(a,1,s+1,t+b)]+=c

            # -1,1

            if not s-1 and not t-b+a: n+=c
            Y[(a,1,s-1,t-b)]+=c

            # 1,-1

            if not s-1 and not t+b-a: n+=c
            Y[(a,-1,s-1,t+b)]+=c

            # -1,-1

            if not s+1 and not t-b-a: n+=c
            Y[(a,-1,s+1,t-b)]+=c

            # 1,0

            c+=c

            if not s and not t+b: n+=c
            Y[(a,0,s,t+b)]+=c

            # -1,0

            if not s and not t-b: n+=c
            Y[(a,0,s,t-b)]+=c

        thresh-=1

main()

Optimisations implemented:

put everything into main() -- local variable access is faster than global
handle N=1 explicitly to avoid the check (1,-1) if N else [a] (which enforces that the first element in the tuple is consistent, when adding elements to A starting from the empty list)
unroll the inner loops, which also eliminates multiplication
double the count c for adding a 0 to B instead of doing those operations twice
the denominator is always 8^N so we do not need to keep track of it
now taking symmetry into account: we can fix the first element of A as 1 and divide the denominator by 2, since the valid pairs (A,B) with A[1]=1 and those with A[1]=-1 can be put into one-to-one correspondence by negating A. Similarly, we can fix the first element of B as non-negative.
now with pruning. You would need to fiddle with N_MAX to see what score it can get on your machine. It could be rewritten to find an appropriate N_MAX automatically by binary search, but seems unnecessary? Note: We do not need to check the pruning condition until reaching around N_MAX / 2, so we could get a little speedup by iterating in two phases, but I decided not to for simplicity and code cleanliness.

This is a really great answer! Could you explain what you did in your speed up?

@Lembik Thank you :) Added an explanation, plus another small optimisation, and made it Python3 compliant.

On my computer, I got N=57 for the first version and N=75 for the second.

Your answers have been awesome. It's just that Min_25's answer was even more so :)

Python
Using Min_25's idea of random walk, I was able to arrive at a different formula:

Here is a Python implementation based on Min_25's:
from time import*
from itertools import*

def main():
    def binom(n, k):
        return facts[n]/(facts[k]*facts[n-k])

    def p(n):
        numer=0
        for i in range(n/2+1):
            t=binom(2*i,i)
            t*=t
            t*=binom(n,2*i)
            t<<=2*(n-2*i)
            numer+=t
        if not n&1:
            numer+=t
        e=(numer&-numer).bit_length()-1
        numer>>=e
        denom=1<<(3*n-e)
        return numer, denom

    facts=[1]
    time_limit=time()+10

    for i in count(1):
        facts.append(facts[-1]*i)

        n,d=p(i)

        if time()>time_limit:
            break

        print("%d %d/%d"%(i,n,d))

main()

Explanation / proof:
First we solve a related counting problem, where we allow A[n+1] = -A[1]; that is, the additional element concatenated to A can be 1 or -1 regardless of the first element. So we do not need to keep track of how many times A[i] = A[i+1] occurs. We have the following random walk:
From (x,y) we can move to (x+1,y+1) [1 way], (x+1,y-1) [1 way], (x-1,y+1) [1 way], (x-1,y-1) [1 way], (x,y) [4 ways]
where x and y stand for the two dot products, and we are counting the number of ways to move from (0,0) to (0,0) in n steps. That count would then be multiplied by 2 to account for the fact that A can start with 1 or -1.
We refer to staying at (x,y) as a zero move.
We iterate over the number of non-zero moves i, which has to be even in order to get back to (0,0). Horizontal and vertical movements make up two independent one-dimensional random walks, which can be counted by C(i,i/2)^2, where C(n,k) is binomial coefficient. (For a walk with k steps left and k steps right, there are C(2k,k) ways to choose the order of steps.) Additionally there are C(n,i) ways to place the moves, and 4^(n-i) ways to choose the zero moves. So we get:
a(n) = 2 * sum_{i in (0,2,4,...,n)} C(i/2,i)^2 * C(n,i) * 4^(n-i)

Now, we need to turn back to the original problem. Define an allowable pair (A,B) to be convertible if B contains a zero. Define a pair (A,B) to be almost allowable if A[n+1] = -A[1] and the two dot products are both zero.
Lemma: For a given n, the almost allowable pairs are in one-to-one correspondence with the convertible pairs.
We can (reversibly) convert a convertible pair (A,B) into an almost allowable pair (A',B') by negating A[m+1:] and B[m+1:], where m is the index of the last zero in B. The check for this is straightforward: If the last element of B is zero, we do not need to do anything. Otherwise, when we negate the last element of A, we can negate the last element of B in order to preserve the last term of the shifted dot product. But this negates the last value of the non-shifted dot product, so we fix this by negating the second-to-last element of A. But then this throws off the second-to-last value of the shifted product, so we negate the second-to-last element of B. And so on, until reaching a zero element in B.
Now, we just need to show that there are no almost allowable pairs for which B does not contain a zero. For a dot product to equal zero, we must have an equal number of 1 and -1 terms to cancel out. Each -1 term is composed of (1,-1) or (-1,1). So the parity of the number of -1 that occur is fixed according to n. If the first and last elements of A have different signs, we change the parity, so this is impossible.
So we get
c(n) = a(n)/2 if n is odd, else a(n)/2 + C(n,n/2)^2

p(n) = c(n) / 8^n

which gives the above formula (re-indexing with i' = i/2).
Update: Here is a faster version using the same formula:
from time import*
from itertools import*

def main():
    time_limit=time()+10

    binoms=[1]
    cb2s=[1]
    cb=1

    for n in count(1):
        if n&1:
            binoms=[a+b for a,b in zip([0]+binoms,binoms)]
        else:
            binoms=[a+b for a,b in zip([0]+binoms,binoms+[binoms[-1]])]
            cb=(cb<<2)-(cb+cb)/(n/2)
            cb2s.append(cb*cb)

        numer=0
        for i in xrange(n/2+1):
            t=cb2s[i]*binoms[min(2*i,n-2*i)]
            t<<=2*(n-2*i)
            numer+=t
        if not n&1:
            numer+=t
        e=(numer&-numer).bit_length()-1
        numer>>=e
        denom=1<<(3*n-e)

        if time()>time_limit:
            break

        print("%d %d/%d"%(n,numer,denom))

main()

Optimisations implemented:

inline function p(n)
use recurrence for binomial coefficients C(n,k) with k <= n/2
use recurrence for central binomial coefficients

Just so you know, p(n) doesn't need to be a piecewise function. In general, if f(n) == {g(n) : n is odd; h(n) : n is even} then you can write f(n) == (n-2*floor(n/2))*g(n) + ((n+1)-2*(floor((n+1)/2)))*h(n) or use n mod 2 instead of (n-2*floor(n/2)). See here

@mbomb007 That is obvious and uninteresting.

Explication of Min_25's formula
Min_25 posted a great proof but it took a while to follow. This is a bit of explanation to fill in between the lines.
a(n, m) represents the number of ways to choose A such that A[i] = A[i+1] m times. The formula for a(n,m) is equivalent to a(n,m) = {2 * (n choose m) for n-m even; 0 for n-m odd.} Only one parity is allowed because A[i] != A[i+1] must occur an even number of times so that A[0] = A[n]. The factor of 2 is due to the initial choice A[0] = 1 or A[0] = -1.
Once the number of (A[i] != A[i+1]) is fixed to be q (named i in the c(n) formula), it separates into two 1D random walks of length q and n-q. b(m) is the number of ways to take a one-dimensional random walk of m steps that ends at the same place it started, and has 25% chance of moving left, 50% chance of staying still, and 25% chance of moving right. A more obvious way to state the generating function is [x^m](1 + 2x + x^2)^n, where 1, 2x and x^2 represent left, no move, and right respectively. But then 1+2x+x^2 = (x+1)^2.

Yet another reason to love PPCG!  Thank you.

C++
Just a port of the (excellent) Python answer by Mitch Schwartz. The primary difference is that I used 2 to represent -1 for the a variable and did something similar for b, which allowed me to use an array. Using Intel C++ with -O3, I got N=141! My first version got N=140.
This uses Boost. I tried a parallel version but ran into some trouble.
#include <boost/multiprecision/gmp.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/rational.hpp>
#include <boost/chrono.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <utility>
#include <map>

typedef boost::multiprecision::mpz_int integer;
typedef boost::array<boost::array<std::map<int, std::map<int, integer> >, 3>, 2> array;
typedef boost::rational<integer> rational;

int main() {
    BOOST_AUTO(T, boost::chrono::high_resolution_clock::now());

    int N = 1;
    integer n = 1;
    array* Y = new array, *X = NULL;
    (*Y)[1][0][0][0] = 1;
    (*Y)[1][1][1][0] = 1;

    while (boost::chrono::high_resolution_clock::now() < T+boost::chrono::seconds(10)) {
        std::cout << N << " " << rational(n, boost::multiprecision::pow(integer(8), N)/4) << std::endl;
        ++N;
        delete X;
        X = Y;
        Y = new array;
        n = 0;

        for (int a=0; a<2; ++a)
            for (int b=0; b<3; ++b)
                for (BOOST_AUTO(s, (*X)[a][b].begin()); s != (*X)[a][b].end(); ++s)
                    for (BOOST_AUTO(t, s->second.begin()); t != s->second.end(); ++t) {
                        integer c = t->second;
                        int d = b&2 ? -1 : b, e = a == 0 ? -1 : a;

                        if (s->first == -1 && t->first+d+e == 0) n += c;
                        (*Y)[a][1][s->first+1][t->first+d] += c;

                        if (s->first == 1 && t->first-d+e == 0) n += c;
                        (*Y)[a][1][s->first-1][t->first-d] += c;

                        if (s->first == 1 && t->first+d-e == 0) n += c;
                        (*Y)[a][2][s->first-1][t->first+d] += c;

                        if (s->first == -1 && t->first-d-e == 0) n += c;
                        (*Y)[a][2][s->first+1][t->first-d] += c;

                        c *= 2;

                        if (s->first == 0 && t->first+d == 0) n += c;
                        (*Y)[a][0][s->first][t->first+d] += c;

                        if (s->first == 0 && t->first-d == 0) n += c;
                        (*Y)[a][0][s->first][t->first-d] += c;
                    }
    }

    delete X;
    delete Y;
}

This needs g++ -O3 kirbyfan64sos.cpp  -o  kirbyfan64sos -lboost_system -lboost_timer -lboost_chrono -lrt -lgmp to compile. (Thanks to aditsu.)


text:
Print all colorings of a 3x3 grid
You have a 3x3 grid. Each cell can be colored black or white. Display all 512 of these colorings. Fewest bytes wins.
You can display the grids in any formation as long as they are visually separated and the spacing looks regular. You may use ASCII art or images. Any two distinct visible symbols or colors can be used for black and white. Any whitespace is fine as long as the result is visually correct.
Example output:
...
...
...

...
...
..X

...
...
.X.

...
...
.XX

...
...
X..

...
...
X.X

...
...
XX.

...
...
XXX

...
..X
...

...
..X
..X

...
..X
.X.

...
..X
.XX

...
..X
X..

...
..X
X.X

...
..X
XX.

...
..X
XXX

...
.X.
...

...
.X.
..X

...
.X.
.X.

...
.X.
.XX

...
.X.
X..

...
.X.
X.X

...
.X.
XX.

...
.X.
XXX

...
.XX
...

...
.XX
..X

...
.XX
.X.

...
.XX
.XX

...
.XX
X..

...
.XX
X.X

...
.XX
XX.

...
.XX
XXX

...
X..
...

...
X..
..X

...
X..
.X.

...
X..
.XX

...
X..
X..

...
X..
X.X

...
X..
XX.

...
X..
XXX

...
X.X
...

...
X.X
..X

...
X.X
.X.

...
X.X
.XX

...
X.X
X..

...
X.X
X.X

...
X.X
XX.

...
X.X
XXX

...
XX.
...

...
XX.
..X

...
XX.
.X.

...
XX.
.XX

...
XX.
X..

...
XX.
X.X

...
XX.
XX.

...
XX.
XXX

...
XXX
...

...
XXX
..X

...
XXX
.X.

...
XXX
.XX

...
XXX
X..

...
XXX
X.X

...
XXX
XX.

...
XXX
XXX

..X
...
...

..X
...
..X

..X
...
.X.

..X
...
.XX

..X
...
X..

..X
...
X.X

..X
...
XX.

..X
...
XXX

..X
..X
...

..X
..X
..X

..X
..X
.X.

..X
..X
.XX

..X
..X
X..

..X
..X
X.X

..X
..X
XX.

..X
..X
XXX

..X
.X.
...

..X
.X.
..X

..X
.X.
.X.

..X
.X.
.XX

..X
.X.
X..

..X
.X.
X.X

..X
.X.
XX.

..X
.X.
XXX

..X
.XX
...

..X
.XX
..X

..X
.XX
.X.

..X
.XX
.XX

..X
.XX
X..

..X
.XX
X.X

..X
.XX
XX.

..X
.XX
XXX

..X
X..
...

..X
X..
..X

..X
X..
.X.

..X
X..
.XX

..X
X..
X..

..X
X..
X.X

..X
X..
XX.

..X
X..
XXX

..X
X.X
...

..X
X.X
..X

..X
X.X
.X.

..X
X.X
.XX

..X
X.X
X..

..X
X.X
X.X

..X
X.X
XX.

..X
X.X
XXX

..X
XX.
...

..X
XX.
..X

..X
XX.
.X.

..X
XX.
.XX

..X
XX.
X..

..X
XX.
X.X

..X
XX.
XX.

..X
XX.
XXX

..X
XXX
...

..X
XXX
..X

..X
XXX
.X.

..X
XXX
.XX

..X
XXX
X..

..X
XXX
X.X

..X
XXX
XX.

..X
XXX
XXX

.X.
...
...

.X.
...
..X

.X.
...
.X.

.X.
...
.XX

.X.
...
X..

.X.
...
X.X

.X.
...
XX.

.X.
...
XXX

.X.
..X
...

.X.
..X
..X

.X.
..X
.X.

.X.
..X
.XX

.X.
..X
X..

.X.
..X
X.X

.X.
..X
XX.

.X.
..X
XXX

.X.
.X.
...

.X.
.X.
..X

.X.
.X.
.X.

.X.
.X.
.XX

.X.
.X.
X..

.X.
.X.
X.X

.X.
.X.
XX.

.X.
.X.
XXX

.X.
.XX
...

.X.
.XX
..X

.X.
.XX
.X.

.X.
.XX
.XX

.X.
.XX
X..

.X.
.XX
X.X

.X.
.XX
XX.

.X.
.XX
XXX

.X.
X..
...

.X.
X..
..X

.X.
X..
.X.

.X.
X..
.XX

.X.
X..
X..

.X.
X..
X.X

.X.
X..
XX.

.X.
X..
XXX

.X.
X.X
...

.X.
X.X
..X

.X.
X.X
.X.

.X.
X.X
.XX

.X.
X.X
X..

.X.
X.X
X.X

.X.
X.X
XX.

.X.
X.X
XXX

.X.
XX.
...

.X.
XX.
..X

.X.
XX.
.X.

.X.
XX.
.XX

.X.
XX.
X..

.X.
XX.
X.X

.X.
XX.
XX.

.X.
XX.
XXX

.X.
XXX
...

.X.
XXX
..X

.X.
XXX
.X.

.X.
XXX
.XX

.X.
XXX
X..

.X.
XXX
X.X

.X.
XXX
XX.

.X.
XXX
XXX

.XX
...
...

.XX
...
..X

.XX
...
.X.

.XX
...
.XX

.XX
...
X..

.XX
...
X.X

.XX
...
XX.

.XX
...
XXX

.XX
..X
...

.XX
..X
..X

.XX
..X
.X.

.XX
..X
.XX

.XX
..X
X..

.XX
..X
X.X

.XX
..X
XX.

.XX
..X
XXX

.XX
.X.
...

.XX
.X.
..X

.XX
.X.
.X.

.XX
.X.
.XX

.XX
.X.
X..

.XX
.X.
X.X

.XX
.X.
XX.

.XX
.X.
XXX

.XX
.XX
...

.XX
.XX
..X

.XX
.XX
.X.

.XX
.XX
.XX

.XX
.XX
X..

.XX
.XX
X.X

.XX
.XX
XX.

.XX
.XX
XXX

.XX
X..
...

.XX
X..
..X

.XX
X..
.X.

.XX
X..
.XX

.XX
X..
X..

.XX
X..
X.X

.XX
X..
XX.

.XX
X..
XXX

.XX
X.X
...

.XX
X.X
..X

.XX
X.X
.X.

.XX
X.X
.XX

.XX
X.X
X..

.XX
X.X
X.X

.XX
X.X
XX.

.XX
X.X
XXX

.XX
XX.
...

.XX
XX.
..X

.XX
XX.
.X.

.XX
XX.
.XX

.XX
XX.
X..

.XX
XX.
X.X

.XX
XX.
XX.

.XX
XX.
XXX

.XX
XXX
...

.XX
XXX
..X

.XX
XXX
.X.

.XX
XXX
.XX

.XX
XXX
X..

.XX
XXX
X.X

.XX
XXX
XX.

.XX
XXX
XXX

X..
...
...

X..
...
..X

X..
...
.X.

X..
...
.XX

X..
...
X..

X..
...
X.X

X..
...
XX.

X..
...
XXX

X..
..X
...

X..
..X
..X

X..
..X
.X.

X..
..X
.XX

X..
..X
X..

X..
..X
X.X

X..
..X
XX.

X..
..X
XXX

X..
.X.
...

X..
.X.
..X

X..
.X.
.X.

X..
.X.
.XX

X..
.X.
X..

X..
.X.
X.X

X..
.X.
XX.

X..
.X.
XXX

X..
.XX
...

X..
.XX
..X

X..
.XX
.X.

X..
.XX
.XX

X..
.XX
X..

X..
.XX
X.X

X..
.XX
XX.

X..
.XX
XXX

X..
X..
...

X..
X..
..X

X..
X..
.X.

X..
X..
.XX

X..
X..
X..

X..
X..
X.X

X..
X..
XX.

X..
X..
XXX

X..
X.X
...

X..
X.X
..X

X..
X.X
.X.

X..
X.X
.XX

X..
X.X
X..

X..
X.X
X.X

X..
X.X
XX.

X..
X.X
XXX

X..
XX.
...

X..
XX.
..X

X..
XX.
.X.

X..
XX.
.XX

X..
XX.
X..

X..
XX.
X.X

X..
XX.
XX.

X..
XX.
XXX

X..
XXX
...

X..
XXX
..X

X..
XXX
.X.

X..
XXX
.XX

X..
XXX
X..

X..
XXX
X.X

X..
XXX
XX.

X..
XXX
XXX

X.X
...
...

X.X
...
..X

X.X
...
.X.

X.X
...
.XX

X.X
...
X..

X.X
...
X.X

X.X
...
XX.

X.X
...
XXX

X.X
..X
...

X.X
..X
..X

X.X
..X
.X.

X.X
..X
.XX

X.X
..X
X..

X.X
..X
X.X

X.X
..X
XX.

X.X
..X
XXX

X.X
.X.
...

X.X
.X.
..X

X.X
.X.
.X.

X.X
.X.
.XX

X.X
.X.
X..

X.X
.X.
X.X

X.X
.X.
XX.

X.X
.X.
XXX

X.X
.XX
...

X.X
.XX
..X

X.X
.XX
.X.

X.X
.XX
.XX

X.X
.XX
X..

X.X
.XX
X.X

X.X
.XX
XX.

X.X
.XX
XXX

X.X
X..
...

X.X
X..
..X

X.X
X..
.X.

X.X
X..
.XX

X.X
X..
X..

X.X
X..
X.X

X.X
X..
XX.

X.X
X..
XXX

X.X
X.X
...

X.X
X.X
..X

X.X
X.X
.X.

X.X
X.X
.XX

X.X
X.X
X..

X.X
X.X
X.X

X.X
X.X
XX.

X.X
X.X
XXX

X.X
XX.
...

X.X
XX.
..X

X.X
XX.
.X.

X.X
XX.
.XX

X.X
XX.
X..

X.X
XX.
X.X

X.X
XX.
XX.

X.X
XX.
XXX

X.X
XXX
...

X.X
XXX
..X

X.X
XXX
.X.

X.X
XXX
.XX

X.X
XXX
X..

X.X
XXX
X.X

X.X
XXX
XX.

X.X
XXX
XXX

XX.
...
...

XX.
...
..X

XX.
...
.X.

XX.
...
.XX

XX.
...
X..

XX.
...
X.X

XX.
...
XX.

XX.
...
XXX

XX.
..X
...

XX.
..X
..X

XX.
..X
.X.

XX.
..X
.XX

XX.
..X
X..

XX.
..X
X.X

XX.
..X
XX.

XX.
..X
XXX

XX.
.X.
...

XX.
.X.
..X

XX.
.X.
.X.

XX.
.X.
.XX

XX.
.X.
X..

XX.
.X.
X.X

XX.
.X.
XX.

XX.
.X.
XXX

XX.
.XX
...

XX.
.XX
..X

XX.
.XX
.X.

XX.
.XX
.XX

XX.
.XX
X..

XX.
.XX
X.X

XX.
.XX
XX.

XX.
.XX
XXX

XX.
X..
...

XX.
X..
..X

XX.
X..
.X.

XX.
X..
.XX

XX.
X..
X..

XX.
X..
X.X

XX.
X..
XX.

XX.
X..
XXX

XX.
X.X
...

XX.
X.X
..X

XX.
X.X
.X.

XX.
X.X
.XX

XX.
X.X
X..

XX.
X.X
X.X

XX.
X.X
XX.

XX.
X.X
XXX

XX.
XX.
...

XX.
XX.
..X

XX.
XX.
.X.

XX.
XX.
.XX

XX.
XX.
X..

XX.
XX.
X.X

XX.
XX.
XX.

XX.
XX.
XXX

XX.
XXX
...

XX.
XXX
..X

XX.
XXX
.X.

XX.
XXX
.XX

XX.
XXX
X..

XX.
XXX
X.X

XX.
XXX
XX.

XX.
XXX
XXX

XXX
...
...

XXX
...
..X

XXX
...
.X.

XXX
...
.XX

XXX
...
X..

XXX
...
X.X

XXX
...
XX.

XXX
...
XXX

XXX
..X
...

XXX
..X
..X

XXX
..X
.X.

XXX
..X
.XX

XXX
..X
X..

XXX
..X
X.X

XXX
..X
XX.

XXX
..X
XXX

XXX
.X.
...

XXX
.X.
..X

XXX
.X.
.X.

XXX
.X.
.XX

XXX
.X.
X..

XXX
.X.
X.X

XXX
.X.
XX.

XXX
.X.
XXX

XXX
.XX
...

XXX
.XX
..X

XXX
.XX
.X.

XXX
.XX
.XX

XXX
.XX
X..

XXX
.XX
X.X

XXX
.XX
XX.

XXX
.XX
XXX

XXX
X..
...

XXX
X..
..X

XXX
X..
.X.

XXX
X..
.XX

XXX
X..
X..

XXX
X..
X.X

XXX
X..
XX.

XXX
X..
XXX

XXX
X.X
...

XXX
X.X
..X

XXX
X.X
.X.

XXX
X.X
.XX

XXX
X.X
X..

XXX
X.X
X.X

XXX
X.X
XX.

XXX
X.X
XXX

XXX
XX.
...

XXX
XX.
..X

XXX
XX.
.X.

XXX
XX.
.XX

XXX
XX.
X..

XXX
XX.
X.X

XXX
XX.
XX.

XXX
XX.
XXX

XXX
XXX
...

XXX
XXX
..X

XXX
XXX
.X.

XXX
XXX
.XX

XXX
XXX
X..

XXX
XXX
X.X

XXX
XXX
XX.

XXX
XXX
XXX

@edc65 xnor made the edit, and Filipe approved it (after which I purged the comments). I just added tags.

Can we move the example to a PasteBin? It’s anemic to scroll as of right now. Besides, this is just the power set of the input squared, divided into lines of the input where the 1s and 0s are replaced by X and .

K, 11 bytes
(3 3#)'!9#2

Output example:
((0 0 0
  0 0 0
  0 0 0)
 (0 0 0
  0 0 0
  0 0 1)
 (0 0 0
  0 0 0
  0 1 0)
 (0 0 0
  0 0 0
  0 1 1)
…

This is K's native prettyprinted representation of a list of matrices, which I think is sufficient for the problem spec. Each matrix is delimited by an enclosing set of parentheses.
And a quick sanity check to demonstrate that 512 matrices are constructed:
  #(3 3#)'!9#2
512

Very straightforward. Most of the work is in the !. First we generate a 9-long vector of 2s using "take" (9#2). Then, we make use of the "odometer" monadic form of !- a few examples illustrate its behavior:
  !2 2
(0 0
 0 1
 1 0
 1 1)
  !2 3
(0 0
 0 1
 0 2
 1 0
 1 1
 1 2)
  !2 2 2
(0 0 0
 0 0 1
 0 1 0
 0 1 1
 1 0 0
 1 0 1
 1 1 0
 1 1 1)

Then simply do a 3x3 reshape ((3 3#)) of each (') of the 9-length 0/1 vectors.

Mathematica, 25 bytes
Image/@{0,1}~Tuples~{3,3}

Gives an array with all the grids as images, which is also directly displayed on screen:

(Cropped so as not to blow up the post unnecessarily.)

upvoted for being the prettiest output

JavaScript, 77 80
Revised after the revision of the OP. Now we have a question, so here is an answer.
Run the snippet in any browser to test.

// Test: redefine console to have output inside the snippet

console = { log: function(x) { O.textContent+=x+'\n\n';} }

// Solution: 77 chars (note, distinct outputs to console are automatically separed)

for(i=511;++i<1024;)console.log(i.toString(2).slice(1).match(/.../g).join`
`)

Old post: graphic display  in a browser, with javascript and canvas. ~300 byte of code (can be made shorter).
Run the snippet below.

d=8, // Min block size
C.width=d*64,C.height=d*128,
T=C.getContext('2d')

for(i=0;i<512;i++)
{
  bx=4*(i/32|0)
  by=4*(i%32)
  for(b=1,j=0;j<9;j++,b+=b)
  {
    if(b&i)
      x=j/3|0, y=j%3, T.fillRect((bx+x)*d,(by+y)*d,d,d);
  }
  T.strokeRect(bx*d,by*d,d*3,d*3);
}
<canvas id=C></canvas>

If you specify (ES6), you can replace .join('\n') with .join  (literal newline, not space... stupid comment formatting) to save 3 bytes

@PatrickRoberts yes, template string was already implemented in Firefox 14 months ago, but I was not aware of that. Edit the code after so much time is a little necrobumping

Matlab, 33
reshape(dec2bin(0:511,9)',3,3,[])

Was kind of fiddly to get the dimensions correct, but I am very happy with the result!

POWERSHELL - 65
0..511|%{[convert]::ToString($_,2).padleft(9,'0')-split"(.{3})"}

result
000

000

000

000

000

001

000

000

010

000

000

011

confirmation
(0..511|%{[convert]::ToString($_,2).padleft(9,'0')-split"(.{3})"} | measure -Line).lines/3

512

edit inspired by the mathematica answer's display of results-617
Add-Type -AssemblyName System.Drawing
$a=new-object System.Drawing.Bitmap 992,496
$g=[Drawing.Graphics]::FromImage($a)
$b=@{};$y=@{};$i=$c=$d=$z=$k=$l=$m=0;
0..511|%{$y[$d++]=[convert]::ToString($_,2).padleft(9,'0')}
while($m-lt480){while($l-lt496){for($z=($m+0);$z-lt($m+32);$z++){
      $y[$z].tochararray()|%{if($_-eq"0"){$b[$i++]=[Drawing.Brushes]::Black}
        else{$b[$i++]=[Drawing.Brushes]::White}
      }
      for($j=($l+0);$j-lt($l+30);$j+=10){
        ($k+0),($k+10),($k+20)|%{$g.FillRectangle($b[$c++],$_,$j,10,10)}
      }$k+=31
    }$k=0;$l+=31;$m+=32
  }
}$a.save("$HOME/3X3_Grid.png")

Python 2, 49 bytes
i=2048;exec"print bin(i/4)[i%4*3+3:][:3];i+=1;"*i

Split the binary expansion of i. The length-10 binary values 512 through 1023 are used, cutting off the initial 1 (and prefix 0b). These are split into chunks of 3 as windows [3:6], [6:9], [9:12], and [12:15], with the last one blank to make a blank line. Iterating over the four slices is collapsed with the outer loop of counting through 512 numbers with the divmod trick.

CJam, 12 bytes
2,9m*3f/N*N*

Test it here.
Uses 0 and 1 as the distinct characters.
Explanation
2,  e# Push [0 1].
9m* e# Generate all 9-tuples of 0s and 1s.
3f/ e# Split each 9-tuple into 3 subarrays of length 3.
N*  e# Join all those grids with newlines.
N*  e# Put newlines between all the length-3 arrays.

An alternative (still 12 byte) solution is
2,3m*3m*N*N*

Haskell, 57 54 bytes
r x=sequence[x,x,x]
u=unlines
f=putStr$u$map u$r$r".X"

f gives the same output as in the challenge description, i.e. it starts with
...
...
...

...
...
..X

...
...
.X.

Edit: @Mauris found 3 bytes to save. Thanks!

I think r x=sequence[x,x,x] does the same thing and is shorter.

@Mauris: you're right. Edited my post. Thanks!

Ruby, 86 bytes
0.upto(511).map{|i|i.to_s(2).rjust(9,'0')}.each{|j|p j[0..2];p j[3..5];p j[6..8];puts}

Mine prints with quotes because p is shorter than puts, but it does still fit the rules.

C# - 111
for(int i=0;i<512;i++)Console.WriteLine(Regex.Replace(Convert.ToString(i,2).PadLeft(9,'0'),"(.{3})","$1\r\n"));

Converts every int to its binary representation and splits every 3 chars.

Python 2, 95 Bytes
Distinct characters are 0 and 1, each block is separated by \n\n.
n='\n';print(n+n).join(y[:3]+n+y[3:6]+n+y[-3:]for y in[bin(x)[2:].zfill(9)for x in range(512)])

Python 2, 81
import re
for i in range(512):print re.sub('(.{3})','\\1\n',bin(i)[2:].zfill(9))

Ruby, 92 bytes
0.upto(511){|i|("%09d"%i.to_s(2)).scan(/.{3}/).map{|j|j.scan(/./)}.map{|j|puts j.join};puts}

Counts in 0s and 1s, and each block is separated by an empty line (\n\n)

Pyth, 11 bytes
V^`T9jbc3Nk

Try it here!
Thanks @Jakube :)

Ruby, 68 bytes
Prints the exact same output as the example given in the question
puts (0..511).map{|i|("%09b"%i).tr("01",".X").gsub(/.../){$&+$/}}*$/

No need for  tr, outputting 0 and 1 is fine. A few more suggestions 512.times{|i|$><<("%09b"%i).gsub(/.../){$&+$/}+$/} 50 bytes.

Python 3, 80 bytes
for i in range(512):print("\n".join(format(i,'09b')[j:j+3]for j in(0,3,6)),"\n")

I managed to outgolf someone :)

Save a byte using a while loop: i=512 newline
while i:print("\n".join(format(i,'09b')[j:j+3]for j in(0,3,6)),"\n");i-=1

PHP, 55 bytes
for(;$c<512;)echo chunk_split(sprintf("%09b ",$c++),3);

uses 0 and 1. Run with -r.

I just love the way I impletemented the separating newline :)

Python 2, 56 bytes
from itertools import*
print set(combinations('X.'*9,9))

Try it online!
Returns the 512 configurations as a set object in python. Refer to ungolfed version to make output more readable.
Ungolfed Version to make output more readable:
Python 2, 121 bytes
from itertools import*
for i in set(combinations('X.'*9,9)):
	for j in range(3):print''.join(list(i))[j*3:(j*3)+3]
	print

Try it online!

Swift 2, 92 bytes
Int to binary string in Swift takes up too many chars so I just use two nested loops...
var s="";for x in 0..<512{(0..<9).map{s+=($0%3==0 ?"\n":"")+"\(x>>$0&1)"};s+="\n-"};print(s)

C - 97 bytes
i;main(j){for(;i++<512;)for(j=0;j++<13;)putchar(j%4&&j<13?i%(1<<j-j/4)>(1<<j-j/4-1)-1?88:46:10);}

Basically prints the example output from the original question.

Perl, 56 55 bytes
print$_/9&1<<$_%9?1:0,$/x(!(++$_%3)+!($_%9))for+0..4607

Output:
000
000
000

100
000
000
...

Python 3, 123 121 109 103 bytes
Here is my old one:
import itertools
[print(a+b+c,d+e+f,g+h+i,'\n',sep='\n') for a,b,c,d,e,f,g,h,i in itertools.product(['X','.'],repeat=9)]

And here is my new one:
import itertools as i
[print(a[:3],a[3:6],a[6:],'\n',sep='\n') for a in i.product(['X','.'],repeat=9)]

This prints extra characters but the OP said ASCII art is allowed which implies multiple characters are fine.

Prolog (SWI), 98 bytes
Output is a list of 3x3 matrices containing the elements 0 and 1.
r([]).
r([H|T]):-between(0,1,H),r(T).
p(Y):-Z=[[_,_,_],[_,_,_],[_,_,_]],findall(Z,maplist(r,Z),Y).

Online interpreter
I feel like the matrix generation could be shorter.
It should be possible to fit the between in a forall or something similar, but I can't figure out how.
Golfing tips appreciated.

Jelly, 17 bytes
512+ḶBḊ€s€3Y€j“¶¶

Try it online!
Uses 01. Because of a bug in ⁾, I had to use “¶¶ instead of ⁾¶¶, because otherwise, instead of two newlines, two pilcrows would have showed up in the output. As you can see, though, that didn't cost me any bytes at all.
K beats this, so this must be further golfed down.

05AB1E, 15 bytes
žAFNžA+b¦3ô»,¶?

Try it online!

Python 3, 74 bytes
i=512;b="\n"
while i:i-=1;a=format(i,'09b');print(a[:3]+b+a[3:6]+b+a[6:],b)

Just a little shorter than Destructible Lemon's answer

Perl 5, 32 bytes
$_=("{.,#}"x3 .$/)x3;say<"$_\n">

Try it online!

05AB1E, 9 bytes
T3ã¶«3ãJ»

Uses the digits [1,0]. The T could be replaced with ₂, ₃, or ₆ to use the digits [2,6], [9,5], or [3,6] respectively.
Try it online.
Outputting as an unformatted list could have been 5 bytes: T3ã3ã.
Explanation:
T          # Push 10
 3ã        # Take the cartesian power of 3 with its digits:
           #  ["111","110","101",...,"000"]
   ¶«      # Append a newline to each triplet
           #  ["111\n","110\n","101\n",...,"000\n"]
     3ã    # Take the cartesian power of 3 with this list of strings:
           #  [["111\n","111\n","111\n"],["111\n","111\n","110\n"],...,["000\n","000\n","000\n"]]
       J   # Join each inner list together
           #  ["111\n111\n111\n","111\n111\n110\n",...,"000\n000\n000\n"]
        »  # And join that list by newlines
           #  "111\n111\n111\n\n111\n111\n110\n\n...\n000\n000\n000\n"
           # (after which it is output implicitly as result)

Ruby, 42 bytes
512.times{puts ("%09b"%_1).scan(/.../),$/}

Attempt This Online!

Vyxal Hj, 62 bitsv2, 7.75 bytes
U2(3ÞẊṅ¶+

U2(3ÞẊṅ¶+
# #H flag sets stack to 100
U          # uniquify the digits, getting a list of [1,0]. This didn't work with the builtin for 10 when I tried it
 2(        # iterate twice
   3ÞẊ     # cartesian power of 3
      ṅ¶+  # joined on nothing with a newline appended
# j flag joins top of stack on newlines
# this leads to the double newline separator

Created with the help of Luminespire.
Try it Online!
Bitstring:
01100100111011000111001100111101010001110000111111010101000100

Port of Kevin's 05ab1e answer, with different separators.

Vyxal 3 s, 12 8 bytes
₀2(3ẋ“¶+

Try it Online!
port of the 05ab1e answer

Uiua, 12 bytes
≡(↯3_3)⋯⇡512

Outputs an array of 512 3x3 bit matrices. Makes clever use of the bits ⋯ primitive, which converts all numbers in an array to lists of bits.
With &gifs, you can make a very tiny GIF cycling every grid.
Pad, GIF version

Perl, 52 bytes
printf+("%03b
"x3).$/,$_&7,$_/8&7,$_>>6&7 for 0..511

or 54 bytes:
print map$_.$/,sprintf('%09b',$_)=~/.../g,''for 0..511

or Perl 5.14+, 48 bytes:
say sprintf('%09b',$_)=~s/.../$&\n/gr for 0..511

J, 27 bytes
echo@<"2'.X'{~_3]\"1#:i.512

Try it online!

The problem isn't restrictive on output format, so you could use echo _3]\"1#:i.512.

Tcl, 72 bytes
time {puts [regsub -all (...) [format %09b [expr [incr i]-1]] \&\n]} 512

Try it online!

Failed outgolf: https://tio.run/##JcNBCoAgEAXQfaf4i1wGWbToLDoLHQyENFGDIDq7BcF7lffWqg8Od2ETobYjB1MhxtVCuStlKB85w9MgiQhiLj8YWHCXzlrQGx17@2UdHyxyau0F

Japt, 16 15 bytes
#f4o8³_¤Åò3 ·+R

Try it online!

Python 2, 114 bytes
from itertools import *
for i in product(".X",repeat=9):
    i="".join(i);print i[0:3]+"\n"+i[3:6]+"\n"+i[6:]+"\n"

Try it online!

JavaScript (Node.js), 72 bytes
h=console.log;f=u=>h(u/4&1,u/2&1,u&1)|u/8;for(i=0;i<512;h``)f(f(f(i++)))

Try it online!
JavaScript (Node.js), 64 bytes
for(i=0;i<512;f(f(f(i++))))f=u=>console.log(u/4&1,u/2&1,u&1)|u/8

Try it online!
JavaScript (Node.js), 75 bytes
for(i=511;++i<1024;f(f(f(i))))f=u=>console.log(u.toString(2).slice(-3))|u/8

Try it online!

Perl 5, 48 bytes
say((sprintf"%09b",$_)=~s%...%$&$/%gr)for 0..511

Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Seven Slash Display
Write a program that takes in a non-empty string of the digits 0 through 9 and prints how they would be shown on a seven-segment display using slashes (/, \).
These are the precise digit shapes:
/\
\ \
 \/

 \
  \

/\
 /
 \/

/\
 /\
  /

 \
\/\

/
\/\
  /

/
\/\
 \/

/\
  \

/\
\/\
 \/

/\
\/\
  /

When one digit occurs after another, they are chained diagonally up and to the right, with a diagonal space in between. So, for example, 203 would become this:
    /\
     /\
  /\  /
  \ \
/\ \/
 /
 \/

Note that the 1 character takes up the same amount of space as the others. The two lines of the 1 are on the right side of the display, not the left.
So 159114 would become this:
           \
          \/\
         \
          \
       \
        \
    /\
    \/\
  /   /
  \/\
 \  /
  \

There may be any amount and combination of leading/trailing newlines or spaces in the output as long as the digits are in the correct position with respect to one another.
So for 159114, this would also be valid:

          \
         \/\
        \
         \
      \
       \
   /\
   \/\
 /   /
 \/\
\  /
 \

Take input from stdin or the command line, or write a function that takes in a string. Print the result to stdout or you can return it as a string if you write a function.
Any non-empty string of the digits 0 through 9 should work, including single digits strings (e.g. 8) and strings with leading zeros (e.g. in 007, the zeros do need to be printed).
The shortest code in bytes wins.

Totally offtopic: This looks awesome!

This is really really cool. However, I'm not sure kolmogorov-complexity is appropriate for this question - I thought that that required a constant output?

@alexander-brett iirc that was the original intention, however, more recently it's been used for problems where the majority of the code is probably going to be hardcoding.

This made me go like... WOW! just WOW!

Question: Do we need to handle empty strings or strings with non-digit characters?

@frederick No. The program can error or do anything else in those cases.

@Calvin'sHobbies Okay, thanks.

Now I'm curious if this task traces back to numwarp.b or if someone else just had the same idea. :)

@DanielCristofani No, I'm not sure what that is. (And this is hardly my first question involving slashes ;) )

Cool. Independent invention, then--numwarp.b is the brainfuck program I wrote to do this same thing.

[tag:language-request]  a language which is TC, but can only output like this.

CJam, 77 71 70 69 63 62 bytes
r_,5*_Sa*a*\{~"÷ÐëúÜ¾¿ðÿþ"=i2bS"\/"4*W<+.*3/..e>2fm>2m>}/Wf%N*

All characters are printable, so copy and paste should work just fine.
Try it online in the CJam interpreter.
Idea
We start by examining the number of digits n in the input and pushing a square of spaces big enough to cover the output. In the implementation, this square will be encoded as a two-dimensional array of one-character strings.
A square of length 2n+1 would be just right (i.e., no surrounding whitespace) for a straightforward implementation, but we'll use one of length 5n to save a couple of bytes. Thankfully, surrounding whitespace is allowed.
If we reverse the lines of the seven slash representation of 8, we obtain the following:
 \/
\/\
/\

The representation of all digits can be encoded as an 8-bit integer, where the ith bit is 0 iff the ith character should get replaced with a space. For the digits 0 to 9, the resulting integers are
247 208 235 250 220 190 191 240 255 254

which correspond to the following ISO-8559-1 characters:
÷ÐëúÜ¾¿ðÿþ

For each digit in the input, after selecting the corresponding 8-bit integer, we repeat the ith character of the representation of  8 exactly ai times, where ai is the ith bit of the integer. This pushes an array of strings of either one or zero characters. By dividing this array into chunks of length 3, we obtain an array where each element corresponds to a line of the representation.
Now, we compute the vectorized maximum of the strings that represent the square and the strings that represent the digit. The strings / and \ are bigger than the string  , so they will replace the spaces in the square. The empty string, however, is smaller than the string  , so empty strings in the digit representation will preserve the spaces in the square.
We now rotate the rows and columns by two units to place the following digit representation in the proper part of the square and repeat the process for the remaining digits in the input.
Finally, we reverse each row and insert a linefeed between the individual rows.
Code
r_,      e# Read a token from STDIN and push the length of a copy.
5*_      e# Multiply the length by 5 and push a copy.
Sa*      e# Repeat the array [" "] that many times.
a*       e# Repeat the array [[" " ... " "]] that many times.
\{       e# For each character C in the input:
  ~      e#   Push eval(C), i.e., the digit the character represents.

  "÷ÐëúÜ¾¿ðÿþ"

         e#   Push the encodings of all 10 seven slash representations.

  =      e#   Select the proper one.
  i2b    e#   Push the resulting characters code point in base 2, i.e., its bits.
  S      e#   Push " ".
  "\/"4* e#   Push "\/\/\/\/".
  +W<    e#   Concatenate and eliminate the last character.
  .*     e#   Vectorized repetition.

         e#   For the digit 5, e.g., we have [1 0 1 1 1 1 1 0] and  " \/\/\/\" on
         e#   the stack, so .* yields [" " "" "/" "\" "/" "\" "/" ""].

  3/     e#   Divide the representation into chunks of length 3, i.e., its lines.
  ..e>   e#   Compute the twofold vectorized maximum, as explained above.
  2fm>   e#   Rotate each line to characters to the right.
  2m>    e#   Rotate the lines two units down.
}/
Wf%      e# Reverse each line.
N*       e# Place linefeeds between them.

The last rotations would mess up the output if the square's side length was smaller than 2n+3. Since 5n ≥ 2n+3 for all positive integers n, the square is big enough to prevent this.

Would it be sensible to post here a base64 version of your code?

+1, but to be honest, I was hoping CJam et al. would sit this one out :p

@primo: I feel the same way about Pyth and math questions. :P I'm a little bit late to the party because I got nerd-sniped by Rearranging Words. It wasn't until your edit this morning that I remembered this question.

@Dennis challenges seem to go by a lot faster than they used to. I'm still working on one from two weeks ago :p

I always look for CJam first with the expectation that it will have the lowest byte count. I have yet to be disappointed.

Python 3, 189 183 174 bytes
s="a%sa"%input()
while s[1:]:b,a,c,d,e,f,g=[c*(ord(n)>>int(s[~(n>"Ͱ")],16)&1)or" "for c,n in zip("\/"*4,"ΟϭŅͭͱͼϻ")];S=len(s)*"  ";print(S+a+b,c+d+"\n"+S+e+f+g);*s,_=s

The compression looks okay to me, but I'm having trouble coming up with a good way of ditching the seven variables...
Thankfully the spec is fairly relaxed on whitespace rules, because there's a lot of leading/trailing whitespace.
Expanded:
s="a%sa"%input()
while s[1:]:
  b,a,c,d,e,f,g=[c*(ord(n)>>int(s[~(n>"Ͱ")],16)&1)or" "
                 for c,n in zip("\/"*4,"ΟϭŅͭͱͼϻ")]
  S=len(s)*"  "
  print(S+a+b,c+d+"\n"+S+e+f+g)
  *s,_=s

Explanation
The segment positions represented by the variables are:
    ab               /\
    efg               /\
  ab cd            /\  /
  efg              \ \
ab cd            /\ \/
efg               /
 cd               \/

Each segment is encoded by a single 2-byte Unicode character. For example, ϻ encodes g's segment like so:
bin(ord("ϻ")) = bin(1019) = "0b1111111011"
                               ^^^^^^^^^^
                               9876543210

Indeed, 2 is the only digit to not use the bottom-right segment of a seven-segment display.

C, 1098 345 323 319 bytes
First Second Third attempt. Finally decided to ditch the screen buffer to save a few bytes. This program takes a parameter of digits and prints the digits in 7-segment format.
First time participant. Just for fun. Be gentle.
a[]={100489,2056,98569,67849,2440,67969,100737,2057,100745,67977},i,j,k,n,m;char*c=" /\\";
#define f(q,r) for(q=0;q<(r);q++)
#define P(w) putchar(w)
#define Q(d,i,j) P(c[a[v[1][d]-48]>>(i*3+j)*2&3])
main(w,char**v){f(i,n=strlen(v[1]))f(k,(m=n-i-1)?2:3){f(j,m*2)P(32);f(w,3)Q(m,k,w);if(!k&&i)f(w,2)Q(m+1,2,w+1);P(10);}}

Expanded, warning free:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int a[]={100489,2056,98569,67849,2440,67969,100737,2057,100745,67977};
char *c=" /\\";
#define f(q,r) for(q=0;q<(r);q++)
#define P(w) putchar(w)
#define Q(d,i,j) P(c[a[v[1][d]-48]>>(i*3+j)*2&3])
int main(int w, char **v)
{
    int i,j,k,n,m;
    f(i,n=strlen(v[1])) {
        m=n-i-1;
        f(k,m?2:3) {
            f(j,m*2) P(32);
            f(w,3) Q(m,k,w);
            if (!k&&i) f(w,2) Q(m+1,2,w+1);
            P(10);
        }
    }
}

Fastest gun in the west. I'm compressing mine now.

Hey! Welcome to Code Golf. The purpose of this challenge is to make your code as short as possible, so you should make some optimizations in regards to removing spaces, shorting statements, etc, and then report your byte count at the top of your post with the language. Great first post though! Just for reference, your initial post is 1,098 bytes long.

Thanks. Just added the language and byte count. My original even has comments and Usage. :)

Tip: Change all variable names to single characters. Also, you use   for (i = 0; i < digits alot, perhaps replace it with a macro?

Good job here. To make your score more competitive, you could take a look at our tips for golfing in C.

You can also just remove as many spaces as possible.

Thanks for the suggestions. I tried my best to rewrite and compress. Still compiles to a.out if you don't mind the warnings. :)

@someuser Warning are disregarded, as long as it works as it should.

main(int w,char**v){ --> main(w,v)char**v;{

Thanks. Some how I thought I tried that and it didn't work. But indeed it works. And I was able to keep the "char**v" inside main unchanged. So I just removed "int " and saved 4 bytes.

JavaScript, 192 178 167 162 bytes
f=x=>{n=b="\n";for(k in x)for(i=0;i<8;)b+=("î\xA0Öô¸|~àþü".charCodeAt(x[k])>>i++&1?i%2?"/":"\\":" ")+(i%3?"":n+"  ".repeat(k));return b.split(n).reverse().join(n)}

Usage: f("1337"); will return
      /\
        \
    /\
     /\
  /\  /
   /\
 \  /
  \

It uses features of ES6 and may have some implementation dependent behavior due to omission of semicolons and parentheses and such, but it works in Firefox.
Expanded:
f=x=>
{
    n = b = "\n";

    for (k in x)
        for (i=0; i<8;)
            b += ("î\xA0Öô¸|~àþü".charCodeAt(x[k]) >> i++ & 1? i%2? "/" : "\\" : " ") + (i%3? "" : n+"  ".repeat(k));

    return b.split(n).reverse().join(n)
}

Explanation:
l is an array containing 10 single byte characters which correspond to the shape of each digit. For example, the digit 0 is represented by the character î:
/\        11
\ \  -->  101  --> 11 101 110 = î
 \/       011

The input characters are used as keys to the array holding their shape representing counterparts, which get read bit by bit.

Are ==0 and ==1 indeed necessary before ?. Aren't int considered as boolean in js? @Regret

@Regret : "w\x05k/\x1D>~\x07\x7F?" with each character bitwise reversed becomes "\xee\xa0\xd6\xf4\xb8|~\xe0\xfe\xfc" , each of these are printable. This gives 8 more bytes. Although, not enough...

You could shave 2 bytes off by removing the parenthesis in f=(x)=>{} -- they're not needed with only one argument.

You are absolutely right, @Alexey. I will change that.

Does it work? I get 6 more rows with spurious characters.

@edc65: Use a clean environment. If you just opened the console here on SE, the site JS interferes.

Perl - 103 Bytes
#!perl -n
print$i+$%2?U^(u,$i--%2?v9:z)[$i<4+$%2&vec$_,4*$-3-$i,1]:$/.!($i=$--)
while$+=2*y/0-9/wPkz\\>?p~/

The above contains 6 unprintable characters (the source can be downloaded at Ideone), and is equivalent to the following:
#!perl -n
print$i+$^F%2?U^(u,$i--%2?v9:z)[$i<4+$^F%2&vec$_,4*$^F-3-$i,1]:$/.!($i=$^F--)
while$^F+=2*y/0-9/wPkz\\>?p\177~/

Each ^F may be replaced by a literal character 6 (ACK), and \177 replaced by character 127 (DEL).
The shebang is counted as 1, the second newline is uncessary. Input is taken from stdin.

Sample Usage
$ echo 0123 | perl seven-slash.pl

      /\
       /\
    /\  /
     /
   \ \/
    \
/\
\ \
 \/

$ echo 456789 | perl seven-slash.pl

          /\
          \/\
        /\  /
        \/\
      /\ \/
        \
    /
    \/\
  /  \/
  \/\
 \  /
\/\

Explanation
Output is generated one byte at a time. Each character is transliterated, and this is then interpreted as a bit array using vec. The bits are stored in the following way:
   /\           56
   \/\          234
 /\ \/   ->   56 01
 \/\          234
  \/           01

Output alternates between 3 and 5 slashes, so that bits 56 spills over into 01 of the next digit. Bit 7 is not used.

C#, 360 355 331 bytes
Hi there, first attempt at code-golf. Hope this doesn't score too badly for a C#-entry.
string p(string n){var l=new string[n.Length*2+1];var i=l.Length-1;for(;i>0;){var x=@"/\\ \\/ \  \  /\ / \//\ /\ / \\/\  / \/\ // \/\\//\  \  /\\/\\//\\/\ /".Substring((n[0]-48)*7,7);for(var j=i-3;j>=0;){l[j--]+="  ";}l[i--]+=" "+x[5]+x[6];l[i--]+=""+x[2]+x[3]+x[4];l[i]+=""+x[0]+x[1];n=n.Remove(0, 1);}return string.Join("\n",l);}

Usage: p("159114"); will return
          \
         \/\
        \
         \
      \
       \
   /\
   \/\
 /   /
 \/\
\  /
 \

Expanded:
string p(string n)
    {
        var l = new string[n.Length * 2 + 1];
        var i = l.Length - 1;
        for (; i > 0; )
        {
            var x = @"/\\ \\/ \  \  /\ / \//\ /\ / \\/\  / \/\ // \/\\//\  \  /\\/\\//\\/\ /".Substring((n[0] - 48) * 7, 7);

            for (var j = i - 3; j >= 0; )
            {
                l[j--] += "  ";
            }
            l[i--] += " " + x[5] + x[6];
            l[i--] += "" + x[2] + x[3] + x[4];
            l[i] += "" + x[0] + x[1];

            n = n.Remove(0, 1);
        }

        return string.Join("\n", l);
    }

I know it's been almost three years, but you can golf 30 bytes: Try it online. 301 bytes. Nice answer though, +1 from me.

Cool. Feel free to post it as your own answer then :)

No, it's your code. I just shortened a bit by removing the for-loop brackets and combining variables. And changing string s(string n) to n=> by using a lambda. Ah well, you can just leave it like this if you prefer. :) I did create a port to Java crediting you however. ;)

python 2, 317 298 278 273.15
def f(s):
    r=range;n=len(s)*2;l=[[' ']*-~n for x in r(-~n)]
    for x in r(0,n,2):
        for i,[d,y,c]in enumerate(zip('0112012','1021012',r'\\\\///')):l[n-2-x+int(y)][x+int(d)]=[' ',c][('%7s'%(bin(ord('}(7/jO_,\x7fo'[map(int,s)[x/2]])))[2:])[i]=='1']
    for x in l:print''.join(x)

I considered 4-spaces as tabs while counting.
Uncompressed and readable:
def f(s):
    r=['1111101','0101000','0110111','0101111','1101010','1001111','1011111','0101100','1111111','1101111']
    ''.join(map(lambda x:chr(eval('0b'+x)),r))
    n=len(s)*2
    l=[[' ']*(n+1) for x in xrange(n+1)]
    shifts=[(0,1,'\\'),(1,0,'\\'),(1,2,'\\'),(2,1,'\\'),(0,0,'/'),(1,1,'/'),(2,2,'/')]
    for x in xrange(0,n,2):
        y=n-2-x
        for i,[dx,dy,c] in enumerate(shifts):
            l[y+dy][x+dx]=c if r[map(int,s)[x/2]][i]=='1' else ' '
    return '\n'.join(''.join(x) for x in l)

Hey! Great answer, but you can make a few changes to get it even shorter. Changing l[y+dy][x+dx]=c if r[map(int,s)[x/2]][i]=='1' else ' ' to l[y+dy][x+dx]=[' ',c][r[map(int,s)[x/2]][i]=='1'] saves 5 bytes, changing return '\n'.join(''.join(x) for x in l) to print'\n'.join(''.join(x)for x in l) saves 3 bytes, plus a few more changes. Here's a link to a Gist where I got the byte count down to 440 from 508.

Too early :) but I appreciate your comments and will change the resulting code resp.

@Vioz- : Now too late :) Thanks for your comments. :)

Kelvin would have been very pleased with that score.

Your answer is actually 272 bytes, but you can save one more because a space is shorter than a tab. See here. How could you have 273.15 bytes anyway?

273.15 bytes means @AlexeyBurdin figured out analog computing on a digital platform. Why in the world did you publish it here, instead of in Science? ;-)

This means only that the solution is frozen at absolute zero, i.e. I don't want to focus on a thing that has already lost. :)

KDB(Q), 172 136 bytes
{d:(9#1 2 0 2)*/:-9#'0b vs'427 136 403 409 184 313 315 392 443 441;
 -1" /\\"{m+(c,/:y),c:(count[m:0 0,x,\:0 0]-3)#0}/[3 3#/:d"J"$'(),x];}

Explanation
1) Create d map with all the digits' shapes.
2) Pad the matrix with extra zeros and add them together. i.e. "01"
0           0 0 0 2 0
0           0 0 0 0 2
1 2 0 0 0 + 0 0 0 0 0
2 0 2 0 0   0
0 2 1 0 0   0

3) Use the index to map " /\" and print with -1.
Test
q){d:(9#1 2 0 2)*/:-9#'0b vs'427 136 403 409 184 313 315 392 443 441;-1" /\\"{m+(c,/:y),c:(count[m:0 0,x,\:0 0]-3)#0}/[3 3#/:d"J"$'(),x];}"0123456789"
                  /\
                  \/\
                /\  /
                \/\
              /\ \/
                \
            /
            \/\
          /  \/
          \/\
         \  /
        \/\
      /\
       /\
    /\  /
     /
   \ \/
    \
/\
\ \
 \/

I'm sure this can be shorter!!
Thanks @h.j.k.

The only reduction I spotted is to replace 1 2 0 2 1 2 0 2 1 with (9#1 2 0 2) (-6).

Oh, and replacing enlist with 1# works, so that's another -5.

you are a star! I'll update! but cant replace the enlist though because count[a 0]#0 is not atom :(

ah strange it worked for me though... must be a quirk. ;)

actually, list plus atom will extend the atom to the correct length anyway! you reminded me such mechanism! :D

Pip, 122 + 1 = 123 bytes
Uses the -n flag. Takes input via command-line argument.
l:$.(J"\/ "@^(A_TB3M"⮐䫶ヷ㄃䓳ⴷⴥㅕ⬿⭑")@_.2<>2Ma)z:2*#ap:sXz+2RLz+2Fi,5Fj,z{c:[4-ii]//2+j(pc@0c@1):(lij)}RVp

The characters in the UTF-8 string have the following code points: 11152, 19190, 12535, 12547, 17651, 11575, 11557, 12629, 11071, 11089.
Slightly ungolfed:
t:[120022001 222022202 122012021 122012201 220012202 120212201 120212001 122022202 120012001 120012201]
l:$.({J"\/ "@^t@a.2<>2}Ma)
z:2*#a+2
p:sXzRLz
Fi,5
 Fj,2*#a {
  x:i//2+j
  y:(4-i)//2+j
  p@y@x:l@i@j
 }
P RVp

The basic strategy is to find each number's constituent characters and then skew them appropriately. For example, for 8, we want this (spaces represented by dots):
/.
\\
/.
\\
/.

which will turn into this:
 .
/\.
\/\.
 \/

The nice feature of this strategy is that multiple pre-skewed numbers can simply be concatenated side by side.
Now, we can encode /.\\/.\\/. in base 3 as 1200120012. Then we can convert this to decimal and treat it as a UTF-8 code point.
The expression J"\/ "@^(A_TB3M"⮐䫶ヷ㄃䓳ⴷⴥㅕ⬿⭑")@_.2<>2Ma gets the pre-skewed data by the following process:
                            Ma   Map this lambda function to each character in input:
        (A_TB3M"...")            Create list of the code points of each character in UTF-8
                                   string, converted to base 3
                     @_          Index into that list using the input character
                       .2        Concatenate 2 to the end of the base-3 value (all of the
                                   pre-skewed number grids end in 2, i.e. space)
       ^                         Split the number into a list of its digits
 "\/ "@                          Index into this string with those digits, giving a list
                                   of slashes & spaces
J                                Join the list together into a string
                         <>2     Group string two characters at a time

Once we have concatenated these strings side-by-side using $., we then create a grid of spaces (2*n+2 square), loop through the pre-skewed grid, and replace the corresponding spaces in the post-skewed grid with the appropriate characters. To see it happening, one can modify the code to print each stage and pause for user input:

The grid is actually built upside down, because that seemed to make the math easier.
I'm sure there's better algorithms to use. But I wanted to come up with my own idea rather than copying somebody else's.
More on Pip

Brainfuck - 719 bytes
For historical context only, credits to Daniel B Cristofani. I'm not exactly sure when this was created, but it is available from the Internet Archive as early as May 9th, 2003.
The output for 9 is different than in the problem description.
>>>>+>+++>+++>>>>>+++[
  >,+>++++[>++++<-]>[<<[-[->]]>[<]>-]<<[
    >+>+>>+>+[<<<<]<+>>[+<]<[>]>+[[>>>]>>+[<<<<]>-]+<+>>>-[
      <<+[>]>>+<<<+<+<--------[
        <<-<<+[>]>+<<-<<-[
          <<<+<-[>>]<-<-<<<-<----[
            <<<->>>>+<-[
              <<<+[>]>+<<+<-<-[
                <<+<-<+[>>]<+<<<<+<-[
                  <<-[>]>>-<<<-<-<-[
                    <<<+<-[>>]<+<<<+<+<-[
                      <<<<+[>]<-<<-[
                        <<+[>]>>-<<<<-<-[
                          >>>>>+<-<<<+<-[
                            >>+<<-[
                              <<-<-[>]>+<<-<-<-[
                                <<+<+[>]<+<+<-[
                                  >>-<-<-[
                                    <<-[>]<+<++++[<-------->-]++<[
                                      <<+[>]>>-<-<<<<-[
                                        <<-<<->>>>-[
                                          <<<<+[>]>+<<<<-[
                                            <<+<<-[>>]<+<<<<<-[
                                              >>>>-<<<-<-
  ]]]]]]]]]]]]]]]]]]]]]]>[>[[[<<<<]>+>>[>>>>>]<-]<]>>>+>>>>>>>+>]<
]<[-]<<<<<<<++<+++<+++[
  [>]>>>>>>++++++++[<<++++>++++++>-]<-<<[-[<+>>.<-]]<<<<[
    -[-[>+<-]>]>>>>>[.[>]]<<[<+>-]>>>[<<++[<+>--]>>-]
    <<[->+<[<++>-]]<<<[<+>-]<<<<
  ]>>+>>>--[<+>---]<.>>[[-]<<]<
]
[Enter a number using ()-./0123456789abcdef and space, and hit return.
Daniel B Cristofani (cristofdathevanetdotcom)
http://www.hevanet.com/cristofd/brainfuck/]

I probably wrote it in 2002. The Internet Archive says Panu Kalliokoski added it to his brainfuck repository in August 2002. As for the 9, I think I used the patterns from the second edition of Microprocessors and Interfacing, page 4.

Perl, 270 bytes
I really shouldn't have wasted my time on this.
$e="\\";$g=" ";$_=reverse<>;$l=length;push@a,(119,18,107,91,30,93,125,19,127,95)[$1]while/(.)/g;for($i=0;$i<=$l;$i++){$j=2*($l-$i);$b=$a[$i];$c=$i&&$a[$i-1];print" "x$j,$b&1?"/":$g,$b&2?$e:$g,$g,$c&32?$e:$g,$c&64?"/":$g,"
"," "x$j,$b&4?$e:$g,$b&8?"/":$g,$b&16?$e:$g,"
"}

replace [$1]while/(.)/g with [$_]for/./g to save 4 bytes.
replace for($i=0;$i<=$l;$i++) with for$i(0..$l) to save 9 bytes.

JavaScript (ES6), 191 206
Run snippet in Firefox to test.

F=m=>(
  a='    \\/  /\\/\\ /  /\\  \\\\ \\'.match(/.../g),
  o=f='',r=' ',
  [for(d of m)(
    n=1e3+'¯B\x91ÿ$ê\x86A\x87ë'.charCodeAt(d)+'', // here there are 3 valid characters tha the evil stackoverflow editor just erase off, so I had to put them as hex escape
    o='\n'+f+' '+a[n[2]]+'\n'+r+a[n[1]]+o,
    r=f+a[n[3]],
    f+='  ')],
  r+o
)

//TEST

go=_=>O.innerHTML =(v=I.value)+'\n'+F(v)

go()
<input id=I value='0123456789'><button onclick='go()'>-></button>
<pre id=O></pre>

JavaScript (Node.js),  149  146 bytes
Contains a few unprintable characters which are escaped in the code below.
s=>(g=([d,...s],p='',q=p)=>d?g(s,p+q,88)+(p+=q?`10 65
${p}234
`:865).replace(/\d/g,n=>'\\/ '[Buffer("w\x11k;\x1d>~\x13\x7f?")[n>4?s[0]:d]>>n&1?n&1:2]):s)(0+s)

Try it online!
How?
This recursively builds the following pattern (here with 4 digits):
88888810 65
888888234
888810 65
8888234
8810 65
88234
10 65
234
865

Where:

\$8\$ is a padding character
other even digits are replaced with either \ or a space
odd digits are replaced with either / or a space

Leading to:
______/\ \/
______\/\
____/\ \/
____\/\
__/\ \/
__\/\
/\ \/
\/\
_\/

Java 8, 341 bytes
n->{int i=n.length*2,j=i+1,k=0,t;String l[]=new String[j],x;for(;j-->0;l[j]="");for(;i>0;l[i--]+=" "+x.substring(5,7),l[i--]+=x.substring(2,5),l[i]+=x.substring(0,2))for(x="/~~ ~~/ ~  ~  /~ / ~//~ /~ / ~~/~  / ~/~ // ~/~~//~  ~  /~~/~~//~~/~ /".replace('~','\\').substring(t=(n[k++]-48)*7,t+7),j=i-2;j-->0;)l[j]+="  ";return"".join("\n",l);}

Port of @Shion's C# .NET answer, so make sure to upvote him as well!
Try it online.
Explanation:
n->{                       // Method with character-array parameter and String return-type
  int i=n.length*2,        //  Two times the length of the input array
      j=i+1,               //  Index integer, starting at `i+1`
      k=0,t;               //  Temp integers
  String l[]=new String[j],//  String-array for the rows, default filled with `null`
         x;                //  Temp-String
  for(;j-->0;l[j]="");     //  Replace all `null` with empty Strings
  for(;i>0                 //  Loop `i` downwards in the range [`n.length*2`, 0)
      ;                    //   After every iteration:
       l[i--]+=            //    Append the row at index `i` with:
                           //    (and decrease `i` by 1 afterwards with `i--`)
         " "               //     A space
         +x.substring(5,7),//     And the 6th and 7th characters of temp-String `x`
       l[i--]+=            //    Append the row at index `i` with:
                           //    (and decrease `i` by 1 afterwards with `i--`)
         x.substring(2,5), //     The 3rd, 4th and 5th characters of temp-String `x`
       l[i]+=              //    Append the row at index `i` with:
         x.substring(0,2)) //     The 1st and 2nd characters of the temp-String `x`
    for(x="/~~ ~~/ ~  ~  /~ / ~//~ /~ / ~~/~  / ~/~ // ~/~~//~  ~  /~~/~~//~~/~ /".replace('~','\\')
                           //   String containing all digit-parts
          .substring(t=(n[k++]-48)*7,t+7),
                           //   and take the substring of 7 characters at index
                           //   `n[k]` as integer multiplied by 7
        j=i-2;j-->0;)      //   Inner loop `j` in the range (`i`-2, 0]
      l[j]+="  ";          //    And append the rows at index `j` with two spaces
  return"".join("\n",l);}  //  Return the rows delimited with new-lines

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


text:
Worst Case Manhattan Exclusion
Imagine a W by H grid of squares that wraps toroidally. Items are placed onto the grid as follows.
The first item can be placed on any square, but subsequent items must not be within a Manhattan distance R of any previous item (also known as a Von Neumann neighbourhood of range R). Carefully choosing the positions allows fitting a large number of items onto the grid before there are no more valid positions. However, instead consider the opposite aim: What is the lowest number of items that can be placed and leave no further valid positions?
Here is a radius 5 exclusion zone:

Here is another radius 5 exclusion zone, this time near the edges so the wrapping behaviour is apparent:

Input
Three integers:

W: width of grid (positive integer)
H: height of grid (positive integer)
R: radius of exclusion zone (non-negative integer)

Output
An integer N, which is the smallest number of items that can be placed preventing any further valid placements.
Details

A radius of zero gives an exclusion zone of 1 square (the one the item was placed on).
A radius of N excludes the zone that can be reached in N orthogonal steps (remember the edges wrap toroidally).

Your code must work for the trivial case of R = 0, but does not need to work for W = 0 or H = 0.
Your code must also deal with the case where R > W or R > H.
Time limit and test cases
Your code must be able to deal with all of the test cases, and each test case must complete within 5 minutes. This should be easy (the example JavaScript solution takes a few seconds for each test case). The time limit is mainly to exclude the extreme brute force approach. The example approach is still fairly brute force.
If your code completes within 5 minutes on one machine but not on another that will be close enough.
Test cases in the form inputs: output as W H R : N
5 4 4 : 1
5 4 3 : 2
5 4 2 : 2
5 4 1 : 5

7 5 5 : 1
7 5 4 : 2
7 5 3 : 2
7 5 2 : 4

8 8 8 : 1
8 8 7 : 2
8 8 6 : 2
8 8 5 : 2
8 8 4 : 2
8 8 3 : 4

 7  6  4 : 2
 7  6  2 : 4
11  7  4 : 3
11  9  4 : 4
13 13  6 : 3
11 11  5 : 3
15 14  7 : 2
16 16  8 : 2

Snippet to help visualise and play around with ideas

canvas = document.getElementById('gridCanvas');ctx = canvas.getContext('2d');widthSelector = document.getElementById('width');heightSelector = document.getElementById('height');radiusSelector = document.getElementById('radius');itemCount = document.getElementById('itemCount');canvasMaxWidth = canvas.width;canvasMaxHeight = canvas.height;gridlineColour = '#888';emptyColour = '#ddd';itemColour = '#420';hoverCellColour = '#840';exclusionColour = '#d22';validColour = '#8f7';invalidColour = '#fbb';overlapColour = '#600';resetGrid();x = -1;y = -1;function resetGrid() {gridWidth = widthSelector.value;gridHeight = heightSelector.value;radius = radiusSelector.value;numberOfItems = 0;itemCount.value = numberOfItems + ' items placed.';cells = [gridWidth * gridHeight];for (i=0; i<gridWidth*gridHeight; i++) {cells[i] = '#ddd';}cellSize = Math.min(Math.floor(canvasMaxWidth/gridWidth), Math.floor(canvasMaxHeight/gridHeight));pixelWidth = gridWidth * cellSize + 1;canvas.width = pixelWidth;pixelHeight = gridHeight * cellSize + 1;canvas.height = pixelHeight;leaveCanvas();}function checkPosition(event) {bound = canvas.getBoundingClientRect();canvasX = event.clientX - bound.left;canvasY = event.clientY - bound.top;newX = Math.min(Math.floor(canvasX / cellSize), gridWidth-1);newY = Math.min(Math.floor(canvasY / cellSize), gridHeight-1);if (newX != x || newY != y) {x = newX;y = newY;drawGrid();}}function leaveCanvas() {x = -1;y = -1;drawGrid();}function drawGrid() {ctx.fillStyle = gridlineColour;ctx.fillRect(0, 0, pixelWidth, pixelHeight);cellColour = cells[x + gridWidth * y];if (cellColour == itemColour || cellColour == exclusionColour) {zoneColour = invalidColour;} else {zoneColour = validColour;}for (gridX=0; gridX<gridWidth; gridX++) {for (gridY=0; gridY<gridHeight; gridY++) {colour = (cells[gridX + gridWidth * gridY]);if (x >= 0 && y >= 0) {if (x == gridX && y == gridY) {colour = hoverCellColour;} else if (manhattanDistance(x, y, gridX, gridY) <= radius) {if (colour == exclusionColour) {colour = overlapColour;} else if (colour != itemColour) {colour = zoneColour;}}}ctx.fillStyle = colour;ctx.fillRect(gridX * cellSize + 1, gridY * cellSize + 1, cellSize - 1, cellSize - 1);}}}function manhattanDistance(a, b, c, d) {horizontal = Math.min(Math.abs((gridWidth + c - a) % gridWidth), Math.abs((gridWidth + a - c) % gridWidth));vertical = Math.min(Math.abs((gridHeight + d - b) % gridHeight), Math.abs((gridHeight + b - d) % gridHeight));return vertical + horizontal;}function placeItem(event) {bound = canvas.getBoundingClientRect();canvasX = event.clientX - bound.left;canvasY = event.clientY - bound.top;attemptX = Math.min(Math.floor(canvasX / cellSize), gridWidth-1);attemptY = Math.min(Math.floor(canvasY / cellSize), gridHeight-1);colour = cells[attemptX + gridWidth * attemptY];if (colour != itemColour && colour != exclusionColour) {for (a=0; a<gridWidth; a++) {for (b=0; b<gridHeight; b++) {if (manhattanDistance(a, b, attemptX, attemptY) <= radius) {cells[a + gridWidth * b] = exclusionColour;}}}cells[attemptX + gridWidth * attemptY] = itemColour;drawGrid();numberOfItems++;itemCount.value = numberOfItems + ' items placed.';}}
<canvas id='gridCanvas' width='500' height='300' style='border:none' onmousemove='checkPosition(event)' onmouseleave='leaveCanvas()' onclick='placeItem(event)'></canvas>
<textarea id='itemCount' readonly></textarea>
<button id='reset' onclick='resetGrid()'>Reset</button> with the following values:
Width:<input id='width' type='number' value='20' min='1' max='50' maxlength='2' step='1'>
Height:<input id='height' type='number' value='13' min='1' max='30' maxlength='2' step='1'>
Radius:<input id='radius' type='number' value='5' min='0' max='60' maxlength='2' step='1'>

Example (ungolfed) solution
Just an example for small outputs (resulting from radius not much smaller than the width and height). Can handle any of the test cases but will time out and give up for most larger cases.

itemCount = document.getElementById('itemCount')
calculateButton = document.getElementById('calculate')
widthSelector = document.getElementById('width')
heightSelector = document.getElementById('height')
radiusSelector = document.getElementById('radius')

function calculate() {
    calculateButton.disabled = true
    widthSelector.disabled = true
    heightSelector.disabled = true
    radiusSelector.disabled = true
    itemCount.value = 'Calculating...'
    setTimeout(delayedCalculate, 100)
}

function delayedCalculate() {
    gridWidth = widthSelector.value
    gridHeight = heightSelector.value
    radius = radiusSelector.value
    startingMin = gridWidth*gridHeight + 1
    var cells = [gridWidth * gridHeight]
    for (i=0; i<gridWidth*gridHeight; i++) {
        cells[i] = 0
    }
    var gridState = gridWithItemAdded(cells, 0, 0)
    var minimum = minFromHere(gridState) + 1
    itemCount.value = 'Minimum ' + minimum + ' items required.'
    calculateButton.disabled = false
    widthSelector.disabled = false
    heightSelector.disabled = false
    radiusSelector.disabled = false
}

function minFromHere(gridState) {
    var x
    var y
    var newGridState
    var noCells = true
    var min = startingMin
    for (x=0; x<gridWidth; x++) {
        for (y=0; y<gridHeight; y++) {
            if (gridState[x + gridWidth * y] == 0) {
                noCells = false
                newGridState = gridWithItemAdded(gridState, x, y)
                m = minFromHere(newGridState)
                if (m < min) {
                    min = m
                }
            }
        }
    }
    if (noCells) return 0
    return min + 1
}

function gridWithItemAdded(gridState, x, y) {
    var a
    var b
    var grid = gridState.slice()
    for (a=0; a<gridWidth; a++) {
        for (b=0; b<gridHeight; b++) {
            if (manhattanDistance(a, b, x, y) <= radius) {
                grid[a + gridWidth * b] = 1
            }
        }
    }
    return grid
}

function manhattanDistance(a, b, c, d) {
    horizontal = Math.min(Math.abs((gridWidth + c - a) % gridWidth), Math.abs((gridWidth + a - c) % gridWidth))
    vertical = Math.min(Math.abs((gridHeight + d - b) % gridHeight), Math.abs((gridHeight + b - d) % gridHeight))
    return vertical + horizontal
}
<textarea id='itemCount' readonly></textarea>

<button id='calculate' onclick='calculate()'>Calculate</button> with the following values:

Width:<input id='width' type='number' value='5' min='1' max='50' maxlength='2' step='1'>

Height:<input id='height' type='number' value='4' min='1' max='30' maxlength='2' step='1'>

Radius:<input id='radius' type='number' value='1' min='0' max='60' maxlength='2' step='1'>

Awesome code snippet!

@StretchManiac thanks :) I'm trying to learn JavaScript so any feedback is welcome

That is a pretty nice snippet. I like that color scheme too. Is it from a palette?

@miles thank you - the colours are just guessed and then fine tuned a bit (but not much - they are still all 3 character colour codes rather than 6). You can see the colours used in the third block of lines in the snippet code.

Python 2, 216 182 bytes
def f(W,H,R):L={(i%W,i/W)for i in range(W*H)};M={(x,y)for x,y in L if min(x,W-x)+min(y,H-y)>R};g=lambda s:min([1+g(s-{((a+x)%W,(b+y)%H)for x,y in L-M})for a,b in s]or[1]);return g(M)

Input like f(16,16,8). Uses pretty much the same algorithm as @trichoplax's sample, but with sets. Initially I didn't place the first item at (0, 0), but this made it choke on the last few cases.
All cases above complete within 10 seconds, well under the limit. In fact, the cases are small enough that I had a little room to be less efficient, allowing me to remove a check which checked for duplicate states.
(Thanks to @trichoplax for golfing help)
Expanded:
def f(W,H,R):
  # All cells
  L={(i%W,i/W)for i in range(W*H)}

  # Mask: Complement of exclusion zone around (0, 0)
  M={(x,y)for x,y in L if min(x,W-x)+min(y,H-y)>R}

  # Place recursively
  g=lambda s:min([1+g(s-{((a+x)%W,(b+y)%H)for x,y in L-M})for a,b in s]or[1])
  return g(M)

Python 3, 270 262 260 251 246 226
(Thanks to Sp3000 for:

-~ instead of +1, which lets me lose a space after return on the last line.
losing superfluous parentheses around W*H.
lambdas...
putting everything on one line.
python modulo % gives positive result for negative numbers, to save another 20 bytes)

This is the JavaScript example answer from the question ported into Python 3.
To avoid having to pass so many function arguments around, I've moved the two supporting functions inside the calculate function so that they share its scope. I've also condensed each of these functions into a single line to avoid the cost of indentation.
Explanation
This fairly brute force approach places the first item at (0, 0), and then marks all the excluded squares. It then recursively places an item at all remaining valid squares until all squares are excluded, and returns the minimum number of items required.
Golfed code:
def C(W,H,R):r=range;M=lambda g:min([M(G(g,x,y))for x in r(W)for y in r(H)if g[x+W*y]]or[-1])+1;G=lambda g,x,y:[g[a+W*b]if min((x-a)%W,(a-x)%W)+min((y-b)%H,(b-y)%H)>R else 0for b in r(H)for a in r(W)];return-~M(G([1]*W*H,0,0))

Ungolfed code:
def calculate(W, H, R):
    starting_min = W * H + 1
    cells = [0] * (W * H)
    grid_state = grid_with_item_added(cells, 0, 0, W, H, R)
    return min_from_here(grid_state, starting_min, W, H, R) + 1

def min_from_here(grid_state, starting_min, W, H, R):
    no_cells = True
    min = starting_min
    for x in range(W):
        for y in range(H):
            if grid_state[x + W * y] == 0:
                no_cells = False
                new_grid_state = grid_with_item_added(grid_state, x, y, W, H, R)
                m = min_from_here(new_grid_state, starting_min, W, H, R)
                if m < min:
                    min = m

    if no_cells:
        return 0
    else:
        return min + 1

def grid_with_item_added(grid_state, x, y, W, H, R):
    grid = grid_state[:]
    for a in range(W):
        for b in range(H):
            if manhattan_distance(a, b, x, y, W, H) <= R:
                grid[a + W * b] = 1

    return grid

def manhattan_distance(a, b, c, d, W, H):
    horizontal = min(abs(W + c - a) % W, abs(W + a - c) % W)
    vertical = min(abs(H + d - b) % H, abs(H + b - d) % H)
    return horizontal + vertical

if __name__ == '__main__':
    import sys
    arguments = sys.argv[1:]
    if len(arguments) < 3:
        print('3 arguments required: width, height and radius')
    else:
        print(calculate(int(arguments[0]), int(arguments[1]), int(arguments[2])))

The ungolfed code defines a function and also includes code to allow it to be called from the command line. The golfed code just defines the function, which is sufficient for standard code golf questions.
If you would like to test the golfed code from the command line, here it is with the command line handling included (but not golfed):
Command line testable golfed code
def C(W,H,R):r=range;M=lambda g:min([M(G(g,x,y))for x in r(W)for y in r(H)if g[x+W*y]]or[-1])+1;G=lambda g,x,y:[g[a+W*b]if min((x-a)%W,(a-x)%W)+min((y-b)%H,(b-y)%H)>R else 0for b in r(H)for a in r(W)];return-~M(G([1]*W*H,0,0))

if __name__ == '__main__':
    import sys
    arguments = sys.argv[1:]
    if len(arguments) < 3:
        print('3 arguments required: width, height and radius')
    else:
        print(C(int(arguments[0]), int(arguments[1]), int(arguments[2])))


text:
Compute minimal string segment sizes
A common optimization to save space in binaries is to merge string literals where one literal is the suffix of another. For instance, a binary with the string literals
a: foobar
b: bar
c: barbaz
d: foobarbaz
e: baz

might contain the following string literal pool (# representing the \0-terminator):
foobar#foobarbaz#

with the symbols a, b, c, and d having the following values relative to the beginning of the string pool:
a:  0
b:  3
c: 10
d:  7
e: 13

In this task, you have to compute the minimal size of a string pool for a given set of input strings.
Input
The input is a series of up to 999 strings each comprising up to 80 ASCII characters (not including the newline) in the range from 32 to 127 inclusive and then a single newline character.
Output
Find the shortest string such that each of the input strings (including the terminating newlines) are substrings of that string. The output shall be the length of that shortest string. Do not output the string, only its length.
Scoring
This challenge is code golf, standard loopholes apply. The solution with the least length in octets wins.
Examples

Input:
foobar
bar
barbaz
foobarbaz
baz

shortest string, # representing newline:
foobar#foobarbaz#

length: 17
Input:
foobar
foobaz
foobarbaz
barbaz

shortest string, # representing newline:
foobar#foobaz#foobarbaz#

length: 24

And 80-character test case would be good. Also, is there any difference between "octet" and "byte"? Otherwise I'm not sure what the benefit of using the obscurer term is.

@MartinBüttner On some machines, a byte has more or less than 8 bits (cf. Knuth's MIX). Octet is the standard word to refer to an 8 bit quantity, byte refers to the least addressable unit of the particular machine you're working on. The 80 character limit is just there so people can work with fixed arrays and so I can't say “this is invalid because it breaks with very long input.”

Are all input strings pairwise distinct?

@AlexeyBurdin No.

Pyth, 20 18 bytes
hljb-{.zsmteM./d.z

Demonstration.
{ can be removed if duplicates are not allowed.
Explanation:
hljb-{.zsmteM./d.z
                .z     The input, as a list of strings.
         m             Map each strings to
             ./d       all possible partitions of the string into separate strings.
           eM          take the last element of each, giving all suffixes.
          t            Remove the first suffix, giving all suffixes other than
                       the string itself.
        s              Sum, combining the list of lists into a single list.
    -{.z               From the set of input strings, remove all suffixes.
                       This is the list of strings in the minimal segment.
  jb                   Join the strings together on newlines.
 l                     Take the length of the resulting string.
h                      Add one and print.

CJam, 22 bytes
qN%_&Nf+:G{Gs\/,3<},s,

Try it online.
How it works
qN%   e# Split the input from STDIN at linefeeds, discarding the last, empty chunk.
_&    e# Intersect the array with itself to remove duplicates.
Nf+   e# Append a linefeed to each chunk.
:G    e# Save the result in G.
{     e# Filter; for each chunk in G:
  Gs  e#   Flatten the array of strings G.
  \/  e#   Split at occurrences of G.
  ,3< e#   Compare the resulting number of chunks with 3.
},    e#   Keep the chunk iff the comparision pushed 1 (true).
s,    e# Flatten the resulting array of strings and push the result's length.

python 2, 132
Just to start a race:
def f(s):
    l=set(s.split('\n'))
    for x in l:
        for y in l:
            if x!=y and x.endswith(y):l.remove(y)
    return sum(len(x)+1 for x in l)

It works:
>>> f(r'''foobar
foobaz
foobarbaz
barbaz''')
24
>>> f(r'''foobar
bar
barbaz
foobarbaz
baz
''')
17

Haskell, 101 85 bytes
import Data.List
length.unlines.(\l->[x|x<-nub l,x`notElem`((tails.tail)=<<l)]).lines

A function without a name. Usage example:
*Main>  length.unlines.(\l->[x|x<-nub l,x`notElem`((tails.tail)=<<l)]).lines $ "foobar\nbar\nfoobaz"
14

How it works: split input string at newlines. Remove duplicates from the  word list l. Keep a word x from the remaining list if it's not in the list of all tails of the words of l. Join those x with newlines in-between (and at the end!) to a single string and count it's length.


text:
Help me carry my shopping bags
It was a warm summer evening...
when my stupid car decided to break down in the middle of the road on my way back from the supermarket. I pushed it to the sideline and decided to walk home. I opened the trunk to take out the grocery and remaining stuff. It was then that I noticed the items were not evenly bagged. Some bags had more heavy items while others had few lighter stuff - some even had a mix of such items. To make it easy for me to carry, I decided to group everything in to two bags and make their weights as close to each other as possible.

Your goal
is to help me rearrange the items in to two shopping bags in such a way that the difference between both bags is close to zero as possible.
Mathematically:

WEIGHT LEFT HAND —  WEIGHT RIGHT HAND ≈ 0

Example
If I had only 2 items, Bread and Peanut butter, and the weight of bread is 250 grams and peanut butter is 150 grams, the best way is to carry them separately in two hands.

WLH - WRH = W(BREAD) - W(P.BUTTER)
250 - 150 = 100

The other possibility is :

W(BREAD, P.BUTTER) - W(empty hand) = (250 + 150) - 0 = 400

This is not better than our first case, so you should go with the first one.
Your code should

take inputs of numbers indicating weights of items in the shopping bag. Units are not important, but they should be the same (ideally kilograms or grams). Input can be done one by one or all at once. You may restrict the total count to 20 items max, if you want.
The input format/type is up to you to choose, but nothing else should be present other than the weights.
Any language is allowed, but stick to standard libraries.
Display output. Again, you're free to choose the format, but explain the format in your post. ie, how can we tell which ones are left hand items and which ones are right hand items.

Points

Shortest code wins.

Hint

The two possible algorithms that I could think of are differentiation (faster) and permutations/combinations (slower). You may use these or any other algorithm that does the job.

I like rule 2, it's flexible but does not allow cheating

You've basically reinvented the knapsack problem. https://en.wikipedia.org/wiki/Knapsack_problem

Thank you @Sparr I am wicked smaat (not really)

This problem is far too practical and realistic for this site.

Pyth, 9 bytes
ehc2osNyQ

Input, output formats:
Input:
[1, 2, 3, 4, 5]
Output:
[1, 2, 4]

Demonstration.
ehc2osNyQ
             Q = eval(input())
       yQ    Take all subsets of Q.
    osN      Order those element lists by their sums.
  c2         Cut the list in half.
eh           Take the last element of the first half.

This works because y returns the subsets in such an order that each subset and its complement are equidistant fom the center. Since the sum of a subset and the sum of its complement will always be equidistant from the center, the list after osNyQ will also have this property. Thus, the center two elements of osNyQ are complements, and must have an optimal split. We extract the first of those two elements and print it.

The answer by the OP only prints the bags in one hand, so congrats on your 9 byte solution.

Your write is bugged for input [7 7 7 10 11] Traceback (most recent call last):
File "pyth.py", line 772, in
File "", line 4, in
File "/app/macros.py", line 865, in order
TypeError: unorderable types: int() < list()

@RosLuP This worked at the time, I changed something about s that made it stop working. People didn't like the change, and your comment was the final push I needed to change it back.

In the commented code it should not be "subset of Q" but "sublist of Q"

@RosLuP I disagree - a sublist is typically contiguous. Subset and subsequence are two terms for this kind of thing.

[1,2,2] can not be a subset of [1,2,2,3] because both are not a set...they are both list (or array or vector) instead. [1,2,2,3] can be one valid input, and it is not a set (because there is the element 2 two times) it is a list or one vector or one array

@RosLuP In that case, think of it as a the elements at a subset of the indices, which I refer to as a subset of the elements, as opposed to the concept you are describing, a subset of the values.

Pyth, 16
ho.a-FsMNs./M.pQ

This takes the inputs as a pythonic list on STDIN. The output is a list of 2 lists with the first list being the items in one bag, and the second list representing the items in the second bag. This brute forces all combinations, so it will run very slowly (or run out of memory) for large inputs.
Try it online here
To support the handling of just one input, this goes up to 17:
hho.a-FsMNs./M.pQ

This will print the values that go in one hand.

This is a very impressive solution - it's not obvious at all that it won't give faulty answers like [[2], [1], [1]], but I think it works, due to exactly how ./ works.

Actually, I think this fails on cases where everything goes in one hand, like when there's only 1 object.

@isaacg I had kind of assumed 1 object wasn't valid, as you clearly had to just hold it in one hand. I wouldn't really know what to return for that, [[x], []]?

I guess so - it's probably OK unless OP says otherwise.

@isaacg I've posted an answer below. It gives the correct answer for 1 element (I had to add one more byte to the code)

CJam, 19 18 bytes
{S+m!{S/1fb:*}$W=}

This is an anonymous function that pops an array of integers from the stack and returns an array of integers separated by a space.
Thanks to @jimmy23013 for his ingenious :* trick, which saved 1 byte.
Try it online in the CJam interpreter.
How it works
S+    e# Append a space to the array of integers.
m!    e# Push the array of all possible permutations.
{     e# Sort the array by the following:
  S/  e#   Split the array at the space.
  1fb e#   Add the integers in each chunk (using base 1 conversion).
  :*  e#   Push the product of both sums.
}$    e# Permutations with a higher product will come last.
W=    e# Select the last permutation.

Denote the total weight of the shopping bags with W. Then, if the bags in one of the hands weigh W/2 - D/2, those in the other hand  must weigh and W - (W/2 - D/2) = W/2 + D/2.
We are trying to minimize the difference D. But (W/2 - D/2)(W/2 + D/2) = W^2/4 - D^2/4, which becomes larger as D becomes smaller.
Thus, the maximal product corresponds to the minimal difference.

I think :*...W= should work.

@jimmy23013: Thanks! That made my answer a whole lot more interesting.

Python 2.7, 161, 160
code
from itertools import*
m=input();h=sum(m)/2.;d=h
for r in(c for o in range(len(m)+1) for c in combinations(m,o)):
 t=abs(h-sum(r))
 if t<=d:d=t;a=r
print a

Algorithm

2 x Wone hand = Total weight
Wone hand ~ Total weight / 2

Check if each combination is getting closer to half of total weight. Iterate and find the best one.
input
>>>[1,2,3,4]

output
(2, 3)

The displayed tuple goes in one hand, the ones that are not displayed goes in the other (it is not against the rules).

You could save one byte by doing from itertools import*

JavaScript (ES6) 117
Using a bit mask to try every possible split, so it is limited to 31 items (ok with the rules). Like the ref answer it outputs just one hand. Note: i look for the minimum difference >=0 to avoid Math.abs, as for each min < 0 there is another > 0, just swapping hands.
To test: run the snippet in Firefox, input a list of numbers comma or space separated.

f=(l,n)=>{ // the unused parameter n is inited to 'undefined'
  for(i=0;++i<1<<l.length;t<0|t>=n||(r=a,n=t))
    l.map(v=>(t+=i&m?(a.push(v),v):-v,m+=m),m=1,t=0,a=[]);
  alert(r)
}

// Test

// Redefine alert to avoid that annoying popup when testing
alert=x=>O.innerHTML+=x+'\n';

go=_=>{
  var list=I.value.match(/\d+/g).map(x=>+x); // get input and convert to numbers
  O.innerHTML += list+' -> ';
  f(list);
}
#I { width: 300px }
<input id=I value='7 7 7 10 11'><button onclick='go()'>-></button>

Haskell, 73 bytes
import Data.List
f l=snd$minimum[(abs$sum l-2*sum s,s)|s<-subsequences l]

Outputs a list of items in one hand. The missing elements go to the other hand.
Usage: f [7,7,7,10,11] -> [7,7,7]
For all subsequences s of the input list l calculate the absolute value of the weight difference between s and the missing elements of l. Find the minimum.

Haskell, 51 bytes
f l=snd$minimum$((,)=<<abs.sum)<$>mapM(\x->[x,-x])l

Output format is that left-hand weights are positive and right-hand weights are negative.
>> f [2,1,5,4,7]
[-2,-1,5,4,-7]

To generate every possible split, we use mapM(\x->[x,-x])l to negate every possible subset of elements. Then, ((,)=<<abs.sum) labels each one with its absolute sum and snd$minimum$((,)=<<abs.sum) take the smallest-labeled element.
I couldn't get it point-free because of type-checking issues.

@WillNess They are all in prelude in the current version.

BTW the following point-free code  works at the GHCi prompt: snd.minimum.map((,)=<<abs.sum).mapM(\x->[x,-x]). It's 47 bytes. (though I do have an older version installed...)

Axiom, 292 bytes
R==>reduce;F(b,c)==>for i in 1..#b repeat c;p(a)==(#a=0=>[a];w:=a.1;s:=p delete(a,1);v:=copy s;F(s,s.i:=concat([w],s.i));concat(v,s));m(a)==(#a=0=>[[0],a];#a=1=>[a,a];b:=p(a);r:=[a.1];v:=R(+,a)quo 2;m:=abs(v-a.1);F(b,(b.i=[]=>1;d:=abs(v-R(+,b.i));d<m=>(m:=d;r:=copy b.i);m=0=>break));[[m],r])

A brute force application. This would minimize the set
A={abs(reduce(+,a)quo 2-reduce(+,x))|x in powerSet(a)}

because if is minimum
y=min(A)=abs(reduce(+,a)quo 2-reduce(+,r))

it would be minimum too
2*y=abs(reduce(+,a)-2*reduce(+,r))=abs((reduce(+,a)-reduce(+,r))-reduce(+,r))

where (reduce(+,a)-reduce(+,r)) and reduce(+,r) are the 2 weight of two bags.(
But that last formula not find to me the minimum, in the application).
Ungolf and results
-- Return the PowerSet or the Powerlist of a
powerSet(a)==
    #a=0=>[a]
    p:=a.1;s:=powerSet delete(a,1);v:=copy s
    for i in 1..#s repeat s.i:=concat([p],s.i)
    concat(v,s)

-- Return one [[m], r] where
-- r is one set or list with reduce(+,r)=min{abs(reduce(+,a)quo 2-reudece(+,x))|x in powerSet(a)}
-- and m=abs(reduce(+,a) quo 2-reduce(+,r))
-- because each of two part, has to have the same weight
MinDiff(a)==
    #a=0=>[[0],a]
    #a=1=>[ a ,a]
    b:=powerSet(a)
    r:=[a.1];v:=reduce(+,a) quo 2;m:=abs(v-a.1)
    for i in 1..#b repeat
        b.i=[]=>1
        k:=reduce(+,b.i)
        d:=abs(v-k)
        d<m=>(m:=d;r:=copy b.i)
        m=0=>break
    [[m],r]

--Lista random di n elmenti, casuali compresi tra "a" e "b"
randList(n:PI,a:INT,b:INT):List INT==
    r:List INT:=[]
    a>b =>r
    d:=1+b-a
    for i in 1..n repeat
          r:=concat(r,a+random(d)$INT)
    r

(5) -> a:=randList(12,1,10000)
   (5)  [8723,1014,2085,5498,2855,1121,9834,326,7416,6025,4852,7905]
                                                       Type: List Integer
(6) -> m(a)
   (6)  [[1],[1014,2085,5498,1121,326,6025,4852,7905]]
                                                  Type: List List Integer
(7) -> x:=reduce(+,m(a).2);[x,reduce(+,a)-x]
   (7)  [28826,28828]
                                               Type: List PositiveInteger
(8) -> m([1,2,3,4])
   (8)  [[0],[2,3]]
                                                  Type: List List Integer
(9) -> m([10,1,2,3,4])
   (9)  [[0],[10]]
                                                  Type: List List Integer
(10) -> m([40,20,80,50,100,33,2])
   (10)  [[0],[40,20,100,2]]
                                                  Type: List List Integer
(11) -> m([7,7,7,10,11])
   (11)  [[0],[10,11]]
                                                  Type: List List Integer

Vyxal, 7 bytes
ṗµ∑;Iht

Try it Online!
Port of isaacg's Pyth answer, go upvote that
ṗ       # Subsets
 µ∑;    # Sorted by sum
    I   # Cut in half
     ht # Get the second element of the first half

R (234)
a longer and slower solution with R.
Function:
function(p){m=sum(p)/2;n=100;L=length(p);a=matrix(0,n,L+2);for(i in 1:n){idx=sample(1:L,L);a[i,1:L]=idx;j=1;while(sum(p[idx[1:j]])<=m){a[i,L+1]=abs(sum(p[idx[1:j]])-m);a[i,L+2]=j;j=j+1}};b=which.min(a[,L+1]);print(p[a[b,1:a[b,L+2]]])}

Expected input - vector with the weights.
Expected output - vector with the weights for one hand.

Example
> Weight(c(1,2,3,4))
[1] 3 2
> Weight(c(10,1,2,3,4))
[1] 10
> Weight(c(40,20,80,50,100,33,2))
[1] 100  40  20  2
> Weight(c(7,7,7,10,11))
[1] 7 7 7

Human readable code version:

weight <- function(input) {
  mid <- sum(input)/2
  n <- 100
  input_Length <- length(input)
  answers <- matrix(0, n, input_Length+2)
  for(i in 1:n){
    idx <- sample(1:input_Length, input_Length)
    answers[i, 1:input_Length ] <- idx
    j <- 1
    while(sum(input[idx[1:j]]) <= mid){
        answers[i, input_Length+1] <- abs(sum(input[idx[1:j]]) - mid)
        answers[i, input_Length+2] <- j
        j <- j + 1
    }
  }
  best_line <- which.min(answers[, input_Length+1])
  print(paste("weight diference: ", answers[best_line, input_Length+1]))
  print(input[answers[best_line, 1:answers[best_line, input_Length+2]]])
}