title: N-dimensional N^N array filled with N

text:
# Question
Title: N-dimensional N^N array filled with N
**In:** Enough memory and a positive integer N

**Out:** N-dimensional N^N array filled with N, where N^N means N terms of N-by-N-by-N-by...

**Examples:**

1: `[1]` which is a 1D array (a list) of length 1, containing a single 1

2: `[[2,2],[2,2]]` which is a 2D array (a table) with 2 rows and 2 columns, filled with 2s

3: `[[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]]` which is a 3D array (a cube) with 3 layers, 3 rows, and 3 columns, filled with 3s

4: `[[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]]]`

5 and 6: Please see one of the answers.

# Answer
> 57 votes
# Python, 32 bytes

```
lambda n:eval('['*n+'n'+']*n'*n)

```

Try it online!

Makes a string like `"[[[n]*n]*n]*n"` with `n` multiplcations, and evaluates it as Python code. Since the evaluation happens within the function scope, the variable name `n` evaluates to the function input.

# Answer
> 34 votes
# J, 4 bytes

```
$~#~

```

Try it online!

## Explanation

```
$~#~  Input: integer n
  #~  Create n copies of n
$~    Shape n into an array with dimensions n copies of n

```

# Answer
> 13 votes
# APL (Dyalog APL), 4 bytes

```
⍴⍨⍴⊢

```

Try it online!

# Answer
> 13 votes
# Mathematica, ~~22~~ 20 bytes

```
(t=Table)@@t[#,#+1]&

(* or *)

Table@@Table[#,#+1]&

```

# Answer
> 10 votes
## JavaScript (ES6),  ~~44~~  40 bytes

```
f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k

```

### Demo

```
f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k

console.log(JSON.stringify(f(1)))
console.log(JSON.stringify(f(2)))
console.log(JSON.stringify(f(3)))
console.log(JSON.stringify(f(4)))
```

# Answer
> 10 votes
# Octave, ~~35~~ ~~33~~ ~~25~~ ~~23~~ 20 bytes

```
@(N)ones(N+!(1:N))*N

```

Try it online!

```
@(N)ones(N*ones(1,N))*N

@(N)repmat(N,N*ones(1,N))

```

Thanks to @LuisMendo saved 8 bytes

```
@(N)ones(num2cell(!(1:N)+N){:})*N

```

Try it online!

Previous answer:

```
@(N)repmat(N,num2cell(!(1:N)+N){:})

```

Try it online!

# Answer
> 10 votes
# R, 26

This is the obvious answer but perhaps there is something cleverer?

```
n=scan();array(n,rep(n,n))

```

# Answer
> 9 votes
# 05AB1E (legacy), ~~6~~ 5 bytes

-1 thanks to Kevin Cruijssen

```
F¹.D)

```

Try it online!

```
F     # For 0 .. input
 ¹.D) # Push <input> copies of the result of the last step as an array

```

# Answer
> 9 votes
# Haskell, 52 bytes

```
f n=iterate(filter(>'"').show.(<$[1..n]))(show n)!!n

```

Try it online!

Inspired by @nimi's answer, but using more predefined functions.

* Uses `iterate` and `!!` instead of a recursive help function.
* Instead of constructing list delimiters "by hand", uses `filter(>'"').show` to format a list of strings, then stripping away the extra `"` characters.

# Answer
> 8 votes
## Haskell, 62 bytes

```
n#0=show n
n#l='[':tail((',':)=<<n#(l-1)<$[1..n])++"]"
f n=n#n

```

Usage example: `f 2` -\> `"[[2,2],[2,2]]"`. Try it online!.

Haskell's strict type system prevents a function that returns nested lists of different depths, so I construct the result as a string.

How it works:

```
n#l=                         n with the current level l is
    '[':                     a literal [ followed by
           n#(l-1)<$[1..n]   n copies of   n # (l-1)
        (',':)=<<            each prepended by a , and flattened into a single list
      tail                   and the first , removed
                  ++"]"      followed by a literal ]

n#0=show n                   the base case is n as a string

f n=n#n                      main function, start with level n

```

# Answer
> 7 votes
# Python 2, 36 bytes

-2 bytes thanks to @CalculatorFeline

```
a=n=input()
exec"a=[a]*n;"*n
print a

```

Try it online!

# Answer
> 7 votes
# MATL, 8 bytes

```
ttY"l$l*

```

Try it at **MATL Online** (I have added some code showing the *actual* size of the output since all n-dimensional outputs in MATL are shown as 2D matrices where all dimensions \> 2 are flattened into the second dimension).

**Explanation**

```
        % Implicitly grab the input (N)
tt      % Make two copies of N
Y"      % Perform run-length decoding to create N copies of N
l$1     % Create a matrix of ones that is this size
*       % Multiply this matrix of ones by N
        % Implicitly display the result

```

# Answer
> 7 votes
# Jelly, 5 bytes

```
⁾Wẋẋv

```

**Try it online!**

### How?

```
⁾Wẋẋv - Main link: n                            e.g.       3
⁾Wẋ   - character pair literal ['W','ẋ']                  "Wẋ"
   ẋ  - repeat list n times                               "WẋWẋWẋ"
    v - evaluate as Jelly code with input n          eval("WẋWẋWẋ", 3)
      - ...
        WẋWẋ... - toEval: n                e.g. 3
        W        - wrap                        [3]
         ẋ       - repeat list n times         [3,3,3]
          Wẋ     - wrap and repeat            [[3,3,3],[3,3,3],[3,3,3]]
            ...  - n times total             [[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]]

```

# Answer
> 7 votes
# Jelly, 4 bytes

```
R»µ¡

```

Try it online!

```
R»µ¡
R     Range. 2 -> [1, 2]
 »    Max between left arg and right arg. Vectorizes. -> [2, 2]
  µ   Separates into a new chain.
   ¡  Repeat 2 times. After another iteration this yields [[2, 2], [2, 2]].

```

Same thing but with a single monad and no need for the chain separator:

**4 bytes**

```
»€`¡

```

# Answer
> 6 votes
# CJam, 12 bytes

```
ri:X{aX*}X*p

```

Try it online!

**Explanation**

```
ri:X          Read an integer from input, store it in X (leaves it on the stack)
    {   }X*   Execute this block X times:
     a          Wrap the top of stack in an array
      X*        Repeat the array X times
           p  Print nicely

```

# Answer
> 6 votes
# Java ~~97~~ ~~96~~ 95 bytes

```
Object c(int n,int i){Object[]a=new Object[n];for(int j=0;j<n;)a[j++]=i<2?n:c(n,i-1);return a;}

```

---

Ungolfed:

```
public class N_Dim {

    public static Object create(int n) {
        return create(n, n);
    }

    public static Object create(int n, int i) {
        Object[] array = new Object[n];
        for(int j=0;j<n;j++) {
            array[j] = i<2?n:create(n, i - 1);
        }
        return array;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString((Object[]) create(3)));
    }

}

```

# Answer
> 6 votes
## JavaScript (ES6), 38 bytes

```
f=(n,m=n)=>m?Array(n).fill(f(n,m-1)):n

```

The memory-hungry version of this is 45 bytes:

```
f=(n,m=n)=>m?[...Array(n)].map(_=>f(n,m-1)):n

```

# Answer
> 6 votes
## Batch, 141 bytes

```
@set t=.
@for /l %%i in (2,1,%1)do @call set t=%%t%%,.
@set s=%1
@for /l %%i in (1,1,%1)do @call call set s=[%%%%t:.=%%s%%%%%%]
@echo %s%

```

Batch doesn't actually have arrays so this just prints the string representation of an array. Explanation: The first two lines build up a repeated pattern of `N` `.`s separated by `N-1` `,`s in the variable `t`. The fourth line then uses this as a substitution pattern `N` times to create the `N`-dimensional array. The double `call` is necessary because of how the `for` and `set` statements work. First, the `for` command substitutes variables. As it happens, all of my `%` signs are doubled, so this does nothing except to unquote them all, resulting in `call call set s=[%%t:.=%s%%%]`. It then repeats the resulting statement `N` times. Each time, the `call` command substitutes variables. At this point, the `s` variable only has a single set of `%`s, so it gets substituted, resulting in (e.g.) `call set s=[%t:.=[2,2]%]`. The inner call then substitutes the `t` variable, resulting in (e.g.) `set s=[[2,2],[2,2]]`, performing the desired assignment. The final value of `s` is then printed.

# Answer
> 5 votes
# Jelly, 5 bytes

```
Wẋ³µ¡

```

Try it online!

## Explanation

```
         Implicit input: N
   µ¡    Apply N times to input:
Wẋ³        “N copies of”

```

# Answer
> 5 votes
# Python 3, ~~57~~ ~~53~~ ~~50~~ 38 bytes

```
f=lambda n,c=0:n-c and[f(n,c+1)*n]or 1

```

Try it online!

---

-4 bytes thanks to @CalculatorFeline

---

**34 bytes:**

```
f=lambda c,n:c and[f(c-1,n)*n]or 1

```

Needs to be called as `f(4,4)`

# Answer
> 5 votes
# Ruby, 28 26 bytes

*Thanks to Cyoce for saving 2 bytes!*

```
->n{eval'['*n+'n'+']*n'*n}

```

Stolen shamelessly from xnor's excellent answer.

# Answer
> 5 votes
## Ruby, 27 bytes

```
->a{(z=a).times{z=[z]*a};z}

```

Only 1 byte more but using a different approach instead of the 'eval' trick from xnor's wonderful Python answer.

# Answer
> 5 votes
# Bash \+ GNU utilities, 117 bytes

```
n=$[$1**$1]
seq -f$1o%.fd$n+1-p $n|dc|rev|sed -r "s/(0+|$[$1-1]*).*$/\1/;s/^(0*)/\1$1/;s/^1/[1]/"|tr \\n0$[$1-1] \ []

```

Try it online!

---

The program essentially counts from 0 to (n^n)-1 in base n, where n is the input. For each base-n number k in the count, it does the following:

1. If k ends with at least one digit 0, print a '\[' for each digit 0 at the end of k.
2. Print n.
3. If k ends with at least one digit n-1, print a '\]' for each digit n-1 at the end of k.

(The value n=1 needs to have brackets added as a special case. This input value also generates some output to stderr, which can be ignored under standard PPCG rules.)

Maybe there's a shorter way to implement this idea.

---

Sample run:

```
./array 3
[[[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]]]

```

# Answer
> 5 votes
# Haskell, 51 bytes

Other than the existing Haskell solutions this constructs a usable data type not just a string representation thereof (and is shorter):

```
data L=N[L]|E Int
f n=iterate(N.(<$[1..n]))(E n)!!n

```

Try it online!

### Explanation / Ungolfed

The reason why this is an interesting challenge in Haskell is that a solution to this challenge needs to return different deeply nested lists and Haskell (without importing external modules) does not support this. One workaround which turned out to be the golfiest, is to define our own data type:

```
data NestedList = Nest [NestedList] | Entry Int

```

Now we can just define a function `f :: Int -> NestedList` which is able to represent all the required data types:

```
pow n = iterate (Nest . replicate n) (Entry n) !! n

```

# Answer
> 5 votes
# MathGolf, ~~5~~ 4 bytes

```
_{a*

```

Try it online!

## Explanation using `n = 2` (note that the outermost `[]` are not arrays, but are just there to show the stack)

```
_      duplicate TOS (stack is [2, 2])
 {     loop 2 times (stack is [2])
  a    wrap in array ([2] => [[2]], [[2, 2]] => [[[2, 2]]])
   *   pop a, b : push(a*b) ([[2]] => [[2, 2]], [[[2, 2]]] => [[[2, 2], [2, 2]]])

```

# Answer
> 5 votes
# Raku, 21 bytes

try it online!

```
{[[xx] [xx] $_ xx 3]}

```

# Answer
> 4 votes
# Julia 0.6, ~~23~~ 21 bytes

```
n->n>(n>n)...
> =fill

```

Try it online!

(Thanks to @MarcMush for -2 bytes.)

In Julia, binary operators are parsed as function calls, so `a>b` is `>(a, b)`, which here is `fill(a, b)`. So the above is really saying:

```
n->fill(n,fill(n,n)...)

```

The first argument to `fill` is the value to fill the new array with. The following arguments to that are the dimensions of the new array. Here we create those dimensions themselves using another `fill` call: we create an array of `n` `n`s, then splat that with `...` so that the first `fill`  call gets n number of dimension arguments, each with value n - so it creates an n-dimensional array where each dimension length is n, and filled with the value n.

# Answer
> 3 votes
# PHP, ~~70~~ 62 bytes

This is the simplest I can come up with.

```
for(;$i++<$n=$argv[1];)$F=array_fill(0,$n,$F?:$n);print_r($F);

```

Takes the input as the first argument and prints the resulting array on the screen.

---

Thanks to @user59178 for saving me **8 bytes**!

# Answer
> 3 votes
# Perl 6, 25 bytes

```
{($^n,{$_ xx$n}...*)[$n]}

```

Starts with `n`, and iteratively applies the "repeat n times" transformation `n` times, each time creating an additional level of `List` nesting.

Try it online!

# Answer
> 3 votes
# Clojure, 36 bytes

```
#(nth(iterate(fn[a](repeat % a))%)%)

```

Iterates function which repeats its argument `n` times, it produces infinite sequence of such elements and then takes its `n`th element.

See it online

# Answer
> 3 votes
# Rebol, 45 bytes

```
func[n][array/initial append/dup copy[]n n n]

```

# Answer
> 3 votes
# Clojure, 49 bytes

```
(defmacro r[n]`(->> ~n ~@(repeat n`(repeat ~n))))

```

Not the shortest Clojure example, but I amused myself with the quoting and unquoting.

# Answer
> 3 votes
# , 7 bytes

I got this from my colleague, the creator of I.

```
#Bbhph~

```

`#Bb` the copy `#` function **B**ound to **b**inding
`hp`**h**ook the argument to (the right of) the **p**ower function (repeat)
`h~`**h**ook the argument to the left `~` (of the entire resulting function)

Try it online!

# Answer
> 3 votes
# Common Lisp, ~~128 102 95~~ 79 bytes

```
(defun f(x &optional y)(if(if y(< y 2))x(fill(make-list x)(f x(if y(1- y)x)))))

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 2 bytes

Try it online or verify the first \\$\[1,5\]\\$ test cases.

<sup>: Uses a Bash script to execute the 05AB1E code, so it'll use the (implicit) input within the test suite. If the number would be on the stack instead of as input, it won't work for \\$n=2\\$ (no idea why..): see this traditional test suite, where every output is correct except for \\$n=2\\$.</sup>

**Explanation:**

```
F   # Loop the (implicit) input amount of times:
 и  #  Repeat the (implicit) input the current values amount of times (as list)
    # (after which the resulting nested list is output implicitly)

```

# Answer
> 3 votes
# tinylisp, 76 bytes

Since tinylisp was our most recent LYAL, I figured I had to at least post one answer in the lang. Embarrassingly, this answer (in a golfing dialect of lisp) is just as long as the Common Lisp solution

```
(load library
(d _(q((N D $)(i D(_ N(s D 1)(repeat-val $ N))$
(q((N)(_ N N N

```

Try it online!

This defines a helper function `_` that takes three arguments, the number of times to repeat each layer `N`, the current depth of the iteration `D` (counting down, so deepest depth is zero), and an accumulator `$`. Depending on depth, this function either returns the accumulator (at depth zero), or uses the library builtin `repeat-val` to repeat the current accumulator `N` times, and passes that on to the next depth of the recursion. Then the actual function, `A`, is defined, which takes a single argument `N` in, and calls `_` with that as all three arguments.

## Non-library solution, 86 bytes

This was my first attempt to do this, without using the builtin library (which has rather ungolfy names), but it unfortunately turned out rather longer.

```
(d _(q((X N D I $)(i D(i I(_ X N D(s I 1)(c X $))(_ $ N(s D 1)N()))X
(q((N)(_ N N N N(

```

Try it online!

This works much the same as the library solution, but manually defines the behavior of `repeat-val`, which requires taking two extra arguments in the helper function, which takes the value `X` the current depth is repeating, the number of repetitions on each depth `N`, the current depth `D` (counting down to zero), the number of repetitions remaining in this depth `I`, and an accumulator `$`. The proper function `A` works much the same, taking `N` calling `_` with the proper arguments. (in this case `N` for the first four, and nil `()` for the accumulator)

# Answer
> 3 votes
# Uiua, 4 bytes

```
↯▽..

```

Try it!

```
↯▽..
   .  # duplicate
  .   # duplicate
 ▽    # keep
↯     # reshape

```

# Answer
> 2 votes
# ***Perl 6, 61 bytes***

```
my $x=prompt(0);my @a=$x xx$x;"@a=[@a] xx $x;".EVAL xx$x-1;

```

Big rippof from the Python 2 answer, but converted :P

# Answer
> 2 votes
# Clojure, 63 bytes

```
#(loop[a(repeat % %)d 1](if(= d %)a(recur(repeat % a)(inc d))))

```

This is a lambda function, usage is like so:

```
(#(...) {input_no})

```

...where `{input_no}` is replaced with the number.

Output for `3` is like this:

```
(((3 3 3) (3 3 3) (3 3 3)) ((3 3 3) (3 3 3) (3 3 3)) ((3 3 3) (3 3 3) (3 3 3)))

```

This uses Clojure's definition of lists, which are denoted as `()`.

## Ungolfed code and explanation:

```
; Defines the function
(defn layered [n]
  ; Begins a loop with a variable depth of 1,
  ; and a list of n elements which are all n
  (loop [depth 1
         array (repeat n n)]
    ; If "depth" is equal to n, return the list
    (if (= depth n) array
      ; Else, continue on with the loop, with
      ; an incremented "depth"...
      (recur (inc depth)
        ; ...and a list which contains the
        ; list repeated n times
        (repeat n array)))))

```

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 59 bytes

```
	DEFINE('F(N)')
F	F =ARRAY(DUPL(N ',',N - 1) N,N)	:(RETURN)

```

Try it online!

Defines a function that returns an `ARRAY` with the appropriate dimensions and filled with value `N`.

# Answer
> 2 votes
# C (GCC), 53 bytes

Since C "has" multidimensional arrays (i.e. chunks of memory plus automatic offset calculation), this is almost a reasonable solution. Still, it's mostly a joke and borders on non-competing.

```
f(n){int s=pow(n,n),*p=malloc(s*8);wmemset(p,n,s);}

```

Try It Online

In the TIO I go through the ceremony of casting the result (which is an `int`) to the appropriate array type despite the fact that my array print function (appropriately) takes a generic pointer.

While I can't demonstrate that the structure of the array is determined by `f` (it's not), I do include a flat printout of the elements of the output for an input of 3 using the multidimensional array element access syntax, to show that the layout of the returned memory matches that of the corresponding array type.

## Byte count

* function: 51 bytes
* compiler flags (`-lm`): 2 bytes

## Unportability

* The result pointer is returned through an `int`, so this may not work for all heap addresses.
* By using `wmemset` I require that the sizes of `int` and `wchar_t` are equal, and the scaling in the argument to `malloc` requires the sizes to be at most 8 bytes.
* Implicit declaration madness. I don't even know why passing `int`s to an unprototyped `pow` that actually takes `double`s seems to work correctly.
* The function "returns" by (I think) just leaving the return value of `wmemset` in the proper register. This behavior may be particular to the x86 architecture.

# Answer
> 2 votes
# Japt, 14 bytes

```
_òU}g[UpU ÆUÃ]

```

Try it online!

Output is wrapped in an extra singleton array.

Explanation:

```
          Æ Ã     #Create an array
           U      #Where every element is U
      UpU         #And the length is U^U
_  }g[       ]    #Repeat this function U times:
 òU               # Cut into slices of length U

```

# Answer
> 2 votes
# K (ngn/k), 9 bytes

```
{(x#x)#x}

```

Try it online!

There's probably a way to make this tacit.

# Answer
> 1 votes
# Python 3, 89 Bytes

```
def f(x):
 r=[x for _ in range(x)]
 for _ in range(x-1):r=[r for _ in range(x)]
 print(r)

```

# Answer
> 1 votes
## Lithp, 82 bytes

```
(def f #N::((def i #N,I,K::((if(> I 0)((i N(- I 1)(list-fill N K)))K)))(i N N N)))

```

Try it online!

I tried implementing this as a list comprehension, but couldn't comprehend how to do it correctly. Instead I went for an implementation based on the JavaScript answer. Unfortunately, my language is fairly long-winded, and this is complicated by the fact that I lack shorthand and other useful features.

A more readable version is available at the Try it Online link.

# Answer
> 1 votes
## Hoon, 56 bytes

```
|=
n/@
=+
i=1
|-
?:
=(n i)
(reap n n)
(reap n $(i +(i)))

```

Create a new function that takes an atom `n`. Make a variable `i` starting at 1, and start a loop: if `i==n` return a list with `n` elements of `n`, else return a list with `n` elements of the value returned by recursing to the start of the loop with `i = i + 1`.

I'm a little bit upset that there's not really anything you can do to golf this in Hoon :/ The standard trick of using unnamed variables doesn't apply because it's longer to use lark syntax for once, due to the loop shifting the location of `i`.

```
> =f |=
  n/@
  =+
  i=1
  |-
  ?:
  =(n i)
  (reap n n)
  (reap n $(i +(i)))
> (f 1)
~[1]
> (f 2)
~[~[2 2] ~[2 2]]
> (f 3)
~[~[~[3 3 3] ~[3 3 3] ~[3 3 3]] ~[~[3 3 3] ~[3 3 3] ~[3 3 3]] ~[~[3 3 3] ~[3 3 3] ~[3 3 3]]]
> (f 4)
~[
  ~[
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
  ]
  ~[
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
  ]
  ~[
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
  ]
  ~[
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
    ~[~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4] ~[4 4 4 4]]
  ]
]

```

# Answer
> 1 votes
# WendyScript, 34 bytes

```
#:(x){<<j=[x]*x#i:1->x j=[j]*x/>j}
#:(x){<<j=[x]*x#i:1->x j=[j]*x/>j}(2) // [[2, 2], [2, 2]]

```

Try it online!

# Answer
> 1 votes
# 12-basic, 42 bytes

```
A=[N=INPUT()]*N
FOR I=2TO N
A=[A]*N
NEXT?A

```

# Answer
> 1 votes
# , 14 bytes

```
é,"aPÀñDÀpys0]

```

Try it online!

input

```
é,               # write comma
  "aP            # paste register A (input)
     Àñ          # loop À (number in register A) times
       D         # cut to end of line
        Àp       # paste À times
          ysB]   # surround everything before comma in square brackets

```

# Answer
> 1 votes
# Pip `-p`, 12 bytes

```
YaLaY[y]RLay

```

Try it online!

### Explanation

```
YaLaY[y]RLay
Y             Yank into the y variable
 a            the first command-line argument, a
  La          Fixed-iterations loop, do the following a times:
     [y]       y wrapped in a list
        RLa    repeated a times (results in a list containing a copies of y)
    Y          Yank that list back into y
           y  After the loop, print y

```

# Answer
> 1 votes
# Factor \+ `arrays.shaped`, 39 bytes

```
[ 3 dupn <array> swap repeated-shaped ]

```

Try it online!

`repeated-shaped` Takes a sequence of dimensions (i.e. a shape) and an element and creates an array from them. The rest of the code turns `4` into `{ 4 4 4 4 } 4`, for example.

# Answer
> 1 votes
# Jelly, 3 bytes

```
ḷⱮ¡

```

Try it online!

Like Lynn's solution which heavily inspired this, a full program only.

```
  ¡    Repeat [input] times, starting with the input on the left and right:
 Ɱ     Produce an array containing, for every element of the right argument,
ḷ      the left argument.

```

Although dyadic `¡`, rather than reusing its right argument, uses the previous left argument for each successive iteration, in this case either behavior would do the same thing--since each intermediate result has the same length as the (implicitly rangified) initial input.

# Answer
> 1 votes
# Pari/GP, 33 bytes

```
n->for(i=1,a=n,a=vector(n,x,a));a

```

Try it online!

# Answer
> 1 votes
# Vyxal, 2 bytes

```
(ẋ

```

Try it Online!

# Answer
> 1 votes
# Go, 150 bytes

```
func f(n int)[]any{return g(n,n)}
func g(n,d int)(L[]any){if d<1{return}
for i:=0;i<n;i++{var e any
if d<2{e=n}else{e=g(n,d-1)}
L=append(L,e)}
return}

```

Attempt This Online!

Call with `f(n)`. Returns an `[]any`, that can be casted to a `f(n).([]int)`,`f(n).([][]int)`,`f(n).([][][]int)`,`f(n).([][][][]int)`, etc.

# Answer
> 1 votes
# BQN, 4 bytes

```
⥊˜⥊⊢

```

Anonymous tacit function; takes an integer and returns an N-dimensional array. Try it at BQN online!

### Explanation

Exactly the same as Dennis's APL answer, though independently derived.

The Reshape builtin  takes a shape (list of integer dimensions) on the left and an array of values on the right. It creates an array of the given shape, filled with values taken from the original array. If either argument is a bare integer, it is promoted to a list containing that integer.

With example argument 3:

`⥊˜` reshapes the argument with itself as the shape. The result is a 3-element 1-dimensional array of 3's: `⟨ 3 3 3 ⟩`.

returns the argument unchanged: `3`.

So `⥊˜ ⥊ ⊢` is equivalent to `⟨ 3 3 3 ⟩ ⥊ 3`: reshape `3` into a 3 by 3 by 3 array.

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
{Wọ

```

Attempt This Online!

#### Explanation

```
{Wọ  # Implicit input
{    # Repeat input number of times:
 W   #  Wrap top of stack into a list
  ọ  #  Repeat input number of times
     # Implicit output

```

# Answer
> 0 votes
## Perl 5, 34 bytes

```
sub{eval'@_=[(@_)x$x];'x($x="@_")}

```

Try it online!

# Answer
> 0 votes
# Lua, 85 bytes

```
function f(n,d,x)d=d or 2 x={}for i=1,n do x[i]=d>n and n or f(n,d+1)end return x end

```

Try it online!

(The TIO link contains a bit of extra code to print the table as Lua has no built-in way of printing a table's contents)

## Explanation

```
function f(n, d, x)
  d = d or 2
  x = {}
  for i = 1, n do
    x[i] = d > n and n or f(n, d + 1)
  end
  return x
end

```

As you can probably see, `f` is a recursive function which takes the number N as `n`, and two other arguments, `d` and `x`. `d` is the depth, and is not used in the initial call, in which case it defaults to 2. `x` is not actually used as a parameter, but is there because the function requires a temporary local variable, and it is shorter to declare it as a parameter than to use the `local` keyword.

# Answer
> 0 votes
# Zsh, 74 bytes

try it online!

```
f(){for i ({1..$1})z+=($2);<<<($z)}
for j ({1..$1})k=`f $1 ${k:-$1}`;<<<$k

```

Zsh doesn't have multi dimensional arrays but it can do arrays of strings. Here we build up string `$k` by plugging it into `f`, then taking that result as the new `$k`, iterating N times (`$1`).

# Answer
> 0 votes
# Arturo, 20 bytes

```
$=>[@.of:@.of:<=<=&]

```

Try it

### Huh?

In Arturo, you can initialize a block of values like this:

```
array.of: 5 2    ; [2 2 2 2 2]

```

You can also give it a shape:

```
array.of: [5 3] 2    ; [[2 2 2] [2 2 2] [2 2 2] [2 2 2] [2 2 2]]

```

`@` is syntax sugar for `array`.

`$=>` is syntax sugar for `function [n]`.

`<=<=&` Means push the input to the stack and duplicate it twice.

So putting it all together, `$=>[@.of:@.of:<=<=&]` is the same as:

```
function [n][
    array.of: array.of: n n n
]

```

Or perhaps more clearly:

```
function [n][
    shape: array.of: n n
    return array.of: shape n
]

```

---
Tags: code-golf, array, integer, generation, data-structures
---


title: Is it double speak?

text:
# Question
Title: Is it double speak?
In an earlier challenge I asked code golfers to produce strings which copy each character in a string. For example:

```
TThhiiss  iiss  ddoouubbllee  ssppeeaakk!!

```

This challenge is simply to detect if some text meets the definition of a double speak string.

* There is an even number of characters.
* When split into pairs, every pair consists of two of the same character.

---

The challenge

* It's code golf, do it in few bytes.
* Use any language you choose.
* Please include a link to an online interpreter.
* The code will accept some text.
* For simplicity, the input will only consist of *printable ASCII characters*
* It will return an indication of whether or not the input is double speak. It could be:
* A boolean
* Strings ('true', 'false', 'yes', 'no' etc)
* Integers 0 or 1

---

Test Cases:

```
input -> output
aba -> false
aab -> false
abba -> false
aabb -> true
aaabb -> false
tthhiiss -> true
ttthhhiiisss -> false

```

# Answer
> 64 votes
# Python 3, 24 bytes

```
lambda s:s[::2]==s[1::2]

```

Try it online!

# Answer
> 29 votes
# brainfuck, 20 bytes

*Saved 1 byte thanks to Jo King.*

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

```

Try it online!

Readable output!

Takes input two characters at a time, and moves away from the 1 on the tape if any pair doesn't match. EOF is treated as 0 and thus handled automatically.

Output is a null byte if the string is not double speak, and 0x01 if it is. The readable version outputs these as characters at a cost of 14 bytes.

# Answer
> 18 votes
# MATL, 4 bytes

```
Heda

```

Input is a string, enclosed with single qoutes. Output is `0` for double speak, `1` otherwise.

Try it online!

### Explanation

Consider input `'TThhiiss iiss ddoouubbllee ssppeeaakk!!'` as an example.

```
H    % Push 2
     % STACK: 2
     % Implicit input (triggered because the next function requires two inputs): string
     % STACK: 'TThhiiss  iiss  ddoouubbllee  ssppeeaakk!!', 2
e    % Reshape as a 2-column matrix of chars, in column-major order. Pads with char(0)
     % if needed. Note that char(0) cannot be present in the input
     % STACK: ['This is double speak!';
               'This is double speak!']
d    % Difference of each column
     % STACK: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
a    % Any: gives 0 if and only if all elements are 0
     % STACK: 0
     % Implicit display

```

# Answer
> 14 votes
# 05AB1E, ~~6~~ ~~5~~ 2 bytes

```
ιË

```

Input as a list of characters.

-3 bytes by porting @Shaggy's Japt answer, so make sure to upvote him!

Try it online or verify a few more test cases.

**Explanation:**

```
ι   # Uninterleave the (implicit) input-list of characters
    #  i.e. ["t","t","t","t","e","e","s","s","t","t","!","!","!"]
    #   → [["t","t","e","s","t","!","!"],["t","t","e","s","t","!"]]
 Ë  # Check if both inner lists are equal
    #  → 0 (falsey)
    # (after which the result is output implicitly)

```

# Answer
> 11 votes
# Japt, 4 bytes

```
ó r¶

```

Try it

```
ó r¶     :Implicit input of string
ó        :Uniterleave
  r      :Reduce by
   ¶     :  Testing equality

```

## Alternative

```
ó
¥o

```

Try it

# Answer
> 11 votes
# Stax, 5 bytes

```
■◄┼$Δ

```

Run and debug it

**Procedure:**

* Calculate run-lengths.
* Get GCD of array.
* Is even?

# Answer
> 10 votes
# Retina, 9 bytes

```
(.)\1

^$

```

Try it online.

**Explanation:**

Remove all pair of the same characters:

```
(.)\1

```

Check if there are no characters left:

```
^$

```

# Answer
> 8 votes
# Jelly, 3 bytes

```
ŒœE

```

Try it online!

# Answer
> 7 votes
# JavaScript, 28 bytes

```
s=>s.every((x,y)=>x==s[y|1])

```

Try it online!

---

**23 bytes** using wastl's regex

```
s=>/^((.)\2)*$/.test(s)

```

Try it online!

# Answer
> 7 votes
# x86 machine code, ~~9~~ 8 bytes

```
D1 E9       SHR  CX, 1          ; divide length in half
       L1:
AD          LODSW               ; load next two chars into AH/AL
3A E0       CMP  AH, AL         ; compare AH and AL
E1 FB       LOOPE L1            ; if equal, continue loop
C3          RET                 ; return to caller

```

Callable function. Input string in `SI`, input string length in `CX`. Output `ZF` if is double speak.

### Or *14 bytes* as a complete PC DOS executable:

```
B4 01       MOV  AH, 01H        ; DOS read char from STDIN (with echo)
CD 21       INT  21H            ; read first char into AL
92          XCHG DX, AX         ; put first char into DL
B4 08       MOV  AH, 08H        ; DOS read char from STDIN (no echo)
CD 21       INT  21H            ; read second char into AL
3A C2       CMP  AL, DL         ; compare first and second char
74 F3       JE   -13            ; if the same, continue loop
C3          RET                 ; otherwise exit to DOS

```

Input is via `STDIN`, either pipe or interactive. Will echo the "de-doubled" input until a non-doubled character is detected, at which point will exit (maybe bending I/O rules a little bit, but this is just a bonus answer).

Build and test ISDBL2.COM using `xxd -r`:

```
00000000: b401 cd21 92b4 08cd 213a c274 f3c3       ...!....!:.t..

```

### Original *24 bytes* complete PC DOS executable:

```
D1 EE       SHR  SI, 1          ; SI to DOS PSP (080H)
AD          LODSW               ; load string length into AL
D0 E8       SHR  AL, 1          ; divide length in half
8A C8       MOV  CL, AL         ; put string length into BL
        CLOOP:
AD          LODSW               ; load next two chars into AH/AL
3A E0       CMP  AH, AL         ; compare AH and AL
E1 FB       LOOPE CLOOP         ; if equal, continue loop
        DONE:
B8 0E59     MOV  AX, 0E59H      ; BIOS tty function in AH, 'Y' in AL
74 02       JZ   DISP           ; if ZF, result was valid double
B0 4E       MOV  AL, 'N'        ; if not, change output char to N
        DISP:
B4 0E       MOV  AH, 0EH
CD 10       INT  10H
C3          RET                 ; return to DOS

```

Input from command line, output to screen `'Y'` if double, `'N'` if not.

Build and test ISDBL.COM using `xxd -r`:

```
00000000: d1ee add0 e88a c8ad 3ae0 e1fb b859 0e74  ........:....Y.t
00000010: 02b0 4eb4 0ecd 10c3                      ..N.....

```

### Credits:

* **-2 bytes** thx to @ErikF!

# Answer
> 7 votes
# Malbolge (*unlimited memory access variant*), Around 4 megabytes

You asked the golfers, but for the second time forgot about the bowlers.

This is too big to include in the answer for obvious reason so here is gist link.

You might want to use the fast interpreter to test this program, as it's hellishly slow (hellishly, get it?). I'm going to include the TIO.run link after Dennis (hopefully) takes on my issue on TIO tracker.

// Edit: Nope, no TIO link as the answer size limit is 65536 bytes, and no abusing url shorteners because they just refuse to shorten it

# Answer
> 6 votes
# PHP, ~~58~~ 56 bytes

```
function f($s){return!$s?:$s[0]==$s[1]&f(substr($s,2));}

```

Try it online!

As a recursive function.

# PHP, ~~61~~ ~~56~~ 52 bytes

```
while(''<$l=$argn[$i++])$r|=$l!=$argn[$i++];echo!$r;

```

Try it online!

Or standalone program. Input string via `STDIN`, output is `truthy` (`1`) if it is double speak, and `falsey` (`0`) if it is not double speak.

-4 bytes thx to @Night2!

# Answer
> 6 votes
# Haskell, ~~28~~ 23 bytes

```
f(x:y:z)|x==y=f z
f[]=1

```

Try it online!

Very straightforward. Double speak is only empty or a repeated character prepended to double speak.

Less straightforward now. Outputs via presence or absence of an error, per meta consensus; no error means double speak. Pattern matching fails when the first two characters differ or when there are an odd number of characters. Thanks to Laikoni for these savings!

# Answer
> 6 votes
# Lua, ~~67~~ ~~66~~ ~~63~~ ~~59~~ ~~33~~ 32 bytes

-25 bytes thanks to Giuseppe
-1 byte thanks to val

```
print(#(...):gsub("(.)%1","")<1)

```

Try it online!

Removes every doubled character, then checks if the result is empty.

# Answer
> 5 votes
# Perl 5, 15 bytes

```
$_=/^((.)\2)*$/

```

Try it online!

Outputs 1 for double-speak, nothing for non-double-speak.

# Answer
> 5 votes
# MathGolf, 2 bytes

```
½=

```

Try it online!

Basically the same as the 05AB1E answer, `½` splits the string into even and odd characters, then check for equality. Passes for the empty string.

# Answer
> 5 votes
# PowerShell, ~~39~~ 38 bytes

```
!$($args|?{+$p*($p="$_"[$p-eq$_])};$p)

```

Try it online!

where `$p` contains a previous char.

No recursion, no regex :). Takes input as a char-array via a splatting string (see TIO link).

---

# PowerShell, 48 bytes

```
for(;$b-eq$a-and$args){$a,$b,$args=$args}$b-eq$a

```

Try it online!

No recursion, no regex and no pipe :D. It also takes input as a char-array via a splatting string. It uses `$b-eq$a` instead `$a-eq$b` for a case when a last char has #0 code.

# Answer
> 5 votes
# Shakespeare Programming Language, ~~204~~ 156 bytes

-48 bytes thanks to Jo King (mostly by changing the output method)

```
A.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]Ajax:Open mind.Puck:Open
mind.Is I worse zero?If soSpeak thy.Is you as big as I?If soLet usAct I.

```

Try it online!

Exits with error if the input is double speak, and with warning if it is not double speak (which is allowed by default).

# Answer
> 5 votes
# Husk, ~~6~~ 4 bytes

*-2 bytes thanks to Razetime!*

```
ETC2

```

Try it online!

Hooray for all ASCII solutions! Outputs a positive number if the input is doublespeak, otherwise zero.

```
  C2  Cut list into chunks of 2
 T    Transpose
E     Check if list has all the same elements (return length of list if so)

```

# Answer
> 5 votes
# Vyxal, 2 bytes

```
y=

```

Try it Online!

Look ma, no Unicode!

# Answer
> 4 votes
# Julia 1.0, 25 bytes

```
s->s[1:2:end]==s[2:2:end]

```

Try it online!

# Answer
> 4 votes
# V (vim), 7 bytes

```
Óˆ±
ø^$

```

Try it online! or Verify test cases

Hexdump:

```
00000000: d388 b10a d85e 24                        .....^$

```

Just two regexes. Explanation:

```
Ó   " Remove all occurrences...
 ˆ  "   Any character
  ± "   Followed by itself
    "   This regex is actually just the compressed form of (.)\1
ø   " Count the number of matches
 ^$ "   An empty line

```

# Answer
> 4 votes
# , ~~13~~ ~~11~~ 10 bytes

```
-:2#_2{.\]

```

Try it online!

*-2 bytes thanks to Adám*

*-1 byte thanks to miles*

TLDR explanation: Is the input the same as every other character of the input doubled?

# Answer
> 4 votes
# PowerShell, ~~64~~ 59 bytes

```
filter f($n){$a,$b,$r=$n;$a-eq$b-and$(if($r){f $r}else{1})}

```

Try it online!

Recursive function, no regex. Takes input as a `char`-array (see TIO link). Peels off the first two elements into `$a` and `$b`, stores the remaining into `$r`. If we still have elements remaining, recurse along with `$a -eq $b`. Otherwise just check whether `$a -eq $b`. Output is implicit.

*-5 bytes thanks to mazzy*

# Answer
> 4 votes
# Brachylog, 5 bytes

```
ġ₂z₂=

```

Try it online!

Succeeds or fails.

```
ġ₂       The at-most-length-2 chunks of the input,
  z₂     which have equal length, zipped together,
    =    are equal.

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~27~~ ~~26~~ 24 bytes

```
2==GCD@@Length/@Split@#&

```

Try it online!

```
        Length/@Split@#&    (*for the lengths of runs of characters*)
2==GCD@@                    (*check that they are all even*)

```

# Answer
> 4 votes
# INTERCAL, 192 bytes

```
PLEASE,1<-#2DOCOMEFROM(2)DOWRITEIN,1DO.5<-#1$',1SUB#1'~#256PLEASE(1)NEXTDOREADOUT#1DOGIVEUP(1)DO(1002)NEXTDO.5<-#1$',1SUB#2'~,1SUB#2DO(3)NEXTDOREADOUT#0PLEASEGIVEUP(3)DO(1002)NEXT(2)DOFORGET#2

```

Try it online!

Output is done with INTERCAL's native "butchered Roman numerals", so the true output of 1 prints as `\nI\n`, and the false output of 0 prints as `_\n\n`.

I don't feel like writing out a full explanation at the moment, but the ungolfed code is here, I lifted the control flow from something I wrote earlier, and the gist of what it does is read two characters at a time from the input through the usually unhelpful "Turing Tape" I/O until either the first resulting number is 256 (in which case the entire input has been validated and has even length, so it is double-speak), or the second resulting number is not 0 (in which case the second character is different from the first or does not exist, and the input is not double-speak).

I think I might be able to restructure this to cut down on redundancy, but I'm not quite feeling up to that at the moment either.

# Answer
> 4 votes
# Keg, ~~19~~ 17 characters

```
?{!1<|=[|0.(_)]}1

```

Explanation:

```
?             # read input

{             # while
    !1<       # stack length greater than 1?
|             # end of while condition and beginning of while block
    =         # compare the 2 top values in the stack
    [         # if (the condition is the top of stack)
    |         # end of then block and beginning of else block
        0.    # output 0
        (_)   # clear stack (discard top of stack in for loop stack length times)
    ]         # end if
}             # end while

1             # stack is already empty, push a truthy value

              # implicitly output the stack content if there was no explicit output

```

Try it online!

# Answer
> 4 votes
# Curry, 18 bytes

*Tested to work in both PAKCS and KiCS2*

```
f(a:a:x)=f x
f[]=1

```

Try it online!

Test it on smap!

This returns `1` if string is double speak and nothing otherwise.

## Explanation

This is a pretty straight forward translation of the Haskell program:

```
f(a:b:x)|a==b=f x
f[]=1

```

But it uses Curry's more powerful pattern matches to save a bunch of bytes. And while missing a pattern in Haskell is rather difficult to recover from, making this definitely pretty un-idiomatic at best and perhaps a little cheaty. In curry missing patterns just mean it's not a match which is idiomatic and recoverable. So it's shorter and I don't feel like I'm cheating.

## Testing

TIO has a limited ability to test things like this. I recommend you use the smap link to test this. This test handler I've made on smap will not work in KiCS2 or the newer version of PAKCS so you must select `PAKCS 2.2.0` (both `/one-value` and `/all-values` work fine). This is because of the library `Control.SetFunctions` which I use for the test. But the function itself does work in the versions if you want to manually test it.

# Answer
> 4 votes
# Vyxal, 14 bitsv2, 1.75 bytes

```
y=

```

Try it Online!

Basically every other answer

## Explained

```
y=
y   # Uninterleave the input, dumping to stack
 =  # Are the two items equal?

```

# Answer
> 3 votes
# Brain-Flak, ~~26~~, 22 bytes

```
({<({}[{}])>{()<>}{}})

```

Try it online!

Outputs 1 for false and 0 for true.

Readable version:

```
({
    <({}[{}])>
    {
        ()
        <>
    }
    {}
})

```

I originally had this:

```
{
    ({}[{}])

    {
        <>([()])<>{{}}
    }{}
}
<>({}())

```

Which is 10 bytes longer.

# Answer
> 3 votes
# JavaScript, ~~26~~ 23 bytes

```
s=>/^((.)\2)+$/.test(s)

```

Try it online!

## Recursive Solution, 30 bytes

Thanks to Arnauld for a fix at the cost of 0 bytes.

```
f=([x,y,...s])=>x?x==y&f(s):!y

```

Try it online!

# Answer
> 3 votes
# , ~~53~~ 34 bytes

-19 bytes thanks to Giuseppe

```
function(a)gsub("(.)\\1","",a)==""

```

Try it online!

# Answer
> 3 votes
# QuadR, 11 bytes

```
''≡⍵
(.)\1

```

Try it online!

`''≡⍵` the result is an empty string when

`(.)\1` a character followed by itself

is replaced by nothing

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 40 bytes

```
s=>s.Where((c,i)=>c!=$"{s}"[i|1]).Any()

```

Try it online!

Each character is tested against it's neighbor for inequality. If any inequalities exist, the result is false.

Since input is limited to printable ASCII characters, a control character is appended to input which is compared to the last character of an odd length string.

Outputs are reversed.

-3 bytes inspired by @Oliver

# Answer
> 3 votes
# Red, 36 bytes

```
func[s][parse s[any[copy t skip t]]]

```

Try it online!

## Longer alternative:

# Red, 40 bytes

```
func[s][(extract s 2)= extract next s 2]

```

Try it online!

# Answer
> 3 votes
# Prolog (SWI), 60 45 bytes

thanks to Unrelated String

```
+[].
+[A,A|T]:- +T.
-X:-string_chars(X,Y),+Y.

```

Try it online!

Converting it from a string to a list of atoms kind of ruined the score, but well..

# Answer
> 3 votes
# Brain-Flak, ~~36~~ ~~10~~ ~~42~~ 30 bytes

```
(<>)<>{({}[{}]<>){{}{}}{}<>}<>

```

Outputs 0 if it is double speak, and nothing if it isn't

-12 bytes thanks to Nitrodon

# How it works

```
(<>) Pushes 0 to the second stack
<>   Swaps back to the first stack
{    Begins a loop that will run until the stack is empty
({}[{}]<>)    Pops the top two items off of the first stack and pushes their difference to the second stack
{{}{}}{}      If the difference is zero, it gets popped and nothing happens.
If there difference is one, the zero that was put on at the beginning gets popped, so nothing will get outputted at the end
<>   Swaps back to the first stack
}    End loop
<>   Swap to the second stack for output

```

Try it Online!

# Answer
> 3 votes
# Zsh, 36 bytes

> My Zsh answer to the previous challenge can be found here.

Exits truthy (0) if *NOT* double speak, and falsy (1) if double speak. (As allowed in a comment.)

```
for a b (${(s::)1})r+=${a#$b}
[ $r ]

```

---

```
for a b (${(s::)1})r+=${a#$b}
         ${(s::)1}             # split $1 characterwise
for a b (         )            # take pairs of characters from ${(s::)1}, assign to $a and $b
                      ${a   }  # first character
                      ${ #$b}  # remove second character as prefix
                   r+=         # append to $r as string
[ $r ]                         # exit truthy if $r is non-empty

```

Try it online!

# Answer
> 3 votes
# Mathematica, 31 bytes

```
AllTrue[Length/@Split@#,EvenQ]&

```

This works by converting the input (an array of characters, according to @attinat) into a list of characters, splitting this list into sublists of contiguous identical elements, and checking that each sublist has an even number of elements.

# Answer
> 3 votes
# Scala, 44 bytes

```
_.grouped(2).forall(t=>t.size>1&&t(0)==t(1))

```

Try it online!

# Answer
> 3 votes
# Cubix, 18 bytes

```
;U;;A-!/@/n\nW.\O?

```

Try it online! Outputs 1 if True and nothing if False.

I suppose that it is fitting that this is twice the length to my answer to the previous question

```
    ; U
    ; ;
A - ! / @ / n \
n W . \ O ? . .
    . .
    . .

```

Watch it run

* `A` Put all input onto the stack
* `-` subtract the TOS and start of the test loop
* `!` test result for 0
* `@` if not 0, halt (FALSE for double speak)
* `/;U;;` if 0, pop subtraction result and top two items from the stack, u-turn sends it in the right direction.
* `!\n/?` an ignored "if 0", reflect, negate, reflect and test for EOI (now 1)
* `O\/@` if positive (1) output and reflect a couple of times onto the halt (TRUE for double speak)
* `nW` if negative, reverse the negation and shift lane onto the start of the test loop.

# Answer
> 3 votes
# Gaia, 3 bytes

```
2Zy

```

Almost as trivial as the solution to the other challenge. Errors with an input size \< 2, which was never confirmed to be allowed, so might be invalid.

Try it online!

```
2Z   Unzip input by 2
  y  All equal?

```

Unzipping by 2 basically undoes the result of interleaving 2 strings. So if two equal strings are interleaved, then it is doublespeak.

# Answer
> 3 votes
# Pip, 5 bytes

```
$QUWa

```

The existing solution used a longer iterative comparison. Thankfully, the unweave function exists.

Try it online!

# Answer
> 3 votes
# Labyrinth, 13 bytes

```
,:,
" -@
""}!

```

Try it online!

That's a whole lot of no-ops, but I can't find any easy way to remove them.

Prints -1 if the input is a double speak, nothing otherwise. Allowed by this I/O method.

### How it works

```
,:,    Push char input (,), duplicate (:), push another char input
-      Subtract the top two.
       It can be nonzero for two reasons: the string has odd length or
       the last two chars differ.
       In either case, take a turn and exit, producing no output (@)
}      Remove the top number from scope and reveal the first char pushed
       (out of the last two). If it is negative (EOF), turn left,
       print it as number (-1), and exit (@).
"""    Otherwise, turn right and go through the no-op path back to
       the start of the program.

```

# Answer
> 3 votes
# Factor, 28 bytes

```
[ 2 group [ = ] assoc-all? ]

```

Try it online!

* `2 group` Split a sequence every 2 elements, e.g. `{ 1 1 2 2 3 3 } -> { { 1 1 } { 2 2 } { 3 3 } }`
* `[ = ] assoc-all?` Does every pair in a sequence consist of equal values?

---

# Factor, ~~26~~ 24 bytes

```
[ 2 group flip 1 cut = ]

```

Try it online!

*Thanks to @Bubbler!*
*-2 bytes from me*

* `flip` Transpose a matrix. e.g. `{ { 1 1 } { 2 2 } { 3 3 } }` -\> `{ { 1 2 3 } { 1 2 3 } }`
* `1 cut` Split the matrix in two between its first and second rows. If there isn't a second row, outputs `{ }`. e.g. `{ { 1 2 3 } { 1 2 3 } }` -\> `{ { 1 2 3 } } { { 1 2 3 } }`
* `=` Are they equal?

# Answer
> 3 votes
# Desmos, 225 bytes

```
f\left(i\right)=\left\{\operatorname{total}\left(\left[\left\{i\left[a\cdot2+1\right]=i\left[a\cdot2+2\right]\right\}\operatorname{for}a=\left[0...\frac{\operatorname{length}\left(i\right)}{2}-1\right]\right]\right)>0\right\}

```

Input is taken as a list of ASCII character codes, I don't know much about Desmos, so I'd love to know if there's a better way!

Try it online!

# Answer
> 3 votes
# Lexurgy, 22 bytes

Essentially the inverse of my "DDoouubbllee ssppeeaakk!!" answer.

Capture any character twice, and delete it.

If it's double speak, the result is empty string, and a non-empty string otherwise.

```
a:
{[]$1 $1,$$ $$}=>*

```

# Answer
> 3 votes
# Thunno 2, 2 bytes

```
zạ

```

Attempt This Online!

#### Explanation

```
zạ  # Implicit input                -> s
z   # Uninterleave the input        -> [s[0::2], s[1::2]]
 ạ  # Check if they are both equal  -> s[0::2] == s[1::2]
    # Implicit output

```

# Answer
> 3 votes
# Nekomata \+ `-e`, 2 bytes

```
ĭ=

```

Attempt This Online!

```
ĭ       Deinterleave
 =      Check equality

```

Since Nekomata doesn't have the concept of booleans or truthiness, the flag `-e` is required for every challenge.

# Answer
> 3 votes
# Uiua, 11 bytes

```
≅⊃'▽¬▽◿2⇡⧻.

```

Try it!

```
≅⊃'▽¬▽◿2⇡⧻.
          .  # duplicate
         ⧻   # length
        ⇡    # range
      ◿2     # modulo two
 ⊃'▽¬▽       # get the elements at even and odd indices
≅            # do they match?

```

# Answer
> 2 votes
# K (oK), 12 bytes

**Solution:**

```
&/1==/'0N 2#

```

Try it online!

**Explanation:**

```
&/1==/'0N 2# / the solution
       0N 2# / reshape into Nx2 grid
    =/'      / equals (=) over (/) each (')
  1=         / equal to 1 (ie a match)
&/           / take the minimum

```

**Extra:**

* `(~).+0N 2#` works(ish) for 10 bytes, but not if the only difference is a character on the end of one of the strings :(

# Answer
> 2 votes
# PowerShell, ~~27~~ 24 bytes

-3 bytes thanks to mazzy

```
!($args-creplace"(.)\1")

```

Try it online!

Uses the regex method going around. If the string is emptied out, it will return true, otherwise false.

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 63 bytes

```
	I =INPUT
R	I LEN(1) . X
	I X X =	:S(R)
	OUTPUT =IDENT(I) 1
END

```

Try it online!

Matches the first character `LEN(1)` and saves it `.` to `X`. If `I` matches `X` concatenated with itself, it replaces that substring and repeats. If the remaining string is empty, `IDENT(I,<implicit empty string>)`, then `1` is output, else nothing is output.

# Answer
> 2 votes
# Charcoal, 10 bytes

```
⬤⪪Ｓ²⁼ι⮌…ι²

```

Try it online! Link is to verbose version of code. Outputs Charcoal's default boolean format, which is `-` for true and nothing for false. Explanation:

```
  Ｓ         Input string
 ⪪ ²        Split into substrings of length up to 2
⬤           All substrings
        ι   Current substring
       … ²  Extended to length 2
      ⮌     Reversed
    ⁼       Equals
     ι      Current substring
            Implicitly print

```

# Answer
> 2 votes
# Whitespace, 73 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_input_as_character][T   T   T   _Retrieve][S N
S _Duplicate_input][S S S T S T S N
_Push_10][T S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_input_as_character][T   T   T   _Retrieve][T    S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_LOOP][S S S N
_Push_0][T  N
S T _Print_as_integer][N
S S S N
_Create_Label_EXIT]

```

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

Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done.

Outputs `0` for falsey, or nothing for truthy.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Start LOOP:
  Character c = STDIN as character
  If(c == '\n'):
    Stop program
  Character d = STDIN as character
  If(c == d):
    Go to next iteration of LOOP
  Print 0

```

# Answer
> 2 votes
# APL+WIN, ~~20~~ 15 bytes

5 bytes saved thanks to Adam.

Prompts for input of string:

```
n≡(2×2|⍳⍴n)/n←⎕

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 2 votes
# Befunge-98 (PyFunge), 11 bytes

```
~#@~# -_#q1

```

Try it online!

Returns 1 if double speak, 0 if not.

10 byte solution which returns 0 for double speak and non-0 otherwise:

```
~#q~#1-_#q

```

Try it online!

# Answer
> 2 votes
# Python 3, 75 bytes

```
lambda s:all[([s[2*i]==s[2*i+1]for i in range(int(len(s)/2))]),0][len(s)%2]

```

Try it online!

# Answer
> 2 votes
# Stax, ~~6~~ 5 bytes

```
╩3╦x╨

```

Run and debug it at staxlang.xyz!

Outputs integers. Zero for double speak and nonzero (one now!) otherwise, as allowed here. Replace `1I` below with `|e` if you want the opposite behavior, but I think this version looks nicer.

### Unpacked (6 bytes) and explanation

```
:G|g1I
:G        Array of run lengths
  |g      GCD
    1I    Is odd? Could use 2% instead

```

The GCD of run lengths will be even exactly when all run lengths are.

# Answer
> 2 votes
# PHP, ~~37~~ 40 bytes

+3 bytes to fix `'0'` issue

```
<?=''==preg_replace('/(.)\1/','',$argn);

```

Try it online!

Similar to other RegEx answers.

---

# PHP, 55 bytes

```
for(;($l=$argn[$i++])==$argn[$i++]&&$l.$l;);echo$l=='';

```

Try it online!

Loops to the end of the string as long as every even character (0th, 2nd, 4th, etc ...) is equal to the character after it, else stops the loop. Finally, checks if it has arrived at the end of the string, which means the string is a double speak.

---

Outputs 1 for double speak and nothing for not double speak.

# Answer
> 2 votes
# dzaima/APL, ~~14~~ 11 bytes

```
⊢≡⊢⌿⍨2 0⍴⍨≢

```

Try it online!

-3 thanks to Adám!

# Answer
> 2 votes
# Kotlin, ~~56~~ 52 bytes

```
{it.chunked(2).filter{it.toHashSet().size>1}.size<1}

```

Try it online!

Thank you Khuldraeseth na'Barya for saving 4 bytes

# Answer
> 2 votes
# Pip, 31 bytes

```
a:qFb,#a{b%2?x(ab+1)Qa@b?xi:1}i

```

Try it online!

slightly different approach with fold operator, 31 bytes

```
a:qFb,#a{I!b%2i:$Q[a@b(ab+1)]}i

```

outputs 0 if double speak, 1 otherwise

# Answer
> 2 votes
# C (gcc), 50 bytes

Returns `0` if double-speak (or empty string), truthy otherwise.

```
f(s,i)char*s;{for(i=*s;i&(i=*s++)&&i==*s++;);s=i;}

```

Try it online!

If the input string is assumed to always be at least 2 characters (gives incorrect result for single-character strings):

## C (gcc), 38 bytes

```
f(char*s){while(*s&&*s++==*s++);s=*s;}

```

Try it online!

# Answer
> 2 votes
# Java (JDK), 64 bytes

```
s->{int i=s.length;for(;i>1;)i=s[--i]==s[--i]?i:i|1;return i<1;}

```

Try it online!

# Explanations

```
s->{
 int i=s.length;
 for(;i>1;)                 // while the length is 2 or greater.
  i=s[--i]==s[--i]?i:i|1;   // check the 2 previous values. If they're identical, don't do anything. Else, make i odd so that it fails at the return.
 return i<1;                // i will be 0 only when the size is even and all characters were doubled.
}

```

# Answer
> 2 votes
# Perl 6, 14 bytes

```
{!S:g/(.)$0//}

```

Try it online!

Replaces all pairs of identical characters with nothing and then boolean NOTs the result to return true if is an empty string (i.e. all characters were next to an identical one), or false otherwise.

# Answer
> 2 votes
# PHP, ~~51 50~~ 38 bytes

```
echo preg_match("/^((.)\2)+$/",$argn);

```

Checks whether input matches pairs of chars where the chars in each pair are the same (using back ref).

Run like this:

```
echo 'dd00uubbllee' | php -nR 'echo preg_match("/^((.)\\2)+$/",$argn);';echo

```
* -1 byte thanks to @manatwork
* -12 bytes by using preg\_match with back references.

# Answer
> 2 votes
# Pushy, 13 bytes

```
LL2%}2/:=};P#

```

Try it online!

```
L              \ Push len(input)
 L2%           \ Take (len(input) + 1) % 2. This will be 1 only if the input had even length.
    }          \ Move this to the bottom of the stack for later.
     2/:  ;    \ Length of original input, divided by 2, times do:
        =      \    Pop top two characters, and check equality. (Pushes 0 or 1)
         }     \    Move this to the bottom of the stack for later.
           P   \ Push the stack's product. If the input had odd length, or any two characters
               \ did not match, then the stack will contain a 0, so the product will be 0.
               \ Else, it will be 1.
            #  \ Print the product.

```

# Answer
> 2 votes
# naz, 50 bytes

```
2a2x1v1x1f1r3x1v2e2x2v1r3x2v1e0m1o0x1x2f0m1a1o0x1f

```

Works for any input string, provided it's passed as a file terminated with the control character STX (U+0002).

**Explanation** (with 0x commands removed)

```
2a2x1v                       # Set variable 1 equal to 2
1x1f1r3x1v2e                 # Function 1
                             # Read a byte and jump to function 2 if it equals variable 1
            2x2v             # Otherwise, store it in variable 2
                1r3x2v1e     # Read another byte
                             # Jump back to the start of function 1 if it equals variable 2
                        0m1o # Otherwise, output 0
1x2f0m1a1o                   # Function 2
                             # Output 1
1f                           # Call function 1

```

# Answer
> 2 votes
# Burlesque, 8 bytes

```
J2en)J==

```

Try it online!

```
                           [AABBCC]         [ABC]
J   #Duplicate             [AABBCC,AABBCC]  [ABC,ABC]
2en #Every other character [AABBCC,ABC]     [ABC,AC]
)J  #Duplicated            [AABBCC,AABBCC]  [ABC,AACC]
==  #Is the same           [1]              [0]

```

# Burlesque, 11 bytes

```
=[{L[2dv}al

```

Try it online!

```
=[   # Group consecutive like values
{
 L[  # Length of (group)
 2dv # Divisible by 2
}al  # All

```

# Answer
> 2 votes
# Marbelous, 84 bytes

No output for false, output one `\u0000` for true using this standard I/O rule

```
@0@1
0000
]]]]&101
eqal\\&1
@0@1..=0\/
:eqal
@0..@1
}0..}1
--..--
<1&0<1&0
{0@0{1@1

```

interpretor

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

```
z=>/^((.)\2)+$/.test(z)

```

Uses a regular expression that match two of the same characters one or more times

Try it online!

# Answer
> 2 votes
# Risky, 5 bytes

```
0?/20_?:?

```

Try it online!

Doesn't work with the empty string; OP hasn't clarified if that's a problem.

## Explanation

```
0   transpose
?       input
/     split into groups of
2       2
0 reduce
_
?       accumulator
:     =
?       item

```

# Answer
> 2 votes
## PHP4 (45 chars)

Given *$argv\[1\]* as a command line argument :

```
echo preg_match('#^((.)\2)*$#',$argv[1])?1:0;

```

The script will output `0` or `1` to answer.

## PHP7.4 (41 chars)

The **$f** arrow function will return the answer :

```
$f=fn($s)=>preg_match('#^((.)\2)*$#',$s);

```

## C gcc (27 chars)

Function **f** today return an indication of whether or not the input is double speak :

```
f(char*s){1[s]-*s||f(s+2);}

```

Usage :

```
#include <stdio.h>

int main() {
    printf("EXPECT %5s ... %-5s .. aba\n","NO", f("aba")?"NO":"YES");
    printf("EXPECT %5s ... %-5s .. abba\n","NO", f("abba")?"NO":"YES");
    printf("EXPECT %5s ... %-5s .. aabb\n","YES", f("aabb")?"NO":"YES");
    printf("EXPECT %5s ... %-5s .. aaabb\n","NO", f("aaabb")?"NO":"YES");
    printf("EXPECT %5s ... %-5s .. tthhiiss\n","YES", f("tthhiiss")?"NO":"YES");
    printf("EXPECT %5s ... %-5s .. ttthhhiiisss\n","NO", f("ttthhhiiisss")?"NO":"YES");
}

```

Try it Online

**C Variants** :

```
g(char*s){s=*s&&g(s+2)+s[1]-*s;} // 32 chars
h(char*s){return*s&&h(s+2)+s[1]-*s;} // 36 chars

```

# Answer
> 2 votes
# \>\<\> (Fish), 22 bytes

```
l2%?v>l?v1n;
 ;n0<^?=<

```

Try it

# Answer
> 2 votes
## X86\_64/Linux Machine Code, 19-Bytes

Try it online!

**Usage:**

```
$> gcc -Wl,-Tbss=0x80000000 -DIDEAL_BSS -s -static -nostartfiles -nodefaultlibs -nostdlib -Wl,--build-id=none double-speak.S -o double-speak
$> echo -n "<input> | ./double-speak; echo $?

```

Program reads input from stdin (it is sensitive to the exact byte count of input, i.e stray spaces/new lines will change result).

**Returns 0 for double-speak, and non-zero otherwise.**

**Notes:**

* Size is measured in machine code (i.e 19 bytes of PROGBITS; .text, .data, etc...)
* The 19-byte size assumes the above compile command which sets the BSS address at an ideal value. With generic compile commands (no linker inputs), its 21-bytes.

**Program:**

```
/* Uncomment below if BSS was setup at 2^20.  */
/* #define IDEAL_BSS */
    .global _start
    .text
_start:
    /* Incoming registers are zero.  */

    decl    %edx
#ifdef IDEAL_BSS
    btsl    %edx, %esi
#else
    movl    $G_mem, %esi
#endif
    /* eax == 0 == SYS_read.  */
    /* edi == 0 == STDIN.  */
    syscall
    xchgl   %eax, %ecx
loop:
    /* Load next pair.  */
    lodsw
    /* Need to decr by 2 each loop.  */
    decl    %ecx
    /* Check that bytes match.  */
    xorb    %ah, %al
    /* Break if ne or end of count.  */
    loope   loop

    /* edi is zero (clears hi bits of eax). eax is zero if double-
       speak. Otherwise non-zero.  */
    xchgl   %eax, %edi
    /* Exit.  */
    movb    $60, %al
    syscall
    .section .bss
G_mem:  .space(4096 * 8)

```

**Example/Test:**

```
$> for x in aba abba aabb aaabb tthhiiss ttthhhiiisss; do echo -n "${x}" | ./double-speak; echo "${x} -> $?"; done
aba -> 3
abba -> 3
aabb -> 0
aaabb -> 3
tthhiiss -> 0
ttthhhiiisss -> 28

```

# Answer
> 2 votes
# TypeScript's Type System, 86 bytes

```
type F<S>=S extends`${infer C}${infer D}${infer R}`?C extends D?F<R>:0:S extends""?1:0

```

Try it at the TypeScript playground!

This is a generic type `F` taking a string-literal type parameter `S`, and outputting `0` for non-double-speak and `1` for double-speak.

None of the test cases offer a case where all of the pairs are equal but the whole string is of odd length, which tripped me up a bit. This is likely golfable, maybe that last `extends` clause can be dropped with something clever.

Explanation:

```
type F<S> =
  // Match S to extract the first two chars C and D and the rest R
  S extends `${infer C}${infer D}${infer R}`
  // if it matched: is C the same type as D?
  ? C extends D
    ? F<R> // if so, recurse with R
    : 0 // otherwise, it's not double-speak; return 0
  // if it didn't match, we check if the string is empty or has one character.
  : S extends "" ? 1 : 0

```

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

```
f=([a,b,...c])=>a==b&&f(c)

```

Attempt This Online!

Outputs via exit-code. I think this is really nice and clean but that's just my opinion. Unfortunately, this doesn't beat the tried-and-true regex.

Explanation:

* `f=([a,b,...c])=>...`

Makes a function `f` that destructures its string argument into the first character `a`, the second character `b`, and rest of the string `c`.
* `a==b&&f(c)`

Check if `a` is equal to `b`. The `&&` (AND) operator only evaluates its right argument if its left is true, so if it is true we recurse with `c`.

If `a` and `b` aren't equal, then it can't be double speak, so we stop recursion to output with a 0 exit code.

If they're equal, we keep checking the next two until either

+ A) recursion stops because `a` isn't equal to `b`, or
    + B) `a` and `b` are both `undefined` because we've reached the end of the string and there are no more characters left, so we recurse until the recursion depth is hit, giving an exit code of 1.

# Answer
> 1 votes
# Kotlin, ~~59~~ 57 bytes

```
{s->(0..s.length-1 step 2).fold(""){t,c->t+s[c]+s[c]}==s}

```

Try it online!

-1 byte thanks to Khuldraeseth na'Barya

-1 byte changing it -\> s

---

Slightly lazy attempt - basically just took my answer from the doublespeak question, applied it to every second char of the input and see if the result is the input.

# Answer
> 1 votes
# Ruby -n, ~~21~~ 14+1 = 15 bytes

```
p~/^((.)\2)*$/

```

Try it online!

# Answer
> 1 votes
# Lua, ~~90~~ ~~87~~ ~~86~~ 82 bytes

```
a,e=1,os.exit;(...):gsub('.',load's=...a=a~=1 and(a==s and 1 or e(1))or s')e(a==1)

```

Try it online!

Take input as argument, use exit code as output.

## Explanation

This is based on abusing few Lua features:

* `os.exit` could accept either number, allowing short code for exit or boolean, making last check possible (`true` meaning success, `false` meaning failure).
* `gsub` can be also used to iterate over string in callback-style, not only for doing replacement.
* `load` is shorter than `function(...) end`.
* `...` is often shorter than `arg[1]`.

Whole idea hidden behind those tricks:

1. For each character: either remember if nothing is already it or perform check: if current is different from remembered, fail. Otherwise, reset remembered value and continue.
2. When done, make sure that there's nothing pending in the buffer (`e(a==1)`). This is required to fail on strings with odd length.

# Answer
> 1 votes
# Gema, 17 characters

```
?$1=
?=0@end
\Z=1

```

Outputs 1 on double speak and 0 on not.

Sample run:

```
bash-5.0$ echo -n 'TThhiiss  iiss  ddoouubbllee  ssppeeaakk!!' | gema '?$1=;?=0@end;\Z=1'
1

```

Try it online!

## Gema, 12 characters

```
?$1=
?=@fail

```

Terminates with exit code 0 on double speak and 2 on not.

Sample run:

```
bash-5.0$ echo -n 'TThhiiss  iiss  ddoouubbllee  ssppeeaakk!!' | gema '?$1=;?=@fail'
bash-5.0$ echo $?
0

```

Try it online!

# Answer
> 1 votes
# C (tcc), 59 55 50 bytes

```
f(char *s){while(*s==*++s)s++;return!*--s&&s!="";}

```

Try it online!

Thanks to Jo King for the 4 bytes and Unrelated String for saving 5 bytes

Can it be even shorter?

# Answer
> 1 votes
# Kotlin, 46~~49~~ bytes

-3 bytes thanks to `@cubic lettuce`

```
{it.chunked(2).all{it.length>1&&it[0]==it[1]}}

```

Try it online!

```
{it.length%2==0&&it.chunked(2).all{it[0]==it[1]}}

```

Try it online!

# Answer
> 1 votes
# T-SQL 2012, 76 bytes

Looping using the following logic.

> Finding the first match on the first character in the rest of the string.
>
> If the match is on the second position, the first 2 characters are removed.
>
> if the match is on a later position, character 0 to 1 is removed, resulting in null string.
>
> If there are no matches, characters 3-4 are removed. Repeating this will eventually result in a null string.

The final string will be an empty string or a null string.

Empty string is "double speak"(1). Null string is not "double speak"(0).

```
DECLARE @ varchar(max)='ccbbddeeff'

WHILE @>''SET
@=stuff(@,-3/~charindex(left(@,1),@,2),2,'')PRINT
iif(@=0,1,0)

```

**Try it online**

# Answer
> 1 votes
# Rust, 73 bytes

```
|s:&str|!s.chars().enumerate().any(|(i,c)|s.chars().nth(i|1).unwrap()!=c)

```

Try it online!

# Answer
> 1 votes
# C++ (gcc), ~~48~~ ~~47~~ ~~45~~ 43 bytes

*-2 bytes thanks to @ceilingcat*
*-2 bytes thanks to @JoKing*

recursive function assuming zero terminated char table

```
int f(char*s){return!*s||*s==s[1]&&f(s+2);}

```

Try it online!

# Answer
> 1 votes
## EDIT:

This solution is totally broken as demonstrated by the `aabbbb` test case. Thanks to @manatwork for pointing this out. Do not pass Go! Do not collect 200 dollars!

## Bash and Gnu utils, 46 45 bytes

```
fold -1|uniq -c|grep -qv "2 "&&echo 0||echo 1

```

Try it online!

-1 byte by skipping the first space in grep expression

# Answer
> 1 votes
# JavaScript (Node.js), 26 bytes

```
s=>!s.replace(/(.)\1/g,'')

```

Try it online!

# Answer
> 1 votes
# Rust, ~~61~~ ~~58~~ 39 bytes

```
|s:&[u8]|s.chunks(2).all(|n|n[0]==n[1])

```

Try it online!

This is a closure that takes the input as a byte slice (`b` prefix on a string), e.g.

```
println!("{}", f(b"aabb"));

```

# Answer
> 1 votes
# C++ (gcc), 156 145 bytes

```
#include <iostream>
int f(){
    char a[2]; while(std::cin.get(a, 3)) if(a[0] != a[1]) return 0; return 1;
}
int main()
{
    std::cout << f();
}

```

Try it online!

# Answer
> 1 votes
# Oracle SQL, 47 bytes

```
select*from t where regexp_like(x,'^((.)\2)+$')

```

It works with an assumption that input data is stored in a table t(x), e.g.

```
with t(x) as (select 'hheelllloo' from dual)

```

Returns either original string or no rows.

# Answer
> 1 votes
# Swift, 109 bytes

```
func a(b:String){let c=Array(b),l=c.count;var d=0,i=0;while i<l-1{if c[i]==c[i+1]{d+=1};i+=2;};print(d*2==l)}

```

Try it online!

# Answer
> 1 votes
# C#, 190 bytes

```
public class P{public static void Main(string[]a){bool d=true;if(a[0].Length%(double)2>0)d=false;else for(int i=0;i<a[0].Length;i+=2){d=a[0][i]==a[0][i+1]?d:false;}System.Console.Write(d);}}

```

Try Online

# Answer
> 1 votes
# Clojure, 48 bytes

```
(fn[x](every? #(apply = %)(partition 2 2[\0]x)))

```

Try it online!

# Answer
> 1 votes
# GolfScript, 7 bytes

```
2/zip~=

```

Try it online!

# Explanation

2/      # Split input into parts of 2,            e.g. tt,ee,ss,tt
  zip   # Read the list horizontally,         yielding test, test
     ~  # Put the two strings onto the stack, yielding test,test
      = # Check whether they are equal,       yielding 1

# False case:
#  tteesst
#->tt,ee,ss,t
#->test,tes
#->0
```
</code></pre>

# Answer
> 1 votes
# Perl 5 \+ `-pF/^((.)\2)+$/`, 7 bytes

Outputs `0` for falsy and `2` for truthy.

```
$_=@F^1

```

Try it online!

# Answer
> 1 votes
# Rockstar, ~~108~~ ~~97~~ ~~88~~ 69 bytes

```
listen to S
cut S
D's 1
while D and S
let D be roll S's roll S

say D

```

Try it here (Code will need to be pasted in)

```
listen to S       :Read input string into variable S
cut S             :Split into an array
D's 1             :Initialise D as 1
while D and S     :While D is truthy and S is not empty
let D be          :  Reassign to D
  roll S          :    Pop the first element from S
  's              :    Check equality with
  roll S          :    Pop the first element from S
                  :End while loop
say D             :Output D

```

# Answer
> 1 votes
# SM83, 7 bytes

Input in `hl`. Output is in `z` flag. All other flags are off.

```
2A B7 C8 BE 23 28 F9 C9

```

```
isdbl:
 ld a,(hl+)                 // 2A       load first byte and inc
 or a                       // B7       test if zero
 ret z                      // C8       return if at end (with z on)
 xor (hl)                   // BE       test sameness
 inc hl                     // 23       inc again (does not change flags)
 jr z,isdbl                 // 28 F9    loop if same
 ret                        // C9       else return

```

# Answer
> 1 votes
# C++, 69 bytes

a solution which would put myself between this and this.

EDIT: you, people, are soooo clever. I love yall

```
[](string a){int c=0,d=1,k;for(int i:a)k=c++%2?d*=k==i,k:i;return d;}

```

# Answer
> 1 votes
# Pyth, 7 bytes

```
q{Q.-Q{

```

Try it online!

---
Tags: code-golf, string, decision-problem
---


# Question
Title: Compute how many are no larger than each item in an array
Input: an array of length \\$n\\$ containing integers in the range \\$0\\$ to \\$2n\\$.

For each integer \\$x\\$ in the array, compute the number of integers that *occur before \\$x\\$* that are no larger than \\$x\\$.

As an example, if the array is

```
[3, 0, 1, 4, 3, 6]

```

the output should be equivalent to:

```
3: 0
0: 0
1: 1
4: 3
3: 3
6: 5

```

How quickly can you compute this as a function of \\$n\\$?

# Answer
# Python, \\$O(n \frac{\log n}{\log \log n})\\$

Uses the approach from the paper "Optimal Algorithms for List Indexing and Subset Rank".

```
import math

def partial_sums(arr):
    for i in range(1, len(arr)):
        arr[i] += arr[i - 1]
    return [0] + arr

class ShortSum:
    cache = None

    def __init__(self, size):
        self.sz = size
        self.logsz = int(math.log2(size)) + 1
        if ShortSum.cache is None:
            ShortSum.cache = [partial_sums([(v >> (i * self.logsz)) & ((1 << self.logsz) - 1) for i in range(self.sz)])
                              for v in range(1 << (self.sz * self.logsz))]
        self.cnt = 0
        self.b = [0] * size
        self.c = 0

    def prefix(self, v):
        return self.b[v] + ShortSum.cache[self.c][v]

    def inc(self, v):
        self.c += 1 << (v * self.logsz)
        self.cnt += 1
        if self.cnt == self.sz:
            self.cnt = 0
            for i in range(self.sz):
                self.b[i] += ShortSum.cache[self.c][i]
            self.c = 0

class Tree:
    def __init__(self, l, r, branching_factor):
        self.sum = 0
        self.sons = []
        self.sons_sum = ShortSum(branching_factor)
        self.l = l
        self.r = r
        self.branching_factor = branching_factor
        if r - l > 1:
            for i in range(branching_factor):
                sl = l + (r - l) * i // branching_factor
                sr = l + (r - l) * (i + 1) // branching_factor
                self.sons.append(Tree(sl, sr, branching_factor))

    def count(self, ind):
        if self.l == self.r:
            return 0
        if self.l + 1 == self.r:
            return self.sum
        son_ind = ((ind - self.l + 1) * self.branching_factor - 1) // (self.r - self.l)
        return self.sons_sum.prefix(son_ind) + self.sons[son_ind].count(ind)

    def inc(self, ind):
        if self.l == self.r:
            return
        if self.l + 1 == self.r:
            self.sum += 1
            return
        son_ind = ((ind - self.l + 1) * self.branching_factor - 1) // (self.r - self.l)
        self.sons_sum.inc(son_ind)
        self.sons[son_ind].inc(ind)

def counts(L):
    N = len(L)
    logN = int(math.log2(N)) + 1
    sqrtlog = math.isqrt(logN) + 1
    ShortSum.cache = None
    t = Tree(0, 2 * N + 1, sqrtlog)
    ans = []
    for v in L:
        ans.append(t.count(v))
        t.inc(v)
    return ans

```

Attempt This Online!

The complexity of `ShortSum`'s operations is amortized \\$O(1)\\$ \+ a one-time \\$o(n)\\$ for initialization of `cache`.

The cost of `Tree.__init__` is the number of nodes, which is \\$O(n)\\$.

The cost of `Tree.inc` and `Tree.prefix` each is the depth of the tree, which is \\$\log\_{\sqrt{\log{n}}}{\log{n}} = O(\frac{\log{n}}{\log \log n})\\$.

They are run \\$n\\$ times, so the total cost is \\$O(n \frac{\log{n}}{\log \log n})\\$
> 10 votes

# Answer
# Python, \\$O(n \log n)\\$

Simple algorithm based on merge sort that runs in \\$O(n \log n)\\$ for inputs in any range (assuming comparisons are \\$O(1)\\$).

```
def counts_by_value(array: list[int]) -> list[tuple[int, int]]:
    """Returns a list of (index, count) tuples ordered by array[index]."""
    if len(array) == 1:
        return [(0, 0)]

    mid = len(array) // 2
    lcounts = counts_by_value(array[:mid])
    rcounts = counts_by_value(array[mid:])
    lpos = rpos = 0
    counts = []
    while lpos < mid or rpos < len(rcounts):
        if lpos < mid and (
            rpos >= len(rcounts)
            or array[lcounts[lpos][0]] <= array[mid + rcounts[rpos][0]]
        ):
            counts.append(lcounts[lpos])
            lpos += 1
        else:
            counts.append((mid + rcounts[rpos][0], lpos + rcounts[rpos][1]))
            rpos += 1
    return counts

def counts(array: list[int]) -> list[int]:
    """Returns a list of counts ordered by index."""
    return [count for i, count in sorted(counts_by_value(array))]

```

Attempt This Online!
> 5 votes

---
Tags: array, fastest-algorithm
---


title: Print the answer before a given answer

text:
# Question
Title: Print the answer before a given answer
In this challenge, you'll take an answer as input, and print the answer before it. If the answer passed as input is the first answer, print your own submission's source. You'll be passed any answer in the chain up to and including your own answer, but none after it in the chain.

For example, if the first submission is `xyz`, the second is `ABCD`, and you submit `pQrSt` as a third answer, you should support the following input/output pairs:

```
xyz -> pQrSt
ABCD -> xyz
pQrSt -> ABCD

```

The first answer's only possible input is its own source code, in which case it should print its own source (i.e., it can be a cat program).

## Rules

* Inputs and outputs should be treated as bytestrings. While some or most answers may be valid UTF-8, you cannot assume all programs will be representable with Unicode
* If your language doesn't support raw binary I/O, you may use lists of numbers (representing bytes) with some consistent formatting (e.g., newline separated) for I/O in place of binary data
* Answers may be in any programming language
* Answers with a negative score (more downvotes than upvotes) are invalid, and someone else may submit a different answer in their place
* Answers must follow quine rules; no reading your own source code (stringifying functions is allowed here; you just can't read your source code directly from a file or similar) or accessing the internet or other external resouces
* No duplicate answers are allowed (same or different language)
* If a user answers multiple times in a row, only their first answer counts for scoring (so that sandbagging with the first for a low score on the second doesn't work)

## Scoring

Scoring is based on percentage increase in byte count. Whatever answer has the lowest percent increase in byte count over the previous submission wins (this may be negative). You may not golf or otherwise change your answer's code after posting it.

# Answer
# 3: Pip, 103 bytes

```
VST Y`h:[v:"x=>x"w:"\`I?L4≠[4Nȯ,Q".vX:2\"a=b=>(t='\w',b==t?'\v':b>a?'a='+a:t)\""VST Y".RPy]h@D:h@?a`

```

Try it online!

This is a pretty standard Pip quine structure. We store a code string in the variable `y` then evaluate it, and then construct all the pieces of code in an array and return the one at the index before the input.
> 6 votes

# Answer
# 2: JavaScript (Node.js), 74 bytes

```
a=b=>(t='`I?L4≠[4Nȯ,Qx=>x`I?L4≠[4Nȯ,Qx=>x',b==t?'x=>x':b>a?'a='+a:t)

```

Try it online!
> 5 votes

# Answer
# 1: Vyxal `D`, 32 bytes

```
`I?L4≠[4Nȯ,Qx=>x`I?L4≠[4Nȯ,Qx=>x

```

Try it Online!

Returns the nasty ahh string when given `x=>x`.

Returns `x=>x` when given the nasty ahh string.
> 4 votes

# Answer
# 4: Vyxal `D`, 149 bytes

```
`q‛:Ė+»∧⋏≬¥Cİ}ż^₀:⅛°Ṅ.V=j₈@Yʁḃk∩Ŀʁ<Kf]ȧ∪?≥]ċ@Kȯ⇩Ż.ε⅛Ṡ↓√⁽∵0}İ∆3ẋ⟇n↳p°5≬≥U≠0rb½¨hĖ¤¢|c¦ẋQƒ∷ε.¼₅Jǔ(;Ḃ…%ɖbU≠r.₍p∞ėwn2¢ȧH↔$[Ṙ»kQ‛ȯ≠pτn8ȯ7Ẏ(n/ṫj)ṫ/J~ḟ‹i`:Ė

```

Try it Online!

I'm quite proud of this one, and I spent way too long compressing it. The basic idea is to use a port of RegPack to efficiently compress redundancies in previous answers. Also, we're out of quote types and I hate backslashes, so I used a giant compressed integer. For future answers, here's a program to convert from the Vyxal codepage to raw bytes (output as hexadecimal)

```
`q‛:Ė+                              `:Ė # Standard eval quine glue: Uneval the string and add the code to eval it
      »...»                             # Giant compressed integer
                 τ                      # Converted to custom string base
           kQ‛ȯ≠p                       # Printable ascii + "ȯ≠" (to deal with previous Vyxal)
                  n8ȯ7Ẏ                 # "ijklmno"
                       (    )           # For every item of that
                        n/ṫj            # Split on that character, and join all but the last item by the last item (regpack bit)
                             ṫ/         # Split on the remaining trailing semicolon, converting into list
                               J        # Prepend the existing source code
                                ~ḟ      # Find the index of the input in the list
                                  ‹i    # Decrement that, and index back into the list

```
> 4 votes

# Answer
# 0: JavaScript (Node.js), 4 bytes

```
x=>x

```

Just a cat program, to get us started

Try it online!
> 3 votes

---
Tags: code-golf, quine, answer-chaining
---


title: Generate Keyboard Friendly Numbers

text:
# Question
Title: Generate Keyboard Friendly Numbers
Most common computer keyboard layouts have the decimal digit keys

`1``2``3``4``5``6``7``8``9``0`

running along at their top, above the keys for letters.

Let a decimal digit's *neighborhood* be the set of digits from its own digit key and from the digit keys immediately to the left and right, if they exist.

For example, the neighborhood of 0 is `{0, 9}`, and the neighborhood of 5 is `{4, 5, 6}`.

Now, define a ***keyboard friendly number*** as a positive integer (in decimal form with no leading zeros) that can be typed on the layout above such that every consecutive digit in the number after the first digit is in the neighborhood of the preceding digit.

* All single digit numbers (1-9) are trivially keyboard friendly.
* A number such as 22321 is keyboard friendly because every digit (not counting the first) is in the neighborhood of the digit just before.
* A number such as 1245 is **not** keyboard friendly because 4 is not in the neighborhood of 2 (nor vice versa).
* A number such as 109 is **not** keyboard friendly because 0 is not in the neighborhood of 1. The ends do not loop around.

By putting the keyboard friendly numbers in order from smallest to largest, we can create an integer sequence.

Here are the first 200 terms of the keyboard friendly numbers sequence:

```
N KFN(N)
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 11
11 12
12 21
13 22
14 23
15 32
16 33
17 34
18 43
19 44
20 45
21 54
22 55
23 56
24 65
25 66
26 67
27 76
28 77
29 78
30 87
31 88
32 89
33 90
34 98
35 99
36 111
37 112
38 121
39 122
40 123
41 211
42 212
43 221
44 222
45 223
46 232
47 233
48 234
49 321
50 322
51 323
52 332
53 333
54 334
55 343
56 344
57 345
58 432
59 433
60 434
61 443
62 444
63 445
64 454
65 455
66 456
67 543
68 544
69 545
70 554
71 555
72 556
73 565
74 566
75 567
76 654
77 655
78 656
79 665
80 666
81 667
82 676
83 677
84 678
85 765
86 766
87 767
88 776
89 777
90 778
91 787
92 788
93 789
94 876
95 877
96 878
97 887
98 888
99 889
100 890
101 898
102 899
103 900
104 909
105 987
106 988
107 989
108 990
109 998
110 999
111 1111
112 1112
113 1121
114 1122
115 1123
116 1211
117 1212
118 1221
119 1222
120 1223
121 1232
122 1233
123 1234
124 2111
125 2112
126 2121
127 2122
128 2123
129 2211
130 2212
131 2221
132 2222
133 2223
134 2232
135 2233
136 2234
137 2321
138 2322
139 2323
140 2332
141 2333
142 2334
143 2343
144 2344
145 2345
146 3211
147 3212
148 3221
149 3222
150 3223
151 3232
152 3233
153 3234
154 3321
155 3322
156 3323
157 3332
158 3333
159 3334
160 3343
161 3344
162 3345
163 3432
164 3433
165 3434
166 3443
167 3444
168 3445
169 3454
170 3455
171 3456
172 4321
173 4322
174 4323
175 4332
176 4333
177 4334
178 4343
179 4344
180 4345
181 4432
182 4433
183 4434
184 4443
185 4444
186 4445
187 4454
188 4455
189 4456
190 4543
191 4544
192 4545
193 4554
194 4555
195 4556
196 4565
197 4566
198 4567
199 5432
200 5433

```

# Challenge

Write a program or function that takes a positive integer N (via stdin/command line/function arg) and prints (to stdout) or returns the Nth term in the keyboard friendly numbers sequence.

For example, if the input is `191`, the output should be `4544`.

The output may optionally have a single trailing newline.

**The shortest submission in bytes wins.**

# Answer
> 8 votes
# Pyth, ~~27~~ 24 bytes

```
uf!f/h-FY3.:metsd`T2hGQ0

```

Demonstration.

Improvements to the original:

* Using `metd`, instead of `.r ... _UJ`: 2 less bytes. 1 direct, 1 for not having to use J.
* Using `s` and ``T` instead of `JT10`: 1 less byte.

---

We start with the string representation of a number: ``T`.

Then, we convert the string to a list of digits, and rotate the digits digits backwards by one, (9876543210) with `metsd`. Then, we take the 2 element subsequences with `.: ... 2`. These subsequences are filtered on `/h-FY3`. This expression corresponds to `((a-b)+1)/3`, which is zero if and only if the difference between `a` and `b` is at most 1. Thus, the filtered list will be empty if and only if the number is keyboard friendly. With `!`, the result is true only if the number is keyboard friendly.

`f ... hG` filters upwards from `G+1` until the result is true, giving the first keyboard friendly number at `G+1` or above. `u ... Q0` applies this function to its own output `Q` times, starting from 0, where `Q` is the input. This gives the `Q`th Keyboard Friendly Number, as desired.

# Answer
> 4 votes
# Python 3, ~~112~~ 102 bytes

```
f=lambda n,k=0:n+1and f(n-all(-2<~-int(a)%10-~-int(b)%10<2for a,b in zip(str(k),str(k)[1:])),k+1)or~-k

```

We keep track of the count of friendly numbers still needed to find in `n` and the last checked number in `k`.

5 and 5 bytes saved thanks to @isaacg and @Sp3000.

# Answer
> 4 votes
# CJam, ~~29~~ 28 bytes

```
ri_4#{AbAfe|_1>.-W<3,:(-!},=

```

Try it online in the CJam interpreter.

# Answer
> 3 votes
# CJam, ~~34~~ 31 bytes

*3 bytes saved by Dennis.*

I'm sure the gap to Pyth can be closed somehow, but I don't have time right now to golf this further...

```
0q~{{)_s:_2ew{A,s(+f#~m2/},}g}*

```

Test it here.

# Answer
> 3 votes
# JavaScript (ES6), 95

```
F=k=>{for(i=0;k;k-=(f=1,p=NaN,[for(d of''+i)(d=(8-~d)%10,d-p>1|p-d>1?f=0:p=d)],f))++i;return i}

```

**Ungolfed**

```
F=k=>{
  for(i=0; k>0; )
  {
    ++i;
    f = 1; // presume i it's friendly
    p = NaN; // initial value so that first comparison gives false
    for(d of ''+i) // loop for each digit of i
    {
      // rotate digits 1->0, 2->1 ... 9->8, 0->9
      // note d is string, ~~ convert to number (golfed: 8-~d)
      d = (~~d+9) % 10
      if (p-d>1 || p-d<-1)
        f = 0 // not friendly
      else
        // this can go in the 'else', if not friendly I don't care anymore
        p = d // move current digit to prev digit
    }
    k -= f // count if it's friendly, else skip
  }
  return i
}

```

**Test** : execute snippet in Firefox

```
F=k=>{
  for(i=0;k;k-=(f=1,p=NaN,[for(d of''+i)(d=(8-~d)%10,d-p>1|p-d>1?f=0:p=d)],f))++i
  return i
}
```

```
<input id=N><button onclick="R.value=F(N.value)">-></button><input readonly id=R>
```

# Answer
> 3 votes
# Haskell, ~~90~~ 80 bytes

```
([x|x<-[0..],all((<2).abs)$zipWith(-)=<<tail$[mod(1+fromEnum c)10|c<-show x]]!!)

```

This is a function without a name. To use it, call it with a parameter, e.g.:`([x|x<-[0..],all((<2).abs)$zipWith(-)=<<tail$[mod(1+fromEnum c)10|c<-show x]]!!) 199` which returns `5432`.

How it works:

```
[x|x<-[0..]           ]  make a list of all integers x starting with 0
           ,             where
             c<-show x   each character in the string representation of x
  mod(1+fromEnum c)10    turned into the number '(ascii+1) mod 10'
 zipWith(-)=<<tail       then turned into a list of differences between neighbor elements
all((<2).abs)            only contains elements with an absolute value less than 2

                   !!    ... take the element given by the parameter (!! is 0
                         based, that's why I'm starting the initial list with 0)

```

Edit: @Mauris found some bytes to save. Thanks!

# Answer
> 2 votes
## Dart, 92 bytes

```
f(n,[x=0]){t(x)=>x>9?((x+9)%10-((x~/=10)+9)%10).abs()>1||t(x):--n>0;while(t(++x));return x;}

```

With linebreaks:

```
f(n,[x=0]){
  t(x)=>x>9?((x+9)%10-((x~/=10)+9)%10).abs()>1||t(x):--n>0;
  while(t(++x));
  return x;
}

```

See/run it on DartPad

# Answer
> 2 votes
# Vyxal, 83 bitsv2, 10.375 bytes

```
Þ∞'f0₀V¯ȧ2<A;i

```

Try it Online!

## Explanation

```
Þ∞'f0₀V¯ȧ2<A;i
Þ∞              # Natural numbers
  '         ;   # Filtered by:
   f0₀V         # The list of digits where 0 is replaced with 10, ie [9,0] becomes [9,10]
       ¯        # Consecutive differences between digits
        ȧ2<A    # Are the absolute values of those difference all less than 2
             i  # index (from input)

```

Created with the help of Luminespire.

# Answer
> 1 votes
# Batch - 520 Bytes

*Shudder.*

```
@echo off&setLocal enableDelayedExpansion&set a=0&set b=0
:a
set/ab+=1&set l=0&set c=%b%
:b
if defined c set/Al+=1&set "c=%c:~1%"&goto b
set/am=l-2&set f=0&for /l %%a in (0,1,%m%)do (
set x=!b:~%%a,1!&set/an=%%a+1&for %%b in (!n!)do set y=!b:~%%b,1!
set z=0&set/ad=x-1&set/ae=x+1&if !e!==10 set e=0
if !d!==-1 set d=9
if !y!==!d! set z=1
if !y!==!e! set z=1
if !y!==!x! set z=1
if !y!==0 if !x!==1 set z=0
if !y!==1 if !x!==0 set z=0
if !z!==0 set f=1)
if !f!==0 set/aa+=1
if %a% NEQ %1 goto :a
echo %b%

```

# Answer
> 1 votes
# Bash + coreutils, 120 bytes

```
seq $1$1|tr 1-90 0-9|sed 's#.#-&)%B)/3)||(((C+&#g;s/^/(0*((/;s/$/))*0)/'|bc|nl -nln|sed '/1$/d;s/   0//'|sed -n "$1{p;q}"

```

### Some testcases:

```
$ for i in 1 10 11 99 100 200; do ./kfn.sh $i; done
1
11
12
889
890
5433
$

```

# Answer
> 1 votes
# Pyth, 19 bytes

```
e.f.AgL1.aM.+|RTjZT

```

Try it here.

Note: Uses commit newer than this challenge, so shouldn't be considered as an outgolf of isaacg's answer. This is still competing, though.

# Answer
> 0 votes
# JavaScript ES6, 126 bytes

```
f=n=>{b=s=>[...++s+''].every((e,i,a,p=(+a[i-1]+9)%10)=>i?p==(e=+e?e-1:9)|p-e==1|e-p==1:1)?s:b(s)
for(p=0;n--;)p=b(p)
return p}

```

Ungolfed code and tests below. This could certainly be improved more.

```
f=function(n){
  b=function(s){
    return (s+'').split('').every(function(e,i,a){
      e=+e?e-1:9
      p=i?(+a[i-1]+9)%10:e
      return p==e|p-e==1|e-p==1
    })?s:b(s+1)
  }
  for(p=i=0;i<n;i++){
    p=b(p+1)
  }
  return p
}

var input = document.getElementById('n'), results = [];
input.onchange = function(){
  document.getElementById('s').innerHTML = f(input.value)
}
for(var i=0;i<200;i++){
  results.push(i + ': ' + f(i))
}
document.getElementById('r').innerHTML=results.join('<br />')
```

```
N = <input type="number" id="n" min="1" value="191" /><br />
KBD(N) = <samp id="s">4544</samp>
<div id="r"></div>
```

# Answer
> 0 votes
# Cobra - 135

Haven't done this in a while, but here goes:

```
def f(n,i=0)
    while n,if all for x in (s='[i+=1]').length-1get s[x+1]in' 1234567890'[(int.parse(s[x:x+1])+9)%10:][:3],n-=1
    print i

```

Ungolfed:

```
def fn(n as int)
    i = 0
    while n <> 0
        i += 1
        s = i.toString
        l = s.length - 1
        v = true
        for x in l
            k = (int.parse(s[x].toString) + 9) % 10
            if s[x + 1] not in ' 1234567890'[k : k + 3], v = false
        if v, n -= 1
    print i

```

# Answer
> 0 votes
# Jelly, 11 bytes

```
Do⁵IỊẠ
1Ç#Ṫ

```

Try it online!

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

```
f=(n,i)=>n?f(n-![...~i+f].some(e=v=>(e-(e=+v||1+v))**2>1),-~i):i
               ^                            ^
   If exist, don't decrease        1=>1, 0=>10, s=>1s

```

Try it online!

---
Tags: code-golf, number, sequence, number-theory
---