Skip to content

Instantly share code, notes, and snippets.

@jenetics
Last active January 13, 2020 20:19
Show Gist options
  • Save jenetics/8578808cc62516b519b69ef376893703 to your computer and use it in GitHub Desktop.
Save jenetics/8578808cc62516b519b69ef376893703 to your computer and use it in GitHub Desktop.
Codec for creating a split double range
/*
* This codec creates a split range, where only values between [0, 2) and
* [8, 10) are valid. The valid range is marked with '-' and the invalid
* range with 'x'.
*
* +--+--+--+--+--+--+--+--+--+--+
* | | | | | | | | | | |
* 0 1 2 3 4 5 6 7 8 9 10
* |-----|xxxxxxxxxxxxxxxxx|-----|
* ^ |llllllll|rrrrrrrr| ^
* | | | |
* +-------+ +------+
*
* The mapping function maps the left part of the invalid range, denoted
* with 'l', to the lower valid range. The upper half of the invalid range,
* 'r', is mapped to the upper valid range. This way we have created a more
* complex codec by using an existing one.
* If you want to get the best value back from the best genotype, you have
* to decode it using the same codec.
*
* final Genotype<DoubleGene> gt = stream
* .limit(100)
* .collect(EvolutionResult.toBestGenotype());
*
* final double bestValue = CODEC.decode(gt);
*/
private static final Codec<Double, DoubleGene> CODEC = Codecs
.ofScalar(DoubleRange.of(0, 10))
.map((Double v) -> {
if (v >= 2 && v < 8) {
return v < 5 ? ((v - 2)/3)*2 : ((8 - v)/3)*2 + 8;
}
return v;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment