Menu
CoddyTech

Final: Run-length Records

Lesson 47 of 48 in Coddy's C++ for GDScript 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 GDScript reference program to the required C++ API. Both programs consume the same integer input fixtures.

extends Node

func _ready() -> void:
    var text := ""
    var chunk := OS.read_string_from_stdin()
    while not chunk.is_empty():
        text += chunk + " "
        chunk = OS.read_string_from_stdin()
    var values: Array[int] = []
    for token in text.replace("\t", " ").replace("\r", " ").replace("\n", " ").split(" ", false):
        values.append(int(token))
    var groups := PackedStringArray()
    var i := 0
    while i < values.size():
        var j := i + 1
        while j < values.size() and values[j] == values[i]:
            j += 1
        groups.append("%d:%d" % [values[i], j - i])
        i = j
    print(" ".join(groups) if not groups.is_empty() else "empty")

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 GDScript Developers

Practice on your own: Online C++ compiler