Skip to content

Instantly share code, notes, and snippets.

@NicolaM94
Created January 3, 2024 21:10
Show Gist options
  • Save NicolaM94/0dda69b1f877e3797fc213d1a52c22be to your computer and use it in GitHub Desktop.
Save NicolaM94/0dda69b1f877e3797fc213d1a52c22be to your computer and use it in GitHub Desktop.
overlapping rectangles
package main
import (
"fmt"
)
type Rectangle struct {
startingX int
startingY int
width int
height int
}
func (r Rectangle) Points() (out [][]int) {
for w := r.startingX; w <= r.startingX+r.width; w++ {
couple := []int{}
for h := r.startingY; h >= r.startingY-r.height; h-- {
couple = append(couple, w)
couple = append(couple, h)
out = append(out, couple)
couple = []int{}
}
}
return
}
func CommonPoints(a, b Rectangle) (out [][]int) {
for _, p := range a.Points() {
for _, c := range b.Points() {
if p[0] == c[0] && p[1] == c[1] {
out = append(out, p)
}
}
}
return
}
func CalcAreaFromPoints(points [][]int) int {
if len(points) == 0 {
return 0
}
minX := points[0][0]
for p := range points[1:] {
if points[p][0] < minX {
minX = points[p][0]
}
}
maxX := points[0][0]
for p := range points[1:] {
if points[p][0] > maxX {
maxX = points[p][0]
}
}
minY := points[0][1]
for p := range points[1:] {
if points[p][1] < minY {
minY = points[p][1]
}
}
maxY := points[0][1]
for p := range points[1:] {
if points[p][1] > maxY {
maxY = points[p][1]
}
}
return (maxX - minX) * (maxY - minY)
}
func main() {
A := Rectangle{
startingX: 1,
startingY: 4,
width: 3,
height: 3,
}
B := Rectangle{
startingX: 0,
startingY: 5,
width: 4,
height: 3,
}
fmt.Println("Points of A: ", A.Points())
fmt.Println("Points of B: ", B.Points())
internal := CommonPoints(A, B)
fmt.Println("Common points: ", internal)
commonArea := CalcAreaFromPoints(internal)
fmt.Println("Common area size: ", commonArea)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment