| Bytes | Lang | Time | Link |
|---|---|---|---|
| 070 | Scala 3 | 240227T092743Z | t9dupuy |
| 006 | BQN | 240226T235342Z | DLosc |
| 067 | Python 3.8 prerelease | 230714T202400Z | Hunaphu |
| 006 | Uiua | 231012T195722Z | chunes |
| 009 | Itr | 230731T150701Z | bsoelch |
| 077 | PowerShell Core | 230731T214721Z | Julian |
| 008 | Pyth | 230717T180714Z | CursorCo |
| 065 | Kotlin | 230717T174216Z | Cactusro |
| 006 | Pip P | 230717T160138Z | DLosc |
| 005 | 05AB1E | 230717T120037Z | Kevin Cr |
| 007 | Japt | 230717T112217Z | Shaggy |
| 009 | Dyalog APL | 230714T165247Z | RubenVer |
| 062 | TypeScript's Type System | 230717T004021Z | noodle m |
| 053 | ><> Fish | 230716T174155Z | mousetai |
| 002 | MATL | 230714T170146Z | Luis Men |
| 021 | KamilaLisp v0.3 | 230716T103159Z | Kamila S |
| 006 | Nekomata | 230716T052611Z | alephalp |
| 055 | Python | 230715T051305Z | SuperSto |
| 034 | Haskell | 230716T030214Z | xnor |
| nan | Go | 230714T174031Z | bigyihsu |
| 081 | Rust | 230715T215125Z | leo848 |
| 039 | Haskell | 230715T151445Z | Magma |
| 067 | Haskell | 230715T125134Z | matteo_c |
| 007 | K ngn/k | 230715T085445Z | south |
| 3125 | Vyxal | 230715T054444Z | lyxal |
| 033 | Excel | 230715T045132Z | Jos Wool |
| 014 | Mathematica | 230715T045717Z | 138 Aspe |
| 097 | Racket | 230715T003454Z | Ed The & |
| 034 | JavaScript Node.js | 230715T000831Z | l4m2 |
| 009 | APLDyalog Unicode | 230714T200809Z | att |
| 005 | Thunno 2 | 230714T171825Z | The Thon |
| 023 | Python | 230714T183607Z | The Thon |
| 004 | Octave | 230714T183225Z | Hunaphu |
| 015 | Factor + math.matrices | 230714T181438Z | chunes |
| 020 | R | 230714T174853Z | pajonk |
| 011 | Charcoal | 230714T173356Z | Neil |
| 011 | PARI/GP | 230714T171816Z | RubenVer |
| 006 | J | 230714T171748Z | Jonah |
| 066 | Python | 230714T171616Z | Sapherey |
| 005 | Jelly | 230714T164611Z | Unrelate |
Scala 3, 70 bytes
x=>x.zipWithIndex.map((e:Int,i:Int)=>Seq.fill(x.size)(0).updated(i,e))
BQN, 6 bytes
⊢×⍋=⌜⍋
Explanation
⊢×⍋=⌜⍋
⍋ Grade up; for our purposes, gives a list of unique integers of the same
length as the argument
⍋ Grade up again
=⌜ Create an equality table
This gives an identity matrix the same size as the length of the argument
⊢× Multiply each row by the corresponding element of the argument
Python 3.8 (pre-release), 67 bytes
lambda a:[[x*(i==j) for i,x in enumerate(a)]for j in range(len(a))]
A 42-byte solution that only works if all elements are unique:
lambda a:[[x*(x==y) for x in a]for y in a]
Uiua, 7 6 bytes
×⊞=.⍏.
-1 thanks to Bubbler
×⊞=.⍏.
. # duplicate
⊞=.⍏ # identity matrix
× # multiply
Itr, 9 bytes
#äLºµÍ·®£
prints the elements of the matrix separated by spaces, with , separating the rows. Does not print the zero entries above the diagonal.
Explanation
# ; read array from standard input
äLº ; push the range from zero to array.length-1
µÍ ; replace each element in the range with a vector having a one at the given index
; this will give an identity matrix of size array.length represented as 2D array
· ; point-wise multiplication
® ; convert result to matrix
£ ; print
Itr, 10 9 bytes
(broken in current version)#äLºµÍ·®+£
#LºµÍ·®+£
Adds zero to the result to force the entries above the diagonal to be printed.
Itr, 8 bytes
#LºµÍ·®£
the ä before the L is no longer necessary in newer versions
PowerShell Core, 77 bytes
if($l=($a=$args).count){($k=1..$l)|%{$r++
$c=1
,($k|%{$a[$_-1]*!($c++-$r)})}}
Pyth, 8 bytes
.eXmZQkb
Explanation
.eXmZQkbQ # implicitly add Q
# implicitly assign Q = eval(input())
.e Q # enumerated map Q over lambda, b, k
mZQ # list of zeros the same length as Q
X kb # replace position k with b
Pip -P, 6 bytes
g*EY#g
(The flag is only necessary to format the output in a readable way; any of -P, -p, -S will do.)
Explanation
g*EY#g
g ; List of command-line arguments
# ; Length
EY ; Identity matrix of that size
g* ; Multiply each row by the corresponding element of g
05AB1E, 5 bytes
āDδQ*
Try it online or verify all test cases.
Explanation:
āDδQ # Create an identify matrix the size of the input-length:
ā # Push a list in the range [1, (implicit) input-length]
D # Duplicate it
δ # Apply double-vectorized:
Q # Check whether the values are equal
* # Multiply the values in each row with the values of the (implicit) input-list
# (after which the matrix is output implicitly as result)
Japt, 7 bytes
£çT hYX
£çT hYX :Implicit input of array U
£ :Map each X at index Y
ç : Fill U with
T : 0
hYX : Replace the element at index Y with X
Dyalog APL, 9 bytes
Thanks to @att for -4
⊢×⍤1⍋∘.=⍋
⊢ # v
×⍤1 # multiplied row-wise with
⍋∘.=⍋ # the identity matrix of size (#v)
💎 Created with the help of Luminespire
Dyalog APL, 16 bytes + Not Bonus
The only other applicable scalar type are characters, where APL uses the space as the empty character, so this code also does
,⍨∘≢⍴∊⍤(⊢↑¨⍨1+≢)
⍴ # Reshape
,⍨∘≢ # to (#v)*(#v) matrix
∊⍤ # the flattened list of lists built by
⊢ ¨ # taking each item of v
↑ ⍨ # and padding it with
1+≢ # (#v) zeros
💎
Created with the help of Luminespire
This works by noticing that, if the diagonalized matrix is read as a single list, row by row, each entry of v is spaced with as many zeros as the length of v.
TypeScript's Type System, 62 bytes
type F<V>={[I in keyof V]:{[J in keyof V]:J extends I?V[J]:0}}
Try it at the TypeScript Playground!
It's been a little while since I've golfed in TS types, so it's possible (though I think unlikely) that I missed a shorter way to do this. This one is pretty simple, but I'll leave an explanation anyway:
type F<V> = // type F taking generic tuple type V
{ [I in keyof V]: // for each I in V's indices:
{ [J in keyof V]: // for each J in V's indices:
J extends I // are J and I the same type?
? V[J] // if so, index into V with J
: 0 // otherwise, 0
} // end
} // end
I tried putting keyof V into type F<V,K=keyof V> but that doesn't work since the compiler complains that K could be a type unrelated to an array key, and it doesn't save enough bytes for //ts-ignore to be worth it.
MATL, 2 bytes
Xd
The code uses the builtin function Xd (which corresponds to MATLAB's diag). Try it online!
KamilaLisp v0.3, 21 bytes
[* #0[(⌼ =)#0#0]∘⍳∘⍴]
The code generates a range vector from 0 to the size of the argument; then it computes the Cartesian product of the range vector and itself using equality as the functor, therefore computing the identity matrix. Each row of the identity matrix is then multiplied by the initial vector.
Nekomata, 6 bytes
x:ᵒ-¬*
Multiplies the identity matrix like other answers.
x:ᵒ-¬*
x [0 .. length - 1]
: Duplicate
ᵒ Outer product with
- Subtract
¬ Logical NOT
* Multiply
Haskell, 34 bytes
foldr(\a m->(a:(0<$m)):map(0:)m)[]
Uses the recursive method from Magma of expanding the matrix with a new value in the top left, but with foldr and <$.
Go, 135 130 bytes
func(v[]int)(A[][]int){for i,_:=range v{r:=make([]int,len(v))
for j,_:=range v{e:=0
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}
Go, 141 136 bytes + Not Bonus
func f[T any](v[]T)(A[][]T){for i,_:=range v{r:=make([]T,len(v))
for j,_:=range v{var e T
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}
Rust, 83 81 bytes
Simple and dirty imperative solution.
-2 bytes by taking a slice instead of a vec
|v:&[i8]|{let l=v.len();let mut r=vec![vec![0;l];l];for i in 0..l{r[i][i]=v[i]}r}
Rust, 126 124 bytes + Not Bonus
The Copy bound is technically too strict and a Clone bound would be enough, but it would also be one byte longer :shrug:.
fn f<T:Default+Copy>(v:&[T])->Vec<Vec<T>>{let l=v.len();let mut r=vec![vec![T::default();l];l];for i in 0..l{r[i][i]=v[i]}r}
Haskell, 39 bytes
f[]=[];f(a:b)=(a:map(0*)b):map(0:)(f b)
Recursively generates the matrix by appending a value at the top left corner of a smaller matrix.
Haskell, 67 bytes
f v=m.(m.).h where m g=map g[0..length v-1];h z i j|i==j=v!!i|1>0=z
K (ngn/k), 7 bytes
{x*=#x}
My first K post. I tried real hard to make a Bubbler train work here but failed.
Vyxal, 25 bitsv2, 3.125 bytes
LÞ□*
The P flag on the permalink is to make the test cases pass (for some strange reason, I never made it not check exact string representation.) Individual cases all produce the right output with vyxal list syntax without the flag.
Explained
LÞ□*
L # Push the length of the input
Þ□ # Construct an NxN identity matrix
* # and pair-wise vectorise multiplication
💎
Created with the help of Luminespire.
Excel, 33 bytes
=IFERROR(MUNIT(ROWS(A1#))*A1#,"")
Excel, 39 bytes + Not Bonus
=IFERROR(IF(MUNIT(ROWS(A1#)),A1#,0),"")
Input is vertical spilled range A1#.
Having to deal with the empty vector is inconvenient; otherwise these would be just 21 and 27 bytes respectively.
Racket, 97 bytes; Not Bonus
(define(f v)(let([n(length v)])(for/list([i(range n)])(list-set(make-list n 0)i(list-ref v i)))))
Explanation
After reading in the input as a list called v, we obtain the length of v and store it as n.
(define (f v)
(let ([n (length v)])
...))
We then loop through the range \$ 0 \le i < n \$ and for each iteration, we return a new list (a row of the matrix) of n length filled with zeros except at the index of i which is filled with the corresponding value from v at index i.
(define (f v)
(let ([n (length v)])
(for/list ([i (range n)])
(list-set (make-list n 0)
i
(list-ref v i)))))
The for/list function returns the collected rows after each iteration.
Not Bonus
While the rows start with zeros, any data in v will still be preserved. What this means is that we can pass list of strings to f and receive a matrix with both strings and zeros as the zero-value:
; Strings
(f '("h" "e" "y"))
;;> '(("h" 0 0) (0 "e" 0) (0 0 "y"))
; Symboles
(f '(a b c))
;;> '((a 0 0) (0 b 0) (0 0 c))
; Characters
(f '(#\d #\e #\f))
;;> '((#\d 0 0) (0 #\e 0) (0 0 #\f))
Have a wonderful weekend!
APL(Dyalog Unicode), 9 bytes SBCS
-∘⍳⍤≢↑⍤0⊢
Left-pads each \$v_i\$ to a vector of length \$i\$ and implicitly mixes.
Each row's fill elements match the type of the corresponding element of the vector.
Thunno 2, 5 bytes
ėDȷ=×
Inspired by Unrelated String's Jelly answer.
Explanation
ėDȷ=× # Implicit input
ė # Length range
D # Duplicate
ȷ # Outer product over:
= # Check for equality
× # Multiply by the input
# Implicit output
R, 20 bytes
\(x)diag(x,sum(x|1))
The diag built-in almost works here, but fails for inputs of length 1, where it produces identity matrix of size of the input. Unless specified nrow argument.
Less boring - without diag built-in:
R, 54 bytes
\(x,`[`=matrix)c(x,rep(0*x,n<-sum(x|1)))[n+1,n,T][n,n]
Idea: construct a vector such that every entry of the input \$x\$ of length \$n\$ is followed by \$n\$ zeros. A matrix with \$x\$ in the first row and followed by \$n\$ rows of zeros works too. Then, we can put this in a \$n\times n\$ matrix resulting in \$x\$ on the diagonal.
Ungolfed:
\(x){n=length(x)
m=matrix(c(x,rep(0,n^2)), nrow=n+1, ncol=n, byrow=TRUE)
matrix(m, nrow=n, ncol=n)}
R, 27 bytes
\(v,x=seq(a=v))v*!x%o%x-x^2
Heavily inspired by @Kirill L.'s answer to the linked challenge.
Charcoal, 11 bytes + Not Bonus
⭆¹EθEθ×⁼μξν
Try it online! Link is to verbose version of code. Explanation:
θ Input array
E Map over elements
θ Input array
E Map over elements
μ Row index
⁼ Equals
ξ Column index
× Multiplied by
ν Inner element
⭆¹ Pretty-print
Using And instead of Times would have made the code minusculely more efficient but this way the code produces empty strings on the non-diagonal entries when given a string array as input.
PARI/GP, 11 bytes
matdiagonal
Builtins are always a sad answer, aren't they?
Python, 66 bytes
def f(a):n=range(len(a));return[[(i==j)*a[i]for i in n]for j in n]
Python, 66 bytes
def f(a):x=len(a);return[[0]*i+[a[i]]+[0]*(x+~i)for i in range(x)]
This solution was inspired by this answer.
Jelly, 5 bytes
J=þ`a
J=þ` Identity matrix:
þ table
J [1 .. length]
` with itself
= by equality.
a Vectorizing logical AND; replace ones with elements of the vector.
If output can be flat:
Jelly, 3 bytes
jn`
j Join the vector on
n the list of, for each element, if it doesn't equal
` itself.
If the empty vector didn't have to be handled, this could tie non-flat as jn`sL; it passes all current test cases as j¬ owing to all inputs being nonzero (which is not guaranteed by the spec).