Dijkstra Implement

Dijkstra’s algorithm is a graph traversal algorithm that finds the shortest path between the source vertex and all other vertices in the graph. data structure Vertex: a struct that holds the vertex id. Edge: a struct that holds the vertex id of the start and end points, and the cost of the edge which must be a positive integer. Graph: a struct that holds the vertices and edges. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 use std::cmp::Ordering; #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub struct Vertex { // `id`: A unique identifier for the vertex, represented as a String. id: String, } #[derive(Debug, PartialEq, Eq, Clone)] pub struct Edge { // `from`: The ID of the starting vertex of the edge. from: String, // `to`: The ID of the ending vertex of the edge. to: String, // `cost`: The weight or cost associated with traversing the edge. cost: u32, } #[derive(Debug, PartialEq, Eq)] pub struct Graph { // `vertices`: A vector of `Vertex` structs, representing all vertices in the graph. vertices: Vec<Vertex>, // `edges`: A vector of `Edge` structs, representing all edges in the graph. edges: Vec<Edge>, } #[derive(Clone, Eq, PartialEq)] struct Node { // `cost`: The current shortest distance from the source vertex to this vertex. cost: u32, // `vertex_id`: The ID of the vertex represented by this node. vertex_id: String, } // Implement `Ord` trait for `Node` to make it usable in `BinaryHeap`. impl Ord for Node { fn cmp(&self, other: &Self) -> Ordering { // Reverse the ordering of `cost` to make `BinaryHeap` behave as a min-heap. // `BinaryHeap` in Rust is a max-heap by default, so flipping the comparison results // in a min-heap behavior. other.cost.cmp(&self.cost) } } // Implement `PartialOrd` trait for `Node`. impl PartialOrd for Node { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } Dijkstra algorithm lowest cost Initialize the distance from the source vertex to itself as 0. Push the source vertex into the priority queue with cost 0. Loop until the priority queue is empty. Pop the vertex with the smallest distance from the priority queue. If the current vertex is the destination, break the loop. If a shorter path to the current vertex has already been found, skip it. Iterate over all edges starting from the current vertex. Calculate the cost to the neighbor vertex through the current vertex. If a shorter path to the neighbor vertex is found, update the distance, and push it into the priority queue. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 use std::collections::{BinaryHeap, HashMap}; impl Graph { // Computes the lowest cost from src to dest using Dijkstra's algorithm. pub fn dijkstra_cost(&self, src: &str, dest: &str) -> Option<u32> { // `distances`: A `HashMap` to store the shortest distances from the source vertex to each vertex. let mut distances: HashMap<String, u32> = HashMap::new(); // `pq`: A `BinaryHeap` (priority queue) to efficiently select the vertex with the smallest distance. let mut pq: BinaryHeap<Node> = BinaryHeap::new(); // Initialize the distance from the source vertex to itself as 0. distances.insert(src.to_string(), 0); // Push the source vertex into the priority queue with cost 0. pq.push(Node { cost: 0, vertex_id: src.to_string(), }); // Loop until the priority queue is empty. while let Some(Node { cost, vertex_id }) = pq.pop() { // If the current vertex is the destination, return the cost. if vertex_id == dest { return Some(cost); } // If a shorter path to the current vertex has already been found, skip it. if cost > *distances.get(&vertex_id).unwrap_or(&u32::MAX) { continue; } // Iterate over all edges starting from the current vertex. for edge in self.edges.iter().filter(|e| e.from == vertex_id) { // Calculate the cost to the neighbor vertex through the current vertex. let next_cost = cost + edge.cost; // If a shorter path to the neighbor vertex is found, update the distance and push it into the priority queue. if next_cost < *distances.get(&edge.to).unwrap_or(&u32::MAX) { distances.insert(edge.to.clone(), next_cost); pq.push(Node { cost: next_cost, vertex_id: edge.to.clone(), }); } } } // If no path is found, return None. None } } shortest path Much the same as the lowest cost, but keep a previous HashMap to store the previous vertex in the shortest path to each vertex. ...

March 11, 2025 · datewu

Kafka Quick Start

what’s kafka Kafka is a distributed streaming platform. Think of it as a high-throughput, fault-tolerant message queue on steroids. It’s designed for handling real-time data feeds. Concepts Topic: A category or feed name to which records are published. Partition: A topic is divided into partitions, which are ordered, immutable sequences of records. Partitions enable parallelism and scalability. Producer: An application that publishes records to a Kafka topic. Consumer: An application that subscribes to one or more topics and processes the records. ...

March 10, 2025 · datewu

Test Mermaid

Create a Partial for Mermaid Initialization Create a new file in your layouts/partials directory named mermaid-init.html. Add the following code to mermaid-init.html: HTML 1 2 3 4 <script type="module"> import mermaid from '/js/mermaid.esm.min.mjs'; mermaid.initialize({ startOnLoad: true }); </script> Create a Shortcode for mermaid Create a new file named mermaid.html in layouts/shortcodes/. Add the follwoing code to mermaid.html: 1 2 3 4 5 6 7 8 9 10 11 12 13 {{- $scratch := .Page.Scratch -}} {{- if not ($scratch.Get "mermaid-counter") -}} {{- $scratch.Set "mermaid-counter" 1 -}} {{- partial "mermaid-init.html" . -}} {{- else -}} {{- $scratch.Add "mermaid-counter" 1 -}} {{- end -}} {{- $id := printf "mermaid-%d" ($scratch.Get "mermaid-counter") -}} <div id="{{ $id }}"> <pre class="mermaid"> {{- .Inner | safeHTML }} </pre> </div> Explanation of Changes: ...

March 9, 2025 · datewu

Travel BST

Binary Search Tree (BST) data structure: left subtree nodes are less than root node right subtree nodes are greater than root node left and right subtree are also binary search tree empty node is also binary search tree insert new node: find the position insert left tree if val < current node insert right tree if val >= current node keep the binary search tree property repeat 1-4 Implement BST with Box<T> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Maybe I should use a reference count instead of a box pointer // for the bfs method. #[derive(Debug, PartialEq, Eq, Clone)] pub struct BinarySearchBoxNode { val: i32, left: Option<Box<Self>>, right: Option<Box<Self>>, } impl BinarySearchBoxNode { fn new(val: i32) -> Self { Self { val, left: None, right: None, } } fn insert(&mut self, val: i32) { if val < self.val { if let Some(left) = &mut self.left { left.insert(val); } else { self.left = Some(Box::new(Self::new(val))); } return; } if let Some(right) = &mut self.right { right.insert(val); } else { self.right = Some(Box::new(Self::new(val))); } } } BFS vs DFS Key Differences: ...

March 9, 2025 · datewu

My WireGuard VPN Headache

Why GitHub Hated My MTU (And How I Fixed It) Let me tell you about the frustrating day I spent wrestling with my WireGuard VPN and why GitHub decided to be the only site that wouldn’t play nice. I’m hoping my experience, especially if you’re running WireGuard in a microk8s environment like I was, can save you some headaches. The Setup: microk8s, Ubuntu, and WireGuard My setup was a bit complex. I had a microk8s cluster running on an Ubuntu 24.04.2 LTS server node (GNU/Linux 6.8.0-54-generic x86_64). I was running my WireGuard VPN server as a pod within this microk8s cluster. This added a layer of network complexity that I didn’t initially account for. ...

March 4, 2025 · datewu

The First Americans (Home, School, and Neighborhood)

Key Vocabulary culture a way of life of a group, or organization, or country. tribe dance. Native Americans the people who were living in North America before Europeans. native born and existing in a particular place or country. hunt to chase and kill animals for their meat or skin. fish to try to catch fish. fishing pole. craftwork work made by special skills. settle to go and live in a place. settle down. ...

February 26, 2025 · datewu

Magnets (Physical Science)

Key Vocabulary magnet A magnet a piece of metal that attracts iron or steel. horseshoe. bar. magnetism. strong, weak. pole A pole is one of the two ends of a magnet. attract Attract means to pull toward. repel Repel means to push away. iron Iron is a metal that is used to make many things. steel Steel is a kind of metal that is strong and has iron in it. bolts. screws. ...

February 26, 2025 · datewu

Motion ??? (Physical Science)

Key Vocabulary motion Motion is the act of moving. It is in motion. speed Speed is how fast something moves. force A power that produces a change in a movement. A push or a pull is a force. friction. gravity Gravity is a force that pull things to the ground. pull Pull is a force that moves things closer to you. push Push is a force that moves things away from you. ...

February 26, 2025 · datewu

Electricity (Physical Science)

Key Vocabulary electricity Electricity is energy that gives computers and other machines power to work. power plant A power plant is a building that produces electricity for many things or people. nuclear power plant. fuel Fuel is something burned to make heat or power. battery A battery is an object that stores electricity. wire A wire is a long, thin cable that carries electricity. metal, plastic. outlet An outlet is a place on w wall for electricity. ...

February 26, 2025 · datewu

Sound (Physical Science)

Key Vocabulary sound Sound is the energy that you can hear. vibrate Vibrate means to move back and forth quickly. vocal chords. jack hammer. pitch Pitch is how high or low a sound is. high/low pitched sound. yell Yell means to shout. Don’t yell/shout. yell at each other. volume Volume is how loud or soft a sound is. increase/descrese sound. turn the volume up/down. speak up. whisper Whisper means to speek quietly or softly. volume. ...

February 25, 2025 · datewu