-2

been trying to find a way to solve this CodeWars challenge but can't find a way to check if there are eg. 4 consecutive numbers. If i got 2 i could just do: if (s.get(i) == s.get(i + 1) but how do I actually check if there are maybe 10 consecutive numbers? I cant just do s.get(i) == ... == s.get(i + 10) becasue there might be 11, so for sure thats not the answer Im looking for. So far Ive got this, because Im pretty sure I have to iterate through all the objects but have no clue how to do the comparison and addition to my result ArrayList so it replaces those consecutive numbers.

public static List<Integer> sumConsecutives(List<Integer> s) {
    List<Integer> result = new ArrayList<Integer>(s);
   for (int i : s) {
       if () // checking if there are consecutive same numbers
   }
}
lospejos
  • 1,976
  • 3
  • 19
  • 35
doublemc
  • 3,021
  • 5
  • 34
  • 61

1 Answers1

1

Here is the most straightforward solution I can think of:

public static List<Integer> sumConsecutives(List<Integer> s) {
    ArrayList<Integer> returnList = new ArrayList<>();
    int currentRepeating = 0;
    for (int i : s) {
        if (returnList.isEmpty() || currentRepeating != i) {
            currentRepeating = i;
            returnList.add(i);
        } else {
            returnList.set(returnList.size() - 1, returnList.get(returnList.size() - 1) + i);
        }
    }
    return returnList;
}

For each number i in the input, if the current repeating number is not equal to i, add i to the return list and set the current repeating number to i. If it is equal to the current repeating number, add it to the last element in the list.

Sweeper
  • 213,210
  • 22
  • 193
  • 313