68 lines
1.4 KiB
C#
68 lines
1.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
|
|
|
|
namespace magicSeries
|
|
{
|
|
class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
var n = Convert.ToInt32(args[0]);
|
|
var series = new MinConflictsMagicSeries(n);
|
|
var solution = series.Solve();
|
|
|
|
if (solution != null)
|
|
{
|
|
var s = string.Join(" ", solution.Select(i => i.ToString()));
|
|
Console.WriteLine(n);
|
|
Console.WriteLine(s);
|
|
Debug.WriteLine(n);
|
|
Debug.WriteLine(s);
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine("No solution");
|
|
}
|
|
}
|
|
}
|
|
|
|
internal class MinConflictsMagicSeries
|
|
{
|
|
private readonly int _n;
|
|
|
|
public MinConflictsMagicSeries(int n)
|
|
{
|
|
_n = n;
|
|
}
|
|
|
|
public IList<int> Solve()
|
|
{
|
|
var series = new Series(_n);
|
|
var random = new Random();
|
|
while (true)
|
|
{
|
|
if (series.IsFeasible())
|
|
return series.Values;
|
|
// select the largest violation
|
|
var updateValue =
|
|
(from i in Enumerable.Range(0, series.Size)
|
|
let value = series.Values[i]
|
|
let occurrances = series.GetOccurrances(i)
|
|
let violationDegree = Math.Abs(value - occurrances)
|
|
select new {i, occurrances, violationDegree})
|
|
.GroupBy(arg => arg.violationDegree)
|
|
.OrderByDescending(arg => arg.Key)
|
|
.First()
|
|
.OrderBy(arg => random.Next())
|
|
.First();
|
|
|
|
// adjust it to correct value
|
|
series.UpdateValue(updateValue.i, updateValue.occurrances);
|
|
}
|
|
}
|
|
}
|
|
}
|