Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Last active March 10, 2023 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuongmep/9d60851ce4f3c23fdf3653a9fa5ed819 to your computer and use it in GitHub Desktop.
Save chuongmep/9d60851ce4f3c23fdf3653a9fa5ed819 to your computer and use it in GitHub Desktop.
using System;
void Main()
{
// define the cost matrix
int[,] costMatrix = {{17, 10, 21},
{15, 12, 19},
{13, 10, 17}};
int numRows = costMatrix.GetLength(0);
int numCols = costMatrix.GetLength(1);
// generate all possible assignments
var assignments = GetPermutations(Enumerable.Range(0, numCols), numRows).ToList();
// calculate the cost of each assignment
int minCost = int.MaxValue;
List<int> minAssignment = new List<int>();
foreach (var assignment in assignments)
{
int cost = 0;
for (int i = 0; i < numRows; i++)
{
cost += costMatrix[i, assignment.ToList()[i]];
}
Console.WriteLine($"Assignment: {string.Join(", ", assignment)}, Cost: {cost}");
if (cost < minCost)
{
minCost = cost;
minAssignment = assignment.ToList();
}
}
Console.WriteLine($"\nMinimum cost: {minCost}, Assignment: {string.Join(", ", minAssignment)}");
}
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1)
{
return list.Select(x => new[] { x });
}
return GetPermutations(list, length - 1)
.SelectMany(x => list.Where(y => !x.Contains(y)),
(t1, t2) => t1.Concat(new[] { t2 }));
}
@chuongmep
Copy link
Author

Assignment: 0, 1, 2, Cost: 46
Assignment: 0, 2, 1, Cost: 46
Assignment: 1, 0, 2, Cost: 42
Assignment: 1, 2, 0, Cost: 42
Assignment: 2, 0, 1, Cost: 46
Assignment: 2, 1, 0, Cost: 46

Minimum cost: 42, Assignment: 1, 0, 2

@chuongmep
Copy link
Author

import itertools

# define the cost matrix
cost_matrix = [[17, 10, 21], [15, 12, 19], [13, 10, 17]]

# generate all possible assignments
assignments = list(itertools.permutations(range(len(cost_matrix[0]))))

# calculate the cost of each assignment
min_cost = float('inf')
min_assignment = []
for assignment in assignments:
    cost = sum([cost_matrix[i][assignment[i]] for i in range(len(assignment))])
    print(f"Assignment: {assignment}, Cost: {cost}")
    if cost < min_cost:
        min_cost = cost
        min_assignment = assignment

print(f"\nMinimum cost: {min_cost}, Assignment: {min_assignment}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment