Search code examples
javascriptlogic

How to rewrite a negated line?


Negating takes me hours of trial and error until nothing breaks, any method of negating other than intuitively? For example:

//x and y are whole numbers

!((x<9) && (y<=(8-x)))
((x>8) || (y>(8-x)))

Solution

  • The simplest thing is to ignore questions about the domain of values, and treat this as an entirely logical problem. Then we can break it down into cases such as:

    !(A || B) ~= !A && !B
    !(A && B) ~= !A || !B
    !(!A) ~= A
    !(x > y) ~= x <= y
    !(x >= y) ~= x < y
    

    The first two can easily be extended:

    !(A || B || C || D || ...) ~= !A && !B && !C && !D && ...
    !(A && B && C && D && ...) ~= !A || !B || !C || !D || ...
    

    So, for one of your examples, we have:

    !((x < 9) && (y <= (8 - x)))
    !(x < 9) || !(y <= (8 - x))
    (x >= 9) || (y > (8 - x))
    

    We could leave it as this, but as you had additional domain information, ("x and y are whole numbers"), you might incorporate it to return a slightly less specific, but accurate enough in context answer, such as

    (x > 8) || (y > (8 - x))
    

    You would have to decide on a case-by-case basis whether this is worth the additional steps. What it might gain is a somewhat reduced codebase, it can also lose in a less transparent link to the original format.