Jump to content

Rep-string: Difference between revisions

New post without using external libraries. In addition to an existing post which uses the "Boost" library.
(New post without using external libraries. In addition to an existing post which uses the "Boost" library.)
Line 971:
0
1 is no rep string!</pre>
 
===Without external libraries===
<syntaxhighlight lang="c++">
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
 
std::string repeat(const std::string& text, const int32_t& repetitions) {
std::stringstream stream;
std::fill_n(std::ostream_iterator<std::string>(stream), repetitions, text);
return stream.str();
}
 
std::vector<std::string> rep_string(const std::string& text) {
std::vector<std::string> repetitions;
if ( text.length() < 2 ) {
return repetitions;
}
 
for ( uint64_t len = 1; len <= text.length() / 2; ++len ) {
std::string possible = text.substr(0, len);
uint64_t quotient = text.length() / len;
uint64_t remainder = text.length() % len;
std::string candidate = repeat(possible, quotient) + possible.substr(0, remainder);
if ( candidate == text ) {
repetitions.emplace_back(possible);
}
}
return repetitions;
}
 
int main() {
const std::vector<std::string> tests = { "1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" };
 
std::cout << "The longest rep-strings are:" << std::endl;
for ( const std::string& test : tests ) {
std::vector<std::string> reps = rep_string(test);
uint64_t size = reps.size();
std::cout << std::setw(10) << test << " -> " << ( size > 0 ? reps[size - 1] : "Not a rep-string" ) << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
The longest rep-strings are:
1001110011 -> 10011
1110111011 -> 1110
0010010010 -> 001
1010101010 -> 1010
1111111111 -> 11111
0100101101 -> Not a rep-string
0100100 -> 010
101 -> Not a rep-string
11 -> 1
00 -> 0
1 -> Not a rep-string
</pre>
 
=={{header|Clojure}}==
908

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.