Here is the Golang code. Even though it uses the exact same algorithm, it runs surprisingly faster!
packagemainimport("bufio""fmt""math""os""strconv""strings")typecoordstruct{xintyint}// readLines reads a whole file into memory// and returns a slice of its lines.funcreadLines(pathstring)([]string,error){file,err:=os.Open(path)iferr!=nil{returnnil,err}deferfile.Close()varlines[]stringscanner:=bufio.NewScanner(file)forscanner.Scan(){lines=append(lines,scanner.Text())}returnlines,scanner.Err()}funcabs(xint)int{ifx<0{return-x}returnx}funcmax(a,bint)int{ifa<b{returnb}returna}funcmin(a,bint)int{returnmax(-a,-b)}funccalculateDistance(p1,p2coord)int{returnabs(p1.x-p2.x)+abs(p1.y-p2.y)}funcmakeCoord(dstring)coord{c:=strings.Split(d,", ")x,_:=strconv.Atoi(c[1])y,_:=strconv.Atoi(c[0])returncoord{x:x,y:y}}funcmain(){data,err:=readLines("input")iferr!=nil{panic(err)}// Find the outer border:varouterTop,outerBottom,outerLeft,outerRightintouterBottom=math.MaxInt32outerLeft=math.MaxInt32P:=[]coord{}for_,d:=rangedata{c:=makeCoord(d)P=append(P,c)outerTop=max(outerTop,c.y)outerBottom=min(outerBottom,c.y)outerLeft=min(outerLeft,c.x)outerRight=max(outerRight,c.x)}// Map coordinates to closest points and count:countP:=map[coord]int{}canvas:=map[coord]int{}fory:=outerBottom;y<=outerTop;y++{forx:=outerLeft;x<=outerRight;x++{c:=coord{x:x,y:y}canvas[c]=0minDist:=math.MaxInt32varminPcoordfor_,p:=rangeP{dist:=calculateDistance(c,p)canvas[c]+=distifdist==minDist{minP=coord{x:math.MinInt32,y:math.MinInt32}}elseifdist<minDist{minP=pminDist=dist}}ifminP.x!=math.MinInt32&&minP.y!=math.MinInt32{ifcountP[minP]!=math.MinInt32{countP[minP]=countP[minP]+1}ify==outerTop||y==outerBottom||x==outerLeft||x==outerRight{countP[minP]=math.MinInt32}}}}// Part 1:fmt.Println("Part 1:")maxi:=math.MinInt32varmaxiPcoordfork,v:=rangecountP{ifv>maxi{maxi=vmaxiP=k}}fmt.Printf("Point with largest area: %v\n",maxiP)fmt.Printf("The area is: %v\n",maxi)// Part 2:fmt.Println("\nPart 2:")varregion[]coordforp,d:=rangecanvas{ifd<10000{region=append(region,p)}}fmt.Printf("Size of region: %v\n",len(region))}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is the Golang code. Even though it uses the exact same algorithm, it runs surprisingly faster!