practical application of indirect recursion [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
In an interview they asked me to "give some practical applications of indirect recursion". I just replied the difference between direct recursion and indirect recursion. I googled but still didn't get any satisfying answers.
Any information on this topic is most welcome..

One obvious example of indirect recursion is a recursive descent parser.
For a simple example, consider a grammar something like:
expression = product (+|-) product
product = term (*|/) term
term = number | variable | '(' expression ')'
To parse that grammar with a recursive descent parser, we basically create a function to represent each element:
expression(input) {
product(input);
assert(operator(input) == '-' || '+');
product(input);
}
product(input) {
term(input);
assert(operator(input) == '/' || '*');
term(input);
}
term(input) {
if (next(input) == '(')
expression(input);
// ...
}
I'm obviously simplifying a lot here, but hopefully the general idea comes though: an expression is composed of products combined by + or -. A product is composed of terms combined by / or *. A term is a number or a variable or an expression enclosed in parentheses. We call a function to recognize each of those, so when we're recognizing an expression in parentheses as a term, we use indirect recursion -- expression() -> product() -> term() -> expression().

BTW, I knew it under the name of mutual recursion.
It can be used to simulate finite automata, but only if the language implements tail call optimization, which means that when one recursive call terminates with a return statement consisting solely of a further recursive call, that recursive call reuses the current stack frame. Without this optimization the mutual recursion could easily lead to Stack Overflow (pun ... well :-).
To be more explicit, here is a Lua script that recognizes the first occurrence of the string 111 inside the input string. Each function represent a state of the finite automaton and state transitions are simulated by mutually recursive calls (Lua performs proper tail call optimization, so stack overflow won't happen even for much longer input strings). In C++ the same technique is not applicable, since proper tail call optimization is not guaranteed by the standard (AFAIK). If you don't know Lua, take it as pseudo code (it is fairly readable, since it has a Pascal-like syntax). Anyway you can cut and paste the code in the live demo.
function Init( input, pos )
if pos > #input then return 0 end
local bit = input:sub( pos, pos )
if bit == "0" then
return Got0( input, pos + 1 )
else
return Got1( input, pos + 1 )
end
end
function Got0( input, pos )
if pos > #input then return 0 end
local bit = input:sub( pos, pos )
if bit == "0" then
return Got0( input, pos + 1 )
else
return Got1( input, pos + 1 )
end
end
function Got1( input, pos )
if pos > #input then return 0 end
local bit = input:sub( pos, pos )
if bit == "0" then
return Got0( input, pos + 1 )
else
return Got11( input, pos + 1 )
end
end
function Got11( input, pos )
if pos > #input then return 0 end
local bit = input:sub( pos, pos )
if bit == "0" then
return Got0( input, pos + 1 )
else
print( "recognized 111 sequence at position " .. pos - 2 )
print( input )
print( (" "):rep( pos - 3 ) .. "^" )
return 1
end
end
Init( "1101101101110110101", 1 )

Related

Is there a standard C++ tool to parse arithmetic expressions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I'm trying to do is described in the comment block immediately inside the function:
bool CalculusWizard::partitionEquation(const std::string & eq, std::string & eq1,
std::string & eq2, CalcWizConsts::eqOps & oper)
{
/* Given an equation eq, partion eq into
eq = eq1 oper eq2
where oper is the operator with the lowest precedence,
e.g. eq = "x*sin(x)+x^2" --> eq1 = "x*sin(x)", oper = ADDITION, eq2 = "x^2".
If there is no operator, e.g. eq = "x", then oper = NONE.
The error checking is done in this function. If there is a syntactical error
in eq, then return false.
*/
bool eqGood = true;
eq1.clear();
eq2.clear();
oper = CalcWizConsts::NONE;
int netParans = 0;
std::string::const_iterator it(eq.begin()), offend(eq.end());
while (it != offend)
{
char thisChar(*it);
char nextChar(((it+1) != offend) ? *(it+1) : '\0');
if (thisChar == '(')
{
if ()
++netParans;
}
else if (thisChar == ')')
{
if (isOp(nextChar))
{
}
--netParans;
}
else if (CalcWizConsts::digMap.count(thisChar) == 1)
{
}
}
if (netParans != 0)
eqGood = false;
return eqGood;
}
You can ignore the gunk that I've started to write. I've just about given up. Time to see whether someone has already done what I'm trying to do.
The operators I have, in order of precedence, are ^, *, /, + and -. The functions that might be in the equation are x, sin(x), cos(x), e^x and log(x) (although I want to be able to add more later). Is there any standard mechanism of doing what I'm trying to do?
What you mostly probably want to do is to break the expression into expression tree - in such form it is a lot easier to process.
To do that, first you need some kind of parser, which will break expression into tokens. Then you can use Reverse Polish Notation conversion algorithm to build an expression tree. Wikipedia page has a lot relevant informations.
In your example, the expression tree would look like the following:
x*sin(x)+x^2
+
/ \
* ^
/ \ / \
x sin x 2
|
x
With this tree you can easily process the whole expression in any way you want.
What you're looking for is a parser that can translate a string into a data structure that represents the expression, taking operator precedence into account. Parsing is a broad topic and you'll need to do some reading, but the Boost Spirit library is a decent way to write parsers in C++, and this SO question also provides some useful background (though it's not specific to C++).

Implementing Longest Common Substring using Suffix Array

I am using this program for computing the suffix array and the Longest Common Prefix.
I am required to calculate the longest common substring between two strings.
For that, I concatenate strings, A#B and then use this algorithm.
I have Suffix Array sa[] and the LCP[] array.
The the longest common substring is the max value of LCP[] array.
In order to find the substring, the only condition is that among substrings of common lengths, the one occurring the first time in string B should be the answer.
For that, I maintain max of the LCP[]. If LCP[curr_index] == max, then I make sure that the left_index of the substring B is smaller than the previous value of left_index.
However, this approach is not giving a right answer. Where is the fault?
max=-1;
for(int i=1;i<strlen(S)-1;++i)
{
//checking that sa[i+1] occurs after s[i] or not
if(lcp[i] >= max && sa[i] < l1 && sa[i+1] >= l1+1 )
{
if( max == lcp[i] && sa[i+1] < left_index ) left_index=sa[i+1];
else if (lcp[i] > ma )
{
left_index=sa[i+1];
max=lcp[i];
}
}
//checking that sa[i+1] occurs after s[i] or not
else if (lcp[i] >= max && sa[i] >= l1+1 && sa[i+1] < l1 )
{
if( max == lcp[i] && sa[i] < left_index) left_index=sa[i];
else if (lcp[i]>ma)
{
left_index=sa[i];
max=lcp[i];
}
}
}
AFAIK, This problem is from a programming contest and discussing about programming problems of ongoing contest before editorials have been released shouldn't be .... Although I am giving you some insights as I got Wrong Answer with suffix array. Then I used suffix Automaton which gives me Accepted.
Suffix array works in O(nlog^2 n) whereas Suffix Automaton works in O(n). So my advice is go with suffix Automaton and you will surely get Accepted.
And if you can code solution for that problem, you will surely code this.
Also found in codchef forum that:
Try this case
babaazzzzyy
badyybac
The suffix array will contain baa... (From 1st string ) , baba.. ( from first string ) , bac ( from second string ) , bad from second string .
So if you are examining consecutive entries of SA then you will find a match at "baba" and "bac" and find the index of "ba" as 7 in second string , even though its actually at index 1 also .
Its likely that you may output "yy" instead of "ba"
And also handling the constraint ...the first longest common substring to be found on the second string, should be written to output... would be very easy in case of suffix automaton. Best of luck!

Fix expression; operator precedence [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am reading C++ Primer, 5th Edition to learn C++ however I have come across a question that I am kind of stuck at. The question is as follows:
The following expression fails to compute due to operator precedence.
How would you fix it?
string s = "word";
string p1 = s + s[s.size() - 1] == 's' ? "" : "s";
I have tried various solutions but I can't seem to get it. My logic is that the equality operator needs two expressions so I need to create that but my solutions don't work.. Any help is much appreciated!
In general, you don't want to fit your solution in to one line, so lets break this up in to the indivdual parts so we can see why it doesn't work, what we want and how we would do that.
What it is at the moment
string s = "word";
string p1 = s + s[s.size() - 1] == 's' ? "" : "s";
means:
if(s + s[s.size() - 1] == 's')
{
p1 = "";
}
else
{
p1 = "s";
}
What's wrong
It is now clear why this won't work, firstly we are comaring a string (s + s[s.size() -1]) to a character s
Also, looking at the result, I suspect that isn't what you want.
The Fix
Instead we want to append an 's' if the last character is not an s. So in long form:
if(s[s.size() - 1] == 's') // compare the last character
{
p1 = s + ""; // equivalently = s but for clarity in the next step we'll write it like this
}
else
{
p1 = s + "s"; // append the s
}
So now we can condense this back down, adding in brackets to get the desired behaviour
string p1 = s + (s[s.size() - 1] == 's' ? "" : "s");
We append something to s, where the something is determined by the last character of s
I assume you want something like this:
string p1 = s + ((s[s.size() - 1] == 's')? "" : "s");
You want something like:
string s = "word";
string p1 = s + ((s[s.size() - 1] == 's')? "" : "s");

Interview: Adding two binary numbers given as strings [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
While looking through some interview questions at http://www.glassdoor.com/Interview/Facebook-Interview-Questions-E40772.htm I came across the following question:
Given two string representations of binary numbers (e.g. "1001", "10") write a function that adds them and returns the result as a string as well (e.g. "1011").
Here's some Python code that I started to write for the problem (it is incomplete right now), but I am not very sure if this is the best (or even correct) approach. I also thought about implementing the same in C++ first, but gave up considering the added complexities in string manipulations.
def add_binary(a,b):
temp = ""
carry = false
//i from len(a) to 1 and j from len(b) to 1
bit_sum = add_bit ((a[i],b[j])
if (bit_sum == "10"):
temp.append("0")
carry = true
elif carry:
temp.append(add_bit("1",bit_sum))
else:
temp.append(bit_sum)
return temp.reverse()
def add_bit(b1, b2):
if b1 == '0':
return b2
elif b2 == '0':
return b1
elif (b1 = '1' and b2 =='1'):
return "10"
else return None
a = "1001"
b = "10"
add_binary(a,b)
First, if the strings are short enough (less than 64 bits), I'd
probably just convert them to an internal integral type
(unsigned long long), do the addition there, and then
reconvert the results. Converting between binary strings and
internal format is really, really trivial.
Otherwise, I'd probably first normallize them so that they have
the maximum length of the results. Something like:
size_t size = std::max( lhs.size(), rhs.size() ) + 1;
lhs.insert( lhs.begin(), size - lhs.size(), '0' );
rhs.insert( rhs.begin(), size - rhs.size(), '0' );
I'd also create a results string of this size:
std::string results( size, '0' );
And a carry variable, initialized to '0':
char carry = '0';
I'd then loop over the three strings, using reverse iterators,
or more likely, just an index (which will ensure accessing the
same element of each string):
size_t current = size;
while ( current != 0 ) {
-- current;
// ...
}
With in the loop, you really only have four possibilities: I'd
just count the '1's (in lhs[current], rhs[current] and
carry), and do a switch on the results, setting
results[current] and carry appropriately:
int onesCount = 0;
if ( carry == '1' ) {
++ onesCount;
}
if ( lhs[current] == '1' ) {
++ onesCount;
}
if ( rhs[current] == '1' ) {
++ onesCount;
}
swith ( onesCount ) {
case 0:
carry = '0';
results[current] = '0';
break;
case 1:
carry = '0';
results[current] = '1';
break;
case 2:
carry = '1';
results[current] = '0';
break;
case 3:
carry = '1';
results[current] = '1';
break;
}
Personally, I think this is the simplest and the cleanest
solution, albeit a bit verbose. Alternatively, you can replace
the switch with something like:
results[current] = onesCount % 2 == 0 ? '0' : '1';
carry = onesCount < 2 ? '0' : '1';
Finally, if desired, you can suppress any leading zeros in the
results (there will be at most one), and maybe assert that
carry == '0' (because if it isn't, we've screwed up our
calculation of the size).
The most difficult part here is the fact that we need to process the strings from right to left. We can do this by either:
Reversing the strings (input and output).
In a recursive call, process the bits when "going back", i.e. first call a recursive add on the "next bits", then add the "current bit".
Use reverse iterators and construct the result from right to left. A problem will still be how to know the resulting length in advance (so you know where to start).
The recursive solution has problems when the numbers are large, i.e. the stack might overflow.
Reversing the strings is the easiest solution, yet not the most efficient one.
A combination of the first and third option would be to process the input strings in reverse using reverse iterators, but construct the result in reverse order (so you can simply append bits), then reverse the result.
This is more or less also your approach. Implement the loop counting i and j from the string length minus 1 (!) until 0, so this will walk through the input strings in reverse order. If carry was set to true, add one to the bit sum in the next iteration. Represent the bit sum of add_bit as an integer, not as a string again, so you can add the carry.
In C++, you have the possibility to iterate through any sequence in reverse order using rbegin() and rend().
in Python you can convert strings to integers with int, which also allows a base for conversion:
num = '111'
print int(num, 2)
prints 7.
For converting the result back to binary:
print "{:b}".format(4)
prints 100

c++ string member function substr usage

Please tell me if I am understanding the the substr member function correctly?
result = result.substr(0, pos) + result.substr(pos + 1);
It takes the string from pos, 0 until (but not including), remove[i]
and then + result.substr(pos + 1); concatenates the rest of the string, except but not including the string / char in remove?
string removeLetters2(string text, string remove)
{
int pos;
string result = text;
for (int i = 0; i < remove.length(); i++)
{
while (true)
{
pos = result.find(remove[i]);
if (pos == string::npos)
{
break;
}
else
{
result = result.substr(0, pos) +
result.substr(pos + 1);
}
}
}
return result;
}
In short, you are asking if
result = result.substr(0, pos) +
result.substr(pos + 1);
removes the character at position pos, right?
Short Answer:
Yes.
Longer Answer:
The two-argument call takes the start index and the length (the one argument call goes to the end of string).
It helps to imagine the string like this:
F o o / B a r
0 1 2 3 4 5 6 <- indices
Now remove /:
F o o / B a r
0 1 2 3 4 5 6 <- indices
1 2 3 | <- 1st length
| 1 2 3 <- 2nd length
result = result.substr(0, 3) <- from index 0 with length 3
+ result.substr(4); <- from index 4 to end
As a programmer, always be aware of the difference between distance/index and length.
Better: If index is known:
Your code creates two new, temporary strings, which are then concatenated into a third temporary string, which is then copied to result.
It would be better to ask string to erase (wink wink) in place:
result.erase(pos,1);
// or by iterator
string::iterator it = ....;
result.erase(it,it+1);
This leaves more optimization freedom to the string implementer, who may choose to just move all characters after pos by one to the left. This could, in a specialized scenario, be implemented with a single assignment, a single loop, and within the loop with the x86 swap instruction.
Better: If characters to be deleted are known:
Or, but I am not sure if this gives better performance, but it may give better code, the algorithm remove_if:
#include <algorithm>
// this would remove all slashes, question marks and dots
....
std::string foobar = "ab/d?...";
std::remove_if (foobar.begin(), foobar.end(), [](char c) {
return c=='/' || c=='?' || '.';
});
remove_if accepts any function object.
If there is just one character, it gets easier:
// this would remove all slashes
std::remove (foobar.begin(), foobar.end(), '/');
Although the answer to your question is "yes", there is a better way to go about what you are trying to do. Use string::erase, like this:
result.erase(pos, 1);
This API is designed for removal of characters from the string; it achieves the same result much more efficiently.
Yes, this function removes all letters in remove from text.
since you seem to delete more than one type of character have a look at remove_if from <algorithm> with a special predicate too, although the response of dasblinkenlignt is the good one