Iterating through 3 loops

Hello, I'm trying to port java logic to rust and stumbled at this piece of logic and couldn't figure out what is equivalent rust code for this. Can you please help how will I make this work with idiomatic rust ??

private int subarraySum(int[] arr) {
    int result = 0;
    for (int i = 0; i < arr.length; i++) {
        for (int j = i; j < arr.length; i++) {
            for (int k = i; k <= j; k++) {
                result += arr[k];
            }
        }
    }
    return result;
}

I would probably go for this:

fn subarray_sum(arr: &[i32]) -> i32 {
    let mut result = 0;
    
    for i in 0..arr.len() {
        for j in i..arr.len() {
            result += arr[i ..= j].iter().sum::<i32>();
        }
    }
    
    result
}

Assuming you meant to increment j in the middle loop.

Thanks for the quick & prompt reply.

Another solution would be the following:

fn subarray_sum(arr: &[i32]) -> i32 {
    let mut result = 0;
    
    for (i, &value) in arr.iter().enumerate() {
        let combinations_before = 1 + i;
        let combinations_after = arr.len() - i;
        result += value * (combinations_before * combinations_after) as i32;
    }
    
    result
}
4 Likes