prettify and lint optimization

This commit is contained in:
2023-12-10 17:24:14 +01:00
parent 274c69d0c4
commit 4cd62ef794
32 changed files with 599 additions and 262 deletions

View File

@@ -3,7 +3,9 @@ def generate_difference_table(history):
table = [history]
while not all(value == 0 for value in table[-1]):
try:
next_row = [table[-1][i+1] - table[-1][i] for i in range(len(table[-1]) - 1)]
next_row = [
table[-1][i + 1] - table[-1][i] for i in range(len(table[-1]) - 1)
]
except IndexError as e:
print(f"IndexError in generate_difference_table: {e}")
print(f"Current table: {table}")
@@ -11,22 +13,24 @@ def generate_difference_table(history):
table.append(next_row)
return table
def extrapolate_next_value(table):
"""Extrapolates the next value from the difference table."""
try:
for i in range(len(table) - 2, -1, -1):
table[i].append(table[i][-1] + table[i+1][-1])
table[i].append(table[i][-1] + table[i + 1][-1])
except IndexError as e:
print(f"IndexError in extrapolate_next_value: {e}")
print(f"Current table: {table}")
raise
return table[0][-1]
def solve_puzzle(filename):
"""Solves the puzzle by reading histories from the file and summing their extrapolated next values."""
total = 0
try:
with open(filename, 'r') as file:
with open(filename, "r") as file:
for line in file:
try:
history = [int(x) for x in line.split()]
@@ -37,14 +41,15 @@ def solve_puzzle(filename):
print(f"ValueError processing line '{line}': {e}")
except IndexError as e:
print(f"IndexError processing line '{line}': {e}")
except FileNotFoundError as e:
print(f"FileNotFoundError: The file {filename} was not found.")
except FileNotFoundError:
print(f"FileNotFoundError: The file {filename} was not found")
raise
except Exception as e:
print(f"Unexpected error processing file {filename}: {e}")
raise
return total
def test():
"""Runs the test using the test.txt file and asserts the expected outcome."""
expected = 114 # Expected result from the test data
@@ -56,6 +61,7 @@ def test():
print(e)
raise
def main():
"""Main function to run the test and then solve the puzzle."""
print("Running test...")
@@ -64,5 +70,6 @@ def main():
result = solve_puzzle("../input.txt")
print(f"Puzzle result: {result}")
if __name__ == "__main__":
main()

View File

@@ -3,7 +3,9 @@ def generate_difference_table(history):
table = [history]
while not all(value == 0 for value in table[-1]):
try:
next_row = [table[-1][i+1] - table[-1][i] for i in range(len(table[-1]) - 1)]
next_row = [
table[-1][i + 1] - table[-1][i] for i in range(len(table[-1]) - 1)
]
except IndexError as e:
print(f"IndexError in generate_difference_table: {e}")
print(f"Current table: {table}")
@@ -11,22 +13,24 @@ def generate_difference_table(history):
table.append(next_row)
return table
def extrapolate_previous_value(table):
"""Extrapolates the previous value from the difference table."""
try:
for i in range(len(table) - 2, -1, -1):
table[i].insert(0, table[i][0] - table[i+1][0])
table[i].insert(0, table[i][0] - table[i + 1][0])
except IndexError as e:
print(f"IndexError in extrapolate_previous_value: {e}")
print(f"Current table: {table}")
raise
return table[0][0]
def solve_puzzle(filename):
"""Solves the puzzle by reading histories from the file and summing their extrapolated previous values."""
total = 0
try:
with open(filename, 'r') as file:
with open(filename, "r") as file:
for line in file:
try:
history = [int(x) for x in line.split()]
@@ -37,7 +41,7 @@ def solve_puzzle(filename):
print(f"ValueError processing line '{line}': {e}")
except IndexError as e:
print(f"IndexError processing line '{line}': {e}")
except FileNotFoundError as e:
except FileNotFoundError:
print(f"FileNotFoundError: The file {filename} was not found.")
raise
except Exception as e:
@@ -45,6 +49,7 @@ def solve_puzzle(filename):
raise
return total
def test():
"""Runs the test using the test.txt file and asserts the expected outcome for the second part of the puzzle."""
expected = 2 # Expected result from the test data for the second part
@@ -56,6 +61,7 @@ def test():
print(e)
raise
def main():
"""Main function to run the test and then solve the puzzle."""
print("Running test for the second part...")
@@ -64,5 +70,6 @@ def main():
result = solve_puzzle("../input.txt")
print(f"Puzzle result for the second part: {result}")
if __name__ == "__main__":
main()

View File

@@ -38,7 +38,10 @@ fn solve_puzzle(filename: &str) -> Result<i32, io::Error> {
if line.trim().is_empty() {
continue;
}
let history: Vec<i32> = line.split_whitespace().map(|s| s.parse().unwrap()).collect();
let history: Vec<i32> = line
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();
let mut diff_table = generate_difference_table(&history);
let prev_value = extrapolate_previous_value(&mut diff_table);
total += prev_value;
@@ -51,7 +54,11 @@ fn test() -> Result<(), io::Error> {
// Runs the test using the test.txt file and asserts the expected outcome
let expected = 2; // Expected result from the test data for the second part
let result = solve_puzzle("../test.txt")?;
assert_eq!(result, expected, "Test failed: Expected {}, got {}", expected, result);
assert_eq!(
result, expected,
"Test failed: Expected {}, got {}",
expected, result
);
println!("Test passed successfully.");
Ok(())
}

View File

@@ -2,9 +2,9 @@ import fs from 'fs';
function generateDifferenceTable(history: number[]): number[][] {
// Generates a difference table for a given history
let table: number[][] = [history];
const table: number[][] = [history];
while (!table[table.length - 1].every(value => value === 0)) {
let nextRow: number[] = [];
const nextRow: number[] = [];
for (let i = 0; i < table[table.length - 1].length - 1; i++) {
nextRow.push(table[table.length - 1][i + 1] - table[table.length - 1][i]);
}