title: Lifetime of a Worm

text:
# Question
Title: Lifetime of a Worm
## Terms

A **worm** is any list of nonnegative integers, and its *rightmost* (i.e., *last*) element is called the **head**. If the head is not 0, the worm has an **active segment** consisting of *the longest contiguous block of elements that includes the head and has all of its elements at least as large as the head*. The **reduced active segment** is the active segment with the head decremented by 1. For example, the worm `3 1 2 3 2` has active segment `2 3 2`, and the reduced active segment is `2 3 1`.

## Rules of evolution

A worm evolves step-by-step as follows:

> In step t (= 1, 2, 3, ...),
> if the head is 0: delete the head
> else: replace the active segment by t+1 concatenated copies of the reduced active segment.

**Fact**: *Any worm eventually evolves into the empty list*, and the number of steps to do so is the worm's **lifetime**.

(Details can be found in *The Worm Principle*, a paper by L. D. Beklemishev. The usage of "list" to mean a finite sequence, and "head" to mean its *last* element, is taken from this paper -- it should not be confused with the common usage for lists as an abstract data type, where *head* usually means the *first* element.)

## Examples (active segment in parentheses)

**Worm: 0,1**

```
step    worm
         0(1)
1        0 0 0
2        0 0
3        0
4           <- lifetime = 4

```

**Worm: 1,0**

```
step    worm
         1 0
1       (1)
2        0 0 0
3        0 0
4        0
5           <- lifetime = 5

```

**Worm: 1,1**

```
step    worm
        (1 1)
1        1 0 1 0
2        1 0(1)
3        1 0 0 0 0 0
4        1 0 0 0 0
5        1 0 0 0
...
8       (1)
9        0 0 0 0 0 0 0 0 0 0
10       0 0 0 0 0 0 0 0 0
...
18       0
19           <- lifetime = 19

```

**Worm: 2**

```
step    worm
        (2)
1       (1 1)
2        1 0 1 0 1 0
3        1 0 1 0(1)
4        1 0 1 0 0 0 0 0 0
5        1 0 1 0 0 0 0 0
6        1 0 1 0 0 0 0
...
10       1 0(1)
11       1 0 0 0 0 0 0 0 0 0 0 0 0 0
12       1 0 0 0 0 0 0 0 0 0 0 0 0
...
24      (1)
25       0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
...
50       0
51          <- lifetime = 51

```

**Worm: 2,1**

```
        (2 1)
1        2 0 2 0
2        2 0(2)
3        2 0(1 1 1 1)
4        2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0
5        2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0(1 1 1)
6        2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0
7        2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0(1 1)
8        2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0{1 0}^9
...
??          <- lifetime = ??

```

**Worm: 3**

```
step    worm
        (3)
1       (2 2)
2       (2 1 2 1 2 1)
3        2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0
4        2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1(2)
5        2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0(2 1 2 1 1 1 1 1 1 1)
6        2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0{2 1 2 1 1 1 1 1 1 0}^7
7        2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0{2 1 2 1 1 1 1 1 1 0}^6 (2 1 2 1 1 1 1 1 1)
...      ...
??          <- lifetime = ??

```

## Aside

Worm lifetimes are typically enormous, as shown by the following lower bounds in terms of the standard fast-growing hierarchy of functions fα:

```
worm                lower bound on lifetime
----------------    ------------------------------------------
11..10 (k 1s)       f_k(2)
2                   f_ω(2)
211..1 (k 1s)       f_(ω+k)(2)
2121..212 (k 2s)    f_(ωk)(2)
22..2 (k 2s)        f_(ω^k)(2)
3                   f_(ω^ω)(2)
...
n                   f_(ω^ω^..^ω)(2) (n-1 ωs)  >  f_(ε_0) (n-1)

```

Remarkably, worm \[3\] already has a lifetime that far surpasses Graham's number, G:

fωω(2) = fω2(2) = fω2(2) = fω+2(2) = fω+1(fω+1(2)) \>\> fω+1(64) \> G.

## Code Golf Challenge

> Write the shortest possible function subprogram with the following behavior:
>
> **Input**: Any worm.
> **Output**: The lifetime of the worm.
>
> Code size is measured in bytes.

Here's an example (Python, golfs to about 167 bytes):

```
from itertools import *
def T(w):
    w=w[::-1]
    t=0
    while w:
        t+=1
        if w[0]:a=list(takewhile(lambda e:e>=w[0],w));a[0]-=1;w=a*(t+1)+w[len(a):]
        else:w=w[1:]
    return t

```

**NB**: If t(n) is the lifetime of the worm \[n\], then the rate of growth of t(n) is roughly that of the Goodstein function. So *if this can be golfed to below 100 bytes, it could well give a winning answer to the Largest Number Printable question*. (For that answer, the growth-rate could be vastly accelerated by always starting the step-counter at n -- the same value as the worm \[n\] -- instead of starting it at 0.)

# Answer
> 15 votes
## GolfScript (56 54 chars)

```
{-1%0\{\)\.0={.0+.({<}+??\((\+.@<2$*\+}{(;}if.}do;}:L;

```

Online demo

I think that the key trick here is probably keeping the worm in reverse order. That means that it's pretty compact to find the length of the active segment: `.0+.({<}+??` (where the `0` is added as a guard to ensure that we find an element smaller than the head).

---

As an aside, some analysis of the worm lifespan. I'll denote the worm as `age, head tail` (i.e. in reverse order from the question's notation) using exponents to indicate repetition in the head and tail: e.g. `2^3` is `2 2 2`.

**Lemma**: for any active segment `xs`, there is a function `f_xs` such that `age, xs 0 tail` transforms into `f_xs(age), tail`.

Proof: no active segment can ever contain a `0`, so the age by the time we delete everything before the tail is independent of the tail and is hence a function only of `xs`.

**Lemma**: for any active segment `xs`, the worm `age, xs` dies at age `f_xs(age) - 1`.

Proof: by the previous lemma, `age, xs 0` transforms into `f_xs(age), []`. The final step is deletion of that `0`, which is not touched previously because it can never form part of an active segment.

With those two lemmata, we can study some simple active segments.

For `n > 0`,

```
age, 1^n 0 xs -> age+1, (0 1^{n-1})^{age+1} 0 xs
              == age+1, 0 (1^{n-1} 0)^{age+1} xs
              -> age+2, (1^{n-1} 0)^{age+1} xs
              -> f_{1^{n-1}}^{age+1}(age+2), xs

```

so `f_{1^n} = x -> f_{1^{n-1}}^{x+1}(x+2)` (with base case `f_{[]} = x -> x+1`, or if you prefer `f_{1} = x -> 2x+3`). We see that `f_{1^n}(x) ~ A(n+1, x)` where `A` is the Ackermann–Péter function.

```
age, 2 0 xs -> age+1, 1^{age+1} 0 xs
            -> f_{1^{age+1}}(age+1)

```

That's enough to get a handle on `1 2` (`2 1` in the notation of the question):

```
1, 1 2 -> 2, 0 2 0 2
       -> 3, 2 0 2
       -> f_{1^4}(4), 2
       -> f_{1^{f_{1^4}(4)+1}}(f_{1^4}(4)+1) - 1, []

```

So given input `2 1` we expect output ~ `A(A(5,4), A(5,4))`.

```
1, 3 -> 2, 2 2
     -> 3, 1 2 1 2 1 2
     -> 4, 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2
     -> 5, 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2
     -> f_{21212}^4(5) - 1

age, 2 1 2 1 2 -> age+1, (1 1 2 1 2)^{age+1}
               -> age+2, 0 1 2 1 2 (1 1 2 1 2)^age
               -> age+3, 1 2 1 2 (1 1 2 1 2)^age

```

and I can really start to comprehend why this function grows so insanely.

# Answer
> 9 votes
### GolfScript, 69 62 characters

```
{0:?~%{(.{[(]{:^0=2$0+0=<}{\(@\+}/}{,:^}if;^?):?)*\+.}do;?}:C;

```

The function `C` expects the worm on the stack and replaces it by the result.

Examples:

```
> [1 1]
19

> [2]
51

> [1 1 0]
51

```

# Answer
> 7 votes
### Ruby — 131 characters

I know this can't compete with the GolfScript solutions above and I'm fairly sure that this can be reduced a score or more characters, but honestly I'm happy to have been able to solve the problem ungolfed. Great puzzle!

```
f=->w{t=0;w.reverse!;until w==[];t+=1;if w[0]<1;w.shift;else;h=w.take_while{|x|x>=w[0]};h[0]-=1;w.shift h.size;w=h*t+h+w;end;end;t}

```

My pre-golfed solution from which the above is derived:

```
def life_time(worm)
  step = 0
  worm.reverse!
  until worm.empty?
    step += 1
    if worm.first == 0
      worm.shift
    else
      head = worm.take_while{ |x| x >= worm.first }
      head[0] -= 1
      worm.shift(head.size)
      worm = head * (step + 1) + worm
    end
  end
  step
end

```

# Answer
> 6 votes
# Sclipting (43 characters)

```
글坼가⑴감套擘終長①加⒈丟倘⓶增⓶가采⓶擘❷小終⓷丟❶長貶❷가掊貶插①增復合감不가終終

```

This expects the input as a space-separated list. This outputs the correct answer for `1 1` and `2`, but for `2 1` or `3` it takes too long so I gave up waiting for it to finish.

With commentary:

```
글坼 | split at spaces
가⑴ | iteration count = 0

감套 | while:
  擘終長①加⒈丟 | remove zeros from end and add to iteration count
  倘 | if the list is not empty:
    ⓶增⓶ | increment iteration count
    가采⓶擘❷小終⓷丟 | separate out active segment
    ❶長貶❷가掊貶插 | compute reduced active segment
    ①增復合 | repeat reduced active segment and concat
    감 | continue while loop
  不 | else
    가 | stop while loop
  終 | end if
終 | end while

```

# Answer
> 5 votes
# k (83)

`worm:{-1+*({x,,(,/((x+:i)#,@[y@&w;(i:~~#y)#0;-1+]),y@&~w:&\~y<*y;1_y)@~*y}.)/(1;|,/x)}`

this can probably be golfed further, as it just implements the recurrence fairly straightforwardly.

the basic evolution function, `{x,,(,/((x+:i)#,@[y@&w;(i:~~#y)#0;-1+]),y@&~w:&\~y<*y;1_y)@~*y}`, is 65 chars, and uses some tricks to stop incrementing the age when the worm dies. the wrapper coerces an input of a single integer to a list, reverses the input (it's shorter to write the recurrence in terms of a worm reversed from your notation), asks for the fixpoint, selects the age as the output, and adjusts the result to account for the overshoot in the last generation.

if i do the coercion and reversal manually, it drops to 80 (`{-1+*({x,,(,/((x+:i)#,@[y@&w;(i:~~#y)#0;-1+]),y@&~w:&\~y<*y;1_y)@~*y}.)/(1;x)}`).

some examples:

```
  worm 1 1 0
51
  worm 2
51
  worm 1 1
19

```

unfortunately, it's probably not much use for Largest Number Printable, except in a very theoretical sense, as it's quite slow, limited to 64-bit integers, and probably not particularly memory-efficient.

in particular, `worm 2 1` and `worm 3` just churn (and would probably throw `'wsfull` (out of memory) if i let them keep going).

# Answer
> 2 votes
# APL (Dyalog Unicode), 52 bytesSBCS

Saved 7 bytes thanks to @ngn and @Adám.

```
0{⍬≡⍵:⍺⋄n←⍺+1⋄0=⊃⍵:n∇1↓⍵⋄n∇∊(⊂1n/-∘1@1¨)@1⊆∘⍵⍳⍨⌊\⍵}⌽

```

Try it online!

Explanation:

```
0{...}⌽    ⍝ A monadic function train. We define a recursive function with two
           ⍝ arguments: zero (our counter), and the reverse of our input
⍬≡⍵:⍺      ⍝ Our base case - if our input is an empty list, return our counter
n←⍺+1      ⍝ Define 'n' as our counter plus 1
0=⊃⍵:n∇1↓⍵ ⍝ If the first element of the input is zero, recurse with the tail
           ⍝ of our input and n
⌊\⍵        ⍝ Minimum-expand: creates a new list from our input where each element
           ⍝ is the incremental minimum
⍳⍨         ⍝ Applies above to both sides of the index-of function. Index-of returns
           ⍝ the index of the first occurence of each element in the left-side list.
           ⍝ At this point, a (reversed) input list of [3 4 5 2 3 4] would result
           ⍝ in [1 1 1 4 4 4]
⊆∘⍵        ⍝ Partition, composed with our input. Partition creates sublists of the
           ⍝ right input whenever the integer list in the left input increases.
           ⍝ This means we now have a list of sub-lists, with the first element
           ⍝ being the worm's active segment.
(...)@1    ⍝ Take the active segment and apply the following function train...
-∘1@1¨     ⍝ Subtract 1 from the first element of the active segment
1n/        ⍝ Replicate the resultant list above n+1 times
⊂          ⍝ Enclose the above, so as to keep the original shape of our sub-array
∊          ⍝ Enlist everything above together - this recursively concatenates our
           ⍝ new active segment with the remainder of the list
n∇         ⍝ Recurse with the above and n

```

# Answer
> 1 votes
# Scala, 198

```
type A=List[Int]
def T(w:A)={def s(i:Int,l:A):Stream[A]=l match{case f::r=>l#::s(i+1,if(f<1)r
else{val(h,t)=l.span(_>=l(0));List.fill(i)(h(0)-1::h.tail).flatten++t})
case _=>Stream()};s(2,w).length}

```

Usage:

```
scala> T(List(2))
res0: Int = 51

```

# Answer
> 1 votes
# K, 95

```
{i::0;#{~x~,0}{((x@!b),,[;r]/[i+:1;r:{@[x;-1+#x;-1+]}@_(b:0^1+*|&h>x)_x];-1_x)@0=h:*|x:(),x}\x}

```

.

```
k)worm:{i::0;#{~x~,0}{((x@!b),,[;r]/[i+:1;r:{@[x;-1+#x;-1+]}@_(b:0^1+*|&h>x)_x];-1_x)@0=h:*|x:(),x}\x}
k)worm 2
51
k)worm 1 1
19
q)worm 1 1 0 0 0 0
635

```

# Answer
> 1 votes
# C (gcc), 396 bytes

```
#define K malloc(8)
typedef*n;E(n e,n o){n s=K,t=s;for(*s=*o;o=o[1];*t=*o)t=t[1]=K;t[1]=e;e=s;}main(c,f,l,j,a)n*f;{n w=K,x=w;for(;l=--c;x=x[1]=K)*x=atoi(f[c]);for(;w&&++l;)if(*w){n v=K,z=v,u=w,t=K;for(a=*v=*w;(u=u[1])&&*u>=*w;*z=*u)z=z[1]=K;for(x=v[1],v=K,*v=a-1,1[u=v]=x;u;u=u[1])w=w[1];for(j=~l;j++;)u=t=E(t,v);for(;(u=u[1])&&(x=u[1])&&x[1];);u[1]=0;w=w?E(w,t):t;}else w=w[1];printf("%d",--l);}

```

Try it online!

I know I'm EXTREMELY late to the party, but I thought I'd try my hand at this in C, which required a linked-list implementation. It's not really golfed at all besides changing all the identifiers to single characters, but it functions!

All in all, I'm pretty happy considering this is the 3rd C/C++ program I've ever wrote.

# Answer
> 1 votes
# Haskell, 84 bytes

```
(0!).reverse
n!(x:y)|x<1=(n+1)!y|(a,b)<-span(>=x)y=(n+1)!(([-1..n]*>x-1:a)++b)
n!_=n

```

Try it online!

Thanks to @xnor for two bytes.

I feel like there should be a good way to factor out the common increment, but I haven't found a short one yet.

# Answer
> 1 votes
# Pyt, 206 bytes

```
ĐƩ?ŕ:ŕ0;áƑ0`⇹ĐŁ⁻?ŕ:ŕÁ⇹⁺Đ↔⁻⇹⁺⑴*;⇹⁺⁺⇹Đ1~⦋¬?ŕ⁺ĐŁĐř≠*ž⁻:ŕĐ1~⦋⇹Đ⁺ĐŁĐř≠*ž⁻Đ04Ș06Ș+<ĐŁř*↑Đ¬?ŕŕŕĐŁĐř=-0↔Đ3Ș+↔+⇹⑴⇹ɐ*Ƒ:ŕ⑴*ĐŁ3Ș⁺⇹ĐŁ⇹04ȘĐŁř⇹04Ș>*ž⁻ĐŁĐř=-+0↔+⇹ŕ+Đ4Ș⇹04Ș⑴⇹ɐ*Ƒ0↔++↔+áƑĐ0⦋⇹⁺ĐŁř1≠*ž⁻;ĐƩ¬?ŕŁ+0:ŕ⇹⁻;łŕ⁻⁻⁻?⁺⁺:⁺;

```

Try it online!

Takes input as an array.

| Code | Pseudocode |
| --- | --- |
| ĐƩ?ŕ:ŕ0;áƑ | If sum of w (worm parts) is 0, add another zero to avoid breaking the function (kludge) |
| ĐƩ?ŕ:ŕ1~; | if all zeroes, ctr=-1, otherwise ctr=0 (kludge) |
| \` | do... |
| ⇹ĐŁ⁻?ŕ | if len(w)!=1, do nothing |
| :ŕÁ⇹⁺Đ↔⁻⇹⁺⑴\* | otherwise, decrement w\[0\] and push 2 copies |
| ;⇹⁺⁺⇹ | ctr+=2 |
| Đ1~⦋¬? | if w\[-1\]=0: |
| ŕ⁺ĐŁĐř≠\*ž⁻ | remove the head |
|  | otherwise: |
| Đ1~⦋⇹ | q=w\[-1\]-1 |
| Đ⁺ĐŁĐř≠\*ž⁻ | x=w\[:-1\] |
| Đ04Ș06Ș+\<ĐŁř\* | h=\[x\_i\*(x\_i\>q) for i in range(len(x))\] |
|  | k=max(h) |
| Đ¬?ŕŕŕ | if k=0 |
| ĐŁĐř=- | decrement the head |
| 0↔Đ3Ș+↔+⇹⑴⇹ɐ\*Ƒ | concatenate the head ctr times |
|  | otherwise |
| ⑴\*ĐŁ3Ș⁺⇹ĐŁ⇹04ȘĐŁř⇹04Ș\>\*ž⁻ĐŁĐř=-+ | g=w\[:k\]; b=\[w\_i-(i=len(w)-1) for i in \[k...len(w)-1\]\] |
| 0↔+⇹ŕ+Đ4Ș⇹04Ș⑴⇹ɐ\*Ƒ | concatenate the reduced head (b) ctr times |
| 0↔++↔+ | clean up the stack |
| áƑĐ0⦋⇹⁺ĐŁř1≠\*ž⁻ | assemble the new worm |
| ;ĐƩ¬?ŕŁ+0:ŕ⇹⁻; | if worm is not dead, decrement the counter |
| ł | ... while the worm is not dead |
| ŕ⁻ | decrement ctr and implicitly print |

# Answer
> 0 votes
# Perl 5 `-pa`, 92 bytes

```
while(@F){++$\;my@a;if($b=pop@F){unshift@a,pop@F while$F[-1]>=$b;push@F,(@a,--$b)x($\+1)}}}{

```

Try it online!

# Answer
> 0 votes
# Stax, 31 bytes

```
àîz7αan♣óàNµK2☻₧⌡▐`Γl½f{♂♂_KZÖÄ

```

Run and debug it

---
Tags: code-golf, array, function
---


title: Sum of strings (UTF-16 codepoints)

text:
# Question
Title: Sum of strings (UTF-16 codepoints)
Your function must accept two strings and return new string where are UTF-16 code of all symbols is the sum of UTF-16 codes of inputs symbols

* If the resulting sum is greater than `65535` (maximum UTF-16 codepoint), take the sum modulo `65536`
* If there are more symbols in one string then sum with zero, codes of symbols which doesn't have pairs

For example:

* `'a' + 'b' = a(97) + b(98) = 97 + 98 = 195 => 'Ã'`
* `'A' + 'B' = A(65) + B(66) = 65 + 66 = 131 => '\u0083' (No Break Here)`
* `'Aa' + 'BbC' = [A(65) + B(66)][a(97) + b(98)][(0) + C(67)] => '\u0083ÃC'` \- `\u0083` will not be displayed but it must be here so the length of result string must be 3 not 2

**Test cases**:

```
'a', 'b' --> 'Ã'

'A', 'B' --> '\u0083'

'Aa', 'BbC' --> '\u0083ÃC'

'耀', '耀' --> '\u0000' (Null character)

'Программирование', 'Programming' --> 'ѯҲҭҚҲґҩҩҡҮҥвание'

```

Ungolfed version (check in real time):

```
const updateResult = () => {
  const string_1 = input1.value;
  const string_2 = input2.value;
  resultString = [];

  for (let i = 0; i < string_1.length || i < string_2.length; ++i) {
    resultString.push(
      (string_1.charCodeAt(i) || 0) +
      (string_2.charCodeAt(i) || 0)
    );
  }

  resultString = String.fromCharCode(...resultString);

  result.innerHTML = resultString;
  resultLength.innerHTML = 'Length: ' + resultString.length;
}

input1.addEventListener('input', updateResult);
input2.addEventListener('input', updateResult);

updateResult();
```

```
<input id="input1" value="aA"/>
<input id="input2" value="bB"/>

<br/><br/>

<div id="result"></div>
<div id="resultLength"></div>
```

The shortest code in each programming language wins!

# Answer
> 6 votes
# Excel, ~~92~~ 89 bytes

```
=CONCAT(
    TOCOL(UNICHAR(MOD(MMULT(IFERROR(UNICODE(MID(A1:B1,ROW(A:A),1)),),{1;1}),4^8)),2)
)

```

Inputs in cells `A1` and `B1`.

*Thanks to JvdV for the 3-byte save*.

# Answer
> 4 votes
# Vyxal, 6 bytes

```
C∑k₴%C

```

Try it Online!

**How it works**:

```
C∑k₴%C
C∑       Sum codepoints of each word
  k₴%    Push 65535 and modulo by each element
     C   Convert codepoints to words

```

# Answer
> 3 votes
# Japt, 11 bytes

Takes input as an array of 2 character arrays, outputs a single character array.

```
ÕËxc uG²² d

```

Try it

```
ÕËxc uG²² d     :Implicit input of 2D array
Õ               :Transpose
 Ë              :Map
  x             :  Sum of
   c            :    Codepoints
     u          :  Modulo
      G         :    16
       ²²       :    Squared twice
          d     :  Character at resulting codepoint

```

# Answer
> 3 votes
# Python, 89 bytes

```
lambda x,y:[chr(sum(map(ord,a))%4**8)for a in zip(f'{x:\0<{len(y)}}',f'{y:\0<{len(x)}}')]

```

Try it online!

-15 bytes thanks to @SevC\_10

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
0ζOžH%ç

```

Try it online!

#### Explanation

```
0ζOžH%ç  # 05AB1E automatically converts the strings
         # to codepoints since they are delimited by '
0ζ       # Transpose with filler 0
  O      # Sum each inner list
   žH    # Push 65536
     %   # Mod each value by 65536
      ç  # Convert back from codepoint to character

```

# Answer
> 3 votes
# , ~~30~~ ~~27~~ 25 bytes

```
(65536|+/@,:)&.(3 u:7&u:)

```

-3 thanks to ovs, and -2 more.

Attempt This Online!

```
(65536|+/@,:)&.(3 u:7&u:)
             &.            NB. u&.v applies v to both args and u to the results
                           NB. then applies the inverse of v to the results of u
               (3 u:7&u:)  NB. monadic fork
                    7&u:   NB. converts each char to a single unicode codepoint
                3 u:       NB. convert string to a list of codepoints
(65536|+/@,:)              NB. dyadic fork
          ,:               NB. stacks codepoint lists filling with 0s
       +/@                 NB. then sum the columns of the resulting table
 65536|                    NB. mod each sum by 65536
                           NB. inverse of v converts codepoints to chars

```

# Answer
> 3 votes
# Z80 machine language, 52 bytes

Null-terminated strings, addresses passed in `DE` and `HL`; output string address passed in `BC`. Little-endian.

```
D5 E5 7E 23 B6 23 EB 28 0A 7E 23 B6 23 EB 20 F4
37 E1 D5 30 03 EB C5 7E 02 23 03 B6 7E 02 23 03
20 F7 E1 1A 47 86 77 13 23 1A 4F 8E 77 13 23 78
B1 20 F2 C9

```

Disassembled:

```
f:
    push de         // D5
    push hl         // E5
wl:
    ld a,(hl)       // 7E       // test one wchar of each
    inc hl          // 23
    or (hl)         // B6
    inc hl          // 23
    ex de,hl        // EB
    jr z,fzero      // 28 0A
    ld a,(hl)       // 7E
    inc hl          // 23
    or (hl)         // B6
    inc hl          // 23
    ex de,hl        // EB
    jr nz,wl        // 20 F4
    scf             // 37       // if we have made it here, first was shorter
fzero:
    pop hl          // E1
    pop de          // D5
    jr nc,copy      // 30 03
    ex de,hl        // EB
copy:               //          when we get here, wstrlen(hl)>wstrlen(de)
    push bc         // C5
cl:
    ld a,(hl)       // 7E       // copy a byte
    ld (bc),a       // 02
    inc hl          // 23
    inc bc          // 03
    or (hl)         // B6       // or in the second to see if both 0
    ld a,(hl)       // 7E       // copy the second (preserves flags)
    ld (bc),a       // 02
    inc hl          // 23
    inc bc          // 03
    jr nz,cl        // 20 F7    // if either nonzero, loop again
    pop hl          // E1       // put dest in hl
aloop:
    ld a,(de)       // 1A
    ld b,a          // 47
    add (hl)        // 86
    ld (hl),a       // 77
    inc de          // 13       // *(hl++) += (b = *(de++)
    inc hl          // 23
    ld a,(de)       // 1A
    ld c,a          // 4F
    adc (hl)        // 8E
    ld (hl),a       // 77
    inc de          // 13
    inc hl          // 23       // *(hl++) += (c = *(de++)) + cf
    ld a,b          // 78
    or c            // B1
    jr nz,aloop     // 20 F2    // continue if b|c
    ret             // C9

```

# Answer
> 2 votes
# Python 3, 76 bytes

```
f=lambda a,b:a and b and chr(ord(a[0])+ord(b[0])&65535)+f(a[1:],b[1:])or a+b

```

Try it online!

# Answer
> 2 votes
# Raku, 61 bytes

```
{utf16(roundrobin(@_».encode('utf16'))».sum X%4⁸).decode}

```

Try it online!

(The older Raku version on TIO requires a ".new" after the first "utf16" for four additional bytes.)

* `@_` are the string arguments to the function.
* `».encode('utf16')` encodes each of those strings as a utf16 blob object.
* `roundrobin` combines corresponding elements of those blobs as lists, like `zip`, but doesn't stop when the end of the shortest input is reached. `roundrobin <1 2>, <3 4 5 6>` returns `(1 3), (2, 4), (5,), (6,)`.
* `».sum` converts each of those zipped lists to its sum.
* `X% 4⁸` takes each of those sums modulo 65536. (`4⁸` is one byte shorter than `65536`.)
* `utf16` converts that list of integers to a utf16 blob.
* `.decode` converts that blob into a string.

# Answer
> 1 votes
# JavaScript, 91 bytes (tsh's method)

With recursion

```
(a,b)=>(g=i=>a[i]?String.fromCharCode(a[c='charCodeAt'](i)+~~b[c](i))+g(i+1):b.slice(i))(0)

```

Try it:

```
f=(a,b)=>(g=i=>a[i]?String.fromCharCode(a[c='charCodeAt'](i)+~~b[c](i))+g(i+1):b.slice(i))(0)

const inputHandler = () => {
  resultString = f(input1.value, input2.value)

  result.innerHTML = resultString;
  resultLength.innerHTML = 'Length: ' + resultString.length;
}

input1.addEventListener('input', inputHandler);
input2.addEventListener('input', inputHandler);

inputHandler();
```

```
<input id="input1" value="aA"/>
<input id="input2" value="bB"/>

<br/><br/>

<div id="result"></div>
<div id="resultLength"></div>
```

# JavaScript, 97 bytes

Without recursion

```
(a,b)=>String.fromCharCode(...[...a].map((s,i)=>(g=c=>c.charCodeAt(j=i)|0)(a)+g(b)))+b.slice(j+1)

```

Try it:

```
f=(a,b)=>String.fromCharCode(...[...a].map((s,i)=>(g=c=>c.charCodeAt(j=i)|0)(a)+g(b)))+b.slice(j+1)

const inputHandler = () => {
  resultString = f(input1.value, input2.value)

  result.innerHTML = resultString;
  resultLength.innerHTML = 'Length: ' + resultString.length;
}

input1.addEventListener('input', inputHandler);
input2.addEventListener('input', inputHandler);

inputHandler();
```

```
<input id="input1" value="aA"/>
<input id="input2" value="bB"/>

<br/><br/>

<div id="result"></div>
<div id="resultLength"></div>
```

# Answer
> 1 votes
# Factor, 38 bytes

```
[ 0 pad-longest [ + 65536 mod ] 2map ]

```

Try it online!

* `0 pad-longest` pad the shorter of two sequences with 0s until it is the same length as the longer one
* `[ ... ] 2map` map over two sequences with a binary function
* `+ 65536 mod` add the code points together modulo 65536

# Answer
> 1 votes
# Charcoal, 37 bytes

```
Ｆ²⊞υＳＵＭυ⁺ι×ψ⁻Ｌ§υ¬ιＬι⭆⊟υ℅﹪⁺℅ι℅§ΣυκＸ⁴¦⁸

```

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

```
Ｆ²⊞υＳ

```

Input the two strings.

```
ＵＭυ⁺ι×ψ⁻Ｌ§υ¬ιＬι

```

Pad the shorter to the length of the longer with null bytes.

```
⭆⊟υ℅﹪⁺℅ι℅§ΣυκＸ⁴¦⁸

```

Pairwise add the character codes of the two strings, reduce module `4⁸`, then convert back to characters.

# Answer
> 1 votes
# Brachylog, 15 bytes

```
ạᵐz₁+ᵐ%₆₅₅₃₆ᵐ~ạ

```

Try it online!

### Explanation

```
ạᵐ               Map to codes
  z₁             Zip without cycling
    +ᵐ           Map sum
      %₆₅₅₃₆ᵐ    Map mod 65536
             ~ạ  Codes to string

```

# Answer
> 1 votes
# C (gcc) with `-fwide-exec-charset=UTF16LE`, 78 bytes

Takes inputs in UCS-2 (UTF-16LE) encoding and outputs in UCS-2 (UTF-16LE) encoding. TIO and shells don't seem to like UTF-16: running this from an actual machine and redirecting the output gives the correct results.

Output (in KWrite, UTF-16 encoding):

```
f(i,j,k)short*i,*j;{for(;*i|*j;*i&&i++,*j&&j++)printf("%2$c%c",k>>8,k=*i+*j);}

```

Try it online!

# Answer
> 1 votes
# CJam, 9 bytes

```
z::i::+:c

```

Try it online!

# Explanation

```
z::i::+:c # a function taking an array with two strings [x y]
z         # zip; transpose rows with columns (i.e, ["Aa" "BbC"] => ["AB" "ab" "C"]
 ::i      # map `i`nt convert to all values
    ::+   # map add to all values, effectively summing each
       :c # map each summed value to `c`hars

```

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


title: Bubbler numbers

text:
# Question
Title: Bubbler numbers
## Background

My user ID is 78410, or \\$1 0 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0\_2\\$. One interesting property of this number is that, in binary,

* it doesn't have three consecutive identical digits, and yet
* it has a substring \\$100100100\\$ which is three copies of \\$100\\$.

So, I define a **Bubbler number** as a positive integer whose binary representation satisfies the following:

* it doesn't have three consecutive identical digits (so it is a member of A063037), and
* it contains a substring which is three consecutive copies of some nonempty string (so it is NOT a member of A286262).

## Task

Given a positive integer as input, determine if it is a Bubbler number.

You can use truthy/falsy values in your language or two distinct values to indicate true/false respectively.

There are 55 Bubbler numbers under 1000:

```
42 84 85 106 149 169 170 171 212 213 292 298 299 338 339 340 341 342 362 365
405 425 426 427 438 585 596 597 598 618 658 661 676 677 678 681 682 683 684 685
724 725 730 731 804 810 811 850 851 852 853 854 874 876 877

```

Standard rules apply. The shortest code in bytes wins.

# Answer
# Brachylog, 10 bytes

```
ḃsᶠ~j₃ˢlⁿ1

```

Try it online!

This was meant to only be a partial solution, but it turns out that  fails on empty inputs.

```
  ᶠ           Find every
 s            substring of
ḃ             the input's binary digits,
      ˢ       then for each substring
   ~j₃        map it to the string which it is three copies of
      ˢ       (ignoring and discarding it if there is no such string).
        ⁿ     For none of those strings (of which there is at least one)
       l      is its length
         1    1.

```
> 8 votes

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

```
bŒʒ3ä1ìË}{нË

```

Outputs `0` for truthy and `1` for falsey.

Try it online or verify some more test cases.

**Explanation:**

```
b         # Convert the (implicit) input to a binary-string
 Œ        # Take all substrings of the binary-string
  ʒ       # Filter it by:
   3ä     #  Split the substring into 3 equal-sized parts
     1ì   #  Prepend a 1 to each part
       Ë  #  Check that the three parts are equal
          #  (the prepend 1 is necessary, because ["01","01","1"] would be truthy,
          #   since strings and integers are interchangeable in 05AB1E)
  }{      # After the filter: sort all remaining substrings
          # (this causes any "000" and/or "111" to be leading)
    н     # Pop and push the first substring (or "" if none are left)
     Ë    # Check if all characters in this string are equal (also truthy for "")
          # (after which the result is output implicitly)

```
> 7 votes

# Answer
# Python 2, ~~64 63 61~~ 58 bytes

```
f=lambda n,i=2:[n>i>0<f(n,i+1),i>3][3*bin(i)[3:]in bin(n)]

```

Try it online!

A recursive function that returns `True` if the number is a Bubbler number, and `False` otherwise.

Generates all possible binary string, then for each binary string checks if `n` contains 3 consecutive copies of that string.

The binary strings are generated by evaluating `bin(i)[3:]` for \\$i\\$ from \\$2\\$ to \\$n-1\\$. The slice `[3:]` gets rid of the first 3 characters in the binary representation of \\$i\\$, which are always `0b1`. This allows us to generate binary strings that has leading 0.
> 7 votes

# Answer
# JavaScript (ES6),  ~~54~~  49 bytes

*Saved 5 bytes thanks to @l4m2!*

```
n=>/^(?!.*(.)\1\1).*(.+)\2\2/.test(n.toString(2))

```

Try it online!

### Regular expression

```
/^(?!.*(.)\1\1).*(.+)\2\2/
 ^                         // match the beginning of the string
  (?!         )            // must NOT be followed by:
       (.)                 //   a single character
     .*                    //   appearing anywhere
          \1\1             //   immediately followed by 2 copies of itself
                           // must also match:
                 (.+)      //   a string
               .*          //   appearing anywhere
                     \2\2  //   immediately followed by 2 copies of itself

```

---

# JavaScript (ES6), 55 bytes

This version uses a helper function to test `/(.+.)\1{2}/` and `/(.)\1{2}/` separately.

```
n=>(g=p=>n.toString(2).match(p+".)\\1{2}"))`(.+`&&!g`(`

```

Try it online!
> 7 votes

# Answer
# Jelly, 10 bytes

```
BẆẋ3ẇɗƇ$ḢḊ

```

A monadic Link accepting a positive integer which yields a list - in Jelly an empty list (non-Bubbler) is falsey while a non-empty list is truthy (Bubbler).

**Try it online!** Or see the test-suite (identifying all Bubbler numbers in \\$\[1..1000\]\\$).

### How?

```
BẆẋ3ẇɗƇ$ḢḊ - Link: positive integer, n
B          - convert n to binary (say b)
       $   - last two links as a monad - f(b):
 Ẇ         -   all sublists (say s) - Note these are sorted from shortest to longest
      Ƈ    -   filter keep those x of s which are truthy under:
     ɗ     -     last three links as a dyad - f(x, b):
   3       -       three
  ẋ        -       repeat (e.g. [1,0] -> [1,0,1,0,1,0])
    ẇ      -       is a sublist of (b)?
        Ḣ  - head (given an empty list this yields 0)
         Ḋ - dequeue

```
> 4 votes

# Answer
# K (ngn/k), 46 bytes

```
{(*/0<3!+/+3':x)>*/^a?,/'3#','a:,/,\'|',\x}@2\

```

Try it online!

`2\` binary encode

`{` `}@` apply function

first condition:

* `,/,\'|',\x` all substrings of the argument, i.e. prefixes (`,\`), reverse each (`|'`), prefixes each (`,\'`), raze (`,/`)
* `a:` assign to `a`
* `,/'3#','` triplicate each, i.e. enlist each (`,'`), 3-reshape each (`3#'`), raze each (`,/'`)
* `a?` find - indices in `a`, or nulls (`0N`) for not found
* `^` is null?
* `*/` all

second condition:

* `3':` sliding window of size 3
* `+` transpose
* `+/` sum
* `3!` mod 3
* `0<` positive?
* `*/` all

`>` and not (between the two conditions)
> 4 votes

# Answer
# APL (Dyalog 18.0), ~~34~~ 33 bytes

```
⊃1<∘⍸⊢{∨/⍺⍷⍨∊3/⊂1↓⍵}Ö(2∘⊥⍣¯1)¨2↓⍳

```

Try it online!

This uses `⎕IO←0` and the Over operator (, which was added in 18.0). The current version on TIO is 17.1, so it's been implemented manually (thanks Bubbler!). I think this does well for a non-regex answer.

### Explanation

```
                              2↓⍳     ⍝ The range 2 to n-1
     ⊢               (2∘⊥⍣¯1)         ⍝ Convert this range and the input to base 2
      {∨/⍺⍷⍨∊3/⊂1↓⍵}Ö        ¨        ⍝ Before applying the function to each
                1↓⍵                   ⍝ Drop the first 1 of the binary number
           ∊3/⊂                      ⍝ Repeat the list 3 times and flatten
       ∨/⍺⍷⍨                          ⍝ Is this sublist in the binary input?
⊃   ⍸                                 ⍝ Is the index of the first element
 1<∘                                  ⍝ Greater than one?

```
> 4 votes

# Answer
# Bash \+ Unix utilities, 44 bytes

```
dc -e2o?n|egrep -v 000\|111|egrep '(.+)\1\1'

```

Try it online!

Input is on stdin, and the output is the exit code (0 for truthy, 1 for falsey, as usual with shell scripts).

Or verify the Bubbler numbers under 1000.
> 3 votes

# Answer
# perl -M5.010 -n, 45 bytes

```
$_=sprintf"%b",$_;say!/(.)\1\1/&&!!/(.+)\1\1/

```

Try it online!

Turns the input into a string with the binary representation of the number, applies regexes to test the requirements, then prints 1 or an empty string accordingly. Two bytes (the `!!`) could be saved if there wasn't a restriction for two distinct values -- without them, for bubbly numbers, it prints the thrice repeated string.
> 3 votes

# Answer
# Husk, 9 bytes

```
tṠḟ·€*3Qḋ

```

Returns a list, which is nonempty iff the input is a Bubbler number. In Husk, empty lists are falsy and nonempty lists are truthy.

Try it online!

## Explanation

```
tṠḟ·€*3Qḋ   Implicit input: a number, say n=84.
        ḋ   Binary representation: [1,0,1,0,1,0,0]
       Q    Sublists: [[1],[0],[1,0], …, [1,0,1,0,1,0,0]]
  ḟ         Find the first one that satisfies this (or an empty list if none do):
              Example list: [1,0]
     *3       Repeat three times: [1,0,1,0,1,0]
 Ṡ ·€         It occurs in the list of sublists: yes.
            Result: [1,0]
t           Remove the first element: [0], truthy.

```

The correctness of this program relies on the fact that `Q` enumerates the sublists in a "good" order (all sub-sublists of a sublist occur in the result before the sublist itself) and  returns the first match it finds. If 000 occurs in the binary representation, then \[0\] is listed before any longer triply repeated sublist (unless that sublist consists of only 1s, in which case \[1\] is listed before it).
> 3 votes

# Answer
# Jelly, ~~14~~ ~~13~~ ~~12~~ ~~11~~ 10 bytes

```
BẆẋ3eɗƇ`ḢṖ

```

Try it online!

*The third -1 takes some inspiration from Kevin Cruijssen's 05AB1E solution.*

*Fourth -1 thanks to Jonathan Allan reminding me of Jelly's truthiness semantics.*

Outputs truthy or falsy.

```
 Ẇ            Every substring of
B             the input's binary digits.
      Ƈ       Filter them by
  ẋ3 ɗ        repeated three times
    e         membership in
BẆ     `      every substring of the input's binary digits.
         Ṗ    Is there more than one element to remove from
        Ḣ     the first (i.e., shortest) of the filtered substrings?

```
> 2 votes

# Answer
# Retina 0.8.2, 44 bytes

```
.+
$*
+`(1+)\1
$+0
01
1
A`000|111
1`(.+)\1\1

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary

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

```

Convert to binary.

```
A`000|111

```

Delete the string if it contains `000` or `111` (`A`(.)\1\1` also works for the same byte count).

```
1`(.+)\1\1

```

Check whether there are three consecutive substrings.
> 1 votes

# Answer
# T-SQL, 258 bytes

Added some line changes to make it readable

```
DECLARE @ char(99)=''
WHILE @i>0
SELECT @=left(@i%2,1)+@,@i/=2;
WITH C as(SELECT number+1n FROM spt_values WHERE'P'=type)
SELECT count(*)FROM C,C D
WHERE not(@ like'%000%'or @ like'%111%'or len(@)<D.n*3+C.n+2)
and @ like'%'+replicate(substring(@,C.n,D.n+1),3)+'%'

```

Returns 1 or more for true, 0 for false

**Try it online**
> 1 votes

# Answer
# Charcoal, 28 bytes

```
≔⍘Ｎ²θ¿⬤01¬№θ×ι³⊙θΦκ№θ×³✂θλ⊕κ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:

```
≔⍘Ｎ²θ

```

Input the number and convert it to base 2 as a string.

```
¿⬤01¬№θ×ι³

```

Test whether neither digit `0` nor `1` appears triplicated in the string.

```
⊙θΦκ№θ×³✂θλ⊕κ

```

Check whether any nontrivial substring appears triplicated. (I use `Φ` instead of a second  since Charcoal doesn't currently accept an implicit range there, but the effect is the same.)
> 1 votes

# Answer
# C (gcc), ~~124~~ ~~120~~ ~~114~~ 113 bytes

```
b,c,i,j;f(a){for(b=c=1;a;a/=2)for(b&=a&7^7&&a&7,i=~3,j=1;++j<11;i*=2)c&=~i&(a>>j^a|a>>j*2^a)||!(a>>j*3-1);b&=!c;}

```

Try it online!

~~-4~~ -5 bytes: ceilingcat
> 1 votes

# Answer
# Raku, 37 bytes

```
{.base(2)~~/(.+)$0$0/&none /(.)$0$0/}

```

Try it online!

This matches the base-2 representation of the input number against the junction

```
/(.+)$0$0/ & none /(.)$0$0/

```

...which succeeds if it matches the first pattern, but not the second one.
> 1 votes

# Answer
# Vyxal, 11 bytes

```
bṅÞS'3/≈;h≈

```

Try it Online! or get all the Bubbler numbers up to a given number.

Port of Kevin Cruijssen's 05AB1E answer. Outputs \\$0\\$ for truthy and \\$1\\$ for falsy.

#### Explanation

```
bṅÞS'3/≈;h≈   # Implicit input
bṅ            # Input as a binary string
  ÞS          # All substrings
    '   ;     # Filtered by:
     3/       #  Split into three parts
       ≈      #  All equal?
         h    # First item
          ≈   # All equal?
              # Implicit output

```
> 1 votes

# Answer
# Ruby, 42 bytes

```
->n{n.to_s(2)=~/^(?!.*(.)\1\1).*(.+)\2\2/}

```

Try it online!

### How it works:

```
->n{
  n.to_s(2)      # convert to binary representation string
  =~ /           # check if it matches regex
  ^(?!.*(.)\1\1) # (from the start) assert that there are no 3
                 # repeated characters anywhere in the string
  .*             # skip any number of characters
  (.+)\2\2/      # check that there is a sequence of 1 or more
                 # characters repeated 3 times (note that there
                 # are no 3 repetitions of a single character so
                 # the 1 case is irrelevant (equivalent to ..+))
}

```

*squints eyes*
"regex..."
> 0 votes

# Answer
# PowerShell Core, 74 bytes

```
($s=[Convert]::ToString("$args",2))-notmatch'(.)\1\1'*($s-match'(.+)\1\1')

```

Try it online!
> 0 votes

---
Tags: code-golf, number, decision-problem, binary
---


title: Generate number from given range

text:
# Question
Title: Generate number from given range
Your function must accept three numbers in any order:

* A signed real number (or `±Infinity`) - The number (`N`) for which you have to generate a number from the range
* A signed integer - Minimum of the range
* A signed integer - Maximum of the range

**Input**:

* The minimum of the range will always be less than the maximum of the range, so don't worry about it
* `N` can be any real (if it is possible `Infinity` and `-Infinity` also can be passed)

**Requirements**:

* Your function must output same result each time for same inputs
* Your function must output different result each time for different `N` (except when it's due to a floating point error)
* The output must be in the given range
* The outputs of your function for all numbers `N` must cover the entire range (except when missing outputs are due to floating point error)

**Please specify**:

* The order of the input
* Is it possible to pass `±Infinity` as a `N`?
* Are the minimum and maximum of the range inclusive or exclusive?

Unable to provide test cases because there are many ways to solve this problem, so please provide your test cases.

The shortest code in each programming language wins!

# Answer
> 6 votes
# Python, 29 bytes

```
lambda a,b,c:a+(b-a)/(1+2**c)

```

Attempt This Online!

Does not include the upper bound.

Uses the mapping $$f(c) = \frac{a-b}{1+2^c}+a$$

An interactive graph of what this looks like:

# Answer
> 4 votes
# Wolfram Language (Mathematica), 33 bytes

```
N@Rescale[#1,{-∞,∞},{#2,#3}]&

```

Try it online!

Mathematica easily operates with infinities both signs, so here it is. For input infinite values you can use `\[Infinity]` or  with sign.

# Answer
> 3 votes
# Thunno, \\$ 10 \log\_{256}(96) \approx \\$ 8.21 bytes

```
-s2@1+/A$+

```

Port of 97.100.97.109's Python answer

Attempt This Online!

```
-s2@1+/A$+ # stack is min, max, wind
-          # subtract
 s         # swap, wind is on top
  2@       # 2 ^ wind
    1+     # add one
      /    # divide (max-min) by (1 + 2^wind)
       A$+ # add the first input

```

## Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.93 bytes

```
-DZs*$

```

Attempt This Online!

This uses the formula `((b - a) * c) % (b - a)`, where a is the minimum of the range, b is the maximum of the range, and c is the wind. I noticed after posting this that the formula doesn't really work though.

```
-DZs*$ # stack is min, max, wind
-      # subtract
 D     # duplicate
  Zs   # swap bottom two
    *  # multiply
     $ # swapped modulus

```

# Answer
> 3 votes
# , 31 bytes

```
\(w,a,b)(.5+atan(w)/pi)*(b-a)+a

```

Attempt This Online! or Try it at rdrr.io with graphical output

# Answer
> 2 votes
# Pyt, 14 bytes

```
Ť←←Đ3Ș⇹-⇹↔⁺₂*+

```

Try it online!

Takes inputs as `c b a` (each on their own line)

Uses `tanh` as the mapping function

```
Ť                       implicit input (c); Ťanh(c)
 ←←                     get input twice (b, then a)
   Đ                    Đuplicate a
    3Ș                  Șwap top three items of stack
      ⇹                 swap top two on stack
       -                subtract (b-a)
        ⇹               swap top two on stack
         ↔              flip the stack
          ⁺             increment [tanh(c)+1]
           ₂            halve [(tanh(c)+1)/2]
            *           multiply [(b-a)*(tanh(c)+1)/2]
             +          add [a+(b-a)*(tanh(c)+1)/2]; implicit print

```

# Answer
> 1 votes
# Charcoal, 13 bytes

```
ＮθＩ⁺θ∕⁻Ｎθ⊕Ｘ²Ｎ

```

Try it online! Link is to verbose version of code. Explanation: Another port of @adam's Python answer.

```
Ｎθ              First input as a number
       Ｎ        Second input as a number
      ⁻         Minus
        θ       First input
     ∕          Divided by
           ²    Literal integer `2`
          Ｘ     Raised to power
            Ｎ   Third input as a number
         ⊕      Incremented
   ⁺            Plus
    θ           First input
  Ｉ             Cast to string
                Implicitly print

```

Originally this was meant to be based on @KiptheMalamute's answer, so I started with:

$$ f(c) = a + \frac {2(b - a)} {1 + \tanh c} $$

Charcoal doesn't have hyperbolic (or indeed trigonometric) functions, so I rewrote this in terms of the exponential function:

$$ f(c) = a + \frac {b - a} {1 + e ^ {-2 c}} $$

But there's no particular reason to use \\$ e^{-2} \\$; any base will do, such as \\$ 2 \\$, which is much golfier:

$$ f(c) = a + \frac {b - a} {1 + 2 ^ c} $$

---
Tags: code-golf, number, open-ended-function
---


title: Tips for golfing in Jelly

text:
# Question
Title: Tips for golfing in Jelly
Jelly is a tacit, golf-oriented programming language by our very own Dennis. It’s popping up in answers here more and more often, beating other golf-y languages like Pyth and CJam, both by using its own code page and its powerful *chain* system to succinctly express programs.

Let’s collect some useful tips for golfing in Jelly. (As always, one tip per answer, please!)

# Answer
# String compression

> If you're looking for a more optimized/automatic string compressor, try **this one**.

Try it online!

A compressed string looks like `“...»`, where the dots are a chunk of base-250-encoded data. The decompression algorithm is a bit complicated: the chunk is interpreted as a “mixed-base” integer, with `divmod` breaking off various parts of this integer and constructing a string out of them.

I’ve created a little Python 3 interface to compress Jelly strings:

```
import dictionary
code_page = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''

class Compress(list):
    def character(self, c):
        if c in '\n\x7f¶':
            o = 95
        elif ' ' <= c <= '~':
            o = ord(c)-32
        else:
            raise ValueError(c + " is neither printable ASCII nor a linefeed.")
        self += [lambda z: 3*z+0, lambda z: 96*z+o]; return self
    def string(self, s):
        for c in s: self.character(c)
        return self
    def dictionary(self, w):
        ts = bool(self)
        if w[:1] == ' ': w = w[1:]; ts = not ts
        dct = dictionary.short if len(w) < 6 else dictionary.long
        W, sc = (w, 0) if w in dct else (w[:1].swapcase() + w[1:], 1)
        if W not in dct: raise ValueError(w + " isn't in the dictionary.")
        f = ts or sc; j = (2 if sc else 1) if ts else 0; i = dct.index(W)
        self += [lambda z: 3*z+2, lambda z: 3*z+j] if f else [lambda z: 3*z+1]
        self += [lambda z: 2*z+int(len(w) < 6), lambda z: len(dct)*z+i]
        return self
    def go(self):
        compressed = []; z = 0
        for f in self[::-1]: z = f(z)
        while z:
            c = z % 250
            if c == 0: c = 250
            z = (z - c) // 250
            compressed.append(code_page[c - 1])
        return '“{0}»'.format(''.join(compressed[::-1]))

```

Use the compressor as follows.

```
print(Compress()
      .dictionary('public')
      .dictionary(' static')
      .dictionary(' boolean')
      .string(' is')
      .dictionary('Power')
      .string('Of')
      .dictionary('Ten')
      .string('(')
      .dictionary('long')
      .dictionary(' input')
      .string(') {\n ')
      .dictionary(' return')
      .string('\n   ')
      .dictionary(' input')
      .string(' ==')
      .go())

```

`Compress` is a string builder:

* `.string(s)` will insert raw, printable ASCII characters into the string.

**(Each character costs about 0.827 compressed bytes.)**
* `.dictionary(w)` will look up a string in Jelly’s built-in dictionaries. You may begin the string with a single space, if you want one. If this needs to deviate from the normal string-adding behavior, or flip the capitalization of a dictionary word, it’ll add flags accordingly.

**(Costs about 1.997 bytes for short words, 2.433 bytes for long words; if there are flags, add 0.199 bytes.)**
> 35 votes

# Answer
> *This is part of what became the Jelly wiki tutorial.*

# Chains

(This is sort of a follow-up to **Tacit programming**.)

How does Jelly evaluate a chain? As explained before, there are three cases to consider: whether this chain was called *niladically*, *monadically*, or *dyadically*.

---

## 1. Niladic chains

These are the easiest of the bunch. To evaluate a niladic chain that *starts* with a nilad, like `α f g h`, evaluate the monadic chain `f g h` at that nilad `α`. (Caveats: if the whole chain is empty, 0 is returned instead. If `α` *isn’t* a nilad, replace use `α=0` instead.)

For example,  is just `½` evaluated at `4`, which is `2`.

---

## 2. Monadic chains

Monadic chains are broken down from left to right, until there are no links left to consider. Also, we’re passed some argument `ω` here. There are two questions to answer:

### What’s the starting value for this left-to-right evaluation?

* If our chain starts with a nilad `α`, and is followed by zero or more monads (like `½`), dyad-nilad pairs (like `+2`), and nilad-dyad pairs (like `4*`): we start by evaluating `α`, and then consider the rest of the chain.
* Otherwise, we start from the argument passed to this chain, `ω`, and consider the entire chain.

### How do we walk down the chain?

Let’s call `V` the current value – initially, it’s the value described above, but it gets update as we go through the chain – and denote

* nilads using digits,
* monads using lowercase letters,
* dyads using operator symbols `+`, `×`, `÷`.

Then the following patterns are matched against, from top to bottom:

```
                                 ┌───────────┬─────────┐
                                 │ old chain │ new V   │
                                 ╞═══════════╪═════════╡
                                 │ + × 1 ... │ (V+ω)×1 │ *
                                 │ + f ...   │ V+f(ω)  │
                                 │ + 1 ...   │ V+1     │
                                 │ 1 + ...   │ 1+V     │
                                 │ + ...     │ V+ω     │
                                 │ f ...     │ f(V)    │
                                 └───────────┴─────────┘
      (* Only if `...` consists of monads, dyad-nilad pairs, and nilad-dyad pairs.)

```

> Let’s try this out on the chain `+²×`.
>
> * `+` isn’t a nilad, so we start out at `V = ω`.
> * Then, we chop off , matching the second pattern, and get `V = ω+ω²`.
> * Then, we chop off `×`, matching the fifth pattern, and get `V = (ω+ω²)×ω`.
> * The chain is now empty, so `(ω+ω²)×ω` is our final result.

---

## 3. Dyadic chains

These are basically like monadic chains, but this time, there are two arguments, `λ` (left) and `ρ` (right).

### What’s the starting value?

* If the chain starts with three dyads like `+ × %`, we start at `λ+ρ`, and consider the chain `× % ...` next.
* Otherwise, we start from `λ`, and consider the entire chain.

### How do we walk down the chain?

This time, the patterns are

```
                                 ┌───────────┬─────────┐
                                 │ old chain │ new V   │
                                 ╞═══════════╪═════════╡
                                 │ + × 1 ... │ (V+ρ)×1 │ *
                                 │ + × ...   │ V+(λ×ρ) │
                                 │ + 1 ...   │ V+1     │
                                 │ 1 + ...   │ 1+V     │
                                 │ + ...     │ V+ρ     │
                                 │ f ...     │ f(V)    │
                                 └───────────┴─────────┘
      (* Only if `...` consists of monads, dyad-nilad pairs, and nilad-dyad pairs.)

```

> Let’s try this out on the chain `+×÷½`.
>
> * The chain starts with three dyads, so we start at `V = λ+ρ`, and throw away the `+`.
> * Then, we chop off `×÷`, matching the second pattern, and get `V = (λ+ρ)×(λ÷ρ)`.
> * Then, we chop off `½`, matching the sixth pattern, and get `V = sqrt((λ+ρ)×(λ÷ρ))`.
> * The chain is now empty, so we’re done.
> 22 votes

# Answer
## Special-cased numeric values

Here are some special cases for Jelly's numerics parser:

* `-` evaluates to `-1`
* `.` evaluates to `0.5`
* `ȷ` evaluates to `1000` (`ȷ` is for scientific notation, e.g. `2ȷ6` is `2000000`)
* `ı` evalulates to `1j` (`ı` is for complex numbers, e.g. `2ı3` is `2+3j`)

It's also worth noting that something like  is actually `4+1j`, rather than `4`.

You can mix and match these, e.g.:

* `-.` is `-0.5` and  is `-1000`
* is `-1+1j`, `ı-` is `-1j` and `-ı-` is `-1-1j`
* is `500.0`
* is `0.5+1j`, `ı.` is `0.5j` and `.ı.` is `0.5+0.5j`
* `ȷı` is `1000+1j`, `ıȷ` is `1000j` and `ȷıȷ` is `1000+1000j`

Note that `ȷ-` is `0.1`, but that doesn't save any bytes over `.1`. Then there's also the following, which can already be done in the corresponding number of bytes by using the builtin variable for 10 (), but might be useful in the rare case that the builtin is unavailable or to save on needing to use `¤`:

* `ȷ.` is `sqrt(10) ~ 3.162277`, `.ȷ.` is `sqrt(10)/2 ~ 1.5811` and `ȷ-.` is `1/sqrt(10) ~ 0.31162`
> 18 votes

# Answer
# Optimal string compressor

Recently I asked *Erik the Outgolfer* to add the optimized string compressor to JHT references page, but they said that

> sorry, but that compressor doesn't seem to be fully implemented
> it says `“ugtestslug”` is the shortest possible for `ugtestslug`, while `“#ṀȮụḄPƇ»` also does the job

So I decide to implement the optimal string compressor.

Simple approach, but guarantee to find the smallest possible value (and hence byte count)

Take input from `stdin`, output to `stdout`. Just like the original compressor,  or  (literal newline character) can be entered as newline.

Trying to run it with a lot of punctuation (for example, input `¶-----¶`) will output the uncompressed string.

**Of course, a lot of credit for this goes to Lynn for creating the original compressor.**
> 17 votes

# Answer
# Optimised string compressor

Try it online!

Lynn's post details what compressed strings are exactly, along with having a compressor that will produce these compressed strings. However, while tinkering around with a program in Jelly, I found it tiring to have to combine `.dictionary` and `.string` along with the correct placements of spaces and so on and so forth, in order to achieve the shortest possible string.

Therefore I decided to create an extension to Lynn's script that would take user input, and find the shortest way it can be compressed without the user having to do any work. The script is quite long, and so I've added in a TIO link, rather than the code itself.

The way the program works is by compressing using 3 different methods and determining which is shortest:

1. Method 1 simply encodes each byte of the input at a time, which tends to produce the longest result, as compared to the others. Even when the input is very short, it still manages to create rather long alternatives. For example, the shortest way that `test` can be compressed is `“¡ḌY»`, whereas this method returns `“¡⁷ƑKʂ»` (2 bytes longer). As a general rule, this only works if the string is less than 4 characters long
2. The second method breaks the string into words and punctuation, as the two are added to the compressor in different ways. Words that are part of the dictionary are added with the `.dictionary` method of Lynn's code, which compresses them more than if they were simply added by code points. Punctuation however has to be added by code point as, unfortunately, they aren't part of the dictionary.

Punctuation includes spaces, which is where method number 3 comes into play, but first and evaluation of method 2: let's compare methods one and two compressing the string `Hello, World!` (contains words, punctuation and spaces, so is perfect). Compressing character by character results in the final string of `“ŒCdẉa÷¹ṂȤƓ(Ẋ)»` (15 bytes long), which, as it turns out, is longer than the easier way to output Hello, World!: `“Hello, World!`. Now lets take a look at method two. This produces the compressed string `“Ọƥ⁷Ƭė3⁶»` which weighs in at 9 bytes, a great improvement over the old one. However, the shortest Hello, World! program in Jelly is 8 bytes, so something can be improved
3. Here comes method 3, making it even shorter. As expected, output for Hello, World is, of course, `“3ḅaė;œ»` which is the shortest possible program. So what does method 3 do, that method 2 doesn't? Method 3 combines lone spaces into leading spaces, which the Jelly decompressor has a flag for. In the code for both the compressor and the decompressor, you can see code like `if flag_space: word = ' ' + word`, showing that leading spaces are a) supported and b) byte-saving. Therefore, the string splitter from method two is adapted so that spaces by themselves are combined into the string directly after is, to create leading strings. This means that `Hello, World!` is parsed as `["Hello", ",", " World", "!"]`, which when compressed is only 6 bytes (8 when including delimiters). This is almost always the shortest method of compression, excluding the "extension" I added,

This is the bulk of the program, but there are a few more options that help it compress data even more.

* The program checks whether or not each compressed version is correct, by using Dennis' sss decompressor that Jelly uses (go straight to the source)
* You can see all different compressed strings by making the first command line argument `--debug`, which, rather than simply showing the shortest compressed string, shows all 3 along with a "This is the shortest" copy
* The program handles "non-words"

## Non-words

I started work on Lynn's compressor after seeing this message, took a crack at it and got frustrated at the fact that I couldn't find the shortest way to compress it (it's 29 or 32 bytes for the record). However, while testing my improvements, I found that words such as `knowns` aren't in Jelly's dictionary. Therefore, I set out to find a way to compress these "non-words" in the shortest Jelly code possible.

I created a function (`trim`) that splits the string as a point where at least one of the parts of the string are words. For example `knowns` would be split into `["known", "s"]` and have the program add the first word via a dictionary add (`.dictionary`) and the second part of the word via a `.string` call. But this still leaves two edge cases: strings which have no words in them (such as `ajdl`) and non-words which have words at the end, such as `abctest`, which wouldn't get split by the `trim` function.

As there is no way of finding words in a string which has no words in it, the simplest and shortest way to handle these is by adding them in character by character via a `.string` call. So `ajdl` would get added by `.string('ajdl')`. Whereas non-words which end with recognised words, essentially implements the trimmer but in reverse, and applying `.dictionary` and `.string` the other way round to the forwards trimmer.

As it turns out, trimming the string, either from the start or the end is, of course, shorter than adding each character to the compressor, as demonstrated by an input of `abctest this string`, which produces a debug output of

```
Original        : abctest this string

Optimised       : “¡J+v(p⁸ụƘ$,»
Seperate spaces : “Ç⁴ṭḍµḄ7oeṂdḷp»
No trimmer      : “¤ɦ?Ɓ¢#fḲOạ⁾¶ɼȥƬ»
All characters  : “µẓþ"Y7_ḣṗḢ))9Þ⁴⁺Ẉ²)ɱ»
Non-compressed  : “abctest this string
Shortest        : “¡J+v(p⁸ụƘ$,»
=====

```

The different between the optimal output (which uses the trimmer) and the one which doesn't is a whopping (for Jelly) 4 bytes. Finally, there are occasions where the string itself is shorter than any compressed version, which has now been factored in.

**Of course, a lot of credit for this goes to Lynn for creating the original compressor**
> 15 votes

# Answer
You can use superscript three to nine (`³⁴⁵⁶⁷⁸⁹`) to golf some usually used values, but this depends on the amount of command line arguments, and in case of links, on the arguments of the links.

* `³` returns 100, and works only if there's no input.
* returns 16, and works only if there's at most one input.
* returns 10, and works only if there's at most two inputs.
* returns a space if there's at most three inputs.
* returns a new line if there's at most four inputs.

If there are five inputs, however, you're out of luck.

Recently, a new version of the language lowered the value of `³` to 100, and introduced some new atoms that return values or (for links) their arguments.

* returns a blank list everywhere except links which have a left argument passed to them.
* returns 256 everywhere except links which have a right argument passed to them.

If you're in a link, and have arguments from both sides passed to it, however, you're out of luck.
> 12 votes

# Answer
# Abuse string bugs

*Credits go to Adnan for taking advantage of this first in Write a program to elasticize strings*.

Jelly is supposed to get character arithmetic one day, but until that happens, we can take advantage of the fact that Python overloads most arithmetic operators and that Jelly does no type checking.

For example

```
“abcd”Ḥ

```

isn't supposed to do anything useful right now, but since  (unhalve) is implemented as

```
lambda z: z * 2

```

and arithmetic atoms vectorize at depth **0** (i.e., they operate on numbers or characters), the above Jelly code yields

```
['aa', 'bb', 'cc', 'dd']

```

Careful that this produces actual Python strings (a type Jelly isn't supposed to have), so this won't be usable in all situations.

Likewise, `+/` can be useful to concatenate strings, with the same caveats.
> 10 votes

# Answer
> *This is part of what became the Jelly wiki tutorial.*

# Multi-chain links

Remember when I wrote that you define a link by making a chain of other links? I wasn’t telling the whole truth: in reality, it’s a two-layer process. A link is a *chain of chains*, and by default, the outer chain simply has unit length.

Consider this program:

```
C+H

```

That’s *complement plus half*. It takes an input value `n` and calculates `(1-n)+(n/2)`. Not too exciting, I know. But the structure is really like this:

The link we wrote is, itself, actually a chain containing a single chain.

Suppose that we want to calculate `(1-n)+(1-n)(n/2)` instead. The dyadic chain  would work: by the chaining rules, it calculates `λ+(λ×ρ)`, which looks a lot like what we need. However, simply replacing `+` by  in our program won’t do: `C+×H` is a 1,2,2,1-chain – *complement, then add (the argument), then multiply by half* – computing `((1-n)+n)×(n/2)`.

We want Jelly to treat  as a unit, and make a 1,2,1-chain of the sub-chains `C`, , and `H`. **Multi-chain links** let us do just that! To construct them, we use the **chain separators** `øµð`: in the image above, they would introduce a new blue rectangle, of arity 0, 1 and 2, respectively. In our case, we can group the chains the way we want by writing `Cð+×µH`:

There’s no way to nest these things even further. You’ll have to define multiple links, instead.
> 9 votes

# Answer
> *This is part of what became the Jelly wiki tutorial.*

# Tacit programming

Jelly is a tacit programming language. This means you define links (functions) by composing existing links into a **chain**, without explicitly talking about the arguments involved. Which way the arguments “flow” through this composition is defined by the pattern the links are arranged in. An example of this will be given soon, but first we’ll need to introduce some concepts.

The **arity** of a link is a very crucial concept. All of the **atoms** – the built-ins, like `+` and `½` – have fixed arities. Links are sorted into three categories, depending on their arity:

> * **Nilads** take no arguments (arity 0); other than some I/O and stateful commands, they mostly represent constant values. For example, the literal `3` is a nilad.
> * **Monads** take one argument (arity 1). (There’s no connection to *functional programming* monads here.) For example, `½` (square root) is a monad.
> * **Dyads** take two arguments (arity 2): a left and a right argument. For example, `+` is a dyad.
>
> (Using adjectives, we say that a link is *niladic*, *monadic*, or *dyadic*.)

So what’s the arity of the links we define when writing a program? By default, they are *variadic* – that is, it’s up to the *caller* to specify how many arguments to use, and in the case of the **main link**, it depends on how many arguments the program is passed.

As an example,  is a chain of `+` (addition) and `½` (square root). As the respective arities of the elements of this chain are 2 and 1, we call it a **2,1-chain**. The interpreter has specific rules for breaking down chains, based on their arities: those rules dictate that, given an input `n`, this new link computes `n + sqrt(n)`. (You can read  as *“... plus its square root.”*)

Jelly programming, then, is essentially the art of learning these rules well, and composing clever chains that get the job done, *tacitly*.
> 8 votes

# Answer
# Integer compression

String compression is useful when producing text in English, but if you need to compress other sorts of data, it's fairly ineffective. As such, most of the time you want to store a large fixed constant in your program, it's best to store it as an integer.

Now that Jelly has its own code page as a constant, the compression algorithm for integers is most simply expressed in Jelly itself:

```
ḃ250ịØJ”“;;”’ṄV

```

Try it online!

(The above program also contains a check to show the value that the integer decompresses to.)

In addition to just using an integer as an integer, you can also use it to create a string via doing base conversion on it, then indexing into an alphabet of characters. The  atom automates this process, and is fairly useful because it can describe the entire process of decompression (other than the alphabet being decompressed into) in a single byte.
> 8 votes

# Answer
> *This is part of what became the Jelly wiki tutorial.*

# Program structure

Each line in a Jelly program is a *link definition*. Links are basically functions. The bottom line represents “`main`”: it's the link that gets evaluated using the arguments passed on the command line.

All links but the last one, then, are function definitions: you can refer to them using actors. For example, `ç` is *“the link above this one, as a binary operator (dyad)”*. Consider this example program, which computes the square of the sum of its arguments:

```
+
ç²

```

This is sort of like the pseudocode:

```
define f:
    the built-in link +
define main:
    apply the dyad f
    square the result

```
> 6 votes

# Answer
# If TMTOWTDI, pick the one that fits your chain.

One of the advantages of a tacit language is that you *usually* can get away without using variable references. However, this works only if the links in your chain have the right arities.

For example, the straightforward way of taking the sum of all arrays in a 2D array is

```
S€

```

which maps the sum atom over all elements of the array.

Now say you have a monadic chain that consists of the atom

```
*

```

which maps each **x** of a 2D array to **x<sup>x</sup>**. For example, for **A = \[\[1, 2\], \[3, 1\], \[2, 3\]\]**, calling the chain would yield **\[\[1, 4\], \[27, 1\], \[4, 27\]\]**.

Now, we want to take the sum of each pair. Unfortunately,

```
*S€

```

doesn't work since `*` doesn't act like a *hook* anymore (using **A** itself as right argument), but as a *fork*, meaning that `S€` gets applied to **A** first, and the result is the right argument of `*`.

Fixing this is easy enough:

```
*¹S€
*⁸S€

```

Both produce the desired result:  is a *fork* where `¹` is the identity function, and `*⁸` is an *atop*, where  is a reference to the chain's left argument (**A**).

However, there's a way to save a byte! The atop `ḅ1` (convert from unary to integer) also computes the sum of each array in **A<sup>A</sup>**, but unlike `S€`,  is a *dyadic* link.

The chain

```
*ḅ1

```

returns **\[5, 28, 31\]** (as desired); since  is dyadic, `*` hooks instead of forking
> 6 votes

# Answer
# Use outer products to create useful integer matrices

*Here is a gist I have created of this post with slightly nicer HTML table formatting.*

The outer product quick `þ` can be attached to dyads and causes the dyad to act on each pair of elements in its left and right arguments. It is shorthand for `€Ð€`. For example if we had the code `[1,2]+€Ð€[0,10]` we could shorten it to `[1,2]+þ[0,10]` and they would both yield `[[1,2],[11,12]]`. I will refer to a dyad with `þ` applied (such as ) as an outer product dyad.

When an integer is one of the arguments of an outer product dyad, Jelly takes the range of that number first then uses the result as the argument. Knowing this, the above example can be further shortened to `2+þ[0,10]`. This is true for both the left and right arguments of an outer product dyad.

Some outer product dyads when acting monadically on an integer yield certain integer matrices that can be useful in golfing (especially ASCII art challenges) but would take many bytes to otherwise construct. For example  when applied to an integer `n` yields an `n×n` identity matrix. Try  online!

Below is a table of dyads and the type of matrices they yield when turned into outer product dyads and acted monadically on an integer. Dyads listed in the same row will yield the same matrices. There are dyads I haven't included in the table like `&`, `|`, `%`, `w`,  and  that also produce integer matrices but their patterns are not as simple and would likely be useful in fewer situations. Try  online!

| Dyad | Resulting matrix | Example |
| --- | --- | --- |
| `=`, , `i` or `ċ` | Identity matrix. | `1 0 0`<br>`0 1 0`<br>`0 0 1` |
| `>` | Elements above diagonal are `1`, all other elements are `0`. | `0 1 1`<br>`0 0 1`<br>`0 0 0` |
| `<` | Elements below diagonal are `1`, all other elements are `0`. | `0 0 0`<br>`1 0 0`<br>`1 1 0` |
| `n` or | Diagonal elements are `0`, off diagonal elements are `1`. | `0 1 1`<br>`1 0 1`<br>`1 1 0` |
| `a`, ,  or `ȧ` | Row index of each element. | `1 1 1`<br>`2 2 2`<br>`3 3 3` |
| `o`,  or `ȯ` | Column index of each element. | `1 2 3`<br>`1 2 3`<br>`1 2 3` |
| `_` | Main diagonal is `0`, upper diagonals are `1`, `2`..., lower diagonals are `-1`, `-2`... | `0 1 2`<br>`-1 0 1`<br>`-2-1 0` |
| `_@` | Main diagonal is `0`, upper diagonals are `-1`, `-2`, etc., lower diagonals are `1`, `2`, etc. The only dyad in this table that doesn't have a one byte alternative that results in a transposed matrix is `_`. | `0 -1-2`<br>`1 0 -1`<br>`2 1 0` |
|  | Main diagonal is `0`, upper and lower diagonals are `1`, `2`, `3`... | `0 1 2`<br>`1 0 1`<br>`2 1 0` |
| `+` | Row index plus column index. | `2 3 4`<br>`3 4 5`<br>`4 5 6` |
| `«` | Minimum of row and column indices. | `1 1 1`<br>`1 2 2`<br>`1 2 3` |
| `»` | Maximum of row and column indices. | `1 2 3`<br>`2 2 3`<br>`3 3 3` |
> 6 votes

# Answer
# Consider using `i` rather than `e`

* `e`: If **x** occurs in **y**, then **1**, else **0**
* `i`: Find the first index of element **y** in list **x**, or **0**

The key thing here is that `e` and `i` take arguments in opposite orders. This can be exploited in two main cases:

* The question allows you to return an inconsistent truthy value, and your answer works by generating a list and checking if the argument is in this list

For example, checking if a number is a Fibonacci number takes 5 bytes using `e`:

```
RÆḞe@

```

But only 4 using `i`, assuming any truthy value may be returned:

```
RÆḞi

```
* Using a filter quick (`Ƈ` or `Ðḟ`). Let’s say you have generated a list of lists and want to keep only those where the input is (or is not) contained in it. As `i` returns a truthy value if the right argument is in the left, you can set up a dyadic link  to remove lists that don’t contain the left argument, saving a byte over `e@Ƈ`

Generally, this tip works best for answers that generate a list, then test the left argument for membership in some way, allowing you to avoid the `@` quick or using a “grouper” like `$` or `Ɗ`
> 6 votes

# Answer
# Jelly IDE/Debugger

After struggling a lot with Jelly's codepage, parsing, error messages and debugging, I decided to build a IDE/debugger for Jelly. This has been in the works for a very long time, but I finally decided to finish most of the features.

> **Download:** https://gitlab.com/PurkkaKoodari/jellyide

Installation instructions are in the repo `README`. You may need to install the DejaVu Sans Mono font (included) to your system to allow Tkinter to find it.

### Features

#### Tkinter-based GUI

Run as `python -m jellyide [filename]`.

* Code editor
* UTF-8 and Jelly codepage support
* Code suggestion with keyword search (press Ctrl+Space)
* Windowed output console
* Jelly runs in a separate thread and can be killed/restarted
* **Notably missing:** command line arguments

#### Augmented Jelly CLI with most of the features

Run as `python -m jellyide.jelly [--opts] <jelly args...>`. Use `--help` for more instructions.

Supports debugging, nice stack traces and everything the Jelly CLI supports.

#### Code visualization (links, quicks, chains, arities)

Only in the GUI, determines the links used and visualizes how they are parsed and executed.

* Block colors indicate arity of link/chain
* Bunched-together blocks indicate chain execution steps (`+1`, `1+`, `+F` and so on)

#### Step-by-step debugging

* Break/continue (via GUI or using Ctrl-C in CLI)
* Start program with stepping (via GUI or `--step` in CLI)
* Step to next entry/return of an atom/quick
* Step to return of current atom/quick
* Shows args or return value in console

```
--- PAUSED ---
Ḥç€
^^^
left arg: [1, 2, -1, -2]
right arg: 3
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
--- PAUSED ---
Ḥç€
^
arg: [1, 2, -1, -2]
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
--- PAUSED ---
Ḥç€
^
return: [2, 4, -2, -4]
[s]tep, [c]ontinue, [q]uit?
--- PAUSED ---
Ḥç€
 ^^
left arg: [2, 4, -2, -4]
right arg: 3
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
--- PAUSED ---
ç€
^
left arg: 2
right arg: 3
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
```

#### Error stack traces with Jelly code locations

I'll let the results speak for themselves. I'm sure you've seen Jelly's built-in error messages.

```
in Æs
,Æs
 ^^
arg: -2

in ,Æs$
,Æs$×
^^^^
arg: -2

in ,Æs$×
,Æs$×
^^^^^
left arg: -2
right arg: 3

in ç
ç€
^
left arg: -2
right arg: 3

in ç€
Ḥç€
 ^^
left arg: [2, 4, -2, -4]
right arg: 3

in Ḥç€
Ḥç€
^^^
left arg: [1, 2, -1, -2]
right arg: 3

ValueError: n must be a positive integer
```
> 5 votes

# Answer
There are several nonobvious ways to check properties of an argument using `Ƒ`. Below are a few. I left out plenty of uses of this quick (E.g. , `ŒuƑ`, ) because they are already the most straightforward methods of achieving their behavior.

```
OƑ  Is number?
ỌƑ  Is character? (errors on negative numeric input)
ḂƑ  Between 0 and 2? 0<=x<2 (python). <2aAƑƊ or of course ⁼Ḃ$ in Jelly.
ḞƑ  Is integer?
UƑ  Like `ŒḂ`, but checks if all sublists of depth 1 are palindromes.
ṠƑ  Is one of -1, 0, 1? (e-r1¤$)

```

Feel free to edit this to add more interesting cases.
> 4 votes

# Answer
You may want to try an online editor Jelly Balls designed to easily build code in Jelly Language.

The features include:

* Command palette with all atoms and syntax characters organized by type
* Online parser recognizing literals and 2-byte atoms in the code
* Simplified in-browser Jelly interpreter to run your Jelly code on the webpage in javascript
* Direct links for transferring the code into TIO or another Jelly Balls session
* Automatic hints
* Optimised for mobile devices

### Give it a try: https://jellyballs.github.io

* Detailed trace report showing arguments and results of every executed step

* Code report showing description of every step

* Recipes page with Jelly examples

* Interactive code page of 256 Jelly characters
> 4 votes

# Answer
# The various uses of

, the "index into" command has some extended capabilities beyond the standard index into command in most languages. For example:

| Command | Functionality | TIO |
| --- | --- | --- |
| `0ị` | Return the last element | Try it online! |
| `Lị` | Return the last element | Try it online! |
| `.ị` | Return the last and first elements | Try it online! |
| `-.ị` | Return the last two elements | Try it online! |
| `1.ị` | Return the first two elements | Try it online! |
| `Ø½ị` | Return the first two elements | Try it online! |
| `JŻị` | Prepend the final element | Try it online! |
| `JŻ‘ị` | Append the first element | Try it online! |
| `Ø+ị` | Return the first and penultimate elements | Try it online! |
| `L‘Hị` | Return the middle elements <br>(2 if even length, else 1) | Try it online! |
| `L‘HịṢ` | Return the median of the array | Try it online! |
| `Tị` | Remove all falsey elements | Try it online! |
| `¬Tị` | Remove all truthy elements | Try it online! |
| `Mị` | Remove all but the maximal elements | Try it online! |
> 4 votes

# Answer
# Chain shapes

Here are all the possible chain shapes of nilads `1234`, monads `FGHJ` and dyads `+*%&` up to length 4.

Each is given with its monadic and dyadic behaviors in a non-tacit Ruby-like syntax, where `(x+y).F` applies/calls `F` on `x+y`.

For example, we wish to parse `P+€Tọ`. We know that `P` is a monad, `+€` is a dyad, `T` is a monad, and  is a dyad. So we look up `F+G*` in the below table and see that it's `((a.F+a.G)*a)`, and we can understand the program as `((a.Product +€ a.Truthy) ọrder a)`.

```
Code   Monadic (arg=a)     Dyadic (args=x,y)
==================================================
   1   1                   1
   F   a.F                 x.F
   +   (a+a)               (x+y)
  1+   (1+a)               (1+x)
  FG   a.F.G               x.F.G
  F+   (a.F+a)             (x.F+y)
  +1   (a+1)               (x+1)
  +F   (a+a.F)             (x+y).F
  +*   ((a+a)*a)           (x+(x*y))
 1+F   (1+a).F             (1+x).F
 1+*   ((1+a)*a)           ((1+x)*y)
 F1+   (1+a.F)             (1+x.F)
 FGH   a.F.G.H             x.F.G.H
 FG+   (a.F.G+a)           (x.F.G+y)
 F+1   (a.F+1)             (x.F+1)
 F+G   (a.F+a.G)           (x.F+y).G
 F+*   ((a.F+a)*a)         (x.F+(x*y))
 +1F   (a+1).F             (x+1).F
 +1*   ((a+1)*a)           ((x+1)*y)
 +FG   (a+a.F).G           (x+y).F.G
 +F*   ((a+a.F)*a)         ((x+y).F*y)
 +*1   ((a+a)*1)           ((x+y)*1)
 +*F   ((a+a)*a.F)         (x+(x*y)).F
 +*%   (((a+a)*a)%a)       ((x+y)*(x%y))
1+2*   (2*(1+a))           (2*(1+x))
1+FG   (1+a).F.G           (1+x).F.G
1+F*   ((1+a).F*a)         ((1+x).F*y)
1+*2   ((1+a)*2)           ((1+x)*2)
1+*F   ((1+a)*a.F)         ((1+x)*y).F
1+*%   (((1+a)*a)%a)       ((1+x)*(x%y))
F1+G   (1+a.F).G           (1+x.F).G
F1+*   ((1+a.F)*a)         ((1+x.F)*y)
FG1+   (1+a.F.G)           (1+x.F.G)
FGHJ   a.F.G.H.J           x.F.G.H.J
FGH+   (a.F.G.H+a)         (x.F.G.H+y)
FG+1   (a.F.G+1)           (x.F.G+1)
FG+H   (a.F.G+a.H)         (x.F.G+y).H
FG+*   ((a.F.G+a)*a)       (x.F.G+(x*y))
F+1G   (a.F+1).G           (x.F+1).G
F+1*   ((a.F+1)*a)         ((x.F+1)*y)
F+GH   (a.F+a.G).H         (x.F+y).G.H
F+G*   ((a.F+a.G)*a)       ((x.F+y).G*y)
F+*1   ((a.F+a)*1)         ((x.F+y)*1)
F+*G   ((a.F+a)*a.G)       (x.F+(x*y)).G
F+*%   (((a.F+a)*a)%a)     ((x.F+(x*y))%y)
+12*   (2*(a+1))           (2*(x+1))
+1FG   (a+1).F.G           (x+1).F.G
+1F*   ((a+1).F*a)         ((x+1).F*y)
+1*2   ((a+1)*2)           ((x+1)*2)
+1*F   ((a+1)*a.F)         ((x+1)*y).F
+1*%   (((a+1)*a)%a)       ((x+1)*(x%y))
+F1*   (1*(a+a.F))         (1*(x+y).F)
+FGH   (a+a.F).G.H         (x+y).F.G.H
+FG*   ((a+a.F).G*a)       ((x+y).F.G*y)
+F*1   ((a+a.F)*1)         ((x+y).F*1)
+F*G   ((a+a.F)*a.G)       ((x+y).F*y).G
+F*%   (((a+a.F)*a)%a)     ((x+y).F*(x%y))
+*1F   ((a+a)*1).F         ((x+y)*1).F
+*1%   (((a+a)*1)%a)       (1%(x+(x*y)))
+*FG   ((a+a)*a.F).G       (x+(x*y)).F.G
+*F%   (((a+a)*a.F)%a)     ((x+(x*y)).F%y)
+*%1   (((a+a)*a)%1)       (((x+y)*y)%1)
+*%F   (((a+a)*a)%a.F)     ((x+y)*(x%y)).F
+*%&   ((((a+a)*a)%a)&a)   (((x+y)*(x%y))&y)

```

The table demonstrates how the same program can parse very differently depending on the number of arguments. The following program has a `*1` step in it when parsed monadically, but `1%` when parsed dyadically:

```
+*1%   (((a+a)*1)%a)       (1%(x+(x*y)))

```
> 3 votes

# Answer
# List commands and literals

If you attempt to use many of the **non-vectorizing list commands** on a **literal** `n` or a **list of literals** `z`, the list command will first convert to a list of some sort and then carry out the command on that list.

These commands appear use calls to the `iterable` function in jelly.py.

```
def iterable(argument, make_copy = False, make_digits = False, make_range = False):
    the_type = type(argument)
    if the_type == list:
        return copy.deepcopy(argument) if make_copy else argument
    if the_type != str and make_digits:
        return to_base(argument, 10)
    if the_type != str and make_range:
        return list(range(1, int(argument) + 1))
    return [argument]

```

Here are some incomplete lists of what those list commands will do.

**Wraps in a list**

The simplest return from `iterable` to wrap the argument in a list, and return that to be processed by the function. This happens if the argument is not already a list, is a string, and `iterable`'s arguments don't call for other methods.

```
-------------------------------------------------------------------------------
| Command | Description     | Process                       | Effect          |
-------------------------------------------------------------------------------
| F       | Flattens a list | 4953F -> [4953]F -> [4953]    | Same as W       |
-------------------------------------------------------------------------------
| G       | Format a list   | 4953G -> [4953]G -> [4953]    | Same as W       |
|         | as a grid       |                               |                 |
-------------------------------------------------------------------------------
| I       | Increments      | 4953I -> [4953]I -> <nothing> | Empty list      |
-------------------------------------------------------------------------------
| S       | Sums a list     | 4953S -> [4953]S -> 4953      | Same as ¹       |
-------------------------------------------------------------------------------
| Ṭ       | Boolean array,  | 4Ṭ -> [4]Ṭ -> [0, 0, 0, 1]    | n-1 zeroes,     |
|         | 1s at indices   |                               | 1 at end        |
-------------------------------------------------------------------------------
| Ụ       | Sort indices by | 4Ụ -> [4]Ụ -> [1]             | Yields [1]      |
|         | by their values |                               |                 |
-------------------------------------------------------------------------------
| Ė       | Enumerate list  | 4Ė -> [4]Ė -> [[1, 4]]        | Yields [[1, n]] |
-------------------------------------------------------------------------------
| Ġ       | Group indices   | 4Ġ -> [4]Ġ -> [[1]]           | Yields [[1]]    |
|         | by values       |                               |                 |
-------------------------------------------------------------------------------
| Œr      | Run-length      | 4Œr -> [4]Œr -> [[4, 1]]      | Yields [[n, 1]] |
|         | encode a list   |                               |                 |
-------------------------------------------------------------------------------

```

**Convert to base 10**

The functions here call `iterable` to converts to a number to a list of its digits `D`, and then run on those digits.

```
-------------------------------------------------------------------------
| Command | Description     | Process                      | Effect     |
-------------------------------------------------------------------------
| Q       | Unique elements | 299Q -> [2, 9, 9]Q -> [2, 9] | Unique     |
|         | ordered by      |                              | digits     |
|         | appearance      |                              | of n       |
-------------------------------------------------------------------------
| Ṛ       | Non-vectorized  | 4953Ṣ -> [4, 9, 5, 3]Ṛ       | Reverses D |
|         | reverse         | -> [3, 5, 4, 9]              |            |
-------------------------------------------------------------------------
| Ṣ       | Sort a list     | 4953Ṣ -> [4, 9, 5, 3]Ṣ       | Sorts D    |
|         |                 | -> [3, 4, 5, 9]              |            |
-------------------------------------------------------------------------

```

**Convert to list with range**

The functions here convert a number to the range `R = [1 ... n]`, and then run on that range.

```
-----------------------------------------------------------------------------------------
| Command | Description       | Process                             | Effect            |
-----------------------------------------------------------------------------------------
| X       | Random element    | 4R -> [1 ... 4]X -> 2               | Random element    |
|         |                   |                                     |  of R             |
|         |                   |                                     |                   |
-----------------------------------------------------------------------------------------
| Ḋ       | Dequeue from list | 4R -> [1 ... 4]Ḋ -> [2, 3, 4]       | Range [2 ... n]   |
-----------------------------------------------------------------------------------------
| Ṗ       | Pop from list     | 4Ṗ -> [1 ... 4]Ṗ -> [1, 2, 3]       | Range [1 ... n-1] |
-----------------------------------------------------------------------------------------
| Ẇ       | Sublists of list  | 4Ẇ -> [1 ... 4]Ẇ                    | All sublists of R |
|         |                   | -> [[1], [2], [3], [4], [1, 2],     |                   |
|         |                   |     [2, 3], [3, 4], [1, 2, 3],      |                   |
|         |                   |     [2, 3, 4], [1, 2, 3, 4]]        |                   |
-----------------------------------------------------------------------------------------
| Ẋ       | Shuffle list      | 4Ẋ -> [1 ... 4]Ẋ -> [2, 1, 3, 4]    | Shuffles R        |
-----------------------------------------------------------------------------------------
| Œ!      | All permutations  | 3Œ! -> [1, 2, 3]Œ!                  | All permutations  |
|         | of a list         | -> [[1, 2, 3], [1, 3, 2],           | of R              |
|         |                   |     [2, 1, 3], [2, 3, 1],           |                   |
|         |                   |     [3, 1, 2], [3, 2, 1]]           |                   |
-----------------------------------------------------------------------------------------
| ŒḄ      | Non-vectorized    | 4ŒḄ -> [1 ... 4]ŒḄ                  | Bounces R         |
|         | bounce,           | -> [1, 2, 3, 4, 3, 2, 1]            |                   |
|         | z[:-1] + z[::-1]  |                                     |                   |
-----------------------------------------------------------------------------------------
| Œc      | Unordered pairs   | 4Œc -> [1 ... 4]Œc                  | Unordered pairs   |
|         | of a list         | -> [[1, 2], [1, 3], [1, 4], [2, 3], | of R              |
|         |                   |     [2, 4], [3, 4]]                 |                   |
-----------------------------------------------------------------------------------------
| Œċ      | Unordered pairs   | 4Œċ -> [1 ... 4]Œċ                  | Unordered pairs   |
|         | with replacement  | -> [[1, 1], [1, 2], [1, 3], [1, 4], | with replacement  |
|         | of a list         |     [2, 2], [2, 3], [2, 4], [3, 3], | of R              |
|         |                   |     [3, 4], [4, 4]]                 |                   |
-----------------------------------------------------------------------------------------
| ŒP      | Powerset of       | 3ŒP -> [1 ... 3]                    | Powerset of R     |
|         | a list            | -> ['', [1], [2], [3], [1, 2],      |                   |
|         |                   |     [1, 3], [2, 3], [1, 2, 3]]      |                   |
-----------------------------------------------------------------------------------------
| Œp      | Cartesian         | 4,2Œp -> [[1 ... 4], [1 ... 2]]Œp   | Cartesian product |
|         | product of z's    | -> [[1, 1], [1, 2], [2, 1], [2, 2], | of [1 ... z[i]]   |
|         | items             |     [3, 1], [3, 2], [4, 1], [4, 2]] | for i in z        |
-----------------------------------------------------------------------------------------

```
> 2 votes

# Answer
# It's sometimes worthwhile to read from standard input when there are exactly two inputs

Jelly is optimized for taking input from command-line arguments. However, it's also optimized for writing monads rather than dyads; with dyads there are so many possible meanings for each builtin that you often need to spend characters to disambiguate, whereas with monads there are typically many ways to say the same thing.

As such, if you use one of two inputs only once, and the problem is such that it can't easily be implicitly read from  (i.e. you either need to make the  explicit, or else spend a character on `}`, `@`, or the like), consider reading it from standard input with `Ɠ` rather than placing it on the command line; that lets you precisely place the input right where you need it via the placement of your `Ɠ`, whilst ensuring that every other implicit input will be taken from your other input. That costs a byte and saves a byte, and depending on the problem, may well save a second byte by giving you more scope to reorder the code.
> 2 votes

# Answer
# `Ƒ` combines very well with vectorising commands

For example:  returns the sign of an integer. If given an array, it applies  to each element and returns the corresponding array:

```
-3Ṡ = -1
1,2,-2,5,0Ṡ = 1,1,-1,1,0

```

Under , only `1`, `0` and `-1` are unchanged. Therefore, `ṠƑ` returns true if its argument is one of `1`, `0` or `-1`.

However, `Ƒ` doesn't vectorise over lists. This means that given a list and an atom that vectorises, it acts something similar to `<atom>Ƒ€Ạ`, which saves at least 2 bytes and potentially more if using filters and other quicks (`<atom>Ƒ€Ạ$Ƈ` vs `<atom>ƑƇ`). As an example, compare:

```
-,1,0,1,- ṠƑ
-,2,0,1,- ṠƑ

```

Try it online!

---

This works best with the following atoms. All of these vectorise with depth 0 unless stated otherwise, meaning they vectorise to all levels of nested arrays:

| Atom | What does `<atom>Ƒ` test? |
| --- | --- |
| `<nilad>` | All equal `nilad` |
| `A` | All are non-negative |
| `H`, `N`, ,  <br>`÷`, `%`, `:` | All zeros <br>`÷%:` only work if the right argument doesn't lead to a division by zero |
| `O` | All numbers (i.e. no strings) |
| `U` | All subarrays are palindromes. <br>Note that due to the behaviour of `ŒḂ` on integers, this is different to `ŒḂ€Ạ` for flat arrays <br>See below for a breakdown of the differences and more details on |
| `²`, | All elements are 1 or 0 |
| , `İ`, `Æ²` | Only contains 1. <br>Can usually be replaced by `Ȧ`, but not always |
|  | All strings (i.e. no numbers) |
| `Ċ`, | All integers |
|  | All elements are -1, 0 or 1 |
| `×` | All elements are zero <br>Or, the right argument is 1 |
| `+`, `_`, `^` | Is the right argument 0? |
| `a`, `&` | Are all elements 0 or equal to the right argument? |
| `o` | If the right argument is not zero, is the left argument all non-zero? <br>If the right argument is zero, return `1` |
| `|` | If the right argument is zero, is the left argument all integers? <br>If the right argument is non-zero, are all elements equal to the right argument? |
| `«` | Are all elements less than or equal to the right argument? |
| `»` | Are all elements greater than or equal to the right argument? |

For `|^&`, the arguments must only involve integers

###

Due to `U` vectorising at depth 0 and `ŒḂ` not vectorising, , `ŒḂ` and `ŒḂ€Ạ` have very different behaviours in some cases (note that `ŒḂ` also checks if integers are palindromic by checking their digits):

* If the argument is a flat list of integers/strings:

+ `ŒḂ` returns true if the list is palindromic
    + `ŒḂ€Ạ` returns true if all elements of the list are palindromic
    + returns true if the list is palindromic
* If the argument is a list containing integers and single nested lists (e.g. `[[0, 1], 2, 3, [4, 5, 6]]`):

+ `ŒḂ` returns true if the list is palindromic, ignoring if elements themselves are palindromic
    + `ŒḂ€Ạ` returns true if each element in the list is palindromic, ignoring whether the list as a whole is palindromic.
    + will always return false
* If the argument is a list containing single nested lists (e.g. `[[1, 2], [3, 4], [5]]`):

+ `ŒḂ` returns true if the list is palindromic, ignoring if elements themselves are palindromic
    + `ŒḂ€Ạ` returns true if each element in the list is palindromic, ignoring whether the list as a whole is palindromic.
    + acts the same as `ŒḂ€Ạ`
* If the argument is a list with multiple levels of nesting (e.g. `[2, [2, 2], [2, [2, 2]]]`):

+ `ŒḂ` returns true if the list is palindromic, ignoring if elements themselves are palindromic
    + `ŒḂ€Ạ` returns true if each first order element in the list is palindromic, ignoring whether the list as a whole is palindromic. This does not check the nested elements if they are palindromes, it just iterates through the first level elements and checks them
    + checks each subarray at all depths and returns true iff all these subarrays are palindromes. As  returns false for integers, if the list contains any subarrays containing both integers and lists, it'll return false.

As an example, compare the behaviour of each will the following arguments:

| Argument | `ŒḂ` | `ŒḂ€Ạ` |  |
| --- | --- | --- | --- |
| `[[2], [2, 2], [[2], [2, 2]]]` | 0 | 0 | 1 |
| `[2, [2, 2], [[2, 2], [2, 2]]]` | 0 | 1 | 0 |
| `[[2, [2, 2]], [2, [2, 2]]]` | 1 | 0 | 0 |
| `[[[2], [2, 2]], [[2], [2, 2]]]` | 1 | 0 | 1 |

---

Some additional helpful uses of `Ƒ`:

* `ṄƑ`, `ȮƑ` and `ṘƑ` all print their argument and replace it with `1` if you need to output the argument and start a new chain with 1 as the argument. Saves bytes if the chain prevents using `1` as an unparseable nilad
* and `ẎƑ` both test if their argument is a flat list
* returns true iff the left argument consists entirely of the right argument.
* `ḟƑ` returns true iff the left argument does not contain the right argument
* `ṁƑ` tests if the left argument has the same "shape" as the right argument (i.e. length and depth of each element)
* tests if the left argument begins or ends with the right argument (returning 1 if it does not)
* `ÆṣƑ` tests if its argument is perfect, or, if a list, is all perfect numbers
> 2 votes

# Answer
# Monads don't have to be monads

Not very frequently applicable, but in some cases where a series of monads (or dyad-nilad/nilad/dyad pairs, i.e. would be an LCC if there was a leading constant) grouped with `$ƊƲ` is to the right of a dyad in a monadic chain, but the `(2,1)` pattern is not desired, the grouping quick can be replaced with `¥ɗʋ` without affecting its behavior at no cost. This pretty much only comes up if there's another quick applied to the group which inherits its operand's adicity, like `Ƈ`, and there's no monad to the right of that.
> 2 votes

# Answer
## Optimal Integer / List Compression

An integer compressor exists for a single large integer already; however, there are many ways of representing integers and lists - basic literals, exponential literals, codepage index lists, long compressed numbers, and two-byte short compressed numbers. These are all mentioned in this thread, but this is a unified compression tool for all of them.

This is available of my site here (affiliation disclosure: I made this site. I don't get any money from it. It's just a project entirely for fun). In case my site ceases to exist (and also because this answer should be self-contained), you can use the following code snippet to compress any valid value (where a valid value is an integer or a list of valid values).

Note that this only compresses into literals. There are often shorter ways to represent certain numbers or lists using constants, base decompression, grade up / group indices, etc, but that is beyond what I have implemented for this, and this will always return a single literal representing the inputted value.

```
let codepage  = "¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !\"#$%&'()*+,-./0123456789:;<=>?";
    codepage += "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶";
    codepage += "°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂ";
    codepage += "ĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”";

function go() {
  var value = document.getElementById("value").value;
  console.clear();
  if (value.match(/^\s*$/)) {
    console.log();
  } else if (value.match(/^[\[\]\d\s,-]*$/)) {
    try {
      value = eval("[" + value.replace(/\d+/g, x => x + "n") + "]");
    } catch {
      console.log("not a valid value");
      return;
    }
    if (value !== undefined) {
      if (value.length == 1) value = value[0];
      console.log(compress(value));
    }
  }
}

function compress(value, surround_list = false) {
  var converted = "";
  for (var f of [trivial, exponential, cp_index_list, compressed_integer, short_compressed]) {
    var c = f(value);
    if (c && (converted == "" || c.length < converted.length)) {
      converted = c;
    }
  }
  if (Array.isArray(value)) {
    var list_form = value.map(function(sub) {
      return compress(sub, true);
    }).join(",");
    if (surround_list || value.length == 1) {
      list_form = "[" + list_form + "]";
    }
    if (list_form && (converted == "" || list_form.length < converted.length)) {
      converted = list_form;
    }
  }
  return converted;
}

function trivial(number) {
  if (Array.isArray(number)) return;
  if (number == -1n) {
    return "-";
  } else {
    return number.toString();
  }
}

function exponential(number) {
  if (Array.isArray(number)) return;
  var exp = 0n;
  while (number % 10n == 0n) {
    exp++;
    number /= 10n;
  }
  return (number == 1 ? "" : number == -1 ? "-" : number.toString()) + "ȷ" + (exp == 3 ? "" : exp.toString());
}

function cp_index_list(numbers) {
  if (!Array.isArray(numbers)) return;
  if (numbers.every(function(x) {
    return !Array.isArray(x) && 0n <= x && x < 250n;
  })) {
    return "“" + numbers.map(function(x) {
      return codepage[x];
    }).join("") + "‘";
  } else if (numbers.every(function(x) {
    return Array.isArray(x) && x.every(function(x) {
      return !Array.isArray(x) && 0n <= x && x < 250n;
    });
  })) {
    var k = numbers.map(function(x) {
      return "“" + x.map(function(x) {
        return codepage[x];
      }).join("");
    }).join("") + "‘";
    if (numbers.length == 1) {
      return "[" + k + "]";
    } else {
      return k;
    }
  }
}

function compressed_integer(number) {
  if (Array.isArray(number) && number.every(function(x) {
    return !Array.isArray(x) && x >= 0n;
  })) {
    k = number.map(function(e) {
      var string = compressed_integer(e);
      return string.substring(0, string.length - 1);
    }).join("") + "’";
    if (number.length == 1) {
      return "[" + k + "]";
    } else {
      return k;
    }
  } else if (!Array.isArray(number) && number >= 0n) {
    var builder = "’";
    while (number) {
      var digit = number % 250n;
      if (digit == 0n) digit = 250n;
      number -= digit;
      number /= 250n;
      builder = codepage[digit - 1n] + builder;
    }
    return "“" + builder;
  }
}

function short_compressed(number) {
  if (Array.isArray(number)) return;
  if (number < -31349n || (number > -100n && number < 1001n) || number > 32250n) return;

  if (number < 0) number += 62850n;
  else            number -= 750n;

  var last = number % 250n;
  if (last == 0n) last = 250n;
  number -= last;
  number /= 250n;

  return "⁽" + codepage[number - 1n] + codepage[last - 1n];
}
```

```
input {
  padding: 5px;
  font-family: monospace;
  width: 100%;
}
```

```
<input id="value" type="text" placeholder="Enter a valid integer/list here" />
<br /><br />
<button onclick="go()">Compress!</button>
```
> 1 votes

# Answer
# Most quick-link monads get a free `{`

Quicks that expect dyads typically error when run on monads, because most monads have their underlying `call` as a lambda accepting only one argument. However, most quicks that emit monads--whether conditionally or unconditionally--implement the emitted monad's `call` as a lambda accepting up to two arguments, with the only exceptions being `Ɲɼ`⁺`.

This is *completely useless* unless you're already severely abusing one of the handful of quicks that strictly require a dyad, but it can come up. I could also see this coming up with `\` in some circumstance, most likely in conjunction with a simple grouping quick.
> 1 votes

---
Tags: code-golf, tips, jelly
---