2020-12-02 17:47:40 +01:00
package helper
import (
2020-12-09 18:14:44 +01:00
"errors"
2020-12-02 17:47:40 +01:00
"io/ioutil"
2020-12-09 18:14:44 +01:00
"sort"
2020-12-02 17:47:40 +01:00
"strconv"
"strings"
)
func GetInput ( filename string ) ( [ ] string , error ) {
content , err := ioutil . ReadFile ( filename )
if err != nil {
return nil , err
}
lines := strings . Split ( string ( content ) , "\n" )
return lines , err
}
2020-12-04 17:45:16 +01:00
func GetFile ( filename string ) ( string , error ) {
content , err := ioutil . ReadFile ( filename )
if err != nil {
return "" , err
}
return string ( content ) , err
}
2020-12-02 17:47:40 +01:00
func MapToNumber ( strings [ ] string ) ( [ ] int , error ) {
var numbers [ ] int
for _ , line := range strings {
number , err := strconv . Atoi ( line )
if err != nil {
return numbers , err
}
numbers = append ( numbers , number )
}
return numbers , nil
}
2020-12-09 18:14:44 +01:00
func FindAddendsForSum ( possibleAddends [ ] int , sum int ) ( int , int , error ) {
var array = make ( [ ] int , len ( possibleAddends ) )
copy ( array , possibleAddends )
sort . Ints ( array )
p1 := 0
p2 := len ( array ) - 1
for p1 < p2 {
if array [ p1 ] + array [ p2 ] < sum {
p1 ++
}
if array [ p1 ] + array [ p2 ] > sum {
p2 --
}
if array [ p1 ] + array [ p2 ] == sum {
return array [ p1 ] , array [ p2 ] , nil
}
}
return 0 , 0 , errors . New ( "No fitting Addends found" )
}
2020-12-15 16:43:32 +01:00
func SliceIndex ( limit int , predicate func ( i int ) bool ) int {
for i := 0 ; i < limit ; i ++ {
if predicate ( i ) {
return i
}
}
return - 1
}