Nested List structure management - java

I am stuck trying to manager a list of list of lists. I have declared and initialized my data structure as so:
List<Vector<ArrayDeque<Vector_t>>> mData = new ArrayList<Vector<ArrayDeque<Vector_t>>>(
6);
for (int i = 0; i < 6; ++i) {
mData.add(i, new Vector<ArrayDeque<Vector_t>>());
// mData.get(i).setSize(200);
}
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 200; k++) {
mData.get(i).add(new ArrayDeque<Vector_t>());
mData.get(i).get(k).add(new Vector_t());
}
}
where Vector_t is:
class Vector_t {
float x;
float y;
float z;
}
Is this initialization correct? When adding values to the array deque at the last position, it replaces the whole arraydeque with the last element, and I have no idea why.
Also, when I changing values using the code mdata.get(1).get(42) the element at mdata.get(0).get(40) is also affected. Again, I have no idea why?
I have given hardcoded values for example..this is the way i m adding
if (mData.get(dir.value).get(slice).size() >= sMaxNum_c)
{
mData.get(dir.value).get(slice).removeFirst();
}
mData.get(dir.value).get(slice).addLast(result.acc);
when adding values to one direction other direction values are changing...:(
Please help me to solve this.

My suggestion would be to either introduce some classes as Amir suggested, or at least make your code easier to understand by introducing some well-named, temporary local variables.
I don't know what you're trying to acheive, but re-writing with the use of some local variables might allow you to spot an issue:
List<Vector<ArrayDeque<Vector_t>>> mData = new ArrayList<Vector<ArrayDeque<Vector_t>>>(
6);
for (int i = 0; i < 6; ++i) {
mData.add(i, new Vector<ArrayDeque<Vector_t>>());
}
for (Vector nextVector : mData) {
for (int k = 0; k < 200; k++) {
ArrayDeque<Vector_t> tempArray = new ArrayDeque<Vector_t>());
tempArray.add(new Vector_t());
nextVector add(tempArray);
}
}

I am not sure of what you are trying to achieve, but for starters, you should consider using another Data Structure besides Vector as it is obsolete.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
// Consider using another DataStructure such as Arraylist, as Vector<> is obsolete.
import java.util.Vector;
public class main {
public static void main(String[] args) {
// Use diamond inference.
List<Vector<ArrayDeque<Vector_t>>> mData = new ArrayList<>(6);
for (int i = 0; i < 6; i++) {
Vector<ArrayDeque<Vector_t>> vav = new Vector<>();
ArrayDeque<Vector_t> av = new ArrayDeque<>();
for (int k = 0; k < 200; k++) {
av.add(new Vector_t(2.0f, 2.0f, 2.0f));
}
vav.add(av);
}
}
}
Use variables instead of calling get() so much.
public class Vector_t {
private float x;
private float y;
private float z;
public Vector_t() {
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
public Vector_t(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public float GetX() {
return x;
}
public float GetY() {
return y;
}
public float GetZ() {
return z;
}
public void SetX(float x) {
this.x = x;
}
public void SetY(float y) {
this.y = y;
}
public void SetZ(float z) {
this.z = z;
}
}
use setters and getters for your class, it's all about using OOP programming concepts :)
If you are a little more specific on what you are trying to accomplish, I am sure we could help.
-Francisco

Related

Anyone know what I am doing wrong to execute this java code?

I am just trying to execute some Java code and print them out to the console, however, when I try to run it, it gives an error and says illegal start to expression. Does anyone know what is going on here?
package com.craneai;
public class Main {
public static void main(String[] args) {
public static void int F(int N) {
int X, Y, Z, I;
int X = 2;
if(N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int I = 3; I <=N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
}
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X, Y, Z, I;
X = 2;
if(N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int i = 3; i <=N; i++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
A few things to consider:
1st. You're declaring a void return and then a int, the function must have only 1 return type.
public static void int F(int N)
2nd. The method should be outside the main method
3rd. You declared X twice in the code, the second time you call it, you don't have to declare the type, the compiler will try to process it as a new variable with a name that is already in use.
4th. In your for method, you declared X, once again, Java is case sensitive, so X and x are different in the compiler.
5th. You've also declared I twice, you don't need to provide a temporary variable before calling the for method, since you can do it inside the for loop;
Looks like you're starting to learn Java, a few tips from who works with it since the Java 5..
Don't declare your variables with a single letter;
Don't declare your functions/methods with a single letter;
Don't declare your variables in UPPER CASE, always low case and camelCase;
Even as an example you should make your code cleaner, improve the readability for others, other people will be happier in the future if you do this (this include yourself).
First: you're declaring a method inside another method - see that the F method is inside the main method. Java does not support nested methods.
Second: you're declaring X and I twice.
Third: You wrote two return types to your method: void and int.
This will work:
public class Main {
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X, Y, Z, I;
X = 2;
if (N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (I = 3; I <= N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
}
Three main errors:
Nested method: F method inside main
Method F return int and void
You declared X and I twice.
Here is your class fixed:
public class Main {
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X = 2, Y, Z;
if (N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int I = 3; I <= N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
}
Output is going to be this:
8
3
2

issues in indexing a class in Java

I have happened to have a problem in defining an array where the index should be elements of a class as follows:
MWE:
package thisModel;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ThisCode {
public static void main(String[] args) {
class Arc {
private int i; //starting node
private int j; // ending node
public Arc(int i, int j) {
this.i = i;
this.j = j;
}
#Override
public String toString() {
return Integer.toString(i) + " " + Integer.toString(j);
}
}
List<Arc> arcs = new ArrayList<Arc>();
int N = 7;
int [] b = new int [N];
}
}
so, here, if I define the array as follows:
int [] y = new int [arcs.size()];
Then, errors are popping up in the following loop:
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
//my issue lies here:
//y[Arc(i,j)] - y[Arc(j,i)] = b[i];
}
}
and I think it is because y[arcs.size()] has a dimension of the size of the list, but not its elements.
My question is if there is any way to define the y like as an array of Arc not arcs.size() like this:
int[] y = new int [Arc(i,j)];
If you type y as a two-dimensional array
int[][] y = new int[N][N];
then you can use the Arc's components i and j as index of y to retrieve values:
int value = y[i][j];
You can also type it as a Map (if I read your first sentence literally):
Map<Arc, Integer> y = new HashMap<>();
This allows you to get values from y by asking for them with a particular Arc instance:
Arc myArc = ...;
int value = y.get(myArc);
In this case you should define proper hashCode and equals methods in your Arc class:
#Override
public boolean equals(Object x) {
if (!(x instanceof Arc)) return false;
Arc that = (Arc) x;
return this.i == that.i && this.j == that.j;
}
#Override
public int hashCode() {
return this.i + 31*this.j;
}
otherwise the HashMap will not find any values if you try to get them by passing new Arc instances with same components to it.

Java: Invoking a Class-type Array to Test for Equality

I'm working on a program that first takes an even array of doubles and sequentially creates a second array of (x, y) coordinates. Then, an invoking PointArray has to be compared to the argument PointArray by comparing the x-coordinates and y-coordinates of each point in the array. I know conceptually that I'll have to sort each array and compare each point using the indeces and the defined equals method, but I don't know how to refer to a point of the invoking class-type array when it is not given as a parameter.
private double x;
private double y;
public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
public boolean equals(Point anotherPoint)
{
if(x == anotherPoint.x && y == anotherPoint.y)
{
return true;
}
return false;
}
int count;
private Point[] points = new Point[count];
public PointArray(double[] doubleArray)
{
count = (doubleArray.length) / 2;
if(doubleArray.length % 2 == 0)
{
count = (doubleArray.length) / 2;
for(int i = 0, j = 0; i < count; i++, j += 2)
{
double x = doubleArray[j];
double y = doubleArray[j + 1];
points[i] = new Point(x, y);
}
}
else
{
System.out.println("Error: The given array must be even.");
}
}
public boolean equals(PointArray anotherPointArray)
{
double x = 0;
double y = 0;
double xAnother = 0;
double yAnother = 0;
Point newPoint = new Point(x, y);
Point newAnotherPoint = new Point(xAnother, yAnother);
anotherPointArray.sort();
anotherPointArray.newPoint;
for(int i = 0; i < points.length; i++)
{
for(int j = 0; i < anotherPointArray.length; j++)
{
if(newPoint.equals(newAnotherPoint))
{
return true;
}
}
}
return false;
}
EDIT: To clarify, my problem is that I don't know how to set up the Point equals method using the PointArray objects.
When you call a method on an object like:
something.myMethod(argObject);
inside the myMethod you can then refer to something (the object the method is called on) as the this-object.
I hope this tuto demonstrates it better than words do.

Fruchterman and Reingold algorithm vertices occupy same place in output (graph layout)

I was attempting to implement Fruchterman and Reingold algorithm in Java, but for some reasons, the coordinate of output vertices sometimes occupy the same coordinates, which is not something this algorithm would want. Where did I go wrong?
Coordinate object (vector)
public class Coordinates {
private float x;
private float y;
public Coordinates(float xx, float yy){
x = xx; y = yy;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public String toString(){
return x+" "+y;
}
public Coordinates subtract(Coordinates c){
return new Coordinates(x-c.x, y - c.y);
}
public Coordinates add(Coordinates c){
return new Coordinates(x + c.x, y + c.y);
}
public Coordinates unit(){
if(length() == 0)
return new Coordinates(0.000001f,0.0000001f);
else
return new Coordinates(x/(float)Math.sqrt(x*x + y*y),y/(float)Math.sqrt(y*y + x*x));
}
public float length(){
return (float)Math.sqrt(x*x + y*y);
}
public float distance(Coordinates c){
return (float) Math.sqrt((x-c.x)*(x-c.x) + (y-c.y)*(y-c.y));
}
public Coordinates scale(float k){
return new Coordinates(k*x,k*y);
}
}
Node object
import java.util.LinkedList;
public class Node {
private LinkedList<Node> incidentList; //has 30 elements for 30 vertices. 1 if incident, 0 if not
private int color;
private Coordinates coord;
private Coordinates disp;
public Coordinates getDisp() {
return disp;
}
public void setDisp(float x, float y) {
disp.setX(x);
disp.setY(y);
}
public void setDisp(Coordinates d) {
disp = d;
}
private int id;
public Node(){
incidentList = new LinkedList<Node>();
color = 0;
coord = new Coordinates(0,0);
disp = new Coordinates(0,0);
id = -1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public LinkedList<Node> getIncidentList() {
return incidentList;
}
public void addEdge(Node n) {
incidentList.add(n);
}
public void removeEdge(Node n){
incidentList.remove(n);
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public Coordinates getCoord() {
return coord;
}
public void setCoord(float x, float y) {
coord.setX(x);
coord.setY(y);
}
public int getDegree(){
return incidentList.size();
}
public boolean isAdjacent(Node n){
return incidentList.contains(n);
}
}
Graph object (with layout algorithm function frlayout)
import java.util.ArrayList;
import java.util.Random;
public class MyGraph{
private final int DISRESPECT = -1;
private final int MORECOLOR = -3;
private final float EPSILON = 0.003f;
private ArrayList<Node> graphNodes; //maximum of 30 vertices
private int nVertices = 0;
private int score = 50;
int maxColor = 0;
int[] colorPopulation = new int[15];
double boundx, boundy, C;
public double getBoundx() {
return boundx;
}
public void setBoundx(double boundx) {
this.boundx = boundx;
}
public double getBoundy() {
return boundy;
}
public void setBoundy(double boundy) {
this.boundy = boundy;
}
public double getC() {
return C;
}
public void setC(double c) {
C = c;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getnVertices() {
return nVertices;
}
public MyGraph(){
graphNodes = new ArrayList<Node>();
}
public ArrayList<Node> getGraphNodes() {
return graphNodes;
}
//add a new node into the graph
//also set the id of that node
public void addNode(Node n){
graphNodes.add(n);
n.setId(nVertices++);
}
public void addEdge(Node n1, Node n2){
n1.addEdge(n2);
n2.addEdge(n1);
}
//randomly generate a graph with parsity
public void randomGenerating(double parse){ //parse is between 0 and 1
Random gen = new Random(System.currentTimeMillis());
int tempNVertices = 6; //CHANGE HERE TO BECOME A RANDOM NUMBER
for(int i = 0; i< tempNVertices; i++){
Node n = new Node();
float x = 0,y = 0;
while(true){
boolean flag = true;
x = gen.nextFloat();
y = gen.nextFloat();
for(int j = 0; j < i; j++){
if(x*boundx == graphNodes.get(j).getCoord().getX() && y*boundx == graphNodes.get(j).getCoord().getY())
flag = false; break;
}
if (flag)
break;
}
n.setCoord((float)(x*boundx),(float)(y*boundy));
addNode(n);
}
for(int i = 0; i < tempNVertices; i++){
for(int j = i + 1; j < tempNVertices; j++){
if(gen.nextDouble() < parse){
addEdge(graphNodes.get(i),graphNodes.get(j));
}
}
}
}
public void frLayout(){
double w = boundx, h = boundy;
double area = w*h;
double k = C*Math.sqrt(area/nVertices);
double temperature = 1000;
for(int i = 0; i < nVertices; i++)
System.out.println(graphNodes.get(i).getCoord().getX()+" "+graphNodes.get(i).getCoord().getY());
System.out.println("------------------------------");
for(int m = 0; m< 900; m++){
for(int i = 0; i < nVertices; i++){
Node v = graphNodes.get(i);
v.setDisp(0,0);
for(int j = 0; j< nVertices; j++){
Node u = graphNodes.get(j);
if(i!= j){
Coordinates delta = v.getCoord().subtract(u.getCoord());
double myFr = fr(u,v,k);
v.setDisp(v.getDisp().add(delta.unit().scale((float)myFr)));
if(Double.isNaN(v.getDisp().getX())){
System.out.println("PANIC: "+u.getCoord().getX()+" "+u.getCoord().getY()+" "+delta.getX()+" "+v.getCoord().getX());
return;
}
}
}
}
for(int i = 0; i < nVertices; i++){
Node v = graphNodes.get(i);
for(int j = i+1; j< nVertices; j++){
Node u = graphNodes.get(j);
if(v.isAdjacent(u)){
Coordinates delta = v.getCoord().subtract(u.getCoord());
double myFa = fa(u,v,k);
v.setDisp(v.getDisp().subtract(delta.unit().scale((float)myFa)));
u.setDisp(u.getDisp().add(delta.unit().scale((float)myFa)));
}
}
}
for(int i = 0; i< nVertices; i++){
//actually adjusting the nodes
Node v = graphNodes.get(i);
if(i == 0){
System.out.println(v.getCoord().getX()+" "+v.getCoord().getY());
Coordinates disp = v.getDisp().unit().scale((float)Math.min(v.getDisp().length(), temperature));
System.out.println(">>"+disp.getX()+" "+disp.getY());
}
Coordinates newCoord = (v.getCoord().add(v.getDisp().unit().scale((float)Math.min(v.getDisp().length(), temperature))));
v.setCoord(newCoord.getX(), newCoord.getY());
// //prevent from going outside of bound
// float x = (float)Math.min(w, Math.max(0,v.getCoord().getX()));
// float y = (float)Math.min(h, Math.max(0, v.getCoord().getY()));
//
// v.setCoord(x,y);
if(i == 0){
System.out.println(v.getCoord().getX()+" "+v.getCoord().getY());
}
}
temperature *= 0.9;
System.out.println("TEMPERATURE = "+temperature);
}
for(int i = 0; i< nVertices; i++){
Node v = graphNodes.get(i);
System.out.println(v.getCoord().getX()+" "+v.getCoord().getY());;
}
}
private double fa(Node ni, Node nj, double k){
double distance = ni.getCoord().distance(nj.getCoord());
return distance*distance/k;
}
private double fr(Node ni, Node nj, double k){
double distance = ni.getCoord().distance(nj.getCoord());
return k*k/(distance+0.000001);
}
public static void main(String[] args){
MyGraph grph = new MyGraph();
grph.setBoundx(480);
grph.setBoundy(480);
grph.setC(1);
grph.randomGenerating(1);
grph.frLayout();
}
}
Apologies for the overly long question. I tried tutorials on net, but couldn't get anywhere closer to figuring out what's going wrong. Note that when finding unit vector, if a vector is zero (0,0), I make it a very small, non-zero vector so that when two vertices are close to one another, they will repel violently just as the author of the algorithm hoped.
Any instructions would be appreciated.
I found my bug. I was taking square root of the distance twice while computing the attraction and repulsion forces as well as a few other smaller bugs. I posted the corrected code in my question. Hopefully anyone out there attempting this algorithm will find it useful. Note that by removing the boundary, we let the graph free to evolve, it could produce better shape. Once obtaining the resulting graph, we could always translate/scale it so that it fit into whatever dimension required.

Finding elements in treemap

I want to find out whether a number passed through a method is part of a randomly generated object (created from a tree map). I've been looking online to find an attribute to the class that can help me find it but have come up short, I've tried HashCodes, Equals(), and this the like... At the moment I have it set up like this and what I'm asking, I guess, is whether I'm using what I read right or wrong?
Here's the code:
public class a {
private final TreeMap<Integer,TreeMap<Integer,Double>> rectangle;
private final int height;
private final int width;
public a(int h, int w) {
this.rectangle = new TreeMap<>();
this.height = h;
this.width = w;
}
public double get(int i, int j) {
if ( i > j ) {
largest = i; // defined earlier
}
for(int a = 0; a < largest; a++) {
if (this.height.equals(a) == i && this.width.equals(a) == j){
int[] position = new int[1];
position[0] = i;
position[1] = j;``
}
else {
return 0.0;
}
}
}

Categories