Landei
  • Member for 10 years, 9 months
  • Last seen more than 1 year ago
Remove Last Comma
98 votes

for ( String p : paramList ) { if (result.length() > 0) result.append( ", " ); result.append( p ); }

View answer
Optimizing Java Anagram checker (compare 2 strings)
Accepted answer
28 votes

Start with a simple, easy to understand version. Try to reuse API functions. import java.util.Arrays; ... public boolean areAnagrams(String s1, String s2) { char[] ch1 = s1.toCharArray(); ...

View answer
Return explicitly or implicitly?
Accepted answer
19 votes

Usually you get the advice to avoid multiple exit points in a method. However the reasoning behind this rule is only valid if you have long methods - and then you have more to worry about than exit ...

View answer
Simple function in Java
Accepted answer
16 votes

I wouldn't search for a "rule", just store the "truncate points" private final static int[] truncateSizes = {10,7,5,3,1,0}; public int generateListSize(int listSize) { for(int truncateSize : ...

View answer
Country selector: if or ternary?
11 votes

If you can use Java 7, you can put Strings in switch statements (this came with JSR334): String fileId = "CPP420.A2_2012072416244467745"; String country = ""; String fileReg = fileId.split("...

View answer
"Deal or No Deal" console game
11 votes

There are a few things, I'll expand on this over time. First, always write method and variable names in lowerCamelCase. Everything starting with an uppercase letter wil be considered a class or a ...

View answer
Determining if f(n) = n^2 + 3n + 5 is ever divisible by 121
Accepted answer
11 votes

I don't know Lisp, but you can speed up the calculation by observing that n² + 3n + 5 is never divisible by 11 (and hence never divisible by 121), except when n mod 11 == 4. If you check the ...

View answer
Game of Life in Haskell
11 votes

Refactor's answer is excellent and captures most points. One thing in your code which sticks out is the overuse of if. E.g. consider get_bounds xs = if null xs then (0, 0) else (length xs, ...

View answer
Rot -n algorithm in Java
10 votes

First, your process method violates the Single Responsibility Principle: It calculates something, and it prints it out. Such coupling makes it inflexible. It's better to return a String, and letting ...

View answer
Changing bits in given big strings
9 votes

Don't use arrays as representation for binary numbers. BitSet could save you a lot of work. Except from that, your code is very repetitive. An example: if ((A[idx] == '0' && B[idx] == '1'...

View answer
Java Implementation of Quick Sort
9 votes

I see one small improvement. Instead of... i++; while ( i< r && a[i] < x) i++; j--; while (j>p && a[j] > x) j--; ...you can write: do { i++; } while (i < r &...

View answer
Blackjack odds calculator
8 votes

Additionally to the excellent answer from ratchet freak: Always encode data according to their meaning, don't use another type just because it seems more "convenient". E.g. variables like soft17 ...

View answer
Empty method in abstract class
Accepted answer
8 votes

If you are really sure that an empty method body is okay for most sub-classes, you could follow the example of Swing listeners (e.g. WindowListener / WindowAdapter): Make the methods in your Foo class ...

View answer
Extracting the five most frequent queries from a log file
Accepted answer
8 votes

Your names could be improved, e.g. hm isn't a good name for a member variable. You could replace the HashMap by a multiset implementation, e.g. HashMultiset from Google Guava. Then you get putWord ...

View answer
Decided to learn Scala. Here's an attempt at a Cloth simulation
Accepted answer
8 votes

for (row <- grid) { for (p <- row) { //should be written as: for(row <- grid; p <- row) { Tuple2("bla", 42) //should be written as ("bla", 42) I don't really understand why you use ...

View answer
asMap-implementation for Java (based on Arrays.asList)
Accepted answer
8 votes

In my opinion MapBuilder should contain a Map, not extend one. Another possible design would be to use a single call with varargs: public class MapUtil { public static <K,V> Map<K,V> ...

View answer
Text-based RPG in Java
7 votes

IO: You use everywhere System.out.println and System.in (BTW, Scanner is much more convenient than a Reader). Even if you want to switch from console output to a simple Swing application with little ...

View answer
Scala list folding
Accepted answer
7 votes

There is already a sum function: def totalCost = value + children.map(_.totalCost).sum

View answer
Reversing the digits of an integer
6 votes

Why not throw in some arithmetics? private static String reverseInt(int i) { StringBuilder sb = new StringBuilder(); for(int d = i; d != 0; d /=10) { sb.append(d % 10); } ...

View answer
Reorder a list of courses, given their prerequisites
6 votes

Yes, this code is hard to follow. Some thoughts: use generics, e.g. private List<String> prerequisites Provide useful constructors. E.g. Does a course without name make any sense? If not, the ...

View answer
Ways to improve my coding test FizzBuzz solution for a TDD role?
6 votes

You can avoid the special case for FizzBuzz No need to hard-code the limits It's not really bad if you have multiple returns in a short (!) method, but it should be avoided if you have an equally ...

View answer
Approach to string split by character in Haskell
6 votes

Another version, using the Prelude function break. groupBy :: String -> Char -> [String] groupBy str delim = let (start, end) = break (== delim) str in start : if null end ...

View answer
Refactoring code duplication so the same textArea is not used in 4 different classes
Accepted answer
6 votes

Write your own class: class MyTextArea extends JTextArea{ private final List<Foo> list; MyTextArea(int row, int col, List<Foo> list) { super(row, col); this....

View answer
Getting the largest element in an array using recursion
6 votes

I would use a helper function, and I would avoid copying the array (using indices instead): public static int getLargest(int ... myArray) { return getLargest(myArray, 0, myArray.length); } ...

View answer
How can I avoid unchecked cast warning in my generic recursive Iterator?
Accepted answer
6 votes

I don't think you can do anything about this. You have to cast here, and in the process you lose all information about the type parameter: The compiler can't know that if you have a RecursiveElement, ...

View answer
BMI calculator/assessor
5 votes

Not bad for a beginner, and I agree with Ben Aaronson's comments. Maybe not now, but when you progress, you should change some things: Break the code up in logical parts (here: methods), and every ...

View answer
Function which finds the sum of factors from one to N
5 votes

Just a little remark as an addition to the other excellent answers: Don't repeat yourself, always try to to find an abstraction for common tasks. E.g. If you need to time methods, don't do it "...

View answer
BestApproximationDiv2 problem in Haskell
Accepted answer
5 votes

Hmmm, not much ideas, only syntax: showResult :: (Int, Int, Int) -> String showResult (a, b, x) = concat [show a, "/", show b, " has ", show x, " exact digits"] preciseDivision :: Int -> Int -&...

View answer
Sums of perfect powers
5 votes

That's how I would write it: import java.util.ArrayList; import java.util.List; public class SumsOfPerfectPowers { private final static int SIZE = 5000001; private final boolean[] result = ...

View answer
Finding "lucky numbers"
Accepted answer
5 votes

While everybody mentioned optimizing isPrime, nobody spotted the one glaring ineffiency: You can break the loop as soon as i*i > sum. Further you can skip the even divisors except 2: public static ...

View answer