Suppose we have these comparison operators:
export enum ComparisonOperators {
MATCH_CONTAINS = 'contains',
MATCH_DOES_NOT_CONTAIN = 'not_contains',
MATCH_EQUALS = 'equals',
MATCH_NOT_EQUALS = 'not_equals',
MATCH_STARTS_WITH = 'starts_with',
MATCH_DOES_NOT_START_WITH = 'not_starts_with',
MATCH_ENDS_WITH = 'ends_with',
MATCH_DOES_NOT_END_WITH = 'not_ends_with',
MATCH_REGEX = 'matches_regex',
DOES_NOT_MATCH_REGEX = 'not_matches_regex',
}
And suppose we have this Or(And) logical statement in a Json format:
{
nodeType: 'OR',
children: [
{
nodeType: 'AND',
children: [
{
operator: ComparisonOperators.MATCH_EQUALS,
field: 'A',
nodeType: 'LEAF',
value: 'abc',
},
{
operator: ComparisonOperators.MATCH_STARTS_WITH,
field: 'B',
nodeType: 'LEAF',
value: 'rfg',
},
],
},
{
nodeType: 'AND',
children: [
{
operator: ComparisonOperators.MATCH_DOES_NOT_END_WITH,
field: 'C',
nodeType: 'LEAF',
value: 'esa',
},
{
operator: ComparisonOperators.MATCH_REGEX,
field: 'D',
nodeType: 'LEAF',
value: '/[0-9]{4}/.source',
},
],
},
],
}
Meaning (in simple language):
('A' equals 'abc' AND 'B' startsWith 'rfg') OR ('C' doesNotEndWith 'esa' AND 'D' matchRegex '/[0-9]{4}/.source')
I need to create an algorithm to convert
OR(AND) = (-- AND -- AND ...) OR (-- AND -- AND ...) OR ...
to
AND(OR) = (-- OR -- OR ...) AND (-- OR -- OR ...) AND ...
And vice versa
Converting AND(OR) to OR(AND) is easy => (a+b) * (c+d) = a*c + a*d + b*c + b*d
But I can't find how to do the reverse ?
As you pointed out, (a+b) * (c+d) = a*c + a*d + b*c + b*d.
You said you cannot find how to do the inverse. So let's think about why the above statement is true.
This is because the following holds:
(a+b) * c = a*c + b*c. Thus, (a+b) * (c+d) = a*(c+d) + b*(c+d) = a*c + a*d + b*c + b*d.
But keep in mind, that we are not operating on addition and multiplication, but on logical AND and OR operations. This means that perhaps, not only AND distributes over OR, but maybe OR distributes over AND.
Indeed it is true, that (a*b) + c = a+c * b+c. (Can you see why? If not, simply consider all 8 possibilities.
Thus it follows, that (a*b) + (c*d) = a+c * a+d * b+c * b+d. So in fact, you can do exactly the same thing you already mentioned, but with the operations flipped. Isn't that neat?
Now this means, that converting from AND(OR) to OR(AND) and then back to AND(OR) will very likely result in a much longer output than the original input, but reducing the length of this output is probably a very hard problem to solve algorithmically and I doubt is required in your task.
Related
The problem is not about programming, but about algorithm. We need to solve |x-y| in unary code on the Turing machine. For example if we have 111 * 11 on the tape. * as a number separator, then we need to leave 1. I understand that when we have a space left or right near the *, the program should remove the * and terminate, but I always get it to work if only the numbers on the right are larger or vice versa. To make the same algorithm work and if the ribbon is 11 * 1 and 1 * 11 does not work.
If it is possible to write a system command:
q1 1 -> q2 _ R
Or with a function table as in the screenshot
I would apply this algorithm:
Move to the right and ensure that there is a "1" at both sides of the "*"
Wipe out the rightmost "1" and then walk back to wipe out the leftmost "1"
Repeat
When the condition in the first scan is not true, then wipe out the "*" and stop.
This leads to the following transition table:
State
In
Out
Move
New State
start
1
1
→
toright
start
*
_
→
stop
toright
1
1
→
toright
toright
*
*
→
toright
toright
_
_
←
delright
delright
1
_
←
toleft
delright
*
_
←
stop
toleft
1
1
←
toleft
toleft
*
*
←
toleft
toleft
_
_
→
delleft
delleft
1
_
→
start
Here is a little implementation in JavaScript:
class Turing {
constructor(str, idx=0) {
this.tape = Array.from(str);
this.idx = idx;
}
read() {
return this.tape[this.idx] || " ";
}
writeAndMove(chr, move) {
this.tape[this.idx] = chr;
this.idx += (move > 0) - (move < 0);
}
toString() {
return this.tape.join("").trim();
}
static run(input, transitions, state, endState) {
const turing = new Turing(input);
let move, chr;
while (state !== endState) {
chr = turing.read();
[,,chr, move, state] = transitions.find(t => t[0] === state && t[1] === chr);
turing.writeAndMove(chr, move);
}
return turing.toString();
}
}
const transitions = [
// STATE IN OUT MOVE NEWSTATE
// --------- ---- --- -- ----------
["start" , "1", "1", +1, "toright" ],
["start" , "*", " ", +1, "stop" ],
["toright" , "1", "1", +1, "toright" ],
["toright" , "*", "*", +1, "toright" ],
["toright" , " ", " ", -1, "delright"],
["delright", "1", " ", -1, "toleft" ],
["delright", "*", " ", -1, "stop" ],
["toleft" , "1", "1", -1, "toleft" ],
["toleft" , "*", "*", -1, "toleft" ],
["toleft" , " ", " ", +1, "delleft" ],
["delleft" , "1", " ", +1, "start" ],
];
// Demo run
const output = Turing.run("1*111", transitions, "start", "stop");
console.log(output);
I want to write a function that given a set of numbers, for example:
2, 3
It returns all the combinations of operations with +, -, *, and /.
The result for these two numbers would be:
2+3
2-3
2*3
2/3
For the numbers:
2, 3, 4
it would be:
(2+3)+4
(2+3)-4
(2+3)*4
(2+3)/4
(2-3)+4
(2-3)-4
(2-3)*4
(2-3)/4
...
2+(3+4)
2+(3*4)
2+(3-4)
2+(3/4)
...
3+(2+4)
3+(2*4)
3+(2-4)
3+(2/4)
...
and so on
The order of the operators doesn't matter, the point is to obtain all the results from all the possible combinations of operations.
I would tackle this by using Reverse Polish Notation, where you can just append operators and operands to a string while being considerate to a few simple rules.
For example, the expression 2 + (3 * 4) would be 2 3 4 * + in Reverse Polish Notation. On the other hand, (2 + 3) * 4 would be 2 3 + 4 *.
If we already have a partial expression, we can either add an operand or an operator.
Adding an operand can always be done and will increase the size of the stack by 1. On the other hand, adding an operator decreases the size of the stack by 1 (remove the two top-most operands and add the result) and can therefore only be done if the stack has at least two entries. At the end, to form a valid expression, the stack size has to be exactly 1.
This motivates a recursive function with the following interface:
getSubexpressions(remainingOperands, currentStackSize)
The function returns a list of subexpressions that can be appended to a partial expression with stack size currentStackSize and using the operands remainingOperands.
The base case of this recursive function is when there are no more remaining operands and the stack size is 1:
if remainingOperands = ∅ and currentStackSize = 1
return { "" }
In this case, we can only add the empty string to the expression.
In all other cases, we need to gather a set of subexpressions
subexpressions = { } // initialize an empty set
If we can add an operator, we can simply append it:
if currentStackSize >= 2
for each possible operator o
subexpressions.add(o + getSubexpressions(remainingOperands, currentStackSize - 1))
The notation o + getSubexpressions(remainingOperands, currentStackSize - 1) is shorthand for concatenating the operand o with all subexpressions returned from the call to getSubexpressions().
We are almost there. The last remaining bit is to add potential operands:
for each o in remainingOperands
subexpressions.add(o + getSubexpressions(remainingOperands \ { o }, currentStackSize + 1))
The notation remainingOperands \ { o } stands for set difference, i.e., the set of remaining operands without o.
That's it. In full:
getSubexpressions(remainingOperands, currentStackSize)
if remainingOperands = ∅ and currentStackSize = 1
return { "" }
subexpressions = { } // initialize an empty set
if currentStackSize >= 2
for each possible operator o
subexpressions.add(o + getSubexpressions(remainingOperands, currentStackSize - 1))
for each o in remainingOperands
subexpressions.add(o + getSubexpressions(remainingOperands \ { o }, currentStackSize + 1))
return subexpressions
This recursive call will usually have overlapping subcalls. Therefore, you can use memoization to cache intermediate results instead of re-calculating them over and over.
Here is a proof-of-concept implementation without memoization in C#. Expecially the operand management can be designed more efficiently with more appropriate data structures:
static void Main(string[] args)
{
foreach (var expr in GetSubexpressions(new List<string> { "1", "2", "3" }, 0, new StringBuilder()))
{
Console.WriteLine(expr);
}
}
static char[] operators = { '+', '-', '*', '/' };
static IEnumerable<StringBuilder> GetSubexpressions(IList<string> remainingOperands, int currentStackSize, StringBuilder sb)
{
if (remainingOperands.Count() == 0 && currentStackSize == 1)
{
yield return sb;
yield break;
}
if(currentStackSize >= 2)
{
foreach (var o in operators)
{
sb.Append(o);
foreach (var expr in GetSubexpressions(remainingOperands, currentStackSize - 1, sb))
yield return expr;
sb.Remove(sb.Length - 1, 1);
}
}
for (int i = 0; i < remainingOperands.Count; ++i)
{
var operand = remainingOperands[i];
remainingOperands.RemoveAt(i);
sb.Append(operand);
foreach (var expr in GetSubexpressions(remainingOperands, currentStackSize + 1, sb))
yield return expr;
sb.Remove(sb.Length - operand.Length, operand.Length);
remainingOperands.Insert(i, operand);
}
}
The program prints the following output:
12+3+
12-3+
12*3+
12/3+
12+3-
12-3-
12*3-
12/3-
12+3*
12-3*
12*3*
12/3*
12+3/
12-3/
12*3/
12/3/
123++
123-+
123*+
123/+
123+-
123--
123*-
123/-
123+*
123-*
123**
123/*
123+/
123-/
123*/
123//
13+2+
13-2+
13*2+
13/2+
13+2-
13-2-
13*2-
13/2-
13+2*
13-2*
13*2*
13/2*
13+2/
13-2/
13*2/
13/2/
132++
132-+
132*+
132/+
132+-
132--
132*-
132/-
132+*
132-*
132**
132/*
132+/
132-/
132*/
132//
21+3+
21-3+
21*3+
21/3+
21+3-
21-3-
21*3-
21/3-
21+3*
21-3*
21*3*
21/3*
21+3/
21-3/
21*3/
21/3/
213++
213-+
213*+
213/+
213+-
213--
213*-
213/-
213+*
213-*
213**
213/*
213+/
213-/
213*/
213//
23+1+
23-1+
23*1+
23/1+
23+1-
23-1-
23*1-
23/1-
23+1*
23-1*
23*1*
23/1*
23+1/
23-1/
23*1/
23/1/
231++
231-+
231*+
231/+
231+-
231--
231*-
231/-
231+*
231-*
231**
231/*
231+/
231-/
231*/
231//
31+2+
31-2+
31*2+
31/2+
31+2-
31-2-
31*2-
31/2-
31+2*
31-2*
31*2*
31/2*
31+2/
31-2/
31*2/
31/2/
312++
312-+
312*+
312/+
312+-
312--
312*-
312/-
312+*
312-*
312**
312/*
312+/
312-/
312*/
312//
32+1+
32-1+
32*1+
32/1+
32+1-
32-1-
32*1-
32/1-
32+1*
32-1*
32*1*
32/1*
32+1/
32-1/
32*1/
32/1/
321++
321-+
321*+
321/+
321+-
321--
321*-
321/-
321+*
321-*
321**
321/*
321+/
321-/
321*/
321//
I am using Kotlintest and data tables to test an application that uses Kotlin, SpringBoot and Gradle because the syntax is way more concise than ParameterizedJunitTests when you have complex data in your tables.
Is there a way to use the parameter names in the method-titles like there is for parameterized tests in JUnit? Moreover, all my test-executions are listed as one test, but I would like to have a row in my test results per data table row. I found neither of the two topics in the Documentation.
To make things clearer an example with Kotlintest:
class AdditionSpec : FunSpec() {
init {
test("x + y is sum") {
table(
headers("x", "y", "sum"),
row(1, 1, 2),
row(50, 50, 100),
row(3, 1, 2)
).forAll { x, y, sum ->
assertThat(x + y).isEqualTo(sum)
}
}
}
}
and a corresponding example with JUnit:
#RunWith(Parameterized::class)
class AdditionTest {
#ParameterizedTest(name = "adding {0} and {1} should result in {2}")
#CsvSource("1,1,2", "50, 50, 100", "3, 1, 5")
fun testAdd(x: Int, y: Int, sum: Int) {
assertThat(x + y).isEqualTo(sum);
}
}
With 1/3 failures:
Kotlintest:
Junit:
Is there something similar to #ParameterizedTest(name = "adding {0} and {1} should result in {2}") in kotlintest when using data tables?
You can reverse nesting. Instead of having table within test, simply nest test within table.
class AdditionSpec : FunSpec() {
init {
context("x + y is sum") {
table(
headers("x", "y", "sum"),
row(1, 1, 2),
row(50, 50, 100),
row(3, 1, 2)
).forAll { x, y, sum ->
test("$x + $y should be $sum") {
x + y shouldBe sum
}
}
}
}
}
This is possible using the FreeSpec and the minus operator like this:
class AdditionSpec : FreeSpec({
"x + y is sum" - {
listOf(
row(1, 1, 2),
row(50, 50, 100),
row(3, 1, 2)
).map { (x: Int, y: Int, sum: Int) ->
"$x + $y should result in $sum" {
(x + y) shouldBe sum
}
}
}
})
This gives this output in Intellij:
See the documentation on this here
My goal is to integrate the following double integral in R:
Here is the doubleintegral
I dont know how to implement the upper bound in R. (min(0,t))
The way I calculatet the integral is:
library('cubature')
adaptIntegrate(doubleintegralfunction, lowerLimit = c(-2.5, -2), upperLimit = c(0, 2), x=x,r=r,m=m,n=n)$integral
Dont worry about the different boundaries, the only one that i would like to change is the 0 to min(0,t). Any ideas?
for illustration copy past this into google:
((-x)^(2-1)*(y-x)^(2-1)*exp((16.8+72.9)*x))*exp(-72.9*y- (-0.036-y-0.0332*1+0.5*0.0311^2*1)^2/(2*0.0311^2*1))
Thank you for your help
Here's an approach, but I'm not sure how to check if the answer is correct. The two implementations give the same answer, which is promising. The first implementation has everything inside the dx integral, while the second implementation splits out the dt portion, as the integral is written.
n=2
m=2
nd=16.8
nw=72.9
r = -0.036
mu = 0.0332
s = 1
sig = 0.0311
g <- function(t) {
if (t<0) t
else 0
}
integrate(function(t) {
sapply(t, function(t) {
integrate(function(x)
# (-x)^?(2-?1) *?
# (y-?x)^?(2-?1)*?
# exp(?(16.8+?72.9)*?x) *?
# exp(?(-72.9)*?y-?((-0.036)-?y-?0.0332*?1+?0.5*?0.0311^?2*?1)^?2/?(2*?0.0311^?2*?1))
(-x)^(n-1) *
(t-x)^(m-1)*
exp((nw+nd)*x) *
exp(-nw*t-(r-t-mu*s+0.5*sig^2*s)^2 / (2*sig^2*s) ),
-Inf, g(t))$value
}
)
}, -Inf, Inf)
integrate(function(t) {
sapply(t, function(t) {
integrate(function(x)
# (-x)^?(2-?1) *?
# (y-?x)^?(2-?1)*?
# exp(?(16.8+?72.9)*?x) *?
# exp(?(-72.9)*?y-?((-0.036)-?y-?0.0332*?1+?0.5*?0.0311^?2*?1)^?2/?(2*?0.0311^?2*?1))
(-x)^(n-1) *
(t-x)^(m-1)*
exp((nw+nd)*x) ,
-Inf, g(t))$value
}
) *
exp(-nw*t-(r-t-mu*s+0.5*sig^2*s)^2 / (2*sig^2*s) )
}, -Inf, Inf)
ref: http://www.pitt.edu/~njc23/Lecture7.pdf
Since I don't quite know the language of these types of algorithms (i.e. how to google this), I'll just demonstrate what I'm looking for:
I have a three arrays (source arrays are of not equal lengths):
$array1 = array('A', 'B', 'C', 'D');
$array2 = array('x', 'y', 'z');
$array3 = array('1', '2', '3');
I would like all possible combinations of these arrays where:
No more than one element from each source array is taken.
The order of array1, array2, array3 is never broken (ABC always comes before xyz always comes before 123).
So the result would be:
array(
array('A', 'x', '1'),
array('A', 'x', '2'),
array('A', 'x', '3'),
array('A', 'y', '1'),
// etc ...
// But I also need all the partial sets, as long as the rule about
// ordering isn't broken i.e.:
array('B'),
array('B', 'x'),
array('B', 'x', '1'),
array('x'),
array('x', '1'),
array('1'),
);
The order of the results doesn't matter to me.
Working in php, but similar language or pseudo code is fine of course. Or I'd just take a tip on what specific types of permutation/combination algorithms I should be looking at.
I'd say these are Cartesian products. Generating them is quite easy.
for fixed number of arrays (in Perl):
for my $a(#arrayA) {
for my $b(#arrayB) {
push #result, [$a, $b];
}
}
general procedure: Assume #partial is an array for Cartesian product of A1 x A2 x ... x An and we want A1 x ... x An x An+1
for my $a(#partial) {
for my $b(#An_plus_1) {
push #result, [#$a, $b];
}
}
This would obviously need to iterate over all the arrays.
Now, that you want also to omit some of the elements in the sets, you just twist it a little. In the first method, you can just add another element to each of the arrays (undef is obvious choice, but anything will do) and then filter out these elements in the result sets. In the second method, it is even easier: You just add #partial and map { [$_] } #An_plus_1 to the result (or, in English, all the sets resulting from the partial Cartesian product of A1 x ... x An plus the single element sets made form the elements of the new set).
With RBarryYoung's hint, this is the shortest way to produce them, bash (and sed, to remove D, w, and 4):
echo {A..D}{w..z}{1..4} | sed 's/[Dw4]//g'
A1 A2 A3 A Ax1 Ax2 Ax3 Ax Ay1 Ay2 Ay3 Ay Az1 Az2 Az3 Az
B1 B2 B3 B Bx1 Bx2 Bx3 Bx By1 By2 By3 By Bz1 Bz2 Bz3 Bz
C1 C2 C3 C Cx1 Cx2 Cx3 Cx Cy1 Cy2 Cy3 Cy Cz1 Cz2 Cz3 Cz
1 2 3 x1 x2 x3 x y1 y2 y3 y z1 z2 z3 z
Another, easy way, is SQL, which does it by default:
SELECT upper, lower, num
FROM uppers, lowers, numbers
WHERE upper in ('A', 'B', 'C', ' ')
AND lower in (' ', 'x', 'y', 'z')
AND (number in (1, 2, 3) OR number IS NULL);
If your tables only contain 'A,B,C, ,' and 'x,y,z, ,' and '1,2,3, ' it is much shorter:
SELECT upper, lower, num
FROM uppers, lowers, numbers;
Another word, beside cartesian product, for this combinations is cross product.
For an unknown number of unknown size of Lists/Sequences/other collections, I would recommend an Iterator - if PHP has such things. Here is an implementation in Scala:
class CartesianIterator (val ll: Seq[Seq[_]]) extends Iterator [Seq[_]] {
var current = 0
def size = ll.map (_.size).product
lazy val last: Int = len
def get (n: Int, lili: Seq[Seq[_]]): List[_] = lili.length match {
case 0 => List ()
case _ => {
val inner = lili.head
inner (n % inner.size) :: get (n / inner.size, lili.tail)
}
}
override def hasNext () : Boolean = current != last
override def next (): Seq[_] = {
current += 1
get (current - 1, ll)
}
}
val ci = new CartesianIterator (List(List ('A', 'B', 'C', 'D', ' '), List ('x', 'y', 'z', ' '), List (1, 2, 3, 0)))
for (c <- ci) println (c)
List(A, x, 1)
List(B, x, 1)
List(C, x, 1)
List(D, x, 1)
List( , x, 1)
List(A, y, 1)
List(B, y, 1)
...
List( , z, 0)
List(A, , 0)
List(B, , 0)
List(C, , 0)
List(D, , 0)
List( , , 0)
A wrapper could be used to remove the '0' and ' ' from the output.