package cse1030.img;
import java.awt.Color;
import java.util.List;
public class Recursion {
private Recursion() {
// intentionally empty and private
}
/**
* Multiply two integers using recursive addition.
*
* @param m an integer
* @param n an integer
* @return the value m * n
*/
public static int multiply(int m, int n) {
if (n == 0) {
return 0;
}
else if (n < 0) {
return -multiply(m, -n);
}
return m + multiply(m, n - 1);
}
/**
* Determines if a list contains a given element by
* recursively examining the first element of the list.
*
* @param t the list to search through
* @param element the element to search for
* @return true
if element
is in
* the list, and false
otherwise
*/
public static boolean contains(T element, List t) {
if (t.size() == 0) {
return false;
}
if (t.size() == 1) {
return t.get(0).equals(element);
}
return t.get(0).equals(element) || contains(element, t.subList(1, t.size()));
}
/**
* Determines if an integer is prime.
*
* @param x
* an integer value greater than 2
* @return true
if n
is prime, false
* otherwise
*/
public static boolean isPrime(int x) {
return isPrime(x, 2);
}
/**
* Recursively determine if an integer is prime.
*
* @param n
* an integer value greater than 2
* @param divisor
* @return true
if n
is prime, false
* otherwise
*/
private static boolean isPrime(int x, int divisor) {
if (divisor > Math.sqrt(x)) {
return true;
}
if (x % divisor == 0) {
return false;
}
return isPrime(x, divisor + 1);
}
/**
* Downsample a picture n
times by a factor of 2
* using recursion. See the lab problem for a description of
* downsampling.
*
* @pre. the width and height of the picture are both multiples of 2 to the power n
* @param p the picture to downsample
* @param n the number of times to downsample the picture by a factor of 2
* @return the downsampled picture
*/
public static Picture downsample(Picture p, int n) {
if (n == 0) {
return p;
}
int width = p.width() / 2;
int height = p.height() / 2;
Picture q = new Picture(width, height);
for (int qx = 0; qx < width; qx++) {
for (int qy = 0; qy < height; qy++) {
int px = 2 * qx;
int py = 2 * qy;
Color c00 = p.get(px, py);
Color c01 = p.get(px + 1, py);
Color c10 = p.get(px, py + 1);
Color c11 = p.get(px + 1, py + 1);
int r = c00.getRed() + c01.getRed() + c10.getRed() + c11.getRed();
int g = c00.getGreen() + c01.getGreen() + c10.getGreen() + c11.getGreen();
int b = c00.getBlue() + c01.getBlue() + c10.getBlue() + c11.getBlue();
q.set(qx, qy, new Color(r / 4, g / 4, b / 4));
}
}
return downsample(q, n - 1);
}
/**
* Create your own main method to test your methods.
*
* @param args
*/
public static void main(String[] args) {
System.out.println(multiply(5, -10));
Picture p = new Picture("snowflake.jpg");
p.show();
downsample(p, 1).show();
downsample(p, 2).show();
downsample(p, 3).show();
}
}