Infinite Loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string Automaton :: generation_to_string(const vector<int>& gen, size_t width){
	if(width%2 ==0) return "";
	string ans = "";
	for(auto u:gen){
		if(!u) ans += " ";
		else ans +="*";
	}
	size_t append_count = (width-gen.size())/2; 
	for (size_t i=0; i<append_count; i++){
		ans = " "+ans; 
	}
	for (size_t i=0; i<append_count; i++){
		ans+=" ";   
	}
	return ans; 
}

When I remove one of the for loops that adds the spaces before or after ans it runs in time, but otherwise, if I run them together, it goes on forever. I've also tried this
1
2
3
for (size_t i=0; i<append_count; i++){
		ans = " "+ans+" "; 
	}

and it doesn't run in time either. I literally have no idea what is happening.
What's the value of append_count?
What's the size of gen?
it runs in time
doesn't run in time
What do you mean by that?
I mean like the testing server times out.
@Thomas1965, I think the issue may be somewhere else, as if I only keep the first for loop it runs fine.
Last edited on
Line 10 seems like it might be pretty inefficient. You are repeatedly moving characters. Without context I don't know how critical this function is to the entire program. But one solution would be to use the "fill" string constructor to remove the second and 3rd loops.
1
2
3
4
5
if (append_count > 0)
{
    auto pad = std::string(append_count, ' ');
    ans = pad + ans + pad;
}
@doug4 The issue seems to be that (width-gen.size())/2; can be negative, causing size_t to be a very large number. I have another problem now. This to_string method is supposed to take the gen vector (full of 0's and 1's) and convert 0's to spaces and 1's to *. It is then supposed to center that string within a string of length width, which is what my code does. However, I have encountered another error: it works well for some cases, but when I submitted it to the testing server, the answer was supposed to be blank, and instead it outputted "**". Any idea why?
Topic archived. No new replies allowed.