开发者

Translating Ruby code to Java

开发者 https://www.devze.com 2023-01-22 04:25 出处:网络
I have never used ruby but need to translate this code to java. Can anyone help me. This is the code in Ruby.

I have never used ruby but need to translate this code to java.

Can anyone help me.

This is the code in 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

I obtained it from here so maybe some clues can be found there. its about calculating averages

How to rank products based on user input

This was the solution. In case anyone needs it

    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;
}


The code does the following things:

It set a constant named DEFAULT_PRIOR (java equivalent would be a static final variable) to an array containing the number 2 five times. In java:

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

It defines a two-argument method named score where the second argument defaults to DEFAULT_PRIOR. In java this can be achieved with overloading:

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

Inside the score method, it does the following:

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

This creates an array posterior, where each element is the sum of the corresponding element in votes and the corresponding element in prior (i.e. posterior[i] = votes[i] + prior[i]).

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

This sets sum to be the sum of all elements in posterior.

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

This bit multiplies each element in posterior with its index plus one and then sums that. The result is converted to a float and then divided by sum.

In java you would iterate over posterior with for-loop (not foreach) and in each iteration add (i + 1) * posterior[i] (where i is the index of the for-loop) to a variable tmp, which you set to 0 before the loop. Then you would cast tmp to float and divide it by sum.

0

精彩评论

暂无评论...
验证码 换一张
取 消