title: Construct the Identity Matrix

text:
# Question
Title: Construct the Identity Matrix
The challenge is very simple. Given an integer input `n`, output the `n x n` identity matrix. The identity matrix is one that has `1`s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

**Example input and output**

```
1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.

```

This is , so the shortest code in bytes wins.

# Answer
# MATL, 2 bytes

```
Xy

```

A translation of my Octave answer.

Try it online.

A 4 byte version with no built-ins (thanks to Luis Mendo):

```
:t!=
:     take input n and a generate row array [1,2,...n]
 t    duplicate
  !   zip
   =  thread compare over the result

```
> 26 votes

# Answer
## TI-BASIC, 2 bytes

```
identity(Ans

```

Fun fact: The shortest way to get a list `{N,N}` is `dim(identity(N`.

Here's the shortest way without the builtin, in 8 bytes:

```
randM(Ans,Ans)^0

```

`randM(` creates a random matrix with entries all integers between -9 and 9 inclusive (that sounds oddly specific because it is). We then take this matrix to the 0th power.
> 20 votes

# Answer
# Julia, ~~9~~ 3 bytes

```
eye

```

This is just a built-in function that accepts an integer `n` and returns an `nxn Array{Float64,2}` (i.e. a 2D array). Call it like `eye(n)`.

Note that submissions of this form are acceptable per this policy.
> 18 votes

# Answer
# APL, 5 bytes

```
∘.=⍨⍳

```

This is a monadic function train that accepts an integer on the right and returns the identity matrix.

Try it here
> 18 votes

# Answer
## Python 2, 42 bytes

```
lambda n:zip(*[iter(([1]+[0]*n)*n)]*n)[:n]

```

An anonymous function, produces output like `[(1, 0, 0), (0, 1, 0), (0, 0, 1)]`,

First, creates the list `([1]+[0]*n)*n`, which for `n=3` looks like

```
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

```

Using the zip/iter trick `zip(*[iter(_)]*n` to make groups of `n` gives

```
[(1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]

```

Note that the `1` comes one index later each time, giving the identity matrix. But, there's an extra all-zero row, which is removed with `[:n]`.
> 16 votes

# Answer
# Octave, ~~10~~ 4 bytes

```
@eye

```

Returns an anonymous function that takes a number `n` and returns the identity matrix.
> 14 votes

# Answer
# R, 4 bytes

```
diag

```

When given a matrix, `diag` returns the diagonal of the matrix. However, when given an integer `n`, `diag(n)` returns the identity matrix.

Try it online
> 12 votes

# Answer
# Jelly, 4 bytes

```
R=€R

```

Doesn't use a built-in. Try it online!

### How it works

```
R=€R    Main link. Input: n

R       Range; yield [1, ..., n].
   R    Range; yield [1, ..., n].
 =€     Compare each.
        This compares each element of the left list with the right list, so it
        yields [1 = [1, ..., n], ..., n = [1, ..., n]], where comparison is
        performed on the integers.

```
> 10 votes

# Answer
# J, 4 bytes

```
=@i.

```

This is a function that takes an integer and returns the matrix.
> 10 votes

# Answer
# JavaScript ES6, ~~68~~ ~~62~~ 52 bytes

*Saved 10 bytes thanks to a neat trick from @Neil*

```
x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z)))

```

Trying a different approach than @Cᴏɴᴏʀ O'Bʀɪᴇɴ's. Could possibly be improved.
> 8 votes

# Answer
**Haskell, ~~43~~ 37 bytes**

```
f n=[[0^abs(x-y)|y<-[1..n]]|x<-[1..n]]

```

Pretty straightforward, though I think one can do better (without a language that already has this function built in, as many have done).

Edit: dropped some bytes thanks to Ørjan Johansen
> 8 votes

# Answer
# Pyth, 7 bytes

```
XRm0Q1Q

```

Try it online: Demonstration

Creating a matrix of zeros and replacing the diagonal elements with ones.
> 8 votes

# Answer
# Python 3, 48

Saved 1 byte thanks to sp3000.

I love challenges I can solve in one line. Pretty simple, build a line out of 1 and 0 equal to the length of the int passed in. Outputs as a 2d array. If you wrap the part after the : in `'\n'.join()`, it'll pretty print it.

```
lambda x:[[0]*i+[1]+[0]*(x+~i)for i in range(x)]

```
> 7 votes

# Answer
# Retina, 25

Credit to @randomra and @Martin for extra golfing.

```
\B.
 0
+`(.*) 0$
$0¶0 $1

```

Try it online.

Note this takes input as a unary. If this is not acceptable, then decimal input may be given as follows:

# Retina, 34

```
.+
$0$*1
\B.
 0
+`(.*) 0$
$0¶0 $1

```

Try it online.
> 7 votes

# Answer
# Haskell, 54 bytes

```
(#)=replicate
f n=map(\x->x#0++[1]++(n-x-1)#0)[0..n-1]

```

`f` returns the identity matrix for input n. Far from optimal.
> 6 votes

# Answer
# Lua, ~~77 75~~ 65 bytes

```
x,v=z.rep,io.read()for a=1,v do print(x(0,a-1)..'1'..x(0,v-a))end

```

Well, I'm not sure if lua is the best language for this with the two period concatenation... But hey, there's a shot at it. I'll see if there's any improvements to be made.

**EDIT:**

I figured something out on accident which I find rather odd, but, it works.

In Lua, everyone knows you have the ability to assign functions to variables. This is one of the more useful CodeGolf features.

This means instead of:

```
string.sub("50", 1, 1) -- = 5
string.sub("50", 2, 2) -- = 0
string.sub("40", 1, 1) -- = 4
string.sub("40", 2, 2) -- = 0

```

You can do this:

```
s = string.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

```

But wait, Lua allows some amount of OOP. So you could potentially even do:

```
z=""
s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

```

That will work as well and cuts characters.

Now here comes the weird part. You don't even need to assign a string at any point. Simply doing:

```
s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

```

Will work.

---

So you can visually see the difference, take a look at the golfed results of this:

**Using string.sub (88 characters)**

```
string.sub("50", 1, 1)string.sub("50", 2, 2)string.sub("40", 1, 1)string.sub("40", 2, 2)

```

**Assigning string.sub to a variable (65 characters)**

```
s=string.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

```

**Assigning string.sub using an OOP approach (64 characters)**

```
z=""s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

```

**Assigning string.sub using a.. nil approach? (60 characters)**

```
s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

```

If someone knows why this works, I'd be interested.
> 6 votes

# Answer
# C,  ~~59 or 59~~  56 or 56

Two versions of identical length.

3 bytes saved due to suggestion from anatolyg: `(n+1)` --\> `~n`

Iterates `i` from `n*n-1` to zero. Prints a 1 if i%(n+1) is zero, otherwise 0. Then prints a newline if `i%n`=0 otherwise a space.

```
i;f(n){for(i=n*n;i--;)printf(i%n?"%d ":"%d\n",!(i%~n));}

i;f(n){for(i=n*n;i--;)printf("%d%c",!(i%~n),i%n?32:10);}

```
> 6 votes

# Answer
# Mata, 4 bytes

```
I(3)

```

**Output**

```
[symmetric]
       1   2   3
    +-------------+
  1 |  1          |
  2 |  0   1      |
  3 |  0   0   1  |
    +-------------+

```

Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n\*n
> 6 votes

# Answer
# Brain-Flak, ~~206~~ ~~170~~ 162 bytes

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

```

Try it online!
> 6 votes

# Answer
# K6, 1 byte

```
=

```

`=` is exactly this

Try it online!
> 5 votes

# Answer
# Japt, ~~14~~ ~~12~~ 10 bytes

```
Uo £Z®¥X|0

```

Test it online! Note: this version has a few extra bytes to pretty-print the output.

```
Uo £Z®¥X|0    // Implicit: U = input integer
Uo £          // Create the range [0..U). Map each item X and the full array Z to:
    Z®        //  Take the full array Z, and map each item Z to:
      ¥X|0    //   (X == Z) converted to a number. 1 for equal, 0 for non-equal.
              // Implicit: output result of last expression

```
> 4 votes

# Answer
# K, 7 bytes

```
t=\:t:!

```

Take the equality cross product of two vectors containing \[0,n).

In action:

```
  t=\:t:!3
(1 0 0
 0 1 0
 0 0 1)
  t=\:t:!5
(1 0 0 0 0
 0 1 0 0 0
 0 0 1 0 0
 0 0 0 1 0
 0 0 0 0 1)

```
> 4 votes

# Answer
## Pyth, 8 bytes

```
mmsqdkQQ

```

Try it here.
> 4 votes

# Answer
# Mathematica, 14 bytes

```
IdentityMatrix

```

**Test case**

```
IdentityMatrix[4]
(* {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} *)

```
> 4 votes

# Answer
# Mathematica, 35 Bytes

without using IdentityMatrix

```
Table[Boole[i==j],{i,1,#},{j,1,#}]&

```
> 4 votes

# Answer
## Javascript, 40

```
f=
n=>'0'.repeat(n).replace(/./g,"$`1$'\n")

I.oninput=_=>O.innerHTML=f(+I.value)
I.oninput()
```

```
<input id=I value=5>
<pre id=O>
```
> 4 votes

# Answer
# , 28 bytes

```
function(n,x=1:n)+!x%o%x-x^2

```

Try it online!

For pure fun, just another attempt at a non-built-in R solution. Uses the shortcut `%o%` version of the `outer` function.
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
°¨œÙ

```

Try it online!

Unique permutations of (10^input)\[0:-1\]
> 4 votes

# Answer
# Jolf, 7 + 1 = 8 bytes

Replace all ☺s with `\x01` and `\xad` with a soft hyphen, or use the online interpreter. (Turn pretty output on for one byte.)

```
!☺!X\xad☺j
  !X       eye
    \xad☺   take one argument
         j  (the input)
!☺         get the data
           implicit printing

```

Probably more interesting, a solution without a builtin is 11 + 1 = 12 bytes

```
ZXZyjjdP=Sn
  Zyjj       create a matrix of width = height = j (input)
ZX    d      matrix map
        =Sn  if x-marker is y-marker
       P     as a number

```
> 3 votes

# Answer
# JavaScript, ~~75~~ 74 bytes

```
n=>eval("for(a=[],i=0;i<n;i++){a[i]=[];for(j=0;j<n;)a[i][j]=+(i==j++)};a")

```

Can be improved, probably.

## If `n=0` isn't necessary... 70 bytes

```
n=>eval("for(a=[i=0];i<n;i++)for(a[i]=[j=0];j<n;)a[i][j]=+(i==j++);a")

```
> 3 votes

# Answer
# Python 3.5 with NumPy - 57 49 30 bytes

```
import numpy
numpy.identity

```

NumPy.identity takes in an integer, n, and returns a n by n identity matrix. This answer is allowable via this policy.
> 3 votes

# Answer
# Java, 60 bytes

```
n->{int[][]i=new int[n][n];for(;n-->0;)i[n][n]=1;return i;};

```

Creates a 2D array and replaces elements where row and column are equal with `1`.
> 3 votes

# Answer
# CJam, 7 bytes

```
{,_ff=}

```

This is a code block that pops an integer from the stack and pushes a 2D array in return.

Try it online!
> 3 votes

# Answer
## Perl, ~~39~~ 33 bytes

```
/$/,say map$`==$_|0,@%for@%=1..<>

```

Thanks to Ton Hospel for saving 6 bytes

Running with the `-E` perlrun:

```
$ echo 3 | perl -E'@%=1..<>;$a=$_,say map{$a==$_|0}@%for@%'
100
010
001

```
> 3 votes

# Answer
# R, 50 bytes

```
f=function(n)matrix(c(1,rep(c(rep(0,n),1),n-1)),n)

```

Without using diag(), because I started coding without checking if there was a command for that... Also, I like my solution, despite being way too long.
> 3 votes

# Answer
# , ~~32~~ 31 bytes

```
function(n)+outer(1:n,1:n,"==")

```

Try it online!

*Thanks to Kirill L. for -1 byte*

Alternative to Ivanneke's solution, but obviously far longer than just plain old `diag`.
> 3 votes

# Answer
# Octave, 15 bytes

Because built-ins are no fun!

```
@(x)(k=1:x)==k'
@(x)~~diag(1:x)

```

Try it online!

The first one creates a vector from `1, 2, .. x`, and compares it to itself transposed, expanding it to a square matrix where the diagonal elements are `1`.

The second one creates a diagonal matrix with `1, 2, .. x` is on the diagonal, then negates it twice, to get the diagonal equal `1, 1, .. 1`.
> 3 votes

# Answer
## PowerShell, 52 bytes

```
param($a)1..$a|%{$d++;(1..$a|%{+($d-eq$_)})-join' '}

```

Since the only built-in .NET class for matrices is ... umm ... inadequate, shall we say, we're just going to construct and output a string representation here...

Takes input `$a` then executes a double-for-loop over range `1..$a`. Each outer loop we increment helper variable `$d` (the first loop, since `$d` isn't initialized, turns `$d++` into `$null + 1 = 1` ... in PowerShell logic it makes sense), and each inner loop is simply an integer-cast with `+` of an equality between `$d` and the current element `$_`. Each inner loop is `-join`ed together with spaces so it prints nicely, and each outer loop causes a newline, so output code is pretty cheap.

### Example

```
PS C:\Tools\Scripts\golfing> .\construct-identity-matrix.ps1 10
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

```
> 2 votes

# Answer
## Haskell, 27 bytes

```
import Data.Matrix
identity

```

Maybe a little bit boring.

Usage example:

```
Prelude Data.Matrix> identity 4
( 1 0 0 0 )
( 0 1 0 0 )
( 0 0 1 0 )
( 0 0 0 1 )

```
> 2 votes

# Answer
# Ruby, ~~56~~ 48 bytes

```
->n{(([1]+[0]*n)*(n-1)+[1]).each_slice(n).to_a}

```

Explanation:

Concatenates `n - 1` sequences of `1` followed by `n` `0`s into an array, and appends `1` to the end. Then slices the result into `n` arrays of length `n` and evaluates to an array having the slices as its elements.

Per Alex A., shaved 8 bytes by putting it in the form of a lambda.
> 2 votes

# Answer
# Perl 6,  ~~41 37~~  35 bytes

```
{$/=1..$_;$/.map: {$/.map: {+($^a==$_)}}} # 41 bytes
{$/=1..$_;$/.map: {$/.map: +(*==$_)}}     # 37 bytes
{$_=1..$^a;.map: {.map: +(*==$^a)}}       # 35 bytes

```

This outputs a list of lists.

### Usage:

```
# give it a lexical name
my &identity-matrix = {…}

# format it so that it is readable
sub readable ( @_ ) { @_.join: "\n" }

say readable identity-matrix 10

```

```
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

```
> 2 votes

# Answer
# Ruby,38 bytes

Returns a 2D array.

```
->n{(0..n-1).map{|i|s=[0]*n;s[i]=1;s}}

```

Iterates through each row of the array. For each iteration generates a row of `n` zeros, then changes one of them to a `1`

**Usage**

```
f=->n{(0..n-1).map{|i|s=[0]*n;s[i]=1;s}}
p f[5]

[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

```

**A different approach (string):**

# Ruby, 47 bytes

```
->n{(0..n-1).map{|i|s='0 '*n;s[i*2]=?1;puts s}}

```

for each row, makes a string of `'0 '`repeated `n` times, changes one of the `0`s to `1`, and prints it
> 2 votes

# Answer
# PARI/GP, ~~11~~ 5 bytes

```
matid

```

is sufficient, or

```
n->matid(n)

```

(11 bytes) as a 'roll-your-own' closure. If you want to work entirely by hand,

```
n->matrix(n,n,i,j,i==j)

```

(23 bytes) should suffice.
> 2 votes

# Answer
# Python 3, ~~116~~ 107 characters

```
def M(n):
 x=[]
 for i in range(n):
  r=[]
  for j in range(n):
   r+=[1 if i==j else 0]
  x+=[r]
 return x

```

### Output

```
iM(1)
[[1]]
iM(2)
[[1, 0], [0, 1]]
iM(3)

```
> 2 votes

# Answer
# Perl, ~~31~~ 24 bytes

Includes +3 for `-p` (code contains `'` so I can't just use the implied `-e`)

Run with the count on STDIN, e.g.

```
./diagonal.pl <<< 3

```

Outputs:

```
100
010
001

```

`diagonal.pl`:

```
#!/usr/bin/perl -p
$_=0 x$_;s/./$`1$'
/g

```
> 2 votes

# Answer
## Matlab, 3 bytes

```
eye

```

Does exactly this. `eye(n)` for an `n`-by-`n` matrix.

and also one without `eye`, 15 bytes:

```
diag(ones(1,n))

```
> 2 votes

# Answer
# Bash (w/ coreutils and awk), ~~51~~ ~~50~~ 45 bytes

```
yes 0|head -$((N*N))|xargs -n$N|awk {\$NR=1}1

```

## Usage

Set the `N` environment variable to the matrix size

```
$ N=5
$ yes 0|head -$((N*N))|xargs -n$N|awk {\$NR=1}1
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

```

## Explanation

* `yes 0` generates an endless stream of `0`s to `stdout`;
* `head -$((N*N))` takes the first N2 lines;
* `xargs -n$N` groups every N lines and outputs them together;
* `awk {\$NR=1}1` changes the value of the field whose index matches the line number to a `1` (otherwise it remains `0`) and then outputs the whole record.

There may be a shorter way to generate N2 lines of `0`s, but I haven't found one yet...
> 2 votes

# Answer
# APL (Dyalog Extended), 11 bytes

```
{⍵ ⍵⍴1,⍵/0}

```

Try it online!

Just for fun dfn submission

`⍵/0` replicate ⍵ zeros

`1,` prepend a 1

`⍵ ⍵⍴` mold to ⍵×⍵ square

So like for left argument 4 it will construct

```
1 0 0 0 0

```

And molding cycles from the beginning so, it will generate

```
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

```

the 4×4 identity matrix.
> 2 votes

# Answer
# Knight, 35 bytes

```
;=nP;=i~1W<=i+1i nO S*"0 "n *2i 1 1

```

Try it online!

Outputs a bunch of strings. It works by generating the string `0 0 ... 0`  (a space-separated string of \\$n\\$ `0`s), then changing the \\$2i\\$th character to `1` and outputting the result for each \\$i\\$ between \\$0\\$ and \\$n-1\\$.

Expanded code:

```
;=n PROMPT
;=i~1
WHILE <(=i +1 i) n
  OUTPUT (SET (*"0 " n) (*2 i) 1 1)

```
> 2 votes

# Answer
# Husk, 4 bytes

```
´Ṫ=ḣ

```

Try it online!

```
´         # argdup: use input as both arguments to function
 Ṫ        # table: generate the outer product of all pairs
  =       # equals: 1 if arguments equal, zero otherwise
   ḣ      # heads: 1..input

```
> 2 votes

# Answer
# Arturo, 36 bytes

```
$=>[unique permutate[1]++@.of:&-1,0]

```

Try it
> 2 votes

# Answer
# , 3 chars / 6 bytes

```
Мƕï

```

`Try it here (Firefox only).`

I'm finding a lot of these 3-char solutions. It's just a builtin.

# Bonus solution, 11 chars / 22 bytes

```
⩥ïⓜãĉ⇝+($≔a

```

`Try it here (Firefox only).`

The code in the interpreter link uses some more bytes to pretty-print output.

### Explanation

```
⩥ïⓜãĉ⇝+($≔a // implicit: ï=input
⩥ïⓜ         // create a range [0,ï) and map over it
    ãĉ⇝      // get a copy of range ã and map over it
       +($≔a // output 1 or 0 depending on whether item in first map == item in current map
             // implicit output

```
> 1 votes

# Answer
# Scala, ~~53~~ 51 bytes

```
(n:Int)=>Seq.tabulate(n,n){(i,j)=>if(i==j)1 else 0}

```
> 1 votes

# Answer
# Samau, 5 bytes

```
,;`=o

```

It's a function that takes a number and return a 2D array.

```
,;`=o
,      range from 0 to n-1
 ;     duplicate
    o  take the outer product by
  `=   equality

```
> 1 votes

# Answer
# Mouse, 75 bytes

```
N:1I:(I.N.1+<^1J:(J.I.<^0!32!'1J.+J:)1!32!'(J.N.<^0!32!'1J.+J:)10!'1I.+I:)$

```

This is a full program that reads from STDIN and prints to STDOUT. Each line will have a single trailing space and there will be one trailing newline at the end of the output.

Explanation:

```
~ Read N from STDIN
? N:

~ Initialize a row index
1 I:

~ Loop while we've printed fewer than N+1 rows
( I. N. 1 + < ^

  ~ Initialize a column index
  1 J:

  ~ Print I-1 space-separated zeros
  ( J. I. < ^
    0 !
    32 !'
    1 J. + J:
  )

  ~ Print 1 and a space
  1 !
  32 !'

  ~ Print the remaining zeros
  ( J. N. < ^
    0 !
    32 !'
    1 J. + J:
  )

  ~ Newline
  10 !'

  ~ Increment the row index
  1 I. + I:
)
$

```
> 1 votes

# Answer
# Java, 200 Bytes

This is the shortest working java code i could come up with. Nothing to special ;)

```
class a{public static void main(String[]a){int c=Integer.parseInt(a[0]);int[][]b=new int[c][c];for(int d=0;d<c;d++){for(int e=0;e<c;e++){b[d][d]=1;System.out.print(b[d][e]);}System.out.println();}}}

```

Partly posting this hoping someone could explain why TNT 's answer is valid (it has no class declaration and no `main(String[] args)`)? I'm new to code golf and i thought that answers had to be a working program?
> 1 votes

# Answer
# Python 3, 22 bytes

```
from numpy import*;eye

```

It's a bit boring, but it's short! Because of discussion on meta, I think this follows the spirit of the rules a bit more closely.
> 1 votes

# Answer
# Ruby 42 bytes

```
->n{([1]+[0]*(n-1)).permutation.to_a.uniq}

```

creates every permutation of the array `[1,0,0,0...]` and then takes the unique ones. this will end up with the ones we want, in the correct order.
> 1 votes

# Answer
# C++, 111 bytes

I love abusing for loops.

```
#include <stdio.h>
void f(int n){for(int j,i=0;i++<n;putchar(10))for(j=0;j++<n;putchar(32))putchar(i-j?48:49);}

```
> 1 votes

# Answer
# Oracle SQL 11.2, 102 bytes

```
SELECT SUBSTR(RPAD(0,:1,0),:1-LEVEL+2)||1||SUBSTR(RPAD(0,:1,0),LEVEL+1)FROM DUAL CONNECT BY LEVEL<=:1;

```
> 1 votes

# Answer
## Sage, 15 bytes

```
identity_matrix

```

Exactly what it says on the tin

Try it online

Thanks to Lynn for pointing out that I was being a doofus.
> 1 votes

# Answer
## Jellyfish, 12 bytes

```
P`N(Rri
   -

```

Try it online! This entry is non-competing.

## Explanation

* `i` is input, and `r` computes the range from 0 to input-1.
* The operator `(` is a *left hook*. On inputs `-` and `R`, it applies `R` (rotate) to the range and its negated version. This gives the `i×i` matrix whose rows are the ranges `ri`, rotated **k** steps to the right for each row **k**.
* ``N` computes the logical negation of each entry: 0 goes to 1 and everything else to 0. Since the 0s are on the diagonal, this gives the identity matrix.
* `P` prints the matrix.
> 1 votes

# Answer
# picTuring \- 16 States (320 bytes)

I thought this challenge might be a good chance to show off my new Turing Machine interpreter.

```
0 * 0 * r
0 _ 1 * r
1 * 2 1 l
2 * 2 * l
2 _ d * l
d _ f * r
d 0 d 1 l
d 1 p 0 r
p * p * r
p _ q * r
q * q * r
q _ 2 0 l
f * f _ r
f _ g * r
g 1 g _ r
g 0 r 1 r
r * r * l
r _ c * r
c _ n * d
c 0 o * d
c 1 i * d
o * e 0 u
i * j 0 r
j * h 1 u
h * k * r
k _ halt * *
k * c * *
e * c * r
n * r * l

```

The input must be in binary (1 / 0), with the number terminating at the head (the white circle).

**How to Run it:**

In case you didn't realize that the link in the header leads to my interpreter, you can find it here -\> http://fred-choi.com/projects/picTuring/index.html

Here is the compressed test case (since my interpreter does not support permalinks yet):

```
AwAlH0QRhBaGLTgJjCSMg AwAgVCoQTgUKB9EBGcI6ogJhSANrDtmgTkgCYmyyVIBmaclolqBrIADpOtdxP17ckAR0awxESbzFIcoArAYQGSOKpABzcbG2pta3T2i44sEzComkAYx12kAOzTlYd0AHsXb3AEtvsF4QAKY8AK7U-hAAVsawsRAAFrgRyRAA1uKZSIkAhngALmhgsJkQdhAlsKHlOs6WEHhAA

```

To use it, just hover over save, paste the compressed code in the text box, and click load.

To edit the tape, make sure you're in "Type" mode (Edit -\> Paint), then double click the tape, and a red box should show up, indicating that you're now editing the tape.

Once you're finished, hit *Edit -\> Ok* to save the tape, then *Controls -\> Run*. *Controls -\> Reset* will restore the tape to when you hit *Edit -\> Ok*.

Again, this is interpreter is still indev, I don't have a manual yet, so feel free to leave comments if I left anything out.
> 1 votes

# Answer
# PHP, 106 bytes

```
<?php $i=$argv[1];for($j=0;$j<$i;$j++){for($h=0;$h<$i;$h++){$l="0 ";if($h==$j)$l="1 ";echo$l;}echo"\n";}?>

```

Based on a double for loop, it uses the command-line argument for the input.

```
php 70365.php 3
1 0 0
0 1 0
0 0 1

```

Expanded code:

```
<?php
    $i = $argv[1];
    for($j = 0; $j < $i; $j++)
    {
        for($h = 0; $h < $i; $h++)
        {
            $l="0 ";
            if($h == $j)
                $l="1 ";
            echo $l;
        }
        echo "\n";
    }
?>

```
> 1 votes

# Answer
# PHP, 64 bytes

```
for(;$i<$argn**2;$m?:$k++)echo$k==$m?:0,($m=++$i%$argn)?" ":"
";

```

Try it online!
> 1 votes

# Answer
# Jelly, 2 bytes

Try it online!
> 1 votes

# Answer
# Rust, 59 bytes

```
|n|{let mut l=vec![vec![0;n];n];for i in 0..n{l[i][i]=1};l}

```

Defines an anonymous function, creates a vector of vectors of the specified length, sets the diagonals to 1 and returns it. Boring, but shorter than any iterator-based approaches due to .collect overhead.

Alternatively, if returning an iterator of iterators is allowed it can be done in 44 characters:

```
|n|(0..n).map(|i|(0..n).map(|j|(j==i)as u8))

```
> 1 votes

# Answer
# tinylisp repl, 107 bytes

```
(d =(q((A R C S)(i C(=(c(e R C)A)R(s C 1)S)A
(d #(q((A R S)(i R(#(c(=()R S S)A)(s R 1)S)A
(d f(q((S)(#()S S

```

Using the repl saves 6 bytes in implied closing parentheses at the ends of lines. Defines a function `f` which takes a positive integer and returns the identity matrix of that size as a nested list. Try it online!

### Explanation

The function `=` constructs a row in the matrix. Its arguments are (in order) an Accumulator, the Row number, the current Column number, and the Size of the matrix. If the column is not zero `(i C ...)`, then cons a number to the accumulator (1 if the row and column are equal, 0 otherwise) `(c (e R C) A)`, decrease the column number `(s C 1)`, and recurse `(= ...)`. Otherwise, return the accumulator `A`.

The function `#` constructs the matrix as a list of rows. Its arguments are an Accumulator, the current Row number, and the Size of the matrix. If the row number is not zero `(i R ...)`, then generate a row `(=()R S S)` and cons it to the accumulator `(c ... A)`, decrease the row number `(s R 1)`, and recurse `(# ...)`. Otherwise, return the accumulator `A`.

Finally, the function `f` is simply a single-argument wrapper function that calls `#`.
> 1 votes

# Answer
## Clojure, 45 bytes

```
#(for[i(range %)](assoc(vec(repeat % 0))i 1))

```
> 1 votes

# Answer
# PHP, 49 bytes

```
function($n){for(;$n--;)$k[$n][$n]=1;return $k;};

```

There is a bit of a caveat with this answer, and I will delete it or mark it as non-competing if it is deemed invalid.

The array returned by this function technically only has `n` elements, those being a 1 at every intersection. ie: 0:0 1:1, 2:2, etc

However, not only does this satisfy the definition of the identity matrix as given by the question:

> The identity matrix is one that has 1s spanning from the top left down to the bottom right

It also works if used as an identity matrix, as an empty value in an array in PHP is treated as 0 if used arithmetically.
> 1 votes

# Answer
# Axiom, 68 bytes

```
f(n:PI):Matrix INT==matrix([[(i=j=>1;0)for i in 1..n]for j in 1..n])

```

test and results

```
(30) -> for i in 1..3 repeat output f(i)
   [1]
   +1  0+
   |    |
   +0  1+
   +1  0  0+
   |       |
   |0  1  0|
   |       |
   +0  0  1+
                                                               Type: Void

```
> 1 votes

# Answer
# Python 2, 52 bytes

```
y=x=2**input()
while~-x:x/=2;print str(bin(y+x))[3:]

```

Try it online!

Using binary representation of powers of 2.
> 1 votes

# Answer
# Mathematica ,26 bytes

without using IdentityMatrix

```
Boole[#==#2]&~Array~{#,#}&

```
> 1 votes

# Answer
## PowerShell, 45 bytes

```
{param($n)0..--$n|%{"$(,0*$_+1+,0*($n-$_))"}}

```

Try It Online!
> 1 votes

# Answer
# Excel VBA, ~~55~~ ~~52~~ 43 Bytes

Anonymous VBE immediate window function that takes input as number from cell `[A1]` and outputs the identity matrix to the range of `[A1].Resize(n,n)`

```
[A1].Resize([A1],[A1])="=1*(Row()=Column())

```

-2 bytes thanks to Engineer Toast

### Previous Version

```
n=[A1]:[A1].Resize(n,n)=0:For i=1To n:Cells(i,i)=1:Next

```
> 1 votes

# Answer
# Vim, 47 keystrokes

```
"zy$␘a@q␛"xYoa␛"zPy$qqo␛@"0␛q@x3Gqqr1jlq@x1G2dd

```

is `Ctrl``X` and  is `Esc`

## Explanation

```
"zy$␘           Save n for use later
a@q␛"xY         Create the macro `x` that repeats the macro `q` n-1 times
oa␛"zPy$        Create an anonymous macro that inserts a character n times
qqo␛@"0␛q@x    Create the macro `q` that adds a new line with n zeroes and run it n times
3G               Go to the top-left corner of the matrix
qqr1jlq@x        Redefine `q` as a macro that replaces the character at the cursor with
                   a one and moves the cursor one step down-right. Run `q` n times
1G2dd            Delete the two lines used in macro defenitions

```
> 1 votes

# Answer
# Tcl, 92 bytes

```
proc I n {time {incr j;set a "";set i 0;time {lappend a [expr [incr i]==$j]} $n;puts $a} $n}

```

Try it online!
> 1 votes

# Answer
# Husk, 4 bytes

```
´Ṫ=ḣ

```

Try it online!

### Explanation

```
´Ṫ=ḣ  -- example input: 2
   ḣ  -- range: [1,2]
´     -- duplicate argument: [1,2] [1,2]
 Ṫ    -- outer product by
  =   -- | equality: [[1==1,1==2],[2==1,2==2]]
      -- : [[1,0],[0,1]]

```
> 1 votes

# Answer
# Gol\>\<\>, 10 bytes

```
IR0PlF}D|;

```

Try it online!

The output for `n = 5` looks like this:

```
[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]

```

### How it works

```
IR0PlF}D|;

IR0P       Take input n, then fill the stack with that many 0s
           and then make the top 1; stack = [0 ... 0 1]
    lF..|  Do the following n times...
      }D   Rotate the stack once to the right, and print the whole stack
         ; Terminate

```
> 1 votes

# Answer
# 05AB1E, 6 bytes

```
Lã€Ësô

```

Try it online.

**Explanation:**

```
L         # List in range [1,n]
          #  i.e. 3 → [1,2,3]
 ã        # Cartesian power of this list
          #  i.e. [1,2,3] → [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
  €Ë      # Check for every pair if they are equal or not
          #  i.e. [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
          #   → [1,0,0,0,1,0,0,0,1]
    sô    # Split it into parts equal to the input
          #  i.e. [1,0,0,0,1,0,0,0,1] and 3 → [[1,0,0],[0,1,0],[0,0,1]]

```
> 1 votes

# Answer
# Jellyfish, ~~8~~ 7 bytes

```
P&O`=ri

```

Try it online!

### Explanation

```
P&O`=ri
     ri  Range(input)
 &       With that list and itself,
  O      make a table (outer product)
   `=    using vectorized equality
P        Print as matrix

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
Þ□

```

Try it Online!

Vyxal literally has a builtin for this.
> 1 votes

# Answer
# Factor \+ `math.matrices`, 15 bytes

```
identity-matrix

```

Try it online!
> 1 votes

# Answer
# BQN, 4 bytes

```
=⌜˜↕

```

Anonymous tacit function; returns a 2D array. Try it at BQN online!

### Explanation

```
   ↕  Range(argument)
=⌜    Create an equality table
  ˜   between that list and itself

```
> 1 votes

# Answer
# Pip `-P`, 6 bytes

```
_=BMCa

```

Try It Online!

Just for completeness sake, here's the shortest **non-builtin** answer that I could find in Pip. In other words, an answer without the usage of `EY`.

```
_=BMCa         Input is "a"
   MCa         Map over all x,y pairs in an a by a coordinate grid
_=B            Is the x-coordinate equal to the y-coordinate?
               Implicit output joined by newlines (-P flag)

```
> 1 votes

# Answer
# K (ngn/k), 1 byte

```
=

```

Try it online!
> 1 votes

# Answer
# Pyt, 5 bytes

```
řĐɐ=Ɩ

```

Try it online!

```
ř              implicit input; create řange [1,2,...,n]
 Đ             Đuplicate
  ɐ=           for ɐll pairs: are elements equal?
    Ɩ          cast to Ɩnteger; implicit print

```
> 1 votes

# Answer
# Nekomata, 3 bytes

```
ᵒ-¬

```

Attempt This Online!

```
ᵒ-     Generate a 2d table with subtraction
  ¬    Logical not (converts 0 to 1 and other numbers to 0)

```
> 1 votes

# Answer
# Fortran (GFortran), 110 bytes

```
allocatable K(:,:);read*,n;allocate(K(n,n));K=0;forall(i=1:n)K(i,i)=1
do i=1,n;print*,(K(i,j),j=1,n);enddo;end

```

Try it online!
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
RD€=

```

Attempt This Online!

#### Explanation

```
RD€=  # Implicit input
R     # Push the range [1..n]
  €   # For each number,
   =  # Compare it with
 D    # The range [1..n]
      # Implicit output

```
> 1 votes

# Answer
# Itr, 4 bytes

`ºµÍT`

using array operations, returns a nested array

online interpreter

`¹®0^`

using matrix operations, returns a matrix

online interpreter

## Explanation

```
ºµÍT  ; implicit input
º     ; convert to zero-based array
 µÍ   ; replace each element with an array that has a 1 at the specified position
   T  ; transpose to fill in missing zero elements
      ; implicit output

```

```
¹®0^ ; implicit input
¹    ; 1-based range
 ®   ; converted to matrix
  0^ ; to the 0th power (matrix implicitly padded with zeros)
     ; implicit output

```
> 1 votes

# Answer
# **T-SQL**, 202 bytes

`DECLARE @s VARCHAR(MAX);SELECT @s='SELECT '+STRING_AGG('CASE WHEN value='+CAST(value AS CHAR)+' THEN 1 ELSE 0 END',',')+' FROM GENERATE_SERIES(1,'+CAST(@n AS CHAR)+')'FROM GENERATE_SERIES(1,@n);EXEC(@s)`

dbfiddle

Explanation:

```
DECLARE @n INT = 5; -- Input integer assigned to the variable @n. Not counted in byte count
DECLARE @s VARCHAR(MAX); -- string variable to house the upcoming dynamic sql

-- dynamically builds a sql query that will have @n many columns and stores it in @s.
SELECT @s='SELECT '+STRING_AGG('CASE WHEN value='+CAST(value AS CHAR)+' THEN 1 ELSE 0 END',',')+' FROM GENERATE_SERIES(1,'+CAST(@n AS CHAR)+')'
FROM GENERATE_SERIES(1,@n);
EXEC(@s) -- Executes the string @s as t-sql code.

    --Example, dynamically built query looks like this for @n = 5
    SELECT CASE WHEN value=1                              THEN 1 ELSE 0 END
        ,CASE WHEN value=2                              THEN 1 ELSE 0 END
        ,CASE WHEN value=3                              THEN 1 ELSE 0 END
        ,CASE WHEN value=4                              THEN 1 ELSE 0 END
        ,CASE WHEN value=5                              THEN 1 ELSE 0 END
    FROM GENERATE_SERIES(1,5                             )
    --Note, white space after integer values due to casting as CHAR. casting as VARCHAR would clean this up but cost an extra 3 bytes per call.

```

Output for @n=5

Will only work on SQL server 2022 or greater (GENERATE\_SERIES needs compatibility level 160 or greater). Likely also work on Azure SQL database etc...

There is already a superior (in terms of byte count) **oracle sql answer**. But that answer produces a single string column of zeros and ones, whereas this answer produces an n by n table of numeric zeros and ones. So I figured this was different enough to still share.
> 1 votes

# Answer
# jamforth, 152 bytes

```
: F DUP DUP 2* 1- DUP ALLOT SWAP DFOR 2DUP + 48 SWAP C! REPEAT TUCK + 1- 49 SWAP C! SWAP TUCK + 1- SWAP DUP DFOR -ROT 2DUP TELL CR -ROT 1- -ROT REPEAT ;
```

196 bytes compiled, theoretically half that on a 16 bit machine or token threaded forth with 16 bit tokens. F, when called, prints the NxN identity matrix where N is the number on top of the stack.

Here it is deobfuscated:

```

: POPULATE ( len )
    DUP 2* 1- ( len 2len-1 )
    DUP ALLOT ( len 2len-1 ptr )
    SWAP DFOR
        2DUP + [CHAR] 0 SWAP C!
    REPEAT
    TUCK + 1- [CHAR] 1 SWAP C!
;
: PRINT ( ptr len )
    TUCK + 1- SWAP
    DUP DFOR
        ( ptr len idx )
        -ROT 2DUP TELL CR
        -ROT 1-
        -ROT
    REPEAT
;
: GO DUP POPULATE SWAP PRINT ;

```

I know I committed to jamforth about 25 minutes before posting this, but I wrote DFOR a few weeks back and just didn't get around to committing it.
> 1 votes

# Answer
# Kamilalisp, 16 bytes

```
[$(⌼ =) #0 #0]∘⍳

```

Attempt This Online!
> 1 votes

# Answer
## Malbolge Unshackled, 1,664,383 bytes.

A link to GitHub as StackExchange does not allow posting answers so long. One of my fastest Malbolge programs.
> 1 votes

# Answer
## Seriously, 24 bytes

```
,;╗r`╙k╜#"{:0%sb}"%f#`MR

```

Try it online!

Explanation:

```
,;╗r`╙k╜#"{:0%sb}"%f#`MR
,;╗                       get input (n), save a copy in register 0
   r                      push [0..n-1]
    `                `M   map the function:
     ╙k                     push [2**a]
       ╜#"{:0%sb}"%         push "{:0nb}"
                   f#       format and explode string
                            (push binary representation, padded with zeroes to n digits)
                       R  reverse list

```
> 0 votes

# Answer
# , ~~16~~, 11 bytes

```
Ài0 ÀÄòjl

```

Try it online!
> 0 votes

# Answer
# Common Lisp, ~~96 94~~ 92 bytes

```
(lambda(n)(set'a(make-array(list n n):initial-element 0))(dotimes(i n)(setf(aref a i i)1))a)

```

Try it online!
> 0 votes

# Answer
# PHP, 55 bytes

```
while($p**.5<$z=+$argn)echo$p%-~$z?0:1,"
 "[++$p%$z>0];

```

requires PHP 5.6 or later for the power operator. Note that the second line begins with a space!

Run as pipe with `-nR` or try it online.
> 0 votes

# Answer
# Charcoal, 7 bytes

```
ＥθＥθ⁼κμ

```

Try it online!

This returns an array, which in Charcoal is not readable in its default format. A version using Wolfram `List`s is included below for readability.

### Explanation

```
Ｅθ       Map for each number from 0 to first input
   Ｅθ    Map for each number from 0 to first input
      ⁼κμ Return whether both loop indices (yes, indices) are the same. The variables here are: i = first loop variable, k = first loop index, l = second loop variable, m = second loop index.

```

Readable version
Even accepts input as unary :P
> 0 votes

# Answer
## PHP 88 Bytes

**Try it online**

**Code**

```
<?php for($i=0;$i++<$argv;){$a=array_fill(1,$argv,0);$a[$i]=1;echo implode(",",$a)."
";}

```

**Explanation**

```
<?php
  for($i=0;$i++<$argv;){          // loop up to the argument
      $a=array_fill(1,$argv,0);   // create an array fill with 0 with length = $argv value
      $a[$i]=1;                   // use the current iteration to place the "1"
      echo implode(",",$a)."      // implode to output the matrix
     ";}

```

**Output**

```
  $argv=5

  1,0,0,0,0
  0,1,0,0,0
  0,0,1,0,0
  0,0,0,1,0
  0,0,0,0,1

```
> 0 votes

# Answer
# Forth (gforth), 48 bytes

```
: f dup 0 do dup 0 do 0 i j = - . loop cr loop ;

```

Try it online!

### Explanation

uses nested loops to output the matrix. For each element it outputs 1 if the indexes are equal, and 0 otherwise.

### Code Explanation

```
:f           \ start a new word definition
  dup        \ duplicate input
  0 do       \ outer counted loop from 0 to input - 1
    dup      \ duplicate input again
    0 do     \ inner counted loop from 0 to input - 1
      0      \ put a 0 on the stack (used to convert -1 to 1)
      i j =  \ -1 if i equals j, 0 otherwise
      - .    \ subtract from 0 to convert -1 to 1, and output
    loop     \ end inner loop
    cr       \ output a newline
  loop       \ end outer loop
;            \ end word definition

```
> 0 votes

# Answer
# , 114 bytes

```
void f(int n){import std.stdio;int N=n*n;while(N--){if(N%(n+1))write("0 ");else write("1 ");if(N%n==0)writeln();}}

```

Try it online!
> 0 votes

# Answer
# PARI/GP, 14 bytes

```
n->matrix(n)^0
```

Attempt This Online!

Takes the zeroth power of the zero matrix.

See also Charles's answer,
> 0 votes

# Answer
# Pip, 3 bytes

```
EYa

```

Try It Online!

Builtin.
> 0 votes

# Answer
# Nibbles, ~~6~~ 5 bytes (10 nibbles)

```
.;,$.@==$_

```

```
.               # map across each value of
  ,$            # 1..input
 ;              # (saving this range)
    .           #   map across each value of
     @          #   the saved range (1..input again)
      ==$_      #     are the two values equal?

```
> 0 votes

---
Tags: code-golf, math, matrix, linear-algebra, binary-matrix
---


title: Checkmate (aka the urinal problem)

text:
# Question
Title: Checkmate (aka the urinal problem)
My Precalc teacher has one of his favorite problems that he made up (or more likely ~~stole~~ inspired by xkcd) that involves a row of `n` urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an `X`, then

`X-X--X`

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

## Task

Your program will take a number through `stdin`, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

## Examples

`0 -> 1` (the null case counts as checkmate)
`1 -> 1` (`X`)
`2 -> 2` (`X-` or `-X`)
`3 -> 2` (`X-X` or `-X-`)
`4 -> 3` (`X-X-`, `-X-X`, or `X--X`)
`5 -> 4` (`X-X-X`, `X--X-`, `-X-X-`, or `-X--X`)
`6 -> 5` (`X-X-X-`, `X--X-X`, `X-X--X`, `-X--X-` or `-X-X-X`)
`7 -> 7` (`X-X-X-X`, `X--X-X-`, `-X-X--X`, `-X--X-X`, `X-X--X-`, `X--X--X` or `-X-X-X-`)
`8 -> 9` (`-X--X--X`, `-X--X-X-`, `-X-X--X-`, `-X-X-X-X`, `X--X--X-`, `X--X-X-X`, `X-X--X-X`, `X-X-X--X`, `X-X-X-X-`)
`...`

## Scoring

The smallest program in bytes wins.

# Answer
> 22 votes
# Oasis, 5 bytes

**Code**

```
cd+2V

```

**Extended version**

```
cd+211

```

**Explanation**

```
1 = a(0)
1 = a(1)
2 = a(2)

a(n) = cd+
       c      # Calculate a(n - 2)
        d     # Calculate a(n - 3)
         +    # Add them up

```

Try it online!

# Answer
> 12 votes
## Java 7, ~~65~~ 42 bytes

```
int g(int u){return u>1?g(u-2)+g(u-3):1;}

```

The sequence just adds previous elements to get new ones. Hat tip to orlp and Rod for this shorter method ;)

**Old:**

```
int f(int u){return u<6?new int[]{1,1,2,2,3,4}[u]:f(u-1)+f(u-5);}

```

After the fifth element, the gap in the sequence rises by the element five previous.

# Answer
> 9 votes
# Python 2, 42 40 39 35 bytes

```
f=lambda n:n>1and f(n-2)+f(n-3)or 1

```

Generating the actual sets:

```
lambda n:["{:0{}b}".format(i,n).replace("0","-").replace("1","X")for i in range(2**n)if"11"not in"{:0{}b}".format(i*2,2+n).replace("000","11")]

```

# Answer
> 8 votes
# Ruby, ~~58~~ 34 bytes

Heavily inspired by Geobits' original Java answer.

```
f=->n{n<3?n:n<6?n-1:f[n-1]+f[n-5]}

```

See it on repl.it: https://repl.it/Dedh/1

## First attempt

```
->n{(1...2**n).count{|i|!("%0#{n}b"%i)[/11|^00|000|00$/]}}

```

See it on repl.it: https://repl.it/Dedh

# Answer
> 6 votes
## Python, 33 bytes

```
f=lambda n:+(n<2)or f(n-2)+f(n-3)

```

Uses the shifted base cases `f(-1) = f(0) = f(1) = 1`. If `True` could be used for 1, we would not need 3 bytes for the `+()`.

# Answer
> 6 votes
# J, ~~31~~ ~~27~~ 23 bytes

*Saved 4 bytes thanks to miles!*

```
0{]_&(]}.,+/@}:)1 1 2"_

```

An explanation is to come soon.

## Old solution

```
(>.1&^)`(-&3+&$:-&2)@.(2&<)

```

This is an agenda. The LHS is a gerund composed of two verbs: `>.1&^` and `-&3+&$:-&2`. The first one is used if the condition (`2&<`) fails. That means the fork `>.1&^` is activated over the argument. Observe:

```
   1 ^ 0 1 2
1 1 1
   (1&^) 0 1 2
1 1 1
   0 1 2 >. (1&^) 0 1 2
1 1 2
   (>.1&^) 0 1 2
1 1 2

```

Here, `>.` takes the max of two values. Thus, it yields 1, 1, and 2 as the initial terms.

The second verb in the gerund is a fork:

```
-&3 +&$: -&2

```

The left and right tines are applied to the verb, subtracting 3 and 2 respectively; then the middle verb is called with left and right arguments equal to those. `$:` calls the verb on each argument, and `+` adds those two. It's basically equivalent to `($: arg - 3) + ($: arg - 2)`

### Test cases

```
   f =: (>.1&^)`(-&3+&$:-&2)@.(2&<)
   f 0
1
   f 2
2
   f 4
3
   f 6
5
   f 8
9
   F =: f"0         NB. for tables
   F i.13
1 1 2 2 3 4 5 7 9 12 16 21 28
   i.13
0 1 2 3 4 5 6 7 8 9 10 11 12
   (,. F) i.13
 0  1
 1  1
 2  2
 3  2
 4  3
 5  4
 6  5
 7  7
 8  9
 9 12
10 16
11 21
12 28

```

# Answer
> 4 votes
# PHP, ~~105~~ ~~113~~ 93 bytes

+3 for `n=1`; +9 for `$argv`, -1-3 golfed
-20: noticed that I don´t have to the combinations, but only their count

```
for($i=1<<$n=$argv[1];$i--;)$r+=!preg_match("#11|(0|^)0[0,]#",sprintf("%0{$n}b,",$i));echo$r;

```

run with `-r`

loop from 2\**n-1 to 0:

* check binary n-digit representation for `11`, `000`, `00` at the beginning or the end, or a single `0`
* if no match, increase result

print result

**same size, slightly simpler regex**

```
for($i=1<<$n=$argv[1];--$i;)$r+=!preg_match("#11|^00|00[,0]#",sprintf("%0{$n}b,",$i));echo$r;

```
* loop from 2\**n-1 to 1 (instead of 0)
* check binary representation for `11`, `00` at the beginning or the end, or `000`
* prints nothing for n=0

**PHP, 82 bytes**

Arnauld´s answer ported and golfed:

```
for($i=$k=1<<$n=$argv[1];--$i;)$r+=!($i&$x=$i/2|$i*2)&&(($i|$x)&~$k)==$k-1;echo$r;

```

prints nothing for n=0

# Answer
> 4 votes
# JavaScript (ES6) / Recursive, ~~30~~ 27 bytes

*Edit: saved 3 bytes thanks to Shaun H*

```
let

f=n=>n<3?n||1:f(n-2)+f(n-3)

for(var n = 1; n < 16; n++) {
  console.log(n, f(n));
}
```

# JavaScript (ES6) / Non-recursive ~~90~~ 77 bytes

*Edit: saved 13 bytes thanks to Conor O'Brien and Titus*

```
let f =

n=>[...Array(k=1<<n)].map((_,i)=>r+=!(i&(x=i>>1|i+i))&&((i|x)&~k)==k-1,r=0)|r

for(var n = 1; n < 16; n++) {
  console.log(n, f(n));
}
```

# Answer
> 4 votes
# MATL, ~~25~~ 23 bytes

```
W:qB7BZ+t!XAw3BZ+!3>a>s

```

Try it online! Or check all test cases.

### Explanation

*Two* convolutions! Yay!

This builds an array, say A, where each possible configuration is a row. `1` in this array represents an occupied position. For example, for input `4` the array A is

```
0 0 0 0
0 0 0 1
0 0 1 0
···
1 1 1 0
1 1 1 1

```

The code then convolves array A with `[1 1 1]`. This gives an array B. Occupied positions and neighbours of occupied positions in A give a nonzero result in array B:

```
0 0 0 0
0 0 1 1
0 1 1 1
···
2 3 2 1
2 3 3 2

```

So the first condition for a configuration to be a checkmate is that B contains no zeros in that row. This means that in that row of A there no empty positions, or there were some but were neighbours of occupied positions.

We need a second condition. For example, the last row fulfills the above condition, but is not part of the solution because the configuration was not valid to begin with. A valid configurations cannot have two neighbouring occupied positions, i.e cannot have two contiguous `1`'s in A. Equivalently, it cannot have two contiguous values in B exceeding `1`. So we can detect this by convolving B with `[1 1]` and checking that in the resulting array, C,

```
0 0 0 0
0 1 2 1
1 2 2 1
···
5 5 3 1
5 6 5 2

```

no value in that row exceeds `3`. The final result is the number of configurations that fulfill the two conditions.

```
W:q    % Range [0 1 ... n-1], where n is implicit input
B      % Convert to binary. Each number produces a row. This is array A
7B     % Push array [1 1 1]
Z+     % 2D convolution, keeping size. Entries that are 1 or are horizontal
       % neighbours of 1 produce a positive value. This is array B
t!     % Duplicate and transpose (rows become columns)
XA     % True for columns that contain no zeros
w      % Swap. Brings array B to top
3B     % Push array [1 1]
Z+     % 2D convolution, keeping size. Two horizontally contiguous entries
       % that exceed 1 will give a result exeeding 3. This is array C
!      % Transpose
3>     % Detect entries that exceed 3
a      % True for columns that contain at least one value that exceeds 3
>      % Element-wise greater-than comparison (logical and of first
       % condition and negated second condition)
s      % Sum (number of true values)

```

# Answer
> 4 votes
# Jelly, 11 bytes

```
,’fR_2ß€So1

```

Try it online! or verify all test cases.

### How it works

```
,’fR_2ß€So1  Main link. Argument: n

 ’           Decrement; yield n - 1.
,            Pair; yield [n, n - 1].
   R         Range; yield [1, ..., n].
  f          Filter; keep the elements that are common to both lists.
             This yields [n, n - 1] if n > 1, [1] if n = 1, and [] if n < 1.
    _2       Subtract 2 from both elements, yielding [n - 2, n - 3], [-1], or [].
      ß€     Recursively call the main link for each integer in the list.
        S    Take the sum of the resulting return values.
         o1  Logical OR with 1; correct the result if n < 1.

```

# Answer
> 3 votes
# Mathematica, 35 bytes

```
a@0=a@1=1;a@2=2;a@b_:=a[b-2]+a[b-3]

```

Defines a function `a`. Takes an integer as input and returns an integer as output. Simple recursive solution.

# Answer
> 3 votes
# AnyDice, 51 bytes

```
function:A{ifA<3{result:(A+2)/2}result:[A-2]+[A-3]}

```

There should be more AnyDice answers around here.

My solution defines a recursive function that calculates `a(n)=a(n-2)+a(n-3)`. It returns `a(0)=a(1)=1` and `a(2)=2` using some integer division magic.

Try it online

Note: the output may look weird, and that's because it's usually used to output dice probabilities. Just look at the number to the left of the bar chart.

# Answer
> 3 votes
# Perl, ~~35~~ 34 bytes

Includes +1 for `-p`

Give input on STDIN

```
checkmate.pl <<< 8

```

`checkmate.pl`:

```
#!/usr/bin/perl -p
$\+=$b-=$.-=$\-$b*4for(++$\)x$_}{

```

A newly developed secret formula. Ripple update 3 state variables without the need for parallel assignments.

It is equally short (but a lot slower and taking a lot more memory) to just solve the original problem:

```
#!/usr/bin/perl -p
$_=grep!/XX|\B-\B/,glob"{X,-}"x$_

```

but that doesn't work for `0`

# Answer
> 2 votes
# Jelly, 19 bytes

The recursive solution is ~~probably~~ shorter...

```
Ḥ⁹_c@⁸
+3µ:2R0;ç€µS

```

See it at **TryItOnline**
Or see the series for `n = [0, 99]`, also at **TryItOnline**

How?

Returns the `n+3`th Padovan's number by counting combinations

```
Ḥ⁹_c@⁸ - Link 1, binomial(k, n-2k): k, n
Ḥ      - double(2k)
 ⁹     - right argument (n)
  _    - subtract (n-2k)
     ⁸ - left argument (k)
   c@  - binomial with reversed operands (binomial(k, n-2k))

+3µ:2R0;ç€µS - Main link: n
  µ       µ  - monadic chain separation
+3           - add 3 (n+3)
   :2        - integer divide by 2 ((n+3)//2)
     R       - range ([1,2,...,(n+3)//2]
      0;     - 0 concatenated with ([0,1,2,...,(n+3)//2]) - our ks
        ç€   - call previous link as a dyad for each
           S - sum

```

# Answer
> 2 votes
## JavaScript (ES6), 62 bytes

```
n=>[1,...Array(n)].reduce(($,_,i,a)=>a[i]=i<3?i:a[i-3]+a[i-2])

```

This is the first time that I've needed two dummy variable names. A recursive version would probably be shorter, but I really like `reduce`... Edit: Found a solution, also 62 bytes, which only has one dummy variable:

```
n=>[1,...Array(n)].reduce((p,_,i,a)=>a[i]=i<5?i+2>>1:a[i-5]+p)

```

# Answer
> 2 votes
# CJam, 20 bytes

```
1_2_{2$2$+}ri*;;;o];

```

Try it online!

### Explanation

This uses the recurrence relationship shown in the OEIS page.

```
1_2_                   e# Push 1, 1, 2, 2 as initial values of the sequence
           ri          e# Read input
    {     }  *         e# Repeat block that many times
     2$2$              e# Copy the second and third elements from the top
         +             e# Add them
              ;;;      e# Discard the last three elements
                 o     e# Output
                  ];   e# Discard the rest to avoid implicit display

```

# Answer
> 2 votes
# FRACTRAN, ~~104~~ 93 bytes

Input is `11**n*29` and output is `29**checkmate(n)`.

This is mostly for fun, especially since I'm currently being outgolfed by Python, JS, *and* Java. Same number of bytes as PHP though :D Golfing suggestions welcome.

```
403/85 5/31 3/5 9061/87 3/41 37/3 667/74 37/23 7/37 38/91 7/19 5/77 1/7 1/17 1/2 340/121 1/11

```

**Ungolfing**

```
               At the start we have 11**n * 29
1/11           If n < 2, we remove the 11s and print 29**1
340/121        If n >= 2, we subtract two 11s (n-2) and add one 17, two 2s and one 5.
                 We now have 17**1 * 29**1 * 2**2 * 5.
                 These are the register for a, b, c at registers 17, 29, and 2.
                 5 is an indicator to start the first loop.
                 This loop will move a to register 13.
403/85 5/31    Remove the 17s one at a time, adds them to the 13 register.
                 5 and 31 reset the loop.
3/5            Next loop: moves b to a and adds b to a in register 13.
9061/87 3/41   Remove the 29s one at a time, adds them to the 17 and 13 registers.
                 3 and 41 reset the loop.
37/3           Next loop: moves c to b in register 29.
667/74 37/23   Remove the 2s one at a time, adds them to the 29 register.
                 37 and 23 reset the loop.
7/37           Next loop: moves a+b to c in register 2.
38/91 7/19     Remove the 13s one at a time, adds them to the 2 register.
                 7 and 19 reset the loop.
5/77           Move to the first loop if and only if we have an 11 remaining.
1/7 1/17 1/2   Remove the 7 loop indicator, and all 17s and 2s.
               Return 29**checkmate(n).

```

# Answer
> 2 votes
# \>\<\>, 25+2 = 27 bytes

```
211rv
v!?:<r@+@:$r-1
>rn;

```

Needs the input to be present on the stack at program start, so +2 bytes for the `-v` flag. Try it online!

The first line initialises the stack to `1 1 2 n`, where `n` is the input number. The second line, running backwards, checks that `n` is greater than 1. If it is, `n` is decremented and the next element in the sequence is generated as follows:

```
r$:@+@r              a(n-3) a(n-2) a(n-1) n

r        Reverse   - n a(n-1) a(n-2) a(n-3)
 $       Swap      - n a(n-1) a(n-3) a(n-2)
  :      Duplicate - n a(n-1) a(n-3) a(n-2) a(n-2)
   @     Rotate 3  - n a(n-1) a(n-2) a(n-3) a(n-2)
    +    Add       - n a(n-1) a(n-2) a(n)
     @   Rotate 3  - n a(n) a(n-1) a(n-2)
      r  Reverse   - a(n-2) a(n-1) a(n) n

```

The final line outputs the number on the bottom of the stack, which is the required element in the sequence.

# Answer
> 2 votes
# 05AB1E, 12 bytes

```
XXXIGX@DŠ0@+

```

**Explanation**

```
XXX            # initialize stack as 1, 1, 1
   IG          # input-1 times do:
     X@        # get the item 2nd from bottom of the stack
       DŠ      # duplicate and push one copy down as 2nd item from bottom of the stack
         0@    # get the bottom item from the stack
           +   # add the top 2 items of the stack (previously bottom and 2nd from bottom)
               # implicitly print the top element of the stack after the loop

```

Try it online!

# Answer
> 1 votes
# Actually, 25 bytes

This seems a little long for a simple `f(n) = f(n-2) + f(n-3)` recurrence relation. Golfing suggestions welcome. Try it online!

```
╗211╜¬`);(+)`nak╜2╜2<I@E

```

**Ungolfing**

```
         Implicit input n.
╗        Save n to register 0.
211      Stack: 1, 1, 2. Call them a, b, c.
╜¬       Push n-2.
`...`n   Run the following function n-2 times.
  );       Rotate b to TOS and duplicate.
  (+       Rotate a to TOS and add to b.
  )        Rotate a+b to BOS. Stack: b, c, a+b
         End function.
ak       Invert the resulting stack and wrap it in a list. Stack: [b, c, a+b]
╜        Push n.
2        Push 2.
╜2<      Push 2 < n.
I        If 2<n, then 2, else n.
@E       Grab the (2 or n)th index of the stack list.
         Implicit return.

```

# Answer
> 1 votes
# Actually, 18 bytes

This is an Actually port of Dennis' longer Jelly answer. Golfing suggestions welcome. Try it online!

```
3+;╖½Lur⌠;τ╜-@█⌡MΣ

```

**Ungolfing**

```
         Implicit input n.
3+       Add 3. For readibility, m = n+3.
;╖       Duplicate and store one copy of m in register 0.
½Lu      floor(m/2) + 1.
r        Range from 0 to (floor(m/2)+1), inclusive.
⌠...⌡M   Map the following function over the range. Variable k.
  ;        Duplicate k.
  τ╜-      Push m-2k. Stack: [m-2k, k]
  @█       Swap k and m-2k and take binomial (k, m-2k).
            If m-2k > k, █ returns 0, which does not affect the sum() that follows.
         End function.
Σ        Sum the list that results from the map.
         Implicit return.

```

# Answer
> 1 votes
# Haskell, 27 bytes

```
r=1:1:2:zipWith(+)r(tail r)

```

Try it online!

# Answer
> 1 votes
# Vyxal, 7 bytes

```
⁺»‡_+TḞ

```

Try it Online!

Uses the same recurrence relation `a(n) = a(n-2) + a(n-3)`

```
      Ḟ # Create an infinite list
⁺»      # Starting from digits of 112
  ‡     # Generate new terms by a function
     T  # Taking in the last three terms
   _    # Pop the first
    +   # Add the other two together

```

# Answer
> 0 votes
# Stax, 7 bytes

```
ÉKΦΘÄO¢

```

Run and debug it

Uses the recurrence relation. `C(n) = C(n-2) + C(n-3)`

# Answer
> 0 votes
# C (gcc), 33 bytes

```
f(n){return n<2?1:f(n-2)+f(n-3);}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
ƵBSλè₂₃+

```

Try it online or verify the infinite list.

**Explanation:**

```
ƵB        # Push compressed integer 112
  S       # Convert it to a list of digits: [1,1,2]
   λ      # Start a recursive environment,
    è     # to output the 0-based (implicit) input'th value
          # (which will be output implicitly as result afterwards)
ƵBS       # Starting at a(0)=1, a(1)=1, a(2)=2
          # And where every following a(n) is calculated as:
     ₂₃+  #  a(n-2) + a(n-3)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ƵB` is `112`.

---
Tags: code-golf, sequence, counting
---


title: Modulus Summation

text:
# Question
Title: Modulus Summation
I call this sequence "the Jesus sequence", because it is the *sum of mod*.\</pun\>

For this sequence, you take all the positive integers *m* less than the input *n*, and take the sum of *n* modulo each *m*. In other words:

$$a\_n = \sum\_{m=1}^{n-1}{n\bmod m}$$

For example, take the term *14*:

```
14 % 1 = 0
14 % 2 = 0
14 % 3 = 2
14 % 4 = 2
14 % 5 = 4
14 % 6 = 2
14 % 7 = 0
14 % 8 = 6
14 % 9 = 5
14 % 10 = 4
14 % 11 = 3
14 % 12 = 2
14 % 13 = 1
0+0+2+2+4+2+0+6+5+4+3+2+1=31

```

Your goal here is to write a function that implements this sequence. You should take the sequence term (this will be a positive integer from 1 to 231) as the only input, and output the value of that term. This is OEIS A004125.

As always, standard loopholes apply and the shortest answer in bytes wins!

# Answer
# 05AB1E, 3 bytes

```
L%O

```

Try it online!
> 7 votes

# Answer
# Haskell, 22 bytes

```
f x=sum$mod x<$>[1..x]

```

Try it online!

### Explanation

Yes.
> 10 votes

# Answer
# Funky, 25 bytes

```
n=>fors=~-i=1i<n)s+=n%i++

```

Just the Naïve answer, seems to work.

Try it online!

# Desmos, 25 bytes.

```
f(x)=\sum_{n=1}^xmod(x,n)

```

Paste into Desmos, then run it by calling `f`.

When pasted into Desmos, the latex looks like this

The graph however looks like

Although it looks random and all over the place, that's the result of only supporting integers.

# RProgN 2, 9 bytes

```
x=x³x\%S+

```

## Explained

```
x=x³x\%S+
x=          # Store the input in "x"
  x         # Push the input to the stack.
   ³x\%     # Define a function which gets n%x
       S    # Create a stack from "x" with the previous function. Thus this gets the range from (1,x), and runs (i%x) on each element.
        +   # Get the sum of this stack.

```

Try it online!

# ReRegex, 71 bytes

```
#import math
(_*)_a$/d<$1_>b$1a/(\d+)b/((?#input)%$1)+/\+a//u<#input
>a

```

Try it online!

# ARBLE, 19 bytes

```
sum(range(1,a)|a%i)

```

Try it online!

# MaybeLater, 56 bytes

```
whenf is*{n=0whenx is*{ifx>0{n=n+f%x x--}elseprintn}x=f}

```

Try it online!
> 8 votes

# Answer
# Ruby, ~~28~~ ~~27~~ 23 bytes

-4 bytes thanks to @daniero.

```
->n{(1..n).sum{|i|n%i}}

```

Try it online!

## Ruby, 28 bytes

```
f=->n{n>($.+=1)?n%$.+f[n]:0}

```

Try it online!
> 7 votes

# Answer
# Jelly, 3 bytes

```
%RS

```

**Explanation**

```
%RS
 R   Range(input)  [1...n]
%    Input (implicit) modulo [1...n]->[n%1,n%2...n%n]
  S  Sum of the above

```

Try it online!
> 5 votes

# Answer
# MATL, 4 bytes

```
t:\s

```

Try it online!

Explanation:

```
t      % Duplicate input. Stack: {n, n}
 :     % Range 1...n. Stack: {n, [1...n]}
  \    % Modulo. Stack: {[0,0,2,2,4,...]}
   s   % Sum. Implicitly display result.

```
> 5 votes

# Answer
# R, 20 bytes

```
sum((n=scan())%%1:n)

```

Try it online!
> 5 votes

# Answer
# Ohm v2, 4 bytes

```
D@%Σ

```

Try it online!
> 4 votes

# Answer
# APL (Dyalog), 5 bytes

```
+/⍳|⊢

```

Try it online!

**How?**

Monadic train -

`+/` \- sum

\- `n`

`|` \- vectorized modulo

\- the range of `n`
> 4 votes

# Answer
# Python 2, 44 bytes

```
lambda n:sum(map(lambda x:x%(n-x),range(n)))

```

Try it online!

EDIT: Changed range(0,n) to range(n)
> 4 votes

# Answer
# Rust, 27 characters

```
|n|(1..n).map(|i|n%i).sum()

```

Based on Should rust anonymous functions fully specify parameter types? I assume that return type inference is also fine.

Try it online!
> 4 votes

# Answer
# Julia 1.0, 16 bytes

```
~x=sum(x.%(1:x))

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 26 bytes

```
f=(n,k=n)=>n&&k%n+f(n-1,k)

```

### Demo

```
f=(n,k=n)=>n&&k%n+f(n-1,k)

for(n = 1; n < 30; n++) {
  console.log('a(' + n + ') = ' + f(n))
}
```
> 3 votes

# Answer
# Python 3, 37 bytes

```
lambda a:sum(a%k for k in range(1,a))

```

Try it online!
> 3 votes

# Answer
# Japt, ~~6~~ 5 bytes

*Saved 1 byte thanks to @Shaggy*

```
Æ%XÃx

```

Test it online!

### How it works

```
         Implicit: U = input number
Æ        Create the range [0, U),
 %XÃ       mapping each item X to U%X. U%0 gives NaN.
    x    Sum, ignoring non-numbers.
         Implicit: output result of last expression

```
> 3 votes

# Answer
# Charcoal, 9 bytes

```
ＩΣＥＮ﹪Ｉθ⊕ι

```

Try it online!

Link is to the verbose version of the code:

```
Print(Cast(Sum(Map(InputNumber(),Modulo(Cast(q),++(i))))));

```
> 3 votes

# Answer
# Standard ML (MLton), ~~53~~ 51 bytes

```
fn& =>let fun f 1a=a|f%a=f(% -1)(a+ &mod%)in f&0end

```

Try it online!

**Ungolfed:**

```
fn n =>
   let fun f 1 a = a
         | f x a = f (x-1) (a + n mod x)
   in
       f n 0
   end

```

---

### Previous 53 byte version:

```
fn n=>foldl op+0(List.tabulate(n-1,fn i=>n mod(i+1)))

```

Try it online!

**Explanation:**

`List.tabulate` takes an integer `x` and a function `f` and generates the list `[f 0, f 1, ..., f(x-1)]`. Given some number `n`, we call `List.tabulate` with `n-1` and the function `fn i=>n mod(i+1)` to avoid dividing by zero. The resulting list is summed with `foldl op+0`.
> 3 votes

# Answer
# Java (OpenJDK 8), 45 bytes

```
n->{int m=n,s=0;for(;m-->1;)s+=n%m;return s;}

```

Try it online!
> 3 votes

# Answer
# Mathematica, 18 bytes

```
#~Mod~i~Sum~{i,#}&

```

Try it online!
> 3 votes

# Answer
# T-SQL, ~~80~~ 79 bytes

*-1 byte thanks to @MickyT*

```
WITH c AS(SELECT @ i UNION ALL SELECT i-1FROM c WHERE i>1)SELECT SUM(@%i)FROM c

```

Receives input from an integer parameter named `@`, something like this:

```
DECLARE @ int = 14;

```

Uses a Common Table Expression to generate numbers from `1` to `n`. Then uses that cte to sum up the moduluses.

Note: a cte needs a `;` between the previous statement and the cte. Most code I've seen puts the `;` right before the declaration, but in this case I can save a byte by having it in the input statement (since technically my code by itself is the only statement).

Try it (SEDE)

---

The less "SQL-y" way is only 76 bytes. This time the input variable is `@i` instead of `@` (saves one byte). This one just does a `while` loop.

```
DECLARE @ int=2,@o int=0WHILE @<@i BEGIN SELECT @o+=@i%@,@+=1 END PRINT @o

```
> 3 votes

# Answer
# , 67 bytes

**4** doesn't have any *modulo* built in.

```
3.79960101002029980200300023049903204040310499040989804102020195984

```

Try it online!
> 3 votes

# Answer
# Vyxal, 3 bytes

```
ɽ%∑

```

Try it Online!

# Vyxal `s`, 2 bytes

```
ɽ%

```

Try it Online!
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
ÎGIN%+

```

Try it online!

My first 05AB1E program ;)

~~Btw I got two 39s, 1 for JS6 and 1 for python, but I was too late~~

Explanation:

```
ÎGIN%+
Î                      # Push 0, then input, stack = [(accumulator = 0), I]
 G                     # For N in range(1, I), stack = [(accumulator)]
  IN                   # Push input, then N, stack = [(accumulator), I, N]
    %                  # Calculate I % N, stack = [(accumulator), I % N]
     +                 # Add the result of modulus to accumulator

```
> 2 votes

# Answer
# Pyth, 5 bytes

```
s%LQS

```

---

```
s%LQS - Full program, inputs N from stdin and prints sum to stdout
s     - output the sum of
 %LQ  - the function (elem % N) mapped over
    S - the inclusive range from 1..N

```

Try it online!
> 2 votes

# Answer
## Windows Batch (CMD), 63 bytes

```
@set s=0
@for /l %%i in (1,1,%1)do @set/as+=%1%%%%i
@echo %s%

```

Previous 64-byte version:

```
@set/ai=%2+1,s=%3+%1%%i
@if %i% neq %1 %0 %1 %i% %s%
@echo %s%

```
> 2 votes

# Answer
# Ruby, 23 bytes

```
->n{(1..n).sum{|i|n%i}}

```

Try it online!
> 2 votes

# Answer
# Julia 0.4, 15 bytes

```
x->sum(x%[1:x])

```

Try it online!
> 2 votes

# Answer
# Add++, 14 bytes

```
L,RAdx$p@BcB%s

```

Try it online!

## How it works

```
L,   - Create a lambda function.
     - Example argument:     [7]
  R  - Range;        STACK = [[1 2 3 4 5 6 7]]
  A  - Argument;     STACK = [[1 2 3 4 5 6 7] 7]
  d  - Duplicate;    STACK = [[1 2 3 4 5 6 7] 7 7]
  x  - Repeat;       STACK = [[1 2 3 4 5 6 7] 7 [7 7 7 7 7 7 7]]
  $p - Swap and pop; STACK = [[1 2 3 4 5 6 7] [7 7 7 7 7 7 7]]
  @  - Reverse;      STACK = [[7 7 7 7 7 7 7] [1 2 3 4 5 6 7]]
  Bc - Zip;          STACK = [[7 1] [7 2] [7 3] [7 4] [7 5] [7 6] [7 7]]
  B% - Modulo each;  STACK = [0, 1, 1, 3, 2, 1, 0]
  s  - Sum;          STACK = [8]

```
> 2 votes

# Answer
# PHP, 61 bytes

*-2 bytes for removing the closing tag*

```
<?php $z=fgets(STDIN);for($y=1;$y<$z;$y++){$x+=$z%$y;}echo$x;

```

Try it online!
> 2 votes

# Answer
# Japt `-mx`, 3 bytes

```
N%U

```

Try it online!
> 2 votes

# Answer
# Brachylog, 9 bytes

```
⟨gz⟦₆⟩%ᵐ+

```

Try it online!
> 2 votes

# Answer
# Ruby, 23 bytes

```
->n{eval [*0..n]*"+n%"}

```

Try it online!

Evaluates a string like `0+n%1+n%2+n%3+n%4+n%5` for n=5.
> 2 votes

# Answer
# Nim, 52 bytes

```
import sugar,sequtils
n=>toSeq(1..n).foldl(a+n%%b,0)

```

Attempt This Online!
> 2 votes

# Answer
# K (ngn/k), ~~13~~ 12 bytes

-1 byte from @ovs' improvement

```
+/1_!'/|1!:\

```

Try it online!

* `|1!:\` generate a two-item list containing `(0..n; n)`
* `!'/` mod `n` by each of `0..n`
* `1_` drop the first result, corresponding to `n % 0`
* `+/` take the sum and (implicitly) return
> 2 votes

# Answer
# Husk, 5 bytes

```
ΣṠM%ḣ

```

Try it online!

### Explanation

```
ΣṠM%ḣ  -- implicit input x, example: 5
 ṠM%   -- map (mod x) over the following..
    ḣ  -- ..the range [1..x]: [5%1,5%2,5%3,5%4,5%5] == [0,1,2,1,0]
Σ      -- sum: 0+1+2+1+0 == 4

```
> 1 votes

# Answer
# Perl 5, 23 + 1 (`-p`) = 24 bytes

```
//;map$\+=$'%$_,1..$_}{

```

Try it online!
> 1 votes

# Answer
# Neim, 3 bytes

Try It Online!

```

```

Explanation:

```
      # Inclusive range
     # Modulo each element with input
      # Sum the list

```
> 1 votes

# Answer
# APL+WIN, 10 bytes

```
+/(⍳n)|n←⎕

```

Prompts for screen input.
> 1 votes

# Answer
# Pari/GP, 17 bytes

```
n->sum(m=1,n,n%m)

```

Try it online!
> 1 votes

# Answer
# Perl 6, ~~21~~ 16 bytes

~~{sum $\_ «%«(1..$\_)}~~

```
{sum $_ X%1..$_}

```

Try it online!

-5 bytes (!) thanks to Brad Gilbert.
> 1 votes

# Answer
# Brain-Flak, ~~70~~ 62 bytes

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

```

Try it online!

It turns out that the straightforward approach is better. Also, keeping a copy of n on the third stack instead of the first stack saves bytes.

```
(([{}])<>)                                                      Initialize both stacks with -n
           {                                              }{}   For all k from n down to 1:
             <>(({})<                      >)                   Store -n on third stack
                     <>{(({})){({}())<>}{}}                     Main part of standard modulus program
                                                                (except that the arguments are negative)
                                             <>
            <                                  >                Ignore evaluation of -n
                                                {}[({}())]      Recover n mod k, and decrement k for the next iteration
          (                                                  )  Sum over all iterations and push

```
> 1 votes

# Answer
**Labyrinth - 45 Characters**

```
?:}}""):={%={{+
     ;        "
@!{{{-{=:}}}::}

```

Basically, it sets up by taking the input of the number that we are modulo summing. It then starts at one, takes the modulo of that number, and checks if it has reached the target number yet. If it hasn't, take the modulo again and add it to the previous one.

(I left out a lot of stack manipulations if you hadn't guessed, and yes, it actually does output the sum of the modulus up to that number)
> 1 votes

# Answer
# Clean, 39 bytes

Literally just Bruce Forte's Haskell answer, but in Clean.

```
import StdEnv
@x=sum(map((rem)x)[1..x])

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 35 bytes

```
: f 0 over 1 do over i mod + loop ;

```

Try it online!

### Explanation

Loops over all numbers from 1 to n-1 and adds n%i to the sum

### Code Explanation

```
: f            \ start a new word definition
  0 over       \ add a 0 to the stack and place a copy of n above it
  1 do         \ start a counted loop from 1 to n-1
    over i     \ copy n to the the top of the stack and place the loop index above it
    mod +      \ take n%i and add it to the sum
  loop         \ end the counted loop
;              \ end the word definition

```
> 1 votes

# Answer
# Labyrinth, 38 bytes

```
?_"):}}:{%={
@ ;        {
!{{=-{:}}:}+

```

Try it online!

Slight improvement to existing answer.

### How it works

Stack notation is `a b ... c | d e ... f` where `a b ... c` part is the main stack, `d e ... f` is auxiliary, and `c` and `d` are the top of two stacks. I found this notation useful in developing and explaining the answer.

```
        Start at the top left
?_"     Push input and a 0, going straight through the junction
        n i=0 | sum=0
)       Increment i
:}}     n | i i sum
:{%=    n i | n%i sum
{{+}    n i | sum'=sum+n%i
:}}:{-  n n-i | i sum'
={      n i n-i | sum'
;       If n-i is nonzero, turn right and discard n-i, continuing the loop
{!@     Otherwise go straight, print sum and terminate

```
> 1 votes

# Answer
# Knight, 30 bytes

```
;=x+=s=y 0P;W>x=y+yT=s+s%x yOs

```

Try it online!

Pretty straightforward.

```
# init x with input converted to number,
# and sum and y to 0
; = x + (= sum = y 0) PROMPT
# for 1..x
; WHILE (> x (= y + y 1))
    # sum += x % y
    : = sum + s (% x y)
: OUTPUT sum

```
> 1 votes

# Answer
# PowerShell Core, ~~37~~ 30 bytes

```
param($a)1..$a|%{$r+=$a%$_}
$r

```

Try it online!

*-7 bytes thanks to @mazzy!*
> 1 votes

# Answer
# J-uby, 24 bytes

Equivalent to my Ruby answer.

```
(:-&(:& &:%|:+&:sum))%:+

```

Attempt This Online!
> 1 votes

# Answer
# K (ngn/k), 16 bytes (Non-competitive)

```
{+/{x!g}'1+!g-1}

```

Try it online!

Non-competitive, because required the use of a global variable called `g` to get input. The reason is because lambda functions in K cannot access variables of another function if they are in that function.

Explanation:

```
{+/{x!g}'1+!g-1}    Main function. Takes g as input (g=14)
           !        Generate a range from 0 to
            g-1     g - 1 (exclusive)               (g-1=13=>range=0..12)
         1+         + 1 for each element            (range=1..13)
        '           For each element
   {   }            Execute a function that returns
    x!g             g mod x (x = element)
 +/                 Sum

```
> 1 votes

# Answer
# Go, 52 bytes

```
func(n int)(o int){for k:=1;k<=n;k++{o+=n%k};return}

```

Attempt This Online!
> 1 votes

# Answer
# Mathematica, 20 bytes

```
Sum[Mod[#,i],{i,#}]&

```

View it on Wolfram Cloud!
> 1 votes

# Answer
# Thunno 2 `S`, 2 bytes

```
R%

```

Attempt This Online!

#### Explanation

```
R%  # Implicit input.
R   # Range. Push [1..input].
 %  # Mod. Vectorises.
    # S flag sums.
    # Implicit output.

```
> 1 votes

# Answer
# Rockstar, 91 bytes

```
listen to N
D's 0
O's 0
while N-D
let D be+1
let M be N/D
turn M down
let O be+N-M*D

say O

```

Try it (Code will need to be pasted in)
> 1 votes

# Answer
# Trilangle, 45 bytes

```
<'?0'1...Lj2'<.zj2'.......L-)S+%,7#..@!,,,/^S

```

Try it on the online interpreter!

TODO: add colorized explanation

```
<'?0'1...Lj2'<.zj2'.......L-)S+%,7#..@!,,,/^S

  ?                                           Get number from stdin
   0'                                         Start sum at 0
 '   1                                        Start counter at 1
          j2'  zj2'       L-     7            Compare the counter and the input
                                     @!,,,/   If they're the same, print the sum and exit
                            )S+%,           S Otherwise, add one iteration and increment the counter
             <      .             #        ^  Loop

```
> 1 votes

# Answer
# Uiua, 7 bytes

```
/+◿+1⇡.

```

Try it!

```
/+◿+1⇡.
      .  # duplicate
     ⇡   # range
   +1    # plus one
  ◿      # mod
/+       # sum

```
> 1 votes

# Answer
# APL(Dyalog Unicode), 8 bytes SBCS

```
+/⊢|⍨1↓⍳

```

Try it on APLgolf!
> 1 votes

# Answer
# C, 43 bytes

```
s,m;f(n){for(s=m=0;m++<n;s+=n%m);return s;}

```

Try it online!

# C (gcc), 38 bytes

```
s,m;f(n){for(s=m=0;m++<n;s+=n%m);s=s;}

```

Try it online!
> 0 votes

# Answer
# , 9 bytes

```
-~1#.i.|]

```

## How it works

```
        ] - the argument
       |  - mod
     i.   - list from 0 to argument - 1
  1#.     - sum (base 1 conversion)
-~        - subtract the argument (to get rid of the n mod 0)

```

Try it online!
> 0 votes

# Answer
# Pip, 7 bytes

```
$+a%\,a

```

Try it online!

```
         a is 1st cmdline arg
    \,a  Inclusive range from 1 through a
  a%     Take a mod each of those numbers (a%a is 0, so doesn't affect the sum)
$+       Fold on +
         Output (implicit)

```
> 0 votes

# Answer
# MATLAB, 19 bytes

```
@(n)sum(mod(n,1:n))

```

Very straightforward, `mod` calculates `n%x` for each natural number below `n`. and `sum` just sums them all. Test:

```
@(n)sum(mod(n,1:n))
ans(14)
ans =

    @(n)sum(mod(n,1:n))
ans =
    31.0000e+000

```
> 0 votes

# Answer
# Gaia, 8 bytes

```
@:…)¦%¦Σ

```

Try it online!
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~69~~ 68 bytes

```
	N =INPUT
A	I =I + 1
	S =LT(I,N) S + REMDR(N,I)	:S(A)
	OUTPUT =S
END

```

Try it online!

```
	N =INPUT				;* read in input
A	I =I + 1				;* I is initialized to 0 so this increments it to 1
	S =LT(I,N) S + REMDR(N,I)	 :S(A)	;* similarly with S, add to the remainder
	LT(I,N) :S(A)				;* on success (I < N), goto A
	OUTPUT =S				;* output the sum
END						;* terminate the program

```
> 0 votes

# Answer
## Clojure, 38 bytes

```
#(apply +(for[i(range 1 %)](mod % i)))

```

Well this is boring, I was hoping `#(apply +(map mod(repeat %)(range 1 %)))` would have been shorter as `mod` gets rarely used in `map` context.
> 0 votes

# Answer
# J, 14 Bytes

```
M=:+/@:|~}.@i.

```

### How it works:

```
M=:                 | Define the verb M
            i.      | Get integers in the range [0, input)
         }.@        | Remove the leading 0
       |~           | Take the original input mod each of these integers, making a new array
   +/@:             | Sum this array

```

### Example:

```
    M 14
31
    M"0 >:i.20    NB. Apply M to each of the integers from 1-20 inclusive
0 0 1 1 4 3 8 8 12 13 22 17 28 31 36 36 51 47 64 61

```
> 0 votes

# Answer
# Common Lisp, ~~50~~ 47 bytes

```
(lambda(n)(loop as i from 1 to n sum(mod n i)))

```

Try it online!
> 0 votes

# Answer
# Befunge-93, 36 bytes

```
p&:10p1>-#1:_$v_g.@
 :p00+g00%\g01<^

```

Try It Online
> 0 votes

# Answer
# Pushy, 13 bytes

```
&1{:2d%vh;OS#

```

**Try it online!**

```
&1{                 \ Make the stack [n, 1, n]
   :     ;          \ n times do (this consumes last n):
    2d              \    Copy the last two items
      %v            \    Get remainder and put result on stack
        h           \    Increment divisor
          OS        \ Sum the second stack
            #       \ Output the result

```
> 0 votes

# Answer
# dc, 31 bytes

```
[dz%rdz<B]sBd1<B0*0[+z1<C]dsCxp

```

Try it online!

Assume our input is the only value on the stack. Macro `B` duplicates top of stack, calculates stack depth, and performs modulo. Runs until stack depth is equal to the input. This works for numbers greater than 1, so we don't run `B` automatically, but instead only if it's greater than 1 (`d1<B`). `B` leaves the input value on top-of-stack, so we multiply by 0. Since 0 is the desired result for an input of 1, this is fine for 1 as well. However, 1 doesn't leave us enough items on the stack to do the initial summation in macro `C`, so we put another 0 on the stack just in case. Macro `C` simply adds the two values on top of the stack, and keeps going until the stack only has a single value. Finally, we `p`rint.
> 0 votes

# Answer
## F#, 35 bytes

```
let s v=Seq.sumBy(fun x->v%x){1..v}

```

Try it online!

Pretty straight-forward.
> 0 votes

# Answer
# Ahead, 21 bytes

```
I&l@O+K<
~>td-! ntd%~

```

Try it online!
> 0 votes

# Answer
# MMIX, 32 bytes (8 instrs)

```
00000000: c1020000 e3010000 1cff0002 25020201  Ḋ£¡¡ẉ¢¡¡÷”¡£%££¢
00000010: feff0006 200101ff 5b02fffc f8020000  “”¡© ¢¢”[£”‘ẏ£¡¡

```

```
modsum  SET  $2,$0              // i = n
        SET  $1,0               // s = 0
0H      DIV  $255,$0,$2
        SUB  $2,$2,1
        GET  $255,rR
        ADD  $1,$1,$255         // loop: s += n % i--
        PBNZ $2,0B              // if(i) goto loop
        POP  2,0                // return [s,n]

```
> 0 votes

# Answer
# Ly, ~~15~~ 13 bytes

```
ns,[:lf%f,]&+

```

Try it online!

*Thanks LyricLy for the tip that dropped 2 chars.*

This generates the modulo numbers on a stack, then sums them and relies on the default action to print the stack to show the answer.

```
ns,             # Read the N req from STDIN, stash it away, then decrement
    [     ,]    # Loop to decrement the top of stack and exit then that's 0
     :l         # Duplicate the top of stack, restore N from backup cell
       f%f      # Flip top two stack enrtries, do modulo math, flip again
             &+ # Sum the stack
                # Ends with one entry on the stack, which prints as a number

```
> 0 votes

# Answer
# Factor \+ `math.unicode`, 33 bytes

```
[ dup [1,b) [ mod ] with map Σ ]

```

Try it online!

* `dup` Duplicate the input.

**Stack:** (e.g.) `14 14`
* `[1,b)` Make a range from `1` inclusive to `14` exclusive.

**Stack:** `14 { 1 2 ... 13 }`
* `[ mod ] with map` Do `14 1 mod`, `14 2 mod`, `14 3 mod`, etc. and collect the results in a sequence the same length as the range.

**Stack:** `{ 0 0 2 2 4 2 0 6 5 4 3 2 1 }`
* `Σ` Sum.

**Stack:** `31`
> 0 votes

# Answer
# Arturo, 21 bytes

```
$->n[∑map n'x->n%x]

```

Try it!
> 0 votes

# Answer
## Malbolge Unshackled, 1,828,225 bytes.

Available on GitHub as StackExchange does not allow posting answers this long.

Use as, having obtained fast20 or any Malbolge Unshackled interpreter:

```
$ echo -ne "\xFF" | time ./fast20 150563.mb | xxd
00000000: c3

```
> 0 votes

---
Tags: code-golf, sequence, division
---


title: Implement an argwhere function

text:
# Question
Title: Implement an argwhere function
The \\$\text{argwhere}\\$ function takes a list of values and a predicate/boolean function as arguments and returns a list of indices where the predicate function returns true in the input list. For example,

```
argwhere([1, 2, 3, -5, 5], x -> x > 2)

```

would produce an output of `[2, 4]` because those are the (0-indexed) indices whose values are greater than two.

## Challenge

Implement the \\$\text{argwhere}\\$ function in your language of choice.

## Format

For the purposes of this challenge, we will deal with lists of integers. You must accept a list of integers and a black box function and return a list of integers in any reasonable format. You may assume the input list will never be empty. Your output may be either 0-indexed or 1-indexed — please specify which.

## Rules

* Builtins are allowed, but please consider adding a less trivial answer so we can see how \\$\text{argwhere}\\$ might be implemented in your language.
* Explaining your answer(s) is encouraged!
* Standard loopholes are forbidden.
* This is , so the code with the fewest bytes (in each language) wins.

###### Why argwhere?

argfoo is a naming convention where you don't want the elements themselves — you want their indices or some other quality. \\$\text{argmax}\\$, \\$\text{argmin}\\$, and \\$\text{argsort}\\$ are examples of this. Read more about it here. (Also, because my favorite programming language comes with this function and it's called `arg-where`. )

## Test cases

0-indexed

| Input | Output |
| --- | --- |
| ``` [1, 2, 0, 0, 3, 0, 0, 0, 4], x -> x == 0<br>[4, 3, 5, 7, 11, 13, 17], x -> x % 2 == 0<br>[8, 9, 10, 11, 12, 13], x -> x + 10 > 20<br>[5, -5, 2, -2, 0], x -> x < 0<br>[5, 2, 0], x -> x < 0 ``` | ``` [2, 3, 5, 6, 7]<br>[0]<br>[3, 4, 5]<br>[1, 3]<br>[] ``` |

1-indexed

| Input | Output |
| --- | --- |
| ``` [1, 2, 0, 0, 3, 0, 0, 0, 4], x -> x == 0<br>[4, 3, 5, 7, 11, 13, 17], x -> x % 2 == 0<br>[8, 9, 10, 11, 12, 13], x -> x + 10 > 20<br>[5, -5, 2, -2, 0], x -> x < 0<br>[5, 2, 0], x -> x < 0 ``` | ``` [3, 4, 6, 7, 8]<br>[1]<br>[4, 5, 6]<br>[2, 4]<br>[] ``` |

# Answer
> 10 votes
# Python 3.8 (pre-release), 45 bytes

```
lambda l,F:[i for i,e in enumerate(l)if F(e)]

```

Try it online!

Looks like it won't get much shorter than this.

Explanation: keep all indexes (found by unpacking; the index is the first item of each 2-element tuple in the return value of `enumerate`) for which the function returns `True` for the corresponding element.

# Answer
> 9 votes
# Haskell, 28 bytes

```
p!v=[i|(i,x)<-zip[0..]v,p x]

```

Try it online!

## Explanation

To get the indices we `zip` the list with the natural numbers `[0..]`. Then we use a list comprehension to get only the correct indices.

# Answer
> 6 votes
# , 24 bytes

```
function(x,f)which(f(x))

```

Try it online!

Uses 's built-in `which` function, which is pretty-close to `argwhere` except for the manner in which `x` and `f` are supplied...

---

# , 26 bytes

```
function(x,f)seq(!x)[f(x)]

```

Try it online!

Roll-your-own version without any built-in.

Note that many/most  functions vectorize, and this is assumed here (and indeed applies to all the test-cases). However, this isn't universal, so if `f` is a non-vectorizing function we'd need +7 bytes: `function(x,f)seq(!x)[sapply(x,f)]`.

# Answer
> 6 votes
# Raku, 13 bytes

```
{grep :k,|@_}

```

Try it online!

Raku's `grep` filtering built-in can return matching indices instead of matching values if given the adverb `:k`. This is just an anonymous function that adds `:k` to the arguments it's given and passes them all to `grep`.

Raku's function objects actually have an `assuming` method that returns a new function with some of the arguments to the original function fixed in advance, so this code would more idiomatically be written `&grep.assuming(:k)` or the even terser `&grep.assuming:k`, but that's too long for golf.

# Answer
> 5 votes
# Vyxal, 2 bytes

```
MT

```

Try it Online!

100% pure ascii. 0-indexed

## Explained

```
MT
M  # Map the function to the list
 T # and return indicies where the result is truthy

```

# Answer
> 5 votes
# JavaScript (V8), 34 bytes

```
a=>f=>a.map((x,i)=>f(x)&&print(i))

```

Try it online!

# Answer
> 5 votes
# Java 8, ~~74~~ 73 bytes

```
f->a->{for(int i=0;i<a.length;i++)if(f.test(a[i]))System.out.println(i);}

```

-1 byte thanks to *@Unmitigated*

0-based. Outputs the indices on separated newlines to STDOUT.

Try it online.

**Explanation:**

```
f->a->{              // Method with Function & integer-array parameters and no return
  for(int i=0;i<a.length;i++)
                     //  Loop `i` in the range [0,length):
    if(f.test(a[i])) //   If the Function for the `i`'th integer of the array is truthy:
      System.out.println(i);}
                     //    Print index `i` with trailing newline

```

# Answer
> 5 votes
# APL (Dyalog Unicode), 4 bytes

Full program. Prompts for array, then function.

```
⍸⎕¨⎕

```

Try it online!

where

the function

`¨` mapped to

the array

# Answer
> 4 votes
# Pari/GP, 20 bytes

-9 bytes thanks to @Joe Slater. Didn't know that `select` can take a flag.

```
(a,g)->select(g,a,1)

```

Try it online!

---

# Pari/GP, 29 bytes

```
(a,g)->[i|i<-[1..#a],g(a[i])]

```

Try it online!

# Answer
> 3 votes
# Ruby, 35 bytes

```
->a,f{(0..a.size).select{f[a[_1]]}}
```

Attempt This Online!

# Answer
> 3 votes
# Haskell + hgl, 19 bytes

```
(cx<ixm pM).^m<m gu

```

## Explanation

Here's the same code converted to a more convenient format:

```
f q x =
  cx $ ixM pM $ m (gu q) x

```

To start we have `gu` which takes a boolean and produces `[]` if false and `[()]` if true.

We map `gu q` across the input list, this converts things that pass the test to `[()]` and things that fail to `[]`.

`pM` takes a list and a value and replaces everything in that list with that value. `ixM` is an index map. It combines every element with its index using some function. Here we use `pM` as the function so that our `[()]`s get replaced with `[index]`.

Then `cx` concats everything back together.

You can reorganize things a bit to get:

# 19 bytes

```
cx.^ixm<(pM^.)<m gu

```

Which is equivalent to

```
f q x =
  cx $ ixM (\x y -> pM x $ gu $ q y)

```

But this is also 19 bytes so nothing is saved.

There is also:

# 19 bytes

```
(st.^^fl<fm cr)^.eu

```

This solution uses an entirely different set of tools to solve the problem but is the same length.

This can be translated to the more conventional

```
f q x =
  m st $ fl (q < cr) $ eu x

```

First `eu` pairs every element with its index in the list. Then `fl (q < cr)` filters using `q` on the second element of each pair. Finally `m st` gets all the indices from the remaining list.

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

*Edit: -1 byte thanks to Razetime*

```
`fNm

```

Try it online!

Razetime already pointed-out in the comments that Husk has a one-byte built-in for `argwhere`: the `where` or `W` function.

So this is an implementation without `W` or any other function that acts-on or returns indices.

```
`f     # filter (select the elements that satisfy a condition)
  N    # the natural numbers
       # using this list to represent yes/no:
   m   # map
       # the black-box function provided as (implicit) argument 1
       # across all elements of (implicit) argument 2

```

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

```
Position[1>0]@*Map

```

Try it online!

Input `[f, list]`. Returns a list of 1-indexed `{index}`s.

Finds the positions of `True`s when the function is mapped onto the list.

---

### Wolfram Language (Mathematica), 13 bytes

```
Position@_?#&

```

Try it online!

Input `[f][list]`. Returns a list of 1-indexed `{index}`s.

Finds the positions of elements that satisfy a predicate - basically a built-in. However, this can possibly include the index of the head of the expression (`{0}`) if the predicate returns `True` when applied to that head (`List`).

# Answer
> 3 votes
# Nim, 60 bytes

```
proc a[S,F](s:S,f:F):S=
 for i,x in s:
  if f x:result.add i

```

Try it online!

# Answer
> 3 votes
# Pip `-xp`, 7 bytes

```
bMa@*:1

```

Takes a list and a function that returns 0 (falsey) or 1 (truthy) as command-line arguments. Uses 0-indexing. Attempt This Online!

### Explanation

```
b        ; Second argument (the function)
 M       ; Mapped to each element of
  a      ; First argument (the list)
   @*:   ; Find all indices of
      1  ; 1 (truthy)

```

# Answer
> 3 votes
# tinylisp, 84 bytes

```
(d w(q((L F N)(i L(i(F(h L))(c N(w(t L)F(a 1 N)))(w(t L)F(a N 1)))L
(q((L F)(w L F 0

```

The second line is an anonymous function that implements argwhere; the first line is a helper function. Uses 0-indexing (though it could just as easily be 1-indexing; simply change the number on the second line). Try it online!

### Explanation

The helper function `w`, in addition to `L` (the list) and `F` (the function), gets an extra argument `N` (the current index). Its logic boils down to:

* If `L` is nonempty:
    + If the result of calling `F` on the `h`ead of `L` is truthy, `c`ons `N` to the front of a recursive call to `w` with arguments:
        - `t`ail of `L`
        - `F`
        - `a`dd 1 to `N`
    + Else, just do the recursive call
* Else, return `L` (empty list)

The anonymous function calls `w` with an initial index of 0.

# Answer
> 3 votes
# JavaScript (Node.js), 34 bytes

```
x=>y=>x.flatMap((b,i)=>y(b)?i:[]);

```

Try it online!

```
f = x => y => x.flatMap((b, i) => y(b) ? i : []);

console.log(f([1, 2, 0, 0, 3, 0, 0, 0, 4])(x => x == 0))
console.log(f([4, 3, 5, 7, 11, 13, 17])(x => x % 2 == 0))
console.log(f([8, 9, 10, 11, 12, 13])(x => x + 10 > 20))
console.log(f([5, -5, 2, -2, 0])(x => x < 0))
console.log(f([5, 2, 0])(x => x < 0))
```

# Answer
> 3 votes
# Julia 1.0, 16 bytes

```
l/f=findall(f,l)

```

Try it online!

Boring builtin, just change of order of parameters, let's move on. (The answers are all 1-indexed, by the way.)

### Julia 1.0, 18 bytes

```
l/f=findall(f.(l))

```

Try it online!

This looks very similar, but works differently and shows off Julia's generalized broadcasting feature: `f.(l)` automatically maps `f` over each element of `l`, collects the results into an Array, type-infers that to be as a `BitVector` (a 1-D array of booleans), and passes that on to `findall`. This single argument version of `findall` accepts only arrays of booleans, and returns indices where there are `true` values.

### Julia 1.0, 21 bytes

```
l/f=axes(l)[1][f.(l)]

```

Try it online!

Even avoiding `findall` altogether, the answer isn't too much longer!

`axes(l)` returns the indices in each dimension of `l`. Here since `l` is one dimensional, we take `axes(l)[1]` which gives the indices of the list. On that, we use Logical indexing: As seen above, `f.(l)` returns an array of booleans. When we use that to index within the list of indices, we get back the indices where the function `f` returns `true`.

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

```
x=>y=>x.reduce((a,b,i)=>y(b)?[...a,i]:a,[])

```

Try it online!

0-indexed, takes input in curry format f(array)(function)

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
δ.Vƶ0K

```

The input black-box function is a string. 1-based.

Try it online or verify all test cases.

**Explanation:**

```
δ       # Map over the (implicit) second input-list,
        # using the first (implicit) input-string as argument:
 .V     #  Evaluate the string as 05AB1E code
   ƶ    # Multiply each item by its 1-based index
    0K  # Remove all 0s
        # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Desmos, 34 bytes

```
a=[1...l.length]b(l)
f(l)=a[a<1/0]

```

\\$b(l)\\$ is the inputted black box function, which you will need to change for each test case (Desmos doesn't support inputting functions as arguments). \\$f(l)\\$ is the argwhere function. The output will be 1-indexed.

Further details in the graph links.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# Python 3, 45 bytes

```
def f(L,F,t=0):F(L[t])and print(t);f(L,F,t+1)

```

Try it online!

A function that prints the indices to STDOUT and terminates with an error.

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

1-based.

Takes an integer array with a length and a function taking an integer.

```
m;f(s,l,p)int*s,p();{putchar(91);for(m=l;l--;s++)p(*s)&&printf("%d,",m-l);puts("]");}

```

Try it online!

# Answer
> 2 votes
# tinylisp, 48 bytes

```
(load library
(d A(q((L F)(all-indices(map F L)1

```

Try it online!

The `library` unsurprisingly contains some rather useful functions for golfing; not sure if this should be scored as `tinylisp + library`. Takes the test harness from DLosc's answer.

# Answer
> 2 votes
# Go, 85 bytes

```
func(f func(int)bool,L[]int)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}

```

Attempt This Online!

# Go, generic, 90 bytes

```
func g[T any](f func(T)bool,L[]T)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}

```

Attempt This Online!

# Answer
> 2 votes
# Ruby, 31 bytes

```
->a,f{a.zip(0..){f[_1]&&p(_2)}}

```

Attempt This Online!

# Answer
> 2 votes
# K (ngn/k), ~~12~~ ~~10~~ ~~9~~ 6 bytes

```
{&x'y}

```

Try it online!

*Down 3 bytes thanks to Steffan*

Takes `x` as black box function and `y` as list of integers.

Explanation:

```
{&x'y}  Main function.
  x'y   Apply each value y to x (x(y)), return a binary list
 &      Get all the truthy indices

```

# Answer
> 2 votes
# Japt, 2 bytes

Black box function is pre-assigned to variable V.

```
ðV

```

Try it

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

```
TM

```

Try it online!

The `'>+10x20` bit in the link is the function \\$f(x) = x + 10 \> 20\\$.

```
TM # Takes a function and a list in any order
 M # Map the list by the function
T  # Return the truthy indexes of the resulting list

```

# Answer
> 2 votes
# , ~~13~~ 11 bytes

*2 bytes saved thanks to Razetime's approach of using `I.`*

```
1 :'I.u"+y'

```

Try it online! Assumes the given predicate is a true boolean predicate, which yields `1` for truthy and `0` for falsey, as is standard in J.

I don't think there's a tacit way to make an adjective as complex as this. Technically, as per standard IO, we can have ~~8~~ bytes by assuming the function is stored in a predefined variable `u`:

```
[:I.u"+

```

## Explanation

Approach c/o Razetime:

```
I.u"+y
  u      the given boolean function
   "+    applied at each cell of
     y   y, the input list
I.       obtain indices where truthy

```

Old approach:

```
u"0#i.@#
    i.     the indices from 0 to
      @#   the length of the input, right-exclusive
   #       and keeping only the elements corresponding to
u          the given boolean function
 "0        applied to each cell of the input

```

# Answer
> 2 votes
# tinylisp 2, ~~33~~ 29 bytes

```
(\(L F)(f(. F(p nth L))(r(# L

```

Try it at Replit. Example session:

```
tl2> (\(L F)(f(. F(p nth L))(r(# L
(() (L F) (f (. F (p nth L)) (r (# L))))
tl2> (def argwhere _)
argwhere
tl2> (argwhere (list 1 2 3 -5 5) (partial < 2))
(2 4)

```

### Explanation

```
(\(L F)(f(. F(p nth L))(r(# L))))
(\                              ) ; Lambda function
  (L F)                           ; that takes a list L and a function F:
       (f                      )  ;  Filter
                       (r(# L))   ;  range(length(L)), the indices of L
         (.           )           ;  by the composition of
            F                     ;  F with
             (p nth L)            ;  a partial application of nth to L

```

That is, for each index, get the element of L at that index and call F on it. If it's truthy, keep that index, otherwise discard it.

# Answer
> 1 votes
# Fortran, 180 bytes

Since there are anonymous functions for other languages allowed, I assume that I can name my argwhere function with a letter and make use of the implicit typing.

```
function J(v,n,f)
integer v(*)
interface
logical function g(m)
end function
end interface
procedure(g) f
allocatable J(:)
J = pack([(i,i=1,n)],mask=[(f(v(i)),i=1,n)])
end function

```

An ungolfed version looks like this.

program test_argwhere
    implicit none
    abstract interface
        logical pure function predicate_t(n)
            integer, intent(in) :: n
        end function
    end interface

    write(*, *) argwhere([1, 3, 4, 8, 5], is_even)

contains

    pure function argwhere(vals, predicate) result(res)
        integer, intent(in) :: vals(:)
        procedure(predicate_t) :: predicate
        integer, allocatable :: res(:)
        integer :: i
        res = pack([(i, i = 1, size(vals))], mask=[(predicate(vals(i)), i = 1, size(vals))])
    end function

    logical pure function is_even(n)
        integer, intent(in) :: n
        is_even = mod(n, 2) == 0
    end function

end program
```
</code></pre>

# Answer
> 1 votes
# Kotlin, 72 61 bytes

```
fun <T> List<T>.f(p:(T)->Boolean)=indices.filter{p(this[it])}

```

0-based solution.

Uses built-in `indices` to perform a filter on.

Example:

```
fun main() {
    println(listOf(1, 2, 0, 0, 3, 0, 0, 0, 4).f { it == 0 })
}

```

# Answer
> 1 votes
# F#, 79 bytes

```
let x a p = a|>Seq.mapi(fun i a -> i,a)|>Seq.filter(fun(_,a)->p a)|>Seq.map fst

```

# Answer
> 1 votes
# J-uby, 31 bytes

Based on Cool guy's Ruby answer and the same length as my Ruby answer but vastly less readable! J-uby still hasn't "clicked" for me so I'm sure some J-uby experts could golf this a lot more.

```
->a,f{:select+(:[]&a|f)^(+a).*}

```

Attempt This Online!

# Answer
> 1 votes
# Arturo, 37 bytes

```
$[a,f][select 1..size a'n->f a\[n-1]]

```

Try it

1-indexed.

# Answer
> 0 votes
# Uiua, 3 bytes

```
⊚^1

```

Try it!

```
⊚^1
 ^1  # call the function
⊚    # where is the result equal to one?

```

---
Tags: code-golf, array, functional-programming
---