-
Notifications
You must be signed in to change notification settings - Fork 1
/
palindrome.rs
executable file
·73 lines (65 loc) · 1.94 KB
/
palindrome.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::env;
use std::collections::HashMap;
fn is_palindrome(input: &str) -> bool {
let forward: Vec<char> = input.chars().collect();
let mut reverse: Vec<char> = input.chars().collect();
reverse.reverse();
forward == reverse
}
fn build_palindrome(input: &str) {
let split: Vec<char> = input.chars().collect();
let mut map: HashMap<&char, i32> = HashMap::new();
for ch in split.iter() {
if !map.contains_key(ch) {
map.insert(ch, 1);
} else if let Some(n) = map.get_mut(ch) {
*n = *n + 1;
}
}
let mut evens_map: HashMap<&char, i32> = HashMap::new();
let mut odds_map: HashMap<&char, i32> = HashMap::new();
for (k, v) in map {
if v % 2 == 0 {
evens_map.insert(k, v);
} else {
odds_map.insert(k, v);
}
}
if odds_map.len() > 1 {
println!("{} cannot be made into a palindrome", input);
} else {
let mut build_str = String::new();
for (k, v) in evens_map {
for i in 0..(v / 2) {
build_str.push(k.to_owned());
}
}
let mut single = 'x';
for (k, v) in odds_map {
if v > 1 {
for i in 0..(v / 2) {
build_str.push(k.to_owned());
}
} else {
single = k.to_owned();
}
}
let mut str_rev_chs: Vec<char> = build_str.chars().collect();
str_rev_chs.reverse();
let mut final_str = build_str;
final_str.push(single);
for ch in str_rev_chs {
final_str.push(ch);
}
println!("A palindromic form of {} is {}", input, final_str);
}
}
fn main() {
let args: Vec<_> = env::args().collect();
let input = &args[1];
let is_pal = is_palindrome(&input);
match is_pal {
true => println!("{} is a palindrome", input),
_ => build_palindrome(&input),
}
}