Skip to content

Commit

Permalink
Primera subida
Browse files Browse the repository at this point in the history
  • Loading branch information
vikman90 committed Jan 29, 2015
1 parent 95dd9df commit ab93b44
Show file tree
Hide file tree
Showing 18 changed files with 1,315 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,6 @@ $RECYCLE.BIN/
Network Trash Folder
Temporary Items
.apdisk
C#/bin
C++/Release
C++/x64
6 changes: 6 additions & 0 deletions C#/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
199 changes: 199 additions & 0 deletions C#/Chess.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
/*******************************************************************************
* N queens problem (C# version)
* Class Chess
*
* Copyleft 2013 Vikman - All rights revoked.
* vikman90.blogspot.com - [email protected]
* February 8, 2013
*
******************************************************************************/

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Queens
{
class Chess
{
//----------------------------------------------------------------------
// Constructor

public Chess(int size)
{
IEnumerable<int> completeSet = Enumerable.Range(0, size);

this.size = size;
this.nSteps = 0;
this.board = new HashSet<int>[size];

for (int i = 0; i < size; i++)
this.board[i] = new HashSet<int>(completeSet);

this.discardedPairs = new Stack<int[]>();
this.discardedCount = new Stack<int>();
}

//----------------------------------------------------------------------
// Solve queens problem

public bool Solve()
{
int index = SelectIndex();
HashSet<int> currentSet;

if (index == -1)
return true;

currentSet = board[index];
board[index] = new HashSet<int>(currentSet);

foreach (int value in currentSet)
{
if (!Assign(index, value))
{
board[index] = new HashSet<int>(currentSet);
continue;
}

if (Solve())
return true;

RestoreLast();
board[index] = new HashSet<int>(currentSet);
}

return false;
}

//----------------------------------------------------------------------
// Representation of the chessboard

public override string ToString()
{
StringBuilder builder = new StringBuilder();

for (int i = 0; i < size; i++)
builder.Append("Fila " + (i + 1) + " - columna " + (board[i].Single() + 1) + "\n");

return builder.ToString();
}

//----------------------------------------------------------------------
// Get number of total tries of assignation

public long Steps
{
get
{
return nSteps;
}
}

//----------------------------------------------------------------------
// Assign a value to a row and propagate constraints

private bool Assign(int index, int value)
{
board[index].Clear();
discardedCount.Push(0);
nSteps++;

for (int i = 0; i < size; i++)
{
if (i == index)
continue;

int diag1 = value + (index - i);
int diag2 = value - (index - i);

if (!(Discard(i, value) && Discard(i, diag1) && Discard(i, diag2)))
{
RestoreLast();
return false;
}
}

board[index].Add(value);
return true;
}

//----------------------------------------------------------------------
// Discard candidate values (constraints propagation)

private bool Discard(int index, int value)
{
if (!board[index].Remove(value))
return true;

discardedPairs.Push(new int[] {index, value});
discardedCount.Push(discardedCount.Pop() + 1);

if (board[index].Count == 0)
return false;

if (board[index].Count == 1)
{
value = board[index].Single();

for (int i = 0; i < size; i++)
{
if (i == index)
continue;

int diag1 = value + (index - i);
int diag2 = value - (index - i);

if (!(Discard(i, value) && Discard(i, diag1) && Discard(i, diag2)))
return false;
}
}

return true;
}

//----------------------------------------------------------------------
// Undo last assignation (restore constraints)

private void RestoreLast()
{
int n = discardedCount.Pop();

for (int i = 0; i < n; i++)
{
int[] pair = discardedPairs.Pop();
board[pair[0]].Add(pair[1]);
}
}

//----------------------------------------------------------------------
// Get index of a unsolved row (minimum remaining values heuristics)

private int SelectIndex()
{
int curCount, minCount = size + 1;
int index = -1;

for (int i = 0; i < size; i++)
{
curCount = board[i].Count;

if (curCount > 1 && curCount < minCount)
{
index = i;
minCount = curCount;
}
}

return index;
}

//----------------------------------------------------------------------

readonly int size; // Number of queens
private long nSteps; // Number of calls to Assign()
private HashSet<int>[] board; // Queens' positions (set of candidate positions)
private Stack<int[]> discardedPairs; // Discarded candidates (index-value)
private Stack<int> discardedCount; // Number of discards in the last assignation
}
}
54 changes: 54 additions & 0 deletions C#/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*******************************************************************************
* N queens problem (C# version)
* Main file
*
* Copyleft 2013 Vikman - All rights revoked.
* vikman90.blogspot.com - [email protected]
* February 8, 2013
*
* Syntax: queens [-test] [N]
*
******************************************************************************/

using System;

namespace Queens
{
class Program
{
static void Main(string[] args)
{
Chess chess;
int n = 0;
long time;
bool testing = false;

foreach (string arg in args) {
if (arg == "-test")
testing = true;
else
n = int.Parse(args[0]);
}

while (n < 4)
{
Console.Write("Introduzca cantidad de reinas: ");
n = int.Parse(Console.ReadLine());
}

chess = new Chess(n);
time = DateTime.Now.Ticks;
chess.Solve();
time = DateTime.Now.Ticks - time;

if (testing)
Console.WriteLine(chess.Steps + "\t" + time / 10000);
else
{
Console.WriteLine(chess.ToString());
Console.Write("Resuelto en " + chess.Steps + " pasos. ");
Console.WriteLine("Tiempo: " + time / 10000 + " ms.");
}
}
}
}
36 changes: 36 additions & 0 deletions C#/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("Queens problem")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Queens")]
[assembly: AssemblyCopyright("Copyleft 2013 Vikman - All rights revoked.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]

// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("e85f9194-14a6-4cee-ad11-c18faee96038")]

// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
63 changes: 63 additions & 0 deletions C#/Reinas.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?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>{0D063331-0349-48CD-B250-E485C84E9D8F}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Reinas</RootNamespace>
<AssemblyName>queens</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</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>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<StartupObject>Queens.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<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="Chess.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>
20 changes: 20 additions & 0 deletions C#/Reinas.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Express 2012 for Windows Desktop
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Reinas", "Reinas.csproj", "{0D063331-0349-48CD-B250-E485C84E9D8F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0D063331-0349-48CD-B250-E485C84E9D8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0D063331-0349-48CD-B250-E485C84E9D8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0D063331-0349-48CD-B250-E485C84E9D8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0D063331-0349-48CD-B250-E485C84E9D8F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
Binary file added C++/Queens.sdf
Binary file not shown.
Loading

0 comments on commit ab93b44

Please sign in to comment.