Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feedback #1

Open
wants to merge 18 commits into
base: feedback
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ fn main() {
println!("{}", multiply(10, 20));
}

fn multiply(a: i32, b: i32) {
fn multiply(a: i32, b: i32) -> i32 {
a * b
}

// Tests; run with `cargo test --bin 01`
// Tests; run with cargo test --bin 01
#[cfg(test)]
mod tests {
use super::*;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
fn main() {
if (bigger(10, 20)) {
if bigger(10, 20) {
println!("10 is bigger than 20");
} else {
println!("10 still isn't bigger than 20");
}
}

fn bigger(a: i32, b: i32) -> i32 {
// TODO
fn bigger(a: i32, b: i32) -> bool {
a > b
}

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
fn main() {
let input = [23, 82, 16, 45, 21, 94, 12, 34];

// TODO
let largest = input.iter().max().unwrap();
let smallest = input.iter().min().unwrap();

println!("{} is largest and {} is smallest");
println!("{} is largest and {} is smallest", largest, smallest);
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
fn main() {
for (n in [10, 20, 30, 40]) {
for n in [10, 20, 30, 40] {
let mult = if n < 25 {
n * 4
} else {
n * 3;
n * 3
};
println!("{}", mult);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
fn main() {
let data = [22, 12, 13, 17, 18];
let mut data = [22, 12, 13, 17, 18];
for i in 0..5 {
data.i = floored_half(data.i);
data[i] = floored_half(data[i]);
}
println!("{:?}", data);
}

fn floored_half(data: i32) {
fn floored_half(data: i32) -> i32 {
data / 2
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
fn main() {
let s0 = String::from("Hello");

let mut s1 = append_to_string(s0);

// Don't change the following line!
println!("{} == `{}`", stringify!(s0), s0);

let mut s1 = append_to_string(s0);

s1.push('!');

println!("{} == `{}`", stringify!(s1), s1);
Expand All @@ -22,3 +22,4 @@ fn append_to_string(s: String) -> String {

s
}

Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ fn main() {
println!("{} == `{}`", stringify!(s1), s1);
}

fn append_to_string(s: String) -> String {
fn append_to_string(mut s: String) -> String {
s.push_str("Hello World");

s
}

Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
//! function.

fn main() {
let s0 = String::new();

let mut s1 = create_string(s0);
let mut s1 = create_string();

println!("{} == `{}`", stringify!(s1), s1);

Expand All @@ -14,9 +12,10 @@ fn main() {
println!("{} == `{}`", stringify!(s1), s1);
}

///`create_string()` no longer takes `s: String` as argument
/// `create_string()` nu mai primește un argument `s: String`
fn create_string() -> String {
let mut s = s;
let mut s = String::from("Hello"); // Creăm stringul în funcție

s
}

Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut x;
*y += 100;
let z = &mut x;
*z += 1000;
assert_eq!(x, 1200);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@
fn main() {
let data = "Rust is great!".to_string();

get_char(data);
get_char(&data);

string_uppercase(&data);
string_uppercase(data);
}

// Should not take ownership
fn get_char(data: String) -> char {
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}

// Should take ownership
fn string_uppercase(mut data: &String) {
data = &data.to_uppercase();
fn string_uppercase(mut data: String) {
data = data.to_uppercase();

println!("{}", data);
}

Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,44 @@ use std::io::{self, BufRead, BufReader, Lines};

//change this into:
//fn read_lines(filename: &str) -> Result<Lines<BufReader<File>>, io::Error> {
fn read_lines(filename: &str) -> Lines<BufReader<File>> {
let file = File::open(filename).unwrap(); // this can easily fail
BufReader::new(file).lines()
fn read_lines(filename: &str) -> Result<Lines<BufReader<File>>, io::Error> {
let file = File::open(filename)?;
Ok(BufReader::new(file).lines())
}

//change this into:
//fn count_bytes_and_lines(filename: &str) -> Result<(usize, usize, usize), io::Error> {
fn count_bytes_and_lines(filename: &str) -> (usize, usize, usize) {
let lines = read_lines(filename);
fn count_bytes_and_lines(filename: &str) -> Result<(usize, usize, usize), io::Error> {
let lines = read_lines(filename)?;
let mut line_count = 0;
let mut word_count = 0;
let mut byte_count = 0;

for line in lines {
let text = line.unwrap(); // this will usually not fail
let text = line?;
line_count += 1;
word_count += text.split_whitespace().count();
byte_count += text.len();
}

(line_count, word_count, byte_count)
Ok((line_count, word_count, byte_count))
}

fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <filename>", args[0]);
return;
}

let filename = &args[1];

let (lines, words, bytes) = count_bytes_and_lines(filename);
println!("{filename}: {lines} lines, {words} words, {bytes} bytes");
match count_bytes_and_lines(filename) {
Ok((lines, words, bytes)) => {
println!("{filename}: {lines} lines, {words} words, {bytes} bytes");
}
Err(e) => {
eprintln!("Error processing file '{}': {}", filename, e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,49 @@
// NOTE: You will (hopefully) discover that "?" doesn't work in this context, and the resulting code
// is a bit explicit about the errors --- we can solve that with traits, next week!

use std::io::{BufRead, self, Write};
use std::io::{self, BufRead, Write};

#[derive(Debug)]
enum MyError{ InvalidName,IOError( io::Error),
enum MyError {
InvalidName,
IOError(io::Error),
}

fn get_username( )
-> String
{
fn get_username() -> Result<String, MyError> {
print!("Username: ");
io::stdout().flush();
io::stdout().flush().map_err(MyError::IOError)?;

let mut input=String::new();
io::stdin().lock().read_line(&mut input); input=input.trim().to_string();
let mut input = String::new();
io::stdin().lock().read_line(&mut input).map_err(MyError::IOError)?;
input = input.trim().to_string();

for c in input.chars()
{
if !char::is_alphabetic(c) { panic!("that's not a valid name, try again"); }
if input.is_empty() {
return Err(MyError::InvalidName);
}

if input.is_empty() {
panic!("that's not a valid name, try again");
}
for c in input.chars() {
if !char::is_alphabetic(c) {
return Err(MyError::InvalidName);
}
}

input
Ok(input)
}

fn main() {
let name=get_username();
println!("Hello {name}!")
loop {
match get_username() {
Ok(name) => {
println!("Hello {name}!");
break;
}
Err(MyError::InvalidName) => {
eprintln!("That's not a valid name, try again.");
}
Err(MyError::IOError(e)) => {
eprintln!("An I/O error occurred: {}", e);
break;
}
}
}
}
40 changes: 19 additions & 21 deletions 2-foundations-of-rust/3-advanced-syntax/3-slices/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,34 @@

/// Merge two array slices (that have to be sorted) into a vector
fn merge(a: &[i32], b: &[i32]) -> Vec<i32> {
let mut dest = Vec::new();
let mut dest = Vec::with_capacity(a.len() + b.len());y

let a_idx = 0;
let b_idx = 0;
let mut a_idx = 0;
let mut b_idx = 0;

while a_idx < a.len() && b_idx < b.len() {
if a[a_idx] <= b[b_idx] {
dest.push(a[a_idx]);
a_idx += 1
a_idx += 1;
} else {
dest.push(b[b_idx]);
b_idx += 1
b_idx += 1;
}
}

for elem in a[a_idx..] {
dest.push(elem)
}
for elem in b[b_idx..] {
dest.push(elem)
}
dest.extend_from_slice(&a[a_idx..]);
dest.extend_from_slice(&b[b_idx..]);

dest
}

/// Take an array slice, and sort into a freshly constructed vector using the above function
fn merge_sort(data: &[i32]) -> Vec<i32> {
if data.len() > 1 {
// implement this
todo!()
let mid = data.len() / 2;
let left = merge_sort(&data[..mid]);
let right = merge_sort(&data[mid..]);
merge(&left, &right)
} else {
data.to_vec()
}
Expand All @@ -49,7 +47,7 @@ fn read_numbers() -> Vec<i32> {
let mut result = Vec::new();
for line in io::stdin().lines().flatten() {
for word in line.split_whitespace() {
result.push(word.parse().unwrap())
result.push(word.parse().unwrap());
}
}

Expand All @@ -59,11 +57,11 @@ fn read_numbers() -> Vec<i32> {
fn main() {
let input = read_numbers();
println!("Data to be sorted:");
println!("{input:?}");
println!("{:?}", input);

let sorted_input = merge_sort(&input);
println!("Sorted data:");
println!("{sorted_input:?}");
println!("{:?}", sorted_input);
}

// you can run these automatic tests by typing 'cargo test'
Expand All @@ -73,10 +71,10 @@ mod test {

#[test]
fn test_sort() {
assert_eq!(merge_sort(&[]), vec![]);
assert_eq!(merge_sort(&[5]), vec![5]);
assert_eq!(merge_sort(&[1,2,3]), vec![1,2,3]);
assert_eq!(merge_sort(&[47,42,5,1]), vec![1,5,42,47]);
assert_eq!(merge_sort(&[6,47,42,5,1,123]), vec![1,5,6,42,47,123]);
assert_eq!(merge_sort(&[]), vec![]);
assert_eq!(merge_sort(&[5]), vec![5]);
assert_eq!(merge_sort(&[1, 2, 3]), vec![1, 2, 3]);
assert_eq!(merge_sort(&[47, 42, 5, 1]), vec![1, 5, 42, 47]);
assert_eq!(merge_sort(&[6, 47, 42, 5, 1, 123]), vec![1, 5, 6, 42, 47, 123]);
}
}
Loading