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; } } }
相关文章推荐
- Java 的 Socket 服务器和客户端通信的例子 存在一个小问题
- Java中一个运用反射解决问题例子+思考
- 《Thinking in java》第四版中的例子tupeinfo/SweetShop.java存在问题,全限定名;forName()方法
- java线程同步问题(一个理解wait()与notify()的例子)
- 鸡兔同笼问题java暴力求解算法
- 《spring in action》第一章DI例子报java.lang.NoClassDefFoundError问题
- java--String常量池问题的几个例子
- java 多线程经典例子——生产者与消费者的问题
- java 鸡兔同笼问题
- java多线程同步问题(生产者和消费者)典型例子
- java学习多线程中遇到的例子:做饭买盐问题
- Java 的 Socket 服务器和客户端通信的例子 存在一个小问题
- 动态规划简单例子(数塔问题)java
- Java String 常量池问题的几个例子
- java线程冲突问题——不安全的线程例子
- (转载) java--String常量池问题的几个例子
- java 接口实现简单并能说明问题的例子
- java--String常量池问题的几个例子
- java--String常量池问题的几个例子
- java--String常量池问题的几个例子