Author Archives: Gregor Ulm

CodingBat: Java. Warmup-2, Part II


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


Here is the second part of the solutions to Warmup-2:

stringMatch:

public int stringMatch(String a, String b) {
		int count = 0;
		int minLength = Math.min(a.length(), b.length());
		for (int i = 0; i < minLength - 1; i++) {
			if (a.substring(i, i + 2).equals(b.substring(i, i + 2)))
				count++;
		}
		return count;
}

stringX:

public String stringX(String str) {
		String result = "";
		if (str.length() <= 2) return str;
		
		result += str.charAt(0);
		for (int i = 1; i < str.length() - 1; i++) {
			if (str.charAt(i) != 'x') result += str.charAt(i);
		}
		result += str.charAt(str.length() - 1);
		return result;
}

altPairs:

public String altPairs(String str) {
		String result = "";
		for (int i = 0; i < str.length(); i += 4) {
			result += str.charAt(i);
			if (i + 1 < str.length())
				result += str.charAt(i + 1);
		}
		return result;
}

stringYak:

public String stringYak(String str) {
		int posYak = str.indexOf("yak");
		while (posYak != -1) {
			str = str.substring(0, posYak) + str.substring(posYak + 3);
			posYak = str.indexOf("yak");
		}
		return str;
  }

There is a mistake in the description on the website, which says “Given a string, return a version where all the “yak” are removed, but the “a” can be any char.” All test cases use “yak”, though, which simplifies the solution.

Also, please note that the purpose of exercises such as this one is to familiarize yourself with loops. Using str.replace() would completely defeat this purpose.

array667:

public int array667(int[] nums) {
		int count = 0;
		for (int i = 0; i < nums.length - 1; i++)
			if (nums[i] == 6 && (nums[i + 1] == 6 || nums[i + 1] == 7))
				count++;
		return count;
}

noTriples:

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

has271:

public boolean has271(int[] nums) {
		for (int i = 0; i < nums.length - 2; i++)
			if (nums[i] == nums[i + 1] - 5
					&& (Math.abs((nums[i + 2] + 1) - nums[i]) <= 2))
				return true;
		return false;
}

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


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.