// n and m are the dimensions of the matrix
// A, B, C, and D are the minimum and maximum number of potatoes for each row and column
int[,] matrix = new int[n, m];
int[] rowSum = new int[n];  // keep track of the sum of each row
int[] colSum = new int[m];  // keep track of the sum of each column

for (int i = 0; i < n; i++) {
    int rowMax = Math.Min(B[i], D.Sum() - colSum.Sum());  // maximum sum for this row
    int rowMin = Math.Max(A[i], C.Sum() - colSum.Sum());  // minimum sum for this row
    if (rowMin > rowMax) {
        // if the minimum sum is greater than the maximum sum, there is no solution
        throw new Exception("No solution exists");
    }

    for (int j = 0; j < m; j++) {
        // generate a random number between rowMin and rowMax
        matrix[i, j] = UnityEngine.Random.Range(rowMin, rowMax+1);
        rowSum[i] += matrix[i, j];
        colSum[j] += matrix[i, j];
    }
}

// now adjust the rows and columns if necessary
bool rowsChanged = true;
bool colsChanged = true;
while (rowsChanged || colsChanged) {
    rowsChanged = false;
    colsChanged = false;

    // adjust the rows
    for (int i = 0; i < n; i++) {
        int rowMax = Math.Min(B[i], D.Sum() - colSum.Sum() + rowSum[i]);  // maximum sum for this row
        int rowMin = Math.Max(A[i], C.Sum() - colSum.Sum() + rowSum[i]);  // minimum sum for this row
        if (rowMin > rowMax) {
            // if the minimum sum is greater than the maximum sum, there is no solution
            throw new Exception("No solution exists");
        }
        if (rowSum[i] < rowMin || rowSum[i] > rowMax) {
            // if the row sum is less than the minimum or greater than the maximum, adjust the row
            for (int j = 0; j < m; j++) {
                int oldVal = matrix[i, j];
                int newVal = Mathf.Clamp(oldVal + rowMin - rowSum[i], A[i], B[i]);
                matrix[i, j] = newVal;
                rowSum[i] += newVal - oldVal;
                colSum[j] += newVal - oldVal;
            }
            rowsChanged = true;
        }
    }

    // adjust the columns
    for (int j = 0; j < m; j++) {
        int colMax = Math.Min(D[j], B.Sum() - rowSum.Sum() + colSum[j]);  // maximum sum for this column
        int colMin = Math.Max(C[j], A.Sum() - rowSum.Sum() + colSum[j]);  // minimum sum for this column
        if (colMin > colMax) {
            // if the minimum sum is greater than the maximum sum, there is no solution
            throw new Exception("No solution exists");
        }
        if (colSum[j] < colMin || colSum[j] > colMax) {
            // if the column sum is less than the minimum or greater than the maximum, adjust the column
            for (int i = 0; i < n; i++) {
                int oldVal = matrix[i,