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()).
Related
Hi,
Update: Thanks for all your suggestion
assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,
List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));
and I want to count how many of them are immediately followed by a lower number, recursively.
For example
[5,0,5,3].count() == 2, [5,5,0].count() == 1
The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.
Any solutions are welcome.
abstract class List {
public abstract boolean empty();
public abstract int first();
public abstract int count();
}
class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty(){
return false;
}
public int first(){
return elem;
}
#Override
public int count() {
if(elem>NEXT) {
return 1 + next.count();
}else {
return next.count();
}
}
```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.
Main Class
This your application entry point:
public static void main(String[] args) {
int count = RecursiveList.startRecursion().count();
System.out.printf("List has %d recursive elements", count);
}
RecursiveList Class
abstract class RecursiveList {
protected static int index = -1;
protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };
public static RecursiveList startRecursion() {
return new Cons();
}
public abstract boolean empty();
public abstract int count();
public abstract Integer getElement();
public static int incIndex() {
return index += 1;
}
}
Cons Class
public class Cons extends RecursiveList {
private static int result;
private final Integer elem;
private final RecursiveList prev;
private final RecursiveList next;
private Cons(Cons parent) {
prev = parent;
elem = incIndex() < elements.length ? elements[index] : null;
System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
next = elem != null ? new Cons(this) : null;
}
Cons() {
this(null);
}
public boolean empty() {
return false;
}
#Override
public /*#Nullable*/ Integer getElement() {
return elem;
}
#Override
public int count() {
if (elem != null)
{
if (prev != null && elem < prev.getElement())
result += 1;
if (next != null) {
return next.count();
}
}
return result;
}
}
EDIT
Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.
Main Class
public static void main(String[] args) {
List l = new Cons(3, new Cons(2,new Cons(1, new
Cons(4, new Cons(1, new Nil())))));
assert l.count() == 3;
l = new Cons(5, new Nil());
assert l.count() == 0;
l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
assert l.count() == 1;
l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
assert l.count() == 2;
System.out.println("All tests completed successfully!");
}
Cons Class
import java.util.NoSuchElementException;
public class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty()
{ return false; }
public int first()
{ return elem; }
public int count()
{
try {
if (first() > next.first()) {
return 1 + next.count();
}
else return next.count();
}
catch (NoSuchElementException e) {
return 0;
}
}
}
Nil Class
import java.util.NoSuchElementException;
public class Nil extends List {
public boolean empty()
{ return true; }
public int first()
{ throw new NoSuchElementException(); }
public int count()
{
throw new IllegalAccessError();
}
}
public int NEXT(){
if(next!=null)
return next.first()
else
throw new Exception("No next element")
}
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.
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?
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.
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.