代码之家  ›  专栏  ›  技术社区  ›  Farouk Alhassan

将Ruby代码转换为Java

  •  2
  • Farouk Alhassan  · 技术社区  · 16 年前

    我从未使用过ruby,但需要将这段代码翻译成java。

    这是Ruby中的代码。

    DEFAULT_PRIOR = [2, 2, 2, 2, 2]
    ## input is a five-element array of integers
    ## output is a score between 1.0 and 5.0
    def score votes, prior=DEFAULT_PRIOR
    posterior = votes.zip(prior).map { |a, b| a + b }
    sum = posterior.inject { |a, b| a + b }
    posterior.
    map.with_index { |v, i| (i + 1) * v }.
    inject { |a, b| a + b }.
    to_f / sum
    end
    

    我是从这里得到的,所以也许能在那里找到一些线索。关于计算平均数

    How to rank products based on user input

    这就是解决办法。以防有人需要

        static final int[] DEFAULT_PRIOR = {2, 2, 2, 2, 2};
    
    static float  score(int[] votes) {
        return score(votes, DEFAULT_PRIOR);
    }
    
    private static float score(int[] votes, int[] prior) {
    
        int[] posterior = new int[votes.length];
        for (int i = 0; i < votes.length; i++) {
            posterior[i] = votes[i] + prior[i];
        }
        int sum = 0;
        for (int i = 0; i < posterior.length; i++) {
            sum = sum + posterior[i];
        }
    
        float sumPlusOne = 0;
        for (int i = 0; i < posterior.length; i++) {
            sumPlusOne = sumPlusOne + (posterior[i] * (i + 1));
        }
        return sumPlusOne / sum;
    }
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   sepp2k    16 年前

    代码执行以下操作:

    它设置了一个名为 DEFAULT_PRIOR

    static final int[] DEFAULT_PRIOR = {2,2,2,2,2};
    

    它定义了一个名为score的双参数方法,其中第二个参数默认为 默认值

    float score(int[] votes) {
        return score(votes, DEFAULT_PRIOR);
    }
    

    在score方法中,它执行以下操作:

    posterior = votes.zip(prior).map { |a, b| a + b }
    

    这将创建一个后向数组,其中每个元素是投票中相应元素和前一个元素(即。 posterior[i] = votes[i] + prior[i]

    sum = posterior.inject { |a, b| a + b }
    

    这将sum设置为 posterior .

    posterior.
    map.with_index { |v, i| (i + 1) * v }.
    inject { |a, b| a + b }.
    to_f / sum
    

    sum .

    在java中,您可以使用 for (i + 1) * posterior[i] (其中 i 是 -循环)到变量 tmp tmp公司 到 float 总和 .

    推荐文章