title: Tuple Assignment in Pyth

text:
# Question
Title: Tuple Assignment in Pyth
I was wondering if there is any way to assign 2 values (G and H) to say a list of \["egg", "chicken"\] in Pyth. In python it would be something along the lines of

```
G, H = ["egg", "chicken"]

```

At the moment the shortest way I can think of would be something like

```
=N["egg""chicken")=G@N0=H@N1

```

which uses the lookup function to index the list and store each one individually. I tried doing something like

```
=(G H)["egg""chicken")

```

but when I look at the debug info Pyth debug info it doesn't seem to be what im after. Any help would be good thanks. This may include shortening the original solution or giving me an explanation on how to do the tuple assignment

# Answer
> 9 votes
This is exactly what the `A` builtin does: “Assign the first value of the list to G and the second to H. Return the input.”

```
A["egg""chicken")

```

---
Tags: tips, pyth
---


title: Chinese Zodiac of the year

text:
# Question
Title: Chinese Zodiac of the year
2015 was the year of the goat! In this challenge, you will figure out which animal represents the year. To avoid making this challenge to complex you won't need to calculate Chinese new year.

Because they are only 12 animals in the Zodiac, your code will need to be as short as possible.

## Examples

**Your program must get the system year**, the first line is just for reference

```
2015
Goat

1924
Rat

1923
Pig

2008
Rat

```

## Specification

The order of the Zodiac is:

```
Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig

```

`Rat` starts at 2008, `Pig` is 2007, `Ox` at 2009, etc. at the end this loops back around.

Output must be correctly capitalized.

# Answer
> 5 votes
# Pyth, 54 bytes

```
@rR3c."ayÖÚ©*ÐPk<`eüµÜxþ!¬Ì ¾½hÑðÙBwp"\c.d3

```

Try it online: Demonstration

You can replace the last 3 chars `.d3` with any year number to test the other Zodiac animals.

### Explanation:

```
     ."ayö..."        packed string, decrypts to "monkeycroostercdogcpig..."
    c         \c      split this string at "c"s
 rR3                  make the first letter of each animal uppercase
                .d3   current year
@                     take the correct animal of the list and print

```

# Answer
> 6 votes
# Pyth - 65 bytes

```
@c." y=CÅQ¯@îR
°©ÀáëªfÞ#[õNqÀN8Ô'¼ô,n7Ë¶~fB").d3

```

Try it online here.

```
@                     Modular indexing
 c           )        Split string, use default of spaces
  ."ajs&^asd"         Packed string to compress space separated zodicas
 .d3                  Current year

```

# Answer
> 4 votes
# JavaScript ES6, ~~106~~ ~~105~~ ~~104~~ 103 bytes

Saved 1 byte thanks to Maltysen, 1 byte to insertusernamehere, *and* 1 byte to edc65!

```
x=>"RatOxTigerRabbitDragonSnakeHorseGoatMonkeyRoosterDogPig".match(/.[a-z]+/g)[new Date().getYear()%12]

```

Pretty self explanatory.

# Answer
> 3 votes
# CJam, ~~82~~ ~~80~~ 75 bytes

~~This is was a direct port of my Milky Way answer.~~

```
"Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat"S/et0==

```

*Saved 7 bytes thanks to NinjaBearMonkey.*

# Answer
> 3 votes
## Japt, ~~72~~ 65 bytes

```
`Mkey RooÐP Dog Pig R Ox Tig Rabb Dg Snake HÆ  Go`¸gÐ i %C

```

Try it online!

# Answer
> 1 votes
# Milky Way 1.6.1, ~~101~~ 96 bytes

```
M" "\=A12n"Goat Horse Snake Dragon Rabbit Tiger Ox Rat Pig Dog Rooster Monkey"" "\;>=<&{~1-;^};!

```

*Saved 5 bytes thanks to a reminder by Luis Mendo.*

---

### Explanation

The code modulos the system year by 12 and outputs the proper animal.

---

### Usage

```
./mw <path-to-code>

```

# Answer
> 1 votes
# MATL, 85 bytes

```
'Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey'YbZ'10H$XOU12X\)

```

Uses release 6.0.0 of the language/compiler. Works in Octave.

### Example

```
>> matl
 > 'Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey'YbZ'10H$XOU12X\)
 >
Monkey

```

### Explanation

Note that the initial string is cyclically displaced by 3 to avoid a subtraction.

```
'Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey'
Yb                    % split at spaces
Z'                    % number representing current date and time
10H$XO                % get year as a string
U                     % convert to number
12X\                  % modulo 12, with 0 converted to 12
)                     % index (and implicitly print)

```

# Answer
> 1 votes
# CJam, 69 bytes

```
"SKiN<lEz=2)aFBY8H[$h-0|4=K`T2Cp%-a)o6"132b26b'`f+'`/et0==(eu\

```

Contains a bunch of unprintables. Try it here.

# Answer
> 1 votes
# Python 3, ~~126~~ ~~116~~ 112 bytes

**Edit:** I'm keeping the other answer because it's cool, but this is shorter.

```
from time import*
"Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Goat".split()[localtime().tm_year%12]

```

If trailing whitespace is ok, then it's 126 bytes. If not, it's 134 bytes after adding `.strip()` to the end of the code.

```
from datetime import*
"MRDPROTRDSHGoooiaxiarnoonoggt gbaaraks    ebgkstet    rioee ye     tn    r"[datetime.now().year%12::12]

```

# Answer
> 0 votes
# R, 119 bytes

```
scan(t="Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat",w="")[(format(Sys.Date(),"%Y"):1)[1]%%12+1]

```

`format(Sys.Date(),"%Y")` returns the year as a character string, `(format(Sys.Date(),"%Y"):1)[1]` is the shortest way i could think of to coerce it into an integer so that we can apply `%%` to it (the sequence generator `:` indeed coerces automatically to integer). `+1` because R indices are 1-based and not 0-based.

# Answer
> 0 votes
# PHP \>= 5.6, 84 bytes

Very straight forward:

```
<?=[Monkey,Rooster,Dog,Pig,Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat][date(Y)%12];

```

# Answer
> 0 votes
# Python ~~129~~ 126 bytes

**EDIT**: I just learnt s.split(' ')=s.split()

Although this isn't the shortest method, here is an alternative answer to @Sherlock9's one:

```
from datetime import*
print 'Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat'.split()[date.today().year%12]

```

Try it here

# Answer
> 0 votes
## PowerShell, 92 bytes

```
(-split"Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat")[(date).Year%12]

```

Similar in spirit to other answers, added here only for sake of cataloging. This takes the string `"Monkey ... Goat"` and `-split`s it on spaces to create an array, which is cheaper than specifying the elements individually with `("Monkey","Rooster",...)`. We index into that array with the current `year` mod `12`, which outputs the result. Nothing too fancy.

# Answer
> 0 votes
## C# 159

```
using System;class P{static void Main(){Console.Write("Monkey;Rooster;Dog;Pig;Rat;Ox;Tiger;Rabbit;Dragon;Snake;Horse;Goat".Split(';')[DateTime.Now.Year%12]);}}

```

Readable / ungolfed version

```
using System;
class Program
{
    static void Main(string[] args)
    {
        Console.Write("Monkey;Rooster;Dog;Pig;Rat;Ox;Tiger;Rabbit;Dragon;Snake;Horse;Goat".Split(';')[DateTime.Now.Year % 12]);
    }
}

```

# Answer
> 0 votes
# , 78 bytes

```
(>;:'Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat'){~12|

```

Usage:

```
    (>;:'Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat'){~12| 2015
 Goat

```

Explanation:

```
;:      separates the string into boxed array according to the spaces
>       opens the boxed array so that it becomes a normal array
x {~ y  is choose the y-th element from x.
        the ~ reverses the argument, so x { y is choose the x-th element from y.
12|     is the residue when the year is divided by 12

```

# Answer
> 0 votes
# Vyxal, 49 bytes

```
`⌊ẇ ₃¼ Roos≠∴ •∞ Ḣ⟩ ₀⌊ Ox ṗȦ ₈Ė ėɾ Ċṅ ½√`⌈kD⌊12%i

```

Try it Online!

```
`...`         # Compressed  string of names
     ⌈        # Split on spaces
      kD⌊     # Current year
         12%  # Modulo 12
            i # Index into list of names

```

---
Tags: code-golf, kolmogorov-complexity, date
---


title: Outputting Blum Integers

text:
# Question
Title: Outputting Blum Integers
According to Wikipedia,

> In mathematics, a natural number \\$n\\$ is a Blum integer if \\$n = p \times q\\$ is a semiprime for which \\$p\\$ and \\$q\\$ are distinct prime numbers congruent to \\$3 \bmod 4\\$. That is, \\$p\\$ and \\$q\\$ must be of the form \\$4t + 3\\$, for some integer \\$t\\$. Integers of this form are referred to as Blum primes. This means that the factors of a Blum integer are Gaussian primes with no imaginary part.

The first few Blum integers are:

```
21, 33, 57, 69, 77, 93, 129, 133, 141, 161, 177, 201, 209, 213, 217, 237, 249, 253, 301, 309, 321, 329, 341, 381, 393, 413, 417, 437, 453, 469, 473, 489, 497, 501, 517, 537, 553, 573, 581, 589, 597, 633, 649, 669, 681, 713, 717, 721, 737, 749, 753, 781, 789

```

This is OEIS A016105

Your task is to make a program that does one of the following:

* Take an index \\$n\\$ and output the \\$n^{th}\\$ Blum integer, either 0 or 1 indexing.
* Take a positive integer \\$n\\$ and output the first \\$n\\$ Blum integers.
* Output all Blum integers infinitely.

This is so shortest answer wins.

# Answer
> 6 votes
# Python 3, 65 bytes

```
n=1
while[[d%4for d in range(2,n)if n%d<1]==[3,3]!=print(n)]:n+=4

```

Try it online!

Prints indefinitely. Identifies Blum integers as those with exactly two proper factors, both of which are 3 mod 4.

# Answer
> 5 votes
# Jelly, 10 bytes

```
ÆḌ%4Ḅ⁼13µ#

```

A full program accepting an integer, \\$n\\$, from STDIN, that prints a list of the first \\$n\\$ Blum integers.

**Try it online!**

### How?

First, note that a semi-prime has exactly three proper divisors: \\$(1, p, q)\\$, thus Blum integers may be identified by having \\$X=(1\mod 4, p\mod 4, q\mod 4)\\$ equal to \\$(1,3,3)\\$.

Next, note that if we treat \\$X\\$ as a binary number then Blum integers all evaluate to:
\\$2^2\cdot 1 + 2^1\cdot 3 + 2^0\cdot 3=13\\$

Next, note that the only way to have a string of \\$\[0..3\]\\$ evaluate as \\$13\\$ this way is to have either three or four proper divisors. Two is too few since \\$2^1\cdot 3+2^0\cdot 3\<13\\$ and five is too many since \\$2^4\cdot 1\>13\\$ and the smallest proper divisor is always \\$1\\$.

Lastly, note that the only numbers with exactly four proper divisors are fourth powers of primes, with proper divisors of \\$(1, p, p^2, p^3)\\$. Since \\$p\mod 4\\$ is never zero \\$(1, 0, 1, 3)\\$ and \\$(1, 0, 2, 1)\\$ cannot happen, so the only possible false positive that could exist after taking modulo four would be \\$(1, 1, 0, 1)\\$, but if \\$p\equiv 1\pmod 4\\$ then \\$p^2\equiv 1\pmod 4\\$, so that cannot happen either.

```
ÆḌ%4Ḅ⁼13µ# - Main Link: no arguments
        µ# - read n from STDIN, count up from k=0
             finding the first n k for which this f(k) is truthy:
ÆḌ         -   proper divisors
  %4       -   mod four
    Ḅ      -   convert from binary
     ⁼13   -   equals 13?

```

# Answer
> 4 votes
# , 32 bytes

```
(>:[]echo~~:/@q:*3 3-:4|q:)^:_@3

```

Try it online!

Outputs all Blum primes.

* `^:_@3` Starting with 3, and continuing to a fixed point (which will never be reached)...
* `]echo~~:/@q:*3 3-:4|q:` If the the current number `n`'s prime factors mod 4 exactly matches `3 3`, and the numbers are not equal `~:/@q:*`, then `echo n` as a side effect...
* `>:[` Return `n+1` for the next iteration.

# Answer
> 3 votes
# 05AB1E, ~~14~~ 13 bytes

-1 byte thanks to Adnan!

Prints the infinite list of Blum numbers.

```
∞ʒfʒ4%Í}ü*θyQ

```

Try it online!

```
∞                 # infinite list of positive integers [1,2,...
 ʒ                # filter, keep y if
  f               #   push list of unique prime factors
   ʒ4%Í}          #   keep those where k%4-2==1
        ü*        #   get the products of all adjacent factors
          θ       #   take the last one (or the empty list if there are none)
           yQ     #   is this equal to y?

```

# Answer
> 3 votes
# , ~~61~~ 56 bytes

*-5 bytes thanks to @Dominic*

```
while(T<-T+1)if(all(which(!T%%2:T)%%4==c(2,2,0)))show(T)

```

Try it online!

Outputs all Blum integers infinitely.

### Explanation

As R doesn't have build-ins for prime factorisation we have to circumvent this.

Let's notice that:

* Blum integer needs to have exactly three non-trivial factors (prime or not) - including the number itself;
* The remainders \\$ mod\ 4 \\$ need to be \\$3,3,1\\$ respecitvely.

Therefore it suffices to check if the divisors of the number (`which(!T%%2:T)` is off-by-one) are `all` equal \\$ mod\ 4 \\$ to vector `[3 3 1]` (`c(2,2,0)` correcting the off-by-one).

Actually we could skip testing the number itself for mod4, but, you know, bytes...

# Answer
> 3 votes
# Vyxal, 13 bytes

```
∞››'Ǐ'›4Ḋ;÷*=

```

Try it Online!

Prints infinitely.

```
∞››           # Positive integers (except 1)
   '          # Filtered by
    Ǐ         # Prime factors
     '   ;    # Filtered by
      ›       # Incremented
       4Ḋ     # Is divisible by 4?
          ÷   # Push all to the stack separately
           *  # Product of the top two
            = # Is equal to (implicit input / another factor)

```

Let's go through the outcomes after ÷.

Case 1: 1 factor left. This gets multiplied by the original number, and since it's not 1, it can never equal the original number.

Case 2: 2 factors left. These two get multiplied together, and if it's the same as the original, it will be outputted.

Case 3: 3+ factors left. The top two will be multiplied, but can't equal the third because it's a prime.

# Answer
> 2 votes
# Retina, 78 bytes

```
\d*$
_
"$&"}/(^_|\1__)+$|^(__(___?)?(____)*)\2+$|^(?!(___(____)*)\5+$)/+`$
_
_

```

Try it online! Link includes test cases. Outputs the `n`th term. Explanation:

```
"$&"}`

```

Repeat `n` times.

```
\d*$
_

```

Delete the numeric input, and increment the result.

```
/(^_|\1__)+$|^(__(___?)?(____)*)\2+$|^(?!(___(____)*)\5+$)/+`

```

While the result: `(^_|\1__)+$` is square, or `^(__(___?)?(____)*)\2+$` contains a nontrivial proper factor that is not of the form `4t+3`, or `(?!(___(____)*)\5+$)` does not contain a nontrivial proper factor that is of the form `4t+3`, then...

```
$
_

```

... increment the result.

```
_

```

Convert to decimal.

All numbers contain a trivial factor not of the form `4t+3`, i.e. 1. Since the product of two factors `4t+3` would be of the form `4t+1`, the only way a number to only contain nontrivial factors of the form `4t+3` is for the number to be a prime of the form `4t+3`. The next step is to consider numbers with nontrivial proper factors which are all of the form `4t+3`. This set contains only products of two primes of the form `4t+3` (since 3 primes would generate nontrivial proper factors of the form `4t+1` as the product of two of the primes), so it remains to exclude perfect squares which then leaves Blum integers.

# Answer
> 2 votes
# 05AB1E,  ~~10~~  9 bytes

-1 thanks to Adnan (`26` is a built-in, , and `1` is the only truthy integer in 05AB1E)

A port of my Jelly answer, just using divisors rather than proper divisors.

```
∞ʒÑ4%JC27Q

```

A full program printing an infinite list of the Blum integers.

**Try it online!**

### How?

For an explanation of why this works see my Jelly answer (and add \\$(p\cdot q)\mod 4\\$ to the list to be converted from binary, noting that this will be \\$1\\$ for a Blum integer, while \\$13\cdot2+1=27\\$ and the existence of two final potential false-positives, \\$(1,1,0,0,3)\\$ and \\$(1,1,0,1,1)\\$ neither of which can happen since \\$p\equiv 1\pmod 4 \implies p^2\equiv 1\pmod 4\\$.)

```
∞ʒÑ4%JC₂-
∞         - the positive integers
 ʒ        - filter keep if truthy under:
  Ñ       -   divisors
   4      -   push four
    %     -   modulo
     J    -   join
      C   -   from binary -> x
       ₂  -   push 26
        - -   subtract -> x-26 (truthy when x=27 as only 1 is truthy in 05AB1E)

```

# Answer
> 1 votes
# Jelly, 14 bytes

```
ÆfQƑa%ɗ4⁼3,3µ#

```

Try it online!

Outputs the first \\$n\\$ Blum integers. Takes \\$n\\$ on STDIN

-1 byte thanks to Nick Kennedy

## How it works

```
ÆfQƑa%ɗ4⁼3,3µ# - Main link. Takes no arguments
            µ  - Group the previous links into a monad f(k):
Æf             -   Prime factors of k; F
      ɗ4       -   Previous 3 links as a dyad g(F, 4):
  QƑ           -     Are the prime factors unique?
     %         -     Mod each factor by 4
    a          -     And; If the prime factors are unique, yield the
                      factors mod 4, otherwise, yield 0
        ⁼3,3   -   Does that equal [3, 3]?
             # - Read n. Count up k = 0, 1, ... until n such k return true under f(k)

```

# Answer
> 1 votes
# JavaScript (V8),  ~~59~~  57 bytes

This version is inspired by xnor's answer in Python. We print `n` if the concatenation of its proper divisors modulo 4 (in ascending order and without repetition) is `"133"`.

```
for(n=0;g=d=>--d&&g(d)+[[d%4][n%d]];)g(++n)^133||print(n)

```

Try it online!

---

# JavaScript (V8),  ~~76~~  75 bytes

Prints the sequence 'forever' (i.e. until a recursion error occurs).

```
for(n=0;g=d=>k%--d?g(d):d;)g(k=p=g(k=++n))*g(k=n/p)^p!=k|~(p&k)&3||print(n)

```

Try it online!

### Commented

```
for(               // loop:
  n = 0;           //   start with n = 0
  g = d =>         //   define the helper function g
    k % --d ? g(d) //   which returns the highest proper divisor of k
            : d;   //
)                  //
  g(               // get the highest proper divisor of ...
    k = p =        //   ... the highest proper divisor p of ...
      g(k = ++n)   //     ... n, after it's been incremented
  ) *              // and multiply it by
  g(               // the highest proper divisor of
    k = n / p      //   k = n / p
  )                // this product is either 1 (success) or greater than 1
  ^ p != k         // make sure that p is not equal to k
                   // (so the product XOR'ed with p != k must give 0)
  | ~(p & k) & 3   // make sure that both p and k are congruent to 3 mod 4
  || print(n)      // print n if all tests pass

```

# Answer
> 1 votes
# Python 3.8 (pre-release), 134 bytes

```
f=lambda n,p=[],s=2:sorted(i*j for j in p for i in p if i<j)[:n]if n<len(p)else f(n,p+[s]*(all(s%i for i in range(2,s))and s%4>2),s+1)

```

Try it online!

Output the first n numbers of the sequence.

## Explanation

Creates a list of primes `p` starting with the empty list. First, check if `p` has more than `n` elements (this is frankly quite arbitrary, we clearly need less primes than that.)

If there are, then we output the first `n` elements of the sorted list of products `i*j` for each possible duo of `i` and `j` in `p` if i\<j to prevent duplicates.

Otherwise check if the counter is `s` is prime. Recall `f` with `n` and either p unchanged if s is composite or `p+[s]` if s is prime. Also increment `s`.

Remove the colon before n to get a program which outputs the nth Blum integer, 0-indexed.

Log: 151-\>150-\>142-\>139-\>138-\>137-\>134

# Answer
> 1 votes
# Brachylog, 8 bytes

```
ḋĊ≠%₄ᵛ3&

```

Try it online!

Acts as an infinite generator.

## Explanation

```
ḋĊ≠%₄ᵛ3&
ḋ         The input's prime decomposition
 Ċ        is a pair
  ≠       of distinct values
   ᵛ      which all
    %₄    modulo 4
      3   equal 3.
       &  The input and the output are the same.

```

# Answer
> 0 votes
# Python 2, ~~118~~ 112 bytes

Prints the first `n` Blum integers.

```
n=input()
P=4
k=3
r=p=[]
while p[n:]<=p:
 if P%k&k/2:r=r+[x*k for x in p];p+=k,
 P*=k*k;k+=1
print sorted(r)[:n]

```

Try it online!

Uses Wilson's theorem. `p` keeps track of all primes of the form \\$4t+3\\$, `r` is a unique list of all Blum integers that can be created with the primes in `p`.

# Answer
> 0 votes
# Charcoal, 28 bytes

```
ＦＮ«≦⊕χＷ⁻³¹↨⁴﹪Φχ∧μ¬﹪χλ⁴≦⊕χ»Ｉχ

```

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

```
ＦＮ«

```

Loop the given number of times.

```
≦⊕χ

```

Increment the result variable (predefined to `10`, which is fortunately less than the first Blum integer).

```
Ｗ⁻³¹↨⁴﹪Φχ∧μ¬﹪χλ⁴

```

Take the proper factors of the variable, reduce them modulo `4`, interpret the list as a base `4` integer, and repeat while the result is not `31` (`133` in base 4)...

```
≦⊕χ

```

... increment the result variable.

```
»Ｉχ

```

Output the result.

# Answer
> 0 votes
# jq, 61 bytes

Prints all Blum integers.

```
0|while(1;.+1)|select([[.%range(2;.)]|indices(0)[]%4]==[1,1])

```

Try it online!

For all practical reasons `0|while(1;.+1)` could be replaced with `range(0|-y0)`, but it feels more like an infinite sequence this way, even if both are limited by the range of representable numbers.

---
Tags: code-golf, sequence, primes
---


title: Parse a lambda for correctness

text:
# Question
Title: Parse a lambda for correctness
*The goal of this challenge is to fill a niche that is mostly lacking on this site. In my observations there most parsing verification challenges fall into two categories:*

*1. Super easy parsing. This parsing can usually be done with a regex, and regex based answers usually do well.
2. Super complex parsing. These are challenges with a lot of small parsing components that would on their own be type 1, but together make for long code with a lot of edge cases.*

*Neither of these categories are really bad, each can have fun challenges, but I want to shoot for something different. A challenge which is hard, hard enough that a regex will be unable to do the brunt of the work but with an easy to understand spec.*

---

The goal of this challenge is to parse a *lisp-like* lambda function. Your code should accept a string as input and output of two possible consistent values. One which corresponds to an affirmative response (i.e. the input is a properly formatted lambda) and the other corresponds to a negative response (i.e. the input is *not* a properly formatted lambda). The string will only contain lowercase letters, spaces and parentheses (`(` or `)`).

I've put together 3 specifications of what constitutes a validly formatted lambda for this challenge. The first is a quick intuition base explanation. It explains the process and what things mean even if it is not perfectly rigorous. The second a formal grammar which expresses the idea succinctly and with no ambiguity. And the third is raw code, which is the hardest to read for humans but allows you to play around with the idea by trying different inputs. I recommend you read one of the first two and play around with the third.

## Formatting

The challenge uses a lisp like format. This consists of "lists" which are just parentheses enclosing lowercase words, and other lists separated each by exactly one space. So

```
(foo (bar baz) foobar)

```

Would be a lisp-like "list". For our challenge each list will be identified by it's first element (which should by highlighted by the syntax highlighter), which must be either `app`, `abs`, or `var`, representing applications, abstractions and variables, respectively.

An application is the application of one lambda function to another. It is represented by a three element list starting with of course `app` followed by two other valid lambda expressions. So if `S` and `K` were valid lambdas then:

```
(app S K)

```

would be a valid lambda too.

The other two abstractions and variables work together, an abstraction introduces new names for variables and variables use those names. An abstraction encloses some lambda which must be valid with the introduced variable name, and a variable can only use names which are given by abstractions that surround it. So

```
(abs x (abs y (var x)))

```

Is valid because the `x` name was introduced and used in a nested context. But

```
(app (abs x (var x)) (var x))

```

Is not because even though there is an abstraction for `x` the second `(var x)` is not surrounded by any abstraction at all, let alone one that introduces `x`.

Additionally abstractions can only introduce *new* variables, so

```
(abs x (abs x (var x)))

```

is not valid because the name `x` is ambiguous, it could refer to either abstraction. Variable names must be a string of lowercase ascii letters (`a`-`z`).

## Grammar

Now for the golfy definition. This parse cannot be defined in terms of a context free grammar, so this grammar uses context. The context is a set of strings of lowercase ascii letters (these are the valid variable names) and is represented here with \\$C\\$. To start \\$C\\$ is empty.

\\$ S\left(C\right) := \left\\{ \begin{array}\[rr\] \ \color{green}{\texttt{(var }}x\color{green}{\texttt{)}} & \textrm{ where } x\in C \\ \color{green}{\texttt{(abs }} x\texttt{ }S(C\cup\\{x\\})\color{green}{\texttt{)}} & \textrm{ where } x\notin C\\ \color{green}{\texttt{(app }} S(C)\texttt{ }S(C)\color{green}{\texttt{)}} & \end{array} \right. \\$

Any string spanned by the grammar from \\$S(\\{\\})\\$ is valid and any string not is invalid.

## Code

```
lambda :: [String] -> Parser ()
lambda variables =
  do
    char '('
    choice
      [ do
        string "abs "
        name <- some $ charBy (`elem` ['a'..'z'])
        guard $ notElem name variables
        char ' '
        lambda (name : variables)
      , do
        string "var "
        choice (map string variables)
        return ()
      , do
        string "app "
        lambda variables
        char ' '
        lambda variables
      ]
    char ')'
    return ()

```

Try it online!

## Scoring

This is so answers will be scored in bytes with the goal being a smaller score.

## Test cases

### Reject

```
(abs x (var x
uuuuuuuuu
)))(abs x (var x))
app (abs x (var x)) (abs x (var x))
(mmm hummus)
(abs x (var y))
(abs x (abs x (var x)))
(app (abs x (var x)) (var x))
(abs (var k) (var (vark k)))
(abs x (abs y (abs y (var x))))
(abs x(var x))

```

### Accept

```
(abs x (var x))
(abs x (abs y (var x)))
(abs xx (app (var xx) (var xx)))
(app (abs ab (app (var ab) (var ab))) (abs ab (app (var ab) (var ab))))

```

# Answer
# Perl 5 `-p`, 86 bytes

Who said this can’t be solved with a regex? ☺

```
$_=reverse=~/^(\)(((\w+) (?=([^)]|(?1))* \4 ))rav|(?1) ((?!(?3))\w+ sb|(?1) pp)a)\()$/

```

Try it online!

Outputs `1` for acceptance or the empty string for rejection. To get around restrictions on lookbehind, I reverse the input and use lookahead instead.
> 19 votes

# Answer
# Raku (Perl 6) `-p`, 123 bytes

```
my %v;my$r=rx["(abs "(\w+)<!{%v{$0}++}>\s<~~>{--%v{$0}}")"|"(app "<~~>\s<~~>")"|"(var "(\w+)<?{%v{$0}}>")"];$_=so m/^^$r$$/

```

Try it online!

First time golfing in Raku (this seemed like an apt challenge to give it a spin), so there's probably room for improvement. It's a simple parse of the text, using the `%v` hash to keep track of existing variables.
> 5 votes

# Answer
## Tiny Lisp, 318

```
(d C(q((E L)(i(e L())0(i(e E(h L))1(C E(t L)))))))(d H(q((le li)(i(e()li)(e le 0)(H(s le 1)(t li))))))(d I(q((L X)(i(e(q abs)(h L))(i(H 3 L)(i(C(h(t L))X)0(I(h(t(t L)))(c(h(t L))X)))0)(i(e(q var)(h L))(i(H 2 L)(i(C(h(t L))X)1 0)0)(i(e(q app)(h L))(i(H 3 L)(i(I(h(t L))X)(I(h(t(t L)))X)0)0)0))))))(d V(q(()(L)(I L()))))

```

This defines a macro `V` (for verify) which can be applied to a list, and will check whether it is of the proper form as defined in the question.

This can't do any checks on a lexical level, as Tiny Lisp has no string input (and not even a string type). Therefore it is running out of competition

Here are some test cases:

```
------examples-from-question-----
((V (abs x (abs y (var x))))  ––→  1)
((V (app (abs x (var x)) (var x)))  ––→  0)
((V (abs x (abs x (var x))))  ––→  0)
----examples-from-TIO----
((V (var x))  ––→  0)
((V (abs vv (var vv)))  ––→  1)
((V (abs xy (var fg)))  ––→  0)
((V (abs x (abs y (var x))))  ––→  1)
((V (app (abs x (var x)) (var x)))  ––→  0)
((V (abs x (app (var x) (var x))))  ––→  1)
((V (app (abs x (app (var x) (var x))) (abs y (app (var y) (var y)))))  ––→  1)
((V (abs x (abs x (var x))))  ––→  0)
((V (abs x (abs y (abs y (var x)))))  ––→  0)
((V (abs (var)))  ––→  0)
---reject---------
((V uuuuuuuuu)  ––→  0)
((V (mmm hummus))  ––→  0)
((V (abs x (var y)))  ––→  0)
((V (abs x (abs x (var x))))  ––→  0)
((V (app (abs x (var x)) (var x)))  ––→  0)
((V (abs (var k) (var (vark k))))  ––→  0)
((V (abs x (abs y (abs y (var x)))))  ––→  0)
((V (abs x (var x)))  ––→  1)
--------accept--------
((V (abs x (var x)))  ––→  1)
((V (abs x (abs y (var x))))  ––→  1)
((V (abs xx (app (var xx) (var xx))))  ––→  1)
((V (app (abs ab (app (var ab) (var ab))) (abs ab (app (var ab) (var ab)))))  ––→  1)

```

The last "reject" case (with the missing space) is accepted, as we are parsing this as a tiny lisp list, not as a lambda. The test cases with unbalanced parentheses can't even be run.

Here is the code formatted, and with some comments (I've extended the reference implementation of Tiny Lisp to include Python-style line comments). (The comments all start with `#!` because that can be handled by my automated whitespace-and-comment-remover made for Ceylon.)

```
#! tinylisp.py

#! Parse a lambda for correctness.
#! Question: https://codegolf.stackexchange.com/q/233453/2338
#! My answer: https://codegolf.stackexchange.com/a/233925/2338

#! checks whether some element is contained in a list.
(d C #! for "contains"
   (q ((E L) #! E = the element to be checked
             #! L = the list in which the element is searched
       (i (e L ())
          0
          (i (e E (h L))
             1
             (C E (t L))
          )
       )
      )
   )
)

#! checks whether a list has a specified length.
#! len = expected length
#! list = list to check
(d H #! for has-length
   (q ((le li) #! le = the asserted length
               #! li = the list to check
       (i (e () li)
          (e le 0)
          (H (s le 1) (t li))
       )
      )
   )
)

#! This is the main working force here.
#! I (for "is-valid") checks (recursively) whether a lambda expression is valid
#! in a given context of defined variable names.
(d I
   (q ((L X)
       #! L = candidate for a lambda function,
       #! X (context) = list of defined variable names
       (i (e (q abs) (h L))
          (i (H 3 L)
             (i (C (h (t L)) X)
                0
                (I (h (t (t L))) (c (h (t L)) X)))
             0)
          (i (e (q var) (h L))
             (i (H 2 L)
                (i (C (h (t L)) X)
                   1
                   0)
                0
             )
             (i (e (q app) (h L))
                (i (H 3 L)
                   (i (I (h (t L)) X)
                      (I (h (t (t L))) X)
                      0)
                   0)
                0
             )
          )
       )
      )
   )
)

#! V (for "verify") is the entry point to call from the outside.
#! `(V (...))` returns 1 when it's a valid lambda expression, 0 when it is not.
(d V
   (q (()
       (L)
       (I L ())
      )
   )
)

```
> 3 votes

# Answer
# Curry (PAKCS), 116 bytes

```
p"(var "a x|elem a x=0
p"(app "(a++' ':b)x=a#x+b#x
p"(abs "(a++' ':b)x|all(>'@')a=b#(a:x)
(#)(k++n++")")=p k n
(#[])

```

Try it online!

`g` returns `0` if there is a match and fails to find a match if there is none.

## Explanation

This looks and sort of works like a Haskell answer might. However Curry's pattern matches are way more powerful than Haskell's because it has a trick up it's sleeve. As well as a functional programming language Curry is a logical language. It has non-determinism.

In Haskell a pattern either matches or it doesn't. In Curry a pattern can match a string multiple ways and it will follow through each to find the one you meant. So

```
p("(app "++a++' ':b++")")

```

Will cold potentially match many things. For example

```
p"(app (var x) (var y))"

```

can break that apart at any space in the string. Curry will match all of them and attempt to run them. All the bad ones will fail later down the line.
> 3 votes

# Answer
# Scala, 293 bytes

The function that does all the work:

```
def f(s:Any,c:Set[Any]=Set()):Option[Any]=s match{case
s"(var $v)$r"=>Option.when(c(v))(r)case
s"(abs $v $r"=>if(!c(v)&v.matches("[a-z]+"))f(r,c+v).collect{case s")$r"=>r}else None case
s"(app $o"=>f(o,c).collect{case s" $r"=>f(r,c)}.flatten.collect{case s")$r"=>r}case
_=>None}

```

This one simply turns an `Option` into a `Boolean`.

```
f(_)==Some("")

```

Try it in Scastie!

Ungolfed:

```
//sexpr is the string to parse, ctx is the context (a Set[String] in reality)
//If valid, it will return a Some containing the rest of the string, otherwise a None
def f(sexpr: Any, ctx: Set[Any] = Set()): Option[Any] = sexpr match {
  case s"(var $varName)$rest" =>
    //Check if varName is defined, and only then return the rest
    Option.when(ctx.contains(varName))(rest)
  case s"(abs $varName $rest" =>
    //Make sure varName isn't already defined and that it's a valid name
    if (!ctx.contains(varName) && varName.matches("[a-z]+"))
      //If so, parse the rest, adding varName to the context
      f(rest, ctx + varName)
        .collect { case s")$rest" => rest } //Ensure there's a matching `)`
    else None //If the name is invalid, so is the expression
  case s"(app $first" =>
    //Try parsing the first argument
    f(first, c)
      //Ensure there's a space after it and parse the rest
      .collect { case s" $rest" => f(rest, ctx) }
      .flatten //Turn the Option[Option[String]] into an Option[String]
      .collect { case s")$rest" => rest } //Ensure there's a matching `)`
  case _ => None //If it's not a var, abs, or app, it's invalid
}

```
> 1 votes

---
Tags: code-golf, string, decision-problem, parsing, lambda-calculus
---


title: Code golf edit distance up to 3

text:
# Question
Title: Code golf edit distance up to 3
The **edit distance** between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other.

This task is simply to write code that determines if two strings have edit distance at most 3 from each other. The twist is that your code must run in **linear time**. That is if the sum of the lengths of the two strings is `n` then your code should run in `O(n)` time.

# Example of strings with edit distance 2.

```
elephant elepanto
elephant elephapntv
elephant elephapntt
elephant lephapnt
elephant blemphant
elephant lmphant
elephant velepphant

```

# Example of strings with edit distance 3.

```
   elephant eletlapt
   elephant eletpaet
   elephant hephtant
   elephant leehanp
   elephant eelhethant

```

# Examples where the edit distance is more than 3. The last number in each row is the edit distance.

```
elephant leowan 4
elephant leowanb 4
elephant mleowanb 4
elephant leowanb 4
elephant leolanb 4
elephant lgeolanb 5
elephant lgeodanb 5
elephant lgeodawb 6
elephant mgeodawb 6
elephant mgeodawb 6
elephant mgeodawm 6
elephant mygeodawm 7
elephant myeodawm 6
elephant myeodapwm 7
elephant myeoapwm 7
elephant myoapwm 8

```

You can assume the input strings have only lower case ASCII letters (a-z).

Your code should output something Truthy if the edit distance is at most 3 and Falsey otherwise.

If you are not sure if your code is linear time, try timing it with pairs of strings of increasing length where the first is all 0s and the second string is two shorter with one of the 0s changed to a 1. These all have edit distance 3. This is not a good test of correctness of course but a quadratic time solution will timeout for strings of length 100,000 or more where a linear time solution should still be fast.

(This question is based on this older one)

# Answer
> 1 votes
# Haskell, ~~93~~ 90 bytes

```
x%y=[0,0,0]>=x#y
u@(a:b)#v@(c:d)|a==c=b#d|k<-zipWith(+)=0:k(d#u)(k(b#v)$b#d)
a#b=a++b>>[0]

```

Try it online!

This is taken from this previous answer of mine with basically no modification.

## How it works:

We start by looking at a naive version of edit distance:

```
lDistance :: ( Eq a ) => [a] -> [a] -> Int
lDistance [] t = length t   -- If s is empty the distance is the number of characters in t
lDistance s [] = length s   -- If t is empty the distance is the number of characters in s
lDistance (a:s') (b:t') =
  if
    a == b
  then
    lDistance s' t'         -- If the first characters are the same they can be ignored
  else
    1 + minimum             -- Otherwise try all three possible actions and select the best one
      [ lDistance (a:s') t' -- Character is inserted (b inserted)
      , lDistance s' (b:t') -- Character is deleted  (a deleted)
      , lDistance s' t'     -- Character is replaced (a replaced with b)
      ]

```

(I wrote this program for Wikipedia here)

This is pretty bad because every time it finds a discrepancy between the two strings it branches into 3 options (insert, delete or replace) so in the worst case it will have the time complexity of \\$O(3^n)\\$.

The thing to notice though is that whenever we branch we increase the total distance by 1. So if we are on a particular search path that has already branched 3 times and we would branch another time. So we can just stop there and say return `False` for this branch since it can never find the result.

Now there is a hard limit on the number of branches that can occur, \\$3^3 = 27\\$, so our computation is \\$O(n)\\$.

In general this strategy has a complexity of \\$O(3^mn)\\$ where \\$m\\$ is the limiting distance.

# Answer
> 1 votes
# Prolog (SWI), 120 bytes

```
_+[]+[].
N+[A|B]+[A|C]:-!,N+B+C.
N+[_|B]+C:-N>0,N-1+B+C.
N+B+[_|C]:-N>0,N-1+B+C.
N+[_|B]+[_|C]:-N>0,N-1+B+C.
B*C:-3+B+C.

```

Try it online!

This is the same basic algorithm as my Haskell answer, but it implements it using Prolog's built in search.

We have to add a cut on the second case

```
N+[A|B]+[A|C]:-!,N+B+C.

```

If we don't the will try to branch even when the first two characters are the same. This will cause exponential branching with respect to the length of the string.

The cut here ensures that if the first two characters are the same we don't backtrack.

The Haskell answer doesn't have this issue because Haskell will eagerly follow the first path of execution.

# Answer
> 1 votes
# Prolog (SWI), 109 bytes

```
_+[]+[].
N+[A|B]+[A|C]:-!,N+B+C.
\N+B+C:-B=[_|X],N+X+C;C=[_|Y],N+B+Y;B=[_|X],C=[_|Y],N+X+Y.
B*C:- \ \ \a+B+C.

```

Try it online!

This is a golf of Wheat Wizard's answer. The key modification I made was that instead of using Prolog's built in numbers and arithmetic to keep track of the the current edit distance, I instead used nested compound terms, built using the unary operator `\`. Thus instead of having to check if `N` is greater than zero and then use subtraction, I can roll both of those steps into a single pattern match by matching the current remaining edit distance to `\N`. This left me with the following program (111 bytes):

```
_+[]+[].
N+[A|B]+[A|C]:-!,N+B+C.
\N+[_|B]+C:-N+B+C.
\N+B+[_|C]:-N+B+C.
\N+[_|B]+[_|C]:-N+B+C.
B*C:- \ \ \a+B+C.

```

I managed to save a couple more bytes by merging the latter three rules for the `+` predicate into a single rule, as described here.

---
Tags: code-golf, restricted-time
---


# Question
Title: Rock Paper Scissors Meta-Gaming Tournament
This is a rock paper scissors competition. Algorithms will face each other in 100 rounds of rock paper scissors. Except that the algorithms will also be able to read the source code of each other!

# Leaderboard

```
1. Chaos Bot (by Aiden4) - 27 Points, 168 bytes
2. Anti-99%-of-posts (by Lyxal) - 24 Points, 489 bytes
3. Psuedo-Hash Cycle (by qwatry) - 23 Points, 143 bytes
4. Destroyer of Bots (by Baby_Boy) - 23 Points, 433 bytes
5. If-If (by PkmnQ) - 21 Points, 63 bytes
6. Biased-Cycler (by HighlyRadioactive) - 20 Points, 17 bytes
7. RadiationBot v0.1 (by HighlyRadioactive) - 18 Points, 121 bytes
8. Cycler (by petStorm) - 17 Points, 17 bytes
9. Craker (by petStorm) - 17 Points, 58 bytes
10. Lookup (by petStorm) - 17 Points, 61 bytes
11. Custom (by petStorm) - 16 Points, 56 bytes
12. Anti-Cycler (by Lyxal) - 14 Points, 17 bytes
13. Mr. Paper - 13 Points, 58 bytes
14. PseudoRandom (by HighlyRadioactive) - 13 Points, 89 bytes
15. Itna-Cycler (by petStorm) - 11 Points, 17 bytes
16. Lycler (by petStorm) - 11 Points, 24 bytes
17. Mr. Rock - 11 Points, 57 bytes
18. Mr. Scissors - 10 Points, 61 bytes

```

Submissions are graded automatically via an online judge

View Online Judge

# The Competition

Your code will be a javascript anonymous function (sorry, other languages aren't supported!) that takes in two arguments:

* The source code of your opponent AI (as a string)
* The current round number

It should then return one of "R", "P", or "S", indicating that it will throw a rock, paper, or scissors for that round.

Your code must follow these rules, otherwise it will be disqualified:

* **Your code may not be longer than 500 bytes**
* **Your function must be pure**
    + That is, if your function is given the same set of arguments, your code must always return the same result
    + This is to ensure that the tournament results are consistent
* **eval() calls are banned!**
    + If this were allowed, two submissions with eval() would end up calling each other in an endless loop which would never terminate.
    + (See the discussion in the comments for more details/reasoning)
* Your code may not:
    + Access external resources (e.g. make web fetch/get requests)
    + Attempt to modify or tamper with the judge system code
    + Cause excessive lag or time delay
    + Modify any globals or object prototypes
    + Attempt to do an XSS attack or any other sketchy/illegal stuff

## Example submission

```
(code, round) => {
  if (round === 1) {
    // Throw rock if it's the first round
    return "R";
  }
  else if (code.includes('"R"')) {
    // Throw paper if the opponent code includes "R"
    return "P";
  } else {
    // Otherwise throw scissors
    return "S";
  }
}

```

# Tournament structure

Each submission will play 100 rounds of rock paper scissors with each other submission.

To get the ball rolling, the following three functions will be submitted by default:

```
(code, round) => {
  // Always throw rock
  return "R";
}

```

```
(code, round) => {
  // Always throw paper
  return "P";
}

```

```
(code, round) => {
  // Always throw scissors
  return "S";
}

```

# Scoring

A submission gains 2 points for winning against another submission, and 1 point for tying against another submission (no points are awarded for losses).

Leaderboard positions are ordered by most points first. If two submissions have the same number of points, they will be ranked in order of least bytes. If two submissions have the same number of points and bytes, the older submission will be ranked higher.

# Judging & Testing

Post your submissions here, I will periodically add submissions to the online judge which will automatically rank each algorithm.

You can also test your algorithms using the online judge testing area. A testing area is provided at the bottom to test different algorithms against each other.

# Answer
# Chaos Bot

I lost track of what's going on here, but it seems to win or tie everything but the standard cycler.

```
(c,r) => {if(c.includes("else")){return "SSR"[r%3];}if(c.includes("/")){if(c.includes("P")){return "S";//17
} return "SRP"[r%3];} else{return "PPS"[(c.length + r)%3];}}

```
> 5 votes

# Answer
# Anti-99%-of-posts

```
(code,r)=>{var S="S";var R="R";var P="P";var x=S+R+P;var y=R+P+S;var z=P+S+R
if(code.includes("17")){return "P";}
else if(code.includes("[r%2]")){return"RR"[r%2]}
else if(code.includes("[r%3]")){
if (code.includes(x)){return (R+P+S)[r%3];}
else if(code.includes(y)){return (P+S+R)[r%3];}
else if(code.includes(z)){return (S+R+P)[r%3];}
}else{if(code.includes("scissors")){return "R"}else if (code.includes("rock")){return "P"}else if (code.includes("paper") ){return "S"}else{return "P"}}}

```

Haha. Testing it on submissions gives either a win or a tie.
> 4 votes

# Answer
# If-If

```
(c,r)=>{if(c.includes("i")){return"RPS"[2]}else{return"P"}; 17}

```

This was built off of an algorithm that detected if "if" was in the code.
> 4 votes

# Answer
## Cycler

Picks depending on the round number.

```
(c,r)=>"RPS"[r%3]

```
> 3 votes

# Answer
## Custom

A bot designed to beat the default bots. I'm a horrible golfer indeed...

Edit: I'm now also trying to get around RadiationBot, by changing the algorithm.

```
(c,r)=>["P","S","R"][-~[["P","S","R"].findIndex(i=>!c.indexOf(i))%3]]

```
> 3 votes

# Answer
# Anti-Cycler

```
(c,r)=>"PSR"[r%3]

```

Someone had to do it. Why not me? ;P
> 3 votes

# Answer
# RadiationBot v0.1

HighlyRadioactive's botty bot.

```
(c,r)=>{if(c.indexOf("RP")>=0){return "PSR"[r%3];}else if(c.indexOf("PS")>=0){return "SRP"[r%3];}else{return "RP"[r%2];}}

```
> 2 votes

# Answer
## Lookup

The lookup table here explains everything.

```
(c,r)=>({17:["R","P","S"][(r-(~-c.slice(8).indexOf(`S`)||(r-3+r%2))+3)%3],24:"S",56:"S",58:"S",63:["P","S","R"][2],69:"S",81:"P",121:"PS"[r%2],168:"SSR"[(c.length+r)%3],489:"S"})[c.length]||"R"

```
> 2 votes

# Answer
## Lycler

Like Cycler, but this time with length.

```
(c,r)=>"RPS"[c.length%3]

```
> 2 votes

# Answer
# Destroyer of Bots

```
//"P" else
(c,r) => {if(c.includes("SSR")){return "R";}else if(c.includes("PRPSRS")){return "S"}else if(c.includes("RRP")){return "F";return"S"}else if(c.includes("paper")){return"S"}else if(c.includes("rock")){return"P"}else if(c.includes(".findIndex")){return"F";return "PSR"[c.length%3]}else if(c.includes("SRP")){return "RPS"[r%3]}else if(c.includes("RPS")){return"F";return "PSR"[r%3]}else if(c.includes("RP")){return"S"}else{return "R";}}

```

This bot uses confusion tactics and targeted attacks to win or tie against all current bots.

note: Wins against Chaos Bot, current #1 bot.
> 2 votes

# Answer
# PseudoRandom

```
(c,r)=>{a=0;for(i=0;i<c.length;i++){a+=c[i].charCodeAt()^r^i;}return "RPS"[a%3];}

```

Not too random I guess but I tried.
> 1 votes

# Answer
## Itna-Cycler

Let's raise the maximum score of the cycler family to 8!

```
(c,r)=>"SRP"[r%3]

```
> 1 votes

# Answer
## Craker

Inspired by Custom. (Hopefully) does something different.

```
(c,r)=>"RPS"[-~[..."RPS"].findIndex(i=>c.indexOf(i)>-1)%3]

```
> 1 votes

# Answer
# Biased-Cycler

```
(c,r)=>"RRP"[r%3]

```

Yay.
> 1 votes

# Answer
## #\</\>

Let's add an awful hash answer.

```
(c,r)=>"SPR"[c.split``.reduce((t,i)=>(t<<5)+i.charCodeAt(0),5381)%3]

```
> 1 votes

# Answer
# Psuedo-Hash Cycle

```
(c, r) => {var hash = 0;for (var i = 0; i < c.length; i++){var char = c.charCodeAt(i);hash = hash + char;}return "PRPSRS"[(c.length+hash+r)%6]}

```

This function is intended to return nearly-random values that will be difficult to predict.
> 1 votes

---
Tags: king-of-the-hill
---


title: Asciimation Jumping Jacks

text:
# Question
Title: Asciimation Jumping Jacks
This is my first challenge, so I'm keeping it fairly simple.

If you've ever typed `telnet towel.blinkenlights.nl` on your command line and pressed enter, you will have experienced the joy of asciimation. Asciimation is, quite simply, doing an animation with ascii art. Today we will be doing a very basic asciimation of a person doing jumping jacks.

There will be two ascii pictures that we will put together into one asciimation. Number 1:

```
_o_
 0
/ \

```

Number 2:

```
\o/
_0_
<blank line>

```

Note that the second one has a blank line at the end.

So your program should do these steps:

1. Clear the console screen.
2. Print the correct ascii art image.
3. Set a flag or something so you know to do the other image next time.
4. Wait a moment (about a second).
5. Continue at 1.

# Rules

* Your program must be a (theoretically) infinite loop.
* The programming language you use must have been created before this challange was posted.
* This is , so shortest code in bytes wins.
* Standard loopholes apply.

Enjoy!

# Answer
# CJam, ~~51~~ ~~45~~ ~~42~~ ~~38~~ 36 bytes

```
"c\o/
_0_""^[c_o_
 0
/ \^["{_o\6e4m!}g

```

The above uses caret notation; the sequence `^[` is actually the ASCII character with code point 27.

I've borrowed the escape sequence (`^[c`) from @DomHastings' answer (with his permission) to save 4 bytes.

### Verification

You can recreate the file like this:

```
base64 -d > jj.cjam <<< ImNcby8KXzBfIiIbY19vXwogMAovIFwbIntfb1w2ZTRtIX1n

```

To run the code, download the CJam interpreter and execute this:

```
java -jar cjam-0.6.5.jar jj.cjam

```

This will work on any terminal that supports console\_codes or an appropriate subset.1

### How it works

```
e# Push both jumping jacks on the stack.

"c\o/
_0_"

"^[c_o_
 0
/ \^["

e# When chained together, they contain two occurrences of the string "\ec",
e# which resets the terminal. Encoding the ESC byte in the second string
e# eliminates the need two escape a backslash before the string terminator.

{         e# Do:
  _o      e#   Copy the jumping jack on top of the stack and print the copy.
  \       e#   Swap the order of the jumping jacks.
  6e4m!   e#   Calculate the factorial of 60,000 and discard the result.
          e#   This takes "about a second".
}g        e# Since the discarded factorial was non-zero, repeat the loop.

```

---

1 The jumping jacks will look better if you hide the terminal's cursor before running the program. In Konsole, e.g., you can set the cursor's color to match the background color. This has to be done via your terminal's settings, since `^[c` resets the terminal.
> 28 votes

# Answer
# Pyth - ~~41~~ ~~40~~ 39 bytes

```
.VZ"\x1b[H\x1b[J"@c"_o_
 0
/ \\\o/
_0_"Tb .p9

```

(I'm counting the `\x1b`'s as one byte since SO destroys special characters).

Clearly doesn't work online since its a) an infinite loop and b) uses terminal escape codes.

```
#                Infinite loop
 "..."           Print escape sequences to clear screen
 @               Modular indexing
  c     T        Chop at index ten into the constituent frames
   "..."         Frames 1 & 2 concatenated (Pyth allows literal newlines in strings)
  ~              Post assign. This is an assign that returns the old value.
   h             Increment function. Putting it after an assign makes it augmented assign.
   Z             Variable auto-initialized to zero.
 .p9             Permutations(range(9), 9). Takes about a second on my machine.

```

I was surprised to find out that augmented-assign worked with post-assign. Pyth is awesome.
> 10 votes

# Answer
# QBasic, ~~58~~ 54 bytes

Tested on QB64 and at Archive.org.

```
CLS
?"_o_
?0
?"/ \
SLEEP 1
CLS
?"\o/
?"_0_
SLEEP 1
RUN

```

The right language for the problem can be surprisingly competitive, even if it is usually verbose. The `?` shortcut for `PRINT` helps too, of course. `CLS` is **cl**ear **s**creen; `RUN` without arguments restarts the program, which is the shortest way to get an infinite loop.

The only other trick here is printing `0` for the midsection of the first picture. QBasic puts a space in front of (and after) nonnegative numeric values when it prints them, resulting in  `0` . Saved 2 characters over `" 0`.

I may also point out that the delay in this code is *literally a second*, and is not machine-dependent. ;^P
> 9 votes

# Answer
# Perl *(\*nix)*, 54 bytes

```
sleep print"\x1bc",$-++%2?'\o/
_0_
':'_o_
 0
/ \
'while 1

```

(`\x1b` is counted as 1 byte but escaped for easier testing.) The above has been tested with Bash and shortened by another byte thanks to @Dennis!

# Perl *(Windows)*, 56 bytes

```
sleep print"\x1b[2J",$-++%2?'\o/
_0_
':'_o_
 0
/ \
'while 1

```

Thanks to @Jarmex for his testing and advice!
> 7 votes

# Answer
# Javascript (ES6), ~~109~~ ~~93~~ ~~79~~ 70 bytes + HTML, ~~12~~ 10 bytes = ~~120~~ ~~106~~ ~~91~~ 80 bytes

Fairly straightforward. Uses template strings to store the images, and toggles a boolean value to determine which to use.

**NOTE:** This solution may not be valid, as it does not actually use a console. However, I don't believe it's possible to clear a browser console using JS, at least not while using Firefox.

```
a=!1,setInterval(_=>O.innerHTML=(a=!a)?`_o_
 0
/ \\`:`\\o/
_0_`,1e3)
```

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

# Answer
# Bash, ~~86~~ 84 bytes

```
while sleep 1;do printf "\e[2J_o_\n 0\n/ \\";sleep 1;printf "\r\e[2J\o/\n_0_\n";done

```
> 5 votes

# Answer
# Dash, 67 bytes

Also `bash`, `ksh`, `zsh`, `ash`, `yash` and probably many more besides. While it apparently works in these other shells, their own features and idiosyncrasies may allow for further golfing. I'll leave that as an exercise for the reader.

Notably **not** `fish` or `tcsh`.

```
f(){ clear;echo "$1";sleep 1;f "$2" "$1";};f '_o_
 0
/ \' '\o/
_0_'

```

Try it online! (with STDERR issue -- see **Caveats**)

Try it online! (with visible escape codes issue -- see **Caveats**)

# How it works

Hopefully fairly self explanatory, even so:

Set up a function `f` which

* Clears screen
* Prints contents of `$1`
* Sleeps 1 second
* Calls `f` passing `$1` and `$2` in reverse order. This means the next iteration will display the "other" glyph before flipping them again... and so on.

Outside of the function is the initial call to `f` with literal depictions of the two character glyphs as two arguments.

# Caveats

TIO's terminal implementation doesn't handle the `clear` well -- produces an error to STDOUT. If you add `export TERM=vt100` as a header the error stops and it displays the literal escape string. This is a feature/limitation of TIO, not an issue with my submission. I've included links to both for reference. Code should work as intended in a "proper" terminal.

The recursion will eventually cause it to fail. Tried a soak test with `sleep 0` in a Docker container and it threw a Segmentation Fault within a minute. Adding a trivial counter, which may or may not have quantum implications, it managed ~15000 iterations in my environment. So like 4 hours with the `sleep` -- and who's going to watch it **that** long? :-)

But I'd still argue that this complies with "theoretically" infinite, because it could go forever if it had "theoretically" infinite resources. That's my story and I'm sticking to it.
> 4 votes

# Answer
# awk - 95 92 86 84 83

```
END{
    for(;++j;)
        system("clear;printf '"(j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")"';sleep 1")
}

```

Nice workout :D Just wondered if this was doable. No prices to gain though... ;)

If someone wants to test this: after you run the program you have to press Ctrl+D (end of input) to actually start the END block. To terminate it I have to use Ctrl+Z.

I also have this, which is only 74 bytes, but it starts with pausing a second which isn't the wanted behaviour I think

```
END{
    for(;1;print++j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")
        system("sleep 1;clear")
}

```
> 3 votes

# Answer
# Python 2, 99 bytes

Runs on Windows

```
import os,time
g=0
while 1:os.system("cls");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g

```

For UNIX machines, add two bytes:

```
import os,time
g=0
while 1:os.system("clear");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g

```
> 3 votes

# Answer
# JavaScript ES6, ~~100~~ 95 bytes

```
(f=_=>{console.log(_?`_o_
 0
/ \\`:`\\o/
_0_`)
(b=setTimeout)(q=>(clear(),b(b=>f(!_))),1e3)})()

```

Logs to the console. Tested on Safari Nightly
> 2 votes

# Answer
# Batch, ~~151~~ ~~130~~ 118 bytes

```
cls
@echo _o_
@echo  0
@echo / \
@PING -n 2 127.0.0.1>NUL
cls
@echo \o/
@echo _0_
@PING -n 2 127.0.0.1>NUL
%0

```
> 2 votes

# Answer
# CBM 64 BASIC V2, ~~121~~ ~~119~~ ~~112~~ 117 bytes

```
2?CHR$(147)+"\o/":?" 0":?"/ \"
3GOSUB7
4?CHR$(147)+"_o_":?"_0_"
5GOSUB7
6RUN
7A=TI
8IFTI-A<60THENGOTO8
9RETURN

```
> 2 votes

# Answer
# Batch - 82 bytes

Edit: Muted the timeout command and removed the extra newline.

```
cls&echo _o_&echo  0&echo / \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0

```

I've seen 2 other similar batch answers so I didn't really want to post this, but this is my first ever golf.
> 2 votes

# Answer
# BBC BASIC, 75 bytes

Note that tokenisation pulls it down to 75 bytes. The whitespace is added in by the IDE.

```
      g=0
   10 IFg=0THENPRINT"\o/":PRINT"_0_"ELSEPRINT"_o_":PRINT" 0 ":PRINT"/ \"
      g=1-g:WAIT 100CLS:GOTO10

```
> 2 votes

# Answer
# Julia, 70 bytes

(on **Windows**, by replacing `clear` with `cls`, thanks to undergroundmonorail)

```
n(i=1)=(sleep(1);run(`cls`);print(i>0?"_o_
 0
/ \\":"\\o/
_0_");n(-i))

```

### On Linux, 72 bytes

```
n(i=1)=(sleep(1);run(`clear`);print(i>0?"_o_
 0
/ \\":"\\o/
_0_");n(-i))

```

This uses actual newlines rather than `\n` to save a byte; otherwise, the `i` is either 1 or -1 as the "flag", and it uses recursion to achieve the infinite loop. Call it as either `n(1)` or just `n()`.

Also, `run(`clear`)`/`run(`cls`)` uses a shell command to clear the window, because Julia doesn't have a built-in window-clear command.
> 1 votes

# Answer
# Windows Batch, 83 ~~89~~

**Edit** removed the empty line after the clarification by OP

```
@cls&echo _o_&echo  0&echo./ \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0

```

~~If you get rid of the empty line in the jumping man (that cannot be seen anyway), the score is 83~~

Note: `timeout` is not present in Windows XP. It works in Vista or newer versions. Moreover `timeout` is not precise to the second, so it's a perfect choice to implement step 4 (Wait a moment (*about a second*))
> 1 votes

# Answer
# JavaScript, ~~92~~ ~~91~~ 89 bytes

```
x=0;setInterval(function(){console.log("\033c"+["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3)

```
* No ES6 features (but would be significantly shorter with them)
* Works with Node.js on Linux (don't know about other environments)
* Partially works in Chrome's console (`c` is shown instead of clearing the console, breaking the output)

Removing `"\033c"+` from the above code, the following works in the browser, but doesn't clear the console.

```
x=0;setInterval(function(){console.log(["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3)
```
> 1 votes

# Answer
# Javascript (ES6), 82 bytes

A modification of my previous answer that uses the console. Works partially in Firefox, but only clears the console in Chrome, AFAIK.

```
a=!0,c=console,setInterval(_=>c.log(c.clear(a=!a)|a?`_o_
 0
/ \\`:`\\o/
_0_`),1e3)
```

As always, suggestions welcome!
> 1 votes

# Answer
# CBM BASIC v2.0 (68 characters)

```
0?"S_o_q||0q||N M":goS1:?"SMoN":?"_0_":goS1:gO
1wA161,255,pE(161):reT

```

The above requires some explanation, since Stack Exchange markup doesn't properly represent PETSCII characters:

* The program is shown here for convenience in lowercase, but can and should be entered and run in uppercase mode on a Commodore 64.
* The first and third "S" characters are actually in reverse video, and produced by pressing the `CLR` key (`SHIFT`+`HOME`).
* The "q" characters are actually in reverse video, and produced by pressing the down cursor (`CRSR ⇓`).
* The "|" characters are actually in reverse video, and produced by pressing the left cursor (`SHIFT`+`CRSR ⇒`).
> 1 votes

# Answer
# TI-Basic, ~~58~~ 56 bytes

```
While 1
ClrHome
If not(Ans
Disp "_o_"," 0","/ \
If Ans
Disp "\o/","_0_"
not(Ans
If dim(rand(70
End

```

-2 bytes for assuming that the code is run on a fresh interpreter.
> 1 votes

# Answer
## Ruby, 79 bytes

```
k=!0;loop{puts((k)?"\e[H\e[2J_o_\n 0\n/ \\":"\e[H\e[2J\\o/\n_0_");k=!k;sleep 1}

```

Requires escape codes.
> 0 votes

# Answer
# Forth, 86 bytes

Requires GNU Forth for the escaped strings. To run in a non-GNU Forth, just change `S\"` to `S"`, and the escaped characters won't print correctly.

```
: P PAGE TYPE CR 999 MS ;
: R BEGIN S\" \\o/\n_0_" P S\" _o_\n 0 \n/ \\" P 0 UNTIL ; R

```
> 0 votes

# Answer
# beeswax, ~~119~~ 113 bytes

```
ph0`J2[`}ghq'-<gh0N}`0`}gN`/o\`Ngh0`J`<
>g}`o`}N` `0>'d`0 `N`/ \`0hg>-'phg}`[2`b
dF1f+5~Zzf(.FP9f..F3_#     d   <

```

Explanation of the important parts of the program:

```
left to right  right to left

3FBf   or       fBF3          27       ASCII code for (esc)
3             [x,x,3]•        set lstack 1st to 3
 F            [3,3,3]•        set lstack to 1st
  B           [3,3,27]•       1st=1st^2nd
   f                          push lstack 1st on gstack
——————
9PF.(f   or    f(.FP9         102400   counter to roughly match a wait time
                                       of 1 s on my i5 2410M Laptop
9             [x,x,9]•        set lstack 1st to 9
 P            [x,x,10]•       increment 1st
  F           [10,10,10]•     set lstack to 1st
   .          [10,10,100]•    1st=1st*2nd
    (         [10,10,102400]• 1st=1st<<2nd (100<<10=102400, arithmetic shift left)
     f                        push lstack 1st on gstack
——————
zZ~5+f   or    f+5~Zz         95       ASCII for '_'
z             [0,0,0]•        initialize lstack to zero
 Z            [0,0,90]•       get value from relative coordinate (0,0),
                              which is the location of `Z` itself, ASCII(Z)=90
  ~           [0,90,0]•       flip 1st and 2nd lstack values
   5          [0,90,5]•       set lstack 1st to 5
    +         [0,90,95]•      1st = 1st+2nd
     f                        push lstack 1st on gstack

```

The `f`’s push the values on the gstack (global stack) for later use. These values are accessed by the `0gh` (or the mirrored `hg0`) and `hg` (`gh`) instructions. `h` rotates the gstack upwards, `g` reads the top value of gstack and pushes it onto the lstack (local stack) of the bee (instruction pointer).

```
}`o`}N` 0 `N`/ \`                      sequence to print the standing man

N`\o/`Ng}`0`}N                         sequence to print the jumping man

}`[2J`                        equivalent to the ANSI escape sequence (esc)[2J
                              to clear the screen
>-'p  or >-'q  or >  p        loop for counting down (wait 1 s)
d  <      b  <    d'-<

```

In-depth explanation follows later, if needed. Maybe with animation.
> 0 votes

# Answer
# Noodel, noncompeting 24 bytes

Noncompeting because *Noodel* was born after the challenge was created:)

```
”ṛ|ọBCḊCBCḣ“\o/¶_0_ḷėçḍs

```

Try it:)

### How it works

```
”ṛ|ọBCḊCBCḣ              # Creates a string that gets decompressed into "_o_¶¤0¤¶/¤\" and places it into the pipe.
           “\o/¶_0_      # Creates a string and places it into the pipe.
                   ḷ     # Unconditionally loop the code up to a new line or end of program.
                    ė    # Takes what is in the front of the pipe and puts it into the back.
                     ç   # Clears the screen and prints.
                      ḍs # Delays for one second.

```

---

There currently is not a version of *Noodel* that supports the syntax used in this challenge. Here is a version that does:

**24 bytes**

```
\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs

```

```
<div id="noodel" code="\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs" input="" cols="5" rows="5"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 0 votes

# Answer
# Nim, 107 bytes

```
import os,terminal
var f=0
while 0<1:eraseScreen();sleep 999;echo ["_o_\n 0 \n/ \\","\\o/\n_0_\n"][f];f=1-f

```

Don't Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, animation
---


title: Verify a Superpermutation

text:
# Question
Title: Verify a Superpermutation
A superpermutation on n symbols is a string which contains every permutation of n symbols in its body. For instance, `123121321` is a superpermutation on three symbols because it contains `123`, `132`, `213`, `231`, `312` and `321` as substrings.

# The Challenge

Given a string composed of n unique symbols (and, optionally, n), output whether it is a superpermutation on n symbols.

# Rules

* This is so the shortest answer in bytes wins.
* Assume only valid input will be given.
* Assume n is greater than 0
* Input and output can assume whatever form is most convenient, e.g. the series of symbols can be a string, a list, an integer, a set of n bitmasks, etc, so long as it is indicated in the answer. Additionally, anything may be used as a symbol provided it is distinct from all the other symbols.

# Test Cases

```
In: 1234
Out: False

In: 1
Out: True

In: 11
Out: True

In: 123121321
Out: True

In: 12312131
Out: False

```

See also: this question about generating superpermutations

# Answer
> 9 votes
# 05AB1E, 4 bytes

```
ÙœåP

```

Only takes input \\$J\\$ (I don't need \\$n\\$ with this approach).

Try it online or verify all test cases.

**Explanation:**

```
Ù     # Uniquify the digits of (implicit) input-integer
 œ    # Get all permutations of this uniquified integer
  å   # Check for each if it's a substring of the (implicit) input-integer
   P  # And check if this is truthy for all of them
      # (after which the result is output implicitly)

```

# Answer
> 7 votes
# APL (Dyalog Unicode), 20 bytes

```
{(!⍺)=+/⍺=⍴∘∪¨∪⍺,/⍵}

```

Try it online!

Takes `n` on the left and `J` on the right

### How?

```
⍺,/⍵   ⍝ Overlapping sublists of length n in J
∪      ⍝ Unique sublists
⍴∘∪¨   ⍝ Length of the unique elements of each unique sublist
+/⍺=   ⍝ How many are equal to n?
(!⍺)=  ⍝ Is this equal to the number of permutations of n symbols?

```

# Answer
> 7 votes
# Python 3, 79 bytes

```
lambda s:all(''.join(p)in s for p in permutations({*s}))
from itertools import*

```

Try it online!

---

# Python 2, 81 bytes

```
lambda s:all(''.join(p)in s for p in permutations(set(s)))
from itertools import*

```

Try it online!

# Answer
> 7 votes
# JavaScript (ES6),  ~~83 82~~  81 bytes

Returns `0` if the input string is a superpermutation, or `1` if it's not.

```
f=(s,a=[...new Set(s)],p)=>!s.match(p)|a.some((c,n)=>f(s,a.filter(_=>n--),[p]+c))

```

Try it online!

### How?

If all permutations of the \\$N\\$ symbols are present in the input string \\$s\\$, so are all prefixes of said permutations. Therefore, it's safe to test that all \\$p\\$ are found in \\$s\\$ even when \\$p\\$ is an incomplete permutation whose size is less than \\$N\\$.

That's why we can use a function that recursively builds each permutation \\$p\\$ of the symbols and tests whether \\$p\\$ exists in \\$s\\$ at each iteration, even when \\$p\\$ is still incomplete.

### Commented

```
f = (                     // f is a recursive function taking:
  s,                      //   s = input string
  a = [...new Set(s)],    //   a[] = list of unique characters in s
  p                       //   p = current permutation, initially undefined
) =>                      //
  !s.match(p) |           // force the result to 1 if p is not found in s
                          // NB: s.match(undefined) is truthy because it's equivalent
                          //     to looking for an empty string in s
  a.some((c, n) =>        // for each character c at position n in a[]:
    f(                    //   do a recursive call:
      s,                  //     pass s unchanged
      a.filter(_ => n--), //     remove the n-th character in a[] (0-indexed)
      [p] + c             //     coerce p to a string and append c to p
    )                     //   end of recursive call
  )                       // end of some()

```

# Answer
> 6 votes
# Japt v2.0a0, ~~10~~ 8 bytes

Saved 2 bytes with the clarification that the string can only contain the digits in `[1,n]`.

```
â á e!øU

```

Try it

```
â á e!øU     :Implicit input of string U
â            :Deduplicate
  á          :Permutations
    e        :All
     !øU     :  Contained in U

```

# Answer
> 5 votes
# Io, 104 bytes

```
method(x,n,K :=Range 1 to(n)asList;x map(i,v,x slice(i,i+n))unique select(x,x sort==K)size==K reduce(*))

```

Try it online!

## Explanation (Ungolfed)

```
method(x,n,                        // Take the string and the num of uniquified integers
    K := Range 1 to(n)asList       // K = [1..n]
    x map(i,v,x slice(i,i+n))      // All slices of x of length n
    unique                         // Uniquify these slices
    select(x,                      // Filter: (x : current item)
        x sort==K                  //     sort(x) == [1..n]?
    ) size                         // Number of items that satisfy this
    == K reduce(*)                 // == factorial(n)?
)

```

# Answer
> 4 votes
# Brachylog, 7 bytes

```
dpᶠ~sᵛ?

```

Same algorithm as @Kevin Cruijssen, so upvote that.

Try it online!

### How it works

```
dpᶠ~sᵛ?
d       deduplicate input
 pᶠ     find all permutations
   ~sᵛ  all of them must be substrings of
      ? the input

```

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

```
Union[##~Partition~1]~Count~{a__/;0!=a}<#2!&

```

Try it online!

Takes a list of characters and \\$n\\$ as input. Returns `False` if the string is a superpermutation, and `True` otherwise.

Verifies that the number of unique sequences of \\$n\\$ distinct characters is (un)equal to \\$n!\\$.

# Answer
> 3 votes
# \+ gtools, 79 bytes

```
function(x,n)all(sapply(apply(permutations(n,n),1,paste0,collapse=""),grepl,x))

```

Try it online!

An example of some awfully-verbose names for R functions and mandatory arguments!

Generates all permutations of digits 1..n, pastes them together as strings, and checks that all are present in the input string.

An alternative **66 byte** solution using the R "combinat" library would be: `function(x,n,`[`=sapply)all(permn(n)[paste0,collapse=""][grepl,x])`, but unfortunately this library isn't installed on TIO.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 44 bytes

```
Subsequences@#~SubsetQ~Permutations@Union@#&

```

Try it online!

@att saved 31 bytes

# Answer
> 2 votes
# Jelly, 5 bytes

```
Œ!ẇ€Ạ

```

A dyadic Link accepting \\$n\\$ on the left and the candidate as a list of integers on the right which yields `1` (is) or `0` (is not) as appropriate.

**Try it online!**

### How?

```
Œ!ẇ€Ạ - Link: n, L
Œ!    - all permutations of [1..n]
   €  - for each (permutation, p):
  ẇ   -   is (p) a sublist of (L)?
    Ạ - all?

```

# Answer
> 2 votes
# Scala `-deprecation -encoding=UTF-8 -feature -unchecked -language:postfixOps -language:implicitConversions -language:higherKinds -language:existentials -language:postfixOps -Xfuture -Yno-adapted-args -Ywarn-dead-code -Ywarn-numeric-widen -Ywarn-value-discard -Ywarn-unused`, 44 bytes

```
s=>s.distinct.permutations forall s.contains

```

Pretty straightforward. Finds all the distinct symbols, generates all their permutations, and then checks if each permutation is in the input string.

Try it online

# Scala, ~~56~~ 54 bytes

```
(s,>)=>(1 to>).mkString.permutations forall s.contains

```

As you can tell, the superpermutation string is ~~`|`~~ `s`(lot less readable now) and `n` is `>`. It basically just generates every permutation in the range `1 to n` and checks if each of those are in the input string.

Try it online!

# Answer
> 2 votes
# Haskell, 57 bytes

```
import Data.List
s p=all(`isInfixOf`p)$permutations$nub$p

```

Try it online!

# Answer
> 2 votes
# Husk, 5 bytes

```
Λ€¹Pu

```

Try it online!

Same as the Jelly answer.

# Answer
> 1 votes
# Charcoal, 35 bytes

```
Ｎθ⁼ΠＥθ⊕ιＬΦＥη✂ηκ⁺κθ¹∧⁼κ⌕ηι⁼θＬΦι⁼μ⌕ιλ

```

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

```
Ｎθ

```

Input `n` as a number.

```
⁼ΠＥθ⊕ι

```

`n!` must equal...

```
ＬΦＥη✂ηκ⁺κθ¹

```

... the number of truncated suffixes of the string...

```
∧⁼κ⌕ηι

```

... that have not already been seen earlier in the string, and...

```
⁼θＬΦι⁼μ⌕ιλ

```

... contain `n` distinct characters.

# Answer
> 1 votes
# Pyth, 10 bytes

```
.Am}dz.p{z

```

Try it online!

---

Explanation:

```
.Am}dz.p{z
        {z  Deduplicate, yielding the distinct digits
      .p    Permutate
  m         Map with d as variable
   }dz      Check if d is a substring of z
.A          Verify that all elements are truthy

```

# Answer
> 1 votes
# Vyxal, 9 bytes

```
UṖƛ∑⁰$c;A

```

Try it Online!

A mess.

# Answer
> 0 votes
# Java 10, ~~291~~ ~~287~~ ~~233~~ 229 bytes

```
n->{var t="";for(var d:n.split(t))t+=t.contains(d)?"":d;return p(n,"",t);}boolean p(String n,String p,String s){int l=s.length(),i=0;var r=n.contains(p);for(;i<l;)r&=p(n,p+s.charAt(i),s.substring(0,i)+s.substring(++i));return r;}

```

-4 bytes by taking inspiration from what *@Arnauld* mentioned in his JavaScript answer:

> If all permutations of the \\$N\\$ symbols are present in the input string \\$s\\$, so are all prefixes of said permutations. Therefore, it's safe to test that all \\$p\\$ are found in \\$s\\$ even when \\$p\\$ is an incomplete permutation whose size is less than \\$N\\$.
>
> That's why we can use a recursive function that recursively builds each permutation \\$p\\$ of the symbols and tests whether \\$p\\$ exists in \\$s\\$ at each iteration, even when \\$p\\$ is still incomplete.

Takes the integer-input as String.

Try it online.

**Explanation:**

```
n->{                    // Method with String as parameter and boolean return-type
  var t="";             //  Temp String, starting empty
  for(var d:n.split(t)) //  Loop over the digits of the input:
    t+=                 //   Append to String `t`:
       t.contains(d)?   //    If `t` contains this digit already:
        ""              //     Append nothing
       :                //    Else (it doesn't contain this digit yet):
        d;              //     Append this digit
  return p(n,"",t);}    //  Call the separated recursive method to check if each
                        //  permutation of `t` is a substring of `n` and return it as

// Separated recursive method to get all permutations of String `t`, and check for each
// if it's a substring of String `n`
boolean p(String n,String p,String s){
  int l=s.length(),    //  Get the length of the input-String `s`
      i=0;             //  Set the index `i` to 0
  var r=               //  Result-boolean, starting at:
        n.contains(p); //   Check that String `n` contains part `p` as substring instead
                       //   (this doesn't necessary have to be the full permutation,
                       //    but it doesn't matter if the part is smaller)
  for(;i<l;)           //  Loop `i` in the range [0, length):
    r&=                //   Add the following to the boolean-return (bitwise-AND style):
      p(               //    Do a recursive call with:
        n,p            //     The current part,
          +s.charAt(i),//     appended with the `i`'th character as new part
          s.substring(0,i)+s.substring(++i));
                       //     And the String minus this `i`'th character as new String
                       //     (and increment `i` for the next iteration in the process)
  return r;}           //  And return the resulting boolean

```

# Answer
> 0 votes
# Ruby `-nl`, 44 bytes

```
p$_.chars.uniq.permutation.all?{|x|$_[x*'']}

```

Try it online!

# Answer
> 0 votes
# T-SQL, 186 bytes

Returns 1 for true, 0 for false.

This struggles with more than 6 unique characters

```
WITH B as(SELECT distinct substring(@,number,1)a FROM spt_values),C
as(SELECT a y FROM b UNION ALL SELECT y+a FROM B,C
WHERE y like'%'+a+'%')SELECT 1/sum(1)FROM C WHERE replace(@,y,'')=@

```

**Try it online** ungolfed

---
Tags: code-golf, decision-problem, combinatorics, permutations
---