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

lsmx0 #12

Open
wants to merge 19 commits into
base: main
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
188 changes: 106 additions & 82 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::*;

#[derive(Debug)]
struct Node<T> {
Expand All @@ -22,20 +22,15 @@ impl<T> Node<T> {
}
}
}
#[derive(Debug)]

#[derive(Debug, Default)]
struct LinkedList<T> {
length: u32,
start: Option<NonNull<Node<T>>>,
end: Option<NonNull<Node<T>>>,
}

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

impl<T> LinkedList<T> {
impl<T: std::cmp::PartialOrd + Clone> LinkedList<T> {
pub fn new() -> Self {
Self {
length: 0,
Expand All @@ -45,62 +40,89 @@ impl<T> LinkedList<T> {
}

pub fn add(&mut self, obj: T) {
let mut node = Box::new(Node::new(obj));
node.next = None;
let node = Box::new(Node::new(obj));
let node_ptr = Some(unsafe { NonNull::new_unchecked(Box::into_raw(node)) });

match self.end {
None => self.start = node_ptr,
Some(end_ptr) => unsafe { (*end_ptr.as_ptr()).next = node_ptr },
}

self.end = node_ptr;
self.length += 1;
}

pub fn get(&mut self, index: i32) -> Option<&T> {
pub fn get(&self, index: i32) -> Option<&T> {
self.get_ith_node(self.start, index)
}

fn get_ith_node(&mut self, node: Option<NonNull<Node<T>>>, index: i32) -> Option<&T> {
fn get_ith_node(&self, node: Option<NonNull<Node<T>>>, index: i32) -> Option<&T> {
match node {
None => None,
Some(next_ptr) => match index {
0 => Some(unsafe { &(*next_ptr.as_ptr()).val }),
_ => self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1),
},
Some(next_ptr) => {
if index == 0 {
Some(unsafe { &(*next_ptr.as_ptr()).val })
} else {
self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1)
}
}
}
}
pub fn merge(list_a:LinkedList<T>,list_b:LinkedList<T>) -> Self
{
//TODO
Self {
length: 0,
start: None,
end: None,

pub fn merge(mut list_a: LinkedList<T>, mut list_b: LinkedList<T>) -> Self {
let mut merged_list = LinkedList::new();
let mut current_a = list_a.start;
let mut current_b = list_b.start;

while current_a.is_some() || current_b.is_some() {
if current_a.is_some() && current_b.is_some() {
let node_a = unsafe { current_a.unwrap().as_ref() };
let node_b = unsafe { current_b.unwrap().as_ref() };

if node_a.val < node_b.val {
merged_list.add(node_a.val.clone());
current_a = node_a.next;
} else {
merged_list.add(node_b.val.clone());
current_b = node_b.next;
}
} else if current_a.is_some() {
let node_a = unsafe { current_a.unwrap().as_ref() };
merged_list.add(node_a.val.clone());
current_a = node_a.next;
} else if current_b.is_some() {
let node_b = unsafe { current_b.unwrap().as_ref() };
merged_list.add(node_b.val.clone());
current_b = node_b.next;
}
}
}

merged_list
}
}

impl<T> Display for LinkedList<T>
where
T: Display,
{
impl<T: Display> Display for LinkedList<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.start {
Some(node) => write!(f, "{}", unsafe { node.as_ref() }),
None => Ok(()),
let mut current = self.start;
let mut result = String::new();

while let Some(node_ptr) = current {
let node = unsafe { node_ptr.as_ref() };
result.push_str(&format!("{}, ", node.val));
current = node.next;
}

if result.len() > 2 {
result.truncate(result.len() - 2);
}

write!(f, "{}", result)
}
}

impl<T> Display for Node<T>
where
T: Display,
{
impl<T: Display> Display for Node<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.next {
Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }),
None => write!(f, "{}", self.val),
}
write!(f, "{}", self.val)
}
}

Expand Down Expand Up @@ -130,44 +152,46 @@ mod tests {

#[test]
fn test_merge_linked_list_1() {
let mut list_a = LinkedList::<i32>::new();
let mut list_b = LinkedList::<i32>::new();
let vec_a = vec![1,3,5,7];
let vec_b = vec![2,4,6,8];
let target_vec = vec![1,2,3,4,5,6,7,8];

for i in 0..vec_a.len(){
list_a.add(vec_a[i]);
}
for i in 0..vec_b.len(){
list_b.add(vec_b[i]);
}
println!("list a {} list b {}", list_a,list_b);
let mut list_c = LinkedList::<i32>::merge(list_a,list_b);
println!("merged List is {}", list_c);
for i in 0..target_vec.len(){
assert_eq!(target_vec[i],*list_c.get(i as i32).unwrap());
}
}
#[test]
fn test_merge_linked_list_2() {
let mut list_a = LinkedList::<i32>::new();
let mut list_b = LinkedList::<i32>::new();
let vec_a = vec![11,33,44,88,89,90,100];
let vec_b = vec![1,22,30,45];
let target_vec = vec![1,11,22,30,33,44,45,88,89,90,100];

for i in 0..vec_a.len(){
list_a.add(vec_a[i]);
}
for i in 0..vec_b.len(){
list_b.add(vec_b[i]);
}
println!("list a {} list b {}", list_a,list_b);
let mut list_c = LinkedList::<i32>::merge(list_a,list_b);
println!("merged List is {}", list_c);
for i in 0..target_vec.len(){
assert_eq!(target_vec[i],*list_c.get(i as i32).unwrap());
}
}
}
let mut list_a = LinkedList::<i32>::new();
let mut list_b = LinkedList::<i32>::new();
let vec_a = vec![1, 3, 5, 7];
let vec_b = vec![2, 4, 6, 8];
let target_vec = vec![1, 2, 3, 4, 5, 6, 7, 8];

for &val in &vec_a {
list_a.add(val);
}
for &val in &vec_b {
list_b.add(val);
}
println!("list a {} list b {}", list_a, list_b);
let mut list_c = LinkedList::<i32>::merge(list_a, list_b);
println!("merged List is {}", list_c);
for (i, &target) in target_vec.iter().enumerate() {
assert_eq!(target, *list_c.get(i as i32).unwrap());
}
}

#[test]
fn test_merge_linked_list_2() {
let mut list_a = LinkedList::<i32>::new();
let mut list_b = LinkedList::<i32>::new();
let vec_a = vec![11, 33, 44, 88, 89, 90, 100];
let vec_b = vec![1, 22, 30, 45];
let target_vec = vec![1, 11, 22, 30, 33, 44, 45, 88, 89, 90, 100];

for &val in &vec_a {
list_a.add(val);
}
for &val in &vec_b {
list_b.add(val);
}
println!("list a {} list b {}", list_a, list_b);
let mut list_c = LinkedList::<i32>::merge(list_a, list_b);
println!("merged List is {}", list_c);
for (i, &target) in target_vec.iter().enumerate() {
assert_eq!(target, *list_c.get(i as i32).unwrap());
}
}
}

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

use std::collections::{HashMap, HashSet};
use std::fmt;

#[derive(Debug, Clone)]
pub struct NodeNotInGraph;
impl fmt::Display for NodeNotInGraph {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "accessing a node that is not in the graph")
}
}

pub struct UndirectedGraph {
adjacency_table: HashMap<String, Vec<(String, i32)>>,
}

impl Graph for UndirectedGraph {
fn new() -> UndirectedGraph {
UndirectedGraph {
adjacency_table: HashMap::new(),
}
}

fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>> {
&mut self.adjacency_table
}

fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>> {
&self.adjacency_table
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
}
}
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
if self.contains(node) {
return false;
}
self.adjacency_table.insert(node.to_string(), vec![]);
true
}

fn add_edge(&mut self, edge: (&str, &str, i32)) {
//TODO
let (from_node, to_node, weight) = edge;
if !self.contains(from_node) || !self.contains(to_node) {
panic!("{}", NodeNotInGraph);
}
self.adjacency_table.get_mut(from_node).unwrap().push((to_node.to_string(), weight));
self.adjacency_table.get_mut(to_node).unwrap().push((from_node.to_string(), weight));
}

fn contains(&self, node: &str) -> bool {
self.adjacency_table().get(node).is_some()
}

fn nodes(&self) -> HashSet<&String> {
self.adjacency_table().keys().collect()
}

fn edges(&self) -> Vec<(&String, &String, i32)> {
let mut edges = Vec::new();
for (from_node, from_node_neighbours) in self.adjacency_table() {
Expand All @@ -59,13 +69,28 @@ pub trait Graph {
edges
}
}

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;
fn add_edge(&mut self, edge: (&str, &str, i32));
fn contains(&self, node: &str) -> bool;
fn nodes(&self) -> HashSet<&String>;
fn edges(&self) -> Vec<(&String, &String, i32)>;
}

#[cfg(test)]
mod test_undirected_graph {
use super::Graph;
use super::UndirectedGraph;
#[test]
fn test_add_edge() {
let mut graph = UndirectedGraph::new();
graph.add_node("a");
graph.add_node("b");
graph.add_node("c");
graph.add_edge(("a", "b", 5));
graph.add_edge(("b", "c", 10));
graph.add_edge(("c", "a", 7));
Expand All @@ -81,4 +106,4 @@ mod test_undirected_graph {
assert_eq!(graph.edges().contains(edge), true);
}
}
}
}
21 changes: 17 additions & 4 deletions exercises/algorithm/algorithm2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
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,9 +72,22 @@ impl<T> LinkedList<T> {
},
}
}
pub fn reverse(&mut self){
// TODO
}
pub fn reverse(&mut self) {
let mut current = self.start;
let mut prev = None;
while let Some(node_ptr) = current {
let next = unsafe { (*node_ptr.as_ptr()).next };
unsafe {
(*node_ptr.as_ptr()).next = prev;
(*node_ptr.as_ptr()).prev = next;
}
prev = Some(node_ptr);
current = next;
}
self.start = prev;
self.end = self.start;
}

}

impl<T> Display for LinkedList<T>
Expand Down
Loading