From dd6399aba79ed6b313c1e0447a9561d61395e782 Mon Sep 17 00:00:00 2001 From: Paul Beckingham Date: Sun, 7 Sep 2014 16:54:59 -0400 Subject: [PATCH] CmdIDs - Migrated util.cpp compressIds to CmdIDs::compressIds, as this is the only place it is used. --- src/commands/CmdIDs.cpp | 56 ++++++++++++++++++++++++++++++++++++++++- src/commands/CmdIDs.h | 3 +++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/commands/CmdIDs.cpp b/src/commands/CmdIDs.cpp index 1b1baab09..406e480bd 100644 --- a/src/commands/CmdIDs.cpp +++ b/src/commands/CmdIDs.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include #include @@ -73,6 +72,61 @@ int CmdIDs::execute (std::string& output) return 0; } +//////////////////////////////////////////////////////////////////////////////// +// The vector must be sorted first. This is a modified version of the run- +// length encoding algorithm. +// +// This function converts the vector: +// +// [1, 3, 4, 6, 7, 8, 9, 11] +// +// to ths string: +// +// 1,3-4,6-9,11 +// +std::string CmdIDs::compressIds (const std::vector & ids) +{ + std::stringstream result; + + int range_start = 0; + int range_end = 0; + + for (unsigned int i = 0; i < ids.size (); ++i) + { + if (i + 1 == ids.size ()) + { + if (result.str ().length ()) + result << ","; + + if (range_start < range_end) + result << ids[range_start] << "-" << ids[range_end]; + else + result << ids[range_start]; + } + else + { + if (ids[range_end] + 1 == ids[i + 1]) + { + ++range_end; + } + else + { + if (result.str ().length ()) + result << ","; + + if (range_start < range_end) + result << ids[range_start] << "-" << ids[range_end]; + else + result << ids[range_start]; + + range_start = range_end = i + 1; + } + } + } + + return result.str (); +} + //////////////////////////////////////////////////////////////////////////////// CmdCompletionIds::CmdCompletionIds () { diff --git a/src/commands/CmdIDs.h b/src/commands/CmdIDs.h index b932a6545..7bde8fe91 100644 --- a/src/commands/CmdIDs.h +++ b/src/commands/CmdIDs.h @@ -35,6 +35,9 @@ class CmdIDs : public Command public: CmdIDs (); int execute (std::string&); + +private: + std::string compressIds (const std::vector &); }; class CmdCompletionIds : public Command