Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Created March 8, 2023 07:52
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/59fb81e0a94acd5dc939ed2653ad63d7 to your computer and use it in GitHub Desktop.
Save chuongmep/59fb81e0a94acd5dc939ed2653ad63d7 to your computer and use it in GitHub Desktop.
void Main()
{
// Example cost matrix
int[,] matrix = {{7, 0, 8},
{15, 2, 7},
{5, 3, 5}};
int n = matrix.GetLength(0);
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
permutation[i] = i;
}
int[] minPermutation = new int[n];
int minCost = int.MaxValue;
BruteForceMethod bruteForce = new BruteForceMethod();
// Generate all permutations and find the minimum cost permutation
bruteForce.Permute(permutation, 0, n, matrix, ref minCost, ref minPermutation);
// Output the minimum cost and the corresponding permutation
Console.WriteLine("Minimum Cost: " + minCost);
Console.Write("Permutation: ");
for (int i = 0; i < n; i++)
{
Console.Write(minPermutation[i] + " ");
}
}
public class BruteForceMethod
{
// Function to calculate the total cost of a permutation
static int CalculateCost(int[,] matrix, int[] permutation)
{
int cost = 0;
int n = matrix.GetLength(0);
for (int i = 0; i < n; i++)
{
cost += matrix[i, permutation[i]];
}
return cost;
}
// Function to generate all possible permutations
public void Permute(int[] permutation, int start, int n, int[,] matrix, ref int minCost, ref int[] minPermutation)
{
if (start == n - 1)
{
int cost = CalculateCost(matrix, permutation);
if (cost < minCost)
{
minCost = cost;
Array.Copy(permutation, minPermutation, n);
}
}
else
{
for (int i = start; i < n; i++)
{
int temp = permutation[start];
permutation[start] = permutation[i];
permutation[i] = temp;
Permute(permutation, start + 1, n, matrix, ref minCost, ref minPermutation);
temp = permutation[start];
permutation[start] = permutation[i];
permutation[i] = temp;
}
}
}
}
@chuongmep
Copy link
Author

ảnh

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