Monthly Archives: January 2013

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.