Symmetric Pairs

Sort by

recency

|

1546 Discussions

|

  • + 0 comments

    SET NOCOUNT ON;

    /* Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */

    DECLARE @X INT; DECLARE @Y INT; DECLARE @IT INT = 1; DECLARE @IMAXX INT; DECLARE @JMAXX INT; DECLARE @LINE VARCHAR(MAX)=''; DECLARE @COUNT INT =0;

    DECLARE @CTE TABLE ( RowNum INT, X INT, Y INT );

    -- Populate the table variable INSERT INTO @CTE (RowNum, X, Y) SELECT ROW_NUMBER() OVER (ORDER BY X, Y) AS RowNum, X, Y FROM (SELECT DISTINCT X, Y FROM FUNCTIONS) AS DistinctFunctions; DECLARE @RESULT TABLE( X INT, Y INT )

    SELECT @IMAXX=COUNT() FROM @CTE ; SELECT @JMAXX=COUNT() FROM FUNCTIONS;

    WHILE @IT <= @IMAXX BEGIN DECLARE @JT INT =1; SELECT @X = X, @Y = Y FROM @CTE WHERE RowNum = @IT; WHILE @JT <= @JMAXX BEGIN IF @X <= @Y BEGIN IF @X=@Y BEGIN SELECT @COUNT=COUNT() FROM FUNCTIONS WHERE X=@Y AND Y=@X; IF @COUNT>=2 BEGIN INSERT INTO @RESULT VALUES(@X, @Y); BREAK; END END ELSE BEGIN SELECT @COUNT=COUNT() FROM FUNCTIONS WHERE X=@Y AND Y=@X; IF @COUNT>=1 BEGIN INSERT INTO @RESULT VALUES(@X, @Y); BREAK; END END END SET @JT+=1; END SET @IT+=1; END SELECT * FROM @RESULT; go

  • + 0 comments

    This is my solution. What I like about it is that all the conditions are in one line, so it is easy remove or add to conditions in one place. Also, the problem description isn't very clear that we should return only distict values, I had to assume that from the example and then from the multiple fail test (yes you're not alone if you run into this issue)

    WITH number_functions AS (
        SELECT 
            X, 
            Y, 
            ROW_NUMBER() OVER (ORDER BY X) AS rn
        FROM Functions
    )
    SELECT DISTINCT f1.X, f1.Y FROM number_functions f1
    CROSS JOIN number_functions f2
    WHERE f1.X = f2.Y AND f2.X = f1.Y AND f1.X <= f1.Y AND f1.rn != f2.rn
    ORDER BY f1.X ASC, f1.Y ASC;
    
  • + 0 comments
    SELECT f1.X, f1.Y
    FROM Functions f1
    INNER JOIN Functions f2 ON f1.Y = f2.X
    WHERE f1.X = f2.Y
    GROUP BY f1.X, f1.Y
    HAVING COUNT(*) > 1 OR f1.X < f1.Y
    ORDER BY f1.X;
    
  • + 0 comments

    Good old nested queries: select f.x, f.y from (select f.x, f.y, min(f.rowid) r from functions f where f.x <= f.y group by f.x, f.y) f where exists (select 1 from functions f1 where f1.x = f.y and f1.y = f.x and f1.rowid <> f.r) order by f.x;

  • + 0 comments

    This question has wrong description, something that leads to wrong assumptions. One should not use X1 and X2 in example, it means X1 and X2 are adjecent data points. Instead use Xa and Xp where a and p can be any number from 1 to N, N being the size of the data set.