I have a list of elements that I wanted to print out. The way it is gonna work is that when we read aloud the list [1,1,1,1,4,4,4]
, we most likely say four 1
s and three 4
s, instead
of uttering each number one by one.
Method readAloud(List)
should return a List
.
For example:
• readAloud(List(1,1,1))
should return List(3,1)
.
• readAloud(List(-1,2,7))
should return List(1,-1,1,2,1,7)
.
• readAloud(List(3,3,8,-10,-10,-10))
should return List(2,3,1,8,3,-10)
.
• readAloud(List(3,3,1,1,3,1,1))
should return List(2,3,2,1,1,3,2,1)
.
As you can see, I have already done it. But how can I turn this code into recursion?
List<Integer> answer = new ArrayList<>();
int count=1;
int prev_elt = xs.get(0);
for(int i=1;i<xs.size();i++){
if (prev_elt == xs.get(i)){
count += 1;
}
else{
answer.add(count);
answer.add(prev_elt);
prev_elt=xs.get(i);
count=1;
}
if(i == xs.size()-1){
answer.add(count);
answer.add(prev_elt);
prev_elt=xs.get(i);
count=1;
}
}
return answer;
}