assignment 6-7-8-10

This commit is contained in:
jungin.rhee
2023-08-18 16:08:13 +00:00
parent b1f1f1a5fc
commit ee1f7d0b8f
17 changed files with 48 additions and 1010 deletions

1
Cargo.lock generated
View File

@@ -227,6 +227,7 @@ dependencies = [
"num-traits",
"pest",
"pest_derive",
"rand",
"rayon",
"thiserror",
]

View File

@@ -20,3 +20,4 @@ approx = "0.5.1"
num-traits = "0.2"
ndarray = "0.15.0"
ndarray-rand = "0.14.0"
rand = "0.8.5"

View File

@@ -9,12 +9,12 @@ BASEDIR=$(dirname "$0")
source $BASEDIR/grade-utils.sh
RUNNERS=(
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
)
# Lints.
@@ -22,12 +22,12 @@ run_linters || exit 1
# Executes test for each runner.
for RUNNER in "${RUNNERS[@]}"; do
echo "Running with $RUNNER..."
echo "Running with $RUNNER..."
TESTS=("--lib assignment06_grade")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
TESTS=("--lib assignment06")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
done
exit 0

View File

@@ -9,12 +9,12 @@ BASEDIR=$(dirname "$0")
source $BASEDIR/grade-utils.sh
RUNNERS=(
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
)
# Lints.
@@ -22,12 +22,12 @@ run_linters || exit 1
# Executes test for each runner.
for RUNNER in "${RUNNERS[@]}"; do
echo "Running with $RUNNER..."
echo "Running with $RUNNER..."
TESTS=("--lib assignment07_grade")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
TESTS=("--lib assignment07")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
done
exit 0

View File

@@ -9,12 +9,12 @@ BASEDIR=$(dirname "$0")
source $BASEDIR/grade-utils.sh
RUNNERS=(
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
)
# Lints.
@@ -22,12 +22,12 @@ run_linters || exit 1
# Executes test for each runner.
for RUNNER in "${RUNNERS[@]}"; do
echo "Running with $RUNNER..."
echo "Running with $RUNNER..."
TESTS=("--lib assignment09_grade")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
TESTS=("--lib assignment09")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
done
exit 0

View File

@@ -9,12 +9,12 @@ BASEDIR=$(dirname "$0")
source $BASEDIR/grade-utils.sh
RUNNERS=(
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
"cargo"
"cargo --release"
"cargo_asan"
"cargo_asan --release"
"cargo_tsan"
"cargo_tsan --release"
)
# Lints.
@@ -22,12 +22,12 @@ run_linters || exit 1
# Executes test for each runner.
for RUNNER in "${RUNNERS[@]}"; do
echo "Running with $RUNNER..."
echo "Running with $RUNNER..."
TESTS=("--lib assignment10_grade")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
TESTS=("--lib assignment10")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi
done
exit 0

View File

@@ -24,7 +24,7 @@ run_linters || exit 1
for RUNNER in "${RUNNERS[@]}"; do
echo "Running with $RUNNER..."
TESTS=("--lib assignment11")
TESTS=("--lib assignment11_grade")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi

View File

@@ -24,7 +24,7 @@ run_linters || exit 1
for RUNNER in "${RUNNERS[@]}"; do
echo "Running with $RUNNER..."
TESTS=("--lib assignment11")
TESTS=("--lib assignment12_grade")
if [ $(run_tests) -ne 0 ]; then
exit 1
fi

View File

@@ -1,142 +0,0 @@
//! Assignment 6: Mastering advanced types (1/2).
//!
//! The primary goal of this assignment is to understand generics, traits, and lifetimes.
//!
//! You should fill out the `todo!()` placeholders in such a way that `/scripts/grade-06.sh` works fine.
//! See `assignment06_grade.rs` and `/scripts/grade-06.sh` for the test script.
use std::{collections::HashMap, fmt::Debug};
/// Semiring.
///
/// Consult <https://en.wikipedia.org/wiki/Semiring>.
pub trait Semiring: Debug + Clone + PartialEq {
/// Additive identity.
fn zero() -> Self;
/// Multiplicative identity.
fn one() -> Self;
/// Addition operation.
fn add(&self, rhs: &Self) -> Self;
/// Multiplication operation.
fn mul(&self, rhs: &Self) -> Self;
}
/// Converts integer to semiring value.
pub fn from_usize<T: Semiring>(value: usize) -> T {
let mut result = T::zero();
let one = T::one();
for _ in 0..value {
result = T::add(&result, &one);
}
result
}
impl Semiring for u64 {
fn zero() -> Self {
todo!()
}
fn one() -> Self {
todo!()
}
fn add(&self, rhs: &Self) -> Self {
todo!()
}
fn mul(&self, rhs: &Self) -> Self {
todo!()
}
}
impl Semiring for i64 {
fn zero() -> Self {
todo!()
}
fn one() -> Self {
todo!()
}
fn add(&self, rhs: &Self) -> Self {
todo!()
}
fn mul(&self, rhs: &Self) -> Self {
todo!()
}
}
impl Semiring for f64 {
fn zero() -> Self {
todo!()
}
fn one() -> Self {
todo!()
}
fn add(&self, rhs: &Self) -> Self {
todo!()
}
fn mul(&self, rhs: &Self) -> Self {
todo!()
}
}
/// Polynomials with coefficient in `C`.
///
/// For example, polynomial `x^2 + 5x + 6` is represented in `Polynomial<u64>` as follows:
///
/// ```ignore
/// Polynomial {
/// coefficients: {
/// 2: 1,
/// 1: 5,
/// 0: 6,
/// },
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Polynomial<C: Semiring> {
coefficients: HashMap<u64, C>,
}
impl<C: Semiring> Semiring for Polynomial<C> {
fn zero() -> Self {
todo!()
}
fn one() -> Self {
todo!()
}
fn add(&self, rhs: &Self) -> Self {
todo!()
}
fn mul(&self, rhs: &Self) -> Self {
todo!()
}
}
impl<C: Semiring> From<C> for Polynomial<C> {
fn from(value: C) -> Self {
todo!()
}
}
impl<C: Semiring> Polynomial<C> {
/// Constructs polynomial `x`.
pub fn x() -> Self {
todo!()
}
/// Evaluates the polynomial with the given value.
pub fn eval(&self, value: C) -> C {
todo!()
}
}

View File

@@ -1,91 +0,0 @@
#[cfg(test)]
mod test {
use super::super::assignment06::*;
fn test_polynomial<T: Semiring>() {
// x^2 + 5x + 6
let poly = Polynomial::add(
&Polynomial::add(
&Polynomial::mul(
&Polynomial::from(from_usize::<T>(1)),
&Polynomial::mul(&Polynomial::x(), &Polynomial::x()),
),
&Polynomial::mul(&Polynomial::from(from_usize::<T>(5)), &Polynomial::x()),
),
&Polynomial::from(from_usize::<T>(6)),
);
// 13^2 + 5*13 + 6
let value = poly.eval(from_usize(13));
assert_eq!(value, from_usize(13 * 13 + 5 * 13 + 6));
}
#[test]
fn test_polynomial_u64() {
test_polynomial::<u64>();
}
#[test]
fn test_polynomial_f64() {
test_polynomial::<f64>();
}
#[test]
fn test_polynomial_p_u64() {
test_polynomial::<Polynomial<u64>>();
}
#[test]
fn test_polynomial_xy() {
// (x+1)(y+2)
let poly: Polynomial<Polynomial<u64>> = Polynomial::mul(
&Polynomial::from(Polynomial::add(
&Polynomial::x(),
&Polynomial::from(from_usize::<u64>(1)),
)),
&(Polynomial::add(
&Polynomial::x(),
&Polynomial::from(Polynomial::from(from_usize::<u64>(2))),
)),
);
// poly with y = x+3
let value = poly.eval(Polynomial::add(
&Polynomial::x(),
&Polynomial::from(from_usize::<u64>(3)),
));
// x^2 + 6x + 5
let expected = Polynomial::add(
&Polynomial::add(
&Polynomial::mul(
&Polynomial::from(from_usize::<u64>(1)),
&Polynomial::mul(&Polynomial::x(), &Polynomial::x()),
),
&Polynomial::mul(&Polynomial::from(from_usize::<u64>(6)), &Polynomial::x()),
),
&Polynomial::from(from_usize::<u64>(5)),
);
assert_eq!(value, expected);
}
#[test]
fn test_zero_remove() {
// (x-1)(x+1)
let poly: Polynomial<i64> = Polynomial::mul(
&Polynomial::add(&Polynomial::x(), &Polynomial::from(-1)),
&Polynomial::add(&Polynomial::x(), &Polynomial::from(1)),
);
// (x-1)(x+1) == x^2 - 1
assert_eq!(
poly,
Polynomial::add(
&Polynomial::mul(&Polynomial::x(), &Polynomial::x()),
&Polynomial::from(-1)
)
);
}
}

View File

@@ -1,29 +0,0 @@
//! Assignment 7: Mastering advanced types (2/2).
//!
//! The primary goal of this assignment is to understand generics, traits, and lifetimes.
//!
//! You should fill out the `todo!()` placeholders in such a way that `/scripts/grade-07.sh` works fine.
//! See `assignment07_grade.rs` and `/scripts/grade-07.sh` for the test script.
struct FindIter<'s, T: Eq> {
query: &'s [T],
base: &'s [T],
curr: usize,
}
impl<T: Eq> Iterator for FindIter<'_, T> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
todo!()
}
}
/// Returns an iterator over substring query indexes in the base.
pub fn find<'s, T: Eq>(query: &'s [T], base: &'s [T]) -> impl 's + Iterator<Item = usize> {
FindIter {
query,
base,
curr: 0,
}
}

View File

@@ -1,44 +0,0 @@
#[cfg(test)]
mod test {
use super::super::assignment07::*;
#[test]
fn test_find() {
assert_eq!(
find("abc".as_bytes(), "abcdabcd".as_bytes()).collect::<Vec<usize>>(),
vec![0, 4]
);
assert_eq!(
find("aaba".as_bytes(), "aabaacaadaabaaba".as_bytes()).collect::<Vec<usize>>(),
vec![0, 9, 12]
);
assert_eq!(
find("ababac".as_bytes(), "abababcabababcabababc".as_bytes()).collect::<Vec<usize>>(),
vec![]
);
assert_eq!(
find("ababc".as_bytes(), "abc".as_bytes()).collect::<Vec<usize>>(),
vec![]
);
}
#[test]
fn test_find_usize() {
assert_eq!(
find(&[1, 2, 3], &[1, 2, 3, 4, 1, 2, 3, 4]).collect::<Vec<usize>>(),
vec![0, 4]
);
assert_eq!(
find(
&[5, 5, 7, 5],
&[5, 5, 7, 5, 5, 8, 5, 5, 9, 5, 5, 7, 5, 5, 7, 5]
)
.collect::<Vec<usize>>(),
vec![0, 9, 12]
);
}
}

View File

@@ -1,174 +0,0 @@
//! Assignment 9: Iterators (1/2).
//!
//! The primary goal of this assignment is to get used to iterators.
//!
//! You should fill out the `todo!()` placeholders in such a way that `/scripts/grade-09.sh` works fine.
//! See `assignment09_grade.rs` and `/scripts/grade-09.sh` for the test script.
use std::collections::HashMap;
use itertools::*;
/// Returns whether the given sequence is a fibonacci sequence starts from the given sequence's first two terms.
///
/// Returns `true` if the length of sequence is less or equal than 2.
///
/// # Exmample
///
/// ```
/// use cs220::assignments::assignment09::is_fibonacci;
///
/// assert_eq!(is_fibonacci([1, 1, 2, 3, 5, 8, 13].into_iter()), true);
/// assert_eq!(is_fibonacci([1, 1, 2, 3, 5, 8, 14].into_iter()), false);
/// ```
pub fn is_fibonacci(inner: impl Iterator<Item = i64>) -> bool {
todo!()
}
/// Returns the sum of `f(v)` for all element `v` the given array.
///
/// # Exmaple
///
/// ```
/// use cs220::assignments::assignment09::sigma;
///
/// assert_eq!(sigma([1, 2].into_iter(), |x| x + 2), 7);
/// assert_eq!(sigma([1, 2].into_iter(), |x| x * 4), 12);
/// ```
pub fn sigma<T, F: Fn(T) -> i64>(inner: impl Iterator<Item = T>, f: F) -> i64 {
todo!()
}
/// Alternate elements from three iterators until they have run out.
///
/// You can assume that the number of elements of three iterators are same.
///
/// # Example
///
/// ```
/// use cs220::assignments::assignment09::interleave3;
///
/// assert_eq!(
/// interleave3([1, 2].into_iter(), [3, 4].into_iter(), [5, 6].into_iter()),
/// vec![1, 3, 5, 2, 4, 6]
/// );
/// ```
pub fn interleave3<T>(
list1: impl Iterator<Item = T>,
list2: impl Iterator<Item = T>,
list3: impl Iterator<Item = T>,
) -> Vec<T> {
todo!()
}
/// Returns mean of k smallest value's mean.
///
/// # Example
///
/// ```
/// use cs220::assignments::assignment09::k_smallest_mean;
///
/// assert_eq!(
/// k_smallest_mean(vec![1, 3, 2].into_iter(), 2),
/// ((1 + 2) as f64 / 2.0)
/// );
/// assert_eq!(
/// k_smallest_mean(vec![7, 5, 3, 6].into_iter(), 3),
/// ((3 + 5 + 6) as f64 / 3.0)
/// );
/// ```
pub fn k_smallest_mean(inner: impl Iterator<Item = i64>, k: usize) -> f64 {
todo!()
}
/// Returns mean for each class.
///
/// # Exmaple
///
/// ```
/// use cs220::assignments::assignment09::calculate_mean;
///
/// assert_eq!(
/// calculate_mean(
/// [
/// ("CS100".to_string(), 60),
/// ("CS200".to_string(), 60),
/// ("CS200".to_string(), 80),
/// ("CS300".to_string(), 100),
/// ]
/// .into_iter()
/// ),
/// [
/// ("CS100".to_string(), 60.0),
/// ("CS200".to_string(), 70.0),
/// ("CS300".to_string(), 100.0)
/// ]
/// .into_iter()
/// .collect()
/// );
/// ```
pub fn calculate_mean(inner: impl Iterator<Item = (String, i64)>) -> HashMap<String, f64> {
todo!()
}
/// Among the cartesian product of input vectors, return the number of sets whose sum equals `n`.
///
/// # Example
///
/// The cartesian product of [1, 2, 3] and [2, 3] are:
/// [1, 2], [1, 3], [2, 2], [2, 3], [3, 2], [3, 3].
///
/// Among these sets, the number of sets whose sum is 4 is 2, which is [1, 3] and [2, 2].
///
/// ```
/// use cs220::assignments::assignment09::sum_is_n;
///
/// assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 3), 1);
/// assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 4), 2);
/// assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 5), 2);
/// assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 6), 1);
/// assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 2), 0);
/// ```
pub fn sum_is_n(inner: Vec<Vec<i64>>, n: i64) -> usize {
todo!()
}
/// Returns a new vector that contains the item that appears `n` times in the input vector in increasing order.
///
/// # Example
///
/// ```
/// use cs220::assignments::assignment09::find_count_n;
///
/// assert_eq!(find_count_n(vec![1, 2], 1), vec![1, 2]);
/// assert_eq!(find_count_n(vec![1, 3, 3], 1), vec![1]);
/// assert_eq!(find_count_n(vec![1, 3, 3], 2), vec![3]);
/// assert_eq!(find_count_n(vec![1, 2, 3, 4, 4], 1), vec![1, 2, 3]);
/// ```
pub fn find_count_n(inner: Vec<usize>, n: usize) -> Vec<usize> {
todo!()
}
/// Return the position of the median element in the vector.
///
/// For a data set `x` of `n` elements, the median can be defined as follows:
///
/// - If `n` is odd, the median is `(n+1)/2`-th smallest element of `x`.
/// - If `n` is even, the median is `(n/2)+1`-th smallest element of `x`.
///
/// Please following these rules:
///
/// - If the list is empty, returns `None`.
/// - If several elements are equally median, the position of the first of them is returned.
///
/// # Exmaple
///
/// ```
/// use cs220::assignments::assignment09::position_median;
///
/// assert_eq!(position_median(vec![1, 3, 3, 6, 7, 8, 9]), Some(3));
/// assert_eq!(position_median(vec![1, 3, 3, 3]), Some(1));
/// ```
pub fn position_median<T: Ord>(inner: Vec<T>) -> Option<usize> {
todo!()
}

View File

@@ -1,203 +0,0 @@
#[cfg(test)]
mod test {
use super::super::assignment09::*;
#[test]
fn test_is_fibonacci() {
assert!(is_fibonacci([1, 1, 2, 3, 5, 8, 13].into_iter()));
assert!(!is_fibonacci([1, 1, 2, 3, 5, 8, 14].into_iter()));
assert!(is_fibonacci([2, 4, 6, 10, 16, 26].into_iter()));
assert!(is_fibonacci([4, 9, 13, 22, 35].into_iter()));
assert!(is_fibonacci([0, 0, 0, 0, 0].into_iter()));
assert!(is_fibonacci([1, 1].into_iter()));
assert!(is_fibonacci([1].into_iter()));
assert!(is_fibonacci([].into_iter()));
assert!(!is_fibonacci([1, 1, 2, 2, 3, 3].into_iter()));
assert!(!is_fibonacci([0, 0, 0, 0, 1].into_iter()));
assert!(!is_fibonacci([1, 1, 1, 1].into_iter()));
assert!(!is_fibonacci([4, 3, 2, 1].into_iter()));
}
#[test]
fn test_sigma() {
assert_eq!(sigma([].into_iter(), |x: i64| x * 2), 0);
assert_eq!(sigma([1].into_iter(), |x| x * 3), 3);
assert_eq!(sigma([1, 2].into_iter(), |x| x + 2), 7);
assert_eq!(sigma([1, 2].into_iter(), |x| x * 4), 12);
assert_eq!(sigma([1, 2, 3].into_iter(), |x| x * 5), 30);
assert_eq!(
sigma([-1.2, 3.0, 4.2, 5.8].into_iter(), |x: f64| x.floor() as i64),
10
);
assert_eq!(
sigma([-1.2, 3.0, 4.2, 5.8].into_iter(), |x: f64| x.ceil() as i64),
13
);
assert_eq!(
sigma([-1.2, 3.0, 4.2, 5.8].into_iter(), |x: f64| x.round() as i64),
12
);
assert_eq!(
sigma(["Hello,", "World!"].into_iter(), |x| x.len() as i64),
12
);
}
#[test]
fn test_interleave3() {
assert_eq!(
interleave3([1, 2].into_iter(), [3, 4].into_iter(), [5, 6].into_iter()),
vec![1, 3, 5, 2, 4, 6]
);
assert_eq!(
interleave3(
[1, 2, 3].into_iter(),
[4, 5, 6].into_iter(),
[7, 8, 9].into_iter()
),
vec![1, 4, 7, 2, 5, 8, 3, 6, 9]
);
assert_eq!(
interleave3(
["a", "b", "c"].into_iter(),
["d", "e", "f"].into_iter(),
["g", "h", "i"].into_iter()
)
.into_iter()
.collect::<String>(),
"adgbehcfi"
);
}
#[test]
fn test_k_smallest_man() {
assert_eq!(
k_smallest_mean(vec![1, 3, 2].into_iter(), 2),
((1 + 2) as f64 / 2.0)
);
assert_eq!(
k_smallest_mean(vec![5, 3, 7, 7].into_iter(), 2),
((3 + 5) as f64 / 2.0)
);
assert_eq!(
k_smallest_mean(vec![7, 5, 3, 6].into_iter(), 3),
((3 + 5 + 6) as f64 / 3.0)
);
assert_eq!(
k_smallest_mean(vec![1, 3, 2, 4, 4, 5, 6].into_iter(), 3),
((1 + 2 + 3) as f64 / 3.0)
);
assert_eq!(k_smallest_mean(vec![].into_iter(), 3), (0 as f64 / 3.0));
assert_eq!(
k_smallest_mean(
vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5].into_iter(),
5
),
((1 + 2 + 3 + 4) as f64 / 5.0)
);
}
#[test]
fn test_calculate_mean() {
assert_eq!(
calculate_mean(
[
("CS100".to_string(), 60),
("CS200".to_string(), 60),
("CS200".to_string(), 80),
("CS300".to_string(), 100),
]
.into_iter()
),
[
("CS100".to_string(), 60.0),
("CS200".to_string(), 70.0),
("CS300".to_string(), 100.0)
]
.into_iter()
.collect()
);
assert_eq!(
calculate_mean(
[
("CS220".to_string(), 60),
("CS420".to_string(), 60),
("CS220".to_string(), 80),
("CS431".to_string(), 60),
("CS420".to_string(), 80),
("CS220".to_string(), 100)
]
.into_iter()
),
[
("CS220".to_string(), 80.0),
("CS420".to_string(), 70.0),
("CS431".to_string(), 60.0)
]
.into_iter()
.collect()
)
}
#[test]
fn test_sum_is_n() {
assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 3), 1);
assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 4), 2);
assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 5), 2);
assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 6), 1);
assert_eq!(sum_is_n(vec![vec![1, 2, 3], vec![2, 3]], 2), 0);
assert_eq!(sum_is_n(vec![(1..100).collect()], 50), 1);
assert_eq!(
sum_is_n(vec![(1..10).collect(), (1..10).rev().collect()], 10),
9
);
assert_eq!(
sum_is_n(
vec![
(0..10).map(|x| x * 2 + 1).collect(),
(0..20).map(|x| x * 3).collect(),
(0..30).map(|x| x * 5 + 2).collect()
],
53
),
30
);
}
// find_count_n
#[test]
fn test_find_count_n() {
assert_eq!(find_count_n(vec![], 1), vec![]);
assert_eq!(find_count_n(vec![1, 2], 1), vec![1, 2]);
assert_eq!(find_count_n(vec![1, 3, 3], 1), vec![1]);
assert_eq!(find_count_n(vec![1, 3, 3], 2), vec![3]);
assert_eq!(find_count_n(vec![1, 2, 3, 4, 4], 1), vec![1, 2, 3]);
assert_eq!(find_count_n(vec![1, 3, 2, 3, 2, 3], 3), vec![3]);
assert_eq!(find_count_n(vec![1, 2, 2, 3, 3, 4], 2), vec![2, 3]);
assert_eq!(find_count_n(vec![1, 3, 2, 2, 3], 2), vec![2, 3]);
assert_eq!(find_count_n(vec![0, 2, 2, 4, 3], 0), vec![]);
assert_eq!(find_count_n(vec![1, 1, 1, 2, 2], 1), vec![]);
}
#[test]
fn test_position_median() {
assert_eq!(position_median(Vec::<usize>::new()), None);
assert_eq!(position_median(vec![3]), Some(0));
assert_eq!(position_median(vec![3, 3]), Some(0));
assert_eq!(position_median(vec![3, 3, 3]), Some(0));
assert_eq!(position_median(vec![1, 3, 3, 3]), Some(1));
assert_eq!(position_median(vec![3, 1, 3, 3]), Some(0));
assert_eq!(position_median(vec![3, 1, 5, 3]), Some(0));
assert_eq!(position_median(vec![1, 3, 3, 6, 7, 8, 9]), Some(3));
assert_eq!(position_median(vec![1, 2, 3, 4, 5, 6, 8, 9]), Some(4));
}
}

View File

@@ -1,119 +0,0 @@
//! Assignment 10: Iterators (2/2).
//!
//! The primary goal of this assignment is to get used to iterators.
//!
//! You should fill out the `todo!()` placeholders in such a way that `/scripts/grade-10.sh` works fine.
//! See `assignment10_grade.rs` and `/scripts/grade-10.sh` for the test script.
use itertools::*;
/// Returns the pairs of `(i, j)` where `i < j` and `inner[i] > inner[j]` in increasing order.
///
/// For example, the inversions of `[3, 5, 1, 2, 4]` is `[(0, 2), (0, 3), (1, 2), (1, 3), (1, 4)]` because as follows:
///
/// - `0 < 2`, `inner[0] = 3 > 1 = inner[2]`
/// - `0 < 3`, `inner[0] = 3 > 2 = inner[3]`
/// - `1 < 2`, `inner[1] = 5 > 1 = inner[2]`
/// - `1 < 3`, `inner[1] = 5 > 2 = inner[3]`
/// - `1 < 4`, `inner[1] = 5 > 4 = inner[4]`
///
/// Consult <https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)> for more details of inversion.
pub fn inversion<T: Ord>(inner: Vec<T>) -> Vec<(usize, usize)> {
todo!()
}
/// Represents a node of tree data structure.
///
/// Consult <https://en.wikipedia.org/wiki/Tree_(data_structure)> for more details on tree data structure.
#[derive(Debug)]
pub enum Node<T> {
/// Non-leaf node
///
/// It contains `(the name of node, list of child nodes)`.
NonLeaf((T, Vec<Node<T>>)),
/// Leaf node
///
/// It contains the name of node.
Leaf(T),
}
/// Traverses the tree in preorder.
///
/// The algorithm for preorder traversal is as follows:
///
/// 1. Visit the root.
/// 2. If the root is a leaf node, end the traverse.
/// 3. If the root is a non-leaf node, traverse each subtree from the child nodes.
///
/// For example, the result of preorder traversal for the following tree
///
/// ```text
/// 1
/// /|\
/// 2 3 4
/// /| /|\
/// 5 6 7 8 9
/// ```
///
/// which can be represented as
///
/// ```ignore
/// Node::NonLeaf((
/// 1,
/// vec![
/// Node::NonLeaf((2, vec![Node::Leaf(5), Node::Leaf(6)])),
/// Node::Leaf(3),
/// Node::NonLeaf((4, vec![Node::Leaf(7), Node::Leaf(8), Node::Leaf(9)])),
/// ]
/// ))
/// ```
///
/// is `1 -> 2 -> 5 -> 6 -> 3 -> 4 -> 7 -> 8 -> 9`.
pub fn traverse_preorder<T>(root: Node<T>) -> Vec<T> {
todo!()
}
/// File
#[derive(Debug)]
pub enum File {
/// Directory
///
/// It contains `(name of directory, list of files under the directory)`
///
/// The size of a directory is the sum of the sizes of its sub-files.
Directory(String, Vec<File>),
/// Data
///
/// It contains `(name of data, size of data)`
Data(String, usize),
}
/// Given a file, summarize all subfiles and sizes in ascending order of size.
///
/// - Its behaviour is the same as the `du | sort -h` command on Linux.
/// - If the file size is the same, sort it by name.
/// - Assume that there are no duplicate file names.
///
/// # Example
///
/// Input:
///
/// ```txt
/// root (Directory)
/// |
/// |__a (Directory)
/// | |__a1 (Data, size: 1)
/// | |__a2 (Data, size: 3)
/// |
/// |__b (Directory)
/// | |__b1 (Data, size: 3)
/// | |__b2 (Data, size: 15)
/// |
/// |__c (Data, size: 8)
/// ```
///
/// Output: `[("a1", 1), ("a2", 3), ("b1", 3), ("a", 4), ("c", 8), ("b2", 15), ("b", 18), ("root", 30)]`
pub fn du_sort(root: &File) -> Vec<(&str, usize)> {
todo!()
}

View File

@@ -1,158 +0,0 @@
#[cfg(test)]
mod test {
use super::super::assignment10::*;
#[test]
fn test_inversion() {
assert_eq!(inversion(vec![3, 5, 4]), vec![(1, 2)]);
assert_eq!(inversion(vec!["c", "a", "b", "d"]), vec![(0, 1), (0, 2)]);
assert_eq!(
inversion(vec![2, 5, 4, 6, 3, 1]),
vec![
(0, 5),
(1, 2),
(1, 4),
(1, 5),
(2, 4),
(2, 5),
(3, 4),
(3, 5),
(4, 5)
]
);
}
#[test]
fn test_traverse_preorder() {
let root = Node::NonLeaf((
1,
vec![
Node::NonLeaf((2, vec![Node::Leaf(5), Node::Leaf(6)])),
Node::Leaf(3),
Node::NonLeaf((4, vec![Node::Leaf(7), Node::Leaf(8), Node::Leaf(9)])),
],
));
assert_eq!(traverse_preorder(root), vec![1, 2, 5, 6, 3, 4, 7, 8, 9]);
}
#[test]
fn test_du_sort() {
let rootfile = File::Directory(
"root".to_string(),
vec![
File::Directory(
"a".to_string(),
vec![
File::Data("a1".to_string(), 1),
File::Data("a2".to_string(), 3),
],
),
File::Directory(
"b".to_string(),
vec![
File::Data("b1".to_string(), 3),
File::Data("b2".to_string(), 15),
],
),
File::Data("c".to_string(), 8),
],
);
assert_eq!(
du_sort(&rootfile),
vec![
("a1", 1),
("a2", 3),
("b1", 3),
("a", 4),
("c", 8),
("b2", 15),
("b", 18),
("root", 1 + 3 + 3 + 15 + 8)
]
);
let rootfile = File::Directory(
"root".to_string(),
vec![
File::Directory(
"b".to_string(),
vec![
File::Data("b1".to_string(), 3),
File::Data("b2".to_string(), 15),
],
),
File::Data("c".to_string(), 8),
File::Directory(
"a".to_string(),
vec![
File::Data("a1".to_string(), 1),
File::Data("a2".to_string(), 3),
],
),
],
);
assert_eq!(
du_sort(&rootfile),
vec![
("a1", 1),
("a2", 3),
("b1", 3),
("a", 4),
("c", 8),
("b2", 15),
("b", 18),
("root", 1 + 3 + 3 + 15 + 8)
]
);
let rootfile = File::Directory(
"root".to_string(),
vec![
File::Directory(
"a".to_string(),
vec![
File::Data("a1".to_string(), 1),
File::Data("a2".to_string(), 3),
File::Directory(
"a3".to_string(),
vec![
File::Data("a31".to_string(), 1),
File::Data("a32".to_string(), 3),
File::Data("a33".to_string(), 6),
],
),
],
),
File::Directory(
"b".to_string(),
vec![
File::Data("b1".to_string(), 3),
File::Data("b2".to_string(), 15),
],
),
File::Data("c".to_string(), 16),
],
);
assert_eq!(
du_sort(&rootfile),
vec![
("a1", 1),
("a31", 1),
("a2", 3),
("a32", 3),
("b1", 3),
("a33", 6),
("a3", 10),
("a", 14),
("b2", 15),
("c", 16),
("b", 18),
("root", 48)
]
);
}
}

View File

@@ -15,15 +15,11 @@ mod assignment03_grade;
pub mod assignment04;
mod assignment04_grade;
pub mod assignment06;
mod assignment06_grade;
pub mod assignment07;
mod assignment07_grade;
pub mod assignment08;
mod assignment08_grade;
pub mod assignment09;
mod assignment09_grade;
pub mod assignment10;
mod assignment10_grade;
pub mod assignment11;
pub mod assignment12;
pub mod assignment13;