MiddleCodeOccasionalNot answered yet
Stream numbers across linked files, printing a running average, no cycles
A file yields one number per line, but a line may instead name another file to follow. Read all numbers across the linked files, and after each new number print the running average. File references may form cycles — never open the same file twice.
Requirements:
- Maintain the average incrementally (running sum and count), not by re-summing.
- Detect and skip already-visited files.
void process(const std::string& path) {
// your code here
}
Write the implementation.
Treat files as graph nodes and references as edges; traverse with DFS keeping a visited set of file paths so a cycle never reopens a file. Keep a running sum and count; for each numeric line add it and print sum / count. A reference follows the named file only if unvisited.
- ✗Re-summing all numbers per line instead of keeping a running sum and count
- ✗Omitting the visited set, so a reference cycle loops forever
- ✗Tracking visits by timestamp or size rather than the file path
- →Why does a visited set turn this into a standard graph traversal?
- →How would you keep the running average numerically stable for many values?
Contents
Task
Read numbers across linked files, printing a running average; never open a file twice.
Solution
#include <string>
#include <unordered_set>
#include <fstream>
#include <iostream>
static long long sum = 0, count = 0;
static std::unordered_set<std::string> visited;
void process(const std::string& path) {
if (visited.count(path)) return; // cycle: file already visited
visited.insert(path);
std::ifstream in(path);
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && std::isdigit((unsigned char)line[0])) {
sum += std::stoll(line); ++count; // incremental average
std::cout << path << ' ' << (double)sum / count << '\n';
} else {
process(line); // a reference line to another file
}
}
}
Key points
- Files are nodes, references are edges; graph traversal with a visited set.
- The average is a running
sumandcount, no re-summing. - A set keyed by file path terminates reference cycles.
Contents