From 1c1a09ac3aaf842a252df56b7bcb882d4a9d2a2d Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Sun, 10 Mar 2019 13:50:30 +0000 Subject: [PATCH] find_gaps.cpp --- puzzles/interviews/training/find_gaps.cpp | 79 +++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 puzzles/interviews/training/find_gaps.cpp diff --git a/puzzles/interviews/training/find_gaps.cpp b/puzzles/interviews/training/find_gaps.cpp new file mode 100644 index 0000000..c0517d8 --- /dev/null +++ b/puzzles/interviews/training/find_gaps.cpp @@ -0,0 +1,79 @@ +/* +VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I." +VIM: let b:wcppflags="/O2 /EHsc /DWIN32" +*/ +#include "stdafx.h" +#include +#include +#include +#include +#include + +/* +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 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 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; + } +}