using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; public static class Extensions { public static int GetAbsDiff(this IEnumerable source, IEnumerable next) { return source.Zip(next, (arg1, arg2) => Math.Abs(arg1 - arg2)).Sum(); } public static IEnumerable> GetVariants(this IList source) { if (source.Count == 1) { yield return new[] { source.First() }; } for (int q = 0; q < source.Count; q++) { var localResult = new[] { source[q] }; var next = source.Take(q).Concat(source.Skip(q + 1)).ToList(); foreach (var item in next.GetVariants()) { yield return localResult.Concat(item).ToList(); } } } public static IList GetRow(this IList source, int index) { return source.Skip(3 * index).Take(3).ToList(); } public static IList GetColumn(this IList source, int index) { return new[] { source[index], source[index + 3], source[index + 6] }; } public static IList MixRowIndex(this IList source, IList newOrderRowIndexies) { return newOrderRowIndexies.SelectMany(source.GetRow).ToList(); } public static IList MixColumnIndex(this IList source, IList newOrderColumnIndexies) { var temp = source.GetColumn(0).Reverse() .Concat(source.GetColumn(1).Reverse()) .Concat(source.GetColumn(2).Reverse()) .ToList() .MixRowIndex(newOrderColumnIndexies); return temp.GetColumn(2).Concat(temp.GetColumn(1)).Concat(temp.GetColumn(0)).ToList(); } public static IList> GetALLMagicSquare(this IList template) { var variants = Enumerable.Range(0, 3).ToList().GetVariants().Select(z => z.ToList()).ToList(); var mixedRows = variants.Select(template.MixRowIndex).ToList(); var mixedColumns = variants.SelectMany(z => mixedRows.Select(q => q.MixColumnIndex(z)).ToList()).ToList(); var results = mixedRows.Concat(mixedColumns).ToList(); return results.Where(z => (z[0] + z[4] + z[8] == 15) && (z[2] + z[4] + z[6] == 15)).ToList(); } } class Solution { static void Main(String[] args) { var source = new[] { 4, 9, 2, 3, 5, 7, 8, 1, 6 }.GetALLMagicSquare(); var source1 = new[] { 1, 9, 5, 6, 2, 7, 8, 4, 3 }.GetALLMagicSquare(); var allMagicValues = source.Concat(source1).Distinct(new MComparer()).ToList(); var inputValues = new List(9); for (int q = 0; q < 3; q++) { inputValues.AddRange(Console.ReadLine().Split(' ').Select(int.Parse)); } Console.WriteLine(allMagicValues.Select(z => z.GetAbsDiff(inputValues)).Min()); } internal class MComparer : IEqualityComparer> { public bool Equals(IList x, IList y) { return x.SequenceEqual(y); } public int GetHashCode(IList obj) { return obj.Select((val, index) => val * index).Sum(); } } }