github.com/cycloss/advent-of-code@v0.0.0-20221210145555-15039b95faa6/2015/day2.go (about) 1 package aoc2015 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "reflect" 8 ) 9 10 var intMax = getIntMax() 11 12 func Day2() { 13 var file, _ = os.Open("inputs/day2.txt") 14 var buff = bufio.NewScanner(file) 15 defer file.Close() 16 17 var totalArea = 0 18 var totalRibbon = 0 19 for buff.Scan() { 20 21 var lwh [3]int 22 fmt.Sscanf(buff.Text(), "%dx%dx%d", &lwh[0], &lwh[1], &lwh[2]) 23 totalArea += calculateRequiredPaper(lwh) 24 totalRibbon += calculateRequiredRibbon(lwh) 25 } 26 fmt.Printf("Total sq ft: %d\n", totalArea) 27 fmt.Printf("Total ft of ribbon: %d\n", totalRibbon) 28 } 29 30 func calculateRequiredPaper(lwh [3]int) int { 31 var area = calculateArea(lwh) 32 var smallest, secondSmallest = findSmallestSides(lwh) 33 return area + smallest*secondSmallest 34 } 35 36 func findSmallestSides(lwh [3]int) (int, int) { 37 var smallest = intMax 38 var secondSmallest = intMax 39 for _, v := range lwh { 40 if v < smallest { 41 secondSmallest = smallest 42 smallest = v 43 } else if v < secondSmallest { 44 secondSmallest = v 45 } 46 } 47 return smallest, secondSmallest 48 } 49 50 func calculateArea(lwh [3]int) int { 51 return 2*lwh[0]*lwh[1] + 2*lwh[1]*lwh[2] + 2*lwh[0]*lwh[2] 52 } 53 54 func calculateRequiredRibbon(lwh [3]int) int { 55 var smallest, secondSmallest = findSmallestSides(lwh) 56 var around = smallest*2 + secondSmallest*2 57 58 return around + calculateVolume(lwh) 59 } 60 61 func calculateVolume(lwh [3]int) int { 62 var vol = lwh[0] 63 for i := 1; i < len(lwh); i++ { 64 vol *= lwh[i] 65 } 66 return vol 67 } 68 69 // finds max integer on 32 or 64 bit runtime environments 70 func getIntMax() int { 71 var i = 1 72 var size = reflect.TypeOf(i).Size() * 8 73 if size > 32 { 74 return ^(i << 63) 75 } else { 76 return ^(i << 31) 77 } 78 }