printing all subsequences of an array using recursion in JAVA - java

The following code for above requirement. However I am not getting proper output. There is problem with input list that I am passing in recursion
import java.util.ArrayList;
import java.util.Collections;
public class abc
{
public static void m(ArrayList<Integer> op, ArrayList<Integer> ip) {
if(ip.size()==0) {
System.out.println(op);
return;
}
ArrayList<Integer> l1=new ArrayList<Integer>();
ArrayList<Integer> l2=new ArrayList<Integer>();
l1.addAll(op);
l2.addAll(op);
l1.add(ip.get(0));
ip.remove(0);
m(l2,ip);
m(l1,ip);
}
public static void main(String[] args) {
Integer [] z = {1,3,2};
ArrayList<Integer> ip=new ArrayList<Integer>();
Collections.addAll(ip, z);
ArrayList<Integer> op=new ArrayList<Integer>();
m(op,ip);
}
}

The problem is not, like you said in your comment, that the list ip keeps elements of the previous function call. The problem is that you don't create a new arraylist as ip parameter for the next function call, meaning, as it is call by reference, that you remove the elements of one function call already in the other function call. You can fix this by just creating a new array list for the new function call, like you already to for op. However you could also use this:
m(l2,new ArrayList<>(ip));
m(l1,new ArrayList<>(ip));
so you don't have to use an extra addAll() ;)

Related

incompatible types: List<Integer> cannot be converted to ArrayList<Integer> for Java sublists

I have been having this issue which I am not able to resolve at the moment. It is a type mismatch between List and ArrayList. I am not too sure of what went wrong with my work. Any help will be appreciated.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
// Sum of array
static Integer sumArray(ArrayList<Integer> Array){
Integer sum=Integer.valueOf(0);
for(int i=0;i<Array.size();i++){
sum+=Array.get(i);
}
return sum;
}
public static void main(String[] args){
ArrayList<Integer> RideArr = new ArrayList<Integer>(); // Initializing array
// Print out the RideArr values in list format(~)
RideArr.add(1);
RideArr.add(2);
RideArr.add(3);
RideArr.add(4);
RideArr.add(5);
ArrayList<Integer> jack=RideArr.subList(0, 4);
System.out.println(sumArray(jack));
}
}
Error: incompatible types: List cannot be converted to
ArrayList
ArrayList jack=RideArr.subList(0, 4);
The type of a variable should pretty much never be ArrayList. ArrayList is one specific kind of list implementation. someList.subList(a, b) does not return an ArrayList. It returns a List just fine, it's just not exactly an arraylist. Even ArrayList's own subList does not, itself, return an ArrayList.
It shouldn't matter what the implementation is, hence, using ArrayList anywhere is wrong; except with new ArrayList, as you can't write new List - with new, that is the one time you need to tell java what kind of list implementation you want. Thus:
List<Integer> rideArr = new ArrayList<>();
List<Integer> jack = rideArr.subList(0, 4);
NB: We write TypesLikeThis and variablesLikeThis, so, rideArr, not RideArr.
Try this one:
ArrayList<Integer> jack = new ArrayList<>(RideArr.subList(0,4));
System.out.println(sumArray(jack));

How to access same method with different objects in java

I have created an two Arraylist and a Method for printing the elements of array list. How can I use the same method to print the elements of both ArrayList ?
Simply pass the object of the created ArrayList to the function as paramter.
Here's a short example for printing the ArrayList:
Assuming you put the code inside a class, leaving a snippet here.
I'll demonstrate it with Integer examples.
static void printArrayList(ArrayList<Integer> a){
for(Integer i:a)
System.out.print(i+" ");
System.out.println("");
}
//in the main function:
public static void main(String[] args){
// input driver code
ArrayList<Integer> a1 = new ArrayList<>();
ArrayList<Integer> a2 = new ArrayList<>();
a1.add(1);
a2.add(10);
printArrayList(a1);
printArrayList(a2);
}
For more information on passing parameters - visit official documentation: Function Parameters
For more information on ArrayList - visit official documentation:
ArrayList
you can do it:
public static void printBothListArgs(List<AnyType> listOne, List<AnyType> listTwo){
Stream.concat(listOne.stream(), listTwo.stream()).forEach(System.out::println);
}

The reverse method should print out lst in reverse. It prints an empty arrayList instead. Why is this happening and how do I fix it?

This is the class with the buildList method which builds the in
class Recursive
{
public static ArrayList<Integer> reversedList = new ArrayList<Integer>();
public static ArrayList<Integer> buildList(int n)//builds the arrayList based on integer. If the int is 5 then the contents are 1,2,3,4,5.
{
// write this in terms of a recursive call using a smaller n
ArrayList<Integer> tempList = null;
if (n <= 0) // The smallest list we can make
{
return new ArrayList<Integer>();
}
else // All other size lists are created here
{
tempList= buildList(n-1);
tempList.add(n);
}
return tempList;
}
This is the problem method. Idk why it returns [], I think there is a passing error.
public static ArrayList<Integer> reverse(ArrayList<Integer> lst)//the problem method
{
if(lst.size()<=0) {
}
else {
reversedList.add(lst.remove(lst.size()-1));
reverse(lst);
}
return reversedList;
}
public static void main(String[] args)
{
ArrayList<Integer> lst = Recursive.buildList(5);
System.out.println(lst);
reverse(lst);
System.out.println(lst);
}
}
The reverse method removes the last item of lst and adds it to the empty reversedList. After the first iteration the contents should be [5]. Second [5,4]...all the way to [5,4,3,2,1]. But somehow it ends up being [].
So the reverse method is supposed to print out [5,4,3,2,1] but rather prints []. I think it has something to do with passing the reversedList between the if and else statement but I'm not sure.
You are printing the original list lst only which is now empty as program has removed all the elements.
You must reassign the lst to new object reference returned from function like lst = reverse(lst);
OR you can use System.out.println(reversedList)
public static void main(String[] args)
{
ArrayList<Integer> lst = Recursive.buildList(5);
System.out.println(lst);
lst = reverse(lst); ////update lst reference
System.out.println(lst);
System.out.println(reversedList); //// OR print reversedList directly
}
Hope you find it helpful.

ArrayList method "lastIndexOf" returning -1 when item does exist in ArrayList

I'm trying to get the basics of ArrayLists, but I can't get the lastIndexOf method to work properly. As you can see in my code below, the program runs and should print "1", the index of the number 3, but prints "-1" instead (which should be printed only if 3 didn't exist in the ArrayList). What's my problem?
import java.util.ArrayList;
public class Pile {
public static void main(String[] args)
{
int[] myArray = {1,3,23,4};
ArrayList<Integer> myList = new ArrayList<Integer>();
for (int i=0;i<myArray.length;i++) {
myList.add(myArray[0]);
}
System.out.println(myList.lastIndexOf(3));
}
}
You're only adding the first element of myArray to myList
You should replace
myList.add(myArray[0]);
with this
myList.add(myArray[i]);
Also, instead of manually copying the elements, you could use Arrays#asList (but you would need to change the type of myArray to Integer[]):
List<Integer> myList = Arrays.asList(myArray);
You are only adding the first element of the array multiple times to the list.
myList.add(myArray[0]);
That's why your list doesn't contain 3.
Change it to
myList.add(myArray[i]);

Java - Reading from an ArrayList from another class

We've not covered ArrayLists only Arrays and 2D arrays. What I need to do is be able to read from an ArrayList from another class. The main aim is to read from them in a for loop and use the values stored in them to display items. However, I have made this quick program to test it out and keep getting this error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Main.Main(Main.java:14)
Here is my code
import java.util.ArrayList;
public class Main
{
public static void Main()
{
System.out.println("Test");
ArrayList <Objects> xcoords = new ArrayList<Objects>();
for( int x = 1 ; x < xcoords.size() ; x++ )
{
System.out.println(xcoords.get(x));
}
}
}
And then the class where the ArrayList is
import java.util.ArrayList;
public class Objects
{
public void xco()
{
ArrayList xcoords = new ArrayList();
//X coords
//Destroyable
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
//Static Walls
xcoords.add(600);
xcoords.add(400);
xcoords.add(600);
}
}
If someone can point me in the correct direction it would be so valuable. I've tried to debug however I can get anything helpful.
Thanks in advance.
Strictly speaking, the exception is due to indexing location 1 of an ArrayList with 0 elements. Notice where you start you for loop index variable x. But consider this line:
ArrayList <Objects> xcoords = new ArrayList<Objects>();
xcoords points to a new, empty ArrayList, not the one you created in class Objects. To get that ArrayList, change the method xco like
public ArrayList<Integer> xco() { // make sure to parameterize the ArrayList
ArrayList<Integer> xcoords = new ArrayList<Integer>();
// .. add all the elements ..
return xcoords;
}
then, in your main method
public static void main(String [] args) { // add correct arguments
//..
ArrayList <Integer> xcoords = (new Objects()).xco();
for( int x = 0 ; x < xcoords.size() ; x++ ) { // start from index 0
System.out.println(xcoords.get(x));
}
}
Here you're simply creating two completely unrelated lists. Either have the array list be a property of the Objects class and retrieve it through an instance method, or return it from an instance or static method, or make the property static. IMO the first two are preferable in most situations.
public class Objects {
public static List<Integer> getXcoords() {
List<Integer> xcoords = new ArrayList<Integer>();
// Your same code, but adding:
return xoords;
}
}
Then to use it:
import java.util.ArrayList;
public class Main {
// Note the lower-case "main" here. You want that.
public static void main() {
List<Integer> xcoords = Objects.getXcoords();
// etc.
Also, your List should be of Integer, not of Objects, which would create a collection holding instances of Objects. You may want to take a step back and relate lists to arrays in a better way--you wouldn't create an array of Objects, would you? No, you'd have an array of int or Integer.
Also, there's Arrays.asList.
You have an IndexOutOfBoundsException which means that you are trying to access an element in an array which is not existing.
But in your code posted here you are not accessing an array at all (your for loop will not execute once because the list is empty), which means that your exception is thrown somewhere else.
But also your code doesn't make any sense. I refactored it for you while staying as close to your code as possible, so you can see how it could work:
public static void main(String[] args){
Objects myObjects = new Objects();
ArrayList<Integer> listFromMyObjects = myObjects.getList();
for( int x = 0 ; x < listFromMyObjects.size() ; x++ )
{
System.out.println(listFromMyObjects.get(x));
}
}
public class Objects
{
private ArrayList<Integer> myList;
public Objects(){
myList = new ArrayList<Integer>();
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(600);
myList.add(400);
myList.add(600);
}
public ArrayList<Integer> getList(){
return myList;
}
}

Categories

Resources