text:
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

Derive the intermediate keys for use in the following steps.
Construct and apply the straddling checkerboard.
Construct and apply the first transposition table.
Construct and apply the second (disrupted) transposition table.
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!

adding the first two digits without adding Do you mean carrying?

@isaacg Yes, I did. Edited.

Could you clarify on what you mean by without borrowing and without carrying? Do you mean add and subtract mod 10, i.e. (6+7) mod 10 = 3 and (6-8) mod 10 = 8?

@R.Kap Yeah, let me go clarify that.

Do we have to demarcate numbers?

@R.Kap If you can think of another straddling checkerboard that has the numbers in it, then you can use that and do not have to demarcate numbers, or your system could just have the numbers spelled out and the slot for the number sign used for something else. You have some leeway in the specification here if you need it.

Okay, this is really late, but I finally got back around to trying to finish this. Anyways, can we take the alphanumerical string inputs in any format wanted, i.e. all uppercase, all/some punctuation removed, numbers already demarcated, etc? Also, can we take as many inputs as we want/need as strings, or do they all need to be a specific type when given as input to, say, a function?

@R.Kap Your inputs can already be formatted (I did so with my answer). Your inputs can also be of  whatever type and in whatever order you wish.

A short keyword or phrase is a bit vague in my opinion. What can the maximum length of the keyword or phrase be? Can duplicates appear in this "short" keyword or phrase? I hope I am not bugging you too much with all these questions.

@R.Kap These questions should probably be moved to chat. I don't know how to do that, but I made a chatroom here so that I can answer future questions there.

I'm not sure whether I'm gonna finish it or not (probably not), but here is the beginning of an 05ab1e solution that only computes the step 1 until the chain add operation to 60 characters. If anyone wants to complete the implementation ^^ ... https://tio.run/nexus/05ab1e#@394oVdpyOEtZZUuh1ZWh5ZFVGYfWud3eO6hFYdXVB5apF2rWXt6DlDe6NDi0EObgg9tDtbQDlF1ObxH@9BqF7NDi0GMJcUxh3YcWh1hcHgFUC7C8PAKkDmHV9Rq/v8fkpGqkJZZVFyiUFCUmZecWZCTqpBZrFCSkViiUJlfqpBbCpTKyy9RSMvPzwGJFBWn5qQpPGqYopCYlwJWkliUClSfqpCaWJyZCjIotag4P0@hJB@sR4/LxNzSyJDL2NDcyMDQDAA

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:])

Python 3 allows unicode characters as variables, FYI.

Changing ord(seq[i])+ord(seq[i+1]) to sum(map(ord,seq[i:i+2])) saves 1 character I believe.

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.

1635 bytes

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.

Could you please add a snippet so I can verify that this works? If it does, then I can award you the bounty.

@R.Kap Sure, I've added a demo snippet

Hmm...in the demo, the message identifier seems to be 7 away from the end instead of 6. Also, in your ungolfed version, the same Id seems to be 6 away from the beginning instead of the end.

@R.Kap Yeah there was a bug when I first posted it (must not have fixed it in the ungolfed). As for the golfed, I assumed that was 0-indexed because otherwise if  1 means the very end where would you say the message identifier should go on a 0? I can change it I just need to know.

I would say that on a 0 the message identifier should be omitted from the output.

@R.Kap Update, it should now follow that logic

All right. It now looks all good, and has been verified by me to produce the correct output. This is the shortest successful answer at the end of the bounty period and therefore gets the bounty. Great job! I am especially pleased that this is under 1 kilobyte.

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.

Considered writing a Clojure solution, but my head exploded while I was reading the question. How long did that take to write?

Maybe 3 hours while watching Youtube on the side. This started off quite easy but I was about to give up when I had to implement the second "disrupted transposition". Now that coords is generated twice, first generating the triangular shape and then filling any coordinates which were missing. Also "padding to length of multiply of N" might have more elegant solution than concatenating N - 1 elements and partitioning to lengths of N.

Oh damn I forgot to change the hard-coded split point at (split-at 49 mymsg), 49 should be something like (rand-int(count mymsg)) so correct answer would be a bit over 1200 bytes. zzz

Damn. Probably still less than the c answer though.


text:
Write a VIC cipher decoder
You've received a coded message from your ally that you know is encoded with the VIC cipher. As you know that the VIC cipher is notoriously convoluted, you want to write a program that will decode the VIC cipher but is small enough to hide from the enemy if you are captured, and thus uses as few bytes as possible.
Your instructions are as follows:
The information you have

The encoded message. For this example, we'll use the message we encrypted in the "VIC cipher encoder" challenge: 71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641 70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521
A keyword with the most common letters of your chosen alphabet.
A key phrase, such a quote or song lyric
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.
What you and your ally agreed to use in your encoding is the following: the keyword SENATORI, the key phrase "The first principle is that you must not fool yourself — and you are the easiest person to fool.", and the date 3172016, and the recipient's agent number, 9.
Summary of steps

Derive the intermediate keys for use in the following steps and extract the message identifier from the encoded message.
Construct and apply the second (disrupted) transposition table in reverse.
Construct and apply the first transposition table in reverse.
Construct and apply the straddling checkerboard in reverse.
Finalize the decoding removing nulls and by starting the message at the "message begin" mark.

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 adding 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
      1              2                    0s
      1              2                 3  1
      1           4  2                 3  2
5  6  1           4  2                 3  3s
5  6  1        7  4  2  8        9     3  4s
5  6  1 10     7  4  2  8    11  9     3  5s
5  6  1 10     7  4  2  8 12 11  9     3  7
5  6  1 10 12  7  4  2  8 12 11  9 14  3  8s

I use zero-indexing here, but index however you like.
1. Intermediate Keys
Firstly, you need to retrieve the message identifier M from the message. The last digit of the date 3172016 is 6, so you know that the message identifier was placed sixth from the last in the message.
The encoded message =
  71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641
  70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521
Message id = 47921

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

Subtract, without borrowing, 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, 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 by 50 digits. These digits, in five rows of ten, 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. Reverse the Second Transposition
We fill a transposition table with the message by columns in order of the column headings, K2. The message has 110 digits in 13 columns, leaves 8 full rows and six digits in a final row.
71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641
70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521

starts off with

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

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

resulting in

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

Taking the rows one at a time, and stopping at the disrupted parts
K2   8  7 12  2 10  9  4  5  6  0  3  1 11

                                7  2  4  9  stop at 0
                                   2  2  4
                                      7  9
                                         4
                                            go all the way down until you run out of row
     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

Result so far: 060826428 2466745801 51411542246 272922961311 4010829181414

The continue to avoid disrupted bits until the end...
K2   8  7 12  2 10  9  4  5  6  0  3  1 11

                                7  2  4  9  stop at 0
                                   2  2  4
                                      7  9
                                         4
                                            go all the way down until you run out of row
                                      9  4  restart until 1
                                         3

              5  6  8                       restart until 2

Result so far: 060826428 2466745801 51411542246 272922961311 4010829181414
41443423911 845123433442 2028293488758 041

Then grab the rest:
Result: 060826428 2466745801 51411542246 272922961311 4010829181414
41443423911 845123433442 2028293488758 041 7249 224 79 4 94 3 568

3. Reverse the First Transposition
As before, create the transposition table by filling in columns in order of the column headings, K1. With 110 digits and 12 columns, we have 9 full rows and 2 digits in a final row.
K1   6 10 11  0  1  5  7  9  4  8  2  3

              0
              6
              0
              8
              2
              6
              2
              4
              8

resulting in

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

Reading of the rows in order, with no disruptions this time, we obtain:
407020129312 449648196354 114062831416 479869443442 424271581217
343648181212 495451274059 226284350242 328801481822 94

4. Reversing the Straddling Checkerboard
The heading for the checkerboard is C = 3105968724. We fill in the first row with the keyword SENATORI and the rest of the alphabet is filled in as follows:
  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 #

To decode we simply look up the each number in the checkerboard as we read them. First, 4 must be a row heading, so we move to 40 which is H. 7 is I. 0 is N. 2 is a row heading, so we move to 20 which is G. Continuing in this way, we reveal the original message:
HINGELSE.MOVETOSAFEHOUSEFOXTROT#3#..
WEAREDISCOVERED.TAKEWHATYOUCAN.BURNEVERYT?

The question mark at the end is from the final 4. As this is a row heading, there should be another number after this, but this is end of the message. Thus, we conclude that this is a null, and discard it.
HINGELSE.MOVETOSAFEHOUSEFOXTROT#3#..
WEAREDISCOVERED.TAKEWHATYOUCAN.BURNEVERYT

5. Finalize the Decryption
The program does not need to reinsert spaces and punctuation, but if there is a set convention for where the message originally began (here we used ..), cycle through the message until the message beginning is at the beginning.
The final decrypted message is:
WEAREDISCOVERED.TAKEWHATYOUCAN.
BURNEVERYTHINGELSE.MOVETOSAFEHOUSEFOXTROT#3#..

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 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 the keyword and key phrase have already had all punctuation and spaces removed except for those that you allow in your version, and that numbers are denoted with number signs correctly.
The encoded message should be either a string of space-separated five-digit groups, a list of five-digit integers, one long string without spaces, 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.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Python 3, 1446 bytes
This is even longer than my encoder. Golfing suggestions very welcome.
As this is a counter to my encoder, this also uses the uppercase Latin alphabet with additional characters . and #. The decoder also uses 0-indexing and 0123456789 when converting g to t.
I=int;L=list;E=len;R=range;B=str;J=''.join
def H(s,e):
 for i in R(e-E(s)):s+=chr(48+(ord(s[i])+ord(s[i+1]))%32%10)
 return s
def Q(s):
 r=[0]*E(s);s=L(s);a=R(E(s))
 for z in a:b=min(a,key=lambda i:s[i]);r[b]=z;s[b]="~"
 return r
def T(x,k):
 u=E(x);v=E(k);g=R(v);c=[x[i::v]for i in g];s=[0]*v
 for f in g:s[k[f]]=c[f]
 return J(s)
def U(x,k,d=0):
 c=[];w=[];u=E(x);v=E(k);g=R(v);n=u//v+1;l=u%v or v;e=0
 for j in g:c+=[[]]
 for j in g:i=k.index(j);c[i]+=L(x[e:e+n-(i>=l)]);e+=n-(i>=l)
 for z in R(n):
  w+=[[]]
  for j in c:w[z]+=j[z:z+1]
 if d:
  u=[];r=y=0;i=k.index(y)
  while r<n:
   u+=w[r][:i];w[r]=w[r][i:];i+=1;r+=1
   if i>v:y=(y+1)%v;i=k.index(y)
  for j in w:u+=j
  return J(u)
 else:return J(J(i)for i in w)
def C(m,s,w):
 t={s[-2:]:".",s[-1]*2:"#"};x=64;r='';j=z=n=0;e=-1;h=''
 while x<90:
  x+=1;v=chr(x)
  if v in w:t[s[w.index(v)]]=v
  else:t[s[z-2]+s[j]]=v;j+=z;z=(z+1)%2
 for j in R(E(m)):
  if(e>=0)*(j<e+2):continue
  else:e=-1
  if n:e=m.index(s[-1]*2,j+1);r+=m[j:e]+"#";n=0
  else:
   k=m[j]
   if h:r+=t[h+k];n=t[h+k]=="#";h=''
   elif k in s[:-2]:r+=t[k]
   else:h=k
 b=r.index("..")+2
 return r[b:]+r[:b]
def D(m,w,P,d,A):j=-I(d[-1]);m=m.split();M=m[j];m=J(m[:j]+m[j+1:]);t=J(B(Q(P[10:20])[I(J(B((I(H(J(B((I(M[i])-I(d[i]))%10)for i in R(5)),10)[i])+Q(P[:10])[i])%10)for i in R(10))[i])])for i in R(10));u=H(t,60)[10:];p=A+I(u[-2]);v=T(u,Q(t));return C(U(U(m,Q(v[p:p+A+I(u[-1])]),1),Q(v[:p])),J(B(i)for i in Q(u[40:])),w)

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

def sequent(seq):
    res = [0]*len(seq);seq=list(seq)
    for z in range(len(seq)):
        b = min(range(len(seq)),key=lambda i:seq[i])
        res[b] = z
        seq[b] = "~"
    return res

def transpose(text, keys):
    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 untranspose(text, keys, disrupt=False):
    columns = []
    for j in range(len(keys)):
        columns += [[]]
    num_rows, len_last = divmod(len(text),len(keys))
    num_rows += 1
    if len_last == 0:
        len_last = len(keys)
    text_index = 0
    for j in range(len(keys)):
        ind = keys.index(j)
        columns[ind] += list(text[text_index:text_index+num_rows-(ind>=len_last)])
        text_index += num_rows-(ind>=len_last)
    rows = []
    for k in range(num_rows):
        rows += [[]]
        for j in columns:
            rows[k] += j[k:k+1]
    if disrupt:
        undisrupt = []
        current_row = 0
        stop_key = 0
        stop_index = keys.index(stop_key)
        while current_row < num_rows:
            undisrupt += rows[current_row][:stop_index]
            rows[current_row] = rows[current_row][stop_index:]
            stop_index += 1
            current_row += 1
            if stop_index > len(keys):
                stop_key = (stop_key + 1) % len(keys)
                stop_index = keys.index(stop_key)
        for i in rows:
            undisrupt += i
        return ''.join(undisrupt)
    else:
        return ''.join(''.join(i) for i in rows)

def uncheckerboard(message, seq, word):
    trans = {seq[-2:]:".", seq[-1]*2:"#"};x=64;res='';j=z=0
    while x<90:
        x += 1
        v = chr(x)
        if v in word:
            trans[seq[word.index(v)]] = v
        else:
            trans[seq[z-2] + seq[j]] = v
            j += z
            z = (z+1) % 2
    num = False
    end = -1
    h = ''
    for j in range(len(message)):
        if end>=0 and j<end+2:
            continue
        else:
            end = -1
        if num:
            end = message.index(seq[-1]*2,j+1)
            res += message[j:end]+"#"
            num = 0
        else:
            k = message[j]
            if h:
                res += trans[h+k]
                if trans[h+k] == "#":
                    num = 1
                h = ''
            elif k in seq[:-2]:
                res += trans[k]
            else:
                h = k
    begin = res.index("..") + 2
    return res[begin:] + res[:begin]

def decode(message, keyword, phrase, date, agent):
    mkey = -int(date[-1])
    message = message.split()
    m_id = message[mkey]
    message = ''.join(message[:mkey] + message[mkey+1:])

    s1 = sequent(phrase[:10])
    s2 = sequent(phrase[10:20])
    b = ''.join(str((int(m_id[i])-int(date[i]))%10) for i in range(5))
    a = chain_add(b, 10)
    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:]))
    z = untranspose(message,k2,1)
    y = untranspose(z,k1)
    x = uncheckerboard(y,c,keyword)
    return x

I seem to be getting an Index Error: http://ideone.com/TTzsRb

@R.Kap I missed a step in the ungolfing. Should be fixed now.

source: Stack Exchange

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

sort: votes


text:
Gauss to Eisenstein
Given a Gaussian integer \$a+bi\$ where \$a\$,\$b\$ are integers and \$i = \exp\left(\pi i/2\right)\$ is the imaginary unit, return the closest (w.r.t to the Euclidean distance) Eisenstein integer \$k+l\omega\$ where \$k\$,\$l\$ are integers and \$\omega = \exp(2\pi i/3) = (-1+i\sqrt{3})/2\$.
Background
It is probably quite obvious that every Gaussian integer can uniquely be written as \$a+bi\$ with \$a\$,\$b\$ integers. It is not so obvious but nonetheless true: Any Eisenstein integer can uniquely be written as \$k+l\omega\$ with \$k\$,\$l\$ integers. They both form a \$\mathbb{Z}\$-module within the complex numbers, and are both p-th cyclotomic integers for \$p=2\$ or \$3\$ respectively. Note that \$3+2i \neq 3+2\omega\$

Source: commons.wikimedia.org
Details

In case the given complex number has two or three closest points, any of those can be returned.

The complex number is given in rectangular coordinates (basis \$(1,i)\$), but other than that in any convenient format like (A,B) or A+Bi or A+B*1j etc.

The Eisenstein integer has to be returned as coordinates of the basis \$(1,\omega)\$ but other than that in any convenient format like (K,L) or K+Lω or K+L*1ω etc.

Examples
All real integers should obviously be mapped to the real integers again.
  6,14 -> 14,16
  7,16 -> 16,18
-18,-2 ->-19,-2
 -2, 2 -> -1, 2
 -1, 3 -> 1, 4

Nice, I don't remember seeing a hexagonal grid since http://codegolf.stackexchange.com/q/70017/17602

Related

@Neil There have been three others since then. ;)

You should also include test cases when a and b have opposite signs.

@SmileAndNod Added one. But one could also just use the symmetry with respect to the real axis and just replace (1,w) with (-1,1+w). And I also renamed this section to Examples to make it clear that it is not sufficient to just provide the right results for these cases.

@flawr It's an interesting puzzle for highlighting the difference between the floor function and the int function.

Suggested testcase: -1, 3 -> 1, 4. Some solutions (e.g. this and this) give the wrong answer 1, 3 or 0, 3.

@Bubbler Added!

APL (Dyalog Extended), 16 bytesSBCS
⎕0+⌈3÷⍨1 2×⌊⎕×√3

Try it online!
A full program that takes y then x from standard input and prints a 2-element vector of integers.
How it works: the math
First of all, note that any Gaussian integer will be placed on the vertical diagonal of a diamond, with the point \$Z\$ placed at \$(x,\sqrt3y)\$ for some integer \$x,y\$.
      + W
     /|\
    / | \
   /  |  \
  /   + X \
 /    |    \
+-----|-----+V
 \    |    /
  \   + Y /
   \  |  /
    \ | /
     \|/
      + Z

In the figure, \$\overline{WZ}=\sqrt3\$ and \$\overline{WX}=\overline{XY}=\overline{YZ}=\overline{XV}=\overline{YV}=\frac{1}{\sqrt3}\$. So, given the vertical position of a point, we can identify the nearest Eisenstein point as follows:
$$
\text{Given a point }P \in \overline{WZ}, \\
\left\{
\begin{array}{c}
P \in \overline{WX} \implies \text{the nearest point is } W \\
P \in \overline{XY} \implies \text{the nearest point is } V \\
P \in \overline{YZ} \implies \text{the nearest point is } Z
\end{array}
\right.
$$
Given a Gaussian point \$P\$, we first determine which diamond \$P\$ belongs to, measured by how many diamonds (denoted \$h\$) \$Z\$ is away from the \$x\$-axis.
$$
h = \lfloor P.y \div \sqrt3 \rfloor
$$
Then the Eisenstein coordinates of \$Z\$ are
$$
Z.x_E = P.x+h, \quad Z.y_E = 2h
$$
Now, we determine which of the segments \$\overline{WX},\overline{XY},\overline{YZ}\$ \$P\$ belongs to. For this, we can calculate the indicator \$w\$ as follows:
$$
w = \lfloor P.y \times \sqrt3 \rfloor \% 3
$$
Then the cases \$ w = 0, 1, 2 \$ correspond to \$\overline{YZ},\overline{XY},\overline{WX}\$ respectively. Finally, the nearest Eisenstein point of \$P\$ (which is one of \$Z\$, \$V\$, or \$X\$) can be calculated as:
$$
P_E.x_E = P.x+h+\lceil \frac{w}2 \rceil, \quad P_E.y_E = 2h+w
$$
Using the identities for \$h\$ and \$w\$, we can further simplify to:
$$
y' = \lfloor P.y \times \sqrt3 \rfloor, \quad P_E.x_E = P.x+\lceil y' \div 3 \rceil, \quad P_E.y_E = \lceil 2y' \div 3 \rceil
$$
How it works: the code
⎕0+⌈3÷⍨1 2×⌊⎕×√3
           ⌊⎕×√3  ⍝ Take the first input (P.y) and calculate y'
   ⌈3÷⍨1 2×       ⍝ Calculate [ceil(y'/3), ceil(2y'/3)]
⎕0+  ⍝ Take the second input(P.x) and calculate [P.x+ceil(y'/3), ceil(2y'/3)]

JavaScript (ES6), 112 bytes
(a,b,l=b/Math.pow(.75,.5),k=a+l/2,f=Math.floor,x=k-(k=f(k)),y=l-(l=f(l)),z=x+y>1)=>[k+(y+y+z>x+1),l+(x+x+z>y+1)]

ES7 can obviously trim 9 bytes. Explanation: k and l initially represent the floating-point solution to k+ωl=a+ib. However, the coordinates needed to be rounded to the nearest integer by Euclidean distance. I therefore take the floor of k and l, then perform some tests on the fractional parts to determine whether incrementing them would result in a nearer point to a+ib.

I guess your tests on the fractional parts are taking advantage of the facts that x is always .2887 or 0.577and y is always either .1547 or .577

@SmileAndNod 3 years ago? I really can't remember, but I don't think it's that complicated, I'm just working out which is the nearest corner of the diamond.

MATL, 39 38 35 bytes
t|Ekt_w&:2Z^tl2jYP3/*Zeh*!sbw6#YkY)

Input format is 6 + 14*1j (space is optional). Output format is 14 16.
Try it online!
Explanation
The code first takes the input as a complex number. It then generates a big enough hexagonal grid in the complex plane, finds the point that is closest to the input, and returns its Eisenstein "coordinates".
t         % Take input implicitly. This is the Gauss number, say A. Duplicate
|Ek       % Absolute value times two, rounded down
t_        % Duplicate and negate
w&:       % Range. This is one axis of Eisenstein coordinates. This will generate
          % the hexagonal grid big enough
2Z^       % Cartesian power with exponent 2. This gives 2-col 2D array, say B
t         % Duplicate
l         % Push 1
2jYP3/*   % Push 2*j*pi/3
Ze        % Exponential
h         % Concatenate. Gives [1, exp(2*j*pi/3)]
*         % Multiply by B, with broadcast.
!s        % Sum of each row. This is the hexagonal grid as a flattened array, say C
bw        % Bubble up, swap. Stack contains now, bottom to top: B, A, C
6#Yk      % Index of number in C that is closest to A
Y)        % Use as row index into B. Implicitly display

Haskell, 128 bytes
i=fromIntegral;r=[floor,ceiling];a!k=(i a-k)**2;c(a,b)|l<-2*i b/sqrt 3,k<-i a+l/2=snd$minimum[(x k!k+y l!l,(x k,y l))|x<-r,y<-r]

Try it online!
For input Gaussian integer (a,b), convert it into Eisenstein coordinates, floor and ceil both components to get four candidates for closest Eisenstein integer, find the one with minimal distance and return it.

Tcl, 124 116 106 bytes
{{a b f\ int(floor(2*$b/3**.5)) {l "[expr $f+(1-$f%2<($b-$f)*3**.5)]"}} {subst [expr $l+$a-($f+1)/2]\ $l}}

Try it online!
This is somewhat inspired by the three-year old post from @Neil
The floor function returns the corner of the rhombus whose edges are the vectors 1 and \$\omega\$. With respect to this rhombus, the Gaussian integer lies on the perpendicular bi-sector of either the top (if l is even) or bottom (if l is odd).  This is important because it means that either the lower left corner or the upper right corner will be an acceptable solution. I compute k for the lower left corner, and do one test to see if the Gaussian integer lies above or below the diagonal separating the two corners; I add 1 to k when above the diagonal, and I do likewise for l.
Saved 10 bytes by using the "sign of the cross-product v x d of the diagonal d with the vector v joining the lower right corner and (a,b)" as the test for which side of the diagonal the point lies.

Burlesque, 24 bytes
pe@3r@2././J2./x/.+CL)R_

Try it online!
Pretty sure this can be shorter. Input read as a b
pe      # Parse input to two ints
@3r@2./ # sqrt(3)/2
./      # Divide b by sqrt(3)/2
J2./    # Duplicate and divide by 2
x/.+    # swap stack around and add to a
CL      # Collect the stack to a list
)R_     # Round to ints

05AB1E, 13 bytes
Port of Bubbler's APL answer
3t*ïx‚3/îRÎ‚+

Try it online!
Input and output are both y first, x second.

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

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


text:
Is there a way of shortening fat-arrow functions?
From what I've seen throughout my time here on PPCG, most JavaScript entries involving fat arrow functions tend to be one of two camps:

The simple ones that are capable of running as a single statement and returning an answer, straight off the bat, like x=(a,b)=>a*a+b
The more complex ones that usually have curly braces because of the use of loops, and as a result require the use of a return statement.. like p=b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}

Taking the above example from category 2 with the curly braces concept as proof-of-concept... Would there be a way to re-golf this code (or similar) like this so as to eliminate the curly braces as well as the return? I'm only asking this as this could potentially (not saying this will happen all the time) eliminate 8 bytes from a JS golfer's code. Are there any techniques that one could use in this instance? I've tried recursion, but the m=b statement has proven to be a bit of a bugbear, as I can't seem to shake it.
For the above code, how would one golf that further so as to eliminate the return statement, regardless of whether it golfs shorter or not?

Use Recursion
I've found that recursion is (almost) always shorter than eval+for. The general way to convert from for to eval is:
for(a=n;b;c);d
(f=a=>b?f(c):d)(n)

So let's see your example:
b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}

We can first simplify it to:
for(m=b,a=1;~-m;--m,a*=m*m)a%b;

What did we do here? Well we simply moved everything inside the for statement, this helps us reduce the amount of semicolons which is not directly better but almost always leads to some golf.

Let's put this in eval and compare it to the recursion version:
b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}
b=>eval('for(m=b,a=1;~-m;--m,a*=m*m)a%b')
b=>(f=a=>~-m?(--m,f(a*=m*m)):a%b)(1,m=b)

The first part of the for loop (a=n), we can start that off by passing those variables in as arguments. The condition is simply: b?(c,f(a)):d where d is the return value. Usually c just modifies a so it can be merged into it. So we can golf it even more using what I've mentioned:
b=>(f=a=>~-m?(--m,f(a*=m*m)):a%b)(1,m=b)
b=>(f=a=>~-m?f(a*=--m*m):a%b)(1,m=b) // --m moved into a*=
b=>(f=a=>--m?f(a*=m*m):a%b)(1,m=b) // --m moved to condition

That said, as noted by @Niel is simplifying your algorithm. An algorithm golfy in one language may not be golfy in another so make sure to try different algoriths and compare them.

You've missed a big saving in simplifying the original code. ~-m is m-1, so the loop can be for(m=b,a=1;--m;a*=m*m)a%b; and the recursive version can be (untested) b=>(f=a=>--m?f(a*=m*m):a%b)(1,m=b)

Sometimes you just have to use a different algorithm but in this case the best I could do was the same length as @PeterTaylor's answer: b=>b>1&(f=a=>--a<2||b%a&&f(a))(b)

Abuse eval.
It's simple. Instead of:
f=n=>{for(i=c=0;i<n;i++)c+=n;return c}

Use
f=n=>eval("for(i=c=0;i<n;i++)c+=n;c")

Eval returns the last evaluated statement. In this case, since the last evaluated statement would be c+=n, we would be left with c anyhow, saving two bytes.
f=n=>eval("for(i=c=0;i<n;i++)c+=n")

In general:
f=n=>eval("code;x")

is shorter than this, by a byte:
f=n=>{code;return x}

As a note, using graves to call eval to possibly save bytes doesn't work, since:
eval`string`

is equivalent to
["string"]

Helpful for obfuscation! Not so much for code golf.

foo\string`is always equivalent tofoo(["string"])`, it's just that many functions then cast the array back to the desired string.

@Neil Oh, how interesting!


text:
Change to conventional algebra notations
The Challenge
Given an algebraic expression (eg 2ab, change it so it follows standard convention rules.
The Rules

Letters should be in alphabetical order. ie 2ab is allowed but not 2ba.
Numbers should always go first. ie 2ab is allowed but ab2 is not.
Exponentiation will be given as a^b to mean a to the power of b.
These rules must be applied to every sub-expression. ie 2ab + ba3 becomes 2ab + 3ab, 2vd * vd5 becomes 2dv * 5dv. This must work for at least addition, subtraction, multiplication, division, modulus and exponentiation.
Exponentiation is assumed to belong to the variable immediately preceding it and must stay with the variable it is assigned to. ie 2ba^2 becomes 2a^2b. This means that all variables to the right of ^ are part of the exponentiation.

Sample Input/Output
Input can be given with any amount of white space, which must be ignored. Output can use either one space or none. For example, 2ab               +3ba could become 2ab + 3ab or 2ab+3ab
Input -> Output
2ba -> 2ab
4gb + 5vh * gh7 -> 4bg + 5hv * 7gh
2ba^2 -> 2a^2b
5xk^2ba -> 5k^2abx

(The last couple of outputs don't make sense mathematically because of order of operations, but you don't have to worry about that.)
Scoring
Standard code golf, shortest answer in bytes wins. Answer can be a program which takes input, or a function (can be anonymous).

Do we have to deal with expressions like 2a2b or 2aba?

@MartinEnder No.

“This must work for at least addition, subtraction, multiplication, division, modulus and exponentiation.” You should add test cases for these, then. (Although I advise you just simplify the challenge.)

You should maybe write an EBNF-like description of the possible input strings. Will there be parentheses? Spaces halfway through a monomial?

Can you provide an example of an expression with multiple exponents? I am not sure what the output will look like.

@xsot Such as 2ab^fg3^re8 -> 2ab^3fg^8er?

So "ba2^3" becomes "2a^3b"?

@Neil You can assume that every ^ is preceded by a variable rather than a number.

Ugh, finished my answer only to find the question is now on hold... s=>s.replace(/ /g,'').replace(/[\w^]+/g,g=w=>w.match(/\d+|\w(\^.*)?/g).map(t=>t.replace(/(?!^)\b\w.*/,g)).sort().join\`)`

@Neil, the reason it has been put on hold is to fix unclear parts of the specification which might make that answer no longer work. Hopefully the spec will be fixed, the question will be reopened, and you can fix anything which needs fixing in your answer in order to comply with the clarified spec.

Ruby, 112 + 1 (p flag) = 113 bytes
Run as ruby -pe with the code surrounded by single quotes. Full program, even if it looks like just a recursive function at the beginning.
f=->s{s.scan(/(\w)(\^.+)?/).map{|a,b|[a,b&&?^,b&&f[b]]}.sort_by &:first};gsub(/[\w^]+/){f[$&]*""};gsub(/\s+/,"")


text:
Convert xxd output to shellcode
Taking some output from xxd and turning it into usable shellcode by hand is no fun, so your job is to automate the process.
Rules
Your submission can be a function, lambda, script, or any reasonable equivalent of those. You may print the result, or if your submission is a function/lambda then you may also return it.
You program must take three arguments, the first being a string containing the output of xxd, ran with no arguments other than a filename, like this: xxd some_file. Here's an example of what the the first argument will look like:
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Your need to take that middle section containing the bytes (the first 8 columns after the :) and turn it into shellcode by removing any whitespace, then putting a \x before each byte.
Here's what the output should be for the input above (ignoring any other arguments):
\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59
You can assume the first argument will always be a valid xxd output, ran with no arguments other than the filename.
Your output should also be a string where the backslashes are literal backslashes, not used as escape characters. So when I say "\x65", I'm not talking about the byte 0x65, or even the letter "A". In code, it would be the string "\x65".
The second argument specifies where in the xxd output the shellcode should start, and the third specifies where it should end. If the third argument is -1, it will end at the end of xxd output. The second and third argument will also always be non negative, except for when the third is -1
Here are some test cases:
Argument 1:
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Argument 2: 7, Argument 3: e (these are both strings representing hexadecimal numbers)
Output: \xc9\xcd\x80\xeb\x16\x5b\x31\xc0
Argument 1:
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Argument 2: 0, Argument 3: 2e
Output: \x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e
Argument 1:
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

Argument 2: a, Argument 3: -1
Output: \xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59
The code with the least bytes wins. The winner will be announced in seven days, on August 15, 2016 (but submissions after then are still appreciated).
Update
Congrats to @Adnan to winning the challenge!

Just to clarify, can entries return a string or must they print it?

Returning a string is fine as long as it's a function, lambda, or something like that (I updated the rules to specify that after you asked).

Can we also return the regular ASCII codes when the code is printable? E.g. ~ instead of \x7e. And can we return \t instead of \x09?

@orlp Sorry no, it needs to be in a consistent format.

Are the arguments required to be in hex? Also, the way you've given the second example, 7 looks like a zero-based index and e is a one-based index (e-7=7 but there are 8 hex codes in your output), or am I overlooking something?

@Neil e-7 doesn't account for the beginning byte of the range. The formula should be e-7+1. It's an inclusive range, so the beginning and ending indexes are both included.

@addison make sure you explain all the components of your question in the question itself. For example, many golfers may not know what xxd code and shell code are

You mention that start and end arguments in your examples are hexadecimal strings, but that isn't mentioned in the specification. If we submit a function, do we really have to parse two strings for the arguments?

05AB1E, 39 38 bytes
Input in the form:
arg2
arg3
arg1

Code:
²\|vy9F¦}40£ðK}J2ô„\xì²H>²®Qi²}£¹HF¦}J

Explanation:
²\                                       # Get the first two inputs and discard them.
  |                                      # Take the rest of the input as an array.
   vy         }                          # For each line...
     9F¦}                                #   Ten times, remove the first character.
         40£                             #   Only remain the substring [0:40].
            ðK                           #   Remove spaces.
               J                         # Join the string.
                2ô                       # Split into pieces of 2.
                  „\xì                   # Prepend a "\x" at each string.
                      ²H                 # Convert the second line from hex to int.
                        >                # Increment by one.
                         ²               # Push the second input again.
                          ®Qi }          # If equal to -1...
                             ²           #   Push the second input again.
                               £         # Take the substring [0:(² + 1)].
                                ¹H       # Convert the first input from hex to int.
                                  F¦}    # Remove that many characters at the beginning.
                                     J   # Join the array and implicitly output.

Uses the CP-1252 encoding. Try it online!.

Bash + coreutils + xxd, 73 71 69 bytes
printf \\x%s `xxd -r|xxd -p -s0x$1 -l$[(e=1+0x$2)?e-0x$1:-1]|fold -2`

Expects the hexdump on STDIN and start/end as command-line arguments.
This prints some warnings to STDERR, which is allowed by default.

I was hoping someone would actually use xxd in their solution!

@addison I tried to, but my lang doesn't support newlines in commandline input. :c

I am able to replace 16# with 0x?

@DigitalTrauma I thought it was an xxd thing, but it appears to work everywhere.

Yes, bash parses 0xn hex style and 0m octal style numbers out of the box: https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic. echo $[0x2a] $[052].

Ruby: 90 89 87 79 63 bytes
-2 bytes thanks to @addison
-8 bytes thanks to @PiersMainwaring
->s,x,y{'\x'+s.scan(/(?<=.{9})\w\w(?=.* )/)[x.hex..y.hex]*'\x'}

See the tests on repl.it: https://repl.it/Cknc/5

You can replace .join with *"" to save 2 bytes.

You can replace .map{|h|h.to_i(16)} with .map(&:hex) to save 8 more bytes!

Thanks @PiersMainwaring! Silly of me to forget that. It actually saved me 16 because it turned out to be shorter to call .hex on the arguments individually!

JavaScript, 84 bytes
(s,f,t,u)=>s.replace(/.*:|  .*\n?| /g,'').replace(/../g,'\\x$&').slice(f*4,++t*4||u)

Explanation: Removes all the unwanted parts of the dump, prepends \x to each hex pair, then extracts the desired portion of the result. ||u is used to convert the zero obtained by incrementing the -1 parameter into undefined which is a magic value that causes slice to slice to the end of the string. 101 bytes if f and t are strings of hex digits:
(s,f,t,u)=>s.replace(/.*:|  .*\n?| /g,``).replace(/../g,`\\x$&`).slice(`0x${f}`*4,t<0?u:`0x${t}`*4+4)

Instead of (s,f,t,u)=>, you can do s=>f=>t=>u=>, to save a few bytes.

@IsmaelMiguel Sorry, that only works for a function with exactly two actual parameters. In my specific case the u must be an additional parameter and can't be curried.

@IsmaelMiguel Also that's actually longer...

Jelly, 48 44 bytes
ØhiÐ€ɠ’ḅ¥®L’¤Ạ?⁴‘
ṣ⁷ṫ€⁵ḣ€40Fḟ⁶s©2ḣ¢ṫ¢[“\x”]p

This expects the hexdump as sole command-line argument, and the end and start points on STDIN, in that order, separated by a linefeed.
Try it online!

I'd love to see an explanation for this ;)

I'll add one later, but I'll try to golf it a bit first. 51 bytes of Jelly vs 69 bytes of Bash can't be right...

PowerShell v2+, 175 157 142 133 129 bytes
param($a,$b,$c)'\x'+(($z=$a-split"`n"|%{$_[10..48]-ne32-join''-split'(..)'-ne''})["0x$b"..(("0x$c",$z.count)[$c-eq-1])]-join'\x')

Takes input $a, $b, $c, with $a as either a literal newline-separated string, or with the PowerShell `n character separating the lines. We set helper string $z as the heavily processed $a as follows --
First we -split on newlines, then, for each line |%{...}, we slice the middle section [10..48], use the -ne32 to remove spaces, -join it back together into one long string, -split it on every two characters (keeping the two characters), and -ne'' to remove the empty elements. This results in an array of two-element strings, like ('31','c0','b0'...).
We then slice into that array based on $b cast with the hexadecimal operator up to the value of $c. We need to use a pseudo-ternary here that accounts for whether $c is -1 or not. If it is, we choose the .count (i.e., the end element) of $z. Otherwise, we just prepend the 0x hexadecimal operator with $c in a string. Note that this is zero-indexed.
That array slice has its elements -joined together with a literal \x to form one string. That's prepended with another literal \x and the result is left on the pipeline. Printing is implicit.
Example
PS C:\Tools\Scripts\golfing> .\xxd-output.ps1 "00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY" a -1
\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59

Can you access shell with this language?

@VTCAKAVSMoACE In theory, given the new Windows Subsystem for Linux, it should be possible to pipe things together and/or pass parameters via command line. Implementation is left as an exercise for the reader. ;-)

Jelly, 39 38 37 bytes
ØhiⱮɠ’ḅ¥ȷ9Ṃ?⁴‘
Ỵṫ€⁵ḣ€40Fḟ⁶s2ṭ€⁾\xḣ¢ṫ¢

Try it online!
Now beats 05AB1E! (despite the lack of "convert from hexadecimal" builtin)
Same input format as Dennis' solution.
Use Ɱ, which is a new feature (short for Ð€). Without it, this would take 38 bytes.

Only works for input with len up to 1e9.

But if it's on FAT32 (where input size is at most 2GB) it's enough.

Perl, 114 bytes
($_,$a,$b)=@ARGV;s/^.*:|\S*$|\s//gm;@_=(m/../g);for(@_){s/^/\\x/}$"='';say substr"@_",4*$a,$b!=-1?4*($a+$b):2<<20;

Arguments given on the command line as a quoted string followed by two numbers. The numbers are taken in decimal (I know hex was used in the examples but it wasn't specified in the post)
Technically only works on inputs with up to 2^21 bytes since perl's substring method is silly

Apparently the range is inclusive, so for instance 7 to e should result in a string of length 32.

Python, 140 bytes
lambda O,a,b:''.join(sum([['\\x'+x[:2],('','\\x')[len(x)>2]+x[2:]]for x in O.split()if len(x)<5],[])[int(a,16):(int(b,16)+1,None)[b=='-1']])

https://repl.it/ClB3
Splits the original string and dumps the elements if they're less than five characters, prepends \x, and slices by the second and third arguments.
162 byte version if we need to handle other types of output not specified by the question:
import re
J=''.join
def f(x,a,b):r=J(J(re.findall(':(.*?)  ',x)).split());print J(['\\x'+i+j for i,j in zip(r,r[1:])][::2][int(a,16):(int(b,16)+1,None)[b=='-1']])

This won't work if, e.g., the last line is something like 00000030: 5858 58                                  XXX since it'll pull out the last portion and you'll get something like \x58\x58\x58\xXX\xX.

@TimmyD I didn't think that case needed to be handled, going off the specs of the challenge.

I read the challenge as the given first argument is just an example, so there could be other xxd output used as the argument instead. "Here's an example of what the the first argument will look like:"

Python 2 and 3 - 164 162 150 146 134 150 bytes
Now accepts hex strings for second and third arguments.
j=''.join
def f(a,b,c):s=j(x[10:49].replace(' ','')for x in a.split('\n'));print(j('\\x'+s[i:i+2]for i in range(int(b,16)*2,1+2*int(c,16)%len(s),2))

Python 3.5, 125 bytes
import re
lambda s,b,e:re.sub(r'(\w\w)',r'\\x\1',re.sub(r'^.*?:|  .*$|\s','',s,0,8)[2*int(b,16):[2*int(e,16)+2,None][e<'0']])

Ungolfed:
def f(s,b,e):
    b = 2*int(b,16)
    e = [2*int(e,16)+2,None][e<'0']
    x = re.sub(r'''(?v)   # verbose (not in golfed version)
            ^.*?:     # match begining of line to the ':'
           |  .*$     # or match '  ' to end of line
           |\s        # or match whitespace
           ''',
           '',        # replacement
           s,
           0,         # replace all matches
           re.M       # multiline mode
           )
    y = re.sub(r'(\w\w)', # match pairs of 'word' characters
           r'\\x\1',  # insert \x
            x[b:e])
    return y

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