Created
December 9, 2020 07:14
-
-
Save hellow554/710f7a58b49dcf8203c849edbe35c709 to your computer and use it in GitHub Desktop.
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
use std::cmp::Ordering; | |
const INPUT: &str = include_str!("../input"); | |
type Num = u64; | |
fn check_it(arr: &[Num], number: Num) -> bool { | |
arr.iter() | |
.enumerate() | |
.flat_map(|(i, a)| arr[i + 1..].iter().map(move |b| (a, b))) | |
.any(|(a, b)| a + b == number) | |
} | |
fn check_a(arr: &[Num], size: usize) -> Result<(), usize> { | |
let pos = arr.windows(size + 1).position(|win| { | |
let (number, arr) = win.split_last().unwrap(); | |
!check_it(arr, *number) | |
}); | |
if let Some(p) = pos { | |
Err(p + size) | |
} else { | |
Ok(()) | |
} | |
} | |
fn find_consecutives(arr: &[Num], target: Num) -> &[Num] { | |
for start in 0..arr.len() { | |
for end in start + 1..arr.len() { | |
match arr[start..=end].iter().sum::<Num>().cmp(&target) { | |
Ordering::Less => continue, | |
Ordering::Equal => return &arr[start..=end], | |
Ordering::Greater => break, | |
} | |
} | |
} | |
unreachable!() | |
} | |
fn parse(s: &str) -> Vec<Num> { | |
s.lines().map(|l| l.parse().unwrap()).collect() | |
} | |
fn main() { | |
let parsed = parse(INPUT); | |
let idx = check_a(&parsed, 25).unwrap_err(); | |
println!("A: {}", parsed[idx]); | |
let consecs = find_consecutives(&parsed, parsed[idx]); | |
let min = consecs.iter().min().unwrap(); | |
let max = consecs.iter().max().unwrap(); | |
println!("B: {}", min + max); | |
} | |
#[test] | |
fn test1() { | |
let input = "35 | |
20 | |
15 | |
25 | |
47 | |
40 | |
62 | |
55 | |
65 | |
95 | |
102 | |
117 | |
150 | |
182 | |
127 | |
219 | |
299 | |
277 | |
309 | |
576"; | |
let parsed = parse(input); | |
assert_eq!(Err(14), check_a(&parsed, 5)); | |
assert_eq!(127, parsed[14]); | |
} | |
#[test] | |
fn test2() { | |
let input = "35 | |
20 | |
15 | |
25 | |
47 | |
40 | |
62 | |
55 | |
65 | |
95 | |
102 | |
117 | |
150 | |
182 | |
127 | |
219 | |
299 | |
277 | |
309 | |
576"; | |
let parsed = parse(input); | |
let idx = check_a(&parsed, 5).unwrap_err(); | |
let range = find_consecutives(&parsed, parsed[idx]); | |
let min = range.iter().min().unwrap(); | |
let max = range.iter().max().unwrap(); | |
assert_eq!(&[15, 25, 47, 40], range); | |
assert_eq!(62, min + max); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment