How to get the maximum value in an array using SQL? - postgresql

Task
Given three integers a, b, c, return the largest number obtained after inserting the following operators and brackets: +, *, ()
In other words, try every combination of a,b,c with [*+()] and return the Maximum Obtained
Example
With the numbers are 1, 2 and 3, here are some ways of placing signs and brackets:
1 * (2 + 3) = 5
1 * 2 * 3 = 6
1 + 2 * 3 = 7
(1 + 2) * 3 = 9
So the maximum value that you can obtain is 9.
Notes
The numbers are always positive.
You can use the same operation more than once.
You cannot swap the operands. For instance, in the given example you
cannot get expression (1 + 3) * 2 = 8.
I have created every combination and put it in an array.
SELECT a,b,c, ARRAY[
a * b * c,
a + b + c,
a * b + c,
a + b * c,
(a + b) * c,
a * (b + c)
] AS res
FROM expression_matter
Select result is the following:
a b c res
2 1 2 {4,5,4,4,6,6}
2 1 1 {2,4,3,3,3,4}
2 2 4 {16,8,8,10,16,12}
3 3 3 {27,9,12,12,18,18}
1 1 1 {1,3,2,2,2,2}
Now, I have to obtain the maximum value in this array. But the MAX or GREATEST functions do not working as expected. The SELECT GREATEST(ARRAY[...]) returns with same result. The SELECT MAX(ARRAY[...]) returns with the maximum value for every combination respect to all row.
I would like to obtain the maximum value of every combination in each row.

Use the GREATEST function and replace the array to list of arguments.
SELECT GREATEST(
a * b * c,
a + b + c,
a * b + c,
a + b * c,
(a + b) * c,
a * (b + c)
) AS res
FROM expression_matter
The GREATEST returns the greatest of the list of one or more expressions. See documentation here.

Related

Boolean Simplification - Why does (A + NOT(B.C)).(B + NOT(B.C)).(C + NOT(B.C)) = A + NOT B.C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
This is the answer to the equation, but I do not understand why. Please help!
If you apply the Laws of Boolean Algebra one by one, the solution is a direct result:
de Morgan´s Theorem: The complement of two terms joined together by OR is the same as the complements of two terms joined by AND, and vice versa (i.e. NOT(A + B) = NOT(A) * NOT(B) and NOT(A * B) = NOT(A) + NOT(B)).
Commutative Law: The order of joining two separate terms with AND or OR is not important.
Complement Law: A term joined with its complement with AND equals 0 respectively with OR equals 1 (i.e. A * NOT(A) = 0 and A + NOT(A) = 1).
Annulment Law: A term joined with AND with 0 equals 0 and joined with OR with a 1 equals 1 (i.e. A * 0 = 0 and A + 1 = 1).
Identity Law: A term joined with 1 by AND or with 0 by OR is equal to itself (i.e. A * 1 = A and A + 0 = A).
(there are more, but you don't need them here)
Applied to your term:
(A + NOT(B*C)) * (B + NOT(B*C)) * (C + NOT(B*C))
[with 1.] = (A + NOT(B) + NOT(C)) * (B + NOT(B) + NOT(C)) * (C + NOT(B) + NOT(C))
[with 2.] = (A + NOT(B) + NOT(C)) * (B + NOT(B) + NOT(C)) * (C + NOT(C) + NOT(B))
[with 3.] = (A + NOT(B) + NOT(C)) * (1 + NOT(C)) * (1 + NOT(B))
[with 4.] = (A + NOT(B) + NOT(C)) * 1 * 1
[with 5.] = (A + NOT(B) + NOT(C))
[with 1.] = (A + NOT(B*C))

How to know which Maple command automatically maps on list entries or not?

In Mathematica, almost all commands automatically thread (or map) over a list.
In Maple, how does one determine which command automatically acts over entries of a list or a set?
For example:
y+p*x=2*sqrt(x*y);
r:=[solve(%,y)];
This gives list of two entries (the solutions)
#r := [-p*x+(2*(1+sqrt(1-p)))*x, -p*x+(2*(1-sqrt(1-p)))*x]
Now I found that collect automatically maps on each list entry
collect(r,x);
# [(-p+2+2*sqrt(1-p))*x, (-p+2-2*sqrt(1-p))*x]
But another command does not (I just picked this one)
MmaTranslator[Mma][LeafCount](r);
#37
For the above one needs to explicitly iterate over the entries of a list or a set.
map(MmaTranslator[Mma][LeafCount],r)
#[17, 19]
Is there a way in Maple to find which command automatically threads over entries of a list or a set other than trial and error?
Maple 2018.1
I don't know of any place in the documentation that says exactly which commands will automatically map over a list.
But the collection of such commands is not large. The vast majority of commands will not automatically map over a list. Most of the ones which auto-map over a list relate to simplication or related manipulation of expressions. The collection of commands which auto-map over a list contains at least these:
collect, combine, expand,
evala, evalc, evalf,
factor, normal, radnormal, rationalize, simplify
The auto-mapping over lists for those commands is mostly a convenience to provide a shorter syntax than wrapping explicitly with the map command.
There are also commands which preserve structure (unless explicitly
told, via options, that the outer list structure is the thing to alter) and thus usually accomplish the same thing for a list as mapping over the list:
convert, eval, evalindets, subs, subsindets
Modern Maple has another shorter syntax which can map a command over a list (or a set, or a Vector, etc). It is called the "elementwise" operation, and its syntax consists of appending ~ (tilde) to the command.
Eg,
discont~( [ csc(x), sec(x) ], x );
[{Pi _Z1~}, {Pi _Z2~ + 1/2 Pi}]
As far as your other example goes, note that LeafCount computes a value (metric) for the first argument considered as a single expression. But a list of items is still a single expression. So it certainly should not be surprising that (without the ~) it acts on the list as a whole, rather than automatically mapping over it. It counts the enclosing list as an additional "leaf".
MmaTranslator:-Mma:-LeafCount( L0 );
8
L0 := [ sin(x), 1/2*x*cos(x) ]:
MmaTranslator:-Mma:-LeafCount~( L0 );
[2, 5]
map( MmaTranslator:-Mma:-LeafCount, L0 );
[2, 5]
For an example similar to your original there is no difference in applying collect (which auto-maps) and applying it elementwise with collect~. Here, the first two results are the same because the addtional argument, x, happens to be a scalar. Eg,
r := [p*x+(2*(x^2+p^2))*x, p*x+(2*(x^2-p^2))*x]:
collect(r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
collect~(r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
map(collect, r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
I should mention that the above examples will behave differently if the second argument is a list such as [x,p] rather than a scalar such as x.
s := [a*b+(2*(a^2*b+b^2))*a, a*b+(2*(a^2*b-b^2))*a]:
collect(s, [a,b]);
3 2 3 2
[2 b a + (2 b + b) a, 2 b a + (-2 b + b) a]
map(collect, s, [a,b]);
3 2 3 2
[2 b a + (2 b + b) a, 2 b a + (-2 b + b) a]
collect~(s, [a,b]);
3 2 2 3
[2 b a + (2 b + b) a, -2 a b + (2 a + a) b]
zip(collect, s, [a,b]);
3 2 2 3
[2 b a + (2 b + b) a, -2 a b + (2 a + a) b]
In the above, the elementiwise collect~ example acts like zip when the second argument is also a list. That is, the first item in the first argument is collected wrt the first item in the second argument, and the second item in the first argument is collected wrt to the second item in the second argument.
Another feature of the elementwise operator syntax is that it will not map the command over the operands of a scalar expression (ie. not a list, set, Vector, etc). This is in stark contrast to map, which can be used to map an operation over the operands of an expression.
Here are two examples where map applies the command to the operands of a scalar expression, while using elementwise ~ gets the command applied only to the scalar expression itself. In the first example the operands are the summands of a sum of terms. In the second example the operands are the arguments of an unevaluated function call.
T := x^2 * sin(x) + y^2 * cos(x):
F( T );
2 2
F(x sin(x) + y cos(x))
F~( T );
2 2
F(x sin(x) + y cos(x))
map( F, T );
2 2
F(x sin(x)) + F(y cos(x))
G( arctan(a, b) );
G(arctan(a, b))
G~( arctan(a, b) );
G(arctan(a, b))
map( G, arctan(a, b) );
arctan(G(a), G(b))
So, if you don't want to map a command inadvertantly over the operands of a scalar expression (addend, multiplicands, etc) then you can use the elementwise ~ syntax without having to first test whether the first expression is a scalar or a list (etc).
Again, if there is an additional argument then it makes a difference whether it is a scalar to a list.
F( T, a );
F(sin(x) + cos(x), a)
F~( T, a );
F(sin(x) + cos(x), a)
map( F, T, a );
F(sin(x), a) + F(cos(x), a)
F( T, [a,b] );
F(sin(x) + cos(x), [a, b])
map( F, T, [a,b] );
F(sin(x), [a, b]) + F(cos(x), [a, b])
F~( T, [a,b] );
[F(sin(x) + cos(x), a), F(sin(x) + cos(x), b)]
zip( F, T, [a,b] );
[F(sin(x) + cos(x), a), F(sin(x) + cos(x), b)]

how to modify self-defined scala operators' precedence

Is it possible to modify the precedence of any self-defined operators?
For example, I implement elementary arithmetic with totally self-defined operators.
case class Memory(name:String){
var num:Num = null
def <<=(x:Num): Unit = {
println(s"assign ${x.value}")
this.num = x
}
}
case class Num(var value:Int) {
def +|+(x:Num) = {
println("%d + %d = %d".format( value,x.value,x.value + value ))
Num(value + x.value)
}
def *|*(x:Num) = {
println("%d * %d = %d".format( value,x.value,x.value * value ))
Num(value * x.value)
}
}
val m1 = Memory("R")
val a = Num(1)
val b = Num(3)
val c = Num(9)
val d = Num(12)
m1 <<= a *|* b +|+ c +|+ d *|* a
println("final m1 ",m1.num.value)
The results are
1 * 3 = 3
3 + 9 = 12
12 * 1 = 12
12 + 12 = 24
assign 24
(final m1 ,24)
Apparently the precedence is correct. I want *|* be the same precedence as * and +|+ the same as +, <<= is equivalent as = as well. How scala figure it out?
Answering the question about modyfing operator precedence - to change it you basically just have to change the first character of your custom operator - this is how scala figures out precedense for infix operators, by just looking at the first character. So if you eg. add an operator *|+:
It will have same precedence as *|*, like with * and *.
"Bigger" precedence than +|+, just like with * and +.
Unfortunately there is no other way to deal with it right now. No custom annotations/weights and so on to avoid making reading code too fuzzy.
The precedence rules are very well summarized here - Operator precedence in Scala.
About your issue though - you get the right results.
*|*, as well as * are left-associative operators and their first character is *, so they have equal precedense.
Your operation:
a *|* b +|+ c +|+ d *|* a
Translates to
a * b + c + d * a, which is 1 * 3 + 9 + 12 * 1.
Applying standard precedence rules - (a*b) + c + (d*a) result is 24.

understanding aggregate in Scala

I am trying to understand aggregate in Scala and with one example, i understood the logic, but the result of second one i tried confused me.
Please let me know, where i went wrong.
Code:
val list1 = List("This", "is", "an", "example");
val b = list1.aggregate(1)(_ * _.length(), _ * _)
1 * "This".length = 4
1 * "is".length = 2
1 * "an".length = 2
1 * "example".length = 7
4 * 2 = 8 , 2 * 7 = 14
8 * 14 = 112
the output also came as 112.
but for the below,
val c = list1.aggregate(1)(_ * _.length(), _ + _)
I Thought it will be like this.
4, 2, 2, 7
4 + 2 = 6
2 + 7 = 9
6 + 9 = 15,
but the output still came as 112.
It is ideally doing whatever the operation i mentioned at seqop, here _ * _.length
Could you please explain or correct me where i went wrong.?
aggregate should be used to compute only associative and commutative operations. Let's look at the signature of the function :
def aggregate[B](z: ⇒ B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B): B
B can be seen as an accumulator (and will be your output). You give an initial output value, then the first function is how to add a value A to this accumulator and the second is how to merge 2 accumulators. Scala "chooses" a way to aggregate your collection but if your aggregation is not associative and commutative the output is not deterministic because the order matter. Look at this example :
val l = List(1, 2, 3, 4)
l.aggregate(0)(_ + _, _ * _)
If we create one accumulator and then aggregate all the values we get 1 + 2 + 3 + 4 = 10 but if we decide to parallelize the process by splitting the list in halves we could have (1 + 2) * (3 + 4) = 21.
So now what happens in reality is that for List aggregate is the same as foldLeft which explains why changing your second function didn't change the output. But where aggregate can be useful is in Spark for example or other distributed environments where it may be useful to do the folding on each partition independently and then combine the results with the second function.

Understanding the scala substitution model through the use of sumInts method

I'm doing a scala course and one of the examples given is the sumInts function which is defined like :
def sumInts(a: Int, b: Int) : Int =
if(a > b) 0
else a + sumInts(a + 1 , b)
I've tried to understand this function better by outputting some values as its being iterated upon :
class SumInts {
def sumInts(a: Int, b: Int) : Int =
if(a > b) 0 else
{
println(a + " + sumInts("+(a + 1)+" , "+b+")")
val res1 = sumInts(a + 1 , b)
val res2 = a
val res3 = res1 + res2
println("res1 is : "+res1+", res2 is "+res2+", res3 is "+res3)
res3
}
}
So the code :
object SumIntsMain {
def main(args: Array[String]) {
println(new SumInts().sumInts(3 , 6));
}
}
Returns the output :
3 + sumInts(4 , 6)
4 + sumInts(5 , 6)
5 + sumInts(6 , 6)
6 + sumInts(7 , 6)
res1 is : 0, res2 is 6, res3 is 6
res1 is : 6, res2 is 5, res3 is 11
res1 is : 11, res2 is 4, res3 is 15
res1 is : 15, res2 is 3, res3 is 18
18
Can someone explain how these values are computed. I've tried by outputting all of the created variables but still im confused.
manual-human-tracer on:
return sumInts(3, 6) | a = 3, b = 6
3 > 6 ? NO
return 3 + sumInts(3 + 1, 6) | a = 4, b = 6
4 > 6 ? NO
return 3 + (4 + sumInts(4 + 1, 6)) | a = 5, b = 6
5 > 6 ? NO
return 3 + (4 + (5 + sumInts(5 + 1, 6))) | a = 6, b = 6
6 > 6 ? NO
return 3 + (4 + (5 + (6 + sumInts(6 + 1, 6)))) | a = 7, b = 6
7 > 6 ? YEEEEES (return 0)
return 3 + (4 + (5 + (6 + 0))) = return 18.
manual-human-tracer off.
To understand what recursive code does, it's not necessary to analyze the recursion tree. In fact, I believe it's often just confusing.
Pretending it works
Let's think about what we're trying to do: We want to sum all integers starting at a until some integer b.
a + sumInts(a + 1 , b)
Let us just pretend that sumInts(a + 1, b) actually does what we want it to: Summing the integers from a + 1 to b. If we accept this as truth, it's quite clear that our function will handle the larger problem, from a to b correctly. Because clearly, all that is missing from the sum is the additional term a, which is simply added. We conclude that it must work correctly.
A foundation: The base case
However, this sumInts() must be built on something: The base case, where no recursion is involved.
if(a > b) 0
Looking closely at our recursive call, we can see that it makes certain assumptions: we expect a to be lower than b. This implies that the sum will look like this: a + (a + 1) + ... + (b - 1) + b. If a is bigger than b, this sum naturally evaluates to 0.
Making sure it works
Seeing that sumInts() always increases a by one in the recursive call guarantees, that we will in fact hit the base case at some point.
Noticing further, that sumInts(b, b) will be called eventually, we can now verify that the code works: Since b is not greater than itself, the second case will be invoked: b + sumInts(b + 1, b). From here, it is obvious that this will evaluate to: b + 0, which means our algorithm works correctly for all values.
You mentioned the substitution model, so let's apply it to your sumInts method:
We start by calling sumInts(3,4) (you've used 6 as the second argument, but I chose 4, so I can type less), so let's substitute 3 for a and 4 for b in the definition of sumInts. This gives us:
if(3 > 4) 0
else 3 + sumInts(3 + 1, 4)
So, what will the result of this be? Well, 3 > 4 is clearly false, so the end result will be equal to the else clause, i.e. 3 plus the result of sumInts(4, 4) (4 being the result of 3+1). Now we need to know what the result of sumInts(4, 4) will be. For that we can substitute again (this time substituting 4 for a and b):
if(4 > 4) 0
else 4 + sumInts(4 + 1, 4)
Okay, so the result of sumInts(4,4) will be 4 plus the result of sumInts(5,4). So what's sumInts(5,4)? To the substitutionator!
if(5 > 4) 0
else 5 + sumInts(5 + 1, 4)
This time the if condition is true, so the result of sumInts(5,4) is 0. So now we know that the result of sumInts(4,4) must be 4 + 0 which is 4. And thus the result of sumInts(3,4) must be 3 + 4, which is 7.