I read that three variables a,b, and c can be swapped using the single statement below:
c = a ^ b ^ c ^ (a=b) ^ (b=c)
Similarly, two variables a and b can be swapped as:
a = a ^ b ^ (b=a)
Can somebody please explain how does this work?
P.S. Here is the link saying so.
http://p--np.blogspot.ro/2011/04/reverse-linked-list-using-only-2.html
You only need to make in the original statement all assignments (except the one you want to change to) are countered:
a = a ^ b ^ c ^ (b=c) ^ (c=a);
You assign c=a, b=c. The return value of those is a and c respectevely, so, you want to "counter" a and c, and you use the fact that a^a == 0 and c^c == 0, and just add a,c at the beginning.
In addition, you add a b, to assign a to the value of b.
Here is a demo on ideone
Note that as discussed in comments, it is language dependent if the above is guaranteed to succeed or not. In Java, for example - it is: The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right., while in others, such as C, it is not.
Related
If I have a list of variables, such as {A, B, C} and a list of operators, such as {AND, OR}, how can I efficiently enumerate all permutations of valid expressions?
Given the above, I would want to see as output (assuming evaluation from left-to-right with no operator precedence):
A AND B AND C
A OR B OR C
A AND B OR C
A AND C OR B
B AND C OR A
A OR B AND C
A OR C AND B
B OR C AND A
I believe that is an exhaustive enumeration of all combinations of inputs. I don't want to be redundant, so for example, I wouldn't add "C OR B AND A" because that is the same as "B OR C AND A".
Any ideas of how I can come up with an algorithm to do this? I really have no idea where to even start.
Recursion is a simple option to go:
void AllPossibilities(variables, operators, index, currentExpression){
if(index == variables.size) {
print(currentExpression);
return;
}
foreach(v in variables){
foreach(op in operators){
AllPossibilities(variables, operators, index + 1, v + op);
}
}
}
This is not an easy problem. First, you need a notion of grouping, because
(A AND B) OR C != A AND (B OR C)
Second, you need to generate all expressions. This will mean iterating through every permutation of terms, and grouping of terms in the permutation.
Third, you have to actually parse every expression, bringing the parsed expressions into a canonical form (say, CNF. https://en.wikipedia.org/wiki/Binary_expression_tree#Construction_of_an_expression_tree)
Finally, you have to actually check equivalence of the expressions seen so far. This is checking equivalence of the AST formed by parsing.
It will look loosely like this.
INPUT: terms
0. unique_expressions = empty_set
1. for p_t in permutations of terms:
2. for p_o in permutations of operations:
3. e = merge_into_expression(p_t, p_o)
4. parsed_e = parse(e)
5. already_seen = False
6. for unique_e in unique_expressions:
7. if equivalent(parsed_e, unique_e)
8. already_seen = True
9. break
10. if not already_seen:
11. unique_expressions.add(parsed_e)
For more info, check out this post. How to check if two boolean expressions are equivalent
I am a bit confused about multiple assignments in Go, e.g. varA, varB = varC, varD.
My question is, is such an operation atomic (not on the HW layer of course, but from the programmer's point of view)?
Personally, I expect it to be atomic, so this expression a, b = b, a just swap the values. I tried it in the Go playground and yes, it worked exactly like that.
On the other hand, the Golang specs states:
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.
which I understand as a is assigned b's value, then b is assigned a's value (which is now b), so in the end, both a and b equals b's original value.
Are the specs wrong or do I misunderstand it?
You misunderstood it, and it is not the second part you misunderstood.
The spec say:
First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order.
Here evaluated means all expressions, including variable are ..., well, being evaluated into value and the value is fixed at that time. So in a,b = b,a, in the first part, the lhs expression a,b got resolved, and rhs expression b,a got evaluated into something like 5,3 (assuming a,b:=3,5, of course); and in the second part, the assignment took place, and becomes a = 5; b = 3.
The evaluation is the samething happens when using defer and goroutine. It is why the below code prints 5.
func T() {
x := 5
defer func(i int) {
fmt.Println(i)
}(x)
x = 3
}
I am aware how we can evaluate an expression after converting into Polish Notations. However I would like to know how I can evaluate something like this:
If a < b Then a + b Else a - b
a + b happens in case condition a < b is True, otherwise, if False a - b is computed.
The grammar is not an issue here. Since I only need the algorithm to solve this problem. I am able evaluate boolean and algebraic expressions. But how can I go about solving the above problem?
Do you need to assign a+b or a-b to something?
You can do this:
int c = a < b ? a+b : a-b;
Or
int sign = a < b ? 1 : -1;
int c = a + (sign * b);
Refer to LISP language for S-express:
e.g
(if (> a b) ; if-part
(+ a b) ; then-part
(- a b)) ; else-part
Actually if you want evaluate just this simple if statement, toknize it and evaluate it, but if you want to evaluate somehow more complicated things, like nested if then else, if with experssions, multiple else, variable assignments, types, ... you need to use some parser, like LR parsers. You can use e.g Lex&Yacc to write a good parser for your own language. They support somehow complicated grammars. But if you want to know how does LR parser (or so) works, you should read into them, and see how they use their table to read tokens and parse them. e.g take a look at wiki page and see how does LR parser table works (it's something more than simple stack and is not easy to describe it here).
If your problem is just really parsing if statement, you can cheat from parser techniques, you can add empty thing after a < b, which means some action, and empty thing after else, which also means an action. When you parsed the condition, depending on correctness or wrongness you will run one of actions. By the way if you want to parse expressions inside if statement you need conditional stack, means something like SLR table.
Basically, you need to build in support for a ternary operator. IE, where currently you pop an operator, and then wait for 2 sequential values before resolving it, you need to wait for 3 if your current operation is IF, and 2 for the other operations.
To handle the if statement, you can consider the if statement in terms of C++'s ternary operator. Which formats you want your grammar to support is up to you.
a < b ? a + b : a - b
You should be able to evaluate boolean operators on your stack the way you currently evaluate arithmetic operations, so a < b should be pushed as
< a b
The if can be represented by its own symbol on the stack, we can stick with '?'.
? < a b
and the 2 possible conditions to evaluate need to separated by another operator, might as well use ':'
? < a b : + a b - a b
So now when you pop '?', you see it is the operator that needs 3 values, so put it aside as you normally would, and continue to evaluate the stack until you have 3 values. The ':' operator should be a binary operator, that simply pushes both of its values back onto the stack.
Once you have 3 values on the stack, you evaluate ? as:
If the first value is 1, push the 2nd value, throw away the third.
If the first value is 0, throw away the 2nd and push the 3rd.
Given this logical operation :
(A AND B) OR (C AND D)
Is there a way to write a similar expression without using any parentheses and giving the same result ? Usage of logical operators AND, OR, NOT are allowed.
Yes:
A and B or C and D
In most programming languages, and is taken to have higher precedence than or (this stems from the equivalence of and and or to * and +, respectively).
Of course, if your original expression had been:
(A or B) and (C or D)
you couldn't simply remove the parentheses. In this instance, you'd have to "multiply out" the factors:
A and C or B and C or A and D or B and D
How about A AND B OR C AND D? It's the same because AND takes precedence over OR.
Just don't put any parentheses, it is the same...
It can be written in two ways
A & B | C & D
Type as it is mentioned in question just remove the parenthesis it will show the same result.
We can use & for AND to multiply and | for OR to divide. Also simply you can write them without any parenthesis
How can I pass values to a given expression with several variables? The values for these variables are placed in a list that needs to be passed into the expression.
Your revised question is straightforward, simply
f ## {a,b,c,...} == f[a,b,c,...]
where ## is shorthand for Apply. Internally, {a,b,c} is List[a,b,c] (which you can see by using FullForm on any expression), and Apply just replaces the Head, List, with a new Head, f, changing the function. The operation of Apply is not limited to lists, in general
f ## g[a,b] == f[a,b]
Also, look at Sequence which does
f[Sequence[a,b]] == f[a,b]
So, we could do this instead
f[ Sequence ## {a,b}] == f[a,b]
which while pedantic seeming can be very useful.
Edit: Apply has an optional 2nd argument that specifies a level, i.e.
Apply[f, {{a,b},{c,d}}, {1}] == {f[a,b], f[c,d]}
Note: the shorthand for Apply[fcn, expr,{1}] is ###, as discussed here, but to specify any other level description you need to use the full function form.
A couple other ways...
Use rule replacement
f /. Thread[{a,b} -> l]
(where Thread[{a,b} -> l] will evaluate into {a->1, b->2})
Use a pure function
Function[{a,b}, Evaluate[f]] ## l
(where ## is a form of Apply[] and Evaluate[f] is used to turn the function into Function[{a,b}, a^2+b^2])
For example, for two elements
f[l_List]:=l[[1]]^2+l[[2]]^2
for any number of elements
g[l_List] := l.l
or
h[l_List]:= Norm[l]^2
So:
Print[{f[{a, b}], g[{a, b}], h[{a, b}]}]
{a^2 + b^2, a^2 + b^2, Abs[a]^2 + Abs[b]^2}
Two more, just for fun:
i[l_List] := Total#Table[j^2, {j, l}]
j[l_List] := SquaredEuclideanDistance[l, ConstantArray[0, Length[l]]
Edit
Regarding your definition
f[{__}] = a ^ 2 + b ^ 2;
It has a few problems:
1) You are defining a constant, because the a,b are not parameters.
2) You are defining a function with Set, Instead of SetDelayed, so the evaluation is done immediately. Just try for example
s[l_List] = Total[l]
vs. the right way:
s[l_List] := Total[l]
which remains unevaluated until you use it.
3) You are using a pattern without a name {__} so you can't use it in the right side of the expression. The right way could be:
f[{a_,b_}]:= a^2+b^2;