Distance formula - java

I need help with a lab. My teacher did not tell us anything and he told us to figure it out. So i can use any help I can get. Thank You
Step 1: Is everything good with step one including my distance formula and I am trying to set xx equal to x and yy equal to y so I have not clue how to do that could could you help me with that.
class Point {
private int x;
private int y;
public Point() // (0, 0)
{
x = 0;
y = 0;
}
public Point(int xx, int yy)
{
xx = x;
yy = y;
}
public int getX() // return field values
{
return x;
}
public int getY()
{
return y;
}
// Use the distance formula to find the distance of this point from the origin (0,0)
public double distanceFromOrigin()
{
int d = 0;
d = Math.squrt(Math.pow(xx - x) + (Math.pow(yy - y);
}
Is my distance formula good if not what is wrong and can you help me fix it.
Step 2: I need to find the manhattan distance
// Find the "manhattan" distance between current point and other.
// You can look at http://x...content-available-to-author-only...t.gov/dads//HTML/manhattanDistance.html for help
public double distance(Point other)
{/*write the code for here*/}
I really have no clue how to do step 2 so i can really use a lot of help thank you guys so much
Step 3: After i find the manhattan distance between current point and other. I need to change it to its new values which i have no clue how to get the new value and how to change it. After that i need to shift the point by the translation T which i have no clue how to do that so i need help on that
// Changes the coordinate to new values
public void setLocation(int x, int y)
{/*write the code for here*/}
//Shift the point by the translation T<x+h,y+k>
public void translate(int h, int k)
{/*write the code for here*/}
by the way guys I am just on the basic computer science so I can't use all the fancy stuff so keep it basic and simple

Like torvin said in the comments, that really looks like Java and not Javascript. Those are two different languages, despite the similar names.
Generally looking at your code, there are obvious mistakes, which make me wonder what IDE (integrated development environment) you are using to write code. A proper program that helps you write code will spot those.
Just in your distanceFromOrigin() you are missing:
2 closing bracets
Math.squrt() should be Math.sqrt()
You are not returning a value, despite having set the methods return type to double
You should probably first set up an IDE and do a basic Java tutorial before continuing, honestly.

Related

Can i make a class that behave like a primitive type?

I made a Point class to manage xy coordinate (I know some java default packages already have some Point object that behave in a similar way, I use it as a lazy alternative and this is an example, please dont mind it ^^).
Before using it I was using the int primitive type.
thing is, when passing a class or a primitive type as parameter of a method, both don't act the same way, if I change the value of a primitive variable in a method, the original variable is unaffected, unlike if I was using an object since its the reference that is passed as parameter.
my problem is that since I use Point for math (example below), I have to manually create new object to save the result and I never use it to have a "link" between two variables as I could with how object behave usually.
My Point class:
public class Point {
public int x;
public int y;
public Point(int nx, int ny) {
this.x = nx;
this.y = ny;
}
public Point() {
this(0, 0);
}
}
An example of method:
public Point getAdjacent(int x, int y, Direction dir) {
Point pt = new Point(x, y);//basically, i would like to do that automatically
switch (dir) {
case Up:
pt.y -= 1;
break;
case Down:
pt.y += 1;
break;
case Right:
pt.x -= 1;
break;
case Left:
pt.x += 1;
break;
default:
//do nothing
}
return pt;
}
To summarize, is it possible to make Point behave like a primitive type?
EDIT: i mean that it would automatically copy it when passing it as parameter or doing point1=point2
The question might be a bit too broad, because one could argue quite extensively about what the word "behave" should mean. But to some extent, we can sort this out:
The shortest answer might be: No, this is not possible.
A slightly more elaborate answer might be: No, it is not yet possible to let a class (or more precisely: an object) behave like a primitive value.
The long answer:
There are efforts to achieve a behavior that might come close to what you're trying to accomplish. The relevant keyword here is Value Types.
Some resources:
The original value types proposal by John Rose, Brian Goetz, and Guy Steele: http://cr.openjdk.java.net/~jrose/values/values-0.html
The relevant JEP for Value Objects: http://openjdk.java.net/jeps/169
The Wiki describing the goals and current state of value types: https://wiki.openjdk.java.net/display/valhalla/L-World+Value+Types
The relevant mailing list: https://mail.openjdk.java.net/pipermail/valhalla-dev/
However, this is not supported in current versions of Java and the JVM, and it might still take a while until the details are sorted out.
Until then, there are some conceivable workarounds to achieve the desired goal.
The simplest solution is the one that you already proposed: You always return a new instance instead of modifying a given object.
The example that you showed in the question might not be the best to illustrate this, because the method getAdjacent that you showed could in fact be a static method. It does not use the instance that it is called on in any way.
Then you could always be sure that you received a new instance for each modification. Otherwise, imagine this code snippet:
Point a = new Point(1,2);
Point b = new Point(3,4);
a.add(b);
System.out.println(a); // What does this print?
Depending on the implementation of the add method, the behavior might not be clear. If it was implemented like this:
public void add(Point other) {
this.x += other.x;
this.y += other.y;
}
then the point a would be modified, and the output would be (4,6).
But if it was implemented like this
public Point add(Point other) {
return new Point(this.x+other.x, this.y+other.y);
}
then a would remain unaffected, and the output would still be (1,2).
In general, making something like a Point immutable basically enforces this style of programming. So you could make the variables x and y in your class final, so that you could always be sure that the object cannot be modified after it was created:
public class Point {
// Note that these are FINAL:
private final int x;
private final int y;
public Point(int nx, int ny) {
this.x = nx;
this.y = ny;
}
...
}
There are some further design considerations for such a seemingly trivial thing like a Point class (some of which I mentioned in this answer), but discussing them is beyond the scope of this answer.
First of all: be sure to use break statements in your switch code. Otherwise when case Up is matched, the switch block will "fall through" and will execute:
pt.y -= 1;
pt.y += 1;
pt.x -= 1;
pt.x += 1;
(Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)
According to the question, you can indeed use the Point class. Below code will:
1. Use a Point as input.
2. Extract the variables x and y from the input Point into a copy primitive.
3. Change the copied primitives.
4. Create a new Point, based on the copies.
In this way the "old" Point will be left untouched.
public Point getAdjacent(final Point point, final Direction dir) {
int x = point.x;
int y = point.y;
switch (dir) {
case Up:
y -= 1;
break;
case Down:
y += 1;
break;
case Right:
x -= 1;
break;
case Left:
x += 1;
break;
default:
break;
}
return new Point(x, y);
}

how to take onlythe x and y from Point class

I have a variable private Point _centralStation which located in class that I called her City.
the user in the main class decides which value will be to the location of the centralStation.
So he put for example:
Point center = new Point(5,5) .
I want to create a method who called MoveCentralStation(int x, int y)
that moves the location from his last value to the new one, but
the new points have to be in the first quarter of the x,y axis.
I mean x cannot be -4 for example.
let's say for the exmaple it was 5,5
and now the user entered -4,5
how can I deal with the x and y new values sepertely?
Thank you
You have to explain yourself a little better. However, this is what I understood.
You have such a class:
class City{
private Point _centralStation;
public City(){
this._centralStation = new Point(5,5);
//the initialization you specified
}
public void moveCentralStation(int new_x, int new_y){
//TODO exactly what you have to implement
}
public Point getCentralStation(){
//since you are not implementing just getters and setters you rather do
return new Point(_centralStation.x,_centralStation.y);
//instead of return _centralStation [this is what we call defensive copies]
}
}
Well, somewhere in the code, a client would call
City c = new City();
c.moveCentralStation(x,y); //given x,y are variables in the client's context
And these are the requirements for the moveCentralStation(int x, int y) operation:
x coordinate shall be positive
y coordinate shall be positive
First of all I suggest you to follow style conventions on the way you code: use capital letters only for the class names. Let's jump into the real problem.
We need to refine the above requirements to make a specific implementation compliant with them. They aren't clear enough. An example of refinining i may suggest is the following:
If x coordinate is less than zero, an IllegalArgumentException shall be thrown
If y coordinate is less than zero, an IllegalArgumentException shall be thrown
And that's very simple to implement:
public void moveCentralStation(int new_x, int new_y){
if(new_x < 0) throw new IllegalArgumentException("x must be positive");
if(new_y < 0) throw new IllegalArgumentException("y must be positive");
_centralStation.x = new_x;
_centralStation.y = new_y;
}
It's a good practice to set private fields only when they are all consistants.

Getting two random variables and then comparing them. (java acm)

i failed and now i need to take a resit exam. This question was on the final exam and i feel like similar one will come on resit exam. We cant use our computers on the exam we have to write everything on paper so that was big issue i couldnt understand if im doing it wrong or right. Please be kind while answering because im new at java and i dont want to lose my hope i need to pass.
(i cant remember %100 but this was the main idea)
Q: In this question write two methods. First method should take two random variables. And second method should compare those two random variables and gives the result as higher one.
My solution:
import acm.program.*;
import acm.util.RandomGenerator;
public class RandomGenereratorBaby extends ConsoleProgram {
public RandomGenerator rgen = RandomGenerator.getInstance();{
int x = rgen.nextInt(0,9);
int y = rgen.nextInt(0,9);
}
public char BiggerOneWins (int x, int y){
if(x>=y){
return (char) (x) ;
}else{
return (char) (y);
}
}}
Please help me.
So my interpretation of the question says the method should be taking in the variables and storing them, not making some random numbers. So my solution would look something like this
public class RandomGenereratorBaby extends ConsoleProgram {
private int x;
private int y;
public void takeInNumbers(int x, int y){
this.x = x;
this.y = y;
}
public int biggerOneWins(){
if(x>=y){
return x;
}else{
return y;
}
}
}
I've also changed the return type to int as returning as char seemed a little odd.
This is my interpretation of the question and the answer I would give. I hope that helps

Distance calculating algorithm for an app

I'm trying to calculate the distance for a third grader's geometry game app I'm developing. The basic idea is that the user inputs the directions using directions and how long he wants to go in each direction.( eg input: Right (radians) , travel a metres, left (radians), travel b metres).
So, now my app will find out if the user can get back to the starting point and how far he is away from home.
So far, I have been able to proceed with this logic here. I would like to know if there are other ways to do this? thanks!
You can do it using third grade geometry fittingly.
When you use the commands you listed, you are creating a vector. If you store dir, x, and y you can use simple sin and cosin to figure out your ending location.
dir+=rad
x+=cosin(dir)
y+=sin(dir)
If you have saved your start location, you can use Pythagorean Theorem to figure out the displacement from home!
public double distance (int x, int y){
int xdist = x-startx;
int ydist = y-starty;
int squarex = xdist*xdist
int squarey = ydist*ydist
return Math.sqrt((double)(squarex+squarey));
}

Object Creation and putting them into a 2D array

i am having difficulty with 2D arrays and inserting objects that take 3 parameters (int x, int y, int cost)
This is the beginning of a search algorithm and admittedly im off to a very poor start. I will paste the code below. I am receiving a compiling error when i try to run this code and i'm very sure it is simple but i cannot resolve it.
The Map2 class i intend to use to implement the main bulk of the algorithms, such as sorting etc.
import java.util.Arrays;
public class Map2 {
public static void main (String args[]){
Points[][] grid = new Points[4][4];
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid.length; j++){
grid[i][j] = new Points(i,j,1);
}
}
System.out.print(Arrays.deepToString(grid));
}
}
This class is my object, it contains the movement cost from moving from one position to the next (the next step obviously would be to determine neighbors) and yes, this is part of trying to create a working A star algorithm.
public class Points {
int x;
int y;
int movement_cost;
public Points(int iX, int iY, int cost){
x = iX;
y = iY;
movement_cost = cost;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getMovementCost(){
return movement_cost;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void setMovementCost(int cost){
this.movement_cost = cost;
}
public String toString(){
return ""+getX()+ ""+getY()+""+getMovementCost();
}
}
This is the console read out after compiling (3 address spaces in memory)
run:[[001, 011, 021, 031], [101, 111, 121, 131],
[201, 211, 221, 231], [301, 311, 321, 331]]
BUILD SUCCESSFUL (total time: 2 seconds)
My hope here is simple, each object in the array will contain a reference of its coordinates in memory and contain a cost of movement, which would later be used to compare in order to determine the next best position (i will later implement things such as goal, start)
my question is: whats wrong with the code the way it is ?
I want to thank, in advance whomever responds as your responce will always be appreciated
CURRENT REVISION OF MY QUESTION V0.1:
Wow well thanks for the quick responces, i have learned something new today ^^ that Arrays.deepToString(grid)); is an amasing tool i was not aware of, however i am still receiving a runtime error . Thank you once again for your replies and once again for any further responces :). The code above has been revised as recommended, but the runtime error still exists
There are several things that are wrong with your code:
Your nested loops assume that the array is square (you iterate both dimensions to grid.length),
You print the entire array after initializing each row, and
You print the array incorrectly (Java array do not print their content when passed to System.out.println)
The first item is OK if your matrix is indeed always square. The second item is easy to fix by moving the output outside of the second nested loop.
The third item is the hardest. It would be a good exercise to write a static method that takes your 2D array, and prints it out element-by-element with two nested loops. You can also use System.out.println(Arrays.deepToString(grid)); if you would rather use a system function.

Categories