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++).
Related
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 2 years ago.
Improve this question
I want to know about what is the use of that (index & 0x01) in the code?
if(((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01)))
{
outofplace = index;
}
A number is odd if and only if its last digit is odd, regardless of the base. So if we want to know the number's oddity, it's enough to check if the last bit is set.
index & 0x01
will be 1 if and only if index is odd.
If we have to deduce a general rule, we can say that for any non-negative number x,
x % y == (x & (y - 1))
provided that y is a positive power of 2.
This is a common hack in competitive coding. It is used because the competitive programmers think that bit-wise AND works faster than modulo.
In modern compilers, there is no performance difference at all. Read this thread.
There is no special reason in writing it as 0x01 instead of 1. Both compile to give the same assembly! Almost everyone (who uses this hack),= uses 1, because we have to type 3 characters extra in 0x01. :P
Here in this case, index & 0x1 is equivalent to index % 2 which is simply a condition to check if the number is odd. (Array indexes in C++ are always positive, unless you are going out of bound.)
As the other answers pointed out, while this is a well known pattern (see also this Q&A about that mask), it can be considered a premature optimization.
I'd like to suggest the following alternative to the posted code, which I find more readable. Your mileage may vary.
// Give a meaningful name.
constexpr auto is_odd = [] (auto x) -> bool {
return x % 2;
}
// Use it to simplify the condition.
if ( (arr[index] < 0) == is_odd(index) ) {
// Do something
}
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");
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 9 years ago.
Improve this question
I had an assignment of fractions in which the user sends input as a/b, but the a and b were simple integers and not negative or floats and extracting them was easy using if else statements
But right now I'm making a complex number (calculator type) program. And I'm actually taking a string in form of a + bi (where a and b can integer or float or both).
I'm having difficulty how to go about without using a lot of extra lines.
Edited: My question was actually how to extract 'Real & Imaginary Part' from a + bi.
e.g. Input: 3.45 - 9.87 i and get float Real = 3.45 and float Imaginary = 9.87 out
I'm working in c++ and using visual studio
the iostreams library provides nicely overloaded operators, you can read the components of the expression roughly like this:
string s = "3.45 - 9.87 i";
istringstream ist( s );
double re, im;
char op, ki;
ist >> re >> op >> im >> ki;
// op == '-'
// ki == 'i'
complex<double> a( re, op == '-' ? -im : im );
From there it should be easy to support more flexible expressions as well.
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 )
What would be the most efficient algorithm to solve a linear equation in one variable given as a string input to a function? For example, for input string:
"x + 9 – 2 - 4 + x = – x + 5 – 1 + 3 – x"
The output should be 1.
I am considering using a stack and pushing each string token onto it as I encounter spaces in the string. If the input was in polish notation then it would have been easier to pop numbers off the stack to get to a result, but I am not sure what approach to take here.
It is an interview question.
Solving the linear equation is (I hope) extremely easy for you once you've worked out the coefficients a and b in the equation a * x + b = 0.
So, the difficult part of the problem is parsing the expression and "evaluating" it to find the coefficients. Your example expression is extremely simple, it uses only the operators unary -, binary -, binary +. And =, which you could handle specially.
It is not clear from the question whether the solution should also handle expressions involving binary * and /, or parentheses. I'm wondering whether the interview question is intended:
to make you write some simple code, or
to make you ask what the real scope of the problem is before you write anything.
Both are important skills :-)
It could even be that the question is intended:
to separate those with lots of experience writing parsers (who will solve it as fast as they can write/type) from those with none (who might struggle to solve it at all within a few minutes, at least without some hints).
Anyway, to allow for future more complicated requirements, there are two common approaches to parsing arithmetic expressions: recursive descent or Dijkstra's shunting-yard algorithm. You can look these up, and if you only need the simple expressions in version 1.0 then you can use a simplified form of Dijkstra's algorithm. Then once you've parsed the expression, you need to evaluate it: use values that are linear expressions in x and interpret = as an operator with lowest possible precedence that means "subtract". The result is a linear expression in x that is equal to 0.
If you don't need complicated expressions then you can evaluate that simple example pretty much directly from left-to-right once you've tokenised it[*]:
x
x + 9
// set the "we've found minus sign" bit to negate the first thing that follows
x + 7 // and clear the negative bit
x + 3
2 * x + 3
// set the "we've found the equals sign" bit to negate everything that follows
3 * x + 3
3 * x - 2
3 * x - 1
3 * x - 4
4 * x - 4
Finally, solve a * x + b = 0 as x = - b/a.
[*] example tokenisation code, in Python:
acc = None
for idx, ch in enumerate(input):
if ch in '1234567890':
if acc is None: acc = 0
acc = 10 * acc + int(ch)
continue
if acc != None:
yield acc
acc = None
if ch in '+-=x':
yield ch
elif ch == ' ':
pass
else:
raise ValueError('illegal character "%s" at %d' % (ch, idx))
Alternative example tokenisation code, also in Python, assuming there will always be spaces between tokens as in the example. This leaves token validation to the parser:
return input.split()
ok some simple psuedo code that you could use to solve this problem
function(stinrgToParse){
arrayoftokens = stringToParse.match(RegexMatching);
foreach(arrayoftokens as token)
{
//now step through the tokens and determine what they are
//and store the neccesary information.
}
//Use the above information to do the arithmetic.
//count the number of times a variable appears positive and negative
//do the arithmetic.
//add up the numbers both positive and negative.
//return the result.
}
The first thing is to parse the string, to identify the various tokens (numbers, variables and operators), so that an expression tree can be formed by giving operator proper precedences.
Regular expressions can help, but that's not the only method (grammar parsers like boost::spirit are good too, and you can even run your own: its all a "find and recourse").
The tree can then be manipulated reducing the nodes executing those operation that deals with constants and by grouping variables related operations, executing them accordingly.
This goes on recursively until you remain with a variable related node and a constant node.
At the point the solution is calculated trivially.
They are basically the same principles that leads to the production of an interpreter or a compiler.
Consider:
from operator import add, sub
def ab(expr):
a, b, op = 0, 0, add
for t in expr.split():
if t == '+': op = add
elif t == '-': op = sub
elif t == 'x': a = op(a, 1)
else : b = op(b, int(t))
return a, b
Given an expression like 1 + x - 2 - x... this converts it to a canonical form ax+b and returns a pair of coefficients (a,b).
Now, let's obtain the coefficients from both parts of the equation:
le, ri = equation.split('=')
a1, b1 = ab(le)
a2, b2 = ab(ri)
and finally solve the trivial equation a1*x + b1 = a2*x + b2:
x = (b2 - b1) / (a1 - a2)
Of course, this only solves this particular example, without operator precedence or parentheses. To support the latter you'll need a parser, presumable a recursive descent one, which would be simper to code by hand.