CodingBat: Java. Recursion-1, Part I


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


Recursion is neat in theory and commonly leads to very clean code. Some people have a hard time understanding it, though. If you’ve ever encountered a recurrence relation in mathematics, then you already know everything there is to know about the “mind-bending” nature of recursive problems.

Otherwise, try this simple strategy. First, you may be tempted to think recursively about recursive functions. This may work with factorials, but for something more complex like, say, the Ackermann function, it’s a recipe for disaster. So, don’t do it! Instead, figure out what the base case consists of. The base case immediately returns a result. All other conditions eventually have to revert to the base case, which means that you’ll return “something” in addition to recursively calling the function, but with an input that brings you closer to the base case.

The first example, factorial, of CodingBat’s Recursion-1 section illustrates this strategy very well. All subsequent problems are rather similar.

All solutions were successfully tested on 24 March 2013.

factorial:

public int factorial(int n) {
	if (n <= 1) return 1;
	return n * factorial(n - 1);
}

bunnyEars:

public int bunnyEars(int bunnies) {
	if (bunnies == 0) return 0;
	return 2 + bunnyEars(bunnies - 1);
}

fibonacci:

public int fibonacci(int n) {
	if (n <= 1) return n;
	return fibonacci(n - 2) + fibonacci(n - 1);
}

bunnyEars2:

public int bunnyEars2(int bunnies) {
	if (bunnies == 0) return 0;
	if (bunnies % 2 == 1) return 2 + bunnyEars2(bunnies - 1);
	return 3 + bunnyEars2(bunnies - 1);
}

triangle:

public int triangle(int rows) {
	if (rows == 0) return 0;
	return rows + triangle(rows - 1);
}

sumDigits:

public int sumDigits(int n) {
	if (n == 0) return 0;
	return n % 10 + sumDigits(n / 10);
}

count7:

public int count7(int n) {
	if (n == 0) return 0;
	if (n % 10 == 7) return 1 + count7(n / 10);
	return count7(n / 10);
}

count8:

public int count8(int n) {
	if (n == 0) return 0;
	if (n >= 88 && n % 100 == 88) return 2 + count8(n / 10);
	if (n % 10 == 8) return 1 + count8(n / 10);
	return count8(n / 10);
}

powerN:

public int powerN(int base, int n) {
	if (n == 0) return 1;
	return base * powerN(base, n - 1);
}

countX:

public int countX(String str) {
	if (str.length() == 0) return 0;
	if (str.charAt(0) == 'x') return 1 + countX(str.substring(1));
	return countX(str.substring(1));
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. AP-1, Part III


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


scoresSpecial:

public int scoresSpecial(int[] a, int[] b) {
	return largest(a) + largest(b);
}


public int largest(int[] array) {
	int result = 0;
	for (int i = 0; i < array.length; i++)
		if (array[i] % 10 == 0 && array[i] > result)
			result = array[i];
	return result;
}

sumHeights:

public int sumHeights(int[] heights, int start, int end) {
	int sum = 0;
	for (int i = start; i < end; i++)
		sum += Math.abs(heights[i] - heights[i + 1]);
	return sum;
}

sumHeights2:

public int sumHeights2(int[] heights, int start, int end) {
	int sum = 0;
	for (int i = start; i < end; i++)
		if (heights[i] < heights[i + 1])
			sum += (2 * Math.abs(heights[i] - heights[i + 1]));
		else
			sum += Math.abs(heights[i] - heights[i + 1]);
	return sum;
}

bigHeights:

public int bigHeights(int[] heights, int start, int end) {
	int count = 0;
	for (int i = start; i < end; i++)
		if (Math.abs(heights[i] - heights[i + 1]) >= 5) count++;
	return count;
}

userCompare:

public int userCompare(String aName, int aId, String bName, int bId) {
	if (aName.compareTo(bName) < 0) return -1;
	if (aName.equals(bName)) {
		if (aId == bId) return 0;
		if (aId < bId) return -1;
	}
	return 1;
}

mergeTwo:

public String[] mergeTwo(String[] a, String[] b, int n) {
	String[] result = new String[n];
	int indexResult = 0;
	int indexA = 0;
	int indexB = 0;

	while (indexResult < n)
		if (a[indexA].compareTo(b[indexB]) < 0)
			result[indexResult++] = a[indexA++];
		else if (a[indexA].compareTo(b[indexB]) > 0)
			result[indexResult++] = b[indexB++];
		else { // identical strings
			result[indexResult++] = a[indexA++];
			indexB++;
		}
	return result;
}

commonTwo:

public int commonTwo(String[] a, String[] b) {
	int count = 0;
	String lastChecked = null;
	for (int i = 0; i < a.length; i++)
		if (!a[i].equals(lastChecked))
			for (int j = 0; j < b.length; j++)
				if (a[i].equals(b[j])) {
					count++;
					lastChecked = a[i];
					break;
				}
	return count;
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. AP-1, Part II


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


hasOne:

public boolean hasOne(int n) {
	while (n > 0) {
		if (n % 10 == 1) return true;
		n = n / 10;
	}
	return false;
}

dividesSelf:

public boolean dividesSelf(int n) {
	int copyN = n;
	while (n > 0)
		if (n % 10 == 0) return false;
		else
			if (copyN % (n % 10) == 0) n /= 10;
			else return false;
	return true;
}

copyEvens:

public int[] copyEvens(int[] nums, int count) {
	int[] result = new int[count];
	int position = 0;

	for (int i = 0; i < nums.length; i++) {
		if (nums[i] % 2 == 0) {
			result[position] = nums[i];
			position++;
		}
		if (position == count) break;
	}
	return result;
}

copyEndy:

public int[] copyEndy(int[] nums, int count) {
	int[] result = new int[count];
	for (int i = 0, pos = 0; i < nums.length; i++) {
		if (nums[i] >= 0 && nums[i] <= 10 || nums[i] >= 90
				&& nums[i] <= 100) {
			result[pos] = nums[i];
			pos++;
		}
		if (pos == count) break;
	}
	return result;
}

matchUp:

public int matchUp(String[] a, String[] b) {
	int count = 0;
	for (int i = 0; i < a.length; i++)
		if (!a[i].equals("") && !b[i].equals("")
				&& a[i].charAt(0) == b[i].charAt(0))
			count++;
	return count;
}

scoreUp:

public int scoreUp(String[] key, String[] answers) {
	int sum = 0;
	for (int i = 0; i < answers.length; i++)
		if (answers[i] == key[i]) sum += 4;
		else if (!answers[i].equals("?")) sum -= 1;
	return sum;
}

wordsWithout:

public String[] wordsWithout(String[] words, String target) {
	int count = 0;
	for (int i = 0; i < words.length; i++)
		if (!words[i].equals(target)) count++;

	String[] result = new String[count];
	for (int i = 0, pos = 0; i < words.length; i++)
		if (!words[i].equals(target)) {
			result[pos] = words[i];
			pos++;
		}
	return result;
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. AP-1, Part I


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


After the more demanding Array-3 section, AP-1 on CodingBat is much more relaxing as it reviews basic programming concepts, with a strong focus on array processing.

All solutions were successfully tested on 16 March 2013.

scoresIncreasing:

public boolean scoresIncreasing(int[] scores) {
	for (int i = 0; i <= scores.length - 2; i++)
		if (scores[i] > scores[i + 1]) return false;
	return true;
}

scores100:

public boolean scores100(int[] scores) {  
	for (int i = 0; i <= scores.length - 2; i++)
		if (scores[i] == 100 && scores[i + 1] == 100) return true;
	return false;
}

scoresClump:

public boolean scoresClump(int[] scores) {
	if (scores.length > 2) {
		for (int i = 0; i < scores.length - 2; i++) {
			if (scores[i + 2] - scores[i] <= 2)
				return true;
		}
	}
	return false;
}

scoresAverage:

public int scoresAverage(int[] scores) {
	int first = average(scores, 0, scores.length / 2);
	int second = average(scores, scores.length / 2, scores.length);
	return Math.max(first, second);
}

private int average(int[] scores, int start, int end) {
	int sum = 0;
	int count = 0;
	for (int i = start; i < end; i++) {
		sum += scores[i];
		count++;
	}
	return sum / count;
}

wordsCount:

public int wordsCount(String[] words, int len) {
	int count = 0;
	for (int i = 0; i < words.length; i++)
		if (words[i].length() == len) count++;
	return count;
}

wordsFront:

public String[] wordsFront(String[] words, int n) {
	String[] newWords = new String[n];
	for (int i = 0; i < n; i++)
		newWords[i] = words[i];
	return newWords;
}

wordsWithoutList:

public List wordsWithoutList(String[] words, int len) {
	List result = new ArrayList();
	for (int i = 0; i < words.length; i++)
		if (words[i].length() != len)
			result.add(words[i]);
	return result;
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. Array-3, Part II


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


squareUp:

public int[] squareUp(int n) {
	int[] result = new int[n * n];
	int pos = 0;

	for (int i = 1; i &lt;= n; i++) {
		for (int k = 1; k &lt;= n - i; k++) result[pos++] = 0;
		for (int j = i; j &gt; 0; j--) result[pos++] = j;
	}
	return result;
}

seriesUp:

public int[] seriesUp(int n) {
	int[] result = new int[n * (n + 1) / 2];
	int pos = 0;
	int i = 1;
	while (i &lt;= n + 1) {
		for (int j = 1; j &lt; i; j++) result[pos++] = j;
		i++;
	}
	return result;
}

maxMirror:

public int maxMirror(int[] nums) {
	int[] numsCopy = new int[nums.length];
	for (int i = nums.length - 1, j = 0; i &gt;= 0; i--, j++)
		numsCopy[j] = nums[i];

	int max = 0;

	for (int i = 0; i &lt; nums.length; i++) {
		int count = 0;
		int pos1 = i;
		int pos2 = 0;
		boolean flag = false;

		while (pos1 &lt; nums.length &amp;&amp; pos2 &lt; nums.length) {
			if (!flag) {
				if (nums[pos1] != numsCopy[pos2]) pos2++;
				else {
					flag = true;
					count = 1;
					pos1++;
					pos2++;
				}
			} else {
				if (nums[pos1] == numsCopy[pos2]) {
					count++;
					pos1++;
					pos2++;
				} else {
					if (count &gt; max) max = count;
					pos1 = i;
					flag = false;
				}
			}
			if (count &gt; max) max = count;
		}
	}
	return max;
}

The input array is reversed to make the subsequent steps clearer to follow. This leads to slightly more code, but it should increase comprehensibility.

countClumps:

public int countClumps(int[] nums) {
	int count = 0;
	for (int i = 0; i &lt; nums.length - 1; i++)
		if (nums[i] == nums[i + 1]) {
			count++;
			for (int j = i + 1; j &lt; nums.length; j++)
				if (nums[j] == nums[i]) i++;
				else break;
		}
	return count;
}

At first I was tempted to use only one for loop and operate with a flag variable. Using a second for loop led to a more elegant solution, though. A neat detail is that the running time is linear since the nested for loop only increases i.


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.