Hi all, 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;
}