Category Archives: CodingBat: Java

CodingBat: Java. Warmup-2, Part I


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


The Warmup-2 section on CodingBat gently introduces string and array loops. There wasn’t much to comment since the solutions are all relatively straight-forward. All solutions were successfully tested on 13 January 2013.

stringTimes:

public String stringTimes(String str, int n) {
String result = “”;
for (int i = 0; i < n; i++) result += str; return result; } [/sourcecode]frontTimes:

public String frontTimes(String str, int n) {
String result = “”;
if (str.length() <= 3) for (int i = 0; i < n; i++) result += str; else for (int i = 0; i < n; i++) result += str.substring(0, 3); return result; } [/sourcecode]countXX:

int countXX(String str) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++) if (str.substring(i, i + 2).equals("xx")) count++; return count; } [/sourcecode]doubleX:

boolean doubleX(String str) {
int firstX = str.indexOf(‘x’);
if (firstX < str.length() - 1) return str.charAt(firstX + 1) == 'x'; return false; } [/sourcecode]stringBits:

public String stringBits(String str) {
String result = “”;
for (int i = 0; i < str.length(); i++) { if (i % 2 == 0) result += str.charAt(i); } return result; } [/sourcecode]stringSplosion:

public String stringSplosion(String str) {
String result = “”;
for (int i = 0; i <= str.length(); i++) { result += str.substring(0, i); } return result; } [/sourcecode]last2:

public int last2(String str) {
int count = 0;
for (int i = 0; i < str.length() - 2; i++) { if (str.substring(i, i + 2).equals( str.substring(str.length() - 2))) count++; } return count; } [/sourcecode]arrayCount9:

public int arrayCount9(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) { if (nums[i] == 9) result++; } return result; } [/sourcecode]arrayFront9:

public boolean arrayFront9(int[] nums) {
int check = (nums.length < 4) ? nums.length : 4; for (int i = 0; i < check; i++) { if (nums[i] == 9) return true; } return false; } [/sourcecode]I use the ternary operator for the sake of brevity. You can of course expand the assignment operation into an if/else block.array123:

public boolean array123(int[] nums) {
for (int i = 0; i < nums.length - 2; i++) if (nums[i] == 1 && nums[i + 1] == 2 && nums[i + 2] == 3) return true; return false; } [/sourcecode]


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


CodingBat: Java. Warmup-1, Part III


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


Here are the final ten exercises from the Warmup-1 section of CodingBat.

mixStart:

	public boolean mixStart(String str) {
		return str.length() >= 3 && str.substring(1, 3).equals("ix");
	}

startOz:

	public String startOz(String str) {
		String result = "";
		if (str.length() > 0 && str.charAt(0) == 'o') result += 'o';
		if (str.length() > 1 && str.charAt(1) == 'z') result += 'z';
		return result;
	}

intMax:

	public int intMax(int a, int b, int c) {
		int max = a;
		if (b > max) max = b;
		if (c > max) max = c;		
		return max;
	}

The solution on the website first compares a and b and assigns the greater value to the variable max. This step can be condensed to assigning a to max right away and then check whether b is greater than max.

close10:

	public int close10(int a, int b) {
		if (Math.abs(10 - a) == Math.abs(10 - b)) return 0;
		if (Math.abs(10 - a) < Math.abs(10 - b)) return a;
		return b;
	}

in3050:

	public boolean in3050(int a, int b) {
		boolean condition1 = a >= 30 && a <= 40 && b >= 30 && b <= 40;
		boolean condition2 = a >= 40 && a <= 50 && b >= 40 && b <= 50;
		return condition1 || condition2;
	}

max1020:

	public int max1020(int a, int b) {
		if (b < a) {
			int temp = a;
			a = b;
			b = temp;
		}
		boolean aInRange = a >= 10 && a <= 20;
		boolean bInRange = b >= 10 && b <= 20;
		if (aInRange && bInRange || !aInRange && bInRange)
			return b;
		if (aInRange && !bInRange)
			return a;
		return 0;
	}

stringE:

	public boolean stringE(String str) {
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == 'e') count++;
		}
		return (count >= 1 && count <= 3);
	}

lastDigit:

	public boolean lastDigit(int a, int b) {
		return (Math.abs(a - b) % 2 == 0);
	}

endUp:

	public String endUp(String str) {
		if (str.length() <= 3) return str.toUpperCase();
		return str.substring(0, str.length() - 3)
				+ str.substring(str.length() - 3).toUpperCase();
	}

everyNth:

	public String everyNth(String str, int n) {
		String result = "";
		for (int i = 0; i < str.length(); i++) {
			if (i % n == 0) result += str.charAt(i);
		}
		return result;
	}

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


CodingBat: Java. Warmup-1, Part II


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


This post continues where the last one left off. It contains solutions to another ten exercises, most of which are straightforward.

frontBack:

	public String frontBack(String str) {
		int length = str.length();
		if (length <= 1) return str;
		return str.charAt(length - 1) + str.substring(1, length - 1)
				+ str.charAt(0);
	}
&#91;/sourcecode&#93;

<b>front3:</b>
[sourcecode language="Java" gutter="false"]
	public String front3(String str) {
		int length = str.length();
		if (length <= 3) return str + str + str;
		String front = str.substring(0, 3);
		return front + front + front;
	}
&#91;/sourcecode&#93;

<b>backAround:</b>
[sourcecode language="Java" gutter="false"]
	public String backAround(String str) {
		char add = str.charAt(str.length() - 1);
		return add + str + add;
	}

front22:

	public String front22(String str) {
		if (str.length() < 2)
			return str + str + str;
		String firstTwo = str.substring(0, 2);
		return firstTwo + str + firstTwo;
	}
&#91;/sourcecode&#93;

<b>startHi:</b>
[sourcecode language="Java" gutter="false"]
	public boolean startHi(String str) {
		if (str.length() < 2)
			return false;
		return str.substring(0, 2).equals("hi");
	}
&#91;/sourcecode&#93;

<b>icyHot:</b>
[sourcecode language="Java" gutter="false"]
	public boolean icyHot(int temp1, int temp2) {
		return (temp1 < 0 && temp2 > 100 || temp1 > 100 && temp2 < 0);
	}
&#91;/sourcecode&#93;

<b>in1020:</b>
[sourcecode language="Java" gutter="false"]
	public boolean in1020(int a, int b) {
		return (a >= 10 && a <= 20 || b >= 10 && b <= 20);
	}
&#91;/sourcecode&#93;

<b>hasTeen:</b>
[sourcecode language="Java" gutter="false"]
	public boolean hasTeen(int a, int b, int c) {
		return (a >= 13 && a <= 19 ||
				b >= 13 && b <= 19 ||
				c >= 13 && c <= 19);
	}
&#91;/sourcecode&#93;

<b>loneTeen:</b>
[sourcecode language="Java" gutter="false"]
	public boolean loneTeen(int a, int b) {
		int count = 0;
		if (a >= 13 && a <= 19) count++;
		if (b >= 13 && b <= 19) count++;
		return count == 1;
	}
&#91;/sourcecode&#93;

This solution might strike you as odd at first. My goal was to avoid a cumbersome boolean expression. Thus, I maintain a counter that increases by one if one of the integers is in the specified range. If the value of count is "1", then the boolean XOR condition is fulfilled. You’ll probably agree that this approach is slightly more elegant than the solution on the website:

&#91;sourcecode language="Java" gutter="false"&#93;
	public boolean loneTeen(int a, int b) {
		boolean aTeen = (a >= 13 && a <= 19);
		boolean bTeen = (b >= 13 && b <= 19);
		return (aTeen && !bTeen) || (!aTeen && bTeen);
		// Translation: one or the other, but not both.
		// Alternately could use the Java XOR operator, but it's obscure.
	}
&#91;/sourcecode&#93;

The XOR operator (^) wasn’t mentioned on the CodingBat website. If you use it, the solution shrinks down to just one line:
&#91;sourcecode language="Java" gutter="false"&#93;
	public boolean loneTeen(int a, int b) {
		return (a >= 13 & a <= 19) ^ (b >= 13 && b <= 19);
	}
&#91;/sourcecode&#93;

<b>delDel:</b>
[sourcecode language="Java" gutter="false"]
	public String delDel(String str) {
		if (str.length() > 3 && str.substring(1,4).equals("del"))
			return str.charAt(0) + str.substring(4);
		return str;
	}

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


CodingBat: Java. Warmup-1, Part I


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


The section Warmup-1 contains 30 short exercises to help you getting familiar with basic operations in Java, covering simple boolean operations and string manipulations. I’ve checked my solutions on CodingBat again on 2 January 2013, and they passed all tests.

This post contains solutions to the first ten exercises.

sleepIn:

	public boolean sleepIn(boolean weekday, boolean vacation) {
		return (!weekday || vacation);
	}

monkeyTrouble:

	public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
		return ((aSmile && bSmile) || (!aSmile && !bSmile));
	}

sumDouble:

	public int sumDouble(int a, int b) {
		if (a == b) return 2 * (a + b);
		return a + b;
	}

A note on coding style: Compared to more modern languages, Java is quite verbose, which is one of the reasons why I prefer to write more compact code. One consequence is that I omit superfluous curly braces, like in sumDouble. According to the official Java style guide you are not supposed to do that, though. Further, I am not overly fond of excessive use of variables.

The above method could also have been written as:

	public int sumDouble(int a, int b) {
		int sum = a + b;
		if (a == b) {
			sum = sum * 2;
		} 
		return sum;
	}

I consider this alternative to be inferior because it is less succinct. You’ll spend more time writing it, and you waste the time of everyone who’s ever going to read your code. Stressing this point in this example may sound silly, but there are sound practical reasons. Once you write larger programs, you’ll probably find it easier to organize your work if you wrote in a less verbose style.

diff21:

	public int diff21(int n) {
		if (n > 21)
			return 2 * Math.abs(n - 21);
		return Math.abs(n - 21);
	}

Like in the previous example, you could have used the ternary operator, which allows you to condense this method into just one line:

	public int diff21(int n) {
		return (n > 21) ? 2 * Math.abs(n - 21) : Math.abs(n - 21);
	}

The CodingBat website does not refer to the ternary operator, which is why I will not use it in my solutions. Some programmers find the ternary operator confusing. Yet, you should at least know that it exists.

parrotTrouble:

	public boolean parrotTrouble(boolean talking, int hour) {
		return ((talking && hour < 7) || (talking && hour > 20));
	}

A slightly more succinct solution is:

	public boolean parrotTrouble(boolean talking, int hour) {
		return talking && (hour < 7 || hour > 20);
	}

makes10:

	public boolean makes10(int a, int b) {
		return ((a == 10) || (b == 10) || (a + b == 10));
	}

nearHundred:

	public boolean nearHundred(int n) {
		return (Math.abs(100 - n) <= 10 || Math.abs(200 - n) <= 10);
	}
&#91;/sourcecode&#93;

<b>posNeg:</b>
[sourcecode language="Java" gutter="false"]
	public boolean posNeg(int a, int b, boolean negative) {
		if (negative) return a < 0 && b < 0;
		return (a < 0 && b >= 0) || (a >= 0 && b < 0);
	}
&#91;/sourcecode&#93;

<b>notString:</b>
[sourcecode language="Java" gutter="false"]
	public String notString(String str) {
		if (str.length() >= 3 && str.substring(0, 3).equals("not"))
			return str;
		return "not " + str;

	}

Please note that you are not supposed to use str.startsWith().

missingChar:

	public String missingChar(String str, int n) {
		return str.substring(0, n) + str.substring(n + 1);
	}

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


CodingBat: Java Solutions


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


CodingBat is a website containing a couple hundred exercises for the Java and Python programming languages. It is run by Stanford professor Nick Parlante. You may know him from Google’s Python Class or the “Binky Pointer Fun Video.” Last year, he taught Computer Science 101 on Coursera.

CodingBat is a great resource if you’re starting out with programming. It can also serve as an excellent confidence builder if you’re not sure whether to take some computer science classes in college. If you can make your way through that website, you should find a typical first and second course in computer science to be quite manageable. In my case, I used it to supplement CS106A: Programming Methodology, which is hosted at Stanford Engineering Everywhere and Allen B. Downey’s book Think Java.

There are many CodingBat solutions floating around on the Internet already. What I’ve found, though, was that some were quite badly written and rather verbose. I also came across a few instances of macho posturing where people presented solutions that only showed off their alleged brilliance instead of helping others. This includes a recursive solution to a problem that wasn’t even supposed to be solved via recursion. Others used Java functions that negated the purpose of the exercises. I saw one guy posting what he thought to be oh-so smart one-liners. Of course, one could use String.replace() to replace characters in a string, but if you’re supposed to practice loops, you’re only cheating yourself.

I won’t claim that my solutions are the “best” out there. Yet, I do think that my code is well written. I have also made sure to only use the Java functions mentioned on the CodingBat website. CodingBat contains 13 section on Java, with some sections containing up to 30 exercises. Therefore, I will split my solutions over a long series of posts.


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