Created
May 4, 2021 05:22
-
-
Save JohnBaek/91af05d4d399ed051b66df3d3e2da413 to your computer and use it in GitHub Desktop.
Magic Square
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
List<List<int>> problem = new List<List<int>>() | |
{ | |
new List<int>(){ 4 ,8 ,2 }, | |
new List<int>(){ 4 ,5 ,7 }, | |
new List<int>(){ 6 ,1 ,6 }, | |
}; | |
int[] row1Arr = problem[0].ToArray(); | |
int[] row2Arr = problem[1].ToArray(); | |
int[] row3Arr = problem[2].ToArray(); | |
// int[] inputArr = row1Arr.Join() | |
// for (int i = 0; i < 3; i++){ | |
// for (int j = 0; j < 3; j++){ | |
// if (i == 0) | |
// inputArr[i*3 + j] = row1Arr[j]; | |
// if (i == 1) | |
// inputArr[i*3 + j] = row2Arr[j]; | |
// if (i == 2) | |
// inputArr[i*3 + j] = row3Arr[j]; | |
// } | |
// } | |
int cost = 999; | |
for (int i = 0; i < 8; i++){ | |
int [] solArr = GetSolutionArray(i); | |
int tempCost = ComputeCost(inputArr, solArr); | |
if (tempCost < cost) | |
cost = tempCost; | |
} | |
Console.WriteLine(cost.ToString()); | |
int ComputeCost(int[] inputArr, int[] checkArr){ | |
int cost = 0; | |
for (int i = 0; i < 9; i++){ | |
cost += Math.Abs(inputArr[i] - checkArr[i]); | |
} | |
return cost; | |
} | |
int[] GetSolutionArray(int solutionArray){ | |
int[] sol0 = {2,9,4, | |
7,5,3, | |
6,1,8}; | |
int[] sol1 = {2,7,6, | |
9,5,1, | |
4,3,8}; | |
int[] sol2 = {4,9,2, | |
3,5,7, | |
8,1,6}; | |
int[] sol3 = {8,3,4, | |
1,5,9, | |
6,7,2}; | |
int[] sol4 = {6,1,8, | |
7,5,3, | |
2,9,4}; | |
int[] sol5 = {6,7,2, | |
1,5,9, | |
8,3,4}; | |
int[] sol6 = {4,3,8, | |
9,5,1, | |
2,7,6}; | |
int[] sol7 = {8,1,6, | |
3,5,7, | |
4,9,2}; | |
switch (solutionArray){ | |
case 0: | |
return sol0; | |
case 1: | |
return sol1; | |
case 2: | |
return sol2; | |
case 3: | |
return sol3; | |
case 4: | |
return sol4; | |
case 5: | |
return sol5; | |
case 6: | |
return sol6; | |
case 7: | |
return sol7; | |
default: | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment