Files
test/puzzles/training/find_gaps.cpp

80 lines
1.6 KiB
C++

/*
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
*/
#include "stdafx.h"
#include <iostream>
#include <exception>
#include <chrono>
#include <vector>
#include <algorithm>
/*
google-interview-questions
You are given a sorted list of distinct integers from 0 to 99, for
instance [0, 1, 2, 50, 52, 75]. Your task is to produce a string
that describes numbers missing from the list; in this case
"3-49,51,53-74,76-99".
Examples:
[] “0-99”
[0] “1-99”
[3, 5] “0-2,4,6-99”
*/
inline
void print_range_if_not_empty(int rb, int re)
{
if (re-rb > 2) {
std::cout << ',' << rb + 1 << '-' << re - 1;
}
else if (re-rb > 1) {
std::cout << ',' << rb + 1;
}
}
void print_gaps(std::vector<int> v)
{
int v_prev = -1;
for (int i = 0; i < v.size(); v_prev = v[i++]) {
print_range_if_not_empty(v_prev, v[i]);
}
print_range_if_not_empty(v_prev, 100);
std::cout << std::endl;
}
int main()
{
try {
auto begin = std::chrono::high_resolution_clock::now();
//......
print_gaps({ 0, 1, 2, 50, 52, 75 });
print_gaps({ 2, 4, 5, 7, 90 });
print_gaps({ 0, 4, 5, 7, 99 });
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> seconds = end - begin;
std::cout << "Time: " << seconds.count() << std::endl;
return 0;
}
catch (const std::exception& e)
{
std::cerr << std::endl
<< "std::exception(\"" << e.what() << "\")." << std::endl;
return 2;
}
catch (...)
{
std::cerr << std::endl
<< "unknown exception." << std::endl;
return 1;
}
}