<?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>Yaniv&#039;s Gems &#187; Comp</title>
	<atom:link href="http://yaniv.leviathanonline.com/blog/category/comp/feed/" rel="self" type="application/rss+xml" />
	<link>http://yaniv.leviathanonline.com/blog</link>
	<description>Strain your Brain</description>
	<lastBuildDate>Mon, 28 Mar 2011 22:02:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Zeroing an Array in Constant Time</title>
		<link>http://yaniv.leviathanonline.com/blog/riddles/zeroing-an-array-in-constant-time/</link>
		<comments>http://yaniv.leviathanonline.com/blog/riddles/zeroing-an-array-in-constant-time/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 10:04:41 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Riddles]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/?p=202</guid>
		<description><![CDATA[This one is a really cool (and practical) riddle! Implement an &#8220;integer array&#8221; data structure, that supports the following 3 operations: Init(int n, int k) &#8211; initialize the array to be of size n and with all cells set to the value k. Get(int i) &#8211; return the value at cell i. Set(int i, int [...]]]></description>
			<content:encoded><![CDATA[<p>This one is a really cool (and practical) riddle!</p>
<p>Implement an &#8220;integer array&#8221; data structure, that supports the following 3 operations:</p>
<p><strong>Init(int <em>n</em>, int <em>k</em>)</strong> &#8211; initialize the array to be of size <em>n</em> and with all cells set to the value <em>k</em>.</p>
<p><strong>Get(int <em>i</em>)</strong> &#8211; return the value at cell <em>i</em>.</p>
<p><strong>Set(int <em>i</em>, int <em>k</em></strong><strong>)</strong> &#8211; set the value of cell <em>i</em> to <em>k</em>.</p>
<p>The catch &#8211; all 3 operations should take constant time (not amortized, not probabilistic).</p>
<p>Note &#8211; you can assume that malloc or new are constant time, but that the returned memory is filled with (adversarial) random.</p>
<p><span style="color: #0000ff;">Thanks to Nadav Sherman for this riddle!</span></p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/riddles/zeroing-an-array-in-constant-time/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Differing Neighbors</title>
		<link>http://yaniv.leviathanonline.com/blog/riddles/differing-neighbors/</link>
		<comments>http://yaniv.leviathanonline.com/blog/riddles/differing-neighbors/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 22:49:11 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Riddles]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/?p=195</guid>
		<description><![CDATA[Algorithm A Given an array of N integers, sort the array, and find the 2 consecutive numbers in the sorted array with the maximum difference. Example &#8211; on input [1,7,3,2] output 4 (the sorted array is [1,2,3,7], and the maximum difference is 7-3=4). Algorithm A runs in O(NlogN) time. Implement an algorithm identical in function [...]]]></description>
			<content:encoded><![CDATA[<p><span style="text-decoration: underline;"><strong>Algorithm A</strong></span></p>
<p>Given an array of N integers, sort the array, and find the 2 consecutive numbers in the sorted array with the maximum difference.<br />
<span style="text-decoration: underline;"><em>Example</em></span> &#8211; on input <strong>[1,7,3,2]</strong> output <strong>4</strong> (the sorted array is [1,2,3,7], and the maximum difference is 7-3=4).</p>
<p>Algorithm A runs in O(NlogN) time.</p>
<p>Implement an algorithm identical in function to algorithm A, that runs in O(N) time.</p>
<p><span style="color: #0000ff;">Thanks to Yossi Richter for this riddle!</span></p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/riddles/differing-neighbors/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Better Half</title>
		<link>http://yaniv.leviathanonline.com/blog/riddles/the-better-half/</link>
		<comments>http://yaniv.leviathanonline.com/blog/riddles/the-better-half/#comments</comments>
		<pubDate>Wed, 19 May 2010 19:34:33 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Riddles]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/?p=178</guid>
		<description><![CDATA[A cute and easy algorithmic riddle. You have an array of N bit strings each of length M. You know that there is at least one element that appears more than N/8 times in the array. Using O(M+log(N)) memory and O(NM) time, find such an element. An Easier Version Well, its actually almost exactly the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/easyriddle.gif"><img class="size-full wp-image-54 alignleft" title="easyriddle.gif" src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/easyriddle.gif" alt="" width="200" height="200" /></a>A cute and easy algorithmic riddle.</p>
<p>You have an array of N bit strings each of length M. You know that there is at least one element that appears more than N/8 times in the array. Using O(M+log(N)) memory and O(NM) time, find such an element.</p>
<p><span style="text-decoration: underline;"><strong>An Easier Version<br />
</strong></span></p>
<p>Well, its actually almost exactly the same, but solve the above riddle in case there is an element that appears more than N/2 times in the array. I managed to find 3 distinct solutions to this easier variation, but only one of which generalizes easily.</p>
<p><span style="color: #0000ff;">Thanks Nemo for giving me this riddle!</span></p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/riddles/the-better-half/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Find the Duplicate</title>
		<link>http://yaniv.leviathanonline.com/blog/riddles/find-the-duplicate/</link>
		<comments>http://yaniv.leviathanonline.com/blog/riddles/find-the-duplicate/#comments</comments>
		<pubDate>Sat, 13 Oct 2007 19:54:35 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Riddles]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/riddles/find-the-duplicate/</guid>
		<description><![CDATA[Dany Valevsky gave me this very cool riddle. You are given a vector of size N, the elements of which are numbers in the range 1,&#8230;,N-1. I.e. there is at least one repeating element. Give an algorithm that finds a repeating element (it does not matter which one, in case there are several) with O(N) time complexity [...]]]></description>
			<content:encoded><![CDATA[<p>Dany Valevsky gave me this very cool riddle.</p>
<p>You are given a vector of size N, the elements of which are numbers in the range 1,&#8230;,N-1. I.e. there is at least one repeating element. Give an algorithm that finds a repeating element (it does not matter which one, in case there are several) with O(N) time complexity and O(1) memory complexity.</p>
<p><strong><span style="text-decoration: underline;">NOTE </span></strong>- the time and memory complexities are calculated in integers. I.e. the input is of size N, not N*logN.</p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/riddles/find-the-duplicate/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Turing Machines in Action</title>
		<link>http://yaniv.leviathanonline.com/blog/comp/turing-machines-in-action/</link>
		<comments>http://yaniv.leviathanonline.com/blog/comp/turing-machines-in-action/#comments</comments>
		<pubDate>Sun, 07 Oct 2007 20:49:18 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/comp/turing-machines-in-action/</guid>
		<description><![CDATA[ In this post I will define turing machines and demonstrate a simple one in action. Definition of a Turing Machine A turing machine (TM) description consists of a tuple of 7 objects: a set of states Q, an input alphabet I, a tape alphabet T, a transition function F, a set of accept states Qaccept, a set of reject states [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/10/tmbinaryaddreverse.gif" title="tmbinaryaddreverse.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/10/tmbinaryaddreverse.thumbnail.gif" alt="tmbinaryaddreverse.gif" /></a> In this post I will define turing machines and demonstrate a simple one in action.</p>
<p><u><strong>Definition of a Turing Machine</strong></u></p>
<p>A <u><em>turing machine</em></u> (<u><em>TM</em></u>) description consists of a tuple of 7 objects: a set of states <em>Q</em>, an input alphabet <em>I</em>, a tape alphabet <em>T</em>, a transition function <em>F</em>, a set of accept states <em>Qaccept</em>, a set of reject states <em>Qreject</em> and a start state <em>Qstart</em>.</p>
<p>The following requirements must hold: <em>I</em> is contained in <em>T</em>. &#8216; &#8216; (the space symbol) is a member of <em>T</em> but not of <em>I</em>. <em>F</em> is a function from <em>QxT-&gt;QxTx{1,-1}</em>. <em>Qaccept</em> and <em>Qreject</em> are disjoint subsets of <em>Q</em>. <em>Qstart</em> is a member of <em>Q</em>.</p>
<p>The turing machine itself consists of: its <u><em>description</em></u> (as defined above), an infinite <u><em>tape</em></u>, a <u><em>head</em></u> and a <u><em>current state</em></u>.</p>
<p>The <em><u>tape</u></em> is an infinite list of symbols from <em>T</em> (it is only infinite to the right, i.e. it has indexes 0, 1, 2, &#8230; but no negative indexes). The tape initially contains the <u><em>input</em></u> (a string of symbols from <em>I</em>) starting at index 0 followed by infinitely many &#8217; &#8216; (space) symbols. As we required that the &#8216; &#8216; symbol is not a member of <em>I</em> the TM can detect the end of the input.</p>
<p>The <em><u>head</u></em> is simply a pointer to the tape. It initially points to tape position 0.</p>
<p>The <em><u>current state</u></em> is a member of <em>Q</em>, and is initialized to <em>Qstart</em>.</p>
<p><strong><u>Operation</u></strong></p>
<p>A TM with a description <em>{Q, I, T, F, Qaccept, Qreject, Qstart}</em> is initialized as indicated above. The result of its operation consists of the contents of the tape as well as an additional flag which can be either ACCEPT or REJECT. In the description below, the action accept means setting this flag to the ACCEPT state and halting. The same goes for the reject action.</p>
<p>The TM operates as follows:</p>
<ol>
<li>If current_state is in <em>Qaccept</em>, accept. If it is in <em>Qreject</em>, reject.</li>
<li>Read a symbol from the tape at the position indicated by the head. Denote it as current_symbol.</li>
<li>Set next_state, next_symbol, next_head_pos to <em>F</em>(current_state, current_symbol).</li>
<li>Write next_symbol to the tape at the current head position.</li>
<li>If next_head_pos is 1 move the head one position to the right.</li>
<li>If next_head_pos is -1 move the head one position to the left. If the head tries to move to the left from position 0, do not move the head.</li>
<li>Set current_state to next_state.</li>
</ol>
<p>And that&#8217;s it!</p>
<p><strong><u>An Example</u></strong></p>
<p>The following is the description of a TM that multiplies two integers in unary notation. For example, if its input is of the form &#8217;111*11=&#8217; it will accept with an output tape of &#8217;111*11=111111&#8242;.</p>
<p>The code of the machine:</p>
<p><code>TMUnaryMultiply = {<br />
    'description' : """The input must be of the form '11*111='. The output tape will look like '11*111=111111'.""",<br />
    'start_state' : 'mark_start',<br />
#input verification<br />
    'mark_start' :<br />
        {<br />
            '1':['verify_input_1','#',1],<br />
        },<br />
    'verify_input_1' :<br />
        {<br />
            '1':['verify_input_1','1',1],<br />
            '*':['verify_input_*','*',1]<br />
        },<br />
    'verify_input_*' :<br />
        {<br />
            '1':['verify_input_2','1',1]<br />
        },<br />
    'verify_input_2' :<br />
        {<br />
            '1':['verify_input_2','1',1],<br />
            '=':['verify_input_ ','=',1]<br />
        },<br />
    'verify_input_ ' :<br />
        {<br />
            ' ':['move_head_to_left',' ',-1]<br />
        },<br />
    'move_head_to_left':<br />
        {<br />
            '1':['move_head_to_left','1',-1],<br />
            '=':['move_head_to_left','=',-1],<br />
            '*':['move_head_to_left','*',-1],<br />
            '#':['read_ones','1',-1] # this will try to move the head off the tape<br />
        },<br />
# actual multiplication<br />
    'read_ones' :<br />
        {<br />
            '1':['wait_for_*', '#', 1],<br />
            '*':['halt','*', -1],<br />
        },<br />
    'wait_for_*' :<br />
        {<br />
            '1':['wait_for_*', '1', 1],<br />
            '*':['copy_ones', '*', 1]<br />
        },<br />
    'copy_ones' :<br />
        {<br />
            '1':['wait_for_=', '#', 1],<br />
            '=':['move_left2','=', -1],<br />
        },<br />
    'wait_for_=' :<br />
        {<br />
            '1':['wait_for_=','1',1],<br />
            '=':['wait_for_ ','=',1]<br />
        },<br />
    'wait_for_ ' :<br />
        {<br />
            '1':['wait_for_ ','1',1],<br />
            ' ':['move_left','1',-1]<br />
        },<br />
    'move_left':<br />
        {<br />
            '1':['move_left','1',-1],<br />
            '=':['move_left','=',-1],<br />
            '#':['copy_ones','1', 1]<br />
        },<br />
    'move_left2':<br />
        {<br />
            '1':['move_left2','1',-1],<br />
            '*':['move_left2','*',-1],<br />
            '#':['read_ones','1', 1]<br />
        },<br />
    'halt' : {}<br />
}</code></p>
<p>I think the format of the description is self explanatory (for the python connoisseurs among you, it consists of some nested dictionaries). It can be fed into my Python TM Emulator (the code of which is included at the end of this article). The emulator can also automatically generate a flow graph of the TM. Here is a sample ouput:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/10/tmunarymultiply.gif" alt="tmunarymultiply.gif" /></p>
<p>Running the emulator (in verbose mode) with the TMUnaryMultiply description above on the input &#8217;111*11=&#8217; results in the following:</p>
<p><code>Initialing TM [The input must be of the form '11*111='. The output tape will look like '11*111=111111'.]...<br />
Running tm with input [111*11=]...<br />
                          V<br />
&lt;          mark_start&gt;: ['1', '1', '1', '*', '1', '1', '=', ' ']<br />
                               V<br />
&lt;      verify_input_1&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                    V<br />
&lt;      verify_input_1&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                         V<br />
&lt;      verify_input_1&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                              V<br />
&lt;      verify_input_*&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                                   V<br />
&lt;      verify_input_2&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                                        V<br />
&lt;      verify_input_2&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                                             V<br />
&lt;      verify_input_ &gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                                        V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                                   V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                              V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                         V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                    V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                               V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                          V<br />
&lt;   move_head_to_left&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                          V<br />
&lt;           read_ones&gt;: ['1', '1', '1', '*', '1', '1', '=', ' ']<br />
                               V<br />
&lt;          wait_for_*&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                    V<br />
&lt;          wait_for_*&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                         V<br />
&lt;          wait_for_*&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                              V<br />
&lt;           copy_ones&gt;: ['#', '1', '1', '*', '1', '1', '=', ' ']<br />
                                                   V<br />
&lt;          wait_for_=&gt;: ['#', '1', '1', '*', '#', '1', '=', ' ']<br />
                                                        V<br />
&lt;          wait_for_=&gt;: ['#', '1', '1', '*', '#', '1', '=', ' ']<br />
                                                             V<br />
&lt;          wait_for_ &gt;: ['#', '1', '1', '*', '#', '1', '=', ' ']<br />
                                                        V<br />
&lt;           move_left&gt;: ['#', '1', '1', '*', '#', '1', '=', '1']<br />
                                                   V<br />
&lt;           move_left&gt;: ['#', '1', '1', '*', '#', '1', '=', '1']<br />
                                              V<br />
&lt;           move_left&gt;: ['#', '1', '1', '*', '#', '1', '=', '1']<br />
                                                   V<br />
&lt;           copy_ones&gt;: ['#', '1', '1', '*', '1', '1', '=', '1']<br />
                                                        V<br />
&lt;          wait_for_=&gt;: ['#', '1', '1', '*', '1', '#', '=', '1']<br />
                                                             V<br />
&lt;          wait_for_ &gt;: ['#', '1', '1', '*', '1', '#', '=', '1']<br />
                                                                  V<br />
&lt;          wait_for_ &gt;: ['#', '1', '1', '*', '1', '#', '=', '1', ' ']<br />
                                                             V<br />
&lt;           move_left&gt;: ['#', '1', '1', '*', '1', '#', '=', '1', '1']<br />
                                                        V<br />
&lt;           move_left&gt;: ['#', '1', '1', '*', '1', '#', '=', '1', '1']<br />
                                                   V<br />
&lt;           move_left&gt;: ['#', '1', '1', '*', '1', '#', '=', '1', '1']<br />
                                                        V<br />
&lt;           copy_ones&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                                                   V<br />
&lt;          move_left2&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                                              V<br />
&lt;          move_left2&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                                         V<br />
&lt;          move_left2&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                                    V<br />
&lt;          move_left2&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                               V<br />
&lt;          move_left2&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                          V<br />
&lt;          move_left2&gt;: ['#', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                               V<br />
&lt;           read_ones&gt;: ['1', '1', '1', '*', '1', '1', '=', '1', '1']<br />
                                    V<br />
&lt;          wait_for_*&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1']<br />
                                         V<br />
&lt;          wait_for_*&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1']<br />
                                              V<br />
&lt;           copy_ones&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1']<br />
                                                   V<br />
&lt;          wait_for_=&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1']<br />
                                                        V<br />
&lt;          wait_for_=&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1']<br />
                                                             V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1']<br />
                                                                  V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1']<br />
                                                                       V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1', ' ']<br />
                                                                  V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1', '1']<br />
                                                             V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1', '1']<br />
                                                        V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1', '1']<br />
                                                   V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1', '1']<br />
                                              V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '#', '1', '=', '1', '1', '1']<br />
                                                   V<br />
&lt;           copy_ones&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1']<br />
                                                        V<br />
&lt;          wait_for_=&gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1']<br />
                                                             V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1']<br />
                                                                  V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1']<br />
                                                                       V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1']<br />
                                                                            V<br />
&lt;          wait_for_ &gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1', ' ']<br />
                                                                       V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1', '1']<br />
                                                                  V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1', '1']<br />
                                                             V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;           move_left&gt;: ['1', '#', '1', '*', '1', '#', '=', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;           copy_ones&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;          move_left2&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                              V<br />
&lt;          move_left2&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                         V<br />
&lt;          move_left2&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                    V<br />
&lt;          move_left2&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                               V<br />
&lt;          move_left2&gt;: ['1', '#', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                    V<br />
&lt;           read_ones&gt;: ['1', '1', '1', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                         V<br />
&lt;          wait_for_*&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                              V<br />
&lt;           copy_ones&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;          wait_for_=&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;          wait_for_=&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1']<br />
                                                             V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1']<br />
                                                                  V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1']<br />
                                                                       V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1']<br />
                                                                            V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1']<br />
                                                                                 V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', ' ']<br />
                                                                            V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                                                       V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                                                  V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                                             V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                              V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '#', '1', '=', '1', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;           copy_ones&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;          wait_for_=&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1']<br />
                                                             V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1']<br />
                                                                  V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1']<br />
                                                                       V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1']<br />
                                                                            V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1']<br />
                                                                                 V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1']<br />
                                                                                      V<br />
&lt;          wait_for_ &gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', ' ']<br />
                                                                                 V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                                            V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                                       V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                                  V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                             V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;           move_left&gt;: ['1', '1', '#', '*', '1', '#', '=', '1', '1', '1', '1', '1', '1']<br />
                                                        V<br />
&lt;           copy_ones&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1', '1', '1']<br />
                                                   V<br />
&lt;          move_left2&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1', '1', '1']<br />
                                              V<br />
&lt;          move_left2&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1', '1', '1']<br />
                                         V<br />
&lt;          move_left2&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1', '1', '1']<br />
                                    V<br />
&lt;          move_left2&gt;: ['1', '1', '#', '*', '1', '1', '=', '1', '1', '1', '1', '1', '1']<br />
                                         V<br />
&lt;           read_ones&gt;: ['1', '1', '1', '*', '1', '1', '=', '1', '1', '1', '1', '1', '1']<br />
accept</code></p>
<p>Finally, here is the code of my Python TM Emulator:</p>
<p><code>class TM:<br />
    def __init__(self, states, accept_states, reject_states):<br />
        print 'Initialing TM [%s]...' % (states['description'])<br />
        self.states = states<br />
        self.accept_states = accept_states<br />
        self.reject_states = reject_states<br />
        self.halt_states = accept_states + reject_states<br />
def run(self, input,verbose=False):<br />
        head_pos = 0<br />
        current = self.states['start_state']<br />
        tape = [x for x in input]+[" "]<br />
        while current not in self.halt_states:<br />
            if verbose:<br />
                print ' '*(22+1+1+1+5*(head_pos)+1)+'V'<br />
                print '&lt;%20s&gt;: %s' % (current, tape)<br />
            try:<br />
                next_state, next_symbol, head_movement = self.states[current][tape[head_pos]]<br />
            except KeyError:<br />
                return "reject"<br />
            tape[head_pos] = next_symbol<br />
            head_pos += head_movement<br />
            if head_pos &lt; 0:<br />
                head_pos = 0<br />
            elif head_pos == len(tape):<br />
                tape.append(" ")<br />
            current = next_state<br />
        print ''.join(tape)<br />
        if current in self.accept_states:<br />
            return 'accept'<br />
        else:<br />
            assert(current in self.reject_states)<br />
            return 'reject'<br />
</code></p>
<p>And that of a simple test method:</p>
<p><code>def test():<br />
    mul = TM(TMUnaryMultiply, ["halt"], [""])<br />
    inputs = ['bad_input','111*11=','1*1=','*1=','1*=','11111111*1111111=']<br />
    for input in inputs:<br />
        print 'Running tm with input [%s]...' % (input)<br />
        print mul.run(input)</code></p>
<p>A sample output:</p>
<p><code><br />
&gt;&gt;&gt; test()<br />
Initialing TM [The input must be of the form '11*111='. The output tape will look like '11*111=111111'.]...<br />
Running tm with input [bad_input]...<br />
reject<br />
Running tm with input [111*11=]...<br />
111*11=111111<br />
accept<br />
Running tm with input [1*1=]...<br />
1*1=1<br />
accept<br />
Running tm with input [*1=]...<br />
reject<br />
Running tm with input [1*=]...<br />
reject<br />
Running tm with input [11111111*1111111=]...<br />
11111111*1111111=11111111111111111111111111111111111111111111111111111111<br />
accept</code></p>
<p>A second, more interesting TM performs binary addition:</p>
<p><code><br />
TMBinaryAddReverse = {<br />
    'description' : """The input must be of the form '1010+0010=' (i.e. in reversed binary notation, operands of same size padded with an extra 0). The output will look like '1010+0010=1110'.""",<br />
    'start_state' : 'mark_start_carry_0',<br />
    'halt': {},<br />
    'mark_start_carry_0' :<br />
    {<br />
        '1':['sum_1','#',1],<br />
        '0':['sum_0','#',1],<br />
        '+':['halt','+',1]<br />
    },<br />
    'mark_start_carry_1' :<br />
    {<br />
        '1':['sum_2','#',1],<br />
        '0':['sum_1','#',1],<br />
        '+':['halt','+',1]<br />
    },<br />
    'sum_0' :<br />
    {<br />
        '1':['sum_0','1',1],<br />
        '0':['sum_0','0',1],<br />
        '+':['sum_0_get_next','+',1],<br />
        '=':['write_0','=',1],<br />
    },<br />
    'sum_1' :<br />
    {<br />
        '1':['sum_1','1',1],<br />
        '0':['sum_1','0',1],<br />
        '+':['sum_1_get_next','+',1],<br />
        '=':['write_1','=',1],<br />
    },<br />
    'sum_2' :<br />
    {<br />
        '1':['sum_2','1',1],<br />
        '0':['sum_2','0',1],<br />
        '+':['sum_2_get_next','+',1],<br />
        '=':['write_2','=',1],<br />
    },<br />
    'sum_3' :<br />
    {<br />
        '1':['sum_3','1',1],<br />
        '0':['sum_3','0',1],<br />
        '=':['write_3','=',1],<br />
    },<br />
    'sum_1_get_next':<br />
    {<br />
        '#':['sum_1_get_next','#',1],<br />
        '1':['sum_2','#',1],<br />
        '0':['sum_1','#',1],<br />
    },<br />
    'sum_0_get_next':<br />
    {<br />
        '#':['sum_0_get_next','#',1],<br />
        '1':['sum_1','#',1],<br />
        '0':['sum_0','#',1],<br />
    },<br />
    'sum_2_get_next':<br />
    {<br />
        '#':['sum_2_get_next','#',1],<br />
        '1':['sum_3','#',1],<br />
        '0':['sum_2','#',1],<br />
    },<br />
    'write_0':<br />
    {<br />
        '1':['write_0','1',1],<br />
        '0':['write_0','0',1],<br />
        ' ':['move_left_carry_0','0',-1],<br />
    },<br />
    'write_1':<br />
    {<br />
        '1':['write_1','1',1],<br />
        '0':['write_1','0',1],<br />
        ' ':['move_left_carry_0','1',-1],<br />
    },<br />
    'write_2':<br />
    {<br />
        '1':['write_2','1',1],<br />
        '0':['write_2','0',1],<br />
        ' ':['move_left_carry_1','0',-1],<br />
    },<br />
    'write_3':<br />
    {<br />
        '1':['write_3','1',1],<br />
        '0':['write_3','0',1],<br />
        ' ':['move_left_carry_1','1',-1],<br />
    },<br />
    'move_left_carry_0':<br />
    {<br />
        '0':['move_left_carry_0','0',-1],       <br />
        '1':['move_left_carry_0','1',-1],       <br />
        '=':['move_left_carry_0','=',-1],       <br />
        '#':['move_left_carry_0','#',-1],       <br />
        '+':['move_left_carry_0_part_2','+',-1],       <br />
    },<br />
    'move_left_carry_1':<br />
    {<br />
        '0':['move_left_carry_1','0',-1],       <br />
        '1':['move_left_carry_1','1',-1],       <br />
        '=':['move_left_carry_1','=',-1],       <br />
        '#':['move_left_carry_1','#',-1],       <br />
        '+':['move_left_carry_1_part_2','+',-1],       <br />
    },<br />
    'move_left_carry_0_part_2':<br />
    {<br />
        '0':['move_left_carry_0_part_2','0',-1],       <br />
        '1':['move_left_carry_0_part_2','1',-1],<br />
        '#':['mark_start_carry_0','#',1],<br />
    },<br />
    'move_left_carry_1_part_2':<br />
    {<br />
        '0':['move_left_carry_1_part_2','0',-1],       <br />
        '1':['move_left_carry_1_part_2','1',-1],<br />
        '#':['mark_start_carry_1','#',1],<br />
    },<br />
}</code></p>
<p>Its graph is included here for your convenience (click to enlarge):</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/10/tmbinaryaddreverse.gif" title="tmbinaryaddreverse.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/10/tmbinaryaddreverse.thumbnail.gif" alt="tmbinaryaddreverse.gif" /></a></p>
<p>And a sample run:</p>
<p><code><br />
&gt;&gt;&gt; mul = TM(TMBinaryAddReverse, ["halt"], [])<br />
Initialing TM [The input must be of the form '1010+0010=' (i.e. in reversed binary notation, operands of same size padded with an extra 0). The output will look like '1010+0010=1110'.]...<br />
&gt;&gt;&gt; mul.run('1110+1100=',True)<br />
                                  V<br />
&lt;mark_start_carry_0&gt;          : ['1', '1', '1', '0', '+', '1', '1', '0', '0', '=', ' ']<br />
                                       V<br />
&lt;sum_1&gt;                       : ['#', '1', '1', '0', '+', '1', '1', '0', '0', '=', ' ']<br />
                                            V<br />
&lt;sum_1&gt;                       : ['#', '1', '1', '0', '+', '1', '1', '0', '0', '=', ' ']<br />
                                                 V<br />
&lt;sum_1&gt;                       : ['#', '1', '1', '0', '+', '1', '1', '0', '0', '=', ' ']<br />
                                                      V<br />
&lt;sum_1&gt;                       : ['#', '1', '1', '0', '+', '1', '1', '0', '0', '=', ' ']<br />
                                                           V<br />
&lt;sum_1_get_next&gt;              : ['#', '1', '1', '0', '+', '1', '1', '0', '0', '=', ' ']<br />
                                                                V<br />
&lt;sum_2&gt;                       : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', ' ']<br />
                                                                     V<br />
&lt;sum_2&gt;                       : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', ' ']<br />
                                                                          V<br />
&lt;sum_2&gt;                       : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', ' ']<br />
                                                                               V<br />
&lt;sum_2&gt;                       : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', ' ']<br />
                                                                                    V<br />
&lt;write_2&gt;                     : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', ' ']<br />
                                                                               V<br />
&lt;move_left_carry_1&gt;           : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                                          V<br />
&lt;move_left_carry_1&gt;           : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                                     V<br />
&lt;move_left_carry_1&gt;           : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                                V<br />
&lt;move_left_carry_1&gt;           : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                           V<br />
&lt;move_left_carry_1&gt;           : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                      V<br />
&lt;move_left_carry_1&gt;           : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                 V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                            V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                       V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                  V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                       V<br />
&lt;mark_start_carry_1&gt;          : ['#', '1', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                            V<br />
&lt;sum_2&gt;                       : ['#', '#', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                 V<br />
&lt;sum_2&gt;                       : ['#', '#', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                      V<br />
&lt;sum_2&gt;                       : ['#', '#', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                           V<br />
&lt;sum_2_get_next&gt;              : ['#', '#', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                                V<br />
&lt;sum_2_get_next&gt;              : ['#', '#', '1', '0', '+', '#', '1', '0', '0', '=', '0']<br />
                                                                     V<br />
&lt;sum_3&gt;                       : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0']<br />
                                                                          V<br />
&lt;sum_3&gt;                       : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0']<br />
                                                                               V<br />
&lt;sum_3&gt;                       : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0']<br />
                                                                                    V<br />
&lt;write_3&gt;                     : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0']<br />
                                                                                         V<br />
&lt;write_3&gt;                     : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', ' ']<br />
                                                                                    V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                               V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                          V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                     V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                           V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                      V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                 V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                            V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                       V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                            V<br />
&lt;mark_start_carry_1&gt;          : ['#', '#', '1', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                 V<br />
&lt;sum_2&gt;                       : ['#', '#', '#', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                      V<br />
&lt;sum_2&gt;                       : ['#', '#', '#', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                           V<br />
&lt;sum_2_get_next&gt;              : ['#', '#', '#', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                V<br />
&lt;sum_2_get_next&gt;              : ['#', '#', '#', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                     V<br />
&lt;sum_2_get_next&gt;              : ['#', '#', '#', '0', '+', '#', '#', '0', '0', '=', '0', '1']<br />
                                                                          V<br />
&lt;sum_2&gt;                       : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1']<br />
                                                                               V<br />
&lt;sum_2&gt;                       : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1']<br />
                                                                                    V<br />
&lt;write_2&gt;                     : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1']<br />
                                                                                         V<br />
&lt;write_2&gt;                     : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1']<br />
                                                                                              V<br />
&lt;write_2&gt;                     : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', ' ']<br />
                                                                                         V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                                    V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                               V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                          V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                     V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                           V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                      V<br />
&lt;move_left_carry_1&gt;           : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                 V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                            V<br />
&lt;move_left_carry_1_part_2&gt;    : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                 V<br />
&lt;mark_start_carry_1&gt;          : ['#', '#', '#', '0', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                      V<br />
&lt;sum_1&gt;                       : ['#', '#', '#', '#', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                           V<br />
&lt;sum_1_get_next&gt;              : ['#', '#', '#', '#', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                V<br />
&lt;sum_1_get_next&gt;              : ['#', '#', '#', '#', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                     V<br />
&lt;sum_1_get_next&gt;              : ['#', '#', '#', '#', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                          V<br />
&lt;sum_1_get_next&gt;              : ['#', '#', '#', '#', '+', '#', '#', '#', '0', '=', '0', '1', '0']<br />
                                                                               V<br />
&lt;sum_1&gt;                       : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0']<br />
                                                                                    V<br />
&lt;write_1&gt;                     : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0']<br />
                                                                                         V<br />
&lt;write_1&gt;                     : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0']<br />
                                                                                              V<br />
&lt;write_1&gt;                     : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0']<br />
                                                                                                   V<br />
&lt;write_1&gt;                     : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', ' ']<br />
                                                                                              V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                                                         V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                                                    V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                                               V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                                          V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                                     V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                                V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                           V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                      V<br />
&lt;move_left_carry_0&gt;           : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                 V<br />
&lt;move_left_carry_0_part_2&gt;    : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
                                                      V<br />
&lt;mark_start_carry_0&gt;          : ['#', '#', '#', '#', '+', '#', '#', '#', '#', '=', '0', '1', '0', '1']<br />
####+####=0101<br />
'accept'<br />
</code></p>
<p>I think this machine can be simplified by writing the carry directly to the tape (i.e. writing a &#8217;0&#8242;, a &#8217;1&#8242; or a &#8217;2&#8242; to the result part of the tape, and later converting the &#8217;2&#8242;s to &#8217;1&#8242; and &#8217;0&#8242; as appropriate).</p>
<p>If anyone of you manages to generate an equivalent machine with a shorter description (less states) please post it!</p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/comp/turing-machines-in-action/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Seam Carving</title>
		<link>http://yaniv.leviathanonline.com/blog/math/seam-carving/</link>
		<comments>http://yaniv.leviathanonline.com/blog/math/seam-carving/#comments</comments>
		<pubDate>Mon, 27 Aug 2007 20:39:38 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/math/seam-carving/</guid>
		<description><![CDATA[ I recently watched this interesting video by Shai Avidan and Ariel Shamir from MERL. They developed an extremely cool image resizing technique called seam carving. They explain all about it in this article. One of the coolest things about their idea is that is it easy to implement. I implemented a semi-optimized version of their algorithm in a couple of [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/carved_pagoda.jpg" alt="carved_pagoda.jpg" /> I recently watched <a href="http://www.youtube.com/watch?v=vIFCV2spKtg">this</a> interesting video by Shai Avidan and Ariel Shamir from <a href="http://www.merl.com/">MERL</a>. They developed an extremely cool image resizing technique called <u><em>seam carving</em></u>. They explain all about it in <a href="http://www.faculty.idc.ac.il/arik/imret.pdf">this article</a>.</p>
<p>One of the coolest things about their idea is that is it easy to implement. I implemented a semi-optimized version of their algorithm in a couple of hours of coding. All the images in this post were generated by my code.</p>
<p>The following image of a pagoda will assist me in demonstrating the ideas to follow:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/pagoda.jpg" alt="pagoda.jpg" /></p>
<p>First lets discuss the two image resizing methods currently used, namely scaling and cropping. Scaling consists of uniformly resizing the image. If for example we were to reduce an image 100 pixels wide to an image 50 pixels wide, we could simply average every two neighbouring pixels (a generalization of this technique can be applied even when the image&#8217;s new width does not divide the image&#8217;s original width, and of course to resizing both the width and the height of the image).</p>
<p>Scaling is efficient and, in some sense, you do not lose a lot of information from the original image. There are two big problems with scaling however:</p>
<ul>
<li>If the new dimensions of the image are not proportionate to the original dimensions, the scaled image is distorted.</li>
<li>The method does not take into account the contents of the image at all (I will clarify this point shortly).</li>
</ul>
<p>An example of the pagoda image scaled:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/scaled_pagoda.jpg" alt="scaled_pagoda.jpg" /></p>
<p>A second widely used form of image resizing is cropping. Cropping consists of simply selecting a sub image of the desired proportions from the original image &#8211; i.e. removing the borders of the image. An important question now arises: how do we select which box of the image to keep (or equivalently, how do we select which borders to remove)?</p>
<p>Lets say we assign a weight to each of the pixels of the image, representing its importance. Then selecting the cropping box amounts to simply selecting the box containing the pixels whose sum of weights is highest. We will refer to the weights of the pixels as the <u><em>energy</em></u> of the pixels. So optimal cropping would select the box with the highest energy.</p>
<p>Now, all we are left to do is assign the weights to the pixels. Following Avidan and Shamir, we can use simple <em>gradient magnitude</em> as our energy function. Gradient magnitude simply means calculating the gradient at each pixel (regarding the image as a function from R2 to R) and taking its magnitude at each pixel. Here is the result of applying gradient magnitude on the pagoda image:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/grad_mag.JPG" alt="grad_mag.JPG" /></p>
<p class="sidenote">The perceptive reader would have noticed that a color image is usually a function from R2 to R3 and not to R (as there are usually three independent color channels). There are several ways to calculate the gradient magnitude in this case. The one I used in my code is to calculate the magnitudes of the three gradients separately and average the results. Note that averaging before calculating the gradients is a bad idea as a lot of information is lost in the process!</p>
<p>Note that the gradient magnitude of a pixel constitutes some measure of how likely that pixel is to be a border pixel (and thus more important).</p>
<p>Using all of this, an optimal cropping of the pagoda image is shown here:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/croped_pagoda.jpg" alt="croped_pagoda.jpg" /></p>
<p>The cropping is optimal in the sense that this is the sub-image of the given dimensions containing the most energy.</p>
<p>Note that all the water from the bottom of the image, and the flowers from the top are missing, as well as the left side of the white house on the left of the pagoda.</p>
<p>Now, unlike the scaling method, the cropping technique just presented takes into account the contents of the image. But what if the image contained two pagodas, one at each side of the image? Cropping would only be able to select one of them.</p>
<p>So what we are looking for is some way to automatically remove the uninteresting parts in the middle of the image, and bring the interesting bits closer together.</p>
<p>A naive solution, similar to regular cropping, would be to remove the columns of the image with the least amount of energy not necessarily from the border. This technique causes severe artifacts.</p>
<p>Avidan&#8217;s and Shamir&#8217;s <em>seam carving</em> technique is an improvement of this. They define a vertical <u><em>seam</em></u> as an <em>8-connected</em> path from top-to-bottom of the image containing one pixel in each row. <u><em>8-connectedness</em></u> means that if pixel <em>(x,y)</em> is in the vertical seam, then exactly one of the pixels <em>(x+1, y+1), (x, y+1)</em> or <em>(x-1, y)</em> is in the vertical seam as well (unless of course <em>y</em> = the height of the image). A horizontal seam is defined similarly.</p>
<p>Now instead of deleting the column (row) with the least energy, they suggest deleting the vertical (horizontal) seam with the least energy. The seam with the least energy can be easily found using dynamic programming.</p>
<p>The first seam to be removed in the pagoda image is depicted below:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/seam.JPG" alt="seam.JPG" /></p>
<p>The process of reducing an image&#8217;s size via repeated deletions of the least important seams is called <u><em>seam carving</em></u>. The result of applying some <em>seam carving</em> to the pagoda image is shown here:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/carved_pagoda.jpg" alt="carved_pagoda.jpg" /></p>
<p>Note that although some artifacts are present in the image, it is the best among all the reduced images (at least &#8211; <em>a mon avis</em>).</p>
<p class="sidenote">A problem with seam carving, compared to scaling, is efficiency. I have some algorithmic ideas that I think might substantially reduce computation costs. I will let you know when I will have time to test them.</p>
<p>Another example is shown. The original image:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/pagodas_small.jpg" alt="pagodas_small.jpg" /></p>
<p>Optimal cropping:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/pagodas_small_cropped.jpg" alt="pagodas_small_cropped.jpg" /></p>
<p>Scaling:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/pagodas_small_scaled.jpg" alt="pagodas_small_scaled.jpg" /></p>
<p>And finally, seam carving:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/pagodas_small_carved.jpg" alt="pagodas_small_carved.jpg" /></p>
<p>And just to convince you that the method doesn&#8217;t only work on pagodas:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/hopper_landscape.jpg" alt="hopper_landscape.jpg" /></p>
<p>And the carved version:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/hopper_landscape_carved.jpg" alt="hopper_landscape_carved.jpg" /></p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/math/seam-carving/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>SIMD (Fire)Works!</title>
		<link>http://yaniv.leviathanonline.com/blog/comp/simd-fireworks/</link>
		<comments>http://yaniv.leviathanonline.com/blog/comp/simd-fireworks/#comments</comments>
		<pubDate>Sun, 12 Aug 2007 00:28:47 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Graphics]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/comp/simd-fireworks/</guid>
		<description><![CDATA[When I started yaniv.leviathanonline.com, I declared it to be a site about &#8220;Mathematics and Hacking&#8221;. As of now, most of its content is Mathematical. I thought it was time for a little change&#8230; Those of you with no interest in assembly or low-level programming are welcome to skip this post entirely, although expanding your horizons is never a bad [...]]]></description>
			<content:encoded><![CDATA[<p>When I started <strong>yaniv.leviathanonline</strong>.com, I declared it to be a site about &#8220;Mathematics and Hacking&#8221;. As of now, most of its content is Mathematical. I thought it was time for a little change&#8230;</p>
<p>Those of you with no interest in assembly or low-level programming are welcome to skip this post entirely, although expanding your horizons is never a bad idea!</p>
<p>A few years ago I gave a week-long x86 assembly course for some fellow programmers. As I wanted them to learn how to use the Pentium&#8217;s SIMD extensions, I asked them to program a simple fireworks demo and try to apply some filters to it using MMX. In this article I will detail my solution to the SIMD fireworks exercise.</p>
<p class="sidenote">The following paragraph is intended for those of you without assembly knowledge. All of you assembly masters are welcome to skip to the fun stuff below!</p>
<p><strong><u>Some References </u></strong></p>
<p>Well, for starters I recommend reading the &#8221;<a href="http://webster.cs.ucr.edu/AoA/">The Art of Assembly Language Programming</a>&#8221; (<a href="http://webster.cs.ucr.edu/AoA/">AoA</a>) which covers a lot of the basics. And yes &#8211; Assembly Programming <em>is</em>an Art (maybe more so than programming in other languages). Next, you should also read Intel&#8217;s manuals: <a href="http://www.intel.com/design/processor/manuals/253665.pdf">Volume 1: Basic Architecture</a>, <a href="http://www.intel.com/design/processor/manuals/253666.pdf">Volume 2A: Instruction Set Reference, A-M</a>, <a href="http://www.intel.com/design/processor/manuals/253667.pdf">Volume 2B: Instruction Set Reference, N-Z</a>, <a href="http://www.intel.com/design/processor/manuals/253668.pdf">Volume 3A: System Programming Guide</a>, <a href="http://www.intel.com/design/processor/manuals/253669.pdf">Volume 3B: System Programming Guide</a> and <a href="http://www.intel.com/design/processor/manuals/248966.pdf">Architectures Optimization Reference Manual</a>. Yes, I know its a lot of reading but they are really interesting and you don&#8217;t have to read the whole thing in order (although I recommend it &#8211; so many interesting facts lye in those pages). Finally, if you are going to develop in assembly (e.g. assemble the source included in this article) I recommend using <a href="http://sourceforge.net/projects/nasm">NASM</a>, as it is the simplest and cleanest assembler (although some people prefer <a href="http://masm32.com/">MASM</a>, which is kind of similar, but a bit more clumsy). If you are going to do some 16-bit DOS programming, you will find <a href="http://www.cs.cmu.edu/~ralf/files.html">Ralf Brown&#8217;s Interrupt List </a>(<a href="http://www.cs.cmu.edu/~ralf/files.html">RBIL</a>) a useful tool.</p>
<p>Throughout this article I will assume basic assembly knowledge (the first chapters of AoA will more than cover everything).</p>
<p><strong><u>The Buzzwords</u></strong></p>
<p><u><em>SIMD</em></u> stands for <u><em>Single Instruction Multiple Data</em></u>.  It is clear that most algorithms require repeating the same operation over and over again (each time on different sets of data). From this observation stemmed the idea of a vector computer or SIMD. We will shortly see that indeed our fireworks program will repeat the same operations many times and so we will be using the Pentium&#8217;s SIMD capabilities for that purpose.</p>
<p><u><em>MMX</em></u> was Intel&#8217;s first attempt at bringing SIMD capabilities to the Pentium. MMX does <em>not </em>stand for anything, but it has been offered several meanings since its appearance (such as Multimedia Extensions). MMX adds 8 new registers (mm0,&#8230;,mm7) to the CPU. These are 64-bit registers. The main advantage of these registers (compared to the x86 general purpose registers) is that the MMX registers can function as <u><em>vector registers</em></u>. This means that each of these registers can represent one 64-bit integer value, two 32-bit integer values, four 16-bit integer values or eight 8-bit integer values. For example, the command:</p>
<p><code>psubusb mm0, mm1</code></p>
<p>is essentially equivalent to 8 byte subtractions (it stands for <u><em>Packed SUBtract Unsigned Saturated Byte</em></u>).</p>
<p>Note that in order to be backward compatible with existing OS&#8217;s (mainly Windows) Intel aliased the MMX registers to the FPU registers. This means that when accessing one of them the contents of the other one are altered as well. This allowed the OS&#8217;s to keep using their old context switching mechanisms.</p>
<p><u><em>SSE</em></u> stands for <u><em>Streaming SIMD Extensions</em></u>. This was Intel&#8217;s second attempt at bringing SIMD to the PC (in response to AMD&#8217;s 3DNow!). SSE added many instructions to the instruction set as well as 16 128-bit vector registers (xmm0,&#8230;,xmm15). Unlike the 8 MMX registers, the SSE registers can contain four 32-bit floating point values. As these registers are not aliased to any existing registers (and so require special care by the OS) they are disabled by default and are only turned on when the OS explicitly commands it.</p>
<p><strong><u>Mode 13h</u></strong></p>
<p>The easiest to program DOS graphics mode is probably mode 13h, which we shall therefore use. In mode 13h, the screen is represented as a 320*200 byte buffer (located in address 0xA000). Each byte in the buffer is an index to a 256 bytes long palette. When mode 13h is enabled, simply writing bytes memory in the range 0xA000-0x19A00 (0x19A0 = 0xA000 + 0xFA00, 0xFA00 = 320*200) will draw pixels on the screen. You should not draw directly to this buffer though, as when the video card is drawing the screen, it scans through this buffer, thereby stalling your write commands. What you should do, is allocate an off-screen buffer and render to this buffer and once in a frame spill the contents of this buffer as quickly as possible to the memory block starting at 0xA000. We will get to this later.</p>
<p>Entering mode 13h is very easy, and is done by calling BIOS function 0&#215;10, as such:</p>
<p><code>mov ax, 0x13<br />
int 0x10</code></p>
<p>Calling BIOS functions is done through raising an interrupt. The parameters are passed in the registers (for more information see RBIL).</p>
<p>The default video mode for DOS is mode 3h. It is the mode of choice for displaying text. So upon program exit we should restore the video mode to mode 3h, as such:</p>
<p><code>mov ax, 3<br />
int 0x10</code></p>
<p><strong><u>The Palette </u></strong></p>
<p>Now, in order to render properly colored fireworks, we need to have a decent color palette. In mode 13h the palette is set by outputting the palette index number to port 0x3c8 and then outputting 3 color values (for the red, green and blue components) to port 0x3c9. Note that if the entire palette is to be set in one go, only index 0 needs to be outputted to port 0x3c8, as it is incremented automatically after three writes to port 0x3c9. Each of the 3 color components is represented by a 7 bit value, it is a number in the range 0-63, where a value of 0 means that the component is not present at all in the color, and a value of 63 means that the component is present with full opacity in the color. So the color pure green will be represented by the tuple (0,63,0). The palette we shall use will consist of a simple linear interpolation from black to red to white. Index 0 will be total black, index 128 will be total red and index 255 will be total white.</p>
<p>A simple program that sets such a palette and then draws it to the screen can be found <a href="http://yaniv.leviathanonline.com/blog/exe/palette.com">here</a> (its source is <a href="http://yaniv.leviathanonline.com/blog/code/palette.asm">here</a>) Our fireworks program will use most of this code. Its output is:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/palette.JPG" alt="palette.JPG" /></p>
<p><strong><u>The Basic Fireworks Program</u></strong></p>
<p>Enough with the introductions &#8211; lets get to business!</p>
<p>The design for the fireworks program is very simple. We will manage a buffer of particles, each having the following qualities: x, y, x_speed, y_speed and color (although this version uses a constant white color for all particles, which looks better). Each particle&#8217;s position will be updated according to its speed, which will in turn be updated according to gravitation.</p>
<p>The full source of the program can be found <a href="http://yaniv.leviathanonline.com/blog/code/fireworks.asm">here</a>. The program itself can be found <a href="http://yaniv.leviathanonline.com/blog/exe/fireworks.com">here</a>. It begins with some <em>define</em>s (you can play with the number of particles by changing the NUM_PARTS <em>define</em>). I then allocate a buffer big enough to contain a copy of the entire screen (we will draw to this buffer, so as to avoid the stalling inherent in writing to the video memory itself). We access the buffer though the es register.</p>
<p>We then enter mode 13h, set the palette and zero the buffer.</p>
<p>We then use a little very useful trick. We call the RDTSC instruction, which reads the CPU&#8217;s 64-bit time-stamp register (this time-stamp register is zeroed upon CPU initialization &#8211; i.e. when you turn on your computer &#8211; and is incremented after every instruction! What do you say, is there a chance of overflow?) into registers EDX:EAX. As NASM does not support the RDTSC instruction I coded it as:</p>
<p><code>db 0x0f, 0x31</code></p>
<p>This trick is very useful, as when writing C++ programs for the PC, it can be used to generate very accurate time-stamps very efficiently. The following code will do the trick in Visual Studio:</p>
<p><code><br />
int RDTSC()<br />
{<br />
     __asm _emit 0x0f;<br />
     __asm _emit 0x31;<br />
}<br />
</code></p>
<p>Lets get back to the fireworks program. We use this trick to generate a random seed for the random number generator (RNG). This RNG will later be used to initialize the particles.</p>
<p>Next, is the <em><u>init_particle </u></em>function, which as its name implies, initializes a particle&#8217;s properties. In order to make the particles look like fireworks I initialize the position of bunches of particles to the same value (using the global_x and global_y variables). The <em>init_particle</em> function accepts a single argument (a pointer to a particle) passed through the bp register.</p>
<p>The <em><u>MAIN</u></em> function updates the particles (and calls <em>init_particle</em> when needed) and then draws the particles to our off-screen buffer.</p>
<p>After all of the particles are drawn, the <em>MAIN</em> function calls two functions which apply filters on our buffer, before displaying it on the screen (by copying our video buffer to address 0xA000).</p>
<p><strong><u>The Filters </u></strong></p>
<p>These filters are very important (and are implemented using MMX!). There are three: <u><em>mmx_shade</em></u>, <u><em>mmx_blur</em></u> and <u><em>mmx_blur_right</em></u>.</p>
<p>The particles are drawn by the <em>MAIN</em> function with a solid white color (i.e. an index of 255). Instead of wiping the screen after each frame, we call the <em>mmx_shade</em> function which decreases the value of all the pixels on the screen by 1. Its code is very simple:</p>
<p><code><br />
mmx_shade:<br />
mov cx, 320*200/8<br />
xor di, di<br />
movq mm1, [sub_mask]<br />
.lop:<br />
 movq mm0, [es:di]<br />
 psubusb mm0, mm1<br />
 movq [es:di], mm0<br />
 add di, 8<br />
 loop .lop<br />
ret<br />
</code></p>
<p>Where,</p>
<p><code>sub_mask: dd 0x01010101, 0x01010101</code></p>
<p>Note how simple this is! First of all we gain a big speed factor as we are processing 8 pixels in each iteration. Even more importantly we use the extremely convenient saturated subtraction instruction. Saturated subtraction means that if the result of the subtraction is negative, then instead of getting the value mod 256, we get 0!</p>
<p>Running the fireworks program with only the <em>mmx_shade</em> filter on, results in this:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/shade_only.JPG" alt="shade_only.JPG" /></p>
<p>Not very impressive yet, but it does look like fireworks! (at least when animated&#8230;)</p>
<p>In order to make our program much nicer, we use two more blurring filters. The <em>mmx_blur</em> function averages the value of all pixels with that of their 4 immediate neighbours (giving twice more weight to the value already in the current pixel). Its code is:</p>
<p><code>mmx_blur:<br />
mov cx, (320*200-330*2)/8<br />
mov di, 328<br />
.lop:<br />
 movq mm0, [es:di]<br />
 movq mm1, [es:di+1]<br />
 movq mm2, [es:di-1]<br />
 movq mm3, mm0<br />
 movq mm4, [es:di-320]<br />
 movq mm5, [es:di+320]</code><code> pavgb mm0, mm1<br />
 pavgb mm3, mm2<br />
 pavgb mm4, mm5<br />
 pavgb mm3, mm4<br />
 pavgb mm0, mm3</code><code> movq [es:di], mm0<br />
 add di, 8<br />
 loop .lop<br />
ret</code></p>
<p>Notice that we skip the first and last lines (plus several extra bytes) in order to keep the function as simple as possible. Those of you with sharper eyes will observe a small issue with this function. In order to properly perform these averages, we need to use a third buffer. As we are scanning through our buffer, we use the results of previous blurs as inputs to the following ones, instead of using the original contents of the buffer. This is not very noticeable, and as it saves us the need to allocate a third buffer it is worth it.</p>
<p>Running the program with the <em>mmx_blur</em> filter applied, as well as the <em>mmx_shade</em> filter, results in this:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/mmx_blur.JPG" alt="mmx_blur.JPG" /></p>
<p>Much nicer! Finally we have the <em>mmx_blur_right</em> function, which is a slight variation of <em>mmx_blur</em>, that gives the fireworks comet like appearance. Its code is self-explanatory:</p>
<p><code><br />
mmx_blur_right:<br />
mov cx, (320*200-330*2)/8<br />
mov di, 328<br />
.lop:<br />
 movq mm0, [es:di]<br />
 movq mm1, [es:di+1]<br />
 movq mm2, [es:di+320]<br />
 movq mm3, [es:di+321]<br />
 pavgb mm0, mm1<br />
 pavgb mm3, mm2<br />
 pavgb mm0, mm3<br />
 movq [es:di], mm0<br />
 add di, 8<br />
 loop .lop<br />
ret</code></p>
<p>The <em>MAIN</em> program switches between the two blur functions once in a while. The result of applying the <em>mmx_blur_right</em> function is:</p>
<p><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/08/mmx_blur_right.JPG" alt="mmx_blur_right.JPG" /></p>
<p><strong><u>Exercises to the Reader</u></strong></p>
<ol>
<li>Change the three filter functions so that they use the 16-byte SSE registers, thus gaining a factor of 2 on these functions&#8217; running time. This is very easy!</li>
<li>Add another offscreen buffer and correctly implement the blurring.</li>
<li>Make the program shorter/cleaner/nicer. Play with the parameters. Change the palette. Enjoy!</li>
</ol>
<p>I hope that you now have a decent understanding of SIMD and how to use it when programming the Pentium!</p>
<p>PS &#8211; in case you want to assemble the source use the following command:</p>
<p><code>nasmw.exe fireworks.asm -o fireworks.com</code></p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/comp/simd-fireworks/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>I&#8217;m Back (and so is Phrack)!</title>
		<link>http://yaniv.leviathanonline.com/blog/comp/im-back-and-so-is-phrack/</link>
		<comments>http://yaniv.leviathanonline.com/blog/comp/im-back-and-so-is-phrack/#comments</comments>
		<pubDate>Thu, 19 Jul 2007 01:42:26 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/comp/im-back-and-so-is-phrack/</guid>
		<description><![CDATA[ Hi everyone! As you may have noticed, yaniv.leviathanonline.com has not been updated for a while (exactly one month, pour être précis). This was largely due to my intense exam period. First, I want to thank you for all the interesting ideas you sent me. This extended period of not updating my site resulted in an extremely long idea-list &#8211; so stay tuned! Now, apart from me,  Phrack, which was also on a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/07/blond_small.jpg" title="blond_small.jpg"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/07/blond_small.jpg" alt="blond_small.jpg" /></a> Hi everyone!</p>
<p>As you may have noticed, <em><strong><a href="http://yaniv.leviathanonline.com">yaniv.leviathanonline.com</a></strong></em> has not been updated for a while (<em>exactly one month</em>, pour être précis). This was largely due to my intense exam period.</p>
<p>First, I want to thank you for all the interesting ideas you sent me. This extended period of not updating my site resulted in an extremely long idea-list &#8211; so stay tuned!</p>
<p>Now, apart from me, <a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/phrack-logo.jpg" title="phrack-logo.jpg"><img align="middle" src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/phrack-logo.thumbnail.jpg" alt="phrack-logo.jpg" title="phrack-logo.jpg" /></a> <a href="http://www.phrack.org/">Phrack</a>, which was also on a long vacation, is now back.</p>
<p>I must admit that the new issue #64 does not appear to contain anything ground-breaking, but it deserves a quick read (if only for times past).</p>
<p>For those of you that don&#8217;t know Phrack, I can only recommend that you browse its outstanding articles&#8217; archive since the very first issue on November 17, 1985 (I was exactly 3 years and one day old then&#8230;).</p>
<p>Should you not be interested in hacking or general anarchy, and thus choose not to read all of the issues, at least be sure not to miss the famous Phrack #49&#8242;s <a href="http://www.phrack.org/issues.html?issue=49&amp;id=14#article">Smashing The Stack For Fun And Profit</a>. To get an idea of the Phrack spirit, I also recommend reading the <a href="http://www.phrack.org/issues.html?issue=7&amp;id=3#article">Hacker&#8217;s Manifesto</a> and <a href="http://www.phrack.org/issues.html?issue=45&amp;id=19">Screwing over your local McDonald&#8217;s</a>.</p>
<p>See you soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/comp/im-back-and-so-is-phrack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure Computing &#8211; Part I</title>
		<link>http://yaniv.leviathanonline.com/blog/math/secure-computing-part-i/</link>
		<comments>http://yaniv.leviathanonline.com/blog/math/secure-computing-part-i/#comments</comments>
		<pubDate>Thu, 07 Jun 2007 16:51:00 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/uncategorized/secure-computing-part-i/</guid>
		<description><![CDATA[This article is the first among a series of articles describing the subject of Secure Computing. The material was mainly taken from a Cryptography course by Amos Fiat. Say we have a function F(x1,x2,&#8230;,xn)-&#62;(y1,y2,&#8230;,yn) that takes n inputs and has n outputs. Me and n-1 of my friends (i.e. we are n people in total) have secret numbers. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/whereswaldo.jpg" title="Wheres Waldo?"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/whereswaldo.thumbnail.jpg" alt="Wheres Waldo?" /></a>This article is the first among a series of articles describing the subject of Secure Computing. The material was mainly taken from a Cryptography course by Amos Fiat.</p>
<p>Say we have a function F(x1,x2,&#8230;,xn)-&gt;(y1,y2,&#8230;,yn) that takes n inputs and has n outputs. Me and n-1 of my friends (i.e. we are n people in total) have secret numbers. Lets number the people p1,&#8230;,pn and the secret numbers x1,&#8230;,xn (i.e. person pi knows secret number xi). We want to perform a process after which person pi will know yi, where yi is the i&#8217;th output of F computed on the xi&#8217;s, <strong><u>but he must not know anything else</u></strong>. Let me give you an example:</p>
<p>Say that there are 3 people, each having a monthly salary of xi dollars (for i=1,2,3). They want person number 1 to know the sum of the salaries, person 2 to know the product of the salaries and person 3 to know the maximum of the salaries. But they do not want to reveal their salaries to each other!</p>
<p>A simple solution would be to find a new and neutral person that all of the men trust. They would then reveal to him all of their salaries, one by one, and he will perform the calculation and tell them the results. The goal of this series of articles is to solve this problem without using such a <em><u>trusted party</u></em>.</p>
<p>Before we begin to think of a solution, lets notice some inherent problems:</p>
<ul>
<li><em>The men can lie about their salaries</em>. Since it is assumed that only person pi knows xi, he can lie about it (i.e. input another number, say xi&#8217; instead of xi). There is obviously nothing that can be done about it. We will therefore assume all the men (while they may try to cheat at other parts of the protocol) will input their true numbers to it.</li>
<li><em>The function itself may leak back information about the secret numbers of the other people</em>. For example, if there are only 2 people, and y1 is the sum of the xi&#8217;s and y2 is their product, then after the process each of the men will know the secret number of the other (as the function is reversible). This is simply not considered a problem, as our goal was to do without the trusted party, and if for some reason the function is reversible (or semi-reversible) then the same problem will arise with the trusted party protocol, which is what we are trying to emulate.</li>
</ul>
<p>The solution will consist of several parts (which will be dealt with in the other parts of this topic):</p>
<ol>
<li>Performing a Zero Knowledge Proof (ZKP) of a generic NPC problem. </li>
<li>The &#8220;Oblivious Transfer&#8221; protocol.</li>
<li>Transforming a general function f(x1,&#8230;,xn) to a circuit consisting only of XOR gates and AND gates.</li>
<li>Solving our problem for the specific cases where our function is a XOR gate or an AND gate.</li>
</ol>
<p>So now, after we have set our goals, lets dive in to the the first step:</p>
<p><strong><u>Zero Knowledge Proof of an NPC Problem</u></strong></p>
<p>At this point, I rather not formally define the exact meaning of a ZKP. I will instead try to explain is intuitively. Say I know the answer to a complicated puzzle and you don&#8217;t. The process of me convincing you that I know the answer, <u><strong>without you learning anything about it</strong></u>, is called a Zero Knowledge Proof.</p>
<p>Let me give you this neat example (taken from <a target="_blank" href="http://www.wisdom.weizmann.ac.il/~naor/PUZZLES/waldo.html">Applied Kid Cryptography</a>). Say we are playing the game of <em><strong><a target="_blank" href="http://en.wikipedia.org/wiki/Where's_Waldo">Where&#8217;s Waldo?</a></strong></em> with this picture:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/waldo.jpg" title="waldo.jpg"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/waldo.jpg" alt="waldo.jpg" /></a></p>
<p>After minutes of contemplation, I suddenly find him! The following dialog then takes place between us:</p>
<p>Me: &#8220;Yes! I found him! Wow, he was really well hidden.&#8221;</p>
<p>You: &#8220;I don&#8217;t believe you! Its too hard! You must be lying!&#8221;</p>
<p>Me: &#8220;No, seriously. He&#8217;s right there, next to the&#8230;&#8221;</p>
<p>You: &#8220;Go on &#8211; Where is he?!&#8221;</p>
<p>Me: &#8220;Well, I do not want to ruin this for you&#8230; This is such a cool puzzle&#8230;&#8221;</p>
<p>You: &#8220;I knew it! You are lying &#8211; you haven&#8217;t found him.&#8221;</p>
<p>The situation becomes frustrating for me! How can I prove to you that I know where Waldo is without revealing his location?</p>
<p>I can give you a general fact about his location (for example, that he is near the center of the picture and not near the borders) and later when you will find him too, you will be able to verify that I was indeed right.</p>
<p>There are obvious drawbacks with this method:</p>
<ul>
<li>While not revealing exactly where Waldo is, a lot of information is still leaked (you now know not to look for him in the sides of the image).</li>
<li>I can lie to you with a good probability &#8211; even if I haven&#8217;t found him my general statement may be right.</li>
<li>And finally, the biggest drawback is that you may still not be convinced (i.e. we have to wait for you to find him as well).</li>
</ul>
<p>Suddenly it hits me! I know what to do! I take a big white piece of paper (much bigger than the original image, say twice as big in every direction). I then place the original image at a random location beneath it and cutout Waldo&#8217;s location from the paper. I then place another big piece of paper on top of everything (this time, without the cutout):</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/waldo_ilust.gif" title="waldo_ilust.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/waldo_ilust.gif" alt="waldo_ilust.gif" /></a></p>
<p>In my illustration the covering papers have the same size as the original image, but they should  be much bigger in reality.</p>
<p>You then choose a number: 1 or 2. If you choose 1, I remove both pieces of paper, revealing to you the entire image. If you choose 2, I remove only the top piece of paper, revealing to you that I know where Waldo is, as such:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/waldo_cover.gif" title="waldo_cover.gif"><img align="middle" src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/waldo_cover.thumbnail.gif" alt="waldo_cover.gif" title="waldo_cover.gif" /></a> (click thumbnail for big image)</p>
<p>What does this accomplish? Well, first of all, if indeed I know where Waldo is I can answer both of your questions. If, on the other hand, I was lying, and I put the original image under the papers, then I could not have cut out Waldo&#8217;s location. In order to avoid this, I could have replaced the underlying image all together (as you do not see it at all!) with another image, in which I know where Waldo is. In this case, should you ask me to show you where Waldo is, I will be able to do so, but I will get busted if you selected 1, and made me reveal to you the entire image.</p>
<p>What we got is this:</p>
<ul>
<li>If I know where Waldo is, I can deliver a correct answer that you can verify 100% of the time.</li>
<li>If I am lying and I do not know where Waldo is, you will bust me (no matter what I&#8217;ll do) with a probability of at least 1/2.</li>
</ul>
<p>Well, being busted with a probability of only 1/2 is not very bad, but notice that we can repeat the process any number of times (each time placing the white papers at different locations over the original image). My chances of being correct are independent in each of the times, and so I will get busted with a probability (1/2)^n (where n is the number of iterations). If n is chosen high enough, you can be quite certain that I am not lying (10 iterations suffice for the probability of missing a liar to be less the 1/1000).</p>
<p class="sidenote">Note that the process is not really &#8220;Zero Knowledge&#8221; as by looking at the cutout version of Waldo you get an idea of his immediate surroundings and of his own posture (indeed, my cutout image above helps a little in finding him).</p>
<p>In the next installment of the series I will further discuss the notion of ZKP, especially in relation to solutions of NPC problems.</p>
<p><em>To be continued&#8230;</em></p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/math/secure-computing-part-i/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding Soccer</title>
		<link>http://yaniv.leviathanonline.com/blog/math/understanding-soccer/</link>
		<comments>http://yaniv.leviathanonline.com/blog/math/understanding-soccer/#comments</comments>
		<pubDate>Sun, 03 Jun 2007 16:44:02 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/math/understanding-soccer/</guid>
		<description><![CDATA[In 1998 (I can&#8217;t believe it was so long ago!) I was working at MATE (Media Access Technologies), an Israeli start-up at the time, specialising in face recognition and video searching. It was then that I came to know one of the coolest tricks in image recognition - the Hough Transform (pronounced &#8220;huf transform&#8220;). In this article, I [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/soccer_ball.gif" title="soccer_ball.gif"></a><a rel="attachment wp-att-40" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/resgif/" title="res.gif"></a><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/merged.gif" title="merged.gif"></a><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_res.GIF" title="a_res.GIF"></a><a rel="attachment wp-att-47" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/a_mergedgif/" title="a_merged.GIF"></a><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/soccer_ball.gif" title="soccer_ball.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/soccer_ball.gif" alt="soccer_ball.gif" title="soccer_ball.gif" /></a>In 1998 (I can&#8217;t believe it was so long ago!) I was working at MATE (Media Access Technologies), an Israeli start-up at the time, specialising in face recognition and video searching. It was then that I came to know one of the coolest tricks in image recognition - the <strong><u>Hough Transform</u></strong> (pronounced &#8220;<em>huf transform</em>&#8220;).</p>
<p>In this article, I will demonstrate the algorithm with the following example:</p>
<p>Say you want to write a program that watches soccer. The input to your program is a sequence of frames from the game. The output should be the locations of all the players at all times. Given a frame of soccer, you first need to locate the players in the frame (i.e. you should know that a certain player occupies a certain set of pixels). Next, you need to know what location in the world is represented by those pixels. In order to do that, you need to figure out where the camera is looking at. In this article I will focus on this part of the problem (understanding the view point and direction). I will not deal with the (easier) part of determining what pixels are occupied by players.</p>
<p>Consider the following image of Ronaldinho:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/nike-ronaldinho.jpg" title="nike-ronaldinho.jpg"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/nike-ronaldinho.jpg" alt="nike-ronaldinho.jpg" /></a><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/nike-ronaldinho.jpg" title="nike-ronaldinho.jpg"></a></p>
<p>I manually transformed it to this:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/nike-ronaldinho_small.jpg" title="nike-ronaldinho_small.jpg"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/nike-ronaldinho_small.jpg" alt="nike-ronaldinho_small.jpg" /></a></p>
<p>(the portion of the image covered by grass). I think it is clear how this step can be automatized.</p>
<p>Next I applied an automatic algorithm that got me this:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/bw.gif" title="bw.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/05/bw.gif" alt="bw.gif" /></a></p>
<p>(the same image converted to black and white, for all the pixels that were bright enough). My algorithm simply turned all the pixels that are brighter than the color (80,80,20) (<a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/thresh1.gif" title="Hough Thresh 1"><img align="middle" src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/thresh1.gif" alt="Hough Thresh 1" title="Hough Thresh 1" /></a>) on a per channel basis to white, and all the other pixels to black. Note that my threshold color requires a high value of the red component, which is not present in the green grass, in order to turn the grass itself to black.</p>
<p>Lets return to our original problem &#8211; determining the point and direction of view (POV). We have big clues in the picture for determining the POV, namely the lines on the ground. Note that from the lines on the ground in the black and white picture, it is easy to see that Ronaldinho is standing in the center of the field. Can we somehow detect them?</p>
<p>Lets formulate the following abstact problem:</p>
<p>You are given a matrix <em>M</em> over <em>Z2</em> (i.e. a matrix of bits). The matrix represents an image. Pixel <em>Pij</em> of the image is white if <em>Mij</em> is 0 and black if <em>Mij</em>is 1. The image contains straight lines. The lines are not perfect (i.e. they may overlap, they may not be continuous and there is a lot of noise). Your goal is to develop an efficient algorithm that receives the matrix and outputs the line equations.</p>
<p><strong>Please take some time to think about this before continuing to read. If you spend enough time thinking about it, you will probably reach the conclusion that this is a really though problem.</strong></p>
<p>A solution to this problem is the Hough Transform. The Hough Transform consists of noticing a duality of the Euclidean plane. We Consider a the straight line equation:</p>
<p><em>y = m * x + b</em></p>
<p>In this equation <em>m</em> and <em>b</em> are constants and <em>x</em> and <em>y</em> are variables. But what happens if we make <em>x</em> and <em>y</em> constants and <em>m</em> and <em>b</em> variables?</p>
<p>Well, the set of <em>m&#8217;</em>s and <em>b&#8217;</em>s that satisfy the equation represents all the lines that pass through our point <em>(x, y)</em>!</p>
<p>It is easy to see that for each point in the <em>x-y</em> plane we get a line in the <em>b-m</em> plane, namely, the line:</p>
<p><em>b = -x * m + y</em></p>
<p>Now each line in the <em>x-y</em> plane is matched with a point in the <em>b-m</em> plane! The duality depicted:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/duality.gif" title="Duality"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/duality.gif" alt="Duality" /></a></p>
<p>So the algorithm basically says:</p>
<ul>
<li>Run through the original matrix.</li>
<li>For each pixel <em>(x,y)</em> that is white draw the line that matches it in the dual plane.</li>
<li>Then count the number of line intersections in the dual plane.</li>
<li>All points at which there is an intersection of more than <em>T</em> lines (these correspond to lines in the <em>x-y</em> plane on which we have more than <em>T</em> points in our original image) are considered valid lines.</li>
</ul>
<p>To better illustrate the algorithm, I jotted down a few lines of python. The results follow (I must say that I was really surprised that it worked perfectly the first time around! All the threshold values I picked were somehow correct on the first go <img src='http://leviathanonline.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ).</p>
<p>Note that there is an implementation problem with using the <em>b-m</em> plane - <em>Precision issues</em>. For example, a near vertical line has huge values of m. In order to solve this, I used another duality (which is completely equivalent): the duality of the <em>x-y</em> plane and the <em>a-c</em> plane, where <em>a</em> is the angle of the line with the <em>x</em> axis (i.e. <em>m = tan(a)</em>), and <em>c</em> is <em>b*cos(a)</em>.</p>
<p>The Hough map (i.e. the result of the Hough Transform) my script produced is:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/hough_org.gif" title="hough_org.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/hough_org.gif" alt="hough_org.gif" /></a></p>
<p>Since it is kind of hard to distinguish the different color values, I generated a more human-friendly version (all the values are multiplied by 15):</p>
<p><a rel="attachment wp-att-39" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/houghgif/" title="hough.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/hough.gif" alt="hough.gif" /></a></p>
<p>And finally, the result (after converting back to the <em>x-y</em> plane):</p>
<p><a rel="attachment wp-att-40" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/resgif/" title="res.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/res.gif" alt="res.gif" /></a></p>
<p>And the same result overlayed on the original image:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/merged.gif" title="merged.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/merged.gif" alt="merged.gif" /></a></p>
<p>A perfect match! </p>
<p>This is a big subject, and I only covered a small part of it. I will update this article in the near future with a more detailed analysis. If you have specific questions please post them as comments and I promise I will answer!</p>
<p>Meanwhile, let me just point out that the same method can be used to detect other shapes (e.g. circles). The generalization is trivial.</p>
<p>I will finish by showing the results of running the script on another image. Note that in this case, the threshold values are a little off. The results are nevertheless impressive:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_small.jpg" title="a_small.jpg"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_small.jpg" alt="a_small.jpg" /></a></p>
<p>The black and white image generated was:</p>
<p><a rel="attachment wp-att-44" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/a_bwgif/" title="a_bw.gif"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_bw.gif" alt="a_bw.gif" /></a></p>
<p>The Hough map:</p>
<p><a rel="attachment wp-att-45" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/a_houghgif/" title="a_hough.GIF"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_hough.GIF" alt="a_hough.GIF" /></a></p>
<p>The result:</p>
<p><a href="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_res.GIF" title="a_res.GIF"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_res.GIF" alt="a_res.GIF" /></a></p>
<p>And, finally, the overlayed result:</p>
<p><a rel="attachment wp-att-47" href="http://yaniv.leviathanonline.com/blog/math/understanding-soccer/attachment/a_mergedgif/" title="a_merged.GIF"><img src="http://leviathanonline.com/wordpress/wp-content/uploads/2007/06/a_merged.GIF" alt="a_merged.GIF" /></a></p>
<p>To be updated&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/math/understanding-soccer/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Perl vs. Python One-Liner</title>
		<link>http://yaniv.leviathanonline.com/blog/riddles/perl-vs-python-one-liner/</link>
		<comments>http://yaniv.leviathanonline.com/blog/riddles/perl-vs-python-one-liner/#comments</comments>
		<pubDate>Sat, 19 May 2007 22:45:11 +0000</pubDate>
		<dc:creator>yaniv</dc:creator>
				<category><![CDATA[Comp]]></category>
		<category><![CDATA[Riddles]]></category>

		<guid isPermaLink="false">http://yaniv.leviathanonline.com/blog/riddles/perl-vs-python-one-liner/</guid>
		<description><![CDATA[A few years ago a friend of mine asked me the following Perl riddle. Unfortunately, in order to solve it you must know Perl. As I like Python much better, I translated the riddle to Python. Attached are both versions. I admit the Perl version is a bit more cryptic and if you know both Perl and Python you [...]]]></description>
			<content:encoded><![CDATA[<p>A few years ago a friend of mine asked me the following Perl riddle. Unfortunately, in order to solve it you must know Perl. As I like Python much better, I translated the riddle to Python. Attached are both versions.</p>
<p>I admit the Perl version is a bit more cryptic and if you know both Perl and Python you should try to solve the Perl version (but use Python for everything else in life <img src='http://leviathanonline.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ).</p>
<p>Oh, and try to solve the riddle without running it (run it only as a last resort).</p>
<p><img align="middle" width="145" src="http://yaniv.leviathanonline.com/blog/images/perl_logo2.gif" alt="Perl Logo" height="75" style="width: 145px; height: 75px" title="Perl Logo" /></p>
<p><code>perl -wle 'print "True" if (1 x shift) !~ /^1?$|^(11+?)\1+$/' [number]</code></p>
<p><img align="middle" width="149" src="http://yaniv.leviathanonline.com/blog/images/python-logo.png" alt="Python Logo" height="148" style="width: 149px; height: 148px" title="Python Logo" /></p>
<p><code>python -c "import sys, re; print None == re.match('^1?$|^(11+?)\\1+$','1'*int(sys.argv[1]))" [number]</code></p>
<p>To alleviate all doubt &#8211; [number] denotes a numeric command line argument (e.g. 17).</p>
]]></content:encoded>
			<wfw:commentRss>http://yaniv.leviathanonline.com/blog/riddles/perl-vs-python-one-liner/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

