diff --git a/CMakeLists.txt b/CMakeLists.txt index cee098e..fab0346 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.10) project( - n-queens + n_queens LANGUAGES CXX) set(CMAKE_CXX_STANDARD 11 CACHE STRING "The C++ standard to use") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d370e0e..782b1e0 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,6 +1,8 @@ -add_executable(n-queens - ./n-queens.cpp +add_executable(n_queens + ./n_queens.cpp + ./chess.cpp + ./genetic_algorithm.cpp ) -target_include_directories(n-queens PUBLIC ${CMAKE_CURRENT_LIST_DIR}) +target_include_directories(n_queens PUBLIC ${CMAKE_CURRENT_LIST_DIR}) diff --git a/src/n-queens.cpp b/src/chess.cpp similarity index 100% rename from src/n-queens.cpp rename to src/chess.cpp diff --git a/src/chess.hpp b/src/chess.hpp new file mode 100644 index 0000000..e69de29 diff --git a/src/genetic_algorithm.cpp b/src/genetic_algorithm.cpp new file mode 100644 index 0000000..7c95315 --- /dev/null +++ b/src/genetic_algorithm.cpp @@ -0,0 +1,145 @@ +#include "genetic_algorithm.hpp" +#include +#include +#include + +/* Prints the population strings in a line */ +void print_population(unsigned char population_in[]) { + int iterator = 0; + int member_count = 0; + char cur_member; + while (member_count < N){ + cur_member = population_in[member_count]; + while (iterator < L){ + if (cur_member & 0x80){ + printf("1"); + } + else{ + printf("0"); + } + cur_member = cur_member << 1; + iterator++; + } + member_count++; + iterator = 0; + printf(" "); + } + printf("\n"); +} + +/* Fitness is determined by the number of + 1's in the bitstring. */ +int get_fitness(unsigned char string_in){ + int count = 0; + unsigned char temp = string_in; + while (temp){ + if (temp & 0x01){ + count++; + } + temp = temp >> 1; + } + return count; +} + +/* Randomly initialize the first population */ +void init_population(unsigned char* population){ + int i; + for ( i=0; i +#include +#include + +int main(){ + unsigned char population[N] = {0}; + int selected[N] = {-1}; + int generation_count = 0; + int i; + srand(time(NULL)); + + + //basic genetic algorithm skeleton + init_population(population); + print_population(population); + + while (generation_count < G) { + do_selection(population, selected); + do_crossover(population, selected); + do_mutation(population); + printf("%4d: ", generation_count); + print_population(population); + for (i = 0; i < N; i++) { + if (population[i] == 0xFF) { + printf("Max fit reached.\n"); + return 0; + } + } + generation_count++; + } + + return 0; +}