[Question]
  [
This is the inverse of [Let's do some "deciph4r4ng"](https://codegolf.stackexchange.com/q/115709/38183)
---
In this challenge, your task is to encipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each typical writing character (ASCII range 32-126) must be replaced by a number ***N*** (0-9) to indicate that it is the same as the character ***N+1*** positions before it. The exception is when the character does not appear within the previous 10 positions in the original string. In that case, you should simply print the character again.
Effectively, you should be able to reverse the operation from the original challenge.
### Example
The input string `"Programming"` would be encoded this way:
[![Example1](https://i.stack.imgur.com/WWdbF.png)](https://i.stack.imgur.com/WWdbF.png)
Hence, the expected output is `"Prog2am0in6"`.
### Clarifications and rules
* The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty.
* The original string is guaranteed not to contain any digit.
* Once a character has been encoded, it may in turn be referenced by a subsequent digit. For instance, `"alpaca"` should be encoded as `"alp2c1"`.
* References will never wrap around the string: only previous characters can be referenced.
* You can write either a full program or a function, which either prints or outputs the result.
* This is code golf, so the shortest answer in bytes wins.
* Standard loopholes are forbidden.
### Test cases
```
Input : abcd
Output: abcd
Input : aaaa
Output: a000
Input : banana
Output: ban111
Input : Hello World!
Output: Hel0o W2r5d!
Input : this is a test
Output: this 222a19e52
Input : golfing is good for you
Output: golfin5 3s24o0d4f3r3y3u
Input : Programming Puzzles & Code Golf
Output: Prog2am0in6 Puz0les7&1Cod74G4lf
Input : Replicants are like any other machine. They're either a benefit or a hazard.
Output: Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.
```
  
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~24~~ 23 bytes
```
(.)(?<=\1(.{0,9}).)
$.2
```
[Try it online!](https://tio.run/nexus/retina#HUyxCsIwFNzfVzxBtAUJ6iYoDg46FhFcXF6b1yaY5kkah1b89pp6d8vdcTdmKs@O@8Njk6nPerX75iqHudqOI5WVBkqAknwiXNg5wbsEp2cQje0wiTByF6ERV1vfTEkjorGWgL28oQjSBGrbqSvew@C4wwWeRDOe0wSu/HK2Ih/TU2B09slIvkeJhgO2VBnrWeHNcL9MPdt/Tliy59pGlMkYGiho9QM "Retina – TIO Nexus")
A fairly simple regex substitution. We match each character and try to find a copy of it 0-9 characters before it. If we find it, we replace the character with the number of characters we had to match to get to the copy.
The results don't quite match the test cases, because this one uses the largest possible digit instead of the smallest possible one.
[Answer]
## JavaScript (ES6), ~~74~~ ~~57~~ 54 bytes
*Saved 3 bytes thanks to ETHproductions with the brilliant `p=/./g` instead of `p={}` (inspired by Neil)*
```
s=>s.replace(p=/./g,(c,i)=>(i=p[c]-(p[c]=i))>-11?~i:c)
```
### Test cases
```
let f =
s=>s.replace(p=/./g,(c,i)=>(i=p[c]-(p[c]=i))>-11?~i:c)
console.log(f("abcd"));
console.log(f("aaaa"));
console.log(f("banana"));
console.log(f("Hello World!"));
console.log(f("this is a test"));
console.log(f("golfing is good for you"));
console.log(f("Programming Puzzles & Code Golf"));
console.log(f("Replicants are like any other machine. They're either a benefit or a hazard."));
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~72~~ 66 bytes
*Thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for golfing 6 bytes!*
```
(a:r)%s=last(a:[n|(n,b)<-zip['0'..'9']s,b==a]):r%(a:s)
e%s=e
(%"")
```
[Try it online!](https://tio.run/nexus/haskell#@6@RaFWkqVpsm5NYXAJkR@fVaOTpJGna6FZlFkSrG6jr6albqscW6yTZ2ibGaloVqQIVFWtypQK1pHKl2WqoKilp/s9NzMyzzcwrSS1KTC5RSPsfUJSfXpSYm5uZlw4A "Haskell – TIO Nexus")
The function `%` keeps the partially processed string in reverse in its second argument, so it's able to search the first 10 elements of this string for occurences of the character it's examinating. The submission consists of the unnamed function `(%"")` which calls the previous function with the empty string as its second argument.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20 19~~ 18 bytes
-2 Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)
```
õ¹vDyåiDykëy}?yìT£
```
[Try it online!](https://tio.run/nexus/05ab1e#@695aGeZS@XhpZkuldmHV1fW2lce2nF4Tcihxf//B6UW5GQmJ@aVFCskFqUq5GRmpyok5lUq5JdkpBYp5CYmZ2TmpeophGSkVqoD5VMzweKJCkmpealpmSUK@SBORmJVYlGKHgA "05AB1E – TIO Nexus")
```
õ                  # Push an empty string
 ¹v y              # For each character in input
   D               # Duplicate the string on the stack (call this S)
     åi            # If this character is in S
       Dyk         #   Push the index of that that character 
          ë }      # Else
           y       #   Push the character 
             ?     # Print without newline
              yì   # Prepend this character to S
                T£ # Remove all but the first 10 elements from S
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
s=''
for c in input():d=s[:~10:-1].find(c);s+=-d*c or`d`
print s
```
[Try it online!](https://tio.run/nexus/python2#Lc07C4NAEATg3l@xEMjeRc2jvWiVIq1FOhE09xBBPdnVFBb@dXOFMM0U883OOWLkPIGGbgyZlllIZXIu1fa4q/RRXV03GqHlk@M8NRcNnmpTRxN14wy8n@BjeQ7LnyW2UeTyvhm@pgFSZM2irTg6J1pxLHSJN8x0hgpVFX653AIU/EomlCDKQ3aC5Y4F@ZaaYejGFoplXXvLcIaXNxbevnf4Bw "Python 2 – TIO Nexus")
[Answer]
# [Perl 5](https://www.perl.org/), 36 bytes
35 bytes of code + `-p` flag.
```
s/(\D)(.{0,9})\K\1/length$2/e&&redo
```
[Try it online!](https://tio.run/nexus/perl5#HYtBi8IwFITv@RVPVqqCturNswu74EVE8NLLazM2wdekpPFgxd9eozNz@WaYn0mHILTqxr6Yl7@Lef5cL3evRXkoN4XANdFMtwWyLED7ceSq1oqTVMUuWf1DxNPFB9ETFY3tKYUpoo/qGHwTuG2ta@h4HwZBTxntvQb9ebmqEzqxNbuYHgEk9gZi9yAfDQK1XBvrkNPZ4DFLO@y3Z6rgcLWR/AcMDxx0/gY "Perl 5 – TIO Nexus")
Some explanations:  
The goal is to replace a non-digit character (`\D` but it correspond to the backreference `\1` in my regex) that is preceded by less than 10 characters (`.{0,9}`) and the same character (`(\D)`...`\1`) by the length of the `.{0,9}` group (`length$2`). And `redo` while characters get replaced.
[Answer]
# Python 2, ~~89~~ 84 bytes
```
m=input()[::-1];j=1;t=''
for i in m:s=m[j:].find(i);t=[i,`s`][0<s<10]+t;j+=1
print t
```
[Try it Online!](https://tio.run/nexus/python2#DcmxDoMgEADQ3a@4STTaRlbwJoeu7oTEGsUcETCAiz9P@9ZXHJK/7ty0SogX19IilxkZq0yIQEAenEjolBX6bchvDbX/V9QvadFqGNPIB91laTvk1RXJZ8ilsDmGI36dI3/AfD/PuSeoYQrbDp9wmnViPw)
Iterates throught the string in reverse, and builds a new string with the correct numbers inserted.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
£¯Y w bX s r"..+"X
```
[Try it online!](https://tio.run/nexus/japt#HclNDkAwFEXhrdx0YiDpYsSA4cOVvqCkmgjbsQB7sLH6GZ7vpPu8rxobmgorgrE2N1VKpuAyais@rpBAjDoQ4nfM0TFgktapp0XpuGfvp/4uaOjZa8T8hZNDQmfNAw "Japt – TIO Nexus")
### Explanation
```
£   ¯  Y w bX s r"..+"X
mXY{s0,Y w bX s r"..+"X}
                          // Implicit: U = input string
mXY{                   }  // Replace each char X and index Y in U by this function:
    s0,Y                  //   Take U.slice(0,Y), the part of U before this char.
         w bX             //   Reverse, and find the first index of X in the result.
                          //   This gives how far back this char last appeared, -1 if never.
              s           //   Convert the result to a string.
                r"..+"X   //   Replace all matches of /..+/ in the result with X.
                          //   If the index is -1 or greater than 9, this will revert to X.
                          // Implicit: output result of last expression
```
[Answer]
# JavaScript, ~~100~~ 80 bytes
```
x=>x.split``.map((c,b,a)=>{for(i=0;i++<=9&&a[b-i]!=c;);return i>9?c:i-1}).join``
```
[Try it online!](https://tio.run/nexus/javascript-node#bY4xT8MwFIR3fsWjQ7CVYsFYgsPAwFohNoSUF/c5eeDY1XOK2iB@ewhMCHHb3ek@nbfz0dZHk/eBx6YxQu8kmZQ2A@6Vcut2jdrWHz6JYntVcVne2k1R4HNb8su5dZWuhMaDROB6c@du@PL6U//CvCaOTTO7FHMKZELqlFcrXLTS@uxP/EjLDYdxzIBCEPiNAOMJ0tiTwICu50gGnno6XSw98U@O0FIkzyOkb9PjhLIz/@C3kjrBYeDYwfYwTYEyFHCfdgQPKfhlMX8B "JavaScript (Node.js) – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
õIv¹N£RT£©yåi®ykëy}J
```
[Try it online!](https://tio.run/nexus/05ab1e#@394q2fZoZ1@hxYHhRxafGhl5eGlmYfWVWYfXl1Z6/X/f1BqQU5mcmJeSbFCYlGqQk5mdqpCYl6lQn5JRmqRQm5ickZmXqqeQkhGaqU6UD41EyyeqJCUmpeallmikA/iZCRWJRal6AEA "05AB1E – TIO Nexus")
**Explanation**
```
õ                     # push an empty string
 Iv                   # for each [index,char] [N,y] in input
   ¹N£                # push the first N characters of input
      R               # reverse
       T£             # take the first 10 characters of this string
         ©            # save a copy in register
          yåi         # if y is in this string
             ®yk      #   push the index of y in the string in register
                ë     # else 
                 y    #   push y
                  }   # end if
                   J  # join stack as one string
```
[Answer]
# Python 3, ~~125~~ 118 bytes
```
def p(x):print(x,end='')
l={}
for i,c in enumerate(input()):
 if l.get(c,i+9)<i+9:
  p(i-l[c]-1)
 else:
  p(c)
 l[c]=i
```
[Try it online!](https://tio.run/nexus/python3#JczBCsIwEATQe75ib81iKvRoMV8iHkq6qQsxhmQLBfHb44owDMw7TF8pQrEHzqVyFns4yqsfBjTJvz8mviqwC8AZKO9PqouQ5Vx2sYizAY6QzhuJDY5PF7xqqeohj@kW7uOEBig1@mPQ9WPPvcuDG2gWEGryBQ)
[Answer]
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 113 bytes
Since the function creates a copy of an input string, the maximum size of input is 98 characters (more than enough to fit the longest test input). Of course, this can be changed to any other value.
```
i,j;f(char*s){char n[99];strcpy(n,s);for(i=1;s[i];i++)for(j=i-1;j>-1&&i-j<11;j--)if(n[i]==n[j])s[i]=47+i-j;j=-1;}
```
[Try it online!](https://tio.run/nexus/c-tcc#bY1BS8QwEIXv/RVDwTWxzUJBWNYY754E8VZ7iN2ETFynJckKddnfXtOKeHEuM@/NN/NmrL20rHc63ER@XjpQu993MqbQjxOjOnJph8BQNTK22EmsKr4YXqFopH8QzWaDwt83WQjB0TLKmFLU@o4vF@p2V2VAepX5y4yU4EMjsc8BD7w4F5BrDc6RbafKZzMesdeUIuhg4IjvBjRNMCRnQj7tHZLZwosz03XeG1x9DW@GjMUEwyKc/tLhsC3l@n4MOdWy8pHGU4I7uIqvVNZLIP8BLPubf@GnU8r0P3Bxmb8B "C (tcc) – TIO Nexus")
**Edit**
-15 bytes. Thanks **Johan du Toit**.
[Answer]
# Java 7, ~~102~~ 101 bytes
```
void a(char[]a){for(int b=a.length,c;--b>0;)for(c=b;c-->0&c+11>b;)if(a[c]==a[b])a[b]=(char)(b-c+47);}
```
[Try it online!](https://tio.run/nexus/java-openjdk#nZLBbsMgDEDv@Qqvhy6oS9RJk3aIUinqYTtW66QdohwMcRI0AhUhndKq395B9gULIDA2fjZgoXAYoLjez0bWgLHo0JYVsmtjbCy1A55jqki3rnsSWZLw3TZjwSZynokk2W3XYvP8vOMZk02MpajyHEtesTDlM47FPBGbl1eW3e6nkSspYHDo/DLH7FHq@Ois1G1Zndk1ggIQctD0A0XMsgj@cuJe4vkKuahXqTN7ryysxWk@ginGPAjHaXDUp2Z06ckjndKzPgqevi3z5Kh9X@b7TkoZ@DJW1Q/LCK6TA/iB4GhwyxitUY1/4IBpjanB/yBMZlwGO1jTWuz7ADyMl4uiAdawNzXBm4@zDPpBJ18ZqJ2/qCVQ8psA9QTGdWR9kYhOakrhs6Pp0dtJznoETpoa6cCETYcXtHX6/wxu0e3@Cw "Java (OpenJDK 8) – TIO Nexus")
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). I always enjoy an excuse to use the goes-to operator.
[Answer]
# PHP, 104 Bytes
forward solution
```
for($i=0;$i<strlen($a=&$argn);$f[$l]=$i++)$a[$i]=is_int($f[$l=$a[$i]])&($c=$i-$f[$l]-1)<10?$c:$l;echo$a;
```
Backwards solutions
[Online Versions](http://sandbox.onlinephpfunctions.com/code/258a21bf9091c12366037b4297bc2bf275cab010) 
## PHP, 111 Bytes
```
for(;++$i<$l=strlen($a=&$argn);)!is_int($t=strrpos($argn,$a[-$i],-$i-1))?:($p=$l-$i-$t-1)>9?:$a[-$i]=$p;echo$a;
```
## PHP, 112 Bytes
```
for(;++$i<$l=strlen($a=&$argn);)if(false!==$t=strrpos($argn,$a[-$i],-$i-1))($p=$l-$i-$t-1)>9?:$a[-$i]=$p;echo$a;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/7a425f8f42d9ca94f451fa5f2f72b46971966a5d)
[Answer]
## REXX, ~~124~~ 125 bytes
```
a=arg(1)
b=a
do n=1 to length(a)
  m=n-1
  c=substr(a,n,1)
  s=lastpos(c,left(a,m))
  if s>0&m-s<=9 then b=overlay(m-s,b,n)
  end
say b
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~117~~ ~~103~~ 93 bytes
```
i,j;f(char*s){for(i=strlen(s)-1;s[--i];)for(j=i-1;s[j]&&i-j--<10;)if(s[i]==s[j])s[i]=47+i-j;}
```
[Try it online!](https://tio.run/##bY7BTsMwDIbvfQqrEiNhy8SkSZMIeYCdkBC30kPInMWlpFWSIY1pz16SIjjhk/3/v/3ZiKMx00SrTlpmnA53kV/sEBipmEKPnkUuNjI2QlAreXE6RbPStYsFiU6Ix8295GRZbKhVqhh8bre7ZfbldSKf4EOTZ58DHXh1qSBXgUFmNK2qn3HsyWifIuiA0NM7gvZnGJLDkFeNI49reHF4vs0@0qxreEOPlhIMZXD6S4fDupbz@TFkqmX13o@nBA9wE199vSpA/hPI//71v@GnU8rpf8LVdfoG "C (gcc) – Try It Online")
No string.h import, works w/ warning. If this is against the rules, I'll pull it.
## Pretty Code:
```
i,j;
f(char *s) {
    // Chomp backwards down the string
    for(i=strlen(s)-1; s[--i];)
        // for every char, try to match the previous 10
        for(j=i-1; s[j] && i-j-- < 10;)
            // If there's a match, encode it ('0' + (i-j))
            if (s[i] == s[j])
                s[i] = 47+i-j;
}
```
## Edits:
* Changed from LLVM to gcc to allow implicit i,j declaration, removed lib import.
* Added function wrapper for compliance
* Decrement in loop boundaries thanks to **ceilingcat**
* Removed `break` and braces from loop, first match modifies `s[i]
[Answer]
# MATL, ~~31~~ 30 bytes
```
&=R"X@@f-t10<)l_)t?qV}xGX@)]&h
```
Try it at [**MATL Online!**](https://matl.io/?code=%26%3DR%22X%40%40f-t10%3C%29l_%29t%3FqV%7DxGX%40%29%5D%26h&inputs=%27golfing+is+good+for+you%27&version=19.9.0)
**Explanation**
```
        % Implicitly grab input as a string
&=      % Perform element-wise comparison with automatic broadcasting.
R       % Take the upper-triangular part of the matrix and set everything else to zero
"       % For each column in this matrix
X@      % Push the index of the row to the stack
@f      % Find the indices of the 1's in the row. The indices are always sorted in
        % increasing order
-       % Subtract the index of the row. This result in an array that is [..., 0] where
        % there is always a 0 because each letter is equal to itself and then the ...
        % indicates the index distances to the same letters
t10<)   % Discard the index differences that are > 9
l_)     % Grab the next to last index which is going to be the smallest value. If the index
        % array only contains [0], then modular indexing will grab that zero
t?      % See if this is non-zero...
  qV    % Subtract 1 and convert to a string
}       % If there were no previous matching values
  x     % Delete the item from the stack
  GX@)  % Push the current character
]       % End of if statement
&h      % Horizontally concatenate the entire stack
        % Implicit end of for loop and implicit display
```
]