# Question
Title: Make a minimal and maximal 2-digit number from digits of two 3-digit numbers
Let's solve this user's homework; I think it's an interesting exercise!

### Input

Two 3-digit natural numbers.

### Outputs

Two 2-digit numbers. In each of the output numbers, one digit is taken from one input number, and the other from the other number. The choice is independent. The first output number should be the minimal possible to create using these constraints, and the second one should be the maximal such number (or vice versa).

* Input numbers never have leading zeros; output numbers should also not have leading zeros.
* Input and output can be encoded as numbers, strings, lists of digits, etc.

---

Examples (in format `input` \- `output`):

```
123, 912 - 11, 93
888, 906 - 68, 98
100, 100 - 10, 11
222, 222 - 22, 22
123, 222 - 12, 32
798, 132 - 17, 93

```

# Answer
> 10 votes
# Husk, ~~15 14 13~~ 9 bytes

```
§,▼▲f←ṁP*

```

Try it online!

Takes two input arrays, outputs pair `(min,max)`.

-1 byte from Dominic Van Essen.

-1 more byte from Dominic Van Essen (after some more struggling).

-4 bytes taking arrays of digits as input.

## Explanation

```
§,▼▲f←ṁP*
        * cartesian product pairs of the inputs
      ṁP  map each to permuations, and flatten the list
    f←    remove elements where first digit is falsy(<10)
§,        create pair with
  ▼▲      minimum and maximum

```

# Answer
> 8 votes
# 05AB1E, ~~11~~ 10 bytes

```
â€Â9ÝKWsà‚

```

-1 byte thanks to *@ovs*.

Try it online or verify a few more test cases.

**Explanation:**

```
â           # Take the cartesian product of the digits of the two (implicit) inputs
 €Â         # Bifurcate each value within the list (short for Duplicate & Reverse copy)
   9Ý       # Push the list [0,1,2,3,4,5,6,7,8,9]
     K      # Remove those integers (so all integers with leading 0s)
      W     # Take the minimum of this list (without popping the list itself)
       s    # Swap so the list is at the top of the stack again
        à   # Pop and push its maximum
         ‚  # And pair the minimum and maximum together
            # (after which it is output implicitly as result)

```

# Answer
> 6 votes
# Brachylog, 15 bytes

```
{∋ᵐpcℕ₁₀}ᶠ⟨⌋≡⌉⟩

```

Try it online!

```
{∋ᵐpcℕ₁₀}ᶠ⟨⌋≡⌉⟩
{       }ᶠ      find all possible outputs:
 ∋ᵐ               select a digit from each number
   p              permute them
    c             merge them to a number
     ℕ₁₀          that number is >= 10
                with the list of all possible numbers:
          ⟨⌋≡⌉⟩ [minimum, maximum]

```

First time using `⟨⟩`! :-⟩

# Answer
> 6 votes
# Jelly, 11 10 bytes

```
p;p@ḷ/ƇṢ.ị

```

Try it online!

Dyadic link. Input and output is a list of digits.

## Explanation

```
p;p@ḷ/ƇṢ.ị
p            Cartesian product
 ;           Join with
   @         Reverse arguments
  p            Cartesian product
      Ƈ      Filter by
     /         Reduce by
    ḷ            First argument
       Ṣ     Sort
        .ị   First and last element

```

*-1 byte by using the `.ị` technique to get the first and last element, thanks to caird*

# Answer
> 5 votes
# Python 3, 81 bytes

```
lambda a,b:[m(k for i in a for j in b for k in(i+j,j+i)if'1'<k)for m in(min,max)]

```

Try it online!

# Answer
> 5 votes
# Haskell, 62 bytes

```
a!b=(`foldl1`[s|i<-a,j<-b,s<-[[i,j],[j,i]],s>"1"])<$>[min,max]

```

Try it online!

This is the same approach as Jitse's Python answer.

# Answer
> 5 votes
# C (gcc), ~~233~~ \\$\cdots\\$ ~~189~~ 185

Saved 4 bytes thanks to gastropner!!!
Saved ~~9~~ 13 bytes thanks to ceilingcat!!!

```
#define d(a,i)for(qsort(a,i=3,1,L"\xf06be0f\xd02917beǃ");a[--i]<49;);
s;j;i;f(a,b)char*a,*b;{d(a,i)d(b,j)s=a[2];i=a[i]<b[j]?s=b[2],a[i]:b[j];j=*a;*b++=j>*b?j=*b,*a:*b;*a++=i;*a=s;*b=j;}

```

Try it online!

Inputs two \\$3\\$-digit strings and returns the min and the max as \\$2\\$-digit substrings in the first \\$2\\$ digits of the first and second input string respectively.

# Answer
> 4 votes
# Jelly, ~~12~~ 11 bytes

```
p;U$Ḍ>Ƈ9Ṣ.ị

```

Try it online!

Input as a list of digits (which the Footer does for you)

-1 byte thanks to Unrelated String

## How it works

```
p;U$Ḍ>Ƈ9Ṣ.ị - Main link. Takes x on the left and y on the right
p           - Cartesian product of the digits. Call this list X
   $        - Group the previous two commands into a monad f(X):
  U         -   Reverse each pair in X
 ;          -   And append it to X
    Ḍ       - Convert each pair back to an integer
      Ƈ     - Keep those which:
     >      -   Are greater than:
       9    -   9
        Ṣ   - Sort
         .ị - Take the first and last elements

```

# Answer
> 4 votes
# Retina, 38 bytes

```
Lw$`(.).*,.*(.)
$1$2¶$2$1
A`0.
O`
,,G`

```

Try it online! Link includes test cases. Explanation:

```
Lw$`(.).*,.*(.)
$1$2¶$2$1

```

Take the cartesian product of the inputs and their reverses.

```
A`0.

```

Remove entries with leading zeros.

```
O`

```

Sort.

```
,,G`

```

Take the first and last result.

# Answer
> 4 votes
# JavaScript (ES6), 80 bytes

Expects a pair of 3-digit strings. Returns a pair of 2-digit integers.

```
a=>[(g=n=>(a+[,a]).match(~~(n/10)+'\\d*,\\d*'+n%10)?n:g(n+d%7-2))(d=10),g(d=99)]

```

Try it online!

### How?

We use `a+[,a]` to concatenate `a[]` with itself, with a comma in between. For instance, `['123', '912']` is turned into `'123,912,123,912'`. (We only need the first 3 entries, but the 4th one is harmless.)

We use the recursive function `g` to look for some 2-digit integer `n` such that the above string matches `~~(n/10)+'\\d*,\\d*'+n%10`. That is to say:

* \\$\lfloor n/10\rfloor\\$ (the 'left' digit of \\$n\\$)
* followed by some optional digits
* followed by a comma
* followed by some other optional digits
* followed by \\$n\bmod 10\\$ (the 'right' digit of \\$n\\$)

We add \\$(d\bmod 7)-2\\$ to \\$n\\$ between each recursive call, where \\$d\\$ is also the starting point:

* \\$d=10\rightarrow (d\bmod7)-2=1\\$, so we go from \\$n=10\\$ to \\$n=99\\$ (looking for the lowest valid integer)
* \\$d=99\rightarrow (d\bmod7)-2=-1\\$, so we go from \\$n=99\\$ to \\$n=10\\$ (looking for the highest valid integer)

# Answer
> 4 votes
# Python 2, 70 bytes

```
lambda*l:[m(m(set(l[i])-{'0'})+m(l[~i])for i in(0,1))for m in min,max]

```

Try it online!

**Python 3, 70 bytes**

```
lambda a,b:[m(m({*a}-{'0'})+m(b),m({*b}-{'0'})+m(a))for m in(min,max)]

```

Try it online!

These could be shorter if we can take a list of digits as numbers.

# Answer
> 4 votes
# Desmos, ~~9+68+147+30+49+64+27+27+8+8+51=488~~ 9+68+93+30+49+28+9+9+8+8+33+31+27=402 bytes

Before you even go on I just want to say that I tried my hardest to golf this, but in the middle of doing this I already knew this was far from a competing answer. But by that time though, I was too far in, so I decided to continue. Upvote for effort? Or not.

## Expression 1: 9 bytes

```
g=[0,1,2]

```

## Expression 2: 68 bytes

```
f(n)=\operatorname{floor}(\frac{\operatorname{mod}(n,10^g10)}{10^g})

```

## Expression 3: ~~147~~ 93 bytes

```
h(a,b)=\left\{s[1]p[1]=0:j(\min(s[k(s)+1],p[k(p)+1]),q(s)+q(p)),d(j(\min(s),\min(p)))\right\}

```

## Expression 4: 30 bytes

```
q(a)=\left\{k(a)=0:a,0\right\}

```

## Expression 5: 49 bytes

```
k(a)=\operatorname{total}(\left\{a=0:1,0\right\})

```

## Expression 6: ~~64~~ 28 bytes

```
l(a,b)=d(j(\max(s),\max(p)))

```

## Expression 7: ~~27~~ 9 bytes

```
s=d(f(a))

```

## Expression 8: ~~27~~ 9 bytes

```
p=d(f(b))

```

## Expression 9: 8 bytes

```
w=h(a,b)

```

## Expression 10: 8 bytes

```
z=l(a,b)

```

## Expression 11: ~~51~~ 33 bytes

```
m(a,b)=j(10w[1]+w[2],10z[2]+z[1])

```

## Expression 12: 31 bytes

```
j(a,b)=\operatorname{join}(a,b)

```

## Expression 13: 27 bytes

```
d(a)=\operatorname{sort}(a)

```

Try It On Desmos

The function \\$m(a,b)\\$ is the function where you need to input the two numbers in.

Prettified version: Try It On Desmos!

# Answer
> 3 votes
# Ruby, ~~77~~ ~~74~~ ~~70~~ 53 bytes

-17 bytes thanks to Dingus!!

```
->x,y{((x-[0]).product(y)+(y-[0]).product(x)).minmax}

```

Try it online!

# Answer
> 3 votes
# CJam, 19 bytes

```
q~m*_Wf%+:iA,-$(\W=

```

Try it online!

Takes input as two strings and outputs two integers.

```
q~                    e# Push inputs                      "888" "906"
  m*                  e# Cartesian product                ["89" "80" "86" "89" "80" "86" "89" "80" "86"]
    _Wf%              e# Make a reversed copy             ["89" "80" "86" "89" "80" "86" "89" "80" "86"] ["98" "08" "68" "98" "08" "68" "98" "08" "68"]
        +:i           e# Join and parse to integers       [89 80 86 89 80 86 89 80 86 98 8 68 98 8 68 98 8 68]
           A,-        e# Remove the numbers from 0 to 9   [89 80 86 89 80 86 89 80 86 98 68 98 68 98 68]
              $       e# Sort                             [68 68 68 80 80 80 86 86 86 89 89 89 98 98 98]
               (\     e# Uncon from left                  68 [68 68 80 80 80 86 86 86 89 89 89 98 98 98]
                 W=   e# Get the last element             68 98

```

# Answer
> 3 votes
# MathGolf, ~~33~~ 32 bytes

```
─■myG‼<≥xα─6ö6‼≥<3≥\;]─gÅ£(_╓\╙α

```

Input as a paired list of digits.

Sometimes this language is so frustrating to work with.. :/ It has a cartesian builtin, but it only works on single lists (creating pairs of itself). It also has a convenient  builtin to apply two commands separately to the stack, but this isn't implemented (yet?) for the minimum/maximum builtins (otherwise the `_╓\╙α` could have been `‼╓╙α`)..

Try it online.

**Explanation:**

```
─           # Flatten the list of list of digits
 ■          # Take the cartesian product of this flattened list
  m         # Map over each pair:
   y        #  And join them together to a single integer
            # (note: since we're joining integers, the `m` implicitly converts them to
            # integers as well, removing potential leading 0s)
    G       # Push 12
     ‼      # Apply the following two commands separated on the stack:
      <     #  Slice to only keep the first 12 items in the list
       ≥    #  Slice to remove the first 12 items from the list and keep the remainder
        x   # Reverse the second list
         α─ # Merge the lists together again (wrap in a pair; flatten)
6ö          # Loop 6 times, using the following 7 commands as body:
  6         #  Push 6
   ‼        #  Apply the following two commands separated on the stack:
    ≥       #   Slice to remove the first 6 items from the list and keep the remainder
     <      #   Slice to only keep the first 6 items in the list
      3≥    #  Slice to remove the first 3 items of this sextet
        \   #  Swap the top two lists on the stack so the remainder is at the top
  ;         # After the loop: discard the top of the stack (the final remainder)
   ]        # Wrap all triplets into a list
    ─       # And flatten it

```

We now have all possible pairs (including their reversed pairs).

```
g           # Filter this list of pairs by,
 Å          # using the following 2 commands as body:
  £         #  Get the length of this integer
   (        #  Decrease it by 1
            #  (so 0 for single digit numbers; 1 for intended two-digit numbers)
    _       # Duplicate this list of pairs
     ╓      # Pop and get its minimum
      \     # Swap so the duplicated list is at the top
       ╙    # Pop and get its maximum
        α   # And pair them together
            # (after which the entire stack joined together is output implicitly)

```

# Answer
> 3 votes
# Charcoal, 30 bytes

```
Ｆ²⊞υＳ⟦⌊Ｅυ⁺⌊⁻ι0⌊§υ¬κ⌈Ｅ⟦υ⮌υ⟧⭆ι⌈λ

```

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

```
Ｆ²⊞υＳ

```

Input the two numbers as a pair of strings.

Separate the two outputs.

```
⌊Ｅυ⁺⌊⁻ι0⌊§υ¬κ

```

For each string, string take the minimum digit with `0` excluded and the minimum digit of the other string, then take the minimum result.

```
⌈Ｅ⟦υ⮌υ⟧⭆ι⌈λ

```

Of the pair and its reverse, take the maximum digit of each string, then take the maximum result.

# Answer
> 3 votes
# Scala, 78 bytes

```
a=>b=>{val z=for(x<-a;y<-b;c<-Seq(""+x+y,""+y+x)if"09"<c)yield c;z.min->z.max}

```

Try it online!

Apparently, just storing it in a variable is shorter than folding over all the permutations. Accepts two strings (curried) and returns a 2-tuple of strings.

# Scala, 109 bytes

```
a=>b=>((-1>>>1,0)/:(for(x<-a;y<-b;c<-Seq(""+x+y,""+y+x)if"09"<c)yield c.toInt)){(t,|)=>(t._1 min|,t._2 max|)}

```

Try it online!

# Answer
> 3 votes
# Perl 5, ~~98~~ 94 bytes

```
sub{@i="@_"=~/./g;(sort grep!/^0/,map{/./;$i[$&].$i[$'],$i[$'].$i[$&]}<{0,1,2}{4,5,6}>)[0,-1]}

```

Try it online!

# Answer
> 3 votes
# APL+WIN, 30 bytes.

Index origin = 0. Prompts for input numbers as strings:

```
(⌊/n~⍳10),⌈/n←,⍎¨(⌽¨n),n←⎕∘.,⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 3 votes
# Zsh, 90 bytes

```
for d (${(o)=${(s::)@}})((e&~a&&(a=e,b=d),${z=$d},f=e,e=d))
<<<${z/0/$a}${z/[^0]/$b}\ $d$f

```

Try it online!

`${(o)=${(s::)@}}` sorts the digits, which we loop over. By the end of the loop, we have the following parameters set:

* `z`: The smallest digit
* `a`: The smallest non-zero digit
* `b`: The second-smallest non-zero digit
* `d`,`e`: The largest digit
* `f`: The second-largest digit.

If `z` is zero, then the first number is `$a$z`. If `z` is non-zero, then the first number is `$z$b`.

# Answer
> 3 votes
# Japt, 13 bytes

I/O as an array of digit arrays.

```
rï cá fÎÍé ¯2

```

Try it

```
rï cá fÎÍé ¯2     :Implicit input of array
r                 :Reduce by
 ï                :  Cartesian product
   c              :Flat map
    á             :  Permutations
      f           :Filter by
       Î          :  First element (0 is falsey)
        Í         :Sort
         é        :Rotate right
           ¯2     :Slice to second element

```

# Answer
> 2 votes
# Japt, 17 bytes

```
ïV cVïU)Íf¨A é v2

```

Try it

```
ïV             - pair each digits
   Í           - sort
    f¨A        - remove if <10
        é      - rotate array
          v2   - return first 2 elements ( Max , Min )

```
* Thanks to @Shaggy for spotting an error, fixed by adding `cVïU`

# Answer
> 2 votes
# Haskell, 62 bytes

```
q l=[minimum,maximum]<*>[filter(>"1")$mapM id=<<[l,reverse l]]

```

Try it online!

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

```
MinMax@Select[FromDigits/@Join@@Permutations/@Tuples[IntegerDigits/@#],#>9&]&

```

Try it online!

# Answer
> 2 votes
# Perl 5 `-MList::Util=min,max -p`, 89 bytes

```
s/.\K/,/g;s/ /}{/ for($b=reverse),$_;$_=min(@a=grep$_>9,glob("{$_}"),glob"{$b}").$".max@a

```

Try it online!

# Answer
> 2 votes
# Bash, 126 153 158 bytes

```
for n in {10..99}; {
t=$[n/10]
o=$[n%10]
([[ $1 =~ $t && $2 =~ $o ]]||[[ $2 =~ $t && $1 =~ $o ]])&&A+=($n)
}
echo $A-${A[-1]}

```

Try it online!

# Answer
> 2 votes
# C (MinGW), ~~150~~ 146 bytes

-4 bytes thanks to ceilingcat

The TiO link needs `-lm` but MinGW does not.

```
M,m,x,y,c,t=10;f(a,b){for(M=0,m=99;a;a/=t)for(c=b;c;c/=t)M=fmax(fmax(x=a%t*t+c%t,M),y=c%t*t+a%t),m=y<m&y>9?y:m,m=x<m&x>9?x:m;printf("%d %d",m,M);}

```

Try it online!

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

```
(a,b)=>[(e=a.map(c=>b.map(d=>[c+d,d+c])).flat(3).sort()).find(x=>x>9),e[17]]

```

Try it online!

Input as two lists of character, output as two strings.

# Answer
> 2 votes
# C (gcc),  ~~147 144~~  141 bytes

```
#define g(x,d)x%q!=d&x/q%q!=d&x/100!=d
v,d=1,q=10;f(a,b){for(v=q;g(a,v/q)|g(b,v%q)&&g(b,v/q)|g(a,v%q)||printf("%d ",v)&&(v=99,d=-d)<0;v+=d);}

```

Try it online!

### How?

The macro `g(x,d)` checks whether the digit `d` appears in the 3-digit integer `x` by testing \\$x\bmod 10\\$, \\$\lfloor x/10\rfloor\bmod 10\\$ and \\$\lfloor x/100\rfloor\\$. It returns a falsy value if successful.

We look for the first `v` such that \\$\lfloor v/10\rfloor\\$ appears in `a` and \\$v \bmod 10\\$ appears in `b`, or the other way around. We do it once by going from \\$v=10\\$ to \\$v=99\\$ and once by going from \\$v=99\\$ to \\$v=10\\$, to get the lowest and highest valid integers respectively.

# Answer
> 2 votes
# , ~~138~~ ~~134~~ ~~128~~(thanks pajonk) ~~121~~ 117 bytes

```
k=t(t(expand.grid(strsplit(scan(,""),""))));class(k)=class(1);a=c(A<-k[,1],B<-k[,2]);b=c(B,A);range(10*a[a>0]+b[a>0])

```

Try it online!

Another solution that takes input as a list of digits, allowed per the rules:

# , ~~110~~(thanks pajonk) ~~103~~ ~~99~~ 93 bytes

```
i=scan();k=expand.grid(i[1:3],i[4:6]);a=c(A<-k[,1],B<-k[,2]);b=c(B,A);range(10*a[a>0]+b[a>0])

```

Try it online!

# Answer
> 1 votes
# , 31 bytes

```
0 _1{;~/:~@(#~0<{."1)@:>@,&,&{;

```

Try it online!

* `;` Link the args
* `;~` Link the args reverse
* `&{` Cartesian product of each
* `&,` Flatten of each
* `,` Link those results
* `>` Open them
* `(#~0<{."1)@:` Remove elms whose first digit is 0
* `/:~@` Sort the result
* `0 _1{` Take first and last elms

# Answer
> 1 votes
# Vyxal, 10 bytes

```
ẊvṖÞf~h₍gG

```

Try it Online!

Same as my Thunno 2 answer.

#### Explanation

```
ẊvṖÞf~h₍gG  # Implicit input
Ẋ           # Cartesian product of both inputs
 vṖ         # Permutations of each pair
   Þf       # Flatten the list once
     ~h     # Filter by first item (is non-zero)
       ₍gG  # Get the minimum and maximum
            # Implicit output

```

# Answer
> 0 votes
# Perl 5 `-p`, 70 bytes

```
/(.).* .*(.)(?{push@a,$1.$2,$2.$1})^/;$_="@{[sort grep$_>9,@a]}[0,-1]"

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 9 bytes

```
Ṗ€ṗSœhçMG

```

Try it online!

I/O as digit lists (allowed in challenge). Header/footer convert between digit lists and integers.

#### Explanation

```
Ṗ€ṗSœhçMG  # Implicit input
Ṗ          # Cartesian product of both inputs
 €ṗ        # Permutations of each pair
   S       # Sum (flatten the list once)
    œh     # Filter by first item (is non-zero)
      çMG  # Get the minimum and maximum
           # Implicit output

```

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


title: What's my Body Mass Index?

text:
# Question
Title: What's my Body Mass Index?
# Problem:

Your task is to write a program that takes as input a height (in meters) and weight (in kilograms), and outputs the corresponding BMI category.

BMI is a measure of the ratio of your weight to your height. It's dated and inaccurate for many people, but that doesn't matter here!

BMI can be calculated using the following equation:

```
BMI = (mass in kilograms) / (height in meters)^2

```

The categories will be defined as follows:

* BMI \< 18.5: "Underweight"
* 18.5 \<= BMI \< 25: "Normal"
* 25 \<= BMI: "Overweight"

For the sake of the challenge, I'm ignoring all the "extreme" categories. Also, since some numbers like "25" sit between 2 categories, I adjusted the bounds slightly so there's a definite answer.

You can write either a function, or a full program.

# Input:

Input can be in any reasonable form. Two numbers (or strings), either as 2 separate arguments, or as a single string. An array/list of 2 numbers, a dictionary with "weight" and "height" keys... Decimal values should be supported. You can assume the input will always be valid (no negative values, and height will never be 0).

# Output:

Output will be a string containing the *case-insensitive* category names. The strings must match the category names exactly as above, ignoring case. It can be output to the stdout, returned (in the case of a function), or written to file.

# Test Cases (weight, height =\> result):

```
80, 1 =>   "Overweight"
80, 2 =>   "Normal"
80, 3 =>   "Underweight"

50, 1 =>   "Overweight"
50, 1.5 => "Normal"
50, 2 =>   "Underweight"

Edge Cases:

41, 1.5 => "Underweight" (18.2 BMI)
42, 1.5 => "Normal" (18.667 BMI)

56, 1.5 => "Normal" (24.889 BMI)
57, 1.5 => "Overweight" (25.3 BMI)

73, 2 =>   "Underweight" (18.25 BMI)
74, 2 =>   "Normal" (18.5 BMI)

99, 2 =>  "Normal" (24.75 BMI)
100, 2 => "Overweight" (25 BMI)

```

Here's some pseudocode that shows an example implementation:

```
function bmi_category(weight, height):
    var bmi = (weight / (height**2))

    if (bmi < 18.5):
        return "Underweight"

    if (18.5 <= bmi < 25):
        return "Normal"

    if (25 <= bmi):
        return "Overweight"

```

This is code-golf, so the fewest number of bytes wins.

(Yes, this task is ***exceedingly*** trivial in most languages. Most of the challenges lately seem to be harder than normal, so I thought I'd post a more accessible one).

---

NOTE! An hour after I posted this challenge, I had to modify the ranges slightly since the ranges as stated had "holes" as pointed out in the comments. Please see the new ranges.

# Answer
> 9 votes
# Jelly, 24 bytes

```
÷÷⁹Ḥ“%2‘>Sị“$⁽¿“;ṅẒ“&ċ)»

```

**Try it online!**

### How?

Calculates the BMI, doubles it, compares that with the greater than operator with each of the numbers 37 and 50 (18.5 and 25 doubled), sums the resulting ones and zeros (yielding 1, 2, or 0 for Normal, Underweight, and Overweight respectively) and indexes into the list of strings `["Normal","Underweight","Overweight"]`.

```
÷÷⁹Ḥ“%2‘>Sị“$⁽¿“;ṅẒ“&ċ)» - Main link: weight, height
÷                        - weight ÷ height
  ⁹                      - right argument, height
 ÷                       - ÷ by height again to get the BMI
   Ḥ                     - double the BMI
    “%2‘                 - list of code page indexes [37,50]
        >                - greater than? (vectorises) - i.e [18.5>bmi, 25>bmi]
         S               - sum -- both:=2 (Underweight), just 50:=1 (Normal) or neither:=0 (Overweight)
          ị              - index into (1-based)
           “$⁽¿“;ṅẒ“&ċ)» - compressed list of strings ["Normal","Underweight","Overweight"]
                         - implicit print

```

# Answer
> 21 votes
# Python, 69 bytes

```
lambda w,h:["UOnvd"[w/h/h>20::2]+"erweight","Normal"][18.5<=w/h/h<25]

```

Try it online!

Compare to 72 bytes:

```
lambda w,h:"Underweight"*(w/h/h<18.5)or"Normal"*(w/h/h<25)or"Overweight"

```

# Answer
> 10 votes
# TI-Basic, ~~58~~ 54 bytes

```
Input
X/Y²→C
"NORMAL
If 2C≤37
"UNDERWEIGHT
If C≥26
"OVERWEIGHT

```

Also, for fun, here's a more compact version that is more bytes:

```
Prompt A,B
sub("UNDERWEIGHTNORMAL      OVERWEIGHT ",sum(A/B²≥{18.5,25})11+1,11

```

All I can say is, thank you for making this case-insensitive ;)

P.S. `Input` takes graph input to `X` and `Y` similar to `Prompt X,Y`

# Answer
> 6 votes
# Mathematica, 67 bytes

```
"Normal"["Underweight","Overweight"][[Sign@⌊(2#/#2^2-37)/13⌋]]&

```

Uses the fact that `a[b,c][[Sign@d]]` returns `a` if `d` equals 0, returns `b` if `d` is positive, and returns `c` if `d` is negative. `⌊...⌋` is Mathematica's `Floor` function using the three-byte characters U+230A and U+230B. Couldn't figure out how to do better than using `weight` twice.

# Answer
> 5 votes
# JavaScript (ES6), ~~70 67 64~~ 63 bytes

*Saved 4B thanks to Arnauld*

```
a=>b=>(a/=b*b)<25&a>=18.5?"Normal":(a<19?"Und":"Ov")+"erweight"

```

## Usage

```
f=a=>b=>(a/=b*b)<25&a>=18.5?"Normal":(a<19?"Und":"Ov")+"erweight"
f(80)(1)

```

### Output

```
"Overweight"

```

## Explanation

This answer is quite trivial, though there is one clever trick: `Underweight` and `Overweight` both end in `erweight`, so we only have to change those characters.

I assumed that `Normal` means a BMI between 25 (exclusive) and 18.5 (inclusive). `Underweight` means a BMI less than 18.5, and `Overweight` means a BMI greater than or equal to 25.

# Answer
> 5 votes
# Ruby, 91 77 74 67 bytes

First naive try:

```
->(w,h){case w/h/h
when 0..18.5
'underweight'
when 18.5..25
'normal'
else
'overweight'
end}

```

Second try with ”inspiration“ from previous answers:

```
->w,h{["#{(w/=h*h)<18.5?'und':'ov'}erweight",'normal'][(18.5..25)===(w)?1:0]}

```

Third try:

```
->w,h{["#{(w/=h*h)<18.5?'und':'ov'}erweight",'normal'][w>=18.5&&w<25?1:0]}

```

Fourth try:

```
->w,h{18.5<=(w/=h*h)&&w<25?'normal':"#{w<18.5?'und':'ov'}erweight"}

```

Try it online!

# Answer
> 4 votes
## QBIC, ~~61~~ 58 bytes

```
::m=a/b^2~m<18.5|?@Und`+@erweight`\~m>=25|?@Ov`+B\?@Normal

```

*@Luke used the Force and chopped off two bytes. Thanks!*

*The rules change saved another byte.*

Explanation:

```
::          gets weight and height as a and b
m=a/b^2     Calculates BMI
~m<18.5|    If BMI < 18.5 then
?@Und`      Print the string literal 'Und' (which is now A$)
+@erweight` and the string literal 'erweight'  (which is now B$)
\~m>=25|    else if the BMI is greater than or equal to 25
?@Ov`+B     Print 'Ov' and B$ ('erweight')
\?@Normal   Else, if we're here, BMI is normal.

```

# Answer
> 4 votes
# C, 81 bytes

```
f(float m,float h){m/=h*h;puts(m<26?m<18.6?"Underweight":"Normal":"Overweight");}

```

# Answer
> 4 votes
# 05AB1E, 28 bytes

```
n/©37;‹®25‹O’‚Š‰ß îÂ ‚â‰ß’#è

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 3 votes
# Python 3, ~~97~~ 95 bytes

```
a,b=map(int,input().split())
a/=b*b*5
print(["UOnvd"[a>93::2]+"erweight","Normal"][93<=a<=125])

```

Full program.

Multiply by five to save a byte. Thanks Jonathan Allan.

Line by line:

1. Map the two space separated user input numbers to ints. Unpack to a and b.
2. Calculate
3. If the bmi is between 18.6 and 25, inclusive, the expression on the right will evaluate to True. Booleans can be 0 or 1 when used as list indexes, so we get either "Normal" or the constructed string in the zero index. "erweight" is a shared suffix for the remaining two options, so it doesn't need to be repeated. Then we use the \[start:stop:step\] pattern of Python list/string slicing. c\>18.6 will evaluate to either 0 or 1 (False or True) and becomes our start. Stop isn't indicated so we go to the end of the literal. Step is 2 so we take every second index. If start start evaluates to 1, we get "Ov", otherwise we get "Und". Either way, we append "erweight" to what we got and we have our final output.

# Answer
> 3 votes
# Python 2, 72 bytes

```
lambda a,b:"UNOnovdreemrrawwlee ii gg hh tt"[(18.6<a/b/b)+(a/b/b>25)::3]

```

Try it online!

# Answer
> 3 votes
# PowerShell, 81 bytes

```
param($m,$h)('Underweight','Normal','Overweight')[(18.5,25-lt($m/($h*$h))).Count]

```

Try it online!

## Explanation

The main bit that needs explaining is `18.5,25 -lt $b` (where I'm substituting `$b` for the BMI which is calculated in place in the code). Most operators in PowerShell, when given an array on the left side, return an array of items that satisfy the test, instead of returning a boolean value. So this will return an empty array if `$b` is smaller than 18.5, an array containing only 18.5 if it's in the middle, and an array containing both 18.5 and 25 if it's larger than 25.

I use the count of the elements as an index into an array of the strings, so count `0` gets element `0` which is `'Underweight'`, etc.

# Answer
> 3 votes
## R, ~~89~~ ~~84~~ ~~80~~ 74 bytes

```
f=pryr::f(c('Overweight','Normal','Underweight')[sum(w/h^2<c(18.5,25),1)])

```

With a nod to StewieGriffin's Octave answer, creates an array of strings, then sums the result of `BMI < c(18.5,25)` and references the array at that position + 1.

First argument needs to be height, then weight; if that's not allowed, then

```
f=pryr::f(w,h,c('Overweight','Normal','Underweight')[sum(w/h^2<c(18.5,25),1)])

```

works for 4 more bytes.

# Answer
> 2 votes
# Python, ~~75~~ 74 bytes

```
lambda h,w:18.5<=w/h/h<=25and"normal"or["ov","und"][25>w/h/h]+"erweight"

```

Try it online!

Fairly basic solution that takes advantage of other people's techniques for solving it.

Thanks @ovs for saving a byte.

## Alternatives

### 1. 73 bytes

```
lambda h,w:"normal"if 18.5<=w/h/h<=25 else"uonvd"[25<w/h/h::2]+"erweight"

```

I rejected this as it was too similar to another answer I saw.

### 2. 71 bytes

```
lambda h,w:"normal"if 18.5<w/h/h<25 else"uonvd"[25<w/h/h::2]+"erweight"

```

I rejected this because, despite working on all the tests in the question, there are some numbers it can fail on as it's missing the `=` in the `<=`.

# Answer
> 2 votes
## Clojure, 63 bytes

```
#(condp <(/ %(* %2 %2))25"Overweight"18.5"Normal""Underweight")

```

# Answer
> 2 votes
# Common Lisp, ~~89~~ ~~87~~ ~~85~~ ~~84~~ 83 bytes

A function:

```
(lambda(w h)(if(< #1=(/ w(* h h))18.5)'underweight(if(< #1#25)'normal'overweight)))

```

### Example of usage:

```
((lambda(w h)(if(< #1=(/ w(* h h))18.5)'underweight(if(< #1#25)'normal'overweight)))150 2)

```

Try it online! (I added printing function to see output in TIO)

Ideas for improvement are welcomed.

# Answer
> 2 votes
# dc, 58 bytes

```
Fk[Ov]?2^/d[[Normal]pq][[Und]26]sasb18.5>a25>bn[erweight]p

```

Takes input as 2 space separated numbers in the format `<mass> <height>` . Outputs a string on a separate line.

Try it online!

### Explanation

For the purposes of this explanation, the input is `80 1`.

```
Fk                                                         # Set decimal precision to `16`.
  [Ov]                                                     # Push the string "Ov" onto the main stack.
                                                           # Main Stack: [[Ov]]
      ?2^/d                                                # Take and evaluate input, squaring the 2nd one, and the dividing by the first one by the 2nd. Then duplicate the result.
                                                           # Main Stack: [[Ov],80.000000000000000,80.000000000000000]
           [[Normal]pq][[Und]26]sasb                       # Push and store the executable macros "[Normal]pq" and "[Und]26" on registers "a" and "b", respectively.
                                                           # Main Stack: [[Ov],80.000000000000000,80.000000000000000], reg. a: [[[Normal]pq]], reg. b: [[[Und]26]]
                                    18.5>a25>b             # Push, "18.5" onto stack, and then pop top 2 values. If "18.5 > (top of stack)", then execute the macro on top of reg. "a", which in turn pushes the string "Und" onto the main stack followed by the number 26.
                                                           # The "26" will automatically prompt the next comparison to not execute the macro on top of reg. "b", regardless of the value on top of the main stack.
                                                           # Otherwise, if "18.5 <= (top of stack) < 25", then execute "b"s macro, which in turn pushes the string "Normal" onto the main stack, outputs it, then quits the program.
                                                           # In this case, Main stack: [[Ov]], reg. a: [[[Normal]pq]], reg. b: [[[Und]26]]
                                              n[erweight]p # If "Normal" has not been output, only then will the program get to this point. Here, it will output whatever string, either "Und" or "Ov", on top of the main stack, followed by "erweight" and a new line.

```

# Answer
> 2 votes
# C#, 63 62 61 bytes

*Saved 1 more byte thanks to TheLethalCoder.*

*Saved 1 byte thanks to anonymous user.*

```
w=>h=>w/h/h<18.5?"Underweight":w/h/h<25?"Normal":"Overweight";

```

A pretty straightforward anonymous function. The whole trick is using the ternary operator to return directly (thus omitting the `return` keyword, a pair of curly braces and a variable declaration and assignment).

Full program with test cases:

```
using System;

class BodyMassIndex
{
    static void Main()
    {
        Func<double, Func<double, string>> f =
        w=>h=>w/h/h<18.5?"Underweight":w/h/h<25?"Normal":"Overweight";

        // test cases:
        Console.WriteLine(f(80)(1));  // "Overweight"
        Console.WriteLine(f(80)(2));  // "Normal"
        Console.WriteLine(f(80)(3));  // "Underweight"
        Console.WriteLine(f(50)(1));  // "Overweight"
        Console.WriteLine(f(50)(1.5));  // "Normal"
        Console.WriteLine(f(50)(2));  // "Underweight"
    }
}

```

# Answer
> 2 votes
# Octave, 64 bytes

```
@(w,h){'Underweight','Normal','Overweight'}{3-sum(2*w/h^2<'%2')}

```

Try it online

This is an anonymous function that takes two input arguments, `h` (height) and `w` (weight).

The function creates a cell array containing there strings `'Underweight','Normal','Overweight'`, and outputs string number `3-sum(2*w/h^2<'%2')`.

Yes, that one looks a bit strange. We want the first string if `w/h^2<=18.5`, the second string if `(w/h^2 > 18.5) & (w/h^2 < 25)` and the third string if none of the above conditions are true. Instead of creating a bunch of comparisons, we could simply compare the string to: `w/h^2 < [18.5, 25]`, which would return one of the following arrays `[1 1], [0 1], [0,0]` for Underweight, Normal and Overweight respectively.

`[18.5,25]` takes 9 bytes, which is a lot. What we do instead, is multiply the BMI by 2, and compare the result with `[37, 50]`, or `'%2'` in ASCII. This saves three bytes.

# Answer
> 2 votes
# Perl 6, 59 bytes

```
{<Overweight Normal Underweight>[sum 18.5,25 X>$^a/$^b**2]}

```

### How it works

```
{                                                         }  # A lambda.
                                               $^a/$^b**2    # Compute BMI from arguments.
                                     18.5,25 X>              # Compare against endpoints.
                                 sum                         # Add the two booleans together.
 <Overweight Normal Underweight>[                        ]   # Index into hard-coded list.

```

Too bad the string `erweight` has to be repeated, but all variations I tried in order to avoid that ended up increasing the overall byte count:

* With string substitution, 62 bytes:

```
{<Ov_ Normal Und_>[sum 18.5,25 X>$^a/$^b**2].&{S/_/erweight/}}
```
* With string interpolation, 67 bytes:

```
{$_='erweight';("Ov$_","Normal","Und$_")[sum 18.5,25 X>$^a/$^b**2]}
```
* Rough translation of xnor's Python solution, 65 bytes:

```
{$_=$^a/$^b**2;25>$_>=18.5??"Normal"!!<Und Ov>[$_>19]~"erweight"}
```

# Answer
> 2 votes
# OCaml, 93 bytes

```
let b w h=if w/.h/.h<18.5 then"underweight"else if w/.h/.h>=25.0 then"overweight"else"normal"

```

# Answer
> 2 votes
# MATL, ~~54~~ ~~45~~ ~~44~~ 42 bytes

```
U/E'%2'<sqt?q?'ov'}'und']'erweight'h}x17Y0

```

Try it at matl.io

Starts off by calculating the BMI and doubling it `U\E`, then creates the vector `[37 50]` with the string literal '%2'. Compares the BMI to this vector and uses if statements to get the answer, taking advantage of `normal` as a predefined literal `17Y0`.

# Answer
> 2 votes
# Thunno 2, 25 bytes

```
²/¿}ȯE¿©S‘Ọḃẋɠ Ḳẇ ṁẓẋɠ‘Oi

```

Try it online!

#### Explanation

```
²/...©S...i  # Implicit input
²/           # Divide the weight by the height squared
  ...        # Compressed numeric list [18.5, 25]
     ©       # Vectorised lesser than or equal to
      S      # Sum the list to get an integer from 0 to 2
             # (0=overweight, 1=normal, 2=underweight)
       ...i  # Index into compressed list of strings
             # ["Overweight", "Normal", "Underweight"]
             # Implicit output

```

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

```
{((,"Normal"),("Ov";"Und"),\:"erweight")3!("%2"%2)'x%y*y}

```

Try it online!

# Answer
> 1 votes
# Java 8, 61 bytes

```
w->h->w/h/h<18.5?"Underweight":w/h/h<25?"Normal":"Overweight"

```

Assign to a `DoubleFunction<DoubleFunction<String>>` and call thusly:

```
bmi.apply(50).apply(1.5)

```

# Answer
> 1 votes
# Japt, 46 bytes

```
/=V²U<25©U¨18½?`NŽµl`:ºU<19?`U˜`:"Ov")+`€³ight

```

Try it online!

Inspired by @Luke's answer.

### Explanation

```
/=V²U<25©U¨18½?`NŽµl`:ºU<19?`U˜`:"Ov")+`€³ight

```

Decompresses to :

```
U=U/V**2,U<25&&U>18.5?"Normal":(U<19?"Und":"Ov")+"erweight"

```

Japt has an implicit input `U`. The second input is `V`.

Japt uses the shoco library for string compression. Backticks are used to decompress strings.

Unicode shortcuts used:

```
² : **2
© : &&
¨ : >=
½ : .5
º : ((

```

# Answer
> 1 votes
# dc, 64 bytes

```
[erweight][[Und]PszPq]su[[Normal]Pq]sn9k?d*/d18.5>ud25>n[Ov]PszP

```

Try it online!

# Answer
> 1 votes
# PHP, 69 68/85 bytes

If you want it to be more as a program,

```
$a=$args;$b=$a[0]/($a[1]*$a[1]);echo$b>=18.5&&$b<25?normal:($b<18.5?und:ov).erweight; // 85

$b=$k/($h*$h);echo$b>=18.5&&$b<25?normal:($b<18.5?und:ov).erweight; // 68
$b=$k/pow($h,2);echo$b>=18.5&&$b<25?normal:($b<18.5?und:ov).erweight; // 69

```

You can test with `$k=80; $h=1;`. I had three choices, via `$args`, like this or as defined values (`K`&`H`). I choose the middle as most fair.

# Answer
> 1 votes
## Javascript (ES6), 63 bytes

```
(m,h)=>(w="erweight",b=m/h/h)<18.5?"Und"+w:b<25?"Normal":"Ov"+w

```

Example

```
f=(m,h)=>(w="erweight",b=m/h/h)<18.5?"Und"+w:b<25?"Normal":"Ov"+w

console.log(f(80, 1));
console.log(f(80, 2));
console.log(f(80, 3));
```

# Answer
> 1 votes
# Swift, 97 bytes

```
{(w:Float,h)->String in return 18.5<=w/h/h&&w/h/h<25 ?"normal":"\(w/h/h>25 ?"ov":"und")erweight"}

```

# Answer
> 1 votes
# PHP, 121 bytes

```
function f($a,$b){$i=$a/($b*$b);$x = 18.5;print ($i<$x?"Underweight":($i>=$x&&$i<25?"Normal":($i>=25?"Overweight":"")));}

```

Try it online!

# Answer
> 1 votes
## Scala, 124 bytes

```
val x="erweight"
def b(i:Float,a:Float):Any=i/a/a match{case z if(z<18.5)=>"Und"+x
case z if(z<25)=>"Normal"
case z=>"Ov"+x}

```

# Answer
> 1 votes
## REXX, 113 bytes

```
arg m h
b=m/h**2
e=erweight
select
  when b<18.5 then say 'UND'e
  when b>=25 then say 'OV'e
  otherwise say Normal
end

```

# Answer
> 1 votes
# C, 94 bytes

```
char const*f(float a,float b){return a/b/b<18.5?"Underweight":a/b/b<25?"Normal":"Overweight";}

```

Simply calculates the BMI and returns the appropriate range using the ternary operator. Not using an intermediate variable to store the BMI saves 6 bytes.

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


title: The inverse Collatz Conjecture

text:
# Question
Title: The inverse Collatz Conjecture
I think the Collatz Conjecture is already well-known. But what if we invert the rules?

Start with an integer n \>= 1.

Repeat the following steps:

If n is **even**, multiply it by 3 and add 1.

If n is **odd**, subtract 1 and divide it by 2.

Stop when it reaches 0

Print the iterated numbers.

### Test cases:

```
 1        => 1, 0
 2        => 2, 7, 3, 1, 0
 3        => 3, 1, 0
10        => 10, 31, 15, 7, 3...
14        => 14, 43, 21, 10, ...

```

### Rules:

* This sequence does not work for a lot of numbers because it enters in an infinite loop. You do not need to handle those cases. Only printing the test cases above is enough.
* I suggested to subtract 1 and divide by two to give a valid integer to continue, but it is not required to be computed that way. You may divide by 2 and cast to integer or whatever other methods that will give the expected output.
* You need to print the initial input as well.
* The output does not need to be formatted as the test cases. It was just a suggestion. However, the iterated order must be respected.
* The smallest code wins.

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

```
f 0=[]
f n=n:f(cycle[3*n+1,div n 2]!!n)

```

Try it online!

Now without the final 0.

# Answer
> 5 votes
# Perl 6, 30 bytes

```
{$_,{$_%2??$_+>1!!$_*3+1}...0}

```

Try it online!

Anonymous code block that returns a sequence.

### Explanation:

```
{$_,{$_%2??$_+>1!!$_*3+1}...0}
{                            }   # Anonymous code block
   ,                     ...     # Define a sequence
 $_                              # That starts with the given value
    {                   }        # With each element being
     $_%2??     !!               # Is the previous element odd?
           $_+>1                 # Return the previous element bitshifted right by 1
                  $_*3+1         # Else the previous element multiplied by 3 plus 1
                            0    # Until the element is 0

```

# Answer
> 4 votes
# Jelly, 9 bytes

```
:++‘ƊḂ?Ƭ2

```

Try it online!

# Answer
> 4 votes
# Clean, 53 bytes

```
import StdEnv
$0=[0]
$n=[n: $if(isOdd n)(n/2)(n*3+1)]

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 35 bytes

```
0<Echo@#&&#0[3#+1-(5#+3)/2#~Mod~2]&

```

Try it online!

`0<Echo@# && ...&` is short-circuit evaluation: it prints the input `#`, checks if it's positive, and if so, evaluates `...`. In this case, `...` is `#0[3#+1-(5#+3)/2#~Mod~2]`; since `#0` (the zeroth slot) is the function itself, this is a recursive call on `3#+1-(5#+3)/2#~Mod~2`, which simplifies to `3#+1` when `#` is even, and `(#-1)/2` when `#` is odd.

# Answer
> 2 votes
# Rust, ~~65~~ 64 bytes

```
|mut n|{while n>0{print!("{} ",n);n=if n&1>0{n>>1}else{n*3+1};}}

```

Try it online!

# Answer
> 2 votes
# JAEL, 18 bytes

```
![ؼw>î?èÛ|õÀ

```

Try it online!

# Answer
> 2 votes
# Python 2,  ~~54~~ ~~52~~ 44 bytes

```
n=input()
while n:print n;n=(n*3+1,n/2)[n%2]

```

*-2 bytes thanks to Mr. Xcoder*

There must certainly be a faster way. Oddly, when I tried a lambda it was the same bytecount. I'm probably hallucinating.

Try it online!

# Answer
> 2 votes
# Haskell, ~~76 69 61~~ 56 bytes

I feel like this is way too long. Here `l` produces an infinite list of the inverse-collatz sequence, and the anonymous function at the first line just cuts it off at the right place.

Thanks for -5 bytes @ØrjanJohansen!

```
fst.span(>0).l
l r=r:[last$3*k+1:[div k 2|odd k]|k<-l r]

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~15~~ 14 bytes

```
[Ð=_#Èi3*>ë<2÷

```

-1 byte thanks to *@MagicOctopusUrn*.

Try it online.

**Explanation:**

```
[             # Start an infinite loop
 Ð            #  Duplicate the top value on the stack three times
              #  (Which will be the (implicit) input in the first iteration)
  =           #  Output it with trailing newline (without popping the value)
   _#         #  If it's exactly 0: stop the infinite loop
     Èi       #  If it's even:
       3*     #   Multiply by 3
         >    #   And add 1
      ë       #  Else:
       <      #   Subtract 1
        2÷    #   And integer-divide by 2

```

# Answer
> 2 votes
# Emojicode 0.5, 141 bytes

```
aa 10▶a 0a 2 1a➗a 2a➕✖a 3 1a 10

```

Try it online!

```

a       input integer variable 'a'
a 10       print input int
▶a 0       loop while number isn’t 0
a 2 1      if number is odd
a➗a 2        divide number by 2

       else
a➕✖a 3 1    multiply by 3 and add 1

a 10      print iteration

```

# Answer
> 2 votes
# Thunno `d`, \\$ 19 \log\_{256}(96) \approx \\$ 15.64 bytes

```
[zuZK!)2%?1-2,(3*1+

```

(No ATO link since this needs v1.2.2 and ATO is on v1.2.1)

#### Explanation

```
[zuZK!)2%?1-2,(3*1+  # Implicit input
[                    # Loop forever:
 zu                  #  Quadruplicate the value on the top of the stack
   ZK                #  Print with a trailing newline
     !)              #  If it's 0, break
       2%?           #  If it's odd:
          1-         #   Subtract one
            2,       #   And integer divide by two
              (      #  Else:
               3*    #   Multiply by three
                 1+  #   And add one
                     #  This value is on the top of the stack for the next iteration
                     # The d flag stops the implicit output at the end

```

#### Screenshot

# Answer
> 2 votes
# Nibbles, 7.5 bytes

```
`.$?`%$~@+*3@~

```

Attempt This Online!

```
`. Iterate while unique
$   starting at input
?   if
`%   modulo (also save the quotient)
$     the number
~     2
@    then the quotient
+    else add
*3    multiply by 3
@      the number
~     1

```

# Answer
> 2 votes
# Vyxal, ~~15~~ 12 bytes

Thanks to @Steffan i learned more about Vyxal!

```
{…:|:∷[2ḭ|T›

```

Try it Online!

Naive approach for beginners:

```
{…:Ṡ|:₂[3*›|‹2/

```

# Answer
> 2 votes
# Pyt, 15 bytes

```
`ĐĐ2%?ŕ₂:ŕ3*⁺;ł

```

Try it online!

```
`             ł        do... while top of stack is not 0; implicit print upon exiting loop
 ĐĐ                    duplicate top of stack twice (implicit input if empty)
   2%                  modulo 2
      ?ŕ₂              if top of stack is truthy, then pop from stack and divide next by 2
        :ŕ3*⁺          else: pop from stack and multiply next term by 3 and add 1
             ;         end if-then-else statement

```

# Answer
> 2 votes
# Thunno 2, 12 bytes

```
(ß;DE?3×⁺:⁻½

```

Try it online!

#### Explanation

```
(ß;DE?3×⁺:⁻½  # implicit input
(             # while loop:
 ß            #   (condition)  print the number without popping
              #                and test if it's truthy (non-zero)
  ;D          #   (body)  duplicate the current integer
    E?        #           if it's even:
      3×      #             multiply it by 3
        ⁺     #             and then add one
         :    #           otherwise:
          ⁻   #             decrement it
           ½  #             and then halve it

```

# Answer
> 1 votes
# JavaScript (ES6), 30 bytes

```
f=n=>n&&n+[,f(n&1?n>>1:n*3+1)]

```

Try it online!

# Answer
> 1 votes
# Add++, ~~38~~ ~~35~~ 33 bytes

```
D,f,@:,d3*1+$2/iA2%D
+?
O
Wx,$f>x

```

Try it online!

## How it works

First, we begin by defining a function \\$f(x)\\$, that takes a single argument, performs the inverted Collatz operation on \\$x\\$ then outputs the result. That is,

$$f(x) = \begin{cases} x \\: \text{is even}, & 3x+1 \\ x \\: \text{is odd}, & \lfloor\frac{x}{2}\rfloor \end{cases}$$

When in function mode, Add++ uses a stack memory model, otherwise variables are used. When calculating \\$f(x)\\$, the stack initially looks like \\$S = \[x\]\\$.

We then duplicate this value (`d`), to yield \\$S = \[x, x\]\\$. We then yield the first possible option, \\$3x + 1\\$ (`3*1+`), swap the top two values, then calculate \\$\lfloor\frac{x}{2}\rfloor\\$, leaving \\$S = \[3x+1, \lfloor\frac{x}{2}\rfloor\]\\$.

Next, we push \\$x\\$ to \\$S\\$, and calculate the bit of \\$x\\$ i.e. \\$x \\: \\% \\: 2\\$, where \\$a \\: \\% \\: b\\$ denotes the remainder when dividing \\$a\\$ by \\$b\\$. This leaves us with \\$S = \[3x+1, \lfloor\frac{x}{2}\rfloor, (x \\: \\% \\: 2)\]\\$. Finally, we use `D` to select the element at the index specified by \\$(x \\: \\% \\: 2)\\$. If that's \\$0\\$, we return the first element i.e. \\$3x+1\\$, otherwise we return the second element, \\$\lfloor\frac{x}{2}\rfloor\\$.

That completes the definition of \\$f(x)\\$, however, we haven't yet put it into practice. The next three lines have switched from function mode into vanilla mode, where we operate on variables. To be more precise, in this program, we only operate on one variable, the **active variable**, represented by the letter `x`. However, `x` can be omitted from commands where it is obviously the other argument.

For example, `+?` is identical to `x+?`, and assigns the input to `x`, but as `x` is the **active variable**, it can be omitted. Next, we output `x`, then entire the while loop, which loops for as long as \\$x \neq 0\\$. The loop is very simple, consisting of a single statement: `$f>x`. All this does is run \\$f(x)\\$, then assign that to `x`, updating `x` on each iteration of the loop.

# Answer
> 1 votes
# Pyth, 12 bytes

```
.u?%N2/N2h*3

```

Try it here as a test suite!

# Answer
> 1 votes
# Common Lisp, 79 bytes

```
(defun x(n)(cons n(if(= n 0)nil(if(=(mod n 2)0)(x(+(* n 3)1))(x(/(- n 1)2))))))

```

Try it online!

# Answer
> 1 votes
# PowerShell, ~~53~~ 52 bytes

```
param($i)for(;$i){$i;$i=(($i*3+1),($i-shr1))[$i%2]}0

```

Try it Online!

**Edit:**
-1 byte thanks to @mazzy

# Answer
> 1 votes
# Stax, 11 bytes

```
₧↑╔¶┘tÇ╣;↑è

```

Run and debug it

# Answer
> 1 votes
# x86 machine code, 39 bytes

```
00000000: 9150 6800 0000 00e8 fcff ffff 5958 a901  .Ph.........YX..
00000010: 0000 0074 04d1 e8eb 066a 035a f7e2 4009  ...t.....j.Z..@.
00000020: c075 dec3 2564 20                        .u..%d

```

Assembly (NASM syntax):

```
section .text
	global func
	extern printf
func:					;the function uses fastcall conventions
	xchg eax, ecx			;load function arg into eax
	loop:
		push eax
		push fmt
		call printf	;print eax
		pop ecx
		pop eax
		test eax, 1	;if even zf=1
		jz even		;if eax is even jmp to even
		odd:		;eax=eax/2
			shr eax, 1
			jmp skip
		even:		;eax=eax*3+1
			push 3
			pop edx
			mul edx
			inc eax
		skip:
		or eax, eax
		jne loop	;if eax!=0, keep looping
	ret			;return eax
section .data
	fmt db '%d '

```

Try it online!

# Answer
> 1 votes
# MathGolf, 12 bytes

```
{o_¥¿½É3*)}∟

```

Try it online!

## Explanation

```
{             Start block of arbitrary length
 o            Output the number
  _           Duplicate
   ¥          Modulo 2
    ¿         If-else with the next two blocks. Implicit blocks consist of 1 operator
     ½        Halve the number to integer (effectively subtracting 1 before)
      É       Start block of 3 bytes
       3*)    Multiply by 3 and add 1
          }∟  End block and make it do-while-true

```

# Answer
> 1 votes
# , ~~66~~ 61 bytes

-5 bytes thanks to Robert S. in consolidating ifelse into `if` and removing brackets, and x!=0 to x\>0

```
print(x<-scan());while(x>0)print(x<-`if`(x%%2,(x-1)/2,x*3+1))

```

instead of

```
print(x<-scan());while(x!=0){print(x<-ifelse(x%%2,(x-1)/2,x*3+1))}

```

Try it online!

# Answer
> 1 votes
# Factor \+ `math.extras`, 56 bytes

```
[ [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ] until-zero ]

```

Try it online!

## Explanation:

* `[ ... ]` A quotation. An anonymous function that lives on the data stack until called or used by a combinator.
* Assuming a data stack with `3` on top when this quotation is called...
* `[ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ]` Push a quotation to the data stack to be used later by `until-zero`. **Stack:** `3 [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ]`
* `until-zero` Call a quotation repeatedly until its output is `0`. **Stack:** `3`
* `.s` Non-destructively print the data stack. **Stack:** `3`
* `dup` Duplicate TOS (top-of-stack). **Stack:** `3 3`
* `odd?` Return `t` if input is odd, else `f`. **Stack:** `3 t`
* `[ 1 - 2/ ]` Push a quotation to be used later by `if`. **Stack:** `3 t [ 1 - 2/ ]`
* `[ 3 * 1 + ]` Push another quotation to be used later by `if`. **Stack:** `3 t [ 1 - 2/ ] [ 3 * 1 + ]`
* `if` Takes a boolean and two quotations from the data stack. Calls the first quotation if the boolean is `t`, otherwise calls the second. (Now inside the first quotation...) **Stack:** `3`
* `1` Push `1` to the data stack. **Stack:** `3 1`
* `-` Subtract TOS from NOS (next on stack). **Stack:** `2`
* `2/` Integer divide by 2. Like doing `x>>1` in many languages. **Stack:** `1`
* Now `until-zero` looks at the data stack and sees TOS is not `0`, so calls its input quotation...

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

```
#include<stdio.h>
int g(int x){printf("%d ",x);x?g(x=x%2?(x-1)/2:3*x+1):0;}

```

Try it online!

# Answer
> 1 votes
# Nim, ~~65~~ 50 bytes (-15 due to xigoi)

```
proc f(n:int)=
 echo n;if n>0:f [n*3+1,n/%2][n%%2]
```

Attempt This Online!

Simple recursive solution cum array-based due to xigoi.

# Answer
> 1 votes
# K (ngn/k), 25 bytes

```
{x>0}{$[2!x;_x%2;1+3*x]}\

```

Try it online!

# Answer
> 1 votes
# Pip, 29 bytes

```
YaWy{PyI%y{Y--y/2}EL{Yy*3+1}}

```

Attempt This Online!

#### Explanation

```
YaWy{PyI%y{Y--y/2}EL{Yy*3+1}}  # implicit input as a command line argument
Ya                             # store the argument in y
  Wy{                       }  # while y != 0:
     Py                        #  print y
       I%y{      }             #  if y is odd:
           Y                   #   store the following in y:
            --y/2              #    (y - 1) / 2
                  EL{      }   #  else:
                     Y         #   store the following in y:
                      y*3+1    #    y * 3 + 1

```

# Answer
> 1 votes
# Nekomata, 11 bytes

```
ᶦ{Z:←½$3*→I

```

Attempt This Online!

```
ᶦ{Z:←½$3*→I
ᶦ{              Iterate until failure:
  Z                 Check if nonzero
   :                Duplicate
    ←               Decrement
     ½              Halve; fails if odd
      $             Swap
       3*           Multiply by 3
         →          Increment
          I         Choose the first value that doesn't fail

```

# Answer
> 0 votes
# perl -Minteger -nlE, 39 bytes

```
{say;$_=$_%2?$_/2:3*$_+1 and redo}say 0

```

# Answer
> 0 votes
# Retina 0.8.2, 46 bytes

```
.+
$*
{*M`1
^(..)+$
$&$&$&$&$&$&111
1(.*)\1
$1

```

Try it online! Explanation:

```
.+
$*

```

Convert to unary.

```
{

```

Repeat until the value stops changing.

```
*M`1

```

Print the value in decimal.

```
^(..)+$
$&$&$&$&$&$&111

```

If it is even, multiply by 6 and add 3.

```
1(.*)\1
$1

```

Subtract 1 and divide by 2.

The trailing newline can be suppressed by adding a `;` before the `{`.

# Answer
> 0 votes
# Red, 70 bytes

```
func[n][print n if n = 0[exit]either odd? n[f n - 1 / 2][f n * 3 + 1]]

```

Try it online!

# Answer
> 0 votes
# Racket, 75 bytes

```
(define(f n)(cons n(if(= n 0)'()(if(odd? n)(f(/(- n 1)2))(f(+(* 3 n)1))))))

```

Try it online!

Equivalent to JRowan's Common Lisp solution.

# Answer
> 0 votes
# C# (.NET Core), 62 bytes

```
a=>{for(;a>0;a=a%2<1?a*3+1:a/2)Console.Write(a+" ");return a;}

```

Try it online!

Ungolfed:

```
a => {
    for(; a > 0;                // until a equals 0
        a = a % 2 < 1 ?             // set a depending on if a is odd or even
                a * 3 + 1 :             // even
                a / 2                   // odd (minus one unnecessary because of int casting)
    )
        Console.Write(a + " "); // writes the current a to the console
    return a;                   // writes a to the console (always 0)
}

```

# Answer
> 0 votes
# Dart, 49 bytes

```
f(n){for(;n>0;n=n%2>0?(n-1)>>1:(n*3)+1)print(n);}

```

Try it online!

# Answer
> 0 votes
# Gambit Scheme (gsi), 74 bytes

```
(define(f n)(if(= 0 n)'()(cons n(f(if(even? n)(+ (* 3 n)1)(/(- n 1)2))))))

```

Try it online!

# Answer
> 0 votes
# dc, 35 bytes

```
[3*1+]0:s[1-2/]1:s[pd2%;sxd0<l]dslx

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), 70 bytes

```
NestWhileList[If[EvenQ@#,3#+1,(#-1)/2]&,#,Unequal,All,\[Infinity],-1]&

```

Try it online!

Longer than previous WL, but *with cycles detection*.

---
Tags: code-golf, math, integer
---


# Question
Title: String with the smallest sum of ASCII values
## Description

In this challenge, you need to write a function that takes in a list of strings and returns the smallest string based on their ASCII value. You should assume that the input list contains only lowercase alphabetical strings.

## Test Cases

```
["a", "b", "c"] => "a"
["hello", "world", "code"] => "code"
["aaa", "aa", ""] => ""
["cat", "bat", "rat"] => "bat"
["zab", "xyz", "abcd"] => "zab"

```

Write the function in as few bytes as possible. The code itself can be a function, process or anything provided that it gives the desired output. Use of other ASCII characters like big or small letters, with space function must be supported.

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
ΣÇO}н

```

Try it online!

#### Explanation

```
ΣÇO}н # Implicit input
Σ  }  # Sort by:
 Ç    #  ASCII values
  O   #  Sum
    н # First item
      # Implicit output

```

# Answer
> 3 votes
# BQN, ~~18~~ 16 bytes

-2 from Dominic van Essen for replacing `'0'` with `@`.

```
{⊑˜⊑⍒(+´@⊸-)¨}

```

Try it online!

### Explanation

```
{⊑˜⊑⍒(+´@⊸-)¨}
{              ¨} 1. For each string in the (monadic) input
{     (  @⊸-)  } 2a. convert the string to (negative) its unicode representation...
{     (+´     )  } 2b. and perform a sum reduction.
{    ⍒(       )  } 3. return descending-sorted indices.
{   ⊑            } 4. take the first.
{⊑˜             } 5. take this index into the input  where ˜ "flips" the next function.

```

# Answer
> 3 votes
# Factor, 22 bytes

```
[ [ sum ] infimum-by ]

```

Try it online!

# Answer
> 3 votes
# Java (JDK), 57 bytes

```
l->l.stream().min((a,b)->a.chars().sum()-b.chars().sum())

```

Try it online!

Takes input as a `List<String>` and returns an `Optional<String>`.

# Answer
> 2 votes
# Vyxal, ~~5~~ 4 bytes

```
‡C∑P

```

Try it Online!

*-1 thanks to @mathcat*

#### Explanation

```
‡C∑P  # Implicit input
‡  P  # Minimum by:
 C    #  ASCII values
  ∑   #  Sum
      # Implicit output

```

Old:

```
C∑)ṡh # Implicit input
  )ṡ  # Sort by:
C     #  ASCII values
 ∑    #  Sum
    h # First item
      # Implicit output

```

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

```
f(s,t,u,i,c)char**s,*t,*u;{for(i=~0,u=0;t=*s;c<i+0U?u=*s,i=c:0,s++)for(c=0;*t;c+=*t++);s=u;}

```

Try it online!

Ungolfed:

```
f(s,t,u,i,c)char**s,*t,*u;{
  for(i=~0, // initialize minimum string sum to largest possible
      u=0; // initialize smallest string (in case of empty list)
      t=*s; // scan list
      c<i+0U?u=*s,i=c:0, // reset minimum string sum and pointer if smaller
      s++)
    for(c=0;*t;c+=*t++); // get string sum
  s=u; // return smallest string
}

```

# Answer
> 1 votes
# Swift, ~~64~~  69 bytes

*Now with fewer compiler crashes!*

```
{$0.map{($0.reduce(0){$0+Int($1.asciiValue!)},$0)}.min{$0.0<$1.0}!.1}

```

SwiftFiddle link

# Answer
> 1 votes
# Python, 44 bytes

```
lambda l:min(l,key=lambda x:sum(map(ord,x)))

```

Attempt This Online!

#### Commented

```
lambda l:                                     # Anonymous function taking l, a list of strings
         min(l,                            )  # Return the minimum of l...
               key=                           # ...using the following function:
                   lambda x:                  #  Function taking x, a string
                            sum(          )   #  Sum the following:
                                map(ord,x)    #  Convert all characters to ASCII values

```

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

```
a=>a.sort(g=(x,y)=>x>=x&&~~eval(Buffer(x).join`+`)-g(y))[0]

```

Try it online!

### Commented

```
a =>            // a[] = input array
a.sort(g =      // g is a recursive callback function
  (x, y) =>     // for each pair (x, y) to be tested:
    x >= x &&   //   stop if x is undefined
    ~~eval(     //   otherwise, evaluate as JS code:
      Buffer(x) //     the ASCII codes of x
      .join`+`  //     joined with '+'
    )           //   end of eval()
    - g(y)      //   subtract the result of a recursive call with x = y
)               // end of sort()
[0]             // keep the first entry

```

# Answer
> 1 votes
# Japt `-g`, 4 bytes

Takes input as an array of character arrays.

```
ñÈxc

```

Try it

```
ñÈxc     :Implicit input of 2D array
ñ        :Sort by
 È       :Function
  x      :  Sum of
   c     :    Codepoints
         :Implicit output of first element

```

# Answer
> 1 votes
# Zsh +old utils, 47 ~~55~~ ~~103~~ bytes

Using the filesystem and the old System V `sum`* command:

```
for i;echo $i>$[++n];set `sum -s *|sort -n`;<$3

```

Try it online! ~~55 bytes~~

* On MacOS, `cksum -o2` is equivalent to GNU `sum -s`. According to Wikipedia, the BSD checksum algorithm is "useless from a security perspective"

---

#### 103 bytes, using arrays and builtins only:

```
for x;{w=;for a (${(s::)${x:?}})((w+=#a));k+=($w)}
for i ({1..$#})((k[i]==$(printf ${(n)k})))&&<<<$@[i]

```

Try it online!
Explanation of code is in earlier revisions of this answer

# Answer
> 1 votes
# Excel, 78 bytes

```
=LET(x,A1#,y,ROW(A:A),@SORTBY(x,MMULT(TOROW(y^0),IFERROR(CODE(MID(x,y,1)),))))

```

where `A1#` is a *horizontal* spilled range containing the strings.

# Answer
> 1 votes
# Stax, ~~9~~ 5 bytes

*And pure ASCII!*

```
{|+}e

```

Run and debug it (with test cases)

# Explanation

```
{  }e # minimum by
 |+   # sum

```

# Answer
> 1 votes
# Jelly, 5 bytes

```
OS$ÞḢ

```

Try it online!

#### Explanation

```
OS$ÞḢ  # Main link
  $    # Last two links as a monad:
O      #  Ordinals
 S     #  Sum
   Þ   # Sort the input by this monad
    Ḣ  # First item (minimum)

```

# Answer
> 1 votes
# Pip, 12 bytes

```
@Y{$+A*a}SKg

```

Attempt This Online!

#### Explanation

```
@Y{$+A*a}SKg  ; Input on command line
           g  ; Input list
  {     }SK   ; Sorted by:
   $+         ;  Sum of
     A*       ;  ASCII values of
       a      ;  The string
@Y            ; First item (minimum)
              ; Implicit output

```

# Answer
> 1 votes
# Raku, 17 bytes

```
*.min(*.ords.sum)

```

Try it online!

`*.ords.sum` is an anonymous function that calculates the sum of the ordinal values of its string argument. That function is passed as the argument to `*.min`, which returns the element of the input list with the smallest value computed by the first function.

# Answer
> 1 votes
# Burlesque, 9 bytes

```
{)**++}<m

```

Try it online!

```
{
 )** # Map to ord
 ++  # sum
}<m  # Minimum by

```

# Answer
> 1 votes
# janet, 51 bytes

```
(fn[l](((sort-by first(map(fn[x][(sum x)x])l))0)1))

```

in janet, you can save bytes by not using spaces between brackets, which i personally think is very ugly for a lisp-like language, so here's an de-uglified version and an example

```
(fn [l] (((sort-by first (map (fn [x] [(sum x) x]) l)) 0) 1))

```

```
$ janet
Janet 1.29.1-20230709 openbsd/x64/clang - '(doc)' for help
repl:1:> (def F (fn[l](((sort-by first(map(fn[x][(sum x)x])l))0)1)))
<function 0x028B13B5F580>
repl:2:> (F ["zab" "xyz" "abcd"])
"zab"

```

# Answer
> 0 votes
# Arturo, 42 bytes

```
$=>[minimum&=>[∑to[:integer]to[:char]&]]

```

Try it

# Answer
> 0 votes
# Retina 0.8.2, 74 bytes

```
.
$&$&96$*~
0T1`l`L`\w\w
{`[J-Z]
9$&
}T`_L`dL
\d
$*~
+`(\w)~
~$1
O`
1G`
~

```

Try it online! Only accepts strings of lowercase letters. Explanation:

```
.
$&$&96$*~

```

Duplicate each letter and suffix 96 `~`s to each pair.

```
0T1`l`L`\w\w

```

Uppercase alternate letters.

```
{`[J-Z]
9$&
}T`_L`dL

```

Map uppercase letters into digits that sum to their index i.e. `A=1` to `Z=998`.

```
\d
$*~

```

Expand the digits into that many `~`s.

```
+`(\w)~
~$1

```

Move all of the `~`s to the beginning of the string.

```
O`

```

Sort the strings into order. Since `~` sorts after `z`, this means that the string with the fewest `~`s will sort first.

```
1G`

```

Keep only the first string.

```
~

```

Delete the `~`s.

# Answer
> 0 votes
# Charcoal, 15 bytes

```
ＵＭθ⟦↨Ｅι℅λ¹ι⟧⊟⌊θ

```

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

```
ＵＭθ⟦↨Ｅι℅λ¹ι⟧

```

Calculate the sum of ASCII values for each string.

```
⊟⌊θ

```

Output the string with the smallest sum.

# Answer
> 0 votes
# PowerShell Core, 55 bytes

```
($args|Sort-Object{"$($_|% t*y|%{'+',+$_[0]})"|iex})[0]

```

Try it online!

# Answer
> 0 votes
# Pyth, 6 bytes

```
.msCMb

```

Try it online!

# Answer
> 0 votes
# Husk, 2 bytes

```
◄Σ

```

Try it online!

```
◄     # minlon: Element that minimizes function result
 Σ    # chrsum: Sum of code points

```

# Answer
> 0 votes
# BQN, ~~15~~ 14 bytes

```
⊑∘⍋∘(+´¨-⟜@)⊑⊢

```

Try it at BQN REPL

```
⊑∘⍋∘(+´¨-⟜@)⊑⊢
    (  ¨    )       # for each element of input
        -⟜@         #   subtract the null character from each letter
                    #   (thereby getting codepoint values)
     +´             #   and sum by fold-addition
⊑∘                  # now get the first element of
  ⍋∘                # the indices of sorted elements
             ⊑      # and use this to select from
              ⊢     # the elements of the input

```

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


# Question
Title: Shortest Code to Find the Smallest Missing Positive Integer
## Description

Given an unsorted array of integers, find the smallest positive integer that does not appear in the array. Your task is to write the shortest code possible to solve this problem.

## Input

A non-empty or empty array of integers, where the integers may be negative, zero, or positive.

## Output

The smallest positive integer that does not appear in the array.

## Test cases

Input: `[1, 2, 3]`
Output: 4

Input: `[3, 4, -1, 1]`
Output: 2

Input: `[7, 8, 9, 11, 12]`
Output: 1

Input: `[-5, -4, -3, -2, -1, 0, 1, 2, 3, 5, 7, 10]`
Output: 4

Input: `[]`
Output: 1

Input: `[-1, -4, -7]`
Output: 1

Scoring criteria: Your score is the number of bytes in your code, as counted by the bytecount tool. The code with the smallest number of bytes wins. In the case of a tie, the earlier submission wins.

```
var QUESTION_ID=258335,OVERRIDE_USER=117038;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Nekomata \+ `-1`, 4 bytes

```
ŇPᵖf

```

Attempt This Online!

The flag `-1` set the interpreter to `FirstValue` mode, which prints the first possible result.

```
Ň        Non-deterministically choose an natural number
 P       that is positive
  ᵖ      and such that
   f     the input doesn't contain this number

```

---

## Nekomata v0.1.0.0 \+ `-1`, 6 bytes

```
ℕPᵖ{-Z

```

This is the original answer in an old version of Nekomata. Some symbols are changed in newer versions.

```
ℕ        Non-deterministically choose an natural number
 P       that is positive
  ᵖ{     and such that
    -Z   it minus the input doesn't contain any zero

```
> 12 votes

# Answer
# Nibbles, ~~3~~ 2 bytes (4 nibbles)

```
/-,~

```

I somehow didn't expect that `fold`-ing over an infinite list, starting from infinity (the right-hand end) would work, but it does.

```
/-,~    # full function
/-,~$$  # (with implicit arguments shown):
 -      # remove
    $   #   elements of the input list
        # from
  ,~    #   the infinite list of positive integers
/       # now fold over this infinite list from the right
     $  # each time returning the left-hand argument
  -     # (so, finally, returning the first (left-most) element)

```
> 8 votes

# Answer
# Zsh, 21 bytes

```
seq inf|grep -xvm1 $1

```

Attempt This Online!

* `seq inf`: list of all positive integers
* `grep`: filter those for
    + `$1`: any of the lines in the input
    + `-v`: inverted match (i.e., it must not match any of the input items)
    + `-x`: match whole lines, not substrings
    + `-m1`: output only the first matching line
> 7 votes

# Answer
# Brachylog, ~~7~~ ~~6~~ 5 bytes

```
ℕ₁≜¬∈

```

Try it online!

*-1 stealing Fatalize's solution to the dupe target--note that my ~~accepted~~ reverted golf suggestion fails on the empty list. Whoops*

Reversed I/O.

```
ℕ₁       The output is a positive integer.
  ≜      Try every value for it until one
   ¬∈    isn't in the input.

```
> 5 votes

# Answer
# flax, 7 bytes

```
∵µḟκ→A∴

```

Attempt This Online!

## Explained

```
∵µḟκ→A∴
∵        ⊳ min of
   κ→A∴  ⊳ range(1, abs(max(input)) + 2)
  ḟ      ⊳ set diff with input

```
> 5 votes

# Answer
# JavaScript (ES6), 33 bytes

```
a=>a.reduce(m=>m+a.includes(m),1)

```

Try it online!
> 5 votes

# Answer
# Jelly, 4 bytes

```
1ḟ1#

```

Try it online!

```
  1#    Find the first integer
1       starting from 1
 ḟ      which is not empty with elements of the list filtered out.

```
> 4 votes

# Answer
# x86-64 machine code, 13 bytes

```
31 C0 FF C0 89 F1 57 F2 AF 5F 74 F6 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of an array of 32-bit integers in RDI and its length in ESI, and returns a 32-bit integer in EAX.

In assembly:

```
f:  xor eax, eax    # Set EAX to 0.
r:  inc eax         # Increase EAX by 1.
    mov ecx, esi    # Set ECX to the length.
    push rdi        # Save the value of RDI onto the stack.
    repne scasd     # Compare EAX and the value at address RDI,
                    #  advancing the pointer and counting down ECX,
                    #  and repeat as long as the result is unequal and ECX≠0.
    pop rdi         # Restore the value of RDI from the stack.
    je r            # Jump back if the last comparison result was equal.
    ret             # Return.

```
> 4 votes

# Answer
# Python 3, 38 bytes

```
f=lambda a,i=1:i in a and f(a,i+1)or i

```

A recursive function that accepts the list and returns the first missing positive integer.

**Try it online!**
> 4 votes

# Answer
# Pyth, 3 bytes

```
-#Q

```

Try it online!

This challenge is extremely well-suited for Pyth. Let's go through it step by step:

* `#`: This is the filter function. The predicate function that is used as the filter is `-TQ`, where `T` is the variable representing the values being filtered over. No explicit input is given. When no input is given, `#` outputs the first positive integer for which the predicate function gives a truthy output.
* `-`: This is subtraction function. It is called on `T`, a positive integer, and `Q`, the input list for the program. When `-` is called with an integer followed by a list, it returns a singleton list containing the integer, if the integer is absent from the list, or else an empty list.

Here's an equivalent Python program to the above Pyth program, to hopefully make it clearer what's going on.

```
import ast
Q = ast.literal_eval(input())
T = 1
while True:
    subtract_in = [T]
    subtract_out = [elem for elem in subtract_in if elem not in Q]
    if subtract_out:
        print(T)
        break
    T += 1

```

Try it online!
> 4 votes

# Answer
# Vyxal,  ~~6 5~~  4 bytes

```
?F)ṅ

```

Try it Online!

*-2 thanks to @lyxal*

#### Explanation

```
?F)ṅ  # Implicit input
  )ṅ  # First integer where:
?F    #  Remove elements from the input which are in this number
      #  (i.e. is the number not in the input)

```
> 3 votes

# Answer
# Haskell \+ hgl, 10 bytes

```
he<df[1..]

```

Attempt This Online!

My first hgl answer. Returns the first element of the "set" difference of the input from the positive integers.

Potential useful additions (or that I couldn't find):

* a two or three byte alias for `[1..]`
* find the first item in the list matching a predicate (`(hd<)<fl`)
* find the first positive integer matching a predicate (a special-cased combination of the above two; like Jelly's `#`)
* (I didn't use it in the code itself, but in the footer), `read` Maybe there's some fancy equivalent in `P.Parse`, but I couldn't find it

I'd like to set up an instance of hoogle for hgl - it would make searching for things easier.
> 3 votes

# Answer
# Zsh, 31 bytes

Unlike pxeger's answer, no external programs, just pure shell constructs.

```
<<<${${${:-{1..1$#}}:|argv}[1]}

```

Try it online!

```
       ${:-{1..1$#}}             # List from 1 to a number bigger than the length of the list.
                                 # It's shorter to prepend a "1" than to add 1.
     ${             :|argv}      # :| set difference with the list
<<<${                      [1]}  # print the first result

```
> 3 votes

# Answer
# , 31 bytes

```
\(x,y=seq(c(1,x)))y[!y%in%x][1]

```

Attempt This Online!
> 3 votes

# Answer
# , 27 bytes

```
\(x){while(T%in%x)T=T+1;+T}

```

Attempt This Online!

Naive approach. For a clever one (and currently longer) see @Dominic van Essen's answer.
> 3 votes

# Answer
# Haskell, 30 bytes

```
f a=filter(`notElem`a)[1..]!!0

```

Try it online!
> 3 votes

# Answer
# Jelly, 6 bytes

```
ṀŻ‘ḟ³Ṃ

```

Try it online

### Explanation

```
ṀŻ‘ḟ³Ṃ  #                  | [-1, 0, 1, 4]
Ṁ       # Maximum          | 4
 Ż      # Range from 0     | [0, 1, 2, 3, 4]
  ‘     # Increment        | [1, 2, 3, 4, 5]
   ḟ    # Filter out items |
    ³   # In the input     | [2, 3, 5]
     Ṃ  # Minimum          | 2

```
> 2 votes

# Answer
# Perl 5 -ap, 20 bytes

```
1while++$i~~@F;$_=$i

```

Try it online!
> 2 votes

# Answer
# Japt, 6 bytes

```
@øX}f1

```

Try it

```
@øX}f
@  }f  # first positive integer where the following is false:
 øX    # the array contains the integer

```
> 2 votes

# Answer
# Desmos, ~~70~~ 65 bytes

```
j=join(x,0)
l=[isgn(i-j)^2.minfori=[1...j.max+1]]
f(x)=l[l>0].min

```

Try it on Desmos!

-5 bytes thanks to Aiden Chow.
> 2 votes

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

```
{(~^x?)(1+)/1}

```

Try it online!

Sets up a while-reduce, seeded with `1`, that proceeds to the next iteration (adding one) if the current value is already present in the original input.
> 2 votes

# Answer
# PowerShell Core, 22 bytes

```
for(;++$i-in$args){}$i

```

Try it online!

Takes the input array using splatting, returns an integer
> 2 votes

# Answer
# Julia, ~~36~~ 33 bytes

```
~x=argmax(!in(x),1:1+max(0,x...))

```

Attempt This Online!

Returns the first index of range \[1,max+1\] that isn't in the input. To accommodate the empty list, the input is padded with `0`.

* -3 bytes thanks to MarcMush: replace `findfirst` with `argmax`
* -2 bytes thanks to MarcMush: replace`0∪x...` with `0,x...`
> 2 votes

# Answer
# Julia 1.0, 26 bytes

```
>(x,i=1)=i∈x ? x>i+1 : i

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~5~~ 4 bytes

```
∞IKн

```

Try it online!

*-1 thanks to @KevinCruijssen*

#### Explanation

```
∞IKн  # Implicit input
∞     # Push the infinite list [1, 2, 3, ...]
 IK   # Remove the elements of the input
   н  # First item

```

Old:

```
∞å0k>  # Implicit input
∞      # For each number in the infinite list [1, 2, 3, ...]
 å     # Is it in the input?
  0k   # Get the index of the first 0 (0-indexed)
    >  # And increment it to make it 1-indexed

```
> 1 votes

# Answer
# Charcoal, ~~13~~ 10 bytes

```
Ｉ⌊⁻…·¹⊕Ｌθθ

```

Try it online! Link is to verbose version of code. Explanation: Now a port of @GammaFunction's jq answer.

```
   …·       Inclusive range from
     ¹      Literal integer `1` to
        θ   Input list
       Ｌ    Take the length
      ⊕     Incremented
  ⁻             Set difference with
         θ  Input list
 ⌊          Take the minimum
Ｉ           Cast to string
            Implicitly print

```

Would have been 6 bytes if the input had been guaranteed to be a nonempty list of positive integers:

```
Ｉ⌊⁻⊕θθ

```

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

```
    θ   Input list
   ⊕    Vectorised increment
  ⁻     Set difference with
     θ  Input list
 ⌊      Take the minimum
Ｉ       Cast to string
        Implicitly print

```
> 1 votes

# Answer
# Japt, 6 bytes

```
@øX}f1

```

Try it

```
@øX}f1     :Implicit input of array U
@          :Function taking an integer X as argument
 øX        :  Does U contain X
   }       :End function
    f1     :Get the first integer >=1 that returns false

```
> 1 votes

# Answer
# Excel, 61 bytes

```
=@LET(a,A1#,b,SEQUENCE(MAX(a,-a)+1),SORTBY(b,XMATCH(b,a),-1))

```

Input is spilled array `A1#`.
> 1 votes

# Answer
# Arturo, 26 bytes

```
$[a][min--@1..+1max a++1a]

```

Try it

```
$[a][              ; a function taking an argument a
    min            ; the minimum element of
    --             ; the set difference of
    @              ; the array of
    1..            ; the range from one to
    +1             ; one plus
    max            ; the maximum element of
    a++1           ; a with 1 appended (for empty input)
    a              ; and a -- the second argument to set difference
]                  ; end function

```
> 1 votes

# Answer
# JavaScript (Node.js), ~~35~~ 34 bytes

```
a=>(g=i=>a.includes(++i)?g(i):i)``

```

Try it online!

Port of Jonathan Allan's Python answer.

*-1 thanks to @Shaggy*
> 1 votes

# Answer
# MATL, 6 bytes

```
`@Gm}@

```

Try it at MATL Online! Or verify all test cases.

### Explanation

```
`      % Do...while
  @    %   Push interation index, 1-based
  G    %   Push input
  m    %   Ismember. Gives true or false
}      % Finally (i.e. execeute when exiting the loop)
  @    %   Push iteration index
       % End (implicit). A new iteration is run if top of the stack is true
       % Display (implicit)

```
> 1 votes

# Answer
# Python 3 NumPy, 31 bytes

```
lambda a:min({1,*a+(a>0)}-{*a})

```

Try it online!

Expects a numpy array.

## How?

Returns 1 if that's not in a and otherwise the smallest successor of a positive number in a that's not in a.
> 1 votes

# Answer
# Python 3, 38 bytes

```
lambda a:[*{*range(len(a)+2)}-{*a}][1]

```

Uses set differences to get the missing number after removing negative numbers.

Try it online!

-22 bytes by using `{}` to make set. And no need to check if positive
> 1 votes

# Answer
# Swift, 46 bytes

```
var l={(a:[_])in(1...).first{!a.contains($0)}}

```

The type signature `[_]` tells the compiler to infer the `Array`'s `Element` type via type inference (possible thanks to the `1...` range).
> 1 votes

# Answer
# TI-BASIC, 17 bytes

##

```
1
While sum(Ans=L1
Ans+1
End
Ans

```

We first put 1 in Ans for the first pass of the loop. Because we're using the While loop the condition will be checked first before the loop runs and 1 will return if it's not in the list. The condition returns a list with the operation against each element so for example a list {1,2,3 will turn to {1,0,0 then sum to 1 and pass the condition allowing the loop to continue. the loop itself then can track the counter in Ans instead of needing to store to a variable. After the loop finishes we use the implicit final line Disp to display the value in Ans.
> 1 votes

# Answer
# jq, 26 bytes

```
[range(1;length+2)]-.|.[0]

```

Try it online!

| Input: | `.` | `[]` | `[5,1,0,1]` |
| --- | --- | --- | --- |
| Need to add 2 because `range` isn't inclusive | `length+2` | `2` | `6` |
| `[]` makes it a list | `[range(1;length+2)]` | `[1]` | `[1,2,3,4,5]` |
| `LIST - LIST` is set difference | `[range(1;length+2)]-.` | `[1]` | `[2,3,4]` |
| Select first element | `[range(1;length+2)]-.|.[0]` | `1` | `2` |
> 0 votes

# Answer
# Python, 66 bytes

```
lambda l:min(i for i in range(1,abs(max(l or[1]))+2)if i not in l)

```

Attempt This Online!

## Whython, 57 bytes

```
lambda l:min(i for i in range(1,max(l)+2)if i not in l)?1

```

Attempt This Online!

Whython's `?` command catches the error of either from either `max` or `min`.
> 0 votes

# Answer
# Haskell, 31 bytes

```
import Data.List
head.([1..]\\)

```

A port of pxeger's answer using only the standard library. I quite like the approach using Haskell's lazyness.
> 0 votes

# Answer
# MathGolf, 9 bytes

```
1▐╙)╒\-├Þ

```

Try it online.

**Explanation:**

```
1▐         # Append a 1 to the (implicit) input-list
  ╙        # Pop and push its maximum
   )       # Increase it by 1
    ╒      # Pop and push a list in the range [1,max+1)
     \     # Swap so the (implicit) input-list is at the top of the stack
      -    # Remove all those values from the ranged list
       ├   # Push its first item (without popping unfortunately)
        Þ  # Only keep the top item of the stack
           # (after which the entire stack is output implicitly as result)

```
> 0 votes

# Answer
# Raku, 19 bytes

```
{first *∉$_,1..*}

```

Try it online!

Returns the `first` element of the lazy sequence of positive integers `1 .. *` such that the number is not an element of the input list: `* ∉ $_`.
> 0 votes

# Answer
# Wolfram Language (Mathematica), 25 bytes

```
1//.x_/;#~MemberQ~x:>x+1&

```

Try it online! (verifies all test cases) Exact same implementation as this earlier answer of mine, except testing whether the temporary variable is a member of the input rather than divides the input. (Has the same limitation as that answer, that Mathematica's default recursion limit is 65536.)
> 0 votes

# Answer
# Factor \+ `lists.lazy math.unicode`, 36 bytes

```
[ 1 lfrom [ ∌ ] with lfilter car ]

```

Try it online!

* `1 lfrom` the natural numbers
* `[ ∌ ] with lfilter` select the numbers that are not in the input
* `car` get the first one
> 0 votes

# Answer
# PHP -F, 35 bytes

```
for(;in_array(++$i,$argn););echo$i;

```

Try it online!

I did something a bit unusual here, as command-line arguments give a string, and question says we are provided an array, is to decode the string off the byte count. If you think this is wrong I will include it in the count
> 0 votes

# Answer
# Java 8 (OpenJDK 8), 53 bytes

Solution using inline stream :

```
l->l.stream().sorted().reduce(1,(a,b)->a<b|b<1?a:b+1)

```

Try it online!
> 0 votes

# Answer
## Pascal, 160 bytes

This `function` requires a processor compliant to at least ISO standard 7185 “Standard Pascal”, level 1. Note, in Pascal it is not possible to specify “empty arrays”, therefore the fifth test case is not applicable.

```
function f(x:array[m..n:integer]of integer):integer;var s:set of integer;i:integer;begin s:=[];for i:=m to n do s:=s+[x[i]];i:=1;while i in s do i:=i+1;f:=i end

```

Ungolfed (Extended Pascal, ISO standard 10206, level 1):

```
type
    natural = 1..maxInt;
    integerWithoutMaxint = -maxInt..pred(maxInt);

function naturalSupremum(
        { This is a “conformant-array parameter”. It permits us writing a
          generic routine without specifying the array’s size in advance. }
        sample: array[indexMinimum..indexMaximum: integer] of integerWithoutMaxint
        { The `array` may not contain the value `maxInt`, hence the restriction
          to `integerWithoutMaxint`. Otherwise the `result := result + 1;` will
          overflow if all values in the interval [1, maxInt] are present. }
    ): natural;
var
    range: set of integer value [];
    i: type of indexMinimum;
    result: natural value 1;
begin
    { transform ordered list to “unordered” `set` -------------------- }
    for i := indexMinimum to indexMaximum do
    begin
        range := range + [sample[i]];
    end;

    { analyze step: find first `natural` not part of set ------------- }
    while result in range do
    begin
        result := result + 1;
    end;

    { In Pascal there must be exactly _one_ assignment to the
      implicit result variable bearing the same name as the function. }
    naturalSupremum := result
end;

```
> 0 votes

# Answer
# Python 3 REPL, 52 bytes

```
next(i for i in range(1,max(_+[0])+2) if i not in _)

```

Returns the first integer in the range `[1, (maximum of input and 0) + 2)`, that is not present in the input.

Replacing `max(_+[0])+2` with `10**9` saves 7 bytes, but assumes the input it short enough.

Using the REPL so we can take the input as variable `_`.
> 0 votes

# Answer
# BQN, 17 bytes

```
{1+⊑/¬(«↕2+≠)∊}

```

Try it online!

### Explanation

```
{1+⊑/¬(«↕2+≠)∊}
{     (      )∊} 1. Is the input in...
      ( ↕    )    2a. the natural numbers from 0 to...
      (  2+≠)    2b. the length of the input plus 2...
      («     )    2c. left-shifted (to get rid of 0)
{    ¬          } 3. in -> not in
    /             4. Which indices are true
 1+⊑              5. Take the first (add 1 due to 0-indexing)

```
> 0 votes

# Answer
# C (gcc), ~~58~~ 57 bytes

*1 byte saved thanks to @ceilingcat!*

```
i;c;f(a,k)int*a;{for(i=0,c=1;i<k;i=c-a[i]?i+1:!c++);a=c;}

```

Try it online!

Takes as input a pointer to the start of an integer range, and the number if integers in said range.

I almost had 44 bytes with the beautiful-looking recursive `i;f(a,k)int*a;{a=k?i+=(i=f(a,--k))==a[k]:1;}`, but this unfortunately doesn't work on specific unsorted arrays, such as `[1, 4, 3, 2]`. :(

`i=0,c=1` feels clunky and long but I don't see a way to eliminate it.

## Explanation

Abusing K&R C implementation for saving lots of bytes:

* `i;c;` instead of `int i,c;` for some global variables
* `f(a,k)int*a;` instead of `int f(int*a,int k)`
* `c-a[i]` instead of `c!=a[i]`
* `i=...?i+1:!c++` instead of `if(...)i++;else i=0,c++;`
* `a=c;` instead of `return c;`
> 0 votes

# Answer
# Python 3, 41 bytes

```
lambda x:min({1,*range(max(x)+2)}-{0,*x})

```

Try it online!

A non-recursive approach that works by generating the set of all possible numbers it could be (and 0), removing the ones it can't be, and selecting the smallest remaining number.

Alternatively, `range(1,max(x)+2)` and `{*x}`, but that looks less fun :\>
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
ƘƇ~

```

Try it online!

#### Explanation

```
ƘƇ~  # Implicit input
Ƙ    # First integer where:
 Ƈ~  #  Not in input
     # Implicit output

```
> 0 votes

# Answer
# Rust, 39 bytes

```
|v:Vec<_>|(1..).find(|i|!v.contains(i))

```

Attempt This Online!

Now the thing with this solution is it returns `Some(n)`; not sure if that's allowed. So here is a solution which returns an integer instead:

# Rust, 48 bytes

```
|v:Vec<_>|(1..).find(|i|!v.contains(i)).unwrap()

```

Attempt This Online!
> 0 votes

# Answer
# Scala, 61 bytes

Port of @Jonathan Allan's Python code in Scala.

---

Golfed version. Try it online!

```
def f(a:Seq[Int],i:Int=1):Int=if(a.contains(i))f(a,i+1)else i

```
> 0 votes

---
Tags: code-golf, array, algorithm
---


# Question
Title: When in {country}, do as the {countrians} do
(or: Output the plural demonym.)

When in Rome, do as the Romans do. This is a well-known English phrase meaning that it’s best to follow what others are doing around you — to go with the flow. Today, you're going to rewrite the phrase to fit most (Western) place names.

To get the name of a group that lives within a region, there are a couple of cases:

* If the name ends with an ‘i’, ‘o’, or ‘u’, append ‘ans’. If the name ends with an ‘e’ or ’a’, drop it and append ’ans’.
* If the name ends with a ‘y’, replace it with an ’i’ if the preceding character is a consonant, and finally append ‘ans‘.
* If the name ends in a consonant (excluding ‘y’), append ‘ians’.

Some examples:

* “Italy” ends with a consonant followed by a ‘y’, so we replace the ‘y’ with an ‘i’ and append ‘ans’ to get “Italians”.
* “Rome” ends with an ‘e’, so we drop it and append ‘ans’ to get “Romans”.
* “Hungary” → “Hungarians”
* ”Paraguay” → “Paraguayans”.

So, your task is: Given a name starting with an uppercase letter and ending with a lowercase letter, output the name of that group of people.

This is , so the shortest code per language wins! Defaults for code-golf apply.

## Test cases:

When in Rome, do as the Romans do.

When in Transylvania, do as the Transylvanians do.

When in Code Golf, do as the Code Golfians do.

When in Hawaii, do as the Hawaiians do.

When in Sparta, do as the Spartans do.

When in America, do as the Americans do.

When in South Dakota, do as the South Dakotans do.

When in Korea, do as the Koreans do.

When in India, do as the Indians do.

(And yes, I know there are plenty of outliers, e.g. group names ending in ‘stani’, ‘ese’, ‘er’, etc. However, this formula seems to work for many English place names.)

# Answer
> 9 votes
# Lexurgy, ~~72~~ 65 bytes

```
y:
{y,*}=>i/!{a,e,i,o,u,y} _ $
a:
{e,a}=>ans/_ $
Else: *=>ans/_ $

```

Expects input as just the country name, and outputs the plural demonym.

Requires that spaces in the input be replaced with some non-space character due to how Lexurgy processes spaces.

* -7 bytes by @SuperStomer by using `else`

Used test cases:

```
Italy
Rome
Hungary
Paraguay
Transylvania
Code_Golf
Hawaii
Sparta
America
South_Dakota
Korea
India
Noodle
Noodly
Noodley
Ay
By
Aby
Bay
Ohio

```

# Answer
> 8 votes
# K (ngn/k), 40 bytes

```
{_[-~0 3'a;x],(0<a:"yeaiou"?*|x)_"ians"}

```

Try it online!

# Answer
> 7 votes
# sed, 35 bytes

Using sed with extended regexes:

`s/([^aeiouy])y?$/\1i/;s/[ea]?$/ans/`

# Answer
> 6 votes
# Retina 0.8.2, 31 bytes

```
([^aeiouy])y?$
$1i
r`[ea]?$
ans

```

Try it online! Link includes test cases. Explanation:

```
([^aeiouy])y?$
$1i

```

Add `i`s after trailing consonants and replace consonant + `y` with consonant + `i`.

```
r`[ea]?$
ans

```

Remove any trailing `e` or `a` and append `ans`. The `r`` is needed to prevent a second empty match after removing the trailing `e` or `a`.

# Answer
> 3 votes
# Charcoal, 38 bytes

```
Ｐ←⮌ＳＭ⁼ＫＫy←¿№aeiouＫＫＭⅈ←«→Ｐi»Ｍ¬№aeＫＫ→ans

```

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

```
Ｐ←⮌Ｓ

```

Write the input to the canvas, but with the last letter under the cursor and the first letter to the left.

```
Ｍ⁼ＫＫy←

```

Move left if the last letter is a `y`.

```
¿№aeiouＫＫ

```

If the (previous) letter is a vowel, then...

```
Ｍⅈ←

```

... move back to the last letter, otherwise...

```
«→Ｐi»

```

... move right and place an `i`, which either overwrites a trailing `y` or appends if there was no trailing `y`.

```
Ｍ¬№aeＫＫ→

```

Move right unless the last letter is an `a` or an `e`.

```
ans

```

Overwrite the `a` or `e` with `ans` or append `ans` otherwise.

# Answer
> 3 votes
# 05AB1E, 33 bytes

```
žPSD'y«s„aeS)vDyÅ¿àiNi'i«ë¨]…ans«

```

Try it online or verify all test cases.

**Explanation:**

```
žP              # Push all consonants (minus "y")
  S             # as a list of characters
D'y«           '# Duplicate it, and append an "y" to each consonant
    s           # Then swap so the consonant-list is at the top again
„aeS            # Push pair ["a","e"]
)               # Wrap all three items on the stack into a list
 v              # Pop and loop over this triplet of lists:
  D             #  Duplicate the current string
                #  (which will be the implicit input in the first iteration)
       i        #  If
    Å¿          #  the current string ends with
      à         #  any of the items of
   y            #  the current list of the loop:
        Ni      #   If this is the second iteration (the 0-based index is 1):
          'i«  '#    Append an "i" to the string
         ë      #   Else (index is 0 or 2):
          ¨     #    Remove the last character instead
 ]              # Close both the if-else statement and loop
  …ans«         # Append string "ans"
                # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Python, 119 bytes

-5 bytes thanks to `noodle man`.

```
lambda c,v='iouea',s='ans':(((c+'i'+s,(k:=c[:-1])+'iy'[c[-2]in v]+s)['y'==(l:=c[-1])],k+s)[l in v[3:]],c+s)[l in v[:3]]

```

Attempt This Online!

# Answer
> 2 votes
# JavaScript (SpiderMonkey), 96 bytes

```
x=>((p=[...x])[l=x.length-1]=`${"iou"[c="contains"](r=p[l])?r:!"ae"[c](r)?"i":""}ans`)&&p.join``

```

Try it online!

# Answer
> 2 votes
# Python \>= 3.8, 173 bytes

```
import re
lambda k:any((l:=re.subn(a,b,k))[1]for a,b in map(lambda m:f'({m}ans'.split('|'),(r'\w[iou])$|\1',r'\w)[ea]$|\1',r'[aeiou]y)$|\1',r'[^aeiou])y$|\1i','$)|i')))*l[0]

```

`any` stops iterating after the first truthy result (in this case, when `subn` replaces at least 1 time)

ATO! (`f =`  added to run test cases)

# Answer
> 1 votes
# Vyxal , 186 bitsv2, 23.25 bytes

```
÷‛aeF:\y=¨iȮ:\o+Ah¬\i*`□⟑

```

Try it Online!

---
Tags: code-golf, string, natural-language
---