Error out of bounds exception when running recursive program in Java - java

I'm learning about recursion as part of a Java tutorial and I am looking for a little help.
We need to make a recursive Java program which will work out how to get from one city to the other when there is no direct flight.
My latest issue is Im getting an error out of bounds exception after the code has 2 cities in the flightRoute array List. it gives the error "IndexOutOfBoundsException Index 2 Size 2"
The connection value is an arrayList which takes all the cities that the city connects with and the flightRoute is also an arrayList which keeps track of the cities we have had to travel to in order to reach our destination.
I just cannot work out why it will not proceed.
I would appreciate some help on this if you could.
I do not want to overflow you guys with code so i'll put up the method that you should need. If you need more I will happily add some more code.
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
//the Connections value takes all the connecting cities we can travel to from a departure point
Connections = from.getConnections();
City theCity = Connections.get(i);
//searches in the connecting cities from the current city as to if it contains the city we wish to travel to
if (flightRoute.contains(to)|| 7 >8)
{
System.out.println("Congrats you can go their cause one of its connecting cities is the to city that u wanna go to");
return true;
}
System.out.println("the City name "+theCity);
if(flightRoute.contains(theCity))
{
System.out.println("Sorry it cannot be added "+Connections.get(i));
}
else
{
//add connecting city to list for future reference
flightRoute.add(Connections.get(i));
//takes the lates connection and uses it for recursion (below)
from = Connections.get(i);
i++;
//recursive part which sends a new from city for analysis until the city we want to travel to arises
determineRoute(from, to, flightRoute);
}
return true;
}

Where do you set the i value? Anyway, the only get() you do use i as index, so it is clear that Connections does not have as much items as i.
BTW:
a) Next time mark at which line the exception is thrown (from what I see, probaly the first get()
b) use lowercase for variable names: connections instead of Connections

The problem is that i is non declared locally, so you're forever incrementing some instance variable. Declare it locally and set it to zero.
Before you can make any real progress fixing this code, I advise you clean it up:
Name variables with a leading lowercase - ie connections not Connections
Use local variables where it makes sense - like connections
Remove nonsense code, such as the test if 7 > 8 is true - of course it's always true!
Use proper indentation of blocks
Iterate over collections using a "foreach" loop: for (City city : from.getConnections())
Tend to name your variables the same as the class name, but with a lowercase letter, so city, not theCity

Related

Looping through 2 String Lists

I wanted to know how I could possibly loop through 2 string lists (array lists - Bukkit) to see if I can find the value I need. Currently I have:
for (String parent : fc.getConfigurationSection("generators").getKeys(false)) {
for (String ls : fc.getStringList("generators." + parent)) {
}
}
I then check if the value in 'ls' is equal to the value I am searching for. I see that using 2 for loops is bad practice which is one of the many reasons that I have been trying to find a way around.
My User File:
generators:
262d327f-34e3-42be-87f5-235068661f30:
- Spawn,0,60,-249,Common
Notice how they are player UUIDs followed by a location which is automatically saved, I wish to check if a value in the list is equal to the one I want before returning the parent (UUID) to find who that belongs to.
Hopefully I've made myself clear what I have been trying to approach.

Branch And Bound not working in OptaPlanner

I have a Directed Acyclic Graph, arcs are Entities and Weights associated do each Arc are the PlanningVariables. I use:
#ValueRangeProvider(id = "bufferRange")
public CountableValueRange<Integer> getDelayRange() {
return ValueRangeFactory.createIntValueRange(1, 1000);
}
to assign values to my variables. Also, i've come across this issue:
Exhaustive Search in OptaPlanner does not work on very simple example, which is now solved by setting variables from int to Integer and checking null values in the score calculation.
Now the problem is that the solver seems not to be backtraking when assigning values. I've used a print to check values being attributed to each arc. In the beginning of the solving process i can see values being set to different arcs. But after some time attributions the solver stucks in assigning values to the same arc. Checking the prints I see the attributions going from 1 to 1000 and then starting again. Since all values from the domain are tested one time, why the solver does not backtrack instead of assigning the same values again?
I tested with all the <nodeExplorationType> options and created a class to use the <entitySorterManner> with the same results.
Thanks in advance.
I supose you are right Geoffrey, deactivated the log and let the program run for almost 48h and it came up with an answer. The way logs are printed mislead the analysis. Just for remark, if logger is deactivated the performance is considerably superior.

Figuring out The Big O Notation/Recurrence Relation From My Old Algorithm

**Hi all,
I have a question about recurrence relation/ Big O notation. I was given a homework assignment that asked me to give the Big O notation of some of my old code/ Algorithms that I came up with for previous homework assignments. Sadly, I have not yet taken a course in Finite Mathematics; so this is new to me. I managed to figure out three of the four Algorithms that I used. However, I am stuck on the fourth algorithms. This method is a recursive method and is coded in Java. I have, really, spent hours trying to figure this out, and I’ve watched lots of videos and read lots of articles on Big O notation but sadly can’t get it. Any help would be great!!!
Here is the code:
ArrayList<FacebookUser> getRecommendations(FacebookUser e) {
FacebookUser rootUser = userCallForList.get(0);
if(rootUser.getFriends().isEmpty() || e.getFriends().isEmpty()){
return returnHash();
}
for(FacebookUser hold : e.getFriends()){
if( !hold.equals(rootUser) && addHash(hold)){
getRecommendations(hold);
}
}
return returnHash();
}
Note About the Code:
The method takes a FacebookUser as an argument. The method returns an ArrayList that contains all of the friends of the FacebookUser that is passed into it plus the result of calling the same getRecommendations method on all of that FacebookUser’s friends. It does not add anyone to the list of recommendations if they are already on it and does not add the FacebookUser (E.I rootUser) that is calling it; As that could lead to an infinite loop. I use a HashSet as my collection and then I have to change it back to an ArrayList.
If I'm understanding your code right then this isn't a traditional recurrence because n (the input size) changes on each recursive call but does not necessarily get smaller i.e. it's not a divide and conquer algorithm.
This statement
for(FacebookUser hold : e.getFriends()){
if( !hold.equals(rootUser) && addHash(hold)){
getRecommendations(hold);
}
}
calls getRecommendations() for an unspecified number of friends which then calls it for each friend's friends. To me it seems like this method would be called for every friend in the network or every node if you think of it as a graph problem. This implies to me a running time O(k) where k = number of unique nodes reachable from the initial user by any number of edges.

How do I stop certain code from running?

I have a class that "bans" a player, but I don't want that player to be banned if his name is within a string array. I could loop through the length of the array and use booleans, but there has to be an easier way? I saw something that said just put if a condition is met, put return; and it'll stop all code running below that if statement.
Edit: Thanks for all the help! You were all helpful, even if you're one of the people that downvoted this, which is 4 people at least.
You could make a method that checks if the player is in the array of Strings and yes if you use return in a void method the method will just end.
For example
public void returnUsage(int n)
{
if(n==1)
{
return;
}
System.out.println("n doesn't equal 1.");
}
But it would probably be best to use an if and else to skip the code you don't want to run if the condition is not met. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
An array is the wrong data structure for this task. Add the players to a Set<> allowedPlayers = new HashSet<String>() then use if(allowedPlayers.contains(name)) return; to conditionally exit the method based on whether the name of the player is in the set. The set will remain fast when the number of names gets large. With an array scanning the array will be slow when the array is big.

How do I make an array from inputted information (i.e. names) and then use it as objects within the code?

I've been reading up on it, but every question I've found has asked for slightly different things, such as only wanting a single letter for their array, or in a different language (I'm new and only learning java at the moment), so here I am.
I want to set up an array that uses the user's input for their names.
What I have so far is this, I'm assuming this is the declaration line, where later I use an input line to define a value within the array (which I also am unsure how to do)
String[] array = {"name"};
But I don't know how to for example print.out the object or keep up with which name will be what value. I appreciate your time taken to teach me!
EDIT for further clarification. I'm trying to write up a small app that asks the user for numerous names, addresses, and phone numbers (Type name -> Type name's address -> type name's phone number, ask if they want to add another person, if yes then go back to asking for another name)
I am unsure how to set up a String array or how to use it throughout. However, thanks to your input and coming back after some fresh air, I have a better idea how to word it for google. Thank you guys for your help, even if it was just to gesture a better articulated question.
An array is a sequence of values. You have created an array of Strings that is one String long. To access the value at a specific of an array, use array subscript notation: the name of the array followed by a pair of square brackets ([]) with the index in between them.
String[] anArrayOfStrings = {"string0", "string1", "string2"};
anArrayOfStrings[0]; //the first element
System.out.println(anArrayOfStrings[1]); //print the second element
anArrayOfStrings[2] = "new string value"; //assign the third element to a new value
if (anArrayOfStrings[0].equals("string0") //evaluate the first element and call a method
{
//this block will execute anArrayOfStrings[0] is "string0"
}
anArrayOfStrings[3]; //error, index out of bounds
Simply declaring the array would be
String[] names;
In your code you both declare and assign it in the same line by using an initializer list.
To assign individual elements, use the [] notation. Note that once you initialized you list to be only one String long, it cannot become longer than without be re-assigned. To declare an array of any size, you can use:
String[] arrayWithInitialSize = new String[5]; //holds five strings, each null to begin with

Categories