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

     1  // Package aocshared is the module with the cli logic for the application.
     2  package aocshared
     3  
     4  import (
     5  	"bufio"
     6  	"fmt"
     7  	"os"
     8  	"path/filepath"
     9  )
    10  
    11  // GetFile takes a file name and returns a file handle.
    12  func GetFile(fileName string) (*os.File, error) {
    13  	fileRoot, err := os.Getwd()
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  
    18  	fileRoot = filepath.Clean(fileRoot + "/../../")
    19  	fileName = filepath.Clean(fileRoot + "/" + fileName)
    20  
    21  	// strings.HasPrefix() is pointless since we're generating the full path.
    22  
    23  	// https://securego.io/docs/rules/g304.html - this gosec check seems to want
    24  	// panic() calls
    25  	file, err := os.Open(fileName) // #nosec
    26  
    27  	return file, err
    28  }
    29  
    30  // GetScanner takes a file handle and returns a bufio scanner.
    31  func GetScanner(file *os.File) *bufio.Scanner {
    32  	scanner := bufio.NewScanner(file)
    33  	scanner.Split(bufio.ScanLines)
    34  
    35  	return scanner
    36  }
    37  
    38  // ShowResult prints the passed integer.
    39  func ShowResult(result int) {
    40  	fmt.Printf("%d\n", result)
    41  }
    42  
    43  // Empty type to avoid ugly struct{}{}
    44  var Empty struct{}
    45  
    46  // Set holds a collection of unique items.
    47  type Set map[rune]struct{}
    48  
    49  // SetFromSlice creates a set from a slice.
    50  func SetFromSlice(slice []rune) Set {
    51  	set := make(Set)
    52  
    53  	for _, element := range slice {
    54  		set[element] = Empty
    55  	}
    56  
    57  	return set
    58  }
    59  
    60  // SetIntersect finds the intersection of two sets.
    61  func SetIntersect(s1, s2 Set) []rune {
    62  	common := []rune{}
    63  
    64  	for key := range s1 {
    65  		_, found := s2[key]
    66  		if found {
    67  			common = append(common, key)
    68  		}
    69  	}
    70  
    71  	return common
    72  }
    73  
    74  // SplitString converts a string into a slice of runes.
    75  func SplitString(str string) []rune {
    76  	runes := []rune{}
    77  
    78  	for _, r := range str {
    79  		runes = append(runes, r)
    80  	}
    81  
    82  	return runes
    83  }