Skip to content

Instantly share code, notes, and snippets.

Created November 13, 2015 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/38dd166583d9c1acdf0c to your computer and use it in GitHub Desktop.
Save anonymous/38dd166583d9c1acdf0c to your computer and use it in GitHub Desktop.
Prints a list of the 40 moon pairs that are closest to each other.
<?php
$db = new PDO('sqlite:sqlite-latest.sqlite');
function sortDistances(MoonDistance $a, MoonDistance $b) {
return $a->getDistance() - $b->getDistance();
};
$moons = $db->query('SELECT a.solarSystemID, a.x + b.x as x, a.y + b.y as y, a.z + b.z as z, a.itemName from mapDenormalize a left join mapSolarSystems b on (a.solarSystemID = b.solarSystemID) where a.typeID = 14');
$moonsBySolarSystem = [];
foreach ($moons as $moon) {
$solarSystemID = $moon['solarSystemID'];
if (!isset($moonsBySolarSystem[$solarSystemID])) {
$moonsBySolarSystem[$solarSystemID] = [];
}
$moonsBySolarSystem[$solarSystemID][] = new Moon($moon);
}
$closestDistances = [];
foreach ($moonsBySolarSystem as $solarSystemID => $moons) {
$moonCount = count($moons);
if ($moonCount > 1) {
$distances = [];
for ($i = 0; $i < $moonCount; $i++) {
$moonA = $moons[$i];
for ($j = $i + 1; $j < $moonCount; $j++) {
$distances[] = new MoonDistance($moonA, $moons[$j]);
}
}
usort($distances, 'sortDistances');
$closestDistances[] = $distances[0];
}
}
usort($closestDistances, 'sortDistances');
echo "CLOSEST MOON DISTANCES:\n";
echo join("\n", array_slice($closestDistances, 0, 40));
class MoonDistance
{
private $moonA;
private $moonB;
private $distance;
public function __construct(Moon $moonA, Moon $moonB)
{
$this->moonA = $moonA;
$this->moonB = $moonB;
$this->distance = sqrt(
pow($moonB->getX() - $moonA->getX(), 2) +
pow($moonB->getY() - $moonA->getY(), 2) +
pow($moonB->getZ() - $moonA->getZ(), 2)
);
}
public function __toString()
{
return sprintf('%s, %s: %s km', $this->moonA, $this->moonB, number_format(floor($this->distance / 1000)));
}
public function getDistance()
{
return $this->distance;
}
}
class Moon
{
private $name;
private $x;
private $y;
private $z;
public function __construct($moonData)
{
$this->name = $moonData['itemName'];
$this->x = $moonData['x'];
$this->y = $moonData['y'];
$this->z = $moonData['z'];
}
public function __toString()
{
return $this->name;
}
public function getX()
{
return $this->x;
}
public function getY()
{
return $this->y;
}
public function getZ()
{
return $this->z;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment