mysql coupled OR statement - mysql

I'm trying to do a coupled OR statement
select * from table where cat = "x" OR (cat = "y" AND rand()<=0.25);
So I would like to select all items with cat = x or cat = y, but only 25% of y. The statement above gives med 25% of both x and y.
How can I seperate my statement so this can be done?
Thanks

I don't know what you are doing but i can almost smell that this is a very dodgy way to implement SQL.
I assume, you want to change your where clause if random number generates a result with %25 probability.You can not do this with ORs if cat="x" then it will not even try to look at Y. That gives u all Xs and quarter of Ys.
Try this for implementation of probablity check.
IF (RAND() <= 0.25)
{ sql_statement_forY }
[ ELSE
{ sql_statement_forX } ]

Related

Recursively counting divisors of a number

I have a question, more on the theoretical side. I want to make a recursive function that counts all (not only prime) different divisors of a given natural number.
For example with f(0)=0 (per Def.), f(3) = 2, f(6) = 4, f(16) = 5 etc.
Theoretically, how could I do that?
Thanks.
If I understand correctly, you only want to COUNT them, not to collect them, right?
A second assumption is that you don't want to count only independent divisors (i.e. you want to count "2", "3" but not "6").
If this is the case, the algorithm shown in Sean's answer can be simplified significantly:
You don't need the array divisorList but only a counter,
You as soon as you find a divisor, you can reduce the max limit of the loop by the result of dividing the root number by the divisor (e.g. if your root number is 900 and 2 is the first divisor, you can set the limit of the loop to 450; then, when checking 3 you will reduce the limit to 150 and so on).
EDIT:
After thinking a little bit more, here is the correct algorithm:
Assume that the number is "N". Then, you already start with a count of 2 (i.e. 1 and N),
You then check if N divides by 2; if it does, you need to add 2 to the count (i.e. 2 and N/2),
You then change the limit of the loop to N/2,
Test if dividing by 3 yields an integer; if it does, you add 2 to the count (i.e. 3 and N/3) and reduce the limit to N/3,
Test 4...
Test 5...
...
In Pseudo-code:
var Limit = N ;
Count = 2 ;
for (I = 2 ; I < Limit ; I++) {
if (N/I is integer) {
Count = Count + 3 ;
Limit = N / I ;
} ;
} ;
Note: I don't know which language you are programming, so you need to verify if your language allows you to change the limit of the loop. If it does not, you can include an EXIT-LOOP condition (e.g. if I >= Limit then exit loop).
Hope this resolves your problem.
public static ArrayList<int> recursiveDivisors(int num)
{
ArrayList<int> divisorList = new ArrayList<int>();
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
divisorList.add(i)
}
return divisorList;
}
Something like this?
Returns all divisors in a divisor array list
EDIT: Not recursive

Arduino - waiting on function causes a number pile-up

I have a function filledFunction() that returns a float filled:
float filledFunction(){
if (FreqMeasure.available()) {
sum = sum + FreqMeasure.read();
count = count + 1;
if (count > 30) {
frequency = FreqMeasure.countToFrequency(sum / count);
a = frequency * x;
b = exp (a);
c = w * b;
d = frequency * z;
e = exp (d);
f = y * e;
float filled = c + f;
sum = 0;
count = 0;
return filled;
}
}
}
When I call this function with
while (1){
fillLevel = filledFunction();
int tofill = 500 - fillLevel;
Serial.print("fillLevel: ");
Serial.println(fillLevel);
Serial.print("tofill: ");
Serial.println(tofill);
The serial monitor should output two numbers that add up to 500 named fillLevel and tofill. Instead I get a repeating sequence of similar values:
http://i.imgur.com/Y9Wu8P2.png
The First two values are correct (410.93 + 89 = 500), but the following 60ish values are unknown to me, and do not belong there.
I am using an arduino nano
The filledFunction() function only returns a value if FreqMeasure.available() returns true AND count > 30. As stated in the answers to this question the C89, C99 and C11 standards all say that the default return value of a function is undefined (that is if the function completes without executing a return statement). Which really means that anything could happen, such as outputting arbitrary numbers.
In addition, the output that you're seeing starts off 'correct' with one of the numbers subtracted from 500, even when they have weird values such as 11699.00 and -11199 (which equals 500 - 11699.00). However, lower down in the output this seems to break down and the reason is that on Arduino Nano an int can only hold numbers up to 32767 and therefore the result of the subtraction is too big and 'overflows' to be a large negative number.
Fixing the filledFunction() function to explicitly return a value even if FreqMeasure.available() is false or count <= 30 and ensuring that it can't return a number greater than 500 will likely solve these issues.

How can I prove the correctness of the following algorithm?

Consider the following algorithm min which takes lists x,y as parameters and returns the zth smallest element in union of x and y.
Pre conditions: X and Y are sorted lists of ints in increasing order and they are disjoint.
Notice that its pseudo code, so indexing starts with 1 not 0.
Min(x,y,z):
if z = 1:
return(min(x[1]; y[1]))
if z = 2:
if x[1] < y[1]:
return(min(x[2],y[1]))
else:
return(min(x[1], y[2]))
q = Ceiling(z/2) //round up z/2
if x[q] < y[z-q + 1]:
return(Min(x[q:z], y[1:(z - q + 1)], (z-q +1)))
else:
return(Min(x[1:q], B[(z -q + 1):z], q))
I can prove that it terminates, because z keeps decreasing by 2 and will eventually reach one of the base cases but I cant prove the partial correctness.
Your code is not correct.
Consider the following input:
x = [0,1]
y = [2]
z = 3
You then get q = 2 and, in the if clause that follows, access y[z-q+1], i.e. y[2]. This is an array bounds violation.

how to apply zeroes to non-matching indices of filtered data

I am learning octave, and I have a comparison made like so:
ma = [1,2,3,4,5];
indices = ma > 3;
The conditions filter 'ma', and the var 'indices' prints the indices matching the conditions, which looks like:
[4, 5]
... but what I want is to use that result to return an array like this:
[0,0,0,4,5];
Is there a function for this?
You can do the following:
ma = [1,2,3,4,5];
ma(ma <= 3) = 0
Basically, just invert the condition and use it to set the values to zero.

I have 3 columns x,y and type. I'd like to find out if there's at least 3 connections of the same type on a grid using SQL

I have a game table like:
CREATE TABLE game_piece(
x Integer,
y Integer,
type Integer
);
Each (x,y) can only have 1 piece. Representing a grid (numbers being types):
1235
1134
9678
By connected I mean they have to be directly next to the origin in a vertical or horizontal fashion like:
C C=connected
COC O=origin
C
I'd like to check if there's 3 pieces connected anywhere on the grid without needing to get the whole grid of the database and doing it in python, if there's decent solution. Suggestions?
To clarify my comments on Xophmeister's answer, like this:
SELECT o.x, o.y
FROM game_piece o
JOIN game_piece p
ON p.type = o.type
AND (
(o.x = p.x AND p.y IN (o.y-1,o.y+1))
OR
(o.y = p.y AND p.x IN (o.x-1,o.x+1))
)
GROUP BY o.x, o.y
HAVING COUNT(*) > 1
And here it is working on your test data: http://sqlfiddle.com/#!3/0bd34/1
Edit: Since you only want to know if the condition exists, the best way to do it is to just shove LIMIT 1 on the end and see whether the query returns a result or not. For some reason sqlfiddle doesn't like me putting the LIMIT in there, but I tested it on my server and it works just fine.
By 'connected', I'm going to assume you mean adjacent: That is, (5,3,1234) and (4,3,1234) would be connected.
As such, what you can do is join the table to itself twice, where each join depends on the one that preceded, and the conditions include:
on nextPiece.type = lastPiece.type
and (nextPiece.x in (lastPiece.x - 1, lastPiece.x + 1)
or nextPiece.y in (lastPiece.x - 1, lastPiece.x + 1))
Note that this doesn't consider diagonals as being adjacent.
The problem with this technique is that it will return duplicates: If record A is connected to record B, then both A and B will show in the result set. As you're joining twice, you'll see three duplicates... You can do a select distinct if all you are interested in is whether you've found a match, but the query in general will not be particularly fast either way (depending on how big your grid is and how sparsely it is populated).
EDIT See Braiba's solution (and comments, below): I made a mistake :P
Depending on what do you mean by connected, you don't need to dump the whole db but only the 2 pieces on 4 directions.
select x, y,
from game_piece
where (
(x between origin_x - 2 AND origin_x + 2 AND y = origin_y)
OR (y between origin_y - 2 AND origin_y + 2 AND x = origin_x)
)
AND type = the_type;
origin_x, origin_y are the coordinates of the piece you want to check.
That will dump between 1 and 8 pieces you'll have to check.
If the game table is very large, you should add an index on the x and y column, otherwise that might not be useful.
Hope it helps.
M.
This will return the number of different connection types:
select count(distinct type) as connections
from game_piece
where ((y = $y and x between $x - 1 and $x + 1)
or (x = $x and y between $y - 1 and $y + 1))
and (x != $x or y != $y) -- exclude the origin itself
You can use this solution:
SELECT 1
FROM game_piece
WHERE
(x = $o_x AND y IN ($o_y + 1, $o_y - 1)) OR
(y = $o_y AND x IN ($o_x + 1, $o_x - 1))
GROUP BY type
HAVING COUNT(1) = 3
$o_x and $o_y being the originX and originY input parameters respectively.
If there are exactly 3 pieces of the same type connected to the origin (either vertically or horizontally), this will return 1, otherwise, it will return an empty result-set.
Edit:
What you can try in order to find out if there's any pieces on the grid having 2 or more of the same adjacent types:
SELECT COUNT(1) > 0 AS doesExist
FROM
(
SELECT 1
FROM game_piece p
INNER JOIN game_piece o ON
p.type = o.type AND (
(p.x = o.x AND p.y IN (o.y + 1, o.y - 1)) OR
(p.y = o.y AND p.x IN (o.x + 1, o.x - 1))
)
GROUP BY p.type, o.x, o.y
HAVING COUNT(1) > 1
) a
Which will return 1 if there are one or more pieces and 0 if not.