-2

Most of my codes face similar problems. How do I fix it?.

Problem here: http://usaco.org/index.php?page=viewproblem2&cpid=692

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
string rotate_s(string s){
  int m= s.size();
  string s2;
  for(int i=0; i<m; i++){
    s2[i] = s[(i+m-1)%m];
  }
  return s+s2;

 }
int main()
{
string s;
int n;
cin>>s>>n;
int k = s.size();
while(k<n){
    s = rotate_s(s);
    k = s.size();
}
cout<<s[n-1]<<endl;
return 0;

}
GrGr11
  • 1
  • 3
  • 4
    The code you show has [*undefined behavior*](http://en.cppreference.com/w/cpp/language/ub). When you define a `std::string` object (like for example `s2` in your `rotate_s` function) it starts out *empty*. That means any indexing into that string object will be *out of bounds*. If you have UB (Undefined Behavior) then your whole program is *ill-formed* and invalid, and any speculation about its behavior or problems with it becomes moot. – Some programmer dude Aug 24 '17 at 09:11
  • 1
    Apart from fixing UB mentioned above, I'll suggest rethinking your algorithm. The `rotate_s` function is very expensive(both time and memory), so I'll suggest thinking about how to reduce amount of times it is called. – bezet Aug 24 '17 at 09:17
  • *"N may be too large to fit into a standard 32-bit integer"*. That make really think that you don't have to build the resulting string, but just "count" which index to use from original string. – Jarod42 Aug 24 '17 at 09:24
  • What's a "TLE"? – Ian Aug 24 '17 at 09:29
  • @Ian: **T**oo **L**ong **E**xecution. – Jarod42 Aug 24 '17 at 09:30
  • @Jarod42 Like this one then: [time-limit-exceeded-error-what-does-it-mean](https://stackoverflow.com/questions/24745307/time-limit-exceeded-error-what-does-it-mean). Interestingly, caused by index out of bounds. – Ian Aug 24 '17 at 09:38

1 Answers1

1

You don't have to build the string, just fixing the index progressively:

char foo(const std::string& s, std::size_t index)
{
    auto size = s.size();

    // What would be the size of the (smaller) string containing index
    while (size <= index) {
        size *= 2;
    }
    while (size != s.size()) {
        size /= 2;
        if (index >= size) { // index is on the second part
            index = (index - 1) % size; // negate the rotate
        }
    }
    return s[index];
}

Demo

So

0 1 2   3 4 5 | 6 7 8 9 10 11
0 1 2   3 4 5 | 5 0 1 2  3  4
0 1 2 | 3 4 5
0 1 2 | 2 0 1
0 1 2
Jarod42
  • 203,559
  • 14
  • 181
  • 302