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 7 commits into
base: feedback
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ fn main() {
println!("{}", multiply(10, 20));
}

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

// Tests; run with `cargo test --bin 01`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ fn main() {
}
}

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

#[cfg(test)]
Expand Down
12 changes: 10 additions & 2 deletions 2-foundations-of-rust/1-basic-syntax/1-basic-syntax/src/bin/03.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
fn main() {
let input = [23, 82, 16, 45, 21, 94, 12, 34];

// TODO
let mut min: i32 = i32::MAX;
let mut max: i32 = i32::MIN;
for n in input {
if n > max {
max = n
} else if n < min {
min = n
}
}

println!("{} is largest and {} is smallest");
println!("{} is largest and {} is smallest", max, min);
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
fn main() {
for (n in [10, 20, 30, 40]) {
let mult = if n < 25 {
n * 4
} else {
n * 3;
};
for n in [10, 20, 30, 40] {
let mult = if n < 25 { n * 4 } else { n * 3 };
println!("{}", mult);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
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]);
}
}

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,10 @@
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 Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! Make me compile without adding new lines-- just changing existing lines!

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

let mut s1 = append_to_string(s0);
let s1 = append_to_string(&mut s0);

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

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

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

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

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

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

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

Expand All @@ -16,7 +16,7 @@ fn main() {

///`create_string()` no longer takes `s: String` as argument
fn create_string() -> String {
let mut s = s;
let s = String::from("Hello");

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,19 @@
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,15 +19,15 @@ 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>> {
fn read_lines(filename: &str) -> Result<Lines<BufReader<File>>, io::Error> {
let file = File::open(filename).unwrap(); // this can easily fail
BufReader::new(file).lines()
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).unwrap();
let mut line_count = 0;
let mut word_count = 0;
let mut byte_count = 0;
Expand All @@ -38,13 +38,13 @@ fn count_bytes_and_lines(filename: &str) -> (usize, usize, usize) {
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();
let filename = &args[1];

let (lines, words, bytes) = count_bytes_and_lines(filename);
let (lines, words, bytes) = count_bytes_and_lines(filename).unwrap();
println!("{filename}: {lines} lines, {words} words, {bytes} bytes");
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/// While taking a first stab at programs, using panic!() is a quick-and-dirty way to do error handling; but panic!() has the obvious drawback
/// that it is all-or-nothing: you cannot recover from it (in general).

// Consider this "interactive hello world" (that is a bit fussy about what is a valid name), where the intent is that the program repeats
// the question if the user entered an invalid name.
//
Expand All @@ -20,35 +19,64 @@
//
// 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, Error, ErrorKind, 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();
match io::stdout().flush() {
Ok(_) => (),
Err(err) => {
return Err(MyError::IOError(Error::new(
ErrorKind::Other,
format!("{:?}", err).as_str(),
)))
}
}

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

for c in input.chars()
{
if !char::is_alphabetic(c) { panic!("that's not a valid name, try again"); }
match io::stdin().lock().read_line(&mut input) {
Ok(_) => (),
Err(_) => {
return Err(MyError::IOError(Error::new(
ErrorKind::Other,
"Could not read line!",
)))
}
}
input = input.trim().to_string();

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
if input.is_empty() {
return Err(MyError::InvalidName);
}

Ok(input)
}

fn main() {
let name=get_username();
let name;
loop {
match get_username() {
Ok(val) => {
name = val;
break;
}
Err(MyError::IOError(err)) => panic!("{err}"),
_ => (),
}
}

println!("Hello {name}!")
}
32 changes: 18 additions & 14 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,10 +8,10 @@

/// 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::<i32>::new();

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] {
Expand All @@ -23,11 +23,11 @@ fn merge(a: &[i32], b: &[i32]) -> Vec<i32> {
}
}

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

dest
Expand All @@ -36,8 +36,9 @@ fn merge(a: &[i32], b: &[i32]) -> Vec<i32> {
/// 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 s1 = merge_sort(&data[..(data.len() / 2)]);
let s2 = merge_sort(&data[(data.len() / 2)..]);
merge(s1.as_slice(), s2.as_slice())
} else {
data.to_vec()
}
Expand Down Expand Up @@ -73,10 +74,13 @@ 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