Among 20 sphere, one sphere weight is larger than other 19 sphere. how will you find that ball without seeing it. Explain logic and code.

AnswerBot
1y

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

Rocky Saini
1y

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;

}

}

Help your peers!
Add answer anonymously...
OneAssist Consumer Solutions Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter