Reputation: 31
I know there are similar questions out there and I've tried really hard to implement them but I can't quite seem to make them work for my needs. I don't need to find just consecutive numbers. I need to find consecutive numbers of 3 or more and replace the middle numbers with a hyphen.
For example :
1,3,4,6,7,8,9
. The output should be 1,3,4,6-9
.1,3,4,5,7,8,9
. The output should be 1,3-5,7-9
.The problem I'm having is writing the logic to differentiate between 1 digit, 2 digits, 3 or more digits, and groups of consecutive digits that are 3 or more. Thanks in advance for whatever help you can provide! :-)
Upvotes: 1
Views: 2229
Reputation: 3625
Here's a pretty verbose way. This creates a new array list to which you will either add the number from the original or the range. It finds ranges by testing if the next entry is one greater than the current, and how long that trend continues. If there are at least 3 in a row, it adds the range and starts looking after the range. Otherwise, it just adds each number.
List<String> altered = new ArrayList<>();
for(int i=0; i<list.size(); i++){
int start = i;
int size = 1;
int end = start;
if(i<list.size()-2){
end = start+1;
while(list.get(end) == list.get(end-1)+1){
size++;
end++;
if(end >= list.size())
break;
}
}
if(size >=3){
altered.add(list.get(start)+"-"+list.get(end-1));
i = end-1;
}
else
altered.add(""+list.get(i));
}
System.out.println(altered);
Upvotes: 2