/** 如圖【1.png】所看到的六角形中,填入1~12的數字。使得每條直線上的數字之和都同樣。圖中,已經替你填好了3個數字,請你計算星號位置所代表的數字是多少?請通過瀏覽器提交答案。不要填寫多余的內容。*/
public class 六角填數 {public static void main(String[] args) {// TODO Auto-generated method stublong start = System.currentTimeMillis();// 從上到下,從左到右,依次為數組賦值int[] a = new int[12];a = init(a);// 初始化數組int[] temp = new int[12];for (int i = 0; i < temp.length; i++) {temp[i] = i + 1;}// 初始化1~12數據提供數組,假設使用了,那么值為其絕對值的負數dsf(0, a, temp);long end = System.currentTimeMillis();print("此程序執行,花費的時間是" + ((end - start) / 1000.0) + "秒.");}public static void print(Object o) {System.out.println(o.toString());}// 初始化數組public static int[] init(int[] a) {a[0] = 1;a[1] = 8;a[11] = 3;return a;}public static int[] calculate(int[] a) {int[] b = new int[6];b[0] = 1 + a[2] + a[5] + a[7];b[1] = 8 + a[2] + a[3] + a[4];b[2] = 11 + a[5] + a[8];b[3] = 1 + a[3] + a[6] + a[10];b[4] = a[7] + a[8] + a[9] + a[10];b[5] = a[4] + a[6] + a[9] + 3;return b;}public static boolean isOk(int[] b) {for (int i = 0; i < b.length; i++) {for (int j = i + 1; j < b.length; j++) {if (b[i] != b[j])return false;}}return true;}public static void dsf(int deep, int[] a, int[] temp) {if (deep == 12)// 表示第13層,也就是a的值已經賦值完成{if (isOk(calculate(a))) {// int b[]=calculate(a);for (int i : a) {System.out.print(i + " ");}System.out.println();}} else {if (deep == 0 || deep == 1 || deep == 11) {dsf(deep + 1, a, temp);// 已經有的值,就不用再次賦值了return;}for (int i = 0; i < temp.length; i++) {if (i == 0 || i == 7 || i ==2) {//已經有的值,就不用再次賦值了continue;}if (temp[i] < 0)continue;a[deep] = temp[i];temp[i] = -temp[i];dsf(deep + 1, a, temp);temp[i] = -temp[i];}}}
}
運算結果:
1 8 9 2 7 10 12 6 5 4 11 3?
此程序執行,花費的時間是0.087秒.