Each of the tasks below shows one or more "brute force" solutions (in
Java),
an explanation of why it's a stupid solution, and then a better
solution.
Study and learn, grasshopper. Write simple, concise, easy
to maintain code and earn the respect of your peers.
Brute Force Solution: square = Math.pow(x,2);
What's wrong with it?
Similarly, Math.sqrt(x) is better than Math.pow(x, 0.5);
Brute Force Solution A:
switch (letter)Brute Force Solution B
{
case 'A': return 0;
case 'B': return 1;
case 'C': return 2;
case 'D': return 3;
case 'E': return 4;
case 'F': return 5;
case 'G': return 6;
case 'H': return 7;
case 'I': return 8;
case 'J': return 9;
case 'K': return 10;
case 'L': return 11;
case 'M': return 12;
case 'N': return 13;
case 'O': return 14;
case 'P': return 15;
case 'Q': return 16;
case 'R': return 18;
case 'S': return 18;
case 'T': return 19;
case 'U': return 20;
case 'V': return 21;
case 'W': return 22;
case 'X': return 23;
case 'Y': return 24;
case 'Z': return 25;
default: return 0;
}
Similar to solution A except uses multiple IF statements.
What's wrong with it?
Better Solution
return (letter - 'A');
Brute Force Solution A:
return (letter == '0') || (letter == '1') || (letter ==
'2')
|| (letter == '3') ||
(letter == '4') || (letter == '5') ||(letter
== '6') ||(letter == '7') ||
(letter == '8') ||(letter == '9') ;
Brute Force Solution B:
return (letter >= '0') && (letter <= '9');
What's wrong with it?
Better Solution
return Character.isDigit(letter);
Brute Force Solution
if (mystack.isEmpty() == true) dosomething;
What's wrong with it?
Better Solution
if (mystack.isEmpty()) dosomething;
Brute Force Solution
if (size > 0)
return true;
else
return false;
What's wrong with it?
return size > 0;
Brute Force Solution
private int[] scores = new int[10];
scores[0] = 5;
scores[1] = 3;
scores[2] = 7;
scores[3] = 8;
scores[4] = 2;
scores[5] = 3;
scores[5] = 5;
scores[7] = 6;
scores[8] = 9;
scores[9] = 3;
What's wrong with it?
private int[] scores = {5, 3, 7, 8, 2, 3, 5, 6, 9, 3};
Brute Force Solution
if (turn == 1) color = 1;
elseif (turn == 2) color = 2;
elseif (turn == 3) color = 3;
elseif (turn == 4) color = 4;
elseif (turn == 5) color = 5;
elseif (turn == 6) color = 6;
elseif (turn == 7) color = 7;
elseif (turn == 8) color = 8;
else color = 9;
What's wrong with it?
color = turn;
Brute Force Solution
public static int stringToInt(String input)
{
int result = 0;
int sLen = input.length();
for (int i = 0; i < sLen; i++)
{
result = 10 * result +
((int) (input.charAt(i))
- 48);
}
return result;
}
What's wrong with it?
Java already has a function to do this. This is a clear symptom of ignorance of the language. This is only one of many examples of this kind of brutishness. Others functions already available in Java for which ignorant programmers write their own code include:
Better Solution
result = Integer.parseInt(input);
Brute Force Solution
if (player ==1)
{
if (numberOfPlayers >= 2) player = 2;
else player = 1
}
else if (player == 2)
{
if (numberOfPlayers >= 3) player = 3;
else player = 1
}
.
.
. (repeats five more times!)
.
else if (player == 8)
{
if (numberOfPlayers >= 9) player = 9;
else player = 1
}
What's wrong with it?
Best Solution:
player = (player % numberOfPlayers) + 1;
Brute Force Solution
for(int i = 0; i <= 12; i++) { switch (i) { Case 0: formattedPhoneNumber.append("(") Case 1: formattedPhoneNumber.append(cleanPhoneNumber.Chars(0)) Case 2: formattedPhoneNumber.append(cleanPhoneNumber.Chars(1)) Case 3: formattedPhoneNumber.append(cleanPhoneNumber.Chars(2)) Case 4: formattedPhoneNumber.append(") ") Case 5: formattedPhoneNumber.append(cleanPhoneNumber.Chars(3)) Case 6: formattedPhoneNumber.append(cleanPhoneNumber.Chars(4)) Case 7: formattedPhoneNumber.append(cleanPhoneNumber.Chars(5)) Case 8: formattedPhoneNumber.append("-") Case 9: formattedPhoneNumber.append(cleanPhoneNumber.Chars(6)) Case 10: formattedPhoneNumber.append(cleanPhoneNumber.Chars(7)) Case 11: formattedPhoneNumber.append(cleanPhoneNumber.Chars(8)) Case 12: formattedPhoneNumber.append(cleanPhoneNumber.Chars(9)) } } return formattedPhoneNumber.toString();
What's wrong with it?
Brute Force Solution The Brute Force solution is to add each new item to the end of the list, then call Collections.sort() to sort the entire list.
sortedList.add(item);
Collections.sort(sortedList);
What's wrong with it?
While it certainly is an obvious solution, the performance hit from sorting the entire list can surprise you with huge penalties if your application has to scale up.// Search for the non-existent item
int index = Collections.binarySearch(sortedList, item);
// Add the non-existent item to the list
if (index < 0)
{
sortedList.add(-index-1, item);
}
A common algorithm pattern is to loop a number of times and use the
loop counter to index some data structure.
Brute Force Solution:
for(int direction=0; direction < 4; direction++)What's wrong with it?
{
switch (direction)
{
case 0:
System.out.println("Some big calculation using 0");
break;
case 1:
System.out.println("Some big calculation using 90");
break;
case 2:
System.out.println("Some big calculation using 180");
break;
case 3:
System.out.println("Some big calculation using 270");
break;
}
}
for(int direction=0; direction < 4; direction++)
{
int degrees = direction * 90;
System.out.println("Some big calculation using " + degrees);
}
final int[] degrees = {0,90,180,270};
System.out.println("Some big calculation using " + degrees[direction]);
Frequently programmer store elapsed time in seconds, but want to display it in common MM:SS format.
Brute Force Solution:
/** * getTime returns a string representing the current formatted time elapsed. */ private String getTime() { final int kSecondsPerMinute = 60; final int kTwoDigit = 10; int minutes = time / kSecondsPerMinute; int seconds = time % kSecondsPerMinute; String colon, minZero; // Set the colon spacing if the current seconds is a single digit. if(minutes < kTwoDigit) { minZero = "0"; } // Set the colon spacing if the current seconds is a double digit. else { minZero = ""; } // Set the colon spacing if the current minutes is a single digit. if(seconds < kTwoDigit) { colon = ":0"; } // Set the colon spacing if the current minutes is a double digit. else { colon = ":"; } return(minZero + minutes + colon + seconds); }
java.text.NumberFormat formatter = new java.text.DecimalFormat("00"); return formatter.format(minutes) + ":" + formatter.format(seconds);
Brute Force Solution:
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; String result = ""; for (int index = 0; index < word.length(); index++) { boolean isVowel = false; for (int index2 = 0; index2 < vowels.length; index2++) { if (word.charAt(index) == vowels[index2]) { isVowel = true; } } if (!isVowel) { result += word.charAt(index); } }
result = word.replaceAll("[aeiou]","");
Brute Force Solution:
private final int kSeven = 7;What's wrong with it?
private final int kDaysInWeek = 7;Now we know what 7 refers to; the named constant provides meaningful information.
public String getValueString() { String valName = ""; // Given a value replaces it with an appropriate string switch (value) { case 1: valName = "Ace"; break; case 2: valName = "Two"; break; case 3: valName = "Three"; break; case 4: valName = "Four"; break; case 5: valName = "Four"; break; case 6: valName = "Six"; break; case 7: valName = "Seven"; break; case 8: valName = "Eight"; break; case 9: valName = "Nine"; break; case 10: valName = "Ten"; break; case 11: valName = "Jack"; break; case 12: valName = "Queen"; break; case 13: valName = "King"; break; } return valName; }What's wrong with it?
String[] ranknames = {"","Ace","Two","Three", "Four","Five","Six","Seven", "Eight","Nine","Ten","Jack","Queen","King"} return ranknames[value];
public static final int RED = 1; public static final int YELLOW = 2; public static final int GREEN = 3;or
public static final String LEFT = " < "; public static final String RIGHT = " > "; public static final String CENTER = " . ";What's wrong with it?
String letters = "ABCDEF"; String[] array = letters.split(""); ListWhat's wrong with it?list = Arrays.asList(array); for (String item: list) { System.out.println(item); }
for (int pos=0; pos<letters.length(); pos++) { System.out.println(letters.charAt(pos)); }Better Solution B
for (Character ltr: letters.toCharArray()) { System.out.println(ltr); }
Last modified on 01/20/2015 15:21:25
Home