问题
公鸡每只5元,母鸡每只3元,小鸡3只1元。现在有100元,要买100只鸡,问公鸡、母鸡、小鸡各多少?
思路
这是枚举算法思想的典型应用。思路很简单,就是设公鸡为x,母鸡为y,小鸡为z,然后每次遍历判断它们的价钱相加是否等于100元就行,等于就打印组合,否则就跳过。
用法
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Solution.hundredRMBHundredChickens();
}
}
输出
公鸡:0 价值:0 母鸡:25 价值:75 小鸡:75 价值:25
公鸡:4 价值:20 母鸡:18 价值:54 小鸡:78 价值:26
公鸡:8 价值:40 母鸡:11 价值:33 小鸡:81 价值:27
公鸡:12 价值:60 母鸡:4 价值:12 小鸡:84 价值:28
Process finished with exit code 0
实现
package com.company;
public class Solution {
/**
* 百元百鸡问题,枚举法思想的体现。
* x+y+z=100
* 5x+3y+z/3=100
* 其实就是解方程
* 公鸡最少0,最多100/5=20.
* 母鸡最少0,最多100/3=33.
* 小鸡仔就是100-x-y
*/
static public void hundredRMBHundredChickens() {
int sumMoney = 100;
int sumCount = 100;
int cockPrice = 5;
int henPrice = 3;
int cockCount = sumMoney / cockPrice;
int henCount = sumMoney / henPrice;
for (int counter = 0;counter <= cockCount;counter++) {
for (int counter0 = 0;counter0 <= henCount;counter0++) {
int remainCount = sumCount - counter - counter0;
if (remainCount % 3 == 0 && counter * cockPrice + counter0 * henPrice + remainCount / 3 == 100) {
System.out.print("公鸡:" + counter + " 价值:" + (counter * cockPrice));
System.out.print(" 母鸡:" + counter0 + " 价值:" + (counter0 * henPrice));
System.out.println(" 小鸡:" + remainCount + " 价值:" + (remainCount / 3));
}
}
}
}
}