Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

7 of 9
added 698 characters in body
Giuseppe
  • 29.4k
  • 3
  • 33
  • 106

R, (削除) 78 (削除ここまで) (削除) 70 (削除ここまで) (削除) 69 (削除ここまで) (削除) 68 (削除ここまで) 54 bytes

function(m){d=diag(nrow(m))
d[1,]=d[,1]=1
all(!!m==d)}

Try it online!

Porting Luis Mendo's answer is much shorter than my former approach.

old answer, 68 bytes:

function(m,i=which(!m,T))all(i[,1]-i[,2],i!=1,sum(m>0)==3*nrow(m)-2)

Try it online!

duckmayr's answer tests that all entries on the main diagonal and first row/column (m[i]) are nonzero and the rest (m[-i]) are zero, using some nice arithmetic to get the diagonal and the first row.

This answer, however, tests to make sure that (1) zero entries are not on the main diagonal or the first row/column, and (2) that there are, given an n x n matrix, 3*n-2 nonzero entries.

which returns the indices where its input is TRUE, and with the optional arr.ind=T, returns an array of indices for each array dimension, in this case, two.

Hence when any(i[,1]==i[,2]), there exists a zero on the diagonal, and when any(i==1), there exists a zero in the first row or the first column.

Finally, a little arithmetic shows that the number of nonzero entries must be 3*n-2, n from the first column, n-1 from the diagonal, and n-1 from the first row.

Giuseppe
  • 29.4k
  • 3
  • 33
  • 106

AltStyle によって変換されたページ (->オリジナル) /