Filled in "ReadInts" implementation and test

This commit is contained in:
Dan Buch 2012-11-18 18:51:59 -05:00
parent 869142a314
commit 3f696f3060
2 changed files with 60 additions and 8 deletions

View File

@ -4,23 +4,36 @@ import (
"bufio"
"io"
"strconv"
"strings"
)
func ReadInts(infile io.Reader) ([]int64, error) {
func ReadInts(inbuf io.Reader) ([]int64, error) {
ints := make([]int64, 0)
var i int64
fileReader := bufio.NewReader(infile)
fileReader := bufio.NewReader(inbuf)
line, err := fileReader.ReadString('\n')
for err == nil {
line = strings.TrimSpace(line)
if len(line) > 0 {
i, err = strconv.ParseInt(line, 10, 0)
if err != nil {
return nil, err
}
ints = append(ints, i)
}
line, err = fileReader.ReadString('\n')
}
if err != nil && err != io.EOF {
return nil, err
}
return ints, nil
}

View File

@ -1,11 +1,50 @@
package algs4_test
import (
"fmt"
"strings"
"testing"
)
import (
"meatballhat.com/algs4"
)
const INTS_STRING = `
999
848
-7271
7384
71878
92
0
0
0
-99
`
func TestReadInts(t *testing.T) {
if 1 == 0 {
t.Error("WAT")
ints, err := algs4.ReadInts(strings.NewReader(INTS_STRING))
if err != nil {
t.Error("Wrong wrong wrong: ", err)
}
if ints == nil {
t.Error("Nothing in the ints!: ", ints)
}
fmt.Println("ints =", ints)
if ints[0] != 999 {
t.Error("fail on 0: 999 !=", ints[0])
}
if ints[4] != 71878 {
t.Error("fail on 4: 71878 !=", ints[4])
}
if ints[6] != 0 {
t.Error("fail on 6: 0 !=", ints[6])
}
}