How to write a recursive function using static variables - java

I am trying to write a code to get the set of points (x,y) that are accessible to a monkey starting from (0,0) such that each point satisfies |x| + |y| < _limitSum. I have written the below code and have used static HashSet of members of Coordinate type (not shown here) and have written a recursive method AccessPositiveQuadrantCoordinates. But the problem is the members of the HashSet passed across the recursive calls is not reflecting the Coordinate members added in previous calls. Can anybody help me on how to pass Object references to make this possible? Is there some other way that this problem can be solved?
public class MonkeyCoordinates {
public static HashSet<Coordinate> _accessibleCoordinates = null;
private int _limitSum;
public MonkeyCoordinates(int limitSum) {
_limitSum = limitSum;
if (_accessibleCoordinates == null)
_accessibleCoordinates = new HashSet<Coordinate>();
}
public int GetAccessibleCoordinateCount() {
_accessibleCoordinates.clear();
Coordinate start = new Coordinate(0,0);
AccessPositiveQuadrantCoordinates(start);
return (_accessibleCoordinates.size() * 4);
}
private void AccessPositiveQuadrantCoordinates(Coordinate current) {
if (current.getCoordinateSum() > _limitSum) { return; }
System.out.println("debug: The set _accessibleCoordinates is ");
for (Coordinate c : _accessibleCoordinates) {
System.out.println("debug:" + c.getXValue() + " " + c.getYValue());
}
if (!_accessibleCoordinates.contains(current)) { _accessibleCoordinates.add(current); }
AccessPositiveQuadrantCoordinates(current.Move(Coordinate.Direction.East));
AccessPositiveQuadrantCoordinates(current.Move(Coordinate.Direction.North));
}
I will give points to all acceptable answers.
Thanks ahead,
Somnath

But the problem is the members of the HashSet passed across the recursive calls is not reflecting the Coordinate members added in previous calls.
I think that's very unlikely. I think it's more likely that your Coordinate class doesn't override equals and hashCode appropriately, which is why the set can't "find" the values.
As an aside, using static variables like this seems like a very bad idea to me - why don't you create the set in GetAccessibleCoordinateCount() and pass the reference to AccessPositiveQuadrantCoordinates, which can in turn keep passing it down in the recursive calls?
(As another aside, I would strongly suggest that you start following Java naming conventions...)

i don't see any problem with making the field _accessibleCoordinates non-static
and you should know that HashSet does not guarantee the same iteration order everytime, you could better use a LinkedList for that purpose...
and about pass by reference, i found this post very useful
java - pass by value - SO link
From what you are doing you would be updating _accessibleCoordinates in every recursive call correctly.

Related

different sort outcome(SortedSet) in debug mode vs normal run

so i wrote a comparator to sort out objects of the type Polynom (polynomials but in my lang basically). when i iterate slowly over it with a debugger i seem to get the result im expecting. yet when i run it, one of them craps out and returns the wrong value in the comparison which should be very straight forward.
the Polynom object is as follows:
public class Polynom<E> implements IPolynom<E> , Comparable<Polynom<E>>{
private SortedMap<Integer, FieldMember<E>> coefficients = new TreeMap<>();
while IPolynom is just an interface to define the methods
E can be either a complex number (which i also wrote and includes its methods and two fields real and image but its irrelevant to the error)
public int compareTo(Polynom<E> o) {
Polynom<E> p1 = new Polynom<>(this);
Polynom<E> p2 = new Polynom<>(o);
int deg,co;
while(!p1.coefficients.isEmpty() && !p2.coefficients.isEmpty())
{
deg = p1.degree() - p2.degree();
if(deg != 0)
return deg;
co = p1.getCoefficient(p1.degree()).compareTo(p2.getCoefficient(p2.degree()));
if(co != 0)
return co;
p1.coefficients.remove(p1.degree());
p2.coefficients.remove(p2.degree());
}
return (p1.degree() - p2.degree());
}
this is the compareTo method that i wrote
and the method degree() simply returns the degree of x in this scenario
the coefficient part is never reached in this example so ill skip over it
the objects being compared are as follows:
p1 = Polynom: (1.00+0.00i)x^5
p2 = Polynom: (-1.00-5.00i)x^7
the comparison should be straight forward and indicate that p2 is greater than p1
however when i run the opposite is returned
when i debug (and specifically iterate over the lines as they happen) the method returns the correct result. if i skip over it even in debug it still returns the wrong result
in my main method im adding a bunch of Polynom type objects to a SortedSet and the ordering turns out to be wrong only on a single object (the one being p1 in this case which should be the "smallest" of them and go first up in the sorted set)
im really at loss here...
please tell me if theres any other details that i need to add that would make the situation clearer as this is a fairly large project
p.s. all of this is done in eclipse (without any extensions)
My mistake was making .toString() change the state of the object so the debugger didn't tell the whole story.
Thanks a lot guys!

Java constructor creates many null instances before the required object

this is my first question on here and I did a search before forming it, so I hope everything is as required.
I am working on a school assignment in Java. I am able to produce the required output but there are a lot of null instances created first. I don't understand why. Information about the library the professor created for the course and the code are below
Library included with this course: i2c.jar. It can be found here.
included in this Library are the classes Country and CountryDB. The API for the Country class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/Country.html
The API for the CountryDB class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/CountryDB.html
I am asked to create a class called Game, using the Country and CountryDB APIs.
The only attribute is db, which is an instance of CountryDB.
The constructor only sets the attribute (db) for this instance to a new CountryDB object.
The class is also meant to include a method (called qa) that follows this pseudocode:
get a reference to the database's capital city list
determine the size of this list. Cal it n.
generate a random number in [0,n) called index.
invoke get(index) on the list to get a random capital city. Call it c
get a reference to the database's data map
invoke get(c) on the map to get a reference to a country. Call it ref.
The method is then supposed to return one of two Strings (which will be clear in the code). Everything works as it should, except I get a lot of "nulls" before the desired output. When made into a List, db has size 241 so I suspect I am creating 241 null instances and 1 proper instance. I have no idea why though. I have tested every line of code in my method and the constructor was dictated by the textbook.
CODE
package ca.yorku.eecs.caps;
import java.util.List;
import java.util.Map;
import ca.roumani.i2c.Country;
import ca.roumani.i2c.CountryDB;
public class Game
{
private CountryDB db;
public Game()
{
this.db = new CountryDB();
}
public String qa()
{
List<String> capitals = db.getCapitals();
System.out.println(capitals.toString());
int n = capitals.size();
System.out.println(n);
int index = ((int) (n * Math.random()));
System.out.println(index);
String c = capitals.get(index);
System.out.println(c);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
if (Math.random() > 0.5)
{
return "What is the capital of " + ref.getName() + "? \n" + ref.getCapital();
}
else
{
return ref.getCapital() + " is the capital of? \n" + ref.getName();
}
}
public static void main(String[] args)
{
Game g = new Game();
System.out.println(g.qa());
}
}
the System.out.println() statements are only there to test when the nulls occur. It clearly happens immediately because my psvm output is 241 nulls (on separate lines) followed by my desired output. Can somebody please tell me what I am doing wrong?
And, more generally (to help more people) how do you implement classes, the constructor of which instantiates another class and sets it as an attribute value?
I appreciate any help. Also, please note, I am not trying to get others to do my work for me. I've spent hours on this and my lab TA also wasn't sure why it happens either. He would have helped me correct it had he known how.
Thank you.

I can't get to modify my static variable in java

You give a grid (4x4 here). you need to find out the total no of unique paths from (0,0) to (4,4). main() call a function pathify for this. It finds the possible "next steps" and calls it again. When (4,4) is reached noOfPaths++; is supposed to execute. This doesn't happen and I can't find the problem.
import java.util.ArrayList;
public class NoOfPaths {
static int xRows = 4;
static int yColumns = 4;
static int noOfPaths = 0;
/*A robot is located in the upper-left corner of a 4×4 grid.
* The robot can move either up, down, left, or right,
* but cannot go to the same location twice.
* The robot is trying to reach the lower-right corner of the grid.
* Your task is to find out the number of unique ways to reach the destination.
**/
static ArrayList validNeighbours (int x,int y, ArrayList visited) {
ArrayList valid = new ArrayList();
if((x+1 <= xRows) && !visited.contains(((x+1)*10)+y) ) {
valid.add(((x+1)*10)+y);
}
if((x-1 >= 0) && !visited.contains(((x-1)*10)+y) ) {
valid.add(((x-1)*10)+y);
}
if((y+1 <= yColumns) && !visited.contains(x*10+y+1) ) {
valid.add(x*10+y+1);
}
if((y-1 >= 0) && !visited.contains(x*10+y-1) ) {
valid.add(x*10+y-1);
}
return valid;
}
static void pathify(int x,int y, ArrayList alreadyVisited) {
if(x == xRows && y == yColumns) {
noOfPaths++;
} else {
alreadyVisited.add(x*10+y);
ArrayList callAgain = new ArrayList();
callAgain = validNeighbours(x,y,alreadyVisited);
for (int t=0,temp; t<callAgain.size(); t++) {
temp=(int) callAgain.get(t);
pathify(temp/10, temp%10, alreadyVisited);
}
}
}
public static void main(String[] args) {
ArrayList alreadyVisited = new ArrayList();
pathify(0, 0, alreadyVisited);
System.out.println(noOfPaths);
}
}
The error is in how you're handling alreadyVisited. The first time pathify is called, this list will contain only the initial square (0,0), which is fine. Here's the important part of your code:
for (int t=0,temp; t<callAgain.size(); t++) {
temp=(int) callAgain.get(t);
pathify(temp/10, temp%10, alreadyVisited);
}
You've found the neighbors of the initial cell. Your code will pick the first neighbor; then it will find paths starting with that neighbor, and the recursive calls to pathify will add cells to alreadyVisited.
Now, after all the recursive calls come back, you're ready to find cells starting with the second neighbor of the initial cell. But you have a problem: alreadyVisited still has all the cells it's collected from the paths it found starting with the second neighbor. So you won't find all possible paths starting with the second neighbor; you won't find any path that includes any cell in any path you've previously found. This isn't what you want, since you only want to avoid visiting the same cell in each path--you don't want to avoid visiting the same cell in all your previous paths. (I simplified this a little bit. In reality, the problem will start occurring deeper down the recursive stack, and you won't even find all the paths beginning with the first neighbor.)
When implementing a recursive algorithm, I've found that it's generally a bad idea to keep an intermediate data structure that is shared by recursive invocations that will be modified by those invocations. In this case, that's the list alreadyVisited. The problem is that when an invocation deeper down the stack modifies the structure, this affects invocations further up, because they will see the modifications after the deeper invocations return, which is basically data they need changing underneath them. (I'm not talking about a collection that is used to hold a list of results, if the list is basically write-only.) The way to avoid it here is that instead of adding to alreadyVisited, you could create a clone of this list and then add to it. That way, a deeper invocation can be sure that it's not impacting the shallower invocations by changing their data. That is, instead of
alreadyVisited.add(x*10+y);
write
alreadyVisited = [make a copy of alreadyVisited];
alreadyVisited.add(x*10+y);
The add will modify a new list, not the list that other invocations are using. (Personally, I'd declare a new variable such as newAlreadyVisited, since I don't really like modifying parameters, for readability reasons.)
This may seem inefficient. It will definitely use more memory (although the memory should be garbage-collectible pretty quickly). But trying to share a data structure between recursive invocations is very, very difficult to do correctly. It can be done if you're very careful about cleaning up the changes and restoring the structure to what it was when the method began. That might be necessary if the structure is something like a large tree, making it unfeasible to copy for every invocation. But it can take a lot of skill to make things work.
EDIT: I tested it and it appears to work: 12 if xRows=yColumns=2, 8512 if both are 4 (is that correct?). Another approach: instead of copying the list, I tried
alreadyVisited.remove((Object)(x*10+y));
at the end of the method ((Object) is needed so that Java doesn't think you're removing at an index) and that gave me the same results. If you do that, you'll make sure that alreadyVisited is the same when pathify returns as it was when it started. But I want to emphasize that I don't recommend this "cleanup" approach unless you really know what you're doing.

Is there a way to test for enum value in a list of candidates? (Java)

This is a simplified example. I have this enum declaration as follows:
public enum ELogLevel {
None,
Debug,
Info,
Error
}
I have this code in another class:
if ((CLog._logLevel == ELogLevel.Info) || (CLog._logLevel == ELogLevel.Debug) || (CLog._logLevel == ELogLevel.Error)) {
System.out.println(formatMessage(message));
}
My question is if there is a way to shorten the test. Ideally i would like somethign to the tune of (this is borrowed from Pascal/Delphi):
if (CLog._logLevel in [ELogLevel.Info, ELogLevel.Debug, ELogLevel.Error])
Instead of the long list of comparisons. Is there such a thing in Java, or maybe a way to achieve it? I am using a trivial example, my intention is to find out if there is a pattern so I can do these types of tests with enum value lists of many more elements.
EDIT: It looks like EnumSet is the closest thing to what I want. The Naïve way of implementing it is via something like:
if (EnumSet.of(ELogLevel.Info, ELogLevel.Debug, ELogLevel.Error).contains(CLog._logLevel))
But under benchmarking, this performs two orders of magnitude slower than the long if/then statement, I guess because the EnumSet is being instantiated every time it runs. This is a problem only for code that runs very often, and even then it's a very minor problem, since over 100M iterations we are talking about 7ms vs 450ms on my box; a very minimal amount of time either way.
What I settled on for code that runs very often is to pre-instantiate the EnumSet in a static variable, and use that instance in the loop, which cuts down the runtime back down to a much more palatable 9ms over 100M iterations.
So it looks like we have a winner! Thanks guys for your quick replies.
what you want is an enum set
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumSet.html
put the elements you want to test for in the set, and then use the Set method contains().
import java.util.EnumSet;
public class EnumSetExample
{
enum Level { NONE, DEBUG, INFO, ERROR };
public static void main(String[] args)
{
EnumSet<Level> subset = EnumSet.of(Level.DEBUG, Level.INFO);
for(Level currentLevel : EnumSet.allOf(Level.class))
{
if (subset.contains(currentLevel))
{
System.out.println("we have " + currentLevel.toString());
}
else
{
System.out.println("we don't have " + currentLevel.toString());
}
}
}
}
There's no way to do it concisely in Java. The closest you can come is to dump the values in a set and call contains(). An EnumSet is probably most efficient in your case. You can shorted the set initialization a little using the double brace idiom, though this has the drawback of creating a new inner class each time you use it, and hence increases the memory usage slightly.
In general, logging levels are implemented as integers:
public static int LEVEL_NONE = 0;
public static int LEVEL_DEBUG = 1;
public static int LEVEL_INFO = 2;
public static int LEVEL_ERROR = 3;
and then you can test for severity using simple comparisons:
if (Clog._loglevel >= LEVEL_DEBUG) {
// log
}
You could use a list of required levels, ie:
List<ELogLevel> levels = Lists.newArrayList(ELogLevel.Info,
ELogLevel.Debug, ELogLevel.Error);
if (levels.contains(CLog._logLevel)) {
//
}

Java - Error in eclipse: the left hand side of an assignment must be a variable

This is a small part of my code. My project is to simulate a whole school system. To add teachers, courses etc. All of my class members are private, so i created setters and getters methods. I try to give to 'teachersNum' a value and this must be automatic(not from keyboard). So i want to give it value 1 if its the first teacher etc. I hope you can understand. Sorry for my English.
public void addTeachersList(Teachers teachers) {
if(this.teachersSize<100){
this.teachersList[this.teachersSize] = teachers;
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
this.teachersSize++;
}
}
You'll have to call a setter:
this.teachersList[this.teachersSize].setTeacherNum(this.teachersSize-1);
Calling the getter getTeacherNum just gives you the number, it isn't a reference to that property.
Although I must say, you'd really do yourself a favor by using a List implementation instead of arrays.
In this line
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
getTeacherNum() returns a value. You can't assign to it.
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg:
temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg: temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003

Categories