Menu
CoddyTech

Final: Run-length Records

Lesson 47 of 48 in Coddy's C++ for Go Developers course.

challenge icon

Challenge

Easy

Input: whitespace-separated integers. Compress consecutive equal values into value:count groups joined by spaces, or empty for no integers. This final ports the complete source reference shown below.

Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Port this complete Go reference program to the required C++ API. Both programs consume the same integer input fixtures.

package main
import("bufio";"fmt";"os";"strings")
func main(){
    in:=bufio.NewReader(os.Stdin)
    groups:=[]string{}
    previous,count:=0,0
    for {var n int;if _,err:=fmt.Fscan(in,&n);err!=nil{break};if count>0 && n!=previous{groups=append(groups,fmt.Sprintf("%d:%d",previous,count));count=0};previous=n;count++}
    if count>0{groups=append(groups,fmt.Sprintf("%d:%d",previous,count))}
    if len(groups)==0{fmt.Println("empty")}else{fmt.Println(strings.Join(groups," "))}
}

Try it yourself

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<int> v;int n;while(in>>n)v.push_back(n);std::cout<<runs(v)<<"\n";
}

All lessons in C++ for Go Developers

Practice on your own: Online C++ compiler