Menu
CoddyTech

Project: quantity report

Lesson 46 of 48 in Coddy's Go for PHP Developers course.

challenge icon

Challenge

Easy

Implement Report([]Line) string. Aggregate quantities by exact name, sort names bytewise, return items:name=count pairs joined by commas. Empty input returns items:. report skips invalid rows. 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 PHP Developers

Practice on your own: Online Go compiler