Polygon Transform


/*************************************************************************
 *  Compilation:  javac PolygonTransform.java
 *  Execution:    java PolygonTransform
 *
 *  @author: Karen Li
 *
 *************************************************************************/

public class PolygonTransform{


    // Returns a new array that is an exact copy of the given array. 
    // The given array is not mutated. 
    public static double[] copy(double[] array) {
        double[] x = new double[array.length];
        for (int i = 0; i < array.length; i++){
            x[i] = array[i];
        }
        return x;
    }
    
    // Scales the given polygon by the factor alpha. 
    public static void scale(double[] x, double[] y, double alpha) {
        for (int i = 0; i < x.length; i++){
            x[i] = alpha * x[i];
            y[i] = alpha * y[i];
        }
    }
    
    // Translates the given polygon by (dx, dy). 
    public static void translate(double[] x, double[] y, double dx, double dy) {
        for (int i = 0; i < x.length; i++){
            x[i] = x[i] + dx;
            y[i] = y[i] + dy;
        }
    }
    
    // Rotates the given polygon theta degrees counterclockwise, about the origin. 
    public static void rotate(double[] x, double[] y, double theta) {
        double rad = Math.toRadians(theta);
        double a;
        for (int i = 1; i < x.length; i++){
            a = x[i];
            x[i] = x[i] * Math.cos(rad) - y[i] * Math.sin(rad);
            y[i] = y[i] * Math.cos(rad) - y[i] * Math.sin(rad);
        }
    }

    // Tests each of the API methods by directly calling them. 
    public static void main(String[] args) {
        double [] x = {0.0, 1.0, 1.0, 0.0};
        double [] y = {0.0, 0.0, 2.0, 1.0};
        StdDraw.setScale(-5.0, +5.0);
        double alpha = 2.0;
        StdDraw.setPenColor(StdDraw.RED);
        StdDraw.polygon(x, y);
        scale(x, y, alpha);
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.polygon(x, y);

        //Translates polygon by (2, 1).
        StdDraw.setScale(-5.0, +5.0);
        double dx = 2.0, dy = 1.0;
        StdDraw.setPenColor(StdDraw.RED);
        StdDraw.polygon(x, y);
        translate(x, y, dx, dy);
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.polygon(x, y);

        // Rotates polygon 45 degrees.
        StdDraw.setScale(-5.0, +5.0);
        double theta = 45.0;
        StdDraw.setPenColor(StdDraw.RED);
        StdDraw.polygon(x, y);
        rotate(x, y, theta);
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.polygon(x, y);
    }
}