initial commit
This commit is contained in:
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
def solveIt(n):
|
||||
# Modify this code to run your puzzle solving algorithm
|
||||
|
||||
# define the domains of all the variables (0..n-1)
|
||||
domains = [range(0,n)]*n
|
||||
|
||||
# start a trivial depth first search for a solution
|
||||
sol = tryall([],domains)
|
||||
|
||||
# prepare the solution in the specified output format
|
||||
# if no solution is found, put 0s
|
||||
outputData = str(n) + '\n'
|
||||
if sol == None:
|
||||
print 'no solution found.'
|
||||
outputData += ' '.join(map(str, [0]*n))+'\n'
|
||||
else:
|
||||
outputData += ' '.join(map(str, sol))+'\n'
|
||||
|
||||
return outputData
|
||||
|
||||
|
||||
# this is a depth first search of all assignments
|
||||
def tryall(assignment, domains):
|
||||
# base-case: if the domains list is empty, all values are assigned
|
||||
# check if it is a solution, return None if it is not
|
||||
if len(domains) == 0:
|
||||
if checkIt(assignment):
|
||||
return assignment
|
||||
else:
|
||||
return None
|
||||
|
||||
# recursive-case: try each value in the next domain
|
||||
# if we find a solution return it. otherwise, try the next value
|
||||
else:
|
||||
for v in domains[0]:
|
||||
sol = tryall(assignment[:]+[v],domains[1:])
|
||||
if sol != None:
|
||||
return sol
|
||||
|
||||
|
||||
# checks if an assignment is feasible
|
||||
def checkIt(sol):
|
||||
n = len(sol)
|
||||
|
||||
items = set(sol)
|
||||
if len(items) != n:
|
||||
return False
|
||||
|
||||
deltas = set([abs(sol[i]-sol[i+1]) for i in range(0,n-1)])
|
||||
if len(deltas) != n-1:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
n = int(sys.argv[1].strip())
|
||||
except:
|
||||
print sys.argv[1].strip(), 'is not an integer'
|
||||
print 'Solving Size:', n
|
||||
print(solveIt(n))
|
||||
|
||||
else:
|
||||
print('This test requires an instance size. Please select the size of problem to solve. (i.e. python allIntervalSeriesSolver.py 5)')
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@@ -0,0 +1,67 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("magicSeries")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("magicSeries")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("c0f99f41-0030-4b13-af15-e4ba1d3eec88")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace magicSeries
|
||||
{
|
||||
[TestFixture]
|
||||
public class SeriesTests
|
||||
{
|
||||
[Test]
|
||||
public void UpdateValueTest()
|
||||
{
|
||||
var series = new Series(5);
|
||||
series.UpdateValue(0,2);
|
||||
series.UpdateValue(1,1);
|
||||
series.UpdateValue(2,2);
|
||||
|
||||
Assert.That(series.IsFeasible(), Is.True);
|
||||
|
||||
Console.WriteLine("Values: " + string.Join(" ", series.Values.Select(i => i.ToString())));
|
||||
Console.WriteLine("Occurr: " + string.Join(" ", series.Occurrances.Select(i => i.ToString())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Linq;
|
||||
|
||||
namespace magicSeries
|
||||
{
|
||||
public class Series
|
||||
{
|
||||
public readonly int[] Values;
|
||||
|
||||
public readonly int[] Occurrances;
|
||||
|
||||
public int Size { get { return Values.Length; } }
|
||||
|
||||
public Series(int size)
|
||||
{
|
||||
Values = new int[size];
|
||||
Occurrances = new int[size + 1];
|
||||
Occurrances[0] = size;
|
||||
}
|
||||
|
||||
public int GetOccurrances(int i)
|
||||
{
|
||||
return Occurrances[i];
|
||||
}
|
||||
|
||||
public bool IsFeasible()
|
||||
{
|
||||
for (var n = 0; n < Values.Count(); n++)
|
||||
if (Values[n] != Occurrances[n])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void UpdateValue(int n, int newValue)
|
||||
{
|
||||
Occurrances[Values[n]]--;
|
||||
Occurrances[newValue]++;
|
||||
Values[n] = newValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{B8C7F1E4-92F4-41AC-83F2-2BFCC13A6820}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>magicSeries</RootNamespace>
|
||||
<AssemblyName>magicSeries</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>..\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="nunit.framework">
|
||||
<HintPath>packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Series.cs" />
|
||||
<Compile Include="Series.Tests.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2012
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "magicSeries", "magicSeries.csproj", "{B8C7F1E4-92F4-41AC-83F2-2BFCC13A6820}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{B8C7F1E4-92F4-41AC-83F2-2BFCC13A6820}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B8C7F1E4-92F4-41AC-83F2-2BFCC13A6820}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B8C7F1E4-92F4-41AC-83F2-2BFCC13A6820}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B8C7F1E4-92F4-41AC-83F2-2BFCC13A6820}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="NUnit" version="2.6.2" targetFramework="net45" />
|
||||
</packages>
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
from subprocess import Popen, PIPE
|
||||
|
||||
def solveIt(inputData):
|
||||
process = Popen(['magicSeries.exe', str(inputData)], stdout=PIPE)
|
||||
(stdout, stderr) = process.communicate()
|
||||
|
||||
return stdout.strip()
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
n = int(sys.argv[1].strip())
|
||||
except:
|
||||
print sys.argv[1].strip(), 'is not an integer'
|
||||
print 'Solving Size:', n
|
||||
print(solveIt(n))
|
||||
|
||||
else:
|
||||
print('This test requires an instance size. Please select the size of problem to solve. (i.e. python magicSeriesSolver.py 5)')
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@@ -0,0 +1,162 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Google.OrTools.ConstraintSolver;
|
||||
|
||||
namespace magicSquare
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var n = int.Parse(args[0]);
|
||||
|
||||
var solution = PatternSolve(n);
|
||||
|
||||
PrintSolution(n, solution);
|
||||
}
|
||||
|
||||
private static void PrintSolution(int n, int[,] solution)
|
||||
{
|
||||
Console.WriteLine(n);
|
||||
var rowValues =
|
||||
from row in Enumerable.Range(0, n)
|
||||
let rowVals =
|
||||
(from col in Enumerable.Range(0, n)
|
||||
select solution[n - 1 - row, col])
|
||||
select rowVals;
|
||||
foreach (var rowValue in rowValues)
|
||||
{
|
||||
Console.WriteLine(string.Join("\t", rowValue.ToArray()));
|
||||
}
|
||||
}
|
||||
|
||||
public static int[,] LSSolve(SquareMatrix squareMatrix)
|
||||
{
|
||||
// lock down diagonals
|
||||
|
||||
while (!squareMatrix.IsFeasible())
|
||||
{
|
||||
// select item
|
||||
var maxColumnDeltaPairs = squareMatrix.MaxColumnDeltaPairs().ToList();
|
||||
var maxRowDeltaPairs = squareMatrix.MaxRowDeltaPairs().ToList();
|
||||
|
||||
var swaps =
|
||||
// build neighborhood
|
||||
from cols in maxColumnDeltaPairs
|
||||
from rows in maxRowDeltaPairs
|
||||
let coord1 = new Tuple<int, int>(cols.Item1, rows.Item1)
|
||||
let coord2 = new Tuple<int, int>(cols.Item2, rows.Item2)
|
||||
// ignore items on the diagonal
|
||||
where !squareMatrix.IsDiagonal(coord1) && !squareMatrix.IsDiagonal(coord2)
|
||||
select new {coord1, coord2};
|
||||
// order descending by sum of delta difference
|
||||
swaps = swaps.OrderByDescending(arg => squareMatrix.AbsDeltaDiff(arg.coord1, arg.coord2));
|
||||
|
||||
// swap
|
||||
var swap = swaps.First();
|
||||
squareMatrix.Swap(swap.coord1, swap.coord2);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int[,] PatternSolve(int n)
|
||||
{
|
||||
var solution = new int[n, n];
|
||||
|
||||
var nover2Floor = Convert.ToInt32(Math.Floor(n / 2.0));
|
||||
for (var row = 1; row <= n; row++)
|
||||
{
|
||||
for (var col = 1; col <= n; col++)
|
||||
{
|
||||
var v = n * ((row + col - 1 + nover2Floor) % n) + ((row + 2 * col - 2) % n) + 1;
|
||||
solution[row - 1, col - 1] = v;
|
||||
}
|
||||
}
|
||||
return solution;
|
||||
}
|
||||
|
||||
public static int[,] CPSolve(int n)
|
||||
{
|
||||
|
||||
var n2 = n * n;
|
||||
var magicNumber = (n * (n * n + 1)) / 2;
|
||||
|
||||
var solver = new Solver("magicSquares");
|
||||
|
||||
var vars = solver.MakeIntVarMatrix(n, n, 1, n2, "hi");
|
||||
|
||||
var varsFlattened = vars.Flatten();
|
||||
|
||||
var cols =
|
||||
from i in Enumerable.Range(0, n)
|
||||
let col =
|
||||
(from j in Enumerable.Range(0, n)
|
||||
select vars[i, j]).ToArray()
|
||||
select col;
|
||||
|
||||
var rows =
|
||||
from j in Enumerable.Range(0, n)
|
||||
let row =
|
||||
(from i in Enumerable.Range(0, n)
|
||||
select vars[i, j]).ToArray()
|
||||
select row;
|
||||
|
||||
var diag1 =
|
||||
(from i in Enumerable.Range(0, n)
|
||||
select vars[i, i]).ToArray();
|
||||
|
||||
var diag2 =
|
||||
(from i in Enumerable.Range(0, n)
|
||||
select vars[i, n - 1 - i]).ToArray();
|
||||
|
||||
foreach (var pieces in
|
||||
cols
|
||||
.Union(rows)
|
||||
.Union(new[] { diag1, diag2 }))
|
||||
{
|
||||
solver.Add(pieces.Sum() == magicNumber);
|
||||
}
|
||||
|
||||
solver.Add(varsFlattened.AllDifferent());
|
||||
|
||||
// TODO: symetry break
|
||||
for (var i = 1; i < n; i++)
|
||||
solver.Add(diag1[i - 1] == diag1[i] - 1);
|
||||
|
||||
// middle number
|
||||
solver.Add(vars[(n - 1) / 2, (n - 1) / 2] == (n * n + 1) / 2);
|
||||
solver.Add(vars[(n - 1) / 2, 0] == 1);
|
||||
solver.Add(vars[(n - 1) / 2, n - 1] == n * n);
|
||||
|
||||
//var nover2floor = Convert.ToInt32(Math.Floor(n / 2.0));
|
||||
//for (var i = 1; i <= n; i++)
|
||||
//{
|
||||
// for (var j = 1; j <= n; j++)
|
||||
// {
|
||||
// var v = n * ((i + j - 1 + nover2floor) % n) + ((i + 2 * j - 2) % n) + 1;
|
||||
// solver.Add(vars[i - 1, j - 1] == v);
|
||||
// }
|
||||
//}
|
||||
|
||||
var db = solver.MakePhase(varsFlattened, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_CENTER_VALUE);
|
||||
|
||||
solver.NewSearch(db);
|
||||
|
||||
var solution = new int[n,n];
|
||||
|
||||
if (solver.NextSolution())
|
||||
{
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
for (var j = 0; j < n; j++)
|
||||
{
|
||||
solution[i, j] = Convert.ToInt32(vars[i, j].Value());
|
||||
}
|
||||
}
|
||||
}
|
||||
solver.EndSearch();
|
||||
|
||||
return solution;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("magicSquare")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("magicSquare")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("72d8c1ae-c92a-4d41-9ca2-ac426853eb3f")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@@ -0,0 +1,205 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace magicSquare
|
||||
{
|
||||
internal class SquareMatrix
|
||||
{
|
||||
public int Size { get; private set; }
|
||||
private int SizeSize { get; set; }
|
||||
public int MagicSum { get; private set; }
|
||||
|
||||
private int[,] Values { get; set; }
|
||||
|
||||
private int[] ColumnSums { get; set; }
|
||||
private int[] RowSums { get; set; }
|
||||
public int Diag1Sum { get; private set; }
|
||||
public int Diag2Sum { get; private set; }
|
||||
|
||||
private int[] ColumnDeltas { get; set; }
|
||||
private int[] RowDeltas { get; set; }
|
||||
public int Diag1Delta { get; private set; }
|
||||
public int Diag2Delta { get; private set; }
|
||||
|
||||
public SquareMatrix(int[,] values)
|
||||
{
|
||||
if (values.GetLength(0) != values.GetLength(1))
|
||||
throw new ArgumentException("must be square matrix");
|
||||
|
||||
Values = values;
|
||||
Size = values.GetLength(0);
|
||||
SizeSize = Size * Size;
|
||||
MagicSum = (Size * (SizeSize + 1)) / 2;
|
||||
|
||||
ColumnSums = (from col in Enumerable.Range(0, Size)
|
||||
let sum = (from row in Enumerable.Range(0, Size)
|
||||
select Values[row, col]).Sum()
|
||||
select sum).ToArray();
|
||||
RowSums = (from row in Enumerable.Range(0, Size)
|
||||
let sum = (from col in Enumerable.Range(0, Size)
|
||||
select Values[row, col]).Sum()
|
||||
select sum).ToArray();
|
||||
Diag1Sum = (from i in Enumerable.Range(0, Size)
|
||||
select Values[i, i]).Sum();
|
||||
Diag2Sum = (from i in Enumerable.Range(0, Size)
|
||||
select Values[Size - 1 - i, i]).Sum();
|
||||
|
||||
ColumnDeltas = (from col in Enumerable.Range(0, Size)
|
||||
select ColumnSums[col] - MagicSum).ToArray();
|
||||
RowDeltas = (from row in Enumerable.Range(0, Size)
|
||||
select RowSums[row] - MagicSum).ToArray();
|
||||
Diag1Delta = Diag1Sum - MagicSum;
|
||||
Diag2Delta = Diag2Sum - MagicSum;
|
||||
}
|
||||
|
||||
public IEnumerable<Tuple<int, int>> MaxColumnDeltaPairs()
|
||||
{
|
||||
return MaxDeltaPairs(ColumnDeltas, Size);
|
||||
}
|
||||
|
||||
public IEnumerable<Tuple<int, int>> MaxRowDeltaPairs()
|
||||
{
|
||||
return MaxDeltaPairs(RowDeltas, Size);
|
||||
}
|
||||
|
||||
public Tuple<int, int> FindValueCoord(int values)
|
||||
{
|
||||
return (
|
||||
from row in Enumerable.Range(0, Size)
|
||||
from col in Enumerable.Range(0, Size)
|
||||
where Values[row, col] == values
|
||||
let coord = new Tuple<int, int>(row, col)
|
||||
select coord).First();
|
||||
}
|
||||
|
||||
public void SolveDiags()
|
||||
{
|
||||
var middleNumber = (SizeSize + 1)/2;
|
||||
var diag1Values = Enumerable.Range(middleNumber - (Size - 1)/2, Size);
|
||||
|
||||
}
|
||||
|
||||
private static IEnumerable<Tuple<int, int>> MaxDeltaPairs(int[] deltas, int size)
|
||||
{
|
||||
const int limit = 4;
|
||||
var deltaIs = (from i in Enumerable.Range(0, size)
|
||||
select new Tuple<int, int>(i, deltas[i])).ToList();
|
||||
|
||||
var lows = deltaIs.OrderBy(tuple => tuple.Item2).Take(limit);
|
||||
var highs = deltaIs.OrderByDescending(tuple => tuple.Item2).Take(limit);
|
||||
|
||||
var pairs =
|
||||
from lo in lows
|
||||
from hi in highs
|
||||
where lo.Item1 != hi.Item1
|
||||
let pair = new Tuple<Tuple<int, int>, Tuple<int, int>>(lo, hi)
|
||||
select pair;
|
||||
return
|
||||
pairs
|
||||
.OrderBy(pair => Math.Abs(pair.Item1.Item2 + pair.Item2.Item2))
|
||||
.Select(pair => new Tuple<int,int>(pair.Item1.Item1, pair.Item2.Item1));
|
||||
}
|
||||
|
||||
public static bool IsDiagonal(int i, int j, int size)
|
||||
{
|
||||
return i == j || size - 1 - j == i;
|
||||
}
|
||||
|
||||
public bool IsDiagonal(int i, int j)
|
||||
{
|
||||
return i == j || Size - 1 - j == i;
|
||||
}
|
||||
|
||||
public bool IsDiagonal(Tuple<int,int> tpl)
|
||||
{
|
||||
return IsDiagonal(tpl.Item1, tpl.Item2);
|
||||
}
|
||||
|
||||
public bool IsFeasible()
|
||||
{
|
||||
return Diag1Sum == MagicSum &&
|
||||
Diag2Sum == MagicSum &&
|
||||
ColumnSums.All(s => s == MagicSum) &&
|
||||
RowSums.All(s => s == MagicSum);
|
||||
}
|
||||
|
||||
public int GetValue(int row, int col)
|
||||
{
|
||||
return Values[row,col];
|
||||
}
|
||||
|
||||
public int ColumnSum(int col)
|
||||
{
|
||||
return ColumnSums[col];
|
||||
}
|
||||
|
||||
public int RowSum(int row)
|
||||
{
|
||||
return RowSums[row];
|
||||
}
|
||||
|
||||
public int ColumnDelta(int col)
|
||||
{
|
||||
return ColumnDeltas[col];
|
||||
}
|
||||
|
||||
public int RowDelta(int row)
|
||||
{
|
||||
return RowDeltas[row];
|
||||
}
|
||||
|
||||
private void UpdateValue(int row, int col, int value)
|
||||
{
|
||||
// update sums
|
||||
var delta = value - Values[row, col];
|
||||
Values[row, col] = value;
|
||||
if (row == col)
|
||||
{
|
||||
Diag1Sum += delta;
|
||||
Diag1Delta += delta;
|
||||
}
|
||||
if (col == Size - 1 - row)
|
||||
{
|
||||
Diag2Sum += delta;
|
||||
Diag2Delta += delta;;
|
||||
}
|
||||
ColumnSums[col] += delta;
|
||||
ColumnDeltas[col] += delta;
|
||||
RowSums[row] += delta;
|
||||
RowDeltas[row] += delta;
|
||||
}
|
||||
|
||||
private int AbsDelta(int row, int col)
|
||||
{
|
||||
return Math.Abs(RowDeltas[row]) + Math.Abs(ColumnDeltas[col]);
|
||||
}
|
||||
|
||||
public int AbsDeltaDiff(int row1, int col1, int row2, int col2)
|
||||
{
|
||||
var v1 = Values[row1, col1];
|
||||
var v2 = Values[row2, col2];
|
||||
|
||||
return Math.Abs(v1 - v2);
|
||||
}
|
||||
|
||||
public int AbsDeltaDiff(Tuple<int, int> coord1, Tuple<int, int> coord2)
|
||||
{
|
||||
return AbsDeltaDiff(coord1.Item1, coord1.Item2, coord2.Item1, coord2.Item2);
|
||||
}
|
||||
|
||||
public void Swap(Tuple<int, int> coord1, Tuple<int, int> coord2)
|
||||
{
|
||||
Swap(coord1.Item1, coord1.Item2, coord2.Item1, coord2.Item2);
|
||||
}
|
||||
|
||||
public void Swap(int row1, int col1, int row2, int col2)
|
||||
{
|
||||
var v1 = Values[row1, col1];
|
||||
var v2 = Values[row2, col2];
|
||||
|
||||
UpdateValue(row1,col1,v2);
|
||||
UpdateValue(row2,col2,v1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace magicSquare.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class SquareMatrixTests
|
||||
{
|
||||
[Test]
|
||||
public void Init()
|
||||
{
|
||||
var vals
|
||||
= new [,]
|
||||
{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
|
||||
var matrix = new SquareMatrix(vals);
|
||||
Assert.That(matrix.IsFeasible(), Is.False);
|
||||
|
||||
Assert.That(matrix.ColumnSum(0), Is.EqualTo(12));
|
||||
Assert.That(matrix.ColumnSum(1), Is.EqualTo(15));
|
||||
Assert.That(matrix.ColumnSum(2), Is.EqualTo(18));
|
||||
Assert.That(matrix.RowSum(0), Is.EqualTo(6));
|
||||
Assert.That(matrix.RowSum(1), Is.EqualTo(15));
|
||||
Assert.That(matrix.RowSum(2), Is.EqualTo(24));
|
||||
Assert.That(matrix.Diag1Sum, Is.EqualTo(15));
|
||||
Assert.That(matrix.Diag2Sum, Is.EqualTo(15));
|
||||
Assert.That(matrix.ColumnDelta(0), Is.EqualTo(-3));
|
||||
Assert.That(matrix.ColumnDelta(1), Is.EqualTo(0));
|
||||
Assert.That(matrix.ColumnDelta(2), Is.EqualTo(3));
|
||||
Assert.That(matrix.RowDelta(0), Is.EqualTo(-9));
|
||||
Assert.That(matrix.RowDelta(1), Is.EqualTo(0));
|
||||
Assert.That(matrix.RowDelta(2), Is.EqualTo(9));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Swap()
|
||||
{
|
||||
var vals
|
||||
= new [,]
|
||||
{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
|
||||
var matrix = new SquareMatrix(vals);
|
||||
matrix.Swap(1,1,2,1);
|
||||
PrintMatrix(matrix);
|
||||
Assert.That(matrix.IsFeasible(), Is.False);
|
||||
|
||||
Assert.That(matrix.ColumnSum(0), Is.EqualTo(12));
|
||||
Assert.That(matrix.ColumnSum(1), Is.EqualTo(15));
|
||||
Assert.That(matrix.ColumnSum(2), Is.EqualTo(18));
|
||||
Assert.That(matrix.RowSum(0), Is.EqualTo(6));
|
||||
Assert.That(matrix.RowSum(1), Is.EqualTo(18));
|
||||
Assert.That(matrix.RowSum(2), Is.EqualTo(21));
|
||||
Assert.That(matrix.Diag1Sum, Is.EqualTo(18));
|
||||
Assert.That(matrix.Diag2Sum, Is.EqualTo(18));
|
||||
Assert.That(matrix.ColumnDelta(0), Is.EqualTo(-3));
|
||||
Assert.That(matrix.ColumnDelta(1), Is.EqualTo(0));
|
||||
Assert.That(matrix.ColumnDelta(2), Is.EqualTo(3));
|
||||
Assert.That(matrix.RowDelta(0), Is.EqualTo(-9));
|
||||
Assert.That(matrix.RowDelta(1), Is.EqualTo(3));
|
||||
Assert.That(matrix.RowDelta(2), Is.EqualTo(6));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Swap2()
|
||||
{
|
||||
var vals
|
||||
= new [,]
|
||||
{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
|
||||
var matrix = new SquareMatrix(vals);
|
||||
matrix.Swap(0,1,1,2);
|
||||
PrintMatrix(matrix);
|
||||
Assert.That(matrix.IsFeasible(), Is.False);
|
||||
|
||||
Assert.That(matrix.ColumnSum(0), Is.EqualTo(12));
|
||||
Assert.That(matrix.ColumnSum(1), Is.EqualTo(19));
|
||||
Assert.That(matrix.ColumnSum(2), Is.EqualTo(14));
|
||||
Assert.That(matrix.RowSum(0), Is.EqualTo(10));
|
||||
Assert.That(matrix.RowSum(1), Is.EqualTo(11));
|
||||
Assert.That(matrix.RowSum(2), Is.EqualTo(24));
|
||||
Assert.That(matrix.Diag1Sum, Is.EqualTo(15));
|
||||
Assert.That(matrix.Diag2Sum, Is.EqualTo(15));
|
||||
Assert.That(matrix.ColumnDelta(0), Is.EqualTo(-3));
|
||||
Assert.That(matrix.ColumnDelta(1), Is.EqualTo(4));
|
||||
Assert.That(matrix.ColumnDelta(2), Is.EqualTo(-1));
|
||||
Assert.That(matrix.RowDelta(0), Is.EqualTo(-5));
|
||||
Assert.That(matrix.RowDelta(1), Is.EqualTo(-4));
|
||||
Assert.That(matrix.RowDelta(2), Is.EqualTo(9));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Swap3()
|
||||
{
|
||||
var vals
|
||||
= new [,]
|
||||
{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
|
||||
var matrix = new SquareMatrix(vals);
|
||||
matrix.Swap(2,0,1,2);
|
||||
PrintMatrix(matrix);
|
||||
Assert.That(matrix.IsFeasible(), Is.False);
|
||||
|
||||
Assert.That(matrix.ColumnSum(0), Is.EqualTo(11));
|
||||
Assert.That(matrix.ColumnSum(1), Is.EqualTo(15));
|
||||
Assert.That(matrix.ColumnSum(2), Is.EqualTo(19));
|
||||
Assert.That(matrix.RowSum(0), Is.EqualTo(6));
|
||||
Assert.That(matrix.RowSum(1), Is.EqualTo(16));
|
||||
Assert.That(matrix.RowSum(2), Is.EqualTo(23));
|
||||
Assert.That(matrix.Diag1Sum, Is.EqualTo(15));
|
||||
Assert.That(matrix.Diag2Sum, Is.EqualTo(14));
|
||||
Assert.That(matrix.ColumnDelta(0), Is.EqualTo(-4));
|
||||
Assert.That(matrix.ColumnDelta(1), Is.EqualTo(0));
|
||||
Assert.That(matrix.ColumnDelta(2), Is.EqualTo(4));
|
||||
Assert.That(matrix.RowDelta(0), Is.EqualTo(-9));
|
||||
Assert.That(matrix.RowDelta(1), Is.EqualTo(1));
|
||||
Assert.That(matrix.RowDelta(2), Is.EqualTo(8));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Deltas()
|
||||
{
|
||||
var vals
|
||||
= new[,]
|
||||
{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
|
||||
var matrix = new SquareMatrix(vals);
|
||||
var pairs = matrix.MaxColumnDeltaPairs().ToArray();
|
||||
Assert.That(pairs.First(), Is.EqualTo(new Tuple<int,int>(0,2)));
|
||||
}
|
||||
[Test]
|
||||
public void Deltas2()
|
||||
{
|
||||
var vals
|
||||
= new[,]
|
||||
{
|
||||
{1, 2, 3, 4},
|
||||
{4, 5, 6, 7},
|
||||
{8, 9, 10, 11},
|
||||
{12,13,14,15}
|
||||
};
|
||||
|
||||
var matrix = new SquareMatrix(vals);
|
||||
var pairs = matrix.MaxColumnDeltaPairs().ToArray();
|
||||
Assert.That(pairs.First(), Is.EqualTo(new Tuple<int,int>(1,3)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IsDiagonalTest()
|
||||
{
|
||||
var vals
|
||||
= new[,]
|
||||
{
|
||||
{1, 2, 3, 4},
|
||||
{4, 5, 6, 7},
|
||||
{8, 9, 10, 11},
|
||||
{12,13,14,15}
|
||||
};
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void PrintMatrix(SquareMatrix sm)
|
||||
{
|
||||
Console.WriteLine(sm.Size);
|
||||
var rowValues =
|
||||
from row in Enumerable.Range(0, sm.Size)
|
||||
let rowVals =
|
||||
(from col in Enumerable.Range(0, sm.Size)
|
||||
select sm.GetValue(row,col))
|
||||
select rowVals;
|
||||
foreach (var rowValue in rowValues)
|
||||
{
|
||||
Console.WriteLine(string.Join("\t", rowValue.ToArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{382D1A78-447D-4E0E-A250-EE9FF4316ACD}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>magicSquare</RootNamespace>
|
||||
<AssemblyName>magicSquare</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>..\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Google.OrTools.ConstraintSolver">
|
||||
<HintPath>..\..\..\..\Documents\or-tools.Windows64\bin\Google.OrTools.ConstraintSolver.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Google.OrTools.LinearSolver, Version=0.0.0.0, Culture=neutral, processorArchitecture=AMD64">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\..\..\Documents\or-tools.Windows64\bin\Google.OrTools.LinearSolver.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="nunit.framework, Version=2.6.2.12296, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="SquareMatrix.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Tests\SquareMatrixTests.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2012
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "magicSquare", "magicSquare.csproj", "{382D1A78-447D-4E0E-A250-EE9FF4316ACD}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{382D1A78-447D-4E0E-A250-EE9FF4316ACD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{382D1A78-447D-4E0E-A250-EE9FF4316ACD}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{382D1A78-447D-4E0E-A250-EE9FF4316ACD}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{382D1A78-447D-4E0E-A250-EE9FF4316ACD}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="NUnit" version="2.6.2" targetFramework="net45" />
|
||||
</packages>
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
from subprocess import Popen, PIPE
|
||||
|
||||
def solveIt(inputData):
|
||||
process = Popen(['magicSquare.exe', str(inputData)], stdout=PIPE)
|
||||
(stdout, stderr) = process.communicate()
|
||||
|
||||
return stdout.strip()
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
n = int(sys.argv[1].strip())
|
||||
except:
|
||||
print sys.argv[1].strip(), 'is not an integer'
|
||||
print 'Solving Size:', n
|
||||
print(solveIt(n))
|
||||
|
||||
else:
|
||||
print('This test requires an instance size. Please select the size of problem to solve. (i.e. python magicSquareSolver.py 3)')
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,74 @@
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace nqueens.tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class NBoardTests
|
||||
{
|
||||
[Test]
|
||||
public void GetConflicts_SameRow()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {0,0,0,0});
|
||||
Assert.That(nBoard.GetConflictCount(0), Is.EqualTo(3));
|
||||
Assert.That(nBoard.GetConflictCount(3), Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetConflicts_SameRow_AfterUpdates()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {0,0,0,0});
|
||||
nBoard.UpdateRow(0,2);
|
||||
Assert.That(nBoard.GetConflictCount(1), Is.EqualTo(2));
|
||||
nBoard.UpdateRow(2,1);
|
||||
Assert.That(nBoard.GetConflictCount(0), Is.EqualTo(0));
|
||||
nBoard.UpdateRow(0,0);
|
||||
nBoard.UpdateRow(1,1);
|
||||
nBoard.UpdateRow(2,2);
|
||||
nBoard.UpdateRow(3,3);
|
||||
Assert.That(nBoard.GetConflictCount(0), Is.EqualTo(3));
|
||||
Assert.That(nBoard.GetConflictCount(1), Is.EqualTo(3));
|
||||
Assert.That(nBoard.GetConflictCount(2), Is.EqualTo(3));
|
||||
Assert.That(nBoard.GetConflictCount(3), Is.EqualTo(3));
|
||||
nBoard.UpdateRow(3,2);
|
||||
Assert.That(nBoard.GetConflictCount(0), Is.EqualTo(2));
|
||||
Assert.That(nBoard.GetConflictCount(1), Is.EqualTo(2));
|
||||
Assert.That(nBoard.GetConflictCount(2), Is.EqualTo(3));
|
||||
Assert.That(nBoard.GetConflictCount(3), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetConflicts_OneNonConflictRow()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {2,0,0,0});
|
||||
Assert.That(nBoard.GetConflictCount(1), Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetConflicts_NoConflicts()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {2,0,1,0});
|
||||
Assert.That(nBoard.GetConflictCount(0), Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetConflicts_AllDiagonalConflict()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {0,1,2,3});
|
||||
Assert.That(nBoard.GetConflictCount(2), Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetConflicts_AllOppositeDiagonalConflict()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {3,2,1,0});
|
||||
Assert.That(nBoard.GetConflictCount(3), Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetConflicts_TwoOppositeDiagonalConflict()
|
||||
{
|
||||
var nBoard = new NBoard(new [] {0,1,2,2});
|
||||
Assert.That(nBoard.GetConflictCount(0), Is.EqualTo(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("nqueens.tests")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("nqueens.tests")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("55a078f8-ec2c-41c5-a0c9-f0fa29d15abe")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{EE40FD45-A2A0-4198-86A0-F7E3ED334B51}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>nqueens.tests</RootNamespace>
|
||||
<AssemblyName>nqueens.tests</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="nunit.framework">
|
||||
<HintPath>..\nqueens\packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="NBoardTests.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\nqueens\nqueens.csproj">
|
||||
<Project>{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}</Project>
|
||||
<Name>nqueens</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="NUnit" version="2.6.2" targetFramework="net45" />
|
||||
</packages>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace nqueens
|
||||
{
|
||||
public class NBoard
|
||||
{
|
||||
public readonly int[] Columns;
|
||||
|
||||
public int Size { get { return Columns.Length; } }
|
||||
|
||||
public readonly int[] Conflicts;
|
||||
|
||||
public NBoard(int[] columns)
|
||||
{
|
||||
Columns = columns;
|
||||
Conflicts =
|
||||
(from n in Enumerable.Range(0, Size)
|
||||
select GetConflictCount(n)).ToArray();
|
||||
}
|
||||
|
||||
public int GetQueenRow(int column)
|
||||
{
|
||||
return Columns[column];
|
||||
}
|
||||
|
||||
public bool IsFeasible()
|
||||
{
|
||||
return Conflicts.All(c => c == 0);
|
||||
}
|
||||
|
||||
public int GetConflictCount(int column)
|
||||
{
|
||||
return GetConflicts(column).Count;
|
||||
}
|
||||
|
||||
public int TestConflictCount(int column, int row)
|
||||
{
|
||||
var originalRow = Columns[column];
|
||||
Columns[column] = row;
|
||||
|
||||
var conflicts = GetConflictCount(column);
|
||||
|
||||
Columns[column] = originalRow;
|
||||
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
private List<int> GetConflicts(int column)
|
||||
{
|
||||
var queenRow = GetQueenRow(column);
|
||||
var conflicts = new List<int>();
|
||||
for (var iColumn = 0; iColumn < Size; iColumn++)
|
||||
{
|
||||
if (iColumn == column)
|
||||
continue;
|
||||
var iRow = Columns[iColumn];
|
||||
if (iRow == queenRow)
|
||||
{
|
||||
conflicts.Add(iColumn);
|
||||
continue;
|
||||
}
|
||||
|
||||
var columnDiff = column - iColumn;
|
||||
if (queenRow - columnDiff == iRow || queenRow + columnDiff == iRow)
|
||||
conflicts.Add(iColumn);
|
||||
}
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
public void UpdateRow(int column, int row)
|
||||
{
|
||||
var oldConflictColumns = GetConflicts(column);
|
||||
foreach (var i in oldConflictColumns)
|
||||
Conflicts[i]--;
|
||||
|
||||
var sum = Conflicts.Any(c => c < 0);
|
||||
|
||||
Columns[column] = row;
|
||||
|
||||
var newConflictColumns = GetConflicts(column);
|
||||
Conflicts[column] = newConflictColumns.Count;
|
||||
foreach (var i in newConflictColumns)
|
||||
Conflicts[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
|
||||
namespace nqueens
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var n = Convert.ToInt32(args[0]);
|
||||
var lsQueens = new MinConflictsQueens(n);
|
||||
var solution = lsQueens.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class MinConflictsQueens
|
||||
{
|
||||
private readonly int _n;
|
||||
|
||||
public MinConflictsQueens(int n)
|
||||
{
|
||||
_n = n;
|
||||
}
|
||||
|
||||
private NBoard Initial()
|
||||
{
|
||||
//var random = new Random(1);
|
||||
//var randValues = (from i in Enumerable.Range(0, _n)
|
||||
// select random.Next(0, _n)).ToArray();
|
||||
|
||||
//var board = new List<int>(_n);
|
||||
//for (var i = 0; i < _n; i++)
|
||||
//{
|
||||
// if (i % 2 == 0)
|
||||
// board.Insert(0,i);
|
||||
// else
|
||||
// board.Insert(i,i);
|
||||
|
||||
//}
|
||||
|
||||
//return new NBoard(board.ToArray());
|
||||
|
||||
var board = new int[_n];
|
||||
var n2 = _n/2;
|
||||
for (var i = 1; i <= n2; i++)
|
||||
{
|
||||
board[i - 1] = 2*i - 1;
|
||||
board[n2 + i - 1] = 2* (i - 1);
|
||||
}
|
||||
//board[n2 - 1] = 0;
|
||||
return new NBoard(board);
|
||||
}
|
||||
|
||||
public IList<int> Solve()
|
||||
{
|
||||
var nBoard = Initial();
|
||||
var random = new Random();
|
||||
int lastColumn = -1;
|
||||
int iterations = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (nBoard.IsFeasible())
|
||||
return nBoard.Columns;
|
||||
|
||||
if (++iterations % 100 == 0)
|
||||
Debug.WriteLine("{0} : {1}", iterations, nBoard.Conflicts.Sum());
|
||||
|
||||
// select the next biggest conflict count
|
||||
var maxConflictColumn =
|
||||
(from c in Enumerable.Range(0, _n)
|
||||
let conflicts = nBoard.Conflicts[c]
|
||||
select new {c, conflicts})
|
||||
.GroupBy(arg => arg.conflicts)
|
||||
.OrderByDescending(grouping => grouping.Key)
|
||||
.First()
|
||||
.OrderBy(arg => random.Next())
|
||||
.First()
|
||||
.c;
|
||||
|
||||
if (maxConflictColumn == lastColumn)
|
||||
maxConflictColumn = random.Next(0, _n);
|
||||
lastColumn = maxConflictColumn;
|
||||
|
||||
var minConflictRow =
|
||||
(from row in Enumerable.Range(0, _n)
|
||||
let conflicts = nBoard.TestConflictCount(maxConflictColumn, row)
|
||||
select new {row, conflicts})
|
||||
.GroupBy(arg => arg.conflicts)
|
||||
.OrderBy(grouping => grouping.Key)
|
||||
.First()
|
||||
.OrderBy(arg => random.Next())
|
||||
.First()
|
||||
.row;
|
||||
|
||||
nBoard.UpdateRow(maxConflictColumn, minConflictRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("nqueens")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("nqueens")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("2653647d-52e8-48ef-af3d-40adb6a2e58e")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>nqueens</RootNamespace>
|
||||
<AssemblyName>nqueens</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>..\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Google.OrTools.ConstraintSolver">
|
||||
<HintPath>..\..\..\..\Documents\or-tools.Windows64\bin\Google.OrTools.ConstraintSolver.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="NBoard.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -0,0 +1,26 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2012
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nqueens", "nqueens.csproj", "{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "nqueens.tests", "..\nqueens.tests\nqueens.tests.csproj", "{EE40FD45-A2A0-4198-86A0-F7E3ED334B51}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0C81AFB2-E3EC-4535-86A6-955BA5BE2576}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{EE40FD45-A2A0-4198-86A0-F7E3ED334B51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{EE40FD45-A2A0-4198-86A0-F7E3ED334B51}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{EE40FD45-A2A0-4198-86A0-F7E3ED334B51}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{EE40FD45-A2A0-4198-86A0-F7E3ED334B51}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
from subprocess import Popen, PIPE
|
||||
|
||||
def solveIt(inputData):
|
||||
process = Popen(['nqueens.exe', str(inputData)], stdout=PIPE)
|
||||
(stdout, stderr) = process.communicate()
|
||||
|
||||
return stdout.strip()
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
n = int(sys.argv[1].strip())
|
||||
except:
|
||||
print sys.argv[1].strip(), 'is not an integer'
|
||||
print 'Solving Size:', n
|
||||
print(solveIt(n))
|
||||
|
||||
else:
|
||||
print('This test requires an instance size. Please select the size of problem to solve. (i.e. python queensSolver.py 8)')
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user