You have 20 Blue balls and 10 Red balls in a bag. You put your hand in the bag
and take off two at a time.
If they’re of the same color, you add a Blue ball to the bag. If they’re of different colors,
you add a Red ball to the bag. What will be the color of the last ball left in the bag?
Note: Assume you have a big supply of Blue and Red balls for this purpose.
When you take the two balls out, you don’t put them back in, so the number
of balls in the bag keeps decreasing.
Approach:
Java
import java.util.*;public class Main{public static void main(String[] args) {String[] bag={"red","red","red","red","red","red","red","red","red","red","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue",};List<String> ballBag = new ArrayList(Arrays.asList(bag));performOperation(ballBag);if(ballBag.get(0).equals(ballBag.get(1))){System.out.println("last ball left : blue");}else{System.out.println("last ball left : red");}}private static int performOperation(List<String> ballBag){int lenght=ballBag.size()-1;Random random = new Random();int index1= random.nextInt(lenght - 0) + 0;int index2= random.nextInt(lenght - 0) + 0;if(index1!=index2){String firstball= ballBag.get(index1);String secondball= ballBag.get(index2);ballBag.remove(index1);ballBag.remove(index2);if(firstball.equals(secondball)){ballBag.add("blue");}else{ballBag.add("red");}}while(lenght>1){return performOperation(ballBag);}return 0;}}
No comments:
Post a Comment