<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rebrained!</title>
	<atom:link href="http://rebrained.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://rebrained.com</link>
	<description>Quick, Blog it before I forget it...</description>
	<lastBuildDate>Sat, 04 Sep 2010 08:52:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Prime numbers and Numpy &#8211; Python</title>
		<link>http://rebrained.com/?p=458</link>
		<comments>http://rebrained.com/?p=458#comments</comments>
		<pubDate>Fri, 27 Aug 2010 20:27:01 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[prime numbers]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=458</guid>
		<description><![CDATA[I&#8217;ve been looking at the element-wise operations in Numpy arrays. The code below generates 100K primes in about 1.3 secs on my laptop. import numpy import math def prime(upto=100): return filter(lambda num: (num % numpy.arange(2,1+int(math.sqrt(num)))).all(), range(2,upto+1)) >>> prime() [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been looking at the element-wise operations in Numpy arrays.   The code below generates 100K primes in about 1.3 secs on my laptop.</p>
<pre class="brush: python">
import numpy
import math
def prime(upto=100):
    return filter(lambda num: (num % numpy.arange(2,1+int(math.sqrt(num)))).all(), range(2,upto+1))
</pre>
<pre>
>>> prime()
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>>
</pre>
<p><nl><br />
Similiar code that uses a for loop runs about 5 times longer for 100K primes, about 7 secs:</p>
<pre class="brush: python">
import numpy
import math
def prime2(upto=100):
    return filter(lambda num: numpy.array([num % factor for factor in range(2,1+int(math.sqrt(num)))]).all(), range(2,upto+1))
</pre>
<p>By not including even numbers, the original code can be optimized to run in half the time again, about .7 secs for 100K primes.</p>
<pre class="brush: python">
import numpy
import math
def prime3(upto=100):
    return [2]+filter(lambda num: (num % numpy.arange(3,1+int(math.sqrt(num)),2)).all(), range(3,upto+1,2))
</pre>
<p>The above code is not the fastest implementation, but illustrative of using the element-wise operations in Numpy arrays rather than looping through a list.<br />
<nl><br />
We can write faster code by breaking after finding the first modulo equal zero condition.  The code below runs in about .4 seconds for 100K primes: </p>
<pre class="brush: python">
import numpy
import math
def prime4(upto=100):
    primes=[2]
    for num in range(3,upto+1,2):
        isprime=True
        for factor in range(3,1+int(math.sqrt(num)),2):
            if not num % factor: isprime=False; break
        if isprime: primes.append(num)
    return primes
</pre>
<p>Ok Scruffy Pete has laid down the challenge in the comments section so I need to get serious about optimization.  The code below uses a few Numpy tricks for a zippy implementation and generates 1 million primes in about .03 secs, about 6X faster than Scruffy Pete&#8217;s.  </p>
<pre class="brush: python">
import math
import numpy
def prime5(upto):
    primes=numpy.arange(2,upto+1)
    isprime=numpy.ones(upto-1,dtype=bool)
    for factor in primes[:int(math.sqrt(upto))]:
        if isprime[factor-2]: isprime[factor*2-2::factor]=0
    return primes[isprime]
</pre>
<p>Scruffy Pete&#8230; Ball&#8217;s in your court matey!<br />
<nl><br />
UPDATE 9/3 &#8211; did a half sieve style implementation of the above (see comments) which runs a little faster &#8211; under .02 secs for 1 million primes:</p>
<pre class="brush: python">
import math
import numpy
def prime6(upto):
    primes=numpy.arange(3,upto+1,2)
    isprime=numpy.ones((upto-1)/2,dtype=bool)
    for factor in primes[:int(math.sqrt(upto))]:
        if isprime[(factor-2)/2]: isprime[(factor*3-2)/2::factor]=0
    return numpy.insert(primes[isprime],0,2)
</pre>
<p>I posted this on the stack overflow site (see comments section).   They run timings which you can see on:<br />
<a href="http://ideone.com/oDg2Y">http://ideone.com/oDg2Y</a></p>
<p>My impl is there listed under nolfonzo_prime6</p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=458</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Birthday Simulations &#8211; Python</title>
		<link>http://rebrained.com/?p=431</link>
		<comments>http://rebrained.com/?p=431#comments</comments>
		<pubDate>Fri, 27 Aug 2010 03:38:50 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[simulations]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=431</guid>
		<description><![CDATA[I&#8217;ve wanted for a while to write simple python simulations of the birthday puzzles I&#8217;d written about previously. Then, recently, I was wondering what the most efficient way to tell if a list has duplicate elements. It suddenly dawned on me that these two topics were related: The following code generates birthday samples for a [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve wanted for a while to write simple python simulations of the <a href="http://rebrained.com/?p=317">birthday puzzles</a> I&#8217;d written about previously.  Then, recently, I was wondering what the most efficient way to tell if a list has duplicate elements.   It suddenly dawned on me that these two topics were related:</p>
<p>The following code generates birthday samples for a given number of people, then works out the proportion of these samples that contain at least one shared birthday:</p>
<pre class="brush: python">
import numpy
def sharedbday1(people,simulations=50000):
    samples = numpy.random.random_integers(0,365, size=(simulations, people))
    hasnoshared=map(lambda x: len(x)==len(set(x)),samples)
    return 1-float(sum(hasnoshared))/simulations
</pre>
<p>Timing this in IPython on my laptop for 50k simulations takes about .5 secs to run:</p>
<pre>
In [579]: time sharedbday1(23)
CPU times: user 0.56 s, sys: 0.00 s, total: 0.56 s
Wall time: 0.56 s
Out[580]: 0.50678000000000001
</pre>
<p><nl><br />
Since we&#8217;re using Numpy, there&#8217;s a cleverer way to see if there&#8217;s a shared birthday in each sample.  We can sort the array, then compare it element-wise against a slice of itself offset by one &#8211; if we find any equivalent elements we&#8217;ve found a sample with a shared birthday.  With Numpy arrays this is achieved very neatly as operations in Numpy are performed element-wise by default:</p>
<pre class="brush: python">
import numpy
def sharedbday2(people, simulations=50000):
    samples = numpy.random.random_integers(0,365, size=(simulations, people))
    samples.sort()
    hasshared  = ((sample[1:]==sample[:-1]).any() for sample in samples)
    return float(sum(hasshared))/simulations
</pre>
<p>Unfortunately this runs at about half the speed of my original code:</p>
<pre>
In [582]: time sharedbday2(23)
CPU times: user 1.01 s, sys: 0.00 s, total: 1.01 s
Wall time: 1.02 s
Out[583]: 0.50988
</pre>
<p><nl><br />
I exchanged some emails with Travis Oliphant of Numpy fame, who suggested the following code which is really neat and I think shows off the power of Numpy in a simple and elegant way:</p>
<pre class="brush: python">
import numpy
def sharedbday3(people, simulations=50000):
    samples = numpy.random.random_integers(0,365, size=(simulations, people))
    samples.sort(axis=-1)
    hasshared = (samples[:,1:] == samples[:,:-1]).any(axis=-1)
    return float(sum(hasshared))/simulations
</pre>
<p>This is fast and shows a speed-up of least 5X on my original code &#8211; with a wall time of .09s:</p>
<pre>
In [585]: time sharedbday3(23)
CPU times: user 0.10 s, sys: 0.00 s, total: 0.10 s
Wall time: 0.09 s
Out[586]: 0.50119999999999998
</pre>
<p>As Travis explains it:<br />
<em> You create a 2-d array up-front with the simulations along one axis (i.e. every row of the 2-d array is a separate simulation).   Then you can use the sample approach used above, but this time letting NumPy do the loop over the rows (down in C).  The sort and any methods on NumPy arrays take an axis keyword which determines the dimension over which the operation works.  The operation is then repeated implicitly over the other dimensions.   So, in the 3rd version shared birthday there are no for loops.    The penalty paid is memory usage: a 2-d array instead of throw-away 1-d arrays.  But, of course, less memory management is also a major reason for the speed gain. </em></p>
<p><nl><br />
For completeness, I made some minor modifications to the original code above to simulate the probability that at least one person in a group shares your birthday (rather than of finding a shared birthday between them).</p>
<pre class="brush: python">
import numpy
def sharemybday(people,simulations=50000):
    mybday=0
    samples = numpy.random.random_integers(0,365, size=(simulations, people))
    hasshared=map(lambda x: mybday in x,samples)
    return float(sum(hasshared))/simulations
</pre>
<pre>
In [1509]: sharemybday(253)
Out[1509]: 0.50431999999999999
</pre>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=431</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shortest Path &#8211; Python</title>
		<link>http://rebrained.com/?p=392</link>
		<comments>http://rebrained.com/?p=392#comments</comments>
		<pubDate>Tue, 24 Aug 2010 18:26:51 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[graphs]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[shortest path]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=392</guid>
		<description><![CDATA[Problem: Write a python function to calculate the shortest path given a start node (or vertex), an end node and a graph. Use Dijkstra&#8217;s algorithm. Return the distance from the start node to the end node, as well as the path taken to get there. The implementation below sticks pretty closely to the algorithm description [...]]]></description>
			<content:encoded><![CDATA[<p>Problem:  Write a python function to calculate the shortest path given a start node (or vertex), an end node and a graph.  Use <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra&#8217;s algorithm</a>. Return the distance from the start node to the end node, as well as the path taken to get there.  </p>
<p>The implementation below sticks pretty closely to the algorithm description in the wikipedia entry, which I turned into something a little more pseudo-code-ish to help me implement it:</p>
<blockquote>
<h4></h4>
<h4>Initial state:</h4>
<ol>
<li> give nodes two properties &#8211; node.visited and node.distance</li>
<li> set node.distance = infinity for all nodes except the start node which is set to zero.</li>
<li> set node.visited = false for all nodes</li>
<li> set current node = start node.</li>
</ol>
<h4></h4>
<h4>Current node loop:</h4>
<ol>
<li> if current node = end node, finish and return current.distance &#038; path</li>
<li> for all unvisited neighbors, calc their tentative distance (current.distance + edge to neighbor).</li>
<li> if tentative distance < neighbor's set distance, overwrite it.</li>
<li> set current.isvisited = true.</li>
<li> set current = remaining unvisited node with smallest node.distance</li>
</ol>
</blockquote>
<p>Here&#8217;s my implementation &#8211; it&#8217;s recursive, as suggested by the algorithm description:</p>
<pre class="brush: python">
import sys
def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
    &quot;&quot;&quot;Find the shortest path between start and end nodes in a graph&quot;&quot;&quot;
    # we&#039;ve found our end node, now find the path to it, and return
    if start==end:
        path=[]
        while end != None:
            path.append(end)
            end=predecessors.get(end,None)
        return distances[start], path[::-1]
    # detect if it&#039;s the first time through, set current distance to zero
    if not visited: distances[start]=0
    # process neighbors as per algorithm, keep track of predecessors
    for neighbor in graph[start]:
        if neighbor not in visited:
            neighbordist = distances.get(neighbor,sys.maxint)
            tentativedist = distances[start] + graph[start][neighbor]
            if tentativedist &lt; neighbordist:
                distances[neighbor] = tentativedist
                predecessors[neighbor]=start
    # neighbors processed, now mark the current node as visited
    visited.append(start)
    # finds the closest unvisited node to the start
    unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not in visited)
    closestnode = min(unvisiteds, key=unvisiteds.get)
    # now we can take the closest node and recurse, making it current
    return shortestpath(graph,closestnode,end,visited,distances,predecessors)

if __name__ == &quot;__main__&quot;:
    graph = {&#039;a&#039;: {&#039;w&#039;: 14, &#039;x&#039;: 7, &#039;y&#039;: 9},
            &#039;b&#039;: {&#039;w&#039;: 9, &#039;z&#039;: 6},
            &#039;w&#039;: {&#039;a&#039;: 14, &#039;b&#039;: 9, &#039;y&#039;: 2},
            &#039;x&#039;: {&#039;a&#039;: 7, &#039;y&#039;: 10, &#039;z&#039;: 15},
            &#039;y&#039;: {&#039;a&#039;: 9, &#039;w&#039;: 2, &#039;x&#039;: 10, &#039;z&#039;: 11},
            &#039;z&#039;: {&#039;b&#039;: 6, &#039;x&#039;: 15, &#039;y&#039;: 11}}
    print shortestpath(graph,&#039;a&#039;,&#039;b&#039;)

    &quot;&quot;&quot;
    Result:
        (20, [&#039;a&#039;, &#039;y&#039;, &#039;w&#039;, &#039;b&#039;])
        &quot;&quot;&quot;
</pre>
<p>You&#8217;ll see I turned the example in wikipedia into a graph for the test case in the code above.  </p>
<p>I found this useful about how to represent and process graphs in python: <a href="http://www.python.org/doc/essays/graphs.html">http://www.python.org/doc/essays/graphs.html</a>.  I think this was written by Guido himself.   </p>
<p>There&#8217;s a bunch of interesting implementations on the web, including two <a href="http://code.activestate.com/recipes/119466/">here</a>.  More elegant, but it took me a while to understand them.</p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=392</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cyclic Linked List &#8211; Python function to find the node at the start of the loop</title>
		<link>http://rebrained.com/?p=366</link>
		<comments>http://rebrained.com/?p=366#comments</comments>
		<pubDate>Mon, 19 Jul 2010 03:01:56 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[linked lists]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=366</guid>
		<description><![CDATA[I&#8217;d blogged previously about writing a python function to find out whether a linked list is acyclic or not &#8211; it&#8217;s worth a read before tackling this one. Problem: Given the head node of a cyclic (or circular) linked list, write a function to return the node that is at the start of the loop. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d blogged <a href="http://rebrained.com/?p=14">previously </a>about writing a python function to find out whether a linked list is acyclic or not &#8211; it&#8217;s worth a read before tackling this one.</p>
<p>Problem:  Given the head node of a cyclic (or circular) linked list, write a function to return the node that is at the start of the loop.  </p>
<p>A cyclic linked list would look something like this:</p>
<p>A->B->C->D->E->F->C</p>
<p>In the case above, A is the head node, and C is the node at the start of the loop.</p>
<p><strong>My Solution</strong></p>
<p>Let&#8217;s call <i>x</i> the distance from the head to the start of the loop, and <i>c</i> the number of nodes in the loop.</p>
<p>We kick off a fast and a slow pointer from the head, with the fast pointer going twice as fast as the slow pointer (skipping every other node).  By the time the slow pointer gets to the start of the loop, the fast pointer will have a head start of <i>x</i> (the fast pointer is always the same distance from the slow pointer as the slow pointer is from the head).  </p>
<p>Given its head start of <i>x</i>, when will the fast pointer catch up to the slow pointer?   The fast pointer always needs twice the initial distance from the slow pointer to catch up.   Moving forward in the loop, the fast pointer is <i>c-x</i> nodes from the slow pointer, so it needs <i>2(c-x)</i> nodes to catch up.  In that time, the slow pointer will have managed to move <i>c-x</i> nodes away from the start (half what the fast pointer travelled).</p>
<p>The key thing to note here is that both pointers are now <i>x</i> nodes away from the start of the loop looking in a forwards direction. So you&#8217;ll see that to find the start of the loop the code below gets the fast and slow pointer to meet in the loop, then walks the slow pointer forward <i>x</i> nodes &#8211; the distance from the head to the start.  </p>
<pre class="brush: python">
def startOfCyclicLoop(head):

    &quot;&quot;&quot;
    &gt;&gt;&gt; e1=Element(1)
    &gt;&gt;&gt; e2=Element(2)
    &gt;&gt;&gt; e3=Element(3)
    &gt;&gt;&gt; e4=Element(4)
    &gt;&gt;&gt; e5=Element(5)
    &gt;&gt;&gt; e1.next=e2
    &gt;&gt;&gt; print startOfCyclicLoop(e1)
    None
    &gt;&gt;&gt; e2.next=e3
    &gt;&gt;&gt; e3.next=e4
    &gt;&gt;&gt; e4.next=e5
    &gt;&gt;&gt; print startOfCyclicLoop(e1)
    None
    &gt;&gt;&gt; e5.next=e3
    &gt;&gt;&gt; print startOfCyclicLoop(e1)
    3
    &gt;&gt;&gt; e5.next=e4
    &gt;&gt;&gt; print startOfCyclicLoop(e1)
    4
    &gt;&gt;&gt; e5.next=e2
    &gt;&gt;&gt; print startOfCyclicLoop(e1)
    2
    &quot;&quot;&quot;
    slow=head
    fast=head
    while fast!=None and fast.next!=None:
        slow=slow.next
        fast=fast.next.next
        if (fast==slow):
            slow=head
            while (fast!=slow):
                slow=slow.next
                fast=fast.next
            return fast
    return  None

class Element:
    def __init__(self,data,next=None):
        self.data=data
        self.next=next
    def __str__(self):
        return str(self.data)

if __name__ == &quot;__main__&quot;:
    import doctest
    doctest.testmod()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=366</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Hands on a Clock</title>
		<link>http://rebrained.com/?p=356</link>
		<comments>http://rebrained.com/?p=356#comments</comments>
		<pubDate>Sun, 06 Jun 2010 04:26:37 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=356</guid>
		<description><![CDATA[For a given time, what will be the angle between the hour and minute hands on a clock? Answer expand(document.getElementById('ddet954686115'));expand(document.getElementById('ddetlink954686115')) This is rather a long winded way of solving this, so please let me know if you have something shorter. The angle of the minute hand (from 12 O&#8217;clock): = (minutes / 60) * 360 [...]]]></description>
			<content:encoded><![CDATA[<p>For a given time, what will be the angle between the hour and minute hands on a clock?</p>
<p><a style="display:none;" id="ddetlink98475108" href="javascript:expand(document.getElementById('ddet98475108'))">Answer</a>
<div class="ddet_div" id="ddet98475108"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet98475108'));expand(document.getElementById('ddetlink98475108'))</script>
This is rather a long winded way of solving this, so please let me know if you have something shorter.</p>
<p>The angle of the minute hand (from 12 O&#8217;clock):<br />
= (minutes / 60)  * 360</p>
<p>The angle of the hour hand (from 12 O&#8217;clock) is the angle of the hour plus an adjustment for the minutes:<br />
= (hours / 12) * 360   +   (minutes / 60) * (1 / 12) * 360</p>
<p>So to get the angle between them we subract the two, and get:<br />
= (hours / 12) * 360   +   (minutes / 60) * (1 / 12) * 360 &#8211; (minutes / 60)  * 360<br />
= (hours * 30)   + minutes * .5 &#8211; minutes * 6<br />
= hours * 30 &#8211; minutes * 5.5</p>
<p>Any angle over 180 we can subtract from 360 to get the shortest angle between them.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=356</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anagrams &#8211; Python</title>
		<link>http://rebrained.com/?p=337</link>
		<comments>http://rebrained.com/?p=337#comments</comments>
		<pubDate>Sat, 05 Jun 2010 03:56:46 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[anagrams]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=337</guid>
		<description><![CDATA[Write a Python function to find all the anagrams for each of a supplied list of words. For the word dictionary to find the anagrams you could use the one found on Unix or OS X boxes at /usr/share/dict/words. So for example: >>> for group in anagrams(['dog','cat','horse']): ... print group ... ['dog', 'god'] ['act', 'cat'] [...]]]></description>
			<content:encoded><![CDATA[<p>Write a Python function to find all the anagrams for each of a supplied list of words.  For the word dictionary to find the anagrams you could use the one found on Unix or OS X boxes at <em>/usr/share/dict/words</em>.  So for example:</p>
<pre>
>>> for group in anagrams(['dog','cat','horse']):
...     print group
...
['dog', 'god']
['act', 'cat']
['horse', 'shoer', 'shore']
</pre>
<p>When called without a parameter, make the function return a list of all the anagram groups in the word dictionary, ordered by the group of anagrams with the most words:</p>
<pre>&gt;&gt;&gt; for group in anagrams():
...     if len(group)&gt;6: print len(group), group
...
9 ['ester', 'estre', 'reest', 'reset', 'steer', 'stere', 'stree', 'terse', 'tsere']
9 ['angor', 'argon', 'goran', 'grano', 'groan', 'nagor', 'orang', 'organ', 'rogan']
9 ['caret', 'carte', 'cater', 'crate', 'creat', 'creta', 'react', 'recta', 'trace']
8 ['leapt', 'palet', 'patel', 'pelta', 'petal', 'plate', 'pleat', 'tepal']
8 ['laster', 'lastre', 'rastle', 'relast', 'resalt', 'salter', 'slater', 'stelar']
7 ['dater', 'derat', 'detar', 'drate', 'rated', 'trade', 'tread']
7 ['easting', 'gainset', 'genista', 'ingesta', 'seating', 'signate', 'teasing']
7 ['darter', 'dartre', 'redart', 'retard', 'retrad', 'tarred', 'trader']
7 ['least', 'setal', 'slate', 'stale', 'steal', 'stela', 'tales']
7 ['atle', 'laet', 'late', 'leat', 'tael', 'tale', 'teal']
7 ['alem', 'alme', 'lame', 'leam', 'male', 'meal', 'mela']
7 ['lapse', 'salep', 'saple', 'sepal', 'slape', 'spale', 'speal']
7 ['armet', 'mater', 'metra', 'ramet', 'tamer', 'terma', 'trame']
7 ['argel', 'ergal', 'garle', 'glare', 'lager', 'large', 'regal']
7 ['aldern', 'darnel', 'enlard', 'lander', 'lenard', 'randle', 'reland']
7 ['alert', 'alter', 'artel', 'later', 'ratel', 'taler', 'telar']
7 ['arist', 'astir', 'sitar', 'stair', 'stria', 'tarsi', 'tisar']
7 ['aril', 'lair', 'lari', 'liar', 'lira', 'rail', 'rial']
7 ['asteer', 'easter', 'reseat', 'saeter', 'seater', 'staree', 'teaser']
7 ['arpent', 'enrapt', 'entrap', 'panter', 'parent', 'pretan', 'trepan']
&gt;&gt;&gt;</pre>
<p>Can you think of an elegant (dare I say pythonic?) way to implement the anagrams function?  </p>
<p><strong>Here&#8217;s my attempt:</strong></p>
<pre class="brush: python">
def anagrams(wordsin=None):
    f=open(&#039;/usr/share/dict/words&#039;)
    ana=dict()
    for word in f.readlines():
        ana.setdefault(&#039;&#039;.join(sorted(word.rstrip())),[]).append(word.rstrip())
    if wordsin!=None:
        return [ana.get(&#039;&#039;.join(sorted(wordin)),[]) for wordin in wordsin]
    else:
        return sorted(ana.values(), key=lambda(v): (len(v)),reverse=True)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=337</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Birthday pairings</title>
		<link>http://rebrained.com/?p=317</link>
		<comments>http://rebrained.com/?p=317#comments</comments>
		<pubDate>Fri, 30 Apr 2010 18:20:16 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[birthday pairings]]></category>
		<category><![CDATA[logarithms]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[stirling's approximation]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=317</guid>
		<description><![CDATA[Here&#8217;s two classic birthday puzzles: How many people do you need in a room to have a better than 50% chance of finding at least one shared birthday among them? Answer expand(document.getElementById('ddet1476010724'));expand(document.getElementById('ddetlink1476010724')) Like a lot of these problems, it&#8217;s easier to first find the chances of the proposition not happening &#8211; that is of not [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s two classic birthday puzzles:</p>
<p>How many people do you need in a room to have a better than 50% chance of finding at least one shared birthday among them?  </p>
<p><a style="display:none;" id="ddetlink450932333" href="javascript:expand(document.getElementById('ddet450932333'))">Answer</a>
<div class="ddet_div" id="ddet450932333"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet450932333'));expand(document.getElementById('ddetlink450932333'))</script></p>
<p>Like a lot of these problems, it&#8217;s easier to first find the chances of the proposition not happening &#8211; that is of not finding a shared birthday.  </p>
<p>For this problem, I like to imagine that I have a bunch of 365-card decks.  I deal one card from each deck.  What are the chances that I haven&#8217;t dealt the same card after after dealing from r decks?  You can see that this is a good analogy for our problem.  Looking back at the previous post on <a href="http://rebrained.com/?p=293">dealing a perfect hand</a> may be a good primer for what follows.  </p>
<p>The answer to our card analogy is to take the number of ways I can deal the cards (one from each deck) and get no duplicates divided by the total number of ways I can deal the cards.   From the first deck, I have 365 ways to deal one card.  From the second deck, I have 364 ways to deal one card and not have duplicates.  From the third deck, there are 363 ways, and so on until I get to 365-r+1 ways.  So the number of ways I can deal cards without duplicates is:</p>
<p>= 365 * 364 * &#8230; * (365-r+1)<br />
= 365! / (365-r)!</p>
<p>Now lets work out how many ways there are to deal the cards without restrictions.  The answer is simply:</p>
<p>= 365 ^ r</p>
<p>So now, the probability of not dealing any duplicate cards (and also the chances of not finding anyone with a shared birthday) is:</p>
<p>= (365! / (365-r)!) / 365 ^ r</p>
<p>I was a little stumped at how to solve this, except through some trial and error.   Even then, 365! seems to make calculators, or even trusty google, blow up.  We can use <a href="http://en.wikipedia.org/wiki/Stirling%27s_approximation">Sterling&#8217;s approximation</a> to find that:</p>
<p>ln(365!) = 1792.33142<br />
ln((365-22)!) = 1663.17935<br />
ln((365-23)!) = 1657.34162</p>
<p>So for r=22, our probability of no shared birthdays:<br />
= e ^ (1 792.33142 &#8211; 1 663.17935) / 365 ^ 22 = 0.524310203</p>
<p>For r=23:<br />
= e ^ (1792.33142 &#8211; 1657.34162) / 365 ^ 23 = 0.492707724</p>
<p>Now remember that this is for finding no shared birthdays.  To have at least 1 shared birthday, we need to subract from 1. </p>
<p>So for r=22, the chances of finding at least 1 shared birthday are:<br />
= 1 &#8211; 0.524310203 = 0.475689797</p>
<p>For r=23, the chances are:<br />
= 1 &#8211; 0.492707724 = 0.507292276</p>
<p>So you can see that it takes at least 23 people in a room to have a greater than 50/50 chance of finding a shared birthday.</p>
<p>By the way, to get the Stirling approximation of ln(365!) I typed the following into google:</p>
<p>365 * ln(365) &#8211; (365) + ln(365)/2 + ln (2*pi) / 2)</p>
<p></div></p>
<p>How many people do you need in a room with you to have a better than 50% chance of finding someone who shares your birthday?</p>
<p><a style="display:none;" id="ddetlink838697211" href="javascript:expand(document.getElementById('ddet838697211'))">Answer</a>
<div class="ddet_div" id="ddet838697211"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet838697211'));expand(document.getElementById('ddetlink838697211'))</script></p>
<p>This one&#8217;s a little simpler than the first. Again, it&#8217;s easier to first find the probability of no one having your birthday.   Let&#8217;s imagine people walking in to a room where you are.  The first person has a 364/365 chance of not having your birthday.  And it&#8217;s the same for all subsequent people who walk into the room.  So the chances of no one sharing your birthday after r people have walked in are:</p>
<p>= (364/365)^r</p>
<p>So the chance that at least one person shares your birthday is:</p>
<p>= 1 &#8211; (364/365) ^ r</p>
<p>Let&#8217;s find r when the equation is 1/2, representing the at least 50% chance we were looking for:</p>
<p>1/2 = 1 &#8211; (364/365) ^ r<br />
(364/365) ^ r = 1/2<br />
r * log (364/365) = log (1/2)<br />
r = log (1/2) / log (364/365)<br />
r = 252.651989</p>
<p>So you need to have at least 253 people with you in a room to have a better than 50/50 chance of finding someone sharing your birthday.  It&#8217;s quite amazing how different this answer is to the answer for the first part.</p>
<p></div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=317</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; A perfect hand</title>
		<link>http://rebrained.com/?p=293</link>
		<comments>http://rebrained.com/?p=293#comments</comments>
		<pubDate>Thu, 29 Apr 2010 18:32:42 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[permutations]]></category>
		<category><![CDATA[probability]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=293</guid>
		<description><![CDATA[You deal the first 13 cards from a well shuffled, 52-card deck to someone. What are the chances the 13 cards you deal are of the same suit? Answer expand(document.getElementById('ddet1212804990'));expand(document.getElementById('ddetlink1212804990')) There&#8217;s a couple of ways to do this &#8211; both incorporate useful techniques for solving these kind of problems. The first way is just to [...]]]></description>
			<content:encoded><![CDATA[<p>You deal the first 13 cards from a well shuffled, 52-card deck to someone.  What are the chances the 13 cards you deal are of the same suit?</p>
<p><a style="display:none;" id="ddetlink583598769" href="javascript:expand(document.getElementById('ddet583598769'))">Answer</a>
<div class="ddet_div" id="ddet583598769"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet583598769'));expand(document.getElementById('ddetlink583598769'))</script></p>
<p>There&#8217;s a couple of ways to do this &#8211; both incorporate useful techniques for solving these kind of problems.</p>
<p>The first way is just to look at the first 13 cards dealt and work out how many ways there are to deal a single-suit hand, and divide this by the number of ways there are to deal any hand.  </p>
<p>There are 52 ways you can deal a first card.  There are then 12 ways you can deal a second card if we restrict it to the suit of the first card.  So we now have 52 * 12 permutations.  With the third card, we&#8217;re up to 52 * 12 * 11 permutations.  So we can see that:</p>
<p>Ways to deal a single-suit 13 card hand = 52 * 12!</p>
<p>Using the same logic, we can see that:</p>
<p>Ways to deal any 13 card hand = 52 * 51 * 50 * &#8230; * 40.    This equals 52! / 39!.  (Hopefully this is clear &#8211; the remaining sequence to finish making 52! is 39!). </p>
<p>So the probability of dealing a single-suit 13 card hand = (52 * 12!) / (52! / 39!) = 12! * 39! / 51!</p>
<p>Is there a way to work this out without blowing up our calculator?  We can go old school and get out our factorial log tables.</p>
<p>The log of the answer equals the log of (12! * 39! / 51!).  If you remember your log rules, this is the same as log(12!) + log (39!) &#8211; log(51!).  If you don&#8217;t have log of factorial tables you can type that equation into google and it magically gives you the answer.  So you get:</p>
<p>log(12!) + log (39!) &#8211; log(51!) = -11.200723</p>
<p>So the log of our answer = -11.200723.  Now let&#8217;s take the antilog to get our answer:</p>
<p>x = 10 ^ -11.200723<br />
x = 6.299078 * 10 ^ -12</p>
<p>This is the probability.  Take the reciprocal to get the odds to 1 against:</p>
<p>1 in 158,753,387,100</p>
<p>Holy cow &#8211; that&#8217;s what in Australia we call between Buckley&#8217;s and none.</p>
<p>The second way to do this is using some combinatorial tricks across the entire deck.</p>
<p>The first thing you have to know is:  if I have a group of things of size n, now many ways are there to select a subset of size r.  It turns out to be:  n! / (r! * (n &#8211; r)!).  So for example if I had 5 balls, I could arrange 2 balls out of the 5 in: 5! / (2! * 3!) = 15 ways.  </p>
<p>As a side note &#8211; and I cover this more at the end of this post &#8211; I&#8217;m treating this as an order doesn&#8217;t matter, repetitions not allowed arrangement.  </p>
<p>How does this help us in this problem?  Let&#8217;s think of the number of ways that I can select 13 cards from this deck.  The order in which the cards are selected doesn&#8217;t matter.   The answer, following our example above would be 52! / (13! * 39!).   Out of all of these possibilities, how many of these give us 13 cards a particular chosen suit?  The answer is only 1. The reason is that there&#8217;s only 13 cards of the chosen suit, and the arrangement I&#8217;m looking for has all of them.  And since order doesn&#8217;t matter, there&#8217;s only one arrangement that has all of these 13 particular cards.  </p>
<p>So dividing the number of arrangements with 13 cards being our chosen suit by the total number of arrangements gives us:  1 / (52! / (13! * 39!)) </p>
<p>Now we have to multiply this by 4, as we have 4 suits. </p>
<p>= 4 * 1 / (52! / (13! * 39!))<br />
= 4  13! * 39! / 52!</p>
<p>We can see that this becomes our original answer above:</p>
<p>12! * 39! / 51!</p>
<p>It&#8217;s probably a good idea at this point to formalize a little the definitions of permutations and combinations, as this is what the above has been all about.</p>
<p>Permutations are when the order of the arrangement does matter &#8211; the order is a factor in making the arrangement unique.  </p>
<p>Combinations are when we want to get the number of arrangements without regard to order.  So we can treat the arrangements as buckets we can shake up and it&#8217;s still the same arrangement.      </p>
<p>Within these, we can also allow repetitions or not.  In other words, in a given arrangement, can a particular item be used more than once?  </p>
<p>Some examples will help: </p>
<p><strong>Combinations</strong>  </p>
<p>Repetitions allowed:  Let&#8217;s say you&#8217;re ordering a sandwich at Subway and can choose 3 meats out of a possible 5.  If you love salami, you could chose salami, salami and salami for your meats.   And we don&#8217;t really care what order we get the meats in the sandwich &#8211; for example, bologna, salami, bologna is the same as salami, bologna, bologna.<br />
No Repetitions:  Let&#8217;s say Subway had only one of each of the meats left &#8211; so you couldn&#8217;t choose the same meat twice.    Another good example is a lottery where you need to match 6 numbers drawn from a pool of 40.  Once a number is drawn it doesn&#8217;t go back in to the pool.  </p>
<p><strong>Permutations</strong></p>
<p>Repetitions:  the classic example is that of a combination lock (which should really be called a permutation lock!).  Order does matter, and repetitions are allowed as your combination could be 7777.<br />
No Repetitions:  How many ways are there to get the first 3 positions in a 100 person race?  Order matters, and you can&#8217;t have the same person in more than one position.</p>
<p><strong>The formulas:</strong></p>
<p>Permutation, repetition:          n ^ r<br />
Permutation, no repetition:      n! / (n-r)!<br />
Combination, repetition:         (n + r &#8211; 1)! / (r! * (n &#8211; 1)!)<br />
Combination, no repetition:     n! / (r! * (n-r)!)</p>
<p>It&#8217;s interesting to note that in the above, the combination no repetition case is just the permutation no repetition case divided by r!.  You can see this by thinking that for arrangements with 3 elements, there will be 3! more ways to arrange them if we care about order as in the permutation case than in the combination case.  </p>
<p>The combination no repetition case is probably the most common and comes up in card-dealing problems and the like.  It is sometimes called the &#8220;n choose r&#8221; case &#8211; or nCr, and also known as the &#8220;Binomial Coefficient&#8221;.</p>
<p>The combination with repetition case seems the most difficult to intuitively understand.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=293</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Patience is a virtue?</title>
		<link>http://rebrained.com/?p=267</link>
		<comments>http://rebrained.com/?p=267#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:08:49 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[probability]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=267</guid>
		<description><![CDATA[Let&#8217;s say you&#8217;re playing a coin-tossing game. You start with $10 and are looking to double your money. The game is very simple: you pick an amount to wager on each toss, and if you toss heads you win the amount you wagered (as well as keeping the wagered amount), and if you toss tails [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you&#8217;re playing a coin-tossing game.  You start with $10 and are looking to double your money.  The game is very simple:  you pick an amount to wager on each toss, and if you toss heads you win the amount you wagered (as well as keeping the wagered amount), and if you toss tails you lose the amount you wagered.  If you get to $0 you go bust and can&#8217;t play anymore.  Moreover, when you get to your $20 target, you stop playing and take your winnings.</p>
<p>You take a bold approach and decide to wager your entire $10 on the first toss.   You have a 50/50 chance of doubling your money, and whether you do or go bust will be determined on the first toss.     </p>
<p>Would it have been better to take a more patient approach and only bet $1 on each toss?</p>
<p><a style="display:none;" id="ddetlink1400190278" href="javascript:expand(document.getElementById('ddet1400190278'))">Answer</a>
<div class="ddet_div" id="ddet1400190278"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1400190278'));expand(document.getElementById('ddetlink1400190278'))</script></p>
<p>You can probably answer this quickly just by thinking about the symmetry of the problem.  In the patient approach, you have an equal chance of gaining or of losing $1 at each turn.  You are the same number of steps from going bust as you are from doubling your money.  So, just as with the bold gambler, your chances of doubling your money will be 50/50.</p>
<p></div></p>
<p>Now let&#8217;s say you start with $10 and want to get to $20, but this time the coin is weighted in your favor and you have a 2/3 chance of rolling heads.  Similarly, let&#8217;s say you&#8217;re betting on even/odd in roulette where you have an 18/38 chance &#8211; slightly less than half &#8211; of winning on each roll.   In these cases, is it better to be a bold gambler or a patient gambler?</p>
<p><a style="display:none;" id="ddetlink2051560904" href="javascript:expand(document.getElementById('ddet2051560904'))">Answer</a>
<div class="ddet_div" id="ddet2051560904"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet2051560904'));expand(document.getElementById('ddetlink2051560904'))</script>
Before answering this problem it&#8217;s useful to read and understand the previous post <a href="http://rebrained.com/?p=237">http://rebrained.com/?p=237</a>.</p>
<p>Let&#8217;s call P the probability that we win this game (by reaching $20 before we go bust) and 1-P the probability that we&#8217;ll lose this game (by going bust before ever reaching $20).  We&#8217;ll also call x our starting amount ($10 in this case) and y our target amount ($20 in this case).</p>
<p>Here&#8217;s the key insight:  if this game kept going even after you&#8217;d reached the the target, there would be two ways to eventually go bust &#8211; never reaching the target, or reaching the target and then going bust.   </p>
<p>Remember from the prior post that from any starting position x, the chances of eventually going bust if we don&#8217;t stop at a target amount are ((1-p)/p)^x.  </p>
<p>In other words the probability of eventually going bust from our starting position if we didn&#8217;t stop after reaching our target (which we get from the above formula) is equal to the probability of eventually going bust without ever reaching our target (which is effectively 1-P, the probability of losing the game), plus the probability of reaching the target (which is P, the probability that we win the game), and then keeping going from the target and eventually going bust from there (which using the above formula we know is ((1-p)/p)^y. </p>
<p>So we can write:<br />
((1-p)/p)^x = (1-P) + P * ((1-p)/p)^y</p>
<p>With some algebra you get the following:<br />
P = (1 &#8211; ((1-p)/p)^x)) / (1 &#8211; ((1-p)/p)^y))</p>
<p>Something strange happens here when we plug in p=1/2 into the above formula &#8211; we get an indeterminate 0/0. To understand what is going on and how to solve this, read <a href="http://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule">L&#8217;Hopital&#8217;s rule in wikipedia</a>.  Using this rule you&#8217;ll find that the answer for the p=1/2 case is that P = x/y, or 1/2.  </p>
<p>So in the case of the fair coin, as per our argument from symmetry, it makes no difference whether you&#8217;re a bold or patient gambler.  But what if the coin is weighted?  </p>
<p>If p=2/3,  the bold gambler has a has a 2/3 change of winning.   Using the above formula, the patient gambler&#8217;s chances of winning are almost certain &#8211; something like 99.9%. </p>
<p>In the case of p=1/3, the bold gambler has a 1/3 chance of winning the game.   The patient gambler&#8217;s chances of winning are vanishingly small &#8211; something like 0.1%.</p>
<p>What about the roulette case?  From the above, we can probably suspect that where p is less than 1/2, the patient gambler&#8217;s chances of winning plummet much more quickly than the bold gambler&#8217;s chances.</p>
<p>In fact, while the bold gambler&#8217;s chances of winning are 18/38 &#8211; or something like 47% &#8211; the patient gambler&#8217;s chances of winning are only about 26%.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=267</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Will the gambler go bust?</title>
		<link>http://rebrained.com/?p=237</link>
		<comments>http://rebrained.com/?p=237#comments</comments>
		<pubDate>Fri, 23 Apr 2010 19:09:02 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[mathematics]]></category>
		<category><![CDATA[puzzles]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[random walk]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=237</guid>
		<description><![CDATA[Let&#8217;s say that you&#8217;re playing a coin-tossing game, and you start with $1. You keep tossing forever, winning $1 if you toss heads, and losing $1 if you toss tails. What are the chances you&#8217;ll eventually go bust (get to $0)? What are the chances you&#8217;ll eventually go bust if the coin was weighted and [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say that you&#8217;re playing a coin-tossing game, and you start with $1.  You keep tossing forever, winning $1 if you toss heads, and losing $1 if you toss tails. What are the chances you&#8217;ll eventually go bust (get to $0)?    What are the chances you&#8217;ll eventually go bust if the coin was weighted and tails only came up 1/3 of the time?</p>
<p><a style="display:none;" id="ddetlink1291542653" href="javascript:expand(document.getElementById('ddet1291542653'))">Answer</a>
<div class="ddet_div" id="ddet1291542653"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1291542653'));expand(document.getElementById('ddetlink1291542653'))</script> </p>
<p>Let&#8217;s call p the chances of winning a dollar on any given toss, and (1-p) the chances of losing a dollar.  Also, lets call P the chances of eventually going bust from our starting $1 position.   </p>
<p>Imagine you managed not to go bust on the first toss, and are about to take the second toss.   At this point, there are two possibilities &#8211; that at some point in the future you&#8217;ll move back to having $1, or that you&#8217;ll never move back to $1.  </p>
<p>Here&#8217;s where a simple but clever insight can lead to this problem magically solving itself: when you&#8217;re at the $2 position, the probability of eventually moving back to $1 is the same as the probability you had of eventually moving to $0 (and going bust) when you started the game.  You can see that it&#8217;s the same situation, it&#8217;s effectively just been transposed.    </p>
<p>So the probability of eventually going bust at the beginning of the game (which we&#8217;ve defined as P) is equal to the probability on the first throw of tossing a tail (1-p), or tossing a head (p) and then going bust from the $2 state.  The probability of going bust from the $2 state is the probability of eventually going back to the $1 state (which we worked out is P) and then eventually going bust from the $1 state (also P).  </p>
<p>We can write the above like this:</p>
<p>P = (1-p) + p * P^2</p>
<p>We can solve this algebraically to have two solutions for P:  1 and (1-p)/p.</p>
<p>There&#8217;s some interesting conclusions from this:<br />
- Without even the formulas we can see that if p = 1, we&#8217;ll keep winning $1 each time and the chances of ever going bust (P) will be 0.   By the same token, if p = 0, then we&#8217;ll directly go bust so P will be 1.<br />
- For p = 1/2, the formula will give 1.  This means that for a fair coin, you&#8217;re guaranteed to go bust if you play long enough.<br />
- For p < 1/2, the formula gives a result greater than 1, which is invalid.  But clearly you'll be guaranteed to go bust in this case as well.<br />
- For p > 1/2, the formula will give a probability ranging from 1 to 0.   When p = 2/3 (as in our question above) then we have a 50/50 chance of eventually going bust.<br />
</div></p>
<p>What if you started with $2 &#8211; what are the chances you&#8217;ll eventually go bust?</p>
<p><a style="display:none;" id="ddetlink105749648" href="javascript:expand(document.getElementById('ddet105749648'))">Answer</a>
<div class="ddet_div" id="ddet105749648"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet105749648'));expand(document.getElementById('ddetlink105749648'))</script> </p>
<p>What we worked out in the previous section is that the probability of eventually getting to $1 less than what you started with is 1 if p is smaller than or equal to 1/2, or (1-p)/p if p > 1/2.   </p>
<p>So if you start with $x, and p is greater than 1/2, then your chances of going bust will be ((1-p)/p)^x.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=237</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; A safe place to drop an egg</title>
		<link>http://rebrained.com/?p=215</link>
		<comments>http://rebrained.com/?p=215#comments</comments>
		<pubDate>Sun, 11 Apr 2010 20:31:09 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=215</guid>
		<description><![CDATA[Let&#8217;s say you need to find out the highest floor in a 100 story building from which you could safely drop an egg without it breaking. What&#8217;s your strategy to minimize the maximum (worst case) number of drops you have to try? If you just had one egg with which to conduct your experiment, you&#8217;d [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you need to find out the highest floor in a 100 story building from which you could safely drop an egg without it breaking.  What&#8217;s your strategy to minimize the maximum (worst case) number of drops you have to try?   </p>
<p>If you just had one egg with which to conduct your experiment, you&#8217;d have to start at floor one, and go up floor by floor looking for the first floor at which your egg broke until you reached floor 100.  So your maxim number of drops would be 100.  </p>
<p>What would be the worst case number of drops if you could use two eggs?</p>
<p><a style="display:none;" id="ddetlink557076223" href="javascript:expand(document.getElementById('ddet557076223'))">Answer</a>
<div class="ddet_div" id="ddet557076223"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet557076223'));expand(document.getElementById('ddetlink557076223'))</script></p>
<p>With two eggs you can be cleverer, and drop the first egg at floor 50, and effectively divide the floor space in half for your second egg.</p>
<p>You could also drop the first egg at floor 10, then assuming it doesn&#8217;t break, floor 20, 30, and so on.  As soon as it broke, you&#8217;d try the 9 floors underneath with your second egg.  So worst case if you get all the way to floor 100 before it breaks, then start at floor 91 with the second egg and get all the way to floor 99, then the total worst case drops is 19.</p>
<p>Can we do better?</p>
<p>Picking 10 as number of floors to skip with the first egg is not particularly efficient in dividing the floor space because if the first egg breaks on floor 10, the worst case is 10.  But if the first egg breaks on floor 20, then the worst case is 11.  As we saw, by the time you get to floor 100 your worst case is 19.  The most efficient solution will be when no matter where the first egg breaks, our worst case stays the same.  </p>
<p>To do that we could say that we&#8217;ll start with our first egg at floor 10, but the second drop will be on floor 19, preserving our 10 drop worst case.  The problem you&#8217;ll find is that you end up reducing the spacing to 1 before you get anywhere close to floor 100.    By trial and error you can find the best number to start with, and it turns out to be 14:</p>
<p>14, 27, 39, 50, 60, 69, 77, 84, 90, 95, 99, 100.</p>
<p>Is there a formula we can use to work this out, so we could do it for any number of floors?</p>
<p>Let&#8217;s look at the number of floors we skip at each turn:</p>
<p>n, n-1, n-2, n-3 &#8230; 1</p>
<p>Flipping that around, we have:</p>
<p>1, 2, 3, 4&#8230;.. n.</p>
<p>We also know that the sum of the number of floors skipped will equal the total number of floors.  </p>
<p>We know that the sum of a sequence like the above is (n+1) * n/2.  You can see this if you pair the first and last numbers, the the second and second to last, etc. </p>
<p>So if we say h is the total number of floors in the building, we have:</p>
<p>h = (n+1) * n/2</p>
<p>So:</p>
<p>n^2 + n = 2h.</p>
<p>To solve for n, let&#8217;s use the completing the square trick:</p>
<p>n^2 + n + .25 = 2h + .25<br />
(n+.5)(n+.5) = 2h + .25<br />
n+.5 = sqrt (2h+.25)<br />
n = sqrt(2h+.25) &#8211; .5</p>
<p>If we try this on our 100 floor problem, we get:</p>
<p>n = sqrt(200.25)-.5<br />
n=13.65</p>
<p>So seeing as we need integer floors, we need 14 floors, which corresponds with our trial and error result.</p>
<p>I have to give props to Scruffy Pete for helping out on this one.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=215</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Alternating coin toss &#8211; redux</title>
		<link>http://rebrained.com/?p=181</link>
		<comments>http://rebrained.com/?p=181#comments</comments>
		<pubDate>Sat, 10 Apr 2010 20:01:38 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[probability]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=181</guid>
		<description><![CDATA[I want to revisit a probability puzzle from a previous post: see problem #5 in http://rebrained.com/?p=20 You play a game where you alternate tossing a coin with a friend, and the first person to toss heads wins. But let&#8217;s make it a little more interesting by making the coin weighted, or biased, so that it [...]]]></description>
			<content:encoded><![CDATA[<p>I want to revisit a probability puzzle from a previous post:  see problem #5 in <a href="http://rebrained.com/?p=20">http://rebrained.com/?p=20</a></p>
<p>You play a game where you alternate tossing a coin with a friend, and the first person to toss heads wins.  But let&#8217;s make it a little more interesting by making the coin weighted, or biased, so that it lands heads only 25% of the time.   If you were to start, what would be your chances of winning?</p>
<p><a style="display:none;" id="ddetlink737797500" href="javascript:expand(document.getElementById('ddet737797500'))">Answer</a>
<div class="ddet_div" id="ddet737797500"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet737797500'));expand(document.getElementById('ddetlink737797500'))</script>
Let&#8217;s call the probability of tossing heads <img src="http://rebrained.com/wp-content/plugins/cache/tex_83878c91171338902e0fe0fb97a8c47a.gif" class="tex" alt="p" /> and the probability of tossing tails <img src="http://rebrained.com/wp-content/plugins/cache/tex_7694f4a66316e53c8cdd9d9954bd611d.gif" class="tex" alt="q" />.</p>
<p>On the starter&#8217;s first toss, his chances of tossing heads are <img src="http://rebrained.com/wp-content/plugins/cache/tex_83878c91171338902e0fe0fb97a8c47a.gif" class="tex" alt="p" />.  The chances he&#8217;ll toss heads on his second toss are <img src="http://rebrained.com/wp-content/plugins/cache/tex_4813901cac17728d0b42c1ffca67e45f.gif" class="tex" alt="q^2\times p" />.  On his 4th toss it&#8217;s <img src="http://rebrained.com/wp-content/plugins/cache/tex_4a229f667c5368ba647114232e002e43.gif" class="tex" alt="q^4\times p" /> and so on.</p>
<p>So his chances of winning the game is the sum of the geometric progression <img src="http://rebrained.com/wp-content/plugins/cache/tex_39b25b9e35562ec2bac6923d64b347f5.gif" class="tex" alt="p\times q^0\;+\;p\times q^2\;+\;p\times q^4\;+" />&#8230;</p>
<p>Let&#8217;s use the shifting approach to solve this.  The idea is to subtract out the first element, and then shift the rest of the elements to the left.   So first subtract:<br />
<img src="http://rebrained.com/wp-content/plugins/cache/tex_6024b77d59b3dfbacbf90b0fe5a9c5e4.gif" class="tex" alt="s-p\times q^0=p\times q^2\;+\;p\times q^4\;+" />&#8230;</p>
<p>Now to shift the terms to the left, we need to divide by <img src="http://rebrained.com/wp-content/plugins/cache/tex_16db377156b6a727777f391bcbe853c0.gif" class="tex" alt="q^2" /><br />
<img src="http://rebrained.com/wp-content/plugins/cache/tex_59306f076f0a65624ad7381654c7421b.gif" class="tex" alt="\frac{s-p\times q^0}{q^2}=p\times q^0\;+\;p\times q^2\;+" />&#8230;</p>
<p>So&#8230;<br />
<img src="http://rebrained.com/wp-content/plugins/cache/tex_1b23669a9340663f44c0a651d7be80f6.gif" class="tex" alt="\frac{s-p\times q^0}{q^2}=s" /><br />
<img src="http://rebrained.com/wp-content/plugins/cache/tex_bc9a4027b5c1be5142060464fa74e1ab.gif" class="tex" alt="s=\frac{p}{1-q^2}" /></p>
<p>This gives us a general solution to the alternating coin toss problem.  If we plug in the unweighted coin probabilities, we get <img src="http://rebrained.com/wp-content/plugins/cache/tex_30ed82d378f3ae9204a8e039f2bed783.gif" class="tex" alt="s=\frac{2}{3}" /> which is what we&#8217;d worked out before.  For the case where the probability of tossing a head is 1/4, then we get <img src="http://rebrained.com/wp-content/plugins/cache/tex_a601f427171ad564b7817c57f21e8c9d.gif" class="tex" alt="s=\frac{4}{7}" />, which is the probability of winning for the starter.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=181</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Take your seats</title>
		<link>http://rebrained.com/?p=167</link>
		<comments>http://rebrained.com/?p=167#comments</comments>
		<pubDate>Wed, 07 Apr 2010 05:22:56 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=167</guid>
		<description><![CDATA[Let&#8217;s say there are 100 people, including you, waiting to board a fully booked flight, each with an assigned seat. The first person to board doesn&#8217;t pay any attention to his assigned seat, and sits somewhere at random. Each of the subsequent people will sit in their assigned seat if they can, but if they [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say there are 100 people, including you, waiting to board a fully booked flight, each with an assigned seat.   The first person to board doesn&#8217;t pay any attention to his assigned seat, and sits somewhere at random.  Each of the subsequent people will sit in their assigned seat if they can, but if they find someone sitting there will pick another seat at random.  You&#8217;re the last to board.  What&#8217;s the probability you&#8217;ll get to sit in your assigned seat? </p>
<p><a style="display:none;" id="ddetlink324947385" href="javascript:expand(document.getElementById('ddet324947385'))">Answer</a>
<div class="ddet_div" id="ddet324947385"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet324947385'));expand(document.getElementById('ddetlink324947385'))</script>
I like problems where I ponder for a while, am contemplating some tedious route to solve it, but then in the nick of time with a flash of insight see the answer.  That was the case for me with this problem.  </p>
<p>After starting toying with conditional probability, I realized that there are only two seats that really matter as each passenger boards:  passenger #1&#8242;s seat (let&#8217;s call that seat #1), and my seat (let&#8217;s call that seat #100).  As soon as someone sits in seat #1, it&#8217;s all over &#8211; I&#8217;ll definitely get to sit in my seat. Also, as soon as someone sits on seat #100, I&#8217;m done &#8211; there&#8217;s no way for me to sit in my seat.  If any passenger chooses seat #1 or seat #100, we can essentially ignore all subsequent events.</p>
<p>Here&#8217;s the key:  until either seat #1 or seat #100 is taken, each passenger that boards has the same probability of choosing seat #1 as they do seat #100.  </p>
<p>That&#8217;s clearly the case for the first guy &#8211; he has a 1/100 chance of choosing seat #1, and a 1/100 chance of choosing seat #100.  Now let&#8217;s take passenger #2.  Regardless of what #1 has done, there&#8217;s be an equal probability he&#8217;ll choose seat #1 or seat #100.  That probability is either going to be zero if he&#8217;s able to sit in his own seat, or if he can&#8217;t because passenger #1 has taken it, he&#8217;s equally likely to choose seat #1 or seat #100 (a 1/99 chance in either case).  Let&#8217;s say we get to passenger #99.  The only way the issue won&#8217;t have been already decided is if the choices he has left are seat #1 and seat #100.  In that case, there&#8217;s still an equal probability (50/50 this time) he&#8217;ll choose seat #1 or choose seat #100.  </p>
<p>So you can see from the above that the chance you get to sit on your own seat is 50/50, because as each passenger boarded there was an equal chance of the question being answered in either of the two possibilities.  </p>
<p>Anybody have a different way to get the answer &#8211; or can get the answer by looking at the sum of conditional probabilities?<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=167</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Leaning Tower of Pisa</title>
		<link>http://rebrained.com/?p=146</link>
		<comments>http://rebrained.com/?p=146#comments</comments>
		<pubDate>Sat, 03 Apr 2010 02:55:48 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[mathematics]]></category>
		<category><![CDATA[puzzles]]></category>
		<category><![CDATA[geometric progressions]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=146</guid>
		<description><![CDATA[Let&#8217;s say you drop a ball from the Leaning Tower of Pisa, which is 179 ft high, and it bounces back 10% of the dropped height &#8211; 17.9 ft. Then on the second bounce it bounces up 10% again &#8211; 1.79 ft, and so on for ever. How far will the ball travel? Answer expand(document.getElementById('ddet388099844'));expand(document.getElementById('ddetlink388099844')) [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you drop a ball from the Leaning Tower of Pisa, which is 179 ft high, and it bounces back 10% of the dropped height &#8211; 17.9 ft.  Then on the second bounce it bounces up 10% again &#8211; 1.79 ft, and so on for ever.  How far will the ball travel?</p>
<p><a style="display:none;" id="ddetlink305665311" href="javascript:expand(document.getElementById('ddet305665311'))">Answer</a>
<div class="ddet_div" id="ddet305665311"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet305665311'));expand(document.getElementById('ddetlink305665311'))</script>
The first thing to realize is that this is a geometric progression which will yield a finite sum, even though it has an infinite number of terms.  This idea of finite sums is the reason Zeno can walk across the room:  <a href="http://en.wikipedia.org/wiki/Geometric_series#Zeno.27s_paradoxes">http://en.wikipedia.org/wiki/Geometric_series#Zeno.27s_paradoxes</a>.</p>
<p>Before answering the question it may be useful to recap geometric progressions from my previous post <a href="http://rebrained.com/?p=20">see the coin-toss puzzle answer</a>.  </p>
<p>In this problem, the total distance travelled by the ball will be: 179 + 179 * 2 * (1/10 + 1/100 + 1/1000&#8230;)</p>
<p>You may be able to see straight away that the sum of the progression is 1/9, and so the total distance 218 + 7/9. </p>
<p>But let&#8217;s do it using the standard approach:</p>
<p>Given that n in the progression will start at 1, we need to get our progression into the form: </p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_b9c8df9481c6a39c62b772c5e1d030e7.gif" class="tex" alt="<br />
\sum_{n=1}^\infty cr^{n-1} = \frac{c}{1-r}<br />
" /></p>
<p>When we do this, we get the same answer as above:  </p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_94aabb01a357c4ca0f92b8e666868035.gif" class="tex" alt="<br />
distance =\;179\;+\;179\;*\;2\;*\;1/10\;*\;\frac{1}{1-\frac{1}{10}}\;=\;218\;\frac{7}{9}<br />
" /><br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=146</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Break a stick to get a triangle</title>
		<link>http://rebrained.com/?p=127</link>
		<comments>http://rebrained.com/?p=127#comments</comments>
		<pubDate>Sat, 03 Apr 2010 01:26:19 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=127</guid>
		<description><![CDATA[I read somewhere this is a Google interview question:  Let&#8217;s say you drop a stick, breaking it randomly in 2 places, leaving you with 3 smaller sticks.   What&#8217;s the probability you can make a triangle out of the 3 sticks? Answer expand(document.getElementById('ddet1488099420'));expand(document.getElementById('ddetlink1488099420')) There are a number of ways to tackle this, including this very elegant [...]]]></description>
			<content:encoded><![CDATA[<p>I read somewhere this is a Google interview question:  Let&#8217;s say you drop a stick, breaking it randomly in 2 places, leaving you with 3 smaller sticks.   What&#8217;s the probability you can make a triangle out of the 3 sticks?</p>
<p><a style="display:none;" id="ddetlink1512642304" href="javascript:expand(document.getElementById('ddet1512642304'))">Answer</a>
<div class="ddet_div" id="ddet1512642304"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1512642304'));expand(document.getElementById('ddetlink1512642304'))</script></p>
<p>There are a number of ways to tackle this, including this very elegant solution: <a href="http://www.cut-the-knot.org/Curriculum/Probability/TriProbability.shtml">http://www.cut-the-knot.org/Curriculum/Probability/TriProbability.shtml</a>. For the less elegantly inclined (and those as unlikely as me to be working at Google any time soon), here&#8217;s another way:</p>
<p>The first insight is that what you want to avoid is ending up with one really long stick and two short sticks &#8211; you need the shorter sticks to have a combined length greater than the longer stick.  This effectively means that if you think about the stick as having two halves, then the two breaks need to be on opposite halves. The probability of the breaks being on opposite sides of the original stick is 50%.</p>
<p>The second insight is that when the breaks are on opposite halves, if you start from the outer ends of the original stick and measure the distance to each break, the sum of those two distances needs to be greater than 1/2 the length of the original stick.  Otherwise we&#8217;d end up with two short sticks having a combined length less than the remaining stick.  What&#8217;s the probability of this?  The probability that two random numbers from 0 to .5 add up to more than .5 is 50%</p>
<p>So that&#8217;s a slightly long-winded way of arriving at the answer &#8211; which is that you have a 50% * 50%, or 1 in 4 chance, that you&#8217;ll be able to make a triangle.<br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=127</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; 4 Bugs chasing each other</title>
		<link>http://rebrained.com/?p=65</link>
		<comments>http://rebrained.com/?p=65#comments</comments>
		<pubDate>Sun, 21 Feb 2010 23:37:11 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[a-ha moment]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=65</guid>
		<description><![CDATA[Say there are four bugs standing at the corners of an imaginary 1m * 1m square.  Each of the bugs is facing the bug that is on the adjacent, clockwise corner from where they are. At the same instant, each of the four bugs starts walking directly towards the bug they are facing at 1m [...]]]></description>
			<content:encoded><![CDATA[<p>Say there are four bugs standing at the corners of an imaginary 1m * 1m square.  Each of the bugs is facing the bug that is on the adjacent, clockwise corner from where they are.</p>
<p>At the same instant, each of the four bugs starts walking directly towards the bug they are facing at 1m per hour, and keeps walking directly towards that bug as that bug itself starts moving.  So the four bugs spiral towards the center of the square in a clockwise direction.</p>
<p>How long does it take for the four bugs to meet?</p>
<p><a style="display:none;" id="ddetlink1897610994" href="javascript:expand(document.getElementById('ddet1897610994'))">Answer</a>
<div class="ddet_div" id="ddet1897610994"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1897610994'));expand(document.getElementById('ddetlink1897610994'))</script><em> </em></p>
<p>It&#8217;s clear that the bugs will meet at the center of the square.  The insight needed is that the bugs effectively stay in a square formation &#8211; a shrinking and spiraling square, but a square that is always centered on the original center. So regardless of where the bugs are in their spiral towards the center, they will always be moving 45 degrees to a line connecting where they are to the center.</p>
<p>Once you get your head around this, you can solve the problem by calculating the effective velocity towards the center:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_92a0ba74dcdc526968a46ed8d80c4212.gif" class="tex" alt="</p>
<p>V_{center} = \cos\;45^\circ\;*\; V_{absolute}\\</p>
<p>V_{center} = \frac{1}{\sqrt(2)}\;m/hr</p>
<p>" /></p>
<p>The total distance towards the center from the starting position is: <img src="http://rebrained.com/wp-content/plugins/cache/tex_fbba03c88d1eab051b01670fec83e3bc.gif" class="tex" alt="\frac{1}{\sqrt(2)}\;m" /></p>
<p>So it will take 1hr for the bugs to meet in the center.</p>
<p>Perhaps an easier way to think about this is that if you draw the square so it looks like a diamond and focus on the bug in the top corner, you&#8217;ll see pretty clearly that the line starting at the top corner and going 45 degrees from a vertical line down to the center, and ending so it&#8217;s horizontally level with the center is effectively a side of the diamond, which is one meter, and would take 1hr to walk.</p>
<p></div></p>
<p>There&#8217;s a way to arrive at the answer to this problem instantly and with no calculations &#8211; but does require somewhat of an a-ha moment.</p>
<p><a style="display:none;" id="ddetlink1176833570" href="javascript:expand(document.getElementById('ddet1176833570'))">A-ha Moment Answer</a>
<div class="ddet_div" id="ddet1176833570"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1176833570'));expand(document.getElementById('ddetlink1176833570'))</script></p>
<p>A bug&#8217;s movement towards the bug it&#8217;s following is always perpendicular to the motion of the followed bug.  So in effect the movement of the followed bug has no effect on how far the follower has to travel to reach it or how long it will take, so the follower has to travel 1 meter, and will catch up to the followed bug in 1 hr.  A-ha!</p>
<p></div></p>
<p><a style="display:none;" id="ddetlink1112535604" href="javascript:expand(document.getElementById('ddet1112535604'))">What if the 3 bugs were in an equilateral triangles with sides 1m?</a>
<div class="ddet_div" id="ddet1112535604"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1112535604'));expand(document.getElementById('ddetlink1112535604'))</script></p>
<p>Same principle as the above:  they stay in formation as they spiral to the center.   One bug is heading towards the other at 1 meter per hour.  In this case, the followed bug is making effective progress towards the follower at  cos(60), or .5 meters per hour.   So they have a combined speed of 1.5 meters per hour towards each other, so they should cover the 1 meter between them in 40 minutes.</p>
<p></div></p>
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=65</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Liars and Truthtellers</title>
		<link>http://rebrained.com/?p=37</link>
		<comments>http://rebrained.com/?p=37#comments</comments>
		<pubDate>Thu, 31 Dec 2009 05:27:58 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[probability]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=37</guid>
		<description><![CDATA[This is another probability question that seems straightforward but can be deceptive&#8230; You&#8217;re an FBI agent and have been monitoring a large gang, and you know that 1/4 of its members always tell the truth, the rest always lie.  Then you get taken hostage by the gang, and two gang members are assigned to guard [...]]]></description>
			<content:encoded><![CDATA[<p>This is another probability question that seems straightforward but can be deceptive&#8230;</p>
<p>You&#8217;re an FBI agent and have been monitoring a large gang, and you know that 1/4 of its members always tell the truth, the rest always lie.  Then you get taken hostage by the gang, and two gang members are assigned to guard you.  You ask the first: &#8221;Am I going to live?&#8221;  He answers &#8220;Yes.&#8221;  Then you ask the second the same question.  He also answers &#8220;Yes.&#8221;  What are your odds of living?</p>
<p><a style="display:none;" id="ddetlink613919491" href="javascript:expand(document.getElementById('ddet613919491'))">Answer</a>
<div class="ddet_div" id="ddet613919491"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet613919491'));expand(document.getElementById('ddetlink613919491'))</script><em><br />
It can be tempting to say it&#8217;s the probability the first is telling the truth multipled by the probability the second is telling the truth, which would mean you have a 1/16th chance of living.</em></p>
<p>It&#8217;s not correct, however, because there&#8217;s another piece of information you have which is that they both gave the same answer.</p>
<p>Let&#8217;s look at the probability tree:</p>
<p>Guard 1       Guard 2      probability</p>
<p>T                  T               1/16</p>
<p>F                   F               9/16</p>
<p>T                   F               3/16</p>
<p>F                   T               3/16</p>
<p>The only two rows that apply to this problem are the first two &#8211; they can either both be telling the truth, or both be lying.  The chances they&#8217;re both telling the truth is:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_fef2cce74957d5290f59bdbfcf04ac39.gif" class="tex" alt="\frac{\frac{1}{16}}{\frac{1}{16}+\frac{9}{16}}=\frac{1}{10}" /></p>
<p></div></p>
<p>So &#8211; what would your chances of living be if the first guard told you that you would live, but the second that you would die?</p>
<p><a style="display:none;" id="ddetlink1337383383" href="javascript:expand(document.getElementById('ddet1337383383'))">Answer</a>
<div class="ddet_div" id="ddet1337383383"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1337383383'));expand(document.getElementById('ddetlink1337383383'))</script></p>
<p>Look at the table in the answer above &#8211; at the rows where the answers were different&#8230; you&#8217;ll see that your chances are 50/50.</p>
<p></div></p>
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=37</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; shortest road system</title>
		<link>http://rebrained.com/?p=35</link>
		<comments>http://rebrained.com/?p=35#comments</comments>
		<pubDate>Fri, 20 Jun 2008 03:20:11 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=35</guid>
		<description><![CDATA[Let&#8217;s say you&#8217;re contracted to build roads to connect four towns that are at the corners of an imaginary square with sides 1 mile. What&#8217;s the shortest length of road system you can build so that every town can get to every other town? Answer expand(document.getElementById('ddet861419538'));expand(document.getElementById('ddetlink861419538')) The first answers that come to mind for most [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you&#8217;re contracted to build roads to connect four towns that are at the corners of an imaginary square with sides 1 mile.   What&#8217;s the shortest length of road system you can build so that every town can get to every other town?</p>
<p><a style="display:none;" id="ddetlink1726857540" href="javascript:expand(document.getElementById('ddet1726857540'))">Answer</a>
<div class="ddet_div" id="ddet1726857540"><script language="JavaScript" type="text/javascript">expand(document.getElementById('ddet1726857540'));expand(document.getElementById('ddetlink1726857540'))</script><em><br />
The first answers that come to mind for most folks are either to do a perimeter road with one one side left off which is 3 miles or to build roads in the shape of an X &#8211; which pythagoras tells is would be 2 * sqrt(2) = 2.828 miles.</p>
<p>Can you do better?  Click on this <a href="http://www.jstor.org/pss/3619370">link</a> to see the answer.</p>
<p>You can work out the length using some basic calculus:</p>
<p>Call <img src="http://rebrained.com/wp-content/plugins/cache/tex_9dd4e461268c8034f5c8564e155c67a6.gif" class="tex" alt="x" /> the length of shared highway in the middle.  So the total length of the road will be:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_1861f57aaa3af9607f47ace28ae8caaf.gif" class="tex" alt="l\;=\;4\sqrt{(\frac{1}{2})^2 + (\frac{(1-x)}{2})^2}\;+\;x" /></p>
<p>Simplifying:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_505bbd815e7d4644fa4563e5ab7e781f.gif" class="tex" alt="l\;=\;\sqrt{4 + 4(1-x)^2}\;+\;x" /></p>
<p>We&#8217;re trying to find <img src="http://rebrained.com/wp-content/plugins/cache/tex_9dd4e461268c8034f5c8564e155c67a6.gif" class="tex" alt="x" />where <img src="http://rebrained.com/wp-content/plugins/cache/tex_2db95e8e1a9267b7a1188556b2013b33.gif" class="tex" alt="l" /> is the shortest.  So we can differentiate  <img src="http://rebrained.com/wp-content/plugins/cache/tex_2db95e8e1a9267b7a1188556b2013b33.gif" class="tex" alt="l" /> with respect to  <img src="http://rebrained.com/wp-content/plugins/cache/tex_9dd4e461268c8034f5c8564e155c67a6.gif" class="tex" alt="x" />, and set this equal to zero.  Recall the chaining rule from high school?</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_d68182800759e2ac76b5d8dd2fe237af.gif" class="tex" alt="\frac{dl}{dx}\;=\;\frac{1}{2}\;*\;(4 + 4(1-x)^2)^{-\frac{1}{2}}\;*\;8(1-x)\;*\;-1\;+\;1\;=\;0" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_d4e751785dddb74c6dfe32a327ff1c09.gif" class="tex" alt="\frac{1}{\sqrt{4 + 4(1-x)^2}}\;=\;\frac{1}{4(1-x)}" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_bada60401f3a6ed94d4e185976a682f4.gif" class="tex" alt="4 + 4(1-x)^2\;=\;\frac{1}{16(1-x)^2}" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_44bad8211ddde1a4a6cb1842fcbc2eb0.gif" class="tex" alt="12(1-x)^2\;=\;4" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_9659b43caf20c2a3bc51f926eceaa282.gif" class="tex" alt="1-x\;=\;\sqrt{\frac{1}{3}}" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_7cbd151c44e65c407525b2675ad48d65.gif" class="tex" alt="x\;=\;1-\sqrt{\frac{1}{3}}" /></p>
<p>And now we can substitute to find the total length of the road:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_32950d5099fd1aa87487bd9d50fae74c.gif" class="tex" alt="l\;=\;4 * \sqrt{\frac{1}{4} + \frac{1}{12}}\;+\;1\;-\;\sqrt{\frac{1}{3}}" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_099b338557ddced8552c55fd53478e2f.gif" class="tex" alt="l\;=\;4 * \sqrt{\frac{1}{3}}\;+\;1\;-\;\sqrt{\frac{1}{3}}" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_dde45f74ab4715ed6ed743a4743da1de.gif" class="tex" alt="l\;=\;3 * \sqrt{\frac{1}{3}}\;+\;1" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_5f7044581ef3661c067c4fda270f14c5.gif" class="tex" alt="l\;=\;sqrt{3}\;+\;1" /></p>
<p>This works out to be 2.732 miles, a little better than our original X approach.</p>
<p>It&#8217;s neat that the angles turn out to be 120 degrees (as is shown in the link above).  A colleague declared to me that this was &#8216;obvious&#8217;, but it&#8217;s not so obvious to me.  Can anyone find a trigonometric way to solve this problem that doesn&#8217;t involve the calculus?  Or at least provide an explanation for why the 120 degrees makes sense (other than that it&#8217;s a beautiful symmetry)? </p>
<p>Now, only because I&#8217;m a maniac and weirdly enjoying doing high school Calculus for the first time in a while, I&#8217;m going to pick <img src="http://rebrained.com/wp-content/plugins/cache/tex_9dd4e461268c8034f5c8564e155c67a6.gif" class="tex" alt="x" /> to be the distance from the shared highway to the edge of the square.  So the shared highway length will be <img src="http://rebrained.com/wp-content/plugins/cache/tex_38de459ae28630cfd8b83b81b3264071.gif" class="tex" alt="1-2x" />.</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_8c38b0132cef60de630168b89b68c7b6.gif" class="tex" alt="l\;=\;4\sqrt{\frac{1}{4} + x^2}\;+\;1\;-\;2x" /></p>
<p>Simplifying:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_7437e1d9cc88945fcbaace623052cd7b.gif" class="tex" alt="l\;=\;\sqrt{4 + 16x^2}\;+\;1\;-\;2x" /></p>
<p>Now we differentiate:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_09a5f684e4a9a7fb3b70222446f41627.gif" class="tex" alt="\frac{dl}{dx}\;=\;\frac{1}{2}\;*\;(4 + 16x^2)^{-\frac{1}{2}}\;*\;32x\;=\;2" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_9aad7c3c21fb94617bcc4613668052d4.gif" class="tex" alt="\sqrt{4 + 16x^2}\;=\;\frac{1}{8x}" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_4bd7c9dbf88dce92de0d76e1428a64bb.gif" class="tex" alt="4+16x^2\;=\;64x^2" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_b65dfbc8bbaea5bcf159a1e1afc1e619.gif" class="tex" alt="4\;=\;48x^2" /></p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_a9c86149b4c25898c5a299edb06cfe83.gif" class="tex" alt="x\;=\;sqrt{\frac{1}{12}}" /></p>
<p>Now we can substitute for the length:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_32950d5099fd1aa87487bd9d50fae74c.gif" class="tex" alt="l\;=\;4 * \sqrt{\frac{1}{4} + \frac{1}{12}}\;+\;1\;-\;\sqrt{\frac{1}{3}}" /></p>
<p>Which we can see is identical to what we had above, so our length is again:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_5f7044581ef3661c067c4fda270f14c5.gif" class="tex" alt="l\;=\;sqrt{3}\;+\;1" /><br />
</em><br />
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=35</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Puzzle &#8211; Clock</title>
		<link>http://rebrained.com/?p=34</link>
		<comments>http://rebrained.com/?p=34#comments</comments>
		<pubDate>Sat, 14 Jun 2008 22:51:50 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[quants]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=34</guid>
		<description><![CDATA[It&#8217;s 3 O&#8217;Clock. What will be the time when the minute and hour hands are next in the same position (coincident)? Answer The Plodder&#8217;s way: Let&#8217;s start with the minute hand at the 12 and hour hand at the 3. Let&#8217;s call x the number of minute markers from 12 O&#8217;clock to where the hands [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s 3 O&#8217;Clock.  What will be the time when the minute and hour hands are next in the same position (coincident)?</p>
<p><a href="javascript:collapseExpand('7273')">Answer</a><div id="7273" style="display:none;">  <em><br />
The Plodder&#8217;s way:  Let&#8217;s start with the minute hand at the 12 and hour hand at the 3.  Let&#8217;s call <em>x</em> the number of minute markers from 12 O&#8217;clock to where the hands meet.  The minute hand will take <em>x</em> minutes to get there (it travels a minute marker a minute).  The hour hand will need to travel (<em>x</em>-15) minute markers and we know it will take (<em>x</em>-15)*12 minutes to get there.  When the hands meet, the same time will have elapsed for both so we can solve for <em>x</em>:<br />
<em>x</em> = (<em>x</em>-15)*12<br />
<em>x</em>=12<em>x</em>-180<br />
11<em>x</em>=180<br />
<em>x</em>=180/11<br />
<em>x</em>=16 and 4/11  minutes</em></p>
<p><em>There&#8217;s a smarter way to solve this problem:  you realize that there&#8217;s 11 intervals at which the minute hand and the hour hand coincide over the course of a 12 hour period, so each is 60/11 minute markers apart on the clock face.  The one after 3 O&#8217;Clock is the third, so it&#8217;s 60*3/11 minutes after the hour, which is 180/11 minutes.<br />
</em><br />
 </div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=34</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>More puzzles&#8230;</title>
		<link>http://rebrained.com/?p=33</link>
		<comments>http://rebrained.com/?p=33#comments</comments>
		<pubDate>Sat, 14 Jun 2008 21:12:41 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[quants]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=33</guid>
		<description><![CDATA[A few more brainteasers.. Some of these are from Heard on the Street &#8211; a book of interview questions for Quants I&#8217;m trying to get through. Well worth a read if you&#8217;re into this sort of thing &#8211; or if you ever want to pretend you&#8217;re a Quant at parties (oh yeah, that will really [...]]]></description>
			<content:encoded><![CDATA[<p>A few more brainteasers..</p>
<p>Some of these are from <a href="http://www.amazon.com/Heard-Street-Quantitative-Questions-Interviews/dp/0970055234">Heard on the Street</a> &#8211; a book of interview questions for <a href="http://en.wikipedia.org/wiki/Quantitative_analyst">Quants</a> I&#8217;m trying to get through.  Well worth a read if you&#8217;re into this sort of thing &#8211; or if you ever want to pretend you&#8217;re a Quant at parties (oh yeah, that will really attract the ladies!)</p>
<p>1. Two ropes of different lengths, and you know that if you were to light either of them at one end it burns through in an hour.  How can use use them to measure 45 mins?<br />
<a href="javascript:collapseExpand('1321')">Answer</a><div id="1321" style="display:none;"> <br />
Light the first of them at both ends, and at the same time the second at one end.  When both lit ends of the first meet (after 30 mins), light the second end of the second rope (which should take another 15mins to meet the other lit end).</p>
<p>Bonus points on this one:  is it a condition for this approach to work that the ropes burn at a constant rate?<br />
 </div></p>
<p>2.  Two identical jugs, one with water, one with vodka.  You pour a bit of vodka into the water, mix it, then pour the mix back to get the jugs to their original volumes.    What&#8217;s the relationship between the new concentration of vodka in the vodka jug and water in the water jug?<br />
<a href="javascript:collapseExpand('8279')">Answer</a><div id="8279" style="display:none;"> <br />
Like a lot of these, getting straight into the algebra is not a good idea.  The key here is that the volume of vodka and water remains the same. Any that displacement of (say) vodka from the vodka jug must have been replaced by an identical amount of water &#8211; so in effect same amounts of vodka and water have just swapped places, and the concentrations are the same.<br />
 </div></p>
<p>3.  Imagine you&#8217;re an ant (you can walk on walls but not fly) and you want to get from a bottom corner of a cubic room (1*1*1) to the extreme opposite corner (farthest from you).  What&#8217;s your shortest path to get there?<br />
<a href="javascript:collapseExpand('7025')">Answer</a><div id="7025" style="display:none;"> <br />
If you said walk diagonally along the floor to the opposite floor corner, then up the joint in the walls to the ceiling corner &#8211; a distance of 1 + sqrt(2), think again.  Think of the room as a box that&#8217;s been laid flat, with the sides out so it&#8217;s like the cross on the swiss flag.   The distance between the two corners in question is sqrt(5).<br />
 </div></p>
<p>4.  Let&#8217;s say you have a bunch of 1*1*1 mini-cubes that you&#8217;ve assembled into a 10*10*10 big cube.  Now let&#8217;s say the whole outer layer of the big cube becomes damaged and has to be replaced &#8211; how many new mini-cubes do you need?<br />
<a href="javascript:collapseExpand('8495')">Answer</a><div id="8495" style="display:none;"> <br />
Two ways of doing this &#8211; the Plodders way and then a smart way.  A Plodder would say you need a top and bottom layer (10*10 + 10*10 = 200) and 8 ring layers (8 * (10+10+8+8) = 288).  Total 488.</p>
<p>The smart way is to think about the inner cube that&#8217;s left, which is 8*8*8, or 8^3.  So your answer is 10^3 &#8211; 8^3.  You should be able to do this in your head:  10^3 is 1000.  8^3 is the same as (2^3)^3, or 2^9.  Everyone knows 2^10 which is 1024.  2^9 is half that, 512.  1000-512 is 488.<br />
 </div></p>
<p>5.  Say there are 100 lights with switches (initially off), and 100 people.  The first person goes through and flips every switch (so all the lights are on).  The second person flips every second switch, so at this point half the lights are off again.  The third person every third switch, and so on.  By the time the 100th person goes through he just flips switch #100.  At the end, how many light bulbs are turned on?<br />
<a href="javascript:collapseExpand('9572')">Answer</a><div id="9572" style="display:none;"> <br />
The trick here is to understand that the number of times a switch gets flipped depends on the number of factors that switch number has.  So for example switch #6 has an even number of factors &#8211; 1,2,3 and 6 &#8211; so it ends up off.  You&#8217;ll see that most numbers have an even number of factors because they have product pairs (for example, 1 and 6, and 2 and 3).  Which numbers don&#8217;t have product pairs?  Well, they all have product pairs, but in some cases both numbers in the product pair are the same &#8211; when the number has an integer square root.  So for example the product pairs for 9 are 1 and 9, and 3 and 3.  So the people who flip the #9 switch are 1, 3 and 9 &#8211; an odd number that leaves the light turned on.  So the lights left on are these &#8220;perfect squares&#8221; of 1, 4, 9, 16, 25, 36, 49, 64, 81 and 100.<br />
 </div></p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=33</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dice puzzle &#8211; redux</title>
		<link>http://rebrained.com/?p=27</link>
		<comments>http://rebrained.com/?p=27#comments</comments>
		<pubDate>Sat, 14 Jun 2008 03:03:52 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[puzzles]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=27</guid>
		<description><![CDATA[I&#8217;d blogged previously about rolling a die and being given whatever you roll in dollars. You get given two more chances if you don&#8217;t like what you get the first time, or the second time, for a max of 3 rolls. What&#8217;s your strategy? You can see the answer in my previous post. A couple [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d blogged previously about<a href="http://rebrained.com/?p=20"> rolling a die and being given whatever you roll in dollars</a>. You get given two more chances if you don&#8217;t like what you get the first time, or the second time, for a max of 3 rolls. What&#8217;s your strategy? You can see the answer in my previous post.</p>
<p>A couple of people have asked &#8211; what if there&#8217;s a pair of dice?</p>
<p>It’s the same principle.  You could write all 36 permutations (but you&#8217;d live in fear you’ll be asked for a 3 dice solution).  You know you can only roll a sum from 2 to a 12, and that you can get these sums from more than one combination of numbers on the dice.</p>
<p>You’ll see in the table below we again start by looking at the last throw. The expected payoff on the third throw is 7 (as you may have figured given the expected payoff for 1 die is 3.5). Following the same strategy as for the 1 die problem, for the second roll we pretend anything less than 7 is 7 for the purposes of figuring the expected payoff, which for roll 2 is 7.97.  And so on for roll 1 which has an expected payoff of 8.54 (this is what you’d expect to win on average from this game).</p>
<p><a href="http://rebrained.com/wp-content/uploads/2008/06/dicetable3.jpg"><img class="alignleft size-full wp-image-28" title="expected payoffs - 2 dice" src="http://rebrained.com/wp-content/uploads/2008/06/dicetable3.jpg" alt="" width="416" height="281" /></a></p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>So the strategy to maximize the expected payoff: on roll 1, stick with 8 or higher. On roll 2, stick with 7 or higher.</p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=27</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mth to last &#8211; a recursive approach</title>
		<link>http://rebrained.com/?p=26</link>
		<comments>http://rebrained.com/?p=26#comments</comments>
		<pubDate>Thu, 12 Jun 2008 19:17:35 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[linked lists]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[recursion]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=26</guid>
		<description><![CDATA[A collegue of mine was pondering the mthToLast problem for a LinkedList I&#8217;d blogged about previously and sent me the following IM message: just a guess - but can you use recursion to solve your link list m problem? a method to track through the list which calls itself, then when you get to the [...]]]></description>
			<content:encoded><![CDATA[<p>A collegue of mine was pondering the mthToLast problem for a LinkedList I&#8217;d <a href="http://rebrained.com/?p=12">blogged about previously</a> and sent me the following IM message:</p>
<pre>
just a guess - but can you use  recursion to solve your link list m problem?
a method to track through the list which calls itself,
then when you get to the end start incrementing a counter,
and when it equals M return the value?
</pre>
<p>I think this is what he meant &#8211; it seems to work. Not as scalable as the trailing pointer approach in the previous post, but an interesting excerise in recursion.  You find the size at the end, and return it all the way back. The code is a little messy with the 1 element case&#8230;anyone have a neater implementation?</p>
<pre class="brush: python">
class Element:
    def __init__(self,value,next=None):
        self.value=value
        self.next=next

def findMToLast(element,m,counter=1):
        &quot;&quot;&quot;
        &gt;&gt;&gt; e1=Element(1)
        &gt;&gt;&gt; e2=Element(2)
        &gt;&gt;&gt; e3=Element(3)
        &gt;&gt;&gt; e4=Element(4)
        &gt;&gt;&gt; e1.next=e2
        &gt;&gt;&gt; e2.next=e3
        &gt;&gt;&gt; e3.next=e4
        &gt;&gt;&gt; findMToLast(e1,1).value
        4
        &gt;&gt;&gt; findMToLast(e1,2).value
        3
        &gt;&gt;&gt; findMToLast(e1,3).value
        2
        &gt;&gt;&gt; findMToLast(e1,4).value
        1
        &quot;&quot;&quot;
        if element.next==None:
            if m==1: mtolast=element
            else: mtolast=None
            if counter ==1: return mtolast
            return (counter,mtolast)
        (size,mtolast)=findMToLast(element.next,m,counter+1)
        if size-counter+1==m: mtolast=element
        if counter==1: return mtolast
        return (size,mtolast)

if __name__ == &quot;__main__&quot;:
    import doctest
    doctest.testmod()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=26</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reverse a string using recursion</title>
		<link>http://rebrained.com/?p=25</link>
		<comments>http://rebrained.com/?p=25#comments</comments>
		<pubDate>Thu, 12 Jun 2008 01:52:38 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[recursion]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=25</guid>
		<description><![CDATA[Very basic &#8211; take a string and reverse it using simple recursion. I&#8217;m sure there&#8217;s a bunch of ways to do it, but like the fibonacci you should aim to be able to code something like the below in about 20 seconds&#8230; >>> def reverse(str): if len(str)==1: return str else: return reverse(str[1:])+str[0] >>> reverse('hello') 'olleh' [...]]]></description>
			<content:encoded><![CDATA[<p>Very basic &#8211; take a string and reverse it using simple recursion.  I&#8217;m sure there&#8217;s a bunch of ways to do it, but like the fibonacci you should aim to be able to code something like the below in about 20 seconds&#8230;</p>
<pre>
>>> def reverse(str):
    if len(str)==1:
        return str
    else:
        return reverse(str[1:])+str[0]

>>> reverse('hello')
'olleh'
>>>
</pre>
<p>Without using recursion, the simplest way to reverse a string is to use the slice function:</p>
<pre>
>>> 'abcdef'[::-1]
'fedcba'
>>>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=25</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deep copy and recursive references</title>
		<link>http://rebrained.com/?p=24</link>
		<comments>http://rebrained.com/?p=24#comments</comments>
		<pubDate>Tue, 10 Jun 2008 01:59:56 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=24</guid>
		<description><![CDATA[Quick one about coding a deep copy and avoiding recursive references&#8230; Let&#8217;s say we have an instance a which has a reference to an instance b and we have to do a deep copy of a. To do this, we need a deep copy of b as well. But let&#8217;s say b had a reference [...]]]></description>
			<content:encoded><![CDATA[<p>Quick one about coding a deep copy and avoiding recursive references&#8230;</p>
<p>Let&#8217;s say we have an instance <em>a</em> which has a reference to an instance <em>b</em> and we have to do a deep copy of <em>a</em>.  To do this, we need a deep copy of <em>b</em> as well.</p>
<p>But let&#8217;s say <em>b</em> had a reference back to <em>a</em>.</p>
<p>Here it is in Python (I know Python has its own __deepcopy__() method but the below is for illustrative purposes).</p>
<pre class="brush: python">
class A:
    def __init__(self,b=None):
        self.b=b
    def deepcopy(self):
        newA=A()
        newA.b=self.b.deepcopy()
        return newA

class B:
    def __init__(self,a=None):
        self.a=a
    def deepcopy(self):
        newB=B()
        newB.a=self.a.deepcopy()
        return newB
</pre>
<p>Now let&#8217;s execute this:</p>
<pre>
>>> a=A()
>>> b=B()
>>> a.b=b
>>> b.a=a
>>> newA=a.deepcopy()
</pre>
<p>What happens?  Not pretty &#8211; a recursion limit error.</p>
<p>To fix this, we can keep track in <em>a</em> as to whether that instance has already created a copy of itself, so when it is called back from <em>b</em> it can just return that instance.  This is sometimes called the &#8220;memo&#8221; copy. See amended code below.</p>
<pre class="brush: python">
class A:
    def __init__(self,b=None):
        self.b=b
        self.memo=None
    def deepcopy(self):
        if self.memo==None:
            newA=A()
            self.memo=newA
            newA.b=self.b.deepcopy()
            self.memo=None
            return newA
        else:
            return self.memo

class B:
    def __init__(self,a=None):
        self.a=a
    def deepcopy(self):
        newB=B()
        newB.a=self.a.deepcopy()
        return newB</pre>
<p>Now when we execute:</p>
<pre>
>>> a=A()
>>> b=B()
>>> a.b=b
>>> b.a=a
>>> newA=a.deepcopy()
>>> newA
<__main__.A instance at 0x00D53A30>
>>> newA.b.a
<__main__.A instance at 0x00D53A30>
>>> newA2=a.deepcopy()
>>> newA2
<__main__.A instance at 0x00D53AF8>
>>> newA2.b.a
<__main__.A instance at 0x00D53AF8>
>>> </pre>
<p>Note that the memo is removed just before the copy is handed back so that if you call deepcopy again you&#8217;ll get a new copy of <em>a</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=24</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Bootstrapping Zero Curves</title>
		<link>http://rebrained.com/?p=23</link>
		<comments>http://rebrained.com/?p=23#comments</comments>
		<pubDate>Sun, 08 Jun 2008 20:07:33 +0000</pubDate>
		<dc:creator>nolfonzo</dc:creator>
				<category><![CDATA[finance]]></category>
		<category><![CDATA[yield curves]]></category>
		<category><![CDATA[zero curves]]></category>

		<guid isPermaLink="false">http://rebrained.com/?p=23</guid>
		<description><![CDATA[A yield curve is a representation of what interest rates you could lock in today for investments over different periods. It&#8217;s effectively a set of yields for securities of different maturities (typically cash rates at the short end, futures and then swaps at the longer maturities &#8211; see the wikipedia entry). These yields are typically [...]]]></description>
			<content:encoded><![CDATA[<p>A <a href="http://en.wikipedia.org/wiki/Yield_curve">yield curve</a> is a representation of what interest rates you could lock in today for investments over different periods.  It&#8217;s effectively a set of yields for securities of different maturities (typically cash rates at the short end, futures and then swaps at the longer maturities &#8211; see the wikipedia entry).  These yields are typically calculated from market prices using standard price/yield formulas.  </p>
<p>The problem is that the quoted rates are from coupon paying securities and tell us the value of a series of cash flows, but they don&#8217;t tell us the rate for a cash flow at the maturity point independently of the other cash flows. So these rates don&#8217;t directly imply the present value of a dollar to be received at the maturity points &#8211; that is, they cant be used directly as discount rates.</p>
<p>A zero curve represents the set of interest rates assuming that there are no periodic cash flows &#8211; as though the rate reflects a single payment of interest and principal made at that maturity point on the curve.  As such, the rate can directly provide the present value of a dollar received at these maturity points.</p>
<p>Let&#8217;s take a very simple example:</p>
<p>A yield curve with 3 points:<br />
Year 1:   5%<br />
Year 2:   6%<br />
Year 3:   7%</p>
<p>This means if you invest $1:</p>
<ul>
<li>For 1 year, you&#8217;ll receive 5% interest plus your principal &#8211; $1.05 &#8211; at the end of year 1.</li>
<li>For 2 years, you&#8217;ll get 6% annually, with your principal included at the end of year 2.  So you will get $.06 at the end of year 1, and $1.06 at the end of year 2.</li>
<li>For 3 years, you&#8217;ll get $.07 at the end of year 1, $.07 at the end of year 2 and $1.07 at the end of year 3.</li>
</ul>
<p>The key point here is that the 2 and 3 year rates effectively represent a coupon paying security.  In the 2 year rate, $1 invested now for two years represents the combined PV of two cash flows.  But what is the PV of just the second cash flow?  If we can work this out, we&#8217;ll have a zero (or discount) rate at 2 years, enabling us to PV any money received 2 years in the future.   </p>
<p>We know the PV of $1 received at the end of the first year using our basic time value of money formula:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_b8b1fde99bc66638e386f783aa9fc10c.gif" class="tex" alt="PV = \frac{FV}{(1 + r)^n} = \frac{1}{(1 + .05)^1} = \frac{1}{1.05}" /></p>
<p>This is effectively the 1 year discount factor.  So any monies received at the end of 1 year can be multiplied by this to get the PV.  Building (or &#8220;bootstrapping&#8221;) the zero curve is obtaining these discount factors for all maturity points.</p>
<p>To get the zero rate, or discount factor, for the 2 year point, we can say that $1 invested today will equal the PV of 1st payment plus the PV of 2nd payment.  So:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_0890ceb4f2af29551ce031616ca36593.gif" class="tex" alt="PV = 1 = (\frac{.06}{1.05}) + (\frac{1.06}{(1+r)^2})" />  (where r equals the 2 year discount factor)</p>
<p>Working this out, we end up with <img src="http://rebrained.com/wp-content/plugins/cache/tex_761c372b910671778494c89049909748.gif" class="tex" alt="r_{\tiny{Z2}}=.0603" /> or 6.03%</p>
<p>For the 3rd year zero rate, we build on the above:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_417c9a03b6476ea8efa2f69b1f7b7aa7.gif" class="tex" alt="PV = 1 = (\frac{.07}{1.05}) + (\frac{.07}{(1+.0603)^2})  + (\frac{1.07}{(1+r)^3})" />  (where r equals the 3 year discount factor)</p>
<p>This gives us <img src="http://rebrained.com/wp-content/plugins/cache/tex_a42afea708cefbec89958dc9e39a1da0.gif" class="tex" alt="r_{\tiny{Z3}}=.07097" /> or 7.097%</p>
<p>Now we have our zero curve that we can used as discount rates for cash flows at the corresponding<br />
maturities.</p>
<p>So the corresponding zero curve:<br />
Year 1:   5%<br />
Year 2:   6.03%<br />
Year 3:   7.097%</p>
<p>It&#8217;s interesting to note that the zero rates are slightly higher than the yield curve rates when the curve is sloping upwards.  If you have trouble seeing why think of an extreme case of a yield curve with 0%  rate in 1 and 100% rate in year 2.  </p>
<p>Another concept worth touching on here are the implied forward rates from these zero rates.  Let&#8217;s say we invest $1 for 2 years under our zero rate, which is 6.03%.  This would give us a return of:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_642820c4cd6c82ad5a4c1e934c84f102.gif" class="tex" alt="FV = 1 * (1 + .0603)^2 = 1.124236" /></p>
<p>We could also have invested for 1 year, then take that return and lock in a forward rate for the second year (the rate at the end of year 1 for investing for year 2).   Under the rules of arbitrage, this forward rate for year 2 needs to give us the same return as investing for 2 years using the 2 year zero rate.  So:</p>
<p><img src="http://rebrained.com/wp-content/plugins/cache/tex_1b40e8555e9a19548731e0f1c74b33ce.gif" class="tex" alt="FV = 1.124236 = 1.05 * (1 + r_{\tiny{1,2}})" />     where <img src="http://rebrained.com/wp-content/plugins/cache/tex_748b856245c61dfd8e7633b16e69cf33.gif" class="tex" alt="r_{\tiny{1,2}}" /> is the forward rate for the second year  </p>
<p>This gives an implied forward rate <img src="http://rebrained.com/wp-content/plugins/cache/tex_adf659881190d5bff5654cdeb2a7c309.gif" class="tex" alt="r_{\tiny{1,2}} = .070707 = 7.07%" /></p>
<p>You can keep building these implied forward rates for all future years using this technique.</p>
]]></content:encoded>
			<wfw:commentRss>http://rebrained.com/?feed=rss2&amp;p=23</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
