title: Write a VIC cipher encoder

text:
# Question
Title: Write a VIC cipher encoder
The VIC cipher is one of the most complicated pencil and paper ciphers ever devised. Used in the 1950s by Soviet spy Reino Häyhänen, codenamed "VICTOR", its main principle is security through obfuscation; a *lot* of obfuscation.

Your task is to write a program or function that will take a message and encode it using the VIC cipher. I have also posted a VIC cipher decoder challenge here. If any of the following instructions are unclear, don't hesitate to ask about them in the comments. The instructions are adapted from this site.

# Encoding the VIC cipher

**Preparation**

You will need five inputs:

* the plaintext message
* a short keyword or phrase containing the most common letters in your language
* a key phrase, such as a quote or a line from a song (at least 20 characters)
* a date (or another number that is six digits or more)
* a personal agent number

In practice, these last four should be agreed upon beforehand by the sender and the recipient, including whether the agent number of the sender or the recipient is used in encoding.

My example message will be: `We are discovered. Take what you can. Burn everything else. Move to Safehouse Foxtrot 3.`

We'll be encoding in English (though you may use whatever language and alphabet you prefer) and the most common letters in the English alphabet are `A, E, I, N, O, R, S, T`. I'll use the keyword `SENATORI`.

My key phrase is a quote by Richard Feynman: "The first principle is that you must not fool yourself — and you are the easiest person to fool."

As a date, I'll use July 31, 2016 (in the format `3172016`), which is the day it was when I wrote this description.

The personal number I have chosen for myself is `9`.

**Summary of steps**

1. Derive the intermediate keys for use in the following steps.
2. Construct and apply the straddling checkerboard.
3. Construct and apply the first transposition table.
4. Construct and apply the second (disrupted) transposition table.
5. Finalize the message by inserting the message indicator group.

**Submechanisms**

Two more things to explain before we get into the meat of the matter: the processes of chain addition and sequentializing.

Chain addition, also known as a lagged Fibonacci generator, works by taking a starting digit sequence, adding the first two digits without carrying (add them together then `mod 10`) and appending the result to the end. For example:

```
79081
7 + 9 = 6

790816
9 + 0 = 9

7908169
0 + 8 = 8

79081698
8 + 1 = 9

790816989
1 + 6 = 7

7908169897
... and so on

```

Sequentializing is essentially taking a sequence of letters or digits and labeling them by their alphabetical/numerical order. Duplicates are labelled left to right. For example:

```
E X A M P L E
    0           # A
1   0       2   # Es
1   0     3 2   # L
1   0 4   3 2   # M
1   0 4 5 3 2   # P
1 6 0 4 5 3 2   # X

3  3  0  5  8  4  2  0  4  7  5  4  8  1
      0              1                     # 0s
      0              1                 2   # 1
      0           3  1                 2   # 2
4  5  0           3  1                 2   # 3s
4  5  0        6  3  1  7        8     2   # 4s
4  5  0  9     6  3  1  7    10  8     2   # 5s
4  5  0  9     6  3  1  7 11 10  8     2   # 7
4  5  0  9 12  6  3  1  7 11 10  8 13  2   # 8s

```

I use zero-indexing here, but index however you like.

**1. Intermediate Keys**

Split the first 20 letters of the key phrase into two groups of 10 and sequentialize each individually, which we will call `S1` and `S2`.

```
    THEFIRSTPR
S1: 8201357946

    INCIPLEIST
S2: 2603751489

```

Choose a random 5-digit message identifier, `M` (this can be one of the inputs if you prefer):

```
M = 47921

```

Subtract, without borrowing (subtract `mod 10`), the first five digits of the key date `3172016` from `M`:

```
M      47921
date - 31720
     = 16201

```

Chain add the result until you have ten digits:

```
1620178218

```

Add these digits to `S1`, without carrying or `mod 10`, to obtain `G`:

```
     1620178218
S1 + 8201357946
G  = 9821425154

```

Above `S2`, write the sequence 0123456789. Locate each digit of `G` in the sequence 0123456789 and replace it with the digit directly below it in `S2`. The result is `T`.

```
   0123456789
S2 2603751489

G  9821425154
T  9806705657

```

Use chain addition to expand `T` to 60 digits.

```
9806705657

becomes

980670565778637511245490262369939288595822106344304316978734

```

These last 50 digits, in five rows of ten digits each, form the `U` block.

```
T  9806705657
U  7863751124
   5490262369
   9392885958
   2210634430
   4316978734

```

The last two non-equal digits of the `U` block are individually added to the agent's personal number to give the widths of the two transpositions, `p` and `q`.

9 + 3 = 12 (p, first transposition width) 9 + 4 = 13 (q, second transposition width)

Sequentialize `T` and use this sequence to copy off the columns of the `U` block, from top to bottom, into a new row of digits, `V`.

```
T     9806705657
seqT  9804612537

U     7863751124
      5490262369
      9392885958
      2210634430
      4316978734

V     69911 56837 12548 26533 30206 13947 72869 49804 84323 75924

```

Sequentialize the first `p` digits to get the key for the first transposition `K1`, and the following `q` digits for the key for the second `K2`.

```
First 12  6  9  9  1  1  5  6  8  3  7  1  2
K1        6 10 11  0  1  5  7  9  4  8  2  3

Next 13   5  4  8  2  6  5  3  3  3  0  2  0  6
K2        8  7 12  2 10  9  4  5  6  0  3  1 11

```

Finally, sequentialize the final row of the `U` block to get `C`, the column headers for the straddling checkerboard:

```
U5  4316978734
C   3105968724

```

**2. Straddling Checkerboard**

First, I will give my example checkerboard then explain the principles in creating it in that way:

```
  3 1 0 5 9 6 8 7 2 4
  S E N A T O R I
2 B D G J L P U W Y .
4 C F H K M Q V X Z #

```

The first line of letters is our short keyword `SENATORI`. Your keyword can be any string without duplicates, but since it defines the top row of your checkerboard, choose wisely. Above the keyword is `C`, and the other rows are the rest of your alphabet in whatever order you choose. In my case, I filled the checkerboard with the rest of the Latin alphabet, a punctuation mark `.` and a mark for demarcating numbers `#`. Essentially, the checkerboard is a fancy substitution cipher. For example, "E" will be substituted with `1`, and "W" will be substituted with `27`.

Once we have encoded our plaintext message with this checkerboard, but first, we need to make the beginning of our message less obvious by splitting it at a random position, and making it all uppercase. To denote the other original beginning, we use two full stops `..`

```
We are discovered. Take what you can. Burn everything else. Move to Safehouse Foxtrot 3.

```

becomes

```
HING ELSE. MOVE TO SAFEHOUSE FOXTROT#3#.. WE ARE
DISCOVERED. TAKE WHAT YOU CAN. BURN EVERYT

```

We encode with the checkerboard, giving us:

```
407020 1293124 496481 96 354114062831 416479869443442424 271 581
2173436481812124 95451 274059 22628 435024 232880 14818229

```

If the length of the message isn't divisible by 5, we add some null characters to pad out the message. Our message is 109 digits long, so I will add one null: "4".

```
40702 01293 12449 64819 63541 14062 83141 64798 69443 44242 42715
81217 34364 81812 12495 45127 40592 26284 35024 23288 01481 82294

```

Note: Since my example message does not contain numbers, I'll say here that you might designate, say, as `#3#`, which is encoded as `44344` here.

**3. First Transposition**

Create the transposition table by writing `K1` (from the Intermediate Keys section) followed by the encoded message from the previous step, in rows of the same length, below the key:

```
K1   6 10 11  0  1  5  7  9  4  8  2  3

     4  0  7  0  2  0  1  2  9  3  1  2
     4  4  9  6  4  8  1  9  6  3  5  4
     1  1  4  0  6  2  8  3  1  4  1  6
     4  7  9  8  6  9  4  4  3  4  4  2
     4  2  4  2  7  1  5  8  1  2  1  7
     3  4  3  6  4  8  1  8  1  2  1  2
     4  9  5  4  5  1  2  7  4  0  5  9
     2  2  6  2  8  4  3  5  0  2  4  2
     3  2  8  8  0  1  4  8  1  8  2  2
     9  4

```

Taking the numbered columns in order of their numbers we get:

```
060826428  246674580  151411542  246272922  961311401  082918141
4414434239 118451234  334422028  293488758  0417249224 794943568

```

**4. Second Transposition**

The first transposition was relatively simple. This one, however, is a disrupted transposition. The disruption pattern is determined by the width of the table and the key. In our example, we have 110 digits and 13 columns, meaning we'll have 8 full rows and 6 leftovers. We start filling in the first row, but stop at column 0, and continue as follows:

```
K2   8  7 12  2 10  9  4  5  6  0  3  1 11

     0  6  0  8  2  6  4  2  8              stop at 0
     2  4  6  6  7  4  5  8  0  1           continue in a triangle pattern
     5  1  4  1  1  5  4  2  2  4  6
     2  7  2  9  2  2  9  6  1  3  1  1
     4  0  1  0  8  2  9  1  8  1  4  1  4  until the end
     4  1  4  4  3  4  2  3  9  1  1        restart and stop at 1
     8  4  5  1  2  3  4  3  3  4  4  2
     2  0  2  8  2  9  3  4  8  8  7  5  8
     0  4  1                                restart and stop at 2

```

Then we fill the last few spaces with the remaining digits.

```
K2   8  7 12  2 10  9  4  5  6  0  3  1 11

     0  6  0  8  2  6  4  2  8  7  2  4  9
     2  4  6  6  7  4  5  8  0  1  2  2  4
     5  1  4  1  1  5  4  2  2  4  6  7  9
     2  7  2  9  2  2  9  6  1  3  1  1  4
     4  0  1  0  8  2  9  1  8  1  4  1  4
     4  1  4  4  3  4  2  3  9  1  1  9  4
     8  4  5  1  2  3  4  3  3  4  4  2  3
     2  0  2  8  2  9  3  4  8  8  7  5  8
     0  4  1  5  6  8

```

Now, we read off the columns in the exactly the same way we did for in the first transposition.

```
71431148  42711925  861904185 22614147  45499243  28261334  80218938
641701404 025244820 645224398 271283226 94944438  064214521

```

And split everything up into 5-digit groups:

```
71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189
38641 70140 40252 44820 64522 43982 71283 22694 94443 80642 14521

```

**5. Finalize the Message**

The final step is to insert our random message identifier, `47921`, into the message itself. The final digit of the key date `6` indicates the distance the group should be from the end.

```
71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641
70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521

```

**Notes for this challenge**

* You are given a minimum of five inputs: the message, the letter keyword, the key phrase, the date, and a personal number. You may include two additional inputs: the random message identifier and the nulls needed to pad out the message, or your function may generate some random numbers on its own.
* You may assume all inputs are valid, with the correct number of digits and letters (5-digit message identifier, at least 20 digits for the key phrase, and so on). You may assume that your strings (the message and keywords) have already had all punctuation and spaces removed except for those that you allow in your version, and that numbers are already demarcated with number signs.
* The first keyword should not have duplicate letters in it, and in your code, you may assume that it never has duplicate letters.
* The language you use to encode in does not matter, as long as the language is preexisting, the alphabet is preexisting, and you specify which language you use in your answer.
* Whichever alphabet you employ for your straddling checkerboard, you may add or remove symbols to pad the checkerboard out. Specify what you use those symbols for (for example, punctuation, a separate "message begin" symbol, symbols for common words). You may forego the number sign entirely and spell out the numbers or include each digit in the checkerboard, using the slot where the number sign was for something else. Please specify which checkerboard you used in your answer.
* The output should be either a string of space-separated five-digit groups, a list of five-digit integers, or something similar.
* I used zero-indexing and `0123456789` in my example. You may use 1-indexing and `1234567890`, or some other system in your answer, as long as you specify what you used.

Here is an example implementation on Ideone.

This is a long post and I wrote most of it by hand, so if there are any confusing parts in this post or errors in my counting and transposing, please let me know. Good luck and good golfing!

# Answer
> 10 votes
# Python 3, ~~1423~~ ~~1348~~ ~~1324~~ ~~1316~~ ~~1300~~ ~~1286~~ ~~1250~~ ~~1249~~ ~~1209~~ ~~1206~~ 1204 bytes

This is definitely the longest golf I've ever done, and the only golf where I was seriously worried about running out of one-character variable names. Golfing suggestions welcome. Try it online!

I'm encoding with the uppercase Latin alphabet with additional characters `.` and `#`, using 0-indexing and `0123456789` when converting `g` to `t`. My checkerboard is in a format similar to the following example:

```
  2 9 7 4 5 8 3 1 0 6    # C
  S E N A T O R I        # keyword
0 B D G J L P U W Y .    # remaining alphabet arranged in columns
6 C F H K M Q V X Z #    # . and # at the end

```

**Edit:** -63 bytes thanks to TuukkaX's suggestion to shorten some of the frequently used functions with one-letter variables. -12 bytes from making `a, g, t` more compact.

**Edit:** -24 bytes from making by removing variable names for intermediate keys that are only used once, namely `a, g, s, S, k, K`.

**Edit:** -74 bytes from consolidating `H(), T() and C()`.

**Edit:** -1 byte thanks to Nick A for their suggestion of changing `ord(s[i])+ord(s[i+1])` to `sum(map(ord,s[i:i+2]))`. -2 bytes from changing 2 `+=[a]` calls to `+=a,`. -13 bytes from changing how `G()` found the index of the minimum of `s`. -2 bytes from changing `y=(y+1)%v` to `y=-~y%v`. -15 bytes from assigning `k.index()` to `K`. -4 bytes from assigning `10` to `W`. -5 bytes from assigning `1-I(d[-1])` to `X` inside `V`. -3 bytes from rewriting `C()`'s main loop. -2 bytes from reorganizing `T()`.

```
I=int;L=list;E=len;R=range;B=str;J=''.join;W=10
def H(s,e):
 for i in R(e-E(s)):s+=chr(48+sum(map(ord,s[i:i+2]))%32%W)
 return s
def Q(s):
 r=[0]*E(s);s=L(s)
 for z in R(E(s)):b=s.index(min(s));r[b]=z;s[b]="~"
 return r
def T(x,k,d=0):
 u=E(x);v=E(k);g=R(v);K=k.index;n=u//v+1;w=[];e=r=y=0;i=K(y);c=[]
 if d:
  while r<n:
   if r>n-1:i=min(i,(u%v or v))
   w+=L(x[e:e+i]),;e+=i;i+=1;r+=1
   if i>v:y=-~y%v;i=K(y)
  r=y=0;i=v-K(y)
  while r<n:
   w[r]+=L(x[e:e+i]);e+=i;i-=1;r+=1
   if i<1:y+=1;i+=v-K(y);r+=1
  w[-1]+=['']*(v-E(w[-1]))
  for j in g:c+=J(z[j]for z in w),
 else:c=[x[i::v]for i in g]
 s=[0]*v
 for f in g:s[k[f]]=c[f]
 return J(s)
def C(m,s,w,n):
 t={".":s[-2:],"#":s[-1]*2};j=z=0
 for x in R(26):
  v=chr(x+65)
  if v in w:t[v]=s[w.index(v)]
  else:t[v]=s[z-2]+s[j];j+=z;z=-~z%2
 r=J(i.isdigit()and i or t[i]for i in m)
 return r+n[:-E(r)%5]
def V(m,w,P,d,A,M,n):X=1-I(d[-1]);t=J(B(Q(P[W:20])[I(J(B((I(H(J(B((I(M[i])-I(d[i]))%W)for i in R(5)),W)[i])+I(Q(P[:W])[i]))%W)for i in R(W))[i])])for i in R(W));u=H(t,60)[W:];p=A+I(u[-2]);v=T(u,Q(t));z=T(T(C(m,J(B(i)for i in Q(u[40:])),w,n),Q(v[:p])),Q(v[p:p+A+I(u[-1])]),1);e=[z[5*i:5*-~i]for i in R(-(-E(z)//5))];return' '.join(e[:X]+[M]+e[X:])

```

**Ungolfing:**

```
def chain_add(seq, end):
    for i in range(end - len(seq)):
        seq += chr(48+sum(map(ord,seq[i:i+2]))%32%10)
    return seq

def sequent(seq):
    res = [0]*len(seq)
    seq = list(seq)
    for z in range(len(seq)):
        b = seq.index(min(seq))
        res[b] = z
        seq[b] = "~"
    return res

def transpose(text, keys, disrupt=False):
    if disrupt:
        num_rows = len(text) // len(keys) + 1
        len_last = len(text) % len(keys)
        if len_last == 0:
            len_last = len(keys)
        d_rows = []
        text_index = 0
        current_row = 0
        stop_key = 0
        stop_index = keys.index(stop_key)
        while current_row < num_rows:
            if current_row > num_rows-1:
                stop_index = min(stop_index, len_last)
            d_rows += [list(text[text_index:text_index+stop_index])]
            text_index += stop_index
            stop_index += 1
            if stop_index>len(keys):
                stop_key = (stop_key+1) % len(keys)
                stop_index = keys.index(stop_key)
            current_row += 1
        current_row = 0
        stop_key = 0
        stop_len = len(keys) - keys.index(stop_key)
        while current_row < num_rows:
            d_rows[current_row] += list(text[text_index:text_index+stop_len])
            text_index += stop_len
            stop_len -= 1
            if stop_len < 1:
                stop_key += 1
                stop_len = len(keys) - keys.index(stop_key)
                current_row += 1
            current_row += 1
        d_rows[-1] += ['']*(len(keys)-len(d_rows[-1]))
        columns = []
        for j in range(len(keys)):
            columns += [''.join(i[j]for i in d_rows)]
    else:
        columns = ['']*len(keys)
        for t in range(len(text)):
            columns[t%len(keys)] += text[t]
    res = [0]*len(keys)
    for index in range(len(keys)):
        res[keys[index]] = columns[index]
    return''.join(res)

def checkerboard(message, seq, word, null):
    trans = {".":seq[-2:], "#":seq[-1]*2};res='';j=z=0
    for x in range(26):
        v = chr(x + 65)
        if v in word:
            trans[v] = seq[word.index(v)]
        else:
            trans[v] = seq[z-2] + seq[j]
            j += z
            z = (z+1) % 2
    for i in message:
        if i.isdigit():
            res += i
        else:
            res += trans[i]
    return res + null[:-len(res)%5]

def vic_cipher(message, keyword, phrase, date, agent, m_id, null):
    s1 = sequent(phrase[:10])
    s2 = sequent(phrase[10:20])
    a = ''.join(str((int(m_id[i])-int(date[i]))%10) for i in range(5))
    g = ''.join(str((int(a[i])+int(s1[i]))%10) for i in range(10))
    t = ''.join(str(s2[int(g[i])]) for i in range(10))
    u = chain_add(t,60)[10:]
    p = agent+int(u[-2])
    q = agent+int(u[-1])
    seqT = sequent(t)
    v = transpose(u,seqT)
    k1 = sequent(v[:p])
    k2 = sequent(v[p:p+q])
    c = ''.join(str(i)for i in sequent(u[40:]))
    x = checkerboard(message,c,keyword,null)
    y = transpose(x,k1)
    z = transpose(y,k2,1)
    e = [z[5*i:5*(i+1)] for i in range(-(-len(z)//5))]
    X = 1-int(date[-1])
    return ' '.join(e[:X] + [m_id] + e[X:])

```

# Answer
> 3 votes
# C, ~~2880~~ ~~2769~~ ~~2766~~ ~~2762~~ ~~2743~~ ~~2741~~ ~~2739~~ ~~2699~~ 2458 bytes

```
#include<stdio.h>
#define m(x)malloc(x)
#define Y(x)strlen(x)
typedef int i;typedef char*c;c _(c A,i B,i D){if(D>=B){return A;}c C=m(Y(A)+2);sprintf(C,"%s%c",A,48+(A[D]+A[D+1]-96)%10);return _(C,B,D+1);}c l(c A){i J=Y(A);c P=m(J+2);for(i m=0;m<J;m++){P[m]=32;}for(i v=0;v<J;v++){char G;i R;for(i u=0;u<J;u++){R=u<1|A[u]<G?u:R;G=u<1|A[u]<G?A[u]:G;}P[R]=48+v;c V=m(J);for(i t=0;t<J;t++){V[t]=t!=R?A[t]:97;}A=V;}return P;}c S(c C,c N,c I,char U){srand(time(NULL));i M=Y(I);i O=Y(N);i R=rand()%M;c Q=m(M+1);for(i u=R;u<M;u++){Q[u-R]=I[u];}Q[M-R]=46;for(i H=0;H<R;H++){Q[H+M-R+1]=I[H];}c g=m(28);c V=m(28);strcat(V,C);sprintf(g,"%s%s",N,"BCDFGHJKLMPQUVWXYZ.#");i B=Y(N);for(i q=B;q<10;q++){for(i x=0;x<10;x++){char J[2]={C[q],C[x]};V[B]=48+atoi(J);B++;}}c w=m(M*2+4);for(i J=0;J<=M;J++){i K=0;for(i X=0;X<28;X++){if(Q[J]==g[X]){char F[3];sprintf(F,"%d",V[X]-48);strcat(w,F);K=1;}}if(K<1){w[Y(w)]=Q[J];}}i f=Y(w);if(f%5>0){c P=m(5-f%5);for(i E=0;E<5-f%5;E++){P[E]=U;}strcat(w,P);}return w;}c a(c I,c U){i M=Y(I),K=Y(U);c T=m(M);i F=0;for(i b=0;b<K;b++){for(i y=0;y<K;y++){if(U[y]==48+b){for(i u=y;u<M;u+=K){T[F]=I[u];F++;}}}}return T;}c da(c I,c K){i e=Y(I),k=Y(K);c T=m(e);for(i y=0;y<e;y++){T[y]=32;}i F,P;F=P=0;for(i u=0;u<k;u++){for(i v=0;v<k;v++){T[F]=I[P];P++;F++;if(K[v+1]-48==u){for(i C=1;C<k-v;C++){F+=k-v-C;for(i E=0;E<=v+C;E++){if(F<e&P<e){T[F]=I[P];}F++;P++;}}break;}}if(F>e){break;}}i U=0;for(i g=0;g<e;g++){U=T[g]-48<10&-1<T[g]-48?U+1:U;}for(i j=U;j<e;j++){for(i x=0;x<e;x++){if(T[x]==32){T[x]=I[j];break;}}}return a(T,K);}En(c n,c m,c k,i d,c v,c s,char u){c S1,S2;S1=m(10);S2=m(10);for(i i=0;i<20;i++){if(i<10){S1[i]=k[i];}else{S2[i-10]=k[i];}}S1=l(S1);S2=l(S2);c M=m(5);for(i i=4;i>-1;i--){M[i]=48+(s[i]-v[i])%10;}c G=_(M,5,0);for(i y=0;y<10;y++){G[y]=48+(S1[y]+G[y]-96)%10;}c N="0123456789";c T=m(10);for(i q=0;q<10;q++){for(i t=0;t<10;t++){if(N[t]==G[q]){T[q]=S2[t];}}}c Z=_(T,50,0);c U=m(50);for(i h=0;h<50;h++){U[h]=Z[h+10];}i p,q;for(i b=49;b>10;b++){if(U[b]!=U[b-1]){q=d+U[b]-48;p=d+U[b-1]-48;break;}}c V=m(50);i Ct=0;for(i j=0;j<10;j++){for(i o=0;o<10;o++){if(l(T)[o]==48+j){for(i x=o;x<o+41;x+=10){V[Ct]=U[x];Ct+=1;}}}}c K1=m(p);c K2=m(q);for(i D=0;D<p+q;D++){if(D<p){K1[D]=V[D];}else{K2[D-p]=V[D];}}K1=l(K1);K2=l(K2);c C=m(10);for(i b=40;b<50;b++){C[b-40]=U[b];}C=l(C);c t=da(a(S(C,m,n,u),K1),K2);i O=0;for(i B=0;B<Y(t)/5+1;B++){if(B==Y(t)/5-v[Y(v)-1]+49){printf("%s ",s);}else{for(i J=O;J<O+5;J++){printf("%c",t[J]);}printf(" ");O+=5;}}}

```

My gosh. This is the longest program I have *ever* had to golf. This is also the first on which I actually ran out of single-character variable names for the global scope and so had to move on to using a few 2 character ones (the fact that I apparently cannot redeclare variables doesn't help). Golfing tips are therefore very much appreciated.

## Ungolfed

Compiles without any warnings, unlike the golfed version. Minor changes made to the golfed version will not be reflected in this ungolfed version.

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

char*Chain_Add(char*String,int End,int Start){
  if(Start>=End){return String;}
  char*C=malloc(strlen(String)+2);
  sprintf(C,"%s%c",String,'0'+(((String[Start]-'0')+(String[Start+1]-'0'))%10));
  return Chain_Add(C,End,Start+1);
}

char*Sequent(char*String){
  int J=strlen(String);
  char*P=malloc(J+2);
  for(int m=0;m<J;m++){
    P[m]=' ';
  }
  for(int v=0;v<J;v++){
    char G;
    int R;
    for(int u=0;u<J;u++){
      R=(u<1||String[u]<G)?u:R;
      G=(u<1||String[u]<G)?String[u]:G;
    }
    P[R]='0'+v;
    char*V=malloc(J);
    for(int t=0;t<J;t++){
      if(t!=R){
    V[t]=String[t];
      }
      else{
    V[t]='a';
      }
    }
    String=V;
  }
  return P;
}

char*Straddling_Checkerboard(char*C,char*Key,char*Message,char null){
  srand(time(NULL));
  int Msg_Len=strlen(Message);
  int Key_Len=strlen(Key);
  int R=rand()%Msg_Len;
  char*Q=malloc(Msg_Len+1);
  for(int u=R;u<Msg_Len;u++){
    Q[u-R]=Message[u];
  }
  Q[Msg_Len-R]='.';
  for(int H=0;H<R;H++){
    Q[H+Msg_Len-R+1]=Message[H];
  }
  char*Alphabet=malloc(26);
  for(int W=0;W<26;W++){
    Alphabet[W]='A'+W;
  }
  int q=0;
  char*e=malloc(Key_Len);
  for(int z=0;z<Key_Len;z++){
    if(strchr(e,Key[z])!=NULL){
      q++;
    }
    else{
      e[z-q]=Key[z];
    }
  }
  int r=0;
  for(int h=0;h<26;h++){
    if(strchr(e,Alphabet[h-r])!=NULL){
      for(int X=h-r;X<26;X++){
    Alphabet[X]=Alphabet[X+1];
      }
      r++;
    }
  }
  char*Checkerboard=malloc(28);
  for(int i=0;i<26;i++){
    if(i<strlen(e)){
      Checkerboard[i]=e[i];
    }
    else{
      Checkerboard[i]=Alphabet[i-strlen(e)];
    }
  }
  Checkerboard[26]='.';
  Checkerboard[27]='#';
  char*Values=malloc(28);
  strcat(Values,C);
  int B=strlen(e);
  for(int q=B;q<10;q++){
    for(int x=0;x<10;x++){
      char J[2]={C[q],C[x]};
      Values[B]='0'+atoi(J);
      B++;
    }
  }
  char*Encoded=malloc(Msg_Len*2+4);
  for(int J=0;J<=Msg_Len;J++){
    int K=0;
    for(int X=0;X<28;X++){
      if(Q[J]==Checkerboard[X]){
    char F[3];
    sprintf(F,"%d",Values[X]-'0');
    strcat(Encoded,F);
    //printf("F = %s while Q[J] = %c and Checkerboard[X] = %c and Encoded = %s\n",F,Q[J],Checkerboard[X],Encoded);
    K=1;
      }
    }
    if(K<1){
      Encoded[strlen(Encoded)]=Q[J];
    }
  }
  int Encded_Len=strlen(Encoded);
  if(Encded_Len%5>0){
    char*P=malloc(5-Encded_Len%5);
    for(int E=0;E<5-Encded_Len%5;E++){
      P[E]=null;
    }
  strcat(Encoded,P);
  }
  return Encoded;
}

char*Transpose(char*Message,char*K1){
  int Msg_Len=strlen(Message),K1_Len=strlen(K1);
  char*T=malloc(Msg_Len);
  int F=0;
  for(int i=0;i<K1_Len;i++){
    for(int y=0;y<K1_Len;y++){
      if(K1[y]=='0'+i){
    for(int u=y;u<Msg_Len;u+=K1_Len){
      T[F]=Message[u];
      F++;
    }
      }
    }
  }
  return T;
}

char*Disrupted_Transpose(char*Message,char*K2){
  int Msg_Len=strlen(Message),K2_Len=strlen(K2);
  char*T=malloc(Msg_Len);
  for(int y=0;y<Msg_Len;y++){
    T[y]=' ';
  }
  int F=0;
  int P=0;
  for(int u=0;u<K2_Len;u++){
    for(int v=0;v<K2_Len;v++){
      T[F]=Message[P];
      P++;F++;
      if(K2[v+1]-'0'==u){
        for(int C=1;C<K2_Len-v;C++){
      F+=K2_Len-v-C;
      for(int E=0;E<=v+C;E++){
        if(F<Msg_Len&P<Msg_Len){
          T[F]=Message[P];
        }
        F++;P++;
      }
    }
    break;
      }
    }
    if(F>Msg_Len){
      break;
    }
  }
  int U=0;
  for(int g=0;g<Msg_Len;g++){
    U=(T[g]-'0'<10&-1<T[g]-'0')?U+1:U;
  }
  for(int j=U;j<Msg_Len;j++){
    for(int x=0;x<Msg_Len;x++){
      if(T[x]==' '){
    T[x]=Message[j];
    break;
      }
    }
  }
  return Transpose(T,K2);
}

void VIC_Encoder(char*Message,char*Phrase,char*Key,int a_id,char*date,char*m_id,char null){
  char*S1=malloc(10);
  char*S2=malloc(10);
  for(int i=0;i<20;i++){
    if(i<10){
      S1[i]=Key[i];
    }
    else{
      S2[i-10]=Key[i];
    }
  }
  S1=Sequent(S1);
  S2=Sequent(S2);
  char*M=malloc(5);
  for(int i=4;i>-1;i--){
    M[i]='0'+(((m_id[i]-'0')-(date[i]-'0'))%10);
  }
  char*G=Chain_Add(M,5,0);
  for(int y=0;y<10;y++){
    G[y]='0'+(((S1[y]-'0')+(G[y]-'0'))%10);
  }
  char*N="0123456789";
  char*T=malloc(10);
  for(int q=0;q<10;q++){
    for(int t=0;t<10;t++){
      if(N[t]==G[q]){
    T[q]=S2[t];
      }
    }
  }
  char*Z=Chain_Add(T,50,0);
  char*U=malloc(50);
  for(int h=0;h<50;h++){
    U[h]=Z[h+10];
  }
  int p,q;
  for(int b=49;b>10;b++){
    if(U[b]!=U[b-1]){
      q=a_id+(U[b]-'0');
      p=a_id+(U[b-1]-'0');
      break;
    }
  }
  char*seqT=Sequent(T);
  char*V=malloc(50);
  int Count=0;
  for(int j=0;j<10;j++){
    for(int o=0;o<10;o++){
      if(seqT[o]=='0'+j){
    for(int x=o;x<o+41;x+=10){
      V[Count]=U[x];
      Count+=1;
    }
      }
    }
  }
  char*K1=malloc(p);
  char*K2=malloc(q);
  for(int D=0;D<p+q;D++){
    if(D<p){
      K1[D]=V[D];
    }
    else{
      K2[D-p]=V[D];
    }
  }
  K1=Sequent(K1);
  K2=Sequent(K2);
  char*C=malloc(10);
  for(int b=40;b<50;b++){
    C[b-40]=U[b];
  }
  C=Sequent(C);
  char*Transposed_2=Disrupted_Transpose(Transpose(Straddling_Checkerboard(C,Phrase,Message,null),K1),K2);
  int O=0;
  for(int B=0;B<strlen(Transposed_2)/5+1;B++){
    if(B==strlen(Transposed_2)/5-date[strlen(date)-1]+'1'){
      printf("%s ",m_id);
    }
    else{
      for(int J=O;J<O+5;J++){
    printf("%c",Transposed_2[J]);
      }
      printf(" ");
      O+=5;
    }
  }
}

```

## Notes

* This uses a checkerboard similar to the following to encode the message:

```
  3 4 5 6 2 3 4 5 6 7
  S E N A T O R I
6 B C D F G H J K L M
7 P Q U V W X Y Z . #

```
* This assumes that all applicable strings are given in uppercase. The message should also have all punctuation *except periods* removed and all numbers demarcated by `#`s, while the key phrase should have *all* punctuation removed.
* The resulting encoded message is output to STDOUT as a string of space-separated five-digit groups.
* The input message should be in English.
* I would have combined a few of the functions I used, but then I would have to resort to using more two-letter variable names, making the final program longer than it would be with a few more functions.
* ~~This currently does *not* assume that the keyword (at least in English) is always going to contain the same set of letters, and so makes up for that by removing duplicates, manipulating the checkerboard, etc. This capability is apparently not required by OP, so I am currently golfing off the extra, unnecessary bytes that is taking up.~~ Updated for golfed version.

# Answer
> 2 votes
# JavaScript (ES6), ~~946~~ ~~938~~ 953 bytes

```
V=(c,d,f,g,j,k,m)=>{S=a=>a.split``,J=a=>a.join``,A=(a,b)=>{for(i=0;a[L="length"]<b;a+=(a[i++]- -a[i])%h);return a},Q=b=>(a=S(b).sort(),S(b).map(b=>a[i=a[X="indexOf"](b)]=i)),u=A(t=J(S(A(J(S(k).map((a,b)=>Math.abs(a-g[b]))),h=10)).map((a,b)=>Q(f[C="slice"](h,20))[(Q(f[C](0,h))[b]- -a)%h])),60)[C](h),T=((a,b,c)=>{if(r=Array(l=b[L]).fill(""),c){for(e=a[L]/l,i=0,w=[],u=R=b[X](x=0);i<e;)w[i++]=a[P](0,R++),u?u=0:R>l||(R=b[X](u=++x));for(i=0;i<e;)w[i]=J(w[i].concat(a[P](0,l-w[i++][L])));a=J(w)}for(i in a)r[+b[i%l]]+=a[i];return r}),v=J(T(u,Q(t))),q=J(Q(u[C](-h))),t="ABCDEFGHIJKLMNOPQRSTUVWXYZ#".match(new RegExp("[^"+d+"]","g")),t[P="splice"](9,0,"."),M=[];for(i in t)M[t[i]]=q[8^i/h]+(M[d[i]]=q[i%h]);for(n=c[L],b=J((c[C](n-=new Date%n)+"."+c[C](0,n)).split(/ |/).map(a=>M[a]||a)),b+=m.repeat(5-b[L]%5),i=f=q=49;f==q;)f=+u[i-1]+j,q=+u[i++]+j;return t=J(T(S(J(T(b,Q(v[C](0,f))))),Q(v.substr(f,q)),1)).match(/.{5}/g),g=-g[C](-1),g++&&t[P](g||t[L],0,k),t}

```

I saw over the weekend there was no JS entry for this yet, so here's my (last minute) attempt. Implementing and golfing this was as crazy as it was fun!

### Demo Snippet

```
V=(c,d,f,g,j,k,m)=>{S=a=>a.split``,J=a=>a.join``,A=(a,b)=>{for(i=0;a[L="length"]<b;a+=(a[i++]- -a[i])%h);return a},Q=b=>(a=S(b).sort(),S(b).map(b=>a[i=a[X="indexOf"](b)]=i)),u=A(t=J(S(A(J(S(k).map((a,b)=>Math.abs(a-g[b]))),h=10)).map((a,b)=>Q(f[C="slice"](h,20))[(Q(f[C](0,h))[b]- -a)%h])),60)[C](h),T=((a,b,c)=>{if(r=Array(l=b[L]).fill(""),c){for(e=a[L]/l,i=0,w=[],u=R=b[X](x=0);i<e;)w[i++]=a[P](0,R++),u?u=0:R>l||(R=b[X](u=++x));for(i=0;i<e;)w[i]=J(w[i].concat(a[P](0,l-w[i++][L])));a=J(w)}for(i in a)r[+b[i%l]]+=a[i];return r}),v=J(T(u,Q(t))),q=J(Q(u[C](-h))),t="ABCDEFGHIJKLMNOPQRSTUVWXYZ#".match(new RegExp("[^"+d+"]","g")),t[P="splice"](9,0,"."),M=[];for(i in t)M[t[i]]=q[8^i/h]+(M[d[i]]=q[i%h]);for(n=c[L],b=J((c[C](n-=new Date%n)+"."+c[C](0,n)).split(/ |/).map(a=>M[a]||a)),b+=m.repeat(5-b[L]%5),i=f=q=49;f==q;)f=+u[i-1]+j,q=+u[i++]+j;return t=J(T(S(J(T(b,Q(v[C](0,f))))),Q(v.substr(f,q)),1)).match(/.{5}/g),g=-g[C](-1),g++&&t[P](g||t[L],0,k),t}
```

```
<div id="demo">
  <h2>Test</h1>
 <p><strong>Message: </strong><input id="message" type="text" value="WE ARE DISCOVERED. TAKE WHAT YOU CAN. BURN EVERYTHING ELSE. MOVE TO SAFEHOUSE FOXTROT #3#."/></p>
 <p><strong>Keyword: </strong><input id="keyword" type="text" value="SENATORI"/></p>
 <p><strong>Phrase: </strong><input id="phrase" type="text" value="THEFIRSTPRINCIPLEISTHATYOUMUSTNOTFOOLYOURSELFANDYOUARETHEEASIESTPERSONTOFOOL"/></p>
 <p><strong>Date: </strong><input id="date" type="text" value="3172016"/></p>
 <p><strong>Agent Id: </strong><input id="agent" type="text" value="9"/></p>
 <p><strong>Message Id: </strong><input id="mid" type="text" value="47921"/></p>
 <p><strong>Null: </strong><input id="null" type="text" value="4"/></p>
 </div>
 <input type="button" value="Run" onclick="alert(V(
 document.getElementById('message').value,
 document.getElementById('keyword').value,
 document.getElementById('phrase').value,
 document.getElementById('date').value,
 document.getElementById('agent').value,
 document.getElementById('mid').value,
 document.getElementById('null').value).join(', '))"/>
```

### Edit: -8 bytes

Realized there were extra parenthesis around function `S,J,A,Q`

### Edit: +15 bytes

Updated the logic for how the `message id` is placed in the final message (now 1-indexed and 0 does not include it in the output).

## Ungolfed

```
chainAdd = (s,l)=>{for(i=0;s.length<l;s+=(s[i++]- -s[i])%10);return s;}

sequentialize = (s)=> {
    a=s.split('').sort();
    return s.split('').map(c=>(i=a.indexOf(c),a[i]='',i));
}

transpose = (s,k,disruptive)=>{
    var result=Array(k.length).fill('')
    if(disruptive){
        rows=[]
        k_index=0;
        rowLength=k.indexOf(k_index);
        triangling=!rowLength;

        expectedRows = s.length/k.length
        for(row=0;row<expectedRows;row++){
            rows[row]=s.splice(0,rowLength++)
            if(triangling){
                if(rowLength>k.length){
                    triangling=false;
                    rowLength=k.indexOf(++k_index)
                }
            }
            else{
                triangling=true;
            }
        }

        for(row=0;row<expectedRows;row++){
            rows[row]= rows[row].concat(s.splice(0,k.length-rows[row].length)).join('')
        }
        s=rows.join('')
    }
    for(i in s)
        result[+k[i%k.length]]+=s[i];
    return result;
}

checkerboard =(message,seq, keyword, nulls)=>{
    t='ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.match(new RegExp('[^'+keyword+']','g'));
    t.splice(9,0,'.')

    map=[]
    for(i in t)
        map[t[i]]=(seq[8^(i/10)])+(map[keyword[i]]=seq[i%10])

    r = new Date%message.length;
    rotateMessage=message.substr(message.length-r)+'.'+message.substr(0,message.length-r)

    result =rotateMessage.split(/ |/).map(x=>map[x]||x).join('');
    result+=nulls.repeat(5-result.length%5)

    return result;
}

vic = (message, keyword, phrase, date, agent, m_id, nulls)=>{
    s1=sequentialize(phrase.substr(0,10))//.join('')
    s2=sequentialize(phrase.substr(10,10))//.join('')

    r = m_id.split('').map((x,i)=>Math.abs(x-date[i])).join('')
    g = chainAdd(r,10).split('').map((x,i)=>(s1[i]- -x)%10);

    t = g.map(i=>s2[+i]).join('');
    u=chainAdd(t,60).substr(10)

    var p,q;
    for(i=49;p==q;i++){
        p=agent + +u[i-1];
        q=agent + +u[i];
    }
    seqT = sequentialize(t);
    v=transpose(u,seqT).join('');

    k1 = sequentialize(v.substr(0,p));
    k2 = sequentialize(v.substr(p,q));
    c  = sequentialize(u.substr(-10)).join('')

    CB =checkerboard(message,c, keyword, nulls);
    t1=transpose(CB,k1).join('')
    t2=transpose(t1.split(''),k2,1).join('').match(/.{5}/g);
    (d=-date.substr(-1))&&t2.splice((d+1)||t2.length,0,m_id);
    return t2;
}

```

## Notes

* This uses a checkerboard similar to the following to encode the message:

```
  3 1 0 5 9 6 8 7 2 4
  S E N A T O R I
2 B C D F G H J K L .
4 M P Q U V W X Y Z #

```
* All strings are given in uppercase. The message is alphanumeric Latin (plus `.` and `#`) and should have all punctuation (except periods) removed. All numbers should already be marked with `#`s. The key phrase should have all punctuation/spaces removed.
* The resulting message is returned as an array of 5 digit strings.

## Enhancements

* I feel like there's a way to abuse the "All languages" to save some bytes. If I had more time I'd refigure this to assume the language was something like Hawaiian which has only 12 letters.
* Any golfing suggestions are always welcome.

# Answer
> 1 votes
## Clojure, ~~1197~~ 1212 bytes

Ough, I'm exhausted.

Update: Added the required random splitting location of the message, ungolfed version uses the same location as the given example so that algorithm can be easily verified.

```
(defn enc[I K E D Y M](let[P split-at A concat Z zipmap R partition W mapcat % count X repeat O vector / map x(fn[C](apply / O C))G range t 10 r(G t)m(fn[i](mod i t))F(fn[[n & N]](/ last(iterate(fn[[[b & N]a]][(A N[(m(+ a b))])b])[N n])))Q(fn[S](for[i(G(% S))a[(nth S i)]](apply +(%(filter #{a}(take i S)))(for[b S :when(pos?(compare a b))]1))))[S J](/ Q(P t(take 20 E)))T(/(Z r J)(/ m(/ + S(F(/ - M D)))))U(take 50(drop t(F T)))l(last U)p(+ Y(last(remove #{l}U)))V(W(Z(Q T)(x(R t U)))r)[k j](/ Q(P p(take(+ p Y l)V)))B(into(Z(/ char(G 48 58))(G))(/(fn[i c][c(+(*(quot i 10)20)(nth(Q(reverse(take t(reverse U))))(m i)))])(G)(A(str K",,")(remove(set K)(/ char(A(G 65 91)".#"))))))?(% k)T(vec(filter some?(W(Z k(x(R ?(A(flatten(R 5(A(W str(/ B(let[[b e](P(rand-int(count I))I)](apply str(A e".. "b)))))(X 4(B\,)))))(X(dec ?)nil)))))(G ?))))w (% j)NR(+(quot(% T)w)1)L(flatten(for[k r](for[i(G(.indexOf j k)(inc w))](G i))))C(for[[r c](/ O(rest(reductions + -1(/(fn[i](get{0 1}i 0))L)))L):when(< r NR)][r c])H(R 5(filter some?(W(Z j(x(R w (A(vals(into(sorted-map)(/ O(A C(for[i(G NR)j(G w)c[[i j]]:when(not((set C)c))]c))T)))(X(dec w)nil)))))(G w))))](/(fn[p](apply str p))(let[[b e](P(-(% H)(D 6)-1)H)](A b[M]e)))))

```

Sample inputs and test case:

```
(def mymsg (clojure.string/upper-case "We are discovered. Take what you can. Burn everything else. Move to Safehouse Foxtrot#3#"))
(def mykey "SENATORI")
(def mypharase (clojure.string/upper-case (apply str (remove #{\space} "The first principle is that you must not fool yourself — and you are the easiest person to fool."))))
(def mydate [3 1 7 2 0 1 6])
(def mynum 9)
(def M [4 7 9 2 1])

;("61231" "12824" "71192" "58609" "92185" "48612" "14927" "22944" "34046" "13348" "04159" "38645" "70546" "20254" "22026" "64584" "21904" "47921" "90253" "42694" "42221" "56644" "14541")
(enc mymsg mykey mypharase mydate mynum M)

```

Ungolfed:

```
(defn enc[mymsg mykey mypharase mydate mynum M]
  (let[t       10
       r       (range t)
       m       (fn[i](mod i t))
       lagfib  (fn[[n & N]](map last(iterate(fn[[[b & N]a]][(concat N[(m(+ a b))])b])[N n])))
       toseq   (fn[S](for[i(range(count S))a[(nth S i)]](apply +(count(filter #{a}(take i S)))(for[b S :when(pos?(compare a b))]1))))
       [S1 S2] (map toseq(split-at t(take 20 mypharase)))
       M2      (take t(lagfib(map - M mydate)))
       G       (map m(map + S1 M2))
       Gmap    (zipmap r S2)
       T       (map Gmap G)
       U       (take 50(drop t(lagfib T)))
       L2      (last U)
       L1      (last(remove #{L2}U))
       p       (+ mynum L1)
       q       (+ mynum L2)
       seqT    (toseq T)
       V       (mapcat(zipmap seqT(apply map vector(partition t U)))r)
       [K1 K2] (map toseq(split-at p(take(+ p q)V)))
       C       (toseq(reverse(take t(reverse U))))
       B       (into(zipmap(map char(range 48 58))(range))(map(fn[i c][c(+(*(quot i 10)20)(nth C(m i)))])(range)(concat(str mykey",,")(remove(set mykey)(map char(concat(range 65 91)".#"))))))
      ;B       (into(zipmap(map char(range 48 58))(range))(map(fn[i c][c(+(nth C(quot i 3))(*(mod i 3)20))])(range)(flatten(apply map vector(partition 10(apply concat mykey",,"(apply map vector (partition 2(remove(set mykey)(map char(concat(range 65 91)".#")))))))))))
       N1      (count K1)
       mymsg   (flatten(partition 5(concat(mapcat str(map B(let[[b e](split-at 49 mymsg)](apply str(concat e".. "b)))))(repeat 4(B\,)))))
       T1      (vec(filter some?(mapcat(zipmap K1(apply map vector(partition N1(concat mymsg(repeat(dec N1)nil)))))(range N1))))
       N2      (count K2)
       NR      (+(quot(count T1)N2)1)
       cols    (flatten(for[k r](for[i(range(.indexOf K2 k)(+(count K2)1))](range i))))
       rows    (rest(reductions + -1(map(fn[i](get{0 1}i 0))cols)))
       coords  (for[[r c](map vector rows cols):when(< r NR)][r c])
       coords  (concat coords(for[i(range NR)j(range N2)c[[i j]]:when(not((set coords)c))]c))
       T2      (partition 5(filter some?(mapcat(zipmap K2(apply map vector(partition N2(concat(vals(into(sorted-map)(map vector coords T1)))(repeat(dec N2)nil)))))(range N2))))]
    (map(fn[p](apply str p))(let[[b e](split-at(-(count T2)(mydate 6)-1)T2)](concat b[M]e)))))

```

It has an alternative implementation on the checkerboard `B` which is the same as on the task definition. But the submission uses an other one in which unused alphabets first fill the 2nd row and then the 3rd instead of filling column-by-column.

---
Tags: code-golf, cryptography
---


# Question
Title: Truth Tables: Your great-grandfather's computer
If you remember back to your schooling years, you might remember learning about Truth Tables. They seemed boring, but they are basis for logic and (some would argue) all computing...

---

# Problem

Your mission, should you choose to accept it is to write a program, function, or widget of code that can output a truth table given input.

## Input

Input will be a string (like data structure) containing the logic statement to make the Truth Table into. For example:

```
p ∧ q

```

This means `p and q`(logical conjuction) and will output:

```
 p  q  p ∧ q
 T  T    T
 T  F    F
 F  T    F
 F  F    F

```

Notice the spacing: The item of the column is **in the center of the header**

# Characters

**Score via characters, not bytes** The logic comparison characters are special and not always what they look like. Use these characters:

Logical Conjunction (AND):  U+2227

Logical Disjunction (OR):  U+2228

Logical Negation (NOT) `~` or `¬` U+7e and U+ac respectively

---

# Bonuses

All of these bonuses are optional, but will knock points off your score. Pick any.

## Logical Negation

Logical Negation is a unary operator in truth tables. It is the equivalent of `!` in most C-based languages. It makes `false`=\>`true` and vise versa. It is notated with a `¬` **or** `~` (you must support both). **Supporting this will knock off 10% of your score.** You must, however, add an additional column to show its results: For example:

```
~p ∧ q

```

will output:

```
p  ~p  q  ~p ∧ q
T  F   T     F
T  F   F     F
F  T   T     T
F  T   F     F

```

## Pretty Print

The normal table notation is boring. Let's make it pretty! Pretty print format is as follows for `p ∧ q` is as follows:

```
+---+---+-------+
| p | q | p ∧ q |
+---+---+-------+
| T | T |   T   |
+---+---+-------+
| T | F |   F   |
+---+---+-------+
| F | T |   F   |
+---+---+-------+
| F | F |   F   |
+---+---+-------+

```

Special details for pretty printing:

* There is a 1 space padding in each cell
* Cell values are still centered

If you pretty print your tables, from your code and then multiply by 0.6. Use this function for this bonus:

```
score = 0.6 * code

```

---

# Examples

`p ∧ q`:

```
p  q  p ∧ q
T  T    T
T  F    F
F  T    F
F  F    F

```

`p ∨ q`:

```
p  q  p ∨ q
T  T    T
T  F    T
F  T    T
F  F    F

```

`~p ∧ q`:

```
p  ~p  q  ~p ∧ q
T   F  T     F
T   F  F     F
F   T  T     T
F   T  F     F

```

`~p ∨ q`:

```
p  ~p  q  ~p ∧ q
T   F  T     T
T   F  F     F
F   T  T     T
F   T  F     T

```

---

# Rules

* Standard loopholes apply
* No external resources
* If you're going to break the rules, be clever ;)

Shortest Code (in characters) wins. Good Luck!

# Answer
# JavaScript (ES6), 141

Simple function, no bonus, 141 chars. (140 uft8, 1 unicode wide)

Complex function handling ~ or ¬, 254 chars (253 utf, 1 unicode wide), score 229

Could save 6 bytes using `alert` instead of `console.log`, but `alert` is particularly unfit to display tables.

Test running the snippet below in an EcmaScript 6 compliant browser (tested with Firefox. Won't work in Chrome as Chrome does not support `...`. Also, the bonus version use an extension of `split` that is Firefox specific).

```
/* TEST: redirect console.log into the snippet body */ console.log=x=>O.innerHTML+=x+'\n'

// Simple
F=s=>{[a,o,b]=[...s],z='  ',r=a+z+b+z+a+` ${o} ${b}
`;for(w='FT',n=4;n--;r+=w[c]+z+w[e]+z+z+w[o<'∧'?c|e:c&e]+`
`)c=n&1,e=n>>1;console.log(r)}

// Simple, more readable
f=s=>{
   [a,o,b]=[...s]
   r=a+'  '+b+'  '+a+` ${o} ${b}\n`
   for(w='FT',n=4; n--; )
   {
     c = n&1, e = n>>1, x=o<'∧' ? c|e : c&e
     r += w[c]+'  '+w[e]+'    '+w[x]+'\n'
   }
   console.log(r)
}

// 10% Bonus
B=s=>{[a,o,b]=s.split(/([∧∨])/),t=a>'z',u=b>'z',z='  ',r=(t?a[1]+z:'')+a+z+(u?b[1]+z:'')+b+z+a+` ${o} ${b}
`;for(s=v=>'FT'[v]+z,n=4;n--;r+=s(c)+(t?s(d)+' ':'')+s(e)+(u?s(f)+' ':'')+(t?'   ':z)+s(o<'∧'?d|f:d&f)+`
`)c=n&1,d=c^t,e=n>>1,f=e^u;console.log(r)}

Test1 = ['q∨p','q∧p']
Test2 = Test1.concat([
  '~q∨p','q∨~p','~q∨~p','~q∧p','q∧~p','~q∧~p',
  '¬q∨p','q∨¬p','¬q∨¬p','¬q∧p','q∧¬p','¬q∧¬p'
])

console.log('SIMPLE')
Test1.forEach(t=>F(t));

console.log('BONUS')
Test2.forEach(t=>B(t));
```

```
<pre id=O></pre>
```
> 6 votes

# Answer
# MediaWiki template - 2347 characters

MediaWiki has a built template function called `{{#expr}}` that can handle logical expressions. This must be the perfect challenge for MediaWiki templates! Features such as variables, loops and a readable syntax would have helped a bit, though. Also, the fact that there is no NOT operator for the expr function made it a bit more complex.

```
{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}} {{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}} {{{1}}}<br>T T  {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|0|1}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|0|1}}|0|1}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}<br>T F  {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|0|1}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|1|0}}|1|0}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}<br>F T  {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|1|0}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|0|1}}|0|1}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}<br>F F  {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|1|0}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|1|0}}|1|0}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}

```

**Test:**

```
{{TemplateName|¬X ∧ ~Y}}

{{TemplateName|p ∨ q}}

```

**Result:**

```
X Y ¬X ∧ ~Y
T T    F
T F    F
F T    F
F F    T

p q p ∨ q
T T   T
T F   T
F T   T
F F   F

```

I'm assuming MediaWiki \>= 1.18, where the ParserFunctions extensions comes bundled with the software.
> 6 votes

# Answer
## Python - 288 characters (+10 penalty cause I couldn't get unicode to work :c)

No bonuses. This is my very first codegolf answer.

```
def f(i):
    i=i.split(" ")
    print i[0],i[2],
    for f in i[0:3]: print f,
    print ""
    for t in["TT","TF","FT","FF"]:
        p,q=t[0],t[1]
        y = t[0]+" "+t[1]
        if i[1]=="^": r=(False,True)[p==q]
        if i[1]=="v": r=(False,True)[p!=q]
        if r: y+="   T"
        else: y+="   F"
        print y

```

`i` is the input.

**EDIT:** Removed a few spaces and it now uses function args as input.
> 4 votes

# Answer
# Dyalog APL, ~~58~~ 48 characters

Requires `⎕IO←0`, which is default on many systems. Takes string as argument.

```
{('p q ',⍵)⍪'FT '[p,q,⍪⍎⍵]\⍨324⊤⍨9⍴≢p q←↓2 2⊤⌽⍳4}

```

No bonuses, but on the plus side, any operator works.

`⍳4` first four indices (0 1 2 3)

reverse (3 2 1 0)

`2 2⊤` two-bit Boolean table

split into two-element list of lists (high-bits, low-bits)

`p q←` store as *p* and *q*

tally them (2)\*

`9⍴` cyclically reshape that to length 9 (2 2 2 2 2 2 2 2 2)

`324⊤⍨` encode 324 thusly, i.e. as 12-bit binary (1 0 1 0 0 0 1 0 0)

`\⍨` use that to expand (insert a space for each 0)...

`'FT '[`...`]` the string "FT ", indexed by

`⍎⍵` the executed argument (valid since *p* and *q* now have values)

make that into a column matrix

`q,` prepend a column consisting of *q* (1 1 0 0)

`q,` prepend a column consisting of *p* (1 0 1 0)

`(`...`)⍪` insert a row above, consisting of

the argument

`'p q ',` prepended with the string "p q "

---

* Please star this issue if you see  as `≢` and not as `̸≡`.
> 3 votes

# Answer
# Julia, 161 bytes

No bonuses.

```
s->(S=split(s);P=println;p=S[1];q=S[3];a=[&,|][(S[2]=="∨")+1];c="  ";P(p,c,q,c,s);for t=["TT","TF","FT","FF"] P(t[1],c,t[2],c^2,"FT"[a(t[1]>'F',t[2]>'F')+1])end)

```

Ungolfed:

```
function f(s::String)
    # Split the input on spaces
    S = split(s)

    # Separate out the pieces of the statement
    p = S[1]
    q = S[3]
    a = [&, |][(S[2] == "∨") + 1]

    # Print the header
    println(p, "  ", q, "  ", s)

    # Create the table entries in a loop
    for t = ["TT", "TF", "FT", "FF"]
        println(t[1], "  ", t[2], "    ", "FT"[a(t[1] > 'F', t[2] > 'F') + 1])
    end
end

```
> 2 votes

# Answer
## Python3, 145 139 120 119 Bytes

No bonus (with bonus at the end)

```
 def f(s):
 a,m,b=s.split(" ");print(a,b,s);F,T,c=0,1,"FT"
 for p in c:
  for q in c:print(p,q," ",c[eval(p+"+*"[m=="∧"]+q)>0])

```

Needing Python3 for Unicode support out of the box.

Based on DJgamer98 Python code, figuring out his table is not right.

Edit1: Splitting into distinct variables and ommiting the operator string variable

Edit2: (ab)using F and T as both variables and string characters

Edit3: Saving one space thanks to NoOneIsHere

### With Bonus, 215 * 0.6 = 129

```
def f(s):
 r="+---"*3+"----+"
 a,m,b=s.split(" ");F,T,c=0,1,"FT"
 print("%s\n| %s | %s | %s |\n%s"%(r,a,b,s,r));
 for p in c:
  for q in c: print("| %s | %s |   %s   |\n%s"%(p,q,c[eval(p+"+*"[m=="∧"]+q)>0],r));

```
> 2 votes

# Answer
## C/C++ 302 Bytes

335 characters less 10% for handling negation. Formatting incomplete but submitting before I see what the impact of completion is.

Marked as C/C++ because my gcc and g++ accepts it with -fpermissive and it looks far more C like than C++ to me.

```
#include <stdio.h>
void T(char*S) { int (*P)(char*,...)=printf;char*v[2]={"F","T"};for(int m=4;m--;){P("|");char*s=S;int x=m&1;X:P(" %s |",v[x]);if(*++s!=' '){x=x^1;goto X;}char*o=++s;s+=3;int y=(m>>1)&1;Y:P(" %s |",v[y]);if(*++s){y=y^1;goto Y;}int g;for(g=o-S+1;g--;)P(" ");P(*++o==39?v[x&y]:v[x|y]);for(g=s-o;g--;)P(" ");P("|\n");}}

```

I'm sure there's probably a few tweaks that could be applied. In fact handling the nots adds more than the 10% bonus removes.

This does assume the input format is as stated, i.e. 2 input values (p and q), with or without the not prefix and nothing else, and all tokens delimited by a single space.

Ungolfed:

```
void ungolfed(char* S)
{
   int (*P)(char*,...) = printf;         // useful lookup stuff
   char* v[2] = {"F","T"};

   for(int m = 4; m--;) {                // loop over all 2 bit bit patterns (truth table inputs)

      P("|");                            // start of line format
      char* s=S;                         // iterator to start of equation for each bit pattern

      int x = m&1;                       // input 1 (aka. p which I called x here to be awkward)
X:    P(" %s |",v[x]);                   // input 1 output and format

      if(*++s!=' ') {                    // if next character is not a space then input must be prefixed with the not character
         x=x^1;                          // so negate the input
         goto X;                         // and redo input 1 output
      }

      char* o = ++s;                     // remember where the operator is
      s+=3;                              // and skip it and following space

      int y = (m>>1)&1;                  // input 2 (aka. q which I called y obviously) processing as for input 1
Y:    P(" %s |",v[y]);

      if(*++s) {
         y=y^1;
         goto Y;
      }

      int g;

      for(g=o-S+1;g--;) P(" ");         // pre-result value padding

      P(*++o==39?v[x&y]:v[x|y]);      // result

      for(g=s-o;g--;) P(" ");           // post-result value padding and format
      P("|\n");
   }
}

```

and the tests:

```
int main()
{
   T("p \x22\x27 q");  // p & q
   puts("");

   T("p \x22\x28 q");  // p | q
   puts("");

   T("\x7ep \x22\x27 q");  // ~p & q
   puts("");

   T("\xacp \x22\x28 q");  // ~p | q
   puts("");

   T("p \x22\x28 \xacq");  // p | ~q
   puts("");

   return 0;
}

```
> 2 votes

# Answer
## Mathematica, 129 Bytes

**Golfed:**

```
t=InputString[];s=Append[StringCases[t,LetterCharacter],t];Grid[Prepend[Map[If[#,"T","F"]&,BooleanTable[ToExpression[s]],{2}],s]]

```

**Ungolfed:**

```
(*Take input*)
t=InputString[];
(* Find all occurrences of letters and append the final statement.*)
s=Append[StringCases[t,LetterCharacter],t];
(* Evaluate the list as expressions and create a boolean table of True/False values, then display as a table. *)
(* To satisfy the output conditions, we must convert each True/False to T/F *)
Grid[Prepend[Map[If[#,"T","F"]&,BooleanTable[ToExpression[s]],{2}],s]]

```

Not a Mathematica expert, but I found this rather elegant compared to having to do direct character comparison.

I had a solution that worked for negation, but it was longer than the score reduction would take off.

Depending on what qualifies for pretty printing, I might try for that bonus. I feel like outputting in ASCII in Mathematica would be far too expensive for the score reduction to compensate, but if the two main features are a dotted border and specified padding inside the cells, that's only a couple options in Grid.

**With pretty printing, 171 * 0.6 = 102.6 Bytes**

```
t=InputString[];s=Append[StringCases[t,LetterCharacter],t];Grid[Prepend[Map[If[#,"T","F"]&,BooleanTable[ToExpression[s]],{2}],s],Spacings->1,Frame->All,FrameStyle->Dashed]

```
> 1 votes

# Answer
## Mathematica, 128 characters

```
TraditionalForm@Grid[({#}~Join~BooleanTable[#,Cases[b,_Symbol,{0,∞}]]&/@Cases[b=ToExpression@#,_,{0,∞}]/.{0<1->"T",0>1->"F"})]&

```

is the private use character `U+F3C7` representing `\[Transpose]`.

Luckily for us Mathematica golfers,  and  *already* represent `And` and `Or`, so all we have to do is convert the input string into a Mathematica expression and we can do symbolic logical operations on it.

Note that this solution will also handle `Not` (`¬`), `Implies` (), `Equivalent` (), `Xor` (), `Nand` (), `Xor` (), and `Nor` (), but it doesn't get the bonus because `~p` is a syntax error in Mathematica. Meh.

## Explanation

```
b=ToExpression@#

```

Converts the input string into a Mathematica expression and stores it in `b`.

```
Cases[b=ToExpression@#,_,{0,∞}]

```

This is a list every possible subexpression of the input. Each will receive its own column.

```
Cases[b,_Symbol,{0,∞}]

```

This is a list of all of the variables that appear in the input.

```
BooleanTable[#,Cases[b,_Symbol,{0,∞}]]&

```

Pure function which takes an input expression `#` and returns a list of truth values for all possible combinations of truth values for the variables.

```
{#}~Join~BooleanTable[...]

```

Prepends the expression itself to this list.

```
.../@Cases[b=ToExpression@#,_,{0,∞}]

```

Applies this function to each subexpression of the input.

```
.../.{0<1->"T",0>1->"F"}

```

Then replace true (`0<1`) with "T" and false (`0>1`) with "F".

```
(...)

```

Interchange rows and columns.

```
Grid[...]

```

Display the result as a `Grid`.

```
TraditionalForm@Grid[...]

```

Convert the `Grid` to traditional form so that it uses the fancy symbols.
> 1 votes

---
Tags: code-golf, ascii-art, logic-gates
---


title: Find an Eulerian Circuit

text:
# Question
Title: Find an Eulerian Circuit
## Challenge

You have been assigned a task to write a program which takes a multigraph as its input and if it contains an Eularian circuit to return one. Otherwise, the program's behavior is undefined, according to the specifications you're handed by your boss.

However, you recently caught your new coworker Steven several times treating undefined behavior in C carelessly and urged him be more careful because undefined behavior can also mean that all files on the system get deleted. He now dared you to write your program in a way such that it deletes itself when the aforementioned case of (previously) undefined behavior occurs. You don't want to lose your honor and accept.

## Description

An Eulerian circuit is a circuit in an undirected multigraph which visits every edge exactly once.

You may choose the formats of your program's input and output yourself. They don't need to be the same formats. For example, you may take a description of the edges like

```
({1,2},{1,4},{2,4},{2,3},{2,3})

```

as your input for this graph

, but return a sequence of vertices as your output:

```
(1,2,3,2,4,1)

```

## Details

You don't need to be able to accept multigraphs which contain vertices without edges.

Holding your program only in RAM and terminating it afterwards doesn't count as deleting it. It needs to be in a file. The file must only be deleted if no Eulerian circuit exists in the input multigraph.

The vertices have to be identifiable (it needs to be possible to tell the Euler circuit in the input provided the output of your program), the edges don't. However, you may restrict the means of identification (e.g. only positive integers or only strings consisting of a `#` followed by a positive integer) as long as large graphs are representable (only 1 letter of the English alphabet isn't sufficient). Identifiers don't have to be explicit. For example, you may let the order of the input determine the number a vertex is identified with in the output.

The means of output (saved to a file, printed at stdout, return value of a function) don't matter.

You can't rely on the name of your program on the disk not changing. If you only write a function, you still have to delete the file on the disk.

## Victory Condition

This is code golf, shortest code wins.

---

**Spoiler warning for this link:** Simple algorithms to solve this problem can be found on the internet.

# Answer
> 4 votes
# Mathematica, 48 bytes

```
FindEulerianCycle@#/.{}->DeleteFile@FileNames[]&

```

Yep, there's a builtin for that. It returns `{}` if there's no Eulerian cycle, so we manually redirect that to a command deleting all files in the current working directory.

---
Tags: code-golf, graph-theory
---


title: Obfuscated Integer Notation

text:
# Question
Title: Obfuscated Integer Notation
**Edit: I will be posting a newer version of this question on `meta-golf` soon. Stay tooned!**

**Edit #2: I will no longer be updating the challenge, but will leave it open. The `meta-golf` version is available here: https://codegolf.stackexchange.com/questions/106509/obfuscated-number-golf**

# Background:

Most numbers can be written with only 6 different symbols:

* `e` (Euler's Constant)
* `-` (Subtraction, Not Negation)
* `^` (Exponentiation)
* `(`
* `)`
* `ln` (Natural Logarithm)

For example, you could convert the imaginary number `i` using this equation:

```
(e-e-e^(e-e))^(e^(e-e-ln(e^(e-e)-(e-e-e^(e-e)))))

```

# Goal:

Given any integer `k` through any reasonable means, output the shortest representation possible of that number using only those 6 symbols.

# Examples:

```
0 => "e-e"
1 => "ln(e)"
2 => "ln(ee)"
// Since - cannot be used for negation, this is not a valid solution:
// ln(e)-(-ln(e))
-1 => "e-e-ln(e)"

```

# Notes:

* Ending parenthesis count towards the total amount of characters.
* `ln(` only counts as 1 character.
* Everything else counts as 1 character.
* `n^0=1`
* Order of operations apply
* Parenthesis multiplying is acceptable, e.g. `(2)(8)=16`, `2(5)=10`, and `eln(e)=e`.
* `ln e` is not valid, you must do `ln(e)`

# Answer
> 2 votes
# Python 3, 402 bytes

```
from itertools import*
from ast import*
from math import*
v,r=lambda x:'UnaryOp'not in dump(parse(x)),lambda s,a,b:s.replace(a,b)
def l(x,y):
    for s in product('L()e^-',repeat=x):
        f=r(r(r(''.join(s),'L','log('),')(',')*('),'^','**')
        g=r(f,'ee','e*e')
        while g!=f:f,g=g,r(g,'ee','e*e')
        try:
            if eval(g)==y and v(g):return g
        except:0
def b(v):
    i=1
    while 1:
        r=l(i,v)
        if r:return r
        i+=1

```

Example usage:

```
>>> b(1)
'log(e)'
>>> b(0)
'e-e'
>>> b(-3)
'e-log(e*e*e)-e'
>>> b(8)
'log(e*e)**log(e*e*e)'

```

Note that although the output format may not reflect it, the code properly counts all lengths according to the question's specifications.

This is a dumb bruteforce through all the possible lengths of strings. Then I use some replacements so that Python can evaluate it. If it's equal to what we want, I also check to exclude unary negative signs by checking the AST.

I'm not very good at golfing in Python, so here's the semi-ungolfed code if anybody wants to help!

```
from itertools import*
from ast import*
from math import*

def valid(ev):
    return 'UnaryOp' not in dump(parse(ev))

def to_eval(st):
    f = ''.join(st).replace('L', 'log(').replace(')(', ')*(').replace('^', '**')
    nf = f.replace('ee', 'e*e')
    while nf != f:
        f, nf = nf, nf.replace('ee', 'e*e')
    return nf

def try_length(length, val):
    for st in product('L()e^-', repeat=length):
        ev = to_eval(st)
        try:
            if eval(ev) == val and valid(ev):
                return st
        except:
            pass

def bruteforce(val):
    for i in range(11):
        res = try_length(i, val)
        if res:
            print(i, res)
            return res

```

---
Tags: code-golf, math, number, number-theory
---


title: Make a string a e s t h e t i c

text:
# Question
Title: Make a string a e s t h e t i c
Basically, between every character of a uni-line string, add a space, but there can't be two spaces in between one character.

* `aesthetic` becomes `a e s t h e t i c`.
* `The quick brown fox jumps over the lazy dog` becomes `T h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g`.
* `I'm Nobody! Who are you?` becomes `I ' m n o b o d y ! W h o a r e y o u ?`

This is code golf, so the shortest answer in bytes wins.

# Answer
> 2 votes
# Jelly, 3 bytes

```
ḟ⁶K

```

ilter out spaces () then join by space (`K`).

Try it online!

# Answer
> 2 votes
# Python, 36 bytes

```
lambda s:" ".join(s.replace(" ",""))

```

# Answer
> 2 votes
# Retina, 8

```

.
$0

```

Whitespace is significant - there are single spaces at the end of the first and last lines.

Try it online.

# Answer
> 2 votes
# Pyth, 4 bytes

```
jdsc

```

Splitting on whitespace and then joining seems shorter than removing the spaces.

In pseudocode:

```
'     ' d,Q = " ",input()  # preinitialized variables
'jd   ' d.join(
'  s  '     sum(
'   cQ'         Q.split() ))

```

Try it online!

# Answer
> 1 votes
## Haskell, 22 bytes

```
(((:" ")=<<)=<<).words

```

Laikoni saved 2 bytes with a nice use of `words`. Previous answer:

```
(=<<)(:" ").filter(>' ')

```

Try it online

# Answer
> 0 votes
# , 7 bytes

```
Íó*/
X

```

Try it online!

Just a straightforward regex, and an "X" to delete one leading space.

# Answer
> 0 votes
# tcl, 28

```
puts [split [join $s ""] ""]

```

testable on http://rextester.com/VFP77495

---
Tags: code-golf, string
---


title: Generate lazy values

text:
# Question
Title: Generate lazy values
Related: Program my microwave oven. Inspired by Generate lazy microwave input.

The lazy value of the non-negative integer *N* is the smallest of the integers that are closest to *N* while all their digits are identical.

Return (by any means) the lazy value of a given (by any means) *N*.

*N*~~the largest integer that your language represents in non-exponent form by default.~~ 1000000 (A lot of interesting solutions are lost because of this too-high requirement.)

## Test cases:

```
   0 →    0
   8 →    8
   9 →    9
  10 →    9
  16 →   11
  17 →   22
  27 →   22
  28 →   33
 100 →   99
 105 →   99
 106 →  111
 610 →  555
 611 →  666
7221 → 6666
7222 → 7777

```

---

The colleague in question proved that there will be no ties: Except for 9/11, 99/111, etc. for which one is shorter than the other, two consecutive valid answers are always an odd distance apart, so no integer can be exactly equidistant from them.

# Answer
> 15 votes
## JavaScript (ES6), 31 bytes

```
n=>~-(n*9+4).toPrecision(1)/9|0

```

Directly computes the lazy value for each `n`.

Edit: Only works up to 277777778 due to the limitations of JavaScript's integer type. Alternative versions:

```
n=>((n*9+4).toPrecision(1)-1)/9>>>0

```

35 bytes, works up to 16666666667.

```
n=>((n=(n*9+4).toPrecision(1))-n[0])/9

```

38 bytes, works up to 944444444444443. But that's still some way short of 253 which is 9007199254740992.

# Answer
> 5 votes
# Jelly, 16 bytes

```
ḤRµDIASµÐḟµạ³ỤḢị

```

Try it online!

### How it works

```
ḤRµDIASµÐḟµạ³ỤḢị  Main link. Input: n

Ḥ                 Compute 2n.
 R                Yield [1, ..., 2n] or [0].
  µ               Begin a new, monadic chain. Argument: R (range)
   D              Convert to base 10.
    I             Compute all differences of consecutive decimal digits.
     A            Take the absolute values of the differences.
      S           Sum the absolute values.
       µÐḟ        Filter-false by the chain to the left.
          µ       Begin a new, monadic chain. Argument: L (lazy integers)
           ạ³     Take the absolute difference of each lazy integer and n (input).
             Ụ    Grade up; sort the indices of L by the absolute differences.
                  This is stable, so ties are broken by earlier occurrence and,
                  therefore, lower value.
              Ḣ   Head; retrieve the first index, corresponding to the lowest
                  absolute difference.
               ị  Retrieve the item of L at that index.

```

# Answer
> 4 votes
# Oracle SQL 11.2, 200 bytes

```
WITH v(i)AS(SELECT 0 FROM DUAL UNION ALL SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1)FROM v WHERE LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1)SELECT:1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum)FROM v;

```

Un-golfed

```
WITH v(i) AS
(
  SELECT 0 FROM DUAL      -- Starts with 0
  UNION ALL
  SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1) -- Increments i, alternating between negatives and positives
  FROM   v
  WHERE  LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1  -- Stop when the numbers is composed of only one digit
)
SELECT :1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum) FROM v;

```

# Answer
> 3 votes
# Pyth - 26 bytes

~~This answer doesn't always return the smallest value in a tie, but that isn't in the specs, so awaiting clarification~~ fixed for 3 bytes.

```
hSh.g.a-kQsmsM*RdjkUTtBl`Q

```

Test Suite.

# Answer
> 3 votes
# MATL, 25 bytes

```
2*:"@Vt!=?@]]N$vtG-|4#X<)

```

Uses brute force, so it may take a while for large numbers.

**Try it online!**

```
2*:       % range [1,2,...,2*N], where is input
"         % for each number in that range
  @V      %   push that number, convert to string
  t!=     %   test all pair-wise combinations of digits for equality
  ?       %   if they are all equal
    @     %     push number: it's a valid candidate
  ]       %   end if
]         % end for each
N$v       % column array of all stack contents, that is, all candidate numbers
t         % duplicate
G-|       % absolute difference of each candidate with respect to input
4#X<      % arg min
)         % index into candidate array to obtain the minimizer. Implicitly display

```

# Answer
> 3 votes
# Pyth, 16 bytes

```
haDQsM*M*`MTSl`Q

```

Try it online: Demonstration or Test Suite

### Explanation:

```
haDQsM*M*`MTSl`Q   implicit: Q = input number
              `Q   convert Q to a string
             l     take the length
            S      create the list [1, 2, ..., len(str(Q))]
         `MT       create the list ["0", "1", "2", "3", ..., "9"]
        *          create every combination of these two lists:
                   [[1, "0"], [1, "1"], [1, "2"], ..., [len(str(Q)), "9"]]
      *M           repeat the second char of each pair according to the number:
                   ["0", "1", "2", ..., "9...9"]
    sM             convert each string to a number [0, 1, 2, ..., 9...9]
  D                order these numbers by:
 a Q                  their absolute difference with Q
h                  print the first one

```

# Answer
> 3 votes
# Perl, 32

Based on the beautiful JavaScript solution by Neil.

```
$_=0|1/9*~-sprintf"%.e",$_*9+4.1

```

Starts to fail at `5e15`

# Answer
> 2 votes
# Mathematica, 122 bytes

```
f@x_:=Last@Sort[Flatten@Table[y*z,{y,1,9},{z,{FromDigits@Table[1,10~Log~x+1-Log[10,1055555]~Mod~1]}}],Abs[x-#]>Abs[x-#2]&]

```

Function named x.

# Answer
> 2 votes
# JavaScript (ES6), 59 bytes

```
n=>eval(`for(i=a=0;i<=n;a=i%10?a:++i)p=i,i+=a;n-p>i-n?i:p`)

```

### Recursive Solution (56 bytes)

This is a bit shorter but does not work for `n > 1111111110` because the maximum call stack size is exceeded, so it is technically invalid.

```
f=(n,p,a,i=0)=>n<i?n-p>i-n?i:p:f(n,i,(i-=~a)%10?a:i++,i)

```

## Explanation

Iterates through every lazy number until it gets to the first which is greater than `n`, then compares `n` to this and the previous number to determine the result.

```
var solution =

n=>
  eval(`           // eval enables for loop without {} or return
    for(
      i=a=0;       // initialise i and a to 0
      i<=n;        // loop until i > n, '<=' saves having to declare p above
      a=i%10?a:++i // a = amount to increment i each iteration, if i % 10 == 0 (eg.
    )              //     99 + 11 = 110), increment i and set a to i (both become 111)
      p=i,         // set p before incrementing i
      i+=a;        // add the increment amount to i
    n-p>i-n?i:p    // return the closer value of i or p
  `)
```

```
N = <input type="number" oninput="R.textContent=solution(+this.value)"><pre id="R"></pre>
```

# Answer
> 2 votes
# Japt, 18 bytes

```
9*U+4 rApUs l¹/9|0

```

Try it online!

Based on Neil's technique

Non-competing solution:

```
*9+4 h /9|0

```

# Answer
> 1 votes
# 05AB1E, 20 bytes

```
9Ývy7L×})˜ïD¹-ÄWQÏ{¬

```

Try it online!

```
9Ý                   # Push 0..9
  vy7L×})˜           # For each digit, 0-9, push 1-7 copies of that number.
          ïD         # Convert to integers, dupe the list.
            ¹        # Push original input (n).
             -Ä      # Push absolute differences.
               WQ    # Get min, push 1 for min indices.
                 Ï{¬ # Push indices from original array that are the min, sort, take first.

```

# Answer
> 1 votes
## Mathematica, 56 bytes

```
Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,6},{d,0,9}],#]&

```

Pure function with first argument `#`, works for inputs up to `10^6`.

For a nonnegative integer `n` and a digit `d`, `10^n-1 = 99...9` (`9` repeated `n` times), so `d(10^n-1)/9 = dd...d` (`d` repeated `n` times). Creates a `Table` of values for `0 <= n <= 6` and `0 <= d <= 9`, then flattens the table, finds the list of elements `Nearest` to `#` and takes the `Min`.

I believe this version will work for arbitrarily large integers:

```
Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,IntegerLength@#},{d,0,9}],#]&

```

---
Tags: code-golf, number, number-theory
---


# Question
Title: Converting Numbers to a "Not quite place-value system"
Lets create a system of numbers where the biggest digit in the nth place value (counting from right to left) of a number length m is always equal to m - n + 1. To give an example the largest 5 digit number expressible in this system is written 12345. Apart from the number of digits available to be used in a particular place being restricted, all other incrementation is standard. Namely when a digit is to surpass its digit limit we add one to the next digit.

Here is how counting would be represented in this system:

```
1; 10; 11; 12; 100; 101; 102; 103; 110; 111; 112; 113; 120; 121; 122; 123; 1000; 1001 ...

```

Your task is to write a function that takes a standard base 10 number and converts it to my numbering system.

Shorter code is preferable. Bonne Chance!

\**If you need digits after 9 (you should) you can choose to use letters, or you can you return a 2 digit number as an element of a list.

Test Cases

```
10 -> 111
20 -> 1003
30 -> 1023
50 -> 1123
100 -> 10035
23116 -> 1234567
21977356 -> 123456789A

```

Last case may be incredibly slow to run depending on how you implemented. You don't need to run it if it takes too long or uses too much memory. However note that there exist ways to have it run quickly and using little memory.

# Answer
> 4 votes
# Mathematica, 64 bytes

```
Part[Join@@Array[Tuples@Join[{{1}},Array[Range,#-1,3]-1]&,#],#]&

```

Unnamed function taking a positive integer argument and returning a list of integers.

`Join[{{1}},Array[Range,#-1,3]-1]` returns the nested list `{ {1}, {0,1,2}, {0,1,2,3}, ..., {0,1,...,#} }`. Then `Tuples` returns the (sorted) set of all tuples whose first element lies in `{1}`, whose second element lies in `{0,1,2}`, and so on; these are the `#`-digit numbers in this numbering system. `Join@@Array[...,#]` returns an array of all the numbers in this numbering system with at most `#` digits, and `Part[...,#]` extracts the `#`th such number.

This is hopelessly slow! It runs fine for the input up to 9. For larger input, test it by replacing the end `,#],#]&` with `,Ceiling[0.9Log[#]]],#]&`; this puts a more realistic cap on the number of digits necessary to go far enough in the numbering system to find the one we want.

# Answer
> 3 votes
## Mathematica, 93 bytes

```
Nest[#/.{x___,y_}:>{x,y+1}//.x:{y___,z_:0,w_,v___}/;w>Tr[1^x]-Tr[1^{v}]:>{y,z+1,0,v}&,{0},#]&

```

Pure function with first argument `#`. If a nonnegative integer is given, it will output the correct list of digits (even handles `0` correctly!).

## Explanation

`Nest[f,expr,n]` gives the result of applying `f` to `expr` `n` times. In this case, `expr` is the list `{0}` and `n` is the input integer `#`. The function `f` is complicated:

```
# (* Starting with the input # *)
 /. (* Apply the following rule *)
   {x___,y_} (* If you see a list of the form {x___,y} *)
            :> (* replace it with *)
              {x,y+1} (* this *)
                     //. (* Now apply the following rule repeatedly until nothing changes *)
                        x:{y___,z_:0,w_,v___} (* If you see a list x starting with a sequence y of 0 or more elements,
                                                 followed by an optional element z (default value of 0),
                                                 followed by an element w,
                                                 followed by a sequence v of 0 or more elements *)
                                             /; (* such that *)
                                               w>Tr[1^x]-Tr[1^{v}] (* w is greater than the length of x minus the length of {v} *)
                                                                  :> (* replace it with *)
                                                                    {y,z+1,0,v}& (* this *)

```

# Answer
> 3 votes
# Perl 6, 38 bytes

```
{map({|[X] 1,|map ^*,3..$_},1..*)[$_]}

```

Takes a positive integer, and outputs a list of integers representing the digits.

### Explanation:

```
{                                    }  # a lambda

 map({                    },1..*)       # for each number length from 0 to infinity,
                                        # offset by 1 to avoid a +1 in next step...

           1,|map ^*,3..$_              # generate the digit ranges, e.g.:
                                        #     length 0  ->  (1)  # bogus, but irrelevant
                                        #     length 1  ->  (1)
                                        #     length 2  ->  (1, 0..2)
                                        #     length 3  ->  (1, 0..2, 0..3)
                                        #     length 4  ->  (1, 0..2, 0..3, 0..4)

       [X]                              # take the cartesian product

      |                                 # slip the results into the outer sequence

                                 [$_]   # Index the sequence generated this way

```

# Answer
> 2 votes
# Pyth - 14 bytes

Simply returns the `nth` value that fits the "less than place value pattern".

```
e.f.A.eghkbjZT

```

Test Suite.

# Answer
> 1 votes
## Haskell, 65 bytes

```
i(x:r)|x>length r=0:i r|1<2=1+x:r
i[]=[1]
reverse.(iterate i[]!!)

```

`i` increases numbers in the number system with the digits in reversed order. `iterate` creates the infinite list of all these numbers starting with zero which is represented by `[]`. Then all that is left to do is take (`!!`) the demanded number and `reverse` it.

The last line is a function, not a function definition, so it can not appear as is in a source code file. Instead, only put the other lines in the source code and use the last line at the interpreter (or bind the function to a name by prepending `f=` to the last line).

Example use:

```
*Main> reverse.(iterate i[]!!) $ 100
[1,0,0,3,5]

```

(8 bytes could be saved if `[5,3,0,0,1]` were an allowed representation of the result.)

# Answer
> 1 votes
## Haskell, 49 bytes

```
x=[1]:[n++[d]|n<-x,d<-[0..length n+1]]
(x!!).pred

```

The first line is an auxiliary definition, and the second evaluates to a function. It takes an integer and returns a list of integers. Try it online!

## Explanation

I define `x` as the infinite list of representations mentioned in the challenge text; the main function just decrements its argument and indexes into `x`. The first line works like this:

```
x=                     -- The list of lists x contains
 [1]:                  -- the list [1], followed by
 [n++[d]|              -- integer d appended to list n, where
  n<-x,                -- n is drawn from x, and
  d<-[0..length n+1]]  -- the new "digit" d is drawn from this range.

```

You see that `x` is defined in terms of itself, but Haskell is lazy, so this is not an issue.

---
Tags: code-golf, number-theory
---


# Question
Title: Expose nondeterminism resulting from the OS thread scheduler
As we all know, modern operating systems have thread schedulers that can pick different orders to schedule your threads based on internal logic which your code is not privy to. Normally you architect your multithreaded code to ensure that this nondeterminism imposed on you does not meaningfully affect your output.

The goal here is the opposite. Produce a program which prints the integers in the interval \[0,99\] but in an order which will vary from run to run due to the OS thread scheduler.

You must achieve "enough nondeterminism", defined as:

> In 10 sequential sets of 10 trials your program must produce at least 9 unique permutations within each trial. You may have a reasonable number of failed sets of trials on either side of the consecutive 10 which succeed.
>
> Or, to put it another way, you need 100 runs of your program where each block of 10 runs has at most two runs which output the same thing.

So, occasionally swapping 98 and 99 won't cut it.

This is a , so the answer which uses the fewest bytes wins.

## Minutiae

* Write your output to stdout, one entry per line
* If you mangle the format by having two threads interleave character writes to stdout (even occasionally) resulting in things like three digit numbers or empty lines, your result is invalid
* The only exception to the above rule is that you may emit a single empty line after printing the last required number (you're welcome)
* If you ever miss or duplicate any required values your result is invalid
* Your program does **not** need to be nondeterministic on a single core processor (though kudos if it is)
* Your program may use green threads/fibers which are not actually managed by the OS kernel iff it still meets the other requirements of the challenge and the threading system is part of your language or the standard library for your language
* Runtime for your program must be reliably under 5 seconds on a modern processor
* You do not get to specify changes to the environment which happen outside of your program such as waits or settings changes; your program should pass whether run 100ish times back to back or with an hour between each run or 100ish times in parallel (that would probably help actually...)
* You may use a coprocessor such as a GPU or Xeon Phi and its own internal scheduling mechanism for tasks. The rules apply to this the same way they apply to green threads.
* Feel free to provoke the scheduler with all manner of sleeps, yields, and other tricks as long as you obey the rules specified in this post

## Banned Operations

The only source of nondeterminism you are allowed to draw on is when the scheduler schedules your threads to run. The following list is not exhaustive, intended only to provides examples of things you are not allowed to do as they admit other sources of nondeterminism.

* Directly or indirectly accessing any sort of PRNG or hardware RNG capability (unless it is as an inherent part of the scheduler).
* Reading in any kind of input (system time, filesystem, network, etc.)
* Reading thread IDs or Process IDs
* Customizing the OS scheduler; you must use a standard OS scheduler from a mainstream OS
* Customizing your green thread/fiber scheduler is also prohibited. This means that if you write a language for this challenge you **must** use OS threads.

## Answer Validation

Preferably an answer would work across all common OSes and modern processors, with kudos awarded proportional to the breadth of support. However, this is not a requirement of the challenge. At a minimum an answer must support one modern SMP processor and modern OS. I'll test leading answers to the extent of my hardware availability.

* If your entry will not produce the required output on an i7 5960x running Windows 10 v1607 x64, specify the environment required
* If it's something I can easily reproduce with VMWare Workstation, provide the exact OS and VM specs
* If it can't be produced in under either of those conditions, record a simultaneous screen capture of the test as described in the header section and a handheld video recording of your screen with your mouse and keyboard interaction (or whatever control scheme your nonstandard computation device uses) clearly visible and post both videos along with your answer and include an explanation of why it works
* Alternately, get a reputable long-standing user (who is not you) with matching hardware to reproduce the result and vouch for you
* If your entry is in an exotic programming language that a typical developer won't be set up to compile/jit/interpret, provide setup instructions
* If you entry depends on a specific version of the JVM/Python interpreter/other, specify which
* If it takes more than 10 minutes of back-to-back runs to get your 10 successful sequential sets of trials in my testing you fail (so don't let the success condition be a freak occurrence, especially if you're near the upper runtime bound)

# Answer
# Perl 6, 27 bytes

```
await map {start .say},^100

```

Explanation:

```
      map {          },^100  # Iterate over the range 0..99, and for each of number:
           start             # Send the following task to a thread pool of OS threads:
                 .say        # Print the number, followed by a newline.
await                        # Wait until all tasks have completed.

```

I hope this satisfies the task. (If not, please let me know).

### Testing:

The shell script I used to test sufficient nondeterminism:

```
#!/usr/bin/bash
for i in {1..10}; do
    set=""
    for j in {1..10}; do
        set="${set}$(perl6 nondet.p6 | tr '\n' ',')\n"
    done
    permutations="$(echo -e "$set" | head -n -1 | sort | uniq | wc -l)"
    echo -n "$permutations "
done

```

For me, this outputs:

```
10 10 10 10 10 10 10 10 10 10

```

### Setup instructions:

I ran the test with an up-to-date Rakudo Perl 6 on 64bit Linux, though I guess it'll work on other platforms.

The Rakudo download page has setup instructions. I compiled mine from git like this:

```
git clone git@github.com:rakudo/rakudo.git
cd rakudo
perl Configure.pl --gen-moar --make-install
export PATH="$(pwd)/install/bin/:$PATH"

```

### Try it online:

Or just test it online, using this Try It Online link provided by @b2gills. I checked a few runs and got a different order each time, but haven't had the patience to run it 100 times through that online interface.
> 4 votes

# Answer
## bash, ~~32~~ 28 bytes

```
for i in {0..99};{ echo $i&}

```

I ran this 100 times and got 100 different results.

Edit: Saved 4 bytes thanks to @DigitalTrauma.
> 4 votes

# Answer
# PowerShell, ~~54~~ ~~46~~ ~~44~~ 39 bytes

```
workflow p{foreach -p($i in 0..99){$i}}

```

PowerShell Workflows are not supported in TIO, so you can't try it there. Should work great on your Windows 10 machine though :)

Defines a function `p` which will output the list of numbers when invoked.

### Timing

A single run reliably runs in about 600ms on my machine. The 100 tests defined below finish in under 2 minutes.

### Testing

Here's complete code to test it:

```
workflow p{foreach -p($i in 0..99){$i}}
#workflow p{foreach($i in 0..99){$i}}
# uncomment above to prove testing methodology does detect duplicates

1..10 | % {
    $set = $_
    Write-Host "Set $set of 10"
    1..10 | % -b {
        $runs = @()
    } -p {
        $run = $_
        Write-Host "-- Run $run of 10 in set $set"
        $runs += "$(p)"
    } -e {
        Write-Host "-- There were $(10-($runs|Get-Unique).Count) duplicate runs in set $set"
    }
}

```

### Output on my machine:

> ```
> Set 1 of 10
> -- Run 1 of 10 in set 1
> -- Run 2 of 10 in set 1
> -- Run 3 of 10 in set 1
> -- Run 4 of 10 in set 1
> -- Run 5 of 10 in set 1
> -- Run 6 of 10 in set 1
> -- Run 7 of 10 in set 1
> -- Run 8 of 10 in set 1
> -- Run 9 of 10 in set 1
> -- Run 10 of 10 in set 1
> -- There were 0 duplicate runs in set 1
> Set 2 of 10
> -- Run 1 of 10 in set 2
> -- Run 2 of 10 in set 2
> -- Run 3 of 10 in set 2
> -- Run 4 of 10 in set 2
> -- Run 5 of 10 in set 2
> -- Run 6 of 10 in set 2
> -- Run 7 of 10 in set 2
> -- Run 8 of 10 in set 2
> -- Run 9 of 10 in set 2
> -- Run 10 of 10 in set 2
> -- There were 0 duplicate runs in set 2
> Set 3 of 10
> -- Run 1 of 10 in set 3
> -- Run 2 of 10 in set 3
> -- Run 3 of 10 in set 3
> -- Run 4 of 10 in set 3
> -- Run 5 of 10 in set 3
> -- Run 6 of 10 in set 3
> -- Run 7 of 10 in set 3
> -- Run 8 of 10 in set 3
> -- Run 9 of 10 in set 3
> -- Run 10 of 10 in set 3
> -- There were 0 duplicate runs in set 3
> Set 4 of 10
> -- Run 1 of 10 in set 4
> -- Run 2 of 10 in set 4
> -- Run 3 of 10 in set 4
> -- Run 4 of 10 in set 4
> -- Run 5 of 10 in set 4
> -- Run 6 of 10 in set 4
> -- Run 7 of 10 in set 4
> -- Run 8 of 10 in set 4
> -- Run 9 of 10 in set 4
> -- Run 10 of 10 in set 4
> -- There were 0 duplicate runs in set 4
> Set 5 of 10
> -- Run 1 of 10 in set 5
> -- Run 2 of 10 in set 5
> -- Run 3 of 10 in set 5
> -- Run 4 of 10 in set 5
> -- Run 5 of 10 in set 5
> -- Run 6 of 10 in set 5
> -- Run 7 of 10 in set 5
> -- Run 8 of 10 in set 5
> -- Run 9 of 10 in set 5
> -- Run 10 of 10 in set 5
> -- There were 0 duplicate runs in set 5
> Set 6 of 10
> -- Run 1 of 10 in set 6
> -- Run 2 of 10 in set 6
> -- Run 3 of 10 in set 6
> -- Run 4 of 10 in set 6
> -- Run 5 of 10 in set 6
> -- Run 6 of 10 in set 6
> -- Run 7 of 10 in set 6
> -- Run 8 of 10 in set 6
> -- Run 9 of 10 in set 6
> -- Run 10 of 10 in set 6
> -- There were 0 duplicate runs in set 6
> Set 7 of 10
> -- Run 1 of 10 in set 7
> -- Run 2 of 10 in set 7
> -- Run 3 of 10 in set 7
> -- Run 4 of 10 in set 7
> -- Run 5 of 10 in set 7
> -- Run 6 of 10 in set 7
> -- Run 7 of 10 in set 7
> -- Run 8 of 10 in set 7
> -- Run 9 of 10 in set 7
> -- Run 10 of 10 in set 7
> -- There were 0 duplicate runs in set 7
> Set 8 of 10
> -- Run 1 of 10 in set 8
> -- Run 2 of 10 in set 8
> -- Run 3 of 10 in set 8
> -- Run 4 of 10 in set 8
> -- Run 5 of 10 in set 8
> -- Run 6 of 10 in set 8
> -- Run 7 of 10 in set 8
> -- Run 8 of 10 in set 8
> -- Run 9 of 10 in set 8
> -- Run 10 of 10 in set 8
> -- There were 0 duplicate runs in set 8
> Set 9 of 10
> -- Run 1 of 10 in set 9
> -- Run 2 of 10 in set 9
> -- Run 3 of 10 in set 9
> -- Run 4 of 10 in set 9
> -- Run 5 of 10 in set 9
> -- Run 6 of 10 in set 9
> -- Run 7 of 10 in set 9
> -- Run 8 of 10 in set 9
> -- Run 9 of 10 in set 9
> -- Run 10 of 10 in set 9
> -- There were 0 duplicate runs in set 9
> Set 10 of 10
> -- Run 1 of 10 in set 10
> -- Run 2 of 10 in set 10
> -- Run 3 of 10 in set 10
> -- Run 4 of 10 in set 10
> -- Run 5 of 10 in set 10
> -- Run 6 of 10 in set 10
> -- Run 7 of 10 in set 10
> -- Run 8 of 10 in set 10
> -- Run 9 of 10 in set 10
> -- Run 10 of 10 in set 10
> -- There were 0 duplicate runs in set 10
>
> ```
> 2 votes

# Answer
# GCC on Linux, 47 bytes

```
main(i){for(i=99;fork()?i--:!printf("%d\n",i););}

```

This gave me different results pretty much every time, having been compiled with `gcc` (no flags) version 4.9.2. Specifically, I was on 64-bit Debian 8.6 (kernel version 3.16.31).

## Explanation

If the `fork()` returns zero (child process), the value of `i` is printed, and the loop condition is false, because `printf` will return a value greater than zero. In the parent process, the loop condition is just `i--`.
> 2 votes

---
Tags: code-golf, concurrency
---