some-advent-of-code: 874684ef5943175a936d6620261bc44d403f025d

     1: package main
     2:  
     3: import (
     4: 	"bufio"
     5: 	"fmt"
     6: 	"log"
     7: 	"os"
     8: 	"strconv"
     9: 	"strings"
    10: )
    11:  
    12: func main() {
    13: 	if len( os.Args ) < 2 {
    14: 		log.Fatal( "Error: need filepath argument" )
    15: 	}
    16: 	filePath := os.Args[ 1 ]
    17: 	fileLines := readLines( filePath )
    18: 
    19: 	calculateDepth( fileLines )
    20: }
    21: 
    22: func readLines( filepath string ) []string {
    23: 	file, err := os.Open(filepath)
    24: 	if err != nil {
    25: 		log.Fatal(err)
    26: 	}
    27: 
    28: 	defer file.Close()
    29: 
    30: 	var lines []string
    31: 
    32: 	scanner := bufio.NewScanner(file)
    33: 	for scanner.Scan() {
    34: 		lines = append(lines, scanner.Text())
    35: 	}
    36: 
    37: 	if scanner.Err() != nil {
    38: 		log.Fatal(scanner.Err())
    39: 	}
    40: 	return lines
    41: }
    42: 
    43: func calculateDepth( fileLines []string ) {
    44: 	horizontalPosition := 0
    45: 	depth := 0
    46: 	dirInd := 0
    47: 	valInd := dirInd +1
    48: 	for _, line := range fileLines {
    49: 		if len( line ) < 1 {
    50: 			continue
    51: 		}
    52: 		
    53: 		direction_magnitude := strings.Split( line, " " )
    54: 		magnitude, err := strconv.Atoi( direction_magnitude[ valInd ] )
    55: 		if err != nil {
    56: 		log.Fatal( "not an int ", direction_magnitude[ valInd ] ) // very paranoid, le sigh
    57: 		}
    58: 		switch direction_magnitude[ dirInd ] {
    59: 		case "up" :
    60: 			depth -= magnitude
    61: 		case "down" :
    62: 			depth += magnitude
    63: 		// fallthrough if I want that behavior
    64: 		default : // forward
    65: 			horizontalPosition += magnitude
    66: 		}
    67: 	}
    68: 	
    69: 	fmt.Println( "\tresult ", ( horizontalPosition * depth ) )
    70: }
    71: 
    72: 
    73: 
    74: 
    75: 
    76: 
    77: 
    78: 
    79: 
    80: 
    81: 
    82: 
    83: 
    84: 
    85: 
    86: 
    87: 

Generated by git2html.