How to compare values within a list and method? - java

I have a LinkedList with different types of data which I need to handle in order to make a comparison and add the values that agree with the scope. More explanation will be given below,
LinkedList is filled with data of Record class:
class Record {
public int id;
public Point location;
public double score;
(...)
}
Point class:
class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double dist(Point p) {
return Math.sqrt((this.x-p.x)*(this.x-p.x)+(this.y-p.y)*(this.y-p.y));
}
RankList class:
class RankList {
private Node first;
private int nodeCount;
private Record record;
public static void main(String[] args) {
RankList list = new RankList();
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
System.out.println(list.insert(record));
double maxDist=point.dist(point);
Point point1 = new Point(1.4, 9.2);
Record record1 = new Record(2, point1, 7.5);
if((point1.dist(point)>maxDist)) maxDist=point1.dist(point);
System.out.println(list.insert(record1));
Point point2 = new Point(2.2, 1.2);
Record record2 = new Record(3, point2, 6.0);
if((point2.dist(point1)>maxDist)) maxDist=point2.dist(point1);
System.out.println(list.insert(record2));
list.nearest(point1,maxDist);
I 've inserted some values to the list and let's say that I have some distance values between the given points like:
Distance between two points:
A->B = 3.2455
B->C = 7.345
C->D = 2.111
D->E = 8.056
From that the maxDist value is 8.059
Now I have to write the method public RankList nearest (Point p,double maxDist) which finds all the distance values between the scope (<=maxDist) and return them in a list with the rest node values. So I need to calculate the distance with the pointers of the LinkedList and the given Point p argument, and add them to a new list.
My problem is if can I access the LinkedList which is already fulfilled with values and copy what I need to the new list structure.
Method nearest:
public RankList nearest (Point p,double maxDist){
RankList nearList = new RankList();
Node current = first;
System.out.print("HEAD -> ");
while (current != null) {
System.out.print(current);
System.out.print(" -> ");
current = current.getNext();
}
System.out.println("null");
return null;
}
I've tried to run the whole LinkedList with the traditional way but I stack on how to make the comparisons and add them to the new list.
Any suggestions?

I'm a little bit confused with your code. I cant find any LinkedList in it. Your class RankList seems to have only three fields and none of them is of the List type. I'm not sure what does the insert method does.
It is not the best idea to have fields in the class with the main method. It would be better if you prepare another class that runs the program.
I'd like to show how I'd write the code:
import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
// I don't want the list to be a field of the class.
RecordsList list = new RecordsList();
// Following code blocks could be extracted as separate methods
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
list.add(record);
double maxDist = point.dist(point);
Point point1 = new Point(1.4, 9.2);
Record record1 = new Record(2, point1, 7.5);
if((point1.dist(point)>maxDist)) maxDist=point1.dist(point);
list.add(record1);
Point point2 = new Point(2.2, 1.2);
Record record2 = new Record(3, point2, 6.0);
if((point2.dist(point1)>maxDist)) maxDist=point2.dist(point1);
list.add(record2);
Point farPoint = new Point(50, 50);
Record recordWithFarPoint = new Record(4, farPoint, 5);
list.add(recordWithFarPoint);
RecordsList nearestList = list.nearest(point1, 20);
for (Record rec : nearestList.getList()) {
System.out.println(rec.id + " " + rec.location.x + " " + rec.location.y + " " + rec.score);
}
/*
* On console:
* 2 1.4 9.2 7.5
* 1 5.4 3.2 8.2
* 3 2.2 1.2 6.0
*/
}
}
/**
* This class is so-called wrapper on ArrayList.
*/
class RecordsList {
// This may be called delegate.
private ArrayList<Record> list = new ArrayList<>();
public void add(Record record) {
this.list.add(record);
}
// This creates shallow copy.
public ArrayList<Record> getList() {
return new ArrayList<>(list);
}
public RecordsList nearest(Point p, double maxDistance) {
RecordsList list = new RecordsList();
List<Record> records = this.getList().stream()
.sorted(Comparator.comparingDouble(oldListElement -> oldListElement.location.dist(p)))
.filter(element -> element.location.dist(p) <= maxDistance)
.collect(Collectors.toList());
for (Record record : records) {
list.add(record);
}
return list;
}
}
class Record {
public int id;
public Point location;
public double score;
public Record(int id, Point location, double score) {
this.id = id;
this.location = location;
this.score = score;
}
}
class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double dist(Point p) {
return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y));
}
}
There are some concepts that may be new for you. The most complicated one is propably streamApi. You may read more about it i.e. here: https://www.baeldung.com/java-8-streams
If you have any questions, or I misunderstood your problem, feel free to ask.

Related

Handle different types of values in a List

I have a singly LinkedList called RankList. In that list I insert information such as ID,Map Point and Score of different shops.
My code for that implementation:
class RankList {
private Node first;
private int nodeCount;
private Record record;
public static void main(String[] args) {
//Inserting values for a node
//Data for the first node
RankList list = new RankList();
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
System.out.println(list.insert(record));
double maxDist=point.dist(point);
//Data for the second node
Point point1 = new Point(1.4, 9.2);
Record record1 = new Record(2, point1, 7.5);
if((point1.dist(point)>maxDist)) maxDist=point1.dist(point);
System.out.println(list.insert(record1));
//Data for the third node
Point point2 = new Point(2.2, 1.2);
Record record2 = new Record(3, point2, 6.0);
if((point2.dist(point1)>maxDist)) maxDist=point2.dist(point1);
System.out.println(list.insert(record2));
list.printList(); //Prints the list
}
The list that I get:
HEAD -> Rank[Identity Number: 1, Location at point: 5.4,3.2, Score: 8.2] -> Rank[Identity Number: 3, Location at point: 2.2,1.2, Score: 6.0] -> Rank[Identity Number: 2, Location at point: 1.4,9.2, Score: 7.5] -> null
Here comes the question. I need to implement a method called nearest with the following arguments.
public RankList nearest (Point p,double maxDist)
NOTE: Method nearest is in the class RankList scope.
In this method I need compare all the Points I have already inserted to the Ranklist with the Point p.
e.g Point p = ( 2.2 , 4.4) with all the Locations at point
It's hard to me to understand how to access only the Point object of a node in RankList in order to use it to the comparison.
I tried to implement this but it doesn't work at all because Point is out of scope.
public RankList nearest (Point p,double maxDist){
RankList nearList = new RankList();
Node current = first;
while (current != null) {
System.out.print(current);
if(point.dist(p)<maxDist){ //Finding the distance between the added points with p argument
nearList.insert(record); //Insert the distances shorter than maxDist in a new list.
}
current = current.getNext();
}
System.out.println("null");
return nearList;
}
Point class:
class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
//Distance between two points
public double dist(Point p) {
return Math.sqrt((this.x-p.x)*(this.x-p.x)+(this.y-p.y)*(this.y-p.y));
}
public Point copy() {
return new Point(this.x, this.y);
}
#Override
public String toString() {
return "point: "+x+","+y;
}
}

How to make use of the result of an A* algorithm for a 2D game?

I am doing my first attempt at introducing pathfinding in one of my games. So far I have implemented an A* algorithm which seems to correctly find a path around a wall that I set up to the location specified according to print statements. However, from the way I understand it, the method I use to generate the path returns a path from the goal to the character rather than the other way around. Therefore I need to reverse the path in order for my character to move to the specified location (if I understood things correctly). How do I do this in the best way possible?
Pathfinder code:
public class PathFinder
{
public static Map<Location, Location> createPath(Location start, Location goal)
{
//A "Location" is a simple vector object that accepts an X and Y value.
HashMap<Location, Location> locationParents = new HashMap<>();
HashMap<Location, Integer> movementCosts = new HashMap<>();
PriorityQueue frontier = new PriorityQueue();
frontier.push(start, 0);
locationParents.put(start, null);
movementCosts.put(start, 0);
//"While we have locations that we need to check in order to get a path"
while(!frontier.isEmpty())
{
Location current = frontier.pop();
//Break if we found the goal
if(current.equals(goal))
break;
//Neighbours around a location are locations in all 8 directions next to it that are passable
for(Location next : SquareGrid.getLocationNeighbours(current))
{
int newCost = movementCosts.get(current) + SquareGrid.getLocationCost(next);
if(!movementCosts.containsKey(next) || newCost < movementCosts.get(next))
{
movementCosts.put(next, newCost);
int priority = newCost + makeGuess(next, goal);
frontier.push(next, priority);
locationParents.put(next, current);
}
}
}
return locationParents;
}
private static int makeGuess(Location a, Location b)
{
return Math.abs(a.getX() - b.getX()) + Math.abs(a.getY() - b.getY());
}
private static class PriorityQueue
{
private LinkedList<LocationPair> elements = new LinkedList<>();
public boolean isEmpty()
{
return elements.isEmpty();
}
public void push(Location loc, int cost)
{
elements.push(new LocationPair(loc, cost));
}
public Location pop()
{
int bestIndex = 0;
for(int i = 0; i < elements.size(); i++)
{
if(elements.get(i).cost < elements.get(bestIndex).cost)
bestIndex = i;
}
return elements.remove(bestIndex).location;
}
private static class LocationPair
{
private final Location location;
private final int cost;
private LocationPair(Location location, int cost)
{
this.location = location;
this.cost = cost;
}
}
}
}
I want the movement code inside the character class to be something like this:
Location currentPos = new Location(x, y);
//Next position to move to
Location nextPosition = targets.get(currentPos);
xVel = Integer.compare(parentPos.getX(), currentPos.getX());
yVel = Integer.compare(parentPos.getY(), currentPos.getY());
x += xVel;
y += yVel;
Since this is my first time doing pathfinding for a game I might be approaching this incorrectly though I am not sure.

How to use ArrayList in Java?

I am new trying to learn programing and java, I am currently working in a program but I need help starting it, I would really appreciate it if anyone could help me.
I have to Implement a class IrregularPolygon that contains an array list of Point2D.Double objects.
The Point2D.Double class defines a point specified in double precision representing a location in (x, y) coordinate space. For example, Point2D.Double(2.5, 3.1) constructs and initializes a point at coordinates (2.5, 3.1).
I'm going to be Using this declarations as a starting point for my lab work.
import java.awt.geom.*; // for Point2D.Double
import java.util.ArrayList; // for ArrayList
public class IrregularPolygon {
private ArrayList <Point2D.Double> myPolygon;
// constructors
public IrregularPolygon() { }
// public methods
public void add(Point2D.Double aPoint) { }
public double perimeter() { }
public double area() { }
}
I would like some tips on how to Write methods that compute the perimeter and the area of a polygon. To compute the perimeter, and to compute the distance between adjacent points, and total up the distances. The area of a polygon with corners is the absolute value of:
I suggest Math.hypot(point1.getX() - point2.getX(), point1.getY() - point2.getY()) for the distance of to adjacent points. For the perimeter (just as you stated) sum up all distances (don't forget to add the distance from the last to the first point). For the area see How do I calculate the surface area of a 2d polygon?.
I hope you can find this example helpful:
import java.awt.geom.*;
import java.util.ArrayList;
public class IrregularPolygon {
private ArrayList<Point2D.Double> myPolygon;
// constructors
public IrregularPolygon() {
this.myPolygon = new ArrayList<Point2D.Double>();
}
// public methods
public void add(Point2D.Double aPoint) {
this.myPolygon.add(aPoint);
}
public double perimeter() {
// compute perimeter
return 0;
}
public double area() {
// compute area
return 0;
}
#Override
public String toString() {
String result = "IrregularPolygon [";
for (Point2D.Double point : myPolygon) {
result += "|X: " + point.x + ". Y: " + point.y + "|";
}
result += "]";
return result;
}
public static void main(String[] args) {
IrregularPolygon irregularPolygon = new IrregularPolygon();
Point2D.Double point1 = new Point2D.Double(0, 2);
Point2D.Double point2 = new Point2D.Double(2, 4);
Point2D.Double point3 = new Point2D.Double(3, 5);
irregularPolygon.add(point1);
irregularPolygon.add(point2);
irregularPolygon.add(point3);
System.out.println(irregularPolygon.toString());
}
}
You can find in the toString() method how to use the ArrayList in Java, as well as in the add() method, so the implementation of the methods perimeter() and area() just depends on the specs you have. You just need to extrapolate that methods to complete the class.
Hope it helps.
Clemencio Morales Lucas.
this is what i have so far:
import java.awt.geom.*;
import java.util.ArrayList;
public class IrregularPolygon {
private ArrayList <Point2D.Double> myPolygon;
public IrregularPolygon()
{
myPolygon = new ArrayList < Point2D.Double > ();
}
public void add(Point2D.Double aPoint)
{
myPolygon.add(aPoint);
}
public void print()
{
for (Object element : myPolygon)
{
System.out.println(element);
}
}
public double distance(Point2D pt)
{
double distance = 0;
x.distance(y);
return distance;
}
public double perimeter()
{
double distance = 0;
for(int x = 0; x < aPoint; x++){ // cords given in groups might have to / by 2
get.point();
if(myPolygon[] != null){
get.nextPoint();
}
else{
distance += thePoint.distance(nextPoint)
}
}
return distance;
}
public double area()
{
double area = 0;
return area;
}
}
//that's irregular polygon. this is polygon application
import javax.swing.*;
import java.awt.geom.Point2D;
public class PolygonApplication
{
public static void main() {
String userInput;
int pointNumber = 1;
Point2D.Double nextPoint;
IrregularPolygon myPolygon = new IrregularPolygon();
do {
userInput = JOptionPane.showInputDialog("Enter x coordinate for point " + pointNumber);
if (userInput != null) {
double x = Double.parseDouble(userInput);
userInput = JOptionPane.showInputDialog("Enter y coordinate for point " +
pointNumber);
if (userInput != null) {
double y = Double.parseDouble(userInput);
nextPoint = new Point2D.Double(x,y);
myPolygon.add(nextPoint);
pointNumber += 1;
}
}
}
while (userInput != null);
myPolygon.print();
}
}

Java: How to pass Point values to a Polyline?

So I have this Polyline class that uses another class (Point) to create a polyline.
The class Point just defines a point with a x and y value and a name to it (Point A, Point B, etc)
public class Polyline
{
private Point [] corner;
public Polyline ()
{
this.corner = new Point[0];
}
public Polyline (Point [] corner)
{
this.corner = new Point [cornerlength];
for (int i = 0; i < corner.length; i++)
this.corner[i] = new Point (corner[i]);
}
Now my question is, how do I give these corners their values? I made a programme called PolylineTest and I would like to give it some values and print it out, but I haven't managed to figure out how to do it.
I figured it would be something like this:
Polyline [] p1 = new Polyline[0];
but I can't figure out how to give it a value.
Could anyone give me a nudge to the right direction?
Thank you in advance
(the code currently does not compile)
Asuming your Point class looks something like:
public class Point {
public String name;
public int x;
public int y;
public Point(String name, int x, int y) {
this.name = name;
this.x = x;
this.y = y;
}
public Point(Point p) {
this.name = p.name;
this.x = p.x;
this.y = p.y;
}
public String toString() {
return name + "[" + x + ", " + y + "]";
}
}
and you add this method to your Polyline class:
public String toString() {
return "Polyline " + Arrays.toString(corner);
}
the usage looks like:
public class PolylineTest {
public static void main(String[] args) {
Point[] points = new Point[] {
new Point("A", 4, 2),
new Point("B", 8, 5),
new Point("C", 1, 7)
};
Polyline polyline = new Polyline(points);
System.out.println(polyline);
}
}

store X and Y coordinates

Hi im new to this site and need help with a program im working on. the problem im having is that i cant seem to store string and two integers (as the coordinates). i have looked at other code but dont see how the values are stored. below is the code ive been using. the code seems to be fine but when trying to stored the values i cant put multiply integers. thanks for your time
import java.util.HashMap;
public class map {
class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new coords(65, 72), "Dan");
}
}
There is a class in java called Class Point.
http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html
This is the same information provided on Java docs API 10:
https://docs.oracle.com/javase/10/docs/api/java/awt/Point.html
A point representing a location in (x,y) coordinate space, specified in integer precision.
You can see an example, and also other important topics related in this link: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/Pointclass.htm
import java.awt.Point;
class PointSetter {
public static void main(String[] arguments) {
Point location = new Point(4, 13);
System.out.println("Starting location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
System.out.println("\nMoving to (7, 6)");
location.x = 7;
location.y = 6;
System.out.println("\nEnding location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
}
}
I hope this can help you!
There seems to be several issues:
"Dan" is a String, not a Character
case is important in Java (new coords(65,72) should be new Coords(65,72))
Coords needs to be static to be instantiated without a reference to an instance the enclosing map class.
This should work:
static class Coords {
...
}
Map<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
ps: although you are allowed to name a local variable map within a class map, it is not a good idea to have such name collision. In Java, classes generally start in upper case, so you could rename your class Map. But it happens that Map is a standard class in Java. So call your class Main or Test or whatever is relevant. ;-)
Adding to #assylias
Make you inner class static in order to insert new objects like you have or new Outer().new Inner() .
Take care of Java Naming Convention
Code like:
public class XYTest {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
}
}
package Lecture3;
import java.util.Scanner;
public class lecture9 {
private int nInleste;
public lecture9() {/*
* tabell/ // T/*chapter 6 in the books.
**/
}
public static void main(String[] args) {
Scanner inn = new Scanner(System.in);
int nInleste = 3;
double[] tall = new double[nInleste];
double sum = 0;
for (int i = 0; i < nInleste; i++) {
System.out.println("Leste en tall!");
tall[i] = inn.nextDouble();
sum += tall[i];
}
System.out.println(sum);
double snitt = nInleste / nInleste;
System.out.println("Gjennomsnittsverdien:" + snitt);
for (int i = 0; i < nInleste; i++) {
double aavik = tall[i] - snitt;
int avvivk = 0;
System.out.println(i + 1 + " Tal sitt avvik fra gjennomsnittet " + avvivk);
}
}/* end of the main methods */
}
if you have problem with your code you can try this , simple code to store string and two int values into a map
class MyCoord{
private int X;
private int Y;
public MyCoord() {
this(0,0);
}
public MyCoord(int X, int Y) {
this.X = X;
this.Y = Y;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public void setX(int X) {
this.X = X;
}
public void setY(int Y) {
this.Y = Y;
}
}
//main class begins
public class PointDemo{
public static void main(String[] args) {
Map <String,MyCoord> multiplePoints=new HashMap<String, MyCoord>();
multiplePoints.put("point1", new MyCoord(10, 20));
multiplePoints.put("point2", new MyCoord(100, 2000));
MyCoord coord=multiplePoints.get("point1");
System.out.println(coord.getX() +" : "+coord.getY());
}
}

Categories