Skip to content

Commit

Permalink
Day 7: part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
dmytro-spivakov committed Oct 13, 2024
1 parent 3d9468d commit 4583037
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 5 deletions.
50 changes: 45 additions & 5 deletions day07/day07.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package day07

import (
"bufio"
"log"
"math"
"os"
"slices"
"strconv"
"strings"
)
Expand Down Expand Up @@ -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,
Expand All @@ -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 {
Expand Down
35 changes: 35 additions & 0 deletions day07/day07_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package day07

import (
"fmt"
"slices"
"strings"
"testing"
)

Expand All @@ -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)
}
}
}

0 comments on commit 4583037

Please sign in to comment.