Created
March 8, 2023 07:52
-
-
Save chuongmep/59fb81e0a94acd5dc939ed2653ad63d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Author
chuongmep
commented
Mar 9, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment