/*************************************************************************
* Name:
* NetID:
* Precept:
*
* Description: Four methods, each of which produce a string of n
* consecutive x's. (e.g., x, xx, xxx, xxxx)
*************************************************************************/
public class Repeat {
// returns a String of n consecutive x's
public static String repeat1(int n) {
String s = "";
for (int i = 0; i < n; i++)
s = s + "x";
return s;
}
// returns a String of n consecutive x's
public static String repeat2(int n) {
char[] temp = new char[n];
for (int i = 0; i < n; i++)
temp[i] = 'x';
return new String(temp);
}
// returns a String of n consecutive x's
public static String repeat3(int n) {
if (n == 0) return "";
else if (n == 1) return "x";
else return repeat3(n / 2) + repeat3(n - (n / 2));
}
// returns a String of n consecutive x's
public static String repeat4(int n) {
if (n == 0) return "";
String temp = repeat4(n / 2);
if (n % 2 == 0) return temp + temp;
else return temp + temp + "x";
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
double startTime;
String nConsecutiveExes;
// clear the memory
nConsecutiveExes = null; System.gc();
// experiment 1
startTime = System.currentTimeMillis();
nConsecutiveExes = repeat1(n);
StdOut.println("Elapsed time for repeat1() = " +
(System.currentTimeMillis() - startTime)/1000 + "s");
// clear the memory
nConsecutiveExes = null; System.gc();
// experiment 2
startTime = System.currentTimeMillis();
nConsecutiveExes = repeat2(n);
StdOut.println("Elapsed time for repeat2() = " +
(System.currentTimeMillis() - startTime)/1000 + "s");
// clear the memory
nConsecutiveExes = null; System.gc();
// experiment 3
startTime = System.currentTimeMillis();
nConsecutiveExes = repeat3(n);
StdOut.println("Elapsed time for repeat3() = " +
(System.currentTimeMillis() - startTime)/1000 + "s");
// clear the memory
nConsecutiveExes = null; System.gc();
// experiment 4
startTime = System.currentTimeMillis();
nConsecutiveExes = repeat4(n);
StdOut.println("Elapsed time for repeat4() = " +
(System.currentTimeMillis() - startTime)/1000 + "s");
}
}