github.com/vpayno/adventofcode-2022-golang-workspace@v0.0.0-20230605190011-dbafed5593de/internal/day02/app.go (about)

     1  // Package day02 is the module with the cli logic for the application.
     2  package day02
     3  
     4  import (
     5  	"bufio"
     6  	"fmt"
     7  	"strings"
     8  
     9  	"github.com/vpayno/adventofcode-2022-golang-workspace/internal/aocshared"
    10  )
    11  
    12  // Run is called my the gain function. It's basically the main function of the app.
    13  func Run(conf Config) error {
    14  	file, err := aocshared.GetFile(conf.inputFileName)
    15  	if err != nil {
    16  		return err
    17  	}
    18  
    19  	scanner := aocshared.GetScanner(file)
    20  
    21  	data, err := loadData(scanner)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	totalScore := getTotalScore(data)
    27  
    28  	aocshared.ShowResult(totalScore)
    29  
    30  	return nil
    31  }
    32  
    33  func loadData(file *bufio.Scanner) (rounds, error) {
    34  	var err error
    35  
    36  	data := rounds{}
    37  
    38  	for file.Scan() {
    39  		line := file.Text()
    40  
    41  		if line == "" {
    42  			continue
    43  		}
    44  
    45  		s := strings.Fields(line)
    46  
    47  		if len(s) != 2 {
    48  			err := fmt.Errorf("wrong number of records: has %d, need %d", len(s), 2)
    49  			return []round{}, err
    50  		}
    51  
    52  		theirMove := string2move[s[them]]
    53  		yourGoal := string2outcome[s[goal]]
    54  
    55  		r := round{
    56  			them: theirMove,
    57  			goal: yourGoal,
    58  		}
    59  
    60  		data = append(data, r)
    61  	}
    62  
    63  	return data, err
    64  }
    65  
    66  func getTotalScore(data rounds) int {
    67  	var result int
    68  
    69  	for _, r := range data {
    70  		result += r.score()
    71  	}
    72  
    73  	return result
    74  }