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

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Is this a Hadamard matrix?

Hadamard matrices is a square matrix whose entries are either +1 or −1 and whose rows are mutually orthogonal.

In other words, it means that each pair of rows has matching entries in exactly half of their columns and mismatched entries in the remaining columns. As a result, the same properties hold for columns as well as rows.

Examples

[ 1 1 1 1
 1 -1 1 -1
 1 1 -1 -1
 1 -1 -1 1 ]

This is a Hadamard matrix, because any pair of rows has matching entries in exactly half of their columns, like:

[ 1 1 1 1
 | / | /
 1 -1 1 -1
 ]

There are 2 |s (matching entries) and 2 /s (mismatched entries). The same logic also applies by columns:

[ 1 ― 1 
 1 ― 1 
 1 ~ -1 
 1 ~ -1 ]

There are two s (matching entries) and two ~s (mismatched entries).

This logic can be applied to every pair of rows and columns.

Another example:

[ 1 1
 1 -1 ]

This is a hadamard matrix, because there is only one pair of rows and one pair of columns, but their matching entries is still half of the size of the matrix.

A counterexample like:

[ 1 -1 1 -1
 -1 1 -1 1
 1 -1 1 -1
 -1 1 -1 1 ]

is not a Hadamard matrix, because two pair of rows match in all columns, and four rows don't match in any column. The same logic applies to pair of columns.

Note that

[ 1 ]

is also a Hadamard (1x1) matrix, and your code should handle that (See challenge).

Notes

  • The matrix inputs are always square

  • The matrix will only contain -1 or 1. No zeros.

Challenge

The shortest answer that checks if a matrix is a Hadamard matrix wins, because this is . You may not take input as 1d array, it must be 2d array if your language has a builtin 2d arrays.

Answer*

Draft saved
Draft discarded
Cancel
2
  • \$\begingroup\$ I don't think the rules allow 2 inputs, unfortunately. \$\endgroup\$ Commented Jan 8 at 14:54
  • \$\begingroup\$ Yes, but the challenge is not about parsing the input. It is trivial to get the head and rest from a 2D array. The consensus is to always allow flexible input formats. \$\endgroup\$ Commented Jan 8 at 15:18

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