title: Binary Countdown Length

text:
# Question
Title: Binary Countdown Length
*inspired by Count down from infinity*

Given a non-negative integer `N`, output the number of repetitions of the following steps it takes to reach 0:

1. Convert `N` to binary (`4812390 -> 10010010110111001100110`)
2. Flip each bit (`10010010110111001100110 -> 01101101001000110011001`)
3. Trim leading zeroes (`01101101001000110011001 -> 1101101001000110011001`)
4. Convert back to decimal (`1101101001000110011001 -> 3576217`)

## Rules

* Input and output may be in any unambiguous, consistent format
* The input will be within the native representable integer range for your language (if your language supports arbitrarily-large integers, there is no bound)

## Test Cases

```
0 -> 0
1 -> 1
42 -> 6
97 -> 3
170 -> 8
255 -> 1
682 -> 10
8675309 -> 11
4812390 -> 14
178956970 -> 28
2863311530 -> 32

```

---

This sequence is A005811 in the OEIS.

# Answer
> 14 votes
# Jelly, ~~6~~ 4 bytes

```
^HBS

```

Try it online! or verify all test cases.

### Background

Let **n** be a non-negative integer.

Steps 2 and 3 of the process described in the spec can alternatively be stated as removing all leading **1**'s and toggling the remaining bits.

This means that we'll remove exactly one group of adjacent and equal binary digits in each iteration, so the Binary Countdown Length of **n** is just the number of these groups in the binary representation of **n**. For the purposes of this challenge, think of **0** as having no digits.

For **n = 8675309**, the process looks as follows in binary.

```
100001000101111111101101
 11110111010000000010010
     1000101111111101101
      111010000000010010
         101111111101101
          10000000010010
           1111111101101
                   10010
                    1101
                      10
                       1
                       0

```

Instead of counting these groups (which would fail for edge case **0**), we do the following.

**n** and **n:2** have the following binary representations.

```
n   = 8675309 = 100001000101111111101101_2
n:2 = 4337654 =  10000100010111111110110_2

```

Note that **n:2**'s binary representation is simply **n**'s, shifted one bit to the left.

If we XOR **n** and **n:2**, we'll obtain a **1** (MSB), and an additional **1** for each pair of different adjacent digits. The number of groups is thus equal to the number of set bits in **n ⊻ n:2**.

### How it works

```
^HBS  Main link. Argument: n

 H    Halve; yield n:2.
^     XOR n with n:2.
  B   Convert the result to binary.
   S  Compute the sum of the resulting binary digits.

```

# Answer
> 8 votes
# Python 2, 30 bytes

```
lambda n:bin(n^n/2).count('1')

```

Test it on Ideone.

### Background

Let **n** be a non-negative integer.

Steps 2 and 3 of the process described in the spec can alternatively be stated as removing all leading **1**'s and toggling the remaining bits.

This means that we'll remove exactly one group of adjacent and equal binary digits in each iteration, so the Binary Countdown Length of **n** is just the number of these groups in the binary representation of **n**. For the purposes of this challenge, think of **0** as having no digits.

For **n = 8675309**, the process looks as follows in binary.

```
100001000101111111101101
 11110111010000000010010
     1000101111111101101
      111010000000010010
         101111111101101
          10000000010010
           1111111101101
                   10010
                    1101
                      10
                       1
                       0

```

Instead of counting these groups (which would fail for edge case **0**), we do the following.

**n** and **n:2** have the following binary representations.

```
n   = 8675309 = 100001000101111111101101_2
n:2 = 4337654 =  10000100010111111110110_2

```

Note that **n:2**'s binary representation is simply **n**'s, shifted one bit to the left.

If we XOR **n** and **n:2**, we'll obtain a **1** (MSB), and an additional **1** for each pair of different adjacent digits. The number of groups is thus equal to the number of set bits in **n ⊻ n:2**.

# Answer
> 8 votes
## Python 2, 29 bytes

```
f=lambda n:n and-n%4/2+f(n/2)

```

Counts the number of alternations between 0 and 1 in the binary expansion, counting the leading 1 as an alternation. Does so by checking whether the last two binary digits are different, then recursing onto the number with the last digit removed. The last two digits are different exactly if `n%4` is 1 or 2, which can be checked as `-n%4/2`.

# Answer
> 6 votes
# Haskell, 34 bytes

```
b 0=0
b n|x<-b$div n 2=x+mod(x+n)2

```

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

```
f=n=>n&&(n^(n>>=1))%2+f(n)

```

Works by counting the transitions between 0 and 1. Only works up to 31 bits. 29 bytes to support 53 bits:

```
f=n=>1<=n&&(n%2^n/2%2)+f(n/2)

```

# Answer
> 5 votes
# 05AB1E, ~~7~~ 5 bytes

Saved 2 bytes thanks to *Dennis*.

```
b0ÛÔg

```

Without the edge case of *0* this could be 3 bytes `bÔg`.

Try it online! or as a Test suite

**Explanation**

```
b      # convert to binary
 0Û    # trim off leading zeroes
   Ô   # remove adjacent duplicates
    g  # length

```

# Answer
> 3 votes
# CJam, 14 bytes

```
ri0{2b:!2bj)}j

```

Try it online!

```
ri      e# read integer
0       e# value for terminal case
{       e# recursive function
  2b    e#   create binary representation with no leading zeros
  :!    e#   flip bits
  2b    e#   convert binary back to integer
  j     e#   recursive call
  )     e#   increment from 0 on the way up
}j      e# end

```

Basically a knock off of my answer to the other question.

# Answer
> 3 votes
# Java 7,~~112 108 100 90~~ 73 bytes

```
int c(int i){int l=1,j=i;for(;(j=j/2)>0;l*=2);return i<1?0:1+c(2*l-1-i);}

```

### Basic idea

```
 Lets take an no 10110(21)
 then you do set all bits in no 21 and you will get 11111
 and after that you would subtract the original number from 11111.
 You will get 01001 and loop it until you will get 0

```

# Answer
> 3 votes
# J, 14 bytes

```
**1+/@,2~:/\#:

```

Counts the number of runs in the binary digits of *n* with the special case returning 0 for *n* = 0.

## Usage

```
   f =: **1+/@,2~:/\#:
   (,.f"0) 0 1 42 97 170 255 682 8675309 4812390 178956970 2863311530
         0  0
         1  1
        42  6
        97  3
       170  8
       255  1
       682 10
   8675309 11
   4812390 14
 178956970 28
2863311530 32

```

## Explanation

```
**1+/@,2~:/\#:  Input: integer n
            #:  Get the binary digits of n
       2   \    For each overlapping sublist of size 2
        ~:/       Reduce by not-equals
  1   ,         Prepend a 1
   +/@          Reduce by addition
*               Sign(n), returns 0 for n = 0 else 1
 *              Multiply with the previous sum and return

```

# Answer
> 3 votes
# CJam, ~~11~~ 10 bytes

*Thanks to @Dennis for saving one byte!*

```
ri_2be`,e&

```

Try it online!

### Explanation

```
ri            #e Read as integer
              #e STACK: 97
  _           #e Duplicate
              #e STACK: 97, 97
   2b         #e Convert to binary
              #e STACK: 97, [1 1 0 0 0 0 1]
     e`       #e Run-length encoding
              #e STACK: 97, [[2 1] [4 0] [1 1]]
       ,      #e Length
              #e STACK: 97, 3
        e&    #e Return first value if 0, or else the second value
              #e STACK: 3

```

# Answer
> 2 votes
## Racket 349 bytes

```
(define(h s)(apply string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))(define(g s)(let*
((l(string-length s))(k(for/list((i s)(n l)#:final(not(equal? i #\0)))n)))(substring s(last k))))
(define(f n)(if(= 0 n)0(begin(let loop((n n)(c 1))(define m(string->number(string-append "#b"
(g(h(number->string n 2))))))(if(> m 0)(loop m(add1 c))c))))

```

Ungolfed:

```
(define (invertBinary s)
  (apply string
         (map
          (λ(x)(if(eq? x #\0)#\1 #\0))
          (string->list s))))

(define (trimLeading0s s)
  (let* ((l (string-length s))
         (k (for/list ((i s)
                       (n l)
                       #:final (not(equal? i #\0)))
              n)))
    (substring s (last k))))

(define (f n)
  (if (= 0 n) 0
      (begin
        (let loop ((n n)
                   (c 1))
          (define m
            (string->number
             (string-append
              "#b"
              (trimLeading0s
               (invertBinary
                (number->string n 2))))))

          (if (> m 0)
              (loop m (add1 c))
              c)))))

```

Testing:

```
(f 0)
(f 1)
(f 42)
(f 97)
(f 170)
(f 255)
(f 682)
(f 8675309)
(f 4812390)
(f 178956970)
(f 2863311530)

```

Output:

```
0
1
6
3
8
1
10
11
14
28
32

```

# Answer
> 2 votes
# MATL, 7 bytes

```
BY'nwa*

```

Try it online!

### Explanation

```
          % Implicit input, for example 97
          % STACK: 97
B         % Convert to binary
          % STACK: [1 1 0 0 0 0 1]
 Y'       % Run-length encoding
          % STACK: [1 0 1], [2 4 1]
   n      % Number of elements
          % STACK: [1 0 1], 3
    w     % Swap
          % STACK: 3, [1 0 1]
     a    % Any: gives 1 if any element is nonzero
          % STACK: 3, 1
      *   % Multiply
          % STACK: 3
          % Implicit display

```

# Answer
> 2 votes
# Vim, ~~62~~ 59 bytes

-3 bytes thanks to DJMcMayhem

```
C0
<C-r>=pri<Tab>'%b',<C-r>")
<Esc>0qqC<C-r>=tr(@",'01','10')
<Esc>:s/^0\+
k<C-a>j@qq@q

```

Here is the xxd output with the unprintable characters intact:

```
0000000: 4330 0d12 3d70 7269 0927 2562 272c 1222  C0..=pri.'%b',."
0000010: 290d 1b30 7171 4312 3d74 7228 4022 2c27  )..0qqC.=tr(@",'
0000020: 3031 272c 2731 3027 290d 1b3a 732f 5e30  01','10')..:s/^0
0000030: 5c2b 0d6b 016a 4071 7140 71              \+.k.j@qq@q

```

Try it online!

## Explanation

```
C                                   " Delete the number (it goes in @")
0<CR>                               " Print 0 (our counter) and a carriage return
<C-r>=pri<Tab>'%b',<C-r>")<CR><Esc> " Use `printf()` to insert the number as base 2
0qq                                 " Return to column 0, start recording a macro
  C<C-r>=tr(@",'01','10')<CR><Esc>  "   Replace 0s with 1s and vice versa
  :s/^0\+<CR>                       "   Delete leading 0s
  k<C-a>                            "   Increment the number on the line above
  j                                 "   Return to the previous line
  @q                                "   Invoke macro recursively
q@q                                 " Stop recording and invoke macro

```

# Answer
> 2 votes
# Burlesque, 8 bytes

```
rib2gnL[

```

Try it online!

```
ri   # Read as integer
b2   # Convert to binary
gn   # Collapse like bits
L[   # Find length

```

# 29 bytes

```
ri0j{j+.j2dg)n!2ug}{^^nz}w!vv

```

Try it online!

Actually doing the calculation

```
ri       #Read val as int
0j       #Push a 0 (counter) to the bottom of the stack
{
 j+.j    # Increment counter and put back
 2dg     # Get the digits of binary val
 )n!     # Not each digit
 2ug     # Convert back to decimal
}
{^^nz}w! # While not zero
vv       # Drop final zero leaving counter

```

# Answer
> 1 votes
# Ruby, 26 bytes

```
f=->n{n<1?0:-n%4/2+f[n/2]}

```

Inspired by xnor's Python answer.

# Answer
> 1 votes
# Vyxal 3 `s`, 3 bytes

```
½⊻b

```

Try it Online!

port of the jelly answer

# Answer
> 1 votes
# Go, 172 bytes

```
import(."fmt";."strings")
func f(n uint)(i int){for;n>0;i++{Sscanf(Map(func(r rune)rune{if r<'1'{return'1'}else{return'0'}},TrimLeft(Sprintf("%b",n),"0")),"%b",&n)}
return}

```

Attempt This Online!

Implements the algorithm more or less verbatim from the OP.

# Answer
> 0 votes
# PHP, 64 bytes

based on my countdown solution

```
for($n=$argv[1];$n;print 1)$n=bindec(strtr(decbin($n),"01",10));

```

prints `1` character `k` times, where `k` is the number of iterations.

---

+4 bytes for integer output: (empty output for `0`)

```
for($n=$argv[1];$n;$i++)$n=bindec(strtr(decbin($n),"01",10));echo$i;

```

# Answer
> 0 votes
# JavaScript (ES6), 44

Recursive function

Limited to javascript positive integer, 31 bits:

```
f=(a,s=0)=>a?f((-1>>>Math.clz32(a))-a,s+1):s

```

Managing double precision number up to 53 significant bits - **59** bytes:

```
F=(a,s=0)=>a?F('0b'+a.toString(2).replace(/./g,1)-a,s+1):s

```

In another way: using the amazing algorithm by @Dennis, non recursive function managing up 53 bits, **43** bytes:

```
a=>a&&a.toString(2).match(/(.)\1*/g).length

```

# Answer
> 0 votes
# PHP, 51 bytes

```
<?=preg_match_all('/(1+|0+)/',decbin($argv[1])?:o);

```

Uses a regex to count the number of runs of 1 or 0. Unfortunately this needs a special case for input of `0` that requires 3 additional bytes (and gives a notice).

# Answer
> 0 votes
# Java 7, 71 bytes

`int b(Long a){return a==0?0:1+b(~a&-1L>>>64-a.toString(a,2).length());}`

I know this is beaten by Geobits' `split` solution (which will eventually be posted) but this was still fun to write

# Answer
> 0 votes
# Octave, 47 bytes

```
@(x)(sum(dec2bin(bitxor(x,idivide(x,2)))=='1'))

```

According to the OEIS entry, the value we are looking for as the solution to this challenge is *also* equal to the number of `1`s in the Gray code for the given integer.

Wikipedia tells me the Gray code can be calculated as x ^ (x \>\> 1), so in the above function I calculate the Gray code as such, convert it to a binary string, and count how many digits of that string are `1`.

# Answer
> 0 votes
## Java 7, 64 bytes

```
long g(Long n){return n.toString(n,2).split("0+").length*2-n%2;}

```

I know this could be beaten by a port of one of the better answers, but I came up with it in chat, and I can't *not* post it after Poke said something about it :)

# Answer
> 0 votes
# C (gcc), 76 Bytes, 72 Bytes (thanks to celingcat)

```
unsigned n,m,i;f(x){for(i=0;n=x;x^=m-1,i++)for(m=2;n/=2;m+=m);return i;}

```

Try it online!

# Answer
> 0 votes
# Tcl, 119 bytes

```
proc D n i\ 0 {
while \$n {set n [regsub ^0+(?=.) [string map {0 1 1 0} [format %b $n]] ""]
incr i
scan $n %b n}
set i}

```

Try it online!

**Still very ungolfed for my taste**

# Answer
> 0 votes
# Bash, 57 bytes

Packages: Core Utililities, grep, sed, vim (for `xxd`)

Assume the number is given in binary format. Any length is acceptable :)

```
xxd -b -c1|cut -d" " -f2|sed s/^0*//|grep -o .|uniq|wc -l

```

# Answer
> 0 votes
# Perl 5, 31 + 1 (`p`) = 32 bytes

```
$_=(sprintf'%b',$_^$_/2)=~y/1//

```

Try it online!

Using @Dennis's method.

# Answer
> 0 votes
# PHP, ~~55~~ 52 bytes

```
for($i=$argn;$i;$c++,$i^=(1<<log($i,2)+1)-1);echo$c;

```

Try it online!

All done arithmetically/bitwise (no strings). Am stuck getting it smaller than the 51 byte answer though...

# Answer
> 0 votes
# APL, 13 characters/bytes

```
+/2≠/0,2⊥⍣¯1⊢

```

base 10 to base 2 conversion with all necessary digits

```
2⊥⍣¯1⊢

2⊥⍣¯1⊢4812390
---> 1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0

```

add a leading 0

```
0,

0,1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0
---> 0 1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0

```

pair-wise reduction that gives 1 if consecutive elements are not equal

```
2≠/

2≠/0 1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0
---> 1 1 0 1 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 0 1 0 1

```

sum

```
+/

+/1 1 0 1 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 0 1 0 1
---> 14

```

# Answer
> 0 votes
# PHP, 50 bytes

```
<?=array_sum(str_split(decbin($argn&-2^$argn*2)));

```

Try it online!

Unfortunately, really don't think I can get it any more golfed than this!

The idea is to count transitions 1-\>0 or 0-\>1.

# Answer
> 0 votes
# Husk, 6 bytes

```
ΣẊ≠:0ḋ

```

Try it online!

Algorithm from Popov's APL answer.

# Husk, 9 bytes

```
←LU¡ȯḋm¬ḋ

```

Try it online!

The approach shown in the question.

## Explanation

```
←LU¡ȯḋm¬ḋ
   ¡      apply function pinfinitely, collecting results
    ȯ     composition of three function
        ḋ convert to binary digits
      m¬  negate each bit
     ḋ    convert back to base-10
  U       split infinite list at first non-unique value
 L        get the length of the list
←         decrement

```

---
Tags: code-golf, sequence, binary, integer
---


title: Apartment Building

text:
# Question
Title: Apartment Building
Draw an "apartment" building according to the specifications below.

## Basic Rules

Take, as input, the number of floors of the building. Return a building with that many floors meeting the following specifications:

The building will be eight characters wide, with eight underscore characters (`_`) on top and eight dashes (`-`) on the bottom.

The first floor of the building will always look like this: `| || |`.

As long as the building has more than one floor, the top floor will always look like this: `| ---- |`

All floors in between must be randomly selected between the following:

`| - - |`

`| [] |`

`|__ __|`

## Example Outputs:

5 floors:

```
________
| ---- |
|  []  |
| -  - |
|__  __|
|  ||  |
--------

```

2 floors:

```
________
| ---- |
|  ||  |
--------

```

1 floor:

```
________
|  ||  |
--------

```

## Specific rules

Your inputted number of floors will, at minimum, be 1.

You may output as a string, a list of strings, a nested list of characters, or any other output format in which the position of each element is clear.

All floor types must have a nonzero chance of appearing at any given level (other than the bottom and the top), but they do not have to be uniformly randomly chosen.

Code-golf, so shortest code wins.

# Answer
# x86-64 machine code, 68 bytes

```
B8 5F 5F 5F 5F BA 7C 20 2D 2D AB 0F C8 3C 5B 75 02 B0 5D AB B0 0A AA 0F C7 F0 9E B8 7C 20 20 5B 72 0C B8 7C 20 2D 20 74 05 B8 7C 5F 5F 20 92 FF CE 7F D7 B8 7C 20 20 7C 74 D0 6A 08 59 B0 2D F3 AA 88 0F C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the input number in ESI.

In assembly:

```
.global f
f:  mov eax, ('_'*0x01010101)  # For the first line.
    mov edx, ('|' | ' '<<8 | '-'<<16 | '-'<<24) # For the next line.
o:  stosd       # Add EAX to the output string, advancing the pointer.
    bswap eax   # Reverse the order of the bytes of EAX.
    cmp al, '[' # Check if the low byte is '[' ...
    jne sf      # ... and if it is ...
    mov al, ']' # ... change it to ']'.
sf: stosd       # Add EAX to the output string, advancing the pointer.
    mov al, '\n'# Set AL to a line feed.
    stosb       # Add that to the output string, advancing the pointer.
    rdrand eax  # Put a random number in EAX.
    sahf        # Set flags from AH (its second byte).
    mov eax, ('|' | ' '<<8 | ' '<<16 | '['<<24) # One of the possibilities.
    jc d        # Jump if CF=1.
    mov eax, ('|' | ' '<<8 | '-'<<16 | ' '<<24) # Another possibility.
    jz d        # Jump if ZF=1.
    mov eax, ('|' | '_'<<8 | '_'<<16 | ' '<<24) # The third possibility.
d:  xchg eax, edx   # Exchange registers.
    dec esi     # Subtract 1 from ESI, counting down from the input number.
    jg o        # Jump back if the number was >1 before the subtraction.
    mov eax, ('|' | ' '<<8 | ' '<<16 | '|'<<24) # For the lowest floor.
    jz o        # Jump back if the number is 0.
    push 8; pop rcx  # Set RCX to 8.
    mov al, '-' # Set AL to '-'.
    rep stosb   # Add AL to the output string RCX times, advancing the pointer.
    mov [rdi], cl   # Add the low byte of RCX, which is now counted down to 0.
    ret         # Return.

```
> 6 votes

# Answer
# 05AB1E, ~~47~~ ~~46~~ 44 bytes

*-2 thanks to Kevin Cruijssen.*

```
'_4×I≠i"| --"¹ÍF"| - |  [|__ "3äΩ]„| º'-4×»º

```

Try it online!
> 5 votes

# Answer
# Vyxal, 41 bytes

```
‹¨2[`  [ - __ `²℅|ð2-]\|p;‛| m4-½J\_4*pøm

```

Try it Online!

```
‹¨2                      ;                 # Dyadic map (val, index) to...
   [                 ]                     # If the index is truthy (i.e. not first)
    `  [ - __ `²                           # String literal "  [ - __ ", made into a square (chunks of 3)
                ℅                          # Choose one of these
                 |   ]                     # Else... (first)
                  ð2-                      # " --" - Take a space and append two -s
                       \|p                 # Prepend a |
                           ‛| m            # Take "| " and mirror it
                               4-          # Append four -s
                                 ½J        # Split that in half and append
                                   \_4*p   # Prepend "____"
                                        øm # Vertically mirror (flipping []) and join by newlines

```
> 5 votes

# Answer
# Python, ~~102~~ ~~139~~ ~~136~~ ,~~134~~ 117 bytes

```
lambda n:[8*"_","| ---- |",*choices(['| -  - |','|__  __|','|  []  |'],k=n)][:n]+[2*"|  |",8*'-']
from random import*
```

Attempt This Online!

Thanks to @Steffan for pointing out I can't read. Now outputs the correct apartment

-3 bytes thanks to @Steffan
-2 bytes from me
-17 bytes thanks to @loopy walt
> 5 votes

# Answer
## C++, 281 bytes

```
#include<random>
#include<string>
using t=std::string;t a[3]={"| -  - |\n","|  []  |\n","|__  __|\n"};t f(int n){std::random_device g;std::uniform_int_distribution<int>d(0,2);t s("________\n");if(n>1)s+="| ---- |\n";for(int i=2;i<n;++i)s+=a[d(g)];s+="|  ||  |\n--------";return s;}

```

I didn't want to use the standard C `rand` and `srand` functions, so here I go with the standard library of C++.
> 4 votes

# Answer
# Perl 5 `-n`, 110 bytes

```
@a=map{('| -  - |','|  []  |','|__  __|')[rand 3]}1..$_;@a[0,-1]=("| ---- |","|  ||  |");say for'_'x8,@a,'-'x8

```

Try it online!
> 4 votes

# Answer
# Charcoal, 36 bytes

```
×_⁴⸿Ｅ⊖Ｎ⎇ι‽⪪| - |  [|__⁴| --⟦|  |⁴⟧‖Ｍ

```

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

```
×_⁴⸿

```

Output four `_`s and then move to the start of the next line.

```
Ｅ⊖Ｎ⎇ι‽⪪| - |  [|__⁴| --

```

Output `| --` for the top floor, but randomly choose between `| -` , `| [` and `|__` for intermediate floors.

```
⟦|  |⁴⟧

```

Output the left half of the ground floor and the ground.

```
‖Ｍ

```

Reflect to complete the building.
> 4 votes

# Answer
# Excel, ~~143~~ 142 bytes

Anonymous worksheet function that takes input from cell `A1` and output to the calling cell.

```
="________
"&If(A1>1,"| ---- |
","")&Concat(IfError(Choose(RandArray(A1-2,,1,3,1),"| -  - ","|  []  ","|__  __")&"|
",""))&"|  ||  |
--------"

```

## Example Output
> 4 votes

# Answer
# JavaScript, ~~168~~ ~~153~~ ~~151~~ ~~149~~ ~~147~~ ~~146~~ ~~140~~ 136 bytes

-13 thanks to Steffan, -2 by emaneresu A, -2 by myself, -2 by myself, -1 by myself, -6 by tsh, and -4 by me

```
n=>`________${[...Array(n-1)].map((_,i)=>`
|${[` -  - `,`  []  `,`__  __`,` ---- `][Math.random()*3|!i*3]}|`).join``}
|  ||  |
--------`

```

Try it online!
> 3 votes

# Answer
# Java (JDK), 160 bytes

```
f->{var b="________\n|"+(f>1?" ---- |\n|":"");for(var r=3;f-->2;r=3)b+=" -  - ,  []  ,__  __".split(",")[r*=Math.random()]+"|\n|";return b+"  ||  |\n--------";}

```

Try it online!
> 2 votes

# Answer
# Google Sheets, ~~162~~ 159 bytes

```
="________
"&IF(A1>1,"| ---- |
","")&JOIN("",ARRAYFORMULA(IFERROR(CHOOSE(INT(RANDARRAY(A1-2)*3)+1,"| -  - ","|  []  ","|__  __")&"|
","")))&"|  ||  |
--------"

```

*-2 bytes thanks to Taylor Alex Raine*
> 2 votes

# Answer
# C++ (GCC), ~~182~~ ~~177~~ 168 bytes

```
#import<ios>
auto f(int i){std::string s(8,95),t[]{" -  - |","  []  |","__  __|"};if(--i)for(s+="\n| ---- |";--i;)s+="\n|"+t[rand()%3];return s+"\n|  ||  |\n--------";}

```

This requires gcc's `#import` directive. `95 == '_'`, so `std::string(8, 95)` constructs a string of 8 `'_'`.

Attempt This Online!
> 2 votes

# Answer
# C (GCC), ~~213~~ 179 bytes

*-31 bytes thanks to @ceilingcat and @JuanIgnacioDíaz*

*-3 bytes thanks to @c--*

```
p(x,i){for(i=9;i--;x/=8)printf(L"\n| _-[]"+x%8+!!i);}c;main(n){srand(&n);scanf("%d",&n);for(p(4793490);--n;)p(c++?L"\x592c8\x4d848\x91290"[rand()%3]:374472);p(294984);p(7190235);}

```

Attempt This Online!
> 2 votes

# Answer
# Perl 5 \+ `-n -M5.10.0`, 93 bytes

This is based on golfing @Xcali's answer.

```
say for"_"x8,(map{(<"|{ ---- , -  - ,  []  ,__  __}|">)[$_-2&&1+rand 3]}2..$_),"|  |"x2,"-"x8

```

Try it online!

---

# Perl 5 \+ `-n -M5.10.0`, 97 bytes

```
say$_.reverse=~y/[/]/r for'_'x4,(map{(<'|{ --, - ,  [,__ }'>)[$_&&1+rand 3]}0..$_-2),'|  |','-'x4

```

Try it online!

Not smaller, but a reasonably different approach that might have potential for more golfing...
> 2 votes

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

Tied with @code's solution. Used the `!i*3` trick to shorten my own solution. Go vote up their answer because mine would be worse without theirs.

```
n=>['________',...[...Array(n-1)].map((_,i)=>['| -  - |','|  []  |','|__  __|','| ---- |'][Math.random()*3|!i*3]),'|  ||  |','--------']

```

Try it online!
> 2 votes

# Answer
# Python 3, 164 161 bytes

```
from random import*
def b(n):
	yield"_"*8
	if n>1:yield"| ---- |"
	for _ in range(n-2):yield choice(["| -  - |","|  []  |","|__  __|"])
	yield"|  |"*2+'\n'+"-"*8

```

Try it online!

Python generator for the win.

Improvement 1 : Removed unnecessary white-spaces. Thank you @jezza\_99 for the suggestion.
> 1 votes

# Answer
# Factor, ~~139~~ 138 bytes

```
[ dup [ "________", 1 > [ "| ---- |", ] when 2 [-] [ { "|__  __|""| -  - |""|  []  |"} random , ] times "|  ||  |", "--------", ] f make ]

```

Try it online!
> 1 votes

# Answer
# Pip, 63 bytes

```
P'_X8Fi,DaPi?RC" -  -   []  __  __"<>6'-X4WRsWR:'|P"|  |"X2'-X8

```

Attempt This Online!

### Explanation

Roof:

```
P'_X8
P      Print
 '_     Underscore
   X8   Repeated 8 times

```

All floors except ground floor:

```
Fi,DaPi?RC" -  -   []  __  __"<>6'-X4WRsWR:'|
Fi                                             For i in
  ,Da                                          Range(argument decremented):

      i?                                        If i is nonzero (not top floor):
        RC                                       Random choice from
          " -  -   []  __  __"                   This string
                              <>6                Split into sections of size 6
                                                Else (top floor):
                                 '-X4            Four hyphens
                                     WRs         Wrapped in spaces
                                        WR:'|   Wrap the whole string in pipes
     P                                          Print it

```

Ground floor and ground:

```
P"|  |"X2'-X8
P              Print
 "|  |"         That string
       X2       Repeated 2 times
         '-X8  Hyphen repeated 8 times
               Last expression is autoprinted

```
> 1 votes

# Answer
# SWI-Prolog, 177 bytes

```
N+[A|T]:-length([_|X],N),A='________',-X,append(X,['|  ||  |','--------'],T).
-X:-X=['| ---- |'|T],+T;+X.
+X:-X=[A|T],random_member(A,['| -  - |','|  []  |','|__  __|']),+T;1=1.

```

Recursion, recursion, recursion.

Try it online!
> 1 votes

# Answer
# PowerShell, ~~111~~ ~~109~~ ~~102~~ ~~96~~ 93 bytes

```
'_'*8
for($x=' ---- ';--$args[0];$x=' -  - ','  []  ','__  __'|random){"|$x|"}
'|  |'*2
'-'*8

```

Try it online!
> 1 votes

# Answer
# Befunge-93, ~~194~~ 189 bytes

-5 (me) small optimistions

```
&&\52**+052*"________">:#,_$:1`#v_>0"--------"52*"|  ||  |">:#,_@
>:#,_$1-:! #v_02vv"| ---- |"*520<0
^"|__  __|"<    5>:#,_$2-:    #v_^
^"|  []  |"? <* <>#5 #2 #0    #< ^
^"| -  - |"<>    ^

```

Try it online!

Takes a two digit integer from stdin as input. Note that for some reason, in TIO the integers have to be on two lines.
> 1 votes

# Answer
# C (gcc `-w`), 162 bytes

```
*a[]={"| -  - |","|  []  |","|__  __|"};f(n,r){r=rand(srand(&n))%3;puts("________");for(n>1&&puts("| ---- |");n-->2;)puts(a[r++%3]);puts("|  ||  |\n--------");}

```

Test main:

```
int main(void) {
  int i;

  for(i=0; i<100; i++) {
    f(i);
    puts("");
  }
}

```

Technically, it's not genuinely random, but every level type has a chance of appearing at every level. Try it online!
> 0 votes

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


title: Are All the Items the Same?

text:
# Question
Title: Are All the Items the Same?
Given a list of non-negative integers, return whether or not that list is all the same number.

## Rules

* Input and output can be taken/given in any reasonable and convenient format
* Truthy/Falsey values can be represented as any value of your choice as long as it's reasonable and relatively consistent (e.g. `1` for falsey and `>= 2` for truthy is fine)
* There will always be at least 1 item in the input list
* The list items are guaranteed to be in the range `[0, 9]` (\\$0 \le n \le 9\\$)
* Standard loopholes apply

This is code golf, so the shortest program in each language wins. I've made a community wiki answer for trivial answers, so feel free to submit potentially longer programs.

## Test Cases

```
[1, 1, 1, 1, 1, 1, 1] -> True
[1, 2, 3, 4] -> False
[6, 9, 6, 9, 6] -> False
[6] -> True
[7, 7] -> True
[4, 2, 0] -> False

```

# Answer
# Trivial Built-in Answers

This is the post for all of the languages where this is a built-in

## Vyxal, 1 byte

Try it Online!

# Jelly, 1 byte

```
E

```

Try it online!

# 05AB1E (legacy), 1 byte

```
Ë

```

Try it online!

# Wolfram Language (Mathematica), 5 bytes

```
Equal

```

Try it online!

`SameQ` also works.

# Brachylog, 1 byte

```
=

```

Try it online!

# Husk, 1 byte

```
E

```

Try it online!

# Haskell + hgl, 2 bytes

```
lq

```

Try it online!

# Factor, 3 bytes

```
std

```

Try it online!

Outputs `0.0` if they're the same, or something else if not. `all-eq?` and `all-equal?` are longer built-ins that output booleans. `all-equal?` uses `=` (ordinary equality) and `all-eq?` uses `eq?` (strict object reference equality), but they behave the same for integers.

# Thunno, \\$2 \log\_{256}(96) \approx\\$ 1.65 bytes

```
ze

```

Attempt This Online!

# Thunno 2, 1 byte

Attempt This Online!
> 14 votes

# Answer
# , ~~17~~ 15 bytes

```
sd(scan()+!1:2)

```

Try it online!

Outputs `0` for truthy and nonzero for falsey.

Using `sd` is a classic R golfing trick: the standard deviation is `0` if and only if all elements are equal. Unfortunately, `sd` returns `NA` for length one input (since it divides by `n-1`). A neat workaround found by pajonk uses R's recycling: `!1:2` is coerced to a vector `c(0,0)` and is added to the input vector. A length-one input is recycled to be length 2 (so the `sd` is guaranteed to be `0`), and for input of length more than `1`, the zeros are recycled to the length of the longer vector, which won't change the standard deviation.

```
sd(rep(scan(),2))

```

Try it online!
> 10 votes

# Answer
# Haskell, 16 bytes

-12 bytes thanks to Delfad0r.

```
f(a:x)=all(==a)x

```

Try it online!

Another 16 byter:

```
f(a:x)=x==(a<$x)

```

Try it online!
> 10 votes

# Answer
# Python 3, 18 bytes

```
lambda x:len({*x})

```

Try it online!

-5 bytes thanks to @hyper-neutrino

I'm lucky.....
> 9 votes

# Answer
# Vim, 8 bytes

```
:g/<C-r><C-w>/d

```

Try it online!

This uses the assumption that list elements are one character. `Ctrl+R``Ctrl+W` inserts the word under the cursor, so this solution applies the `d`elete command to any line which contains the first element of the list. This results in an empty file if they're all the same, or some non-empty lines if they aren't.

If we weren't allowed to assume that items are in the range `[0,9]` then we could give false positives on numbers which are supersets of each other. We could fix this by using a regex instead for one more byte:

### Vim, 9 bytes

```
:%s/<C-r><C-w>\n

```

Try it online!

Vim doesn't have a concept of truthy/falsey values but if one were to believe that a buffer containing only newlines was falsey, then we could drop the `\n` from this regex to get a 7 byte solution.
> 6 votes

# Answer
# Jelly, 2 bytes

```
IẸ

```

Try it online!

Outputs reversed (`0` if all are equal, `1` if not)

## How it works

```
IẸ - Main link. Takes a list L on the left
I  - Increments of L
 Ẹ - Are any non-zero?

```
> 5 votes

# Answer
# JavaScript (non-trivial), ~~22~~ 21 bytes

*Thanks to @l4m2 for -1*

```
d=>!d.some(x=>x-d[0])

```

Try it online!

This one's different from the `new Set` approach because it returns an actual truthy/falsy value. Although it's not as short (by just 4B, surprisingly), it's what you'd probably use if you needed this in real life, so it's definitely worth having here.

You could make it a byte shorter by removing the `!`, but then it returns `false` if all items are the same and `true` otherwise.
> 5 votes

# Answer
# Excel, 18 bytes

```
=MAX(A:A)=MIN(A:A)

```

Input is in column A. The formula can be input anywhere not in column A.
> 5 votes

# Answer
# Jelly, 2 bytes

```
QL

```

Try it online!

# Husk, 2 bytes

```
Lu

```

Try it online!

# 05AB1E, 2 bytes

```
Ùg

```

Try it online!

# APL(Dyalog Unicode), 2 bytes SBCS

```
≢∪

```

Try it on APLgolf!

Thanks to Bubbler for pointing this out!

---

Outputs 1 for truthy, \\$\>1\\$ for falsey. These all use the same method: counting the number of unique elements.

If the same approach is also this trivial/short in your language, feel free to edit it in if you don't want to post an answer
> 4 votes

# Answer
# Proton, 7 bytes

```
set+len

```

Try it online!

Outputs `1` for truthy and anything else for falsy.
> 4 votes

# Answer
# Ruby, 14 bytes

```
->a{!(a|a)[1]}

```

Try it online!
> 4 votes

# Answer
# Zsh `-o extendedglob`, 8 bytes

```
>$@
<^$1

```

Try it online!

Outputs via exit code; `1` for all the same, `0` for not all the same

* `>$@`: create files according to the input. This de-duplicates elements because a file can only be created once
* `^$1`: find a file that doesn't match the first element of the input (`-o extendedglob` is necessary to enable the `^` feature)
* `<`: and try to read from it. If there is no matching file (because all elements are the same) this will fail and exit with `1`
> 4 votes

# Answer
# Racket, ~~37~~ 18 bytes

```
(λ(x)(apply = x))

```

Try it online!

-19 thanks to Wezl

This takes advantages of the fact that `=` in Racket can take any number of arguments. Note that the tio seems to run an old version that requires at least 2 arguments to `=` and so fails on the singleton list, but this works on my local Racket 8 installation.
> 4 votes

# Answer
# brainfuck, 40 bytes

Works for all characters, not just 0 to 9! (except NUL)

Returns zero for true and non-zero for false.

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

```

Try it online!
> 4 votes

# Answer
# Ruby, 17 bytes

```
f=->a{!a.uniq[1]}

```

Explanation: `a.uniq` is an array with unique elements of a. If all elements are the same, its second element `[1]` will be `nil`, and `!nil` is `true`.

Older answer was more readable:

```
f=->a{a.uniq.size==1}

```
> 4 votes

# Answer
# Pari/GP, 19 bytes

```
v(s)=gcd(s)==lcm(s)

```

Try it online!
> 4 votes

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

```
1=#?:

```

Try it online!

*-2 bytes thanks to ngn*

Returns `1` for true, `0` for false.

Checks if `1` is equal to the length of unique elements in `x`
> 4 votes

# Answer
# Uiua, 4 bytes

```
≅↻1.

```

Try it!

```
≅↻1.
   .  # duplicate
 ↻1   # rotate an array by one
≅     # do they match?

```
> 4 votes

# Answer
# Arn 1.0 `-s`, 2 bytes

```
:@

```

Outputs 1 if all the same, \>1 if they aren't all the same. Try it online (works in older version)

`:@` groups identical values, `-s` takes size. This could be written as `(:@)#` as well, which would be 4 bytes (`«×+0`)
> 3 votes

# Answer
# Branch, 27 bytes

```
1O,[^\,N![o#)]n^=/;^\o^*On]

```

Try it on the online Branch interpreter!

There's got to be a much shorter way to do this...
> 3 votes

# Answer
# Pip, 3 bytes

```
$=g

```

Full program; takes the items from command-line arguments. Try it online!

Alternately, a function solution that takes a list as its argument (also 3 bytes):

```
$=_

```

Try it online!

### Explanation

Not *quite* a builtin.

Pip, like Python, has chaining comparison operators: `1<5>=3` means `1<5 & 5>=3`, and `1=1=1=2` means `1=1 & 1=1 & 1=2`. Unlike Python, Pip also has the meta-operator `$`, which folds a list on a binary operator. For example, `$+` folds a list on addition, returning the sum; and `$=` folds a list on `=`. Because `=` chains, this returns the result we want: 1 if all elements are equal and 0 otherwise. The program `$=g` applies this compound operator to the full arglist `g`.
> 3 votes

# Answer
# C (gcc), ~~35~~ 32 bytes

```
f(int*l){l=~l[1]&&*l-*++l+f(l);}

```

Try it online!

* recursive function taking an array -1 ended
* return False if all elements are equal, True otherwise

```
{l=      - return using eax trick
~l[1]&&  - return False if next item is end and skip next part ending recursion
*l-*++l  - 0 if different
+f(l);}  - plus check next item

```
> 3 votes

# Answer
# Charcoal, 5 bytes

```
⁼⌊θ⌈θ

```

Try it online! Link is to verbose version of code. Takes input as a string of digits by default but you can feed it an array if you insist. Outputs a Charcoal boolean, i.e. `-` for equal, nothing if not. Explanation: Simply compares the minimum and maximum input element.
> 3 votes

# Answer
# Retina 0.8.2, 7 bytes

```
D`.
^.$

```

Try it online! Link includes test cases. Takes input as a string of digits. Explanation:

```
D`.

```

Remove duplicate digits.

```
^.$

```

Check that only one digit is left.
> 3 votes

# Answer
## x86-16 machine code, 6 bytes

Hexdump:

```
0000:0000  89 F7 AC F3 AE C3                                ......

```

## Explanation

```
                                   ; Routine A. [All The Same?]
                                   ; Expects CX = Length of input,
                                   ;         SI = Initial address of list.

0000:0000  89F7        MOV DI, SI  ; A1 [Load]. Set DI to SI.
0000:0002  AC          LODSB       ;            AL = [SI++].
0000:0003  F3AE        REPZ SCASB  ; A2 [Compare].
                                   ;       ZF = 1
                                   ;       Loop CX times:
                                   ;           If AX != [DI]:
                                   ;               ZF = 0
                                   ;               Proceed to A3
                                   ;           DI ++
0000:0105  C3          RET         ; A3 [End]. End of algorithm.
                                   ;           ZF = 0 if not all same.
                                   ;           ZF = 1 if all same. █

```
> 3 votes

# Answer
# Ly, 6 bytes

```
a0I=u;

```

Try it online!

This one works by sorting the list of number and comparing the top and bottom of the stack.

```
a       - sort the stack, implicitly reads the numbers first
 0I     - copy the bottom entry to top of the stack
   =    - compare the top two entries
    u;  - print boolean result, exit to stop from auto printing the stack

```

# jq, 14 bytes

```
unique[1]//"T"

```

Try it online!

This one generates a list of unique numbers, then attempts to print the second member of that list. The `//` operator catches the exception and substitutes `T` if there's only one number.
> 3 votes

# Answer
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
LU

```

If you test input cases, the Fig site demands no spaces, ie. `[x,y,z]` not `[x, y, z]`. Outputs `1` if all equal, else `>1`.

Try it online!

```
LU
 U  : Uniquify with implicit input
L   : Length

```
> 3 votes

# Answer
# dc, 27 characters

```
?[0p3Q]sq[d3R!=qz0<c]dscx1p

```

Sample run:

```
bash-5.1$ dc -e '?[0p3Q]sq[d3R!=qz0<c]dscx1p' <<< '1 1 1 1 1 1 1'
1

bash-5.1$ dc -e '?[0p3Q]sq[d3R!=qz0<c]dscx1p' <<< '6 9 6 9 6'
0

```

Try all test cases online!
(Note that choosing `dc` as interpreter and running the test separately fails both in TIO and ATO. ☹)
> 3 votes

# Answer
# sed, 26 bytes

```
$!{N;/^\(.*\)\n\1$/D;Q1};Q

```

Try it online! \- Takes input as a newline separated list of numbers, exits with a non-zero exit code for "false" (i.e. not a uniform list).

##### Explanation

```
$!{                    }     if not last line, do these
   N;                          append next input line to pattern space
     /^\(.*\)\n\1$/            if pattern space is two identical lines
                   D;            delete first line, and GOTO beginning
                     Q1        quit with exit code 1 (no printing)
                        ;Q   quit with exit code 0 (no printing)

```
> 3 votes

# Answer
# PowerShell, 17 bytes

```
($args|gu).length

```

Try it online!

Outputs 1 for truthy and anything else for falsy.
> 2 votes

# Answer
# V (vim), 10 bytes

```
:sor u
Gd{

```

Try it online!

Input as a list of lines. Outputs a falsy value (Empty output) for all items equal, and outputs a number otherwise.

Gets the unique lines, goes to the last line and deletes till the beginning.
> 2 votes

# Answer
# JavaScript, 21 bytes

```
d=>/^(.)\1*$/.test(d)

```

Try it online!
> 2 votes

# Answer
# Raku, ~~7~~ 6 bytes

~~2\>\*.Set~~

```
+*.Set

```

Try it online!

`*.Set` converts the input list into a set. That set's size is then ~~compared with `2`~~ returned.

*-1 byte thanks to Razetime*
> 2 votes

# Answer
# Red, 25 bytes

```
func[s][single? unique s]

```

Doesn't work in TIO - apparently `single?` has been added in the subsequent versions.

# Using `parse`, 54 bytes

```
func[s][parse s[set t skip(r: reduce['quote t])any r]]

```

Try it online!

Much longer, but a bit more interesting.

## Explanation:

Red's `parse` works not only on strings, but on all types of series (block! paren! string! file! url! path! lit-path! set-path! get-path! vector! hash! binary! tag! email! image!).

```
f: func[s][
    parse s [                   ; parse the input
        set t skip              ; sets `t` to the first item
                                ; a literal integer can't be used as a parse rule
        (r: reduce['quote t])   ; that's why set `r` to `t`'s quoted value
        any r                   ; zero or more `r`
    ]
]

```
> 2 votes

# Answer
# Japt, 3 bytes

Returns `1` for true `>1` for false.

```
â l

```

Try it (includes all test cases)
> 2 votes

# Answer
# Scala, 14 bytes

```
_.toSet.size<2

```

Try it online!
> 2 votes

# Answer
# Julia 1.0, 12 bytes

```
length∘∪

```

Try it online!

* outputs 1 if all numbers are equal, \>1 else
* is for function composition
* is `union`, equivalent to `unique` for a single argument. `Set` would also work for the same number of bytes (but  is nicer)

# Julia 1.8, 8 bytes

```
allequal
```

Attempt This Online! when ATO updates to 1.8

* the boring solution

# Julia 0.6, 3 bytes

```
var

```

Try it online!

* outputs `0` or `NaN` for truthy, anything else for falsy
* for Julia 1.0+, add `using Statistics`
* `std` would work the same way
> 2 votes

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

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

```

Try it online!

Since the input is all single digit numbers, this wants the input without spaces.
> 2 votes

# Answer
# APL (Dyalog Unicode), 5 bytes

```
×/⊢=⊃
×/ ⍝ product reduce
  ⊢=⊃ ⍝ three train, each element equal to first element

```

Try it online!
> 2 votes

# Answer
# Husk, 2 bytes

*And thanks to Razetime for some other 2-byters*

(the 1-byte Husk built-in is `E` (`same`))

```
hg

```

Try it online!

Returns truthy (nonempty list) if all elements are not the same, falsy (empty list) if they're all the same. Collects `g`roups of equal values and returns the `h`ead by discarding the last group.

(Other 2-byters with various truthy/falsy & falsy/truthy return values: ËI, Ë=, #≠, and some 3-byters: ΠẊ=, hk=, hġ=, hü=)
> 2 votes

# Answer
# AWK, 18 bytes

```
1,$0=NF~gsub($1,e)
```

Attempt This Online!

Revisiting my former answer, I realized that if I wanted `$0` to be printed every time, I can use range patterns. In fact, if *begpat* (the left part) is always true, then the range pattern is always true. So I substituted the appending `( )e` technique to the range pattern `1,`, saving one byte.

### AWK, 19 bytes (former answer)

```
$0=(NF~gsub($1,e))e

```

Try it online!

In details:

```
       gsub($1,e)    Searches and substitutes every occurrence of the first number
                     of the input ($1) for a null variable (e). It returns the
                     number of substitutions made.

    NF~              Matches the Number of Fields (i.e., number of items) and the
                     number of substitutions.
                     We expect 1 or 0 as result, but there will be no output when
                     it parses as 0. (AWK skips falsey patterns, and 0 is falsey.)

   (             )e  Appending a null variable converts 1 to "1" and 0 to "0".
                     That's good, because strings are always true.

$0=                  Sets the original input to the resulting "1" or "0".
                     As the pattern is a string, it is printed.

```
> 2 votes

# Answer
# Golfscript, 4 bytes

```
~.&,

```

For the input: a set of numbers should be placed in '\[\]' without commas.

For the output: 1 is a truthy value while integers greater than 1 are falsey.

Try it online!

## Explanation:

I hope this does not count as a 'trivial solution'... :)

```
~    # Evals the input to generate a list.
 .   # Duplicates the list.
  &  # Does setwise AND. Doing AND on two same lists will have the effect of removing duplicate elements.
   , # Returns the length of the remaining list.

```
> 2 votes

# Answer
# Whitespace, 66 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Label_LOOP][S N
S _Duplicate_first_input][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate][N
T   T   S N
_If_neg_Jump_to_Label_DONE][T   S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_LOOP][T N
S T _Print_as_integer][N
N
N
_Exit_program][N
S S S N
_Create_Label_DONE][T   N
S T _Print_as_integer]

```

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

Takes the input-list new-line separated with -1 to indicate we're done with the inputs. Outputs `-1` as truthy, and the first input as falsey (+4 bytes to output `0` instead if this is not allowed).

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

**Explanation in pseudo-code:**

```
Integer firstInput = STDIN as integer
Start LOOP:
  Integer next = STDIN as integer
  If (next == -1):
    Print next as integer to STDOUT
    (Stop program with error: no exit defined)
  If (firstInput == next):
    Go to next iteration of LOOP
  Else:
    Print firstInput as integer to STDOUT
    Stop program

```
> 2 votes

# Answer
# Python, 16 bytes

```
def f(a):b,={*a}
```

Attempt This Online!

Signals by exit code.

# Python NumPy, 16 bytes

```
lambda a:a.ptp()
```

Attempt This Online!

Takes a numpy array and returns 0 for True and 1 or more for False.
> 2 votes

# Answer
# TI-Basic, 5 bytes

```
min(Ans=min(Ans

```

Takes input in `Ans`. Outputs `0` for falsey, and `1` for truthy.
> 2 votes

# Answer
# K (ngn/k), ~~10~~ 3 bytes

```
#?:

```

Try it online!

*Down 7 bytes thanks to Steffan*

Dead simple. `1` for true, and `>1` for false.

Explanation:

```
#?:    Main function. Takes implicit input
  :    Right (apply what's on the left to the right)
 ?     Unique
#      Length

```
> 2 votes

# Answer
# Headass, 13 bytes

```
U{N(+)P:R(U)}

```

Try It Online! \- prints `1` for truthy and nothing for falsy

##### Explanation

```
U{N(+)P:R(U)} full program
U             ready first
 {N(+) :    } while inputs remain
        R(U)    if readied input != next input, terminate program
          U     (while running this conditional, ready next input)
      P       print 1

```
> 2 votes

# Answer
# Labyrinth, 14 bytes

```
:,:
" }
=*$
@!

```

Try it online!

Takes input from stdin without any separators. Prints a negative integer if the items are equal, a positive integer otherwise.

```
:,:    Precondition: top of stack is either 0 (first iteration)
" }                  or the previous char (the rest)
=*$    First iteration: [(implicit 0) | ]
       :,:  dup; getchar; dup  [ 0 0 c c | ]
       }    move data to right [ 0 0 c | c ]
       $*   xor; mul           [ 0 | c ]
       top is 0; go straight
       =    swap tops          [ c | 0 ]
       top is positive; turn right
       "    no-op

       Next iterations: [ c | ]
       :,:  [ c c c2 c2 | ]
       }    [ c c c2 | c2 ]
       $*   [ c*(c^c2) | c2 ]
       top is zero iff c == c2. if so, go straight
         =    [ c2 | ... ]
       otherwise, turn left to exit the loop
         !    print c*(c^c2)
         the value is negative if c2 < 0 (EOF), positive otherwise
         @    halt

```

Since the main conditional looks like

```
if some value is zero, keep running the loop
otherwise exit

```

there has to be a straight path somewhere in the loop, so a loop of size 8 is unavoidable.
> 2 votes

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

```
a=>new Set(a).size

```

Try it online!

Couldn't find the name of the `Set` builtint. Thanks dingledooper :P (outputs using the 1,\>1 method that pretty much everyone is using now)

Previously...

# JavaScript (Node.js), 39 bytes

```
a=>a.map(x=>a[0]==x).reduce((x,y)=>x&y)

```

Try it online!
> 1 votes

# Answer
# Pyth, 2 bytes

```
l{

```

Test suite

Outputs 1 if all elements are equal, and some integer\* greater than 1 otherwise.
* Number of unique elements.
> 1 votes

# Answer
# CSASM v2.4.0.2, 57 bytes

Pops an `~arr:i32` from the stack, then pushes `true` (all elements are the same) or `false` (some elements are different).

```
func a:
dup
len
swap
newset
conv ~arr
len
comp.gt
push $f.o
ret
end

```

**Explanation + Full Program:**

.asm_name AllSame

func main:
    .local i : ~arr:i32,5
    .local j : ~arr:i32,5

    ; Initialize the arrays
    ; i = [ 1, 1, 1, 1, 1 ]
    push i
    push 1
    stelem 0

    push i
    push 1
    stelem 1

    push i
    push 1
    stelem 2

    push i
    push 1
    stelem 3

    push i
    push 1
    stelem 4

    ; j = [ 1, 2, 3, 4, 5 ]
    push [1..5]
    conv ~arr
    pop j

    clf.o

    ; Get the first result
    push i
    call a

    ; Print it
    push "Is 'i' all same? "
    swap
    add
    print.n

    clf.o

    ; Get the second result
    push j
    call a

    ; Print it
    push "Is 'j' all same? "
    swap
    add
    print.n

    ret
end

func a:
    dup
    ; [ array, array ]
    len
    ; [ array, length ]
    swap
    ; [ length, array ]
    newset
    ; [ length, set ]
    conv ~arr
    ; [ length, set elements ]
    len
    ; [ length, element count ]
    comp.gt
    ; If "length" is greater than "element count", then the set had duplicate
    ;   entries which were removed

    ; Push the comparison flag
    push $f.o
    ret
end
```
</code></pre>
> 1 votes

# Answer
# K (oK), 4 bytes

**Solution:**

```
1=#?

```

Try it online!

**Explanation:**

Is the count of the unique items equal to 1?

```
1=#? / the solution
   ? / unique
  #  / count
1=   / equal to 1?

```
> 1 votes

# Answer
# MMIX, 36 bytes (9 instrs)

Takes array of bytes and length as two arguments, C conventions

```
00000000: 83020000 27010101 82ff0001 32ffff02  ³£¡¡'¢¢¢²”¡¢2””£
00000010: 52ff0002 f8000000 5b01fffb e3000001  R”¡£ẏ¡¡¡[¢”»ẉ¡¡¢
00000020: f8010000                             ẏ¢¡¡

```

Disassembly and explanation:

```
alleq   LDBU $2,$0,0        // x = *a
0H      SUBU $1,$1,1
        LDBU $255,$0,$1     // loop: t = a[--l]
        CMPU $255,$255,$2
        PBZ  $255,0F        // iflikely(t == x) goto skp
        POP  0,0            // return 0 (abuses how POP works)
0H      PBNZ $1,0B          // skp: iflikely(l) goto loop
        SETL $0,1
        POP  1,0            // return 1

```
> 1 votes

# Answer
# Mascarpone, 25 bytes

```
,['0.]v*1['1.]v*']<[:,>!]v*' <:' >,<:,>!

```

Try It Online!

This program accepts strings similar to this one:

```
"[2 8 1 6 4]"

```

and prints either '1' or '0' to stdout, with no newline.

### Explanation

```
,['0.]v*1['1.]v*']<[:,>!]v*' <:' >,<:,>!
,['0.]v*1                                    First we take and ignore the first input
                                             character '[', and create an interpreter
                                             for which the default operation is to print
         ['1.]v*']<                          '0'. Next we bind the operation "print '1'"
                                             to the symbol ']' under this interpreter.
                   [:,>!]v*                  Now we push an operation that takes a symbol
                                             from stdin, extracts the operation associated
                                             with that symbol from the interpreter on the
                                             stack, and executes it.
                           ' <               We now bind this operation to the space
                              :' >           character.  Immediately, we extract the
                                             operation back out of the interpreter, and
                                  ,<         bind it to the next symbol from stdin, which
                                             is the first number in the list.  Finally, we
                                    :,>!     manually execute the function once, to begin
                                             the cycle.  Now, the interpreter will continue
                                             to take input until it receives a symbol that
                                             is neither space nor the first number.  The
                                             program will print '1' if that symbol is ']',
                                             otherwise it will print '0'.

```

I wrote a solution in 36 characters, however the input/output format is inconvenient enough that I don't think it qualifies:

```
,[$.]v*1['1.]v*']<[:,$,>!]v*,<:,$,>!

```

It takes strings similar to this:

```
"[2 8 1 6 4 ]"

```

and prints '1' if the items are all equal, and '\[' otherwise.

As Mascarpone is character-set-agnostic (provided the set contains the 17 symbols used by the initial interpreter) and only 26 unique characters are needed for this program to succeed (the 17 original instructions, the space character, and the characters 2-9), we require only 5 bits per character. By this logic, the solutions would be 25 bytes and 22.5 bytes in size, respectively.
> 1 votes

# Answer
# Desmos, 24 bytes

```
f(l)=(l[2...]-l)^2.total

```

Returns `0` for truthy, and a positive number (not `0`) for falsey.

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Python 3, 22 bytes

```
lambda n:len(set(n))<2

```

Try it online!

Set function takes all the unique elements of the group only.
> 1 votes

# Answer
# , 6 bytes

```
1=#&~.
```

Attempt This Online!

Outputs `0` for falsey, and `1` for truth.

## How?

```
1=#&~.
   &    Compose:
  #     The length of
    ~.  The nub (of the input)
1=      Is it equal to one?

```
> 1 votes

# Answer
# Batch, 93 bytes

```
@set i=%1
:l
@if %i:~,1%==%i:~-1% (if %i% gtr 9 (set/ai=%i%/10&goto:l)else echo 1)else echo 0

```

Takes input from the command line as a string of numbers. Outputs `0` for falsey, and `1` for truthy.
> 1 votes

# Answer
# Nim, 28 bytes

```
proc(x:any):any=x.min==x.max

```

Try it online!

```
import sugar
x=>x.min==x.max

```

Try it online!
> 1 votes

# Answer
# J-uby, 15 bytes

Same technique as Sony Santos.

```
:uniq|~:[]&1|:!

```

Attempt This Online!

## Explanation

```
:uniq |     # Get unique elements
~:[] & 1 |  # Get element at index 1 (will be nil if there is only one unique)
:!          # Negate (number becomes false, nil becomes true)

```
> 1 votes

# Answer
# Arturo, ~~19~~ 15 bytes

```
$->a->[]=a--a\0

```

Try it

```
$->a->      ; a function taking an argument a
    []=     ; is the empty block equal to...
    a--a\0  ; the input with the value of its first element removed everywhere?

```
> 1 votes

# Answer
**T-SQL 75 bytes**

`declare @x table (y int) insert @x values`...

`select top 1 1 from @x a where not exists (select*from @x b where b.y!=a.y)`

will return 1 for true, nothing for false
> 1 votes

# Answer
# YASEPL, 45 bytes

```
=a=1'±comma=c®1=d¥0,1`1=e¥a,1}7,d,3!+}2,c`3!<

```

input list as numbers seperated by commas (like `5,16,24,26,29,12,1`)

outputs the list's length if true, outputs the first occurrence of a different number if false
> 1 votes

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


title: Next Greater Number

text:
# Question
Title: Next Greater Number
Given an integer `n`, find the next number that follows the following requirements:

* The next greater number is a number where each digit, from left to right, is greater than or equal to the previous one. For example, `1455`:

`1<4`

`4<5`

`5<=5`
* The next greater number has to be bigger than `n`

# Testcases

```
10 -> 11
19 -> 22
99 -> 111
321 -> 333
1455 -> 1456
11123159995399999 -> 11123333333333333

```

This is , so shortest code wins!

These numbers make up **A009994** \- Numbers with digits in nondecreasing order.

# Answer
> 11 votes
# Brachylog, 3 bytes

```
<.o

```

Try it online! or Try more cases

```
?<.o.   # implicit input (?) and output (.)
?<.     # the input is smaller than the output
  .o.   # the output is itself when ordered

```

# Answer
> 7 votes
# Husk, 6 bytes

```
ḟoΛ≤d→

```

Try it online!

### Explanation

```
ḟoΛ≤d→
ḟ       find the first integer
     →  starting from input incremented
 o      such that composed function
  Λ d   every digit
   ≤    is less that or equal to the previous

```

# Answer
> 6 votes
# Jelly, 7 bytes

```
‘DṢƑ$1#

```

Try it online!

## How it works

```
‘DṢƑ$1# - Main link. Takes n on the left
‘       - Yield n+1
    $1# - Starting from n+1, find the first integer after such that:
 D      -   The digits are
   Ƒ    -   Invariant under
  Ṣ     -   Sorting

```

# Answer
> 6 votes
# Ruby, 35 bytes

```
->x{x.next![x.chars.sort*'']||redo}

```

Try it online!

*-8 thanks to Dingus!*

# Answer
> 6 votes
# , ~~65~~ 58 bytes

Or **\>=4.1, 51 bytes** by replacing the word `function` with a `\`.

*Edit: -7 bytes thanks to @Dominic van Essen.*

```
function(n){while(any(diff((n=n+1)%/%10^(n:0)%%10)<0))0
n}

```

Try it online! Try it on rdrr.io (for larger test-cases)!

Straightforward brute-force:

1. Increment `n`.
2. Split to digits (with leading `0`s that don't matter).
3. Take differences.
4. If any of the differences is `<0`, loop back to 1. Otherwise, stop and output `n`.

# Answer
> 6 votes
# Haskell, ~~52~~ 41 bytes

*9 bytes saved by AZTECCO and 2 bytes saved by xnor*

```
g(a:b)|[a]>b=a<$a:b|1>0=a:g b
g.show.(+1)

```

Try it online!

Solves all the cases nearly instantly.

# Explanation

The first thing to observe is that:

> Find the smallest ascending digit number *greater* than \\$n\\$.

Is significantly harder than:

> Find the smallest ascending digit number *greater or equal to* than \\$n\\$.

The former has a lot of edge cases around numbers that are themselves ascending in digits while the latter can be solved fairly easily.

But we can turn the latter to the former by just adding 1 before we run our algorithm. If `g` is the function that solves it then we just have `g.show.(+1)` to solve the actual problem.

So I solve the latter first:

```
g(a:b)|[a]>b=a<$a:b|1>0=a:g b

```

This goes along the list until either we meet a pair of digits that is descending (e.g. `21`) or we reach the end. At that point we replace everything left with the digit we just read and exit.

So for example

```
122334555612990
         ^^
122334555666666

```

---

Here's what the solution looks like without this observation just handling the edge cases naively:

### 92 bytes

```
x!q@(a:b:c)|a>b=a<$q|1>0=(x++[a])!(b:c)
x!"9"=""!x++"1"
x!""="1"
x!y=x++show(1+read y)
f=(""!)

```

Try it online!

# Answer
> 5 votes
# Vyxal, 6 bytes

```
{›Ds≠|

```

Try it Online!

```
{      # While...
 ›     # Increment
  D    # Make three copies
   s≠  # Check if sorted
     | # Do nothing

```

# Answer
> 5 votes
# Perl 5 -p, 26 bytes

```
1while++$_-join'',sort/./g

```

Try it online!

The last test case would take about 194 hours (which is 8 days where I live). So I removed the last five digits from the test case to get the result in 7 sec. For "instant" result, also for the last big test case, this is a 78 byte suggestion: `$_++;s/(@{[join"|",map$_."[0-".($_-1)."]",1..9]}).*/substr($1,0,1)x length$&/e` ...try it online!

# Answer
> 4 votes
# C (gcc), 48 bytes

```
i;f(n){for(i=++n;n=n%10<n/10%10?++i:n/10;);i=i;}

```

Try it online!

# Answer
> 4 votes
# Julia 1.0, ~~34~~ 31 bytes

```
~x=issorted("$(x+=1)") ? x : ~x

```

Try it online!

# Answer
> 3 votes
# C (gcc), ~~59~~ 48 bytes

```
f(n,t){t=++n?t=f(n/10-1),10*t+t%10:0;n=t>n?t:n;}

```

Try it online!

```
f(n,t){
  t=++n             // increment input
    ? t=f(n/10-1),  // recurse on prefix
      10*t+t%10     //   and append its last digit
    : 0;            // (base case =0)
  n=t>n?t:n;        // max of above and input
}

```

# Answer
> 3 votes
# Python 3, 84

```
f=lambda n:n+1if all(int(i)<=int(j)for i,j in zip(str(n+1),str(n+1)[1:]))else f(n+1)

```

Fails on the last case due to exceeding the maximum recursion depth.

# Answer
> 3 votes
# Python 2, 49 bytes

```
f=lambda n:-~n*(list(`-n`)<sorted(`~n`))or f(-~n)
```

Attempt This Online!

Brute force: increments the given number until it is great. Unsurprisingly, chokes on the larger test case.

#### Python, 77 bytes

```
f=lambda n,t=1:(n:=n+t)*([*str(n)]<=sorted(str(n)))or 10*(g:=f(n//10,0))+g%10
```

Attempt This Online!

This constructs the result directly. Handles all test cases.

# Answer
> 3 votes
# PowerShell, 48 bytes

Very simply iterates through numbers starting from the input until a number equals the sorted string representation of itself, then returns that number.

```
param($n)for(;++$n-ne-join("$n"|% T*y|sort)){}$n

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 67 bytes

```
T`9d`d`.9*$
^0
10
.
$*_¶
+`((_+¶)(?!_*\2)(_*¶)*)_*¶$
$2$1
(_+)¶
$.1

```

Try it online! Link includes test cases. Explanation:

```
T`9d`d`.9*$

```

Increment the input.

```
^0
10

```

Deal with any carry.

```
.
$*_¶

```

Convert each digit to unary.

```
+`((_+¶)(?!_*\2)(_*¶)*)_*¶$
$2$1

```

Propagate the first digit greater than its successor to the end of the number. E.g. `11123159995400000`, `11123315999540000`, `11123331599954000`, ... `1123333333333331`, `1123333333333333`.

```
(_+)¶
$.1

```

Convert the digits back to decimal.

# Answer
> 2 votes
# Charcoal, 25 bytes

```
≔Ｉ⊕Ｎθ…θ⌕Ｅθ›ι§θ⊕κ¹×⁻Ｌθⅈ§θⅈ

```

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

```
≔Ｉ⊕Ｎθ

```

Input `n`, increment it, and turn it into a string.

```
…θ⌕Ｅθ›ι§θ⊕κ¹

```

Print the prefix up to the first digit that is greater than its subsequent digit. (There is an edge case here when all the digits are equal but the remaining code will just fill with that digit because it has no other choice.)

```
×⁻Ｌθⅈ§θⅈ

```

Fill the rest of the string with that digit.

# Answer
> 2 votes
# Japt, 8 bytes

```
È-ìn}fUÄ

```

Try it

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
[>Ð{Q#

```

Try it online or verify almost all test cases (except for the last one, which is shortened a bit).

**Explanation:**

```
[       # Loop indefinitely:
 >      #  Increase the current value by 1
        #  (which will be the implicit input in the first iteration)
  Ð     #  Triplicate it
   {    #  Sort the digits in the top copy
    Q   #  Pop it and another copy and check if they're still the same
     #  #  If it is: stop the infinite loop
        # (after which the remaining third value is output implicitly as result)

```

---

Here a different approach which also handles the largest test case (**14 bytes**):

```
>Dü›Å¡ćJs˜¬s∍«

```

Try it online or verify all test cases.

**Explanation:**

```
               #  E.g. input = 11123159995399999
>              # Increase the (implicit) input-integer by 1
               #  STACK: 11123159995400000
 D             # Duplicate it
               #  STACK: 11123159995400000,11123159995400000
  ü            # For each overlapping pair of digits:
   ›           #  Check if the first is larger than the second
               #   STACK: 11123159995400000,[0,0,0,0,1,0,0,0,0,1,1,1,0,0,0,0]
    Å¡         # Split the (implicit) input-integer at the truthy positions
               #   STACK: [[1,1,1,2],[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]]
      ć        # Extract head; pop and push first list and remainder-lists
               # separated to the stack
               #  STACK: [[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]],[1,1,1,2]
       J       # Join this first list together to a single integer
               #  STACK: [[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]],1112
        s      # Swap to get the remainder-list
               #  STACK: 1112,[[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]]
         ˜     # Flatten it
               #  STACK: 1112,[3,1,5,9,9,9,5,4,0,0,0,0,0]
          ¬    # Push its first digit (without popping the list)
               #  STACK: 1112,[3,1,5,9,9,9,5,4,0,0,0,0,0],3
           s   # Swap so the list is at the top
               #  STACK: 1112,3,[3,1,5,9,9,9,5,4,0,0,0,0,0]
            ∍  # Extend this digit to the length of this list
               #  STACK: 1112,3333333333333
             « # Append the two strings together
               #  STACK: 11123333333333333
               # (after which the result is output implicitly)

```

# Answer
> 2 votes
# MathGolf, 7 bytes

```
)∙▒sy=▼

```

Port of my 05AB1E answer.

Try it online.

**Explanation:**

```
      ▼ # Do-while false with pop:
)       #  Increase the current integer by 1
        #  (which will be the implicit input in the first iteration)
 ∙      #  Triplicate it
  ▒     #  Convert the top copy to a list of digits
   s    #  Sort those digits
    y   #  Join it back together to an integer
     =  #  Check if the sorted integer is still the same as the triplicated integer
        # (after the do-while loop, output the entire stack implicitly as result)

```

# Answer
> 2 votes
# Desmos, ~~159~~ ~~155~~ 149 bytes

The code below supports all integers, with negative integers supported as described in Jonathan Allan's comment.

```
o->T(o+1-sign(o-c)min(1-sign(L-sort(L))^2)),c->T(c)
i=0
o=0
c=0
s=sign(o)
a=abs(o)
L=smod(floor(a/10^{[floor(log(a+1-ss))...0]}),10)
T(n)=\{i=c:n,i\}

```

Try It On Desmos!

Try It On Desmos! - Prettified

This uses a variable `c` to cache the input so that changes in the input can be detected (with the function `T(n)`), causing the rest of the program to react accordingly (That is why the program won't break if the input is changed while the ticker is still running).

The byte count can actually be lowered significantly if some liberties (A.K.A. removing the caching variable) can be taken with the I/O method:

### ~~127~~ ~~123~~ 117 bytes, with modified I/O method

```
o->o+1-sign(o-i)min(1-sign(L-sort(L))^2)
i=0
o=0
s=sign(o)
a=abs(o)
L=smod(floor(a/10^{[floor(log(a+1-ss))...0]}),10)

```

Try It On Desmos!

Try It On Desmos! - Prettified

This version removes the caching variable `c` and the function `T(n)` completely, which means that the code cannot detect any changes in the input. This means that extra steps have to be taken in order to enter in or change the input and run the code.

I'm not too sure which I/O method is considered the "accepted" version, so I'm putting both.

Also, it's unclear whether or not we have to support negative integers. If we only have to support non-negative integers or positive integers, the code can be shortened even more (the code below uses the caching variable):

### ~~140~~ 134 bytes, supports all non-negative integers

```
o->T(o+1-sign(o-c)min(1-sign(L-sort(L))^2)),c->T(c)
i=0
o=0
c=0
L=mod(floor(o/10^{[floor(log(a+1-sign(o)))...0]}),10)
T(n)=\{i=c:n,i\}

```

Try It On Desmos!

Try It On Desmos! - Prettified

### ~~128~~ 122 bytes, supports positive integers

```
o->T(o+1-sign(o-c)min(1-sign(L-sort(L))^2))),c->T(c)
i=1
o=1
c=0
L=mod(floor(o/10^{[floor(logo)...0]}),10)
T(n)=\{i=c:n,i\}

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
**APL 16~~12 16~~ bytes**

~~New Approch~~

~~`10⊥⌈/\⍎¨⍕1∘+`
~~

~~It's just a append scan and then maximum of each cell~~  doesnt work in case idetified by @ova

`1∘+⍣{∧/2≤/⍎¨⍕⍺}`

Explanation

`1∘+` adds 1

`{∧/2≤/⍎¨⍕⍺}` checks weather each number is bigger than the one preceding it

`1∘+⍣{∧/2≤/⍎¨⍕⍺}` continously adds 1 untill the previous function returns true i.e. A fixed point function

# Answer
> 2 votes
# Pip, 8 bytes

```
T$<=Ua_a

```

Attempt This Online!

### Explanation

```
          ; a is command-line argument
T         ; Loop till
    Ua    ;   Increment a, and
 $        ;   Fold on
  <=      ;   Less-than-or-equal
          ; is true:
      _   ;   No-op
       a  ; After the loop, autoprint the modified value of a

```

Folding a number such as `1455` on `<=` is the equivalent of computing `1 <= 4 <= 5 <= 5`, which (thanks to Pip's chaining comparison operators) is equivalent to `(1 <= 4) & (4 <= 5) & (5 <= 5)`.

---

Here's a **19-byte** version that can handle the largest test case:

```
O@Ua{y?ya>b?Yab}MPa

```

Attempt This Online!

```
O@Ua{y?ya>b?Yab}MPa
  Ua                 ; Increment a
 @                   ; Get its first digit
O                    ; Output it without a newline
    {          }MPa  ; Map this function to each pair of adjacent digits in a:
     y?              ;   Has y been assigned yet?
       y             ;   If so, use that as the next digit
        a>b?         ;   Otherwise, is the first digit of the pair greater than
                     ;   the second digit of the pair?
            Ya       ;   If so, assign the first digit to y and use that
              b      ;   Otherwise, use the second digit

```

# Answer
> 2 votes
# tinylisp, 95 bytes

```
(load library
(d F(q((N)(i(e N(from-base 10(merge-sort(to-base 10 N))))N(G N
(d G(q((N)(F(a N 1

```

Try it online!

-3 from dlosc

`merge-sort` is shorter than `insertion-sort`. Surprisingly there's no plain sort alias. Since variable assignment is global, i've resorted to using `(+ n 1)` everywhere.

# Answer
> 2 votes
# Factor \+ `math.unicode`, 49 bytes

```
[ [ 1 + dup present [ <= ] monotonic? ¬ ] loop ]

```

Try it online!

Add 1. If the string representation of the number isn't sorted, repeat.

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

```
a->until(vecsort(d=digits(a))==d,a++);a

```

Try it online!

# Answer
> 1 votes
# APL+WIN, 48 bytes

Prompts for integer

```
n←⍴v←⍎¨⍕⎕+1⋄10⊥⌽((n-⍴v)⍴¯1↑v),⌽v←(^\0≤1,-2-/v)/v

```

Try it online! Thanks to Dyalog Classic

The final example throws an error in the final digit in Dyalog Classic on TIO. Dropping the last digit of that example gives the expected result.

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

```
f=n=>(p=[...++n+''])+''>p.sort()?f(n):n

```

Try it online!

Fixed tsh's answer

# Answer
> 1 votes
# Ly, 14 bytes

```
1[p`sSaJlf=!]p

```

Try it online!

This is a pretty straightforward iterative take on the question. It splits the number into digits, sorts them, collapses back to a number, and compare that to the original. The loop ends when the digits are sorted.

```
1              - push a '1' to start the loop
 [p         ]  - loop until the top of the stack is '0'
   `           - increment the current var (first time reads STDIN)
    s          - save number to backup cell
     S         - split the number into digits
      a        - sort the stack
       J       - recombine the digits into a number
        l      - pull the number from the backup cell
         f     - flip the top two entries of the stack
          =    - compare the original and sorted digits
           !   - negate result of comparison
             p - delete iterator var, leaves the answer on the stack

```

# Answer
> 1 votes
# Perl 5 `-p`, 38 bytes

```
$_++;s/./$t||($&<$`%10?$t=$`%10:$&)/ge

```

Try it online!

It's a little longer than @KjetilS' answer, but it has the advantage of being nearly "instant" for any number. Its runtime is based on the length of the number rather than the value. For really big numbers, `-Mbigint` should be added to the command line flags.

# Answer
> 0 votes
# Raku, 27 bytes

```
{first {[<=] .comb},$_^..*}

```

Try it online!

* `$_ ^.. *` is the infinite sequence of numbers starting with, but not including (thanks to the `^`), the input number `$_`.
* `first { ... }, ...` returns the first number in that sequence for which the brace-delimited anonymous function returns a true value.
* `.comb` splits the input number into its individual digits.
* `[<=]` reduces the digits with the `<=` operator. It's equivalent to `digit₁ <= digit₂ <= ... <= digitₙ`.

# Answer
> 0 votes
# Prolog (SWI), 42 bytes

```
N+O:-nth0(O,_,_),O>N,name(O,A),msort(A,A).

```

Try it online!

# Answer
> 0 votes
# YASEPL, 66 bytes

```
=a'(+`1=1)aſ""=h®1=d`2!c¥d,1!f$d+!g¥f,1}2,c,5!d+}2,h,2|6`5!+|`6>a

```

## explanation:

```
=a'(+`1=1)aſ""=h®1=d`2!c¥d,1!f$d+!g¥f,1}2,c,5!d+}2,h,2|6`5!+|`6>a     packed
=a'(                                                                  get user input and set it to "a", making it an integer
    +                                                                 add one to variable a
     `1                                                     |         loop forever...
       =1)aſ""                                                        set variable "1" to string version of variable a
              =h®1                                                    get length of variable "1" and set it to variable h
                  =d                                                  declare variable d / set it to 0
                    `2                          }2,h,2                while d < h...
                      !c¥d,1                                          get item from variable "1" index d and set it to variable c
                            !f$d+                                     set variable f to be d + 1
                                 !g¥f,1                               get item from variable "1" index f and set it to variable g
                                       }2,c,5           `5            if g > c...
                                             !d+                      add one to d.
                                                          !+          ...else, add one to a and loop back
                                                      |6     `6>a     print a and exit if loop completed sucessfully (found next greater number)

```

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