1
- pub fn parse ( input : & str ) -> Vec < & [ u8 ] > {
2
- input. lines ( ) . map ( str:: as_bytes) . collect ( )
1
+ //! # Full of Hot Air
2
+ //!
3
+ //! The SNAFU numbers are balanced quinary, similar to
4
+ //! [an actual base](https://en.wikipedia.org/wiki/Balanced_ternary)
5
+ //! used by some experimental computers.
6
+ pub fn parse ( input : & str ) -> Vec < & str > {
7
+ input. lines ( ) . collect ( )
3
8
}
4
9
5
- pub fn part1 ( input : & [ & [ u8 ] ] ) -> String {
10
+ pub fn part1 ( input : & [ & str ] ) -> String {
6
11
to_snafu ( input. iter ( ) . map ( from_snafu) . sum ( ) )
7
12
}
8
13
9
- pub fn part2 ( _input : & [ & [ u8 ] ] ) -> & ' static str {
14
+ pub fn part2 ( _input : & [ & str ] ) -> & ' static str {
10
15
"n/a"
11
16
}
12
17
13
- fn from_snafu ( snafu : & & [ u8 ] ) -> i64 {
14
- snafu. iter ( ) . fold ( 0 , |acc, c| {
18
+ /// Converting from SNAFU to decimal is straightforward.
19
+ fn from_snafu ( snafu : & & str ) -> i64 {
20
+ snafu. bytes ( ) . fold ( 0 , |acc, c| {
15
21
let digit = match c {
16
22
b'=' => -2 ,
17
23
b'-' => -1 ,
@@ -24,8 +30,10 @@ fn from_snafu(snafu: &&[u8]) -> i64 {
24
30
} )
25
31
}
26
32
27
- fn to_snafu ( decimal : i64 ) -> String {
28
- let mut n = decimal;
33
+ /// Convert to decimal by first finding the result modulus 5 for each digit.
34
+ /// If the answer is 3 or 4 then we must add a carry to the next digit so account for the
35
+ /// subtraction.
36
+ fn to_snafu ( mut n : i64 ) -> String {
29
37
let mut digits = String :: new ( ) ;
30
38
31
39
while n > 0 {
@@ -38,6 +46,8 @@ fn to_snafu(decimal: i64) -> String {
38
46
_ => unreachable ! ( ) ,
39
47
} ;
40
48
digits. insert ( 0 , next) ;
49
+ // If the remainder of n is 3 or higher then this will add a carry digit to account
50
+ // for the subtraction.
41
51
n = ( n + 2 ) / 5 ;
42
52
}
43
53
0 commit comments