path segment

closed account (Dy0fSL3A)
Hey, Ive been trying to work on this problem for at least a couple hours but still am not sure how to approach it. I need to write a bool function with string path with the following requirements:

Let's define a path segment as one or two digit characters followed by one of the four letters N, E, S, or W, in either upper or lower case. Two examples are 2N and 13e. A path is a sequence of zero or more path segments; an example is 2N1e1E2s1e.

bool isPathWellFormed(string path)

This function returns true if its parameter is a syntactically valid path, and false otherwise. A syntactically valid path is a sequence of zero or more path segments (not separated by spaces, commas, or anything else). Here are two syntactically valid paths: 2N1e01E0n2e1e and 42W. Here are four strings that are not syntactically valid paths: s3n, 1ex, 144N, and 2w+3n.

Not asking for anyone to write out the whole code for me just wondering if anyone had any ideas on where to start?
closed account (o1vk4iN6)
Start with a loop.
closed account (Dy0fSL3A)
I came up with this but even a simple segment like 2n returns false
bool isPathWellFormed(string path)
		if(	path[0] !='0' || path[1] !='1' || path[1] !='2' || path[1] !='3' || path[1] !='4' || path[1] !='5' || path[1] !='6' || path[1] !='7' || path[1] !='8' || path[1] !='9');
			return false;
		if (path[1] !='0' || path[1] !='1' || path[1] !='2' || path[1] !='3' || path[1] !='4' || path[1] !='5' || path[1] !='6' || path[1] !='7' || path[1] !='8' || path[1] !='9' || path[1]!='e'|| path[1]!='w'|| path[1]!='s'|| path[1]!='n'|| path[1]!='E'|| path[1]!='W'|| path[1]!='S'|| path[1]!='N')
			return false;
		else for (int k; k <= path.size(); k++)
			if(isalpha(path[k]) && (isalpha(path[k-1]) || isalpha(path[k+1])))
				return false;
			else if(isdigit(path[k]) && (isdigit(path[k-1]) && isdigit(path[k-2])))
				return false;
			else if(isdigit(path[k]) && (isdigit(path[k+1]) && isdigit(path[k+2])))
				return false;
		return true;
if( path[0] !='0' || path[1] !='1' || path[1] !='2'

This is sort of thing is much better if done with a for loop and use the isdigit function.

else for (int k; k <= path.size(); k++)

Variable k is not initialised.

if(isalpha(path[k]) && (isalpha(path[k-1]) || isalpha(path[k+1])))

This fails when k == 0, same for the other if statements.

Maybe you could try having a variable that keeps track of whether or not you are in an alpha or digit part of the string. This would allow appropriate testing.

Edit: You could have several variables for this: Seen1Digit, Seen2digit, Seen1Char.
Last edited on
I would also have a function IsDirection to test whether the direction chars are valid or not. Use a switch to do this. Also use the std::toupper function so you don't have to test them twice.

Also, make use of the continue statement in your for loop, so if all is well so far continue with the next iteration of the loop.
Topic archived. No new replies allowed.