title: Power sequence differences

text:
# Question
Title: Power sequence differences
### Your task

Given two positive integers \\$x\\$ and \\$d\\$ (such that \\$d\<x\\$), output the 5th term of the \\$d\\$th difference of the sequence \\$n^x\\$

### Example

Let's say we are given the inputs \\$x=4\\$ and \\$d=2\\$.

First, we get the series \\$n^4\\$:

* \\$0^4 = 0\\$
* \\$1^4 = 1\\$
* \\$2^4 = 16\\$
* \\$3^4 = 81\\$
* ...

These are the first 10 elements:

```
0 1 16 81 256 625 1296 2401 4096 6561

```

Now we work out the differences:

```
0 1 16 81 256 625 1296 2401  // Original series
 1 15 65 175 369 671 1105    // 1st difference
  14 50 110 194 302 434      // 2nd difference

```

Finally, we get the 5th term (1-indexed) and output:

```
302

```

Note: this is , so as long as the 5th term is somewhere in your output, it's fine.

### Test cases

```
x  d  OUTPUT
4  2  302
2  1  9
3  2  30
5  3  1830

```

This Python program can be used to get the first three differences of any power series.

### Rules

* **This is , so the input/output can be in any form.**
* **This is , so shortest code in bytes wins!**

# Answer
# MathGolf, 6 bytes

```
úr▬kÄ│

```

Inputs in the order \\$d,x\\$. Outputs a list of the first \\$10^{d}-d\\$ amount of values, which gives a minimum of 9 terms (for \\$d=1\\$), including the \\$5^{th}\\$ term.

Try it online.

**Explanation:**

```
ú       # Push 10 to the power the first (implicit) input-integer `d`
 r      # Pop and push a list in the range [0,10ᵈ)
  ▬     # Take each value to the power of the second (implicit) input `x`
   k    # Push the first input `d` again
    Ä   # Loop that many times, using 1 character as inner code-block:
     │  #  Get the forward-differences of the list
        # (after which the entire stack is output implicitly as result)

```

A trailing  (get 0-based 4th item) can be added to only output the \\$5^{th}\\$ term: try it online.
> 2 votes

# Answer
# , ~~26~~ 24 bytes

```
\(x,d)diff((0:5^d)^x,,d)

```

Attempt This Online!

Returns the first `5^d-d+1` elements (which is always ≥5) of `d`-th differences.

Obviously, for `d`\>1 this includes a lot of unneccessary differences, but simply returning the first 5 elements is ~~2~~ 1 byte\* longer: `\(x,d)diff((-d:4+d)^x,,d)` (Attempt it here).

\*Thanks to pajonk
> 13 votes

# Answer
# Python, 53 bytes

```
f=lambda x,d,b=4:d and f(x,d-1,b+1)-f(x,d-1,b)or b**x

```

Attempt This Online!

Straight-forward recursion.

# Python \+ NumPy, 50 bytes using builtin `diff`

```
lambda x,d:diff(r_[4:5+d]**x,d)
from numpy import*

```

Attempt This Online!
> 8 votes

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
∞ImIF¥

```

-1 byte thanks to *@TheThonnu*

Outputs the infinite sequence minus the first item. Inputs in the order \\$x,d\\$.

Try it online.

**Explanation:**

```
∞       # Push the infinite sequence of positive integers: [1,2,3,...]
 Im     # Takes each to the power of the first input
   IF   # Loop the second input amount of times:
     ¥  #  Get the deltas/forward-differences of the infinite list
        # (after which the infinite list is output implicitly)

```

Outputting the \\$5^{th}\\$ term would be 9 bytes instead by adding a trailing `}3è` (close the loop and get the 0-based 3rd item).
> 7 votes

# Answer
# C (gcc), 112 bytes

```
j;i;*v;f(x,d){v=calloc(d+9,8);for(i=0;i<d+5;)v[i++]=pow(i,x);for(;d--;)for(j=0;j++<i;)v[j-1]-=v[j];x=abs(v[4]);}

```

Try it online!

*This works on my machine with gcc version 13.0.0 but the return fails on TIO.*

# C (gcc), ~~66~~ 60 bytes

```
q;f(x,d){q=x;g(d,4);}g(d,b){d=d--?g(d,b+1)-g(d,b):pow(b,q);}

```

Try it online!

*Port of loopy walt's Python answer*
*Saved 6 bytes thanks to the man himself Arnauld!!!*

Inputs \\$x\\$ and \\$d\\$.
Returns the \\$5^\text{th}\\$ term of the power sequence difference.
> 7 votes

# Answer
# Java, ~~127~~ 90 bytes

```
x->d->g(x,d,4)double g(int x,int d,int k){return d>0?g(x,--d,k+1)-g(x,d,k):Math.pow(k,x);}

```

-37 bytes porting *@loopyWalt*'s Python answer

Outputs the \\$5^{th}\\$ term like the test cases, except as double instead of int.

Try it online.

**Explanation:**

```
x->d->              // Method with two integer parameters and double return-type
  g(x,d,4)          //  Call the recursive method below with k=4

double g(int x,int d,int k){
                    // Recursive method with three integer parameters and double return
  return d>0?       //  If `d` is not 0:
    g(x,--d,k+1)    //   Do a recursive call with x, d-1, k+1
    -g(x,d,k)       //   Subtract a recursive call with x, d-1, k
   :                //  Else:
    Math.pow(k,x);} //   Calculate `k` to the power `x`
                    //   (which results in a double, hence the double return-type)

```
> 6 votes

# Answer
# PARI/GP, 43 bytes

```
f(n,d)=polylog(-n,x)*(1-x)^d%x^(d+=5)\x^d--

```

Attempt This Online!

Using the polylogarithm \\$\operatorname{Li}\_{s}(x) = \sum\_{k=1}^\infty\frac{x^k}{k^s}\\$. When \\$s=-n\\$, this is the generating function of the sequence \\$1^n, 2^n, 3^n, \dots\\$. Taking the \\$d\\$th difference is just multiplying the generating function by \\$(1-x)^d\\$.
> 5 votes

# Answer
# Excel (ms365), 143 bytes

```
=INDEX(REDUCE((ROW(1:1048576)-1)^A2,SEQUENCE(B2),LAMBDA(a,b,HSTACK(a,LET(c,TAKE(a,,-1),d,FILTER(c,ISNUMBER(c)),DROP(d,1)-DROP(d,-1))))),5,B2+1)

```
* `ROW(1:1048576)-1)^A2` \- 1st Parameter in `REDUCE()` to have our 'n' thus 'infinite' (as many rows as possible in Excel) to the power of x;
* `SEQUENCE(B2)` \- The 2nd parameter of `REDUCE()` will tell the function to loop d-times;
* `LAMBDA(a,b,HSTACK(a,LET(c,TAKE(a,,-1),d,FILTER(c,ISNUMBER(c)),DROP(d,1)-DROP(d,-1))))` \- The lambda helper function will keep pushing new columns with the difference between each value and it's predecessor;
* The above is wrapped into `INDEX()` to grab the 5th element from the latest column.
> 4 votes

# Answer
# Vyxal, 7 bytes

```
Þ∞$e$(¯

```

Try it Online!

"Make infinite lists of numbers a digraph" they said. "It doesn't need to be 1 byte" they said. Well look where that got us :p. Could be 6 bytes in 2.4.1 but I don't know if it actually prints.

## Explained

```
Þ∞$e$(¯
Þ∞$e    # [1 ** x, 2 ** x, 3 ** x, ...]
    $(  # d times:
      ¯ #   deltas

```
> 4 votes

# Answer
# Charcoal, ~~28~~ 27 bytes

```
ＮθＮη≔Ｅ⁺⁵ηＸιθζＦηＵＭζ⁻κ§ζ⊖λＩ⊟ζ

```

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

```
ＮθＮη

```

Input `x` and `d`.

```
≔Ｅ⁺⁵ηＸιθζ

```

Generate `d+5` `x`th powers.

```
ＦηＵＭζ⁻κ§ζ⊖λ

```

Generate differences `d` times.

```
Ｉ⊟ζ

```

Output the last difference (which is now the fifth).
> 4 votes

# Answer
# Pyth, 9 bytes

```
.+F^Rvz+5

```

Try it online! or Test suite.

Input is in the form \\$d\\$ then \\$x\\$. Returns the first \\$5\\$ terms of the sequence.

**Explanation:**

```
.+F^Rvz+5QQ # Whole program. Implicit input Q (as d) added

    R       #  right map with lambda taking one argument:
   ^        #  using exponentiation
      z     #   the second input (x)
     v      #   evaluated
       +5Q  #  into implicit range(5 + d)
  F         # repeat the function
.+          # deltas
          Q #  d times

```
> 4 votes

# Answer
# JavaScript (ES7), 38 bytes

Expects `(x)(d)`. Same recursion as loopy walt in Python.

```
x=>g=(d,k=4)=>d--?g(d,k+1)-g(d,k):k**x

```

Try it online!
> 4 votes

# Answer
# Desmos, ~~44~~ 43 bytes

-1 byte thanks to Aiden Chow

```
f(n,d)=∑_{k=0}^d(-1)^{d-k}nCr(d,k)(k+4)^n

```

View it on Desmos.

Takes `n` and `d` as the inputs to a function `f`.
> 4 votes

# Answer
# sclin, 29 bytes

```
$W rev ^"."itr
2%`",_ - _"map

```

Try it here! Takes input *n* and returns an infinite list of infinite lists starting from *d* = 0.

For testing purposes:

```
5 ; >kv ( ,_ 10tk >A swap >o ": ">o f>o ) map 10tk >A
$W rev ^"."itr
2%`",_ - _"map

```

## Explanation

Prettified code:

```
$W rev ^ \; itr
2%` ( ,_ - _ ) map

```

Assuming input *d* and *n*.

* `$W` infinite range \[0, ∞)
* `rev ^` i.e. `range ^ n`
* `\; itr` successively apply next line to create infinite list
    + `2%`` sliding pairs
    + `( ,_ - _ ) map` difference of each pair
> 4 votes

# Answer
# Husk, ~~9~~ 7 bytes

*Edit: saved 2 bytes by outputting an infinite list of infinite lists, instead of just the `d+1`-th infinite list*

```
¡Ẋ-m^⁰N

```

Try it online!

Returns an infinite list of infinite lists of differences of `x`-th powers.
The header in the TIO link extracts the `d+1`-th element of this, which is the infinite list of `d`-th differences.

```
    m       # map over
       N    # all integers 1..infinity
     ^⁰     # getting their x-th powers;
 ¡          # now, make an infinite list of infinite lists by repeatedly
  Ẋ-        # taking pairwise differences;

```
> 3 votes

# Answer
# Ruby, 70 bytes

```
->x,d{s=(0..5**d+x).map{_1**x}
d.times{s=s.each_cons(2).map{_2-_1}}
s}

```

Attempt This Online!
> 3 votes

# Answer
# Clojure, 69 bytes

```
#(nth(iterate(fn[x](map -(rest x)x))(for[i(range)](Math/pow i %)))%2)

```

Try it online!

Returns the entire (lazy) sequence.

# Clojure, ~~82~~ 75 bytes

```
#(nth(nth(iterate(fn[x](map -(rest x)x))(for[i(range)](Math/pow i %)))%2)4)

```

Try it online!

Returns specifically the 5th term of the sequence.
> 3 votes

# Answer
# , ~~19~~ 16 bytes

```
2&(-~/\)i.@+&5^]

```

Takes inspiration from Jelly. Accepts `d` as the left arg and `x` as the right arg.

-3 bytes thanks to Jonah

Attempt This Online!

```
2&(-~/\)i.@+&5^]
        i.@+&5^]  NB. dyadic fork
               ]  NB. returns right arg
        i.@+&5    NB. atop, +&5 adds five to left arg, i. creates a range 0..n-1
              ^   NB. raises each item of the range to y
2&(-~/\) ...      NB. dyadic hook
2&(-~/\)          NB. 2 -~/\ y computes the delta of adjacent elements
                  NB. ~ is necessary to flip the args since, for example, 1-16=_15
                  NB. x(n&u)y is a special form of ^:, it is equivalent to
                  NB. n&u^:x y, which applies n&u to y x times

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 27 bytes

```
\!\(\_{i,#2}i^#\)/.i->4&

```

Try it online!

The private-use character  is `\[DifferenceDelta]`.

This character has code point `U+F4A4`, which is different from what the documentation (as of current writing) claims it to be. `U+2206`, the code point in documentation, corresponds to the similar-looking `\[Laplacian]`/ (undocumented).
> 3 votes

# Answer
# Gaia, 13 bytes

```
:e…⟪¤*⟫¦@'ọ&e

```

Try it online!

I finally figured out how to do for loops in Gaia! Outputs approximately (10\**x)-d terms (I think)

## Explained

```
:e…⟪¤*⟫¦@'ọ&e
:e…           # Push range(0, x ** 10) to the stack
   ⟪¤*⟫¦      # and raise each item in that range to the power of x
       @'ọ&   # Repeat the string "ọ" d times (ọ is the deltas/forward differences command)
           e  # and execute that as Gaia code

```
> 2 votes

# Answer
# Jelly, 7 bytes

```
+5Ḷ*I⁸¡

```

A dyadic Link that accepts \\$d\\$ on the left and \\$x\\$ on the right and yields a list of the first five terms.

**Try it online!**

### How?

```
+5Ḷ*I⁸¡ - Link: integer, d; integer, x
+5      - (d) add five -> d+5
  Ḷ     - lowered range -> [0,1,2,...,d+4]
   *    - exponentiate (x) -> [0^x,1^x,2^x,...,(d+4)^x]
      ¡ - repeat...
     ⁸  - ...times: chain's left argument -> d
    I   - ...action: deltas

```
> 2 votes

# Answer
# Factor, 54 49 47 bytes

```
[ dup 5 + iota rot v^n [ differences ] repeat ]

```

Returns the first 5 elements of the sequence.

Try it online!

```
                        ! 4 2
dup                     ! 4 2 2
5                       ! 4 2 2 5
+                       ! 4 2 7
iota                    ! 4 2 { 0 1 2 3 4 5 6 }
rot                     ! 2 { 0 1 2 3 4 5 6 } 4
v^n                     ! 2 { 0 1 16 81 256 625 1296 }
[ differences ] repeat  ! { 14 50 110 194 302 }

```
> 2 votes

# Answer
# Perl 5, 65 bytes

```
sub f{my($x,$d,$p)=(@_,4);$d?f($x,--$d,$p+1)- f($x,$d,$p):$p**$x}

```

Try it online!
> 2 votes

# Answer
# Nibbles, ~~8~~ 7 bytes (14 nibbles)

```
`..,~^$@!>>$@-

```

Function that returns an infinite list of infinite lists of all differences of the `x`-th powers of all integers:

```
=@`..,~^$@!>>$@-
     ,~             # make a list 1..infinity
    .               # and map over each number
       ^$           # raising it to
         @          # the arg1-th power;
  `.                # now iteratively apply this function:
          !         # zip together
           >>$      # this list without the first element
              @     # with itself
               -    # by subtraction (so: get differences)

```

To only output the `d`-th differences (as shown in the screenshot below) costs 1 byte (2 nibbles) more:

```
=                       # get the list at index
 @                      # arg2

```
> 2 votes

# Answer
# MATLAB, 45 bytes

```
function f(x,d)
y=diff((0:5*d).^x,d);y(5)
end

```

Uses built-in diff function with the dth difference argument, outputs the fifth index of the resulting array.

Try it online!
> 2 votes

# Answer
# Haskell, 50 bytes

can someone get rid of `iterate`?

```
x!d=iterate(zipWith(-)=<<tail)[n^x|n<-[0..]]!!d!!4

```

Try it online!
> 2 votes

# Answer
# Haskell, 47 bytes

```
r x 0 i=i^x
r x d i=(r x(d-1)(i+1))-(r x(d-1)i)

```

Try it online!
> 2 votes

# Answer
# \>\<\>, 89 bytes

Prints **d\*2** junk number in the beginning and another **2** junk numbers at the end.

```
:&5*>:0(?v:1-$:{:}\nao92*0.
:2(?v1-}$ :@*{    >
v~@~\02. >&:1-&1(?vl
>:2(    ?^1-@$:@$-}$

```

Try it online

# \>\<\>, 94 bytes

Only prints numbers in the sequence.

```
:&5*>:0(?v:1-$:{:}c2.
 ~@~/01. >~{~v
:2(?^1-}$:@*{
  vlv?(1&-1:&<~~<
2:<$   }-$@:$@-1^?(
 oan<

```

Try it online
> 1 votes

# Answer
# Scala, 198 bytes

Golfed version. Try it online!

```
def F(x:Int,d:Int)={val s=ListBuffer[Double]();for(i<-0 to(Math.pow(5,d)+x).toInt){s+=Math.pow(i,x)};for(_<-1 to d){s.indices.dropRight(1).foreach{i=>s(i)=s(i+1)-s(i)};s.remove(s.length-1)};s.toSeq}

```

Ungolfed version. Try it online!

```
import scala.collection.mutable.ListBuffer

object Main {
  def F(x: Int, d: Int): List[Double] = {
    val s = ListBuffer[Double]()
    for (i <- 0 to (Math.pow(5, d) + x).toInt) {
      s += Math.pow(i, x)
    }
    for (_ <- 1 to d) {
      s.indices.dropRight(1).foreach { i =>
        s(i) = s(i + 1) - s(i)
      }
      s.remove(s.length - 1)
    }
    s.toList
  }

  def main(args: Array[String]): Unit = {
    println(F(4, 2))
    println(F(2, 1))
    println(F(3, 2))
    println(F(5, 3))
  }
}

```
> 1 votes

---
Tags: code-golf, math, sequence
---


# Question
Title: Replace all vowels with repeated "aeiou"
Let's say I have this string:

```
s = "Code Golf! I love Code Golf. It is the best."

```

I want to replace all the vowels with repeated "aeiou".

Notes:

* Uppercase vowels should be replaced by an uppercase letter, and lowercase vowels should be replaced by a lowercase letter.
* Consonants (all alphabet characters except for "aeiou") and non alphabetical characters should be kept the same.

Desired output:

```
Cade Gilf! O luva Cedi Golf. Ut as the bist.

```

As you can see, the vowels are replaced in repetitive order of "aeiou".

Another example:

```
s = "This is a test! This is example number two."

```

Output:

```
Thas es i tost! Thus as eximplo numbar twe.

```

This is , so shortest code in bytes wins.

# Answer
# Vyxal, 11 bytes

```
⟑A[kv¥i$•&›

```

Try it Online!

If I had a nickel for every time I'd answered a vowel-related challenge with an 11 byte Vyxal answer in the last 2 weeks, I'd have 2 nickels, which isn't a lot but it's weird that it's happened twice. Outputs as a list of characters (add the `s` flag if you want a string object).

## Explained

```
⟑A[kv¥i$•&›
⟑           # To each character:
 A[         #  if it is a vowel:
   kv¥i     #    get the (register)th item of the string "aeiou" - wraps around if the register > 5
       $•   #    and give it the same case of the current character
         &› #    increment the register to get the next vowel

```
> 11 votes

# Answer
# C (clang), 65 bytes

```
i;f(*s){for(i=0;*s++^=2130466>>*s&*s>64?i*5^5%++i^*s&30:0;i%=5);}

```

Try it online!

## How?

### Detecting vowels

We determine whether the current character at `*s` is a vowel with:

```
2130466 >> *s & *s > 64

```

The value \\$2130466\\$ is a bitmask describing the positions of vowels:

```
000001000001000001000100010
     ^     ^     ^   ^   ^
zyxwvutsrqponmlkjihgfedcba

```

The shift amount is interpreted modulo 32 (to my knowledge, this is true for at least Intel and ARM processors). This means that we just have to make sure that the character is a letter (with `*s > 64`) and can use the same expression for lower and upper case.

### Turning them into different vowels

An interesting thing about vowels is that all their ASCII codes are odd:

```
A |  65 | 1000001        a |  97 | 1100001
E |  69 | 1000101        e | 101 | 1100101
I |  73 | 1001001        i | 105 | 1101001
O |  79 | 1001111        o | 111 | 1101111
U |  85 | 1010101        u | 117 | 1110101
          ||    |
          ||    '--> always 1
          |'-------> 'case' bit
          '--------> always 1

```

To turn a vowel of a given case into another vowel with the same case, only bits #1 to #4 (0-indexed) need to be modified. This can be represented with the bitmask \\$00011110\_2=30\_{10}\\$.

Hence a possible formula:

```
new_vowel = old_vowel XOR (x XOR (old_vowel AND 30))

```

where \\$x\in\\{0,4,8,14,20\\}\\$ (for A,E,I,O,U respectively).

Given \\$i\in\[0\dots4\]\\$, we get \\$x\_i\\$ with:

$$x\_i=(i\times 5)\operatorname{xor}(5 \bmod (i+1))$$

| i | i * 5 | 5 mod (i+1) | xor |
| --- | --- | --- | --- |
| 0 | 0 | 0 | 0 |
| 1 | 5 | 1 | 4 |
| 2 | 10 | 2 | 8 |
| 3 | 15 | 1 | 14 |
| 4 | 20 | 0 | 20 |

As C code, this gives:

```
*s ^= i * 5 ^ 5 % ++i ^ *s & 30

```

which, conveniently, is incrementing \\$i\\$ at the same time.

### Putting everything together

```
i;                  // i is a counter for vowel replacement
f(*s) {             // s is the input string
  for(              // main loop:
    i = 0;          //   start with i = 0
    *s++ ^=         //   update the character *s:
      2130466 >> *s //     if this looks like a vowel
      & *s > 64 ?   //     and really is a letter:
        i * 5 ^     //       turn it into a different vowel
        5 % ++i ^   //       and increment i afterwards
        *s & 30     //
      :             //     else:
        0;          //       leave it unchanged
                    //   (NB: we stop when the result is NUL)
    i %= 5          //   make sure to keep i in [0..4]
  );                // end of loop
}                   //

```
> 30 votes

# Answer
# Excel (ms365), ~~183~~, 164 bytes

-19 bytes thanks to @jdt

Formula in `B1`:

```
=LET(x,MID(A1,ROW(A:A),1),y,"uaeio",r,SEARCH(x,y),z,SCAN(0,r,LAMBDA(a,b,IF(ISERR(b),a,a+1))),w,MID(y,MOD(z,5)+1,1),CONCAT(IFERROR(IF(r*(CODE(x)<97),UPPER(w),w),x)))

```
> 12 votes

# Answer
# , ~~94~~ ~~81~~ 79 bytes

*Edit: -2 bytes thanks to pajonk*

```
\(i){u=match(i,v<-el(strsplit("aAeEiIoOuU","")),0)
i[!!u]=v[1:5*2-u[!!u]%%2]
i}

```

Attempt This Online!

Input & output as character vectors.
(Splitting-up an input string and reassembling one for the output costs about +36 bytes, for comparison with any alternative approaches that directly use strings).

Previous 94-byte version (using `grep` and `toupper`)
> 12 votes

# Answer
# Python, ~~109 106 104~~ 98 bytes

```
f=lambda s,i=0:s and((c:=s[0])in(v:='uaeioUAEIO')and[v[:5],v[5:]][c<'a'][i:=-~i%5]or c)+f(s[1:],i)

```

Attempt This Online!

* -6 thanks to Steffan

# Python, ~~117 116 112~~ 111 bytes

### (not valid - this is just for fun)

```
lambda s:re.sub('[aeiou]',g,s,0,2)
i=0
def g(c):global i;i=-~i%5;return['uaeio','UAEIO'][c[0]<'a'][i]
import re

```

Attempt This Online!

* -4 thanks to Steffan
* -1 thanks to pxeger

Just wanted to try with a Regex-based approach. The function isn't reusable so it's not a valid solution.
> 8 votes

# Answer
# JavaScript (ES6), 59 bytes

```
s=>s.replace(/[aeiou]/gi,c=>"aAeEiIoOuU"[i++%5*2|c<{}],i=0)

```

Try it online!
> 7 votes

# Answer
# Python, ~~80~~ 74 bytes

* -6 thanks to xnor!

```
V=v='UuAaEeIiOo'
for c in input():print(end=c[c in V:]or(v:=v[2:]+V)[c>V])

```

Attempt This Online! Full program.

---

# Python, ~~85~~ ~~81~~ 78 bytes

* -4 thanks to Steffan!
* -3 thanks to xnor!

```
lambda s,v='uUaAeEiIoO':''.join(c[c in v:]or(v:=v[2:]+v[:2])[c<'a']for c in s)

```

Attempt This Online!
> 7 votes

# Answer
# Pip, 37 21 bytes

*\- 14 bytes of mostly DLosc, and jezza\_99 getting ninja'd*
*\- 2 bytes thanks to jezza\_99*

```
aR-XV{YVW@UvaNz?yUCy}

```

Try It Online!

I'm bad at golfing in pip lol.

```
aR-XV{YVW@UvaNz?yUCy}
aR-XV{                }      Replace (case-insensitive) vowels with ...
      YVW@Uv                 Set y to the (vth*1) vowel
            aNz?yUCy         Copy case to y

```
> 6 votes

# Answer
# Raku, 44 bytes

```
{$!=0;S:g:ii[<[aeiou]>]=<a e i o u>[$!++%*]}

```

Try it online!

Most of the magic here is in the `samecase` flag on the substitution, whose short form is `ii`. It makes the match case-insensitive, and furthermore carries the case information forward into the substituted text.
> 6 votes

# Answer
# Python 3.8+, ~~183 156 127 117~~ 111 bytes

-29 bytes thanks to ElPedro
-10 bytes thanks to Neil
-6 bytes thanks to help from the Discord (mainly by dzaima and me)

```
def x(n):m,j='aeiou',0;return''.join([((m,m.upper())[i<'a'][j%5],j:=j+1)[0]if i.lower()in m else i for i in n])

```
> 5 votes

# Answer
# Japt v2.0a0, 21 bytes

```
r\v@T°g`aeiŒ`c^H*XèXu

```

Try it

```
r\v@T°g`aei`c^H*XèXu     :Implicit input of string
r                         :Replace
 \v                       :RegEx /[aeiou]/gi
   @                      :Pass each match X through the following function
    T°                    :  Postfix increment T (initially 0)
      g                   :  Index into
       `aei`             :    Compressed string "aeiou"
             c            :    Map charcodes
              ^           :      Bitwise XOR with
               H*         :      32 multiplied by
                 Xè       :      Count the occurrences in X of
                   Xu     :        X uppercased

```
> 5 votes

# Answer
# Haskell, 93 bytes

```
(%"aAeEiIoOuU")
(x:r)%u@(v:t:w)|elem x u=c:r%(w++[v,t])|1>0=x:r%u where c|x>'Z'=v|1>0=t
o%_=o

```

Attempt This Online!

Prettified:

```
import Data.Char
g vowels@(vowel:vOWEL:rest) (char:chars)
  | char `elem` vowels
    = mappedChar : g rotatedVowels chars
  | otherwise
    = char : g vowels chars
  where
    rotatedVowels = rest ++ [vowel, vOWEL]
    mappedChar
      | isUpper char = vOWEL
      | otherwise = vowel
g _ "" = ""

```

```
g "aAeEiIoOuU"

```
> 5 votes

# Answer
# Python 3, ~~130~~ ~~122~~ 120 bytes

```
p=print
v='aeiou'
n=0
for i in input():
 if i.lower()in v:p(end=[v[n],v[n].upper()][i.isupper()]);n=-~n%5
 else:p(end=i)

```

Try it online!

*-8 bytes thanks to myself*

*-2 bytes thanks to The Thonnu*
> 4 votes

# Answer
# Retina, ~~82~~ 54 bytes

```
i`[aeiou]
a$&
,Y0`a`v`a.
T`v`V`.[AEIOU]
1,2,i`[aeiou]

```

Try it online! Link includes test cases. Explanation:

```
i`[aeiou]
a$&

```

Prefix `a`s to all of the vowels, both lower and upper case.

```
,Y0`a`v`a.

```

Cyclically transliterate only the new `a`s to vowels.

```
T`v`V`.[AEIOU]

```

Uppercase the new vowels that precede old uppercase vowels.

```
1,2,i`[aeiou]

```

Delete alternate vowels i.e. the old vowels.

If the input had all been in (say) lowercase, then it could have been done in 11 bytes:

```
Y`v`a
Y`a`v

```

Try it online! Link includes test cases. Explanation: Simply cyclically transliterates all the lowercase vowels to `a`s and back to vowels.
> 4 votes

# Answer
# Pyth, 25 bytes

```
sm?}r0dK"uaeio"r@K=hZrId1

```

Try it online!

### Explanation

```
sm?}r0dK"uaeio"r@K=hZrId1dQ    # implicitly add dQ to the end
                               # implicitly assign Q = eval(input())
       K"uaeio"                # assign K to "uaeio"
s                              # sum of
 m                        Q    # map lambda d over Q
  ?}r0dK                       # ternary, if lowercase(d) in K:
               r     rId1      #   map case to d of
                @K             #   (looping) index K at
                  =hZ          #   increment Z, and assign it to the increment
                         d     # else: d

```
> 4 votes

# Answer
# Jelly, 23 bytes

```
ØciⱮðḟ0ØėṁŒs>5$}¡"Ɗż@œp

```

Try it online!

Jelly isn't great at challenges. Full program, as we take advantage of Jelly's smash printing.

## How it works

```
ØciⱮðḟ0ØėṁŒs>5$}¡"Ɗż@œp - Take a string S on the left
Øc                      - Yield "AEIOUaeiou"
   Ɱ                    - For each character C in S:
  i                     -   Get the index of C in "AEIOUaeiou", or 0 if not found
    ð                   - Begin new dyadic chain, with vowel indices V on the left and S on the right
     ḟ0                 - Remove zeros from V, call that V'
                  Ɗ     - Group the previous 3 links into a monad f(V'):
       Øė               -   Uppercase vowels; "AEIOU"
         ṁ              -   Repeat to the same length as V'
                 "      -   For each pair (v, i) with v a vowel and i an index in V':
                ¡       -     Repeat:
              $         -       Iteration count:
               }        -         Is i...
            >5          -         ...greater than 5?
          Œs            -       Action: Swapcase
                     œp - Partition S at the the indices in V
                   ż@   - Zip the partition and the vowels, with reversed @rguments

```
> 4 votes

# Answer
# Factor, ~~87~~ 86 bytes

```
[ EBNF[=[ r=([aeiouAEIOU]=>[[96 > 0 -32 ? 0 inc 0 get 1 - 5 mod "aeiou"nth +]]|.)*]=]]

```

Attempt This Online!

* `[ ... ]` Define a quotation, or anonymous function, that takes a string as input from the data stack and leaves a string as output on the data stack.
* `EBNF[=[ ... ]=]` Define an anonymous EBNF parser that automatically runs on an input and produces an output.
* `r=` Name the topmost EBNF rule. There has to be at least one rule, so here it is.
* `(...|.)*` Match any number (`*`) of ... or (`|`) anything (`.`). The `.` matches consonants which will remain the same.
* `[aeiouAEIOU]` Match any vowel.
* `=>[[...]]` An EBNF action. The code inside the double brackets will run on each token before being added to the parse tree.
* `96 > 0 -32 ?` Is the vowel we matched lowercase? Push `0` on the data stack if so; otherwise, push `-32` on the data stack.
* `0 inc` Increment the value stored at `0`. In Factor, any value (such as `0`) can be used as a variable (key) to store a value in an implicit hierarchy of hash tables. If `0` contains `f`, which all uninitialized variables do by default, `inc` will cause the value to become `1`.
* `0 get` Get the value stored at `0`.
* `1 -` Subtract one. We do this because it's shorter than initializing `0` to `0`.
* `5 mod` Modulo five.
* `"aeiou"nth` Get the nth letter in `"aeiou"`.
* `+` Add this letter to the `0` or `-32` from earlier. This is what capitalizes the letter or keeps it lowercase.
> 4 votes

# Answer
# Java (JDK), 125131 bytes

```
s->{String v="aeiouAEIOU",r="";int j=0,p;for(var c:s.toCharArray()){p=v.indexOf(c);r+=p>=0?v.charAt((p>4?5:0)+j++%5):c;}return r;};

```

Try it online!

(Edited to add some lambda boilerplate.)
> 4 votes

# Answer
# Charcoal, 28 bytes

```
≔uaeioθ⭆Ｓ⎇№θ↧ι§⎇№αι↥θθＬ⊞Ｏυιι

```

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

```
≔uaeioθ

```

Get the vowels into a string to reduce repetition, but start with `u` because they need to be 1-indexed.

```
⭆Ｓ⎇№θ↧ι§⎇№αι↥θθＬ⊞Ｏυιι

```

Loop over the input characters, replacing letters whose lowercase can be found in the string of vowels with letters cyclically chosen from the string or its uppercase according to the number of matches so far.
> 3 votes

# Answer
# Zsh, 87 bytes

Try it Online! ~~123 bytes~~ ~~133 bytes~~

```
w=UAEIOuaeio;for k (${(s::)1}){let j+=${k/[$w]/1}
printf ${k/[$w]/$w[j%5+(#k<91?1:6)]}}

```
> 3 votes

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

```
s/[aeiou]/$&&a|(<A E I O>||U)/ige

```

Try it online!
> 3 votes

# Answer
# Dart (2.18.4), 139 bytes

```
r(s,[j=0,v='aeiouAEIOU',t,i=0])=>[for(var c=(l)=>v[(l?0:5)+j++%5];i<s.length;i++)if(v.contains(t=s[i]))c(t.codeUnitAt(0)>96)else t].join();

```
> 3 votes

# Answer
# APL (Dyalog Extended), 25 bytes

Anonymous tacit prefix function.

```
××(≢⍴v⍨)@(|∊(v←'aeiou')⍨)

```

Try it online!

`×` the case of the letters…

`×` imposed as case onto…

`(``)@(``)` amend the characters **at** the following locations:

`|` where the casefolded characters…

`∊(``)⍨` are members of the following constant:

`v←'aeiou'` the vowels (which are assigned to `v`

… with…

the count of such located vowels

cyclically **r**eshaping the following constant:

`v` the previously created `v`
> 3 votes

# Answer
# Ruby (2.5.5), 113 bytes

```
->(x){p,i='aeiou',0;x.chars.map{|t|(p.include?t.downcase)?(r=p[i%5];o=(t==t.upcase)?(r.upcase):r;i+=1;o):t}.join}

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 17 bytes

```
žMIlåÅÏžM¾è¼s.uiu

```

I/O as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
žM           # Push string "aeiou"
  I          # Push the input-list
   l         # Convert each letter to lowercase
    å        # Check for each letter if it's in the vowels-string
     ÅÏ      # Apply on the truthy indices of the (implicit) input-list:
       žM    #  Push string "aeiou" again
         ¾è  #  Get the (modular) 0-based `¾`'th vowel
           ¼ #  Then increase `¾` by 1
       s     #  Swap so the current character is at the top
        .ui  #  Pop, and if it's uppercase:
           u #   Uppercase the indexed vowel as well
             # (after which the list of characters is output implicitly as result)

```
> 3 votes

# Answer
# Ly, 58 bytes

```
"uoiea">ir[s<l'ZLsf:l' *+fsp~[p' *sp:l-s>pl<psprlr00]pp>o]

```

Try it online!

I thought this would be a "minor" variation on another answer I coded earlier this week. I was wrong. :)

The code uses one stack to hold a list of vowels. They are rotated each time one of them is used. And it uses a second stack as a "burndown" list of the input characters (codepoints). It copies one input character at a time to the vowel stack, searches for it, and if found substitutes the "next" vowel for the top of the burndown stack. Then it switches back to the burndown stack and prints the top codepoint as a character.

The upper/lowercase logic adds a bunch of code to the program and chaos of temporary stack entries...

```
"uoiea">ir  - setup...
"uoiea"     - push vowels onto the stack
       >ir  - switch to a new stack, read STDIN into the stack and reverse

[s<l'ZLsf:l' *+fsp~[...if vowel...]pp>o] - process each char
[                                      ] - loop until empty
 s<l                                     - copy char to vowel stack
    'ZL                                  - upper case?
       s                                 - save result
        f:                               - pull char forward, duplicate
          l                              - retrieve upper case 1|0
           ' *+                          - map to lowercase if appropriate
               f                         - pull original char forward
                sp                       - save it and delete
                  ~                      - search for lower case char
                   [...if vowel...]      - if it's a vowel, do this block
                                   pp    - clean up the stack
                                     >o  - switch stack, print top entry

p' *sp:l-s>pl<psprlr00 - code block run if we find a vowel
p                      - delete "if" test var
 ' *                   - calculate "should uppercase" delta
    sp                 - save and delete from stack
      :                - duplicate current vowel
       l               - load "uppercase" delta
        -              - convert case if called for
         s>            - save vowel to print, switch stacks
           pl          - delete original vowel, load replacement
             <         - switch back to rotating vowel stack
              p        - clean-up stack
               sprlr   - move vowel on top of stack to the bottom
                    00 - push entries on stack to match non-vowel state

```
> 2 votes

# Answer
# Jelly, 17 bytes

```
f€ØcØėṁȯ"Œl⁺i$}¡"

```

Try it online!

Was originally `e€ØcÄịØėa@Ʋo⁸O|O&32ƊỌ`, but that eventually turned into this with some inspiration from caird's answer.

```
 €                   For each character of the input,
f Øc                 filter it to AEIOUaeiou, producing a mix of empty and length-1 strings.
    Øėṁ              Mold AEIOU to the same shape as that.
       ȯ"            Replace empty strings with corresponding characters from the input.
                "    For each pair of such corresponding elements:
         Œl          lowercase the result
               ¡     if
           ⁺  }      the original lowercased (and wrapped in a string)
            i$       contains the original.

```
> 2 votes

# Answer
# Zsh `--extendedglob`, 63 bytes

```
v=aeiouAEIOU
<<<${1//(#m)[$v]/$v[$[#MATCH>91?1+i++%5:6+i++%5]]}

```

Try it online!

Thanks to @roblogic for the answer without `--extendedglob` which kicked this off. I've got basically the same logic, just using `(#m)`+`$MATCH` to keep track of the upper/lower case within a single PE.
> 2 votes

# Answer
# Arturo, 79 bytes

```
$=>[i:0v:"aAeEiIoOuU"map&'c[(v=v--c)?->c[x:(c>`^`)?->0->1v\[x+i%10]'i+2]]|join]

```

Try it
> 1 votes

# Answer
# Scala, 147 bytes

Golfed version. Try it online!

```
def f(x:String)={var (p,i)=("aeiou",0);x.map(t=>if(p.contains(t.toLower)){val r=p(i%5);val o=if(t.isUpper)r.toUpper else r;i+=1;o}else t).mkString}

```

Ungolfed version. Try it online!

```
object VowelShift {
  def main(args: Array[String]): Unit = {
    val f: String => String = (x: String) => {
      val p = "aeiou"
      var i = 0
      x.map { t =>
        if (p.contains(t.toLower)) {
          val r = p(i % 5)
          val o = if (t.isUpper) r.toUpper else r
          i += 1
          o
        } else {
          t
        }
      }.mkString
    }

    println(f("Code Golf! I love Code Golf. It is the best.") == "Cade Gilf! O luva Cedi Golf. Ut as the bist.")
    println(f("This is a test! This is example number two.") == "Thas es i tost! Thus as eximplo numbar twe.")
  }
}

```
> 1 votes

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


title: Enumeration of free polyominoes

text:
# Question
Title: Enumeration of free polyominoes
A polyomino with \\$n\\$ cells is a shape consisting of \\$n\\$ equal squares connected edge to edge.
No *free* polyomino is the rotation, translation or reflection (or a combination of these transformations, i.e. an isometry) of another (they're equal).
The sequence of free polyominoes with \\$n\\$ cells is as follows:

```
1, 1, 1, 2, 5, 12, 35, 108, 369, 1285, ...

```

# Specifications

* \\$n=0\\$ (1) may be excluded
* This is A000105
* Standard rules: you may output the \\$n^{th}\\$ term, all terms up to the \\$n\\$ terms or the entire sequence
* This is , so the shortest answer wins

# Answer
> 5 votes
# JavaScript (ES10), 259 bytes

For now, this is just a slightly modified version of my answer to this other challenge so that reflections are discarded. Supports \\$n=0\\$.

```
f=(n,m=[...o=Array(w=n)],i=c=0)=>n?m.map((r,y)=>m.map((_,x,[...m])=>!i|1<<x&~r&(m[y+1]|r/2|r*2)&&f(n-1,m,m[y]|=1<<x)))|c:[...3/64+''].some(k=>o[M=(k^6||m.reverse(),m=m.map(a=(_,y)=>m.map(b=(v,x)=>a|=b|=(v>>y&1)<<w+~x)|b)).flatMap(v=>v/(a&-a)||[])])?0:o[M]=++c

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 73 bytes

Should have been 1 byte less by replacing `})}€ê` with `}){}`, but the many nested maps/loops cause a bug in 05AB1E here (`})ê}` and `})}€{` also doesn't work strangely enough..)

```
1ÝInãʒOQiyƶIô©Δ2Fø0δ.ø}2Fø€ü3}®Ā*εεÅsyøÅsM}}}˜Ùg<]εIô2Føʒà}}4FDíDø})}€êÙg

```

Basically the exact same approach as my answer for the related challenge, but with a single added `D`uplicate (in step 4) to also remove reflections in addition to the rotations.

Extremely slow brute-force, so is only able to output up to \\$a(4)\\$ on TIO.

Try it online or verify the first few results.

**Explanation:**
Also mostly a copy-paste from my answer of the related challenge, except for step 4.

Step 1: Create all possible \\$n^2\\$-sized lists using `0`s and `1`s, consisting of \\$n\\$ amount of `1`s:

```
1Ý          # Push pair [0,1]
  In        # Push the squared input
    ã       # Cartesian power
ʒ           # Filter this list of lists by:
   i        #  If
 O          #  the sum of the current list
  Q         #  is equal to the (implicit) input-integer:
            #   Continue with the check in step 2 below
            #  (implicit else: implicitly use the implicit input for the filter;
            #   this is only truthy for edge case n=1, which fails step 2 due to the `ü3`)

```

Try just this first step online (without trailing `i`).

Step 2: Filter it further to only keep single polynominos, using a flood-fill approach:

```
 y          #   Push the current list again
  ƶ         #   Multiply each value by its 1-based index
   Iô       #   Convert the list to an input-by-input block
     ©      #   Store this block in variable `®` (without popping)
 Δ          #   Loop until the result no longer changes to flood-fill the matrix:
  2Fø0δ.ø}  #    Add a border of 0s around the matrix:
  2F     }  #     Loop 2 times:
    ø       #      Zip/transpose; swapping rows/columns
      δ     #      Map over each row:
     0 .ø   #       Add a leading/trailing 0
  2Fø€ü3}   #    Convert it into overlapping 3x3 blocks:
  2F    }   #     Loop 2 times again:
    ø       #      Zip/transpose; swapping rows/columns
     €      #      Map over each inner list:
      ü3    #       Convert it to a list of overlapping triplets
  ®Ā        #    Push matrix `®` and convert all its positive values back to 1s
    *       #    Multiply each 3x3 block by this matrix of 0s/1s (so 0s will remain 0s)
  εεÅsyøÅsM #    Get the largest value from the horizontal/vertical cross of each 3x3 block:
  εε        #     Nested map over each 3x3 block:
    Ås      #       Pop and push its middle row
      y     #       Push the 3x3 block again
       ø    #       Zip/transpose; swapping rows/columns
        Ås  #       Pop and push its middle rows as well (the middle column)
          M #       Push the flattened maximum of the entire (scoped) stack,
            #       which is the flattened maximum of the cross of the current 3x3 block
  }}        #     Close the nested map
 }˜         #   After the flood-fill loop: flatten the block to a list
   Ù        #   Uniquify its values
    g       #   Pop and push its length
     <      #   Decrease it by 1 to account for the 0s
            #   (only 1 is truthy in 05AB1E, so only single islands remain)
]           # Close both the if-statement and filter

```

Try just the first two steps online.

Step 3: Convert all valid lists to matrices, and slash off any rows/columns of 0s to have the actual polynominos:

```
ε           # Map over each inner list
 Iô         #  Convert it to an n-by-n block
   2F       #  Inner loop 2 times:
     ø      #   Zip/transpose; swapping rows/columns
      ʒ     #   Filter this list of rows by:
       à    #    Get the maximum of the row (so if it only contains 0s, it'll be removed)
      }     #   Close the filter
    }       #  Close the inner loop

```

Try just the first three steps online.

Step 4: Remove all duplicated rotations and reflections, by first converting each polynomino to a quartet of its four sorted rotations, then get the reflection of each rotation, and then uniquify that list of octets.

```
 4F         #  Inner loop 4 times:
   D        #   Duplicate the current polynomino-matrix
    í       #   Reverse each inner row to reflect it
     D      #   Duplicate this new reflected polynomino-matrix again
      ø     #   Zip/transpose the matrix; swapping rows/columns
  })        #  After the loop: wrap the eight rotations + reflections on the stack into a list

            # Explanation if the 05AB1E bug mentioned at the top wasn't present:
    {       #  Sort the octet of rotations + reflections
}Ù          # After the map: uniquify the list of polynomino-rotations/reflections

            # Actual explanation with bug:
}€          # After the map: open a new map:
  ê         #  Sort and uniquify each octet
   Ù        # After the map: uniquify the list of distinct polynomino-orientations/reflections

```

Try just the first four steps online.

Step 5: Get the amount of unique polynominos left, and output it as result:

```
g           # Pop and push the length
            # (which is output implicitly as result)

```

# Answer
> 2 votes
# Python3, 1374 bytes\*:

```
R=range
E=enumerate
def U(b):
 q,s=[b],[b]
 while q:
  b=q.pop(0)
  if(T:=[i[::-1]for i in b])not in s:q+=T,;s+=T,
  if(T:=[*map(list,zip(*[i[::-1]for i in zip(*b)]))])not in s:q+=T,;s+=T,
  if(T:=[*map(list,zip(*b))])not in s:q+=T,;s+=T,
 return s
Z=lambda B:[[j[0]if j else j for j in i]for i in B]
def S(b):
 b=[[*i]for i in b if any(i)]
 if 1-any([*zip(*b)][0]):b=[i[1:]for i in b]
 if 1-any([*zip(*b)][-1]):b=[i[:-1]for i in b]
 return b
C=lambda b:[(x,y)for x,t in E(b)for y,j in E(t)if j]
P=[(1,0),(0,1),(-1,0),(0,-1)]
def M(b):
 t=C(b)
 q=[t.pop(0)]
 while q:
  x,y=q.pop()
  for j,k in P:
   c=(x+j,y+k)
   if c in t:t.remove(c);q+=c,
 return[]==t
V=lambda b,x,y:x*y==0 or len(b)==x or len(b[0])==y
def f(n):
 w=int(n**0.5)
 b=[[[1,0]for _ in R(w)]for _ in R(n//(w or 1))]+[[[1,0]for _ in R(n%(w or 1))]]*(n%(w or 1)>0)
 B=[i+[0]*(max(map(len,b))-len(i))for i in b]
 q,s=[B],[Z(B)]
 while q:
  b=q.pop(0);c=C(b)
  for x,y in c:
   if 0==b[x][y][1]:
    for X,Y in c:
     if(X,Y)!=(x,y):
      for j,k in P:
       J,K=X-j,Y-k;B=eval(str(b));B[x][y]=0
       if(J,K)not in c:
        if K==len(B[0]):B=[i+[0]for i in B]
        if K<0:B=[[0]+i for i in B];K=0
        if J==len(B):B=B+[[0 for _ in B[0]]]
        if J<0:B=[[0 for _ in B[0]]]+B;J=0
        B[J][K]=[1,1]
        if M(S(Z(B)))and all(S(Q)not in s for Q in U(S(Z(B)))):q+=B,;s+=S(Z(B)),
 return len(s)

```

Try it online!

* Rather long in bytes, but computes solutions up to and including \\$n = 9\\$ in under 40 seconds on TIO.

# Answer
> 2 votes
# , ~~205~~ 199 bytes

```
f=\(n,o={},v=0,u=0,`~`=c,`?`=sort,d=-1~1i~1~-1i){for(j in u)F=F+`if`(length(p<-?j~o)<n,f(n,p,v,setdiff((u=u[-1])~j+d,v<-j~v)),2^(-all(apply(Conj(p)%o%d,2,a<-\(x)any(diff(p-?x))))-a(-p)-a(p*1i))/n);F}

```

Attempt This Online!

A variation of my answer to the related challenge adapted to account for reflections.

Specifically, since the polyominoes \\$p\\$ are stored as complex numbers, reflections across both axes and diagonals can be represented by their complex conjugates \\$Conj(p)\\$ multiplied by directional vectors in \\$d\\$.

# Answer
> 1 votes
# Wolfram Language(Mathematica), ~~532~~ ~~496~~ 366 bytes

saved so many bytes thanks to the comment of @Aiden Chow

---

**Modified from the Mathematica code provided by A000105.** **Really naive. I don't know what I'm doing.**

---

```
z[p_]:=Union[(#-(Min@Re@p+Min@Im@p*I))&/@p];Q[1]={{0}};Q[n_]:=Module[{f,g,a={}},g=((f=#;({f,#+1,f,#+I,f,#-1,f,#-I}&/@f))&)/@Q[n-1];f=Select[Union[z/@Partition[Flatten@g,n]],Length@#==n&];While[f!={},a={a,Z=f[[1]]};f=Complement[f,Union[z/@Flatten[{#,(#-2Re@#)&/@#}&/@Module[{i=Z,a={Z}},While[(i=I*i)!=Z,a~AppendTo~i];a],1]]]];Partition[Flatten@a,n]];F[n_]:=Length@Q@n

```

Try it online!

---

The original Mathematica code looks like

```
(* In this program by Jaime Rangel-Mondragón, polyominoes are represented as a list of Gaussian integers. *)
polyominoQ[p_List] := And @@ ((IntegerQ[Re[#]] && IntegerQ[Im[#]])& /@ p);
rot[p_?polyominoQ] := I*p;
ref[p_?polyominoQ] := (# - 2 Re[#])& /@ p;
cyclic[p_] := Module[{i = p, ans = {p}}, While[(i = rot[i]) != p, AppendTo[ans, i]]; ans];
dihedral[p_?polyominoQ] := Flatten[{#, ref[#]}& /@ cyclic[p], 1];
canonical[p_?polyominoQ] := Union[(# - (Min[Re[p]] + Min[Im[p]]*I))& /@ p];
allPieces[p_] := Union[canonical /@ dihedral[p]];
polyominoes[1] = {{0}};
polyominoes[n_] := polyominoes[n] = Module[{f, fig, ans = {}}, fig = ((f = #1; ({f, #1 + 1, f, #1 + I, f, #1 - 1, f, #1 - I}&) /@ f)&) /@ polyominoes[n - 1]; fig = Partition[Flatten[fig], n]; f = Select[Union[canonical /@ fig], Length[#1] == n &]; While[f != {}, ans = {ans, First[f]}; f = Complement[f, allPieces[First[f]]]]; Partition[Flatten[ans], n]];
a[n_] := a[n] = Length[ polyominoes[n]];
Table[Print["a(", n, ") = ", a[n]]; a[n], {n, 1, 12}] (* Jean-François Alcover, Mar 24 2015, after Jaime Rangel-Mondragón *)

```

---
Tags: code-golf, math, sequence, geometry
---


title: Print the ASCII printable character set

text:
# Question
Title: Print the ASCII printable character set
**Challenge:** Print the **entire** printable ASCII charset (not just a range!) in order.

```
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

**Rules:** *read closely*

* No other characters allowed in the output.
* Program/function does not accept input.
* Try not to hardcode/embed the output.
* This is code golf, shortest answer wins.

# Answer
> 7 votes
# MATL, 3 bytes

```
6Y2

```

**Try it Online**

And for the sake of a non-built-in (7 bytes)

```
32:127c

```

# Answer
> 18 votes
# Brainfuck, ~~30~~ 27 bytes

```
+[[>++<<+>-]>]<<<++[<.+>++]

```

Try it online!

### How it works

`+` changes the initial cell to **1**. After this step, we enter the following, nested loop.

```
[        While the current cell is non-zero:
  [        While the current cell (C) is non-zero:
    >++      Increment the cell to C's right twice.
    <<+      Increment the cell to C's left.
    >-       Decrement C.
  ]
  >        Advance to the cell to C's right.
]

```

This computes consecutive powers of **2** until the the value **256 = 0 (mod 256)** is reached. When the outer loop finishes, the tape is in the following state.

```
                                     v
001 002 004 008 016 032 064 128 000 000 000

```

`<<<++` retrocedes three cells and increments twice, leaving the tape as follows.

```
                         v
001 002 004 008 016 032 066 128 000 000 000

```

Now we're ready to print the actual output. As a stop condition, we increment the cell above twice each time we print and increment the cell to its left. Since **66 + 95 × 2 = 256 = 0 (mod 256)**, we stop after printing all **95** printable ASCII characters. We achieve this as follows.

```
[      While the current cell (C) is non-zero:
  <      Retrocede to the cell to C's left.
  .+     Print its content and increment.
  >++    Increment C twice.
]

```

# Answer
> 7 votes
# Brainfuck, ~~40~~ 39 bytes

```
++++[->++++[->++>++++++<<]<]>>>-[-<.+>]

```

Try it online.

## Explanation

```
++++[->++++[->++>++++++<<]<]

```

The nested loops basically mean you multiply the number of plusses together, so 4 × 4 × 2 = 32 in one cell and 4 × 4 × 6 = 96. Here is the tape after running this:

```
00 00 32 96
 ^

```

---

`>>>-` moves the pointer to the fourth cell and decrements it. Now we're done with the setup. 32 is the code for space, the first printable ASCII character. 95 is the number of characters we have to print. Here is the tape now:

```
00 00 32 95
          ^

```

---

`[-<.+>]` runs until the current cell (the fourth one) is zero. It decrements the counter and prints the character and increments it for the next time.

# Answer
> 7 votes
# Cheddar, 29 bytes

```
->(32:126).map((i)->@"i).fuse

```

Range from 32-126, loop over it and get the string at the given char code `@"` and the fuse together (join)

## Cheddar, 7 bytes

```
32@"126

```

Unfortunately this is broken as of the current release but I'm sure you can go back some versions where this works

# Answer
> 6 votes
## Retina, 18 bytes

```

~
{2`
$`
T01`p`_p
```

The leading linefeed is significant.

Try it online!

### Explanation

**Stage 1: Substitution**

```

~
```

We start by replacing the empty (non-existent) input with a single `~`.

**Stage 2: Substitution**

```
{2`
$`

```

The regex of this substitution is still empty, since the ``` separates configuration from regex and `{2` is therefore just the configuration. The `{` indicates that the remaining two stages should be run in a loop until they stop changing the output. The `2` indicates that this specific stage has a limit of `2`, meaning that only the first two matches of the regex will be replaced. Since the regex is empty, that means we get an empty match in front of the string and an empty match after the first character.

This match is replaced with the prefix `$`` which refers to everything in front of the match. For the first match, there is nothing in front of it, so this doesn't insert anything, but for the second match, there is the leading character in front of it, which therefore gets duplicated.

**Stage 3: Transliteration**

```
T01`p`_p

```

Here, `T` activates transliteration mode, and `0` and `1` are limits (where `0` just means "don't set this limit"). Together, they mean "transliterate only the first character in the string". The actual transliteration maps from `p` to `_p`. Here, `p` expands to the printable ASCII characters and `_` means "remove" this character, so the expanded lists look like this:

```
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
_ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

That means spaces get removed and all other characters get decremented by one.

To see how the last two stages act together here is the string after each of the first few and last stages:

```
~
~~
}~
}}~
|}~
||}~
{|}~

...

"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Since the state of the string is only checked after every other stage to determine whether to end the loop, and the two stages cancel each other once we reach the leading space (since Stage 2 adds a space and Stage 3 removes it), this terminates the loop and therefore the program.

# Answer
> 5 votes
# Python 2.7, 36 bytes:

```
print''.join(map(chr,range(32,127)))

```

Simple enough. A full program that prints out the entire ASCII sequence in order.

# Answer
> 4 votes
# Octave, 13 bytes

```
disp(' ':'~')

```

Try it on ideone.

# Answer
> 4 votes
# Bash, 54 bytes

```
man ascii|fold -w1|LC_ALL=C sort -u|tr -cd '[:print:]'

```

Try it online!

I like that this uses the ASCII man page (which contains an ASCII table) to extract the characters.

# Answer
> 4 votes
# Python 2, 30 bytes

```
print bytearray(range(32,127))

```

Try it online!

# Answer
> 3 votes
## Pyth, 5 bytes

```
srd\

```

Try it here.

```
 r         range from
  d        space
   \<del>  to the delete character, 0x7F (included literally in the program)
s          sum (concatenate all)

```

# Answer
> 3 votes
# JavaScript, 54 bytes

```
for(i=32;i<128;i++)console.log(String.fromCharCode(i))

```

Wasted quite a few bytes printing it... Also prints each char on a new line.

# Answer
> 3 votes
# Java 8, 48 bytes

```
v->{for(char i=31;++i<127;)System.out.print(i);}

```

Try it online.

**Explanation:**

```
v->{                       // Method with empty unused parameter and no return-type
  for(char i=31;++i<127;)  //  Loop characters from ' ' to '~'
    System.out.print(i);}  //   And print it

```

# Answer
> 2 votes
# CJam, 6 bytes

```
',32>

```

The second byte is a DEL character. Try it online!

# Answer
> 2 votes
# Perl 6, 17 bytes

```
print |(' '..'~')

```

```
print chrs ^95+32

```

# Answer
> 2 votes
## C, 40 bytes

```
f(){for(char i=32;i<128;i++)putchar(i);}

```

# Answer
> 2 votes
# Bash + general Linux utilities, 18

```
jot -s '' -c 95 32

```

# Answer
> 2 votes
# Brachylog, 3 bytes

```
@Pw

```

`@P` is the string that contains the printable ASCII characters so… yeah, not very interesting.

It's not clear whether OP accepts built-ins or not, and since others have posted answers that use built-ins, I'll use the 3 bytes version until OP clarifies this point.

### With no built-in, 14 bytes

```
32:126e          Get a number between 32 and 126
       :"~c"w    Format that number to STDOUT as a char code
             \   Backtrack

```

# Answer
> 2 votes
# TSQL, 53 bytes - Vertical solution

```
DECLARE @ int=32x:PRINT char(@)SET @+=1IF @<127GOTO x

```

**Fiddle**

# TSQL, ~~75~~ ~~71~~ 68 bytes - Horizontal solution

```
DECLARE @ char(95)=''WHILE 95>LEN(@)SET @=char(126-LEN(@))+@ PRINT @

```

**Fiddle**

# Answer
> 2 votes
# Ruby, 17 bytes

```
$><<[*' '..?~]*''

```

or

```
print *[*' '..?~]

```

# Answer
> 2 votes
# Canvas, 1 byte

Try it here!

---

*Without builtin:*

## ~~15~~ 14 bytes

```
９⁵×４－｛⁷⁷＋＋╷ｃ］∑

```

Try it here!

# Answer
> 2 votes
# Elixir, 24 bytes

```
IO.puts Enum.uniq 32..?~

```

Try it online!

Prints a trailing newline. If that's not acceptable, it's +1 byte for `write` instead of `puts`.

`uniq` is the cheapest operation I managed to find for converting range to list. As a bonus, here are 4 different programs that all accomplish the task in 27 bytes:

```
IO.puts Enum.to_list 32..?~
IO.puts Enum.into 32..?~,[]
IO.puts Enum.take 32..?~,95
IO.puts for n<-32..?~,do: n

```

# Answer
> 2 votes
### x86\_16 machine code - 21 15 bytes

-6 bytes, thanks @anna328p

```
B8 20 0E        MOV AX, 0E20H
            .LOOP:
CD 10           INT 10H
40              INC AX
3C 7E           CMP AL, 7EH
75 F6           JNE .LOOP
B8 4C00         MOV AX, 4C00H
CD 21           INT 21H

```

Running on DOSBox :

# Answer
> 2 votes
# APL (Dyalog Extended), 7 bytes (SBCS)

Full program.

```
' '…'~'

```

Try it online!

Do I need to explain?

# Answer
> 2 votes
# Perl 5 using only keywords with lowercase alphabets only separating each of them only a space, ~~227~~ 129 bytes

```
eval q y print chr length xor s qq q while uc le q q q x length q q truncate tie q x length q q foreach q y for q q q x ord q q q

```

Try it online!

## How it works

```
eval q y
      print chr length
      xor s qq q
   while
      # default variable has spaces only; equibalent to $_
      uc
      # instead of <=126
      le q q q
         # 126==14*9
         x length q q truncate tie q
         x length q q foreach q
# just noticed i could golf the word
y for q q q x ord q q q

```

## Previous: 227 bytes.

```
eval q y print chr length xor s qq q while chr length lt chr length q q length length length length length length length length length length length length length length length length length length q y foreach q q q x ord q q q

```

Try it online!

### How it works

Using length of default variable to be accumulator.

```
eval q y
      # print chr($accumulator)
      print chr length xor
      # increment it
      s qq q
   while
      # instead of <
      chr length lt
      # 127 is unfortunately a prime; any efficient ideas within the restrictions?
      chr length q q length length length length length length length length length length length length length length length length length length q
# $accumulator=32
y foreach q q q x ord q q q

```

# Answer
> 2 votes
# Vyxal, 5 bytes

```
kPs5ȯ

```

Try it Online!

-2 byte thanks to @AaronMiller

# Answer
> 2 votes
# Python 3, 20 bytes

```
lambda:range(32,127)

```

Try it online! Returns a `range` of codepoints.

```
lambda:range(32,127)  # full program
lambda:               # return function taking no arguments that returns...
       range(  ,   )  # range object of all integers between...
             32       # literal...
       range(  ,   )  # minus 1 and...
                127   # literal

```

# Answer
> 1 votes
# SQL, ~~76~~ 75 bytes

(Microsoft SQL Server 2012+)

```
declare @ int=32;while(@<127)begin;print char(@);set @+=1;end

```

Demo

# Answer
> 1 votes
# PHP, ~~40~~ ~~30~~ ~~29~~ ~~26~~ 24 bytes

Thanks to Mego, manatwork and Titus for helping me golf this down.

```
<?=join(range(' ','~'));

```

# Answer
> 1 votes
# Dyalog APL, 11 bytes

```
⎕UCS 31+⍳99

```

`⍳99` integers 1 through 99

`31+` add 31 to them

`⎕UCS` pick those from the Unicode Character Set

# Answer
> 1 votes
# Julia 0.4, 18 bytes

```
map(print,' ':'~')

```

Try it online!

If returning a string from a function is acceptable, a further byte can be saved.

```
f()=' ':'~'|>join

```

# Answer
> 1 votes
## Haskell, 16 bytes

```
putStr[' '..'~']

```

# Answer
> 1 votes
## C#, ~~51~~ ~~45~~ 40 bytes

```
for(char x=' ';x<=128;)Debug.Write(x++);

```

# Answer
> 1 votes
## Pyke, 5 bytes

```
~KS4>

```

Try it here!

Pyke's printable variable isn't sorted and it contains tabs and newlines etc... :(

# Answer
> 1 votes
## C - 35 bytes

```
f(i){for(i=31;++i<128;putchar(i));}

```

Call:

```
int main() {
    f();
}

```

Uses the horrible `int`-as-a-string trick I learnt from Lynn. (Will again if OP confirms that a vertical output is OK).

# Answer
> 1 votes
# Mathematica, 22 bytes

```
32~CharacterRange~126&

```

Pretty simple. `&` creates an anonymous function and `32~CharacterRange~126` outputs a list of characters from 32 () to 126 (`~`). Actually, I'm pretty sure this is optimal this time.

# Answer
> 1 votes
# Excel VBA, 57 bytes:

Prints individual characters

```
Sub a()
For i = 32 To 126
Debug.Print Chr(i)
Next
End Sub

```

Prints out joined string, **68 bytes**

```
Sub a()
For i = 32 To 126
b = b & Chr(i)
Next
Debug.Print b
End Sub

```

# Answer
> 1 votes
## **Majc** (formely hashmap), 6 bytes

```
r af

```

The delete character is unprintable so here's the hex code (xxd):

```
0000000: 7220 7f61 660a                           r .af.

```

# Answer
> 1 votes
# C, 33 bytes

```
i;f(){++i<96&&putchar(i+31)|f();}

```

# Answer
> 1 votes
# Retina, 12 bytes

The  is the Unit Separator character `\x1F` (31)

```

+;T`p`p_

```

Try it online!

---

# Retina 0.8.2, 18 bytes

Same method as above, but requires some extra bytes for printing and not having a trailing newline.

```

+*\T`p`p_
\`.

```

Try it online!

---

If, like in Martin's answer, a trailing newline is acceptable, then this is possible, beating him by 5 bytes:

# Retina 0.8.2, 13 bytes

```

+*\T`p`p_

```

Try it online!

# Answer
> 1 votes
# Gol\>\<\>, 9 bytes

```
`_FLss|rH

```

Try it online!

### How it works

```
`_FLss|rH

`_F...|    Run the following 95 times:
   Lss       Push the loop counter + 32
       rH  Print all the chars in the pushed order and halt

```

# Answer
> 1 votes
# F# (.NET Core), 30 bytes

```
Seq.iter(printf"%c")[' '..'~']

```

Try it online!

# Answer
> 1 votes
# Tcl, 55 bytes

```
set i 31
time {puts -nonewline [format %c [incr i]]} 95

```

Try it online!

# Answer
> 1 votes
# Common Lisp, 41 bytes

```
(dotimes(i 95)(princ(code-char(+ i 32))))

```

Try it online!

# Answer
> 1 votes
# Charcoal, 1 byte

```
γ

```

Try it online!

No builtin, 7 bytes:

```
⪫…· ¦~ω

```

Try it online!

### Explanation

```
⪫     ω  Join by empty string
 …· ¦~    Inclusive range from " " to "~"

```

# Answer
> 1 votes
# Add++, 12 bytes

```
L^,126 32rBF

```

Try it online!

### Explanation

```
L^,          Lambda returning stack cast to string (takes character code of numbers)
   126 32r   Inclusive range from 32 to 126
          BF Flatten stack

```

# Answer
> 1 votes
# \>\<\>, ~~21~~ 19 bytes

```
48*v
)?;>:o1+:763**

```

Try it online!

### Explanation

```
48*v               Push 32 and move down
                   Print character, increment, stop if greater than 126
)?;>:o1+:763**

```

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
žQ

```

Try it online!

No builtin, 8 bytes:

```
95Ý32+çJ

```

Try it online!

### Explanation

```
95Ý       Push [0..95]
   32+    Add 32 (vectorizes)
      ç   chr (vectorizes)
       J  Join by empty string

```

# Answer
> 1 votes
# Japt, 2 bytes

```
;E

```

Test it

Or, without a built-in:

# Japt `-P`, 5 bytes

```
95odH

```

Test it

```
95o       :Range [0,95)
   d      :Get the characters at those codepoints
    H     :After adding 32

```

# Answer
> 1 votes
# Ruby, 14 bytes

```
print *?\s..?~

```

Try it online!

# Answer
> 1 votes
# Chip `-w` `-gii` `-c127`, 19 bytes

```
aABbcC,~S
dDEefF^Gg

```

Try it online!

### Flags:

* `-w` Don't attempt to read stdin
* `-gii` Generate incrementing bytes for input
* `-c127` Cut off execution at 127 cycles

### Code:

This is a cat program suitable for ASCII (only handles 7 bits):

```
aABbcC
dDEefF Gg

```

And this suppresses output for values outside the range `0x20`-`0x7f`. (More accurately, it requires that at least one of the bits `0x20` or `0x40` to be true):

```
      ,~S
     F^G

```

# Answer
> 1 votes
# Whitespace, 52 bytes

```
[S S S T    S S S S S N
_Push_32][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][T N
S S _Print_as_character][S S S T    N
_Push_1][T  S S S _Add][S N
S _Duplicate][S S S T   T   T   T   T   T   T   N
_Push_127][T    S S T   _Subtract][N
T   T   N
_If_negative_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs, and new-lines).
Program stops with error: No exit defined.

**Pseudo-code:**

```
Integer c = 32
Start LOOP:
  Print c as character
  c = c + 1
  If c - 127 is negative:
    Go to next iteration of LOOP

```

# Answer
> 1 votes
# Forth (gforth), 27 bytes

```
: f 127 32 do i emit loop ;

```

Try it online!

## Explanation

```
127 32 do  \ loop from 32 to 126 (127 is not printable)
  i emit   \ get the index of the loop, then print it as its ascii representation
loop       \ end the loop

```

# Answer
> 1 votes
# PowerShell 5.1, 22 Bytes

```
-join[char[]](32..126)

```

Or 17 bytes if newlines are allowed and we can ditch the join.

# Answer
> 1 votes
# Rattle, 10 bytes

```
32|![,+]96

```

Try it Online!

# Explanation

This is reasonably simple:

```
32|            sets the top of the stack to 32
   !           disables implicit output of the top of the stack
    [  ]96     loops 96 times
     ,         prints the ASCII character of the int value on top of the stack
      +        increments the top of the stack

```

# Answer
> 1 votes
# Julia 1.0, 15 bytes

```
print.(' ':'~')

```

Try it online!

# Answer
> 1 votes
# AMD64 Bare Metal, 512 bytes

```
mov ah, 0x0e
mov al, 0x20
for_1:
int 0x10
add al, 1
cmp al, 0x7f
je for_1_end
jmp for_1
for_1_end:
jmp $
times 510-($-$$) db 0
db 0x55
db 0xaa

```

```
nasm asciiprintable.asm -f bin
qemu-system-x86_64 -drive format=raw,file=asciiprintable

```

# Answer
> 1 votes
# Zsh builtins only, 25 bytes

Using "builtins only" to avoid competing with the `jot` solution (18 bytes).

25 bytes: try it online

```
for a ({\ ..~})echo -n $a

```

---

32 bytes: try it online

```
for a ({32..126})echo -n ${(#)a}

```

# Answer
> 1 votes
# , 13 bytes

```
10h$32+til 95

```

# k, 10 bytes

```
10h$32+!95

```

Generate 32, 33, ..., 126, 127 and convert these to their ASCII character representations.

# Answer
> 1 votes
# GolfScript, 15 14 bytes

*-1 byte thanks to Steffan*

```
95,{[32+]''+}/

```

Try it online!

## Explanation

```
     {...}/ # for each item in
95,         # 0-95
      [32+] # add 32 to that number and put it in an array
      ''+   # output that value as ascii

```

# Answer
> 1 votes
# Lua, 38 bytes

```
for i=32,126 do print(('').char(i))end

```

Try it online!

or, if newlines are not allowed, 41 bytes:

```
for i=32,126 do io.write(('').char(i))end

```

Try it online!

# Answer
> 0 votes
# Scala, 25 bytes

```
()=>' 'to'~'foreach print

```

Anonymous function with no args which prints given range

See it online: https://ideone.com/fX2rwf

# Answer
> 0 votes
## Lua - 41 bytes

```
for i=32,127 do io.write(("").char(i))end

```

# Answer
> 0 votes
# Perl 5, 21 bytes

```
print map{chr}32..127

```

Try it online!

# Answer
> 0 votes
# 2sable, 8 bytes

```
95Ý32+çJ

```

Try it online!

Same as for 05AB1E

### Explanation

```
95Ý       Push [0..95]
   32+    Add 32 (vectorizes)
      ç   chr (vectorizes)
       J  Join by empty string

```

# Answer
> 0 votes
# 3var, 20 bytes

```
iiss+<+<>+<+<kkF[Pi]

```

Try it online!

### Explanation

```
iiss                 Increment A twice, square A twice (set a to 16)
    +                Add A to B (set R to 16)
     <               Set B to R
      +<>            Add A and B (16 + 16 = 32), store to A and B
         +<+<        Add 32 to B twice more (B = 96)
             kk      Decrement B twice (B = 94)
               F[  ] Do B times
                 Pi  Print A as character and increment A

```

# Answer
> 0 votes
# Actually, 12 bytes

```
:95r:32+♂┌εj

```

Try it online!

### Explanation

```
:95r          Push [0 .. 95]
    :32+      Add 32
        ♂┌    Map chr over TOS
          εj  Join by empty string

```

# Answer
> 0 votes
**VBA (Excel), 28 bytes**

using immediate window.

`for i=32to 126:?chr(i);:next`

# Answer
> 0 votes
# Prolog (SWI), ~~80~~ ~~68~~ ~~67~~ ~~62~~ 45 bytes

```
?-between(32,126,I),writef('%n',[I]),1=0;1=1.

```

Try it online!

# Answer
> 0 votes
# Swift 4, 57 bytes

```
for i in 32...126{print(UnicodeScalar(i)!,terminator:"")}

```

Try it online!

# Answer
> 0 votes
# Stax, 2 bytes

```
Vp

```

Run and debug it

# Answer
> 0 votes
# Jelly, 2 bytes

```
ØṖ

```

Try it online!

Yep, it's included, but here's an answer without the builtin:

# Jelly, 7 bytes

```
95Ḷ+32Ọ

```

Try it online!

```
95Ḷ        create lowered range, from 0 to 94 inclusive
   +32     add 32 to every element in the range
      Ọ    cast the entire list to characters and implicitly print

```

# Answer
> 0 votes
# Yabasic/VBA, 29 bytes

An anonymous function that takes no input and outputs to the console.

Note that the VBA answer could be 1 byte shorter by using `Chr` instead of `Chr$`.

```
For i=32To 126:?Chr$(i);:Next

```

Yabasic: Try it online!

VBA: There is no TIO for VBA :(

# Answer
> 0 votes
# JavaScript (Node.js), 47 bytes

```
for(i=31;++i<127;)alert(String.fromCharCode(i))

```

Try it online!

# Answer
> 0 votes
# Befunge-93, 18 bytes

```
 g:"~"`#@_:,1+00p#

```

You can try it here. The leading space is important!

```
                     The current character to be printed/checked, starts loop with a space
  g                  Push character from (0|0) onto stack(using the implicit 0s on the empty stack)
   :"~"`#@_          Check whether the char on (0|0) is over ~, if yes then end
           :,1+00p   Duplicate current char for output and incrementation
                  #  Since the code is a torus, it would continue at (0|0) so we skip it, since it could break the code.

```

# Answer
> 0 votes
# Python - 41 bytes

```
for i in range(32, 127, 1):
 print(chr(i))

```

Python has a built-in ASCII function, so we can use that and print all 95 characters in a loop, one at a time.

### No newlines - 50 bytes

```
for i in range(32, 127, 1):
 x = x + chr(i)
print(x)

```

This is *just in case* newlines aren't allowed, so this entry still gets in.

# Answer
> 0 votes
# naz, 32 bytes

```
4a5m6m6a2x1v1x1f1a1o3x1v1l0x4d1f

```

Try it online!

**Explanation** (with `0x` instructions removed)

```
4a5m6m6a2x1v   # Set variable 1 equal to 126
1x1f           # Function 1
    1a1o       # Add 1 to the register, then output
        3x1v1l # Goto the start of the function if the register is less than variable 1
4d             # Integer divide by 4, setting the register to a value of 31
1f             # Call function 1

```

# Answer
> 0 votes
# Pxem, 17 bytes (filename) + 0 bytes (content) = 17 bytes.

* Filename (some unprintables are escaped): `~.z.c\001.-.c\037.a.s.p`
* Content: empty.

Try it online!

## With comments

```
XX.z
.a~.zXX.z # push 127; while size<2 || (pop!=pop); do
  .a.cXX.z # dup
  .a\001.-XX.z # push 1; push abs(pop-pop) iff size>=2
  .a.cXX.z # dup
.a\037.aXX.z # push 31; done
.a.s.pXX.z # pop (* to remove 31 *); while size>0; do printf "%c", pop; done
.a

```

# Answer
> 0 votes
# Factor, 18 bytes

```
32 126 [a,b] write

```

Works in any modern version of Factor that supports printing non-string sequences directly. (i.e. not TIO.)

# Answer
> 0 votes
# Kotlin, 27 bytes

```
(' '..'~').joinToString("")

```

Try it online!

# Answer
> 0 votes
# Knight, 23 bytes

```
;=a 31W>127=a+1aO+Aa"\"

```

Try it online!

Unminified:

```
; = a 31
: WHILE (> 127 (= a (+ 1 a)))
    : OUTPUT (+ (ASCII a) "\")

```

# Answer
> 0 votes
# Ly, 7 bytes

```
' '~R&o

```

Try it online!

```
' '~     - push first (" ") and last ("~") printable characters
    R    - generate a rage of codepoints
     &o  - print the stack as characters

```

# Answer
> 0 votes
# Z80Golf, 9 bytes

```
00000000: 3e 20 06 5f ff 3c 10 fc 76                     > ._.<..v

```

Try it online!

Assembler source (z80asm):

```
start:
    ; start at space
    ld      a, ' '
    ; loop counter
    ; I could also cp 0x7f; jr nz, .loop but this is faster to TOTALLY make up for below
    ld      b, 0x7F - ' '
.loop:
    ; Call 0x38, then nop slide to 0x8000 to print A to stdout
    ; only has a 130842 cycle overhead, which is worth the 2 bytes it saves
    rst     0x38
    ; set A to the next char
    inc     a
    ; Decrement b, then loop if non-zero
    djnz    .loop
    ; Exit
    halt

```

Pretty straightforward loop approach.

# Answer
> 0 votes
# Knight (v2), 23 bytes

```
;;=s@W>95s=s+sA+32sO^sN

```

Try it online!

Another Alternative is

```
;=a@W>95=a+1aO+A+31a"\"

```

# Answer
> 0 votes
# Pascal, 66 B

This program *requires* to be run on a processor using the ASCII character set (or a binary-compatible superset). The output will look quite different for instance on an IBM mainframe using EBCDIC.

```
program p(output);var c:char;begin for c:=' 'to'~'do write(c)end.

```

Note, in Pascal `for`-loop limits are *inclusive*. During the final iteration `c` assumes the specified value `'~'`.

# Answer
> 0 votes
# Alice, 14 bytes

```
' w.oh.'~h-$K@

```

Try it online!

## Explanation

```
' w.oh.'~h-$K@   Full program
'                Adds 32 (space) on the stack
  w        $K@   Repeat until...
      .'~h-      ...we reach 126 (~)
   .oh           Print and increase the current character

```

# Answer
> 0 votes
# Go, 45 bytes

```
func(){for i:=32;i<127;i++{print(string(i))}}

```

Attempt This Online!

Prints to STDERR.

# Answer
> 0 votes
# International Phonetic Esoteric Language, 21 bytes

```
{3j}{w}ɑeχue1søɒ

```

## Ungolfed

```
{3j}{w}   ( loop bounds: 32 w <= e < 127 3j )
ɑ         ( loop )
 e        ( push index )
  χ       ( ord index )
   u      ( pop-output without newline )
    e1sø  ( increment index )
        ɒ ( end loop )

```

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


title: Identify 22-TET intervals

text:
# Question
Title: Identify 22-TET intervals
# Objective

Given the distance between two keys in an octave, identify its name.

But there's a caveat. In this challenge, there are 22 keys in an octave, not usual 12.

Here, a porcupine\[7\] scale will be assumed.

# Mapping

White keys are marked **bold**.

| Distance | Name |
| --- | --- |
| **0** | `Unison` |
| 1 | `Augmented Unison` or `Diminished Second` |
| 2 | `Minor Second` |
| **3** | `Major Second` |
| 4 | `Augmented Second` |
| 5 | `Diminished Third` |
| **6** | `Minor Third` |
| 7 | `Major Third` |
| 8 | `Augmented Third` or `Diminished Fourth` |
| **9** | `Perfect Fourth` |
| 10 | `Major Fourth` |
| 11 | `Augmented Fourth` or `Diminished Fifth` |
| 12 | `Minor Fifth` |
| **13** | `Perfect Fifth` |
| 14 | `Augmented Fifth` or `Diminished Sixth` |
| 15 | `Minor Sixth` |
| **16** | `Major Sixth` |
| 17 | `Augmented Sixth` |
| 18 | `Diminished Seventh` |
| **19** | `Minor Seventh` |
| 20 | `Major Seventh` |
| 21 | `Augmented Seventh` or `Diminished Octave` |
| *(others)* | *(don't care)* |

# Rule

You can freely mix cases in output. Trailing whitespaces are permitted.

# Answer
# Vyxal, 54 bytes

```
6ɾ›∆o`diø¤Ṁ§ ↑ṙ €ǐ ÷¨ «ø⟑ƒ₄ḭ`⌈vMƒJRvṄ»9Tr⌈»bTİ`Ẏ↲½Ŀ`pi

```

Try it Online!

### How?

Get the list `["second", "third", ... , "seventh"]`:

```
6ɾ›∆o

```

Get the list `["diminished", "minor", "perfect", "major", "augumented"]`:

```
`diø¤Ṁ§ ↑ṙ €ǐ ÷¨ «ø⟑ƒ₄ḭ`⌈

```

Get all pairs in the correct order and join them by space:

```
vMƒJRvṄ

```

Only keep the some of the pairs:

```
»9Tr⌈»bTİ

```

Prepend `"unison"` and index into the list:

```
`Ẏ↲½Ŀ`pi

```
> 6 votes

# Answer
# JavaScript (ES6), 153 bytes

```
n=>n?(a="AugmentedDiminishedMinorMajorPerfectSecondThirdFourthFifthSixthSeventh".match(/.[a-z]+/g))["51324"[n-9]^n%13%4]+' '+a[n+3*(n>11)+19>>2]:'Unison'

```

Try it online!

### How?

The case \\$n=0\\$ is processed separately.

We use the repeating sequence ***Diminished** / **Minor** / **Major** / **Augmented*** for \\$1\le n\le 8\\$ and for \\$14\le n\le 21\\$. The corresponding indices in the lookup array are \\$\[1,2,3,0\]\\$. This is done by reducing \\$n\\$ modulo \\$13\\$ and then modulo \\$4\\$.

We actually use the same calculation for \\$9\le n\le 13\\$, but we apply a bitwise XOR to get the correct indices \\$\[4,3,0,2,4\]\\$, corresponding to ***Perfect** (Fourth) / **Major** (Fourth) / **Augmented** (Fourth) / **Minor** (Fifth) / **Perfect** (Fifth)*.

This gives:

```
"51324"[n - 9] ^ n % 13 % 4

```

We then need to append ***Second*** to ***Seventh*** with indices \\$5\\$ to \\$10\\$ in the lookup array. The expected sequence is:

```
     n | 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21
-------+---------------------------------------------------------------
 index | 5  5  5  5  6  6  6  6  7  7  7  8  8  9  9  9  9 10 10 10 10

```

Basically, each index is repeated 4 times but 3 indices are omitted between \\$n=11\\$ and \\$n=12\\$.

This can be obtained with:

```
n + 3 * (n > 11) + 19 >> 2

```
> 10 votes

# Answer
# Charcoal, ~~95~~ 94 bytes

```
⪫Ｅ§⪪”$＆⊞ςq×Ｐ5μ·⸿§▷"↑Ｗ4⪪9Ｑλς”²⊖Ｎ§⪪”↶⌈∨Ｓ⎚χ]¹↶Ｅ´üêＢ⭆↓ＨηW◧⁻◨~,⦄Zi≦r⊗Þπ↖Z):⊕À´Ａeδ∨8:≧#$/ＶMχ)Ａ” ⌕αι

```

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

```
    ”...”                   Compressed lookup table
   ⪪     ²                  Split into substrings of length `2`
  §                         Index by
           Ｎ                Input integer
          ⊖                 Decremented
 Ｅ                          Map over letters
             ⪪”...”         List of words
            §               Indexed by
                    ⌕αι     Uppercase letter index
⪫                           Join with spaces
                            Implicitly print

```

Note that the lookup table is `43` letters long so that the last entry only has one letter; this is the one that is then selected for an input of `0`.

Previous 95-byte solution:

```
Ｎθ∧θ§⪪”↶↧*y³↨Cⅈ～➙…⟧⊖⁺¡κＹ⁸⁴Σ1|R6；” §”)⊞⮌i›‽”θＭ→§⪪”↶⌈∨l⟲Ｅχ⁼⁰θ℅ＢNμ↨%),ρ℅«◨ TＨＹ¬O⬤ε” §”)➙:⌊B/Ｍ⁷ê\`”θ

```

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

```
Ｎθ

```

Input the distance.

```
∧θ§⪪”...” §”...”θ

```

If it's not zero, cyclically index into the compressed table `4012301234231` to find the index into the compressed list of words `diminished minor major augmented perfect`.

```
Ｍ→

```

Leave a space between the two words.

```
§⪪”...” §”...”θ

```

Index into the compressed table `0111122223334455556666` to find the index into the compressed list of words `unison second third fourth fifth sixth seventh`.
> 2 votes

# Answer
# 05AB1E, ~~71~~ 70 bytes

```
.•10°ÝΣËðw¶\ƵUʒ•…‡®¢ÑíÀ«#•”Öζт'µ•5вè“…Þ‰ª¦ƒ³äÇïÖµ“#•γ¤æ•ÅΓø.•I¢#€•šÅв»

```

Outputs in lowercase.

Try it online or verify all test cases.

**Explanation:**

```
.•10°ÝΣËðw¶\ƵUʒ• # Push compressed string "augmented diminished "
 …‡®¢ÑíÀ         # Push dictionary string "major minor perfect"
        «        # Append them together
         #       # Split this string on spaces:
                 #  ["augmented","diminished","major","minor","perfect"]
•”Öζт'µ•        '# Push compressed integer 160475945053335
        5в       # Convert it to base-5 as list:
                 #  [1,3,2,0,1,3,2,1,4,2,1,3,4,1,3,2,0,1,3,2,0]
          è      # 0-based index each into the previous list of strings
“…Þ‰ª¦ƒ³äÇïÖµ“   # Push dictionary string "second third fourth fifth sixth seventh"
              #  # Split it by spaces as well
•γ¤æ•            # Push compressed integer 4333444
     ÅΓ          # Run-length decode the list of strings and digits of this integer
ø                # Create pairs of the two list of strings
 .•I¢#€•         # Push compressed string "unison"
        š        # Prepend it to the list of pairs
Åв               # Convert the (implicit) input-integer to this custom base as list
  »              # Join each inner pair by spaces, and then the strings by newlines,
                 # which simply pushes the only string in the list in this case
                 # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (all four sections) to understand why `.•10°ÝΣËðw¶\ƵUʒ•` is `"augmented diminished "`; `…‡®¢ÑíÀ` is `"major minor perfect"`; `•”Öζт'µ•` is `160475945053335`; `•”Öζт'µ•5в` is `[1,3,2,0,1,3,2,1,4,2,1,3,4,1,3,2,0,1,3,2,0]`; `“…Þ‰ª¦ƒ³äÇïÖµ“` is `"second third fourth fifth sixth seventh"`; `•γ¤æ•` is `4333444`; and `.•I¢#€•` is `"unison"`.
> 1 votes

---
Tags: code-golf, music
---