1

I've already asked for the name of a problem in which we search for a certain matrix with given sums of each row and column in the Math StackExchange:

https://math.stackexchange.com/questions/3697532/find-matrices-given-sums-of-each-row-and-column-with-bounded-integer-entries-ma

Its name is Fixed-Charge Transportation Problem and it is also related to graph theory and integer programming.

I've also implemented some algorithms to solve it in javascript, but they are slow. Basically, it tests for every possibility.

Do somebody have already implemented, or knows some js lib with this (and maybe more) graph algorithm available?

EDIT 1

Only a fixed cost equal one is being considered. This is enough to solve my problem. I am after any solution at first, since it is possible to swap quantities in rectangularly positioned cells to find a local minimum.

This is my current recursive algorithm (variable names come from portuguese, so I added some comments for clarity):

var gra; //desired sums for rows
var dem; //desired sums for columns
var x; //current solution being built (bidimensional array); will be returned when one is found

var [iMax, jMax] = [gra.length, dem.length];

function passo(i, j) {
    if (j == jMax - 1) { //if last column
        var m = gra[i];
        
        if (m > max[i][j]) {
            return;
        }
        
        x[i][j] = m;
        gra[i] -= m;
        dem[j] -= m;
        
        if (i == iMax - 1) {
            if (gra[i] == 0 && dem[j] == 0) {
                return true;
            }
        } else {
            if (passo(i + 1, j)) return true;
        }
        
        gra[i] += m;
        dem[j] += m;
    } else {
        if (i == iMax - 1) { //if last row
            var m = dem[j];
            if (m <= max[i][j] && m <= gra[i]) {
                x[i][j] = m;
                gra[i] -= m;
                dem[j] -= m;
                
                if (passo(0, j + 1)) return true;
                
                gra[i] += m;
                dem[j] += m;
            }
        } else {
            for (var m = Math.min(max[i][j], gra[i], dem[j]); m >= 0; m--) {
                x[i][j] = m;
                gra[i] -= m;
                dem[j] -= m;
                
                if (passo(i + 1, j)) return true;
                
                gra[i] += m;
                dem[j] += m;
            }
        }
    }
}

passo(0, 0);
Eduardo Poço
  • 2,819
  • 1
  • 19
  • 27
  • Might be worthwhile posting the functioning algorithms so that others can offer performance advice. – Trentium Dec 21 '20 at 01:22

1 Answers1

2

Got a lib for it.

It is glpk.js, a wrapper for GLPK with a json interface.

https://github.com/jvail/glpk.js

The problem can be solved with (mixed) integer linear programming.

Eduardo Poço
  • 2,819
  • 1
  • 19
  • 27