Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add Numbers in a Matrix to Yield Minimum Result?

This is more of an algorithmic/math problem but I'm hoping to implement a solution in C++.

Suppose I have a matrix like so where the dots represent integers:

   W  X  Y  Z
A  .  .  .  . 
B  .  .  .  .
C  .  .  .  .
D  .  .  .  .

How would I yield the minimum result if I had to pick one number from each column such that there is at most one number from each row?

For instance, I could choose AW BX CY DZ or AZ BX CY DW but NOT AW BW CZ DZ

The brute force approach would seem to take n! calculations. Is there a quicker way? Eventually I would like to add numbers in matrices of size ~60.

Also, all numbers range from 0 to 256.

like image 988
user2445455 Avatar asked Jul 03 '13 19:07

user2445455


People also ask

How do you find the minimum value of a matrix?

M = min( A ) returns the minimum elements of an array. If A is a vector, then min(A) returns the minimum of A . If A is a matrix, then min(A) is a row vector containing the minimum value of each column of A .

How do you add numbers to a matrix in MATLAB?

You can add one or more elements to a matrix by placing them outside of the existing row and column index boundaries. MATLAB automatically pads the matrix with zeros to keep it rectangular. For example, create a 2-by-3 matrix and add an additional row and column to it by inserting an element in the (3,4) position.

How do you sum all values in a matrix in MATLAB?

S = sum( A , 'all' ) computes the sum of all elements of A . This syntax is valid for MATLAB® versions R2018b and later. S = sum( A , dim ) returns the sum along dimension dim . For example, if A is a matrix, then sum(A,2) is a column vector containing the sum of each row.

How do you accumulate values in MATLAB?

B = cumsum( A ) returns the cumulative sum of A starting at the beginning of the first array dimension in A whose size does not equal 1. If A is a vector, then cumsum(A) returns a vector containing the cumulative sum of the elements of A .


1 Answers

And if you'd rather not code it yourself, you could always use someone else' hard-work and kind publication. This one in Haskell, solves a 60x60 random matrix in less than two tenths of a second on my old laptop. What a great algorithm!

import Data.Algorithm.Munkres
import Data.Array.Unboxed
import Data.List (transpose)

solve n matrix = 
  hungarianMethodInt (listArray ((1,1),(n,n)) $ concat $ transpose matrix)
like image 68
גלעד ברקן Avatar answered Oct 25 '22 02:10

גלעד ברקן