Suppose you are given unique numbers like
11,2,7,6,17,13,8,9,3,5,12
The result will be group of numbers list containing sub list i.e.,
[2,3]-[5,6,7,8,9]-[11,12,13]-[17]
I took this approach to solve this below:
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> ListMain = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i + 1] == a[i] + 1) {
temp.add(a[i + 1]);
} else {
ListMain.add(temp);
temp.clear();
}
}
Your overall logic is mostly correct. You have a few problems in your execution, though.
a[i+1]
when i = a.length
. Change the loop condition to a.length - 1
.ArrayList
each time, otherwise each array will get wiped out. Change temp.clear();
to temp = new ArrayList<>();
.temp.add(a[0]);
at the beginning and temp.add(a[i+1])
when you've detected you need a new sublist.Here's the modified program:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class SubList {
public static void main(String... args) {
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> ListMain = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
temp.add(a[0]);
for (int i = 0; i < a.length - 1; i++) {
if (a[i + 1] == a[i] + 1) {
temp.add(a[i + 1]);
} else {
ListMain.add(temp);
temp = new ArrayList<>();
temp.add(a[i+1]);
}
}
ListMain.add(temp);
System.out.println(ListMain);
}
}
Output:
[[2, 3], [5, 6, 7, 8, 9], [11, 12, 13], [17]]
Thanks Garis M Suero for your suggestion after which i got answer
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> listMain = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if ((i + 1<a.length)&&( a[i] + 1==a[i + 1])) {
temp.add(a[i]);
} else {
temp.add(a[i]);
listMain.add(temp);
temp = new ArrayList<>();
}
}
for (List<Integer> lstI : listMain) {
for (Integer i : lstI) {
System.out.println(i);
}
System.out.println("================");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With