function X = transportation ( supply, demand, C )

%*****************************************************************************80
%
%% transportation() computes a good solution to the transportation problem.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    01 April 2026
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Frank Hitchcock,
%    The distribution of a product from several sources to numerous localities,
%    MIT Journal of Mathematics and Physics,
%    Volume 20, pages 224-230, 1941.
%
%  Input:
%
%    real supply(m): the amount of resource available from each supply site.
%
%    real demand(n): the amount of resource needed at each demand site.
%
%    real C(m,n): C(i,j) is the cost of shipping one unit from supply site i 
%    to demand site j.
%
%  Output:
%
%    real X(m,n): X(i,j) is the amount of resource to be shipped from supply
%    site i to demand site j.
%

%
%  Make temporary copies of supply and demand.
%
  s = supply;
  d = demand;
%
%  Initialize the allocation matrix.
%
  [ m, n ] = size ( C );
  X = zeros ( m, n );

  while ( any ( s ) && any ( d ) )
%
%  Find the lowest cost link in the system.
%
    minCost = inf;
    for i = 1 : m
      for j = 1 : n
        if ( ( 0 < s(i) ) && ( 0 < d(j) ) )
          if ( C(i,j) < minCost )
            minCost = C(i,j);
            row = i;
            col = j;
          end
        end
      end
    end
%
%  Allocate as much as possible for this link.
%
    allocation = min ( s(row), d(col) );
    X(row,col) = allocation;
%    
%  Reduce the supply and demand by the amount just shipped.
%
    s(row) = s(row) - allocation;
    d(col) = d(col) - allocation;

  end

  return
end

