Skip to content

Commit

Permalink
Rust challenge 2 (YearOfProgramming#416)
Browse files Browse the repository at this point in the history
* Add main.rs to use find_single mod

* Add test cases

* Add print statements for more clarity

* Add README.md
  • Loading branch information
Naren authored and Remillardj committed Jan 18, 2017
1 parent 7d9c2fa commit 1022957
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 0 deletions.
4 changes: 4 additions & 0 deletions challenge_2/rust/makernaren/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions challenge_2/rust/makernaren/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "makernaren"
version = "0.1.0"
authors = ["naren <makernaren@gmail.com>"]

[dependencies]
18 changes: 18 additions & 0 deletions challenge_2/rust/makernaren/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
## Single Number
#### To run the code :
* Open this directory in terminal and run `cargo run` to compile and run the code.
* To test the code just run, `cargo test` in same directory.
```
$ cargo run
Finished debug [unoptimized + debuginfo] target(s) in 0.62 secs
Running `target/debug/makernaren`
Given array is [1, 1, 2, 2, 3, 3, 5]
Single occurance : 5
$ cargo test
Finished debug [unoptimized + debuginfo] target(s) in 0.70 secs
Running target/debug/makernaren-bf4fafb462d1be5f
running 1 test
test single_number::tests::test_int ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
7 changes: 7 additions & 0 deletions challenge_2/rust/makernaren/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
mod single_number;
fn main() {
// let input = vec!['a', 'a', 'b', 'b', 'c', 'c', 'd'];
let input = vec![1, 1, 2, 2, 3, 3, 5];
println!("Given array is {:?} \n Single occurance : {}",input.clone(), single_number::find_single(input));

}
30 changes: 30 additions & 0 deletions challenge_2/rust/makernaren/src/single_number.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::collections::HashMap;

// Finds the unique character in given array
pub fn find_single(input: Vec<i32>) -> i32 {
// Create hashmap, let the key be the element in input array
// and value be its count. Then return the key with count of 1.
let mut occurances: HashMap<i32, i32> = HashMap::new();
for key in input {
*occurances.entry(key).or_insert(0) += 1;
}
let mut result: i32 = 0;
for (key, val) in occurances.iter() {
if *val == 1 {
result = key.to_owned();
}
}
return result
}


#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_int() {
let expected = 5;
let input = vec![2, 3, 4, 2, 3, 5, 4, 6, 4, 6, 9, 10,9 ,8 ,7 ,8 ,10 ,7];
assert_eq!(expected.to_owned(), find_single(input));
}
}

0 comments on commit 1022957

Please sign in to comment.