将C++函数翻译成Java

Translate C++ function to Java

本文关键字:Java 翻译 函数 C++      更新时间:2023-10-16

首先,如果问题是基本的,我很抱歉,但我不是C++专家。

我正在研究Java中的遗传算法,我到达了这个链接,其中包含有趣的信息:http://web.archive.org/web/20100216182958/http://fog.neopages.org/helloworldgeneticalgorithms.php

然而,我完全不明白这种方法在做什么:

int fitness(bool* chromosome)
{
    // the ingredients are:  0     1     2     3   4    5     6
    //          salt sugar lemon egg water onion apple
    return ( -chromosome[0] + chromosome[1] + chromosome[2] 
         -chromosome[3] + chromosome[4] - chromosome[5] 
         -chromosome[6] );  
}

出于学术目的,我试图将C++程序"翻译"成Java,但我不理解这种方法,到底返回了什么?(我假设它是用数组操作的。)

它返回一个整数。布尔值在相加/相减之前会被转换为整数。True为1。False为0。

这是Java翻译。在我们的例子中,我们必须自己将布尔值转换为整数。

int fitness(boolean[] chromosome)
{
    int[] intChromosome = toInt(chromosome);
    // the ingredients are:  0     1     2     3   4    5     6
    //          salt sugar lemon egg water onion apple
    return ( -intChromosome [0] + intChromosome [1] + intChromosome [2] 
         -intChromosome [3] + intChromosome [4] - intChromosome [5] 
         -intChromosome [6] );  
}
int[] toInt(boolean[] values) {
    int[] integers = new int[values.length];
    for (int i = 0; i < values.length; i++) {
        integers[i] = values[i] ? 1 : 0;
    }
    return integers;
}