Skip to content

Commit

Permalink
feat: add string guessing example
Browse files Browse the repository at this point in the history
Issue #15
  • Loading branch information
morinim committed Jun 14, 2024
1 parent de7c1ce commit 679de8f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
53 changes: 53 additions & 0 deletions src/examples/string_guess.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* \remark This file is part of ULTRA.
*
* \copyright Copyright (C) 2024 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*
* \see https://github.com/morinim/ultra/wiki/string_guessing_tutorial
*/

#include <iostream>
#include <string>

#include "kernel/ultra.h"

const std::string target = "Hello World";
const std::string CHARSET =
" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!";

// The fitness function.
double fitness(const ultra::ga::individual &x)
{
double found(0.0);

for (std::size_t i(0); i < target.length(); ++i)
if (target[i] == CHARSET[x[i]])
++found;

return found;
}

int main()
{
using namespace ultra;

// A solution of this problem is a fixed length (`target.length()`) string of
// characters in a given charset (`CHARSET`).
ga::problem prob(target.length(), {0, CHARSET.size()});

prob.params.population.individuals = 300;

ga::search search(prob, fitness);
auto result(search.run().best_individual);

std::cout << "\nBest result: ";
for (auto gene : result)
std::cout << CHARSET[gene];

std::cout << " (fitness " << fitness(result) << ")\n";
}
4 changes: 3 additions & 1 deletion src/kernel/ultra.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
#define ULTRA_ULTRA_H

#include "kernel/de/individual.h"
#include "kernel/de/primitive.h"
#include "kernel/de/problem.h"
#include "kernel/de/search.h"
#include "kernel/ga/individual.h"
#include "kernel/ga/problem.h"
#include "kernel/ga/search.h"
#include "kernel/gp/individual.h"
#include "kernel/gp/primitive/integer.h"
#include "kernel/gp/primitive/real.h"
Expand Down

0 comments on commit 679de8f

Please sign in to comment.