-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added sort by increasing frequency solution.
- Loading branch information
Showing
3 changed files
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
use std::collections::HashMap; | ||
|
||
pub fn frequency_sort(mut numbers: Vec<i32>) -> Vec<i32> { | ||
let mut counter: HashMap<i32, i32> = HashMap::new(); | ||
for x in numbers.iter() { | ||
*counter.entry(*x).or_default() += 1; | ||
} | ||
|
||
numbers.sort_by_key(|n| (counter.get(n).unwrap(), -n)); | ||
numbers | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn items_sorted_by_frequency() { | ||
let numbers = vec![2, 3, 1, 3, 2]; | ||
let actual = frequency_sort(numbers); | ||
assert_eq!(vec![1, 3, 3, 2, 2], actual) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -47,3 +47,4 @@ mod x_kind; | |
mod remove_duplicates; | ||
mod sort_people; | ||
mod max_repeating_substr; | ||
mod freq_sort; |