From 3f696f3060c6fa2acf73e35c44512cc1012751bd Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sun, 18 Nov 2012 18:51:59 -0500 Subject: [PATCH] Filled in "ReadInts" implementation and test --- algs4/src/meatballhat.com/algs4/io.go | 25 ++++++++++--- algs4/src/meatballhat.com/algs4/io_test.go | 43 +++++++++++++++++++++- 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/algs4/src/meatballhat.com/algs4/io.go b/algs4/src/meatballhat.com/algs4/io.go index 2b87eec..624a137 100644 --- a/algs4/src/meatballhat.com/algs4/io.go +++ b/algs4/src/meatballhat.com/algs4/io.go @@ -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 { - i, err = strconv.ParseInt(line, 10, 0) - if err != nil { - return nil, err + 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) } - ints = append(ints, i) + line, err = fileReader.ReadString('\n') } + if err != nil && err != io.EOF { + return nil, err + } + return ints, nil } diff --git a/algs4/src/meatballhat.com/algs4/io_test.go b/algs4/src/meatballhat.com/algs4/io_test.go index 14dbb73..307a5dc 100644 --- a/algs4/src/meatballhat.com/algs4/io_test.go +++ b/algs4/src/meatballhat.com/algs4/io_test.go @@ -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]) } }