├── traverse_tree_level ├── .gitignore ├── Cargo.toml └── src │ └── main.rs ├── sorting ├── src │ ├── lib.rs │ ├── quicksort.rs │ └── mergesort.rs └── Cargo.toml ├── rangesum ├── Cargo.toml └── src │ └── main.rs ├── flood_fill ├── Cargo.toml ├── README.md └── src │ └── main.rs ├── graph_loop ├── Cargo.toml └── src │ └── main.rs ├── int2roman ├── Cargo.toml └── src │ └── main.rs ├── lcancestor ├── Cargo.toml └── src │ └── main.rs ├── roman2int ├── Cargo.toml └── src │ └── main.rs ├── happy_number ├── Cargo.toml └── src │ └── main.rs ├── num_islands ├── Cargo.toml ├── README.md └── src │ └── main.rs ├── reverse_int ├── Cargo.toml ├── README.md └── src │ └── main.rs ├── expression_tree ├── Cargo.toml └── src │ └── main.rs ├── number_to_words ├── Cargo.toml ├── README.md └── src │ └── main.rs ├── alien_dictionary ├── Cargo.toml └── src │ └── main.rs ├── min_size_subarray └── Cargo.toml ├── subarray_sum_divisible ├── Cargo.toml └── src │ └── main.rs ├── oceans_flow ├── Cargo.toml └── src │ └── main.rs ├── ocr_scan ├── Cargo.toml └── src │ └── main.rs ├── runlength ├── Cargo.toml └── src │ └── main.rs ├── subarray_sum_divisible_bool ├── Cargo.toml └── src │ └── main.rs ├── word_break2 ├── Cargo.toml └── src │ └── main.rs ├── add_strings ├── Cargo.toml └── src │ └── main.rs ├── vec_shuffle ├── Cargo.toml └── src │ └── main.rs ├── array_pair_sum ├── Cargo.toml └── src │ └── main.rs ├── count_and_say ├── Cargo.toml └── src │ └── main.rs ├── bipartite_graph ├── Cargo.toml └── src │ └── main.rs ├── contains_duplicate3 ├── Cargo.toml └── src │ └── main.rs ├── coin_boxes ├── Cargo.toml └── src │ └── main.rs ├── pow ├── Cargo.toml └── src │ └── main.rs ├── .gitignore ├── max_subarray ├── Cargo.toml ├── benches │ └── my_benchmark.rs └── src │ └── lib.rs ├── README.md └── LICENSE /traverse_tree_level/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /sorting/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod mergesort; 2 | pub mod quicksort; 3 | 4 | pub trait Sort { 5 | fn sort(slice: &mut [T]) -> &mut [T]; 6 | } 7 | -------------------------------------------------------------------------------- /rangesum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rangesum" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /flood_fill/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "flood_fill" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /graph_loop/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "graph_loop" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /int2roman/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "int2roman" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /lcancestor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lcancestor" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /roman2int/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "roman2int" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /happy_number/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "happy_number" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /num_islands/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "num_islands" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /reverse_int/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "reverse_int" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /expression_tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "expression_tree" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /number_to_words/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "number_to_words" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /alien_dictionary/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "alien_dictionary" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /min_size_subarray/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "min_size_subarray" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /traverse_tree_level/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "traverse_tree_level" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /subarray_sum_divisible/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "subarray_sum_divisible" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /sorting/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sorting" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /oceans_flow/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "oceans_flow" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | maplit = "1.0.2" 10 | -------------------------------------------------------------------------------- /ocr_scan/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ocr_scan" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /runlength/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "runlength" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /subarray_sum_divisible_bool/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "subarray_sum_divisible_bool" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /word_break2/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "word_break2" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | maplit = "1.0.2" 10 | -------------------------------------------------------------------------------- /add_strings/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "add_strings" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /vec_shuffle/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vec_shuffle" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /array_pair_sum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "array_pair_sum" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /count_and_say/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "count_and_say" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /bipartite_graph/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bipartite_graph" 3 | version = "0.1.0" 4 | authors = ["James McMurray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /contains_duplicate3/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "contains_duplicate3" 3 | version = "0.1.0" 4 | authors = ["James McMurray"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /coin_boxes/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "coin_boxes" 3 | version = "0.1.0" 4 | authors = ["James McMurray "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /pow/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pow" 3 | version = "0.1.0" 4 | authors = ["jamesmcm"] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | num-traits = "0.2.11" 11 | num-integer = "0.1.42" 12 | 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | target/ 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /max_subarray/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "max_subarray" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | 10 | [dev-dependencies] 11 | criterion = "0.3" 12 | rand = "0.7.3" 13 | 14 | [[bench]] 15 | name = "my_benchmark" 16 | harness = false 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Common Interview Questions solved in Rust 2 | 3 | ## Easy 4 | 5 | ### Recursive Problems 6 | 7 | * [Flood Fill](flood_fill): https://leetcode.com/problems/flood-fill 8 | * [Number of Islands](num_islands): https://leetcode.com/problems/number-of-islands/ 9 | * [Reverse Integer](reverse_int): https://leetcode.com/problems/reverse-integer/ 10 | 11 | ## Medium 12 | 13 | * [Number to Words](number_to_words): https://leetcode.com/problems/integer-to-english-words/ 14 | 15 | -------------------------------------------------------------------------------- /reverse_int/README.md: -------------------------------------------------------------------------------- 1 | # Reverse Integer problem 2 | 3 | LeetCode: https://leetcode.com/problems/reverse-integer/ 4 | 5 | ## Description 6 | 7 | Given a 32-bit signed integer, reverse digits of an integer. 8 | 9 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: \[−2^31, 2^31 − 1\]. 10 | 11 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 12 | 13 | ## Provided test cases 14 | 15 | ### Test 1 16 | 17 | #### Input 18 | 19 | 123 20 | 21 | #### Output 22 | 23 | 321 24 | 25 | ### Test 2 26 | 27 | #### Input 28 | 29 | -123 30 | 31 | #### Output 32 | 33 | -321 34 | 35 | ### Test 3 36 | 37 | #### Input 38 | 39 | 120 40 | 41 | #### Output 42 | 43 | 21 44 | 45 | ## Solution 46 | 47 | This solution is implemented recursively, avoiding string operations. 48 | 49 | -------------------------------------------------------------------------------- /happy_number/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/happy-number/ 2 | 3 | use std::collections::HashSet; 4 | 5 | struct Solution {} 6 | 7 | impl Solution { 8 | pub fn is_happy(n: i32) -> bool { 9 | let mut n = n; 10 | let mut ss: i32 = 0; 11 | let mut seen: HashSet = HashSet::new(); 12 | 13 | loop { 14 | while n > 0 { 15 | ss += (n % 10).pow(2); 16 | n = n / 10; 17 | } 18 | if ss == 1 { 19 | return true; 20 | } 21 | if seen.contains(&ss) { 22 | return false; 23 | } 24 | seen.insert(ss); 25 | n = ss; 26 | // println!("{:?}", seen); 27 | ss = 0; 28 | } 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn test1() { 38 | assert!(Solution::is_happy(19)); 39 | } 40 | } 41 | 42 | fn main() { 43 | println!("{:?}", Solution::is_happy(2)); 44 | } 45 | -------------------------------------------------------------------------------- /pow/src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Implement pow(x,y) 3 | Ignore real number exponents 4 | */ 5 | 6 | #![feature(step_trait)] 7 | 8 | extern crate num_integer; 9 | extern crate num_traits; 10 | use num_integer::Integer; 11 | use num_traits::identities::One; 12 | use num_traits::identities::Zero; 13 | use num_traits::sign::abs; 14 | use num_traits::NumAssign; 15 | use num_traits::sign::Signed; 16 | use std::iter::Step; 17 | use num_traits::FromPrimitive; 18 | 19 | struct Solution {} 20 | 21 | impl Solution { 22 | fn pow( 23 | base: T, 24 | exponent: U, 25 | ) -> T { 26 | let mut out: T = base; 27 | match exponent { 28 | x if x != num_traits::Zero::zero() => { 29 | for _i in num_traits::One::one()..abs(exponent) { 30 | out *= out 31 | } 32 | } 33 | _ => {out = num_traits::One::one()}, 34 | } 35 | 36 | if exponent < num_traits::Zero::zero() { out = T::from_i32(1).unwrap() / out ;} 37 | out 38 | } 39 | } 40 | 41 | fn main() { 42 | println!("{:?}", Solution::pow(2, 4)); 43 | } 44 | -------------------------------------------------------------------------------- /number_to_words/README.md: -------------------------------------------------------------------------------- 1 | # Number to Words problem 2 | 3 | LeetCode: https://leetcode.com/problems/integer-to-english-words/ 4 | 5 | ## Description 6 | 7 | Convert a non-negative integer to its English words representation. 8 | 9 | Assume input is guaranteed to be less than 2^31 - 1. 10 | 11 | ## Provided test cases 12 | 13 | ### Test 1 14 | 15 | #### Input 16 | 17 | 123 18 | 19 | #### Output 20 | 21 | "One Hundred Twenty Three" 22 | 23 | ### Test 2 24 | 25 | #### Input 26 | 27 | 12345 28 | 29 | #### Output 30 | 31 | "Twelve Thousand Three Hundred Forty Five" 32 | 33 | ### Test 3 34 | 35 | #### Input 36 | 37 | 1234567 38 | 39 | #### Output 40 | 41 | "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" 42 | 43 | ### Test 4 44 | 45 | #### Input 46 | 47 | 1234567891 48 | 49 | #### Output 50 | 51 | "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" 52 | 53 | ## Solution 54 | 55 | The idea of the solution implemented here is as follows: 56 | 57 | * Split the number in to groups of thousands and process the groups individually. 58 | * Work backwards from the smallest group to the largest. 59 | * Have fixed lookups for numbers less than 20 and the multiples of ten < 100. 60 | 61 | -------------------------------------------------------------------------------- /max_subarray/benches/my_benchmark.rs: -------------------------------------------------------------------------------- 1 | use core::time::Duration; 2 | use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; 3 | use max_subarray::Solution; 4 | use rand::distributions::{Distribution, Uniform}; 5 | 6 | fn rand_vec(n: usize) -> Vec { 7 | let between = Uniform::from(-100..100); 8 | let mut rng = rand::thread_rng(); 9 | between.sample_iter(&mut rng).take(n).collect() 10 | } 11 | 12 | fn bench_fibs(c: &mut Criterion) { 13 | let mut group = c.benchmark_group("MaxSubarray"); 14 | group.warm_up_time(Duration::from_millis(5)); 15 | group.measurement_time(Duration::from_millis(10)); 16 | group.sample_size(10); 17 | 18 | let mut rand_arrays: Vec> = Vec::with_capacity(100); 19 | for i in [ 20 | 1, 2, 5, 10, 15, 20, 25, 30, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 21 | ] 22 | .iter() 23 | { 24 | rand_arrays.push(rand_vec(*i)); 25 | } 26 | 27 | for i in rand_arrays.iter() { 28 | group.bench_with_input(BenchmarkId::new("N", i.len()), i, |b, i| { 29 | b.iter(|| Solution::max_sub_array(i.clone())) 30 | }); 31 | group.bench_with_input(BenchmarkId::new("N**2", i.len()), i, |b, i| { 32 | b.iter(|| Solution::max_sub_array_n2(i.clone())) 33 | }); 34 | group.bench_with_input(BenchmarkId::new("N**3", i.len()), i, |b, i| { 35 | b.iter(|| Solution::max_sub_array_n3(i.clone())) 36 | }); 37 | } 38 | group.finish(); 39 | } 40 | 41 | criterion_group!(benches, bench_fibs); 42 | criterion_main!(benches); 43 | -------------------------------------------------------------------------------- /flood_fill/README.md: -------------------------------------------------------------------------------- 1 | # Flood Fill 2 | 3 | LeetCode: https://leetcode.com/problems/flood-fill/ 4 | 5 | ## Description 6 | 7 | An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). 8 | 9 | Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. 10 | 11 | To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. 12 | 13 | At the end, return the modified image. 14 | 15 | ## Test Cases 16 | ### Test 1 17 | #### Input 18 | ``` 19 | image = [[1,1,1],[1,1,0],[1,0,1]] 20 | sr = 1, sc = 1, newColor = 2 21 | ``` 22 | #### Output 23 | ``` 24 | [[2,2,2],[2,2,0],[2,0,1]] 25 | ``` 26 | #### Notes 27 | From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected 28 | by a path of the same color as the starting pixel are colored with the new color. 29 | 30 | Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. 31 | 32 | ## Solution 33 | 34 | The solution implemented is recursive. Note this will fail for large vectors, where we exceed the stack space with the stack frames from so many recursive calls. 35 | 36 | To avoid this we could implement an iterative solution. 37 | 38 | Note the implementation is a bit awkward here due to the LeetCode problem requiring we pass by value, and return a new modified Vector (i.e. we shouldn't edit in place). 39 | -------------------------------------------------------------------------------- /vec_shuffle/src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Transpose array so rows become columns and vice versa 4 | a = [ [1,2,3], [4,5,6], [7,8,9] ] 5 | 6 | output = [ [1,4,7], [2,5,8], [3,6,9] ] 7 | */ 8 | 9 | struct Solution {} 10 | 11 | impl Solution { 12 | fn transpose_clone(input: Vec>) -> Vec> { 13 | (0..input[0].len()) 14 | .map(|f| { 15 | input 16 | .iter() 17 | .cloned() 18 | .flat_map(|x| { 19 | x.iter() 20 | .cloned() 21 | .enumerate() 22 | .filter(|y| y.0 == f) 23 | .map(|z| z.1) 24 | .collect::>() 25 | }) 26 | .collect::>() 27 | }) 28 | .collect() 29 | } 30 | 31 | fn transpose_noclone(input: Vec>) -> Vec> { 32 | let l: usize = input[0].len(); 33 | let mut output: Vec> = Vec::new(); 34 | for _i in 0..l { 35 | output.push(Vec::new()); 36 | } 37 | 38 | input 39 | .into_iter() 40 | .for_each(|mut x| x.drain(..).enumerate().for_each(|y| output[y.0].push(y.1))); 41 | output 42 | } 43 | } 44 | 45 | fn main() { 46 | println!("Hello, world!"); 47 | } 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | #[test] 54 | fn test_clone() { 55 | assert_eq!( 56 | Solution::transpose_clone(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]), 57 | vec![vec![1, 4, 7], vec![2, 5, 8], vec![3, 6, 9]] 58 | ); 59 | } 60 | 61 | #[test] 62 | fn test_noclone() { 63 | assert_eq!( 64 | Solution::transpose_noclone(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]), 65 | vec![vec![1, 4, 7], vec![2, 5, 8], vec![3, 6, 9]] 66 | ); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /graph_loop/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/course-schedule/ 2 | use std::collections::HashMap; 3 | use std::collections::HashSet; 4 | 5 | struct Solution {} 6 | 7 | impl Solution { 8 | pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { 9 | // Build HashMap 10 | let mut map: HashMap> = HashMap::new(); 11 | for pair in prerequisites { 12 | map.entry(pair[0]) 13 | .and_modify(|v| v.push(pair[1])) 14 | .or_insert(vec![pair[1]]); 15 | } 16 | 17 | while !map.is_empty() { 18 | let preq: &i32 = map.keys().nth(0).unwrap(); 19 | let mut innerset: Vec<(i32, HashSet)> = vec![(*preq, HashSet::new())]; 20 | 21 | while !innerset.is_empty() { 22 | let ks = innerset.pop().unwrap(); 23 | let k: i32 = ks.0; 24 | let mut seen: HashSet = ks.1; 25 | if seen.contains(&k) { 26 | return false; 27 | } 28 | seen.insert(k); 29 | 30 | for el in map.remove(&k).iter() { 31 | for iel in el { 32 | innerset.push((*iel, seen.clone())); 33 | } 34 | } 35 | } 36 | } 37 | true 38 | } 39 | } 40 | 41 | fn main() { 42 | println!("Hello, world!"); 43 | } 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | // Note this useful idiom: importing names from outer (for mod tests) scope. 48 | use super::*; 49 | 50 | #[test] 51 | fn test1() { 52 | assert!(Solution::can_finish(2, vec![vec![1, 0]])); 53 | } 54 | #[test] 55 | fn test2() { 56 | assert!(!Solution::can_finish(2, vec![vec![1, 0], vec![0, 1]])); 57 | } 58 | #[test] 59 | fn test3() { 60 | assert!(Solution::can_finish( 61 | 4, 62 | vec![vec![1, 0], vec![2, 0], vec![3, 1], vec![3, 2]] 63 | )); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /num_islands/README.md: -------------------------------------------------------------------------------- 1 | # Number of Islands problem 2 | 3 | LeetCode: https://leetcode.com/problems/number-of-islands/ 4 | 5 | ## Description 6 | 7 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 8 | 9 | ## Provided test cases 10 | 11 | ### Test 1 12 | 13 | #### Input 14 | 15 | ``` 16 | 11110 17 | 11010 18 | 11000 19 | 00000 20 | ``` 21 | 22 | #### Output 23 | 24 | 1 25 | 26 | ### Test 2 27 | 28 | #### Input 29 | 30 | ``` 31 | 11000 32 | 11000 33 | 00100 34 | 00011 35 | ``` 36 | 37 | #### Output 38 | 39 | 3 40 | 41 | ## Solution 42 | 43 | The idea of the solution implemented here is as follows: 44 | 45 | * Scan through the 2D Vector of characters 46 | * If we are on Land ('1'), and this Position (i.e. 2D index, (0, 0)) has not yet been seen (i.e. not in Seen set) then: 47 | ** Apply the Flood Fill algorithm to the current position. 48 | ** Increment the num\_islands counter. 49 | * Flood Fill will add the Positions of all the connected Land sites to the Seen set, including the starting position (but never Water ('0')). 50 | * We continue until the of the 2D Vector, and return num\_islands when we have checked all Positions. 51 | 52 | We use the recursive Flood Fill implementation created in [Flood Fill](../flood_fill). 53 | 54 | ### Performance 55 | 56 | * The recursive solution will fail for large Vectors as we exceed the stack limit with our stack frames due to the large number of recursive calls. 57 | * Rust does not support tail call recursion to avoid this issue (the compiler could convert the recursion to a loop under the hood, if the recursive call is the final operation in the function). 58 | * Can we avoid visiting every element in the 2D Char Vector? 59 | ** i.e. what if there was one huge land mass, and we still check that all the elements are in Seen, one-by-one? 60 | ** What if we have a large sea mass - can we use flood fill on the sea to avoid checking all of those elements one-by-one? 61 | ** A new island can never be directly adjacent to a previous island, so we can skip those Positions. 62 | 63 | 64 | -------------------------------------------------------------------------------- /reverse_int/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2019 James McMurray 2 | // 3 | // This source code is subject to the terms of the GNU General Public License v3.0. 4 | // You should have received a copy of the GNU General Public License 5 | // along with this source code. If not, see . 6 | 7 | 8 | // https://leetcode.com/problems/reverse-integer/ 9 | 10 | struct Solution {} 11 | 12 | impl Solution { 13 | pub fn reverse(x: i32) -> i32 { 14 | let mut nums: Vec = Solution::reverse_recurse(x); 15 | let mut out: i32 = 0; 16 | nums.reverse(); 17 | 18 | for (i, num) in nums.iter().enumerate() { 19 | match num.overflowing_mul(10_i32.pow(i as u32)) { 20 | (x, false) => match out.overflowing_add(x) { 21 | (_, false) => out += x, 22 | (_, true) => { 23 | out = 0; 24 | break; 25 | } 26 | }, 27 | (_, true) => { 28 | out = 0; 29 | break; 30 | } 31 | } 32 | } 33 | 34 | out 35 | } 36 | 37 | pub fn reverse_recurse(x: i32) -> Vec { 38 | match x { 39 | 0 => vec![], 40 | _ => [vec![(x % 10)], Solution::reverse_recurse(x / 10)].concat(), 41 | } 42 | } 43 | } 44 | 45 | fn main() { 46 | println!("{}", Solution::reverse(123)); 47 | } 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | #[test] 54 | fn test_recurse() { 55 | assert_eq!(Solution::reverse_recurse(123), vec![3, 2, 1]); 56 | } 57 | #[test] 58 | fn test_123() { 59 | assert_eq!(Solution::reverse(123), 321); 60 | } 61 | #[test] 62 | fn test_neg123() { 63 | assert_eq!(Solution::reverse(-123), -321); 64 | } 65 | #[test] 66 | fn test_120() { 67 | assert_eq!(Solution::reverse(120), 21); 68 | } 69 | #[test] 70 | fn test_0() { 71 | assert_eq!(Solution::reverse(0), 0); 72 | } 73 | #[test] 74 | fn test_1000() { 75 | assert_eq!(Solution::reverse(1000), 1); 76 | } 77 | #[test] 78 | fn test_2147483647() { 79 | assert_eq!(Solution::reverse(2147483647), 0); // Overflow 80 | } 81 | #[test] 82 | fn test_1563847412() { 83 | assert_eq!(Solution::reverse(1563847412), 0); // Overflow 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /roman2int/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2019 James McMurray 2 | // 3 | // This source code is subject to the terms of the GNU General Public License v3.0. 4 | // You should have received a copy of the GNU General Public License 5 | // along with this source code. If not, see . 6 | 7 | use std::collections::HashMap; 8 | 9 | 10 | struct Solution {} 11 | 12 | impl Solution { 13 | 14 | pub fn roman_to_int(s: String) -> i32 { 15 | let powers: HashMap = [('I', 1), ('V', 5), ('X', 10), ('L', 50), 16 | ('C', 100), ('D', 500), ('M', 1000)].iter().cloned().collect(); 17 | let mut sum: i32 = 0; 18 | 19 | let s: Vec = s.chars().collect(); 20 | for i in 0 .. s.len() { 21 | let first = s.get(i); 22 | let second = s.get(i+1); 23 | 24 | match (first, second) { 25 | (Some(x), Some(y)) if powers[x] >= powers[y] => sum += powers[x], 26 | (Some(x), Some(y)) if powers[x] < powers[y] => sum -= powers[x], 27 | (Some(x), None) => sum += powers[x], 28 | _ => (), 29 | } 30 | } 31 | println!("{:?}", sum); 32 | sum 33 | } 34 | 35 | } 36 | 37 | 38 | fn main() { 39 | Solution::roman_to_int(String::from("MCMXII")); 40 | } 41 | 42 | 43 | #[cfg(test)] 44 | mod tests { 45 | // Note this useful idiom: importing names from outer (for mod tests) scope. 46 | use super::*; 47 | 48 | #[test] 49 | fn test_xii() { 50 | assert_eq!(Solution::roman_to_int(String::from("XII")), 12); 51 | } 52 | #[test] 53 | fn test_ix() { 54 | assert_eq!(Solution::roman_to_int(String::from("IX")), 9); 55 | } 56 | #[test] 57 | fn test_mcmxii() { 58 | assert_eq!(Solution::roman_to_int(String::from("MCMXII")), 1912); 59 | } 60 | #[test] 61 | fn test_mcmxci() { 62 | assert_eq!(Solution::roman_to_int(String::from("MCMXCI")), 1991); 63 | } 64 | #[test] 65 | fn test_il() { 66 | assert_eq!(Solution::roman_to_int(String::from("IL")), 49); 67 | } 68 | #[test] 69 | fn test_iii() { 70 | assert_eq!(Solution::roman_to_int(String::from("III")), 3); 71 | } 72 | #[test] 73 | fn test_iv() { 74 | assert_eq!(Solution::roman_to_int(String::from("IV")), 4); 75 | } 76 | #[test] 77 | fn test_lviii() { 78 | assert_eq!(Solution::roman_to_int(String::from("LVIII")), 58); 79 | } 80 | #[test] 81 | fn test_mcmxciv() { 82 | assert_eq!(Solution::roman_to_int(String::from("MCMXCIV")), 1994); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /subarray_sum_divisible/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-sums-divisible-by-k/ 2 | 3 | use std::collections::HashMap; 4 | 5 | struct Solution {} 6 | 7 | impl Solution { 8 | pub fn subarrays_div_by_k(a: Vec, k: i32) -> i32 { 9 | let mut seen_modulos: HashMap = HashMap::with_capacity(k as usize); 10 | 11 | let mut result: i32 = 0; 12 | seen_modulos.insert(0, 1); 13 | let mut cumsum = 0; 14 | for num in a { 15 | cumsum += num; 16 | let modulo = cumsum.rem_euclid(k); 17 | result += *seen_modulos 18 | .entry(modulo) 19 | .and_modify(|e| *e += 1) 20 | .or_insert(1) 21 | - 1; 22 | // dbg!(&seen_modulos, &result); 23 | } 24 | result 25 | } 26 | pub fn subarrays_div_by_k_n2(a: Vec, k: i32) -> i32 { 27 | Solution::gen_array(&a) 28 | .iter() 29 | .filter(|&x| (x % k == 0)) 30 | .count() as i32 31 | } 32 | 33 | fn trinum(n: usize) -> usize { 34 | (n * (n + 1)) / 2 35 | } 36 | 37 | fn gen_array(nums: &Vec) -> Vec { 38 | let n = nums.len(); 39 | let mut arr = Vec::with_capacity(Solution::trinum(n)); 40 | 41 | for (i, val) in nums.iter().enumerate() { 42 | let tri = Solution::trinum(i); 43 | arr.push(*val); 44 | for j in 0..i { 45 | // println!("{}, {}", i, j); 46 | let newval = val + arr[j + tri - i]; 47 | arr.push(newval); 48 | } 49 | } 50 | arr 51 | } 52 | } 53 | 54 | fn main() { 55 | println!("Hello, world!"); 56 | } 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | // Note this useful idiom: importing names from outer (for mod tests) scope. 61 | use super::*; 62 | 63 | #[test] 64 | fn test_trinum() { 65 | assert_eq!(Solution::trinum(5), 15); 66 | } 67 | #[test] 68 | fn test_gen_array() { 69 | assert_eq!(Solution::gen_array(&vec![1, 2, 3]), vec![1, 2, 3, 3, 5, 6]); 70 | } 71 | 72 | #[test] 73 | fn test_actual() { 74 | assert_eq!(Solution::subarrays_div_by_k(vec![4, 5, 0, -2, -3, 1], 5), 7); 75 | } 76 | #[test] 77 | fn test_actual2() { 78 | assert_eq!( 79 | Solution::subarrays_div_by_k(vec![0; 30000], 10000), 80 | 450015000 81 | ); 82 | } 83 | #[test] 84 | fn test_actual3() { 85 | assert_eq!(Solution::subarrays_div_by_k(vec![-1, 2, 9], 2), 2); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /coin_boxes/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://www.reddit.com/r/rust/comments/jeu7xj/faang_interview_question_in_rust/ 2 | 3 | // Given an MxN array of “boxes”, where each box contains some number of coins C[i][j], 4 | // you want to maximize the number of coins you can take. You take coins by traversing 5 | // row by row, taking all of the coins from ONE box in each row. However, any time you 6 | // change the index of the box you take coins from, you must pay a “change fee” equal 7 | // to ABS(x - y) where x and y are the previous and new row indices. Write a function 8 | // that can determine the optimal set of boxes to take coins from in order to maximize 9 | // your profit after change fees 10 | 11 | // O(N*M*M) for N rows, M columns 12 | 13 | pub fn coin_problem(mut input: Vec>) -> (i32, Vec) { 14 | let rows = input.len(); 15 | let cols = input[0].len(); 16 | let mut paths: Vec> = (0..cols).map(|x| vec![x]).collect(); 17 | let mut best_elem: usize = 10000; 18 | 19 | for i in 1..rows { 20 | let mut new_paths: Vec> = Vec::with_capacity(cols); 21 | for j in 0..cols { 22 | let mut best_score = -100_000; 23 | for k in 0..cols { 24 | let cur_score = input[i][j] + input[i - 1][k] - (k as i32 - j as i32).abs(); 25 | if cur_score > best_score { 26 | best_score = cur_score; 27 | best_elem = k; 28 | } 29 | } 30 | input[i][j] = best_score; 31 | // TODO: This allocation is bad, could instead use MxN grid of best path taken 32 | // And then reconstruct at the end 33 | let mut new_path = paths[best_elem].clone(); 34 | new_path.push(j); 35 | new_paths.push(new_path); 36 | } 37 | paths = new_paths; 38 | } 39 | 40 | let (best_elem, score) = input 41 | .swap_remove(rows - 1) 42 | .into_iter() 43 | .enumerate() 44 | .max_by(|&(_ind1, val1), &(_ind2, val2)| val1.cmp(&val2)) 45 | .unwrap(); 46 | (score, paths.swap_remove(best_elem)) 47 | } 48 | 49 | fn main() { 50 | println!( 51 | "{:?}", 52 | coin_problem(vec![vec![0, 0, 10, 0], vec![0, 2, 0, 3], vec![5, 0, 0, 0]]) 53 | ); 54 | 55 | println!( 56 | "{:?}", 57 | coin_problem(vec![ 58 | vec![1, 1, 1, 1, 1, 1, 1], 59 | vec![1, 1, 1, 1, 1, 1, 1], 60 | vec![1, 1, 1, 1, 1, 1, 1], 61 | vec![1, 1, 1, 1, 1, 1, 2], 62 | vec![1, 1, 1, 1, 1, 1, 1000], 63 | ]) 64 | ); 65 | } 66 | -------------------------------------------------------------------------------- /count_and_say/src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * The count-and-say sequence is the sequence of integers with the first five terms as following: 3 | 4 | 1 5 | 11 6 | 21 7 | 1211 8 | 111221 9 | 10 | 1 is read off as "one 1" or 11. 11 | 11 is read off as "two 1s" or 21. 12 | 21 is read off as "one 2, then one 1" or 1211. 13 | Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. 14 | Note: Each term of the sequence of integers will be represented as a string. 15 | Example 1: 16 | Input: 1 17 | Output: "1" 18 | Example 2: 19 | Input: 4 20 | Output: "1211" 21 | */ 22 | 23 | struct Solution {} 24 | 25 | struct CountAndSay { 26 | val: u32, 27 | } 28 | 29 | impl CountAndSay { 30 | fn count_and_say(init: u32) -> String { 31 | let mut lastc: char = 'z'; 32 | let mut countc: u32 = 0; 33 | let mut output: String = String::new(); 34 | 35 | for c in format!["{:?}", init].chars() { 36 | if c != lastc { 37 | if countc > 0 { 38 | output.push_str(&format!["{:?}", countc]); 39 | output.push(lastc); 40 | } 41 | countc = 0; 42 | lastc = c; 43 | } 44 | countc += 1; 45 | } 46 | output.push_str(&format!["{:?}", countc]); 47 | output.push(lastc); 48 | output 49 | } 50 | } 51 | 52 | impl Iterator for CountAndSay { 53 | type Item = u32; 54 | 55 | fn next(&mut self) -> Option { 56 | let origval = self.val; 57 | self.val = CountAndSay::count_and_say(self.val).parse().unwrap(); 58 | Some(origval) 59 | } 60 | } 61 | 62 | impl Solution { 63 | fn count_and_say_n(n: usize) -> u32 { 64 | CountAndSay { val: 1 }.nth(n - 1).unwrap() 65 | } 66 | } 67 | 68 | fn main() { 69 | println!("{:?}", CountAndSay { val: 1 }.take(5).collect::>()); 70 | } 71 | 72 | #[cfg(test)] 73 | mod tests { 74 | use super::*; 75 | 76 | #[test] 77 | fn test_generation1() { 78 | assert_eq!(CountAndSay::count_and_say(1), String::from("11")); 79 | } 80 | #[test] 81 | fn test_generation2() { 82 | assert_eq!(CountAndSay::count_and_say(11), String::from("21")); 83 | } 84 | #[test] 85 | fn test_generation3() { 86 | assert_eq!(CountAndSay::count_and_say(21), String::from("1211")); 87 | } 88 | #[test] 89 | fn test_first_element() { 90 | assert_eq!(Solution::count_and_say_n(1), 1); 91 | } 92 | #[test] 93 | fn test_fourth_element() { 94 | assert_eq!(Solution::count_and_say_n(4), 1211); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /add_strings/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/add-strings/ 2 | 3 | struct Solution {} 4 | 5 | impl Solution { 6 | pub fn add_strings(mut num1: String, mut num2: String) -> String { 7 | unsafe { 8 | let n1b = num1.as_bytes_mut(); 9 | n1b.reverse(); 10 | let n2b = num2.as_bytes_mut(); 11 | n2b.reverse(); 12 | 13 | let maxlen = n1b.len().max(n2b.len()); 14 | let mut carry = false; 15 | let mut out_chars: Vec = Vec::with_capacity(maxlen); 16 | 17 | for i in 0..maxlen { 18 | let mut n = 0; 19 | if n1b.get(i).is_some() && n2b.get(i).is_some() { 20 | n = (n1b[i] - 48) + (n2b[i] - 48); 21 | } else if n1b.get(i).is_some() { 22 | n = n1b[i] - 48; 23 | } else if n2b.get(i).is_some() { 24 | n = n2b[i] - 48; 25 | } 26 | 27 | if carry { 28 | n += 1; 29 | carry = false; 30 | } 31 | if n >= 10 { 32 | carry = true; 33 | n = n % 10; 34 | } 35 | out_chars.push(n + 48) 36 | } 37 | if carry { 38 | out_chars.push(49); 39 | } 40 | 41 | out_chars.reverse(); 42 | String::from_utf8_unchecked(out_chars) 43 | } 44 | } 45 | } 46 | 47 | fn main() { 48 | println!( 49 | "{}", 50 | Solution::add_strings("9".to_string(), "99".to_string()) 51 | ); 52 | } 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn test_add() { 60 | assert_eq!(Solution::add_strings("1".to_string(), "1".to_string()), "2"); 61 | } 62 | #[test] 63 | fn test_carry() { 64 | assert_eq!( 65 | Solution::add_strings("9".to_string(), "1".to_string()), 66 | "10" 67 | ); 68 | } 69 | #[test] 70 | fn test_add2() { 71 | assert_eq!( 72 | Solution::add_strings("9".to_string(), "2".to_string()), 73 | "11" 74 | ); 75 | } 76 | #[test] 77 | fn test_add3() { 78 | assert_eq!( 79 | Solution::add_strings("99".to_string(), "99".to_string()), 80 | "198" 81 | ); 82 | } 83 | #[test] 84 | fn test_add4() { 85 | assert_eq!( 86 | Solution::add_strings("1000".to_string(), "1".to_string()), 87 | "1001" 88 | ); 89 | } 90 | #[test] 91 | fn test_add5() { 92 | assert_eq!( 93 | Solution::add_strings("9".to_string(), "99".to_string()), 94 | "108" 95 | ); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /rangesum/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-sum-query-immutable/ 2 | 3 | struct NumArray { 4 | lookup: Vec, 5 | nums: usize, 6 | } 7 | 8 | /** 9 | * `&self` means the method takes an immutable reference. 10 | * If you need a mutable reference, change it to `&mut self` instead. 11 | */ 12 | impl NumArray { 13 | fn new(nums: Vec) -> Self { 14 | let trisize: usize = nums.len() * (nums.len() + 1) / 2; 15 | let mut lookup: Vec = Vec::with_capacity(trisize); 16 | 17 | for (i, vi) in nums.iter().enumerate() { 18 | for (j, vj) in (&nums[i..]).iter().enumerate() { 19 | if j == 0 { 20 | lookup.push(*vj); 21 | } else { 22 | //println!("{}, {}, {}", i, j, (i * (i + 1) / 2) + j - 1); 23 | let thistri = trisize - ((nums.len() - i) * (nums.len() + 1 - i) / 2); 24 | let lastval: i32 = lookup[thistri + j - 1]; 25 | 26 | // Min range 27 | // if lastval <= *vj { 28 | // lookup.push(lastval); 29 | // } else { 30 | // lookup.push(*vj); 31 | // } 32 | // Sum range 33 | lookup.push(lastval + *vj); 34 | } 35 | } 36 | } 37 | 38 | NumArray { 39 | lookup, 40 | nums: nums.len(), 41 | } 42 | } 43 | 44 | fn sum_range(&self, i: i32, j: i32) -> i32 { 45 | let i = i as usize; 46 | let j = j as usize; 47 | let thistri = self.lookup.len() - ((self.nums - i) * (self.nums + 1 - i) / 2); 48 | self.lookup[thistri + (j - i)] 49 | } 50 | } 51 | 52 | /** 53 | * Your NumArray object will be instantiated and called as such: 54 | * let obj = NumArray::new(nums); 55 | * let ret_1: i32 = obj.sum_range(i, j); 56 | */ 57 | 58 | fn main() { 59 | println!("Hello, world!"); 60 | } 61 | 62 | #[cfg(test)] 63 | mod tests { 64 | // Note this useful idiom: importing names from outer (for mod tests) scope. 65 | use super::*; 66 | 67 | #[test] 68 | fn test1() { 69 | let nums: Vec = vec![-2, 0, 3, -5, 2, -1]; 70 | let numarray = NumArray::new(nums); 71 | assert_eq!(numarray.sum_range(0, 2), 1); 72 | } 73 | #[test] 74 | fn test2() { 75 | let nums: Vec = vec![-2, 0, 3, -5, 2, -1]; 76 | let numarray = NumArray::new(nums); 77 | assert_eq!(numarray.sum_range(2, 5), -1); 78 | } 79 | #[test] 80 | fn test3() { 81 | let nums: Vec = vec![-2, 0, 3, -5, 2, -1]; 82 | let numarray = NumArray::new(nums); 83 | assert_eq!(numarray.sum_range(0, 5), -3); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /bipartite_graph/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/is-graph-bipartite/ 2 | 3 | use std::collections::HashSet; 4 | 5 | struct Solution {} 6 | 7 | #[derive(PartialEq)] 8 | enum Colour { 9 | Red, 10 | Blue, 11 | } 12 | 13 | impl Colour { 14 | fn opposite(&self) -> Self { 15 | match self { 16 | Colour::Red => Colour::Blue, 17 | Colour::Blue => Colour::Red, 18 | } 19 | } 20 | } 21 | 22 | impl Solution { 23 | pub fn is_bipartite(graph: Vec>) -> bool { 24 | let mut red: HashSet = HashSet::new(); 25 | let mut blue: HashSet = HashSet::new(); 26 | 27 | // Iterate through nodes 28 | // Set children to opposite colour - BFS or DFS 29 | // If this is impossible (colour already set to other) then not bipartite 30 | // Otherwise is bipartite 31 | // 32 | // For disconnected graph should be sufficient to show that all components are bipartite? 33 | let mut out = true; 34 | for (node, _edges) in graph.iter().enumerate() { 35 | if red.contains(&(node as i32)) || blue.contains(&(node as i32)) { 36 | continue; 37 | } 38 | 39 | let inout = Solution::recurse_colour(node as i32, &graph, red, blue, Colour::Red); 40 | out = out && inout.0; 41 | red = inout.1; 42 | blue = inout.2; 43 | } 44 | out 45 | } 46 | 47 | fn recurse_colour( 48 | node: i32, 49 | graph: &Vec>, 50 | mut red: HashSet, 51 | mut blue: HashSet, 52 | colour: Colour, 53 | ) -> (bool, HashSet, HashSet) { 54 | let (target_set, opposite_set) = match colour { 55 | Colour::Red => (&mut red, &mut blue), 56 | Colour::Blue => (&mut blue, &mut red), 57 | }; 58 | if target_set.contains(&node) { 59 | return (true, red, blue); 60 | } 61 | if opposite_set.contains(&node) { 62 | return (false, red, blue); 63 | } 64 | target_set.insert(node); 65 | 66 | let mut out = true; 67 | for child in graph[node as usize].iter() { 68 | let inout = Solution::recurse_colour(*child, graph, red, blue, colour.opposite()); 69 | out = out && inout.0; 70 | red = inout.1; 71 | blue = inout.2; 72 | } 73 | (out, red, blue) 74 | } 75 | } 76 | 77 | fn main() { 78 | println!("Hello, world!"); 79 | } 80 | 81 | #[cfg(test)] 82 | mod tests { 83 | use super::*; 84 | 85 | #[test] 86 | fn test_true() { 87 | assert_eq!( 88 | Solution::is_bipartite(vec![vec![1, 3], vec![0, 2], vec![1, 3], vec![0, 2]]), 89 | true 90 | ); 91 | } 92 | 93 | #[test] 94 | fn test_false() { 95 | assert_eq!( 96 | Solution::is_bipartite(vec![vec![1, 2, 3], vec![0, 2], vec![0, 1, 3], vec![0, 2]]), 97 | false 98 | ); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /sorting/src/quicksort.rs: -------------------------------------------------------------------------------- 1 | use super::Sort; 2 | 3 | struct QuickSort {} 4 | 5 | impl QuickSort { 6 | /// Move element at index partition_elem to correct place in list] 7 | /// and return its new index 8 | /// We always use last element as pivot element otherwise splitting is painful! 9 | fn partition(slice: &mut [T]) -> usize { 10 | unsafe { 11 | // Pivot element is last element in slice 12 | let (pivot, slice) = slice.split_last_mut().unwrap(); 13 | let mut i = 0; 14 | for j in 0..slice.len() { 15 | // Ensure all elements less than pivot are to the left of i 16 | if slice[j] < *pivot { 17 | slice.swap(j, i); 18 | i += 1; 19 | } 20 | } 21 | 22 | // Recombine split slice (i.e. combining with pivot element on the end) 23 | let len = slice.len() + 1; 24 | let ptr = slice.as_mut_ptr(); 25 | let slice = std::slice::from_raw_parts_mut(ptr, len); 26 | // Swap the pivot element with the ith element 27 | // (i.e. the first element in the slice >= pivot) 28 | // Pivot element is now in the correct position :) 29 | slice.swap(len - 1, i); 30 | i 31 | } 32 | } 33 | 34 | pub fn quicksort(slice: &mut [T]) -> &mut [T] { 35 | if slice.len() <= 1 { 36 | return slice; 37 | } 38 | 39 | let orig_len = slice.len(); 40 | 41 | let pos = Self::partition(slice); 42 | 43 | let (left, right) = slice.split_at_mut(pos); 44 | let (_partition, right) = right.split_first_mut().unwrap(); 45 | 46 | let leftsort = Self::quicksort(left); 47 | let _rightsort = Self::quicksort(right); 48 | 49 | let ptr = leftsort.as_mut_ptr(); 50 | unsafe { std::slice::from_raw_parts_mut(ptr, orig_len) } 51 | } 52 | } 53 | 54 | impl Sort for QuickSort { 55 | fn sort(slice: &mut [T]) -> &mut [T] { 56 | QuickSort::quicksort(slice) 57 | } 58 | } 59 | 60 | #[cfg(test)] 61 | mod tests { 62 | use super::*; 63 | 64 | #[test] 65 | fn it_works() { 66 | let mut to_sort = vec![3, 4, 1, 2]; 67 | let sorted = QuickSort::sort(&mut to_sort); 68 | assert_eq!(sorted, &[1, 2, 3, 4]); 69 | } 70 | #[test] 71 | fn it_works2() { 72 | let mut to_sort = vec![1, 5, 7, 2, 6, 8]; 73 | let sorted = QuickSort::sort(&mut to_sort); 74 | assert_eq!(sorted, &[1, 2, 5, 6, 7, 8]); 75 | } 76 | #[test] 77 | fn it_works3() { 78 | let mut to_sort = vec![ 79 | "aa".to_string(), 80 | "ac".to_string(), 81 | "aa".to_string(), 82 | "ab".to_string(), 83 | ]; 84 | let sorted = QuickSort::sort(&mut to_sort); 85 | assert_eq!( 86 | sorted, 87 | &[ 88 | "aa".to_string(), 89 | "aa".to_string(), 90 | "ab".to_string(), 91 | "ac".to_string() 92 | ] 93 | ); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /traverse_tree_level/src/main.rs: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None 16 | } 17 | } 18 | } 19 | 20 | struct Solution { 21 | } 22 | 23 | 24 | use std::rc::Rc; 25 | use std::cell::RefCell; 26 | impl Solution { 27 | pub fn level_order(root: Option>>) -> Vec> { 28 | let mut curlevel: Vec>> = Vec::new(); 29 | let mut nextlevel: Vec>> = Vec::new(); 30 | let mut output: Vec> = Vec::new(); 31 | 32 | if root.is_none() { return Vec::new() } 33 | 34 | curlevel.push(root.unwrap()); 35 | 36 | loop { 37 | let mut thisoutput: Vec = Vec::new(); 38 | while !curlevel.is_empty(){ 39 | let node = curlevel.pop().unwrap(); 40 | thisoutput.push(node.borrow().val); 41 | if let Some(x) = node.clone().borrow().left.clone() { 42 | nextlevel.push(x); 43 | } 44 | if let Some(x) = node.clone().borrow().right.clone() { 45 | nextlevel.push(x); 46 | } 47 | } 48 | output.push(thisoutput); 49 | nextlevel.reverse(); 50 | if nextlevel.is_empty(){ 51 | break; 52 | } else { 53 | curlevel = nextlevel.clone(); 54 | nextlevel.clear(); 55 | } 56 | } 57 | output 58 | } 59 | } 60 | fn main () -> () { 61 | 62 | } 63 | 64 | 65 | 66 | #[cfg(test)] 67 | mod tests { 68 | // Note this useful idiom: importing names from outer (for mod tests) scope. 69 | use super::*; 70 | 71 | #[test] 72 | fn test_1() { 73 | let mut root = TreeNode::new(3); 74 | root.left = Some(Rc::new(RefCell::new(TreeNode::new(9)))); 75 | root.right = Some(Rc::new(RefCell::new(TreeNode::new(20)))); 76 | { 77 | (&mut root.right).as_mut().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(15)))); 78 | } 79 | { 80 | (&mut root.right).as_mut().unwrap().borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(7)))); 81 | } 82 | 83 | assert_eq!(Solution::level_order(Some(Rc::new(RefCell::new(root)))), vec![vec![3], vec![9, 20], vec![15, 7]]); 84 | } 85 | 86 | #[test] 87 | fn test_2() { 88 | let mut root = TreeNode::new(1); 89 | root.left = Some(Rc::new(RefCell::new(TreeNode::new(2)))); 90 | root.right = Some(Rc::new(RefCell::new(TreeNode::new(3)))); 91 | { 92 | (&mut root.right).as_mut().unwrap().borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(5)))); 93 | } 94 | { 95 | (&mut root.left).as_mut().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(4)))); 96 | } 97 | 98 | assert_eq!(Solution::level_order(Some(Rc::new(RefCell::new(root)))), vec![vec![1], vec![2, 3], vec![4, 5]]); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /alien_dictionary/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/verifying-an-alien-dictionary/ 2 | 3 | use std::mem::MaybeUninit; 4 | struct Solution {} 5 | 6 | impl Solution { 7 | pub fn is_alien_sorted(words: Vec, order: String) -> bool { 8 | let order_arr = Solution::get_order_arr(order); 9 | 10 | words 11 | .as_slice() 12 | .windows(2) 13 | .map(|x| Solution::check_pair(x[0].as_bytes(), x[1].as_bytes(), &order_arr)) 14 | .fold(true, |acc, x| acc && x) 15 | } 16 | 17 | fn get_order_arr(s: String) -> [u8; 26] { 18 | let mut order_arr: [MaybeUninit; 26] = unsafe { MaybeUninit::uninit().assume_init() }; //[0; 26]; 19 | for (i, byte) in s.as_bytes().iter().enumerate() { 20 | // Could skip check here 21 | unsafe { 22 | *order_arr.get_unchecked_mut((*byte - 97) as usize) = MaybeUninit::new(i as u8); 23 | } 24 | } 25 | 26 | unsafe { std::mem::transmute::<_, [u8; 26]>(order_arr) } 27 | 28 | // order_arr 29 | } 30 | fn check_pair(word1: &[u8], word2: &[u8], order: &[u8]) -> bool { 31 | for (i, c1) in word1.iter().enumerate() { 32 | let c2: u8; 33 | if let Some(x) = word2.get(i) { 34 | c2 = *x - 97; 35 | } else { 36 | return false; 37 | } 38 | 39 | if order[(*c1 - 97) as usize] < order[c2 as usize] { 40 | return true; 41 | } 42 | if order[(*c1 - 97) as usize] > order[c2 as usize] { 43 | return false; 44 | } 45 | } 46 | true 47 | } 48 | } 49 | 50 | fn main() { 51 | println!("Hello, world!"); 52 | } 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | // Note this useful idiom: importing names from outer (for mod tests) scope. 57 | use super::*; 58 | 59 | #[test] 60 | fn test1() { 61 | assert!(Solution::is_alien_sorted( 62 | vec![String::from("hello"), String::from("leetcode")], 63 | String::from("hlabcdefgijkmnopqrstuvwxyz") 64 | )) 65 | } 66 | #[test] 67 | fn test2() { 68 | assert_eq!( 69 | Solution::is_alien_sorted( 70 | vec![ 71 | String::from("words"), 72 | String::from("world"), 73 | String::from("row") 74 | ], 75 | String::from("worldabcefghijkmnpqstuvxyz") 76 | ), 77 | false 78 | ) 79 | } 80 | #[test] 81 | fn test3() { 82 | assert_eq!( 83 | Solution::is_alien_sorted( 84 | vec![String::from("apple"), String::from("app")], 85 | String::from("abcdefghijklmnopqrstuvwxyz") 86 | ), 87 | false 88 | ) 89 | } 90 | #[test] 91 | fn test2_sub() { 92 | assert_eq!( 93 | Solution::check_pair( 94 | String::from("words").as_bytes(), 95 | String::from("world").as_bytes(), 96 | &Solution::get_order_arr(String::from("worldabcefghijkmnpqstuvxyz")) 97 | ), 98 | false 99 | ) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /sorting/src/mergesort.rs: -------------------------------------------------------------------------------- 1 | use super::Sort; 2 | 3 | struct MergeSort {} 4 | 5 | impl MergeSort { 6 | pub fn mergesort(slice: &mut [T]) -> &mut [T] { 7 | if slice.len() <= 1 { 8 | return slice; 9 | } 10 | let (left, right) = slice.split_at_mut(slice.len() / 2); 11 | let left = Self::mergesort(left); 12 | let right = Self::mergesort(right); 13 | Self::merge(left, right) 14 | } 15 | 16 | pub fn merge<'a, T: PartialOrd>(left: &'a mut [T], right: &mut [T]) -> &'a mut [T] { 17 | // in-place is too hard :( - https://stackoverflow.com/questions/2571049/how-to-sort-in-place-using-the-merge-sort-algorithm 18 | let mut out_slice = Vec::with_capacity(left.len() + right.len()); 19 | 20 | let mut i = 0; 21 | let mut j = 0; 22 | while i < left.len() || j < right.len() { 23 | if i < left.len() && (j == right.len() || left[i] <= right[j]) { 24 | // Here we really want to pop from front of slice 25 | let val = unsafe { std::ptr::read(&left[i]) }; 26 | out_slice.push(val); 27 | i += 1; 28 | } else { 29 | // Here we really want to pop from front of slice 30 | let val = unsafe { std::ptr::read(&right[j]) }; 31 | out_slice.push(val); 32 | j += 1; 33 | } 34 | } 35 | 36 | unsafe { 37 | // Copy our allocated vector back over the two adjacent, contiguous slices we were given 38 | // And return as a single slice 39 | let len = out_slice.len(); 40 | let ptr = left.as_mut_ptr(); 41 | let out_ptr = out_slice.as_ptr(); 42 | 43 | // Forget so we don't trigger destructors when we overwrite with copy_nonoverlapping 44 | // TODO: Does this leak memory or does dropping the final new slice still drop the 45 | // elements? 46 | std::mem::forget(out_slice); 47 | // Note copy_nonoverlapping handles the size_of:: part for us 48 | std::ptr::copy_nonoverlapping(out_ptr, ptr, len); 49 | std::slice::from_raw_parts_mut(ptr, len) 50 | } 51 | } 52 | } 53 | 54 | impl Sort for MergeSort { 55 | fn sort(slice: &mut [T]) -> &mut [T] { 56 | MergeSort::mergesort(slice) 57 | } 58 | } 59 | 60 | #[cfg(test)] 61 | mod tests { 62 | use super::*; 63 | 64 | #[test] 65 | fn it_works() { 66 | let mut to_sort = vec![3, 4, 1, 2]; 67 | let sorted = MergeSort::sort(&mut to_sort); 68 | assert_eq!(sorted, &[1, 2, 3, 4]); 69 | } 70 | #[test] 71 | fn it_works2() { 72 | let mut to_sort = vec![1, 5, 7, 2, 6, 8]; 73 | let sorted = MergeSort::sort(&mut to_sort); 74 | assert_eq!(sorted, &[1, 2, 5, 6, 7, 8]); 75 | } 76 | #[test] 77 | fn it_works3() { 78 | let mut to_sort = vec![ 79 | "aa".to_string(), 80 | "ac".to_string(), 81 | "aa".to_string(), 82 | "ab".to_string(), 83 | ]; 84 | let sorted = MergeSort::sort(&mut to_sort); 85 | assert_eq!( 86 | sorted, 87 | &[ 88 | "aa".to_string(), 89 | "aa".to_string(), 90 | "ab".to_string(), 91 | "ac".to_string() 92 | ] 93 | ); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /contains_duplicate3/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn contains_nearby_almost_duplicate(nums: Vec, k: i32, t: i32) -> bool { 5 | if nums.len() < 2 { 6 | return false; 7 | } 8 | let mut startindex: usize = 0; 9 | let mut endindex: usize = (nums.len() - 1).min(startindex + k as usize); 10 | let mut sorted = nums[startindex..=endindex].to_vec(); 11 | sorted.sort(); 12 | if Self::check_sorted_diff(&sorted, t) { 13 | return true; 14 | } 15 | 16 | let mut to_add; 17 | let mut to_remove = nums[startindex]; 18 | startindex += 1; 19 | endindex += 1; 20 | while endindex < nums.len() { 21 | to_add = nums[endindex]; 22 | Self::update_sorted(&mut sorted, to_remove, to_add); 23 | if Self::check_sorted_diff(&sorted, t) { 24 | return true; 25 | } 26 | to_remove = nums[startindex]; 27 | startindex += 1; 28 | endindex += 1; 29 | } 30 | 31 | false 32 | } 33 | 34 | fn check_sorted_diff(sorted: &[i32], t: i32) -> bool { 35 | // TODO: Avoud 64-bit case, can use unsafe? 36 | for window in sorted.windows(2) { 37 | if window[1] as i64 - window[0] as i64 <= t as i64 { 38 | return true; 39 | } 40 | } 41 | false 42 | } 43 | 44 | fn update_sorted(sorted: &mut Vec, to_remove: i32, to_add: i32) { 45 | // TODO: Remove double iteration here (can return enum of found type from closure?) 46 | let remove_index = sorted 47 | .iter() 48 | .enumerate() 49 | .find(|x| *x.1 == to_remove) 50 | .unwrap() 51 | .0; 52 | sorted.remove(remove_index); 53 | 54 | let add_index = sorted 55 | .iter() 56 | .enumerate() 57 | .find(|x| *x.1 >= to_add) 58 | .unwrap_or((sorted.len(), &(to_add - 1))) 59 | .0; 60 | sorted.insert(add_index, to_add); 61 | } 62 | } 63 | 64 | fn main() { 65 | println!("Hello, world!"); 66 | } 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | // Note this useful idiom: importing names from outer (for mod tests) scope. 71 | use super::*; 72 | 73 | #[test] 74 | fn test1() { 75 | assert!(Solution::contains_nearby_almost_duplicate( 76 | vec![1, 2, 3, 1], 77 | 3, 78 | 0 79 | )); 80 | } 81 | #[test] 82 | fn test2() { 83 | assert!(Solution::contains_nearby_almost_duplicate( 84 | vec![1, 0, 1, 1], 85 | 1, 86 | 2 87 | )); 88 | } 89 | #[test] 90 | fn test3() { 91 | assert_eq!( 92 | Solution::contains_nearby_almost_duplicate(vec![1, 5, 9, 1, 5, 9], 2, 3), 93 | false 94 | ); 95 | } 96 | 97 | #[test] 98 | fn test4() { 99 | assert_eq!( 100 | Solution::contains_nearby_almost_duplicate(vec![-2147483648, 2147483647], 1, 1), 101 | false 102 | ); 103 | } 104 | #[test] 105 | fn test5() { 106 | assert_eq!( 107 | Solution::contains_nearby_almost_duplicate(vec![2147483646, 2147483647], 3, 3), 108 | true 109 | ); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /max_subarray/src/lib.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray 2 | pub struct Solution {} 3 | 4 | impl Solution { 5 | pub fn max_sub_array(nums: Vec) -> i32 { 6 | // O(N) 7 | let mut cumsum: i32 = 0; 8 | let mut best: i32 = std::i32::MIN; 9 | 10 | for n in nums { 11 | cumsum += n; 12 | if cumsum > best { 13 | best = cumsum; 14 | } 15 | if cumsum < 0 { 16 | cumsum = 0; 17 | } 18 | } 19 | best 20 | } 21 | 22 | pub fn max_sub_array_n2(nums: Vec) -> i32 { 23 | // O(N**2) 24 | Solution::gen_array(&nums).1 25 | } 26 | 27 | fn trinum(n: usize) -> usize { 28 | (n * (n + 1)) / 2 29 | } 30 | 31 | fn gen_array(nums: &Vec) -> (Vec, i32) { 32 | let n = nums.len(); 33 | let mut max: i32 = std::i32::MIN; 34 | let mut arr = Vec::with_capacity(Solution::trinum(n)); 35 | 36 | for (i, val) in nums.iter().enumerate() { 37 | let tri = Solution::trinum(i); 38 | arr.push(*val); 39 | if *val > max { 40 | max = *val 41 | } 42 | for j in 0..i { 43 | let newval = val + arr[j + tri - i]; 44 | arr.push(newval); 45 | if newval > max { 46 | max = newval 47 | } 48 | } 49 | } 50 | (arr, max) 51 | } 52 | 53 | pub fn max_sub_array_n3(nums: Vec) -> i32 { 54 | // O(N**3) 55 | let mut best: i32 = std::i32::MIN; 56 | for i in 0..nums.len() { 57 | for j in i..nums.len() { 58 | let sum = nums[i..=j].iter().sum(); 59 | if sum > best { 60 | best = sum; 61 | } 62 | } 63 | } 64 | best 65 | } 66 | } 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | // Note this useful idiom: importing names from outer (for mod tests) scope. 71 | use super::*; 72 | 73 | #[test] 74 | fn test_trinum() { 75 | assert_eq!(Solution::trinum(5), 15); 76 | } 77 | #[test] 78 | fn test_gen_array() { 79 | assert_eq!( 80 | Solution::gen_array(&vec![1, 2, 3]), 81 | (vec![1, 2, 3, 3, 5, 6], 6) 82 | ); 83 | } 84 | 85 | #[test] 86 | fn test_actual() { 87 | assert_eq!( 88 | Solution::max_sub_array(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), 89 | 6 90 | ); 91 | } 92 | 93 | #[test] 94 | fn test_actual2() { 95 | assert_eq!(Solution::max_sub_array(vec![-1]), -1); 96 | } 97 | 98 | #[test] 99 | fn test_actual_n2() { 100 | assert_eq!( 101 | Solution::max_sub_array_n2(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), 102 | 6 103 | ); 104 | } 105 | 106 | #[test] 107 | fn test_actual2_n2() { 108 | assert_eq!(Solution::max_sub_array_n2(vec![-1]), -1); 109 | } 110 | 111 | #[test] 112 | fn test_actual_n3() { 113 | assert_eq!( 114 | Solution::max_sub_array_n3(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), 115 | 6 116 | ); 117 | } 118 | 119 | #[test] 120 | fn test_actual2_n3() { 121 | assert_eq!(Solution::max_sub_array_n3(vec![-1]), -1); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /array_pair_sum/src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a list of integers, return indices of the two numbers such that they add up to a specific target. 3 | * You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | * Example: 5 | * Given nums = [2, 7, 11, 15], target = 9, 6 | * 7 | * Because nums[0] + nums[1] = 2 + 7 = 9, 8 | */ 9 | 10 | // Extensions: 11 | // If we have repeat values we should decrement our indices over all values and not repeatedly test 12 | // the same ones 13 | // What if we wanted all possible pairs if many are possible? 14 | // What if we allow negative numbers - initial binary search for high_index no longer works, would 15 | // need to start from end of array 16 | 17 | struct Solution {} 18 | 19 | impl Solution { 20 | fn find_pairs(arr: &[i32], target: i32) -> Option<(usize, usize)> { 21 | let mut low_index: usize = 0; 22 | let mut high_index: usize = Solution::binary_search(&arr, target); 23 | 24 | while low_index < high_index { 25 | if arr[low_index] + arr[high_index] == target { 26 | return Some((low_index, high_index)); 27 | } else if arr[low_index] + arr[high_index] > target { 28 | // Decrement high_index 29 | if high_index > 0 { 30 | high_index -= 1; 31 | } else { 32 | return None; 33 | } 34 | } else { 35 | // Increment low_index 36 | low_index += 1; 37 | } 38 | } 39 | None 40 | } 41 | 42 | fn binary_search(arr: &[i32], target: i32) -> usize { 43 | // Recurse with half-slices 44 | let midpoint: usize = arr.len() / 2; 45 | 46 | if arr.len() <= 1 { 47 | return 0; 48 | } 49 | 50 | match arr[midpoint] { 51 | x if x < target => { 52 | midpoint + Solution::binary_search(&arr[midpoint..arr.len()], target) 53 | } 54 | x if x > target => Solution::binary_search(&arr[0..midpoint], target), 55 | x if x == target => midpoint, 56 | _ => midpoint, 57 | } 58 | } 59 | } 60 | 61 | fn main() { 62 | println!( 63 | "{:?}", 64 | Solution::find_pairs(&(vec![2 as i32, 7, 11, 15])[..], 9) 65 | ); 66 | } 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | use super::*; 71 | 72 | #[test] 73 | fn test_bs1() { 74 | assert_eq!( 75 | Solution::binary_search(&(vec![1 as i32, 2, 3, 4, 5])[..], 4), 76 | 3 77 | ); 78 | } 79 | 80 | #[test] 81 | fn test_bs2() { 82 | assert_eq!( 83 | Solution::binary_search(&(vec![1 as i32, 2, 3, 4, 5])[..], 1), 84 | 0 85 | ); 86 | } 87 | #[test] 88 | fn test_bs3() { 89 | assert_eq!(Solution::binary_search(&(vec![1 as i32, 2])[..], 2), 1); 90 | } 91 | #[test] 92 | fn test_bs4() { 93 | assert_eq!(Solution::binary_search(&(vec![1 as i32])[..], 1), 0); 94 | } 95 | #[test] 96 | fn test_bs5() { 97 | assert_eq!(Solution::binary_search(&(vec![1 as i32])[..], 5), 0); 98 | } 99 | #[test] 100 | fn test_bs6() { 101 | assert_eq!(Solution::binary_search(&(vec![1 as i32, 2])[..], 5), 1); 102 | } 103 | #[test] 104 | fn test_bs7() { 105 | assert_eq!(Solution::binary_search(&(vec![1 as i32, 2])[..], 0), 0); 106 | } 107 | 108 | #[test] 109 | fn test_pairs1() { 110 | assert_eq!( 111 | Solution::find_pairs(&(vec![2 as i32, 7, 11, 15])[..], 9), 112 | Some((0, 1)) 113 | ); 114 | } 115 | #[test] 116 | fn test_pairs2() { 117 | assert_eq!( 118 | Solution::find_pairs(&(vec![2 as i32, 7, 11, 15])[..], 10), 119 | None 120 | ); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /num_islands/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2019 James McMurray 2 | // 3 | // This source code is subject to the terms of the GNU General Public License v3.0. 4 | // You should have received a copy of the GNU General Public License 5 | // along with this source code. If not, see . 6 | 7 | // https://leetcode.com/problems/number-of-islands/ 8 | // Recursive solution 9 | 10 | use std::collections::HashSet; 11 | struct Solution(); 12 | 13 | const LAND: char = '1'; 14 | 15 | type Position = (usize, usize); 16 | impl Solution { 17 | pub fn num_islands(grid: Vec>) -> i32 { 18 | let mut seen = HashSet::::new(); 19 | let mut num_i: i32 = 0; 20 | 21 | for y in 0..grid.len() { 22 | for x in 0..grid[y].len() { 23 | if grid[y][x] == LAND && !seen.contains(&(y, x)) { 24 | num_i = num_i + 1; 25 | Solution::flood_fill((y, x), &grid, &mut seen); 26 | } 27 | } 28 | } 29 | num_i 30 | } 31 | 32 | fn flood_fill(pos: Position, grid: &Vec>, seen: &mut HashSet) -> () { 33 | seen.insert(pos); 34 | 35 | // Left 36 | if !seen.contains(&(pos.0, pos.1.overflowing_sub(1).0)) { 37 | match grid[pos.0].get(pos.1.overflowing_sub(1).0) { 38 | Some(x) if *x == LAND => { 39 | Solution::flood_fill((pos.0, pos.1.overflowing_sub(1).0), &grid, seen); 40 | } 41 | _ => (), 42 | } 43 | } 44 | // Right 45 | if !seen.contains(&(pos.0, pos.1 + 1)) { 46 | match grid[pos.0].get(pos.1 + 1) { 47 | Some(x) if *x == LAND => { 48 | Solution::flood_fill((pos.0, pos.1 + 1), &grid, seen); 49 | } 50 | _ => (), 51 | } 52 | } 53 | // Up 54 | if !seen.contains(&(pos.0.overflowing_sub(1).0, pos.1)) { 55 | match grid.get(pos.0.overflowing_sub(1).0) { 56 | Some(x) if x[pos.1] == LAND => { 57 | Solution::flood_fill((pos.0.overflowing_sub(1).0, pos.1), &grid, seen); 58 | } 59 | _ => (), 60 | } 61 | } 62 | // Down 63 | if !seen.contains(&(pos.0 + 1, pos.1)) { 64 | match grid.get(pos.0 + 1) { 65 | Some(x) if x[pos.1] == LAND => { 66 | Solution::flood_fill((pos.0 + 1, pos.1), &grid, seen); 67 | } 68 | _ => (), 69 | } 70 | } 71 | } 72 | } 73 | 74 | fn main() { 75 | let grid: Vec> = vec![ 76 | vec!['1', '1', '0', '0', '0'], 77 | vec!['1', '1', '0', '0', '0'], 78 | vec!['0', '0', '1', '0', '0'], 79 | vec!['0', '0', '0', '1', '1'], 80 | ]; 81 | println!("{}", Solution::num_islands(grid)); 82 | } 83 | 84 | #[cfg(test)] 85 | mod tests { 86 | // Note this useful idiom: importing names from outer (for mod tests) scope. 87 | use super::*; 88 | 89 | #[test] 90 | fn test_islands1() { 91 | let grid: Vec> = vec![ 92 | vec!['1', '1', '1', '1', '0'], 93 | vec!['1', '1', '0', '1', '0'], 94 | vec!['1', '1', '0', '0', '0'], 95 | vec!['0', '0', '0', '0', '0'], 96 | ]; 97 | assert_eq!(Solution::num_islands(grid), 1); 98 | } 99 | 100 | #[test] 101 | fn test_islands2() { 102 | let grid: Vec> = vec![ 103 | vec!['1', '1', '0', '0', '0'], 104 | vec!['1', '1', '0', '0', '0'], 105 | vec!['0', '0', '1', '0', '0'], 106 | vec!['0', '0', '0', '1', '1'], 107 | ]; 108 | assert_eq!(Solution::num_islands(grid), 3); 109 | } 110 | 111 | #[test] 112 | fn test_flood_fill1() { 113 | let mut seen = HashSet::::new(); 114 | let grid: Vec> = vec![ 115 | vec!['1', '1', '1', '1', '0'], 116 | vec!['1', '1', '0', '1', '0'], 117 | vec!['1', '1', '0', '0', '0'], 118 | vec!['0', '0', '0', '0', '0'], 119 | ]; 120 | Solution::flood_fill((0, 0), &grid, &mut seen); 121 | assert!( 122 | seen.contains(&(0, 0)) 123 | && seen.contains(&(0, 1)) 124 | && seen.contains(&(0, 2)) 125 | && seen.contains(&(0, 3)) 126 | && seen.contains(&(1, 0)) 127 | && seen.contains(&(1, 1)) 128 | && seen.contains(&(1, 3)) 129 | && seen.contains(&(2, 0)) 130 | && seen.contains(&(2, 1)) 131 | && !seen.contains(&(0, 4)) 132 | ); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /expression_tree/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | use std::rc::Rc; 3 | 4 | #[derive(Debug, Clone)] 5 | struct Node { 6 | value: Symbol, 7 | children: (Option>>, Option>>), 8 | } 9 | 10 | impl Node { 11 | pub fn new( 12 | value: Symbol, 13 | children: (Option>>, Option>>), 14 | ) -> Self { 15 | Self { value, children } 16 | } 17 | } 18 | 19 | #[derive(Debug, Clone, Copy)] 20 | enum Symbol { 21 | Operator(char), 22 | Value(u32), 23 | } 24 | 25 | fn split_with_matches<'a, F>(s: &'a str, f: F) -> Vec<&'a str> 26 | where 27 | F: Fn(char) -> bool, 28 | { 29 | let mut out: Vec<&'a str> = Vec::new(); 30 | let mut prevpos: usize = 0; 31 | 32 | for (pos, c) in s.bytes().enumerate() { 33 | if f(c as char) { 34 | if prevpos != pos { 35 | out.push(&s[prevpos..pos]); 36 | } 37 | out.push(&s[pos..pos + 1]); 38 | prevpos = pos + 1; 39 | } 40 | } 41 | if prevpos != s.len() { 42 | out.push(&s[prevpos..]); 43 | } 44 | out 45 | } 46 | 47 | fn parse(s: &str) -> Node { 48 | let operators: Vec = vec!['/', '*', '+', '-']; 49 | let mut root: Option>> = None; 50 | 51 | for c in split_with_matches( 52 | &s.chars().filter(|c| !c.is_whitespace()).collect::(), 53 | |c: char| operators.contains(&c), 54 | ) { 55 | let symbol: Symbol = match c { 56 | c if operators.contains(&c.parse::().unwrap_or('9')) => { 57 | Symbol::Operator(c.parse::().unwrap()) 58 | } 59 | x => Symbol::Value(x.parse::().unwrap()), 60 | }; 61 | 62 | println!("{:?}", symbol); 63 | // Empty tree 64 | if let None = root { 65 | root = Some(Rc::new(RefCell::new(Node::new(symbol, (None, None))))); 66 | continue; 67 | } 68 | 69 | // Root is Value so we are on second element - operator 70 | if let Symbol::Value(_) = { root.as_ref().unwrap().clone().borrow().value.clone() } { 71 | // TODO: Fix clone 72 | let origval = { root.as_ref().unwrap().clone().borrow().clone() }; 73 | root = Some(Rc::new(RefCell::new(Node::new( 74 | symbol, 75 | (Some(Rc::new(RefCell::new(origval))), None), 76 | )))); 77 | continue; 78 | } 79 | 80 | // Root has no right child, so fill that (we must be value) 81 | if { 82 | root.as_ref() 83 | .unwrap() 84 | .clone() 85 | .borrow() 86 | .children 87 | .1 88 | .clone() 89 | .is_none() 90 | } { 91 | root.as_ref().unwrap().borrow_mut().children.1 = 92 | Some(Rc::new(RefCell::new(Node::new(symbol, (None, None))))); 93 | continue; 94 | } 95 | 96 | // Traverse tree - values are leaf nodes 97 | // Lowest precedence should be at root 98 | // Traverse operators until we find operator that is higher precedence - we should be parent of that subtree 99 | if let Symbol::Operator(o) = symbol { 100 | if let Symbol::Operator(o2) = { root.as_ref().unwrap().borrow().value } { 101 | if operators.iter().position(|&r| r == o) >= operators.iter().position(|&r| r == o2) 102 | { 103 | (&root).as_ref().unwrap().replace(Node::new( 104 | symbol, 105 | ( 106 | Some(Rc::new(RefCell::new( 107 | // TODO: Fix clone 108 | Rc::try_unwrap(root.as_ref().unwrap().clone()) 109 | .unwrap() 110 | .into_inner(), 111 | ))), 112 | None, 113 | ), 114 | )); 115 | continue; 116 | } else { 117 | // TODO: if children are values (leaf nodes) 118 | // TODO: loop here 119 | let movechild = ((&root).as_ref().unwrap().borrow_mut().children).1.take(); 120 | (&root).as_ref().unwrap().borrow_mut().children.1 = 121 | Some(Rc::new(RefCell::new(Node::new(symbol, (movechild, None))))); 122 | 123 | continue; 124 | } 125 | } 126 | } else { 127 | // Symbol is Value not Operator 128 | // Fill last none with value 129 | } 130 | } 131 | 132 | let out = Rc::try_unwrap(root.unwrap()).unwrap().into_inner(); 133 | out 134 | } 135 | 136 | fn main() { 137 | println!("{:?}", parse("25 + 3 + 2")); 138 | } 139 | -------------------------------------------------------------------------------- /int2roman/src/main.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | use std::collections::HashSet; 4 | use std::iter::FromIterator; 5 | 6 | impl Solution { 7 | pub fn int_to_roman(num: i32) -> String { 8 | let powers: Vec<(i32, char)> = vec![ 9 | (1000, 'M'), 10 | (500, 'D'), 11 | (100, 'C'), 12 | (50, 'L'), 13 | (10, 'X'), 14 | (5, 'V'), 15 | (1, 'I'), 16 | ]; 17 | // Loop through powers find first divisible 18 | // Check if we are within one rank lower of the rank higher, i.e. within 10 of 100 if >= 50 19 | // If so we use subtraction form (subtract greatest power): XCIII - 93 20 | // Else just add this rank and recurse on subtraction i.e. L + int_to_roman(6) - 56 21 | if num == 0 { 22 | return String::from(""); 23 | } 24 | 25 | for (i, item) in powers.iter().enumerate() { 26 | if num / item.0 == 0 { 27 | continue; 28 | } 29 | // Subtraction 30 | if let Some(_x) = powers.get(i + (i % 2)) { 31 | if i > 0 { 32 | let y = powers[i - 1]; 33 | if let Some(z) = 34 | Solution::greatest_power(y.0, num, &powers[i..(i + 1 + (i % 2))]) 35 | { 36 | return z.1.to_string() 37 | + &y.1.to_string() 38 | + &Solution::int_to_roman(num - (y.0 - z.0)); 39 | } 40 | } 41 | } 42 | // Addition 43 | return item.1.to_string() + &Solution::int_to_roman(num - item.0); 44 | } 45 | String::from("ERROR") 46 | } 47 | 48 | fn greatest_power(limit: i32, n: i32, powers: &[(i32, char)]) -> Option<(i32, char)> { 49 | // let powers: Vec<(i32, char)> = vec![(1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I')]; 50 | let vals: HashSet = HashSet::from_iter(powers.iter().map(|x| x.0)); 51 | for p in powers { 52 | if p.0 < limit 53 | && (limit - p.0) <= n 54 | && (p.0 < limit / 2) 55 | && (!(vals.contains(&(limit - n)))) 56 | || (p.0 == (limit - n) && p.0 != n) 57 | { 58 | return Some(*p); 59 | } 60 | } 61 | None 62 | } 63 | } 64 | 65 | fn main() { 66 | println!("Hello, world!"); 67 | } 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | // Note this useful idiom: importing names from outer (for mod tests) scope. 72 | use super::*; 73 | 74 | #[test] 75 | fn test_xlv() { 76 | assert_eq!(Solution::int_to_roman(45), String::from("XLV")); 77 | } 78 | #[test] 79 | fn test_v() { 80 | assert_eq!(Solution::int_to_roman(5), String::from("V")); 81 | } 82 | #[test] 83 | fn test_i() { 84 | assert_eq!(Solution::int_to_roman(1), String::from("I")); 85 | } 86 | #[test] 87 | fn test_mmm() { 88 | assert_eq!(Solution::int_to_roman(3000), String::from("MMM")); 89 | } 90 | #[test] 91 | fn test_ic() { 92 | assert_eq!(Solution::int_to_roman(99), String::from("XCIX")); 93 | } 94 | #[test] 95 | fn test_xm() { 96 | assert_eq!(Solution::int_to_roman(990), String::from("CMXC")); 97 | } 98 | #[test] 99 | fn test_xlviii() { 100 | assert_eq!(Solution::int_to_roman(48), String::from("XLVIII")); 101 | } 102 | #[test] 103 | fn test_xl() { 104 | assert_eq!(Solution::int_to_roman(40), String::from("XL")); 105 | } 106 | #[test] 107 | fn test_xii() { 108 | assert_eq!(Solution::int_to_roman(12), String::from("XII")); 109 | } 110 | #[test] 111 | fn test_ix() { 112 | assert_eq!(Solution::int_to_roman(9), String::from("IX")); 113 | } 114 | #[test] 115 | fn test_mcmxii() { 116 | assert_eq!(Solution::int_to_roman(1912), String::from("MCMXII")); 117 | } 118 | #[test] 119 | fn test_cmxci() { 120 | assert_eq!(Solution::int_to_roman(991), String::from("CMXCI")); 121 | } 122 | #[test] 123 | fn test_mcmxci() { 124 | assert_eq!(Solution::int_to_roman(1991), String::from("MCMXCI")); 125 | } 126 | #[test] 127 | fn test_il() { 128 | assert_eq!(Solution::int_to_roman(49), String::from("XLIX")); 129 | } 130 | #[test] 131 | fn test_iii() { 132 | assert_eq!(Solution::int_to_roman(3), String::from("III")); 133 | } 134 | #[test] 135 | fn test_iv() { 136 | assert_eq!(Solution::int_to_roman(4), String::from("IV")); 137 | } 138 | #[test] 139 | fn test_lviii() { 140 | assert_eq!(Solution::int_to_roman(58), String::from("LVIII")); 141 | } 142 | #[test] 143 | fn test_mcmxciv() { 144 | assert_eq!(Solution::int_to_roman(1994), String::from("MCMXCIV")); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /flood_fill/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2019 James McMurray 2 | // 3 | // This source code is subject to the terms of the GNU General Public License v3.0. 4 | // You should have received a copy of the GNU General Public License 5 | // along with this source code. If not, see . 6 | 7 | // Recursive solution 8 | struct Solution(); 9 | 10 | impl Solution { 11 | pub fn flood_fill(image: Vec>, sr: i32, sc: i32, new_color: i32) -> Vec> { 12 | let mut copy: Vec> = image; 13 | Solution::flood_fill_recurse( 14 | &mut copy, 15 | sr as usize, 16 | sc as usize, 17 | new_color, 18 | ); 19 | copy 20 | } 21 | 22 | fn flood_fill_recurse(mut m: &mut Vec>, sr: usize, sc: usize, new_color: i32) { 23 | let origval: i32 = m[sr][sc]; 24 | if new_color == origval { 25 | return; 26 | } 27 | m[sr][sc] = new_color; 28 | 29 | // Left 30 | match m[sr].get(sc.overflowing_sub(1).0) { 31 | Some(x) if *x == origval => { 32 | Solution::flood_fill_recurse(&mut m, sr, sc.overflowing_sub(1).0, new_color); 33 | } 34 | _ => (), 35 | } 36 | // Right 37 | match m[sr].get(sc + 1) { 38 | Some(x) if *x == origval => { 39 | Solution::flood_fill_recurse(&mut m, sr, sc + 1, new_color); 40 | } 41 | _ => (), 42 | } 43 | // Up 44 | match m.get(sr.overflowing_sub(1).0) { 45 | Some(x) if x[sc] == origval => { 46 | Solution::flood_fill_recurse(&mut m, sr.overflowing_sub(1).0, sc, new_color); 47 | } 48 | _ => (), 49 | } 50 | // Down 51 | match m.get(sr + 1) { 52 | Some(x) if x[sc] == origval => { 53 | Solution::flood_fill_recurse(&mut m, sr + 1, sc, new_color); 54 | } 55 | _ => (), 56 | } 57 | } 58 | } 59 | 60 | fn main() { 61 | let m: Vec> = vec![ 62 | vec![0, 0, 1, 0], 63 | vec![0, 0, 1, 1], 64 | vec![0, 0, 1, 1], 65 | vec![0, 0, 0, 0], 66 | ]; 67 | let out = Solution::flood_fill(m, 0, 0, 2); 68 | println!("{:#?}", out); 69 | } 70 | 71 | #[cfg(test)] 72 | mod tests { 73 | // Note this useful idiom: importing names from outer (for mod tests) scope. 74 | use super::*; 75 | 76 | #[test] 77 | fn test_leetcode_flood() { 78 | let m: Vec> = vec![vec![1, 1, 1], vec![1, 1, 0], vec![1, 0, 1]]; 79 | let result: Vec> = vec![vec![2, 2, 2], vec![2, 2, 0], vec![2, 0, 1]]; 80 | let out = Solution::flood_fill(m, 0, 0, 2); 81 | assert_eq!(out, result); 82 | } 83 | 84 | #[test] 85 | fn test_flood1() { 86 | let m: Vec> = vec![ 87 | vec![0, 0, 1, 0], 88 | vec![0, 0, 1, 1], 89 | vec![0, 0, 1, 1], 90 | vec![0, 0, 0, 0], 91 | ]; 92 | let result: Vec> = vec![ 93 | vec![2, 2, 1, 0], 94 | vec![2, 2, 1, 1], 95 | vec![2, 2, 1, 1], 96 | vec![2, 2, 2, 2], 97 | ]; 98 | let out = Solution::flood_fill(m, 0, 0, 2); 99 | assert_eq!(out, result); 100 | } 101 | 102 | #[test] 103 | fn test_flood2() { 104 | let m: Vec> = vec![ 105 | vec![0, 0, 1, 0], 106 | vec![0, 0, 1, 1], 107 | vec![0, 0, 1, 1], 108 | vec![0, 0, 0, 0], 109 | ]; 110 | let result: Vec> = vec![ 111 | vec![0, 0, 1, 2], 112 | vec![0, 0, 1, 1], 113 | vec![0, 0, 1, 1], 114 | vec![0, 0, 0, 0], 115 | ]; 116 | let out = Solution::flood_fill(m, 0, 3, 2); 117 | assert_eq!(out, result); 118 | } 119 | 120 | #[test] 121 | fn test_flood3() { 122 | let m: Vec> = vec![ 123 | vec![0, 0, 1, 0], 124 | vec![0, 0, 1, 1], 125 | vec![0, 0, 1, 1], 126 | vec![0, 0, 0, 0], 127 | ]; 128 | let result: Vec> = vec![ 129 | vec![0, 0, 3, 0], 130 | vec![0, 0, 3, 3], 131 | vec![0, 0, 3, 3], 132 | vec![0, 0, 0, 0], 133 | ]; 134 | let out = Solution::flood_fill(m, 2, 3, 3); 135 | assert_eq!(out, result); 136 | } 137 | #[test] 138 | fn test_flood4() { 139 | let m: Vec> = vec![ 140 | vec![0, 0, 1, 0], 141 | vec![0, 0, 1, 1], 142 | vec![0, 0, 1, 1], 143 | vec![0, 0, 0, 0], 144 | ]; 145 | let result: Vec> = vec![ 146 | vec![0, 0, 1, 0], 147 | vec![0, 0, 1, 1], 148 | vec![0, 0, 1, 1], 149 | vec![0, 0, 0, 0], 150 | ]; 151 | let out = Solution::flood_fill(m, 0, 0, 0); 152 | assert_eq!(out, result); 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /runlength/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/string-compression 2 | 3 | struct Solution {} 4 | 5 | impl Solution { 6 | pub fn compress(chars: &mut Vec) -> i32 { 7 | let mut ptr = chars.as_mut_ptr(); 8 | let mut vec_length = chars.len(); 9 | 10 | let mut cur_char: Option = None; 11 | let mut cur_count: u32 = 0; 12 | let mut new_length: usize = 0; 13 | 14 | for i in 0..vec_length { 15 | unsafe { 16 | match cur_char { 17 | None => { 18 | cur_char = Some(*ptr); 19 | cur_count = 1; 20 | } 21 | Some(c) if c == *(ptr.offset(i as isize)) => { 22 | cur_count += 1; 23 | } 24 | Some(c) if c != *(ptr.offset(i as isize)) => { 25 | // Write 26 | 27 | *(ptr.offset(new_length as isize)) = cur_char.unwrap(); 28 | cur_char = Some(*(ptr.offset(i as isize))); 29 | new_length += 1; 30 | 31 | if cur_count > 1 { 32 | // Write cur_count 33 | // *(ptr + new_length + 1) = cur_count; 34 | 35 | let mut num_digits: usize = 0; 36 | 37 | for (ix, power) in [1000, 100, 10, 1].iter().enumerate() { 38 | if cur_count / power > 0 { 39 | *(ptr.offset((new_length + num_digits) as isize)) = 40 | std::char::from_digit(cur_count / power, 10).unwrap(); 41 | num_digits += 1; 42 | cur_count = cur_count % power; 43 | if cur_count == 0 { 44 | for _j in 0..(3 - ix) { 45 | *(ptr.offset((new_length + num_digits) as isize)) = '0'; 46 | num_digits += 1; 47 | } 48 | break; 49 | } 50 | } 51 | } 52 | new_length += num_digits; 53 | } 54 | 55 | cur_count = 1; 56 | } 57 | _ => { 58 | panic!("bad case"); 59 | } 60 | } 61 | } 62 | } 63 | 64 | // Write last piece 65 | unsafe { 66 | *(ptr.offset(new_length as isize)) = cur_char.unwrap(); 67 | new_length += 1; 68 | 69 | if cur_count > 1 { 70 | // Write cur_count 71 | // *(ptr + new_length + 1) = cur_count; 72 | 73 | let mut num_digits: usize = 0; 74 | 75 | for (ix, power) in [1000, 100, 10, 1].iter().enumerate() { 76 | if cur_count / power > 0 { 77 | *(ptr.offset((new_length + num_digits) as isize)) = 78 | std::char::from_digit(cur_count / power, 10).unwrap(); 79 | num_digits += 1; 80 | cur_count = cur_count % power; 81 | if cur_count == 0 { 82 | for _j in 0..(3 - ix) { 83 | *(ptr.offset((new_length + num_digits) as isize)) = '0'; 84 | num_digits += 1; 85 | } 86 | break; 87 | } 88 | } 89 | } 90 | new_length += num_digits; 91 | } 92 | } 93 | 94 | (new_length) as i32 95 | } 96 | } 97 | 98 | fn main() { 99 | println!("Hello, world!"); 100 | } 101 | 102 | #[cfg(test)] 103 | mod tests { 104 | // Note this useful idiom: importing names from outer (for mod tests) scope. 105 | use super::*; 106 | 107 | #[test] 108 | fn test1() { 109 | let mut chars = vec!['a', 'a', 'b', 'b', 'c', 'c', 'c']; 110 | let out = Solution::compress(&mut chars); 111 | assert_eq!(out, 6); 112 | assert_eq!(&chars[0..6], &['a', '2', 'b', '2', 'c', '3']); 113 | } 114 | 115 | #[test] 116 | fn test2() { 117 | let mut chars = vec!['a']; 118 | let out = Solution::compress(&mut chars); 119 | assert_eq!(out, 1); 120 | assert_eq!(&chars[0..1], &['a']); 121 | } 122 | 123 | #[test] 124 | fn test3() { 125 | let mut chars = vec![ 126 | 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 127 | ]; 128 | let out = Solution::compress(&mut chars); 129 | assert_eq!(out, 4); 130 | assert_eq!(&chars[0..4], &['a', 'b', '1', '2']); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /ocr_scan/src/main.rs: -------------------------------------------------------------------------------- 1 | // An Optical Character Recognition (OCR) scanner scans an image of text 2 | // and tries to produce a string. However, sometimes characters cannot be 3 | // correctly identified are marked as unknown with a question mark: ? 4 | 5 | // e.g. "Apple" might be scanned as "A??le" if the "p"s are not identified 6 | // correctly. 7 | 8 | // Our OCR scanner compresses the output, so that a run of N unidentified 9 | // characters is written as the number N. i.e. the above output would 10 | // actually be "A2le" 11 | 12 | // Our text only contains uppercase and lowercase ASCII letters A-Z and a-z. 13 | 14 | // Write a function that can take the output of two OCR scans and return 15 | // true if they could be the same string or false if they could not be 16 | // the same string. 17 | 18 | // e.g. A2le and Ap2e could be from the same string: Apple 19 | 20 | // But Am1le and Ap2e could not be. 21 | 22 | // Note that the scans must have exactly the same length to be the 23 | // same underlying string, i.e. A2le3 and A2le2 have different total lengths and so 24 | // could not represent the same string. 25 | 26 | #[derive(Debug, Clone, Copy, PartialEq)] 27 | pub enum Token { 28 | Char(char), 29 | Number(u32), 30 | } 31 | 32 | pub fn get_next_token>( 33 | ic: &mut std::iter::Peekable, 34 | ) -> Option { 35 | match ic.peek() { 36 | None => { 37 | ic.next(); 38 | None 39 | } 40 | // if number then read parse whole number 41 | Some(c) if c.is_digit(10) => { 42 | let mut num = ic.next().unwrap().to_digit(10).unwrap(); 43 | while let Some(x) = ic.peek() { 44 | if x.is_digit(10) { 45 | num *= 10; 46 | num += ic.next().unwrap().to_digit(10).unwrap(); 47 | } else { 48 | break; 49 | } 50 | } 51 | Some(Token::Number(num)) 52 | } 53 | // else return char 54 | Some(_) => Some(Token::Char(ic.next().unwrap())), 55 | } 56 | } 57 | 58 | pub fn same_string(s1: &str, s2: &str) -> bool { 59 | let mut s1_chars = s1.chars().peekable(); 60 | let mut s2_chars = s2.chars().peekable(); 61 | 62 | let mut c1 = get_next_token(&mut s1_chars); 63 | let mut c2 = get_next_token(&mut s2_chars); 64 | 65 | loop { 66 | match (c1, c2) { 67 | (None, None) => break true, 68 | (None, _) => break false, 69 | (_, None) => break false, 70 | (Some(Token::Number(n)), Some(Token::Number(m))) => { 71 | if n > 1 { 72 | c1 = Some(Token::Number(n - 1)); 73 | } else { 74 | c1 = get_next_token(&mut s1_chars); 75 | } 76 | 77 | if m > 1 { 78 | c2 = Some(Token::Number(m - 1)); 79 | } else { 80 | c2 = get_next_token(&mut s2_chars); 81 | } 82 | } 83 | (Some(Token::Number(n)), Some(Token::Char(_))) => { 84 | if n > 1 { 85 | c1 = Some(Token::Number(n - 1)); 86 | } else { 87 | c1 = get_next_token(&mut s1_chars); 88 | } 89 | c2 = get_next_token(&mut s2_chars); 90 | } 91 | (Some(Token::Char(_)), Some(Token::Number(m))) => { 92 | if m > 1 { 93 | c2 = Some(Token::Number(m - 1)); 94 | } else { 95 | c2 = get_next_token(&mut s2_chars); 96 | } 97 | c1 = get_next_token(&mut s1_chars); 98 | } 99 | (Some(Token::Char(a)), Some(Token::Char(b))) => { 100 | if a != b { 101 | break false; 102 | } else { 103 | c1 = get_next_token(&mut s1_chars); 104 | c2 = get_next_token(&mut s2_chars); 105 | } 106 | } 107 | } 108 | } 109 | } 110 | 111 | #[cfg(test)] 112 | mod tests { 113 | // Note this useful idiom: importing names from outer (for mod tests) scope. 114 | use super::*; 115 | 116 | #[test] 117 | fn test_true() { 118 | assert_eq!(same_string("A2le", "Ap2e"), true); 119 | } 120 | #[test] 121 | fn test_true_no_unknown() { 122 | assert_eq!(same_string("Apple", "Apple"), true); 123 | } 124 | 125 | #[test] 126 | fn test_false() { 127 | assert_eq!(same_string("Am1le", "Ap2e"), false); 128 | } 129 | #[test] 130 | fn test_false_length() { 131 | // Strings must have exact same length, we do not allow substring "matches" 132 | assert_eq!(same_string("A2le3", "A2le2"), false); 133 | } 134 | #[test] 135 | fn test_long_false() { 136 | assert_eq!(same_string("50000a49999", "50000b49999"), false); 137 | } 138 | #[test] 139 | fn test_long_true() { 140 | assert_eq!(same_string("49999a50000", "50000b49999"), true); 141 | } 142 | #[test] 143 | fn test_long_true_repeat() { 144 | assert_eq!(same_string("15a4de3", "14bad3d4"), true); 145 | } 146 | #[test] 147 | fn test_long_true_identical() { 148 | assert_eq!(same_string("15a5de3", "15a5de3"), true); 149 | } 150 | #[test] 151 | fn test_long_false_repeat() { 152 | assert_eq!(same_string("15a5de3", "14bcd3d4"), false); 153 | } 154 | #[test] 155 | fn short_test1() { 156 | assert_eq!(same_string("A2Le", "2pL1"), true); 157 | } 158 | #[test] 159 | fn short_test2() { 160 | assert_eq!(same_string("a10", "10a"), true); 161 | } 162 | #[test] 163 | fn short_test3() { 164 | assert_eq!(same_string("ba1", "1Ad"), false); 165 | } 166 | #[test] 167 | fn short_test4() { 168 | assert_eq!(same_string("3x2x", "8"), false); 169 | } 170 | } 171 | 172 | fn main() { 173 | println!("Hello, world!"); 174 | } 175 | -------------------------------------------------------------------------------- /word_break2/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-break-ii/ 2 | //TODO: Spawns Too many theads: 3 | //"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 4 | //["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] 5 | 6 | #[macro_use] 7 | extern crate maplit; 8 | 9 | use std::collections::HashSet; 10 | use std::iter::FromIterator; 11 | use std::sync::Arc; 12 | 13 | struct Task { 14 | found_words: Vec, 15 | word_dict: Arc>, 16 | cs: String 17 | } 18 | 19 | impl Task { 20 | pub fn join(self) -> Vec> { 21 | Solution::word_break_inner(self.cs, self.word_dict, self.found_words) 22 | } 23 | } 24 | 25 | struct Solution {} 26 | 27 | impl Solution { 28 | pub fn word_break(s: String, word_dict: Vec) -> Vec { 29 | let word_set: HashSet = HashSet::from_iter(word_dict); 30 | Solution::word_break_inner(s, Arc::new(word_set), Vec::new()) 31 | .iter() 32 | .map(|x| String::from(x.join(" "))) 33 | .collect() 34 | } 35 | 36 | pub fn word_break_inner( 37 | cs: String, 38 | word_dict: Arc>, 39 | mut found_words: Vec, 40 | ) -> Vec> { 41 | let mut teststring: String = String::new(); 42 | let chars_remaining: usize = cs.len(); 43 | let mut my_threads: Vec = Vec::new(); 44 | let mut output: Vec> = Vec::new(); 45 | let maxlen: usize = word_dict.iter().map(|x| x.len()).max().unwrap_or(0); 46 | 47 | for (i, c) in cs.chars().enumerate() { 48 | if i > maxlen {break;} 49 | teststring.push(c); 50 | if i < chars_remaining - 1 { 51 | if word_dict.contains(&teststring) { 52 | let newstr: String = cs[i + 1..cs.len()].into(); 53 | let mut new_fw: Vec = found_words.clone(); 54 | let shared_wd = word_dict.clone(); 55 | new_fw.push(teststring.clone()); 56 | 57 | my_threads.push( Task { 58 | cs: newstr, 59 | word_dict: shared_wd, 60 | found_words: new_fw, 61 | }); 62 | 63 | } 64 | } else { 65 | if word_dict.contains(&teststring) { 66 | for thread in my_threads { 67 | for v in thread.join() { 68 | output.push(v); 69 | } 70 | } 71 | found_words.push(teststring); 72 | output.push(found_words); 73 | return output; 74 | } 75 | } 76 | } 77 | for thread in my_threads { 78 | for v in thread.join() { 79 | output.push(v); 80 | } 81 | } 82 | output 83 | } 84 | } 85 | 86 | fn main() { 87 | println!( 88 | "{:?}", 89 | Solution::word_break(String::from("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 90 | vec![String::from("a"),String::from("aa"),String::from("aaa"),String::from("aaaa"),String::from("aaaaa"),String::from("aaaaaa"),String::from("aaaaaaa"),String::from("aaaaaaaa"),String::from("aaaaaaaaa"),String::from("aaaaaaaaaa")]) 91 | ); 92 | } 93 | 94 | #[cfg(test)] 95 | mod tests { 96 | use super::*; 97 | 98 | #[test] 99 | fn test_single_word() { 100 | assert_eq!( 101 | Solution::word_break(String::from("test"), vec![String::from("test")]), 102 | vec![String::from("test")] 103 | ); 104 | } 105 | 106 | #[test] 107 | fn test1() { 108 | let vec_result = Solution::word_break( 109 | String::from("catsanddog"), 110 | vec![ 111 | String::from("cat"), 112 | String::from("cats"), 113 | String::from("and"), 114 | String::from("sand"), 115 | String::from("dog"), 116 | ], 117 | ); 118 | 119 | assert_eq!( 120 | HashSet::from_iter(vec_result), 121 | hashset![String::from("cats and dog"), String::from("cat sand dog")] 122 | ); 123 | } 124 | 125 | #[test] 126 | fn test2() { 127 | let vec_result = Solution::word_break( 128 | String::from("pineapplepenapple"), 129 | vec![ 130 | String::from("apple"), 131 | String::from("pen"), 132 | String::from("applepen"), 133 | String::from("pine"), 134 | String::from("pineapple"), 135 | ], 136 | ); 137 | 138 | assert_eq!( 139 | HashSet::from_iter(vec_result), 140 | hashset![String::from("pine apple pen apple"), String::from("pineapple pen apple"), String::from("pine applepen apple")] 141 | ); 142 | } 143 | #[test] 144 | fn test3() { 145 | let vec_result = Solution::word_break( 146 | String::from("catsandog"), 147 | vec![ 148 | String::from("cat"), 149 | String::from("cats"), 150 | String::from("and"), 151 | String::from("sand"), 152 | String::from("dog"), 153 | ], 154 | ); 155 | 156 | assert_eq!( 157 | HashSet::from_iter(vec_result), 158 | hashset![] 159 | ); 160 | } 161 | 162 | #[test] 163 | fn empty() { 164 | let vec_result = Solution::word_break( 165 | String::from(""), 166 | vec![ 167 | ], 168 | ); 169 | 170 | assert_eq!( 171 | HashSet::from_iter(vec_result), 172 | hashset![] 173 | ); 174 | } 175 | } 176 | 177 | -------------------------------------------------------------------------------- /number_to_words/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2019 James McMurray 2 | // 3 | // This source code is subject to the terms of the GNU General Public License v3.0. 4 | // You should have received a copy of the GNU General Public License 5 | // along with this source code. If not, see . 6 | 7 | // https://leetcode.com/problems/integer-to-english-words/ 8 | 9 | macro_rules! vec_of_strings { 10 | ($($x:expr),*) => (vec![$($x.to_string()),*]); 11 | } 12 | 13 | struct Solution {} 14 | 15 | impl Solution { 16 | pub fn number_to_words(num: i32) -> String { 17 | // Split in to triples, convert to number in hundreds then add thousand, million, billion 18 | let lowers: Vec = vec_of_strings![ 19 | "Zero", 20 | "One", 21 | "Two", 22 | "Three", 23 | "Four", 24 | "Five", 25 | "Six", 26 | "Seven", 27 | "Eight", 28 | "Nine", 29 | "Ten", 30 | "Eleven", 31 | "Twelve", 32 | "Thirteen", 33 | "Fourteen", 34 | "Fifteen", 35 | "Sixteen", 36 | "Seventeen", 37 | "Eighteen", 38 | "Nineteen" 39 | ]; 40 | 41 | let tens: Vec = vec_of_strings![ 42 | "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" 43 | ]; 44 | let joinwords: Vec = vec_of_strings!["", "Thousand", "Million", "Billion"]; 45 | let mut inner_num: i32 = num; 46 | let mut string_return: Vec = vec![]; 47 | let mut count: usize = 0; 48 | 49 | if num == 0 { 50 | return String::from("Zero"); 51 | } 52 | 53 | while inner_num > 0 { 54 | if inner_num % 1000 > 0 { 55 | string_return.push(joinwords[count].clone()); 56 | string_return.push(String::from(" ")); 57 | string_return.push(Solution::handle_triple(inner_num % 1000, &lowers, &tens)); 58 | string_return.push(String::from(" ")); 59 | } 60 | 61 | inner_num /= 1000; 62 | count += 1; 63 | } 64 | 65 | string_return.reverse(); 66 | string_return.concat().trim().to_string() 67 | } 68 | 69 | fn handle_triple(num: i32, lowers: &[String], tens: &[String]) -> String { 70 | if num == 0 { 71 | return String::from(""); 72 | } 73 | // Handle case < 1000 74 | let mut string_return: Vec = vec![]; 75 | let mut inner_num: i32 = num; 76 | if inner_num > 99 { 77 | string_return.push(lowers[(inner_num / 100) as usize].clone()); 78 | string_return.push(String::from(" Hundred")); 79 | inner_num %= 100; 80 | } 81 | if inner_num > 19 { 82 | if !string_return.is_empty() { 83 | string_return.push(String::from(" ")); 84 | } 85 | string_return.push(tens[(inner_num / 10) as usize].clone()); 86 | inner_num %= 10; 87 | } 88 | if inner_num != 0 { 89 | if !string_return.is_empty() { 90 | string_return.push(String::from(" ")); 91 | } 92 | string_return.push(lowers[inner_num as usize].clone()); 93 | } 94 | 95 | string_return.concat() 96 | } 97 | } 98 | 99 | fn main() { 100 | println!("{}", Solution::number_to_words(1156)); 101 | } 102 | 103 | #[cfg(test)] 104 | mod tests { 105 | // Note this useful idiom: importing names from outer (for mod tests) scope. 106 | use super::*; 107 | 108 | #[test] 109 | fn test_123() { 110 | assert_eq!(Solution::number_to_words(123), "One Hundred Twenty Three"); 111 | } 112 | 113 | #[test] 114 | fn test_12345() { 115 | assert_eq!( 116 | Solution::number_to_words(12345), 117 | "Twelve Thousand Three Hundred Forty Five" 118 | ); 119 | } 120 | 121 | #[test] 122 | fn test_1234567() { 123 | assert_eq!( 124 | Solution::number_to_words(1234567), 125 | "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" 126 | ); 127 | } 128 | 129 | #[test] 130 | fn test_1234567891() { 131 | assert_eq!(Solution::number_to_words(1234567891), "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"); 132 | } 133 | 134 | #[test] 135 | fn test_0() { 136 | assert_eq!(Solution::number_to_words(0), "Zero"); 137 | } 138 | 139 | #[test] 140 | fn test_1_000_000() { 141 | assert_eq!(Solution::number_to_words(1_000_000), "One Million"); 142 | } 143 | #[test] 144 | fn test_10_000() { 145 | assert_eq!(Solution::number_to_words(10_000), "Ten Thousand"); 146 | } 147 | #[test] 148 | fn test_100() { 149 | assert_eq!(Solution::number_to_words(100), "One Hundred"); 150 | } 151 | #[test] 152 | fn test_100_000() { 153 | assert_eq!(Solution::number_to_words(100_000), "One Hundred Thousand"); 154 | } 155 | #[test] 156 | fn test_1000() { 157 | assert_eq!(Solution::number_to_words(1000), "One Thousand"); 158 | } 159 | #[test] 160 | fn test_max() { 161 | assert_eq!(Solution::number_to_words(2147483647), "Two Billion One Hundred Forty Seven Million Four Hundred Eighty Three Thousand Six Hundred Forty Seven"); 162 | } 163 | #[test] 164 | fn test_1_000_010() { 165 | assert_eq!(Solution::number_to_words(1_000_010), "One Million Ten"); 166 | } 167 | #[test] 168 | fn test_1_000_073() { 169 | assert_eq!( 170 | Solution::number_to_words(1_000_073), 171 | "One Million Seventy Three" 172 | ); 173 | } 174 | #[test] 175 | fn test_1_000_373() { 176 | assert_eq!( 177 | Solution::number_to_words(1_000_373), 178 | "One Million Three Hundred Seventy Three" 179 | ); 180 | } 181 | #[test] 182 | fn test_1_020_010() { 183 | assert_eq!( 184 | Solution::number_to_words(1_020_010), 185 | "One Million Twenty Thousand Ten" 186 | ); 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /oceans_flow/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/pacific-atlantic-water-flow/ 2 | 3 | #[macro_use] 4 | extern crate maplit; 5 | 6 | use std::collections::HashSet; 7 | use std::sync::mpsc::channel; 8 | use std::sync::Arc; 9 | use std::thread; 10 | 11 | struct Solution {} 12 | 13 | #[derive(Debug)] 14 | enum Ocean { 15 | Pacific, 16 | Atlantic, 17 | } 18 | 19 | type Position = (usize, usize); 20 | 21 | impl Solution { 22 | pub fn pacific_atlantic(matrix: Vec>) -> Vec> { 23 | if matrix.len() == 0 { 24 | return vec![]; 25 | } 26 | let s = Solution::pacific_atlantic_inner(matrix); 27 | s.iter().cloned().map(|x: (usize, usize)| vec![x.0 as i32, x.1 as i32]).collect() 28 | } 29 | 30 | fn check_matrix( 31 | matrix_shared: Arc>>, 32 | thread_set: &mut HashSet, 33 | x: &Position, 34 | to_check: &mut Vec, 35 | ) -> () { 36 | // UP 37 | if let Some(sub) = (x.0).checked_sub(1) { 38 | if let Some(row) = matrix_shared.get(sub as usize) { 39 | if let Some(col) = row.get(x.1 as usize) { 40 | if *col >= matrix_shared[x.0 as usize][x.1 as usize] 41 | && !thread_set.contains(&(sub, x.1)) 42 | { 43 | to_check.push((sub, x.1)); 44 | } 45 | } 46 | } 47 | } 48 | // DOWN 49 | if let Some(row) = matrix_shared.get((x.0 + 1) as usize) { 50 | if let Some(col) = row.get(x.1 as usize) { 51 | if *col >= matrix_shared[x.0 as usize][x.1 as usize] 52 | && !thread_set.contains(&(x.0 + 1, x.1)) 53 | { 54 | to_check.push((x.0 + 1, x.1)); 55 | } 56 | } 57 | } 58 | // LEFT 59 | if let Some(row) = matrix_shared.get(x.0 as usize) { 60 | if let Some(sub) = (x.1).checked_sub(1) { 61 | if let Some(col) = row.get((sub) as usize) { 62 | if *col >= matrix_shared[x.0 as usize][x.1 as usize] 63 | && !thread_set.contains(&(x.0, sub)) 64 | { 65 | to_check.push((x.0, sub)); 66 | } 67 | } 68 | } 69 | } 70 | // RIGHT 71 | if let Some(row) = matrix_shared.get(x.0 as usize) { 72 | if let Some(col) = row.get((x.1 + 1) as usize) { 73 | if *col >= matrix_shared[x.0 as usize][x.1 as usize] 74 | && !thread_set.contains(&(x.0, x.1 + 1)) 75 | { 76 | to_check.push((x.0, x.1 + 1)); 77 | } 78 | } 79 | } 80 | } 81 | 82 | fn pacific_atlantic_inner(matrix: Vec>) -> HashSet { 83 | let (tx, rx) = channel(); 84 | let tx2 = tx.clone(); 85 | 86 | let matrix = Arc::new(matrix); 87 | let matrix_shared1 = matrix.clone(); 88 | // DFS 89 | let pacific = thread::spawn(move || { 90 | tx.send({ 91 | let mut thread_set: HashSet = HashSet::new(); 92 | let mut to_check: Vec = vec![]; 93 | for y in 0..matrix_shared1.len() { 94 | to_check.push((y, 0)); 95 | } 96 | for x in 1..matrix_shared1[0].len() { 97 | to_check.push((0, x)); 98 | } 99 | 100 | while let Some(x) = to_check.pop() { 101 | thread_set.insert(x); 102 | Solution::check_matrix( 103 | matrix_shared1.clone(), 104 | &mut thread_set, 105 | &x, 106 | &mut to_check, 107 | ); 108 | } 109 | // println!("{:?}", (Ocean::Pacific, &thread_set)); 110 | (Ocean::Pacific, thread_set) 111 | }) 112 | .unwrap(); 113 | }); 114 | 115 | let matrix_shared2 = matrix.clone(); 116 | let atlantic = thread::spawn(move || { 117 | tx2.send({ 118 | let mut thread_set: HashSet = HashSet::new(); 119 | let mut to_check: Vec = vec![]; 120 | for y in 0..matrix_shared2.len() { 121 | to_check.push((y, matrix_shared2[0].len() - 1)); 122 | } 123 | for x in 0..matrix_shared2[0].len()-1 { 124 | to_check.push((matrix_shared2.len() - 1, x)); 125 | } 126 | 127 | while let Some(x) = to_check.pop() { 128 | thread_set.insert(x); 129 | Solution::check_matrix( 130 | matrix_shared2.clone(), 131 | &mut thread_set, 132 | &x, 133 | &mut to_check, 134 | ); 135 | } 136 | // println!("{:?}", (Ocean::Atlantic, &thread_set)); 137 | (Ocean::Atlantic, thread_set) 138 | }) 139 | .unwrap(); 140 | }); 141 | let value = rx.recv(); 142 | // println!("{:?}", value); 143 | let value2 = rx.recv(); 144 | // println!("{:?}", value2); 145 | (value.unwrap().1) 146 | .intersection(&(value2.unwrap().1)) 147 | .cloned() 148 | .collect() 149 | } 150 | } 151 | 152 | fn main() { 153 | println!("{:?}", Solution::pacific_atlantic(vec![ 154 | vec![1, 2, 2, 3, 5], 155 | vec![3, 2, 3, 4, 4], 156 | vec![2, 4, 5, 3, 1], 157 | vec![6, 7, 1, 4, 5], 158 | vec![5, 1, 1, 2, 4] 159 | ])); 160 | } 161 | 162 | #[cfg(test)] 163 | mod tests { 164 | use super::*; 165 | 166 | #[test] 167 | fn test1() { 168 | assert_eq!( 169 | Solution::pacific_atlantic_inner(vec![ 170 | vec![1, 2, 2, 3, 5], 171 | vec![3, 2, 3, 4, 4], 172 | vec![2, 4, 5, 3, 1], 173 | vec![6, 7, 1, 4, 5], 174 | vec![5, 1, 1, 2, 4] 175 | ]), 176 | hashset! {(0, 4), (1, 3), (1, 4), (2, 2), (3, 0), (3, 1), (4, 0)} 177 | ); 178 | } 179 | #[test] 180 | fn test2() { 181 | assert_eq!( 182 | Solution::pacific_atlantic_inner(vec![ 183 | vec![3, 3, 3], 184 | vec![3, 1, 3], 185 | vec![0, 2, 4] 186 | ]), 187 | hashset! {(0,0),(0,1),(0,2),(1,0),(1,2),(2,0),(2,1),(2,2)} 188 | ); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /lcancestor/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 2 | use std::collections::HashSet; 3 | 4 | // Adapted from solution to rangesum: 5 | // https://leetcode.com/problems/range-sum-query-immutable/ 6 | struct NumArray { 7 | lookup: Vec, 8 | nums: usize, 9 | } 10 | 11 | /** 12 | * `&self` means the method takes an immutable reference. 13 | * If you need a mutable reference, change it to `&mut self` instead. 14 | */ 15 | impl NumArray { 16 | fn new(nums: Vec) -> Self { 17 | let trisize: usize = nums.len() * (nums.len() + 1) / 2; 18 | let mut lookup: Vec = Vec::with_capacity(trisize); 19 | 20 | for (i, vi) in nums.iter().enumerate() { 21 | for (j, vj) in (&nums[i..]).iter().enumerate() { 22 | if j == 0 { 23 | lookup.push(i); 24 | } else { 25 | //println!("{}, {}, {}", i, j, (i * (i + 1) / 2) + j - 1); 26 | let thistri = trisize - ((nums.len() - i) * (nums.len() + 1 - i) / 2); 27 | let lastval: usize = nums[lookup[thistri + j - 1]]; 28 | 29 | // Min range 30 | if lastval <= *vj { 31 | lookup.push(lookup[thistri + j - 1]); 32 | } else { 33 | lookup.push(i + j); 34 | } 35 | } 36 | } 37 | } 38 | 39 | NumArray { 40 | lookup, 41 | nums: nums.len(), 42 | } 43 | } 44 | 45 | fn min_range(&self, i: usize, j: usize) -> usize { 46 | let i = i as usize; 47 | let j = j as usize; 48 | let thistri = self.lookup.len() - ((self.nums - i) * (self.nums + 1 - i) / 2); 49 | self.lookup[thistri + (j - i)] 50 | } 51 | } 52 | 53 | /** 54 | * Your NumArray object will be instantiated and called as such: 55 | * let obj = NumArray::new(nums); 56 | * let ret_1: i32 = obj.sum_range(i, j); 57 | */ 58 | 59 | #[derive(Debug, Eq, PartialEq)] 60 | struct TreeNode { 61 | label: T, 62 | children: Vec>, 63 | } 64 | 65 | type Tree = Vec>>; 66 | 67 | const fn num_bits() -> usize { 68 | std::mem::size_of::() * 8 69 | } 70 | 71 | fn log_2(x: usize) -> usize { 72 | if x == 0 { 73 | return 0; 74 | } 75 | num_bits::() as usize - x.leading_zeros() as usize - 1 76 | } 77 | 78 | fn build_binary_tree(arr: Vec>) -> Tree { 79 | let mut out = Vec::with_capacity(arr.len()); 80 | for (i, el) in arr.iter().enumerate() { 81 | // 2**depth + 2**child 82 | let depth = log_2(i + 1); 83 | let child = i - ((2 as usize).pow(depth as u32) - 1); 84 | 85 | if let Some(elem) = el { 86 | let left_index = 87 | (2 as usize).pow(depth as u32) + ((2 as usize).pow(child as u32)) + i - 1; 88 | let left_child = match arr.get(left_index) { 89 | None => None, 90 | Some(None) => None, 91 | Some(Some(_)) => Some(left_index), 92 | }; 93 | 94 | let right_child = match arr.get(left_index + 1) { 95 | None => None, 96 | Some(None) => None, 97 | Some(Some(_)) => Some(left_index + 1), 98 | }; 99 | 100 | out.push(Some(TreeNode { 101 | label: (*elem).clone(), 102 | children: vec![left_child, right_child], 103 | })); 104 | } else { 105 | out.push(None); 106 | } 107 | } 108 | 109 | out 110 | } 111 | 112 | /// Complete euler walk of tree and return node visit order and depths 113 | fn euler_walk(tree: &Tree) -> (Vec, Vec) { 114 | let mut stack: Vec<(&TreeNode, usize, usize)> = Vec::with_capacity(tree.len()); 115 | 116 | let mut visits = Vec::with_capacity(2 * tree.len()); 117 | let mut depths = Vec::with_capacity(2 * tree.len()); 118 | let mut seen = HashSet::with_capacity(tree.len()); 119 | 120 | stack.push((tree[0].as_ref().unwrap(), 0, 0)); 121 | 122 | while stack.len() > 0 { 123 | let task = stack.pop().unwrap(); 124 | visits.push(task.2); 125 | depths.push(task.1); 126 | seen.insert(task.2); 127 | 128 | for child in &task.0.children { 129 | if let Some(x) = child { 130 | if !seen.contains(&x) { 131 | stack.push((task.0, task.1, task.2)); 132 | stack.push((tree[*x].as_ref().unwrap(), task.1 + 1, *x)); 133 | break; 134 | } 135 | } 136 | } 137 | } 138 | 139 | (visits, depths) 140 | } 141 | 142 | fn lowest_common_ancestor(tree: &Tree, p: usize, q: usize) -> usize { 143 | let (visits, depths) = euler_walk(&tree); 144 | 145 | let firstp = visits.iter().position(|&x| x == p).unwrap(); 146 | let firstq = visits.iter().position(|&x| x == q).unwrap(); 147 | let numarray = NumArray::new(depths); 148 | let mindepth = numarray.min_range(firstp, firstq); 149 | visits[mindepth] 150 | } 151 | 152 | fn lowest_common_ancestor_from_labels(tree: &Tree, p: T, q: T) -> &T { 153 | let (visits, depths) = euler_walk(&tree); 154 | 155 | let indexp = tree 156 | .iter() 157 | .position(|x| x.is_some() && x.as_ref().unwrap().label == p) 158 | .unwrap(); 159 | let indexq = tree 160 | .iter() 161 | .position(|x| x.is_some() && x.as_ref().unwrap().label == q) 162 | .unwrap(); 163 | 164 | let mut firstp = visits.iter().position(|&x| x == indexp).unwrap(); 165 | let mut firstq = visits.iter().position(|&x| x == indexq).unwrap(); 166 | 167 | if firstp > firstq { 168 | std::mem::swap(&mut firstq, &mut firstp); 169 | } 170 | 171 | let numarray = NumArray::new(depths); 172 | let mindepth = numarray.min_range(firstp, firstq); 173 | &tree[visits[mindepth]].as_ref().unwrap().label 174 | } 175 | 176 | /** 177 | * Definition for a binary tree node. 178 | * struct TreeNode { 179 | * int val; 180 | * TreeNode *left; 181 | * TreeNode *right; 182 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 183 | * }; 184 | */ 185 | 186 | fn main() { 187 | let tree = build_binary_tree(vec![ 188 | Some(3), 189 | Some(5), 190 | Some(1), 191 | Some(6), 192 | Some(2), 193 | Some(0), 194 | Some(8), 195 | None, 196 | None, 197 | Some(7), 198 | Some(4), 199 | ]); 200 | 201 | for node in tree { 202 | println!("{:?}", node); 203 | } 204 | } 205 | 206 | #[cfg(test)] 207 | mod tests { 208 | // Note this useful idiom: importing names from outer (for mod tests) scope. 209 | use super::*; 210 | 211 | #[test] 212 | fn test1() { 213 | let nums: Vec = vec![42, 0, 3, 5, 2, 1]; 214 | let numarray = NumArray::new(nums); 215 | assert_eq!(numarray.min_range(0, 2), 1); 216 | } 217 | #[test] 218 | fn test2() { 219 | let nums: Vec = vec![42, 0, 3, 5, 2, 1]; 220 | let numarray = NumArray::new(nums); 221 | assert_eq!(numarray.min_range(2, 5), 5); 222 | } 223 | #[test] 224 | fn test3() { 225 | let nums: Vec = vec![42, 0, 3, 5, 2, 1]; 226 | let numarray = NumArray::new(nums); 227 | assert_eq!(numarray.min_range(0, 5), 1); 228 | } 229 | #[test] 230 | fn test_euler() { 231 | let tree = build_binary_tree(vec![Some(3), Some(5), Some(1)]); 232 | 233 | assert_eq!( 234 | tree, 235 | vec![ 236 | Some(TreeNode { 237 | label: 3, 238 | children: vec![Some(1), Some(2)] 239 | }), 240 | Some(TreeNode { 241 | label: 5, 242 | children: vec![None, None] 243 | }), 244 | Some(TreeNode { 245 | label: 1, 246 | children: vec![None, None] 247 | }) 248 | ] 249 | ); 250 | 251 | let (visits, depths) = euler_walk(&tree); 252 | assert_eq!(visits, vec![0, 1, 0, 2, 0]); 253 | assert_eq!(depths, vec![0, 1, 0, 1, 0]); 254 | } 255 | 256 | #[test] 257 | fn test_small() { 258 | let tree = build_binary_tree(vec![Some(3), Some(5), Some(1)]); 259 | let (visits, depths) = euler_walk(&tree); 260 | let lca = lowest_common_ancestor(&tree, 1, 2); 261 | 262 | assert_eq!(lca, 0); 263 | } 264 | 265 | #[test] 266 | fn test_small_self() { 267 | let tree = build_binary_tree(vec![Some(3), Some(5), Some(1)]); 268 | let (visits, depths) = euler_walk(&tree); 269 | let lca = lowest_common_ancestor(&tree, 2, 2); 270 | 271 | assert_eq!(lca, 2); 272 | } 273 | 274 | #[test] 275 | fn test_large_1() { 276 | let tree = build_binary_tree(vec![ 277 | Some(3), 278 | Some(5), 279 | Some(1), 280 | Some(6), 281 | Some(2), 282 | Some(0), 283 | Some(8), 284 | None, 285 | None, 286 | Some(7), 287 | Some(4), 288 | ]); 289 | let (visits, depths) = euler_walk(&tree); 290 | let lca = lowest_common_ancestor(&tree, 1, 2); 291 | 292 | assert_eq!(lca, 0); 293 | } 294 | #[test] 295 | fn test_large_2() { 296 | let tree = build_binary_tree(vec![ 297 | Some(3), 298 | Some(5), 299 | Some(1), 300 | Some(6), 301 | Some(2), 302 | Some(0), 303 | Some(8), 304 | None, 305 | None, 306 | Some(7), 307 | Some(4), 308 | ]); 309 | let (visits, depths) = euler_walk(&tree); 310 | let lca = lowest_common_ancestor(&tree, 1, 10); 311 | 312 | assert_eq!(lca, 1); 313 | } 314 | #[test] 315 | fn test_large_3() { 316 | let tree = build_binary_tree(vec![ 317 | Some(3), 318 | Some(5), 319 | Some(1), 320 | Some(6), 321 | Some(2), 322 | Some(0), 323 | Some(8), 324 | None, 325 | None, 326 | Some(7), 327 | Some(4), 328 | ]); 329 | let (visits, depths) = euler_walk(&tree); 330 | let lca = lowest_common_ancestor_from_labels(&tree, 4, 7); 331 | 332 | assert_eq!(*lca, 2); 333 | } 334 | } 335 | -------------------------------------------------------------------------------- /subarray_sum_divisible_bool/src/main.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/continuous-subarray-sum/ 2 | 3 | struct Solution {} 4 | use std::collections::HashMap; 5 | impl Solution { 6 | pub fn check_subarray_sum(nums: Vec, k: i32) -> bool { 7 | let mut cumsum = 0; 8 | let mut modulo = 0; 9 | // First seen 10 | let mut seen_modulos: HashMap = HashMap::with_capacity(nums.len()); 11 | 12 | seen_modulos.insert(0, -1); 13 | 14 | for (i, n) in nums.iter().enumerate() { 15 | cumsum += n; 16 | if k != 0 { 17 | modulo = cumsum.rem_euclid(k); 18 | } else { 19 | modulo = cumsum; 20 | } 21 | 22 | match seen_modulos.get(&modulo) { 23 | Some(&x) => { 24 | if x < (i as i32 - 1) { 25 | return true; 26 | } 27 | } 28 | None => { 29 | seen_modulos.insert(modulo, i as i32); 30 | } 31 | } 32 | } 33 | false 34 | } 35 | 36 | pub fn check_subarray_sum_n2(nums: Vec, k: i32) -> bool { 37 | let n = nums.len(); 38 | let mut arr = Vec::with_capacity(Solution::trinum(n)); 39 | 40 | for (i, val) in nums.iter().enumerate() { 41 | let tri = Solution::trinum(i); 42 | arr.push(*val); 43 | for j in 0..i { 44 | // println!("{}, {}", i, j); 45 | let newval = val + arr[j + tri - i]; 46 | 47 | if (newval == 0) { 48 | return true; 49 | } 50 | if (k != 0) && (newval % k == 0) && (newval >= k) { 51 | return true; 52 | } 53 | arr.push(newval); 54 | } 55 | } 56 | false 57 | } 58 | 59 | fn trinum(n: usize) -> usize { 60 | (n * (n + 1)) / 2 61 | } 62 | } 63 | 64 | fn main() { 65 | println!("Hello, world!"); 66 | } 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | // Note this useful idiom: importing names from outer (for mod tests) scope. 71 | use super::*; 72 | 73 | #[test] 74 | fn test_trinum() { 75 | assert_eq!(Solution::trinum(5), 15); 76 | } 77 | 78 | #[test] 79 | fn test_actual() { 80 | assert_eq!(Solution::check_subarray_sum(vec![23, 2, 4, 6, 7], 6), true); 81 | } 82 | #[test] 83 | fn test_actual2() { 84 | assert_eq!(Solution::check_subarray_sum(vec![23, 2, 6, 4, 7], 6), true); 85 | } 86 | #[test] 87 | fn test_actual3() { 88 | assert_eq!(Solution::check_subarray_sum(vec![23, 2, 6, 4, 7], 0), false); 89 | } 90 | #[test] 91 | fn test_actual4() { 92 | assert_eq!(Solution::check_subarray_sum(vec![0, 0], 0), true); 93 | } 94 | #[test] 95 | fn test_actual5() { 96 | assert_eq!(Solution::check_subarray_sum(vec![0; 6], 1), true); 97 | } 98 | #[test] 99 | fn test_actual6() { 100 | assert_eq!(Solution::check_subarray_sum(vec![23, 2, 4, 6, 7], -6), true); 101 | } 102 | #[test] 103 | fn test_actual7() { 104 | assert_eq!(Solution::check_subarray_sum(vec![0], 0), false); 105 | } 106 | #[test] 107 | fn test_actual8() { 108 | assert_eq!(Solution::check_subarray_sum(vec![1, 0], 2), false); 109 | } 110 | #[test] 111 | fn test_actual9() { 112 | assert_eq!(Solution::check_subarray_sum(vec![0], -1), false); 113 | } 114 | #[test] 115 | fn test_actual12() { 116 | assert_eq!(Solution::check_subarray_sum(vec![2, -1, -1], 0), true); 117 | } 118 | #[test] 119 | fn test_actual14() { 120 | assert_eq!(Solution::check_subarray_sum(vec![2, -1, -1], 5), true); 121 | } 122 | #[test] 123 | fn test_actual13() { 124 | assert_eq!(Solution::check_subarray_sum(vec![0, 0, 0], 7), true); 125 | } 126 | #[test] 127 | fn test_actual11() { 128 | assert_eq!(Solution::check_subarray_sum(vec![0, 0], -1), true); 129 | } 130 | #[test] 131 | fn test_actual10() { 132 | assert_eq!(Solution::check_subarray_sum(vec![1, 2, 12], 6), false); 133 | } 134 | #[test] 135 | fn test_actual15() { 136 | assert_eq!(Solution::check_subarray_sum(vec![0, 1, 0], 0), false); 137 | } 138 | #[test] 139 | fn test_actual16() { 140 | assert_eq!( 141 | Solution::check_subarray_sum(vec![1000000000], 1000000000), 142 | false 143 | ); 144 | } 145 | #[test] 146 | fn test_actual17() { 147 | assert_eq!( 148 | Solution::check_subarray_sum( 149 | vec![ 150 | 358, 432, 465, 409, 331, 226, 256, 387, 35, 468, 313, 153, 139, 326, 161, 451, 151 | 450, 241, 213, 26, 449, 185, 522, 389, 192, 348, 14, 370, 433, 4, 34, 360, 80, 152 | 446, 520, 429, 246, 524, 439, 165, 333, 444, 447, 218, 357, 191, 86, 236, 338, 153 | 212, 121, 340, 119, 246, 467, 22, 520, 140, 452, 429, 275, 344, 345, 190, 516, 154 | 205, 231, 104, 140, 469, 15, 393, 322, 399, 164, 437, 392, 54, 59, 300, 8, 463, 155 | 264, 242, 224, 480, 372, 96, 270, 425, 453, 524, 434, 381, 204, 242, 10, 311, 156 | 187, 460, 456, 293, 199, 146, 476, 42, 500, 130, 420, 521, 79, 56, 453, 421, 157 | 497, 315, 442, 282, 23, 428, 239, 218, 460, 42, 263, 240, 129, 526, 214, 287, 158 | 457, 97, 315, 74, 240, 357, 311, 359, 464, 427, 478, 452, 266, 327, 129, 172, 159 | 282, 25, 345, 172, 325, 70, 38, 198, 182, 244, 54, 211, 309, 519, 367, 244, 160 | 411, 310, 410, 132, 19, 175, 446, 6, 416, 449, 98, 328, 490, 339, 107, 517, 161 | 196, 162, 285, 484, 250, 52, 483, 115, 468, 187, 387, 229, 213, 380, 184, 189, 162 | 481, 93, 420, 400, 263, 70, 221, 147, 314, 23, 405, 189, 428, 122, 14, 263, 163 | 170, 103, 328, 469, 399, 449, 187, 493, 164, 283, 387, 166, 260, 271, 393, 347, 164 | 93, 15, 69, 183, 422, 346, 49, 1, 389, 240, 516, 23, 90, 134, 414, 226, 67, 165 | 309, 274, 328, 497, 180, 405, 187, 165, 202, 355, 261, 312, 334, 213, 31, 280, 166 | 8, 317, 168, 127, 124, 483, 452, 133, 160, 66, 319, 76, 333, 94, 55, 199, 492, 167 | 242, 165, 51, 286, 290, 444, 371, 471, 29, 216, 362, 156, 343, 366, 262, 240, 168 | 403, 220, 65, 306, 228, 477, 237, 340, 217, 121, 255, 278, 511, 124, 235, 268, 169 | 160, 23, 279, 406, 431, 410, 431, 211, 319, 116, 264, 476, 495, 244, 480, 299, 170 | 399, 20, 513, 361, 120, 286, 198, 31, 256, 475, 442, 223, 277, 179, 379, 48, 171 | 387, 235, 55, 32, 480, 167, 353, 59, 499, 44, 220, 392, 254, 293, 345, 481, 172 | 183, 361, 492, 286, 245, 254, 356, 350, 240, 217, 71, 337, 190, 519, 279, 354, 173 | 218, 242, 487, 304, 35, 165, 425, 76, 40, 318, 160, 341, 269, 233, 40, 344, 174 | 276, 347, 298, 30, 63, 275, 235, 339, 50, 263, 119, 344, 95, 184, 192, 230, 175 | 460, 314, 432, 122, 58, 161, 318, 51, 63, 47, 382, 301, 143, 350, 7, 48, 240, 176 | 325, 114, 306, 437, 467, 230, 438, 235, 284, 306, 108, 509, 245, 30, 413, 147, 177 | 403, 19, 302, 1, 366, 249, 116, 107, 303, 91, 146, 385, 127, 91, 135, 500, 26, 178 | 512, 278, 272, 519, 432, 230, 448, 474, 115, 406, 264, 170, 59, 331, 294, 160, 179 | 390, 194, 56, 398, 287, 520, 412, 194, 346, 396, 503, 523, 473, 157, 139, 308, 180 | 214, 189, 476, 405, 2, 297, 301, 511, 474, 357, 520, 365, 169, 471, 198, 132, 181 | 76, 392, 62, 48, 466, 118, 181, 118, 472, 472, 46, 47, 243, 149, 289, 462, 206, 182 | 9, 149, 240, 370, 489, 129, 250, 217, 381, 133, 340, 344, 68, 310, 179, 119, 183 | 397, 348, 292, 358, 288, 337, 176, 231, 135, 10, 515, 188, 303, 437, 436, 473, 184 | 392, 306, 236, 296, 92, 241, 342, 193, 312, 470, 73, 437, 222, 391, 401, 490, 185 | 305, 174, 15, 11, 369, 113, 502, 26, 341, 257, 409, 516, 138, 493, 134, 91, 186 | 430, 162, 131, 328, 198, 85, 285, 118, 307, 49, 472, 406, 41, 64, 34, 209, 479, 187 | 228, 438, 306, 292, 275, 488, 515, 473, 189, 372, 19, 165, 438, 127, 69, 408, 188 | 409, 28, 517, 493, 120, 68, 199, 305, 457, 192, 352, 139, 341, 40, 287, 38, 189 | 220, 69, 418, 186, 522, 96, 301, 17, 359, 473, 99, 4, 152, 88, 316, 41, 379, 190 | 136, 242, 370, 365, 8, 501, 200, 182, 465, 135, 183, 307, 261, 95, 374, 40, 191 | 447, 501, 26, 457, 88, 252, 113, 117, 32, 148, 298, 202, 220, 6, 107, 116, 55, 192 | 433, 99, 490, 397, 177, 302, 73, 282, 147, 20, 288, 229, 257, 209, 491, 221, 193 | 355, 243, 271, 148, 22, 211, 366, 68, 270, 318, 403, 25, 14, 261, 500, 61, 460, 194 | 72, 259, 285, 185, 335, 194, 185, 495, 270, 132, 159, 444, 78, 269, 169, 447, 195 | 304, 296, 110, 364, 321, 320, 303, 168, 20, 32, 166, 170, 292, 418, 61, 438, 196 | 411, 51, 64, 189, 480, 225, 496, 411, 501, 498, 18, 299, 109, 227, 210, 195, 197 | 264, 369, 499, 480, 124, 457, 317, 47, 151, 53, 94, 20, 344, 525, 116, 307, 51, 198 | 120, 20, 368, 379, 118, 381, 154, 325, 403, 120, 263, 61, 475, 296, 25, 251, 199 | 377, 459, 465, 120, 408, 57, 226, 218, 500, 61, 179, 219, 492, 487, 493, 500, 200 | 410, 19, 453, 351, 341, 407, 191, 368, 240, 422, 2, 463, 321, 9, 445, 374, 471, 201 | 248, 306, 9, 180, 38, 40, 249, 287, 267, 385, 29, 266, 100, 214, 242, 285, 97, 202 | 272, 206, 90, 95, 11, 68, 223, 185, 376, 358, 427, 395, 146, 32, 375, 423, 465, 203 | 17, 191, 293, 166, 83, 507, 51, 16, 316, 122, 169, 147, 414, 223, 60, 166, 354, 204 | 420, 14, 15, 53, 355, 383, 166, 97, 457, 472, 55, 35, 391, 94, 523, 168, 79, 205 | 92, 177, 2, 149, 198, 224, 512, 264, 298, 253, 383, 463, 343, 281, 504, 206, 206 | 271, 270, 177, 381, 329, 452, 4, 92, 41, 418, 209, 312, 162, 283, 395, 489, 207 | 215, 128, 278, 493, 150, 315, 133, 11, 202, 33, 181, 302, 301, 319, 26, 342, 208 | 430, 182, 196, 519, 502, 484, 395, 69, 308, 306, 23, 3, 409, 149, 153, 486, 209 | 333, 466, 485, 156, 204, 419, 252, 445, 51, 28, 515, 297, 465, 9, 418, 85, 467, 210 | 488, 187, 453, 375, 212, 106, 442, 237, 400, 198, 325, 134, 425, 499, 511, 324, 211 | 55, 233, 127, 427, 316, 112 212 | ], 213 | 732193917 214 | ), 215 | false 216 | ); 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------