You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.6 KiB
Go

10 years ago
package main
import (
"database/sql"
"fmt"
"math"
"math/rand"
)
10 years ago
var (
index map[int]System
)
type System struct {
10 years ago
x, y, z float64
planets int
name string
}
10 years ago
func (e System) Store(db *sql.DB) {
10 years ago
_, err := db.Exec(`
insert into planets
(name, x, y, z, planets)
values
(?, ?, ?, ?, ?)
;`, e.name, e.x, e.y, e.z, e.planets)
if err != nil {
log_error("%v", err)
}
}
10 years ago
func (e System) String() string {
10 years ago
return fmt.Sprintf("<name: %s x: %v y: %v z: %v planets: %v>", e.name, e.x, e.y, e.z, e.planets)
}
func countPlanets() (int, error) {
row := db.QueryRow(`select count(*) from planets`)
var n int
err := row.Scan(&n)
return n, err
}
func sq(x float64) float64 {
return x * x
}
func dist3d(x1, y1, z1, x2, y2, z2 float64) float64 {
return math.Sqrt(sq(x1-x2) + sq(y1-y2) + sq(z1-z2))
}
10 years ago
func planetDistance(p1, p2 System) float64 {
10 years ago
return dist3d(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z)
}
10 years ago
func indexPlanets(db *sql.DB) map[int]System {
10 years ago
rows, err := db.Query(`select * from planets`)
if err != nil {
log_error("unable to select all planets: %v", err)
return nil
}
defer rows.Close()
10 years ago
index = make(map[int]System, 551)
10 years ago
for rows.Next() {
var id int
10 years ago
p := System{}
10 years ago
if err := rows.Scan(&id, &p.name, &p.x, &p.y, &p.z, &p.planets); err != nil {
log_info("unable to scan planet row: %v", err)
continue
}
10 years ago
index[id] = p
10 years ago
}
10 years ago
return index
10 years ago
}
10 years ago
func randomPlanet() (*System, error) {
n := len(index)
10 years ago
if n == 0 {
return nil, fmt.Errorf("no planets are known to exist")
}
pick := rand.Intn(n)
10 years ago
planet := index[pick]
10 years ago
return &planet, nil
}