穷举算法
2019-02-15 本文已影响1人
FORGET_静哥哥
package com.xj.www.algo;
import java.util.Scanner;
/**
* 穷举算法
* @author xiongjing
*
*/
public class AlgorithmTest {
// chichen鸡的个数,rabbit兔的个数
static int chichen, rabbit;
// 算法具体实现
public static int qiongJu(int head, int foot) {
int re, i, j;
re = 0;
for (i = 0; i <= head; i++) {
j = head - i;
// 鸡的脚+兔的脚=总数量
if (i * 2 + j * 4 == foot) {
re = 1;
chichen = i;
rabbit = j;
}
}
return re;
}
// 程序主入口
public static void main(String[] args) {
int re, head, foot;
System.out.println("穷举算法求解鸡兔同笼问题:");
System.out.println("请输入头数:");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
head = sc.nextInt();
System.out.println("请输入脚数:");
foot = sc.nextInt();
re = qiongJu(head, foot);
if (re == 1) {
System.out.println("鸡有" + chichen + "只,兔有" + rabbit + "只");
} else {
System.out.println("无法求解");
}
}
}