/
ch-2.rs
executable file
·57 lines (53 loc) · 1.3 KB
/
ch-2.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
#! /bin/sh
//usr/bin/env rustc --test $0 -o ${0}x && ./${0}x --nocapture; rm -f ${0}x ; exit
use std::collections::{HashSet, HashMap};
#[test]
fn test_ex1() {
assert_eq!(happy(8), vec![1, 7, 10, 13, 19, 23, 28, 31]);
}
fn ssd(n0: usize) -> usize {
let mut n = n0;
let mut out = 0;
while n > 0 {
let d = n % 10;
out += d * d;
n /= 10;
}
out
}
fn happy(ct: usize) -> Vec<usize> {
let mut hm: HashMap<usize, bool> = HashMap::from([(1, true)]);
let mut c = 0;
let mut out = Vec::new();
loop {
c += 1;
if !hm.contains_key(&c) {
let mut v = c;
let mut ss: HashSet<usize> = HashSet::from([v]);
let h;
loop {
if hm.contains_key(&v) {
h = *hm.get(&v).unwrap();
break;
} else {
v = ssd(v);
if ss.contains(&v) {
h = false;
break;
}
ss.insert(v);
}
}
for i in ss {
hm.insert(i,h);
}
}
if *hm.get(&c).unwrap() {
out.push(c);
if out.len() >= ct {
break;
}
}
}
out
}