Skip to content
Open

hw #18

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 39 additions & 11 deletions exercises/basic-of-rust/src/conditions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,25 @@
// - another function call
// - additional variables
pub fn bigger(a: i32, b: i32) -> i32 {
todo!()
if a > b {
a
} else {
b
}
}

//Exercise 2
// Input: Provide an arbitrary value of number
// Check number is Positive or Negative or Zero
// Output: &str
fn check_number(number: u32) -> &'static str {
todo!()
fn check_number(number: i32) -> &'static str {
if number < 0 {
return "Negative";
} else if number == 0 {
return "Zero";
} else {
return "Positive";
}
}

// Exercise 3
Expand All @@ -22,34 +32,54 @@ fn check_number(number: u32) -> &'static str {
pub fn foo_if_fizz(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else if fizzish == "fuzz" {
"bar"
} else {
1
"baz"
}
}

// Exercise 4
// Determine if a given year is a leap year
// Implement logic
fn is_leap_year(year: i32) -> bool {
todo!()
if year % 4 == 0 && year % 100 != 0 || year % 400 == 0 {
true
} else {
false
}
}

// Exercise 5
// Calculate the factorial of a number
// Implement logic
fn factorial(n: u32) -> u32 {
todo!()
if n == 0 {
return 1;
}
let mut res: u32 = 1;
for i in 1..n + 1 {
res = res * i;
}
res
}

// Exercise 6
// Check if a number is prime
// Implement logic

fn is_prime(n: u32) -> bool {
todo!()
if n <= 1 {
return false;
}
for i in 2..n {
if n % i == 0 {
return false;
}
}
true
}


// Don't mind this for now :)
#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -143,6 +173,4 @@ mod tests {
assert_eq!(is_prime(10), false);
assert_eq!(is_prime(15), false);
}


}
}
40 changes: 28 additions & 12 deletions exercises/basic-of-rust/src/functions.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,52 @@
// Exercise 1
// Fix all errors
fn sum(x, y: i32) {
x + y;
// 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
// Output: Calculate sum 1 to n
pub fn sum_one_to_n(n: u32) -> u32 {
// your code for summing all digits from 1 to `n` (inclusive) should go
// here (you can remove the sample return of `0`)
0
let mut res: u32 = 0;
for i in 1..n + 1 {
res = res + i;
}
return res;
}

// Exercise 3
// Input: list of arbitrary numbers
// Problem: Calculate the average of a list of numbers
// Output: Average Number
// Output: Average Number
fn calculate_average(numbers: &[f64]) -> f64 {
todo!()
if numbers.len() as u32 == 0 {
return 0.0;
}
let mut res: f64 = 0.0;
for num in numbers {
res = res + num;
}
res = res / numbers.len() as f64;

return res;
}

// Exercise 4
// Calculate the sum of all even numbers in a list
fn sum_even_numbers(numbers: &[i32]) -> i32 {
todo!()
let mut sum: i32 = 0;
for i in numbers {
if i % 2 == 0 {
sum = sum + i;
}
}
return sum;
}


#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -38,7 +56,7 @@ mod tests {
fn sum_should_work() {
let (x, y) = (1, 2);
let s = sum(x, y);

assert_eq!(s, 3);
}

Expand Down Expand Up @@ -73,7 +91,6 @@ mod tests {
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
Expand All @@ -83,7 +100,6 @@ mod tests {
let numbers = [];
let result = calculate_average(&numbers);
assert_eq!(result, 0.0);

}

// Test for exercise 4
Expand Down
39 changes: 25 additions & 14 deletions exercises/basic-of-rust/src/strings.rs
Original file line number Diff line number Diff line change
@@ -1,45 +1,57 @@
// Exercise 1
#[allow(dead_code)]
fn exercise1(color: &str) -> String {
todo!()
return color.to_string();
}

// Exercise 2
// Fix all errors without adding newline
fn exercise2() -> String {
let s = String::from("hello");
let mut s = String::from("hello");
s.push(',');
s.push(" world");
s += "!".to_string();
s.push_str(" world");
s += "!" as &str;
s
}
// Exercise 3
// Fix errors without removing any line
fn exercise3() -> String {
let s1 = String::from("hello,");
let s1 = String::from("hello, ");
let s2 = String::from("world!");
let s3 = s1 + s2;
let s3 = s1 + s2.as_str();
s3
}

// Exercise 4
// Reverse a string

fn reverse_string(input: &str) -> String {
todo!()
let res = input as &str;
return res.chars().rev().collect();
}


// Exercise 5
// Check if a string is a palindrome
fn is_palindrome(word: &str) -> bool {
todo!()
if word.to_lowercase() == reverse_string(word).to_lowercase() {
return true;
}
false
}

// Exercise 6
// Count the occurrences of a character in a string
fn count_char_occurrences(string: &str, ch: char) -> usize {
todo!()
let mut cnt = 0;
let mut new_string = String::new();
new_string.push_str(string);

for k in new_string.chars() {
if k == ch {
cnt = cnt + 1;
}
}
return cnt;
}

#[cfg(test)]
Expand All @@ -63,7 +75,7 @@ mod tests {
fn exercise3_work() {
assert_eq!("hello, world!".to_string(), exercise3());
}

// Test for exercise 4
#[test]
fn test_reverse_string() {
Expand Down Expand Up @@ -92,8 +104,7 @@ mod tests {
#[test]
fn test_count_char_occurrences() {
assert_eq!(count_char_occurrences("Hello", 'l'), 2);
assert_eq!(count_char_occurrences("Rust is fun", 'u'), 1);
assert_eq!(count_char_occurrences("Rust is fun", 'u'), 2);
assert_eq!(count_char_occurrences("Mississippi", 's'), 4);
}

}
}
37 changes: 20 additions & 17 deletions exercises/ownership-borrowing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
fn exercise1() {
// Use as many approaches as you can to make it work
let x = String::from("hello, world");
let y = x;
let z = x;
let y = &x;
let z = &x;
}

// Exercise 2
Expand Down Expand Up @@ -33,15 +33,15 @@ fn exercise3() {

let values_number = values.len();

let additions: Vec<usize> = vec![0];
let additions: Vec<usize> = vec![0, 1];

println!("{:?}", values_number);

while additions.len() > 0 {
let mut addition: f64 = 0.0;

// Sumar valores en additions
for element_index in additions {
for &element_index in &additions {
let addition_aux = values[element_index];
addition = addition_aux + addition;
}
Expand All @@ -50,9 +50,9 @@ fn exercise3() {

// Exercise 4
// Make it compile
fn exercise4(value: u32) -> &'static str {
fn exercise4(value: u32) -> String {
let str_value = value.to_string(); // Convert u32 to String
let str_ref: &str = &str_value; // Obtain a reference to the String
let str_ref = str_value; // Obtain a reference to the String
str_ref // Return the reference to the String
}

Expand All @@ -65,11 +65,11 @@ fn exercise5() {
let key = 3;

let res = match my_map.get(&key) {
Some(child) => child,
Some(child) => child.to_string(),
None => {
let value = "3.0".to_string();
my_map.insert(key, value);
&value // HERE IT FAILS
my_map.insert(key, value.clone());
value // HERE IT FAILS
}
};

Expand All @@ -82,50 +82,53 @@ fn exercise5() {
use std::io;

fn exercise6() {
let mut prev_key: &str = "";
let mut prev_key = String::new();

for line in io::stdin().lines() {
let s = line.unwrap();

let data: Vec<&str> = s.split("\t").collect();
if prev_key.len() == 0 {
prev_key = data[0];
prev_key = data[0].to_string();
}
}
}

// Exercise 7
// Make it compile
fn exercise7() {
let mut v: Vec<&str> = Vec::new();
let mut v: Vec<String> = Vec::new();
{
let chars = [b'x', b'y', b'z'];
let s: &str = std::str::from_utf8(&chars).unwrap();
v.push(&s);
v.push(s.to_string());
}
println!("{:?}", v);
}

// Exercise 8
// Make it compile
fn exercise8() {
let mut accounting = vec!["Alice", "Ben"];
let mut accounting = vec!["Alice".to_string(), "Ben".to_string()];

loop {
let mut add_input = String::from("");

io::stdin()
.read_line(&mut add_input)
.expect("Failed to read line");

let add_vec: Vec<&str> = add_input.trim()[..].split_whitespace().collect();
let add_vec: Vec<String> = add_input.trim()[..]
.split_whitespace()
.map(|x| x.to_string())
.collect();

if add_vec.len() < 1 {
println!("Incorrect input, try again");
continue;
}

let person = add_vec[0];
let person = add_vec[0].to_string();
accounting.push(person);
}
}