Search code examples
javaswap

How to swap the coordinates of two point?


I have defined two points, p1 and p2. I would like to write a method swapPoints which replaces the x and y coordinates of p1 with p2, and vice versa.

I can easily do this by creating a dummy temporary point, however, I want to do it using only the two points p1 and p2. As you can see by my attempt I'm only able to replace the coordinates for one point. I have tried using the ^= function however that did not give me the correct coordinates either.

import java.awt.Point;

public class SwapCoord{
    public static void main(String[] args) {
        Point p1 = new Point(5, 2);
        Point p2 = new Point(-3, 6);
        swapPoints(p1, p2);
        System.out.println("(" + p1.x + ", " + p1.y + ")");
        System.out.println("(" + p2.x + ", " + p2.y + ")");
      }
    public static void swapPoints(Point p1, Point p2) {
        p1.x = p2.x;
        p1.y = p2.y;

        p2.x = p1.x;
        p2.y = p1.y;
    }
}

Solution

  • The idea behind swapping two values using xor is that xoring a value with itself is equal to zero, so you can exchange two ints by doing:

    public static void swapPoints(Point p1, Point p2) {
        p1.x ^= p2.x;
        p2.x ^= p1.x;
        p1.x ^= p2.x;
    
        p1.y ^= p2.y;
        p2.y ^= p1.y;
        p1.y ^= p2.y;
    }