Skip to content

Commit

Permalink
finish all
Browse files Browse the repository at this point in the history
  • Loading branch information
陈羿华 committed Dec 16, 2024
1 parent bcf7281 commit 4c21bdf
Show file tree
Hide file tree
Showing 24 changed files with 416 additions and 56 deletions.
58 changes: 50 additions & 8 deletions exercises/algorithm/algorithm1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
single linked list merge
This problem requires you to merge two ordered singly linked lists into one ordered singly linked list
*/
// I AM NOT DONE


use std::fmt::{self, Display, Formatter};
use std::ptr::NonNull;
use std::vec::*;
use std::{result, vec::*};

#[derive(Debug)]
struct Node<T> {
Expand All @@ -29,13 +29,13 @@ struct LinkedList<T> {
end: Option<NonNull<Node<T>>>,
}

impl<T> Default for LinkedList<T> {
impl<T:Ord+Clone> Default for LinkedList<T> {
fn default() -> Self {
Self::new()
}
}

impl<T> LinkedList<T> {
impl<T: Ord+Clone> LinkedList<T> {
pub fn new() -> Self {
Self {
length: 0,
Expand Down Expand Up @@ -72,11 +72,53 @@ impl<T> LinkedList<T> {
pub fn merge(list_a:LinkedList<T>,list_b:LinkedList<T>) -> Self
{
//TODO
Self {
length: 0,
start: None,
end: None,
// Self {
// length: 0,
// start: None,
// end: None,
// }
let mut list_c = LinkedList::<T>::new();
let mut ptr_a = list_a.start;
let mut ptr_b = list_b.start;
while ptr_a.is_some() && ptr_b.is_some() {
let val_a = unsafe { &(*ptr_a.unwrap().as_ptr()).val };
let val_b = unsafe { &(*ptr_b.unwrap().as_ptr()).val };
let result = val_a.cmp(val_b);
// if val_a.cmp(val_b) {
// list_c.add(val_a);
// ptr_a = unsafe { ptr_a.unwrap().as_ref().next };
// } else {
// list_c.add(val_b);
// ptr_b = unsafe { ptr_b.unwrap().as_ref().next };
// }
match result {
std::cmp::Ordering::Less => {
list_c.add(val_a.clone());
ptr_a = unsafe { ptr_a.unwrap().as_ref().next };
}
std::cmp::Ordering::Greater => {
list_c.add(val_b.clone());
ptr_b = unsafe { ptr_b.unwrap().as_ref().next };
}
std::cmp::Ordering::Equal => {
list_c.add(val_a.clone());
list_c.add(val_b.clone());
ptr_a = unsafe { ptr_a.unwrap().as_ref().next };
ptr_b = unsafe { ptr_b.unwrap().as_ref().next };
}
}
}
while ptr_a.is_some() {
let val_a = unsafe { ptr_a.unwrap().as_ref().val.clone() };
list_c.add(val_a);
ptr_a = unsafe { ptr_a.unwrap().as_ref().next };
}
while ptr_b.is_some() {
let val_b = unsafe { ptr_b.unwrap().as_ref().val.clone() };
list_c.add(val_b);
ptr_b = unsafe { ptr_b.unwrap().as_ref().next };
}
list_c
}
}

Expand Down
32 changes: 30 additions & 2 deletions exercises/algorithm/algorithm10.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
graph
This problem requires you to implement a basic graph functio
*/
// I AM NOT DONE


use std::collections::{HashMap, HashSet};
use std::fmt;
Expand Down Expand Up @@ -30,6 +30,21 @@ impl Graph for UndirectedGraph {
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (from_node, to_node, weight) = edge;
if !self.contains(from_node) {
self.add_node(from_node);
}
if !self.contains(to_node) {
self.add_node(to_node);
}
self.adjacency_table_mutable()
.get_mut(from_node)
.unwrap()
.push((to_node.to_string(), weight));
self.adjacency_table_mutable()
.get_mut(to_node)
.unwrap()
.push((from_node.to_string(), weight));
}
}
pub trait Graph {
Expand All @@ -38,10 +53,23 @@ pub trait Graph {
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
fn add_node(&mut self, node: &str) -> bool {
//TODO
true
// true
self.adjacency_table_mutable().insert(node.to_string(), Vec::new());
true
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (from_node, to_node, weight) = edge;
if !self.contains(from_node) {
self.add_node(from_node);
}
if !self.contains(to_node) {
self.add_node(to_node);
}
self.adjacency_table_mutable()
.get_mut(from_node)
.unwrap()
.push((to_node.to_string(), weight));
}
fn contains(&self, node: &str) -> bool {
self.adjacency_table().get(node).is_some()
Expand Down
14 changes: 13 additions & 1 deletion exercises/algorithm/algorithm2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
double linked list reverse
This problem requires you to reverse a doubly linked list
*/
// I AM NOT DONE

use std::fmt::{self, Display, Formatter};
use std::ptr::NonNull;
Expand Down Expand Up @@ -74,6 +73,19 @@ impl<T> LinkedList<T> {
}
pub fn reverse(&mut self){
// TODO
let mut current = self.start;
let mut temp = None;
while current.is_some() {
let mut current_node = unsafe { current.unwrap().as_mut() };
temp = current_node.prev;
current_node.prev = current_node.next;
current_node.next = temp;
temp = current;
current = current_node.prev;
}
if temp.is_some() {
self.start = temp;
}
}
}

Expand Down
16 changes: 14 additions & 2 deletions exercises/algorithm/algorithm3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,22 @@
This problem requires you to implement a sorting algorithm
you can use bubble sorting, insertion sorting, heap sorting, etc.
*/
// I AM NOT DONE

fn sort<T>(array: &mut [T]){
fn sort<T: Ord>(array: &mut [T]){
//TODO
let mut n = array.len();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..n {
if array[i - 1] > array[i] {
array.swap(i - 1, i);
swapped = true;
}
}
n -= 1;
}

}
#[cfg(test)]
mod tests {
Expand Down
52 changes: 50 additions & 2 deletions exercises/algorithm/algorithm4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This problem requires you to implement a basic interface for a binary tree
*/

//I AM NOT DONE

use std::cmp::Ordering;
use std::fmt::Debug;

Expand Down Expand Up @@ -51,12 +51,42 @@ where
// Insert a value into the BST
fn insert(&mut self, value: T) {
//TODO
// let new_node = TreeNode::new(value);
match self.root {
Some(ref mut node) => {
if value < node.value {
if node.left.is_none() {
node.left = Some(Box::new(TreeNode::new(value)));
} else {
node.left.as_mut().unwrap().insert(value);
}
} else if value > node.value {
if node.right.is_none() {
node.right = Some(Box::new(TreeNode::new(value)));
} else {
node.right.as_mut().unwrap().insert(value);
}
}
},
None => {
self.root = Some(Box::new(TreeNode::new(value)));
},
}
}

// Search for a value in the BST
fn search(&self, value: T) -> bool {
//TODO
true
// true
let mut current = &self.root;
while let Some(node) = current {
match value.cmp(&node.value) {
Ordering::Less => current = &node.left,
Ordering::Greater => current = &node.right,
Ordering::Equal => return true,
}
}
false
}
}

Expand All @@ -67,6 +97,24 @@ where
// Insert a node into the tree
fn insert(&mut self, value: T) {
//TODO

match value.cmp(&self.value) {
Ordering::Less => {
if self.left.is_none() {
self.left = Some(Box::new(TreeNode::new(value)));
} else {
self.left.as_mut().unwrap().insert(value);
}
},
Ordering::Greater => {
if self.right.is_none() {
self.right = Some(Box::new(TreeNode::new(value)));
} else {
self.right.as_mut().unwrap().insert(value);
}
},
Ordering::Equal => (),
}
}
}

Expand Down
19 changes: 18 additions & 1 deletion exercises/algorithm/algorithm5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This problem requires you to implement a basic BFS algorithm
*/

//I AM NOT DONE

use std::collections::VecDeque;

// Define a graph
Expand Down Expand Up @@ -31,6 +31,23 @@ impl Graph {
//TODO

let mut visit_order = vec![];
let mut visited = vec![false; self.adj.len()];
let mut queue = VecDeque::new();
queue.push_back(start);
visited[start] = true;

while !queue.is_empty() {
let node = queue.pop_front().unwrap();
visit_order.push(node);

for &neighbour in &self.adj[node] {
if !visited[neighbour] {
queue.push_back(neighbour);
visited[neighbour] = true;
}
}
}

visit_order
}
}
Expand Down
11 changes: 10 additions & 1 deletion exercises/algorithm/algorithm6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This problem requires you to implement a basic DFS traversal
*/

// I AM NOT DONE

use std::collections::HashSet;

struct Graph {
Expand All @@ -24,6 +24,15 @@ impl Graph {

fn dfs_util(&self, v: usize, visited: &mut HashSet<usize>, visit_order: &mut Vec<usize>) {
//TODO
visited.insert(v);
visit_order.push(v);

for &neighbour in &self.adj[v] {
if !visited.contains(&neighbour) {
self.dfs_util(neighbour, visited, visit_order);
}
}

}

// Perform a depth-first search on the graph, return the order of visited nodes
Expand Down
31 changes: 28 additions & 3 deletions exercises/algorithm/algorithm7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This question requires you to use a stack to achieve a bracket match
*/

// I AM NOT DONE

#[derive(Debug)]
struct Stack<T> {
size: usize,
Expand Down Expand Up @@ -32,7 +32,12 @@ impl<T> Stack<T> {
}
fn pop(&mut self) -> Option<T> {
// TODO
None
// None
if 0 == self.size {
return None;
}
self.size -= 1;
self.data.pop()
}
fn peek(&self) -> Option<&T> {
if 0 == self.size {
Expand Down Expand Up @@ -102,7 +107,27 @@ impl<'a, T> Iterator for IterMut<'a, T> {
fn bracket_match(bracket: &str) -> bool
{
//TODO
true
// true
let mut stack = Stack::new();
for c in bracket.chars() {
match c {
'(' => stack.push(')'),
'{' => stack.push('}'),
'[' => stack.push(']'),
')' | '}' | ']' => {
if let Some(top) = stack.pop() {
if top != c {
return false;
}
}
else {
return false;
}
},
_ => (),
}
}
stack.is_empty()
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 4c21bdf

Please sign in to comment.