1.Description
You have
n
coins (
n
may be even or odd) such that
n−1
coins are of the same weight and one has different weight. You have a balance scale; you can put any number of coins on each side of the scale at one time, and it will tell you if the two sides weigh the same, or which side is lighter if they do not weigh the same.Outline an algorithm for finding the coin with different weight for each of the following conditions. The number of weighings using your algorithm in each case should be
O(logn)
. You know that one coin weighs more than the others.
2.Algorithm
(1)If the number of coins is even, split them into two parts. If the number is odd, split them into two parts and one coin.
Get the weight of the two parts. The coin which weighs more than other must lie in the part which weighs more.
In the side which weighs more, recursively call step 1. If the weight of two parts are the same, the special coin is the last remaining one.
3.Implementation
public class Coin {
public static void findCoin(int coins[],int left, int right) {
int mid=(int) Math.ceil((left+right)/2); //get the upper limit
int LeftSum=0,RightSum=0;
if(left==right)
{
System.out.println("The special coin is coins["+right+"]");
}
else if(right-left==1)
{
if(coins[left]>coins[right])
{
System.out.println("The special coin is coins["+left+"]");
}
else if(coins[left]>coins[right])
{
System.out.println("The special coin is coins["+right+"]");
}
}
else
{
for(int i=left;i<mid;i++)
{
LeftSum+=coins[i]; //iteratively get the weight of the left side coins
RightSum+=coins[i+mid-left];
}
//if the weight of left side is bigger than right side, the special coin should be in the left side
if(LeftSum>RightSum)
{
right=mid;
findCoin(coins,left,right);
}
else if(LeftSum<RightSum)
{
left=mid;
findCoin(coins,left,right);
}
//if the weight of left side is equal to right side, the special coin should be the last remaining one
else if(LeftSum==RightSum)
{
System.out.println("The special coin is coins["+right+"]");
}
}
}
public static void main(String[] args) {
int coins1[]={1,1,1,1,1,1,1,1,1,2};
int coins2[]={1,1,1,1,2,1,1,1,1};
int left1=0,right1=coins1.length-1;
findCoin(coins1,left1,right1);
int left2=0,right2=coins1.length-1;
findCoin(coins2,left2,right2);
}
}
Screenshot of the result: