您的位置:首页 > 编程语言 > Java开发

Java 小例子:行列式和鸡兔同笼问题

2009-11-24 09:59 274 查看
鸡兔同笼问题就是二元一次方程组,高等数学里面用行列式来解此方程。具体过程可 Google “行列式 二元一次方程组
”。对于鸡兔同笼问题还要加上一个限制:方程的解必须是正整数。



下面是代码示例:

/**
 * 鸡兔同笼问题。解法请 Google:“行列式 二元一次方程组”
 *
 * @author yiding.he
 */
public class BinaryLinearEquationGroup {
 
    // 程序入口
    public static void main(String[] args) {
        int heads = 10;
        int legs = 36;
 
        int[] result = calculate(new int[][]{
                {1, 1, heads}, // 鸡和兔子各有一个头,共 10 个;
                {2, 4, legs}   // 鸡有两只脚,兔子四只脚,共 36 只。
        });
 
        if (result != null && result.length > 0) {
            System.out.println("结果:鸡有 " + result[0] + " 只,兔子有 " + result[1] + " 只。");
        } else if (result == null) {
            System.out.println("该题无解。");
        } else if (result.length == 0) {
            System.out.println("该题有无穷解。");
        }
    }
 
    /**
     * 解二元一次方程组,方程组的解必须是正整数,否则视为无解。
     *
     * @param params 方程组参数
     *
     * @return 返回 null 表示无解,返回空数组表示无穷解,否则表示正解。
     */
    private static int[] calculate(int[][] params) {
        Matrix2 delta = new Matrix2(new int[][]{
                {params[0][0], params[0][1]},
                {params[1][0], params[1][1]}
        });
 
        Matrix2 delta_x = new Matrix2(new int[][]{
                {params[0][2], params[0][1]},
                {params[1][2], params[1][1]}
        });
 
        Matrix2 delta_y = new Matrix2(new int[][]{
                {params[0][0], params[0][2]},
                {params[1][0], params[1][2]}
        });
 
        // 判定无穷解或无解的条件
        if (delta.isZero() && delta_x.isZero() && delta_y.isZero()) {
            return new int[]{};
        } else if (delta.isZero() && (!delta_x.isZero() || !delta_y.isZero())) {
            return null;
        }
 
        int[] result = {
                delta_x.value() / delta.value(),
                delta_y.value() / delta.value()
        };
 
        // 结果必须是整数
        if (delta_x.value() % delta.value() != 0 || delta_y.value() % delta.value() != 0) {
            return null;
        }
 
        // 结果不能是负数
        if (result[0] < 0 || result[1] < 0) {
            return null;
        }
        return result;
    }
 
    // 二阶行列式
    private static class Matrix2 {
 
        private int[][] data;
 
        private Matrix2(int[][] data) {
            this.data = data;
        }
 
        public int value() {
            return data[0][0] * data[1][1] - data[0][1] * data[1][0];
        }
 
        public boolean isZero() {
            return value() == 0;
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: