diff --git a/day07/day07.go b/day07/day07.go index c16b5df..164e5ac 100644 --- a/day07/day07.go +++ b/day07/day07.go @@ -1,8 +1,11 @@ package day07 import ( + "bufio" "log" "math" + "os" + "slices" "strconv" "strings" ) @@ -118,10 +121,11 @@ func (h1 Hand) compare(h2 Hand) int { } cardValueMap := map[string]int{ - "A": 13, - "K": 12, - "Q": 11, - "J": 10, + "A": 14, + "K": 13, + "Q": 12, + "J": 11, + "T": 10, "9": 9, "8": 8, "7": 7, @@ -146,7 +150,43 @@ func (h1 Hand) compare(h2 Hand) int { } func Solution1(filepath string) int { - return 0 + file, err := os.Open(filepath) + if err != nil { + log.Fatalf("Failed to open the input file: %v\n", err.Error()) + } + + var hands []Hand + scanner := bufio.NewScanner(file) + for scanner.Scan() { + currentLineSplit := strings.Split(scanner.Text(), " ") + newHand := makeHand( + strings.TrimSpace(currentLineSplit[0]), + strings.TrimSpace(currentLineSplit[1]), + ) + + placed := false + for i := 0; i < len(hands); i++ { + if newHand.compare(hands[i]) <= 0 { + hands = slices.Insert(hands, i, newHand) + placed = true + break + } + } + + if !placed { + hands = append(hands, newHand) + } + } + if err = scanner.Err(); err != nil { + log.Fatalf("Error during input file read: %v\n", err.Error()) + } + + result := 0 + for i, hand := range hands { + result += (i + 1) * hand.bid + } + + return result } func Solution2(filepath string) int { diff --git a/day07/day07_test.go b/day07/day07_test.go index 723b50b..6621016 100644 --- a/day07/day07_test.go +++ b/day07/day07_test.go @@ -2,6 +2,8 @@ package day07 import ( "fmt" + "slices" + "strings" "testing" ) @@ -19,3 +21,36 @@ func TestSolution1(t *testing.T) { } } } + +func TestMakeHand(t *testing.T) { + result := makeHand("AAKKQ", "999") + + if result.combinationStrength == 200 && result.bid == 999 && slices.Compare(result.cards, []string{"A", "A", "K", "K", "Q"}) == 0 { + fmt.Println("makeHand() OK") + } else { + t.Fatalf("makeHand() unexpected result %v\n", result) + } +} + +func TestCalcCombinationStrength(t *testing.T) { + cases := map[string]int{ + "AAAAA": 100000, // five of a kind + "KKJKK": 10000, // four of a kind + "JJQQJ": 1100, // full house + "AKQKK": 1000, // three of a kind + "77AQQ": 200, // two pairs + "22AQK": 100, // one pair + "AKQJ9": 1, // highest card + } + + for inputCards, expectedResult := range cases { + input := strings.Split(inputCards, "") + + result := calcCombinationStrength(input) + if result != expectedResult { + t.Fatalf("calcCombinationStrength() = %d, expecting %d\n", result, expectedResult) + } else { + fmt.Printf("calcCombinationStrength() = %d, OK\n", result) + } + } +}