Project Euler > Problem 102 > Triangle containment (Java Solution)

Problem:

Three distinct points are plotted at random on a Cartesian plane, for which -1000 [≤] x, y [≤] 1000, such that a triangle is formed.

Consider the following two triangles:

A(-340,495), B(-153,-910), C(835,-947)

X(-175,41), Y(-421,-714), Z(574,-645)

It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.

Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin.

NOTE: The first two examples in the file represent the triangles in the example given above.


Solution:

4613732

Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
* Solution to Project Euler problem 2
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/


public final class p002 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p002().run());
}


public String run() {
int sum = 0;
for (int i = 0; ; i++) {
int fib = fibonacci(i);
if (fib > 4000000)
break;
if (fib % 2 == 0)
sum += fib;
}
return Integer.toString(sum);
}


private static int fibonacci(int x) {
if (x < 0 || x > 46)
throw new IllegalArgumentException();
int a = 0;
int b = 1;
for (int i = 0; i < x; i++) {
int c = a + b;
a = b;
b = c;
}
return a;
}

}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact