Printing all subsets of a given array. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Printing all subsets of a given array.

I am trying to print all subsets of an array but getting IndexOutOfBoundException for the following code :- public static void getSubsets(int in,int [] arr,List<Integer> store) { if(in==arr.length) { System.out.println(store); return; } store.add(arr[in]); getSubsets(in+1, arr, store); store.remove(arr[in]); getSubsets(in+1, arr, store); } function call => getSubsets(0, arr, new ArrayList<Integer>());

13th Jan 2022, 11:40 AM
Ashutosh Raturi
Ashutosh Raturi - avatar
4 Answers
+ 2
you are taking value from arr and it is used as index in remove(arr[in]) result is unexpected (depends of values in arr) arr = [1,2,3,4,5] 0 [] before add arr[0] 1 [1] 2 [1, 2] 3 [1, 2, 3] 4 [1, 2, 3, 4] 5 [1, 2, 3, 4, 5] if (5 == length) [1, 2, 3, 4, 5] print result return now after first return in == 4 and arr[4] == value5 you are use value from array as index !! .remove( value5 ) //remove at index 5 actual possible index for store is 0-4 not 5 (length==5) Exception IndexOutOfBoundsException: Index: 5, Size: 5 at java.util.ArrayList.remove()
13th Jan 2022, 5:06 PM
zemiak
+ 3
Is this C++ or Java or JavaScript? Tag only the language used in your question, tagging too much languages irrelevant to the question results in lesser answers
13th Jan 2022, 12:46 PM
Rishi
Rishi - avatar
+ 2
Rishi noted👍
13th Jan 2022, 12:50 PM
Ashutosh Raturi
Ashutosh Raturi - avatar
+ 1
Thank you so much zemiak
13th Jan 2022, 7:03 PM
Ashutosh Raturi
Ashutosh Raturi - avatar