Logical Question 3
Javed Mulla
(Immediate Joiner, Valid Work Visa for UK)Senior Software Engineer at Consors Finanz BNP Paribas
you have a set of integers between 1 .. n in a random order with one of the numbers being repeated. find the best possible way (time and space) to obtain the repeating number.
XOR all elements form given set, let say...X
and XOR elements form 1...n,let say..Y
then repeated element is = X(xor)Y
for example set is 1,2,3,4,4
X=1xor2xor3xor4xor4
Y=1xor2xor3xor4
and repeated element is=X(xor)Y=4
public int repeated(int[] arr,int n){
int xor=0;
for(int i=0;i<arr.length;i++){
xor^=arr[i];
}
for(int i=1;i<=n;i++){
xor^=i;
}
return xor;
}
}
There are 10 balls .Determine the faulty ball in minimum steps
Divide balls into 3 groups (A, B, C) of 3 balls each, and an extra ball (X).
Compare groups A and B, and then compare B and C.
If A=B=C then X is the faulty ball.
If A!=B and B!=C then the faulty ball is in B, other wise it's in A if A!=B, or in C if B!=C.
After determining the group that the faulty ball belongs to, compare two of the balls (b0, b1) in this group (the last ball left is b2).
If b0=b1 then the faulty ball is b2.
if b0!=b1 compare b0 and b2. If b0=b2 then b1 is fauly, otherwise b0 is faulty.
Max comparisons are 4.
OR
A B C D
3 3 3 1
weigh A and B: same ->1 weigh over
weigh B and C: same ->1 weigh over
D is probelmatic
maximum weighing 2.
Worst case:
weigh A and B: same ->1 weigh over
weigh B and C: not same ->1 weigh over
C is problematic so divide C as 1, 1 and 1.
Weigh 1 and 1 : same so third 1 is probelmatic : 3 weigh over
maximum weighing 3.
Design a Tic Tac Toe Game. Classes Segregation and Code Flow
The key thing on this type of question is not to freeze up. Get something on the whiteboard:
1) You want to draw the board. Have a DrawBoard class (or function).
2) You have players. Have a Player class.
3) Players take turns. Have a GamePlay class.
4) You need to keep track which moves have been made. Have a Game class.
5) You need to decide if somebody won. Have a GameEvaluate class.
Get something out there, then work with the interviewer to simplify things. Do you really need a special GameEvaluate class? Maybe a Game object can supply the method that says whether a game is over. Seems like a reasonable responsibility for the game class. But maybe the actual calculation drives out a simple Matrix class.
The key thing here is to be flexible and brainstorm.
Also, don't let the full complexity of the problem overwhelm you. Before you figure out how to orchestrate players taking turns, simplify the problem. Say that you just read the player's answers from a file, fill in the grid, and then say who won. If you can figure out how to model that, you have a good foundation for the rest of the problem.
There are 25 horses and 5 lanes. You have no idea about which horse is better than other.
Find in minimum possible races, the first three fastest running horses.
Answer would be 7. Explanation :
Make group of 5 horses and run 5 races.Suppose five groups are a,b,c,d,e and next alphabet is its individual rank in tis group(of 5 horses).for eg. d3 means horse in group d and has rank 3rd in his group. [ 5 RACES DONE ]
a1 b1 c1 d1 e1
a2 b2 c2 d2 e2
a3 b3 c3 d3 e3
a4 b4 c4 d4 e4
a5 b5 c5 d5 e5
Now make a race of (a1,b1,c1,d1,e1).[RACE 6 DONE] suppose result is a1>b1>c1>d1>e1
which implies a1 must be FIRST.
b1 and c1 MAY BE(but not must be) 2nd and 3rd.
FOR II position,horse will be either b1 or a2
(we have to fine top 3 horse therefore we choose horses b1,b2,a2,a3,c1 do racing among them [RACE 7 DONE].the only possibilities are :
c1 may be third
b1 may be second or third
b2 may be third
a2 may be second or third
a3 may be third
The final result will give ANSWER. suppoose result is a2>a3>b1>c1>b2
then answer is a1,a2,a3.
HENCE ANSWER is 7 RACES
OR
divided into 5 groups, each 5 horses.
race 5 rounds.
pick top 3 of each group. Because in the any one group we can find 3 fastest horse so we are do this.
15 horse. 5 groups.
let took the race of horse comes top in each races. so we can find a who is fastest.
throw the two slowest groups. <chose the first one.>
8 horses left.
throw the last one horse of the second fast group. 7 horse left
throw the last two horse of the third fast group. 5 horse left
race again, <pick top 2>
You are given two candles of equal size, which can burn 1 hour each. Youhaveto measure 90 minutes with these candles. (There is no scale or clock). Also urgiven a lighter.
First light up the two ends of the 1st candle. When it will burn out light up one end of the second candle.
Try the similar problem to measure 45 minutes
First light up the two ends of the 1st candle and light up one ends of the 2nd candle.
A contractor had employed 100 labourers for a flyover construction task. He didnot allowany woman to work without her husband. Also, atleast half the men working camewith theirwives.He paid five rupees per day to each man, four ruppes to each woman and one rupeeto eachchild. He gave out 200 rupees every evening.How many men, women and children were working with the constructor?
16 men, 12 women and 72 children were working with the constructor.
Let's assume that there were X men, Y women and Z children working with theconstructor.
Hence,X + Y + Z = 1005X + 4Y + Z = 200
Eliminating X and Y in turn from these equations,
we getX = 3Z - 200Y = 300 - 4ZAs if woman works, her husband also works and atleast half the men working camewith theirwives; the value of Y lies between X and X/2. Substituting these limiting valuesinequations, we getif Y = X,300 - 4Z = 3Z - 2007Z = 500Z = 500/7 i.e. 71.428if Y = X/2,300 - 4Z = (3Z - 200)/2
600 - 8Z = 3Z - 20011Z = 800Z = 800/11 i.e. 72.727
Consider a series in which 8 teams are participating. each team plays twice with all other teams. 4 of them will go to the semi final.How many matches should a team win, so that it will ensure that it will go to semi finals.?
56 points are distributed to 8 team. In the worst case, team0 loses all the games, he gets 0 point. team1 win two games with team0 and loses all other games, he gets 2 points. In the same way, team2 gets 4 points, team3 gets 6 points. So there are 44 points left which can be distributed to the remaining 4 teams. So the assurance points for a team should be 11 points
OR
It's 11:
Let number the teams : 1 , 2.. 8, and say 8 beats all 1..7, 7 beats all 1..6 we will have this:
8: 14
7: 12
6: 10
5: 8
4: 6
3: 4
2: 2
1: 0
Ok for now it seams that 8 is a good answer, but is it?
Let's make very equilibrated, and make team number 4 closer to the top:
1) Let's assume Team 4 bets team 8 twice: that will result in:
8:12 (14 - 2)
7:12
6:10
5:8
4:8 (6 + 2)
3:4
2:2
1:0
Now it seams that 8 is not good, and it's 9, but is it?
2) Let assume Team5 beats team 8 twice
8:10 (14 - 2 - 2)
7:12
6:10
5:10 ( 8 + 2)
4:8 (6 + 2)
3:4
2:2
1:0
Now it seams that 10 is just perfect , but is it?
3) The final match: Team4 beats Team 7 twice:
8:10 (14 - 2 - 2)
7:10 (12 - 2)
6:10
5:10 ( 8 + 2)
4:10 (6 + 2 + 2)
3:4
2:2
1:0
It seamns that if this would happend 11 is the perfect number
Another reason is that the 5 team beats all the team, but still, remains 6 points( beacause there must play Team3 vs Team2 twice, T3 vs T1 and T2 vs T1) and remains 50 points
50/5 = 10 points in the perfect case . and because of that 11 is the number.
There were 3 racers A, B and C. When A finished the race, B was 8 mts behind A and C was 16 mts behind A. When B finished the race, C was 10 mts behind B. Assuming that three of them ran at constant speed, find the length of the track.
40 meters.
yt / y-8 = (y-10) t / y - 16
y is length of track
t is time in which A finished the race.
There are some glasses with equal volume 1 litre. The glasses kept as follows
1
2 3
4 5 6
7 8 9 10
You can put water to only top glass. If you put more than 1 litre water to 1st glass, water overflow and fill equally both 2nd and 3rd glass. Glass 5 will get water from both 2nd glass and 3rd glass and so on..
If you have X litre of water and you put that water in top glass, so tell me how much water contained by jth glass in ith row.
Example. If you will put 2 litre on top.
1st – 1 litre
2nd – 1/2 litre
3rd - 1/
n this problem the rates at which glasses get filled in are rational numbers, whose numerators form the binomial coefficients and denominators are powers of 2 - specifically 2 raised to the power of level at which glasses are present.
A litre of water (overflowed from previous level) gets distributed among the glasses at each level as follows:
level 0: 1
level 1: 1/2 1/2
level 2: 1/4 2/4 1/4
level 3: 1/8 3/8 3/8 1/8
level 4: 1/16 4/16 6/16 4/16 1/16
The above distribution pattern provides with a partial progress towards the actual algorithm that finds the amount of water in jth glass of ith row. The algorithm gets tricky because all the glasses at a level might not be completely filled yet, before water starts getting filled up in levels below (albeit, in an inverted triangle fashion).
----------------------------------------------------------------------------
The above observation apart, a DP-like algorithm below(that remembers quantities in glasses of the previous row) to find out the amount of water in jth jug of ith row can solve the problem.
- For each glass, maintain 2 variables - the amount of water it holds and the amount of water it overflows.
- For a glass at index i in the given row, look up two glasses in the previous row at index i-1 & i. (Boundary cases of indices need to be checked though)
- The inflow into the current glass = half of outflow of glass in the previous row at i-1 + half of outflow of glass in the previous row at index i
- Based on the inflow, volume held in the current glass = min(1, inflow) and the overflow at the current glass = inflow - volume held by the current glass
- Repeat steps 1 to 3 until we reach the required glass.
An implementation in java goes like the below:
import java.util.Scanner;
import java.util.regex.Pattern;
class GlassStatus {
float heldVolume;
float overflownVolume;
}
public class GlassPyramid {
static int ipRowNum, ipGlassNum, ipVolume;
public static float computeWaterAt(float volume, int level, GlassStatus[] previousRows) {
if (volume <= 0)
return 0;
GlassStatus[] rows = new GlassStatus[level + 1];
float overflow1 = 0, overflow2 = 0, inflow = 0, tempVol = 0;
for (int i = 0, prev = i-1, next = i; i <= level; i++, prev++, next++) {
rows[i] = new GlassStatus();
if (prev < 0) {
overflow1 = 0;
} else {
overflow1 = previousRows[prev].overflownVolume/2;
}
if (next >= level) {
overflow2 = 0;
} else {
overflow2 = previousRows[next].overflownVolume/2;
}
if (level == 0) {
inflow = volume;
} else {
inflow = overflow1 + overflow2;
}
tempVol += rows[i].heldVolume = Math.min(1, inflow);
rows[i].overflownVolume = inflow - rows[i].heldVolume;
}
if (level == ipRowNum) {
return rows[ipGlassNum].heldVolume;
} else {
return computeWaterAt(volume - tempVol, level + 1, rows);
}
}
public static void readInput() {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator"));
Pattern delimiters = Pattern.compile(System.getProperty("line.separator")+"|\\s");
scanner.useDelimiter(delimiters);
System.out.println("Input row#:");
ipRowNum = scanner.nextInt();
System.out.println("Input glass#:");
ipGlassNum = scanner.nextInt();
System.out.println("Input volume:");
ipVolume = scanner.nextInt();
}
public static void main(String[] args) {
readInput();
System.out.println("Volume in the glass=" + computeWaterAt(ipVolume, 0, new GlassStatus[] {}));
}
}
given two very big files , each having around 1 billion lines , u have to print all the lines that are common to both files . Please suggest a good optimal approach
Maintain a hash table with the following structure.
- Use a Pair object with (line#, count) elements
- Key of hash table would be the hashcode(something like MD5) of the string and value would be an arraylist of Pair objects.
[hashCodeOfString]-> ArrayList<Pair>()
For the first file, for each of the lines, compute the hashcode for key.. As it's value, store the corresponding line# and the initial count set to 1.
For the second file, for each of the lines, compute the hash code and if the hashcode matches, from the Pair object, match the current line with the corresponding lines from the 1st file. If the string comparison also matches increment the count field of the pair object.
Iterate over the hash table and print those lines with count > 1
A lady buys goods worth Rs.200 from a shop. (shopkeeper is selling the goods with zero profit). The lady gives him Rs.1000 note. The shopkeeper gets the change from the next shop and keeps Rs.200 for himself and returns Rs.800 to the lady. Later the shopkeeper of the next shop comes with the Rs.1000 note saying “duplicate” and takes his money back.How much LOSS did the shopkeeper face?
The answer is Rs.1000
How?
Solution 1
To get the loss of shopkeeper we can get the profit lady and the other shopkeeper.
Loss of first shopkeeper = (Profit of the lady + Profit of the second shopkeeper)
Profit of the lady = Rs.200(for goods) + Rs.800(for the change she received) = Rs.1000
Profit of the second shopkeeper = Rs.0(as he got his money back)
So the loss of the shopkeeper is = 1000 + 0 = Rs.1000
Solution 2
Second way of looking at is what shopkeeper gave to others and what is took from others
Loss of the shopkeeper = What he gave to others - what he took.
What he took
From Lady: Nothing(as the note was a duplicate one)
From Second Shopkeeper: Rs.1000
What he gave
To Lady:- Rs.200(goods) + Rs.800(change)
To second shopkeeper: Rs. 1000
So the loss = (200 + 800 + 1000) – (1000) = Rs.1000
Javed don't confuse between actual loss and perceived loss. The actual loss is Rs. 1000 only since the shopkeeper lost Goods worth Rs. 200 and cash worth Rs. 800 in consideration of a fake note of Rs. 1000. The fake note was never his anyway. As regards his transaction with the other shopkeeper it is just an exchange which got reversed lateron. So the two transactions negated each others impact and hence the shopkeeper lost only in the first transaction with the old lady.
There are 100 doors, all closed. In a nearby cage are 100 monkeys. The first monkey is let out, and runs along the doors opening every one. The second monkey is then let out, and runs along the doors closing the 2nd, 4th, 6th,… all the even-numbered doors. The third monkey is let out. He attends only to the 3rd, 6th, 9th,… doors (every third door, in other words), closing any that is open and opening any that is closed, and so on. After all 100 monkeys have done their work in this way, what state are the doors in after the last pass, which doors are left open and which are closed ?
Consider door number 56, monkeys will visit it for every divisor it has. So 56 has 1 & 56, 2 & 28, 4 & 14, 7 & 8. So on pass 1 1st monkey will open the door, pass 2 2nd one will close it, pass 4 open, pass 7 close, pass 8 open, pass 14 close, pass 28 open, pass 56 close. For every pair of divisors the door will just end up back in its initial state. But there are cases in which the pair of divisor has same number for example door number 16. 16 has the divisors 1 & 16, 2 & 8, 4&4. But 4 is repeated because 16 is a perfect square, so you will only visit door number 16, on pass 1, 2, 4, 8 and 16… leaving it open at the end. So only perfect square doors will be open at the end.
For example, after the first pass every door is open. on the second pass you only visit the even doors (2,4,6,8…) so now the even doors are closed and the odd ones are opened. the third time through you will close door 3 (opened from the first pass), open door 6 (closed from the second pass), etc..
question: what state are the doors in after the last pass? which are open which are closed?
solution: you can figure out that for any given door, say door #42, you will visit it for every divisor it has. so 42 has 1 & 42, 2 & 21, 3 & 14, 6 & 7. so on pass 1 i will open the door, pass 2 i will close it, pass 3 open, pass 6 close, pass 7 open, pass 14 close, pass 21 open, pass 42 close. for every pair of divisors the door will just end up back in its initial state. so you might think that every door will end up closed? well what about door #9. 9 has the divisors 1 & 9, 3 & 3. but 3 is repeated because 9 is a perfect square, so you will only visit door #9, on pass 1, 3, and 9… leaving it open at the end. only perfect square doors will be open at the end.
There are n bulbs in a circle, each bulb has one switch associated with it, on operating the switch, it toggles the state of the corresponding bulb as well as two bulbs adjacent to that one. Given all bulbs are in off state initially, give a plan to turn all bulbs on finally.
Note: n >= 1.
The idea is to check the value of n%3, there can be three cases
Case 1: when n%3 = 0, bulbs are complete multiple of 3
This is the simplest case, here assume n/3 pairs of bulbs and operate the middle bulb from each pair, ultimately all n bulbs will be on.
n bulbs in a circle puzzle solution case 1
Case 2: when n%3 = 1, case 1 + one extra bulb
In this case, if we reach to a state where only one bulb is on and remaining n-1 bulbs are off, we can turn on remaining n-1 bulbs easily as (n-1) is complete multiple of 3.
Lets assume n =7, and do as described in step 1 to 5.
n bulbs in a circle puzzle solution case 2
Step 1: Toggle bulbs in pair of 3, 2nd, 5th, till n-2th bulb. at this stage only nth bulb will be off and rest all will be in on state.
Step 2: Toggle 1st bulb, it will make 1st and 2nd bulb off and nth bulb(7th for our example) ON.
Step 3: Toggle 3rd bulbs, it will make 1st, 2nd and 4th bulbs off and remaining bulbs ON.
Step 4: Leave 1st,2nd,3rd and 4th bulbs as it is and turn off remaining (n-4) bulbs in pair of 3′s. as (n-4) is complete power of 3 this can be done easily as in case 1. after this only 2nd bulbs will be ON.
Step 5: Leave 2nd bulb and turn on remaining (n-1) bulbs in pair of 3′s, again as (n-1) is complete multiple of 3, this can be done easily as in case 1. at this point all bulbs will be ON.
Case 3: when n%3 = 2, case 1 + two extra bulbs
In this case, if we reach to a state where only two bulbs are on and remaining n-2 bulbs are off, we can turn on remaining n-2 bulbs easily as (n-2) is complete multiple of 3.
Lets assume n =8, and do as described in step 1 to 5.
n bulbs in a circle puzzle solution case 3
Step 1: Toggle bulbs in pair of 3, 2nd, 5th, till (n-3)th bulb. at this stage only nth and (n-1)th bulbs will be off and rest all will be in on state.
Step 2:Toggle nth bulb, (8th for our case), this will leave only 1st bulb off, rest all ON.
Step 3: Leave 1st and nth bulb and turn off remaining (n-2) bulbs in pair of 3′s, as (n-2) is complete multiple of 3
Step 4: Toggle nth bulb again, this will turn on 1st and 2nd bulb and remaining all will be off.
Step 5: Leave 1st and 2nd bulb and turn on remaining (n-2) bulbs in pair of 3′s, as (n-2) is a complete power of 3, it can be done easily as in case 1.
four glasses on a square table puzzle, also known as the blind bartender’s problem
Four glasses are placed on the corners of a square table. Some of the glasses are upright (up) and some upside-down (down). You have to arrange the glasses so that they are all up or all down (while keeping your eyes closed all the time). The glasses may be re-arranged in turns subject to the following rules.
- Any two glasses may be inspected in one turn and after feeling their orientation you may reverse the orientation of either, neither or both glasses.
- After each turn table is rotated through a random angle.
- At any point of time if all four glasses are of the same orientation a ring will bell
You have to come up with a solution to ensure that all glasses have the same orientation (either up or down) in a finite number of turns. The algorithm must be non-stochastic i.e. it must not depend on luck.
- On the first turn choose a diagonally opposite pair of glasses and turn both glasses up.
- On the second turn choose two adjacent glasses. At least one will be up as a result of the previous step. If the other is down, turn it up as well. If the bell does not ring then there are now three glasses up and one down(3U and 1D).
- On the third turn choose a diagonally opposite pair of glasses. If one is down, turn it up and the bell will ring. If both are up, turn one down. There are now two glasses down, and they must be adjacent.
- On the fourth turn choose two adjacent glasses and reverse both. If both were in the same orientation then the bell will ring. Otherwise there are now two glasses down and they must be diagonally opposite.
- On the fifth turn choose a diagonally opposite pair of glasses and reverse both. The bell will ring for sure.
At a party, everyone shook hands with everybody else. There were 66 handshakes. How many people were at the party?
lets say there are n persons
first person shakes hand with everyone else: n-1 times(n-1 persons)
second person shakes hand with everyone else(not with 1st as its already done): n-2 times
3rd person shakes hands with remaining persons: n-3
So total handshakes will be = (n-1) + (n-2) + (n-3) +…… 0;
= (n-1)*(n-1+1)/2 = (n-1)*n/2 = 66
= n^2 -n = 132
=(n-12)(n+11) = 0;
= n = 12 OR n =-11
-11 is ruled out so the answer is 12 persons.
A guy has two wires of varying thickness, which each burns in 60 minutes. He actually wants to measure 45 mins. How can he measure 45 mins using only these two wires. (he can’t cut the one wire in half because the wires are non-homogeneous and he can’t be sure how long it will burn)
He will burn the first wire at both the ends and the second wire at one end. After half an hour, the first one burns completely and at this point of time, he will burn the other end of the second wire so now it will take 15 mins more to completely burn.. so total time is 30+15 i.e. 45mins.
Two MIT math grads bump into each other at Fairway on the upper west side. They haven’t seen each other in over 20 years.
The first grad says to the second: “how have you been?”
Second: “great! i got married and i have three daughters now”
First: “really? how old are they?”
Second: “well, the product of their ages is 72, and the sum of their ages is the same as the number on that building over there..”
First: “right, ok.. oh wait.. hmm, i still don’t know”
Second: “oh sorry, the oldest one just started to play the piano”
First: “wonderful! my oldest is the same age!”
How old are the daughters ?
We know that there are 3 daughters whose ages multiply to 72. Let’s look at the possibilities…
Ages: Sum of ages:
1 1 72 74
1 2 36 39
1 3 24 28
1 4 18 23
1 6 12 19
1 8 9 18
2 2 18 22
2 3 12 17
2 4 9 15
2 6 6 14
3 3 8 14
3 4 6 13
After looking at the building number the second man still can’t figure out what their ages are, so that means that the sum of the ages (or building number) must be 14, since that is the only sum that has more than one possibility. Finally the man discovers that there is an oldest daughter. That rules out the “2 6 6″ possibility since the two oldest would be twins. Therefore, the daughters ages must be “3 3 8″.
How many trailing zeroes are there in 100! (100 factorial) ?
For every factor of 10, there will be one trailing zero similarly for every factor of 5 there will be one trailing zero (as 5*2 =10, and there are enough number of 2′s). But we have to take care of repetitions.
10, 20,…., 90 = 9 zeros
100 = 2 zeros
5, 15, 25……95 = 10 zeros
and 1 extra 5 in each of 25, 50 and 75 = 3 zeros
so total 9+2+10+3 = 24 zeros.
13 caves and a thief puzzle
There are 13 caves arranged in a circle. There is a thief hiding in one of the caves. Each day the the thief can move to any one of of the caves that is adjacent to the cave in which he was staying the previous day. And each day, you are allowed to enter any two caves of your choice.
What is the minimum number of days to guarantee in which you can catch the thief?
Note:
- Thief may or may not move to adjacent cave.
- You can check any two caves, not necessarily be adjacent.
- If thief and you exchange your caves, you will surely cross at some point, and you can catch the thief immediately.
Answer is 12 days.
How?
Lets assume the thief is in cave C1 and going clockwise and you start searching from cave C13 and C12 on your first day.
Cave C13 and C11 on second day,
C13 and C10 on third day and so on till C13 and C1 on 12th day.
So basically the idea is to check C13 everyday so that if thief tries to go anti clockwise you immediately catch it and if goes clockwise you will catch him in maximum 12 days(including the case where he remains in Cave C1).
In INDIA
A man was found murdered on 15/8/2007 Wednesday afternoon at 12.35pm in his house. His wife called police.
Police questioned everyone
Wife: I was sleeping.
Neighbors: We went 4 the marriage.
Driver: I went to Bank.
Cook: I went to Market.
Watch Man: I went to My relations Marriage.
Police arrested murderer immediately.
Can you tell who was the murderer?
Its the driver.
How?
Actually 15/08/2007 is nothing but independence day in India, and it is a national holiday. On a national holiday all the banks are closed, so it is not possible for driver to go to the bank on that day, it means he is lying.
Their are 10 prisoners in a jail for a minor crime, they all request the jail officer to set them free, jail officer agrees to release them tomorrow, saying i will
- Make you all stand in a queue in ascending order of your heights(smallest first).
- You will not be allowed to turn your head(they have to look straight)
- I will put one hat on your head, either BLACK or WHITE in color.
- Everyone of you has to tell the color of his hat starting from the tallest prisoner, you can only say BLACK or WHITE.
- You all will be released, if and only if at least 9 of you guess your hat’s color correctly.
Can you suggest a strategy to the prisoners to maximize the chances of their release?
I would suggest, think once again before reading the solution
Okay, If you tried enough:-
- The strategy is to count the number of white and black hats in front of them and say white if number of white hats are odd else say black.
- Now the next prisoner will count the white or black hats(depending on what the first person said) and if the count is even it means he has the same color hat else it is the opposite color hat.
- Now all other prisoner will keep making the count as odd or even depending on the previous prisoners answer and can predict their own hat color.
- This way, all prisoner will be able to guess the color of their hats correctly accept the first one, which will be having 50% probability.
In the above image:-
For the last prisoner=> number of white hats in front of him: 3(odd), so he will say white
For next prisoner: number of white hats in front of him: 3(odd), as the previous prisoner said white so it is black hat on his head.
Again for the next prisoner: number of white hats in front of him: 3(odd), as the the previous prisoner said black so it must be black hat on his head too.
Same logic for next 2 prisoners as well
Now the sixth prisoner from last see number of white hats as 2:(even)-> he can say it is his hat which was making the white at count odd, so his hat must be white in color.
Seventh prisoner can see now white hat count for previous prisoner is even and can predict the color of his hat.
Java | Multithreading | Microservices
9 年nice
Technical Lead at Synechron
9 年Mulla, still i don't understand answer of shopekeeper loss puzzle, answer should be 1200