-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Issue #15
- Loading branch information
Showing
2 changed files
with
56 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters