Issue in understanding java method - java

maybe I've a serious gap in java fondamental comprehension. In the code below I can't understand how getLength method can calculate walk length. Why recall itself on tail?
class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public static void main(String argv[]) {
Point p1 = new Point(0, 0);
// Walk w1 = new Right(new Down(new Left(new Up(new Stop()))));
Move w2 = new Left(new Left(new Up(new Stop())));
// Walk w3=new Right(new Stop());
System.out.println(w2.tail);
}
}
abstract class Walk {
public abstract boolean isStop();
public abstract int getLength();
}
class Stop extends Walk {
#Override
public boolean isStop() {
return true;
}
#Override
public int getLength() {
return 0;
}
}
abstract class Move extends Walk {
Walk tail;
#Override
public int getLength() {
return 1 + tail.getLength();
}
Move(Walk tail) {
this.tail = tail;
}
#Override
public boolean isStop() {
return true;
}
}
class Right extends Move {
public Right(Walk tail) {
super(tail);
}
}
class Left extends Move {
public Left(Walk tail) {
super(tail);
}
}
class Up extends Move {
public Up(Walk tail) {
super(tail);
}
}
class Down extends Move {
public Down(Walk tail) {
super(tail);
}
}

You appear to be creating your own linked list, and the getLength() method iterates through the entire list, returning the full sum.
As an aside, please work on your code formatting for this site, especially your indentation.

It calculates the total length, from what I can tell.
return 1+tail.getLength();
This appears to say that the current object's walk length is 1, and it adds that to whatever tail walk length is. This gives the total length.
NOTE: Whoever wrote this, should look at the Java Naming Conventions.

Related

What is a good way to implement calculations for extended classes?

I have the following classes:
public class Node {
private int x;
private int y;
}
public abstract class Map {
protected Node[][] grid;
public abstract Set<Node> findNeighbours(Node node);
}
public class SquareMap extends Map {
private static final int VERTICAL_COST= 10;
private static final int HORIZONTAL_COST= 10;
private static final int DIAGONAL_COST = 14;
#Override
public Set<Node> findNeighbours(Node node) {
//return the 8 adjacent nodes
}
}
public class HexMap extends Map {
private static final int MOVE_COST = 10;
#Override
public Set<Node> findNeighbours(Node node) {
//return the 6 adjacent nodes
}
}
I would like to create a method like
public int calculateMoveCost(Node current, Node target, <whatever else is needed>) {}
Where I only pass in the nodes, and the logic in either the method, or the nodes, or the map recognizes what kind of map I'm using. My current solution looks like this:
private int calculateMoveCost(Node current, Node target, Map map) {
int cost;
if(isHexMap(map)) {
cost = map.getMoveCost();
} else {
if(isSquareMap(map)) {
if(verticalNeighbours(current, target)) {
cost = map.getVerticalMoveCost();
} else {
cost = map.getHorizontalMoveCost();
}
}
}
return cost;
}
When I look at this code, I think there has to be a better way to implement this. Could you recommend a nice object oriented way of implementing this? I can create any reference in any object, the goal is to have a nice solution. Thanks!
I do think there is a right answer for this, just have an abstract getMoveCost method on Map and implement it in each subclass. Then you can just call map.getMoveCost(from, to).
public abstract class Map {
protected Node[][] grid;
public abstract int getMoveCost(Node current, Node target);
public abstract Set<Node> findNeighbours(Node node);
}
public class SquareMap extends Map {
private static final int VERTICAL_COST= 10;
private static final int HORIZONTAL_COST= 10;
private static final int DIAGONAL_COST = 14;
#Override
public Set<Node> findNeighbours(Node node) {
//return the 8 adjacent nodes
}
#Override
public int getMoveCost(Node current, Node target) {
if(verticalNeighbours(current, target)) {
cost = getVerticalMoveCost();
} else {
cost = getHorizontalMoveCost();
}
}
}

How to create some methods(ex: insertAtIndex()) for custom linked list?

I am new to the concept of Linked list, and I am having a lot of trouble building this custom linked list for the first time.
I have two classes: CellPhone and CellList.
In CellPhone, I have 4 attributes: serialNum(long), brand(String), year(int), and price(double).
In CellList, I have:
an inner class called CellNode, which has two attributes: phone(CellPhone), and next(CellNode)
and two attributes head(CellNode) and size(int)
This is from my CellList class:
private CellNode head; // point first node in this list object
private int size; // current size of the list(how many nodes in the list)
public CellList() {
head = null;
size = 0;
}
public CellList(CellList c) { // is this a correct deep copying?
head = new CellNode(c.head);
size = c.getSize();
}
public int getSize() {
return size;
}
public void addToStart(CellPhone c) {
head = new CellNode(c, null); //head.getPhone() = c, head.getNextNode() = null.
size++;
}
I am not even sure if that addToStart method is correctly done, and now I need to add methods like insertAt(/deleteFrom)Index(CellPhone c, int index). I've done till here:
public void insertAtIndex(CellPhone c, int index) { //index is invalid when it's not 0<index<size-1
if(index<0 || index>size-1) {
throw new NoSuchElementException("index is invalid! System terminated.");
}
but I can't fully understand how this Node thing works, so I am stuck.
Here is the full code:
import java.util.NoSuchElementException;
public class CellList {
class CellNode {
private CellPhone phone;
private CellNode next;
public CellNode() {
phone = null;
next = null;
}
public CellNode(CellPhone c, CellNode n) {
phone = c;
next = n;
}
public CellNode(CellNode c) {
this(c.getPhone(), c.getNextNode());
}
public CellNode clone() {
CellNode c = new CellNode(phone, next);
return c;
}
public CellPhone getPhone() {
return phone;
}
public CellNode getNextNode() {
return next;
}
public void setPhone(CellPhone c) {
phone = c;
}
public void setNextNode(CellNode n) {
next = n;
}
}
private CellNode head; // point first node in this list object
private int size; // current size of the list(how many nodes in list)
public CellList() {
head = null;
size = 0;
}
public CellList(CellList c) {
head = new CellNode(c.head);
size = c.getSize();
}
public int getSize() {
return size;
}
public void addToStart(CellPhone c) {
head = new CellNode(c, null); //head.getPhone() = c, head.getNextNode() = null.
size++;
}
public void insertAtIndex(CellPhone c, int index) { //index is invalid when it's not 0<index<size-1
if(index<0 || index>size-1) {
throw new NoSuchElementException("index is invalid! System terminated.");
}
}
public void showContents() {
while(head.getNextNode() != null) {
System.out.println(head.getPhone()+"---->");
head = head.getNextNode();
}
}
}
If you want to insert a node at an index x you have to,
go to the node at index x-1, store the next value of node x-1 in a temp variable, put the node you want to insert in next property of x-1 node, and put the value in the temp variable in the next property of the node you want to insert.

Having a static nested class be a subtype of the enclosing class when trying to implement a Tree data type

I have been following along in the book Data Structures (Into Java) by Paul Hilfinger and I am having trouble implementing some part of a Tree structure.
When during the implementation, the book suggested that we have a nested static class represent an empty tree to make so methods using a Tree do not have to check for null pointers. The example code looks like this
public class Tree<T> {
public Tree(T label) ...
public Tree(T label, int k) ...
public T label() ...
public int degree() ...
public int numChildren() ...
public Tree<T> child(int k) ...
public void setChild(int k, Tree<T> C) ...
public boolean isEmpty() { return false }
public final Tree<T> EMPTY = new EmptyTree();
static class EmptyTree<T> extends Tree<T> {
private EmptyTree() {}
public boolean isEmpty() { return true }
public int degree() { return 0 }
public int numChildren() { return 0 }
public Tree<T> getChild(int i) {
throw new Exception;
}
public T label() {
throw new Exception;
}
}
}
Here is my implementation:
public class NonEmptyGTree<T> {
public NonEmptyGTree(T label, int arity) {
this.label = label;
children = (NonEmptyGTree<T>[]) new Object[arity];
for (int i = 0; i < arity; i++)
children[i] = EMPTY;
}
public NonEmptyGTree() {
}
public NonEmptyGTree<T> getChild(int i) {
return children[i];
}
public void setChild(int i, NonEmptyGTree<T> set) {
if (children[i].isEmpty()) deg += 1;
children[i] = set;
}
public T getLabel() {
return label;
}
public void setLabel(T label) {
this.label = label;
}
public int numChildren() {
return children.length;
}
public int degree() {
return deg;
}
public boolean isLeaf() {
return deg == 0;
}
public boolean isEmpty() {
return false;
}
public class EmptyGTree<T> extends NonEmptyGTree<T> {
private EmptyGTree() {}
public int degree() { return 0; }
public int numChildren() {
return 0;
}
public NonEmptyGTree<T> getChild(int i) {
throw new IllegalStateException();
}
public void setChild(int i, NonEmptyGTree<T> set) {
throw new IllegalStateException();
}
public T getLabel() {
throw new IllegalStateException();
}
public void setLabel(T label) {
throw new IllegalStateException();
}
public boolean isEmpty() {
return true;
}
}
private T label;
private NonEmptyGTree[] children;
private int deg = 0;
public final NonEmptyGTree<T> EMPTY = new EmptyGTree<T>();
}
This made sense to me since that way we won't have to check for null pointers when we use trees elsewhere, but when I try to initialize a tree, it goes into a loop with the Tree initializing EMPTY then EMPTY calling super() which then initializes Tree again looping.
I then tried to use a Null design pattern where I made a Tree interface and and then had two files implementing it, one for an empty tree and a nonempty tree. This seems messy to me because then for any subtype of a Tree, I would have to split it up into a nonempty tree and empty tree for every subtype. It seems like the idea of making an empty tree should stop with just this one implementation since functionally all empty trees are the same (if you do not need to access the parent nodes).
Is it not possible to make it so that I would only have to implement the EmptyTree once? Or is what I am asking to do not possible?

Trouble casting an interface to an implemented class

Here is my class:
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node (){}
public Node (int x)
{
data = x;
}
public int data()
{
return data;
}
public Node next()
{
return next;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
Here is my interface:
public interface Set {
public boolean isEmpty();
public void makeEmpty();
public boolean isMember(int x);
public void add(int x);
public void remove(int y);
public void union(Set other, Set result);
public void intersection (Set other, Set result);
public void difference (Set other, Set result);
#Override
public String toString();
#Override
public boolean equals(Object other);
public void setList(int i); //i added this to use it as an identifier for each
//list element in the set array
public String getListId(); //these two extra methods make life easier
}
I have a method like this (in the LinkedListSet class):
public void difference (Set other, Set result)
{
if (other.isEmpty())
{
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty())
{
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
differenceHelper(this.first, othr.first, res);
result = res;
}// the print statements were added for debugging
The problem is, in the above method I am unable to cast the Set Other into its linked list implementation. When I call this method in the main program, the parameter is actually of type linked list (so I don't get any errors obviously).
However, all the instance variables are null. The list is empty before and after I cast it (when it actually isn't empty). I know this is because the interface doesn't include any information about the Nodes, but is there anything I can do other than editing the interface to incorporate the Node?
I hope I've made this clear enough. Any help would be appreciated.
edit:
In the main program I created an array of Sets.
Set[] sets = new Set[7];
for (int i = 0; i< sets.length; i++) //initialize each element
{
sets[i] = new LinkedListSet();
}
each list has nodes with data values which are added on later on in the code...
then I call the difference method.
sets[0].difference(sets[1], sets[4])
sets[1].isEmpty returns true for some reason (even though it is not).
If I were to do something like:
System.out.println(sets[1].first.data()) I would have no problem whatsoever.
For some reason all the values become null when the parameters are passed to the difference method.
public boolean isEmpty()
{
return first == null;
}
I tested what you are trying to do with the following code and I see no problems:
import org.junit.Test;
public class RandomCastTest {
public interface Set {
boolean isEmpty();
void add(int x);
void difference(Set other, Set result);
#Override
String toString();
#Override
boolean equals(Object other);
}
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node() {
}
public Node(int x) {
data = x;
}
public int data() {
return data;
}
public Node next() {
return next;
}
public void next(Node node) {
next = node;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public void add(int x) {
Node node = new Node(x);
if (first == null) {
first = node;
} else {
Node currentNode;
Node nextNode = first;
do {
currentNode = nextNode;
nextNode = currentNode.next();
} while (nextNode != null);
currentNode.next(node);
}
Size++;
}
#Override
public void difference(Set other, Set result) {
if (other.isEmpty()) {
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty()) {
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
result = res;
}
}
#Test
public void test() {
Set[] sets = new Set[7];
for (int i = 0; i < sets.length; i++) {
sets[i] = new LinkedListSet();
}
for (int i = 0; i < 5; i++) {
sets[1].add(i);
}
for (int i = 5; i < 10; i++) {
sets[0].add(i);
}
sets[0].difference(sets[1], sets[4]);
// ... find difference
}
}
To simplify I removed unimplemented methods from the interface. Also added the add method implementation. Please see if it works for you.

How to get predecessor and successors from an adjacency matrix

Hi I am am trying to complete an assignment, where it is ok to consult the online community. I have to create a graph class that ultimately can do Breadth First Search and Depth First Search. I have been able to implement those algorithms successfully however another requirement is to be able to get the successors and predecessors and detect if two vertices are either predecessors or successors for each other. I'm having trouble thinking of a way to do this. I will post my code below, if anyone has any suggestions it would be greatly appreciated.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Graph<T>
{
public Vertex<T> root;
public ArrayList<Vertex<T>> vertices=new ArrayList<Vertex<T>>();
public int[][] adjMatrix;
int size;
private ArrayList<Vertex<T>> dfsArrList;
private ArrayList<Vertex<T>> bfsArrList;
public void setRootVertex(Vertex<T> n)
{
this.root=n;
}
public Vertex<T> getRootVertex()
{
return this.root;
}
public void addVertex(Vertex<T> n)
{
vertices.add(n);
}
public void removeVertex(int loc){
vertices.remove(loc);
}
public void addEdge(Vertex<T> start,Vertex<T> end)
{
if(adjMatrix==null)
{
size=vertices.size();
adjMatrix=new int[size][size];
}
int startIndex=vertices.indexOf(start);
int endIndex=vertices.indexOf(end);
adjMatrix[startIndex][endIndex]=1;
adjMatrix[endIndex][startIndex]=1;
}
public void removeEdge(Vertex<T> v1, Vertex<T> v2){
int startIndex=vertices.indexOf(v1);
int endIndex=vertices.indexOf(v2);
adjMatrix[startIndex][endIndex]=1;
adjMatrix[endIndex][startIndex]=1;
}
public int countVertices(){
int ver = vertices.size();
return ver;
}
/*
public boolean isPredecessor( Vertex<T> a, Vertex<T> b){
for()
return true;
}*/
/*
public boolean isSuccessor( Vertex<T> a, Vertex<T> b){
for()
return true;
}*/
public void getSuccessors(Vertex<T> v1){
}
public void getPredessors(Vertex<T> v1){
}
private Vertex<T> getUnvisitedChildNode(Vertex<T> n)
{
int index=vertices.indexOf(n);
int j=0;
while(j<size)
{
if(adjMatrix[index][j]==1 && vertices.get(j).visited==false)
{
return vertices.get(j);
}
j++;
}
return null;
}
public Iterator<Vertex<T>> bfs()
{
Queue<Vertex<T>> q=new LinkedList<Vertex<T>>();
q.add(this.root);
printVertex(this.root);
root.visited=true;
while(!q.isEmpty())
{
Vertex<T> n=q.remove();
Vertex<T> child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=true;
bfsArrList.add(child);
q.add(child);
}
}
clearVertices();
return bfsArrList.iterator();
}
public Iterator<Vertex<T>> dfs()
{
Stack<Vertex<T>> s=new Stack<Vertex<T>>();
s.push(this.root);
root.visited=true;
printVertex(root);
while(!s.isEmpty())
{
Vertex<T> n=s.peek();
Vertex<T> child=getUnvisitedChildNode(n);
if(child!=null)
{
child.visited=true;
dfsArrList.add(child);
s.push(child);
}
else
{
s.pop();
}
}
clearVertices();
return dfsArrList.iterator();
}
private void clearVertices()
{
int i=0;
while(i<size)
{
Vertex<T> n=vertices.get(i);
n.visited=false;
i++;
}
}
private void printVertex(Vertex<T> n)
{
System.out.print(n.label+" ");
}
}
Look here.
If v is reachable from u, then u is a predecessor of v and v is a successor of u. If there is an arc from u to v, then u is a direct predecessor of v, and v is a direct successor of u.
It should be trivial to implement this since you already seem to have the adjacency matrix built and also the traversal functions. So just run BFS / DFS and find what you're interested in.
Note that, unless your graph is directed, it makes no sense to talk about predecessors and successors, since the edges are bidirectional. Your graph seems to be undirected, so are you sure the assignment isn't to find if one node is reachable from another or not?
I believe this function is in error:
public void addEdge(Vertex<T> start, Vertex<T> end) {
if (adjMatrix == null) {
size = vertices.size();
adjMatrix = new int[size][size];
}
int startIndex = vertices.indexOf(start);
int endIndex = vertices.indexOf(end);
adjMatrix[startIndex][endIndex] = 1;
adjMatrix[endIndex][startIndex] = 1;
}
The second assignment is saying, effectively, that the edges are directionless. If I remove the second assignment, then this test
import junit.framework.TestCase;
public class GraphTest extends TestCase {
public void testIsPredecessor() throws Exception {
Graph<Integer> graph = new Graph<Integer>();
Vertex<Integer> zero = new Vertex<Integer>(0, "zero");
Vertex<Integer> one = new Vertex<Integer>(1, "one");
Vertex<Integer> two = new Vertex<Integer>(2, "two");
graph.addVertex(zero);
graph.addVertex(one);
graph.addVertex(two);
graph.addEdge(zero, one);
graph.addEdge(one, two);
assertTrue(graph.isPredecessor(zero, one));
assertFalse(graph.isPredecessor(one, zero));
}
}
can be passed by the following implementation:
public boolean isPredecessor( Vertex<T> a, Vertex<T> b){
int startIndex=vertices.indexOf(a);
int endIndex=vertices.indexOf(b);
return adjMatrix[startIndex][endIndex]==1;
}
isSuccessor() has an obvious implementation - just call isPredecessor(b, a). By the way, the deleteEdge() method should probably be assigning to 0, not 1 (and should only do so once, like addEdge()).

Categories

Resources