关于12个球的天平称法问题
最近一直有人在问12(13)个球有一个重量跟别的不同,然后只用天平称3次,找出来的问题,
正好女朋友面试也问到了这个问题,我就写了一个比较烂的程序是12个球的,关于13个的
其实差不多,因为5个球2次是可以称出来的(有8个好的球的前提下,因为过程中,你会一直用到正常球的),一起附上,想想去年的这个时候我还整天乐哉乐哉的,过了年开始找工作,才发现一直被鄙视,呵呵,知道四月底才找到工作,所以希望大家都能找到好的工作啊!!还有新年快乐,今天天很冷,昨天刚下乐大学,女朋友还去找工作,感觉很心疼的,希望她能早点找到工作,天天开心,也祝CSDN的所有朋友天天开心,工作顺利,还没有工作的,顺利找到工作.
下边是我写的一段代码:
大家帮我看看,抛砖引玉,共同学习
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int IndexErr;//error number
int ball[12];//number of ball
int index;
int weight = 8;//deflaut weight of abnormal ball
int NorWeight = 5;//deflaut weight of abnormal ball
int result;
srand(time(NULL));
IndexErr = rand()%12;
printf("The abnormal number is %d\n", IndexErr);
for(index = 0; index < 12; index++)
{
ball[index] = NorWeight;
}
ball[IndexErr] = weight;
if((ball[0] + ball[1] + ball[2] + ball[3])
== (ball[4] + ball[5] + ball[6] + ball[7]))
{
if((ball[4] + ball[5] + ball[6]) > (ball[8] + ball[9] + ball[10]))
{
if(ball[8] < ball[9])
result = 8;
else if(ball[8] > ball[9])
result = 9;
else
result = 10;
}
else if((ball[4] + ball[5] + ball[6]) < (ball[8] + ball[9] + ball[10]))
{
if(ball[8] < ball[9])
result = 9;
else if(ball[8] > ball[9])
result = 8;
else
result = 10;
}
else
result = 11;
}
else if((ball[0] + ball[1] + ball[2] + ball[3])
< (ball[4] + ball[5] + ball[6] + ball[7]))
{
if((ball[0] + ball[1] + ball[2] + ball[4])
< (ball[3] + ball[9] + ball[10] + ball[11]))
{
if(ball[0] < ball[1])
result = 0;
else if(ball[0] > ball[1])
result = 1;
else
result = 2;
}
else if((ball[0] + ball[1] + ball[2] + ball[4])
> (ball[3] + ball[9] + ball[10] + ball[11]))
{
if(ball[0] == ball[3])
result = 4;
else
result = 3;
}
else
{
if(ball[5] < ball[6])
result = 6;
else if(ball[5] > ball[6])
result = 5;
else
result = 7;
}
}
else
{
if((ball[0] + ball[1] + ball[2] + ball[4])
> (ball[3] + ball[9] + ball[10] + ball[11]))
{
if(ball[0] < ball[1])
result = 1;
else if(ball[0] > ball[1])
result = 0;
else
result = 2;
}
else if((ball[0] + ball[1] + ball[2] + ball[4])
< (ball[3] + ball[9] + ball[10] + ball[11]))
{
if(ball[0] == ball[3])
result = 4;
else
result = 3;
}
else
{
if(ball[5] < ball[6])
result = 5;
else if(ball[5] > ball[6])
result = 6;
else
result = 7;
}
}
printf("The result is %d\n", result);
return 0;
}
另5个球2次问题
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int ball[5];
int Index;
int ErrIndex;
int NorWeight = 5;
int ErrWeight = 3;
int result;
srand(time(NULL));
ErrIndex = rand()%5;
for(Index = 0; Index < 5; Index++)
{
ball[Index] = NorWeight;
}
ball[ErrIndex] =ErrWeight;
if((ball[0] + ball[1] + ball[2]) < (NorWeight * 3))
{
if(ball[0] < ball[1])
result = 0;
else if(ball[0] > ball[1])
result = 1;
else
result = 2;
}
else if((ball[0] + ball[1] + ball[2]) > (NorWeight * 3))
{
if(ball[0] < ball[1])
result = 1;
else if(ball[0] > ball[1])
result = 0;
else
result = 2;
}
else
{
if(ball[0] == ball[3])
result = 3;
else
result = 4;
}
return 0;
}