Final: Run-length Records
Lesson 47 of 48 in Coddy's C++ for C# Developers course.
Challenge
EasyInput: 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 C# reference program to the required C++ API. Both programs consume the same integer input fixtures.
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
var groups=new List<string>();int? previous=null;int count=0;string input=Console.In.ReadToEnd();foreach(string token in input.Split((char[])null,StringSplitOptions.RemoveEmptyEntries)){int n=int.Parse(token);if(previous.HasValue && n!=previous.Value){groups.Add(previous.Value+":"+count);count=0;}previous=n;count++;}if(previous.HasValue)groups.Add(previous.Value+":"+count);Console.WriteLine(groups.Count==0?"empty":string.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 C# Developers
1C++ Files and Values
Run the C++ FilesStrings and OutputTypes and InitializationDivision and RemaindersBooleans and ConditionsRecap: Parcel Charges4Copies and Algorithms
Value CopiesReferences and MutationFilter and TransformSorting with ComparatorsRecap: Top Unique Scores2Conditions and Iteration
Text EqualityBranches and RangesCounted IterationEarly Exit and SkippingRecap: Ticket Bands5Functions and Templates
Functions and ReturnsOverloads and DefaultsLambdas and CapturesFunction TemplatesRecap: Tiered Discounts8Composition and Ownership
Composition by ValueVirtual DispatchAbstract Base ContractsMove-only OwnershipRecap: Polymorphic Prices3Standard Containers
Fixed-size ArraysGrowing VectorsMaps and LookupSets and MembershipRecap: Shared Tags6Parsing and Lifetime
Streams and Exact ParsingExceptions and ContractsHeaders and LinkageRAII and Scope ExitRecap: Validate Lines9Project: Library Desk
Project: Book StockProject: Loan FeesPractice on your own: Online C++ compiler