Skip to content

Instantly share code, notes, and snippets.

@hellvesper
Created December 23, 2015 11:30
Show Gist options
  • Save hellvesper/39ba4903dc3117f3b747 to your computer and use it in GitHub Desktop.
Save hellvesper/39ba4903dc3117f3b747 to your computer and use it in GitHub Desktop.
<?php
$x = [];
$y = [];
// triangle #1 left
$x1[1] = -1;
$y1[1] = -1;
$x1[2] = -1;
$y1[2] = 0;
$x1[3] = 0;
$y1[3] = 0;
// triangle #2 right
$x2[1] = 0;
$y2[1] = 0;
$x2[2] = 1;
$y2[2] = 0;
$x2[3] = 1;
$y2[3] = -1;
// square
// left top angle
$X[1] = -1;
$Y[1] = 1; // placed on X axis
// right bottom angle
$X[2] = 1;
$Y[2] = 0;
$dot = [
'x' => rand(-10, 10)/10,
'y' => rand(-10, 10)/10
];
if ($dot['y'] < 0) {
// under square, doing with triangles
$ans = inTrinagle($x1[1], $y1[1], $x1[2], $y1[2], $x1[3], $y1[3], $dot['x'], $dot['y']);
if (($ans['a'] >= 0 && $ans['b'] >= 0 && $ans['c'] >= 0) || ($ans['a'] <= 0 && $ans['b'] <= 0 && $ans['c'] <= 0)) {
printScrTriang($ans['a'], $ans['b'], $ans['c'], $dot['x'], $dot['y'], 'Found in triangle #1 !!!111один!1упчяка');
die;
} else {
// nope, doing with second triangle
$ans = inTrinagle($x2[1], $y2[1], $x2[2], $y2[2], $x2[3], $y2[3], $dot['x'], $dot['y']);
if (($ans['a'] >= 0 && $ans['b'] >= 0 && $ans['c'] >= 0) || ($ans['a'] <= 0 && $ans['b'] <= 0 && $ans['c'] <= 0)) {
printScrTriang($ans['a'], $ans['b'], $ans['c'], $dot['x'], $dot['y'], 'Found in triangle #2 !!!111один!1упчяка');
die;
} else {
echo "Dot( x = " . $dot['x'] . ", y = " . $dot['y'] . " )" . "<br>" . "Out of figure!";
die;
}
}
# maybe in square? doing with square
} elseif (($X[1] <= $dot['x'] && $X[2] >= $dot['x']) && ($Y[1] <= $dot['y'] && $Y[1] >= $dot['y'])) {
# so dot in square
echo "Dot( x = " . $dot['x'] . ", y = " . $dot['y'] . " )" . "<br>" . "In square!!1!";
die;
} else echo "Dot( x = " . $dot['x'] . ", y = " . $dot['y'] . " )" . "<br>" . "Out of figure!";
die;
function inTrinagle($x1 = null, $y1 = null, $x2 = null, $y2 = null, $x3 = null, $y3 = null, $dotX = null, $dotY = null )
{
if ($x1 !== null && $x2 !== null && $x3 !== null && $y1 !== null && $y2 !== null && $y3 !== null && $dotX !== null && $dotY !== null) {
$a = ($x1 - $dotX) * ($y2 - $y1) - ($x2 - $x1) * ($y1 - $dotY);
$b = ($x2 - $dotX) * ($y3 - $y2) - ($x3 - $x2) * ($y2 - $dotY);
$c = ($x3 - $dotX) * ($y1 - $y3) - ($x1 - $x3) * ($y3 - $dotY);
} else {
return null;
}
return ['a' => $a, 'b' => $b, 'c' => $c];
}
function printScrTriang($a = null, $b = null, $c = null, $dotX = null, $dotY = null, $message = '')
{
echo "Dot( x = " . $dotX . ", y = " . $dotY . " )" . "<br>";
echo "a = " . $a . "<br>";
echo "b = " . $b . "<br>";
echo "c = " . $c . "<br>";
echo $message;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment