advent2020

package
v0.0.0-...-a2894a6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 22, 2023 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Northward HexDirection = "n"
	Northeast              = "ne"
	Eastward               = "e"
	Southeast              = "se"
	Southward              = "s"
	Southwest              = "sw"
	Westward               = "w"
	Northwest              = "nw"
)
View Source
const (
	North   = Action("N")
	South   = Action("S")
	East    = Action("E")
	West    = Action("W")
	Left    = Action("L")
	Right   = Action("R")
	Forward = Action("F")
)

Variables

View Source
var FirstVisible = NeighboringStrategy(func(locale location.Coordinate, seatsByLocation map[location.Coordinate]Seat) []Seat {
	var maxRow, maxCol int

	for l := range seatsByLocation {
		if l.Row > maxRow {
			maxRow = l.Row
		}

		if l.Col > maxCol {
			maxCol = l.Col
		}
	}

	type modifier func(location.Coordinate) location.Coordinate

	upwardLeftDiagonal := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row - 1, l.Col - 1}
	})
	upward := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row - 1, l.Col}
	})
	upwardRightDiagonal := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row - 1, l.Col + 1}
	})
	left := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row, l.Col - 1}
	})
	right := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row, l.Col + 1}
	})
	downwardLeftDiagonal := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row + 1, l.Col - 1}
	})
	down := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row + 1, l.Col}
	})
	downwardRightDiagonal := modifier(func(l location.Coordinate) location.Coordinate {
		return location.Coordinate{l.Row + 1, l.Col + 1}
	})

	modifiers := []modifier{
		upwardLeftDiagonal,
		upward,
		upwardRightDiagonal,
		left,
		right,
		downwardLeftDiagonal,
		down,
		downwardRightDiagonal,
	}

	visibleNeighbors := make(chan Seat, len(modifiers))
	var wg sync.WaitGroup

	for _, m := range modifiers {
		wg.Add(1)
		go func(origin location.Coordinate, mod modifier, out chan<- Seat, waitGroup *sync.WaitGroup) {
			current := location.Coordinate{origin.Row, origin.Col}

			for {
				current = mod(current)

				if seat, present := seatsByLocation[current]; present {
					out <- seat
					break
				}

				if current.Row < 0 || current.Col < 0 || current.Row > maxRow || current.Col > maxCol {
					break
				}
			}

			waitGroup.Done()
		}(locale, m, visibleNeighbors, &wg)
	}

	wg.Wait()
	close(visibleNeighbors)

	collected := map[location.Coordinate]struct{}{}

	neighbors := []Seat{}

	for neighbor := range visibleNeighbors {
		if _, seen := collected[neighbor.Location]; !seen {
			neighbors = append(neighbors, neighbor)
			collected[neighbor.Location] = struct{}{}
		}
	}

	return neighbors
})
View Source
var NearestNeighbor = NeighboringStrategy(func(locale location.Coordinate, seatsByLocation map[location.Coordinate]Seat) []Seat {
	var neighbors []Seat

	neighboringLocations := []location.Coordinate{
		{locale.Row - 1, locale.Col - 1},
		{locale.Row - 1, locale.Col},
		{locale.Row - 1, locale.Col + 1},
		{locale.Row, locale.Col - 1},
		{locale.Row, locale.Col + 1},
		{locale.Row + 1, locale.Col - 1},
		{locale.Row + 1, locale.Col},
		{locale.Row + 1, locale.Col + 1},
	}

	for _, l := range neighboringLocations {
		if seat, present := seatsByLocation[l]; present {
			neighbors = append(neighbors, seat)
		}
	}

	return neighbors
})

Functions

func CountAffirmatives

func CountAffirmatives(groups []Group) int

func CountDistinctPossibleArrangements

func CountDistinctPossibleArrangements(r io.Reader) int

func CountEncounteredTrees

func CountEncounteredTrees(tm TrajectoryMap, slope location.Slope) int

func CountValidPasswords

func CountValidPasswords(r io.Reader) int

func CountValidPasswordsUpdatedPolicy

func CountValidPasswordsUpdatedPolicy(r io.Reader) int

func DetermineAccumulatorValueBeforeLoop

func DetermineAccumulatorValueBeforeLoop(commands []Command) int

func DetermineEncryptionKey

func DetermineEncryptionKey(r io.Reader) int

func EvaluateExpression

func EvaluateExpression(e Expression) int

func FindEarliestBus

func FindEarliestBus(i Itinerary) (int, int)

func FindEarliestTimestampWithDepartureCadence

func FindEarliestTimestampWithDepartureCadence(i Itinerary) int

func FindEncryptionWeakness

func FindEncryptionWeakness(values []int, target int) (int, int)

func FindFirstEncodingError

func FindFirstEncodingError(r io.Reader, preambleLength, lookbackLength int) (int, []int)

func FindJoltDifferences

func FindJoltDifferences(r io.Reader) map[int]int

func FindMaxSeatID

func FindMaxSeatID(r io.Reader) int

func FindMissingSeatID

func FindMissingSeatID(r io.Reader) int

func FindNthSpokenNumber

func FindNthSpokenNumber(r io.Reader, n int) int

func FindSeatLocation

func FindSeatLocation(boardingPass string) (int, int)

func NewCardQueue

func NewCardQueue(cards []Card) *cardQueue

func ParseDecks

func ParseDecks(r io.Reader) (Deck, Deck)

func RepairReport

func RepairReport(r io.Reader) int

func RepairReportTriplet

func RepairReportTriplet(r io.Reader) int

func Run

func Run(commands []Command) int

func SerializeRound

func SerializeRound(firstPlayer, secondPlayer Deck) string

Types

type Action

type Action string

type BagRules

type BagRules map[string]map[string]int

func ParseBagRules

func ParseBagRules(r io.Reader) BagRules

func (BagRules) FindAncestorsOf

func (b BagRules) FindAncestorsOf(bag string) []string

func (BagRules) TotalDescendantsOf

func (b BagRules) TotalDescendantsOf(ancestor string) int

type Bus

type Bus struct {
	ID, ArrivalOffset int
}

type Card

type Card int

type CardQueue

type CardQueue interface {
	Enqueue(Card)
	Dequeue() (Card, error)
	Peek() (Card, error)
	Size() int
}

type Circle

type Circle struct {
	Cups      *ring.Ring
	CupsByID  map[int]*ring.Ring
	Current   *ring.Ring
	Low, High int
}

func ParseCups

func ParseCups(r io.Reader) Circle

func (*Circle) AddAdditionalCups

func (c *Circle) AddAdditionalCups(n int)

func (*Circle) Move

func (c *Circle) Move()

func (Circle) Serialize

func (c Circle) Serialize(start ...int) string

type Command

type Command struct {
	// contains filtered or unexported fields
}

func ParseProgram

func ParseProgram(r io.Reader) []Command

func PatchProgram

func PatchProgram(commands []Command) []Command

type Computer

type Computer struct {
	Version Version
	Mask    string
	Memory  map[int]int
}

type CoordinateQueue

type CoordinateQueue interface {
	Enqueue(location.Coordinate)
	Dequeue() (location.Coordinate, error)
	Peek() (location.Coordinate, error)
	Size() int
}

func NewCoordinateQueue

func NewCoordinateQueue(coordinates ...location.Coordinate) CoordinateQueue

type Cube

type Cube struct {
	CellsByLocation map[location.Point]CubeCell
}

func ParseConwayCube

func ParseConwayCube(r io.Reader) Cube

func (Cube) CellCountByStatus

func (c Cube) CellCountByStatus(status CubeStatus) int

func (*Cube) RunCycle

func (c *Cube) RunCycle()

type CubeCell

type CubeCell struct {
	Coordinate location.Point
	Status     CubeStatus
}

func (CubeCell) NeighborLocations

func (c CubeCell) NeighborLocations() []location.Point

type CubeStatus

type CubeStatus int
const (
	Active CubeStatus
	Inactive
)

type Deck

type Deck struct {
	Player int
	Queue  *cardQueue
}

func Battle

func Battle(firstDeck, secondDeck *Deck) *Deck

func NewDeck

func NewDeck(player int, cards []Card) Deck

func RecursiveBattle

func RecursiveBattle(firstDeck, secondDeck *Deck) *Deck

func (*Deck) PlaceCards

func (d *Deck) PlaceCards(winner, loser Card)

func (Deck) Score

func (d Deck) Score() int

func (Deck) Serialize

func (d Deck) Serialize() string

type Door

type Door struct {
	Encryptor
}

type Edge

type Edge uint16

func (Edge) Flip

func (e Edge) Flip(bits ...int) Edge

type Encryptor

type Encryptor struct {
	LoopNumber int
}

func (*Encryptor) DeriveLoopNumber

func (e *Encryptor) DeriveLoopNumber(publicKey int)

func (Encryptor) Encrypt

func (e Encryptor) Encrypt(publicKey int) int

type Expression

type Expression []Token

func ParseExpression

func ParseExpression(s string) Expression

func ParseExpressions

func ParseExpressions(r io.Reader) []Expression

type Floor

type Floor struct {
	AllDirections [][]HexDirection
	// contains filtered or unexported fields
}

func ParseAllDirections

func ParseAllDirections(r io.Reader) Floor

func (*Floor) Follow

func (f *Floor) Follow(directions []HexDirection)

func (Floor) GetBlackCount

func (f Floor) GetBlackCount() int

func (*Floor) Rotate

func (f *Floor) Rotate()

type Food

type Food struct {
	Ingredients []string
	Allergens   []string
}

type FoodListing

type FoodListing []Food

func ParseFoodListing

func ParseFoodListing(r io.Reader) FoodListing

func (FoodListing) CountOccurrencesFor

func (f FoodListing) CountOccurrencesFor(ingredients []string) map[string]int

func (FoodListing) FindNonAllergenicIngredients

func (f FoodListing) FindNonAllergenicIngredients() ([]string, []string)

type Group

type Group struct {
	Affirmatives map[int]map[rune]struct{}
}

func ParseGroups

func ParseGroups(r io.Reader) []Group

type HexDirection

type HexDirection string

func ParseDirections

func ParseDirections(value string) []HexDirection

type Instruction

type Instruction struct {
	Operation       Op
	Location, Value int
	Mask            string
}

func (Instruction) Apply

func (i Instruction) Apply(c *Computer)

type Itinerary

type Itinerary struct {
	EarliestDeparture int
	Busses            []Bus
}

func ParseShuttleItinerary

func ParseShuttleItinerary(r io.Reader) Itinerary
type NavigationInstruction struct {
	Action Action
	Value  int
}

func ParseNavigationInstructions

func ParseNavigationInstructions(r io.Reader) []NavigationInstruction

type NeighboringStrategy

type NeighboringStrategy func(location.Coordinate, map[location.Coordinate]Seat) []Seat

type Op

type Op int
const (
	SetMask Op
	Write
)

type Operand

type Operand int

func (Operand) Value

func (o Operand) Value() string

type Operation

type Operation string
const (
	NoOp       Operation = "nop"
	Accumulate Operation = "acc"
	Jump       Operation = "jmp"
)

type Operator

type Operator string

func (Operator) Apply

func (o Operator) Apply(a, b Operand) int

func (Operator) Precedence

func (o Operator) Precedence() int

func (Operator) Value

func (o Operator) Value() string

type Orientation

type Orientation int
const (
	Unknown Orientation = iota
	Northbound
	Eastbound
	Southbound
	Westbound
)

type Passport

type Passport struct {
	BirthYear, IssueYear, ExpirationYear, Height string
	HairColor, EyeColor, PassportID, CountryID   string
}

func ParsePassports

func ParsePassports(r io.Reader) []Passport

func (Passport) IsValid

func (p Passport) IsValid() bool

type PasswordDBEntry

type PasswordDBEntry struct {
	Policy   PasswordPolicy
	Password string
}

func (PasswordDBEntry) IsValid

func (p PasswordDBEntry) IsValid(policyType ...PolicyType) bool

type PasswordPolicy

type PasswordPolicy struct {
	Character                      rune
	MinOccurrences, MaxOccurrences int
}

type Pixel

type Pixel rune

type PolicyType

type PolicyType int
const (
	Legacy PolicyType
	Current
)

type Program

type Program []Instruction

func ParseInitializationProgram

func ParseInitializationProgram(r io.Reader) Program

func (Program) Run

func (p Program) Run(c *Computer)

type Queue

type Queue interface {
	Enqueue(string)
	Dequeue() (string, error)
	Size() int
}

func NewStringQueue

func NewStringQueue() Queue

type RangeValidator

type RangeValidator struct {
	LowerBound, UpperBound int
}

func (RangeValidator) Validate

func (r RangeValidator) Validate(i int) bool

type RoomCard

type RoomCard struct {
	Encryptor
}

type Rule

type Rule struct {
	ID       int
	Letter   string
	Subrules [][]int
}

type Ruleset

type Ruleset map[int]Rule

func ParseRulesAndMessages

func ParseRulesAndMessages(r io.Reader) (Ruleset, []string)

func (Ruleset) FindMatches

func (rs Ruleset) FindMatches(ruleNumber int, values []string) int

func (Ruleset) Match

func (rs Ruleset) Match(ruleNumber int, value string) []int

type Seat

type Seat struct {
	Location location.Coordinate
	Status   State
}

func (Seat) GetNeighbors

func (s Seat) GetNeighbors(strategy NeighboringStrategy, seatsByLocation map[location.Coordinate]Seat) []Seat

type SeatingArrangement

type SeatingArrangement []Seat

func ParseSeatingArrangement

func ParseSeatingArrangement(r io.Reader) SeatingArrangement

func (SeatingArrangement) Equals

func (s SeatingArrangement) Equals(other SeatingArrangement) bool

func (SeatingArrangement) RunSeatingCycle

func (s SeatingArrangement) RunSeatingCycle(occupancyThreshold int, strategies ...NeighboringStrategy) SeatingArrangement

func (SeatingArrangement) SeatsByState

func (s SeatingArrangement) SeatsByState(state State) []Seat

type Ship

type Ship struct {
	Location    location.Point
	Orientation Orientation
	Waypoint    location.Point
}

func (*Ship) Navigate

func (s *Ship) Navigate(instructions []NavigationInstruction)

func (*Ship) NavigateByWaypoint

func (s *Ship) NavigateByWaypoint(instructions []NavigationInstruction)

type Side

type Side int
const (
	TOP Side = iota
	RIGHT
	BOTTOM
	LEFT
)

type Stack

type Stack interface {
	Push(i int)
	Pop() (int, error)
	Peek() (int, error)
	Size() int
}

func NewIntStack

func NewIntStack() Stack

type State

type State int
const (
	Occupied State
	Empty
)

type TicketRules

type TicketRules map[string][]Validator

func ParseTicketRules

func ParseTicketRules(r io.Reader) (TicketRules, [][]int)

func (TicketRules) DetermineFieldLocale

func (t TicketRules) DetermineFieldLocale(tickets [][]int) map[string]int

func (TicketRules) FindErrorScanRate

func (t TicketRules) FindErrorScanRate(tickets [][]int) (int, [][]int)

type Tile

type Tile struct {
	ID     int
	Pixels [][]Pixel
}

func (Tile) Edges

func (t Tile) Edges() [4]Edge

func (*Tile) Flip

func (t *Tile) Flip()

func (Tile) Print

func (t Tile) Print(row int) string

func (Tile) PrintAll

func (t Tile) PrintAll() string

func (*Tile) Rotate

func (t *Tile) Rotate()

type Tileset

type Tileset []Tile

func ParseImageTiles

func ParseImageTiles(r io.Reader) Tileset

func (Tileset) AllEdges

func (t Tileset) AllEdges() map[Edge][]int

func (Tileset) FindCorners

func (t Tileset) FindCorners() ([]int, map[int]struct{})

func (Tileset) Print

func (t Tileset) Print() string

func (*Tileset) ProperlyArrange

func (t *Tileset) ProperlyArrange()

type Token

type Token interface {
	Value() string
}

type TokenQueue

type TokenQueue interface {
	Enqueue(Token)
	Dequeue() (Token, error)
	Peek() (Token, error)
	Size() int
}

func NewTokenQueue

func NewTokenQueue() TokenQueue

type TokenStack

type TokenStack interface {
	Push(Token)
	Pop() (Token, error)
	Peek() (Token, error)
	Size() int
}

func NewTokenStack

func NewTokenStack() TokenStack

type TrajectoryMap

type TrajectoryMap struct {
	Trees         map[location.Coordinate]struct{}
	Rows, Columns int
}

func NewTrajectoryMap

func NewTrajectoryMap(r io.Reader) TrajectoryMap

type Validator

type Validator interface {
	Validate(int) bool
}

type Version

type Version int
const (
	Version1 Version
	Version2
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL