We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
SELECTx,yFROMfunctionsASf1/* This is not made clear as part of the problem statement, but we only want the 'first' instance of any symmetric pair, as ranked by x ascending. Setting the condition that y >= x ensures that the first instance is the one we include. */WHEREy>=xGROUPBY1,2/* Here's the meat of the query. We count the number of symmetric pairs we can find for the current x, y pair. There are three possible values: there might be no symmetric pairs, in which case we exclude the current pair; there might be 1 symmetric pair; or there might be two.The tricky bit here is that if a pair consists of (x,y) such that x = y, then we can always find one pair - itself - which looks to be symmetric. So when x = y, that's when we want to find two symmetric pairs - itself and its 'actual' symmetric partner.This ends up being easier than it sounds. */HAVINGCOUNT((SELECTxFROMfunctionsf2/* Set the WHERE conditions from the definition of symmetric pair */WHEREf2.x=f1.yANDf2.y=f1.xLIMIT1)/* As explained above, if x = y, we want to find two results, otherwise we want one. */)=IF(x=y,2,1)/* Finally, as indicated in the problem, we order by ascending x */ORDERBY1ASC;
Symmetric Pairs
You are viewing a single comment's thread. Return to all comments →