Category Archives: CodingBat: Java

CodingBat: Java. String-1, Part IV


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


startWord:

public String startWord(String str, String word) {
		if (word.length() > str.length()) return "";
		if (str.substring(0, word.length()).equals(word)) return word;
		if (str.substring(1, word.length()).equals(word.substring(1)))
			return str.charAt(0) + word.substring(1);
		return "";
}

withoutX:

public String withoutX(String str) {
		if (str.length() == 0) return "";
		if (str.charAt(0) == 'x') str = str.substring(1);
		if (str.length() > 0 && str.charAt(str.length() - 1) == 'x')
			str = str.substring(0, str.length() - 1);
		return str;
}

withoutX2:

public String withoutX2(String str) {
if (str.length() < 2) return "";String result = ""; if (str.charAt(0) != 'x') result += str.charAt(0); if (str.charAt(1) != 'x') result += str.charAt(1); result += str.substring(2); return result; } [/sourcecode]The website said that "withoutX2" was a bit trickier than it looks like. However, the key is to not directly manipulate the input string but instead create a new one. Then this exercise is simpler than the preceding one.


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


CodingBat: Java. String-1, Part III


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


atFirst:

public String atFirst(String str) {
		if (str.length() == 0) return "@@";
		if (str.length() == 1) return str + "@";
		return str.substring(0, 2);
}

Let’s talk about style and conciseness for a moment. My solution of “atFirst” is probably a bit shorter than what some coding style guides would suggest. If you look at it, you’ll have no problem with the control flow, and it takes a mere three lines. Furthermore, there is no visual clutter.

On the other hand, some people tend to add if/else structures when they are unnecessary. This is a waste of time and screen space. But let’s just follow some “best practices” and keep the return statements on separate lines. The result is quite unsightly: Six lines instead of three, and two superfluous key words. Three versus six lines might not be a big absolute difference, but imagine you worked on a program that is several thousand lines long. You can easily waste a couple hundred lines like this.

public String atFirst(String str) {
		if (str.length() == 0)
			return "@@";
		else if (str.length() == 1)
			return str + "@";
		else
			return str.substring(0, 2);
}

If this wasn’t bad enough, you can of course add curly braces and end up with code that’s just painful to look at:

public String atFirst(String str) {
		if (str.length() == 0) {
			return "@@";
		} else if (str.length() == 1) {
			return str + "@";
		} else {
			return str.substring(0, 2);
		}
	}

This isn’t even the worst you could do. For instance, the so-called Allman style dictates that you put braces on separate lines.

lastChars:

public String lastChars(String a, String b) {
		if (a.length() == 0 && b.length() != 0)
			return "@" + "" + b.charAt(b.length() - 1);
		if (b.length() == 0 && a.length() != 0)
			return a.charAt(0) + "@";
		if (a.length() == 0 && b.length() == 0)
			return "@@";
		return a.charAt(0) + "" + b.charAt(b.length() - 1);
}

Without the empty string, the return value would be a numerical ASCII value.

conCat:

public String conCat(String a, String b) {
		if (a.length() != 0 && b.length() != 0
				&& a.charAt(a.length() - 1) == b.charAt(0))
			return a + b.substring(1);
		return a + b;
}

lastTwo:

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

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

frontAgain:

public boolean frontAgain(String str) {
		int len = str.length();
		if (len < 2) return false;
		return str.substring(0, 2).equals(str.substring(len - 2));
}
&#91;/sourcecode&#93;

<b>minCat:</b>
[sourcecode language="Java" gutter="false"]
public String minCat(String a, String b) {
		int lenA = a.length();
		int lenB = b.length();
		if (lenA == lenB) return a + b;
		if (lenA > lenB) return a.substring(lenA - lenB) + b;
		return a + b.substring(lenB - lenA);
}

extraFront:

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

<b>without2:</b>
[sourcecode language="Java" gutter="false"]
public String without2(String str) {
		int len = str.length();
		if (len == 0 || len == 2) return "";
		if (len == 1) return str;
		if (str.substring(len - 2).equals(str.substring(0, 2)))
			return str.substring(2);
		return str;
}

deFront:

public String deFront(String str) {      
		if (str.charAt(0) == 'a' && str.charAt(1) != 'b')
			return str.charAt(0) + str.substring(2);
		if (str.charAt(0) != 'a' && str.charAt(1) == 'b')
			return str.substring(1);
		if (str.charAt(0) == 'a' && str.charAt(1) == 'b')
			return str;
		return str.substring(2);
}

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


CodingBat: Java. String-1, Part II


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


left2:

public String left2(String str) {
		return str.substring(2) + str.substring(0, 2);
}

right2:

public String right2(String str) {
		int len = str.length();
		return str.substring(len - 2) + str.substring(0, len - 2);
}

theEnd:

public String theEnd(String str, boolean front) {
		if (front) return str.substring(0, 1);
		return str.substring(str.length() - 1);
}

withouEnd2:

public String withouEnd2(String str) {
		if (str.length() <= 2) return "";
		return str.substring(1, str.length() - 1);
}

middleTwo:

public String middleTwo(String str) {
		int len = str.length();
		return str.substring(len / 2 - 1, len / 2 + 1);
}

endsLy:

public boolean endsLy(String str) {
		int len = str.length();
		if (len < 2) return false;
		return (str.substring(len - 2).equals("ly"));
}

nTwice:

public String nTwice(String str, int n) {
		return str.substring(0, n) + str.substring(str.length() - n);
}

twoChar:

public String twoChar(String str, int index) {
		if (index < 0 || index + 2 > str.length())
			return str.substring(0, 2);
		return str.substring(index, index + 2);
}

middleThree:

public String middleThree(String str) {
		int len = str.length();
		if (len == 3) return str;
		return str.substring(len / 2 - 1, len / 2 + 2);
}

hasBad:

public boolean hasBad(String str) {
		if (str.length() <= 2) return false;
		if (str.length() == 3) return str.substring(0, 3).equals("bad");
		return str.substring(0, 3).equals("bad")
				|| str.substring(1, 4).equals("bad");
}

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


CodingBat: Java. String-1, Part I


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


In the String-1 section on CodingBat you have the chance to familiarize yourself with basic string operations. The exercises do get a bit repetitive, but you should be able to quickly go through all of them and move on to more challenging parts.

All solutions were successfully tested on 19 January 2013.

helloName:

public String helloName(String name) {
		return "Hello " + name + "!";
}

makeAbba:

public String makeAbba(String a, String b) {
		return a + b + b + a;
}

makeTags:

public String makeTags(String tag, String word) {
		return "<" + tag + ">" + word + "</" + tag + ">";
}

makeOutWord:

public String makeOutWord(String out, String word) {
		return out.substring(0,2) + word + out.substring(2);
}

extraEnd:

public String extraEnd(String str) {
		int len = str.length();
		return str.substring(len - 2) + str.substring(len - 2)
				+ str.substring(len - 2);
}

firstTwo:

public String firstTwo(String str) {
		if (str.length() < 2) return str;
		return str.substring(0, 2);
}

firstHalf:

public String firstHalf(String str) {
		return str.substring(0, str.length()/2);
}

withoutEnd:

public String withoutEnd(String str) {
		return str.substring(1, str.length() - 1);
}

comboString:

public String comboString(String a, String b) {  
		if (a.length() > b.length()) return b + a + b;
		return a + b + a;
}

nonStart:

public String nonStart(String a, String b) {
		return a.substring(1) + b.substring(1);
}

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


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.