From 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb Mon Sep 17 00:00:00 2001 From: Orangerot Date: Thu, 27 Jun 2024 11:30:16 +0200 Subject: Initial commit --- design-hashmap/src/main.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 design-hashmap/src/main.rs (limited to 'design-hashmap/src') diff --git a/design-hashmap/src/main.rs b/design-hashmap/src/main.rs new file mode 100644 index 0000000..f35bd69 --- /dev/null +++ b/design-hashmap/src/main.rs @@ -0,0 +1,43 @@ +fn main() { + println!("Hello, world!"); + let mut a = MyHashMap::new(); + a.put(1,1); + a.put(2,2); + a.get(1); + a.get(3); + a.put(2,1); + a.get(2); + a.remove(2); + a.get(2); +} + +struct MyHashMap { + map: Vec<(i32,i32)> +} + +impl MyHashMap { + + fn new() -> Self { + MyHashMap { + map: Vec::new() + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.map.iter_mut().find(|x| x.0 == key) { + Some(e) => e.1 = value, + None => self.map.push((key, value)) + }; + } + + fn get(&self, key: i32) -> i32 { + self.map.iter().find(|&x| x.0 == key).map(|x| x.1).unwrap_or(-1) + } + + fn remove(&mut self, key: i32) { + if let Some(e) = self.map.iter().position(|x| x.0 == key) { + self.map.swap_remove(e); + } + } +} + -- cgit v1.2.3