public class SqlCreator { public static String createQueryString(int[][] problem) { final int n = problem.length; final int m = (int) java.lang.Math.sqrt(n); StringBuilder selectPhrase=new StringBuilder("SELECT "); StringBuilder fromPhrase=new StringBuilder(" FROM "); StringBuilder wherePhrase=new StringBuilder(" WHERE "); String label1, label2; // 1行1列なら「1_1」というようなラベル String item1, item2; // where節の項 for (int r1 = 0; r1 < n; ++r1) { for (int c1 = 0; c1 < n; ++c1) { label1 = (r1 + 1) + "_" + (c1 + 1); if (problem[r1][c1] == 0) { item1 = "t"+label1+".n"; selectPhrase.append(item1 + " AS v" + label1+","); fromPhrase.append("x t" + label1+","); } else item1 = Integer.toString(problem[r1][c1]); for (int r2 = 0; r2 < n; ++r2) { // 問題の数字をもう一度列挙する for (int c2 = 0; c2 < n; ++c2) { if (n * r1 + c1 < n * r2 + c2) { // セルのペアに対して、 if (problem[r1][c1] == 0 || problem[r2][c2] == 0) { // どちらかが未定の場合に条件句を作る if ((r1 == r2) // 条件句を作るのは、行が同じ || (c1 == c2) // あるいは列が同じ || (r1 / m == r2 / m && c1 / m == c2 / m)) { // あるいはブロックが同じもの label2 = (r2 + 1) + "_" + (c2 + 1); if (problem[r2][c2] == 0) item2="t" + label2 + ".n"; else item2=Integer.toString(problem[r2][c2]); //条件の重複を削除してもよい(9x9に限定するなら_を削除してもよい) // String constraint; // if (0"+item2; // else constraint=item2+"<>"+item1; // if (wherePhrase.indexOf(constraint)<0) wherePhrase.append(constraint+" AND "); //簡単に wherePhrase.append(item1+"<>"+item2+" AND "); } } } } } } } return selectPhrase.substring(0, selectPhrase.length()-1) // 最後のコンマを削除 +fromPhrase.substring(0, fromPhrase.length()-1) // 最後のコンマを削除 +wherePhrase.substring(0, wherePhrase.length()-5)+";"; // 最後の「 AND 」を削除 } }