day 3a complete

This commit is contained in:
Luke Else 2021-12-03 19:40:58 +00:00
parent 6d016405ad
commit e9a8f04140
4 changed files with 1087 additions and 0 deletions

3
day3/3a/go.mod Normal file
View File

@ -0,0 +1,3 @@
module PWD
go 1.17

72
day3/3a/main.go Normal file
View File

@ -0,0 +1,72 @@
package main
import (
"bufio"
"fmt"
"math"
"os"
)
func main() {
content := returnContent("../input")
//content := returnContent("testInput")
gamma, epsilon := findGammaAndEpsilon(content)
fmt.Println(binaryToInteger(gamma) * binaryToInteger(epsilon))
}
func findGammaAndEpsilon(content *[]string) (gamma string, epsilon string) {
for i := 0; i < len((*content)[1]); i++ {
count := 0
//Loop through list checking index[i] for each string
for j := 0; j < len(*content); j++ {
if ((*content)[j])[i] == '1' {
count++
}
}
if count >= len(*content)/2 {
gamma += "1"
epsilon += "0"
} else {
gamma += "0"
epsilon += "1"
}
}
return
}
func binaryToInteger(input string) (value int) {
n := 0
for i := len(input) - 1; i >= 0; i-- {
if input[i] == '1' {
value += (int(math.Pow(float64(2), float64(n))))
}
n++
}
return
}
func returnContent(path string) *[]string {
//read file and return it as an array of integers
file, err := os.Open(path)
var content []string
if err != nil {
fmt.Println("Unlucky, the file didn't open")
return &content
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
content = append(content, scanner.Text())
}
return &content
}

12
day3/3a/testInput Normal file
View File

@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010

1000
day3/input Normal file

File diff suppressed because it is too large Load Diff