天平称重问题
/************************************************************************
* 现有4个重量均不等的砝码,每个重量都是整数克,总重量为40克,放在天平上可以称出1~40克的
* 物体。求这4个砝码各多少克。
* java版
************************************************************************/
public class TWeight {
//定义4个砝码的重量w1,w2,w3,w4
private int w1,w2,w3,w4;
//定义要求的重量总和weight
private final int MAXWEIGHT=34;
private final int TOTALWEIGHT=40;
public TWeight(){
//4个砝码,w1+w2+w3+w4=40,且w1,w2,w3,w4均为整数,假设不相等(假设w1<w2<w3<w4)故最大为34
this.w1=0;
this.w2=0;
this.w3=0;
this.w4=0;
}
public void calculate(){
for(w1=1;w1<MAXWEIGHT;w1++)
for(w2=w1+1;w2<MAXWEIGHT;w2++)
for(w3=w2+1;w3<MAXWEIGHT;w3++)
for(w4=w3+1;w4<MAXWEIGHT;w4++){
if(w1+w2+w3+w4==TOTALWEIGHT){
if(testWeight(w1,w2,w3,w4)){
System.out.println(TOTALWEIGHT+": w1="+w1+", w2="+w2+", w3="+w3+", w4="+w4);
outprint(w1,w2,w3,w4);
}
}
}
}
//从1~40,不管哪个重量都要找到相应的砝码放置方法
//w1,w2,w3,w4分别为4个砝码的重量
public boolean testWeight(int w1,int w2,int w3,int w4){
//砝码只有4个,且每次称重时,这4个砝码只能出现0次或者1次
//出现时,砝码要么在物体盘,要么在砝码盘,要解该问题,转换思路
//假设砝码在物体盘,认定其出现-1次
//假设砝码在砝码盘,认定其出现1次
//若该次称重,不需要该砝码,认定其出现0次
//4个砝码在每次称重中出现的次数
int x1,x2,x3,x4;
int count=0;
int w=0;
for(w=1;w<=TOTALWEIGHT;w++)
for(x1=-1;x1<=1;x1++)
for(x2=-1;x2<=1;x2++)
for(x3=-1;x3<=1;x3++)
for(x4=-1;x4<=1;x4++){
if(w1*x1+w2*x2+w3*x3+w4*x4==w){
count++;
x1=x2=x3=x4=2;
}
}
if(count==TOTALWEIGHT){
return true;
}else{
return false;
}
}
//输出1~40中每个重量对应的砝码组合(负数表示该砝码放在物体盘)
public void outprint(int w1,int w2,int w3,int w4){
int x1,x2,x3,x4;
int w=0;
for(w=1;w<=TOTALWEIGHT;w++)
for(x1=-1;x1<=1;x1++)
for(x2=-1;x2<=1;x2++)
for(x3=-1;x3<=1;x3++)
for(x4=-1;x4<=1;x4++){
if(w1*x1+w2*x2+w3*x3+w4*x4==w){
System.out.print("w="+w+": ");
if(x1!=0){
System.out.print(x1*w1+" ");
}
if(x2!=0){
System.out.print(x2*w2+" ");
}
if(x3!=0){
System.out.print(x3*w3+" ");
}
if(x4!=0){
System.out.print(x4*w4);
}
System.out.println();
}
}
}
public static void main(String[] args) {
TWeight tw=new TWeight();
tw.calculate();
}
}
补充:软件开发 , Java ,