+ 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>());
4 Antworten
+ 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()
+ 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
+ 2
Rishi noted👍
+ 1
Thank you so much zemiak