String manipulation with std::adjacent_findConverting between std::wstring and std::stringstd::vector memory manipulation with serialization and deserializationString manipulation in JavaStreambuffer and string manipulationMimic sprintf with std::string outputHomebrew std::string for use with kernelPrinting doubles using string manipulationDetermining if an std::string contains a numerical typeStudent class with std::stringstd::string implementation attempt
Confirming the Identity of a (Friendly) Reviewer After the Reviews
How to befriend private nested class
OR-backed serious games
Apex code to find record diff between two dates (to call API only when needed)
Single word for "refusing to move to next activity unless present one is completed."
Historical experience as a guide to warship design?
GDPR rights when subject dies; does family inherit subject rights?
What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?
Is there any word for "disobedience to God"?
What's the difference between 役割 and 役回り?
Why does this potentiometer in an op-amp feedback path cause noise when adjusted?
Some interesting calculation puzzle that I made
Swapping "Good" and "Bad"
When an electron changes its spin, or any other intrinsic property, is it still the same electron?
Does the Pole of Angling's command word require an action?
Killing Magic Numbers: "const int" vs "constexpr int" (or is there no difference in the end)
Why did Harry Potter get a bedroom?
How can I get a player to accept that they should stop trying to pull stunts without thinking them through first?
What happens to unproductive professors?
Is English unusual in having no second person plural form?
Why isn't pressure filtration popular compared to vacuum filtration?
Why do we need common sense in AI?
Do I have a right to cancel a purchase of foreign currency in the UK?
What's it called when the bad guy gets eaten?
String manipulation with std::adjacent_find
Converting between std::wstring and std::stringstd::vector memory manipulation with serialization and deserializationString manipulation in JavaStreambuffer and string manipulationMimic sprintf with std::string outputHomebrew std::string for use with kernelPrinting doubles using string manipulationDetermining if an std::string contains a numerical typeStudent class with std::stringstd::string implementation attempt
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
For the given strings (not containing numbers), print their shortened
versions, where each adjacent sequence of the same characters longer
than 2, change to an expression consisting of a sign and a number of
repetitions.
Sample input:
4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE
Sample output:
A3
ABCDEF
C6D7
ZZAAC3D4E6
My code:
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
std::string reduce(std::string const& word)
std::string result;
for (auto it = word.cbegin(); true;)
auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
auto dist = std::distance(it, curr) + (curr != word.cend());
if (dist < 3)
result += std::string(dist, *it);
else
result += *it + std::to_string(dist);
if (curr == word.cend())
break;
it = 1 + curr;
return result;
int main()
std::size_t tests;
std::cin >> tests;
while (tests--)
std::string word;
std::cin >> word;
std::cout << reduce(word) << "n";
How could I simplify or improve this code?
c++ programming-challenge strings c++14
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
For the given strings (not containing numbers), print their shortened
versions, where each adjacent sequence of the same characters longer
than 2, change to an expression consisting of a sign and a number of
repetitions.
Sample input:
4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE
Sample output:
A3
ABCDEF
C6D7
ZZAAC3D4E6
My code:
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
std::string reduce(std::string const& word)
std::string result;
for (auto it = word.cbegin(); true;)
auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
auto dist = std::distance(it, curr) + (curr != word.cend());
if (dist < 3)
result += std::string(dist, *it);
else
result += *it + std::to_string(dist);
if (curr == word.cend())
break;
it = 1 + curr;
return result;
int main()
std::size_t tests;
std::cin >> tests;
while (tests--)
std::string word;
std::cin >> word;
std::cout << reduce(word) << "n";
How could I simplify or improve this code?
c++ programming-challenge strings c++14
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
For the given strings (not containing numbers), print their shortened
versions, where each adjacent sequence of the same characters longer
than 2, change to an expression consisting of a sign and a number of
repetitions.
Sample input:
4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE
Sample output:
A3
ABCDEF
C6D7
ZZAAC3D4E6
My code:
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
std::string reduce(std::string const& word)
std::string result;
for (auto it = word.cbegin(); true;)
auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
auto dist = std::distance(it, curr) + (curr != word.cend());
if (dist < 3)
result += std::string(dist, *it);
else
result += *it + std::to_string(dist);
if (curr == word.cend())
break;
it = 1 + curr;
return result;
int main()
std::size_t tests;
std::cin >> tests;
while (tests--)
std::string word;
std::cin >> word;
std::cout << reduce(word) << "n";
How could I simplify or improve this code?
c++ programming-challenge strings c++14
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
For the given strings (not containing numbers), print their shortened
versions, where each adjacent sequence of the same characters longer
than 2, change to an expression consisting of a sign and a number of
repetitions.
Sample input:
4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE
Sample output:
A3
ABCDEF
C6D7
ZZAAC3D4E6
My code:
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
std::string reduce(std::string const& word)
std::string result;
for (auto it = word.cbegin(); true;)
auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
auto dist = std::distance(it, curr) + (curr != word.cend());
if (dist < 3)
result += std::string(dist, *it);
else
result += *it + std::to_string(dist);
if (curr == word.cend())
break;
it = 1 + curr;
return result;
int main()
std::size_t tests;
std::cin >> tests;
while (tests--)
std::string word;
std::cin >> word;
std::cout << reduce(word) << "n";
How could I simplify or improve this code?
c++ programming-challenge strings c++14
c++ programming-challenge strings c++14
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 8 hours ago
Dessus
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 8 hours ago
DessusDessus
263 bronze badges
263 bronze badges
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
First impressions: nicely presented code; good use of the appropriate standard library functions and classes.
A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?
I'd suggest extracting the constant 3 to give it a meaningful name.
Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)
We can avoid constructing a new string here:
result += std::string(dist, *it);
by using the overload of append() that takes two iterators:
result.append(dist, *it);
$endgroup$
add a comment |
$begingroup$
A few things might be better, but you will need to measure if they actually help. (untested code)
The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try
result.reserve(word.size());
and
constexpr int LargeBuffer 4096 ;
std::string word;
word.reserve(LargeBuffer); // reuse the buffer.
while (tests--)
std::cin >> word;
std::cout << reduce(word) << "n"; // this call might use NRVO
That might still trigger one allocation per word, so a more drastic rebuild could be
std::string& reduce(std::string const& word, std::string & result)
and
constexpr int LargeBuffer 4096 ;
std::string word, result;
word.reserve(LargeBuffer); // reuse the buffer.
result.reserve(LargeBuffer);
while (tests--)
std::cin >> word;
result.clear(); // should not dealloc.
std::cout << reduce(word, result) << "n";
The strings will grow and keep their new size if the actual word is larger than expected.
The next most expensive should be the std::to_string
if (dist < 3)
result.append(dist, *it); // from Toby's answer
else
result.append(*it);
if (dist < 10)
result.append('0'+dist);
else
result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation
The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Dessus is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223812%2fstring-manipulation-with-stdadjacent-find%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
First impressions: nicely presented code; good use of the appropriate standard library functions and classes.
A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?
I'd suggest extracting the constant 3 to give it a meaningful name.
Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)
We can avoid constructing a new string here:
result += std::string(dist, *it);
by using the overload of append() that takes two iterators:
result.append(dist, *it);
$endgroup$
add a comment |
$begingroup$
First impressions: nicely presented code; good use of the appropriate standard library functions and classes.
A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?
I'd suggest extracting the constant 3 to give it a meaningful name.
Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)
We can avoid constructing a new string here:
result += std::string(dist, *it);
by using the overload of append() that takes two iterators:
result.append(dist, *it);
$endgroup$
add a comment |
$begingroup$
First impressions: nicely presented code; good use of the appropriate standard library functions and classes.
A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?
I'd suggest extracting the constant 3 to give it a meaningful name.
Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)
We can avoid constructing a new string here:
result += std::string(dist, *it);
by using the overload of append() that takes two iterators:
result.append(dist, *it);
$endgroup$
First impressions: nicely presented code; good use of the appropriate standard library functions and classes.
A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?
I'd suggest extracting the constant 3 to give it a meaningful name.
Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)
We can avoid constructing a new string here:
result += std::string(dist, *it);
by using the overload of append() that takes two iterators:
result.append(dist, *it);
answered 7 hours ago
Toby SpeightToby Speight
30.5k7 gold badges45 silver badges132 bronze badges
30.5k7 gold badges45 silver badges132 bronze badges
add a comment |
add a comment |
$begingroup$
A few things might be better, but you will need to measure if they actually help. (untested code)
The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try
result.reserve(word.size());
and
constexpr int LargeBuffer 4096 ;
std::string word;
word.reserve(LargeBuffer); // reuse the buffer.
while (tests--)
std::cin >> word;
std::cout << reduce(word) << "n"; // this call might use NRVO
That might still trigger one allocation per word, so a more drastic rebuild could be
std::string& reduce(std::string const& word, std::string & result)
and
constexpr int LargeBuffer 4096 ;
std::string word, result;
word.reserve(LargeBuffer); // reuse the buffer.
result.reserve(LargeBuffer);
while (tests--)
std::cin >> word;
result.clear(); // should not dealloc.
std::cout << reduce(word, result) << "n";
The strings will grow and keep their new size if the actual word is larger than expected.
The next most expensive should be the std::to_string
if (dist < 3)
result.append(dist, *it); // from Toby's answer
else
result.append(*it);
if (dist < 10)
result.append('0'+dist);
else
result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation
The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.
$endgroup$
add a comment |
$begingroup$
A few things might be better, but you will need to measure if they actually help. (untested code)
The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try
result.reserve(word.size());
and
constexpr int LargeBuffer 4096 ;
std::string word;
word.reserve(LargeBuffer); // reuse the buffer.
while (tests--)
std::cin >> word;
std::cout << reduce(word) << "n"; // this call might use NRVO
That might still trigger one allocation per word, so a more drastic rebuild could be
std::string& reduce(std::string const& word, std::string & result)
and
constexpr int LargeBuffer 4096 ;
std::string word, result;
word.reserve(LargeBuffer); // reuse the buffer.
result.reserve(LargeBuffer);
while (tests--)
std::cin >> word;
result.clear(); // should not dealloc.
std::cout << reduce(word, result) << "n";
The strings will grow and keep their new size if the actual word is larger than expected.
The next most expensive should be the std::to_string
if (dist < 3)
result.append(dist, *it); // from Toby's answer
else
result.append(*it);
if (dist < 10)
result.append('0'+dist);
else
result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation
The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.
$endgroup$
add a comment |
$begingroup$
A few things might be better, but you will need to measure if they actually help. (untested code)
The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try
result.reserve(word.size());
and
constexpr int LargeBuffer 4096 ;
std::string word;
word.reserve(LargeBuffer); // reuse the buffer.
while (tests--)
std::cin >> word;
std::cout << reduce(word) << "n"; // this call might use NRVO
That might still trigger one allocation per word, so a more drastic rebuild could be
std::string& reduce(std::string const& word, std::string & result)
and
constexpr int LargeBuffer 4096 ;
std::string word, result;
word.reserve(LargeBuffer); // reuse the buffer.
result.reserve(LargeBuffer);
while (tests--)
std::cin >> word;
result.clear(); // should not dealloc.
std::cout << reduce(word, result) << "n";
The strings will grow and keep their new size if the actual word is larger than expected.
The next most expensive should be the std::to_string
if (dist < 3)
result.append(dist, *it); // from Toby's answer
else
result.append(*it);
if (dist < 10)
result.append('0'+dist);
else
result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation
The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.
$endgroup$
A few things might be better, but you will need to measure if they actually help. (untested code)
The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try
result.reserve(word.size());
and
constexpr int LargeBuffer 4096 ;
std::string word;
word.reserve(LargeBuffer); // reuse the buffer.
while (tests--)
std::cin >> word;
std::cout << reduce(word) << "n"; // this call might use NRVO
That might still trigger one allocation per word, so a more drastic rebuild could be
std::string& reduce(std::string const& word, std::string & result)
and
constexpr int LargeBuffer 4096 ;
std::string word, result;
word.reserve(LargeBuffer); // reuse the buffer.
result.reserve(LargeBuffer);
while (tests--)
std::cin >> word;
result.clear(); // should not dealloc.
std::cout << reduce(word, result) << "n";
The strings will grow and keep their new size if the actual word is larger than expected.
The next most expensive should be the std::to_string
if (dist < 3)
result.append(dist, *it); // from Toby's answer
else
result.append(*it);
if (dist < 10)
result.append('0'+dist);
else
result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation
The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.
answered 48 mins ago
SurtSurt
5022 silver badges8 bronze badges
5022 silver badges8 bronze badges
add a comment |
add a comment |
Dessus is a new contributor. Be nice, and check out our Code of Conduct.
Dessus is a new contributor. Be nice, and check out our Code of Conduct.
Dessus is a new contributor. Be nice, and check out our Code of Conduct.
Dessus is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223812%2fstring-manipulation-with-stdadjacent-find%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown