Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Running sum of 1d array

// Running sum of 1d array

// Iterative
fn running_sum1(nums: Vec<i32>) -> Vec<i32> {
    let mut arr = vec![nums[0]];
    for i in 1..nums.len() {
        arr.push(nums[i] + arr[i - 1]);
    }
    arr
}

// Functional
fn running_sum2(nums: Vec<i32>) -> Vec<i32> {
	let mut sum = 0;
	nums.into_iter().map(|i| {sum += i; sum}).collect::<Vec<i32>>()
}

fn main() {
    println!("Running sum = {:?} ", running_sum1(vec![4,1,7,10,1]));
    println!("Running sum = {:?} ", running_sum2(vec![4,1,7,10,1]));    
}
 
PREVIOUS NEXT
Tagged: #Running #sum #array
ADD COMMENT
Topic
Name
8+8 =