Search code examples
c++sortingmatrixkeyranking

Fast key generation for sorting matrices in python/C++


Working in C++ and python, I am looking for a matrix function f (i.e., function that takes a matrix as input and returns a scalar value) that I can use to generate a key for sorting square matrices/2-d arrays with non-negative integer entries.

Example: I have a set of three (or more) matrices A, B,C... with f(A)=a,f(b)=b,f(C)=c... If a<b<c, the program returns the list (A,B,C). If b<a<c the program returns the list (B,A,C).

To ensure that this sorting procedure is reliable, I need that f(A)=f(B) if and only if A==B. I am looking for function that fulfills this condition and computes fast for matrices with up to 100 rows and columns.


Solution

  • In order to correctly overload the < operator, your relation would have to be a strict weak ordering, meaning that, for it to be a strict order, it would have to be asymmetric and transitive, and for it to be a weak order, its incomparability relation must be transitive. In other words, this means that if you're comparing three matrices, A, B, and C, then your "<" cannot have both A

    To satisfy that last requirement, the comparison of A and B must return "equal" only if the matrix A is the same as matrix B, which we know can only be true if every element of A is equal to every element of B. Taking this into consideration, we must use every element in the matrices to ensure that A and B returns "equal" only if the matrix A is the same as matrix B.

    Consider the following function:

    1. If matrix A has less rows than matrix B (return A is less than B)

    2. If matrix B has less rows than matrix A (return B is less than A)

    3. If they have the same number of rows, continue

    4. If matrix A has less cols than matrix B (return A is less than B)

    5. If matrix B has less cols than matrix A (return B is less than A)

    6. If they have the same number of cols, continue

    7. Iterate through every element in A

      i. Compare the integer value at each position and the integer value of B at that same position

      ii. If element at A < element at B (return A is less than B)

      iii. If element at B < element at A (return B is less than A)

    8. If all entries are equal (return A = B)

    This means that in the worst case, the function will have to check every element in the matrices, but in order for the < operator to be correctly overloaded, there is no other choice

    In every other case, the function will return as soon as there is a difference in the elements which will be fairly quick most times