Genetic Algorithm & Binding

Genetic Algorithm & Binding
Ya que sabemos como implementar un algoritmo genético básico con la Interface de Waki, vamos a usar el algoritmo genético de ordenamiento del tablero de ajedrez del post Interface. Algoritmo Genético II y crearemos una interfaz gráfica con WPF y como no, aplicaremos lo que sabemos con Binding.
Lo primero que vamos a hacer es que la clase ChessBoard implemente la interfaz INotifyPropertyChanged del namespace System.ComponentModel. Una vez hecho esto, añadimos el evento public event PropertyChangedEventHandler PropertyChanged y creamos un método que realice la llamada. Ahora que ya podemos notificar cambios en las propiedades, le incluimos una llamada a este método desde la propiedad BestParent, es decir, cada vez que se encuentre una solución parcial en el algoritmo queremos que actualice la pantalla, para ello cambiamos también la propiedad Bestparent por su equivalente de propiedad completa.

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string property)
{
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
private List bestparent;

public List BestParent
{
        get { return bestparent; }
        set
        { 
            bestparent = value;
            OnPropertyChanged(nameof(BestParent));
        }
}

A la clase ChessPiece le he añadido una propiedad nueva llamada Picture para incluirle la forma de la pieza de ajedrez.
Acto seguido, preparamos nuesto código XAMl, donde yo lo que he hecho, como nuestra clase ChessBoard era una lista de objetos ChessPiece, no he cambiado a coordenadas y simplemente he incluido 64 Textblock, uno por casilla y el DataContext de cada Textblock es el que corresponde a cada objeto de la lista de objetos ChessPiece. Posteriormente cada Textblock tendrá un style asociado donde se le crea el Binding con el texto o la figura de ajedrez. (Las piezas de ajedrez son caracteres Unicode. ♜♞♝♛♚♟♖♘♗♕♔♙).
El estilo aplicado a cada Textblock es el siguiente:

<Style x:Key="piece" TargetType="TextBlock">
            <Setter Property="Text" Value="{Binding Picture}"/>

Código XAML

<Window x:Class="ChessBoardProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ChessBoardProject"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20"/>
            <ColumnDefinition Width="20*"/>
            <ColumnDefinition Width="20"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20*"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="board">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="55"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="55"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="55"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="55"/>
            </Grid.RowDefinitions>
            

            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="0" Grid.Column="0"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="0" Grid.Column="1"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="0" Grid.Column="2"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="0" Grid.Column="3"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="0" Grid.Column="4"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="0" Grid.Column="5"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="0" Grid.Column="6"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="0" Grid.Column="7"/>

            <Rectangle Style="{StaticResource blackCell}" Grid.Row="1" Grid.Column="0"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="1" Grid.Column="1"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="1" Grid.Column="2"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="1" Grid.Column="3"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="1" Grid.Column="4"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="1" Grid.Column="5"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="1" Grid.Column="6"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="1" Grid.Column="7"/>

            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="2" Grid.Column="0"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="2" Grid.Column="1"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="2" Grid.Column="2"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="2" Grid.Column="3"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="2" Grid.Column="4"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="2" Grid.Column="5"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="2" Grid.Column="6"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="2" Grid.Column="7"/>

            <Rectangle Style="{StaticResource blackCell}" Grid.Row="3" Grid.Column="0"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="3" Grid.Column="1"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="3" Grid.Column="2"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="3" Grid.Column="3"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="3" Grid.Column="4"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="3" Grid.Column="5"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="3" Grid.Column="6"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="3" Grid.Column="7"/>

            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="4" Grid.Column="0"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="4" Grid.Column="1"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="4" Grid.Column="2"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="4" Grid.Column="3"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="4" Grid.Column="4"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="4" Grid.Column="5"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="4" Grid.Column="6"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="4" Grid.Column="7"/>

            <Rectangle Style="{StaticResource blackCell}" Grid.Row="5" Grid.Column="0"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="5" Grid.Column="1"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="5" Grid.Column="2"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="5" Grid.Column="3"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="5" Grid.Column="4"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="5" Grid.Column="5"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="5" Grid.Column="6"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="5" Grid.Column="7"/>

            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="6" Grid.Column="0"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="6" Grid.Column="1"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="6" Grid.Column="2"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="6" Grid.Column="3"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="6" Grid.Column="4"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="6" Grid.Column="5"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="6" Grid.Column="6"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="6" Grid.Column="7"/>

            <Rectangle Style="{StaticResource blackCell}" Grid.Row="7" Grid.Column="0"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="7" Grid.Column="1"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="7" Grid.Column="2"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="7" Grid.Column="3"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="7" Grid.Column="4"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="7" Grid.Column="5"/>
            <Rectangle Style="{StaticResource blackCell}" Grid.Row="7" Grid.Column="6"/>
            <Rectangle Style="{StaticResource whiteCell}" Grid.Row="7" Grid.Column="7"/>

            <Rectangle Fill="Transparent" Stroke="Black" StrokeThickness="3" Grid.RowSpan="8" Grid.ColumnSpan="8"/>

            <TextBlock DataContext="{Binding BestParent[0]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[1]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[2]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[3]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[4]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[5]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[6]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[7]}" Style="{StaticResource piece}"  Grid.Row="0" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[8]}" Style="{StaticResource piece}"   Grid.Row="1" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[9]}" Style="{StaticResource piece}"   Grid.Row="1" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[10]}" Style="{StaticResource piece}"  Grid.Row="1" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[11]}" Style="{StaticResource piece}"  Grid.Row="1" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[12]}" Style="{StaticResource piece}"  Grid.Row="1" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[13]}" Style="{StaticResource piece}"  Grid.Row="1" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[14]}" Style="{StaticResource piece}"  Grid.Row="1" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[15]}" Style="{StaticResource piece}"  Grid.Row="1" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[16]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[17]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[18]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[19]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[20]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[21]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[22]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[23]}" Style="{StaticResource piece}"  Grid.Row="2" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[24]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[25]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[26]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[27]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[28]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[29]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[30]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[31]}" Style="{StaticResource piece}"  Grid.Row="3" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[32]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[33]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[34]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[35]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[36]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[37]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[38]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[39]}" Style="{StaticResource piece}"  Grid.Row="4" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[40]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[41]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[42]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[43]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[44]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[45]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[46]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[47]}" Style="{StaticResource piece}"  Grid.Row="5" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[48]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[49]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[50]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[51]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[52]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[53]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[54]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[55]}" Style="{StaticResource piece}"  Grid.Row="6" Grid.Column="7"/>

            <TextBlock DataContext="{Binding BestParent[56]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="0"/>
            <TextBlock DataContext="{Binding BestParent[57]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="1"/>
            <TextBlock DataContext="{Binding BestParent[58]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="2"/>
            <TextBlock DataContext="{Binding BestParent[59]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="3"/>
            <TextBlock DataContext="{Binding BestParent[60]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="4"/>
            <TextBlock DataContext="{Binding BestParent[61]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="5"/>
            <TextBlock DataContext="{Binding BestParent[62]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="6"/>
            <TextBlock DataContext="{Binding BestParent[63]}" Style="{StaticResource piece}"  Grid.Row="7" Grid.Column="7"/>
        </Grid>
        <Button Content="Start" Grid.Column="1" HorizontalAlignment="Right" Grid.Row="1" VerticalAlignment="Bottom" Width="75" Margin="20" Click="Button_Click"/>
    </Grid>
   
</Window>

Para no bloquear la interfaz, creamos una tarea y ejecutamos. Le he puesto un retardo de unos cuantos milisegundos en cada solución parcial para ver como actua el algoritmo y el resultado.
ScreenCapture_05-09-2020 12.44.10.gif
Licencia Creative Commons
Esta obra está bajo una Licencia Creative Commons Atribución-CompartirIgual 4.0 Internacional.

Anuncio publicitario

Interface. Genetic Algorithm II

Interface. Genetic Algorithm II
En este post veremos como un algoritmo genético es capaz de ordenar un tablero de ajedrez. Es como si un niño de 2 años pusiera las piezas aleatoriamente en el tablero y el algoritmo se encargara de poner cada una en su sitio.

Crearemos una clase ChessPiece para cada figura de ajedrez y una clase ChessBoard que implementará la interfaz IMutable. Esto quiere decir que nuestro cromosoma es una lista de piezas de ajedrez y que el Fitness es del tipo doble.
Acto seguido, creamos el geneset o conjunto de genes que formarán el cromosoma donde incluiremos también la casilla vacía. Luego le daremos un valor a cada pieza y otro valor a cada casilla, cada vez que se acierte, el fitness se verá incrementado hasta el 100%.

class ChessBoard : IMutable {
    override val geneset = mutableListOf(
            ChessPiece("T",ChessPieceColor.BLACK,11),
            ChessPiece("C",ChessPieceColor.BLACK,13),
            ChessPiece("A",ChessPieceColor.BLACK,15),
            ChessPiece("D",ChessPieceColor.BLACK,16),
            ChessPiece("R",ChessPieceColor.BLACK,18),
            ChessPiece("A",ChessPieceColor.BLACK,15),
            ChessPiece("C",ChessPieceColor.BLACK,13),
            ChessPiece("T",ChessPieceColor.BLACK,11),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("P",ChessPieceColor.BLACK,4),
            ChessPiece("T",ChessPieceColor.WHITE,10),
            ChessPiece("C",ChessPieceColor.WHITE,12),
            ChessPiece("A",ChessPieceColor.WHITE,14),
            ChessPiece("D",ChessPieceColor.WHITE,17),
            ChessPiece("R",ChessPieceColor.WHITE,19),
            ChessPiece("A",ChessPieceColor.WHITE,14),
            ChessPiece("C",ChessPieceColor.WHITE,12),
            ChessPiece("T",ChessPieceColor.WHITE,10),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5),
            ChessPiece("P",ChessPieceColor.WHITE,5))

    init {

        geneset.addAll((1..32).map { ChessPiece("_",ChessPieceColor.EMPTY,0) })
    }

    override val target: Double = 64.0
    override var bestParent = createParent(0)
    override var bestFitness: Double = 0.0
    private val values = mutableListOf(11,13,15,16,18,15,13,11,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,5,5,5,5,5,5,5,10,12,14,17,19,14,12,10)

    override fun isSuccess(): Boolean = bestFitness == 1.0

    var result=""
    override fun start() {
        bestFitness = getFitness(bestParent)
        var childFitness: Double
        var child: MutableList
        //Display(bestParent, bestFitness)
        var attemps=0

        do {
            do {
                child = mutate(bestParent)
                childFitness = getFitness(child)

            } while (bestFitness > childFitness)

            bestFitness = childFitness
            bestParent = child
            result +=toShortString() + "\n\n\n"
            attemps ++
            println(toShortString() + "\n")
        } while (!isSuccess())
        println("Nº de intentos: $attemps")
    }

    override fun createParent(param: Any): MutableList {
        // llena el tablero con las 32 fichas piezas + 32 vacias
        return geneset.shuffled().toMutableList()
    }

    override fun getFitness(obj: MutableList): Double = obj.mapIndexed { index, chessPiece -> if (values[index] == chessPiece.value) 1.0 else 0.0  }.sum() / target

    override fun mutate(parent: MutableList): MutableList {
        val parentFitness: Double = getFitness(parent)
        var childFitness = 0.0
        var child = mutableListOf()

        do {
            child.clear()
            child.addAll(parent)

            val startIndex = Random.nextInt(bestParent.size)
            val endIndex = Random.nextInt(bestParent.size)
            val start = parent[startIndex]
            val end = parent[endIndex]
            child[startIndex] = end
            child[endIndex] = start
            childFitness = getFitness(child)

        }while (childFitness chessPiece.toString() + if ((index+1) % 8 ==0) "\n" else "\t" }
            .joinToString("")}\nFitness: $bestFitness"

    fun toShortString(): String ="${bestParent
                    .mapIndexed { index, chessPiece -> (if (chessPiece.value==0) " " else if (chessPiece.value == values[index]) (if (chessPiece.color==ChessPieceColor.WHITE) "○" else "●") else "#")+if ((index+1) % 8 == 0) "\n" else "" }
                    .joinToString("")
        }\nFitness: ${"%.3f".format(bestFitness)}"
    fun  foo(collection: MutableList){

    }
}

fun main(){
    val chessBoard = ChessBoard()
    chessBoard.start()
    println(chessBoard.bestParent)
}

Y este es el resultado del progreso de los cromosomas para 36 intentos
cromosomas.png

TN	CN	AN	DN	RN	AN	CN	TN
PN	PN	PN	PN	PN	PN	PN	PN
__	__	__	__	__	__	__	__
__	__	__	__	__	__	__	__
__	__	__	__	__	__	__	__
__	__	__	__	__	__	__	__
PB	PB	PB	PB	PB	PB	PB	PB
TB	CB	AB	DB	RB	AB	CB	TB

Fitness: 1.0

Y ahora implementaremos la interfaz con mi mejor amigo, C#

 public class ChessPiece
    {
        public ChessPiece(string name, Colors color, int value)
        {
            Name = name;
            ChessPieceColor = color;
            Value = value;
        }

        public string Name { get; set; }
        public int Value { get; set; }
        public Colors ChessPieceColor { get; set; }

        public enum Colors
        {
            Black,
            White,
            Empty
        }

        public string ColorToString => ValueToString(ChessPieceColor);

        public new string ToString => $"{Name}{ColorToString}";

        private string ValueToString(Colors color)
        {
            switch (color)
            {
                case Colors.Black:
                    return "N";
                case Colors.White:
                    return "B";
                case Colors.Empty:
                    return "_";
                default:
                    return "";
            }
        }

    }

    public class ChessBoard : IMutable
    {
        public ChessBoard()
        {
            Geneset = new List()
            {
                    new ChessPiece("T", ChessPiece.Colors.Black, 11),
                    new ChessPiece("C", ChessPiece.Colors.Black, 13),
                    new ChessPiece("A", ChessPiece.Colors.Black, 15),
                    new ChessPiece("D", ChessPiece.Colors.Black, 16),
                    new ChessPiece("R", ChessPiece.Colors.Black, 18),
                    new ChessPiece("A", ChessPiece.Colors.Black, 15),
                    new ChessPiece("C", ChessPiece.Colors.Black, 13),
                    new ChessPiece("T", ChessPiece.Colors.Black, 11),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("P", ChessPiece.Colors.Black, 4),
                    new ChessPiece("T", ChessPiece.Colors.White, 10),
                    new ChessPiece("C", ChessPiece.Colors.White, 12),
                    new ChessPiece("A", ChessPiece.Colors.White, 14),
                    new ChessPiece("D", ChessPiece.Colors.White, 17),
                    new ChessPiece("R", ChessPiece.Colors.White, 19),
                    new ChessPiece("A", ChessPiece.Colors.White, 14),
                    new ChessPiece("C", ChessPiece.Colors.White, 12),
                    new ChessPiece("T", ChessPiece.Colors.White, 10),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5),
                    new ChessPiece("P", ChessPiece.Colors.White, 5)
            };

            Geneset.AddRange(Enumerable.Range(0, 32).ToList().Select(k => new ChessPiece("_", ChessPiece.Colors.Empty, 0)));           

        }

        public List Geneset { get; set; }
        public double Target { get; set; } = 64;
        public List BestParent { get; set; }
        public double BestFitness { get; set; }

        private Random rnd = new Random();
        private IList Values = new List() { 11, 13, 15, 16, 18, 15, 13, 11, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 10, 12, 14, 17, 19, 14, 12, 10 };
        private string result = "";

        public List CreateParent(object param) => Suffled(Geneset);

        public double GetFitness(List obj) => obj
            .Select((item, index) => new { Item = item, Index = index })
            .Select(k => k.Item.Value == Values[k.Index] ? 1.0 : 0.0)
            .Sum()/Target;

        public bool IsSuccess() => BestFitness == 1.0;

        public List Mutate(List parent)
        {

            var parentFitness = GetFitness(parent);
            var childFitness = 0.0;
            var child = new List();

            do
            {
                child.Clear();
                child.AddRange(parent);

                var startIndex = rnd.Next(BestParent.Count());
                var endIndex = rnd.Next(BestParent.Count());
                var start = parent[startIndex];
                var end = parent[endIndex];

                child.RemoveAt(startIndex);
                child.Insert(startIndex, end);
                child.RemoveAt(endIndex);
                child.Insert(endIndex, start);

                childFitness = GetFitness(child);
                //print(child);
            } while (childFitness k.Value)));
        }

        public void Start()

        {
            BestParent = CreateParent(null);
            BestFitness = GetFitness(BestParent);
            var childFitness = 0.0;
            var child = new List();

            var attemps = 0;
            do
            {
                do
                {
                    child = Mutate(BestParent);
                    childFitness = GetFitness(child);
                } while (BestFitness > childFitness);

                BestFitness = childFitness;
                BestParent = child;
                result += ToShortString + "\n\n\n";
                Console.WriteLine(result);
                attemps++;
            } while (!IsSuccess());

            Console.WriteLine(ToShortString + "\n");
            Console.WriteLine($"Nº intentos: {attemps}");
        }

        private List Suffled(List source) => source
            .Select(x => new { value = x, order = rnd.Next() })
            .OrderBy(x => x.order).Select(x => x.value).ToList();

        public new string ToString => $"{string.Join("",BestParent.Select((item, index) => new { Item = item, Index = index }).Select(k => k.Item.ToString + (((k.Index + 1) % 8 == 0) ? '\n' : ' '))) }";
        public string ToShortString => $"{string.Join("",BestParent.Select((item, index) => new { Item = item, Index = index }).Select(k => (k.Item.Value == 0 ? " " : (k.Item.Value == Values[k.Index]) ? (k.Item.ChessPieceColor == ChessPiece.Colors.White ? "O" : "■") : "#") + (((k.Index + 1) % 8 == 0) ? '\n' : ' '))) }";

    }
 class Program
    {
        static void Main(string[] args)
        {
            var chessboard = new ChessBoard();
            chessboard.Start();
            Console.WriteLine(chessboard.ToString);
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
    }

Si quieres leer mi anterior post sobre la interface de algoritmos genéticos, aquí lo tienes.

Licencia Creative Commons
Esta obra está bajo una Licencia Creative Commons Atribución-CompartirIgual 4.0 Internacional.