Skip to content

Commit

Permalink
rustlings 111 done
Browse files Browse the repository at this point in the history
  • Loading branch information
ubuntu committed Jul 13, 2024
1 parent b0d269d commit f9ee537
Show file tree
Hide file tree
Showing 13 changed files with 263 additions and 64 deletions.
70 changes: 64 additions & 6 deletions exercises/algorithm/algorithm1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
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;
Expand Down Expand Up @@ -69,14 +68,73 @@ impl<T> LinkedList<T> {
},
}
}
}

// 递归
/*
impl<T: PartialOrd + Copy> LinkedList<T> {
pub fn merge(list_a:LinkedList<T>,list_b:LinkedList<T>) -> Self
{
//TODO
Self {
length: 0,
start: None,
end: None,
if list_a.length == 0 {
return list_b;
}
if list_b.length == 0 {
return list_a;
}
let a_node = list_a.start;
let b_node = list_b.start;
let mut ans = LinkedList::<T>::new();
let a_val = unsafe { (*a_node.unwrap().as_ptr()).val };
let b_val = unsafe { (*b_node.unwrap().as_ptr()).val };
if a_val < b_val {
ans.add(a_val);
let mut list_a = list_a;
list_a.length -= 1;
list_a.start = unsafe { (*a_node.unwrap().as_ptr()).next };
let list_c = Self::merge(list_a, list_b);
ans.length = list_c.length + 1;
unsafe { (*ans.start.unwrap().as_ptr()).next = list_c.start };
} else {
ans.add(b_val);
let mut list_b = list_b;
list_b.length -= 1;
list_b.start = unsafe { (*b_node.unwrap().as_ptr()).next };
let list_c = Self::merge(list_a, list_b);
ans.length = list_c.length + 1;
unsafe { (*ans.start.unwrap().as_ptr()).next = list_c.start };
}
ans
}
}
*/

// 迭代
impl<T: PartialOrd + Copy> LinkedList<T> {
pub fn merge(list_a:LinkedList<T>,list_b:LinkedList<T>) -> Self
{
let mut a_node = list_a.start;
let mut b_node = list_b.start;
let mut ans = LinkedList::<T>::new();
while a_node.is_some() && b_node.is_some() {
let a_val = unsafe { a_node.unwrap().as_ref().val };
let b_val = unsafe { b_node.unwrap().as_ref().val };
if (a_val < b_val) {
ans.add(a_val);
a_node = unsafe { a_node.unwrap().as_ref().next };
} else {
ans.add(b_val);
b_node = unsafe { b_node.unwrap().as_ref().next };
}
}
if b_node.is_some() {
std::mem::swap(&mut a_node, &mut b_node);
}
while a_node.is_some() {
let a_val = unsafe { a_node.unwrap().as_ref().val };
ans.add(a_val);
a_node = unsafe { a_node.unwrap().as_ref().next };
}
ans
}
}

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

use std::collections::{HashMap, HashSet};
use std::fmt;
Expand All @@ -29,20 +28,26 @@ impl Graph for UndirectedGraph {
&self.adjacency_table
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (from, to, w) = edge;
self.add_node(from);
self.add_node(to);
let adj_tab = self.adjacency_table_mutable();
adj_tab.get_mut(from).unwrap().push((to.to_string(), w));
adj_tab.get_mut(to).unwrap().push((from.to_string(), w))
}
}
pub trait Graph {
fn new() -> Self;
fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>>;
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
fn add_node(&mut self, node: &str) -> bool {
//TODO
true
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
if !self.contains(node) {
let adj_tab = self.adjacency_table_mutable();
adj_tab.insert(node.to_string(), Vec::new());
}
true
}
fn add_edge(&mut self, edge: (&str, &str, i32));
fn contains(&self, node: &str) -> bool {
self.adjacency_table().get(node).is_some()
}
Expand Down
20 changes: 17 additions & 3 deletions 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 @@ -72,8 +71,23 @@ impl<T> LinkedList<T> {
},
}
}
pub fn reverse(&mut self){
// TODO
pub fn reverse(&mut self) {
if self.length == 0 {
return;
}

let mut node = self.end;
let mut prev = unsafe { node.unwrap().as_ref().prev };
unsafe { (*node.unwrap().as_ptr()).prev = None; }
while prev.is_some() {
unsafe { (*node.unwrap().as_ptr()).next = prev; };
let mut pprev = unsafe { prev.unwrap().as_ref().prev };
unsafe { (*prev.unwrap().as_ptr()).prev = node; };
node = prev;
prev = pprev;
}
unsafe { (*node.unwrap().as_ptr()).next = None };
std::mem::swap(&mut self.start, &mut self.end);
}
}

Expand Down
13 changes: 10 additions & 3 deletions exercises/algorithm/algorithm3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
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]){
//TODO
fn sort<T: PartialOrd + Copy>(array: &mut [T]){
//bubble sorting
let n = array.len();
for i in 0..n {
for j in 0..n-1-i {
if array[j] > array[j + 1] {
array.swap(j, j + 1);
}
}
}
}
#[cfg(test)]
mod tests {
Expand Down
52 changes: 37 additions & 15 deletions exercises/algorithm/algorithm4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
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 @@ -37,8 +36,37 @@ where
right: None,
}
}

// Insert a value into the tree
fn insert(&mut self, value: T) {
match &self.value.cmp(&value) {
Ordering::Less => {
match &mut self.left {
Some(node) => node.insert(value),
_ => self.left = Some(Box::new(TreeNode::<T>::new(value))),
}
},
Ordering::Greater => {
match &mut self.right {
Some(node) => node.insert(value),
_ => self.right = Some(Box::new(TreeNode::<T>::new(value))),
}
},
_ => {},
}
}

// Search for a value in the tree
fn search(&self, value: T) -> bool {
match &self.value.cmp(&value) {
Ordering::Less => self.left.as_ref().map_or(false, |n| n.search(value)),
Ordering::Greater => self.right.as_ref().map_or(false, |n| n.search(value)),
_ => true,
}
}
}


impl<T> BinarySearchTree<T>
where
T: Ord,
Expand All @@ -50,27 +78,21 @@ where

// Insert a value into the BST
fn insert(&mut self, value: T) {
//TODO
match &mut self.root {
Some(root) => root.insert(value),
_ => self.root = Some(Box::new(TreeNode::<T>::new(value))),
}
}

// Search for a value in the BST
fn search(&self, value: T) -> bool {
//TODO
true
}
}

impl<T> TreeNode<T>
where
T: Ord,
{
// Insert a node into the tree
fn insert(&mut self, value: T) {
//TODO
match &self.root {
Some(root) => root.search(value),
_ => false,
}
}
}


#[cfg(test)]
mod tests {
use super::*;
Expand Down
22 changes: 17 additions & 5 deletions exercises/algorithm/algorithm5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
This problem requires you to implement a basic BFS algorithm
*/

//I AM NOT DONE
use std::collections::VecDeque;
use std::collections::{VecDeque, HashSet};

// Define a graph
struct Graph {
Expand All @@ -27,10 +26,23 @@ impl Graph {

// Perform a breadth-first search on the graph, return the order of visited nodes
fn bfs_with_return(&self, start: usize) -> Vec<usize> {

//TODO

let mut visit_order = vec![];
let mut deque = VecDeque::new();
let mut visited = HashSet::new();
deque.push_back(start);
visited.insert(start);
while !deque.is_empty() {
let node = deque.pop_front().unwrap();
visit_order.push(node);
for i in &self.adj[node] {
if visited.contains(i) {
continue;
}
visited.insert(*i);
deque.push_back(*i);
}

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

// I AM NOT DONE
use std::collections::HashSet;

struct Graph {
Expand All @@ -23,7 +22,17 @@ impl Graph {
}

fn dfs_util(&self, v: usize, visited: &mut HashSet<usize>, visit_order: &mut Vec<usize>) {
//TODO
if visited.contains(&v) {
return;
}
visited.insert(v);
visit_order.push(v);
for i in &self.adj[v] {
if visited.contains(i) {
continue;
}
self.dfs_util(*i, visited, visit_order);
}
}

// Perform a depth-first search on the graph, return the order of visited nodes
Expand Down
34 changes: 29 additions & 5 deletions exercises/algorithm/algorithm7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
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 @@ -31,8 +30,11 @@ impl<T> Stack<T> {
self.size += 1;
}
fn pop(&mut self) -> Option<T> {
// TODO
None
if self.size == 0 {
return None
}
self.size -= 1;
self.data.pop()
}
fn peek(&self) -> Option<&T> {
if 0 == self.size {
Expand Down Expand Up @@ -101,8 +103,30 @@ impl<'a, T> Iterator for IterMut<'a, T> {

fn bracket_match(bracket: &str) -> bool
{
//TODO
true
let mut s = Stack::new();
for c in bracket.chars() {
match c {
'(' | '{' | '[' => s.push(c),
')' => {
if s.pop() != Some('(') {
return false;
}
},
'}' => {
if s.pop() != Some('{') {
return false;
}
},
']' => {
if s.pop() != Some('[') {
return false;
}
},
_ => {},
}
}
println!("{:?}", s);
s.is_empty()
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit f9ee537

Please sign in to comment.