Among 20 spheres, one sphere's weight is larger than the other 19 spheres. How will you find that sphere without seeing it? Explain the logic and code.

Finding the heavier sphere among 20 spheres without seeing it.
Divide the spheres into groups of 3, weigh any two groups against each other.
If both groups weigh the same, the heavier sphere is in the t...read more
public class FindHeavierSphere {
public static void main(String[] args) {
int[] spheres = new int[20];
// Assign weights to the spheres, where one sphere has a higher weight
int heavierSphere = findHeavierSphere(spheres);
System.out.println("The heavier sphere is: " + heavierSphere);
}
public static int findHeavierSphere(int[] spheres) {
// Divide the spheres into groups A, B, and C
int[] groupA = new int[6];
int[] groupB = new int[6];
int[] groupC = new int[2];
// Weigh group A against group B
int weightComparison = weighGroups(groupA, groupB);
if (weightComparison == 0) {
// The heavier sphere is in group C
return weighIndividuals(groupC[0], groupC[1]);
} else if (weightComparison > 0) {
// The heavier sphere is in group A
return weighIndividuals(groupA[0], groupA[1]);
} else {
// The heavier sphere is in group B
return weighIndividuals(groupB[0], groupB[1]);
}
}
public static int weighGroups(int[] groupA, int[] groupB) {
int totalWeightA = calculateTotalWeight(groupA);
int totalWeightB = calculateTotalWeight(groupB);
return Integer.compare(totalWeightA, totalWeightB);
}
public static int weighIndividuals(int sphere1, int sphere2) {
return Integer.compare(sphere1, sphere2);
}
public static int calculateTotalWeight(int[] group) {
int totalWeight = 0;
for (int weight : group) {
totalWeight += weight;
}
return totalWeight;
}
}
Interview Questions Asked to Software Developer at Other Companies
Top Skill-Based Questions for OneAssist Consumer Solutions Software Developer


Reviews
Interviews
Salaries
Users

