You are viewing a single comment's thread. Return to all comments →
C# solution, O(n^2) for small n
public static int formingMagicSquare(List<List<int>> s) { int[][] allMagicSquares = { new int[] {8, 3, 4, 1, 5, 9, 6, 7, 2}, new int[] {4, 3, 8, 9, 5, 1, 2, 7, 6}, new int[] {6, 7, 2, 1, 5, 9, 8, 3, 4}, new int[] {2, 7, 6, 9, 5, 1, 4, 3, 8}, new int[] {4, 9, 2, 3, 5, 7, 8, 1, 6}, new int[] {2, 9, 4, 7, 5, 3, 6, 1, 8}, new int[] {6, 1, 8, 7, 5, 3, 2, 9, 4}, new int[] {8, 1, 6, 3, 5, 7, 4, 9, 2}, }; // bruteforce it var costs = new List<int>(); foreach (var square in allMagicSquares) { var l1 = square .Take(3) .Zip(s[0], (fst, snd) => (F: fst, S: snd)); var l2 = square .Skip(3).Take(3) .Zip(s[1], (fst, snd) => (F: fst, S: snd)); var l3 = square .Skip(6).Take(3) .Zip(s[2], (fst, snd) => (F: fst, S: snd)); var cost = l1.Aggregate(0, (a, n) => a + Math.Abs(n.F - n.S)) + l2.Aggregate(0, (a, n) => a + Math.Abs(n.F - n.S)) + l3.Aggregate(0, (a, n) => a + Math.Abs(n.F - n.S)); costs.Add(cost); } return costs.Min(); }
Seems like cookies are disabled on this browser, please enable them to open this website
Forming a Magic Square
You are viewing a single comment's thread. Return to all comments →
C# solution, O(n^2) for small n