I am trying to align some fairly long equations the way I would usually do with LaTeX in groff. The general form I am aiming for:
A = B + C
= D * E
+ F * G
= H + I = J
In LaTeX I would do this as follows:
\documentclass[fleqn]{article}
\usepackage{amsmath}
\begin{document}
\begin{alignat*}{3}
A
& = B + C \\
& =
\begin{aligned}[t]
& D * E \\
& + F * G
\end{aligned} \\
& = H + I
&& = J
\end{alignat*}
\end{document}
In eqn, equation alignment is accomplished with the mark and lineup commands. Quoting Kernighan and Cherry from Typesetting Mathematics 2nd Ed (found here) on how these work:
The word mark may appear once at any place in an equation. It remembers the horizontal position where it appeared. Successive equations can contain one occurence of the word lineup. The place where lineup appears is made to line up with the place marked by the previous mark if at all possible.
Upon reading this I was under the impression that the system does not prohibit both aligning with the previous mark with lineup as well as setting a new mark within the same line of an equation, e.g. I would expect the following:
.PP
.EQ I
A mark =
B + C
.EN
.EQ I
lineup = mark
D * E
.EN
.EQ I
lineup + F * G
.EN
to produce something like this:
A = B + C
= D * E
+ F * G
That is not the case, however. eqn aligns the plus sign with the equals:
A = B + C
= D * E
+ F * G
and produces a warning:
eqn:test.ms:10: multiple marks and lineups
I compile my .ms files with a small script:
eqn $1 -Tpdf | groff -ms -Tpdf > ${1/%.ms/.pdf}
I would like to know if there is some macro that would let me store multiple horizontal offsets (or how to define one). Some clarification as to how exactly mark and lineup macros work would also help.
It is very disappointing that eqn does not allow a new mark to be set. Here is a poor workaround that might be of some use. It consists of repeating the first equation but with the keyword mark in the new position, and diverting the output to nowhere so it does not appear. .di is a base troff to start and end a diversion.
.EQ I
A mark = B + C
.EN
.EQ I
lineup = D * E
.EN
.di mydump
.EQ I
A = mark B + C
.EN
.di
.EQ I
lineup + F * G
.EN
Note, you can also use eqn commands like fwd 99 to move right 99/100 ems, where an em is about the width of the character "m".
Here's a possible solution for having a second mark on the same line as lineup. It uses the base troff sequence \k to mark the current horizontal position into a register myposn. There is then an eqn macro mylineup which calls the eqn special command to run a troff define MyLineup which "returns" a character that has a horizontal movement of myposn units. Before the call eqn sets up some registers with the word following the call, and expects them to be updated to whatever output is desired at that point. We do not use this dummy word, which can be anything, but must not be omitted. For example,
.de MyLineup
. ds 0s "\h'\\n[myposn]u'
. nr 0w \\n[myposn]u
. nr 0h 0
. nr 0d 0
. nr 0skern 0
. nr 0skew 0
..
.EQ I
define mymark '\k[myposn]'
define mylineup 'special MyLineup'
A mark = B + C
.EN
.EQ I
lineup = mymark D * E
.EN
.EQ I
mylineup dummy + F * G
.EN
The lines from .de to .. are the MyLineup definition. The two define lines should be in the first equation. Thereafter, mymark and mylineup dummy can be used in place of mark and lineup. The original mark and lineup are unchanged. If necessary, the real mark can be used again in the line with mylineup, and so on.
To generalise this to having many marks is complicated. The first problem is that mymark is just an eqn define and cannot take a number parameter. It cannot use the special command because it needs to be inline. A trivial solution is just to create a lot of definitions at the start:
define mymark1 '\k[myposn1]'
define mymark2 '\k[myposn2]'
The second problem is that when eqn calls MyLineup it does not pass the following argument ("dummy" which we intend to change to "1") as a parameter of the call, but in the variable 0s; also the string is embedded in formatting code and is actually (in my test anyway) \f[R]\,1\/\fP. So we need to substring the number out of this, with .substring 0s 7 -6. The modified macro and test is:
.\" gets passed 0s = \f[R]\,1\/\fP !!! not just 1
.de MyLineup
. substring 0s 7 -6
. ds 0s \\h'\\n[myposn\\*[0s]]u'
. nr 0w \\n[myposn\\*[0s]]u
. nr 0h 0
. nr 0d 0
. nr 0skern 0
. nr 0skew 0
..
.EQ I
define mymark1 '\k[myposn1]'
define mymark2 '\k[myposn2]'
define mylineup 'special MyLineup'
A mark = B + C
.EN
.EQ I
lineup = mymark1 D * mymark2 E
.EN
.EQ I
mylineup 1 + F * G
.EN
.EQ I
mylineup 2 + X
.EN
.EQ I
lineup = H + I
.EN
I may have been misled by there being several .EQ calls in your example. I was assuming there would be text between the calls and the equations. However, if the intention is to have a single, multi-line equation, it can be done using matrix (or perhaps lpile too). For example,
.nr PS 20p
.nr VS 24p
.PP
.EQ
matrix {
lcol { A }
lcol { = above = above ~ above = }
lcol { B + C above D * E above + F * G above H + I }
lcol { ~ above ~ above ~ above = J }
}
.EN
Related
Im having a bit of difficulty with the following question:
Given a DFA A = (E = {a,b,c} , Q ,q0 ,F , l) (where l is the transition function), build a new DFA B such that L(B) = L(A) - {a}.
Now I understand that Eb = Ea, but how can I define B transition function, or accepting states, without knowing the accepting states of A?
Thank you.
First, let us construct a DFA called C which accepts w. This DFA has |w| + 2 states: one initial state, one dead state, one accepting state.
Second, let us construct a DFA called D which accepts everything except w. Simply change all non-accepting states to accepting, and vice versa.
Third, let us construct B using the Cartesian Product Machine construction on input DFAs A and D with intersection as the operator. This DFA will hav |Q| x (|w| + 2) states in total.
The language of B is everything accepted by A and D simultaneously. D accepts anything that isn't w; so, B accepts anything in L(A) that isn't w, as required.
EDIT: Some more detail about what B ends up looking like.
Let the states of A be QA and the states of D be QD. Let the accepting states of A be FA and the accepting states of D be FD. Let dA be the transition function for A and dD be the transition function for D. From our construction above, we have:
Q = {(x, y) for x in QA y in QD}
E = the same alphabet as A and D, assumed to be the same. If w contains only symbols in A's alphabet then just use A's alphabet. If w contains symbols not in A's alphabet then w is not in L(A) and we can just let B = A.
q0 = (q0, q0')
F = {(x, y) in Q | x in FA and y in FD}
d((x, y), s) = (dA(x, s), dD(y, s))
As for what D looks like:
QD = {q0', q1', …, q(|w|+1)'}
E = same as A's
q0' is the initial state
FD = QD \ {q(|w|)}
d(qi, s) = q(i+1) if s is the (i+1)th symbol of w, or q(|w|+1) otherwise
I try to remove 1 whitespace from this string:
m y r e a l n a m e i s d o n a l d d u c k
Expected result:
my real name is donald duck
My code are:
def solve_cipher(input)
input.split('').map { |c| (c.ord - 3).chr }.join(' ') # <- Here I tried everything
end
puts solve_cipher('p| uhdo qdph lv grqdog gxfn')
# => m y r e a l n a m e i s d o n a l d d u c k
I tried everything to solve my problem, example:
input.....join(' ').squeeze(" ").strip # => m y r e a l n a m e...
or
input.....join.gsub(' ','') # => myrealnameisdonaldduck
or
input.....join(' ').lstrip # => m y r e a l n a m e...
and so on...
Well, you could split the string into words first, then split each word into characters. Using the same method you used in your code, it could look like this.
def solve_cipher(input) input.split(' ').map{ |w| w.split('').map { |c| (c.ord - 3).chr}.join('')}.join(' ') end
When joining the characters in the same word, we put no space between them; when joining the words together we put one space between them.
As stated in the question, you are using Rails, so you can also try squish method:
def solve_cipher( input )
input.split(' ').map(&:squish).join(' ')
end
str = "m y r e a l n a m e i s d o n a l d d u c k"
str.gsub(/\s(?!\s)/,'')
#=> "my real name is donald duck"
The regex matches a whitespace character not followed by another whitespace character and replaces the matched characters with empty strings. (?!\s) is a negative lookahead that matches a whitespace.
If more than two spaces may be present between words, first replace three or more spaces with two spaces, as follows.
str = "m y r e a l n a m e i s d o n a l d d u c k"
str.gsub(/\s{3,}/, " ").gsub(/\s(?!\s)/,'')
#=> "my real name is donald duck"
I know that it is not a fancy way of doing it but you could just try to create a new string and have a function traversal(input) with a counter initiated at 0, that would return this new string.
It would go through your input (which is here your string) and if the counter is 0 and it sees a space it just ignores it, increments a counter and go to the next character of the string.
If the counter is different of 0 and it sees a space it just concatenates it to the new string.
And if the counter is different of 0 and it sees something different of a space, it concatenates it to the new string and counter equals 0 again.
The trick is to use a capture group
"m y r e a l n a m e i s d o n a l d d u c k".gsub(/(\s)(.)/, '\2')
=> "my real name is donald duck
I have a question for the Follow sets of the following rules:
L -> CL'
L' -> epsilon
| ; L
C -> id:=G
|if GC
|begin L end
I have computed that the Follow(L) is in the Follow(L'). Also Follow(L') is in the Follow(L) so they both will contain: {end, $}. However, as L' is Nullable will the Follow(L) contain also the Follow(C)?
I have computed that the Follow(C) = First(L') and also Follow(C) subset Follow(L) = { ; $ end}.
In the answer the Follow(L) and Follow(L') contain only {end, $}, but shouldn't it contain ; as well from the Follow(C) as L' can be null?
Thanks
However, as L' is Nullable will the Follow(L) contain also the Follow(C)?
The opposite. Follow(C) will contain Follow(L). Think of the following sentence:
...Lx...
where X is some terminal and thus is in Follow(L). This could be expanded to:
...CL'x...
and further to:
...Cx...
So what follows L, can also follow C. The opposite is not necessarily true.
To calculate follows, think of a graph, where the nodes are (NT, n) which means non-terminal NT with the length of tokens as follow (in LL(1), n is either 1 or 0). The graph for yours would look like this:
_______
|/_ \
(L, 1)----->(L', 1) _(C, 1)
| \__________|____________/| |
| | |
| | |
| _______ | |
V |/_ \ V V
(L, 0)----->(L', 0) _(C, 0)
\_______________________/|
Where (X, n)--->(Y, m) means the follows of length n of X, depend on follows of length m of Y (of course, m <= n). That is to calculate (X, n), first you should calculate (Y, m), and then you should look at every rule that contains X on the right hand side and Y on the left hand side e.g.:
Y -> ... X REST
take what REST expands to with length n - m for every m in [0, n) and then concat every result with every follow from the (Y, m) set. You can calculate what REST expands to while calculating the firsts of REST, simply by holding a flag saying whether REST completely expands to that first, or partially. Furthermore, add firsts of REST with length n as follows of X too. For example:
S -> A a b c
A -> B C d
C -> epsilon | e | f g h i
Then to find follows of B with length 3 (which are e d a, d a b and f g h), we look at the rule:
A -> B C d
and we take the sentence C d, and look at what it can produce:
"C d" with length 0 (complete):
"C d" with length 1 (complete):
d
"C d" with length 2 (complete):
e d
"C d" with length 3 (complete or not):
f g h
Now we take these and merge with follow(A, m):
follow(A, 0):
epsilon
follow(A, 1):
a
follow(A, 2):
a b
follow(A, 3):
a b c
"C d" with length 0 (complete) concat follow(A, 3):
"C d" with length 1 (complete) concat follow(A, 2):
d a b
"C d" with length 2 (complete) concat follow(A, 1):
e d a
"C d" with length 3 (complete or not) concat follow(A, 0) (Note: follow(X, 0) is always epsilon):
f g h
Which is the set we were looking for. So in short, the algorithm becomes:
Create the graph of follow dependencies
Find the connected components and create a DAG out of it.
Traverse the DAG from the end (from the nodes that don't have any dependency) and calculate the follows with the algorithm above, having calculated firsts beforehand.
It's worth noting that the above algorithm is for any LL(K). For LL(1), the situation is much simpler.
I used the Z3_ast fs = Z3_parse_smtlib2_file(ctx,arg[1],0,0,0,0,0,0) to read file.
Additionally to add into the solver utilized the expr F = to_expr(ctx,fs) and then s.add(F).
My question is how can I get the number of total constraints in each instance?
I also tried the F.num_args(), however, it is giving wrong size in some instances.
Are there any ways to compute the total constraints?
Using Goal.size() may do what you want, after you add F to some goal. Here's a link to the Python API description, I'm sure you can find the equivalent in the C/C++ API: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#Goal-size
An expr F represents an abstract syntax tree, so F.num_args() returns the number of (one-step) children that F has, which is probably why what you've been trying doesn't always work. For example, suppose F = a + b, then F.num_args() = 2. But also, if F = a + b*c, then F.num_args() = 2 as well, where the children would be a and b*c (assuming usual order of operations). Thus, to compute the number of constraints (in case your definition is different than what Goal.size() yields), you can use a recursive method that traverses the tree.
I've included an example below highlighting all of these (z3py link here: http://rise4fun.com/Z3Py/It5E ).
For instance, my definition of constraint (or rather the complexity of an expression in some sense) might be the number of leaves or the depth of the expression. You can get as detailed as you want with this, e.g., counting different types of operands to fit whatever your definition of constraint might be, since it's not totally clear from your question. For instance, you might define a constraint as the number of equalities and/or inequalities appearing in an expression. This would probably need to be modified to work for formulas with quantifiers, arrays, or uninterpreted functions. Also note that Z3 may simplify things automatically (e.g., 1 - 1 gets simplified to 0 in the example below).
a, b, c = Reals('a b c')
F = a + b
print F.num_args() # 2
F = a + b * c
print F.num_args() # 2
print F.children() # [a,b*c]
g = Goal()
g.add(F == 0)
print g.size() # number of constraints = 1
g.add(Or(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 2
print g
g.add(And(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 6
print g
def count_constraints(c,d,f):
print 'depth: ' + str(d) + ' expr: ' + str(f)
if f.num_args() == 0:
return c + 1
else:
d += 1
for a in f.children():
c += count_constraints(0, d, a)
return c
exp = a + b * c + a + c * c
print count_constraints(0,0,exp)
exp = And(a == b, b == c, a == 0, c == 0, b == 1 - 1)
print count_constraints(0,0,exp)
q, r, s = Bools('q r s')
exp = And(q, r, s)
print count_constraints(0,0,exp)
I want to learn how calculators work. For example, say we have inputs in infix notation like this:
1 + 2 x 10 - 2
The parser would have to respect common rules in math. In the above example this means:
1 + (2 x 10) - 2 = 19 (rather than 3 x 10 - 2 = 28)
And then consider this:
1 + 2 x ((2 / 9) + 7) - 2
Does it involve an Abstract Syntax Tree? A binary tree? How is the order of operations ensured to be mathematically correct? Must I use the shunting-yard algorithm to convert this to postfix notation? And then, how would I parse it in postfix notation? Why convert in the first place?
Is there a tutorial which shows how these relatively simple calculators are built? Or can someone explain?
One way to do evaluate an expression is with a recursive descent parser.
http://en.wikipedia.org/wiki/Recursive_descent_parser
Here's an example grammar in BNF form:
http://en.wikipedia.org/wiki/Backus-Naur_form
Expr ::= Term ('+' Term | '-' Term)*
Term ::= Factor ('*' Factor | '/' Factor)*
Factor ::= ['-'] (Number | '(' Expr ')')
Number ::= Digit+
Here * means the preceding element is repeated zero or more times, + means one or more repeats, square brackets means optional.
The grammar ensures that the elements of highest precedence are collected together first, or in this case, evaluated first.
As you visit each node in the grammar, instead of building an abstract syntax tree, you evaluate the current node and return the value.
Example code (not perfect but should give you an idea of how to map BNF to code):
def parse_expr():
term = parse_term()
while 1:
if match('+'):
term = term + parse_term()
elif match('-'):
term = term - parse_term()
else: return term
def parse_term():
factor = parse_factor()
while 1:
if match('*'):
factor = factor * parse_factor()
elif match('/'):
factor = factor / parse_factor()
else: return factor
def parse_factor():
if match('-'):
negate = -1
else: negate = 1
if peek_digit():
return negate * parse_number()
if match('('):
expr = parse_expr()
if not match(')'): error...
return negate * expr
error...
def parse_number():
num = 0
while peek_digit():
num = num * 10 + read_digit()
return num
To show how your example of 1 + 2 * 10 - 2 would evaluate:
call parse_expr stream is 1 + 2 * 10 - 2
call parse term
call parse factor
call parse number which returns 1 stream is now + 2 * 10 - 2
match '+' stream is now 2 * 10 - 2
call parse factor
call parse number which returns 2 stream is now * 10 - 2
match '*' stream is now 10 - 2
call parse number which returns 10 stream is now - 2
computes 2 * 10, return 20
compute 1 + 20 -> 21
match '-' stream is now 2
call parse factor
call parse number which returns 2 stream is empty
compute 21 - 2, return 19
return 19
Try looking at Antlr. It is what I used to build a custom compiler/parser... and could easily relate to a calculator which would be a very simple thing to create.