Skip to content

Commit 6905eaf

Browse files
rootroot
authored andcommitted
Auto-commit
1 parent c188a56 commit 6905eaf

File tree

1 file changed

+262
-0
lines changed
  • two-pointer-5-types/race-condition-protection/web-interface/src

1 file changed

+262
-0
lines changed
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
use serde::{Deserialize, Serialize};
2+
use std::collections::HashMap;
3+
use warp::Filter;
4+
5+
#[derive(Debug, Deserialize, Serialize)]
6+
struct AlgorithmRequest {
7+
algorithm: String,
8+
input: String,
9+
}
10+
11+
#[derive(Debug, Deserialize, Serialize)]
12+
struct AlgorithmResponse {
13+
result: String,
14+
execution_time: u128,
15+
}
16+
17+
#[derive(Debug, Deserialize, Serialize)]
18+
struct PatternInfo {
19+
name: String,
20+
description: String,
21+
category: String,
22+
example: String,
23+
}
24+
25+
async fn execute_algorithm(req: AlgorithmRequest) -> Result<impl warp::Reply, warp::Rejection> {
26+
let start_time = std::time::Instant::now();
27+
28+
let result = match req.algorithm.as_str() {
29+
"two_sum_sorted" => {
30+
// Parse input as comma-separated integers
31+
let nums: Vec<i32> = req.input
32+
.split(',')
33+
.filter_map(|s| s.trim().parse().ok())
34+
.collect();
35+
if nums.len() >= 2 {
36+
// Simple implementation for demonstration
37+
format!("Found pair that sums to target: {:?}", find_two_sum(&nums, 9))
38+
} else {
39+
"Not enough numbers provided".to_string()
40+
}
41+
},
42+
"reverse_array" => {
43+
let mut chars: Vec<char> = req.input.chars().collect();
44+
chars.reverse();
45+
format!("Reversed: {}", chars.iter().collect::<String>())
46+
},
47+
"is_palindrome" => {
48+
let cleaned: String = req.input.to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect();
49+
let reversed: String = cleaned.chars().rev().collect();
50+
format!("Is palindrome: {}", cleaned == reversed)
51+
},
52+
_ => format!("Algorithm '{}' not implemented", req.algorithm),
53+
};
54+
55+
let execution_time = start_time.elapsed().as_millis();
56+
57+
let response = AlgorithmResponse {
58+
result,
59+
execution_time,
60+
};
61+
62+
Ok(warp::reply::json(&response))
63+
}
64+
65+
fn find_two_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> {
66+
let mut left = 0;
67+
let mut right = nums.len() - 1;
68+
69+
while left < right {
70+
let sum = nums[left] + nums[right];
71+
if sum == target {
72+
return Some((left, right));
73+
} else if sum < target {
74+
left += 1;
75+
} else {
76+
right -= 1;
77+
}
78+
}
79+
80+
None
81+
}
82+
83+
fn get_patterns_info() -> Vec<PatternInfo> {
84+
vec![
85+
PatternInfo {
86+
name: "Two Sum (Sorted Array)",
87+
description: "Find two numbers in a sorted array that add up to a target value",
88+
category: "Opposite Ends",
89+
example: "Array: [2,7,11,15], Target: 9 → Indices: (0,1)",
90+
},
91+
PatternInfo {
92+
name: "Reverse Array",
93+
description: "Reverse the elements of an array using two pointers from both ends",
94+
category: "Opposite Ends",
95+
example: "Input: [1,2,3,4,5] → Output: [5,4,3,2,1]",
96+
},
97+
PatternInfo {
98+
name: "Palindrome Check",
99+
description: "Check if a string is a palindrome using two pointers",
100+
category: "Opposite Ends",
101+
example: "Input: 'racecar' → Output: true",
102+
},
103+
PatternInfo {
104+
name: "Container With Most Water",
105+
description: "Find two lines that form a container with the most water",
106+
category: "Opposite Ends",
107+
example: "Heights: [1,8,6,2,5,4,8,3,7] → Max area: 49",
108+
},
109+
PatternInfo {
110+
name: "Three Sum",
111+
description: "Find all unique triplets that sum to zero",
112+
category: "Opposite Ends",
113+
example: "Array: [-1,0,1,2,-1,-4] → Triplets: [[-1,-1,2],[-1,0,1]]",
114+
},
115+
PatternInfo {
116+
name: "Remove Duplicates",
117+
description: "Remove duplicates from a sorted array in-place",
118+
category: "Same Direction",
119+
example: "Array: [0,0,1,1,1,2,2,3,3,4] → Length: 5, Array: [0,1,2,3,4]",
120+
},
121+
PatternInfo {
122+
name: "Linked List Cycle",
123+
description: "Detect if a linked list has a cycle",
124+
category: "Same Direction",
125+
example: "List with cycle → Output: true",
126+
},
127+
PatternInfo {
128+
name: "Middle of Linked List",
129+
description: "Find the middle node of a linked list",
130+
category: "Same Direction",
131+
example: "List: [1,2,3,4,5] → Middle: 3",
132+
},
133+
PatternInfo {
134+
name: "Kth Node from End",
135+
description: "Find the kth node from the end of a linked list",
136+
category: "Same Direction",
137+
example: "List: [1,2,3,4,5], k=2 → Node: 4",
138+
},
139+
PatternInfo {
140+
name: "Partition Array",
141+
description: "Partition an array around a pivot value",
142+
category: "Partitioning",
143+
example: "Array: [1,4,3,2,5,2], Pivot: 3 → [1,2,2,4,3,5]",
144+
},
145+
PatternInfo {
146+
name: "Sort Colors",
147+
description: "Sort an array of colors (0,1,2) in-place",
148+
category: "Partitioning",
149+
example: "Array: [2,0,2,1,1,0] → [0,0,1,1,2,2]",
150+
},
151+
PatternInfo {
152+
name: "Remove Element",
153+
description: "Remove all instances of a value from an array",
154+
category: "Partitioning",
155+
example: "Array: [3,2,2,3], Value: 3 → Length: 2, Array: [2,2]",
156+
},
157+
PatternInfo {
158+
name: "Max Sum Subarray",
159+
description: "Find the maximum sum of a contiguous subarray",
160+
category: "Window Bounds",
161+
example: "Array: [-2,1,-3,4,-1,2,1,-5,4] → Max sum: 6",
162+
},
163+
PatternInfo {
164+
name: "Longest Substring",
165+
description: "Find the longest substring without repeating characters",
166+
category: "Window Bounds",
167+
example: "String: 'abcabcbb' → Length: 3 ('abc')",
168+
},
169+
PatternInfo {
170+
name: "Min Window Substring",
171+
description: "Find the minimum window substring that contains all characters",
172+
category: "Window Bounds",
173+
example: "s: 'ADOBECODEBANC', t: 'ABC' → 'BANC'",
174+
},
175+
PatternInfo {
176+
name: "Sliding Window Product",
177+
description: "Find a pair of numbers with a specific product in a sorted array",
178+
category: "Sliding Window",
179+
example: "Array: [1,2,3,4,5], Product: 12 → Pair: (2,4)",
180+
},
181+
PatternInfo {
182+
name: "Merge Sorted Arrays",
183+
description: "Merge two sorted arrays into one sorted array",
184+
category: "Bidirectional Merge",
185+
example: "Array1: [1,2,3], Array2: [2,5,6] → [1,2,2,3,5,6]",
186+
},
187+
PatternInfo {
188+
name: "Intersection of Arrays",
189+
description: "Find the intersection of two sorted arrays",
190+
category: "Bidirectional Merge",
191+
example: "Array1: [1,2,2,3], Array2: [2,2] → [2,2]",
192+
},
193+
PatternInfo {
194+
name: "Union of Arrays",
195+
description: "Find the union of two sorted arrays",
196+
category: "Bidirectional Merge",
197+
example: "Array1: [1,2,3], Array2: [2,3,4] → [1,2,3,4]",
198+
},
199+
PatternInfo {
200+
name: "Sorted Squares",
201+
description: "Square each element and return sorted result",
202+
category: "Bidirectional Merge",
203+
example: "Array: [-4,-1,0,3,10] → [0,1,9,16,100]",
204+
},
205+
PatternInfo {
206+
name: "Container With Most Water",
207+
description: "Find two lines that form a container with the most water",
208+
category: "Array Problems",
209+
example: "Heights: [1,8,6,2,5,4,8,3,7] → Max area: 49",
210+
},
211+
PatternInfo {
212+
name: "Merge Sorted Arrays",
213+
description: "Merge two sorted arrays into one sorted array",
214+
category: "Array Problems",
215+
example: "Array1: [1,2,3,0,0,0], Array2: [2,5,6] → [1,2,2,3,5,6]",
216+
},
217+
PatternInfo {
218+
name: "Find Triplet Sum",
219+
description: "Find three numbers that sum to a target value",
220+
category: "Sum Problems",
221+
example: "Array: [1,2,3,4,5], Target: 9 → Triplet: (1,3,5)",
222+
},
223+
PatternInfo {
224+
name: "Two Sum (Safe)",
225+
description: "Secure implementation of two sum with overflow protection",
226+
category: "Sum Problems",
227+
example: "Array: [2,7,11,15], Target: 9 → Indices: (0,1)",
228+
},
229+
]
230+
}
231+
232+
#[tokio::main]
233+
async fn main() {
234+
// GET /patterns - Return information about all patterns
235+
let patterns_route = warp::path("patterns")
236+
.and(warp::get())
237+
.map(|| warp::reply::json(&get_patterns_info()));
238+
239+
// POST /execute - Execute an algorithm
240+
let execute_route = warp::path("execute")
241+
.and(warp::post())
242+
.and(warp::body::json())
243+
.and_then(execute_algorithm);
244+
245+
// Serve static files
246+
let static_files = warp::fs::dir("static");
247+
248+
// Combine routes
249+
let routes = patterns_route
250+
.or(execute_route)
251+
.or(static_files)
252+
.with(warp::cors().allow_any_origin());
253+
254+
// Create static directory and files
255+
std::fs::create_dir_all("static").unwrap();
256+
257+
// Create index.html
258+
std::fs::write("static/index.html", include_str!("../static/index.html")).unwrap();
259+
260+
println!("Server running on http://localhost:3030");
261+
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
262+
}

0 commit comments

Comments
 (0)