Sunday, May 8, 2011

Matrix Checkerboard


We wish to find, for an arbitrary N, an N x N matrix with the following property: each entry in the matrix is the smallest non-negative number which does not appear either above the entry or to its left.
For example, for N=6, we might have the matrix:
012345
103254
230167
321076
456701
547610

  1. Write a function that computes the entry in a particular row and column. That is, complete the following:

    int entry_at(int row, int column) {

        // ...

    }

  2. Can you write the entry_at function to run in constant space and constant time?
Soln: Assume we count rows and columns starting with 0: 0, 1, 2, and so on. Let amn denote the number that appears in the (m, n)-cell. Then

amn = m ^ n.
It follows that this particular Latin square serves as the "addition" table for the XOR operation over the set of nonnegative integers. In particular, using the binary representation,
a100, 1000= 100 ^ 1000
= (1100100)2 ^ (1111101000)2
= (1110001100)2
= 908.
[Of course, if initially rows and columns were counted starting with 1, then we should consider instead 99 ^ 999 which is 900!]

1 comment:

  1. You can find the proof of O(1) time and space algorithm here http://tech-queries.blogspot.com/2011/08/matrix-madness-smallest-non-negative.html

    ReplyDelete