There are N stones arranged in a circle. A frog sits on the first stone. The frog keeps jumping in clock-wise direction from stone to stone. It skips the stones in increments of 1 for each jump. ie, for the first jump it will skip 0 stones, it skips one stone for the 2nd jump, 2 stones for the 3rd jump and so on.
The task is, given the number of stones N, find out if the frog will reach all the stones.
Eg:
N=1 ---> true
N=2 ---> true --> jumps=(1,2)
N=3 ---> false --> jumps=(1,2,1,1,2,1,1,2,1.....)
N=4 ---> true --> jumps=(1,2,4,3)
I have tried out for different values for N. All I could see was, if N is a power of 2 then all stones can be reached. Also if the any stone is visited more than once before visiting all the stones, then the answer is false. I could not find a reasoning for the observations and hence could not prove it.
I think you're thinking about this the wrong way. Don't get me wrong, it's cool to do mathematical analysis and come out with a simple result, like, "All stones can be reached if and only if N is a power of 2." (And in fact, I believe that that result is correct.) But you don't need to find that sort of result in order to write an algorithm that can answer the question.
Instead, your algorithm can just simulate the frog's jumps (which you've obviously already figured out how to do), and see if it hits every stone. The only tricky part is that the frog plans to continue jumping forever, and obviously you want your algorithm to finish in a finite amount of time. The key insight is that the frog's sequence of jumps will always end up in a loop, so you only need to continue simulating the sequence long enough to be sure that you've entered the loop and completed one pass through it.
How do we know this?
To see why, imagine that we know that the frog has just jumped from stone #i to stone #j. Is that enough to tell us where the frog will jump to next? The answer is "yes"; we don't know whether the frog thinks it skipped j−i−1 stones vs. N+j−i−1 stones vs. 2N+j−i−1 stones or whatnot, but it doesn't matter, because the next stone it lands on doesn't depend on whether the next jump skips j−i stones vs. N+j−i stones vs. 2N+j−i stones — these are all equivalent. So if we know its last jump then we know its next jump, and if we know its next jump then we know the jump after that, and so on: so this one jump is enough to determine the whole rest of the sequence of stones.
This means that there at most N2 possible "states" that the sequence can be in, always determined by the prior stone and the next stone, where each state fully determines all subsequent states. So if you simulate the sequence through at least N2 states, then either you've visited every state exactly once or you've visited some state at least twice (by the pigeonhole principle), so you've necessarily hit all the states you're going to, which means you've necessarily landed on all the stones that you're going to.
That gives you an algorithm in O(N2) time and O(N) space.
You can potentially improve this by
tracking which states you've already visited, and terminating as soon as you find that you've returned to a state.
tracking how many stones you've already landed on, and terminating as soon as you find that you've landed on all of them.
which would complete in O(N) time if you're right that "if the any stone is visited more than once before visiting all the stones, then the answer is false", while still behaving correctly (and still within O(N2) time) if that theory is wrong.
Related
So I had a programming competition ,I was stuck in a question and I trying to solve it these few days. because I want to know the answer so much, but I'm not able to do it. Any explanation or answer will be appreciated. Here is the question:
There’s a concert happening at a Hall. The hall is an infinitely long 1D number line, where each of the N students are standing at a certain point in the number line. Since they are all scattered around different positions in the number line, its getting harder to manage them. So the organizer Kyle wants to move them in the hall in such a way so that they all are in consecutive positions, for example, they are in positions 2,3,4,5 instead of being scattered around like 1,3,5,6. In simpler words, there is no gap between them. At one time Kyle can pick one person who is on the most outer positions on any side. For example in 1,3,5,6 the most outer positions are 1 and 6. He can pick either of them and move them to any unoccupied position so that they are not in the most outer position anymore. This makes them come closer and closer with each move until they are all in consecutive positions. Find the maximum and minimum number of moves that can accomplish this task.
The maximum is the count of gaps, since the most inefficient move will reduce the count of gaps between the outermost pair by one.
For the minimum, given k people, in linear time (using a sliding window) find the stretch of k consecutive positions with the most people, and call this count c. Then the minimum is k-c, where each move puts someone from outside this window to inside it.
I have some idea for you but I'm not totally sure I got it right..
So:
If number 1 is currently the most outer than he is then jumping to the highest number
and number 2 is now the outer and it goes infinitely and same goes for the other end the outer on the other side is moving to the next becoming last and so on.. make sense?
I'm self-learning with the edX course CS 188.1x Artificial Intelligence. Since the course concluded a year ago, it is in "archive mode" and there are no teaching staff to help with the questions. This also means I get no credit for finishing the course, so hopefully asking for help with a "homework" question here is okay.
In the first homework assignment the following question is asked:
Question 9: Hive Minds Lost at Night It is night and you control a single insect. You know the maze, but you do not know what square the
insect will start in. You must pose a search problem whose solution is
an all-purpose sequence of actions such that, after executing those
actions, the insect will be on the exit square, regardless of initial
position. The insect executes the actions mindlessly and does not know
whether its moves succeed: if it uses an action which would move it in
a blocked direction, it will stay where it is. For example, in the
maze below, moving right twice guarantees that the insect will be at
the exit regardless of its starting position.
It then asks the size of the state space. The answer is given as 2^MN, where M and N are the horizontal and vertical dimensions of the maze. Why is the answer the power set of MN? In my mind, the bug can only be in one square at the beginning, and we only have one bug, so I know the number of start states is MN. But the number of start states != state space, and that is where I am confused.
FYI - the cost per move is 1, and the bug can only move 1 square left, right, up, or down at a time. The goal is to get to the X (goal square).
Okay - I think I got it.
Set of all subsets (power set*) is exactly the right way to think about this. The state space is the set of all states.
1) Definition of state:
"A state contains all of the information necessary to predict the effects of an action and to
determine if it is a goal state." (http://artint.info/html/ArtInt_48.html)
The actions in this scenario are simple: left, right, up, down. They are the possible movements a bug could make.
2) Definition of solution:
Solutions are sequences of actions that lead to the goal test being
passed.
If we only permitted MN states, one for each possible starting position the bug was in, then we would have a state space that gave solutions that were valid only for discrete starting positions. But, the solution must be valid regardless of the initial state of the bug. This means the solution must work for scenarios in which the bug could occupy any of the MN available squares.
In other words, the solutions must be valid for each and every subset (combination) of possible starting spaces, which yields the power set of MN, which is 2^MN.
Why? Because solutions that are valid for a given start state may not be valid for all other start states. And the problem requires us to find solutions that are valid for all start states. This is also why the state space is much larger than MN even though in reality our bug only occupies 1 of the MN positions upon initialization. Just because a solution (sequence of moves) works when the bug starts at (1, 1) doesn't mean that solution (sequence of moves) will also work for the bug starting at (2, 1).
Bonus Question: Why isn't the state space just 1, the full set where
each of the MN squares 'has' a bug (and bugs are permitted to move
on top of each other)?
I was tempted to say that just because a sequence of moves gives a goal state when the bug can start at all of the MN possible positions, that doesn't mean that same sequence of moves gives a goal state when the bug starts at (3, 2) or at MN - 1 or MN - 2 etc. possible positions. But by definition it must (a solution over all starting points must be a solution over every finite subset of starting points).
So I think the reason you evaluate starting states other than "all boxes have a bug" is because the solution generated by evaluating only that state may not be optimal. And in fact this interpretation is borne out by what the homework gives as admissible heuristics for this problem:
The maximum of Manhattan distances to the goal from each possible
location the insect could be in.
OR
The minimum of Manhattan distances to the goal from each possible
location the insect could be in.
The case where we just have one starting state with bugs on all the boxes (with the magic ability to be on top of each other) is the relaxed problem we use to define our heuristic. Again by definition of admissibility, since the heuristic must not overestimate the true (arc) cost of an action, and since arc cost is given by Manhattan distances, both the heuristics above are admissible. (The maximum case is admissible because each possible location for the bug is, in fact, possible - thus the max cost is possible).
*If you don't know what power set means, all you need to know is that the power set is the set of all subsets of a given set. It is given by 2^(size of the set).
In other words, if I have a set of three balls {red, blue, green} and I want to know how many different subsets I have, I can calculate it as follows. A subset either has the element in it (1), or it doesn't (0). So {0, 0, 1} would be the subset of only the green ball, {1, 1, 1} would be the subset of all the balls (yes, technically this is a subset) and {0, 0, 0} would be the subset of none of the balls (again, technically a subset). So we see that the number of all subsets is 2^3 = 8. Or in our problem, 2^MN.
This is a question about the longest palindrome algorithm discussed here some time ago. The quoted blog post, which explains the algorithm, says: "to pick the next center, take the center of the longest palindromic proper suffix of the current palindrome". Unfortunately, they don't provide a proof and I don't really understand why the next center is the center of the longest palindromic proper suffix of the current palindrome.
Can anybody prove/explain it ?
So we're moving to the right...
Say your "current" palindrome is 40 letters big. (Maybe centered on say position 100.) You're trying to find a bigger one.
(OK, there might be a bigger one that is 900 letters long, and that is 50,000 letters to the right -- totally uninvolved with this one. That's fine. But we'll get to that in the future. For now, we have to move the center to the right while looking for longer-than-40 palindromes. Makes sense?)
So we have to move to the right - we could move one step. BUT we want to move as far as possible without missing any.
Now, if the next one to the right is going to include this one...in fact, it has to include the right-most letter of this group of 40. (It can't be further to the left, as we've already checked, so, it must center after 100, and, because it's going to be longer than 40, it must include our right-hand letter, #120.)
So how far back do we have to go?
Well, you can't go back (from 120) further than a palindrome! If it's not a palindrome in the middle it will never be a palindrome.
3333333333333331110111
You can only go "back" to the 0. the 1 sitting to the left of the 0 (for example), could never be a palindrome.
So it's that simple. You have to include our rightmost letter (if we're going to include any of us at all), and, you want it to be as big as possible, and it has to be a palindrome because palindromes can only start (I mean "from the middle") with palindromes.
in the example above it's not possible that the 1 to the left or the 0, or let's say the right-most 3, could ever in this universe center a palindrome, no matter what we later find on the right. They don't have palindromes around them, so they could "never be" a palindrome center!
Note that the 3 in the middle of the 3s could possibly center a bigger palindrome .... but don't forget we've already checked this is the longest palindrome so far (based on centers, from the left), so that cannot be true.
So any palindrome that is longer than this one -- rather, the next possible starting point for a palindrome longer than this one -- is that 0.
In other words, it's simply the center of the biggest palindrome we currently have at the right. (so, not the "111" which is a palindrome but short, but the "1110111" which is the longest palindrome you can see stuck on the right.)
Indeed, the two possibilities we have to check are (A) the "0" and (B) the "1" at the second-last spot. of course, among those two possibilties, we have to go from left to right, so (A) the "0" is indeed the next one to check.
Don't forget those two (the 0 and the 1 in question) are equivalent to saying "there's a palindrome 1110111 stuck to the end, and there's a shorter palindrome 111 stuck to the end".
Of course 1110111 is longer, so the center of 1110111 is obviously to the left of the center of 111.
The longest palindrome stuck to the right, will of course have the center closest the left.
So hopefully that makes clear JUST the specific part of the discussion on the linked blog, which, you asked about!!! I deliberately repeated myself in a number of ways, hopefully it helps. It's Jungian algorithms day :)
Again please note I am specifically and only trying to clarify the very specific issue Michael asked about.
Bloody confusing eh?
BTW, I simply ignored the issue of on-character off-character centers - but it is irrelevant to understanding what you asked about.
A question from Math Battle.
This particular question was also asked to me in one of my job interviews.
" A monkey has two coconuts. It is fooling around by throwing coconut down from the balconies
of M-storey building. The monkey wants to know the lowest floor when coconut is broken.
What is the minimal number of attempts needed to establish that fact? "
Conditions: if a coconut is broken, you cannot reuse the same. You are left with only with the other coconut
Possible approaches/strategies I can think of are
Binary break ups & once you find the floor on which the coconut breaks use upcounting from the last found Binary break up lower index.
Window/Slices of smaller sets of floors & use binary break up within the Window/Slice
(but on the down side this would require a Slicing algorithm of it's own.)
Wondering if there are any other ways to do this.
Interview questions like this are designed to see how you think. So I would probably mention a O(N^0.5) solution as above, but also I would give the following discussion...
Since the coconuts may have internal cracking over time, the results may not be so consistent to a O(N^0.5) solution. Although the O(N^0.5) solution is efficient, it is not entirely reliable.
I would recommend a linear O(N) solution with the first coconut, and then verify the result with the second coconut. Where N is the number of floors in the building. So for the first coconut you try the 1st floor, then the 2nd, then the 3rd, ...
Assuming both coconuts are built structurally exactly the same and are dropped on the exact same angle, then you can throw the second coconut directly on the floor that the first one broke. Call this coconut breaking floor B.
For coconut #2, you don't need to test on 1..B-1 because you already know that the first cocounut didn't break on floor B-1, B-2, ... 1. So you only need to try it on B.
If the 2nd coconut breaks on B, then you know that B is the floor in question. If it doesn't break you can deduce that there were internal cracking and degradation of the coconut over time and that the test is flawed to begin with. You need more coconuts.
Given that building sizes are pretty limited, the extra confidence in your solution is worth the O(N) solution.
As #Rafał Dowgird mentioned, the solution also depends on whether the monkey in question is an African monkey or a European monkey. It is common knowledge that African monkeys throw with a much greater force. Hence making the breaking floor B only accurate with a variance of +/- 2 floors.
To guarantee that the monkey doesn't get tired from all those stairs, it would also be advisable to attach a string to the first coconut. That way you don't need to do 1+2+..+B = B*(B+1)/2 flights of stairs for the first coconut. You would only need to do exactly B flights of stairs.
It may seem that the number of flights of stairs is not relevant to this problem, but if the monkey gets tired out in the first place, we may never come to a solution. This gives new considerations for the halting problem.
We are also making the assumption that the building resides on earth and the gravity is set at 9.8m/s^2. We'll also assume that no gravitation waves exist.
A binary search is not the answer, because you only get one chance to over-estimate. Binary search requires log m maximum over-estimations.
This is a two phase approach. The first is to iterate over the floors with relatively big steps. After the first coconut breaks, the second phase is to try each floor starting after the last safe floor.
The big steps are roughly sqrt(m), but they are bigger early, and smaller later because if the first coconut breaks early, you can afford more iterations in the second phase.
StepSize = (minimum s such that s * (s + 1) / 2 >= m)
CurrentFloor = 0
While no coconuts broken {
CurrentFloor += StepSize
StepSize -= 1
Drop coconut from CurrentFloor
}
CurrentFloor -= StepSize + 1
While one remains coconut unbroken {
CurrentFloor += 1
Drop remaining coconut from CurrentFloor
}
// CurrentFloor is now set to the lowest floor that will break the coconut,
// using no more total drops than the original value of StepSize
The best solution I know is 2*sqrt(n). Drop the first coconut from sqrt(n), 2*sqrt(n),... up to n (or until it breaks). Then drop the second one from the last known "safe" point, in one floor increments until it breaks. Both stages take at most sqrt(n) throws.
Edit: You can improve the constant within O(sqrt(n)), see comment by recursive. I think that the first step should be around sqrt(2*n) and decrease by 1 with each throw, so that the last step (if the breaking height is actually n) is exactly 1. Details to be figured out by readers :)
Since it's an interview question, consider
The expensive operation is the monkey going up and down the stairs, not tossing the coconut. Thinking about it this way, the 'linear' approach is actually N2.
The energy imparted to the coconut by falling is roughly proportional to the height of the drop. If the shell is broken after absorbing some amount of energy in ALL of it's falls ...
Tough interview question. It took me several days.
I believe the # of tries is 1.5 times SQRT of # of floors. (For 100 floors and 2 coco it is 15)
We want to minimize the size of each try and the # of tries, using both together to cover all possible floors. In such cases a sqroot turns out to be a good starting point, but we vary the size of each try and average around the sqroot.
This way we have the best of both worlds : Having the size of each try evenly distributed around the sqroot gives us the best results. For 100 and 2, this is 15,14,13,12,11,10,9,8,7,6
This works out to 1.5 times 10.
100 (or some even number 2N :-) ) prisoners are in a room A. They are numbered from 1 to 100.
One by one (from prisoner #1 to prisoner #100, in order), they will be let into a room B in which 100 boxes (numbered from 1 to 100) await them. Inside the (closed) boxes are numbers from 1 to 100 (the numbers inside the boxes are randomly permuted!).
Once inside room B, each prisoner gets to open 50 boxes (he chooses which one he opens). If he finds the number that was assigned to him in one of these 50 boxes, the prisoner gets to walk into a room C and all boxes are closed again before the next one walks into room B from room A. Otherwise, all prisoners (in rooms A, B and C) gets killed.
Before entering room B, the prisoners can agree on a strategy (algorithm). There is no way to communicate between rooms (and no message can be left in room B!).
Is there an algorithm that maximizes the probability that all prisoners survive? What probability does that algorithm achieve?
Notes:
Doing things randomly (what you call 'no strategy') indeed gives a probability of 1/2 for each prisoner, but then the probability of all of them surviving is 1/2^100 (which is quite low). One can do much better!
The prisoners are not allowed to reorder the boxes!
All prisoners are killed the first time a prisoner fails to find his number. And no communication is possible.
Hint: one can save more than 30 prisoners on average, which is much more that (50/100) * (50/99) * [...] * 1
This puzzle is explained at http://www.math.princeton.edu/~wwong/blog/blog200608191813.shtml and that person does a much better job of explaining the problem.
The "all prisoners are killed" statement is wrong.
The "you can save 30+ on average" is also wrong, the article says that 30% of the time you can save 100% of the prisoners.
I find a low tech solution to this type of problem is always the best way to go.
first we make some assumptions about the situation
The prisoners are not all programmers or mathematicians
They don't want to die
The guards are well armed
So with a 0.005% chance that they will see tomorrow, there is a very simple and low tech solution to this problem. RIOT
its all about losses v potential gain, the chances are the prisoners far out number the guards, and using each other as human shields, as they are all dead men anyway if they don't, they can increase the chances they will over power a guard, once they have his weapon there chance goes up, helping them over power more guards to get more fire power to further increase there survival rate. once the guards realise what's happening, they will probably run for the hills and lock down the prison, this will give the media a heads up and then its a human rights issue.
Implement a sorting algorithm and sort the boxes according to the numbers inside them.
First prisoner sorts 50 boxes, and the second prisoner sorts the other 50 and merges with the first one. (Note that the second prisoner can guess the values inside the first 50 boxes)
After the 2nd prisoner, all of the boxes will be in a sorted order !!!
Everybody else can open the boxes containing their numbers easily then.
I don't know if this is allowed but the best approximation I can find is:
EDIT: Ok, I think this makes it. Of course I'm treating this as a computing problem, I don't think any prisioner will be able to perform this, although is pretty straight forward if you don't.
Find the first 50 primes, let's asume we hold them in an array called primes.
The first prissioner enters room B and opens the first box and finds the number m.
Wait primes[1]^m (that would be 3^m)
Open box 2 and read the number --> n
Wait (primes[2]^n - 1) * primes[1]^m, that would be (5^n - 1) * 3^m and the total time he has been waiting would be 3^n * 5^n
Repeat. After the first prisioner the total time for him would be:
3^m * 5^n * 7^p ... = X
Before the second prisioner enters the room factorize X. You know beforehand the prime numbers that have been used so the factorization is trivial. Doing so you obtain m, n, p, etc so the second prisioner knows every box/number combination the previous prisioner used.
The probability of the first one getting everybody killed is 1/2, the second one will have a 50 / (100 - n) (being n the numbers of attemps of the first one) the third one will have 50 / (100 - n - m) (if n + m = 100 then all positions are known) and so on.
Obviously the next prissioner must skip the already known boxes (except for the last choice if the box which contains his number is already known)
I don't know what's the exact possibility as it dependes on how many choices they have to do but I'd say it's pretty high.
EDIT: Rereading, if the prissioner does not have to stop when he obtains his number then the probability for the whole group is vastly improved, exactly 50%.
EDIT2: #OysterD see it this way. If the first prisioner can open 50 boxes then the second one know if its number is in any of that boxes. If it is, then he can open other 49 (and by doing so learning the box/number comination of the 100 boxes) and finally open his one. So if the first prissioner succeds then everyone succeds. Remember that each prisioner provides a way for the other to know exactly the boxes/number combination for every box he opens.
Maybe I'm not reading it right, but the question seems to be badly constructed or missing information.
If he finds the number that was
assigned to him in one of these 50
boxes, the prisoner gets to walk into
a room C and all boxes are closed
again before the next one walks into
room B from room A. Otherwise, all
prisoners (in rooms A, B and C) gets
killed.
Does the last sentence there mean that all prisoners are killed the first time a prisoner fails to find their number? If not, what happens to prisoners that don't find their number?
If no communication is possible, and whenever a prisoner enters room B it is always in an identical state then there is no possibility for a strategy.
The prisoners could could say before they leave room A which number box they are going to open. But without subsequent prisoners knowing whether they were successful or not (assuming failure for one isn't failure for all) when the next prisoner enters room B they still have the same odds of picking their number as the previous prisoner (always 1:100).
If failure for one is failure for all, then by knowing which box the previous prisoners opened, and by dint of the fact that they haven't all been killed, each successive prisoner could reduce the odds of picking the wrong box by one box. i.e. 1:100 for the first prisoner, 1:99 for the second, down to 1:1 for the last.
The prisoners could agree that prisoner 1 open boxes 1-50.
If they're all still alive, they agree that the next prisoner opens boxes 2-51. (the 2 is arbitrary, but simple to remember this rule) His odds of surviving given that P1 survived are now 50/99. You want to eliminate opening a box when you know that the previous guy found his.
I don't know if that's optimal, but it's lot better than random.
The probability of surviving that looks like
50/100 * 50/99 * 50/98 *. . .50/51 * 1
I think since no communication is possible, the best strategy would involve
distributing the probability of each prisoners as evenly as possible
Am I on the right path or not?
Information available for each prisoner:
The number of survivied prisoners, so if you have an efficient box picking system that utilizes the order any prisoner enters room B, then a strategy is definitely possible
Which boxes the earlier prisoners picked. Of course, no communication is possible during the run and it wouldn't be possible to remember any 100s box picking permutation. But you could use this information to compute in a system before the run starts.
My take:
Draw a table of numbers with 2 columns, the first column contains the box number (from box #1 to box#100). Each prisoner then gets to pick 50 boxes and whatever box they pick, they should put 1 mark on the corresponding row in the second column.
All prisoners are however required to never pick any box twice. And no box may be marked more than 50. Some prisoners may get less options than others since some box may get filled to 50 marks first.
When a prisoner is moved to room B he/she opens whatever boxes he has marked on.
If all prisoners are killed when someone fails to find their number then you either save 100 or 0. There is no way to save 30 people.
Same concept.
Aonther take:
Write down a list of the first 100 binary numbers which has fifty 1s and fifty 0s.
Sort them from lowest to highest.
Prisoner #1 gets the first number, prisoner #2 gets the second, prisoner #3 gets the third and so on...
Each prisoner remembers his/her binary number.
When any prisoner is moved to room B, he/she then match the binary digits of the number he remembered with each of the box, the highest bit is matched with the leftmost box, the next highest bit is matched with the second leftmost box ... the lowest bit is matched with the rightmost box.
He/she opens whatever boxes matched with 1 and leave closed boxes matched with 0.
This would minimizes the probability because early prisoners will get digits that are different from the later prisoners and prisoners which has number close together would get digits close together. This doesn't guarantee survivability but if the early prisoners do survive, chances are the later prisoners would have a higher probability of surviving as well.
I haven't thought out the exact figures and rationale though, but this is one quick solution I can think of at the moment.
There aren't any time limits in the question so I suggest that prisoners should decide to take 1 hour per box and open them in the order presented. If the second prisoner is allowed into the room after 2 hours then he knows that the first prisoner found his own number in box 2. Therefore he knows to skip box 2 in his sequence and opens boxes 1, 3, 4...51
First prisoners odds on losing are 50/100
Give that the first prisoner survived then the second prisoners chance of winning are 50/99
So answer appears to be ((50 ^51)*49!)/100!
which according to google makes 2.89*10^-9
which is pretty much nil
So even if the prisoners knew the boxes the previously lucky ones found their number in there'd be no hope