我同意BlueNovember,但如果你想要一個更「數學」的解決方案檢查這一點。首先創建一個字符網格,然後返回他們都具有不同於過去了...有點兒沒用的鍵的距離小於2,但它是一個不錯的鍛鍊:)
public class Test {
static String chars = "qwertyuiopasdfghjkl;zxcvbnm,.";
public static void main(String[] args) {
System.out.println(getNeighboringKeys('f'));
System.out.println(getNeighboringKeys('u'));
System.out.println(getNeighboringKeys('m'));
System.out.println(getNeighboringKeys('q'));
}
public static String getNeighboringKeys(char key) {
StringBuffer result = new StringBuffer();
for (char c : chars.toCharArray()) {
if (c!=key && distance(c,key)<2) {
result.append(c);
}
}
return result.toString();
}
public static double distance(char c1, char c2) {
return Math.sqrt(Math.pow(colOf(c2)-colOf(c1),2)+Math.pow(rowOf(c2)-rowOf(c1),2));
}
public static int rowOf(char c) {
return chars.indexOf(c)/10;
}
public static int colOf(char c) {
return chars.indexOf(c) % 10;
}
}
謝謝。 getNeighboringKeys方法可以被優化,以便儘管較少的操作。 – hashable 2010-01-23 00:50:30
優化會產生過小的性能提升,以證明額外的時間去嘗試和優化它。我的意思是,只有80鍵在網格或多或少,你很少會調用這個。不過是我的客人,如果你做到這一點:) – 2010-02-12 11:38:24