title: Integer Lists of Noah

text:
# Question
Title: Integer Lists of Noah
## Introduction:

I think we've all heard of it, but here a very brief summary: Noah gathered two of every species of animal on the planet, male and female, to save in his Ark during a great flood. The actual quote from the Bible is:

> *Genesis 7:2-3*
> You must take with you seven of every kind of clean animal, the male and its mate, two of every kind of unclean animal, the male and its mate, and also seven of every kind of bird in the sky, male and female, to preserve their offspring on the face of the earth.
> source

But for the sake of this challenge we will ignore the clean/unclean part and the part where he took seven of each animal. This challenge is only about this part:

> two of every kind of ~~unclean~~ animal, the male and its mate

## Challenge:

**Input:**

You are given a list of positive integers (in random order).

**Output:**

Two distinct values indicating whether it's a 'List of Noah' or not. This doesn't necessary have to be a truthy/falsey value, so could also be `0`/`1` in Java/C#, or `'A'`/`'B'` in any language, to give some examples.

When is a list a 'List of Noah'? When there are exactly two of every integer in the list.

## Challenge rules:

* I/O is flexible. Input can be a list/array/stream of integers/floats/strings, or read one by one from STDIN. Output can be any two ***distinct*** values, returned from a function or output to STDOUT / a file.
* The integers in the input-list are in random order, and are guaranteed to be positive within the range \\$1\leq n\leq100000\\$.
* The input-list is guaranteed to be non-empty.
* Having an integer a multiple of two times present above 2 (i.e. 4, 6, 8, etc.) will be falsey. I.e. `[6,4,4,6,4,7,4,7]` is falsey, although you could still create equal pairs like this: `[[4,4],[4,4],[6,6],[7,7]]`.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Truthy:
[7,13,9,2,10,2,4,10,7,13,4,9]
[1,2,3,1,2,3]
[10,100,1000,1,100,10,1000,1]
[123,123]
[8,22,57189,492,22,57188,8,492,57188,57189,1,1]

Falsey:
[6,4,4,6,4,7,4,7]
[2,2,2,2,2,2]
[5,1,4,5,1,1,4]
[77,31,5,31,80,77,5,8,8]
[1,2,3,2,1]
[44,4,4]
[500,30,1]
[1,2,1,1]
[2,4,6,4,4,4]
[2,23,34,4]
[2,23,3,3,34,4]

```

# Answer
# Python 3, 31 bytes

```
lambda l:{*map(l.count,l)}=={2}

```

Try it online!

---

# Python 2, 33 bytes

```
lambda l:set(map(l.count,l))=={2}

```

Try it online!
> 20 votes

# Answer
# Python 3.8 (pre-release), 62 bytes (non-competing)

```
lambda x:{*[y.count(C)for C	in	(y:=x)]}!={*[2.]}##!2bcdfilmrtu

```

Try it online!

Just for fun, a solution that is itself a "List of Noah".
> 16 votes

# Answer
# 05AB1E, 4 bytes

```
¢<PΘ

```

Try it online! or as a Test Suite

**Explanation**

```
¢      # count all occurrences of each element in the input list
 <     # decrement each
  P    # product
   Θ   # is equal to 1

```
> 14 votes

# Answer
# Brachylog, 4 bytes

```
ọtᵛ2

```

Try it online!

### Explanation

```
ọ           Get the list of occurences of elements in the input: [[x,2], [y,2], …]
  ᵛ         Verify that for each of those pairs…
 t          …the tail (i.e. the number of occurences)
   2        …is 2

```
> 11 votes

# Answer
# , 20 bytes

-6 bytes thanks to digEmAll by changing the input method

```
any(table(scan())-2)

```

Try it online!

Outputs `FALSE` if it is a list of Noah, and `TRUE` otherwise. Works for any input type, not only integers.

Computes the count of each value in the list, and checks whether any of the counts are different from 2.
> 8 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~39~~, 32 bytes

```
l=>l.All(x=>l.Count(y=>y==x)==2)

```

Thanks to @Expired\_Data

Try it online!
> 7 votes

# Answer
# APL (Dyalog Extended), 5 bytesSBCS

```
2¨≡⍧⍨

```

Try it online!

Is it true that…

two for each element

is identical to

`⍧⍨` the count-in selfie (count of own elements in self)

?
> 7 votes

# Answer
# Haskell, 33 bytes

```
f x=and[sum[1|b<-x,b==a]==2|a<-x]

```

Try it online!

For each element of the input we ensure it appears twice in the input list.

`sum[1|b<-x,b==a]` is just a golfier version of `length(filter(==a)x)`.
> 6 votes

# Answer
# Perl 6, 18 bytes

```
{so.Bag{*}.all==2}

```

Try it online!

* `.Bag` converts the input list to a `Bag`--a set with multiplicity.
* `{*}` extracts all of the multiplicities.
* `.all` creates an and-junction of the multiplicities.
* `== 2` results in another and-junction of Booleans, each true if the multiplicity is 2.
* `so` collapses the junction to a single Boolean.
> 6 votes

# Answer
# JavaScript (ES6), 37 bytes

Returns *false* for Noah or *true* for non-Noah.

```
a=>a.some(v=>a.map(x=>t-=v==x,t=2)|t)

```

Try it online!

### Commented

```
a =>               // a[] = input
  a.some(v =>      // for each value v in a[]:
    a.map(x =>     //   for each value x in a[]:
      t -= v == x, //     decrement t if v is equal to x
                   //     (i.e. if v appears exactly twice, t is decremented twice)
      t = 2        //     start with t = 2
    )              //   end of map()
    | t            //   yield t, which is supposed to be equal to 0
  )                // end of some()

```
> 5 votes

# Answer
# , 10 bytes

```
[:*/2=#/.~

```

Try it online!
> 5 votes

# Answer
# APL (Dyalog Unicode), 8 bytesSBCS

Anonymous tacit prefix function. Returns `0`/`1`.

```
∧/2=⊢∘≢⌸

```

Try it online!

for each value as left argument and indices of occurrences of that value as right argument, call:

tally the right argument (the occurrences)
then
return that, ignoring the left argument

`2=` Boolean list indicating which tallies are 2

`∧/` AND-reduction (i.e. are they all true?)
> 4 votes

# Answer
# MS SQL Server 2017, ~~152~~ ~~150~~ 146 bytes

```
CREATE FUNCTION f(@ NVARCHAR(MAX))RETURNS
TABLE RETURN SELECT IIF(2=ALL(SELECT
COUNT(*)FROM STRING_SPLIT(@,',')GROUP BY
PARSE(value AS INT)),1,0)r

```

The readable version:

```
CREATE FUNCTION f(@ NVARCHAR(MAX)) RETURNS TABLE RETURN
  SELECT IIF(2 = ALL(SELECT COUNT(*)
                     FROM STRING_SPLIT(@, ',')
                     GROUP BY PARSE(value AS INT)), 1, 0) AS r

```

Try it on SQL Fiddle!

*-2 bytes thanks to Kevin Cruijssen*
> 4 votes

# Answer
# Haskell, ~~61~~ 45 bytes

```
import Data.List
all((2==).length).group.sort

```

Try it online!

Thanks to @KevinCruijssen for 12 bytes, and @nimi for another 4.

First Haskell answer, but it was surprisingly easy to do. Can ~~probably~~ be golfed a lot. *Case in point...*
> 4 votes

# Answer
## TI-Basic, 47 Bytes

```
Input(L1
SortA(L1
not(remainder(dim(L1,2)) and prod(not(△List(L1))=seq(remainder(I,2),I,1,-1+dim(L1

```

I am a big of fan of TI-Basic. It's not a great language for really any purpose, but I enjoy programming (and golfing) in it.

How does this code work?

First, it sorts the list.

Second, it uses the △List function to generate another list, which is the difference between elements of the sorted list. (For example, △List({1,3,7,8}) would yield {2,4,1}). Applies not to this list, which converts every non-zero element of the list to zero and every zero to one.

Then, the program checks that the resultant list fits the pattern `{1, 0, 1, 0, ...}`, which will only be true if the original list is a Noah list.

There is also an additional check that the length of the list is even, to catch some edge cases.

Here are some screenshots of test cases:
> 4 votes

# Answer
# Julia, ~~30 characters~~ 26 bytes

```
!a=all(x->2==sum(a.==x),a)

```

Thank you, H.PWiz for this trick!

Try it online!
> 4 votes

# Answer
# Jelly, 4 bytes

```
Qœ^Ƒ

```

Try it online!

```
Q       Is the list of unique elements
   Ƒ    unchanged by
 œ^     symmetric multiset difference with the whole input?

```

In broader terms, "if you remove each unique element once, do you have one of each left?" This is guaranteed to stay in the right order because `œ^` is implemented as equivalent to `œ-œ|œ-@`, `Qœ-` is just empty, and `œ-` specifically removes elements last-first while `Q` is in the order of first appearances.
> 4 votes

# Answer
# Octave / MATLAB, ~~22~~ 21 bytes

```
@(x)any(sum(x==x')-2)

```

Anonymous function that inputs a numeric vector, and outputs `0` if the vector satisfies the condition or `1` otherwise.

Try it online! Or verify all test cases.

### Explanation

```
@(x)                   % define anonymous function with input x
            x          % x
               x'      % x transposed and conjugated
             ==        % equality comparison, element-wise with broadcast. Gives a
                       % square matrix
        sum(     )     % sum of each column
                  -2   % subtract 2, element-wise
    any(            )  % true if and only if any value is not zero

```
> 3 votes

# Answer
# VDM-SL, 64 bytes

```
f(a)==forall y in set inds a&card{x|x in set inds a&a(x)=a(y)}=2

```

---

### Explanation

VDM works predominantly like second order logic statements.

```
forall y in set inds a                //Bind y to each of the indices of a

{x|x in set inds a&a(x)=a(y)}         //build a set of the indices of a who have the same
                                      //value as the value at y

card {...} = 2                        //and check the cardinality of that set is 2

```

---

### Since you can't TIO VDM here's output from a debug session
> 3 votes

# Answer
# PowerShell, ~~66~~ ~~37~~ 26 bytes

-11 bytes thanks to mazzy

```
!(($args|group|% c*t)-ne2)

```

Try it online!

Groups up `$l` and grabs all the counts of matching values. It then filters out all counts of 2 from this list. If the list is empty, it's a Noah number; otherwise, it'll be populated still with non-2 counts. Not-ing the list will yield `True` if it's empty and `False` if it's populated
> 3 votes

# Answer
# Elixir, 52 bytes

```
fn v->Enum.all?v,fn x->2==Enum.count v,&x==&1end end

```

Try it online!

Complete Elixir noob here :-D.
> 3 votes

# Answer
# PHP, 60 bytes

```
function($a){return!array_diff(array_count_values($a),[2]);}

```

Try it online!

PHP has great built-ins for this, though at 20 chars, `array_count_values()` is not a very golfy one.
> 3 votes

# Answer
## Mathematica, ~~25~~ 24 bytes

```
MatchQ[{{_,2}..}]@*Tally

```

Try it online!

The `Tally` function returns a list of the form `{{*element*, *count*}, ...}`, which is then matched against a pattern that checks whether all *count* are 2.
> 3 votes

# Answer
# Attache, 16 bytes

```
${All&x!{_~x=2}}

```

Try it online!

## Explanation

```
${All&x!{_~x=2}}
${             }    lambda with input x
  All&x!{     }     over each element _ of x:
         _~x            check that the number of occurrences of _ in x
            =2          is 2

```

## Alternatives

**17 bytes:** `{All&_!`=&2@`~&_}`

**18 bytes:** `{All[`=&2@`~&_,_]}`

**23 bytes:** `Same@2&`'@Sum@Table[`=]`

**25 bytes:** `Same«2'Sum@Table[`=,_]»`

**25 bytes:** `Same<~2'Sum@Table[`=,_]~>`

**25 bytes:** `{Same[2'Sum@Table[`=,_]]}`

**35 bytes:** `{Commonest@_==Unique@_and _[0]~_=2}`
> 3 votes

# Answer
# K (oK), 9 bytes

**Solution:**

```
&/2=#:'.=

```

Try it online!

**Explanation:**

```
&/2=#:'.= / the solution
        = / group
       .  / value
    #:'   / count (length of) each
  2=      / equal to 2?
&/        / take minimum

```
> 3 votes

# Answer
# Julia 1.0, 32 bytes

```
l->sum(isone,l./l')/length(l)==2

```

Try it online!

Divides each element of the input array `l` by the transpose `l'` giving a matrix. Summing over this matrix while applying `isone` to each element gives twice the length of `l` if each element appears exactly twice.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 17 bytes

```
2==##&@@Counts@#&

```

Try it online!

`Counts` returns an association of `<| *(value)*->*(# occurences)*, ... |>`. Then `2==##&` checks if those occurence-counts are all equal to 2.
> 3 votes

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

```
oĉŤđ

```

Attempt This Online!

```
oĉŤđ
o       Sort
 ĉ      Split into runs of equal elements
  Ť     Transpose; fails if not rectangular
   đ    Check if length is 2

```

---

# Nekomata \+ `-e`, 4 bytes

```
oĭu=

```

Attempt This Online!

```
oĭu=
o       Sort
 ĭ      Uninterleave
  u     Uniquify
   =    Check equality

```

---

# Nekomata \+ `-e`, 4 bytes

```
Ţ≡2=

```

Attempt This Online!

```
Ţ≡2=
Ţ       Tally; produces a list of unique elements and a list of their counts
 ≡      Check if all counts are equal, and return that value
  2=    Check if equal to 2

```
> 3 votes

# Answer
# Elm 0.19, 66 bytes

```
n a=List.all(\x->List.foldl(\y c->if x==y then c+1 else c)0 a==2)a

```

Verify all test cases here.

For every item, iterate over the list and count how many items it is equal to. Return `True` if the count is exactly 2 for each item, `False` otherwise.
> 2 votes

# Answer
# Pyth, 7 bytes

```
!n#2/LQ

```

Try it online!

```
!n#2/LQQ   Implicit: Q=eval(input())
           Trailing Q inferred
     L Q   For each element of Q...
    / Q    ... count its occurrences in Q
  #        Filter keep those elements...
 n 2       ... which are not equal to 2
!          NOT - maps [] to True, others to False
           Implicit print

```
> 2 votes

# Answer
# Jelly, 5 bytes

```
ĠẈ=2Ạ

```

Try it online!

A monadic link that takes a list of integers and returns 1 if a Noah list and 0 if not.
> 2 votes

# Answer
# MATL, 6 bytes

```
8#uqqa

```

Try it online!

0 for truthy, 1 for falsy. Ports Robin Ryder's answer.

# MATL, 6 bytes

```
&=s2=A

```

Try it online!

1 for truthy, 0 for falsy. Ports Luis Mendo's answer.
> 2 votes

# Answer
# Kotlin, ~~96~~ ~~77~~ ~~69~~ 51 bytes

```
fun f(t:List<Int>)=t.count{t.count{i->it==i}!=2}==0

```

Try it online!
> 2 votes

# Answer
# Ruby, 29 bytes

```
->a{a.all?{|e|a.count(e)==2}}

```

Try it online!
> 2 votes

# Answer
## Excel, 45 bytes

```
=SUM(IF(FREQUENCY(A:A,A:A)=2,1))=COUNT(A:A)/2

```

Assumes data in column A, with this entered in any cell other than one in column A. Returns TRUE if there are pairs and FALSE if they are not matching pairs

```
        FREQUENCY(A:A,A:A)                     Counts how many of each value there is
     IF(                  =2,1)                If this is 2, add value of 1 to array otherwise 0
=SUM(                          )               Sum the count in that array that have a exactly 2
                                 COUNT(A:A)/2  Count how many total values in column
                                =              If this is equal, return TRUE else FALSE

```

Tried removing the /2 and adding .5 for the summing, but this did not work.
Tried counting the frequencies that are \<\>2 and this did not return the right amount.
> 2 votes

# Answer
Powershell (5.1), 20 48\* Bytes:

I setup my variables like this (which may not be correct):

```
 $a = (7,13,9,2,10,2,4,10,7,13,4,9)

```

I then add that variable to:

```
$a |group|%{$m=@{}}{$m[$_.Name]=($_.Count)-eq2}{$m}

```

This outputs the "Name" and "True" or "False" (could also use the animals names & it would work)

* group - Groups the items
* % - Abbreviation for For-Each
* $m=@{} - Assigns the new variable
* $\_.Count-eq2 - Item count that equals 2
* $y - List each item with True or False (if it equals 2)

Results are similar to this:

\*Note: This answer has been edited as I bungled things the first multiple time*s*...
> 2 votes

# Answer
# Bash, 26 bytes

Exit code is nonzero iff the list is of Noah.

```
sort|uniq -c|grep -v ' 2 '

```

Try it online!
> 2 votes

# Answer
# Factor, 53 bytes

```
: f ( s -- ? ) dup counts [ last ] map [ 2 = ] all? ;

```

Unfortunately dosn't work in TIO. Here's a screenshot of the Factor Listener (REPL):
> 2 votes

# Answer
# Python 3, 37 bytes

```
lambda l:all(l.count(i)==2for i in l)

```

Try it online!
> 2 votes

# Answer
# Jelly, 5 bytes

```
ċⱮ=2P

```

Try it online!

Not shorter than, but different than the existing jelly answer.
> 2 votes

# Answer
# ///, ~~358~~ 299 bytes

```
/|/\/\///`/'\\|&/%`\%`\%T;`\%R;N`\%T;`\%|:/\\\\|;/`\`\|_/%%|%/`/|%<-::>:::|QT/%R'N%Q'T_<-;>%<-;;>;;_<`->%_L`S%L'S_-` *%-`{*[_-`{*%{-_!`{%{!_^`{*%^{-_[`*%*[_-`*%*-_!`*%*!_-`[%[-_!`[%[!_{`[%!_^`!%^-!_-`$%$_-`!!`$%$_-`!$&0_!`!!$&0_^`$&1_Q`T%Q'T%R'N|RN/QT|<-:>/<-::>::|<\->/|!*/!-|-*/--|LS/^!DATA GOES HERE$|Q\T/QT/RN

```

Try it online!

Try it online! (legible-ish version)

I don't know if this is the first Code Golf answer which uses an actual computational loop in slashes, but I'm very proud of it regardless. The loop construction I use is due to Ørjan Johansen, and is elaborated on on the wiki (although not in very high detail, and he uses `|` instead of `'`). There is a whole lot of escaping involved.

Input is in the form of a string which replaces `DATA GOES HERE` in the source code. The string should be a -delimited list of unary numbers with `*` representing one. Output is `1` if the list is a list of Noah, `0` if it is not.

## Explanation

* The program revolves around the manipulation of the input string, which is prefixed by `^!` and suffixed by `$`. First, the following two substitutions are made: `/!*/!-/` and `/-*/--/`, which turn the first number of the input into dashes. It will be the number line for recording the whole list.
* The rest of the program is inside a loop (not presented in the same order as in the program). First, it organizes the data

```
/- */-\{*[/ /[*/*[/    turn the next number into a "rocket"
                       eg `^!--- **` => `^!---{**[`
/-{*/{-/               the front of the rocket moves forward by "using up fuel"
/!{/{!/                moving forward through a `!` does not cost any fuel
/-*/*-/ /!*/*!/ /-[/[-/ /![/[!/
                       the rest of the rocket follows the head
/^{*/^{-/              the rocket extends the number line if it runs out of room
/{[/!/                 once the rocket runs out of fuel, it becomes a `!`

```
* Since a rocket travels a number of `-`s equal to the number it came from, the result is a backwards number line where every member of the original list is marked with `!`s, eg `^!*** ** *** *****$` =\> `^!--!!-!--$`
* When the last number turns into a rocket, the `$` begins inspecting the number line:

```
/^!/^-!/                 needed for some of the following to work
/-$/$/ /-!!$/$/          the inspector finds things satisfactory so far
/-!$/N\O/ /!!!$/N\O/     the inspector has rejected this input
/^$/Y\S/                 the inspector has accepted this input

```
* The loop works by replacing a "variable" `RN` with a copy of the relevant code. The simplest way to stop the loop and output the result is to conditionally replace RN with the result so that the loop can't continue. We do this by replacing `YS` and `NO` *with a replacement* that replaces RN with the relevant value: `/YS/\/\/T\\\/R\\N\/T\\\/1/ /NO/\/\/T\\\/R\\N\/T\\\/0/`. (It is `//f/r` instead of `/f/r/` because the `YS` and `NO` values already exist inside a replacement, so it becomes works like, eg, `/LS/YS/` =\> `/LS///RN/1/`

## Notes

Variables are two letters because you have to be able to escape them by putting a `\` in the middle (`/V\R/val/` is equivalent to `/VR/val/`), otherwise they'll replace themselves in the copy that's used for looping.

At the beginning of the program are several "golfing substitutions" which serve no purpose other than to make the program shorter and even less legible.

59 bytes saved by using direct replacement instead of `YS` and `NO`, and doing 2 more golfing substitutions (`&` for the replacement-replacement which is nearly the same for accepting and rejecting, and ``` for `'\`)
> 2 votes

# Answer
# Vyxal, 5 bytes

```
vO2J≈

```

Try it Online!

Makes a list of how many times the integer exists in the list, adds `2` to the list and checks if everything is equal. A sneaky way to check if all the items are equal, **and** that they are all 2.
> 2 votes

# Answer
# Factor, 32 bytes

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

```

Try it online!
> 2 votes

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

```
{*(2=#'.=x)^1}

```

Try it online!

This one is a little bit lengthier than it needs to be though. Return `0N` (i.e. null) for true and `0` for false.

Explanations:

```
{*(2=#'.=x)^1}  Main function. Takes x as input
  (      x)     x
        =       Group. Returns a dictionary with the keys being the values
                that appear in the array, and the values being the position
                of the corresponding key.
       .        Get just the value
     #'         Get the length for each of them
   2=           See if it's equal to 2
            ^1  Eliminate 1s in the result (i.e. remove truthy values)
 *              Get the first element

```
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
c⁻pḅ

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

#### Explanation

```
c⁻pḅ  # Implicit input
c     # Counts of each element
 ⁻    # Decrement each
  p   # Product of this list
   ḅ  # Equals one?
      # Implicit output

```
> 2 votes

# Answer
# Charcoal, 7 bytes

```
⬤θ⁼²№θι

```

Try it online! Link is to verbose version of code. Outputs `-` for a List of Noah. Explanation:

```
 θ      Input array
⬤       Do all elements satisfy the condition
    №   Count of
      ι Current element
     θ  In input array
  ⁼     Equals
   ²    Literal 2
        Implicitly output

```
> 1 votes

# Answer
# Retina 0.8.2, 32 bytes

```
O`\d+
(\d+)(,\1)*\b
$#2
^1(,1)*$

```

Try it online! Link includes test cases. Explantion:

```
O`\d+

```

Sort the integers. (This is a string sort but it doesn't matter assuming no leading zeros.)

```
(\d+)(,\1)*\b
$#2

```

Count the number of duplicates of each integer.

```
^1(,1)*$

```

Each integer should have one other duplicate.
> 1 votes

# Answer
# Japt, 6 bytes

Outputs `false` for true and `true` for false.

```
ü mÊdÍ

```

Try it or run all test cases

```
ü mÊdÍ     :Implicit input of integer array
ü          :Group by value
  m        :Map
   Ê       :  Length
    d      :Any truthy (not 0)?
     Í     :  When subtracted from 2

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 38 bytes

```
Gather@#~Cases~{_,_}~Total~2==Total@#&

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
é♪Ccv

```

Run and debug it

**Algorithm:**

1. Sort array.
2. Get run-lengths.
3. Remove all `2`s from run-lengths.
4. Result is empty?
> 1 votes

# Answer
# Red, 52 bytes

```
func[b][(extract sort b 2)= unique extract next b 2]

```

Try it online!
> 1 votes

# Answer
# Python 3, 41 bytes

```
lambda x:set([x.count(i)for i in x])=={2}

```

Try it online!
> 1 votes

# Answer
# C, ~~84~~ 83 bytes

```
c['   '],r,*p,*s,*e;f(){for(p=s;p<e;)c[*p++]++;while(s<e)r=c[*s++]-2?1:r;return r;}

```

Try it online!

`f()` returns 1 if the list is *not* a list of Noah, and 0 otherwise.

The variable `s` should point to the beginning of the array, and `e` should point to the end. Note that after `f()` is called, `c` must be reset to 0s before it can be called again. Also, this might not work on all computers, because I'm pretty sure multi-byte characters are implementation-defined, and it won't work if `INT_MAX < 100000`.

If I/O is *very* flexible, and outputting to a variable is enough, the `return r;` is unnecessary, and it can be reduced to 74 bytes.

De-golfed:

```
int counts[100001], return_value;

int f(int *start, int *end) {
        int *ptr;
        for (ptr = start; ptr < end; ptr++)
                counts[*ptr]++;
        for (ptr = start; ptr < end; ptr++) {
                if (counts[*ptr] != 2) {
                        return_value = 1;
                }
        }
        return return_value;
}

```

Thanks to @ceilingcat for -1 byte!
> 1 votes

# Answer
# APL(NARS), 9 chars, 18 bytes

```
{⍵≡⍦,⍨∪⍵}

```

test:

```
  f←{⍵≡⍦,⍨∪⍵}
  f 7,13,9,2,10,2,4,10,7,13,4,9
1
  f 77,31,5,31,80,77,5,8,8
0
  f 2,4,6,4,4,4
0

```
> 1 votes

# Answer
# Dart, 66 bytes

```
f(n)=>n.map((m)=>n.where((o)=>o==m).length==2).reduce((p,e)=>p&e);

```

Try it online!
> 1 votes

# Answer
# Vim, 45 bytes

```
:sor|%norm J
:g/^\v(.*) \1$/d
:g/./norm ggcG0

```

Try it online!

This will output nothing for a valid Noah list, and a 0 for an invalid Noah list.
> 1 votes

# Answer
# Brainfuck: 69

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

```

The bf interpreter/compiler needs to support 0 as EOF. It also need at least 300003 cells for be be used with number upto 100000. `beef` seems to match this.

The numbers are expected to come in as unary (whatever) terminated by ascii 1. It will output chr 0 on a valid set and chr 99 on an invalid set. If your terminal has UTF-8 you'll get some complaints or a replacement chars (the ?) as an indication.

The code uses bf memory as the first cell as an -1 flag that it seeks to after every number. Each number triggers it to jump 3 cells, since I have a 3 cell item and the whole BF memory is considered an array:

```
flag (-1) [ visited | flag | count ]*

```

Thus if you supply 3 it will set count on the third index to 1 and every visited flags to 1 upto that.

I've tested like this:

```
#!/usr/bin/fish
set -l tests '[7,13,9,2,10,2,4,10,7,13,4,9]
[1,2,3,1,2,3]
[10,100,1000,1,100,10,1000,1]
[123,123]
[8,22,57189,492,22,57188,8,492,57188,57189,1,1]
[6,4,4,6,4,7,4,7]
[2,2,2,2,2,2]
[5,1,4,5,1,1,4]
[77,31,5,31,80,77,5,8,8]
[1,2,3,2,1]
[44,4,4]
[500,30,1]
[1,2,1,1]
[2,4,6,4,4,4]
[2,23,34,4]
[2,23,3,3,34,4]
'

for in in (echo $tests)
  echo -n $in :
  echo $in | perl -pe 's/(\d+)/"1" x $1/ge;s/[^\]\d,]//g;s/(?:]|,)/\x01/g;' | beef  moses.bf
  echo ''
end

```

And got the following output:

```
[7,13,9,2,10,2,4,10,7,13,4,9] :
[1,2,3,1,2,3] :
[10,100,1000,1,100,10,1000,1] :
[123,123] :
[8,22,57189,492,22,57188,8,492,57188,57189,1,1] :
[6,4,4,6,4,7,4,7] :[Invalid UTF-8] \xff
[2,2,2,2,2,2] :[Invalid UTF-8] \xff
[5,1,4,5,1,1,4] :[Invalid UTF-8] \xff
[77,31,5,31,80,77,5,8,8] :[Invalid UTF-8] \xff
[1,2,3,2,1] :[Invalid UTF-8] \xff
[44,4,4] :[Invalid UTF-8] \xff

```
> 1 votes

# Answer
# Kotlin, 46 45 bytes

```
fun f(l:IntArray)=l.all{l.count{i->it==i}==2}

```

Try it online!
> 1 votes

# Answer
## Swift 5.1, 63 bytes

`let x={(a:[Int])in a.allSatisfy{v in a.filter{v==$0}.count==2}}`

When the `count(where:)` function will be available, it'll become:

`let x={(a:[Int])in a.allSatisfy{v in a.count{v==$0}==2}}`

Try it online!
> 1 votes

# Answer
# jq, 30 characters

```
group_by(.)|map(length==2)|all

```

Sample run:

```
bash-5.0$ jq 'group_by(.)|map(length==2)|all' <<< '[7,13,9,2,10,2,4,10,7,13,4,9]'
true

```

Try it online!

Try all test cases online!
> 1 votes

# Answer
# PHP, 58 bytes

```
for(;$n=$argv[++$i];$a[$n]++);echo min($a)==2&&max($a)==2;

```

Each number in the list is passed as an argument.

Outputs 1 for truthy and nothing for falsey.

Try it online!

Tests
> 1 votes

# Answer
# Arturo, 24 bytes

```
$=>[[]=--values tally&2]

```

Try it!

```
$=>[        ; a function where input is assigned to &
    tally&  ; create a dictionary of counts of elements in input
    values  ; get just the counts
    --   2  ; remove all the twos
    []=     ; is it the empty list?
]           ; end function

```
> 1 votes

# Answer
# Desmos, 40 bytes

```
f(L)=0^{[L[L=i].length-2fori=L]^2.total}

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Vyxal 3, 4 bytes

```
SUu₌

```

Try it Online!

Sort, uninterleave, uniquify, check if equal
> 1 votes

# Answer
# Perl 5 `-pl`, 31 bytes

```
$k{$_}++}{$_=!grep$_-2,values%k

```

Try it online!
> 1 votes

# Answer
# Uiua, 8 bytes

```
/×=2⊕⧻⊛.

```

Test pad
> 1 votes

# Answer
# Awk, 44 bytes

```
{++k[$0]}END{for(i in k)a=a||k[i]-2;print a}

```

Try it online!

0 means it is a list of Noah, 1 means that it is not a list of Noah.
> 1 votes

# Answer
# AWK, 36 32 bytes

```
++_[$0]-2{i++}END{print NR/i==2}

```

Try it online!

* -4 bytes, print value of `NR/i==2` assessment instead of using ternary operator.

Will print `1` for `List of Noah` and `0` for `not`.
> 1 votes

---
Tags: code-golf, number, decision-problem, integer
---


title: Find the Cell's Neighbours

text:
# Question
Title: Find the Cell's Neighbours
## ...or Toroidal Moore Neighbourhoods

Given positive integers `h`, `w` and a non-negative integer `i`, return all of the indices surrounding `i`.

You are to assume a matrix consisting of `h` rows of `w` elements, numbered from lowest, in the top left-hand corner, to highest, in the bottom right-hand corner, and return, in any reasonable format, a list of the indices that would surround the index, `i`. This matrix is a torus (an infinite map that wraps around each edge).

For example, inputs `h=4` and `w=4`, would result in the matrix:

```
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

```

but more specifically:

```
**15 12 13 14 15 12**
 **3**  0  1  2  3  **0**
 **7**  4  5  6  7  **4**
**11**  8  9 10 11  **8**
**15** 12 13 14 15 **12**
 **3  0  1  2  3  0**
```

so that if `i` was `0`, you'd need to return `15, 12, 13, 3, 1, 7, 4, 5` (0-based).

## Examples

*0-based:*

```
h   w   i       Expected result

4   4   5       0, 1, 2, 4, 6, 8, 9, 10
4   4   0       15, 12, 13, 3, 1, 7, 4, 5
4   5   1       15, 16, 17, 0, 2, 5, 6, 7
1   3   2       1, 2, 0, 1, 0, 1, 2, 0
1   1   0       0, 0, 0, 0, 0, 0, 0, 0

```

*1-based:*

```
h   w   i       Expected result

4   4   6       1, 2, 3, 5, 7, 9, 10, 11
4   4   1       16, 13, 14, 4, 2, 8, 5, 6
4   5   2       16, 17, 18, 1, 3, 6, 7, 8
1   3   3       2, 3, 1, 2, 1, 2, 3, 1
1   1   1       1, 1, 1, 1, 1, 1, 1, 1

```

## Rules

* Your answer may be 0 or 1-indexed, your choice, please specify.
* You can assume that `i < h * w` (or `i <= h * w` for 1-indexed answers).
* You can assume that `i >= 0` (or `i > 0` for 1-indexed answers).
* The order of the returned values is not important as long as just the eight desired values are included.
* Standard loopholes are forbidden.
* This is so the shortest answer, in each language, wins!

Thanks to @Conor O'Brien for the more technical sounding title and @ngm for more test cases!

# Answer
# JavaScript (ES6), 75 bytes

*Saved 2 bytes thanks to @KevinCruijssen*

Expects a 0-based index.

```
(h,w,i)=>[...'12221000'].map((k,j,a)=>(i+w+~-k)%w+~~(i/w+h+~-a[j+2&7])%h*w)

```

Try it online!

The surrounding indices are returned in the following order:

$$\begin{matrix}5&4&3\\6&\cdot&2\\7&0&1\end{matrix}$$

### How?

The indices \\$I\_{dx,dy}\\$ of each surrounding cell at \\$(x+dx,y+dy)\\$ are given by:

$$\begin{align}I\_{dx,dy}&=((x+dx) \bmod w)+w((y+dy) \bmod h)\\\&=((N+dx) \bmod w)+w((\left\lfloor\frac{N}{w}\right\rfloor+dy) \bmod h)\end{align}$$

where \\$N=wy+x\\$ is the index of the target cell.

We walk through the list \\$\[1,2,2,2,1,0,0,0\]\\$ and subtract \\$1\\$ to get the value of \\$dx\\$, which gives:

$$\[0,1,1,1,0,-1,-1,-1\]$$

For the corresponding values of \\$dy\\$, we use the same list shifted by 2 positions, which gives:

$$\[1,1,0,-1,-1,-1,0,1\]$$
> 8 votes

# Answer
# APL (Dyalog Classic), 27 bytes

```
{(⍺⊥⍺|(⍺⊤⍵)-⊢)¨1-1↓4⌽,⍳3 3}

```

Try it online!

`{` `}` is a function with arguments  (the dimensions `h w`) and  (the index `i`)

`⍳3 3` is a matrix of all 2-digit ternary numbers: `0 0`, `0 1`, ..., `2 2`

`,` enlists the matrix as a vector

`1↓4⌽` removes the centre element `1 1` by rotating 4 to the left (`4⌽`) and dropping one (`1↓`)

`1-` subtracts from 1, giving all 8 neighbour offsets

`(`  applies the function train in parentheses to each offset

`⍺⊤⍵` is the base- encoding of  \- the coordinates of  in the matrix

`(⍺⊤⍵)-⊢` subtracts the current offset, giving the coordinates of a neighbour

`⍺|` is mod `a` to wrap around coordinates and stay within the matrix

`⍺⊥` decodes from base
> 6 votes

# Answer
# APL (Dyalog Unicode), 40 bytesSBCS

Anonymous infix function. Takes `h` `w` as left argument and `i` as right argument.

```
{1↓4⌽,3 3↑,⍨⍣2⍪⍨⍣2⊃⊖∘⍉/(¯1+⍺⊤⍵),⊂⍺⍴⍳×/⍺}

```

Try it online!

`{``}` "dfn";  is left argument (dimensions) and  is right argument (index).

`×/⍺` product (multiplication-reduction) of the dimensions

the first that many indices

`⍺⍴` use the dimensions to **r**eshape that

enclose it (to treat it as a single element)

`(``),` prepend the following:

`⍺⊤⍵` encode the index in mixed-radix `h` `w` (this gives us the coordinates of the index)

`¯1+` add negative one to those coordinates

`⊖∘⍉/` reduce by rotate-the-transpose
this is equivalent to `y⊖⍉x⊖⍉`… which is equivalent to `y⊖x⌽`… which rotates left as many steps as `i` is offset to the right (less one), and rotates up as many steps as `i` is offset down (less one), causing the the 3-by-3 matrix we seek to be in the top left corner

disclose (because the reduction reduced the vector to scalar by enclosing)

`⍪⍨⍣2` stack on top of itself twice (we only really need thrice for single-row matrices)

`,⍨⍣2` append to itself twice (we only really need thrice for single-column matrices)

`3 3↑` take the first three rows of the first three columns

The next two steps can be omitted if returning a 3-by-3 matrix is acceptable:

`,` ravel (flatten)

`4⌽` rotate four steps left (brings the centre element to the front)

`1↓` drop the first element
> 5 votes

# Answer
# , ~~125 111~~ 108 bytes

```
function(x,i,m=array(1:prod(x),x),n=rbind(m,m,m),o=cbind(n,n,n),p=which(m==i,T)+x-1)o[p[1]+0:2,p[2]+0:2][-5]

```

Try it online!

14 and 8 bytes golfed by @JayCe and @Mark.

Input is `[w, h], i` because R populates arrays column first.

Makes the array and then "triples" it row- and column-wise. Then locate `i` in the original array and find it's neighborhood. Output without `i`.
> 4 votes

# Answer
# Python 2, ~~79~~ ~~69~~ 66 bytes

```
lambda h,w,i:[(i+q%3-1)%w+(i/w+q/3-1)%h*w for q in range(9)if q-4]

```

Try it online!

3 bytes gifted by Neil noting that `(x*w)%(h*w)==((x)%h)*w==(x)%h*w`.

0-indexed solution.
> 4 votes

# Answer
# PHP, 165 bytes

This is "0-based". There must be a better solution in PHP, but this is a starting point!

```
<?list(,$h,$w,$i)=$argv;for($r=-2;$r++<1;)for($c=-2;$c++<1;)$r||$c?print(($k=(int)($i/$w)+$r)<0?$h-1:($k>=$h?0:$k))*$w+(($l=$i%$w+$c)<0?$w-1:($l>=$w?0:$l))%$w.' ':0;

```

To run it:

```
php -n <filename> <h> <w> <i>

```

Example:

```
php -n cell_neighbours.php 4 5 1

```

Or Try it online!
> 3 votes

# Answer
# K (ngn/k), ~~27~~ 24 bytes

```
{x/x!''(x\y)-1-3\(!9)^4}

```

Try it online!

`{` `}` is a function with arguments `x` (the dimensions `h w`) and `y` (the index `i`)

`(!9)^4` is `0 1 2 3 4 5 6 7 8` without the `4`

`3\` encodes in ternary: `(0 0;0 1;0 2;1 0;1 2;2 0;2 1;2 2)`

`1-` subtracts from `1`, giving neighbour offsets: `(1 1;1 0;1 -1;0 1;0 -1;-1 1;-1 0;-1 -1)`

`x\y` is the base-`x` encoding of `y` \- the coordinates of `y` in the matrix

`-` subtracts each offset, giving us 8 pairs of neighbour coordinates

`x!''` is mod `x` for each - wrap coordinates around to stay within the matrix

`x/` decodes from base `x` \- turns pairs of coordinates into single integers
> 3 votes

# Answer
# Wolfram Language (Mathematica), 74 bytes

```
Mod[i=#;w=#2;Mod[i+#2,w]+i~Floor~w+w#&@@@{-1,0,1}~Tuples~2~Delete~5,1##2]&

```

Try it online!

Takes input in reverse (`i, w, h`), 0-based.

### 3x3 matrix with the center cell in it, (60 bytes)

```
(Join@@(p=Partition)[Range[#2#]~p~#,a={1,1};3a,a,2a])[[#3]]&

```

Takes (`w, h, i`), 1-based.

Try it online!
> 2 votes

# Answer
# MATL, 24 bytes

```
*:2Geti=&fh3Y6&fh2-+!Z{)

```

Inputs are `h`, `w`, `i`. The output is a row vector or column vector with the numbers.

Input `i` and output are 1-based.

Try it online! Or verify all test cases.

### Explanation

```
*     % Take two inputs implicitly. Multiply
      % STACK: 16
:     % Range
      % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
2G    % Push second input again
      % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16], 4
e     % Reshape with that number of rows, in column-major order
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16]
t     % Duplicate
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16],
      %        [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16]
i=    % Take third input and compare, element-wise
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16],
      %        [0 0 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 0]
&f    % Row and column indices of nonzeros (1-based)
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], 2, 2,
h     % Concatenate horizontally
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2]
3Y6   % Push Moore mask
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2],
      %        [1 1 1; 1 0 1; 1 1 1]
&f    % Row and column indices of nonzeros (1-based)
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2],
      %        [1; 2; 3; 1; 3; 1; 2; 3], [1; 1; 1; 2; 2; 3; 3; 3]
h     % Concatenate horizontally
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2],
      %        [1 1; 2 1; 3 1; 1 2; 3 2; 1 3; 2 3; 3 3]
2-    % Subtract 2, element-wise
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16], [2 2],
      %        [-1 -1; 0 -1; 1 -1; -1 0; -1 0; -1 1; 0 1; 1 1]
+     % Add, element-wise with broadcast
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16],
      %        [1 1; 2 1; 3 1; 1 2; 3 2; 1 3; 2 3; 3 3]
!     % Transpose
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16],
      %        [1 2 3 1 3 1 2 3; 1 1 1 2 2 3 3 3]
Z{    % Convert into a cell array of rows
      % STACK: [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16],
      %        {[1 2 3 1 3 1 2 3], [1 1 1 2 2 3 3 3]}
)     % Index. A cell array acts as an element-wise (linear-like) index
      % STACK: [1 2 3 5 7 9 10 11]

```
> 2 votes

# Answer
## Batch, 105 bytes

```
@for /l %%c in (0,1,8)do @if %%c neq 4 cmd/cset/a(%3/%2+%1+%%c/3-1)%%%1*%2+(%3%%%2+%2+%%c%%3-1)%%%2&echo.

```

0-indexed. Saved 23 bytes by stealing @ChasBrown's modulo 3 trick.
> 2 votes

# Answer
# MATL, 24 bytes

```
X[h3Y6&fh2-+1GX\1Gw!Z}X]

```

Try it on MATL Online

Takes inputs `[w h]` and `i`. 8 bytes of this was ~~shamelessly stolen from~~ inspired by Luis Mendos' answer, though the overall approach is different.
> 2 votes

# Answer
# Clean, ~~85~~ 83 bytes

```
import StdEnv
r=(rem)
$h w i=tl[r(n+i/w)h*w+r(r(m+i)w)w\\n<-[0,1,h-1],m<-[0,1,w-1]]

```

Try it online!

Treats `i` as a coordinate `(0 <= p < h, 0 <= q < w)`, and generates the values of the adjacent elements where the value is `p'w + q'`.
> 1 votes

# Answer
# Jelly, 20 bytes

```
PRs©Ṫ{œi+€Ø-Ż¤ŒpḊœị®

```

A dyadic link accepting a list of the dimensions on the left, `[h,w]`, and the cell as an integer on the right, `i`, which yields a list of the neighbourhood.

Note: the order is different to that in the examples which is allowed in the OP

**Try it online!**

### How?

```
PRs©Ṫ{œi+€Ø-Ż¤ŒpḊœị® - Link: [h,w], i
P                    - product -> h*w
 R                   - range -> [1,2,3,...,h*w]
    Ṫ{               - tail of left -> w
  s                  - split into chunks -> [[1,2,3,...w],[w+1,...,2*w],[(h-1)*w+1,...,h*w]]
   ©                 - ...and copy that result to the register
      œi             - multi-dimensional index of (i) in that list of lists, say [r,c]
             ¤       - nilad followed by link(s) as a nilad:
          Ø-         -   literal list -> [-1,1]
            Ż        -   prepend a zero -> [0,-1,1]
        +€           - addition (vectorises) for €ach -> [[r,r-1,r+1],[c,c-1,c+1]]
              Œp     - Cartesian product -> [[r,c],[r,c-1],[r,c+1],[r-1,c],[r-1,c-1],[r-1,c+1],[r+1,c],[r+1,c-1],[r+1,c+1]]
                Ḋ    - dequeue -> [[r,c-1],[r,c+1],[r-1,c],[r-1,c-1],[r-1,c+1],[r+1,c],[r+1,c-1],[r+1,c+1]]
                   ® - recall (the table) from the register
                 œị  - multi-dimensional index into (1-indexed & modular)

```
> 1 votes

# Answer
# Attache, 66 bytes

```
{a.=[]Moore[Integers@@__2,{Push[a,_]},cycle->1]Flat[a@_][0:3'5:8]}

```

Try it online!

I still need to implement `Moores` and `NMoore`, but I still have `Moore` which serves as an iteration function. Essentially, `Integers@@__2` creates an integer array of shape `__2` (the last two arguments) of the first `Prod[__2]` integers. This gives us the target array. Then, `Moore` iterates the function `{Push[a,_]}` over each Moore neighborhood of size `1` (implied argument), with the option to cycle each element (`cycle->1`). This adds each neighborhood to the array `a`. Then, `Flat[a@_]` flattens the `_`th member of `a`, that is, the Moore neighborhood centered around `_` (the first argument). `[0:3'5:8]` obtains all members except the center from this flattened array.

This solution, with an update to the language, would look something like this (49 bytes):

```
{Flat[NMoore[Integers@@__2,_,cycle->1]][0:3'5:8]}

```
> 1 votes

# Answer
# Kotlin, 88 bytes

Uses zero based indexes and outputs an 8 element list.

```
{h:Int,w:Int,i:Int->List(9){(w+i+it%3-1)%w+(h+i/w+it/3-1)%h*w}.filterIndexed{i,v->i!=4}}

```

Try it online!
> 1 votes

# Answer
# Vyxal 3, 11 bytes

```
Πʀ⁰hẆÞȮ1⁾¹i

```

Try it Online!

Output is sorted in footer but is not necessary to the program bytecount

input is of the form `[w,h], n`

```
Πʀ⁰hẆÞȮ1⁾¹i
Πʀ           # range [0, w*h)
  ⁰hẆ        # split into chunks of given width
     ÞȮ1⁾    # grid neighbors with wraparound flattened by one
         ¹i  # at given index

```

Created with the help of Luminespire.
> 1 votes

---
Tags: code-golf, matrix
---


# Question
Title: Using two linked programs, output ordinal numbers up to n
> ...Ordinal numbers (or ordinal numerals) are words representing position or rank in a sequential order.

*From Wikipedia.*

Your task is, using 2 separate programs (of which can be made from 2 different languages), to output the ordinal sequence from first to `nth`. You will be outputting the full word `second` as opposed to `2nd`.

The challenge of ordinal numbers has been brought up before, particularly in this entry. In this challenge, ordinals are merely a vehicle to facilitate the unique conditions detailed below.

---

## Part 1

You must make a program that, when given the input of `n` must output *anything*.
`n` will always be a positive, non-zero integer no larger than 999.

Valid output includes but **is not limited to**:

* Any output to `stdout` / `stderr` / etc
* Creation of files / folders / etc
* A graphical interface or images of any kind

***Anything goes.***

---

## Part 2

You must make a program that uses the output of part 1's program to output a sequence of ordinal numbers, starting from 1 (first), up to whatever `n` was parsed in part 1.

### General Conditions:

* The total bytes for part 2 must not exceed the total bytes for part 1 (less than or equal to).

### Output conditions:

* Not case sensitive.
* Output must contain only the ordinal sequence (only characters a-Z) and whitespace (newlines allowed).
* Can be output to any source, so long as it is visible either during or after execution.
* Program does not need to terminate so long as its output is correct.
* Output is not required to have any grammar, but may optionally include it (hyphens, commas, "ands", etc). `nine hundred ninety ninth` is just as acceptable as `nine hundred and ninety-ninth`.

### Sample Output

*Where `n` is 8*

```
FIRST SECOND THIRD FOURTH FIFTH SIXTH SEVENTH EIGHTH

```

---

## Scoring

The hierarchy of win conditions is:

> 1. The lowest number of bytes in part 1
> 2. The lowest number of bytes in part 2

```
Entry #1 | Part 1 = 32 bytes, Part 2 = 22 bytes
Entry #2 | Part 1 = 31 bytes, part 2 = 30 bytes

Entry #2 wins - Part 1 contains 31 bytes vs 32 bytes

---

Entry #1 | Part 1 = 21 bytes, Part 2 = 33 bytes
Entry #2 | Part 1 = 80 bytes, Part 2 = 70 bytes

Entry #2 wins - Entry #1 disqualified (Part 2 contains more bytes than Part 1)

---

Entry #1 | Part 1 = 50 bytes, Part 2 = 49 bytes
Entry #2 | Part 1 = 50 bytes, Part 2 = 50 bytes

Entry #1 wins - Part 1 is equal, Part 2 contains 49 bytes vs 50 bytes

```

# Answer
# Sledgehammer 0.5.1 / Sledgehammer 0.5.1, 10 bytes

### Program 1 (10 bytes):

```
⣘⢷⠾⣃⢖⣎⢅⡨⠱⢳

```

Decompresses into this Wolfram Language function:

```
{Range[#1], "Ordinal"} &

```

### Program 2 (7 bytes):

```
⡾⡁⢚⣷⣬⠤⣾

```

Decompresses into this Wolfram Language function:

```
StringRiffle[IntegerName @@ #1, " "] &

```

Try it online!
> 14 votes

# Answer
# (with `english` package), 16 bytes / 16 bytes

### Part 1, 16 bytes

```
f=function(n)1:n

```

### Part 2, 16 bytes

```
english::ordinal

```

Requires the `english` package (which is not installed on TIO, unfortunately).

`english::ordinal(f(22))` outputs `first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth thirteenth fourteenth fifteenth sixteenth seventeenth eighteenth nineteenth twentieth twenty first twenty second`.

Of course, part 1 could be made much shorter (3 bytes: `seq`), but that would go against the constraint that part 2 has to be no longer than part 1.
> 9 votes

# Answer
## Wolfram Language (Mathematica) (both parts), 18 bytes / 15 bytes

-5/-1 thanks to lirtosiast

### Part 1, 18 bytes

```
Range@#|"Ordinal"&

```

### Part 2, 15 bytes

```
IntegerName@@#&

```

Try it online!

Two functions which output via return value.
> 8 votes

# Answer
## Python 3(part 1 & part 2)

Unfortunately Nodebox is very wordy... there is not much room for golfing.

### Part 1 76 bytes

```
for  i  in  range  (  1 ,  int  (  input  (  ) ) + 1 ) : print ( i ,end=" ")

```

### Part 2 (Uses the NodeBox library) 76 bytes

```
import en.number as n
for i in input().split():print(n.ordinal(n.spoken(i)))

```
> 4 votes

# Answer
# JavaScript (Node.js), 47 bytes / 47 bytes

Two functions in the same Node.js environment, invoked like `g(f(n))`. Uses the npm package number-to-words.

### Part 1, 47 bytes (40 bytes + 7 spaces)

```
n=>H=>{for(i=0;i<n;)console.log(H(++i))}

```

### Part 2, 47 bytes

```
F=>F(require("number-to-words").toWordsOrdinal)

```

Try it on Runkit!

---

# JavaScript (Node.js), 48 bytes / 43 bytes

### Part 1, 48 bytes

```
n=>[n,require("number-to-words").toWordsOrdinal]

```

### Part 2, 43 bytes

```
([n,F])=>{for(i=0;i<n;)console.log(F(++i))}

```

Try it on Runkit!
> 1 votes

# Answer
# Perl 5.10 / Common Lisp, 34 / 26 bytes

So, Common Lisp `format` has this as a built-in, because of course it does.

## Program 1 (34 bytes)

```
say"(format t\"~:r \"$_)"for 1..<>

```

Perl does all the iterating. The equivalent Common Lisp code (`(dotimes(i(read)) ...)`) is longer than the much golfier Perl `... for 1..<>`. Perl outputs a bunch of Common Lisp code.

## Program 2 (26 bytes)

```
(loop(eval(read nil nil)))

```

It's a REPL, minus the P. It reads standard input and, well, executes it. Doesn't terminate, but the rules explicitly say that's fine.
> 1 votes

# Answer
# Vyxal, 2/2 bytes

```
ɾ, # print range (1,n+1)

```

```
∆o # nth ordinal of each

```

Try it Online!
> 1 votes

---
Tags: code-golf
---


title: The TAK function

text:
# Question
Title: The TAK function
The TAK function is defined as follows for integers \\$x\\$, \\$y\\$, \\$z\\$:

$$ t(x, y, z) = \begin{cases} y, & \text{if $x \le y$} \\ t(t(x-1,y,z), t(y-1,z,x), t(z-1,x,y)), & \text{otherwise} \end{cases} $$

Since it can be proved that it always terminates and evaluates to the simple function below,

$$ t(x, y, z) = \begin{cases} y, & \text{if $x \le y$} \\ z, & \text{if $x \> y$ and $y \le z$} \\ x, & \text{otherwise} \end{cases} $$

your job is not to just implement the function, but **count the number of calls to \\$t\\$** when initially called with the given values of \\$x\\$, \\$y\\$, and \\$z\\$. (As per the standard rules, you don't need to implement \\$t\\$ if there is a formula for this value.)

You may assume that the three input values are nonnegative integers.

Note that the task is slightly different from the definition of the function \\$T\\$ (the number of "otherwise" branches taken) on the Mathworld page.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
(x, y, z) -> output

(0, 0, 1) -> 1
(1, 0, 2) -> 5
(2, 0, 3) -> 17
(3, 0, 4) -> 57
(4, 0, 5) -> 213
(5, 0, 6) -> 893

(1, 0, 0) -> 5
(2, 0, 0) -> 9
(2, 1, 0) -> 9
(3, 0, 0) -> 13
(3, 1, 0) -> 29
(3, 2, 0) -> 17
(4, 0, 0) -> 17
(4, 1, 0) -> 89
(4, 2, 0) -> 53
(4, 3, 0) -> 57
(5, 0, 0) -> 21
(5, 1, 0) -> 305
(5, 2, 0) -> 149
(5, 3, 0) -> 209
(5, 4, 0) -> 213

```

Python implementation was used to generate the test cases.

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

**Using a single recursive function**

Expects `(x, y, z)`.

```
f=(x,y,z,w)=>x>(r=y)?f(x-1,y,z)+f(y-1,z,x,w=r)+f(z-1,x,y,z=r)-~f(w,z,r):1

```

Try it online!

### Commented

```
f = (                     // f is a recursive function taking:
  x, y, z,                //   (x, y, z) = input integers
  w                       //   w = local variable
) =>                      //
x > (r = y) ?             // save y in the global r; if x is greater than y:
  f(x - 1, y, z) +        //   process the 1st recursive call
  f(y - 1, z, x, w = r) + //   save r in w and process the 2nd recursive call
  f(z - 1, x, y, z = r) - //   save r in z and process the 3rd recursive call
  ~f(w, z, r)             //   last recursive call, using the previous results
                          //   add all returned values together, and add 1
:                         // else:
  1                       //   stop and return 1

```

---

# JavaScript (ES6), 76 bytes

**Using a wrapper function**

Expects `[x, y, z]`.

Simply does exactly what is said on the tin.

```
a=>(r=0,(t=(x,y,z)=>++r&&x>y?t(t(x-1,y,z),t(y-1,z,x),t(z-1,x,y)):y)(...a),r)

```

Try it online!

# Answer
> 4 votes
# Jelly, (22?) 26 bytes

```
ṙJ_JỊ$ṙ-Ñ€Ñ
‘ɼṛṖṪÇ}ṢƑ?
Çṛ®

```

A full program that accepts a list of three non-negative integers, `[x, y, z]`, and prints the call count. (Or 22 bytes as a monadic Link that accepts the same and accumulates in the register (?) - remove the last line.)

**Try it online!** or see the test suite.

### How?

There's probably a clever way to produce the count, but this implements the description from the question.

```
ṙJ_JỊ$ṙ-Ñ€Ñ - Link 1: [x, y, z]
 J          - indices {[x, y, z]} -> [1, 2, 3]
ṙ           - {[x, y, z]} rotate left by -> [[y, z, x], [z, x, y], [x, y, z]]
     $      - last two links as a monad - f([x, y, z]):
   J        -   indices {[x, y, z]} -> [1, 2, 3]
    Ị       -   insignificant?      -> [1, 0, 0]
  _         - subtract     -> [[y-1, z, x], [z-1, x, y], [x-1, y, z]]
      ṙ-    - rotate right -> [[x-1, y, z], [y-1, z, x], [z-1, x, y]]
        Ñ€  - call Link 2 for each
          Ñ - call link 2
           -

‘ɼṛṖṪÇ}ṢƑ? - Link 2, t: [x, y, z]
 ɼ         - apply to the register and yield:
‘          -   increment
   Ṗ       - pop {[x, y, z]} -> [x, y]
  ṛ        - right argument -> [x,y]
         ? - if...
        Ƒ  - ...condition: is {[x, y]} invariant under?:
       Ṣ   -                 sort
    Ṫ      - ...then: tail -> y
     Ç}    - ...else: call Link 1 as a monad - f(x, y, z)

Çṛ® - Main Link: [x, y, z]
Ç   - call Link 2 as a monad - t(x, y, z)
  ® - recall from the register -> count
 ṛ  - right argument -> count

```

# Answer
> 3 votes
# Perl 5 `-Mfeature+signatures -ap`, 83 bytes

```
sub f($x,$y,$z){++$;;$y<$x?f(f($x-1,$y,$z),f($y-1,$z,$x),f($z-1,$x,$y)):$y}f@F;$_=$

```

Try it online!

# Answer
> 1 votes
# Python 2, 103 bytes

```
def t(x,y,z):t.c+=1;return t(t(x-1,y,z),t(y-1,z,x),t(z-1,x,y))if x>y else y
t.c=0
t(*input())
print t.c

```

Attempt This Online!

# Answer
> 0 votes
# Charcoal, 116 bytes

```
≔⦃⦄θ⊞υＥ³ＮＦυ«≔Ｉ⪫()⪫ι,ηＦ¬§θη¿‹§ι¹§ι⁰«≔ＥιＥι⁻§ι⁺μξ¬ξζ⊞ζＥζ§λ∨¬‹§λ¹§λ⁰⊗¬‹§λ²§λ¹≔Ｅζ§θＩ⪫()⪫λ,ε¿⬤ελ§≔θη⊕ΣεＦ⊞Ｏζι⊞υλ»§≔θη¹»Ｉ§θη

```

Attempt This Online! Link is to verbose version of code. Explanation: Charcoal isn't really suited for this.

```
≔⦃⦄θ

```

Start with an empty dictionary which will hold `T(x, y, z)` for each required tuple.

```
⊞υＥ³Ｎ

```

Start with the input tuple.

```
Ｆυ«

```

Loop over the required tuples as they are found.

```
≔Ｉ⪫()⪫ι,η

```

Convert the tuples from a list to a Python tuple so that they can be used as a dictionary key.

```
Ｆ¬§θη

```

Test to see whether this tuple's `T` value is already known.

```
¿‹§ι¹§ι⁰«

```

Test to see whether this is a trivial tuple.

```
≔ＥιＥι⁻§ι⁺μξ¬ξζ

```

Generate the dependent tuples, `(x-1, y, z)`, `(y-1, z, x)` and `(z-1, x, y)`.

```
⊞ζＥζ§λ∨¬‹§λ¹§λ⁰⊗¬‹§λ²§λ¹

```

Also generate the fourth tuple by calculating `t` for each of these tuples nonrecursively.

```
≔Ｅζ§θＩ⪫()⪫λ,ε

```

Get any `T` values we have for these tuples already.

```
¿⬤ελ

```

If all of these tuples already have `T` values, then...

```
§≔θη⊕Σε

```

... take the sum and set this as the `T` value for the required tuple.

```
Ｆ⊞Ｏζι⊞υλ

```

Otherwise push all of the tuples to the list for reprocessing because it's simpler that way.

```
»§≔θη¹

```

If this is a trivial tuple then just set its `T` value to `1`.

```
»Ｉ§θη

```

Output the `T` value of the input tuple.

# Answer
> 0 votes
# 05AB1E, 30 bytes

```
"¼Â¦`@iÅsë2Ý._εć<š®.V}®.V"©.V¾

```

Input as a triplet \\$\[x,y,z\]\\$.

Try it online or verify all test cases.

**Explanation:**

```
"..."        # Push the recursive string explained below
     ©       # Store it in variable `®` (without popping)
      .V     # Pop and evaluate it as 05AB1E code
        ¾    # Push counter variable `¾`
             # (which is output implicitly as result)

¼            # Increase the counter variable `¾` by 1 (starts at 0 by default)
Â            # Bifurcate the current triplet; short for Duplicate & Reverse copy
             # (which will use the implicit input-triplet in the first iteration)
 ¦           # Remove the first item of the reversed triplet (the z)
  `          # Pop and push y and x separated to the stack
   @i        # Pop both, and if x>=y:
     Ås      #  Pop the triplet, and push its middle: y
    ë        # Else:
     2Ý      #  Push list [0,1,2]
       ._    #  Rotate the triplet that many times towards the left: [[x,y,z],[y,z,x],[z,x,y]]
     ε       #  Map over each rotated triplet:
      ć      #   Extract its head; push remainder-pair and first item separately
       <     #   Decrease this first item by 1
        š    #   Prepend it back to the pair
         ®.V #   Do a recursive call by evaluating string `®`
     }®.V    #  After the map: do a recursive call on the resulting triplet as well

```

# Answer
> 0 votes
# AWK, 82 bytes

```
func t(x,y,z){$0=++c;return x>y?t(t(x-1,y,z),t(y-1,z,x),t(z-1,x,y)):y}t($1,$2,$3)1

```

Attempt This Online!

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


# Question
Title: Generate a sequence of \$n\$ consecutive composite numbers
# Definitions

The common methods to generate consecutive composites are

$$\overbrace{(n+1)! + 2, \ (n+1)! + 3, \ \ldots, \ (n+1)! + (n+1)}^{\text{n composites}}$$

$$\overbrace{n!+2,n!+3,...,n!+n}^{\text{n-1 composites}}$$

$$\overbrace{n\\#+2,n\\#+3,…n\\#+n}^{\text{n-1 composites (Primorials)}}$$

---

A less common method involves the Chinese Remainder Theorem (CRT).

For example, define a list of \\$n\\$ pairwise coprimes \\$p\_1, p\_2, \ldots, p\_n\\$.

> A set of integers can also be called coprime if its elements share no common positive factor except 1. A stronger condition on a set of integers is **pairwise coprime**, which means that \\$a\\$ and \\$b\\$ are coprime for every pair \\$(a, b)\\$ of different integers in the set. The set \\$\\{2, 3, 4\\}\\$ is coprime, but it is not pairwise coprime since 2 and 4 are not relatively prime.

Create a set of \\$n\\$ congruences

\begin{align\*} x + 1 &\equiv 0 \pmod{p\_1} \\ x + 2 &\equiv 0 \pmod{p\_2} \\ &\vdots \\ x + n &\equiv 0 \pmod{p\_n} \end{align\*}

By CRT, there exists a unique solution \\$x\\$ which satisfies this sequence of \\$n\\$ consecutive composite numbers:

$$x + 1, x + 2, \ldots, x + n$$

> A **composite number** is a positive integer that can be formed by multiplying two smaller positive integers. Equivalently, it is a positive integer that has at least one divisor other than 1 and itself.

---

# Challenge

Given pairwise coprime inputs, find the smallest range of consecutive composite numbers.

**Input**

A list of \\$n\\$ pairwise coprimes.

**Output**

A sequence of \\$n\\$ consecutive composite numbers.

# Test Cases

These cases were derived from this test.

| n | pairwise coprimes | consecutive composites |
| --- | --- | --- |
| 2 | 2, 3 | 8,9 |
| 3 | 7, 11, 23 | 1792, 1793, 1794 |
| 4 | 2, 3, 5, 7 | 158, 159, 160, 161 |
| 5 | 3, 7, 10, 13, 23 | 47928, 47929, 47930, 47931, 47932 |

Added a JavaScript (V8) tool to validate if the input numbers are pairwise coprime.

# Answer
# Jelly, 11 bytes

```
V+€J%ÞfÞẒƇḢ

```

A monadic Link that accepts a list of pairwise coprime integers and yields a run of the same number of consecutive composites.

**Try it online!**

### How?

Uses the Chinese Remainder theorem in the most naive way possible, systematic search.

```
V+€J%ÞfÞẒƇḢ - Link: Coprimes
V           - Digit-smash {Coprimes}
              (e.g. [2, 11, 17] -> 21117 -- N.B. V >= Product+Max so is sufficient*)
   J        - 1-indexed indices {Coprimes} -> [1..n=length(Coprimes)]
  €         - for each {v in [1..2P]}:
 +          -   {v} add {[1..n]} (vectorises)
     Þ      - sort by:
    %       -   modulo {Coprimes} (vectorises)
       Þ    - sort by:
      f     -   keep those which are in:
         Ƈ  -     {Comprimes} for which:
        Ẓ   -       is prime?
         Ḣ - head

```

---

* Thanks to Leo for this proof that the digit concatenation performed by `V` is guaranteed to be greater than or equal to the product plus the maximum that we may need to search through:

The concatenation \\$a|b\\$ of two positive numbers \\$a\\$ and \\$b\\$ is equal to \\$a\times c + b\\$, where \\$c\\$ is the first power of \\$10\\$ larger than \\$b\\$ (i.e. \\$c = 10^{\lfloor 1 + \log\_{10}{b} \rfloor}\\$).

Since \\$c \ge b + 1\\$ we get \\$a|b \ge a \times (b + 1) + b = a \times b + a + b\\$.

As such the concatenation of two numbers is always at least as large as their product plus their sum. This then extends to more terms as each of the operations, concatenation and taking a product, may be applied in succession.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 67 bytes

```
((r=Range@Tr[1^#])+ChineseRemainder[-r,#,If[Or@@PrimeQ@#,Tr@#,1]])&

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~18~~ 15 bytes

```
ā∞sδ+ʒp≠P}.ΔIÖP

```

Try it online or verify all test cases.

**Explanation:**

```
ā               # Push a list in the range [1, (implicit) input-length]
 ∞              # Push an infinite positive list: [1,2,3,...]
  s             # Swap so the [1,length] list is at the top again
   δ            # Pop both lists, and apply double-vectorized:
    +           #  Add the values together
     ʒp≠P}      # Filter, and remove all overlapping lists that contain primes
          .Δ    # Then find the first list that's truthy for:
            IÖ  #  Check for each value whether its divisible by the input-value at the
                #  same position
              P #  Check whether this is truthy for all of them
                # (after which the found result is output implicitly)

```
> 1 votes

# Answer
# Retina, 63 bytes

```
.+
*_,$:&*
/\b((_+)_+),\1*\2\b|,(?!(__+)\3+\b)/+%`$
_
L$`,
$.%'

```

Try it online! Takes input on separate lines but link is to test suite that converts from and to comma separated for convenience. Explanation: Brute force, so last test case was omitted for speed.

```
.+
*_,$:&*

```

Convert each input to unary and append its index.

```
/\b((_+)_+),\1*\2\b|,(?!(__+)\3+\b)/+`

```

While there is a non-composite output or an output that isn't divisible by an input, ...

```
%`$
_

```

... increment all of the outputs.

```
L$`,
$.%'

```

Delete the inputs and convert the outputs to unary.
> 1 votes

# Answer
# C (gcc), ~~563~~ 461 bytes

*-102 bytes, thanks to @ceilingcat*

The GNU Multiple Precision Arithmetic Library. GMP

```
#import<gmp.h>
i;f(a,b)int a[];{mpz_t c[b],d[i=b],e,f,g,h,j,k;mpz_inits(e,f,g,h,j,k,0);for(mpz_set_ui(f,1);i--;mpz_mul(f,f,c[i]))mpz_inits(c[i],d[i],0),mpz_set_ui(c[i],a[i]),mpz_set_si(d[i],~i);for(;++i<b;mpz_add(e,e,g))mpz_divexact(j,f,c[i]),mpz_invert(k,j,c[i]),mpz_mul(g,d[i],k),mpz_mul(g,g,j);for(mpz_mod(e,e,f);i--;)mpz_probab_prime_p(c[i],15)?mpz_add_ui(g,e,i+1),i=!mpz_cmp(g,c[i])?mpz_add(e,e,f),0:i:0;for(;b/i;gmp_printf("%Zd ",h))mpz_add_ui(h,e,-i--);}

```

Try it online!
> 0 votes

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


title: Find the "Bittiest" Number

text:
# Question
Title: Find the "Bittiest" Number
## The Challenge

Given a list of integers, the "bittiest" number among them is the one with the most bits on - that is, the largest amount of bits set to 1 in its 32-bit two's complement representation.

Write a function (or a program) that takes as input a list of integers between \\$ -2^{31} \\$ and \\$ 2^{31}-1 \\$ (the range of 32-bit signed integers) and returns as output the "bittiest" number among them.

You may assume the list has at least one item.

## Test Cases

```
1, 2, 3, 4 => 3
123, 64, 0, -4 => -4
7, 11 => either 7 or 11
1073741824, 1073741823 => 1073741823

```

Good Luck!

This is code golf, so the shortest program in bytes wins.

# Answer
# Jelly, ~~13~~ ~~12~~ 8 bytes

```
%Ø%B§µÞṪ

```

Try it online!

## Explanation

```
     µÞ  | sort input by
%Ø%      | modulo by 2^32 (Ø% is a quick for 2^32)
   B     | converted to binary
    §    | sum
       Ṫ | get the last

```

Edit: thank you all for the kind response to my first question! I think I've fixed it now, it seems to work for all test cases.

## Original code

```
2*31
B%¢S€iṀị

```
> 10 votes

# Answer
# x86 Machine Language, 18 bytes

```
31 D2 AD F3 0F B8 F8 39 FA 77 03 87 FA 93 E2 F2 93 C3

```

The above bytes define a function that accepts the address of the array in the `esi` register and the number of elements in the array in the `ecx` register, and returns the "bittiest" number in the array in the `eax` register.

Note that this is a custom calling convention that accepts arguments in the `ecx` and `esi` registers, but it is otherwise much like a C function that takes the length of the array and a pointer to the array as its two arguments. This custom calling convention treats all registers as caller-save, including `ebx`.

The implementation of this function pulls some dirty tricks, which assume that the array has at least 1 element, as provided for in the challenge. It also assumes that the direction flag (`DF`) is clear (`0`), which is standard in all calling conventions that I'm aware of.

In ungolfed assembly-language mnemonics:

```
; ecx = length of array
; esi = address of first element in array
Find:
    31 D2          xor    edx, edx                ; start with max bit count set to 0
Next:
    AD             lods   eax, DWORD PTR [esi]    ; load the next value from the array, and
                                                  ;   increment ptr by element size
    F3 0F B8 F8    popcnt edi, eax                ; count # of set bits in value
    39 FA          cmp    edx, edi                ; if # of set bits in value is less than
    77 03          ja     SHORT Skip              ;   the running maximum, skip next 2 insns
    87 FA          xchg   edx, edi                ; save current # of set bits (for comparisons)
    93             xchg   eax, ebx                ; save current array value (for comparisons)
Skip:
    E2 F2          loop   SHORT Next              ; decrement element count, looping until it is 0
    93             xchg   eax, ebx                ; move running maximum value to eax
    C3             ret                            ; return, with result in eax

```

The key feature of this code is, of course, the x86 `popcnt` instruction, which counts the number of set bits in an integer. It iterates through the input array, keeping track of both the value of the maximum element and the number of set bits that it contains. It checks each value in the array to see if its number of set bits is higher than any value it has seen before. If so, it updates the tracking values; if not, it skips this step.

The `popcnt` instruction is a large (4-byte) instruction, but there's nothing that can be done to avoid that. However, the very short (1-byte) `lods` instruction has been used to load values from the array while simultaneously incrementing the pointer, the short (2-byte) `loop` instruction has been used for loop control (automatically decrementing the element counter and looping as long as there are more elements remaining to go through), and the very short (1-byte) `xchg` instruction has been used throughout.

An extra `xchg` had to be used at the end in order to enable use of the `lods` instruction, which *always* loads into the `eax` register, but that trade-off is more than worth it.

## Try it online!

My first attempt was a 20-byte function. So far, 18 bytes is the best I have been able to come up with. I'm curious to see if anyone else can beat this score!

The only route of improvement that I see would be if a `LOOPA` instruction existed. Unfortunately, it doesn't—the only condition codes supported by `LOOP` are `E`/`Z` and `NE`/`NZ`. But maybe someone else can stretch their mind further than me!
> 26 votes

# Answer
# JavaScript (ES6),  ~~49 48 47~~  45 bytes

*Saved 2 bytes thanks to @user81655*

```
a=>a.sort(g=(p,q)=>!p|-!q||g(p&p-1,q&q-1))[0]

```

Try it online!

### How?

We `.sort()` the input list with a recursive function that, given `p` and `q`, clears the least significant bit set in each variable until one of them is equal to 0 (or both of them simultaneously). This allows to order the list from most to least bits set. We then return the first entry, i.e. the "bittiest" one.

### Commented

```
a =>                 // a[] = input list
  a.sort(            // sort a[] ...
    g = (p, q) =>    // ... using the recursive function g:
      !p | -!q       //     -> +1 if p = 0 and q ≠ 0,
                     //     or -1 if q = 0,
      ||             //     or  0 if p ≠ 0 and q ≠ 0, in which case ...
        g(           //     ... we do a recursive call:
          p & p - 1, //       clear the least significant bit set in p
          q & q - 1  //       clear the least significant bit set in q
        )            //     end of recursive call
  )[0]               // end of sort(); return the first entry

```
> 18 votes

# Answer
# APL (Dyalog Unicode), 15 bytes

Saved many bytes thanks to Adam and ngn.

```
{⊃⍒+⌿⍵⊤⍨32⍴2}⊃⊢

```

Try it online!
> 9 votes

# Answer
# C (gcc), ~~80~~ 77 bytes

Saved 3 bytes thanks to att!!!

```
#define b __builtin_popcount(f(n,l
f(n,l)int*l;{n=--n?f(n,l+(b))<b+1)))):*l;}

```

Try it online!
> 8 votes

# Answer
# C++ (GCC), ~~145~~ ~~141~~ ~~140~~ ~~135~~ ~~134~~ ~~133~~ ~~130~~ ~~128~~ 116 bytes

145-\>141 thanks to user
128-\>116 thanks to ceilingcat

```
#import<bits/stdc++.h>
int i,b,v,c;main(){for(;std::cin>>i;b<c?b=c,v=i:0)c=std::bitset<32>(i).count();std::cout<<v;}

```

Try it online!
> 7 votes

# Answer
# Kotlin, ~~41~~ ~~38~~ 29 bytes

Correct code with much fewer bytes :) { Thanks @vrintle }

```
{it.maxBy{it.countOneBits()}}

```

Kotlin Playground

---

```
{it.maxBy{it.toByte().countOneBits()}}

```

Kotlin Playground

---

```
{it.maxBy{it.toString(2).count{it=='1'}}}

```

Try it online!
> 7 votes

# Answer
# 05AB1E, 9 bytes

```
ΣžJ%b1¢}θ

```

Try it online!

```
ΣžJ%b1¢}θ  # full program
        θ  # last element of...
           # implicit input...
Σ          # sorted in increasing order by...
      ¢    # number of...
     1     # ones...
      ¢    # in...
           # (implicit) current element in list...
   %       # modulo...
 žJ        # 4294967296...
    b      # in binary
           # implicit output

```
> 6 votes

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

```
{*x@>+/2\x}

```

Try it online!
> 5 votes

# Answer
# , ~~58~~ ~~55~~ 54 bytes

```
function(x)x[order(colSums(sapply(x,intToBits)<1))][1]

```

Try it online!

-2 thanks to Robin Ryder

-1 thanks to Dominic van Essen.
> 4 votes

# Answer
# Stax, 18 bytes

```
é·║⌂╞8Q⌡ë♀NM╟¥É▌╦!

```

Run and debug it

Manually pads with 1s/0s to get the correct representation.

Displays a single number for each testcase.
> 4 votes

# Answer
# Python 3, 52 bytes

```
lambda l:max(l,key=lambda n:bin(n%2**31).count("1"))

```

Try it online!

`n%2**31` \- since in python integers are infinite, have to change negative numbers. for example `-4` becomes `2147483644`

`bin(...)` \- translate to binary format

`count("1")` \- count the number of units

---

# Python 3, 50 bytes

```
lambda n:n and n%2+z(n//b)
f=lambda l:max(l,key=z)

```

Try it online!

two bytes shorter, but doesn't work with negative numbers
> 4 votes

# Answer
# Scala, 54 42 40 36 bytes

Saved some bytes thanks to caird coinheringaahing, didymus, user, and some tips

```
_.maxBy(_.toBinaryString.count(48<))

```

Try it online!
> 4 votes

# Answer
# Husk, ~~17~~ ~~16~~ 13 bytes

*Edit: -1 byte thanks to Razetime, and then -3 bytes thanks to Leo*

```
►(ΣḋΩ≥0+^32 2

```

Try it online!

Husk natively uses arbitrary-precision integers, and so has no notion of 32-bit 2's complement for representing negative 4-byte signed integers: as a result, the 'get binary digits' function -  \- is sadly useless here for negative inputs.
So we need to calculate the '2's complement bittiness' by hand.

Thanks to Husk help from Leo for the use of `Ω` here.

```
►                       # element of input that maximises result of:
 (Σḋ                    # sum of binary digits of
    Ω                   # repeat until result is
     ≥0                 # greater than or equal to zero:
       +^32 2           # add 2^32

```
> 3 votes

# Answer
# Japt `-h`, 10 bytes

```
ñÈu2pH)¤¬x

```

Try it

```
ñÈu2pH)¤¬x     :Implicit input of array
ñ              :Sort by
 È             :Passing each element through the following function
  u            :Positive modulo
   2p          :  2 raised to the power of
     H         :  32
      )        :End modulo
       ¤       :To binary string
        ¬      :Split
         x     :Reduce by addition
               :Implicit output of last element

```
> 3 votes

# Answer
# Jelly, 9 8 bytes

```
%Ø%BSƲÞṪ

```

Try it online!

*-1 byte by using `Þ` (sort) instead of `ÐṀ` (maximum). This was inspired by Gio D's answer and after their and my edit, both solutions are pretty much the same.*

## Explanation

```
%Ø%BSƲÞṪ   Main monadic link
      Þ    Sort by
     Ʋ     (
%            Modulo
 Ø%            2^32
   B         Binary
    S        Sum
     Ʋ     )
       Ṫ   Last item

```
> 3 votes

# Answer
# Java 10, 73 bytes

```
a->{int r=0,m=0,t;for(var i:a)if((t=i.bitCount(i))>m){m=t;r=i;}return r;}

```

Try it online.

**Explanation:**

```
a->{                     // Method with Integer-array parameter and int return-type
  int r=0,               //  Result-integer, starting at 0
      m=0,               //  Maximum bit-count integer, starting at 0
      t;                 //  Temp integer, uninitialized
  for(var i:a)           //  Loop over each Integer in the input-array:
    if((t=i.bitCount(i)) //   If its amount of 1s in the binary representation
       >m){              //   is larger than the current maximum:
      m=t;               //    Update the maximum with this bit-count
      r=i;}              //    And update the result with this integer
  return r;}             //  After the loop, return the resulting integer

```
> 3 votes

# Answer
# Perl 5 `-pa`, ~~54~~ 45 bytes

```
map$a[(sprintf"%b",$_)=~y/1//]=$_,@F;$_=pop@a

```

Try it online!
> 2 votes

# Answer
# Ruby 2.7, ~~36~~ ~~33~~ 34 bytes

*Thanks to Dingus for correcting my code for a special case! :)*

```
p$*.max_by{("%034b"%_1)[2,32].sum}

```

Try it online!

Uses command-line args for input, outputs the *bittiest number* as a string. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes.
> 2 votes

# Answer
# Java (JDK), 44 bytes

```
a->a.max((x,y)->x.bitCount(x)-x.bitCount(y))

```

Try it online!

This is kind of cheating, as it accepts a `Stream<Integer>` as input and returns an `Optional<Int>`.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~71~~ 58 bytes

```
l=>l.OrderBy(r=>Convert.ToString(r,2).Sum(c=>c-48)).Last()

```

Try it online!

* Refactored to use a lambda as suggested by @user in comments
> 2 votes

# Answer
# Scala, 24 bytes

```
_ maxBy Integer.bitCount

```

Try it online!

Split off from Gabber's great first answer.
> 2 votes

# Answer
# Zsh, 71 bytes

Try it Online! ~~81bytes~~ ~~85bytes~~

```
for i;a=${$((i<0?[##2]2**32+i:[##2]i))//0}&&(($#a>b?(j=i,b=$#a)))
<<<$j

```

Great challenge, required some of the weirdest `Zsh` incantations! Explanation:
`for i;` ... implicit iteration over all arguments
`$((i<0?[##2]2**32+i:[##2]i))` ... convert `i` to 32-bit format, using two's complement trick if `i<0`
`a=${ ~string~ //0}` ... remove all `0`s from string
`(($#a>b?(j=i,b=$#a)))` ... keep track of which input `i` is the "**b**ittiest" according to the length of string `a`
`<<<$j` ... output the winner
> 2 votes

# Answer
# Charcoal, 22 bytes

```
≔ＥθΣ⍘﹪ιＸ²¦³²¦²ηＩ§θ⌕η⌈η

```

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

```
≔ＥθΣ⍘﹪ιＸ²¦³²¦²η

```

For each number in the list, cast it to a 32-bit unsigned number, convert it to binary, and sum the bits.

```
Ｉ§θ⌕η⌈η

```

Output the number at the position of the highest bit count.
> 1 votes

# Answer
## SystemVerilog, 66 bytes

This will be an imperfect answer for now as I’m posting from my phone, but SV’s`$countones()` function is perfect here.

```
function m(int q[$]);
m=q.max with ($countones(item));
endfunction

```
> 1 votes

# Answer
# PowerShell, 53 56 bytes

+5 bytes because it did not handle negatives properly
-2 bytes thanks to mazzy

```
$args|sort{$v=$_;0..31|%{$o+=!!(1-shl$_-band$v)};$o}-b 1

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 39 bytes

```
Last@*SortBy[Mod[#,2^32]~DigitCount~2&]

```

Try it online!
> 1 votes

# Answer
# Nim, 75 bytes

```
import algorithm,bitops
func b(n:seq):int=n.sortedByIt(it.countSetBits)[^1]

```

Try it online!
> 1 votes

# Answer
# , 20 bytes

```
{.@\:[:+/"1(32$2)&#:

```

As written, when given multiple equally, maximally bitty numbers, returns the first in the array. If `{.\:` is changed to `{:/:`, it gives the last. Try it online!
> 1 votes

# Answer
## AArch64, 48 44 bytes

Raw instructions (32-bit little endian hex):

```
1e2703e4 bc404400 0e205801 2e303821
0ea43c23 2ea31c02 2ea31c24 f1000421
54ffff21 1e260040 d65f03c0

```

Uncommented assembly:

```
        .globl bittiest
bittiest:
        fmov    s4, #0
.Lloop:
        ldr     s0, [x0], #4
        cnt     v1.8b, v0.8b
        uaddlv  h1, v1.8b
        cmge    v3.2s, v1.2s, v4.2s
        bit     v2.8b, v0.8b, v3.8b
        bit     v4.8b, v1.8b, v3.8b
        subs    x1, x1, #1
        bne     .Lloop
        fmov    w0, s2
        ret

```

### Explanation

C function signature:

```
int32_t bittiest(int32_t *words, size_t len);

```

Pseudo-C:

```
int32_t bittiest(int32_t *words, size_t len)
{
    int32_t maxcount = 0;
    int32_t maxvalue;
    do {
        int32_t value = *words++;
        int8_t counts[4] = popcount8x4((int8_t *)&value);
        int32_t count = counts[0] + counts[1] + counts[2] + counts[3];
        if (count >= maxcount) {
            maxvalue = value;
            maxcount = count;
        }
    } while (--len);
    return maxvalue;
}

```

AArch64's population count instruction is in NEON (the SIMD/floating point instruction set), and it counts each byte individually. Therefore, it is a little awkward to work with scalars here so we do everything in NEON.

v4 is the max population count (v4, s4, h4, and d4 all refer to the same register). Set it to 0.

```
        fmov    s4, #0

```

Load the next int32 word into v0, and increment words (x0) by 4.

```
        ldr     s0, [x0], #4

```

Store the population count of each byte in v0 into the corresponding byte in v1.

```
        cnt     v1.8b, v0.8b

```

Add all of the 8-bit lanes in v1 together to get the full population count, and store into v1 again.

```
        uaddlv  h1, v1.8b

```

Compare the population count of this word to the maximum. If it is larger or equal, v3 will be all 1 bits (true), otherwise it will be all 0 bits (false).

```
        cmge    v3.2s, v1.2s, v4.2s

```

If v3 is true, set the max word (v2) to the current word. max is not initialized on the first iteration, but it will always be set because the population count will always be \>= 0.

```
        bit     v2.8b, v0.8b, v3.8b

```

Same, but for the new max population count.

```
        bit     v4.8b, v1.8b, v3.8b

```

Decrement len (x1), and loop if it is not zero

```
        subs    x1, x1, #1
        bne     .Lloop

```

End of loop: Move the maximum value from a NEON register to the return register (w0), and return.

```
        fmov    w0, s2
        ret

```

11 instructions = 44 bytes
> 1 votes

# Answer
# K4, 15 bytes

**Solution:**

```
{*x@>+/+0b\:'x}

```

**Explanation:**

Pretty much exactly the same as the ngn/k solution:

```
{            x} / lamdba taking implicit argument x
        0b\:'   / convert (0b \:) each (') to binary representation
       +        / flip (transpose)
     +/         / sum (+) over (/)
    >           / indices to sort descending
  x@            / apply indices to input x
 *              / take the first

```
> 1 votes

# Answer
# Julia 1.0, 28 bytes

```
x->x[argmax(count_ones.(x))]

```

Try it online!
> 0 votes

---
Tags: code-golf, binary
---