I have a problem that is pretty basic but I am struggling to get right. Basically, I have a constructor that has some methods defined on it using this.. I want to pass one of those methods a paramter, but I am struggling to declare it in a way that doesn't cause an error. This is my code:
public class Graph {
public Graph(int[][] gA) {
boolean[] visited = new boolean[gA.length];
Arrays.fill(visited, 0, gA.length, false);
//this is the bit I'm struggling with:
this.adj(int v) = gA[v];
this.array = gA;
this.visited = visited;
}
}
How do I get this.adj to accept a parameter? I also tried creating a method declaration but couldn't get this work either. Is there some kind of design pattern I should use?
Thanks
EDIT: Apologies - made a mistake in the code excerpt. this.adj[v] should be returning a row of the gA array, which it only has access to within the constructor, so I cannot move the function outside.
This :
this.adj(int v) = adj(v);
Is the wrong way. Just use:
adj(v); // Call the method adj with the parameter v
Since you are calling it in the constructor, hence it does not matter if the method is static or not. A constructor can call both of them.
Edit:
I want adj[v] to return the row of gA at v. I've edited the code above
You can do:
gA[v] = adj(v);
why you dont just call the method you defined??
public class Graph {
private YOUR_TYPE adj;
public Graph(int[][] gA) {
boolean[] visited = new boolean[gA.length];
Arrays.fill(visited, 0, gA.length, false);
//this is the bit I'm struggling with:
this.adj = adj(v);
this.array = gA;
this.visited = visited;
}
YOUR_TYPE adj(int v){
return .... something from YOUR_TYPE
}
}
Related
I have an assignment were I have to create run a depth first search through a directed graph, and return the traversal as a linked list. I believe the code for the DFS is correct as it seems to match up with the text book, and as I walk through the steps it makes sense. If I print it out as each vertex gets marked, it keeps printer over and over causing the stack overflow error.
private static boolean[] marked;
private static LinkedList<Integer> ret;
public static LinkedList<Integer> dfs(Digraph g, int s) {
marked = new boolean[g.V()];
ret = new LinkedList<>();
marked[s] = true;
System.out.print(s);
ret.add(s);
for (int i : g.adj(s)) {
if (!marked[i]) {
dfs(g, i);
}
}
return ret;
}
My guess would be the boolean[] marked is reseting every time I call dfs. I tried putting that outside the method but because the method is static and I can't change it(given the assignment parameters), I was getting a static-non static issue which I'm not quite sure how to fix.
Yup, your issue was indeed because the boolean was being reset in a sense. The resetting was happening in this line:
marked = new boolean[g.V()];
On this line, you are creating a new boolean array in the new function call, which is distinct from the original array . Then you are checking the new array which does not contain the changes from the old array.
I would recommend that you create a wrapper function that initializes the dfs process, and then pass the array into each call of your dfs function.
If you do not want to add extra parameters, just create a static variable as such outside of the method:
private static boolean[] marked;
Then initialize it when appropriate
I have a home work in a data structures course, the question is:
Implementation of doubly-linked list class.
the methods:
display()
length() or size()
insertSorted(Comparable)
insertToEnd(Comparable)
insertToHead(Comparable)
delete(Comparable)
boolean search(Comparable)
You must do this in JAVA
Create an application layer to test your class and its methods.
Compress all of your source files into a file and rename it as CS214HW1_first_lastName.zip Put your name in the filename. If needed, add a ReadMe.txt file for extra information such as compilation.
I implemented everything correctly and the code is working fine, but I used for example: insertSorted(int) instead of insertSorted(Comparable), because I didn't know how to do it.
I searched online, and read the JAVA documentation for (Comparable) but it is not enough :(
Can anybody help, please it is very important?
Here's some of my code, I can't write it all, cuz I don't want my friends to get the same code.
I will take zero if there is same code.
Code:
class DLL {
class Node {
Node next;
Node prev;
int data;
Node() {
next = null;
prev = null;
data = 0;
}
Node(int dt) {
next = null;
prev = null;
data = dt;
}
}
Node head;
void insertToHead(int dt) {
if (head == null) {
head = new Node(dt);
}
else {
head.prev = new Node(dt);
head.prev.next = head;
head = head.prev;
}
}
public static void main(String args[]) {
DLL dll = new DLL();
dll.insertToHead(1);
dll.insertToHead(2);
dll.insertToHead(3);
}
}
Please, somebody, tell me what to change in the beginning of the class.
are we gone use extends or implements Comparable<E> or what!
and what changes should i do the method insertToHead(Comparable)
what changes should i do to the main.
You would probably like to look into how generics work as well. The basic idea is that you would like to set up your class so that it will not know exactly the specific type of object but can be given some hint at the types of things it can expect of a declared generic type.
In your case, you would like to set up your list so that you can create linked lists of anything that can be compared. Java has a class for that which you have mention called Comparable<E> this tells Java that it will be able to call such methods as compareTo on the provided object.
More specifically to your closing questions:
Use the following style of class declaration MyClass<MyGenericType extends Comparable<MyGenericType>>. In your case DLL<E extends Comparable<E>>.
Switch the method arguments to accept E our declared generic type.
You should use the class Integer instead of the primitive type int, and change the creation of your list to DLL<Integer> dll = new DLL<Integer>().
Fully updated version of provided code:
public class DLL<E extends Comparable<E>> {
class Node {
Node next;
Node prev;
E data;
Node() {
next = null;
prev = null;
data = null;
}
Node(E dt) {
next = null;
prev = null;
data = dt;
}
}
Node head;
void insertToHead(E dt) {
if (head == null) {
head = new Node(dt);
}
else {
head.prev = new Node(dt);
head.prev.next = head;
head = head.prev;
}
}
public static void main(String args[]) {
DLL<Integer> dll = new DLL<Integer>();
dll.insertToHead(1);
dll.insertToHead(2);
dll.insertToHead(3);
}
}
This new implementation should provide a hint for how to proceed with some of the other homework tasks. For instance you can now compare objects just by their compareTo method which might useful for sorting hint hint.
That doc page gives a very good explanation for how to use this method. You should note that in their docs, they use a generic type called T instead of E, it really doesnt make a difference you can call it whatever you want provided it is unique to your program.
Edit:
An each hint in the sorting direction:
Ojbects which extend the Comparable class have a method which is called compareTo this method is set up so you can call:
object1.compareTo(object2);
this method returns an int which will be:
> 0 when object1 is greater than object2
= 0 when object1 is equal to object2
< 0 when object1 is less than object2
I don't want to give away too much as this is a homework assignment but here is my hint:
The way the above code sets up your classes, you would be able to tell the relationship between NodeA and NodeB by calling:
NodeA.data.compareTo(NodeB.data)
this will return an integer which gives your information according to the list above.
The <=,>=,== operators are likely found in the Integer class's compareTo method.
Something like:
public int compareTo(Object o) {
int otherNumber = ((Integer) o).intValue();
int thisNumber = this.intValue();
if (otherNumber > thisNumber) {
return 1;
} else if (otherNumber < thisNumber) {
return -1;
} else {
return 0;
}
}
but more likely they just do something like:
public int compareTo(Object o) {
return this.intValue() - o.intValue(); // possibly normalized to 1, -1, 0
}
See the Docs on Integer for more info on this.
So this is a stupid dbeginner's question.
I wrote a function that checks if a specific game move is legal (Reversi). The function must only return a boolean true/false value.
Later, in a different function, I actually make the move (makeMove function). In this function, before making the move I call the isLegal function to make sure the move is legal.
Now, when the isLegal function decides the move is legal, it would help me to save the specific info that lead to the decision, and use it in the makeMove function. I have no ideah ow to do that. I tried writing a function that will store the relevant data, and then send it back, but there's an obvious provlem with scopes here.
So here's the relevant code from isLegal:
else if(board[k][l]==player){relevantDirection=false; isLegal=true; ReversiPlay.saveLegalMove(direction, k, l);}
Then the problematic saving function:
public static int[] saveLegalMove(int direction, int row, int column){
if(direction==0){ //get info from function
return legalMoveData;
}
else{ //save legal move data
int[] legalMoveData = new int[3];
legalMoveData[0]= direction;
legalMoveData[1]= row;
legalMoveData[2]= column;
return null;
}
}
And lastly, I try calling the stored data:
int[] getSavedInfo = ReversiPlay.saveLegalMove(0, 0, 0);
I'm sure there's a very simple way of pulling the variables direction+k+l... anyone?
Thanks!
Edit: Here's a clearer example:
public static boolean A(int a){
...calculations...
int x = [value]
int y = [value]
return false;}
public static void B(int a){
...calculations...
boolean h = A(3);
[here I'd like to know what x,y were]
}
else { //save legal move data
int[] legalMoveData = new int[3];
legalMoveData[0]= direction;
legalMoveData[1]= row;
legalMoveData[2]= column;
return null;
}
This part doesn't save anything. It stores the values to a local variable and returns null.
An approach would be to make a Move object that contains the data you need:
public class Move {
private int direction;
private int row;
private int column;
...
}
Your isLegal method would only tell you if the move is legal. Then you can use that same Move instance to make the move.
if(ReversiPlay.isLegalMove(move)) {
ReversiPlay.makeMove(move);
}
There is no need to explicitly save the move; you already have that information inside the Move object instance.
UPDATE
Based on your edit, perhaps it is better to return an object instead of a boolean from A:
public static boolean A(int a) {
...calculations...
int x = [value]
int y = [value]
return new MyObject(x, y, false);
}
...
MyObject myObject = A(someValue);
Then you can query myObject to see what the value of the flag is.
UPDATE
You mentioned you aren't allowed to use objects. If so, instead of making the same calculations however, you can extract that logic into its own method and then call that. That way you won't have to duplicate logic.
I have a node class defined as below, but I keep on getting the error in Eclipse
void is an invalid type for the variable connectNode
Please explain why?
class Node{
char label;
boolean visited = false;
public Node (char l){
this.label=l;
}
public String toString() {
return Character.toString(label);
}
}
I have defined ArrayList as below:
ArrayList<Node> nodes = new ArrayList<Node>();
I'm trying to use the following method to print the values of Start and End index
public void connectNode(Node start,Node end){
int startIndex=nodes.indexOf(start);
int endIndex=nodes.indexOf(end);
System.out.println(startIndex);
System.out.println(endIndex);
}
Your error usually arises when you try to declare a method inside another method.
Recheck your code and file structure.
Is it possible you're doing something like:
nodes.add(connectNode(start, end));
If that's the case then it means you're trying to insert something that is not suitable for this array list. More specifically you try to put void in a list of type Node.
Lets say I have the following code:
public class Collection implements CollectionInterface{
ElementInterface[] elementArray = new ElementInterface[100];
int amountOfElements = 0;
public Collection()
{
}
public Collection(CollectionInterface collection)
{
CollectionInterface tempCollection = new Collection();
while(!collection.isEmpty())
{
ElementInterface element = collection.Remove().clone();
tempCollection.Add(element.clone2());
elementArray[amountOfElements++] = element;
}
collection = tempCollection;
}
public void Add(ElementInterface element){
elementArray[amountOfElements++] = element;
}
public ElementInterface Remove(){
ElementInterface element = elementArray[amountOfElements].clone2();
elementArray[amountOfElements] = null;
amountOfElements--;
return element;
}
public boolean isEmpty(){
return amountOfElements == 0;
}
public CollectionInterface clone()
{
return new Collection(this);
}
}
Allright, it might seem a bit strange, and it is. But if I use the following code:
CollectionInterface collection = new Collection();
collection.Add(new Element("Foo"));
collection.Add(new Element("Bar"));
CollectionInterface collection2 = collection.clone();
The first one doesn't contain any elements anymore. How is that possible?
It makes perfect sense. In the constructor, which is called by clone() with the original collection as an argument, you use:
ElementInterface element = collection.Remove().clone();
So you're removing elements from the original collection as you create the new one. You don't want to do that...
It's not really clear how you can achieve what you want, given that it looks like your CollectionInterface only has Add and Remove methods (which should be add and remove to follow Java naming conventions) to deal with elements - no way of accessing the collection non-destructively. That's very odd for a collection type. Is there any reason you're doing this in the first place instead of using the built-in collections?
EDIT: Ah - I've just had a thought. Within the class, you have access to the internals of the collection you're building... so you can destructively copy the elements from the collection you're given by calling Remove (as you are now) but then when you've built your array, you can use:
for (int i = 0; i < amountOfElements; i++)
{
collection.Add(elementArray[i].clone2());
}
... which will put the elemnts back again. This is horrible though...
You can not change the reference of an input parameter, as you try in the second constructor.
collection = tempCollection.
a) is this a syntax error,
b) collection is a local variable; assigning to it will change nothing on the outside of the constructor.
You can just implement the Clone method as follows:
public Object Clone() {
Collection rv = new Collection();
for (ElementInterface element : elementArray) {
rv.Add(element.clone());
}
return rv;
}
You could easily implement this in the constructor if necessary.