Это Codingame
головоломка.Рассмотрим строку "abcdefghi"
.Он был закодирован следующим образом:
1) Take "a" from abcdefghi, add it at the end of an empty string -> a
2) Take "bc" from bcdefghi, add it at the beginning of a -> bca
3) Take "def" from defghi, add it at the end of bad -> bcadef
4) Take the remaining characters "ghi" and add it at the beginning of bcadef
Результирующая строка - "ghibcadef"
.Задача состоит в том, чтобы декодировать "ghibcadef"
обратно в "abcdefghi"
.
Я поражен if
, else if
заявлениями.И мой способ вычисления числа chunk
s (a
bc
def
ghi
) в исходной строке неверен.
РЕДАКТИРОВАТЬ
Это безобразно, но работает.Я все еще думаю, что должен быть лучший способ рассчитать chunks
:
std::string s = "ghijbcadefkl";
std::string decoded = "";
int chunks = sqrt(s.size() * 2);
// string size if all chunks are filled with letters
int full_chunks = (chunks * (chunks + 1)) / 2;
// string size if all except of the last chunk are filled with letters
int full_chunks_1 = (chunks * (chunks - 1)) / 2;
if (full_chunks < s.size()) {
++chunks;
full_chunks = (chunks * (chunks + 1)) / 2;
full_chunks_1 = (chunks * (chunks - 1)) / 2;
}
bool beginning = true;
if (chunks % 2 == 1) beginning = false;
int idx1 = 0, idx2 = 0;
while (chunks > 0) {
if (beginning && decoded == "") {
decoded = s.substr(idx1, chunks - (full_chunks - s.size())) + decoded;
idx1 += chunks - (full_chunks - s.size());
}
else if (beginning) {
decoded = s.substr(idx1, chunks) + decoded;
idx1 += chunks;
}
else if (!beginning && decoded == "") {
if (idx2 == 0) idx2 = full_chunks_1;
decoded = s.substr(idx2, chunks - (full_chunks - s.size())) + decoded;
idx2 -= chunks - 2;
}
else if (!beginning) {
if (idx2 == 0) idx2 = s.size() - chunks;
decoded = s.substr(idx2, chunks) + decoded;
idx2 -= chunks - 2;
}
--chunks;
beginning = !beginning;
}
std::cout << decoded << std::endl;