prettify and lint optimization
This commit is contained in:
@@ -1,5 +1,3 @@
|
||||
import os
|
||||
|
||||
def map_seed_through_category(seed, line):
|
||||
"""Maps a single seed through a category based on a mapping line."""
|
||||
dest_start, source_start, range_length = map(int, line.split())
|
||||
@@ -7,20 +5,24 @@ def map_seed_through_category(seed, line):
|
||||
return dest_start + (seed - source_start)
|
||||
return seed
|
||||
|
||||
|
||||
def process_category(file, seeds):
|
||||
"""Processes seeds through a single category based on the file lines."""
|
||||
print(f"Starting category processing")
|
||||
print("Starting category processing")
|
||||
updated_seeds = [-1] * len(seeds) # Initialize with -1 to indicate unmapped seeds
|
||||
|
||||
for line in file:
|
||||
line = line.strip()
|
||||
print(f"Processing category line: {line}")
|
||||
if not line or ':' in line: # End of the current category map
|
||||
if not line or ":" in line: # End of the current category map
|
||||
break
|
||||
|
||||
dest_start, source_start, range_length = map(int, line.split())
|
||||
for i, seed in enumerate(seeds):
|
||||
if updated_seeds[i] == -1 and source_start <= seed < source_start + range_length:
|
||||
if (
|
||||
updated_seeds[i] == -1
|
||||
and source_start <= seed < source_start + range_length
|
||||
):
|
||||
updated_seeds[i] = dest_start + (seed - source_start)
|
||||
|
||||
# For seeds that weren't mapped in this category, keep their original value
|
||||
@@ -31,18 +33,19 @@ def process_category(file, seeds):
|
||||
print(f"Seeds after category processing: {updated_seeds}")
|
||||
return updated_seeds
|
||||
|
||||
|
||||
def process_file(file_path, is_test=False):
|
||||
"""Processes the file to find the lowest location number for the seeds."""
|
||||
try:
|
||||
with open(file_path, 'r') as file:
|
||||
seeds = list(map(int, file.readline().split(':')[1].split()))
|
||||
with open(file_path, "r") as file:
|
||||
seeds = list(map(int, file.readline().split(":")[1].split()))
|
||||
print(f"Initial Seeds: {seeds}")
|
||||
|
||||
while True:
|
||||
line = file.readline()
|
||||
if not line: # End of file
|
||||
break
|
||||
if ':' in line: # Start of a new category map
|
||||
if ":" in line: # Start of a new category map
|
||||
seeds = process_category(file, seeds)
|
||||
|
||||
lowest_location = min(seeds)
|
||||
@@ -54,13 +57,15 @@ def process_file(file_path, is_test=False):
|
||||
except Exception as e:
|
||||
print(f"An error occurred processing '{file_path}': {e}")
|
||||
|
||||
|
||||
def test():
|
||||
"""Run tests using the test.txt file."""
|
||||
expected_result = 35 # Based on the given example
|
||||
result = process_file('../test.txt')
|
||||
result = process_file("../test.txt")
|
||||
assert result == expected_result, f"Test failed, expected 35 but got {result}"
|
||||
print(f"Test passed: {result}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to process the input file and display results."""
|
||||
try:
|
||||
@@ -74,5 +79,6 @@ def main():
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import os
|
||||
import gc
|
||||
from itertools import groupby
|
||||
|
||||
|
||||
def free_up_memory():
|
||||
"""Explicitly frees up memory."""
|
||||
gc.collect()
|
||||
|
||||
|
||||
def parse_input(file_path):
|
||||
"""Parses the input file into seeds and categories."""
|
||||
with open(file_path) as file:
|
||||
@@ -20,6 +21,7 @@ def parse_input(file_path):
|
||||
]
|
||||
return seeds_numbers, categories
|
||||
|
||||
|
||||
def process_categories(seeds_numbers, categories):
|
||||
"""Processes the seed ranges through all categories."""
|
||||
for category in categories:
|
||||
@@ -49,6 +51,7 @@ def process_categories(seeds_numbers, categories):
|
||||
seeds_numbers = sources
|
||||
return seeds_numbers
|
||||
|
||||
|
||||
def find_lowest_location(file_path, is_test=False, expected_result=None):
|
||||
"""Finds the lowest location number from the input file."""
|
||||
try:
|
||||
@@ -57,7 +60,9 @@ def find_lowest_location(file_path, is_test=False, expected_result=None):
|
||||
lowest_location = min(seeds_numbers)[0]
|
||||
|
||||
if is_test:
|
||||
assert lowest_location == expected_result, f"Test failed, expected {expected_result} but got {lowest_location}"
|
||||
assert (
|
||||
lowest_location == expected_result
|
||||
), f"Test failed, expected {expected_result} but got {lowest_location}"
|
||||
print("Test passed.")
|
||||
else:
|
||||
print(f"Lowest location from {file_path}: {lowest_location}")
|
||||
@@ -68,11 +73,13 @@ def find_lowest_location(file_path, is_test=False, expected_result=None):
|
||||
except Exception as e:
|
||||
print(f"An error occurred processing '{file_path}': {e}")
|
||||
|
||||
|
||||
def test():
|
||||
"""Run tests using the test.txt file."""
|
||||
print("Starting test")
|
||||
expected_result = 46 # Updated expected result for the new puzzle
|
||||
find_lowest_location('../test.txt', is_test=True, expected_result=expected_result)
|
||||
find_lowest_location("../test.txt", is_test=True, expected_result=expected_result)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to process the input file and display results."""
|
||||
@@ -87,5 +94,6 @@ def main():
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -3,6 +3,13 @@ use std::io::{self, BufRead};
|
||||
use std::path::Path;
|
||||
use std::str::FromStr;
|
||||
|
||||
// Define type aliases for clarity
|
||||
type SeedNumber = (i32, i32);
|
||||
type CategoryItem = (i32, i32, i32);
|
||||
type SeedNumbers = Vec<SeedNumber>;
|
||||
type Category = Vec<CategoryItem>;
|
||||
type Categories = Vec<Category>;
|
||||
|
||||
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
@@ -11,10 +18,10 @@ where
|
||||
Ok(io::BufReader::new(file).lines())
|
||||
}
|
||||
|
||||
fn parse_input(file_path: &str) -> io::Result<(Vec<(i32, i32)>, Vec<Vec<(i32, i32, i32)>>)> {
|
||||
let mut seeds_numbers = Vec::new();
|
||||
let mut categories = Vec::new();
|
||||
let mut current_category = Vec::new();
|
||||
fn parse_input(file_path: &str) -> io::Result<(SeedNumbers, Categories)> {
|
||||
let mut seeds_numbers = SeedNumbers::new();
|
||||
let mut categories = Categories::new();
|
||||
let mut current_category = Category::new();
|
||||
let mut is_seed_line = true;
|
||||
|
||||
for line in read_lines(file_path)? {
|
||||
@@ -22,14 +29,15 @@ fn parse_input(file_path: &str) -> io::Result<(Vec<(i32, i32)>, Vec<Vec<(i32, i3
|
||||
if line.is_empty() {
|
||||
if !current_category.is_empty() {
|
||||
categories.push(current_category);
|
||||
current_category = Vec::new();
|
||||
current_category = Category::new();
|
||||
}
|
||||
is_seed_line = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_seed_line {
|
||||
let seeds_ranges: Vec<i32> = line.split_whitespace()
|
||||
let seeds_ranges: Vec<i32> = line
|
||||
.split_whitespace()
|
||||
.skip(1)
|
||||
.filter_map(|s| i32::from_str(s).ok())
|
||||
.collect();
|
||||
@@ -40,7 +48,8 @@ fn parse_input(file_path: &str) -> io::Result<(Vec<(i32, i32)>, Vec<Vec<(i32, i3
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let numbers: Vec<i32> = line.split_whitespace()
|
||||
let numbers: Vec<i32> = line
|
||||
.split_whitespace()
|
||||
.filter_map(|s| i32::from_str(s).ok())
|
||||
.collect();
|
||||
if numbers.len() == 3 {
|
||||
@@ -55,16 +64,19 @@ fn parse_input(file_path: &str) -> io::Result<(Vec<(i32, i32)>, Vec<Vec<(i32, i3
|
||||
Ok((seeds_numbers, categories))
|
||||
}
|
||||
|
||||
fn process_categories(mut seeds_numbers: Vec<(i32, i32)>, categories: Vec<Vec<(i32, i32, i32)>>) -> Vec<(i32, i32)> {
|
||||
fn process_categories(mut seeds_numbers: SeedNumbers, categories: Categories) -> SeedNumbers {
|
||||
for category in categories {
|
||||
let mut sources = Vec::new();
|
||||
let mut sources = SeedNumbers::new();
|
||||
while let Some((start, end)) = seeds_numbers.pop() {
|
||||
let mut is_mapped = false;
|
||||
for &(destination, source, length) in &category {
|
||||
let overlap_start = std::cmp::max(start, source);
|
||||
let overlap_end = std::cmp::min(end, source + length);
|
||||
if overlap_start < overlap_end {
|
||||
sources.push((overlap_start - source + destination, overlap_end - source + destination));
|
||||
sources.push((
|
||||
overlap_start - source + destination,
|
||||
overlap_end - source + destination,
|
||||
));
|
||||
if overlap_start > start {
|
||||
seeds_numbers.push((start, overlap_start));
|
||||
}
|
||||
@@ -87,14 +99,22 @@ fn process_categories(mut seeds_numbers: Vec<(i32, i32)>, categories: Vec<Vec<(i
|
||||
fn find_lowest_location(file_path: &str) -> io::Result<i32> {
|
||||
let (seeds_numbers, categories) = parse_input(file_path)?;
|
||||
let processed_seeds = process_categories(seeds_numbers, categories);
|
||||
let lowest_location = processed_seeds.iter().map(|&(start, _)| start).min().unwrap();
|
||||
let lowest_location = processed_seeds
|
||||
.iter()
|
||||
.map(|&(start, _)| start)
|
||||
.min()
|
||||
.unwrap();
|
||||
Ok(lowest_location)
|
||||
}
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
// Test
|
||||
let test_result = find_lowest_location("../test.txt")?;
|
||||
assert_eq!(test_result, 46, "Test failed. Expected 46, got {}", test_result);
|
||||
assert_eq!(
|
||||
test_result, 46,
|
||||
"Test failed. Expected 46, got {}",
|
||||
test_result
|
||||
);
|
||||
println!("Test passed.");
|
||||
|
||||
// Process actual input
|
||||
|
||||
Reference in New Issue
Block a user