Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>Online PHP Script Execution</title>
- </head>
- <body>
- <?php
- class Point {
- public $x;
- public $y;
- function __construct($x, $y) {
- $this->$x = $x;
- $this->$y = $y;
- }
- function distanceTo($point) {
- $x2 = ($this->$x - $point->$x) * ($this->$x - $point->$x);
- $y2 = ($this->$y - $point->$y) * ($this->$y - $point->$y);
- return $x2 + $y2;
- }
- }
- class Optimization {
- public $points;
- public $fixed;
- function __construct($array) {
- $points = $array;
- $fixed = array(
- new Point(-1, 1),
- new Point(0, 1),
- new Point(1, 1),
- new Point(-1, 0),
- new Point(0, 0),
- new Point(1, 0),
- new Point(-1, -1),
- new Point(0, -1),
- new Point(1, -1)
- );
- }
- function calcDistance() {
- $distance = 0;
- for ($i = 0; $i < 9; $i++) {
- $distance += $points[$i]->distanceTo($fixed[$i]);
- }
- return $distance;
- }
- function go() {
- $min = 10000;
- for ($i = 0; $i < 9; $i++) {
- $d = $this->calcDistance();
- if ($d < $min) {
- $min = $d;
- }
- $points = next_permutation($points);
- }
- }
- function swap($elements, $i, $j) {
- $temp = $elements[$i];
- $elements[$i] = $elements[$j];
- $elements[$j] = $temp;
- }
- function reverse($elements, $i, $j) {
- for ($x = 0; $x < (int)$j/2; $x++) {
- swap($elements, $i+$x, $j-$x);
- }
- }
- function next_permutation($elements) {
- $i = 7;
- while (i >= 0 && $elements[$i] < $elements[$i+1]) {
- $i--;
- }
- if ($i < 0) {
- reverse($elements, 0, 8);
- } else {
- $j = 8;
- while ($j > $i + 1 && $elements[$j] <= $elements[$i]) {
- $j--;
- }
- swap($elements, $i, $j);
- reverse($elements, $i + 1, 8);
- }
- return $elements;
- }
- }
- $points = array(
- new Point(-1, 1),
- new Point(0, 1),
- new Point(1, 1),
- new Point(-1, 0),
- new Point(0, 0),
- new Point(1, 0),
- new Point(-1, -1),
- new Point(0, -1),
- new Point(1, -1)
- );
- $o = new Optimization($points);
- $o->go();
- ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement