title: Alienese cycles

text:
# Question
Title: Alienese cycles
Alienese refers to two "languages" in the show *Futurama*. In actuality, they are two ciphers of English text with a pictographic alphabet. The first is a simple substitution cipher, but the second is slightly more complex. The second is a type of autokey cipher that follows these steps:

* Take a word to be encrypted, e.g. `FUTURAMA`
* Replace each letter with its 0-index in the alphabet: `[5, 20, 19, 20, 17, 0, 12, 0]`
    + Note that, due to the next step, zero indexing is important and 1 indexing cannot be used
* Take the cumulative sums of the array: `[5, 25, 44, 64, 81, 81, 93, 93]`
* Modulo each term by `26` to bring it within bounds: `[5, 25, 18, 12, 3, 3, 15, 15]`
* Index into the alphabet: `FZSMDDPP`

We can iterate this process until we reach our original word again. For example, for `FUTURAMA`, the full list, space separated, is

```
FUTURAMA FZSMDDPP FEWILODS FJFNYMPH FOTGEQFM FTMSWMRD FYKCYKBE FDNPNXYC FIVKXUSU FNISPJBV FSASHQRM FXXPWMDP FCZOKWZO FHGUEAZN FMSMQQPC FRJVLBQS FWFALMCU FBGGRDFZ FGMSJMRQ FLXPYKBR FQNCAKLC FVIKKUFH FAISCWBI FFNFHDEM FKXCJMQC FPMOXJZB FUGURAZA FZFZQQPP FEJIYODS FJSAYMPH FOGGEQFM FTZFJZEQ FYXCLKOE FDACNXLP FIIKXUFU FNVFCWBV FSNSUQRM FXKCWMDP FCMOKWZO FHTHRNMA FMFMDQCC FRWILBDF FWSALMPU FBTTEQFZ FGZSWMRQ FLKCYKBR FQACAKLC FVVXXHSU FAVSPWOI FFASHDRZ FKKCJMDC FPZBKWZB FUTUEAZA FZSMQQPP FEWIYODS FJFNLZCU FOTGRQSM FTMSJZRD FYKCLKBE FDNPAKLP FIVKKUFU FNISCWBV FSASUQRM FXXPJZQC FCZOXWMO FHGURNZN FMSMDQPC FRJVYODF FWFAYMPU FBGGEQFZ FGMSWMRQ FLXPLXOE FQNCNKYC FVIKXHFH FAISPWBI FFNFUQRZ FKXCWMDC FPMOKWZB FUGUEAZA FZFZDDCC FEJILOQS FJSALZPH FOGGRQFM FTZFWMRD FYXCYKBE FDACAKLP FIIKKUFU FNVFPJOI FSNSHQEM FXKCJZDP FCMOXWZO FHTHEAZN FMFMQQPC FRWIYODF FWSAYMPU FBTTRDSM FGZSJMEQ FLKCLXBR FQACNKLC FVVXKUFH FAVSCWBI FFASUQRZ FKKCWMDC FPZBXJMO

```

and takes 104 steps to return to `FUTURAMA`. I conjecture that, for any non-empty string of letters, this process always returns to the original string in a finite number of steps.

---

You are to "prove" this conjecture. That is, write a program that takes a non-empty string of letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`, or `abcdefghijklmnopqrstuvwxyz`, you may choose), and outputs the number of steps to return to the original input, by iterating this autokey cipher. Note that, by listing the terms, the list should *either* start or end with the input, which counts as either the first or last step.

You may take input in any convenient format, including taking the input as an array of characters. You may only take the input as an array of code points if you are unable to input as characters or as a string (e.g. brainfuck).

This is , so the shortest code in bytes wins.

## Test cases

```
J -> 1
NK -> 2
TQR -> 52
NAK -> 4
AAAQ -> 1
CGCC -> 13
CAIRD -> 26
NNNNX -> 8
FUTURAMA -> 104
ALIENESE -> 104
NANNANNAN -> 16
ZBDMBCWJQJPWF -> 208
MUJJEKIBPULKWRHW -> 2704
HWGYIBRBRBLADVYTXL -> 5408

```

---

Interestingly, it appears as almost all words result in a number of steps either equal to 1 (a fixed point) or divisible by 13. We say a word is "interestingly-aliense" if this *isn't* the case, i.e. it is neither a fixed point, nor has a cycle length divisible by 13. We can see, by brute forcing all combinations of words with 2 or 3 letters, that the full list of these words is

```
NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ ANA ANB ANC AND ANE ANF ANG ANH ANI ANJ ANK ANL ANM ANN ANO ANP ANQ ANR ANS ANT ANU ANV ANW ANX ANY ANZ NAA NAB NAC NAD NAE NAF NAG NAH NAI NAJ NAK NAL NAM NAN NAO NAP NAQ NAR NAS NAT NAU NAV NAW NAX NAY NAZ NNA NNB NNC NND NNE NNF NNG NNH NNI NNJ NNK NNL NNM NNN NNO NNP NNQ NNR NNS NNT NNU NNV NNW NNX NNY NNZ

```

All of which either result in 2 or 4. We can also see that all of these contain the letter `N`. Indeed, we can try out some guesses for longer "interestingly-alienese" words based on this. For example, `NNNNX` has a cycle of 8 (`NNNNX, NANAX, NNAAX, NAAAX, NNNNK, NANAK, NNAAK, NAAAK`), and `NANNANNAN` has a cycle of 16, as shown above. Can you find any more, potentially with longer cycles?

# Answer
# K (ngn/k), ~~13~~ 12 bytes

```
#(26!+\)\65!

```

Try it online!

Git gud, Jelly. Only one byte ahead of an ASCII-only language? :P

Takes uppercase input and computes the length of the loop. -1 byte thanks to ZippyMagician's observation that subtract 65 == mod 65.

```
#(26!+\)\65!     input: a string
         65!     modulo 65 ('A') from each letter (gives a numeric list)
 (     )\        repeat and collect until loop is found:
  26!+\            cumulative sum mod 26
#                length of the result

```
> 11 votes

# Answer
# Wolfram Language (Mathematica), 60 bytes

```
If[#!=##2,1+Accumulate@#~Mod~26~#0~##,0]&[LetterNumber@#-1]&

```

Try it online!

Input a list of characters. Determines the period through recursion. Times out (or reaches the recursion limit) for larger test cases.

---

## Wolfram Language (Mathematica), ~~69~~ ~~65~~ 63 bytes

```
s1//.j_/;!Drop[LetterNumber@s-1,-j]~Mod~#1:>j#&//#@2#@13&

```

Try it online!

Input a list of characters. Computes the period. The private-use characters are `\[Function]` and `\[VectorLess]`.

```
                                              &             g: i =>
1//.j_/;!                                 :>j#                least power of i (=j) such that
         Drop[LetterNumber@s-1,-j]~Mod~#1                      no elements divisible by i outside the final j
                                               //#@2#@13&   g(2)*g(13)

```

### Explanation:

Denote the \\$n\\$th accumulation of the list \\$A=(a\_1,a\_2,...,a\_l)\\$ by \\$A\[n\]=(a\[n\]\_1,a\[n\]\_2,...,a\[n\]\_l)\\$, and the length of the cycle of \\$A\\$ modulo \\$m\\$ by \\$c\_m(A)\\$. Then, in general,
\\$a\[n\]\_k=\displaystyle\sum\_{i=0}^{k-1}\frac{n^{(i)}}{1^{(i)}}a\_{k-i}=a\_k+\sum\_{i=1}^{k-1}\frac{n^{(i)}}{1^{(i)}}a\_{k-i}\\$, where \\$x^{(y)}\\$ is the rising factorial. (These are the diagonals of Pascal's triangle).
By definition of a cycle, for any \\$n\\$ where \\$A\[n\]\equiv A\pmod m\\$, that is, \\$a\[n\]\_k\equiv a\_k\pmod{m}\\$ for all \\$k\\$, \\$c\_m(A)\mid n\\$.

Since 2 and 13 are relatively prime, \\$c\_{26}(A)=\operatorname{LCM}(c\_2(A),c\_{13}(A))\\$.

First consider cycles mod 2. Let \\$2^x\\$ be the least integer power of 2 such that \\$2\mid a\_i\\$ for all \\$a\_i\le l-2^x\\$, i.e. the final \\$2^x\\$ elements contain all those not divisible by 2. Consider the \\$2^x\\$th accumulation \\$A\[2^x\]\\$:
\\$\begin{align\*} a\[2^x\]\_k&=a\_k+\sum\_{i=1}^{k-1}\frac{(2^x)^{(i)}}{1^{(i)}}a\_{k-i}\\ &=a\_k+\sum\_{\substack{1\le &i\<k\\\&i\<2^x}}\frac{(2^x)^{(i)}}{1^{(i)}}a\_{k-i} \end{align\*}\\$
It can be fairly easily be shown that \\$2\mid\frac{(2^x)^{(i)}}{1^{(i)}}\\$ for all \\$0\<i\<2^x\\$, so \\$A\[2^x\]\equiv A\pmod2\\$ and \\$c\_2(A)\mid2^x\\$.

Because of the way we defined \\$2^x\\$ there exists minimal \\$p\\$ such that \\$a\_p\not\equiv0\pmod2\\$ and \\$2^{x-1}\le l-p\<2^x\\$. Then
\\$\begin{align\*} a\[2^{x-1}\]\_{p+2^{x-1}}&=a\_{p+2^{x-1}}&&+\sum\_{i=1}^{p+2^{x-1}-1}\frac{(2^{x-1})^{(i)}}{1^{(i)}}a\_{p+2^{x-1}-i}\\ &=a\_{p+2^{x-1}}&&+\sum\_{i=1}^{2^{x-1}-1}\underbrace{\frac{(2^{x-1})^{(i)}}{1^{(i)}}}\_{\equiv0\pmod2}a\_{p+2^{x-1}-i}\\ &&&+\underbrace{\frac{(2^{x-1})^{(2^{x-1})}}{1^{(2^{x-1})}}a\_p}\_{\text{both }\not\equiv0\pmod2}\\ &&&+\sum\_{i=1}^{p-1}\frac{(2^{x-1})^{(i+2^{x-1})}}{1^{(i+2^{x-1})}}\underbrace{a\_{p-i}}\_{\equiv0\pmod2}\\ &\not\equiv a\_{p+2^{x-1}}&&\pmod2,\\ \end{align\*}\\$
using primality of 2 to show that the middle term must \\$\not\equiv0\pmod2\\$.

Therefore \\$A\[2^{x-1}\]\not\equiv A\pmod2\\$, so \\$c\_2(A)\not\mid2^{x-1}\\$. Since 2 is prime, \\$c\_2(A)=2^x\\$.
(\\$p\\$ does not exist if \\$2^x=1\\$, but in that case the only integer \\$c\_2(A)\mid1\\$ is \\$c\_2(A)=1\\$).

An analogous argument works mod 13, so we can let \\$c\_{13}(A)=13^y\\$, where \\$13^y\\$ is defined in a similar fashion to \\$2^x\\$, and \\$c\_{26}(A)=2^x13^y\\$.
> 8 votes

# Answer
# Jelly, ~~14~~ 12 bytes

```
ØAiⱮ’Ä%26ƊƬL

```

Try it online!
> 4 votes

# Answer
# Ruby, ~~69~~ 64 bytes

```
->s{g=h=s.bytes;1.step.find{r=0;g==h=h.map{|b|(r+=b-13)%26+65}}}

```

Try it online!
> 4 votes

# Answer
# Python 3.8 (pre-release), 83 bytes

```
lambda s:(g:=lambda r,i=1:all(ord(c)%r==~r%2for c in s[:-i])or g(r,i*r)*r)(2)*g(13)

```

Try it online!

Port of my second Mathematica solution, and probably a bit easier to understand. Python plays nicer with out-of-bounds slices.
> 4 votes

# Answer
# JavaScript (Node.js),  ~~62~~  61 bytes

Expects the input in lowercase, as suggested by @UnrelatedString (-1 byte).

```
f=(s,q)=>s!=q&&1+f(Buffer(s).map(c=>(t+=c+7)%26+97,t=0),q||s)

```

Try it online!

Or 56 bytes by taking a Buffer as input.

### Commented

```
f = (s,            // s = input string
        q) =>      // q = reference string, initially undefined
  s != q &&        // stop as soon as s == q
  1 +              // otherwise: increment the final result
  f(               // do a recursive call:
    Buffer(s)      //   turn s into a Buffer
    .map(c =>      //   for each ASCII code c in the Buffer:
      (t += c + 7) //     add c + 7 to t
                   //     (where 7 is -(97 mod 26) + 26)
      % 26         //     reduce t modulo 26
      + 97,        //     add the ASCII code of 'a'
      t = 0        //     start with t = 0
    ),             //   end of map()
    q              //   pass the reference string q,
    || s           //   or s if q is still undefined (1st iteration)
  )                // end of recursive call

```
> 3 votes

# Answer
# QBasic, 119 bytes

```
INPUT w$
n$=w$
1s=0
FOR i=1TO LEN(n$)
s=s+ASC(MID$(n$,i))-65
MID$(n$,i)=CHR$(s MOD 26+65)
NEXT
r=r+1
IF n$<>w$GOTO 1
?r

```

Try it at Archive.org!

### Explanation

```
INPUT w$
n$ = w$

```

Input `w$` (the original word) and set `n$` (the next encrypted form) to `w$`.

```
1 s = 0

```

Label `1` is the start of our main loop. Initialize `s` (the cumulative sum) as 0.

```
FOR i = 1 TO LEN(n$)

```

Loop over the indices of the characters in `n$`.

```
s = s + ASC(MID$(n$, i)) - 65

```

Get the ASCII code of the `i`th character of `n$`, subtract 65, and add to the cumulative sum.

```
MID$(n$, i) = CHR$(s MOD 26 + 65)

```

Take `s` mod 26, add 65, convert from ASCII code, and set the `i`th character of `n$` to that character.

```
NEXT
r = r + 1

```

End of `FOR` loop. Increment `r` (the number of repetitions we've gone through).

```
IF n$ <> w$ THEN GOTO 1

```

If the next encrypted form is different from the original word, loop.

```
PRINT r

```

Otherwise, print the number of repetitions.

---

In QB64, we can get down to **106 bytes** using the extended forms of `ASC` instead of `MID$`:

```
INPUT w$
n$=w$
1s=0
FOR i=1TO LEN(n$)
s=s+ASC(n$,i)-65
ASC(n$,i)=s MOD 26+65
NEXT
r=r+1
IF n$<>w$GOTO 1
?r

```
> 3 votes

# Answer
# Joy, 166 bytes

```
DEFINE i == rotate 1 + rotate [0]swap[[dup dup size 1 - at]dip +[]cons concat]step rest[26 rem]map.
DEFINE a == 0 swap[ord 65 -]map dup i[equal not][i]while pop pop.

```

Crashes on the longer inputs, but as far as I can tell that's because of the implementation.
Explanation:

```
DEFINE sumScan == [0]swap[[dup dup size 1 - at]dip +[]cons concat]step rest.
DEFINE iter == rotate 1 + rotate (* increment counter *)
    sumScan[26 rem]map. (* sum scan, then mod 26 *)
DEFINE alienese == 0 swap[ord 65 -]map (* convert to numbers and set counter *)
    dup iter[equal not][iter]while pop pop. (* iterate until it's equal again, then pop off values that aren't counter *)

```
> 2 votes

# Answer
# Python 3, 136 bytes

```
s=k=input();n=1
while 1:
 l=[ord(x)-65for x in s];s=''.join(chr(sum(l[:x+1])%26+65)for x in range(len(l)))
 if s==k:break
 n+=1
print(n)

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 79 bytes

```
s->d=Mod(1-x,x^#s);p=Mod(Polrev(Vecsmall(s))-65/d,26);i=1;while(p*d^i!=p,i++);i

```

Try it online!

Convert the string to an element \\$P\\$ in the ring \\$\mathbb{Z}\[X\]/(26,X^n)\\$, where \\$n\\$ is the length of the string, and find the smallest \\$i\>0\\$ such that \\$P\*(1-X)^i=P\\$.
> 2 votes

# Answer
# Husk, 16 bytes

```
LU¡₁m(-65D
m%26∫

```

Try it online!

#### Explanation:

```
    m(-65D    # map codepoint - 65
LU¡₁          # length of longest unique prefix of iteration of function on next line
m%26∫         # map %26 on cumsum

```
> 2 votes

# Answer
# Charcoal, ~~32~~ ~~28~~ 25 bytes

```
ＩΠＥ⟦²¦¹³⟧ＸιＬ↨⌈Ｅ⮌θ∧﹪⌕αλιμι

```

Try it online! Link is to verbose version of code. Explanation: Uses @Nitrodon/@att's closed form formula: for each of the prime factors of 26, the offset from the end of the word of the first letter whose alphabet index is not divisible by that prime is rounded up to the next power of the prime and the two values are multiplied together.

```
   ⟦²¦¹³⟧                   Literal list `2,13`
  Ｅ                         Map over the two primes
          ι                 Current prime
         Ｘ                  Raised to power
                θ           Input word
               ⮌            Reversed
              Ｅ             Map over letters
                     λ      Current letter
                   ⌕α       Index in alphabet
                  ﹪         Modulo
                      ι     Current prime
                 ∧          Logical And
                       μ    Current index
             ⌈              Take the maximum
            ↨               Converted to base
                        ι   Current prime
           Ｌ                Take the length
 Π                          Take the product
Ｉ                           Cast to string
                            Implicitly print

```

Conveniently base conversion of zero is the empty list with length zero so that the prime power is simply `1` for a single letter or a word only containing the letter `A`.

Previous 28-byte brute-force version:

```
Ｗ¬№υθ«⊞υθ≔⭆θ§αΣＥ…θ⊕λ⌕αμθ»ＩＬυ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｗ¬№υθ«

```

Repeat until a cycle is detected. (Since cumulative sum is invertible, this will always be the original word.)

```
⊞υθ

```

Save the previous value.

```
≔⭆θ§αΣＥ…θ⊕λ⌕αμθ

```

For each letter, take the prefix so far, convert each letter to its alphabet index, take the sum, and take the letter at that index.

```
»ＩＬυ

```

Output the cycle length.

Much faster ~~36~~ 32-byte version:

```
≔ＥＳ⌕αιθＷ¬№υθ«⊞υθ≔﹪ＥθΣ…θ⊕λ²⁶θ»ＩＬυ

```

Try it online! Link is to verbose version of code. Explanation:

```
≔ＥＳ⌕αιθ

```

Map the input letters to their alphabet index.

```
Ｗ¬№υθ«

```

Repeat until a cycle is detected. (Since cumulative sum is invertible, this will always be the original word.)

```
⊞υθ

```

Save the previous value.

```
≔﹪ＥθΣ…θ⊕λ²⁶θ

```

Calculate the cumulative sum modulo 26.

```
»ＩＬυ

```

Output the cycle length.

The intermediate values for a string of `n+1` `N`s can be read from the columns below, with `N` represented by `1` and `A` by `0`:

```
0   1(1...)
1   10(10...)
2   1100(1100...)
3   1000(1000...)
4   11110000(11110000...)
5   10100000(10100000...)
6   11000000(11000000...)
7   10000000(10000000...)
8   1111111100000000(...)
    (...)
11  1000100000000000(...)
12  1111000000000000(...)
    (...)
15  1000000000000000(...)
    (...)

```

The `2ᵏ`ᵗʰ row consists of a cycle of twice its length given by `2ᵏ` `1`s and `2ᵏ` `0`s. Over the next `2ᵏ-1` rows the `1`s decay into a single `1` as they did for the first `2ᵏ` rows, and then the next row doubles in cycle length.
> 1 votes

# Answer
# Pyth, 23 bytes

```
l.usmC+65%sd26._m-Cd65N

```

Try it online!

```
l.usmC+65%sd26._m-Cd65N         # Full program
 .u                             # Collect until input found
                m     N         # Map over current value (variable d)
                  Cd            # Code point of d
                 -  65          # Minus 65 (Index of alphabet)
              ._                # Prefixes
    m                           # Map over (on prefixes with d)
          sd                    # Sum current prefix
         %  26                  # Modulo 26
      +65                       # Add 65 (Code point)
     C                          # ASCII char
   s                            # Join list
l                               # Length of whole scan-fixedpoint

```
> 1 votes

# Answer
# 05AB1E, ~~17~~ 15 bytes

```
1µAskηOAsèDIQ}N

```

-2 bytes thanks to *@Neil*.

Input as a lowercase list of characters.

Try it online or verify all test cases (except for the last two, which time out).

Slightly faster minor alternative (thanks to *@Neil*):

```
Ask©1µηO₂%D®Q}N

```

Try it online or verify all test cases (except for the last two, which still time out).

**Explanation:**

```
1µ            # Loop until the counter is 1:
    k         #  Get the indices
   s          #  of the current list of characters (this will be the implicit
              #                                     input in the first iteration)
  A           #  in the lowercase alphabet
     η        #  Get the prefixes of this list
      O       #  And sum each inner prefix-list
       Asè    #  Modular index this list into the lowercase alphabet
          D   #  Duplicate it
           IQ #  Pop the copy, and check if it's equal to the input
              #  (if this is truthy, implicitly increase the counter by 1)
 }N           # After the loop: output the last 0-based index of the loop
              # (after which it is output implicitly as result)

```
> 1 votes

# Answer
# Python, 108 bytes

```
i=s=[ord(c)-65for c in input()];a=0
while a<1or s!=i:s=[sum(s[:j+1])%26for j in range(len(i))];a+=1
print(a)
```

Attempt This Online!

This isn't a very interesting answer.

If only Python wasn't *bad*, we could have this for 105 bytes:

```
lambda s:1+len([*iter(lambda:(t:=([sum(t[:j+1])%26for j in range(len(s))])),(t:=[ord(c)-65for c in s]))])
```

Explanation:

```
lambda s:                      # xxx
[ord(c)-65for c in s]          # convert input string to list of alphabet indeces
(t:=)                          # assign to `t` initially
iter(lambda: ,)                # repeat until t recurs:
            [sum(t[:j+1])%26   # cumulative sums of `t`
      for j in range(len(s))]
           (t:=)               # reassign to `t`
1+len([*])                     # length of repeating segment

```

But in the inner lambda, the list comprehension binds `t` as a free variable to the inner lambda, rather than a free variable to the *outer* lambda. If there was a way to do `nonlocal` in a `lambda`, we could avoid this.

Here's a bit of a hack that does actually work: Attempt This Online!
> 1 votes

# Answer
# Japt v1.4.5, 24 bytes

```
;@=mnB å+ £BgXu26Ã eNg}a

```

Try it Switched to array of characters to save 1

```
;       - 2nd set of predef. Vars
@...}a  - repeat until true
          return number of times
=       - reassign U(input) by
mnB       * index each in ALPHA
å+        * cumulative sum
£Bg       * each: get[ABCD..]
Xu26Ã       at X%26
eNg     -  compare to orignal input

```
> 1 votes

# Answer
# ayr, 14 bytes

Unfortunately can't beat Bubbler's K answer, but it comes close. This is practically a direct translation, except for the fact that `65|` is the same as `_65+` in this specific case. Takes capital input.

```
:#(26|+\)$:65|

```

# Explanation

```
:                    A non J-style train
                65|  Input mod 65
       ( ... )$:     Fixpoint
     +\                Cumulative sum
  26|                  Mod 26
 #                   Size

```
> 1 votes

# Answer
# Haskell, 89 bytes

```
import Data.Char
s!o|t==o=1|True=1+t!o where t=scanl1(\x y->chr$(ord x+ord y)`mod`26+65)s

```

Try it online

(65 * 2 mod 26 conveniently equals 0.)
> 0 votes

# Answer
# TI-Basic, ~~129~~ 131 bytes

```
Input Str1
"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2
Str1
Repeat Ans=Str1
cumSum(seq(inString(Str2,sub(Ans,I,1))-1,I,1,length(Ans
1+remainder(Ans,26→R
J+1→J
sub(Str2,ʟR(1),1
For(I,2,dim(ʟR
Ans+sub(Str2,ʟR(I),1
End
End
J

```

+1 byte if not run on a TI-84+/SE with the 2.53 MP OS by replacing `remainder(Ans,26` with `26fPart(Ans/26`.

Output is stored in `Ans` and displayed.
> 0 votes

# Answer
# Burlesque, 32 bytes

```
m{**65.%}J1{{++26.%}pa}C~[-jFi+.

```

Try it online!

```
m{      # Map each char
 **     # Ord(a)
 65.%   # Mod 65
}       # <-- converted to alphabet index
J       # Duplicate
1       # Prefix Arg to infinite loop
{       #
 {      #
  ++    # Sum
  26.%  # Mod 26
 }      #
 pa     # Partial (applied to each init)
}       #
C~      # Infinite list of function evaluated successively on arg
[-      # Drop first element (original converted string)
j       # Swap in duplicated original
Fi      # Find index of original in list
+.      # Increment by 1 (0 indexed)

```
> 0 votes

# Answer
# Python3, 101 bytes:

```
import itertools as i
s,c=(n:=[ord(j)-65for j in n]),1
while(s:=[j%26for j in i.accumulate(s)])!=n:c+=1

```

If anything, a cleaner and more efficient way to produce the cumulative sums.
> 0 votes

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


title: Fetch the answer from the Internet

text:
# Question
Title: Fetch the answer from the Internet
So, normally, this is a forbidden loophole to fetch the desired output from an external source. But this challenge is an exception ! In this challenge you will **have** to fetch data from the internet and output it to the SDTOUT.

# The task

1. For the purpose of this challenge, you'll be the owner of the imaginary `a.pi` domain!
2. You will need to take the first argument from STDIN, pass it to `a.pi/{arg}`, and print the result to STDOUT.
3. You don't need to handle errors, the server is always up and running !
4. This is a , the winner is the shortest (in bytes or equivalent) valid answer.

# Rules

1. You are allowed to invoke `curl` and `wget` **\[1\]** commands as child/sub-processes (like `child_process` with NodeJS).
2. The ressource at `a.pi` will only be available in the `http` and `https` protocol in their default ports (`80` and `443` respectively), you don't need to include the `http://` if your language allow to ommit it.
3. Only the desired output (http response) should be printed, nothing else (no `GET http://a.pi/:` or whatever).
4. The input might contain spaces or otherwise reserved characters, and need to be **percent-encoded**.
Spaces () should be replaced with `%20` and `%` with `%25` (As spaces **cannot** be in URLs). The other characters (including reserved ones) don't need to be encoded, but you **can** encode them (including unreserved characters) if that makes your code shorter.
5. If your language/environement doesn't have a STDIN/STDOUT (like in a browser), the shortest equivalent can be used (like `prompt()` and `alert()` in javascript).
6. The `CORS` Headers are open for any external requests (`Access-Control-Allow-Origin: *`), if you where wondering.

> **Note:** to test your program, you can use any domain and then replace it with `a.pi` for the submission.

**\[1\]** While it should works the same everywhere, I'd recommend you to precise which OS you used for testing.

# Updates

Rule 4 have been modified as it was the hardest part is the percent-encoding, which is already a submitted code golf, and the exact rules of the encoding where unclear.

> **Note:** this the first code-golf challenge that I submit, and I didn't knew about the sandbox before. In the future, I'll definitely post here before submitting.
> Also, this change doesn't affect previous entries (Except for their length).

# Answer
# 05AB1E, ~~29~~ 20 bytes

```
„ %DÇh'%ì‡"a.pi/"ì.w

```

-9 bytes now that the encoding rule (4) has changed.

Try it online (where `.w` will act as no-op, since it's disabled on TIO).

**Original 29 bytes answer encoding all reserved and non-ASCII characters:**

```
žj“"+-.<>“«мDÇh'%ì‡"a.pi/"ì.w

```

\\$\frac{2}{3}rd\\$ of the program is used to encode the characters (19 bytes to be exact).

Try it online (where `.w` will act as no-op, since it's disabled on TIO).

**Explanation:**

```
„ %                # Push string " %"
   D               # Duplicate this string
    Ç              # Convert it to a list of codepoint integers
     h             # Convert each integer to hexadecimal
      '%ì         '# Prepend a "%" in front of each
         ‡         # Transliterate all characters in the (implicit) input-string
          "a.pi/"ì # Prepend "a.pi/" in front of it
.w                 # Browse this page (with leading "http://" implicitly added) and
                   # read and push its contents
                   # (after which this is output implicitly as result)

žj                 # Push builtin "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
  “"+-.<>“«       "# Append string '"+-.<>'
           м       # Remove all these characters from the (implicit) input-string,
                   # so we're left with all reserved and/or non-ASCII characters
DÇh'%ì‡"a.pi/"ì.w '# Same as above

```
> 2 votes

# Answer
# Javascript (ES6), ~~26~~ 23 bytes

```
x=>fetch('/'+escape(x))

```

Percent encode builtin FTW!!!

Returns a `Promise` containing an object with a `text` method, which when called with no properties returns the result, allowed by this.

Must be run on the `a.pi` domain, allowed by this consensus. Since this is impossible, try running the following in your console, on this site:

```
f=
x=>fetch('/'+escape(x))

f('questions').then(x=>x.text()).then(console.log)

```

(This requests the questions page)
> 2 votes

# Answer
# Perl 5 -nlMv5.10, 50 bytes

```
s/\W/sprintf"%%%02x",ord$&/ge;say`curl -s a.pi/$_`

```

Can't try it online unless you swap the two ``` chars with `"` to output the curl command with it's arguments instead of it's response. Percent-encodes all chars except `a-z`, `A-Z`, `0-9` and `_`.
> 1 votes

# Answer
# PHP, ~~54~~ 47 bytes

```
<?=join(file('http://a.pi/'.urlencode($argn)));

```

Try it online!

Note: TIO does not allow external requests, though it probably doesn't really matter since `a.pi` does not really exist.

-7 bytes thx to @Kaddath!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 77 bytes

-10 bytes thanks to Kevin Cruijssen

```
a=>new System.Net.WebClient().DownloadString("a.pi/"+Uri.EscapeDataString(a))

```

Try it online!

# C# (Visual C# Interactive Compiler), 34 bytes

If you only need to return the URL + encoded query string like in some of the answers.

```
a=>"a.pi/"+Uri.EscapeDataString(a)

```

Try it online!
> 0 votes

# Answer
# Factor \+ `http.client`, 42 bytes

```
[ url-encode "a.pi/"prepend http-get nip ]

```

Try it online!
> 0 votes

# Answer
# GNU AWK, 122 bytes

```
BEGIN{RS=ORS="\r\n";s="/inet/tcp/0/a.pi/80"}1gsub("%","%25")gsub(FS,"%20"){print"GET /"$0|&s;while((s|&getline)>0)print$0}

```

Try it online!

> NO WAY! I didn't know AWK could do that!

```
BEGIN{RS=ORS="\r\n";

```

We start by setting `\r\n`(`CR LF`) as the trailing character of the print function, as the default is only `\n`.

```
s="/inet/tcp/0/a.pi/80"}

```

And then we set the server we want to communicate with.

```
1gsub("%","%25")gsub(FS,"%20")

```

This AWK pattern will always return true, even if there are no spaces or `%` in the input.

```
{print"GET /"$0|&s;while((s|&getline)>0)print$0}

```

The last piece of code `GET`s the domain response until the last line.

For this code to work, make sure to input the wanted `ARG` as in `a.pi/{ARG}`, hit `Enter`, and then `Ctrl`+`D` (or your most favorite ASCII-4-End-of-transmission way of doing it).
> 0 votes

---
Tags: code-golf, internet
---


title: Convert codepoint to UTF-9

text:
# Question
Title: Convert codepoint to UTF-9
UTF-9 was an April Fool's Day RFC joke specifications for encoding Unicode suitable for 9-bit nonet platforms.

# Challenge

Your task is to implement a program or a function or a subroutine that takes one integer, who represents the codepoint of a character, to return a sequence of integers that represents its corresponding UTF-9 value.

## Definition of UTF-9

In this problem, the definition of the UTF-9 shall be as follows:

From section 3 of RFC 4042:

> A UTF-9 stream represents \[ISO-10646\] codepoints using 9 bit nonets. The low order 8-bits of a nonet is an octet, and the high order bit indicates continuation.
>
> UTF-9 does not use surrogates; consequently a UTF-16 value must be transformed into the UCS-4 equivalent, and U+D800 - U+DBFF are never transmitted in UTF-9.
>
> Octets of the \[UNICODE\] codepoint value are then copied into successive UTF-9 nonets, starting with the most-significant non-zero octet. All but the least significant octet have the continuation bit set in the associated nonet.

## Constraints

Input is nonnegative integers that is defined on Unicode: which is 0 to 0x7FFFFFFF (inclusive)

# Rules

* Standard loopholes apply.
* Standard I/O rules apply.
* Shortest code wins.

# Test cases

Leftmost column: Input in hexadecimal.

Right items: output as a sequence of octed integers.

```
0000     000
0041     101
00c0     300
0391     403 221
611b     541 033
10330    401 403 060
e0041    416 400 101
10fffd   420 777 375
345ecf1b 464 536 717 033

```

# ~~Hint~~ Notes

~~Section 5.2 of RFC4042 has an example of the impmenentation.~~

~~Here is a non-competing Python function that represents the algorithm:<br>```
def ucs4utf9(x:int)->[int]:
 l=[]
 if x>0x100:
  if x>0x10000:
   if x>0x1000000:
    l.append(0x100|(x>>24)&0xff)
   l.append(0x100|(x>>16)&0xff)
  l.append(0x100|(x>>8)&0xff)
 l.append(x&0xff)
 return l

```~~

~~Test it online!~~

Those two programs were incorrect, as they convert codepoints 0x100, 0x10000, and 0x1000000 incorrectly; they should be converted to `257,0`, `257,256,0`, `257,256,256,0` respectively.

# Answer
> 3 votes
# 05AB1E (legacy), 7 bytes

```
₁вā€₁¨+

```

Port of *@xigoi*'s Jelly answer.

I/O as integers.

Try it online or verify all test cases.

**Explanation:**

```
₁в       # Convert the (implicit) input-integer to base-256 as list
  ā      # Push a list in the range [1,length] (without popping)
   ¨     # Remove the final item to make the range [1,length)
    €₁   # Map each to 256
         # (we now have a list of 256s of size length-1)
      +  # Add the values at the same positions in the lists together
         # (where the larger list keeps its trailing items as is)
         # (after which this list is output implicitly as result)

```

In the new version of 05AB1E both `€₁` and `+` wouldn't work here. `€₁` will add a `256` before each item instead of replacing them (an alternative could be `Ā₁*`), and `+` will cause the final item to be removed, since it will adjust the list to the shortest. In 05AB1E it therefore requires a different approach, which would be 8 bytes instead:

# 05AB1E, 8 bytes

```
₁в₁+`₁-)

```

Try it online or verify all test cases.

**Explanation:**

```
₁в       # Convert the (implicit) input-integer to base-256 as list
  ₁+     # Add 256 to each
    `    # Pop and dump the contents of the list separated to the stack
     ₁-  # Subtract 256 from the top item (the last item of the dumped list)
       ) # Wrap the entire stack into a list again
         # (after which this list is output implicitly as result)

```

# Answer
> 7 votes
# Jelly, 8 bytes

```
b⁹+⁹_0¦⁹

```

Try it online!

## Explanation

```
b⁹+⁹_0¦⁹
b        Convert to base
 ⁹         256
  +      Add
   ⁹       256
      ¦  At index
     0     last
    _      subtract
       ⁹   256

```

# Answer
> 6 votes
# INTERCAL, ~~164~~ ~~162~~ 154 bytes

I made this program before noticing the first comment of the OP. In my comment section the two example programs on both RFC document and my Python implementation says values 0x100, 0x10000, and 0x1000000 are converted incorrectly, while this program converts 256 to \[257,0\]; which seems to be correct.

```
DOWRITEIN:1DOCOMEFROM.3PLEASE.1<-!2$:1~#255'~#54613DOSTASH.1DO.2<-#128PLEASE:1<-:1~#65520$#65520(1)DO.3<-':1~:1'~#1(9)DORETRIEVE.1DOREADOUT.1PLEASE(9)NEXT

```

Try it online!

## Usage

* Input as INTERCAL-72 integer input (e.g. `ONE TWO THREE FOUR FIVE`).
* Outputs several integers as roman numbers, from first to last elements of the list.

## Ungolfed

```
DOWRITEIN:1

DONOTE from label (1) if .3 got at least one bit of one
DOCOMEFROM.3
DONOTE :1~#255 is done first on CLCI
PLEASENOTE obtain lowest 8 bits
DONOTE then do C operation such twospot[1]|spot[2]
DONOTE spot[2] is 256 if second time to visit here 0 otherwise
PLEASE.1<-!2$:1~#255'~#54613
PLEASENOTE this and RETRIEVE statements below
DOSTASH.1
DO.2<-#128
DONOTE like (twospot[1]>>8)
PLEASE:1<-:1~#65520$#65520
(1)DO.3<-':1~:1'~#1

PLEASENOTE finally, until no more .1 stacks
(9)DORETRIEVE.1
DOREADOUT.1
PLEASE(9)NEXT

```

### Algorithm

1. Write in to the codepoint.
2. Make a list from backward, using STASH and RETRIEVE statements and a stack.
3. Then output each item.

# Answer
> 6 votes
# Python 3, ~~104 103~~ 97 bytes

```
def f(n):b=f'{0:08}{n:b}';l=len(b);return[256*(i<l-8)+int(b[i:i+8],2)for i in range(l%8or 8,l,8)]

```

Try it online!

-1 thanks to Kevin Cruijssen

Explanation:

* The program converts the number to binary and left-pads it with 8 zeroes
* It takes each full chunk of 8 bytes (discarding additional zeroes at the start)
* The chunk is converted from a binary string to an int. 256 is added if it isn't the last chunk.

# Answer
> 5 votes
# JavaScript (ES6), 41 bytes

If returning an empty array for \\$n=0\\$ is not acceptable, this version returns `[0]` instead. Thanks to @tsh for pointing this out.

```
f=(n,q)=>n|!q?[...f(n>>8,256),n%256|q]:[]

```

Try it online!

---

# JavaScript (ES6), 38 bytes

```
f=(n,q)=>n?[...f(n>>8,256),n%256|q]:[]

```

Try it online!

# Answer
> 5 votes
# , 51 bytes

```
f=function(x,s=0,b=256)c(if(x>=b)f(x%/%b,b),x%%b+s)

```

Try it online!

# Answer
> 4 votes
# Python 3.8, 81 bytes

```
def f(n):x=n.to_bytes(4,'big');return[i+256 for i in x.lstrip(b'\0')[:-1]]+[x[-1]]

```

# Answer
> 3 votes
# Charcoal, 20 bytes

```
Ｉ⮌Ｅ⮌∨↨Ｎ²⁵⁶⟦⁰⟧⁺ι∧κ²⁵⁶

```

Try it online! Link is to verbose version of code. I/O is in decimal. Would have been 16 bytes if empty output was acceptable for an input of `0`. Explanation:

```
      Ｎ                 Input as an integer
     ↨ ²⁵⁶              Converted to base 256 as a list
    ∨                   Logical Or
          ⟦⁰⟧           List of literal `0`
   ⮌                    Reversed i.e. LSB first
  Ｅ                     Map over bytes
              ι         Current byte
             ⁺          Plus
                κ       Current index
               ∧        Logical And
                 ²⁵⁶    Literal 256
 ⮌                      Reversed i.e. MSB first again
Ｉ                       Cast to string
                        Implicitly print

```

Converting to groups of 8 bits also takes 20 bytes:

```
Ｉ⮌Ｅ⪪⮌⍘Ｎ²¦⁸⁺⍘⮌ι²∧κ²⁵⁶

```

Try it online! Link is to verbose version of code. I/O is in decimal. Explanation:

```
      Ｎ                 Input as an integer
     ⍘ ²                Converted to base 2 as a string
    ⮌                   Reversed i.e. LSB first
   ⪪     ⁸              Split into groups of up to 8 bits
  Ｅ                     Map over bytes
             ι          Current byte
            ⮌           Reversed i.e. MSB first again
           ⍘  ²         Converted from base 2
          ⁺             Plus
                κ       Current index
               ∧        Logical And
                 ²⁵⁶    Literal 256
 ⮌                      Reversed
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 3 votes
# Retina 0.8.2, 71 bytes

```
.+
$*
+`(1+)\1
$+0
01
1
^
7$*0
r`.{8}
¶$&
1A`
.+¶
1$&
1
01
+`10
011
%`1

```

Try it online! Link includes test suite. I/O is in decimal. Explanation:

```
.+
$*

```

Convert to unary.

```
+`(1+)\1
$+0
01
1

```

Convert to binary.

```
^
7$*0
r`.{8}
¶$&
1A`

```

Split into bytes of 8 bits.

```
.+¶
1$&

```

Prefix a `1` to all bytes except the last.

```
1
01
+`10
011

```

Convert to unary.

```
%`1

```

Convert to decimal.

# Answer
> 2 votes
# Ruby, ~~62~~ 42 bytes

```
f=->n,w=0{w+=n%z=256;n<z ?[w]:f[n/z,z]<<w}

```

Try it online!

# Answer
> 1 votes
## Perl 5, 59 bytes

```
sub{my@o;do{unshift@o,$_[0]%256|256*!!@o}while$_[0]>>=8;@o}

```
* `do`-`while` loop to make sure that 0 outputs `(0)` and not `()`
* `unshift` pushes onto the array backwards
* `!!@o` is 0 if the output is empty (this will be the last nonet) or 1 otherwise
* consumes its input
* could lose `my@o;` for -5 points under the old-school Perl golf rules.

TIO.

# Answer
> 1 votes
# Rust, 93 bytes

```
|n|(0..4).rev().map(|i|n>>i*8&255|(i>0)as i32*256).skip_while(|&n|n==256).collect::<Vec<_>>()

```

Try it online!

### Ungolfed

```
|n| {
    (0..4).rev()                 // Iterator over integers from 3 down to 0
    .map(|i|
        (n >> i*8) & 255         // Extract the i'th octet from n
        | ((i > 0) as i32) * 256 // Set the continuation bit if not the last byte
    )
    .skip_while(|&n| n == 256)   // Remove 0x100 bytes at the start
    .collect::<Vec<_>>()         // Evaluate into a vector
}

```

---
Tags: code-golf, unicode
---


title: Convert codepoint to UTF-1

text:
# Question
Title: Convert codepoint to UTF-1
UTF-1 is one of the methods to transform ISO/IEC 10646 and Unicode into a sequence of bytes. It was originally for ISO 10646.

The UTF-1 encodes every character with variable length of byte sequence, just like UTF-8 does. It was designed to avoid control codes. But it was not designed to avoid duplication of a slash character ('/'), which is path delimiter for many operating systems. Additionally it takes a bit long to process the algorithm, because it is based on modulo 190, which is not power of two. Eventually UTF-8 was better than that.

In this challenge we are reviving UTF-1.

# How it works

Every constant value in tables on this section is represented in hexadecimal value.

The symbol / is the integer division operator, % is the integer modulo operator, and ^ means power. The precedence of operators is ^ first, / second, % third, and others last. Here is how to convert each codepoint to UTF-1 (sorry for typo last time):

| codepoint x | UTF-1 |
| --- | --- |
| U+0000 to U+009F | (x) |
| U+00A0 to U+00FF | (A0,x) |
| U+0100 to U+4015 | y=x-100 in (A1+y/BE,T(y%BE)) |
| U+4016 to U+38E2D | y=x-4016 in (F6+y/BE^2,T(y/BE%BE),T(y%BE)) |
| U+38E2E to U+7FFFFFFF | y=x-38E2E in (FC+y/BE^4,T(y/BE^3%BE),T(y/BE^2%BE),T(y/BE%BE),T(y%BE)) |

T(z) is a function such that:

| z | T(z) |
| --- | --- |
| 0 to 5D | z+21 |
| 5E to BD | z+42 |
| BE to DE | z-BE |
| DF to FF | z-60 |

# Challenge

Your task is to implement a program or a function or a subroutine that takes one integer, who represents the codepoint of a character, to return a sequence of integers that represents its corresponding UTF-1 value.

# Constraints

Input shall be an nonnegative integer up to 0x7FFFFFFF.

# Rules

* Standard loopholes apply.
* Standard I/O rules apply.
* Shortest code wins.

# Test cases

Taken from the Wikipedia article.

```
    U+007F  7F
    U+0080  80
    U+009F  9F
    U+00A0  A0 A0
    U+00BF  A0 BF
    U+00C0  A0 C0
    U+00FF  A0 FF
    U+0100  A1 21
    U+015D  A1 7E
    U+015E  A1 A0
    U+01BD  A1 FF
    U+01BE  A2 21
    U+07FF  AA 72
    U+0800  AA 73
    U+0FFF  B5 48
    U+1000  B5 49
    U+4015  F5 FF
    U+4016  F6 21 21
    U+D7FF  F7 2F C3
    U+E000  F7 3A 79
    U+F8FF  F7 5C 3C
    U+FDD0  F7 62 BA
    U+FDEF  F7 62 D9
    U+FEFF  F7 64 4C
    U+FFFD  F7 65 AD
    U+FFFE  F7 65 AE
    U+FFFF  F7 65 AF
   U+10000  F7 65 B0
   U+38E2D  FB FF FF
   U+38E2E  FC 21 21 21 21
   U+FFFFF  FC 21 37 B2 7A
  U+100000  FC 21 37 B2 7B
  U+10FFFF  FC 21 39 6E 6C
U+7FFFFFFF  FD BD 2B B9 40

```

# Answer
> 4 votes
# Python 3, <sup>~~289~~ ~~262~~ ~~241~~ ~~240~~ ~~232~~</sup> 230 bytes

```
lambda n:[p(*[[n-d,4,252],[n-16406,2,246],[n-256,1,161]][(n<16406)+(n<d)]),[160]*(n>159)+[n]][n<256]
c=190
d=233006
t=lambda n:n+[-96,-c,66,33][(n<94)+(n<c)+(n<223)]
p=lambda y,x,z:[z+y//c**x]+[t(y//c**i%c)for i in range(x)][::-1]

```

Try it online!

*-27 bytes cos my implementation of T was wrong*
*-21 bytes thanks to @wasif's implementation of f, which works on t too*
*-1 byte thanks to storing 233006 in a variable*
*-8 bytes thanks to @pxeger in TNB*
*-2 bytes thanks to unneeded parens*

It's a naive approach, and I'm sure there's lots of room for golfing, but it works!

# Python 3.8, 210 bytes

```
lambda n:[[(y:=n-[d:=233006,e:=16406,256][j:=(n<e)+(n<d)])//c**(x:=[4,2,1][j])+(z:=[252,246,161][j])]+[(g:=y//c**i%c)+[-96,-c,66,33][(g<94)+(g<c)+(g<223)]for i in range(x)][::-1],[160]*(n>159)+[n]][n<256]
c=190

```

Attempt This Online!

Same as the Python 3 answer, but uses 3.8's `:=` operator to cram it all into 1 lambda

## Explanation

The lambda `t` is equivalent to the `T()` defined in the challenge.

The lambda `p` takes 3 integers, `y`, `x`, and `z`, and creates:

```
[z+y/190^x, t(y/190^(x-1)%190), t(y/190^(x-2)%190)...t(y/190^0%190)]

```

We only use `x` as `1`, `2`, or `4`, depending on which formula we're handling:

```
(y = n-256, x = 1, z = 161):
    [161+y/190, t(y%190)]
(y = n-16406, x = 2, z = 246):
    [246+y/190^2, t(y/190%190), t(y%190)]
(y = n-233006, x = 4, z = 252):
    [252+y/190^4, t(y/190^3%190), t(y/190^2%190), t(y/190%190), t(y%190)]

```

Finally the lambda `f` handles the 5 formulas and their ranges for input `n`:

```
def f(n):
    if n < 160: return [n]
    if n < 256: return [160, n]
    if n < 16406: return p(n-256, 1, 161)    #first formula
    if n < 233006: return p(n-16406, 2, 246) #second formula
    return p(n-233006, 4, 252)               #third formula

```

# Answer
> 3 votes
# Burlesque, 270 bytes

```
190s1256s216406s7233006s8{g1./}s9%t={g1.%J{{33.+}{66.+}{g1.-}{g6.-}}{94g1223g2}(.<)bcz[{}Z]cne!}J{qbx{40960.+bx}{g2.-{{g9e!161.+}q%t!}M-}{g7.-{{g92E!246.+}{g9e!%t!}q%t!}M-}{g8.-{{g94E!252.+}{g93E!%t!}{g92E!%t!}{g9e!%t!}q%t!}M-}}{160g2g7g82147483648}(.<)bcz[{}Z]cne!qb6\m

```

Try it online!

Pretty sure this can be golfed further/better, but this is already pretty terrifying. Main changes vs. ungolfed are using zips to build the conditional blocks.

```
190s1                       # Store 190
256s2                       # Store 256
16406s7                     # Store 16406
233006s8                    # Store 233006
{g1./}s9                    # Store divide by 190
%t={                        # Assign T
 g1.%                       # Mod 190
 J                          # Duplicate (conditional is destructive)
 {
  {94.<}{33.+}              # <94 add 33 (0x21)
  {g1.<}{66.+}              # <190 add 66 (0x42)
  {223.<}{g1.-}             # <223 sub 190 (0xBE)
  {g2.<}{96.-}              # <256 sub 96 (0x60)
 }
  cne!}                     # Conditional evualuate resulting block
            # END T
J                           # Duplicate (conditional is destructive)
{{160.<}        qbx         # <160 Put in box
 {g2.<}         {40960.+bx} # <256 add 40960 (0xA000) and box
 {g7.<}         {           # <16406 (0x4016)
        g2.-       # Sub 256
        {
         {
          g9e!     # Divide by 190
          161.+    # Add 161
         }
         q%t!      # Apply T
        }M-}       # Cool map (create copy for each block and
 {g8.<}         {  # eval and return list of each result)
        g7.-       # Sub 16406
        {
         {
          g92E!    # Divide by 190 twice
          246.+    # Add 246
         }
         {
          g9e!%t!  # Divide by 190 apply T
         }
         q%t!      # Apply T
        }M-}
 {2147483648.<} {           # < 2147483648
        g8.-       # Sub 233006
        {
         {
          g94E!    # Divide by 190 4x
          252.+    # Add 252
         }
         {
          g93E!%t! # Divide by 190 3x
         } #2x       1x       0x
         {g92E!%t!}{g9e!%t!}q%t!}
        M-}
       }
}cne!              # Evaluate the conditional
qb6\m              # Map to hex and concatenate

```

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

Expects the input as a string. Returns a comma-separated string of bytes.

```
x=>(v=190,p=16406,q=233006,g=(o,n,d,k=1,y=(x-o)/k%v|0)=>--n?g(o,n,d,k*v)+[,y+=y<94?33:y<v?66:y<223?-v:-96]:160-~d+y,x<160?x:x>>8?x<p?g(256,2):x<q?g(p,3,85):g(q,5,91):160+[,x])

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 138 bytes

```
f=x=>x<160?[x]:x>>8?(g=y=>++l<5?[...g(y/190|0),(y%=190)-33*~(y>93)]:[f(n)[0]-~y])(x+~[233005,,16405,255].find((m,j)=>(l=j,n=m)<x)):[160,x]

```

Try it online!

# Answer
> 1 votes
# Charcoal, 99 bytes

```
Ｉ⎇›¹⁶⁰θθ⎇›²⁵⁶θ⟦¹⁶⁰θ⟧Ｅ↨⁺θ⎇›¹⁶⁴⁰⁶θ¹²⁴⎇›²³³⁰⁰⁶θ³¹²⁴²⁹⁴Ｉ”)¶∧‴+νＯ﹪”¹⁹⁰⁺ι⎇κ⎇‹¹⁸⁹ι⎇‹²²²ι±⁹⁶±¹⁹⁰×³³⊕‹⁹³ι¹⁵⁹

```

Try it online! Link is to verbose version of code. Explanation:

```
   ¹⁶⁰                                                      Literal integer 160
  ›                                                         Is greater than
    θ                                                       Input integer
 ⎇                                                          If true then
     θ                                                      Input integer
 ⎇                                                          Else
        ²⁵⁶                                                 Literal 256
       ›                                                    Is greater than
         θ                                                  Input integer
      ⎇                                                     If true then
          ⟦  ⟧                                              List of
           ¹⁶⁰                                              Literal integer 160
            θ                                               Input integer
      ⎇                                                     Else
                 θ                                          Input integer
                ⁺                                           Plus
                    ¹⁶⁴⁰⁶                                   Literal integer 16406
                   ›                                        Is greater than
                     θ                                      Input integer
                  ⎇                                         If true then
                      ¹²⁴                                   Literal integer 124
                  ⎇                                         Else
                         ²³³⁰⁰⁶                             Literal integer 233006
                        ›                                   Is greater than
                          θ                                 Input integer
                       ⎇                                    If true then
                           ³¹²⁴²⁹⁴                          Literal integer 3124294
                       ⎇                                    Else
                             ”)¶∧‴+νＯ﹪”                     Compressed string "121198296994"
                            Ｉ                               Cast to integer
               ↨                                            Convert to base
                              ¹⁹⁰                           Literal integer 190
              Ｅ                                             Map over base 190 digits
                                ι                           Current value
                               ⁺                            Plus
                                  κ                         Current index
                                 ⎇                          If not first digit then
                                     ¹⁸⁹                    Literal integer 189
                                    ‹                       Is less than
                                      ι                     Current value
                                   ⎇                        If true then
                                         ²²²                Literal integer 222
                                        ‹                   Is less than
                                          ι                 Current value
                                       ⎇                    If true then
                                            ⁹⁶              Literal integer 96
                                       ⎇                    Else
                                           ±                Negated
                                              ¹⁹⁰           Literal integer 190
                                             ±              Negated
                                   ⎇                        Else
                                                ³³          Literal 33
                                               ×            Times
                                                   ⁹³       Literal 93
                                                  ‹         Is less than
                                                    ι       Current value
                                                 ⊕          Incremented
                                 ⎇                          If first digit then
                                                     ¹⁵⁹    Literal integer 159
Ｉ                                                           Cast to string
                                                            Implicitly print

```

# Answer
> 1 votes
# Haskell, 234 bytes

```
t z|z<94=33+z|z<130=z+66|z<223=z-190|0<1=z-96
u x|x<256=[160|x>159]++[x]|1>0=let[b,c,d]=head$dropWhile((x<).head)[[233005,5,252],[16406,3,246],[256,2,161]];w=reverse.take c.map(`mod`190).iterate(`div`190)$x-b in d+head w:map t(tail w)

```

Try it online!

# Answer
> 1 votes
# Rust, 250 bytes

```
|n|{let t=|i,b,z|if i<2{b+z}else{z%190+33+(z%190>93)as i32*33};let g=|b,y,p|(1..=p).map(|i|t(i,b,y/190i32.pow(p-i))).collect();match n{0..=159=>vec![n],0..=255=>vec![160,n],0..=16405=>g(161,n-256,2),0..=233005=>g(246,n-16406,3),_=>g(252,n-233006,5)}}

```

Try it online!

### Ungolfed

```
|n| {
    // Modified T: Returns T(Z%0xBE) if i > 1 else B+Z
    let t = |i, b, z|
        if i < 2 {
            b+z
        } else {
            z % 0xBE + 0x21 + if (z % 0xBE) > 0x5D { 0x21 } else { 0 }
        };

    // Helper: Generates the p UTF-1 bytes for codepoints > U+FF
    let g = |b, y, p|
        (1..=p).map(
            |i| t(i, b, y / 190_i32.pow(p-i))
        ).collect();

    // Select encoding variant
    match n{
        0..=159    => vec![n],
        0..=255    => vec![0xA0, n],
        0..=16405  => g(0xA1, n - 0x100,   2),
        0..=233005 => g(0xF6, n - 0x4016,  3),
        _          => g(0xFC, n - 0x38E2E, 5)
    }
}

```

---
Tags: code-golf, unicode
---


title: Make a !!!Batch compiler/translator

text:
# Question
Title: Make a !!!Batch compiler/translator
!!!Batch is another derivative of the Windows Batch programming language, its wiki is here

Your challenge is to create an compiler/translator that reads a !!!Batch program and returns a Windows Batch program.

In !!!Batch each token braced in two question marks like `?!!!?` is converted to another ASCII character, like '?!?' -\> 'a' and so on below, and after decoding the whole !!!Batch program it is a Windows batch program

```
'?!?', 'a'
'?!!?', 'b'
'?!!!?', 'c'
'?!!!!?', 'd'
'?!!!!!?', 'e'
'?!!!!!!?', 'f'
'?!!!!!!!?', 'g'
'?!!!!!!!!?', 'h'
'?!!!!!!!!!?', 'i'
'?!!!!!!!!!!?', 'j'
'?!!!!!!!!!!!?', 'k'
'?!!!!!!!!!!!!?', 'l'
'?!!!!!!!!!!!!!?', 'm'
'?!!!!!!!!!!!!!!?', 'n'
'?!!!!!!!!!!!!!!!?', 'o'
'?!!!!!!!!!!!!!!!!?', 'p'
'?!!!!!!!!!!!!!!!!!?', 'q'
'?!!!!!!!!!!!!!!!!!!?', 'r'
'?!!!!!!!!!!!!!!!!!!!?', 's'
'?!!!!!!!!!!!!!!!!!!!!?', 't'
'?!!!!!!!!!!!!!!!!!!!!!?', 'u'
'?!!!!!!!!!!!!!!!!!!!!!!?', 'v'
'?!!!!!!!!!!!!!!!!!!!!!!!?', 'w'
'?!!!!!!!!!!!!!!!!!!!!!!!!?', 'x'
'?!!!!!!!!!!!!!!!!!!!!!!!!!?', 'y'
'?!!!!!!!!!!!!!!!!!!!!!!!!!!?', 'z'
'?!-?', '&'
'?!!-?', ' '
'?!!!-?', '?'
'?!!!!-?', '!'
'?!!!!!-?', '%'
'?!!!!!!-?', '/'
'?!!!!!!!-?', '.'
'?!!!!!!!!-?', ':'
'?!!!!!!!!!-?', '0'
'?!!!!!!!!!!-?', '1'
'?!!!!!!!!!!!-?', '2'
'?!!!!!!!!!!!!-?', '3'
'?!!!!!!!!!!!!!-?', '4'
'?!!!!!!!!!!!!!!-?', '5'
'?!!!!!!!!!!!!!!!-?', '6'
'?!!!!!!!!!!!!!!!!-?', '7'
'?!!!!!!!!!!!!!!!!!-?', '8'
'?!!!!!!!!!!!!!!!!!!-?', '9'
'?!!!!!!!!!!!!!!!!!!!-?', '='
'?!!!!!!!!!!!!!!!!!!!!-?', '+'
'?!!!!!!!!!!!!!!!!!!!!!-?', '-'
'?!!!!!!!!!!!!!!!!!!!!!!-?', '<'
'?!!!!!!!!!!!!!!!!!!!!!!!-?', '>'
'?!!!!!!!!!!!!!!!!!!!!!!!!-?', '@'
'?!!!!!!!!!!!!!!!!!!!!!!!!!-?', '*'
'?!+?', 'A'
'?!!+?', 'B'
'?!!!+?', 'C'
'?!!!!+?', 'D'
'?!!!!!+?', 'E'
'?!!!!!!+?', 'F'
'?!!!!!!!+?', 'G'
'?!!!!!!!!+?', 'H'
'?!!!!!!!!!+?', 'I'
'?!!!!!!!!!!+?', 'J'
'?!!!!!!!!!!!+?', 'K'
'?!!!!!!!!!!!!+?', 'L'
'?!!!!!!!!!!!!!+?', 'M'
'?!!!!!!!!!!!!!!+?', 'N'
'?!!!!!!!!!!!!!!!+?', 'O'
'?!!!!!!!!!!!!!!!!+?', 'P'
'?!!!!!!!!!!!!!!!!!+?', 'Q'
'?!!!!!!!!!!!!!!!!!!+?', 'R'
'?!!!!!!!!!!!!!!!!!!!+?', 'S'
'?!!!!!!!!!!!!!!!!!!!!+?', 'T'
'?!!!!!!!!!!!!!!!!!!!!!+?', 'U'
'?!!!!!!!!!!!!!!!!!!!!!!+?', 'V'
'?!!!!!!!!!!!!!!!!!!!!!!!+?', 'W'
'?!!!!!!!!!!!!!!!!!!!!!!!!+?', 'X'
'?!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Y'
'?!!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Z'

```

Example Input:

```
?!!!!!!!!!!!!!!!!??!!!!!!!!!??!!!!!!!!!!!!!!??!!!!!!!??!!-??!!!!!!!??!!!!!!!!!!!!!!!??!!!!!!!!!!!!!!!??!!!!!!!??!!!!!!!!!!!!??!!!!!??!!!!!!!-??!!!??!!!!!!!!!!!!!!!??!!!!!!!!!!!!!?

```

Example output:

```
ping google.com

```

\**How the output?

First break down into parts:

```
?!!!!!!!!!!!!!!!!? -> 'p'
?!!!!!!!!!? - 'i'

```

and so on

* For more clarification, please visit the Wiki or ask me here.
* Standard loopholes apply
* This is , shortest code wins

An un-golfed sample compiler in python 2, from the Wiki page

> ```
> s = open(raw_input("Run Script: "), 'r').read()
> s = s.replace('?!?', 'a')
> s = s.replace('?!!?', 'b')
> s = s.replace('?!!!?', 'c')
> s = s.replace('?!!!!?', 'd')
> s = s.replace('?!!!!!?', 'e')
> s = s.replace('?!!!!!!?', 'f')
> s = s.replace('?!!!!!!!?', 'g')
> s = s.replace('?!!!!!!!!?', 'h')
> s = s.replace('?!!!!!!!!!?', 'i')
> s = s.replace('?!!!!!!!!!!?', 'j')
> s = s.replace('?!!!!!!!!!!!?', 'k')
> s = s.replace('?!!!!!!!!!!!!?', 'l')
> s = s.replace('?!!!!!!!!!!!!!?', 'm')
> s = s.replace('?!!!!!!!!!!!!!!?', 'n')
> s = s.replace('?!!!!!!!!!!!!!!!?', 'o')
> s = s.replace('?!!!!!!!!!!!!!!!!?', 'p')
> s = s.replace('?!!!!!!!!!!!!!!!!!?', 'q')
> s = s.replace('?!!!!!!!!!!!!!!!!!!?', 'r')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!?', 's')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!?', 't')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!?', 'u')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!?', 'v')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!?', 'w')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!?', 'x')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!?', 'y')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!!?', 'z')
> s = s.replace('?!-?', '&')
> s = s.replace('?!!-?', ' ')
> s = s.replace('?!!!-?', '?')
> s = s.replace('?!!!!-?', '!')
> s = s.replace('?!!!!!-?', '%')
> s = s.replace('?!!!!!!-?', '/')
> s = s.replace('?!!!!!!!-?', '.')
> s = s.replace('?!!!!!!!!-?', ':')
> s = s.replace('?!!!!!!!!!-?', '0')
> s = s.replace('?!!!!!!!!!!-?', '1')
> s = s.replace('?!!!!!!!!!!!-?', '2')
> s = s.replace('?!!!!!!!!!!!!-?', '3')
> s = s.replace('?!!!!!!!!!!!!!-?', '4')
> s = s.replace('?!!!!!!!!!!!!!!-?', '5')
> s = s.replace('?!!!!!!!!!!!!!!!-?', '6')
> s = s.replace('?!!!!!!!!!!!!!!!!-?', '7')
> s = s.replace('?!!!!!!!!!!!!!!!!!-?', '8')
> s = s.replace('?!!!!!!!!!!!!!!!!!!-?', '9')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!-?', '=')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!-?', '+')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!-?', '-')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!-?', '<')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!-?', '>')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!-?', '@')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!-?', '*')
> s = s.replace('?!+?', 'A')
> s = s.replace('?!!+?', 'B')
> s = s.replace('?!!!+?', 'C')
> s = s.replace('?!!!!+?', 'D')
> s = s.replace('?!!!!!+?', 'E')
> s = s.replace('?!!!!!!+?', 'F')
> s = s.replace('?!!!!!!!+?', 'G')
> s = s.replace('?!!!!!!!!+?', 'H')
> s = s.replace('?!!!!!!!!!+?', 'I')
> s = s.replace('?!!!!!!!!!!+?', 'J')
> s = s.replace('?!!!!!!!!!!!+?', 'K')
> s = s.replace('?!!!!!!!!!!!!+?', 'L')
> s = s.replace('?!!!!!!!!!!!!!+?', 'M')
> s = s.replace('?!!!!!!!!!!!!!!+?', 'N')
> s = s.replace('?!!!!!!!!!!!!!!!+?', 'O')
> s = s.replace('?!!!!!!!!!!!!!!!!+?', 'P')
> s = s.replace('?!!!!!!!!!!!!!!!!!+?', 'Q')
> s = s.replace('?!!!!!!!!!!!!!!!!!!+?', 'R')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!+?', 'S')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!+?', 'T')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!+?', 'U')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!+?', 'V')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!+?', 'W')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!+?', 'X')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Y')
> s = s.replace('?!!!!!!!!!!!!!!!!!!!!!!!!!!+?', 'Z')
> print s
>
> ```

# Answer
# JavaScript, 118 bytes

```
s=>s.replace(/.+?\?/g,x=>x[i=x.length-2]>','?'& ?!%/.:0123456789=+-<>@*'[i-2]:String.fromCharCode(x[i]<'+'?96+i:63+i))

```

Try it online!

---

# JavaScript, 118 bytes

```
s=>s.replace(/.!+(.??)\?/g,(x,y)=>(i=x.length,y>','?'& ?!%/.:0123456789=+-<>@*'[i-4]:String.fromCharCode(61+i+33*!y)))

```

Try it online!

Quite trivial answer.

---

Thanks to Arnauld, changing `String.fromCharCode(n)` into `Buffer([n])` under Node.js environment may save 11 bytes and results 107 bytes.
> 5 votes

# Answer
# 05AB1E, 41 bytes

```
¬¡õKεθ„!+skADužh"& ?!%/.:ÿ=+-<>@*")ćèyć¢è

```

Output as a list of characters.

Try it online (the footer is to join the resulting list to pretty-print as string; feel free to remove it to see the actual list output).

**Explanation:**

```
¬             # Push the first character of the (implicit) input-string: "?"
 ¡            # Split the input on that character
  õK          # Remove all empty strings
    ε         # Map over each string:
     θ        #  Pop and push its last character
      „!+     #  Push string "!+"
         sk   #  Get the index of the last character in this string,
              #  (-1 if not found, for the "-")
     A        #  Push the lowercase alphabet
      Du      #  Create an uppercase copy
        žh    #  Push builtin "0123456789"
          "& ?!%/.:ÿ=+-<>@*"
              #  Push this string, where the `ÿ` is automatically filled with 0123456789
     )        #  Wrap all values into a list
      ć       #  Extract head; pop and push remainder-list and first item separated
       è      #  Use this index to (0-based modulair) index into the triplet
              #  (where the -1 for "-" will index into the last item)
        y     #  Push the current string again
         ć    #  Extract its head as well: "!"
          ¢   #  Count how many times it occurs in the remainder-string
           è  #  0-based index this into the string
              # (after the map, the resulting list of characters is output implicitly)

```

Unfortunately the `"& ?!%/.:0123456789=+-<>@*"` is a bit too irregular to compress. The shortest alternative I could find for this straight-forward string was `žQ33£S•1δÁεöI‡β₆¡ÙÞ‹f31•.I` (`žQ` push printable ASCII builtin; `33£` leave just its first 33 characters; `S` convert it from a string to a list of characters; `•1δÁεöI‡β₆¡ÙÞ‹f30•.I` get the 1586478393328926104294588200482791040th permutation of this list), which is 6 bytes longer.
> 4 votes

# Answer
# Stax, ~~53~~ 46 bytes

```
é♫▼V0⌂Ä╟ì⌡(Φzf■£┘╔╣T╘K*╪☻w²¥íÑ╧zv-¼Ö╨◘P♦ε♦íäq*

```

Run and debug it

I wasn't able to find an expression that matches the symbols, so those are hardcoded (and take a lot of space.)

## Explanation

`'?/{f{%_rh.-+I{"@*& ?!%/.:"Vd+"=+-<>"+@}{63+}{96+}3l@!m`

`'?/` split on `?`

`{f` remove empty lists

`{..m` map the strings to:

`%` push the length of the match

`_` push the match again

`rDh` get the second to last character

`.-+I` index of that in "-+"

`@!` execute the corresponding block for the index:

`{"<>@*& ?!%/.:"Vd+"=+-"+@}{61+}{94+}3l` create a list of 3 blocks

`{63+}` for `+`, add 63 to the length

`{"@*& ?!%/.:"Vd+"=+-<>"+@}` for `-`, index into `<>@*& ?!%/.:0123456789=+-` using the length(modular)

`{96+}` otherwise add 91
> 3 votes

# Answer
# C (gcc), ~~142~~ ~~139~~ ~~130~~ 115 bytes

Thanks to tsh for the -3 and gastropher for the -9.

The function uses a state machine to determine the boundaries of each token:

* loop: load the next input character until the end of the string
* state 0 (initial `?`): clear the counter, then go to state 1
* state 1 (`!`, `+`, `-` or terminating `?`): increment on a `!`, otherwise print the character (adjusted count by 96 \[`?`\] or 64 \[`+`\], or indexed symbol \[`-`\]) and go to state 0, incrementing the input string if a `+` or `-`.

```
t,c,n;f(char*s){for(;c=*s++;)n=t?c-33?t=!putchar(c-63?s++,c-43?" & ?!%/.:0123456789=+-<>@*"[n]:n+64:n+96):n+1:t++;}

```

Try it online!
> 3 votes

# Answer
# Retina 0.8.2, ~~94~~ 94 bytes

```
\?!
!
!\?
a
!\+\?
A
-

!{5}\?
%
+T`_o`lL%/.:d=+\-<>@*!_`!(?![?!]).
!\?
$& &
!(?=..(.))!*...
$1

```

Try it online! Edit: +1 byte to fix a bug but -1 thanks to @tsh. Explanation:

```
\?!
!

```

Remove the `?` at the start of a token.

```
!\?
a

```

`?!?`, which is now `!?`, translates to `a`.

```
!\+\?
A

```

`?!+?`, which is now `!+?`, translates to `A`.

```
-

```

Get rid of the `-`s.

```
!{5}\?
%

```

`?!!!!!-?`, which is now `!!!!!?`, translates to `%`.

```
+T`_o`lL%/.:d=+\-<>@*!_`!(?![?!]).

```

For each additional `!`, cycle the following character; letters get incremented, while `d` represents digits which nestle among the symbols.

```
!\?
$& &

```

The remaining `!?`s represent one of `!`, `?`,  and `&` in reverse order, depending on the number of preceding `!`s. Add the other characters so that the correct decode can be selected.

```
!(?=..(.))!*...
$1

```

Decode the remaining `!?`, `!!?`, `!!!?` and `!!!!?` sequences appropriately.
> 3 votes

# Answer
# Julia, ~~108~~ ~~104~~ 102 bytes

-4 bytes thanks to tsh's better regex

```
s->replace(s,r".+?\?"=>x->(a='.'-x[(l=end)-1];["_& ?!%/.:0123456789=+-<>@*_"[l-2],l+'^',l+'='][a%11]))

```

Try it online!
> 3 votes

# Answer
# Perl 5 `-n`, ~~96~~ ~~84~~ 83 bytes

```
say map/-/?substr'  & ?!%/.:0123456789=+-<>@*',y///c,1:chr/!$/*32+64+y///c,/[^?]+/g

```

Try it online!
> 3 votes

# Answer
# Batch ~~1139~~ ~~1034~~ ~~1009~~ 975 bytes.

*Ouch!* Though I couldn't resist making a batch !!!batch translator.

```
@Echo off&Set $=Set &Set _=%*
%$%_=%_:??=? ?%
%$%"_=%_:!=^!%"&%$%".=!!!!"
%$%"..=%.%%.%"
%$%"...=%..%%..%"
%$%?!-?=^&&%$%"?!!-?= "&%$%?!!!-?=?&%$%"?%.%-?=^!"&%$%"?%.%!-?=%%"&%$%?%.%!!-?=/
%$%?%.%!!!-?=.&%$%?%..%-?=:&%$%?%..%!-?=0&%$%?%..%!!-?=1&%$%?%..%!!!-?=2&%$%?%..%%.%-?=3
%$%?%..%%.%!-?=4&%$%?%..%%.%!!-?=5&%$%?%..%%.%!!!-?=6&%$%?%...%-?=7&%$%?%...%!-?=8
%$%?%...%!!-?=9&%$%?%...%!!!-?==&%$%?%...%%.%-?=+&%$%?%...%%.%!-?=-&%$%?%...%%.%!!-?=^<
%$%?%...%%.%!!!-?=^>&%$%?%...%%..%-?=@&%$%?%...%%..%!-?=*&Setlocal EnableDelayedExpansion
%$%e=&For /l %%i in (97 1 122)Do (%$%"e=!e!^!"&Cmd/cExit %%i
%$%"?!e!?=!=ExitCodeASCII!"&For /f delims^= %%v in ('cmd/c%$%/A%%i-32')DO Cmd/cExit %%v
%$%"?!e!+?=!=ExitCodeASCII!")
%$%#=&%$%p=%%&%$%i=0&%$%"T[0]=%_: ="&Set/Ai+=1&Set "T[!i!]=%"
For /l %%i in (0 1 !i!)Do For /f "tokens=1 delims==" %%v in ('%$%T[%%i]')Do (IF defined # (Call %$%"#=!#:^^=^!!p!!%%~v!!p!")Else Call %$%"#=!p!!%%~v:^^=^!!p!")
Echo(!#:^^=!&Endlocal

```

How:

* assigns each command token as a variable with it's respective character.
* Split input on ??, assign each to a token array - T\[#\]
* Iterates through the array of command tokens, expands each to its value (character) and appends to the command line variable #

Notes:

* run from the command line, input is as taken as a command line argument.
* requires delayed expansion to be disable (default)
> 3 votes

# Answer
# Python 2, ~~191 161~~ 133 bytes

-30 Thanks Kaddath! -28 Thanks tsh!

```
for e in input()[1:-1].split("??"):print(end={"!":chr(len(e)+96),"+":chr(len(e)+63),"-":('<>& ?!%/.:0123456789=+'*9)[len(e)]}[e[-1]])

```

Try it online!

## Explanation

(Will update this later)

Ungolfed:

```
a = input[1:-1].split("??") # Get every part
t = "" # Output string
for e in a: # Iterates over a
 f,l,p=chr,len(e),e[-1] # They are used many times, this is for shorter code
 exec({
  "!":"t+=f(l+96)",                       # if ends with "!", get the l+96 -th ASCII char
  "+":"t+=f(l+63)",                       # ends with "+", get the l+63 -th
  "-":"t+='@*& ?!%/.:0123456789=+<>'[l]"  # hard-coded string
 }[p])
print t # print the result

```
> 2 votes

# Answer
# Red, ~~164~~ 158 bytes

```
func[s][r: copy""parse s[any["?"(n: 0)any["!"(n: n + 1)]["+?"(c: to sp 64 +
n)|"-?"(c: pick"& ?!%/.:0123456789=+-<>@*"n)|"?"(c: to sp 96 + n)](append r c)]]r]

```

Try it online!

## Old, non-Parse solution, 169 bytes

```
func[s][r: copy""foreach c extract next split s"?"2[d: length? c append r switch
to 1 last c[33[to sp 96 + d]43[to sp 63 + d]45[pick"& ?!%/.:0123456789=+-<>@*"d - 1]]]r]

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 125 bytes

```
s=>s.split`?`.map(a=>(b=a.length)?(z=a.slice(-1))==`-`?'& ?!%/.:0123456789=+-<>@*'[b-2]:Buffer([b+(63*z==`+`||96)]):a).join``

```

Try it online!

s.split`?`         splits the string at the char ?, results in an array
.map(a=>           pass item n in array to function and replace item with the return
    (b=a.length)?...            if a is not empty do ...
        a.slice(-1)==`-`?...     if last char in a is - do ...
            '& ?!%/.:0123456789=+-<>@*'[b-2]    get character at index
        :         else
        Buffer(b+(63*z==`+`||96))   character from code
    :a                 else return a
).join``            array to string

```
</code></pre>
> 1 votes

# Answer
# Charcoal, 44 bytes

```
⭆⪪Ｓ?⎇№ι!§⎇№ι-”‴"μ⮌w7Ｌ⁴Vp#ωδk4θO(”⎇№ι+αβ⊖№ι!ι

```

Try it online! Link is to verbose version of code. Explanation:

```
⭆⪪Ｓ?

```

Split the input on `?`s and map over each substring.

```
⎇№ι!

```

If this substring contains a `!`, then...

```
§⎇№ι-”‴"μ⮌w7Ｌ⁴Vp#ωδk4θO(”⎇№ι+αβ⊖№ι!

```

... count the number of `!`s and use this to index into either the compressed string of non-alphabetic characters or the upper or lower case alphabet depending on whether there is a `-` or `+` or not.

```
ι

```

Otherwise leave the substring unchanged.
> 1 votes

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


# Question
Title: SELECT ALL FROM SelectQL WHERE (answer="short" OR NOT length=10000)
I've invented an SQL-like language. Let's call it SelectQL. You can't `INSERT` anything, you can only `SELECT`, and I don't have the time for an interpreter. How about you help?

# The Challenge

Write a full program or a function that takes in a database of tables and a valid SelectQL `SELECT` string, interprets the string, and outputs the resulting `SELECT`ion.

## `SELECT` Specification

The `SELECT` SelectQL statement is as follows (optional portions are in curly brackets):

```
SELECT [column] FROM [table] {WHERE ( [condition] {[AND/OR] [condition] ... } ) }

```
* `[column]` can be `ALL` for selecting all columns, or a valid column name in the `[table]`.
* `[table]` is the name of a table.
* The `WHERE` clause is optional. A `WHERE` clause is followed by a list of `[condition]` separated by any of `AND` or `OR`, surrounded by parentheses `()`.
* A `[condition]` is a key-value pair separated by an equals sign `=`.
* `[condition]` can be preceded with `NOT` to select the complement of the condition.
* Operator Precedence: `NOT` has higher precedence than `AND` and `OR`. `AND` and `OR` is executed left to right.
* Conditions involving arrays/lists (`{980, "abc"}` in `data` below) will look for the existence of a requested value in the array, and return the whole array if true.
* `key` must be a column in `[table]`.
* SelectQL query strings are ***case insensitive***.

## Table Format

Your program should take in an SelectQL database (array of arrays, list of lists, delimited string, JSON object, etc) in the following format:

```
[
    [table name, (column names), [(row), (row), ...]],
    [table name, (column names), [(row), (row), ...]]
]

```
* `table name` is the name of the table.
* `[column names]` is a list of unique strings which are column names. These are the keys in `[condition]`.
* Each column's values all must have the same type.
* `[row]` is a list-like of values. Each row must be the same length as `[column names]`.
* There can be no `[row]`s.
* Elements in `[row]` cannot be empty. Empty strings or arrays are not considered empty.

## Types

There are three types in SelectQL: `number`, `string`, `array`.

Numbers are at least 1 digit in `0-9`, with an optional decimal point with at least 1 digit.

Strings are double-quote-delimited sequences of characters. Empty strings are possible (`""`).

Arrays are curly-bracket-delimited comma-separated sequences of numbers, strings, or arrays. Arrays can be heterogeneous. Empty arrays are possible (`{}`).

# Input

* A valid SelectQL database, and
* A valid SelectQL `SELECT` query. It will always `SELECT` a valid table in the database.

# Output

* The result of the query. The result must have the columns as well as the resulting rows.

# Examples

The examples will use the following database:

```
[
    [data, (d1, d2, 3, ~!@#), [(123, "", {980, "abc"}, "false"), (456, "this isn't empty!", {{},{}}, "-123.4444"), (1, "2", {3, 4}, "five")]],
    [no, (yes, a, 1.5, what), []]
]

```

```
Format:
string --> result
-----------------
"SELECT ALL FROM data"
        --> [(d1, D2, 3, ~!@#), [(123, "", {980, "aBc"}, "false"), (456, "this isn't empty!", {{},{}}, "-123.4444"), (1, "2", {3, 4}, "five")]]

"SELECT D1 FROM DATA"
        --> [(d1), [(123), (456), (1)]]

"SELECT d1, 3 FROM data"
        --> [(d1, 3), [(123, {980, "aBc"}), (456, {{},{}}), (1, {3,4})]]

"SELECT ALL FROM DATA WHERE (NOT d1=123)"
        --> [(d1, D2, 3, ~!@#), [(456, "this isn't empty!", {{},{}}, "-123.4444"), (1, "2", [3, 4], "five")]]

"SELECT all FROM data WHERE (d1=123)"
        --> [(d1, D2, 3, ~!@#), [(123, "", [980, "aBc"], "false")]

"SELECT ~!@# FROM DATA WHERE (3={} OR d2="")"
        --> [(~!@#), [("false"), ("-123.4444")]

"SELECT all FROM DATA WHERE (d1=2)"
        --> [(d1, d2, 3, ~!@#), []]

"select all from no"
        --> [(yes, a, 1.5, what), []]

"select 3 from data where (3=980)"
        --> [(3),[[{980, "aBc"}]]

```

# Additional Rules/Clarifications

Sandbox Link

# Answer
# Python 3.8 (pre-release), 473 bytes

```
from re import*
def s(d,q):
 o,f,c=search(r' (?:all|(.*?)) from (\S+)(?:.*?\((.*)\))?',q,I).groups()
 for x,l,r in d:
  u=str.lower;h=bool;m=o and o.split(', ')or l;y=[]
  for g in r:
   p=0;_,*t=split('(?: (?:(and)|or) |^)(not )?(.*?)=',c or'',0,I)
   while t:
    a,n,k,v,*t=t
    p=h(a)&p&(b:=h(n)^any(i==u(k)and(j==eval(v)or list==type(j)and eval(v)in j)for i,j in zip(l,g)))|p|b
   if 1-h(c)|p:y+=[j for i,j in zip(l,g)for z in m if i==u(z)],
  if u(f)==x:print([m,y])

```

Try it online!

This uses @hyper-neutrino's style of input/output, but is otherwise a completely different implementation.

-5 bytes thanks to @cairdcoinheringaahing.
> 7 votes

# Answer
# Python 3, 682 bytes

```
from regex import*
s=lambda x:str==type(x)and x.lower()or list==type(x)and[*map(s,x)]or x
V=eval
E=lambda x:str(V(x.group()))
def f(d,q):
	c,t,w=match("select (.+) from (.+?)(?: where \((.+)\))?$",s(q)).groups()
	K=[[C for C in map(s,y)if{*c.split(", ")}&{"all",C}]for x,y,z in d if s(x)==t][0];r=[]
	for R in{s(x):[{s(k):l for k,l in zip(y,r)}for r in z]for x,y,z in d}[t]:
		if w:
			v=sub("not \w+",E,sub(r'(\S+)=(\[((?2)(, *(?2))*)?\]|"[^"]*"|\d+)',lambda x:str(e(s(R[x.group(1)]),s(V(x.group(2))))),w))
			while len(v)>5:v=sub("\w+ \w+ \w+",E,v,1)
			if~-V(v):continue
		r+=R,
	print([K,[[q[x]for x in K]for q in r]])
e=lambda x,y:x==y or list==type(x)and any(e(v,y)for v in x)

```

Try it online!

-5 bytes thanks to Razetime
-18 bytes thanks to caird coinheringaahing

this was painful

This uses `[]` for arrays because that's Python's list representation. Please let me know if this is invalid. The DB is just taken in the representation given in the question as a native Python object.
> 6 votes

# Answer
# Python 3, 583 bytes:

```
import re, operator as o
def f(a,q):
 [[c,b]],z=[(c,d)for t,c,d in a if t==(r:=re.findall(' (.+) FROM (\w+)',q)[0])[1]],lambda n,m,w:[o.pos,o.not_][w](n in m if type(m)==set else n==m)
 d=[dict(zip(c,i))for i in b]
 p=lambda e,i:(eval((v:=e.pop().split('='))[-1]),i[re.sub('NOT\s','',v[0])],v[0][:3]=='NOT')
 return (g:=[c,r[0].split(', ')][r[0]!='ALL']),[[i[j]for j in g]for i in d if(y:=lambda e,u:True if not e else(z(*p(e,i))if not e[:-1]or not u else[o.and_,o.or_][u.pop()=='OR'](z(*p(e,i)),y(e,u))))(re.findall('(?:(?:NOT\s)*\w+\=(?:\{.*?\}|".*"|\w+))+', q),re.findall('AND|OR',q))]

```
> 2 votes

---
Tags: code-golf, interpreter, sql
---


# Question
Title: Shortest self-modifying code to wish a happy New Year!
Your code just has to print "Happy 2013". However, if it detects that it's 2014, it has to modify itself (as a running process!!) and print "Happy 2014" instead.

By self-modifying I mean the running process must really modify itself: it should alter its own instructions while it is executing.

Shortest code wins.

-10% size bonus if it's general, so it works for 2015, etc.

Sorry if the task excludes some languages or systems where it's not possible...

# Answer
> 4 votes
# Bash / shell script (35 chars - 10% = 31.5)

I think this shell script counts as self-modifying:

```
$ eval "y()(echo Happy `date +%Y`)";y
Happy 2013
$

```

At least, it does modify its own function `y`:

```
$ set | grep -A3 '^y ()'
y ()
{
    ( echo Happy 2015 )
}
$

```

---

@manatwork suggested `eval "y()(date +Happy\ %Y)";y`, which produces the desired output, but I'm not sure if this counts as self-modifying, to the extent that it self-modifies with the current year. The generated function is as follows, which won't be a different function on a yearly basis:

```
y ()
{
    ( date +Happy\ %Y )
}

```

If it does count, then the score is:

# Bash / shell script (29 chars - 10% = 26.1)

---

A lot of entries don't seem to make any attempt to self-modify. If we lift this restriction for shell-script, then we can do this which weighs in at:

# 15 chars - 10% = 13

```
date +Happy\ %Y

```

# Answer
> 3 votes
## PHP

### Creation of source code statement: 26 - 10% = 23.4

```
eval('?>Happy '.@date(Y));

```

### Overlay of existing instruction: 255 - 10% = 229.5

This can only possibly work on Linux systems configured with a writable `/proc/self/mem`, and `short_tags = On` is also assumed. (If `short_tags = Off`, replace `<?` with `<?php` , for a score of 233.1.)

```
<?$p='/proc/self/';$f=fopen($p.@mem,'r+');foreach(file($p.@maps)as$L)if(sscanf($L,'%x-%x rw%c',$i,$e,$n)>2)for(fseek($f,$i),$a=@xxxx,$e-=$i-4;$e-=4;){$b=$a;$a=fread($f,4);if($j=@strpos("x$b$a",GO.LF)){fseek($f,$j-9,1);fputs($f,@date(Y));}}$f=0?>Happy GOLF

```

Reformatted for readability:

```
<?
$p = '/proc/self/';
$f = fopen($p . @mem, 'r+');
foreach (file($p . @maps) as $L)
if (sscanf($L, '%x-%x rw%c', $i, $e, $n) > 2)
for (fseek($f, $i), $a = @xxxx, $e -= $i - 4; $e -= 4;) {
    $b = $a;
    $a = fread($f, 4);
    if ($j = @strpos("x$b$a", GO.LF)) {
        fseek($f, $j - 9, /* SEEK_CUR */ 1);
        fputs($f, @date(Y));
    }
}
$f = 0
?>Happy GOLF

```

# Answer
> 2 votes
# APL, self-modifying\*, general – 72 chars

Tested on Dyalog APL. On other systems you might have to adjust the `3+` on line 3.

```
∇H
y←2012
→(y=z←1⌷⎕TS)/k
x←⎕CR'H'⋄x[2;3+⍳4]←⍕z
⎕FX x⋄H⋄→0
k:⎕←'Happy'y
∇

```

(\*) This function does the following:

* set a variable y to some constant year;
* test whether y points to the current year; if not:

+ update its own definition, changing the numeric constant in the first line so that it sets variable y to the current year;
    + call itself recursively, so that the recursive call uses the new definition.

*Whether this is acceptable as self-modifying, I'll leave to the OP to decide.*

Example invocation, displaying the function code before and after the invocation. As you can see, line 1 has changed during the invocation:

```
      ∇H[⎕]∇
[0]   H
[1]   y←2012
[2]   →(y=z←1⌷⎕TS)/k
[3]   x←⎕CR'H' ⋄ x[2;3+⍳4]←⍕z
[4]   ⎕FX x ⋄ H ⋄ →0
[5]  k:⎕←'Happy'y

      H
 Happy  2013

      ∇H[⎕]∇
[0]   H
[1]   y←2013
[2]   →(y=z←1⌷⎕TS)/k
[3]   x←⎕CR'H' ⋄ x[2;3+⍳4]←⍕z
[4]   ⎕FX x ⋄ H ⋄ →0
[5]  k:⎕←'Happy'y

```

# Answer
> 2 votes
## Forth: 22 / 32 Chars. ( Using gforth )

```
s" Happy 2022" swap +!              ( 22 chars )

```

A compiled but slightly longer version is shown here, as the result can be decompiled, and its effects demonstrated. Principle of operation is identical to the shorter version above. Consider the longer version as demonstratable proof of concept.

```
: happy s" Happy 2022" swap +! ;    ( 32 chars )

```

I'll decompile this first, then execute, and decompile it again:

```
see happy    ( decompile happy, as it is now )

```

> : happy
> s" Happy 2022" swap +! ;

```
happy   ( execute the self-modifying happy )

see happy ( decompile happy again )

```

> : happy
> s" Rappy 2022" swap +! ;

What happens here is: s" ..." places two items on stack: address of first string character, and string length, which is 10 in this case. The sequence "swap +!" adds string length, 10, to the contents at first string address, thereby changing ASCII H to ASCII R.

A version matching the requirements slightly better is compiled using vfx:

```
: h 1 s" Happy 2021" 2dup type + 1- c+! ;

```

reason for using a different compiler for this version is that it provides c+! already which I'd have to add to gforth first, which should introduce a penalty of about 22 chars.

disassembling first:

> ( 080C0AF0 E81383F9FF ) CALL 08058E08 (S") "Happy 2021"
> ( 080C0B00 8BD3 ) MOV EDX, EBX
> ( 080C0B02 035D00 ) ADD EBX, \[EBP\]
> ( 080C0B05 4B ) DEC EBX
> ( 080C0B06 800301 ) ADD Byte Ptr 0 \[EBX\], 01
> ( 080C0B09 8BDA ) MOV EBX, EDX
> ( 080C0B0B FF15B9DE0408 ) CALL \[0804DEB9\] TYPE
> ( 080C0B11 C3 ) NEXT,

executing several times, output follows immediately:

> h Happy 2022
> h Happy 2023
> h Happy 2024
> h Happy 2025
> h Happy 2026

disassembling again:

> ( 080C0B30 E8D382F9FF ) CALL 08058E08 (S") "Happy 2026"
> ( 080C0B40 8BD3 ) MOV EDX, EBX
> ( 080C0B42 035D00 ) ADD EBX, \[EBP\]
> ( 080C0B45 4B ) DEC EBX
> ( 080C0B46 800301 ) ADD Byte Ptr 0 \[EBX\], 01
> ( 080C0B49 8BDA ) MOV EBX, EDX
> ( 080C0B4B FF15B9DE0408 ) CALL \[0804DEB9\] TYPE
> ( 080C0B51 C3 ) NEXT,

# Answer
> 1 votes
## Python (144 characters; 130 after removal of 10%)

This codes writes a library, thats imported (again after updating the code) and used.

```
import datetime
f=open("y.py",'w')
f.write("def year():return "+str(datetime.date.today().year))
f.close()
import y
print "Happy "+str(y.year())

```

# Answer
> 1 votes
# Befunge 98, 26 bytes - 10% (bonus) = 23.4

```
"EMIT"4(Yd0p"  yppaH"5k,.@

```

The first space immediately after the quote gets overwritten with a unicode character with code point equal to the year.

The self-modifying part of this code actually makes it more verbose. The below code performs the same task without self-modification:

```
"EMIT"4(Y" yppaH"5k,.@

```

# Answer
> 0 votes
# Racket - 139 - 10% = 125.1

```
(let g((y(date-year(seconds->date(current-seconds))))(h"Happy ~a~%"))
(if(< 2013 y)(begin(set! g(lambda()(printf h y)))(g))(printf h 2013)))

```

Ungolfed:

```
(let g ((y (date-year (seconds->date (current-seconds))))
        (h "Happy ~a~%"))
    (if (< 2013 y)
        (begin
          (set! g (lambda () (printf h y)))
          (g))
        (printf h 2013)))

```

So I'm using a named `let` which is creating a procedure `g` and calling it with the parameter y (current year) and h (printf format string). If `y` is higher than 2013 i **redefine** `g` to a procedure that takes no arguments and prints a suitable string for the current year instead just before calling the new procedure. It's short since `h` and `y` are in the new procedures closure variables.

# Answer
> 0 votes
# Perl (100 characters (90 after removal of 10%))

```
$^I="";@ARGV=$0;s/ \K\d+/$l=(localtime)[5]+1900/e,print while<>;exec perl,$0if$&!=$l;print"Happy 1
"

```

It's probably too long, but I don't care (at least it's round in its size). Could be shorter if it would read UTC time (replace `localtime` with `gmtime`). Please note that after running, it will increase its size to 103 characters (unless you run this in year 10000, then 104 characters), but hey, it's self-modifying.

# Answer
> -1 votes
## **Python 2,(151-10%)=136**

Inspired by this answer

```
from datetime import*
s=int(str(datetime.now())[:4]);x=2013;q=globals
def l(): return x
n="def l():return[x,s][s>x]"
exec(n,q(),q())
print'Happy %d'%l()

```

# Answer
> -1 votes
# JavaScript (ECMAScript 5)/HTML (HTML5) - 106

```
<script id=k type=x>2013</script><script>k.innerHTML=new Date().getFullYear();alert('Happy '+k.innerHTML);

```

And here is the jsfiddle

Note that in the jsfiddle, I included a closing `</script>`, but it isn't necessary, it is just necessary to work in jsfiddle

# Answer
> -1 votes
# Javascript 122 - 10% = 109.8

```
function n(){y=0;z=new Date().getFullYear();if(y-z){eval((""+n).replace(y,z));alert("Happy new "+z)}setTimeout(n,1000)}n()

```

It will greet you with a happy new year for the current year, and also keep checking periodically forever and greet you again if a new year comes.

# Answer
> -3 votes
# PHP, 28 (-10% is 25)

```
echo"Happy ".date('Y')."!";

```

# Answer
> -3 votes
## HTML/JavaScript - 63 (70-10%)

```
<body onload="b.innerHTML=new Date().getFullYear()">Happy <b id=b>2013

```

---
Tags: code-golf
---