I am currently working on an algorithm related to cryptography. More specifically, adding points on an elliptic curve. There is an option where I have to handle a situation like adding a point for example P(x,y) = (1,4) and some symbol for the neutral point e.g. Q=(e, e). The result of such "addition" should be Point (1,4). It (e) cannot be a zero value, because then the point will be Q(qx,qy)=(0,0) and another function will be activated, therefore the result will also differ. Can you assign a symbol to BigInteger?
I need something like
if(qx == e){
BigInteger r1 = x1;
BigInteger r2 = x2;
}
Here is full function:
static void addPoints(BigInteger x1, BigInteger y1, BigInteger x2, BigInteger y2, BigInteger a, BigInteger b, BigInteger p) throws Exception {
BigInteger lambda = null;
BigInteger x3 = null;
BigInteger y3 = null;
if (x1.compareTo(x2) == 0 && y1.compareTo(y2) == 0) { //same points
lambda = (((new BigInteger("3").multiply(x1.pow(2))).add(a))
.multiply(Modul1.getReverseNumber(
(new BigInteger("2").multiply(y1)), p)))
.mod(p);
x3 = ((lambda.pow(2)).subtract(new BigInteger("2").multiply(x1))).mod(p);
y3 = ((lambda.multiply(x1.subtract(x3))).subtract(y1)).mod(p);
} else if (x1.compareTo(x2) != 0) { //points are diffrent
lambda = ((y2.subtract(y1)).multiply(
Modul1.getReverseNumber(x2.subtract(x1), p)
)).mod(p);
x3 = (((lambda.pow(2)).subtract(x1)).subtract(x2)).mod(p);
y3 = ((lambda.multiply(x1.subtract(x3))).subtract(y1)).mod(p);
} else if (x1.compareTo(x2) == 0 && y1.compareTo(p.subtract(y2)) == 0) { //y2 is negate
System.out.println(O);
} else { //Point add Neutral Point
System.out.println("Punkt P + neutral : (" + x1 + "," + y1 + ")");
}
}
I solved it a little around. I used String as function parameters for one point. If it is an infinity symbol the result is the first Point, otherwise the null BigInteger is given the value of this String.
static void addPoints(BigInteger x1, BigInteger y1, String e1, String e2, BigInteger a, BigInteger b, BigInteger p) throws Exception {
BigInteger lambda = null;
BigInteger x3 = null;
BigInteger y3 = null;
if (e1.equals("e") || e2.equals("e")) {
System.out.println("Punkt P + O to: (" + x1 + "," + y1 + ")");
} else {
BigInteger x2 = new BigInteger(e1);
BigInteger y2 = new BigInteger(e2);
String O = "symbol O";
if (x1.compareTo(x2) == 0 && y1.compareTo(y2) == 0) {
lambda = (((new BigInteger("3").multiply(x1.pow(2))).add(a))
.multiply(Modul1.getReverseNumber(
(new BigInteger("2").multiply(y1)), p)))
.mod(p);
x3 = ((lambda.pow(2)).subtract(new BigInteger("2").multiply(x1))).mod(p);
y3 = ((lambda.multiply(x1.subtract(x3))).subtract(y1)).mod(p);
System.out.println("lamda to: " + lambda);
System.out.println("x3: " + x3);
System.out.println("y3: " + y3);
System.out.println("Punkt P+P = (" + x3 + "," + y3 + ")");
} else if (x1.compareTo(x2) != 0) {
lambda = ((y2.subtract(y1)).multiply(
Modul1.getReverseNumber(x2.subtract(x1), p)
)).mod(p);
x3 = (((lambda.pow(2)).subtract(x1)).subtract(x2)).mod(p);
y3 = ((lambda.multiply(x1.subtract(x3))).subtract(y1)).mod(p);
System.out.println("Punkt P+Q = (" + x3 + "," + y3 + ")");
} else if (x1.compareTo(x2) == 0 && y1.compareTo(p.subtract(y2)) == 0) {
System.out.println("Infinity,Infinity");
}
}
}
Related
The user inputs 3 space separated coordinates that can make up a rectangle in the xy-plane. The algorithm returns what must be the 4th point to form a rectangle.
Example: "5 5", "5 7", and "7 5", newline separated, should return "7 7".
The below algorithm works for the provided test cases, but I am failing other cases, and I can't figure out why. Can anyone suggest a way to make my algorithm include all possible inputs - assuming that the 3 inputs provided do in fact form 3 corners of a rectangle?
import java.io.*;
public class cetvrta {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String point1 = reader.readLine(); // 5 5
String point2 = reader.readLine(); // 5 7
String point3 = reader.readLine(); // 7 5
String[] cord1 = point1.split(" "); // ["5","5"]
String[] cord2 = point2.split(" "); // ["5", "7"]
String[] cord3 = point3.split(" "); // ["7", "5"]
int x4 = 0;
int y4 = 0;
int x1 = Integer.parseInt(cord1[0]); // 5
int y1 = Integer.parseInt(cord1[1]); // 5
int x2 = Integer.parseInt(cord2[0]);
int y2 = Integer.parseInt(cord2[1]);
int x3 = Integer.parseInt(cord3[0]);
int y3 = Integer.parseInt(cord3[1]);
if (y1 == y2) {
if (x3 == x1) {
x4 = x2;
y4 = y3;
}
if (x3 == x2) {
x4 = x1;
y4 = y3;
}
}
if (y3 == y2) {
if (x2 == x3) {
x4 = x1;
y4 = y2;
}
if (x2 == x1) {
x4 = x3;
y4 = y2;
}
}
if (y1 == y3) {
if (x2 == x1) {
x4 = x3;
y4 = y2;
}
if (x2 == x3) {
x4 = x1;
y4 = y2;
}
}
System.out.println(x4 + " " + y4);
}
}
There is no hard and fast rule that "x-coordinates of 2 points of a rectangle has to match and so do the y-coordinates". Consider the image below for better understanding.
We can see that no two points have same x and y coordinates although there exists a perfect rectangle:
Fix:
I would recommend you to slightly change the algorithm as to proceed in the following way. Given the three points, find the point that isn't the corner(the one that does not pass through diagonal based out of other 2 points). From this point, calculate the slope to remaining points and assuming the 4th corner to be (x,y); draw out 2 locii. to satisfy slope1 * slope 2=-1. These 2 locii solved together will give the 4th point.
This is weird, rethink that:
if (y3 == y2) {
if (x2 == x3) { // <---
x4 = x1; // <---
y4 = y2; // <---
}
if (x2 == x1) {
x4 = x3;
y4 = y2; // <---
}
}
It would be better to use basic vector algebra to resolve this task:
calculate vectors between the three known points
define which point of the given three is a vertex of right angle (90°) - if any
this can be done using the fact that the scalar product of two perpendicular vectors is 0: v1.x * v2.x + v1.y * v2.0 == 0
find the fourth point by adding to the right angle vertex two vectors outgoing from this vertex to the other two known points.
Sample implementation could look like this:
// auxiliary classes
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
Point add(Vector v) {
return new Point(this.x + v.x, this.y + v.y);
}
#Override
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
class Vector {
int x, y;
Vector(int x, int y) {
this.x = x;
this.y = y;
}
Vector(Point p1, Point p2) {
this(p2.x - p1.x, p2.y - p1.y);
}
static boolean isRightAngle(Vector v1, Vector v2) {
return 0 == (v1.x * v2.x + v1.y * v2.y);
}
Vector add(Vector v) {
return new Vector(this.x + v.x, this.y + v.y);
}
}
Method to find the right angle vertex:
static int rightAngleVertexIndex(Point ... p) {
assert p.length == 3;
Vector v01 = new Vector(p[0], p[1]);
Vector v12 = new Vector(p[1], p[2]);
Vector v20 = new Vector(p[2], p[0]);
if (Vector.isRightAngle(v01, v12)) {
return 1;
} else if (Vector.isRightAngle(v12, v20)) {
return 2;
} else if (Vector.isRightAngle(v20, v01)) {
return 0;
} else {
return -1;
}
}
Method to find the 4th point of rectangle (return null if no rectangle is possible):
static Point findFourthVertex(Point ... points) {
assert points.length == 3;
final int[][] otherVertices = {
{1, 2},
{0, 2},
{0, 1},
};
Point result = null;
int rightAngleIx = rightAngleVertexIndex(points);
if (rightAngleIx != -1) {
Point rightAngle = points[rightAngleIx];
Point p1 = points[otherVertices[rightAngleIx][0]];
Point p2 = points[otherVertices[rightAngleIx][1]];
result = rightAngle.add(new Vector(rightAngle, p1).add(new Vector(rightAngle, p2)));
System.out.println("The fourth vertex of the rectangle: " + result);
} else {
System.out.println("No right angle found between any of the points " + Arrays.toString(points));
}
return result;
}
Test:
findFourthVertex(new Point(1, 1), new Point(5, 1), new Point(1, 4));
findFourthVertex(new Point(-1, -1), new Point(5, 0), new Point(6, 5));
Output:
The fourth vertex of the rectangle: (5, 4)
No right angle found between any of the points [(-1, -1), (5, 0), (6, 5)]
I want to translate a java code. I did in only one class but I want to implement OOP using two classes
The original code is working in only one class
However, when I created two classes equationMain and equationData, I get an error in the metod getter
public double calculateSlope() when I try to return the value of m(slope)
"Change method type to String"
I don't understand because I want to retuns a double value?
I will appreciate any help with this code
Original code in only one class:
package equation;
import javax.swing.JOptionPane;
public class Equation {
public static void main(String[] args) {
// TODO Auto-generated method stub
//variables for coordenates, slope, etc.
double x1, x2, y1, y2, m, b;
String firstcoordinate = JOptionPane.showInputDialog("Introduce coordinate 1 x1,y1 split by ,: ");
String[] values = firstcoordinate.split(",");
x1 = Double.parseDouble(values[0]);
y1 = Double.parseDouble(values[1]);
String secondcoordinate = JOptionPane.showInputDialog("Introduce coordinate 2 x2,y2 split by ,: ");
values = secondcoordinate.split(",");
x2 = Double.parseDouble(values[0]);
y2 = Double.parseDouble(values[1]);
if ((x1 == x2) || ((x2 - x1) == 0))
{
System.out.println("There is not equation!!");
}
else
{
m = (y2 - y1) / (x2 - x1);
//y1-mx1=b
b = (y1 - (m * x1));
System.out.println("Coordinates entered: ");
System.out.println(" *-Coordinate 1: (" + x1 + ", " + y1 + ")");
System.out.println(" *-Coordinate 2: (" + x2 + ", " + y2 + ")");
System.out.println("The slope m is = " + m );
System.out.println("The equation is y = " + m + "x + " + b);
}
}
}
However, my new project is:
//main class equationMain
package equationPOO;
import javax.swing.JOptionPane;
public class equationMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
//variables for coordenates, slope, etc.
double x1, x2, y1, y2, m, b;
String firstcoordinate = JOptionPane.showInputDialog("Introduce coordinate 1 x1,y1 split by ,: ");
String[] values = firstcoordinate.split(",");
x1 = Double.parseDouble(values[0]);
y1 = Double.parseDouble(values[1]);
String secondcoordinate = JOptionPane.showInputDialog("Introduce coordinate 2 x2,y2 split by ,: ");
values = secondcoordinate.split(",");
x2 = Double.parseDouble(values[0]);
y2 = Double.parseDouble(values[1]);
equationData eq = new equationData(x1,x2,y1,y2);
if((x1 == x2) || ((x2 - x1) == 0))
{
eq.message();
}
else
{
eq.calculateSlope();
}
}
}
Mys econd class where I want to follow the procedure is
package equationPOO;
public class equationData {
//constructor
public equationData(double x1, double x2, double y1, double y2)
{
this.x1= x1;
this.x2= x2;
this.y1= y1;
this.y2= y2;
}
//getter for calculating slope m
public double calculateSlope()
{
double m,b;
m = (y2 - y1) / (x2 - x1);
//y1-mx1=b
b = (y1 - (m * x1));
System.out.println("Coordinates entered: ");
System.out.println(" *-Coordinate 1: (" + x1 + ", " + y1 + ")");
System.out.println(" *-Coordinate 2: (" + x2 + ", " + y2 + ")");
System.out.println("The slope m is = " + m );
System.out.println("The equation is y = " + m + "x + " + b);
return "The slope m is = " + m;
}
//getter send a message is ((x1 == x2) || ((x2 - x1) == 0))
public String message()
{
return "There is not equation!!";
}
private double x1,x2,y1,y2;
}
Good day! I made a program that would find an equation of a locus of point and I want to have my output to show a "+" sign if it is a positive number. Yet, it shows a "-" sign when its negative because I reciprocate their values. Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int x1 , y1, x2, y2,
inverted_x1, inverted_y1, inverted_x2, inverted_y2,
x1Times2, x2Times2, y1Times2, y2Times2,
x1raised, y1raised, x2raised, y2raised,
computeX, computeY, computeS,
x2inverted, y2inverted, invertedx2times2, invertedy2times2;
try{
x1 = Integer.parseInt(jTextField1.getText());
y1 = Integer.parseInt(jTextField2.getText());
x2 = Integer.parseInt(jTextField3.getText());
y2 = Integer.parseInt(jTextField4.getText());
int[] array = new int[4];
array[0] = x1;
array[1] = x2;
array[2] = y1;
array[3] = y2;
inverted_x1 = x1 *= -1;
inverted_y1 = y1 *= -1;
inverted_x2 = x2 *= -1;
inverted_y2 = y2 *= -1;
jTextField5.setText("(x" + Integer.toString(inverted_x1) + ")² + (y" + Integer.toString(inverted_y1) + ")²"
+ " = (x" + Integer.toString(inverted_x2) + ")² + (y" + Integer.toString(inverted_y2) + ")²" );
x1Times2 = inverted_x1*2;
y1Times2 = inverted_y1*2;
x2Times2 = inverted_x2*2;
y2Times2 = inverted_y2*2;
x1raised = inverted_x1*inverted_x1;
y1raised = inverted_y1*inverted_y1;
x2raised = inverted_x2*inverted_x2;
y2raised = inverted_y2*inverted_y2;
jTextField9.setText("x" + Integer.toString(x1Times2) + "x" + Integer.toString(x1raised) + "+y²" + Integer.toString(y1Times2)
+ "y" + Integer.toString(y1raised) + "= x²" + Integer.toString(x2Times2) + "x" + Integer.toString(x2raised) + "+y²"
+ Integer.toString(y2Times2) + "y" + Integer.toString(y2raised));
x2inverted = x2raised *= -1;
y2inverted = y2raised *= -1;
invertedx2times2 = x2Times2 *= -1;
invertedy2times2 = y2Times2 *= -1;
computeX = x1Times2 + invertedx2times2;
computeY = y1Times2 + invertedy2times2;
computeS = x2inverted + y2inverted + x1raised + y1raised;
jTextField17.setText(Integer.toString(computeX) + "x" + Integer.toString(computeY) + "y" + Integer.toString(computeS) + "=0");
XYLineChart_AWT chart = new XYLineChart_AWT("Locus of Point Graph", "", array);
chart.pack( );
RefineryUtilities.centerFrameOnScreen( chart );
chart.setVisible( true );
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please fill necessary inputs");
}
}
Here is a sample output:
Click Me. Can I have my output to show "+" sign if its positive?
Thank you in advance!
You can check the number with a conditional expression and then print it as String with the sign:
private static String formatSign(int number) {
return (number > 0 ? "+" : "" ) + number;
}
Since you didn't clarify how to handle the 0, I assumed you wanted to leave it unsigned.
Output example:
-5
0
+5
I'm having some trouble with the my cartesian slope calculations in Java.
So my sourcecode lets you input 4 numbers, x1 y1 x2 y2, which represent 2 coordinates of 2 points in an cartesian coordinate system.
then i calculate the slope by calculating deltaX and deltaY.
so i use a double for the slope end calculation (deltaY / deltaX) in case you get a tenth of a number.
then i use an IF function to say: if slope = 0 --> println("not a linear line"). else calculate the cross point of the X and Y polars and println the result
So here is the problem: what if the slope is 0 (example x1:0 y1:1 x2:0 y2:9) then the i get an error: Exception in thread main java.lang.ArithmeticException: / by zero
here is the full script:
import java.io.*;
public class Cartesian
{
public static int leesIn(String var, BufferedReader in) throws IOException
{
System.out.println("type een getal in die " + var + " moet voorstellen.");
return Integer.parseInt(in.readLine());
}
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int x1, x2, y1, y2;
x1 = leesIn("X1", in);
y1 = leesIn("Y1", in);
x2 = leesIn("X2", in);
y2 = leesIn("Y2", in);
System.out.println("The Coördinates of point 1 is: (" + x1 + ", " + y1 + "). The Coördinates of point 2 is: (" + x2 + ", " + y2 + ").");
int deltaY = y2 - y1;
int deltaX = x2 - x1;
double RC = deltaY / deltaX;
if ((RC) == 0)
{
System.out.println("The slope is 0, no linear line.");
}else
{
System.out.println("The slope is: " + RC);
double B = y1-(RC*x1);
System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
}
}
anyone an idea how to fix my problem? tnx in advance!
You should move calculation into area where you are sure that it can be calculated (in your case double RC = deltaY / deltaX;
So your code will be:
int deltaY = y2 - y1;
int deltaX = x2 - x1;
if (deltaY == 0)
{
System.out.println("The slope is 0, no linear line.");
}else if (deltaX == 0)
{
System.out.println("Not a Linear Line");
}else
{
double RC = (double) deltaY / deltaX;
System.out.println("The slope is: " + RC);
double B = y1-(RC*x1);
System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
Make a try catch block
double RC;
try{
RC = deltaY / deltaX;
}
catch(ArithmeticException ex){
System.out.println("Not a Linear Line");
}
try this
try {
double RC = deltaY / deltaX;
if ((RC) == 0)
{
System.out.println("The slope is 0, no linear line.");
}else
{
System.out.println("The slope is: " + RC);
double B = y1-(RC*x1);
System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
} catch(ArithmeticException ae) {
System.out.println("Not a linear line");
}
I have defined a shape using an array of vertices:
float[] points = new float[]{50,60,50,70,60,70, 60,60,50,60};
And I am drawing this here:
shapeRenderer.polygon(floatNew);
This just gives an outline of the shape.
How do I fill it with colour?
Thanks
Currently, ShapeRenderer supports polygon drawing (by line) but not filling.
This code is clipping the polygon on triangles, and then drawing each triangle separately.
Edit ShapeRenderer.java like this:
EarClippingTriangulator ear = new EarClippingTriangulator();
public void polygon(float[] vertices, int offset, int count)
{
if (shapeType != ShapeType.Filled && shapeType != ShapeType.Line)
throw new GdxRuntimeException("Must call begin(ShapeType.Filled) or begin(ShapeType.Line)");
if (count < 6)
throw new IllegalArgumentException("Polygons must contain at least 3 points.");
if (count % 2 != 0)
throw new IllegalArgumentException("Polygons must have an even number of vertices.");
check(shapeType, null, count);
final float firstX = vertices[0];
final float firstY = vertices[1];
if (shapeType == ShapeType.Line)
{
for (int i = offset, n = offset + count; i < n; i += 2)
{
final float x1 = vertices[i];
final float y1 = vertices[i + 1];
final float x2;
final float y2;
if (i + 2 >= count)
{
x2 = firstX;
y2 = firstY;
} else
{
x2 = vertices[i + 2];
y2 = vertices[i + 3];
}
renderer.color(color);
renderer.vertex(x1, y1, 0);
renderer.color(color);
renderer.vertex(x2, y2, 0);
}
} else
{
ShortArray arrRes = ear.computeTriangles(vertices);
for (int i = 0; i < arrRes.size - 2; i = i + 3)
{
float x1 = vertices[arrRes.get(i) * 2];
float y1 = vertices[(arrRes.get(i) * 2) + 1];
float x2 = vertices[(arrRes.get(i + 1)) * 2];
float y2 = vertices[(arrRes.get(i + 1) * 2) + 1];
float x3 = vertices[arrRes.get(i + 2) * 2];
float y3 = vertices[(arrRes.get(i + 2) * 2) + 1];
this.triangle(x1, y1, x2, y2, x3, y3);
}
}
}
You cant draw a filled Polygon with the shaperender yet. take a look at this from the bugtracker
You can also read that in the API.
public void polygon(float[] vertices)
Draws a polygon in the x/y plane. The vertices must contain at least 3
points (6 floats x,y). The ShapeRenderer.ShapeType passed to begin has
to be ShapeRenderer.ShapeType.Line.
API ShapeRender
Sure if its with ShapeType.Line you just get the outlines.
You need to draw it yourself with Triangles in that case. It should be possible to fill at least Triangles.
Maybe take a look at this from Stackoverflow: drawing-filled-polygon-with-libgdx
Edit your ShapeRenderer.java class replacing polygon() method with the following code:
public void polygon(float[] vertices, int offset, int count) {
if (currType != ShapeType.Filled && currType != ShapeType.Line)
throw new GdxRuntimeException(
"Must call begin(ShapeType.Filled) or begin(ShapeType.Line)");
if (count < 6)
throw new IllegalArgumentException(
"Polygons must contain at least 3 points.");
if (count % 2 != 0)
throw new IllegalArgumentException(
"Polygons must have an even number of vertices.");
checkDirty();
checkFlush(count);
final float firstX = vertices[0];
final float firstY = vertices[1];
if (currType == ShapeType.Line) {
for (int i = offset, n = offset + count; i < n; i += 2) {
final float x1 = vertices[i];
final float y1 = vertices[i + 1];
final float x2;
final float y2;
if (i + 2 >= count) {
x2 = firstX;
y2 = firstY;
} else {
x2 = vertices[i + 2];
y2 = vertices[i + 3];
}
renderer.color(color);
renderer.vertex(x1, y1, 0);
renderer.color(color);
renderer.vertex(x2, y2, 0);
}
} else {
for (int i = offset, n = offset + count; i < n; i += 4) {
final float x1 = vertices[i];
final float y1 = vertices[i + 1];
if (i + 2 >= count) {
break;
}
final float x2 = vertices[i + 2];
final float y2 = vertices[i + 3];
final float x3;
final float y3;
if (i + 4 >= count) {
x3 = firstX;
y3 = firstY;
} else {
x3 = vertices[i + 4];
y3 = vertices[i + 5];
}
renderer.color(color);
renderer.vertex(x1, y1, 0);
renderer.color(color);
renderer.vertex(x2, y2, 0);
renderer.color(color);
renderer.vertex(x3, y3, 0);
}
}
}
Usage:
gdx_shape_renderer.begin(ShapeType.Filled);
gdx_shape_renderer.setColor(fill_r, fill_g, fill_b, fill_a);
gdx_shape_renderer.polygon(vertices);
gdx_shape_renderer.end();
gdx_shape_renderer.begin(ShapeType.Line);
gdx_shape_renderer.setColor(border_r, border_g, border_b, border_a);
gdx_shape_renderer.polygon(vertices);
gdx_shape_renderer.end();