Menu
CoddyTech

Project: validate rows

Lesson 44 of 48 in Coddy's Go for C++ Developers course.

challenge icon

Challenge

Easy

Implement ParseLine(string) (Line,error). Accept exactly three pipe-separated fields: nonempty name, positive decimal quantity, nonnegative decimal price. Reject malformed data with a nonnil error. parse counts accepted semicolon-separated rows; an empty row list accepts none. Input line one selects model, parse, total or report. Line two contains the data. Names contain no pipe, semicolon, comma, colon or equals sign; numeric fields and totals are bounded to one million. Preserve all earlier commands. The same locked launcher is used throughout.

Implement the declared APIs; return results without printing. The driver checks required APIs and preserves caller input. Collection stdout uses Go bracket formatting, not JSON.

Your code goes in line.go, parser.go, order.go, report.go, exercise.go. main.go holds the supplied input/output code and cannot be edited. Keep one flat package main; do not add a second main.

Try it yourself

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=L(0); before0:=fmt.Sprint(a0)
a1:=L(1); before1:=fmt.Sprint(a1)
must((Line{"p",2,3}).Subtotal()==6,"Line API"); if L(0)!="model" {l,e:=ParseLine("x|2|4");must(e==nil&&l.Name=="x"&&l.Qty==2&&l.Price==4,"ParseLine API");_,e=ParseLine("x|0|4");must(e!=nil,"invalid quantity");_,e=ParseLine("x|2|-1");must(e!=nil,"invalid price")};if L(0)=="total"||L(0)=="report"{must(Total([]Line{{"p",2,3},{"q",1,4}})==10,"Total API")};if L(0)=="report"{must(Report([]Line{{"b",2,1},{"a",1,9},{"b",1,2}})=="items:a=1,b=3","Report API")};
result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}

All lessons in Go for C++ Developers

Practice on your own: Online Go compiler