Creating an ArrayList inside a recursive method - java

I'm attempting to solve a problem that finds the amount of valid solutions to a chess problem and when the code is printed, it prints 92 arrays of an object PartialSolution I made that are the correct solutions. This is done recursively and I need to add these arrays to an array list but I can't figure out how.
Here's my code:
public ArrayList<PartialSolution> solve(PartialSolution sol ){
ArrayList<PartialSolution> solutions = new ArrayList<PartialSolution>();
int exam = sol.examine();
if(exam == PartialSolution.accept){
solutions.add(sol);
}
else if(exam != PartialSolution.abandon){
for(PartialSolution p : sol.extend()){
solve(p);
}
}
return solutions;
}

Define a variable in class and add your lists to that list instead of print.
Or make your solve method take a second argument as list and change return type from void to list. For the the first call give it an empty list and pass that list in every recursive call. At the end return that list

If you need the ArrayList just to store the solutions for later use then you should create the list out of the method like:
static ArrayList<PartialSolution> x = new ArrayList<PartialSolution>();
then just add the solution to the list when you print sol.

Related

Issue with recursion

I am trying to do a questions in Java which involves taking a Lisp List and a integer, and multiplies all the items in the list by the integer but it has to use recursion. This is my code:
public static LispList<Integer> multipy(LispList<Integer> ls, int m){
LispList<Integer> ls1 = LispList.empty();
if(ls.isEmpty()){
return ls1;
}else{
ls1.cons(ls.head() * b);
}
return multipy(ls1, m)
}
My idea was to first create a empty list, ls1. I then use a base case where I check whether the original list - ls - is empty and if so, to return the new List, ls1. If it isnt empty, I then multiply all items by the integer and pass it into ls1. I then call the method again at the end.
However my issue is this wont work as it will create a new List ls1 each time, thus destroying the list already created. I thought about passing in ls1 into the recursive call but this dosent work either as it operates on ls1 and not ls as required. Is there a way around this or do I have to use a iterative method to do it?
multiply(ls.tail(),m) gets you a list which contains all the values of the tail of ls multiplied. To that list you only have to add the head of ls multiplied, which you seem to do with the cons() method. So, it would be something like:
public static LispList<Integer> multipy(LispList<Integer> ls, int m){
// No point making the else case if your
// last statement of the block is a return
if(ls.isEmpty()) return LispList.empty();
return multiply(ls.tail(),m).cons(ls.head()*m);
}
I'm assuming your LispList has a tail() method.

Return inside a method one or two arrays

Its not duplicated i have read all and nothing suite in my case so please read it and answer it.I have two arrays.One is Vehicle and the other is pin.This is a part of code and it is only the method.
First question :
if i have declare the arrays on the same main out of
this method the way i pass them on the method is right?With other words the parameteres
are good or need (int vehicle[],int pin[]) or something else?
Second question +=
i dont know what it does but i think that in the array pin it takes
as an ecample the pin[1] cost has 10.The number 10 is taken by
getcostosvehicle();(we put it from userinput) so when the array fills
and it hasnt any slot then the costs will be finished.As a result will
have lets say the ended slot is 20 in pin[20] lets say it has 350.The
return statement will give us only the last cost?It would be better to
write return pin[i]; so in that way it will return all the pin with
the whole costs of each one slot,am i right?
Third question
On this code and that i want to write me as an answer could you return
two arrays?I mean return pin[i],vehicle[i]; not only return pin[i];.If
yes,could you do an answer and doesnt need to fill in the vehicle
array.Just to show me if this can happen.
public static int getallcosts(vehicle[],pin[]) {
int costos = 0;
for(int i =0; i < pin.length; i++) {
costos += pin[i].getcostosvehicle();
}
return costos;
}
if i have declare the arrays on the same main out of this method the way i pass them on the method is right?With other words the parameteres are good or need (int vehicle[],int pin[]) or something else?
I'm not sure I understand you correctly but of course getallcosts(vehicle[],pin[]) won't compile, i.e. you need to define the type of the arrays (or the names if vehicle and pin would actually be the types).
It would be better to write return pin[i]; so in that way it will return all the pin with the whole costs of each one slot,am i right?
No, you can only have one return value. If you want to return multiple values then you need to wrap them in an object (array, list, pojo, etc.).
On this code and that i want to write me as an answer could you return two arrays?
See the part above: if you want to return multiple arrays you need to add them so some object and return that object. Since you didn't provide the types for the arrays I'll use another example:
class Result {
String[] strings;
int[] numbers;
}
Result someMethod() {
Result r = new Result();
r.strings = new String[]{"a","b","c"};
r.numbers= new int[]{1,2,3};
return r;
}
First question:
If you are calling a method (so you're not defining it) yuo can write parameters as you do, without type.
Otherwise you need to specify type. In this case you are defining a new method so you need to specify type of parameters.
Second question:
'+=' it's like write
costos = costos + pin[i].getcostosvehicle();
So you will add to the current value of 'costos' the 'costos' of vehicle retrieved by 'getcostosvehicle()';
Third question:
As i know you can't return two Objects of any type in return statement.
So you'll need to reorganize your code to do operation first on an array and return it and then on the other one and return it.
For example you can do a method that have as parameter a generica array do some logic inside and then return it. You will call this method for the first array and then for the second.
Example:
public int[] method(int[] array){
/*do something
*/
return array;
}
Then you will call:
firstArray = method(firstArray);
secondArray = method(secondArray);
If you want more, or i have to change something comment please.

Adding values to ArrayList elements of type class

Here is what I have. I'm trying to add a name value to the ArrayList of type indexStruct and have no idea how to do that. Name is a String, any help would be great. Thanks!
import java.util.ArrayList;
public class Currentindex {
public void indexedWords(String currentWord, ArrayList <Indexstruct> currentIndex){
int convoMax=currentIndex.size();
int convoMin=0;
int placeHolder;
int strComp;
//pull words to skip that appear frequently in a typical conversation
while(convoMax>convoMin){ //binary search
placeHolder=(convoMin+convoMax)/2;
strComp=currentWord.compareToIgnoreCase(currentIndex.get(placeHolder).Word);
if(strComp==0){
currentIndex.add(placeHolder, Word); //<--Where problem occurs
break;
}
else if(strComp<0){
convoMax=placeHolder-1;
}
else{
convoMin=placeHolder+1;
}
}
//addterm(currentIndex);
System.out.println(currentIndex);
}
}
I'm trying to add a name value to the ArrayList of type indexStruct.
The specific ArrayList can only have elements added that are of type indexStruct.
This means, either they are:
objects of class indexStruct.
objects of a class extending indexStruct.
objects of a class implementing an interface called indexStruct.
The only way you could insert your string, is if there is a string field within the indexStruct Object.
You would create such an object, and assign the name. Then add this object to the arraylist.
currentIndex.add(placeHolder, Word);
The problem with the call currentIndex.add(placeHolder, Word); //<--Where problem occurs , is that the Word variable does not exist.
I am assuming that you compare the currentWord with the specific element at placeHolder, and then wish to re-insert the same Word Again when they are equal (ignoring case).
This should work if you change your line to:
currentIndex.add(placeHolder, currentIndex.get(placeHolder));
You would essentially be entering another instance of the same indexStruct object at the position placeHolder.
Also, I'd suggest you look into iterators or enhanced for loops which are optimized for iterating over ArrayLists.
See:
ArrayList.ListIterator(int index) vs ArrayList.get(int index)
http://www.deknight.com/java/enhanced-for-loop-in-java-5-0.html
You are using
ArrayList: Array List which can store objects of Indexstruct.
And you are trying to store indexstruct.word (Probably a String as I guess).
You are getting issues because of the type of Indexstruct.word is not compatible with ArrayList.
Try this
Add currentIndex.add(placeHolder, new Indexstruct(word));
OR alternatively set word to newly constructed Indexstruct object and then add that object.

Comparing int and String from LinkedList

I've got a problem.
I'm trying to compare a String and a int but can't seem to get working.
What am I doing wrong?
Getting this from Eclipse:
The type of the expression must be an array type but it resolved to List
int numberOfMoves;
List<String> highscoreLinkedList = new LinkedList<String>();
if (moves < Integer.parseInt(highscoreLinkedList[2])){
highscoreLinkedList[2] = Integer.toString(moves);
highscoreLinkedList[1] = name;
}
This is for a highscore textfile for a game I'm making. The String at index 2 is a number of moves and the int moves is also a number of moves.
You cannot access a list element using highscoreLinkedList[2] - that syntax is reserved for arrays. To access a list you have to use the get() method, i.e. highscoreLinkedList.get(2)
You are trying to treat list as an array, but the only way to access elements of the is through calling get() method. Your code does not compile.
Lists don't work the same way as arrays in Java. To access a certain element, you have to use the get() method, and to get the element, you need to use set(), like so:
// you have highscoreLinkedList[2], it should be:
highscoreLinkedList.get(2);
// you have highscoreLinkedList[2] = ..., it should be:
highscoreLinkedList.set(2, Integer.toString(moves));
You can see all of the methods for LinkedList here.

how to use my getvalues() method in main to print the list

The method does not show any error but I am unable to use it in main method to display the list.
if (userinput.equalsIgnoreCase("push") )
{ calc.push(value);
calc.displaylist();
System.out.println(calc.getValues());
}
else if (userinput.equalsIgnoreCase("mult"))
{ calc.push(calc.mult());
calc.getValues(); }
how to use this method ... instead i used a methos called display list and that works but i need to know how to use my getValues method. both the methods are as below :
Double[] getValues()
{
Double[] array = new Double[values.size()];
return values.toArray(array);
}
void displaylist()
{
for(Double d : values)
System.out.println(d);
}
You can use a static method called toString(Object[]) in the java.util.Arrays class.
Well your displaylist() method contains a for-each loop that will iterate over the contents of a collection. The collection to iterate over is on the right side of the ':'. You've got a method that returns a collection - specifically, a Double[] - so you can call your getValues() method in place of the collection.
So, try this:
void displaylist()
{
for(Double d : getValues()) System.out.println(d);
}
I'm trying to understand the question - Let me restate it and see if I got it or not:
You have an object that has a Collection (probably a List) of values called values.
You have a method, getValues(), which returns an array containing all of the values in values.
You would like to print out all of the values in values.
You are required (homework?) to use the getValues() method when printing out values in values. (If you're not required to use getValues(), then I don't see what's wrong with the displaylist() method that you already wrote.)
You tried to just call System.out.println() on the array that you got from getValues(), but that just printed something awful like "[Ljava.lang.Double;#39172e08".
Did I get it?
Unfortunately, even with all that, I'm not sure what to suggest because I don't know what you want the printed out version to look like.
Should the values be separated by commas? If so, Ash's answer will do this for you.
Should each one be on its own line? If so, Shakedown's answer will do this for you.
Should the values just be separated by spaces? If so, then you can modify Shakedown's answer to use print(d + " ") instead of println(d).

Categories

Resources