Вы находитесь на странице: 1из 12

Chapter 1

Riddles
1.1 Minimum Weighings

Problem There are 25 1-kilogram weights arranged in a 5x5 matrix. One complete row was replaced with 2-kilogram weights. There is a digital bathroom scale. Find which row contains 2-kilogram weights in least number of weighings. Solution This can be done in one weighing by picking one weight from the rst row, two from the second, three from the third, etc. The weight of the picked weights should tell you which row contains 2-kilogram weights since for every position of the 2-kilogram row, there is a unique sum of weights in the pick.

1.2

Eight Balls

Problem Suppose you have 8 billiard balls, and one of them is slightly heavier, but the only way to tell is by putting it on a scale against another. Whats the fewest number of times youd have to use the scale to nd the heavier ball? Solution Youd have to use the scale twice. Put three balls on one plate of the scale and three balls on the other. If the weights are equal, put the remaining two balls on each of the scale plates and nd the lighter one. If, however, the sets of three balls in the rst weighing are not equal, then discard the heavier set and put any two balls from the lighter set on the scale, one per plate. If the lighter ball happens to be on the scale, youd notice it immediately; if the weights of the 1

CHAPTER 1. RIDDLES

two balls are equal, then the remaining third ball is the lighter ball. Note that even if you had 9 billiard balls, you could nd the heavier ball in 2 weighings. One reason why the problem had 8 balls instead of 9 is to make you think of the binary search, which is not very ecient here. A similar problem could be posed for a collection of 27 balls. In this case you would need to use the scale 3 times to nd the heavier ball. Note the relationship between the minimum number of weighings and the powers of 3.

1.3

Primitive Encryption

Problem There are two islands - A and B - separated by water. Each island has a box, a lock for the box and a key for the lock. Island A also has a diamond that needs to be sent to island B. The only mode of transportation between the islands is the boat operated by a pirate. The pirate will steal anything except the locked box. How do you transport the diamond from island A to island B? Solution Island A sends the diamond in a locked box to island B. Island B adds its own lock to the box and sends it to island A. Island A removes its lock and sends the box back to island B.

1.4

Closet with a Light

Problem There is a closet with a door in a room. The closet contains an incandescent bulb. In the adjacent room there are three switches. One of the switches is connected to the bulb. How do you determine which switch operates the bulb by visiting the switches and the bulb only once? Solution Turn the rst switch one and keep it on for a few minutes (to get the bulb warm). Then turn the rst switch o and turn the second one on. Now go to the closet. If the bulb is on, it has to be connected to the second switch. If the bulb is o and warm, it is connected to the rst switch and otherwise it is connected to the third switch.

1.5. BURNING ROPES

1.5

Burning Ropes

Problem There are two ropes of equal length. Each ropes burns non-uniformly in exactly 60 minutes. If the rope burns half way, it does not mean its burnt for 30 minutes. How do you measure 45 minutes using the two ropes and a box of matches? How do you measure 15 minutes using the two ropes and a box of matches? Solution Light the rst rope from two ends and the second rope from one end. After the rst rope has completely burnt out, 30 minutes have passed. At that time, light the second end of the second rope. The second rope will measure additional 15 minutes, making a total of 45 minutes. Fifteen minutes are measured the same way.

1.6

Measurement by Water

Problem If you had an innite supply of water and a 5 quart and 3 quart pail, how would you measure exactly 4 quarts? Fill the 5-quart pail fully with water. Pour water from the 5-quart pail into the 3-quart pail, leaving 2 quarts in the 5-quart pail. Empty the 3-quart pail. Pour 2 quarts from the 5-quart pail into the 3-quart pail. Fill the 5-quart pail fully with water. Pour water from the 5-quart pail into the 3-quart pail until the 3-quart pail is full. Whats remaining in the 5-quart pail is 4 quarts.

1.7

Measurement of Large Quantities

Problem How many cars are there in the USA? How many gas stations are there in the USA?

4 Solution

CHAPTER 1. RIDDLES

There is no right answer here. One possible solution is to call states licensing authorities, thus completing the task in 50 calls. Alternatively, you can call a few states government agencies and extrapolate the data from a few samples.

1.8

Black and White Hats

Problem Four prisoners are about to be executed. They are lined up, each facing the other persons back: the rst prisoner sees the second prisoners back and so on. The fourth prisoner faces the wall. There is also a wall between prisoners three and four. There are also four hats, two black and two white. The rst prisoner has a black hat on, the second has a white hat, the third has a black hat and the fourth has a white hat. The chief guard tells them that they will be spared if one of them identies which hat he or she is wearing. Which prisoner can identify the color of his or her hat? Why? Solution This is the arrangement: BW B|W |. The second prisoner from the left knows that he or she is wearing the white hat. If he or she was wearing a black hat, then the rst prisoner would immediately know that he or she is wearing a white hat because there are only two black and two white hats and the rst prisoner sees the two black hats in front. Since the rst prisoner is silent, the second inmate knows that he or she must be wearing a white hat.

1.9

Mixed Fruits

Problem There are three buckets. One contains only apples, the second contains only oranges, and the third contains a mixture of apples and oranges. There are also labels on the buckets: Apples, Oranges, and Mixed. Each of the buckets is mislabelled. How many selections does it take to determine the contents of each of the buckets. Solution One. Pick a fruit from the Mixed bucket. Lets say you picked an apple. That means that that bucket contains apples only. Remember that each bucket is mislabelled. That means that the Oranges bucket cannot contain oranges, so it must contain mixed fruits. Therefore the Apples bucket contains oranges.

1.10. GERRYMANDERING

1.10
Problem

Gerrymandering

Two rectangles of dierent shape (i.e. dierent areas) are positioned in an Lshaped gure. Draw one line to divide the newly formed gure into two gures of equal area. Solution Find the center of two rectangles (intersection of the diagonals) and draw the line through the centers. The solution is obvious when reduced to one dimension - draw a line through two perpendicular lines so that the total lengths on both sides of the drawn line are the same. In this case, the solution is simple - draw a line through the centers of the two original lines.

1.11
Problem

Lost in a Forest

You are lost in a forest. The forest is between two villages. In village A live only liars, they always lie. In village B people always tell the truth. You want to go to village B. Then you see a man from village A or B. You can ask him only one question. Which question will you ask him to know for sure where is village B? Solution Ask the man in which city he lives. He will always point to village B.

1.12
Problem

Blue-eyed Samurais

A remote island contains a tribe whose members have either blue or brown eyes. Tribe members do not know the color of their eyes and if they learn it, they must kill themselves the same night. Every member of the tribe always behaves logically. So one day, a sailor visits the island and makes an observation that at least one of the members of the tribe has blue eyes. On the 10th night after that, all people with blue eyes kill themselves. How many blue-eyed people were there in the tribe? Solution Ten. The logic goes as follows. If there were only one person with blue eyes on the island, then he would see that no one else has blue eyes and will kill himself on the rst night. If there were two people with blue eyes, then one of

CHAPTER 1. RIDDLES

the people with blue eyes would see that the second blue-eyed person did not kill himself on the rst night, leading him to conclude that since he sees no one else with blue eyes, he must be one of them and will kill himself on the second night. The other blue-eyed person will follow the same logic and also kill himself on the second night. The same idea applies to the rest of the problem.

1.13
Problem

Paying from the Gold Reserve

Youve got someone working for you for seven days and a gold bar to pay them. The gold bar is segmented into seven connected pieces. You must give them a piece of gold at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker? Solution Break the bar into three cuts: Cut1 = 1, Cut2 = 2, Cut3 = 4. Ask the worker to be nice enough to bring the previous-days pay with him. On the rst day give the worker Cut1 . On the second day, give the worker Cut2 but ask for Cut1 back. On the third day give him Cut1 . On the fourth day, give him Cut4 but ask back Cut1 and Cut2 . You get the idea.

1.14
Problem

Marching Ants

There are 3 ants at 3 corners of a triangle. They randomly start moving towards another corner. What is the probability that they dont collide? Solution 1/4. One ant can move only in one of two possible directions. Therefore, there are 23 = 8 possible ways for the ants to move. Two of those ways, clockwise and counterclockwise will guarantee no collision. Therefore, P(no collision) = 2/8 = 1/4.

1.15
Problem

Spinning Colors

You have a disk spinning like a record player turn table. Half of the disk is black and the other is white. You also have an unlimited number of color sensors. How many sensors would you have to place around the disk to determine the direction the disk is spinning? Where would they be placed?

1.16. MATCHING CLOCK HANDS Solution

Two. Place them next to each other, above the disk. Then track color change, say black, and note which sensor indicates black rst. The second should indicate black immediately after the rst. From the order of color changes of the two color sensors, you can determine the direction the disk is spinning.

1.16
Problem

Matching Clock Hands

Imagine an analog clock set to 12 oclock. Note that the hour and minute hands overlap. How many times each day do both the hour and minute hands overlap? How would you determine the exact times of the day that this occurs? Solution Set V be the set of times during which the two clock hands overlap within a 12-hour period. Then, by observation, V = {12:00, 1:xx, 2:xx, 3:xx, 4:xx, 5:xx, 6:xx, 7:xx, 8:xx, 9:xx, 10:xx }. Here, xx means some undened reading of the minute hand. Since |V | = 11, within a 24-hour period, the two hands of the clock will overlap 22 times. To nd the actual times of overlap, we observe that by the time both hands meet, the minutes hand moves a certain number of minutes from the 12 oclock position, while the hour hand moves a fraction of 5 minutes from the current hour position . To restate, if the minute hand moves m minutes, then the hour hand moves 5m minutes past the current hour. So the general formula that 60 describes this behavior is m = s + 5m , where s is the start location of the hour 60 hand, expressed in minutes, i.e. s {5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55}. The exact times of overlap are obtained by solving for m for every possible value of s.

1.17
Problem

Bridge Crossing

There are 4 women who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one ashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the ashlight with them. The ashlight must be walked back and forth, it cannot be thrown, etc. Each woman walks at a dierent speed. A pair must walk together at the rate of the slower womans pace. Woman 1: 1 minute to cross.

8 Woman 2: 2 minutes to cross. Woman 3: 5 minutes to cross. Woman 4: 10 minutes to cross.

CHAPTER 1. RIDDLES

What is the exact order of women crossing the bridge? Solution


1,2 2 3,4 1 1,2 Time to cross: 2 2 10 1 2 1,2 1 3,4 2 1,2 Time to cross: 2 1 10 2 2

1.18
Problem

One thousand coins

There are 1000 coins on the table. Twenty coins face heads up while the rest face tails up. You are blindfolded and your task is to separate the coins into two groups such that the number of heads in both groups is the same. You cannot determine whether a coin is heads or tails by merely touching it but you are allowed to ip any number of coins. Solution Pick random 20 coins from the entire set, ip them, and make one group from them. Make the remaining 980 coins the second group. Regardless of what coins were picked for the rst group (there can be 0 or all 20 or any other number of coins that were originally heads up), the number of heads in the two groups is the same.

Chapter 2

Algorithms
2.1 Missing Number

Problem An array of 999 elements contains numbers 1 - 1000, with one number missing. The numbers are arranged in a random order. Find the missing number. Solution Let A be the given array and let m be the missing number. Then m = i=1 i Note that this solution takes O(n) time. Sorting the array to nd the missing element will take at least O(n log n) time.
1000 998 i=0

A[i] .

2.2

Duplicate Number

Problem Find a duplicate entry in an array of random elements. Solution Hash the elements into a hash table and on bucket collision, check for the presence of the same element in the bucket.

2.3

The Right Sum

Problem Find two elements in the integer array that add up to the third given element s. 9

10 Solution

CHAPTER 2. ALGORITHMS

Hash each element of the array into a hash table. When hashing an element a, calculate b = s a and look for b in the appropriate hash bucket. If the search for b fails, proceed to hash the next element. Another solution is to sort the array and then search for the two elements from both sides of the array.

2.4

Circular Linked List

Problem You have a singly linked list. Each node of the list contains some value and a pointer to the next node. How can you determine if the list is circular? You may not tinker with the values inside the nodes. Solution Set up two list pointers, with one traversing the list at twice the rate of the other. If the two pointers ever meet, the list must be circular. p1 = p2 = head; do { p1 = p1->next; p2 = p2->next->next; } while (p1 != NULL && p2 != NULL && p1 != p2); if(p1 != NULL && p1 == p2) printf("Circular!") else printf("Not circular!");

2.5

Obscure Test

Problem You have written C code below. What does it test for? if( (x & (x-1)) == 0 ) { /* Code goes here */ } Solution The code tests if x is a power of 2.

2.6. INTEGER SWAP

11

2.6

Integer swap

Problem Interchange the values of two integers, a and b, without using a temporary variable. Solution b=ab a=ab b=ab

2.7

Word Reverse

Problem Given a sentence, devise an algorithm to reverse the words in that sentence. For example, if the original sentence was These pretzels are making me thirsty, then the resulting sentence should be thirsty me making are pretzels These. Solution First reverse all the characters in the sentence. Then starting from the left side, reverse the characters in each word. So for example, the rst step would make the sentence ytsriht em gnikam era slezterp esehT and the second step would transform it to the desired form - thirsty me making are pretzels These. There is, of course, a less tricky solution: parse the sentence and store each word in a doubly-linked list. Then traverse the list in reverse.

2.8

Lecture Schedule

Problem How do you schedule l lectures in the least number of lecture halls? Assume that you know the start time stime and nish time ftime of each lecture. Solution Maintain two min heaps: lecture-heap, whose key is the start time of each lecture and lecture-hall-heap, whose key is the nish time in each lecture hall. while not empty(lecture-heap) { l = extract_min(lecture-heap) if peek_min(lecture-hall-heap).key < l.key

12

CHAPTER 2. ALGORITHMS decrease_key(lecture-hall-heap, root(lecture-hall-heap), l.ftime) else { n = create_new_node(lecture-heap) n.key = l.ftime insert(lecture-hall-heap, n) }

Вам также может понравиться