Skip to content

Instantly share code, notes, and snippets.

@claudioacioli
Last active June 5, 2021 18:20
Show Gist options
  • Save claudioacioli/fa1f4cead89c0394ca9242a035c02194 to your computer and use it in GitHub Desktop.
Save claudioacioli/fa1f4cead89c0394ca9242a035c02194 to your computer and use it in GitHub Desktop.
use std::io;
fn main() {
let arr = get_arr(get_n());
println!("{}", sum_arr(&arr));
}
fn get_n() -> usize {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap_or(0);
s.trim().parse::<usize>().unwrap_or(0)
}
fn get_arr(n :usize) -> Vec<u16> {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap_or(0);
let mut arr = vec![0; n];
for (i, value) in s.trim().split_whitespace().enumerate() {
if i > n {
break;
}
arr[i] = value.parse::<u16>().unwrap_or(0);
}
arr
}
fn sum_arr(arr :&[u16]) -> u16 {
let mut sum :u16 = 0;
for value in arr.iter() {
sum += value;
}
sum
}
#[test]
fn test_sum_arr() {
assert_eq!(10, sum_arr(&[1, 2, 3, 4]));
assert_eq!(5, sum_arr(&[1, 2, 2]));
assert_eq!(3, sum_arr(&[1, 1, 1]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment