Craig
Craig

Reputation: 31

Find groups of 3 consecutive numbers or more in Java ArrayList

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 :

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

Answers (1)

Adam Yost
Adam Yost

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

Related Questions