View Category
Find the distance between two points
go
import "fmt"
import "math"
type Point struct {
x, y float64
}
func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}
func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }
fmt.Println(point.distance(origin))
}
import "math"
type Point struct {
x, y float64
}
func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}
func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }
fmt.Println(point.distance(origin))
}
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
go
fmt.Printf("%08d", 42)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
go
fmt.Printf("%-6d", 1024)
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
go
fmt.Printf("%.2f", 7.0 / 8.0)
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
go
fmt.Printf("%10d", 73)
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
go
rand.Intn(100) + 100
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
go
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()
