Polynomial-time logic puzzle using AND/OR/NOT to create <= on N inputs? - boolean-logic

So let's say you have n boolean inputs of x1, x2, x3, ..., xn. How do you determine that <= k of your boolean inputs are True using only And/Or/Not logic gates, and doing so in polynomial time?
I'm quite honestly befuddled.

There are many ways to do it. One is to (recursively) make two nets:
one (A) determining that <= k-1 of boolean inputs x1 ... x[n-1] are True.
another (B) determining that <= k of boolean inputs x1 ... x[n-1] are True.
Connect them as (B And Not x[n]) Or A

Related

MySQL GROUP BY if Multiple Numbered Columns are Close to Each Other (+/- 1)

I have a mysql table with a large list of coordinates (x, y, z). I want to find the most common spots, but when the same place is logged, it isn't identical. For example, x could be 496.0481 or 496.3904, but that is actually the same place.
When I do the following query I get a list of the absolute exact matches, but those are very few and far between:
SELECT x, y, z, COUNT(*) AS coords
FROM coordinates
GROUP BY x, y, z
ORDER BY coords DESC
LIMIT 10;
How can I adjust this to be grouped by each of x, y, and z to be +/- 1 to catch a larger area? I've tried a mix of IF and BETWEEN statements but can't seem to get anything to work.
If I do GROUP BY round(x), round(y), round(z), that gets a larger range but doesn't capture if the number goes from 496 to 497 even if they are just slightly different.
Thanks in advance for the help.
Very naive way:
select t1.x as x1, t1.y as y1, t1.z as z1, t2.x as x2, t2.y as y2, t2.z as z2
from coordinates t1
join coordinates t2 on sqrt(power(t2.x-t1.x, 2) + power(t2.y-t1.y, 2) + power(t2.z-t1.z, 2)) <= 1
For each coordinates (t1) query finds all other coordinates (t2) that dinstanced less or equal than 1 from each other.
But this query has very bad performance: O(n^2)

Boolean Logic and Truth Tables

I have been Googling around and haven't been able to find a solution. If anyone can link me or explain this, I'd appreciate it.
I have this expression:
¬aΛb | aΛ¬b. Λ is AND, ¬ is NOT.
The truth table is:
A B Expression
--------------
T T F
T F T
F T F
F F T
I am confused as to why they aren't all FALSE. For example, if I were to consider a and b as false: ¬a and ¬b gets precedence, so they become true. But ¬a (TRUE) Λ b (FALSE) is FALSE. And since Λ gets precedence, a (FALSE) Λ ¬b (TRUE) is again FALSE. So FALSE | FALSE = FALSE, right?
Likewise, for a|b|c|d|e, where | is OR. Why is it that when only d is FALSE, and the other are true:
T T T F T
= FALSE
The calculator you're using uses | to mean NAND, not OR. You should use + for OR. Then the truth table comes out as expected. x NAND y is TRUE except when x AND y are true; and NAND has the same precedence as AND, so without parentheses the operators bind leftmost first. A fully parenthesized version of your formula is:
((((not a) and b) nand a) and (not b))
Generating a truth table based on this gives the observed result.

Can Octave combine elements and indices in expressions?

I'd like to create a matrix of elements with each value in column i the ith power of the value in column 1. Easy with a for loop, but is there a way to combine matrix elements and their indices in expressions?
Do you mean something like this?
M = M(:,1) .^ (1:size(M,2));
It is easy to generate an array of indices to manipulate and/or operate on.
Note: For older versions of MATLAB the above gives an error, you need to use bsxfun:
M = bsxfun(#power, M(:,1), 1:size(M,2));
Note 2: If your inputs are v=[3;5;7] and n=3 you can translate the above to
M = v .^ (1:n);
What about this:
F = #(x, n) bsxfun (#realpow, x(:), 1:n);
Example:
>> F ([3;5;7], 3)
ans =
3 9 27
5 25 125
7 49 343

MySQL multiple columns in IN clause

I have a database with four columns corresponding to the geographical coordinates x,y for the start and end position. The columns are:
x0
y0
x1
y1
I have an index for these four columns with the sequence x0, y0, x1, y1.
I have a list of about a hundred combination of geographical pairs. How would I go about querying this data efficiently?
I would like to do something like this as suggested on this SO answer but it only works for Oracle database, not MySQL:
SELECT * FROM my_table WHERE (x0, y0, x1, y1) IN ((4, 3, 5, 6), ... ,(9, 3, 2, 1));
I was thinking it might be possible to do something with the index? What would be the best approach (ie: fastest query)? Thanks for your help!
Notes:
I cannot change the schema of the database
I have about 100'000'000 rows
EDIT:
The code as-is was actually working, however it was extremely slow and did not take advantage of the index (as we have an older version of MySQL v5.6.27).
To make effective use of the index, we could rewrite the IN predicate
example
(x0, y0, x1, y1) IN ((4, 3, 5, 6),(9, 3, 2, 1))
Like this:
( ( x0 = 4 AND y0 = 3 AND x1 = 5 AND y1 = 6 )
OR ( x0 = 9 AND y0 = 3 AND x1 = 2 AND y1 = 1 )
)
EDIT
Newer versions of MySQL optimizer fix the performance problem; generate execution plans that make more effective use of available indexes.
The (a,b) IN ((7,43),(7,44),(8,1)) syntax has been supported in MySQL many versions back, but there were performance problems with it (at least with with non-trivial sets) because of the suboptimal execution plan generated by the optimizer.
But the optimizer has been improved in newer versions of MySQL; the newer optimizer can generate more efficient execution plans.
Note a similar related problem with OR constructs. Here's an example query intended to get the "next page" of 20 rows ordered by columns seq and sub (unique tuple). The last fetched page (seq,sub)=(7,42)
With much older versions of MySQL, this syntax would not be accepted
WHERE (seq,sub) > (7,42)
ORDER BY seq, sub
LIMIT 20
And when MySQL did support the syntax, we would get an execution plan like if we had written
WHERE ( seq > 7 )
OR ( seq = 7 AND sub > 42 )
ORDER BY sub, seq
LIMIT 20
we would get a much more efficient the execution plan if we instead write something subtly different:
WHERE ( seq >= 7 )
AND ( seq > 7 OR sub > 42 )
ORDER BY sub, seq
LIMIT 20
and we would get a much better plan from the MySQL optimizer. we'd expect the optimizer plan to use available UNIQUE INDEX on (sub,seq), and return rows in index order from a range scan operation...
I do not understand your point. The following query is valid MySQL syntax:
SELECT *
FROM my_table
WHERE (x0, y0, x1, y1) IN ((4, 3, 5, 6), ... ,(9, 3, 2, 1));
I would expect MySQL to use the composite index that you have described. But, if it doesn't you could do:
SELECT *
FROM my_table
WHERE x0 = 4 AND y0 = 3 AND x1 = 5 AND y1 = 6
UNION ALL
. . .
SELECT *
FROM my_table
WHERE x0 = 9 AND y0 = 3 AND x1 = 2 AND y1 = 1
The equality comparisons in the WHERE clause will take advantage of an index.
MySQL allows row constructor comparisons like you show, but the optimizer didn't know how to use an index to help performance until MySQL 5.7.
https://dev.mysql.com/doc/refman/5.7/en/row-constructor-optimization.html
You can concatenate the four values into a string and check them like that:
SELECT *
FROM my_table
WHERE CONCAT_WS(',', x0, y0, x1, y1) IN ('4,3,5,6', ..., '9,3,2,1');
The way you are doing is giving correct results in the mysql version on my machine. I am using v5.5.55. Maybe you are using an older one. Please check that.
If you still want to solve this problem in your own version or the above mentioned solution doesn't work then only read the next solution.
I am still not clear about data types and range of all your columns here. So I am assuming that data type is integer and range is between 0 to 9. If this is the case you can easily do this as given below.
select * from s1 where x0+10*x1+100*y1+1000*y2 in (4356,..., 9321);

Making the type of a function depend on input

So I noticed that after n=20 the factorial function given in LearnYouAHaskell (below) craps out because of the finite work range of the Int type.
factorial :: Int -> Int
factorial 0 = 1
factorial n * factorial (n-1)
Using factorial :: Integer -> Integer fixes the issue nicely, but it brought to mind the question. Supposedly Integer is slightly slower than Int so ideally (and I know I'm pinching pennies here) I'd want my factorial function to only resort to Integer when the input is greater than 20 and retain the Int->Int type for the smaller numbers. Seems like there should be an elegant solution for this using if-then-else or guards, but keep running into syntactic pepper (error messages)
You can make a hackish solution without dependent types by using either a sum type and growing when needed or delaying the cast to Integer till the end in some cases. I don't expect either solution would perform better than using Integer - do not fear the Integer, gmp and mpir are quite good.
The casting solution is something like:
selectiveFactorial :: Integer -> Integer
selectiveFactorial i
| i < 20 = fromIntegral $ factorial (fromIntegral i :: Int)
| otherwise = factorial i
factorial :: Integral a => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
As Rein Henrichs said you could do these things in a language with dependent types, which Haskell does not (yet, quite) have. In Idris, say, it would look something like
factorial : (n : Int) -> if n <= 20 then Int else Integer
factorial n with (n <= 20)
factorial n | True = thisfactorial n
factorial n | False = thatfactorial n
But how will you use this result? Well, you'll need to do the comparison to figure out what type to expect, and when all is said and done, I don't see how you've won anything. For completeness, the use site could look something like this:
use : Int -> Integer
use n with (factorial n)
use n | fn with (n <= 20)
use n | fn | False = fn
use n | fn | True = cast fn
Note that the order of the with clauses is significant! The fn binding gets type if n <= 20 then Int else Integer; for reasons I don't entirely understand, the n <= 20 test must be to the right of that in order for the pattern match to affect its type.
It can't be done. There are things you can do however:
Make the type more generic: factorial :: Num a => a -> a;
This allows the user of your function to decide what runtime penalties he wants to occur vs. what range of numbers is permissible.
Use a sum type like data PossiblyBig = Small Int | Big Integer, and then have an implementation instance Num PossiblyBig that encodes things that fit into Int as Small, and things that don't fit as Big; AFAIK Integer already works like that (look up the GMP implementation if you want to know for sure), so this is more of a general example than advice as to what you should do in this particular situation.
Making the type of a function depend on its values is exactly what dependent types are for. Unfortunately, Haskell does not have dependent types so this cannot be done.