12球问题的java算法

来源:互联网 发布:材料仿真软件 编辑:程序博客网 时间:2024/05/17 20:26

问题:12个球中有一个重量异常的球。请你用无砝码天平称三次,找出这个球来,并说出它比普通球轻或重。

    // 一組測試數據,將12個球做好標記
    double a = 1.0, b = 1.0, c = 1.0, d = 1.0, e = 0.9, f = 1.0, g = 1.0, h = 1.0, i = 1.0, j = 1.0, k = 1.0, l = 1.0;
    // 顯示結果
    String result = null;

    // 將12個球分成3組進行比較
    if ((a + b + c + d) == (e + f + g + h)) { // 1
        // 異常球在i,j,k,l中
        if ((a + b + c) == (i + j + k)) { // 2
            if (a > l) { // 3
                result = "l球輕";
            } else {
                result = "l球重";
            }
        } else if ((a + b + c) > (i + j + k)) { // 2
            if (i == j) { // 3
                result = "k球輕";
            } else if (i > j) {
                result = "j球輕";
            } else {
                result = "i球輕";
            }
        } else { // 2
            if (i == j) { // 3
                result = "k球重";
            } else if (i > j) {
                result = "i球重";
            } else {
                result = "j球重";
            }
        }
    } else if ((a + b + c + d) > (e + f + g + h)) { // 1
        // 異常球在a,b,c,d,e,f,g,h,去掉f,g,h,將a,i,j,k和e,b,c,d分成兩組
        if ((a + i + j + k) == (e + b + c + d)) { // 2
            // 異常球在f,g,h中
            if (f == g) { // 3
                result = "h球輕";
            } else if (f > g) {
                result = "g球輕";
            } else {
                result = "f球輕";
            }
        } else if ((a + i + j + k) > (e + b + c + d)) { // 2
            // 異常球在a,e中,i為正常球
            if (a > i) {
                result = "a球重";
            } else {
                result = "e球轻";
            }
        } else { // 2
            // 異常球在b,c,d中
            if (b == c) { // 3
                result = "d球重";
            } else if (b > c) {
                result = "b球重";
            } else {
                result = "c球重";
            }
        }
    } else { // 1(a + b + c + d) < (e + f + g + h)
        // 異常球在a,b,c,d,e,f,g,h,去掉b,c,d,將a,f,g,h和e,i,j,k分成兩組
        if ((a + f + g + h) == (e + i + j + k)) { // 2
            // 異常球在b,c,d中
            if (b == c) { // 3
                result = "d球輕";
            } else if (b > c) {
                result = "c球輕";
            } else {
                result = "b球輕";
            }
        } else if ((a + f + g + h) > (e + i + j + k)) { // 2
            // 異常球在f,g,h中
            if (f == g) { // 3
                result = "h球重";
            } else if (f > g) {
                result = "f球重";
            } else {
                result = "g球重";
            }
        } else { // 2
            // 異常球在a,e中,i為正常球
            if (e > i) { // 3,
                result = "e球重";
            } else {
                result = "a球輕";
            }
        }
    }

    // 打印結果
    System.out.println(result);


http://doctang.blog.163.com/blog/static/23665087200941611369875/

原创粉丝点击