forked from CocDap/Rust-Bootcamp-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.rs
114 lines (96 loc) · 2.41 KB
/
functions.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Exercise 1
// Fix all errors
fn sum(x:i32, y: i32)->i32 {
x + y
}
//Exercise 2
// Input: Provide an arbitrary value of n
// Implement sum function: 1+2+3+..n
// Output: Calculate sum 1 to n
pub fn sum_one_to_n(n: u32) -> u32 {
let mut ans=0;
for i in 1..n+1{
ans+=i;
}
return ans;
}
// Exercise 3
// Input: list of arbitrary numbers
// Problem: Calculate the average of a list of numbers
// Output: Average Number
fn calculate_average(numbers: &[f64]) -> f64 {
let mut ans=0.0;
let mut cnt=0;
for i in numbers.iter(){
ans+=i;
cnt=cnt+1;
}
if cnt==0{
return 0.0;
}
return ans/(cnt as f64);
}
// Exercise 4
// Calculate the sum of all even numbers in a list
fn sum_even_numbers(numbers: &[i32]) -> i32 {
let mut ans=0;
for i in numbers.iter(){
if i%2==0{
ans+=i;
}
}
ans
}
#[cfg(test)]
mod tests {
use super::*;
// Test for exercise 1
#[test]
fn sum_should_work() {
let (x, y) = (1, 2);
let s = sum(x, y);
assert_eq!(s, 3);
}
// Test for exercise 2
#[test]
fn test_sum_0() {
let result = sum_one_to_n(0);
assert_eq!(result, 0);
}
// Test for exercise 2
#[test]
fn test_sum_1() {
let result = sum_one_to_n(1);
assert_eq!(result, 1);
}
// Test for exercise 2
#[test]
fn test_sum_100() {
let result = sum_one_to_n(100);
assert_eq!(result, 5050);
}
// Test for exercise 3
#[test]
fn test_calculate_average() {
// Test case 1: Non-empty slice
let numbers = [2.5, 4.8, 6.3, 1.7, 3.9];
let result = calculate_average(&numbers);
assert_eq!(result, 3.84);
}
// Test for exercise 3
#[test]
fn test_calculate_average_empty() {
// Test case 1: Non-empty slice
let numbers = [];
let result = calculate_average(&numbers);
assert_eq!(result, 0.0);
}
// Test for exercise 4
#[test]
fn test_sum_even_numbers() {
assert_eq!(sum_even_numbers(&[1, 2, 3, 4, 5, 6]), 12);
assert_eq!(sum_even_numbers(&[10, 20, 30, 40, 50]), 150);
assert_eq!(sum_even_numbers(&[15, 25, 35, 45, 55]), 0);
assert_eq!(sum_even_numbers(&[-2, 0, 2, 4, 6]), 10);
}
}