1

I'm trying to reimplement a coding question from HackerRank which was easy enough in Python in Rust.

The input & goal are something like this:

#10 * 1 + 40 * 2 + 30 * 3 + 50 * 4 + 20 + 5     480
#------------------------------------------ =   --- = 32.00
#   1   +   2   +   3   +   4   +   5            15

The numerator is the sum of the first_array[nth] * second_arry[nth] divided by the sum of the second_array's items - it is returning a weighted mean (where the weighting is provided).


My Python looks like this:

for i in range(0, n):
        numerator += fl[i] * sl[i] 
        denominator += sl[i]

In Rust:

fn weighted_avg(fl: Vec<f64>, sl: Vec<f64>) -> f64 {
    let mut n = fl.len() as u32;
    let mut numerator = 0f64;
    let mut denominator = 0f64;

    for i in 1..n {
        denominator += sl[i];
        numerator += fl[i] * &denominator;
    }
    numerator / denominator
}

playground

The error I get is:

error[E0277]: the trait bound `u32: std::slice::SliceIndex<[f64]>` is not satisfied
 --> src/lib.rs:7:24
  |
7 |         denominator += sl[i];
  |                        ^^^^^ slice indices are of type `usize` or ranges of `usize`
  |
  = help: the trait `std::slice::SliceIndex<[f64]>` is not implemented for `u32`
  = note: required because of the requirements on the impl of `std::ops::Index<u32>` for `std::vec::Vec<f64>`

error[E0277]: the trait bound `u32: std::slice::SliceIndex<[f64]>` is not satisfied
 --> src/lib.rs:8:22
  |
8 |         numerator += fl[i] * &denominator;
  |                      ^^^^^ slice indices are of type `usize` or ranges of `usize`
  |
  = help: the trait `std::slice::SliceIndex<[f64]>` is not implemented for `u32`
  = note: required because of the requirements on the impl of `std::ops::Index<u32>` for `std::vec::Vec<f64>`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I encourage you to read the complete error message for any programming problem, but especially for Rust errors. For example, this error message includes "slice indices are of type `usize` or ranges of `usize`" – Shepmaster Sep 23 '18 at 15:55
  • Also, you [probably don't want to take a `Vec` as the argument](https://stackoverflow.com/q/40006219/155423). – Shepmaster Sep 23 '18 at 15:58

0 Answers0