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

@@ -1,24 +1,26 @@
import os
from collections import Counter
def read_hands(file_path):
"""
Reads hands and their bids from the file.
Returns a list of tuples (hand, bid).
"""
try:
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
return [line.strip().split() for line in file]
except Exception as e:
print(f"Error reading file {file_path}: {e}")
raise
def replace_face_cards(hand):
"""
Replaces face cards with characters that maintain the card order.
"""
replacements = {'T': 'a', 'J': 'b', 'Q': 'c', 'K': 'd', 'A': 'e'}
return ''.join(replacements.get(card, card) for card in hand)
replacements = {"T": "a", "J": "b", "Q": "c", "K": "d", "A": "e"}
return "".join(replacements.get(card, card) for card in hand)
def categorize_hand(hand):
"""
@@ -44,6 +46,7 @@ def categorize_hand(hand):
return (category, hand)
def hand_key(hand):
"""
Key function for sorting hands.
@@ -51,25 +54,32 @@ def hand_key(hand):
"""
return categorize_hand(hand[0])
def calculate_total_winnings(file_path):
"""
Calculates the total winnings from the hands in the file.
"""
hands = read_hands(file_path)
sorted_hands = sorted(hands, key=hand_key, reverse=True)
total_winnings = sum(int(bid) * (len(hands) - index) for index, (_, bid) in enumerate(sorted_hands))
total_winnings = sum(
int(bid) * (len(hands) - index) for index, (_, bid) in enumerate(sorted_hands)
)
return total_winnings
def test():
print(f"Running test...")
print("Running test...")
try:
expected_result = 6440
total_winnings = calculate_total_winnings("../test.txt")
assert total_winnings == expected_result, f"Test failed, expected {expected_result} but got {total_winnings}"
assert (
total_winnings == expected_result
), f"Test failed, expected {expected_result} but got {total_winnings}"
print(f"Test passed: {total_winnings}")
except Exception as e:
print(f"Test failed: {e}")
def main():
try:
test()
@@ -80,5 +90,6 @@ def main():
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()

View File

@@ -1,41 +1,45 @@
import os
from collections import Counter
def read_hands(file_path):
try:
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
print("Reading hands...")
return [line.strip().split() for line in file]
except Exception as e:
print(f"Error reading file {file_path}: {e}")
raise
def replace_face_cards(hand):
replacements = {'T': 'a', 'J': '1', 'Q': 'c', 'K': 'd', 'A': 'e'}
return ''.join(replacements.get(card, card) for card in hand)
replacements = {"T": "a", "J": "1", "Q": "c", "K": "d", "A": "e"}
return "".join(replacements.get(card, card) for card in hand)
def strength(hand):
hand = replace_face_cards(hand)
C = Counter(hand)
target = max(C, key=lambda k: (C[k], k != '1')) # Find the target card, excluding joker
target = max(
C, key=lambda k: (C[k], k != "1")
) # Find the target card, excluding joker
if '1' in C and target != '1':
C[target] += C['1']
del C['1']
if "1" in C and target != "1":
C[target] += C["1"]
del C["1"]
if sorted(C.values()) == [5]:
category = 10
elif sorted(C.values()) == [1,4]:
elif sorted(C.values()) == [1, 4]:
category = 9
elif sorted(C.values()) == [2,3]:
elif sorted(C.values()) == [2, 3]:
category = 8
elif sorted(C.values()) == [1,1,3]:
elif sorted(C.values()) == [1, 1, 3]:
category = 7
elif sorted(C.values()) == [1,2,2]:
elif sorted(C.values()) == [1, 2, 2]:
category = 6
elif sorted(C.values()) == [1,1,1,2]:
elif sorted(C.values()) == [1, 1, 1, 2]:
category = 5
elif sorted(C.values()) == [1,1,1,1,1]:
elif sorted(C.values()) == [1, 1, 1, 1, 1]:
category = 4
else:
raise ValueError(f"Invalid hand: {C} {hand}")
@@ -43,27 +47,35 @@ def strength(hand):
print(f"Hand: {hand}, Category: {category}")
return (category, hand)
def hand_key(hand):
return strength(hand[0])
def calculate_total_winnings(file_path):
hands = read_hands(file_path)
print("Sorting hands based on strength...")
sorted_hands = sorted(hands, key=hand_key, reverse=True)
total_winnings = sum(int(bid) * (len(hands) - index) for index, (_, bid) in enumerate(sorted_hands))
total_winnings = sum(
int(bid) * (len(hands) - index) for index, (_, bid) in enumerate(sorted_hands)
)
print("Calculating total winnings...")
return total_winnings
def test(file_path):
print(f"Running test with {file_path}...")
try:
expected_result = 5905
total_winnings = calculate_total_winnings(file_path)
assert total_winnings == expected_result, f"Test failed, expected {expected_result} but got {total_winnings}"
assert (
total_winnings == expected_result
), f"Test failed, expected {expected_result} but got {total_winnings}"
print(f"Test passed: {total_winnings}")
except Exception as e:
print(f"Test failed: {e}")
def main():
try:
test("../test.txt")
@@ -72,5 +84,6 @@ def main():
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()

View File

@@ -7,14 +7,12 @@ fn read_hands(filename: &str) -> io::Result<Vec<(String, i32)>> {
let lines = io::BufReader::new(file).lines();
let mut hands = Vec::new();
for line in lines {
if let Ok(line) = line {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() == 2 {
let hand = parts[0].to_string();
let bid: i32 = parts[1].parse().unwrap();
hands.push((hand, bid));
}
for line in lines.flatten() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() == 2 {
let hand = parts[0].to_string();
let bid: i32 = parts[1].parse().unwrap();
hands.push((hand, bid));
}
}
Ok(hands)
@@ -22,11 +20,11 @@ fn read_hands(filename: &str) -> io::Result<Vec<(String, i32)>> {
fn replace_face_cards(hand: &str) -> String {
let mut replaced = hand.to_string();
replaced = replaced.replace("T", "a");
replaced = replaced.replace("J", "1");
replaced = replaced.replace("Q", "c");
replaced = replaced.replace("K", "d");
replaced = replaced.replace("A", "e");
replaced = replaced.replace('T', "a");
replaced = replaced.replace('J', "1");
replaced = replaced.replace('Q', "c");
replaced = replaced.replace('K', "d");
replaced = replaced.replace('A', "e");
replaced
}
@@ -44,7 +42,11 @@ fn calculate_strength(hand: &str) -> (i32, String) {
let mut best_category = 4; // Default to High card
for (card, count) in &counts {
let adjusted_count = if *card != '1' { count + joker_count } else { *count };
let adjusted_count = if *card != '1' {
count + joker_count
} else {
*count
};
best_category = best_category.max(match adjusted_count {
5 => 10,
4 => 9,
@@ -56,7 +58,10 @@ fn calculate_strength(hand: &str) -> (i32, String) {
// Use original hand for tie-breaking
let tie_breaker_hand = hand.chars().collect::<String>();
println!("Hand: {}, Strength: {}, Tie-breaker hand: {}", hand, best_category, tie_breaker_hand);
println!(
"Hand: {}, Strength: {}, Tie-breaker hand: {}",
hand, best_category, tie_breaker_hand
);
(best_category, tie_breaker_hand)
}
@@ -69,17 +74,30 @@ fn calculate_total_winnings(hands: Vec<(String, i32)>) -> i32 {
(strength_b, tie_breaker_b).cmp(&(strength_a, tie_breaker_a))
});
sorted_hands.iter().enumerate().fold(0, |acc, (i, (hand, bid))| {
let winnings = bid * (i as i32 + 1);
println!("Hand: {}, Rank: {}, Bid: {}, Winnings: {}", hand, i + 1, bid, winnings);
acc + winnings
})
sorted_hands
.iter()
.enumerate()
.fold(0, |acc, (i, (hand, bid))| {
let winnings = bid * (i as i32 + 1);
println!(
"Hand: {}, Rank: {}, Bid: {}, Winnings: {}",
hand,
i + 1,
bid,
winnings
);
acc + winnings
})
}
fn main() {
let test_hands = read_hands("../test.txt").expect("Failed to read test file");
let test_total = calculate_total_winnings(test_hands);
assert_eq!(test_total, 5905, "Test failed: expected 5905, got {}", test_total);
assert_eq!(
test_total, 5905,
"Test failed: expected 5905, got {}",
test_total
);
println!("Test passed: Total winnings = {}", test_total);
let hands = read_hands("../input.txt").expect("Failed to read input file");