<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" version="2.0"><channel><title>Alex Bowe . com</title><description>Programming, Mathematics, Data, etc...</description><link>https://www.alexbowe.com/</link><image><url>https://www.alexbowe.com/favicon.png</url><title>alexbowe.com</title><link>https://www.alexbowe.com/</link></image><generator>Ghost 6.44</generator><lastBuildDate>Tue, 09 Jun 2026 08:22:46 GMT</lastBuildDate><atom:link href="https://www.alexbowe.com/articles/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Iterative Tree Traversal]]></title><description><![CDATA[By memorizing a simple implementation of iterative tree traversal we simplify a large number of programming interview questions.]]></description><link>https://www.alexbowe.com/iterative-tree-traversal/</link><guid isPermaLink="false">61d153a48ffb7c003b6246e7</guid><category><![CDATA[python]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[trees]]></category><category><![CDATA[programming interviews]]></category><category><![CDATA[learning]]></category><category><![CDATA[graph search]]></category><category><![CDATA[fundamentals]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Sat, 15 Jan 2022 03:16:29 GMT</pubDate><media:content medium="image" url="https://images.unsplash.com/photo-1475359524104-d101d02a042b?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDd8fFRyZWVzfGVufDB8fHx8MTY0MTEwOTMxNg&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=2000"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><h1 id="introduction">Introduction</h1>
<img src="https://images.unsplash.com/photo-1475359524104-d101d02a042b?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDd8fFRyZWVzfGVufDB8fHx8MTY0MTEwOTMxNg&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=2000" alt="Iterative Tree Traversal"><p>One common programming interview problem asks candidates to write an in-order binary tree traversal without using recursion (<a href="https://leetcode.com/problems/binary-tree-inorder-traversal/?ref=alexbowe.com">LeetCode #94</a>).</p>
<p>It&apos;s a deceptively simple problem, but I&apos;ll admit that I struggled the first time I saw it. It was a pen-and-paper interview, and I fumbled through it for a while before giving up and writing a recursive version, giving this excuse in the margin: &#x201C;the recursive version is tidier - why wouldn&#x2019;t you write it this way?&#x201D;. Nice save<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>.</p>
<p>Some of the online solutions to this are pretty unintuitive, so in this article I&apos;ll describe an approach that is easy to memorize or re-derive if needed. I&apos;ve used this code verbatim in a surprising number of interview questions (some are in the <a href="#examples">Examples</a> section). Here are some reasons you might want to do the same:</p>
<ol>
<li>
<p><strong><a href="https://refactoring.guru/design-patterns/iterator?ref=alexbowe.com">Iterators</a> decouple traversal logic from the calculation logic.</strong> Factoring code into units of <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle?ref=alexbowe.com">single responsibilities</a> improves readability and reusability (useful in coding, but also the <a href="https://www.dashe.com/blog/learning/chunking-memory-retention/?ref=alexbowe.com">chunking</a> technique used in rapid learning). Doing this in an interview signals good code hygiene, and can allow you to write less code (saving precious time)<sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup>. Admittedly, <em>iterators</em> don&apos;t have to be <em>iterative</em>, but by doing it iteratively...</p>
</li>
<li>
<p><strong>You cover your bases.</strong> By making our iterators iterative we increase the number of questions we can mindlessly<sup class="footnote-ref"><a href="#fn3" id="fnref3">[3]</a></sup> apply it to. If you are asked to write a recursive version specifically, you can just do that instead (it should be easier anyway).</p>
</li>
<li>
<p><strong>Avoiding recursion can prevent a <a href="https://en.wikipedia.org/wiki/Stack_overflow?ref=alexbowe.com">stack overflow</a>.</strong> Operating Systems <a href="https://www.guru99.com/stack-vs-heap.html?ref=alexbowe.com">limit stack space</a>, and the typical recursive approach has non-optimizable <a href="https://en.wikipedia.org/wiki/Tail_call?ref=alexbowe.com">tail calls</a>, so we might face issues with large datasets. This is the main reason why you&apos;d want to avoid recursion at all.</p>
</li>
<li>
<p><strong>The wisdom of Earl Sweatshirt (<a href="https://twitter.com/earlxsweat/status/476033445320474624?ref=alexbowe.com">Source</a>):</strong></p>
<blockquote>
<p>Get your fundamentals on lock so that you can start getting into the ill advanced shit. This is universally applicable.</p>
</blockquote>
</li>
</ol>
<p>Let&apos;s get our fundamentals on lock!</p>
<h1 id="implementation">Implementation</h1>
<h2 id="recursive">Recursive</h2>
<p>No doubt you&#x2019;ve seen recursive in-order tree traversal countless times, so let me instead give an example of an in-order <a href="https://refactoring.guru/design-patterns/iterator?ref=alexbowe.com">iterator</a> using Python 3.3&apos;s <a href="https://www.python.org/dev/peps/pep-0380/?ref=alexbowe.com"><code>yield from</code></a> syntax:</p>
<pre><code class="language-py">def inorder(root):
    if not root: return
    yield from inorder(root.left)
    yield root
    yield from inorder(root.right)
</code></pre>
<p><em>Note: we <code>yield root</code> instead of <code>yield root.value</code> so that we can access the children if needed (like in <a href="#count-the-number-of-leaf-nodes-in-a-binary-tree">the second example below</a>).</em></p>
<p>By separating our traversal logic from the rest of our logic we end up with code that is easier to read and re-combine (see the <a href="#examples">examples</a>). But we haven&apos;t answered the question - it is still recursive! If we implement it iteratively we can use the same code in more problems.</p>
<p><em>I recommend attempting to write an iterative version yourself before continuing (that link again: <a href="https://leetcode.com/problems/binary-tree-inorder-traversal/?ref=alexbowe.com">LeetCode #94</a>). Pain (or slight discomfort) is the best teacher.</em></p>
<h2 id="iterative">Iterative</h2>
<p>All recursive functions can be written iteratively. In fact, like a compiler, we can <a href="https://www.baeldung.com/cs/convert-recursion-to-iteration?ref=alexbowe.com">mechanically convert our function calls to use an explicit stack</a>, but readability/memorability will likely suffer.</p>
<p>While there are other iterative implementations (like <a href="https://www.codeproject.com/tips/723337/depth-first-search-dfs-non-recursive?ref=alexbowe.com">this one</a> using nested loops), I prefer the one below since it is less surprising<sup class="footnote-ref"><a href="#fn4" id="fnref4">[4]</a></sup>, hence easier to remember or re-derive.</p>
<p>We start with a function to define the general approach:</p>
<pre><code class="language-py">def tree_iterator(root, expand):
    frontier = [(False, root)]
    while frontier:
        expanded, curr = frontier.pop()
        if not curr: continue
        if expanded: yield curr
        else: frontier.extend((x is curr, x) for x in reversed(expand(curr)))
</code></pre>
<p>This is just a Depth-First traversal<sup class="footnote-ref"><a href="#fn5" id="fnref5">[5]</a></sup> function, where an <code>expand</code> function provides the order we would like to visit the children and parent, which are then <code>reversed()</code> because stacks are LIFO (so nodes will be popped in reverse).</p>
<p>We don&apos;t use a visited set, since trees are acyclic, but we do mark the nodes as expanded or not so that we can re-visit each parent without expanding it twice.</p>
<p>We can then use <code>tree_iterator</code> to define pre-order, in-order, and post-order:</p>
<pre><code class="language-py">preorder  = lambda root: tree_iterator(root, lambda node: (node,      node.left,  node.right))
inorder   = lambda root: tree_iterator(root, lambda node: (node.left, node,       node.right))
postorder = lambda root: tree_iterator(root, lambda node: (node.left, node.right, node))
</code></pre>
<p>And their <a href="https://en.wikipedia.org/wiki/Tree_traversal?ref=alexbowe.com#Reverse_pre-order,_NRL">reversals</a>:</p>
<pre><code class="language-py">reverse_preorder  = lambda root: tree_iterator(root, lambda node: (node,       node.right, node.left))
reverse_inorder   = lambda root: tree_iterator(root, lambda node: (node.right, node,       node.left))
reverse_postorder = lambda root: tree_iterator(root, lambda node: (node.right, node.left,  node))
</code></pre>
<p>Each function is almost identical - all you have to do is remember the expansion order.</p>
<h1 id="examples">Examples</h1>
<p>Here&apos;s a handful of example problems that are simplified by the above functions:</p>
<h2 id="count-the-number-of-nodes-in-a-binary-tree">Count the number of nodes in a Binary Tree</h2>
<pre><code class="language-py">sum(1 for _ in inorder(tree))
</code></pre>
<h2 id="count-the-number-of-leaf-nodes-in-a-binary-tree">Count the number of leaf nodes in a Binary Tree</h2>
<pre><code class="language-py">is_leaf = lambda x: not x.left and not x.right
sum(1 for x in inorder(root) if is_leaf(x)))
</code></pre>
<p>This is a good example of why our iterators yield the node instead of the value.</p>
<h2 id="flatten-a-binary-search-tree-into-an-ordered-list">Flatten a Binary Search Tree into an Ordered List</h2>
<pre><code class="language-py">[x.value for x in inorder(tree)]
</code></pre>
<h2 id="verify-that-a-binary-tree-is-a-binary-search-tree">Verify that a Binary Tree is a Binary Search Tree</h2>
<pre><code class="language-py">from itertools import pairwise
is_ordered = lambda xs: all(a&lt;=b for a,b in pairwise(xs))
is_ordered(x.value for x in inorder(tree))
</code></pre>
<p><em>Note: <a href="https://docs.python.org/3/library/itertools.html?ref=alexbowe.com"><code>itertools</code></a> is probably one of the most useful modules in the Python standard library - get to know it intimately.</em></p>
<h2 id="find-the-kth-smallest-element-of-binary-search-tree">Find the kth-smallest element of Binary Search Tree</h2>
<pre><code class="language-py">next(x.value for i,x in enumerate(inorder(root)) if i == k-1)
</code></pre>
<h2 id="find-the-kth-largest-element-of-binary-search-tree">Find the kth-largest element of Binary Search Tree</h2>
<pre><code class="language-py">next(x.value for i,x in enumerate(reverse_inorder(root)) if i == k-1)
</code></pre>
<h2 id="check-if-a-binary-tree-is-symmetrical">Check if a Binary Tree is Symmetrical</h2>
<pre><code class="language-py">from itertools import zip_longest
all(a.value == b.value for a,b in zip_longest(inorder(tree_a), reverse_inorder(tree_b)))
</code></pre>
<p>And of course the questions that ask for iterative versions of these, and the traversals themselves.</p>
<p>This is only a small sample of problems - if you find more examples please share them in the comments below!</p>
<h1 id="conclusion">Conclusion</h1>
<p>Although the code is a little more complicated than the standard recursive approach, by implementing a non-recursive tree traversal iterator we can reuse the exact same code for a large amount of problems.</p>
<p>Try it out on some <a href="https://leetcode.com/tag/tree/?ref=alexbowe.com">LeetCode tree questions</a> for yourself and see if this approach lends itself to better solutions, and share any questions that benefit in the comments.</p>
<p>But don&apos;t stop there. Identifying patterns and <a href="https://coda.io/@atc/the-4-hour-chef-learn-anything-by-tim-ferriss/cafe-24?ref=alexbowe.com">compressing</a> them into general solutions like this is an important part of <a href="https://fs.blog/deliberate-practice-guide/?ref=alexbowe.com">deliberate practice</a>. Get into the habit of repeating problems and solving them in new ways. Play <a href="https://en.wikipedia.org/wiki/Code_golf?ref=alexbowe.com">Code Golf</a> with yourself, and save the functions that you keep finding a use for<sup class="footnote-ref"><a href="#fn6" id="fnref6">[6]</a></sup>. Share those in the comments too!</p>
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>Try to not be like I was back then. <a href="https://en.wikipedia.org/wiki/Intellectual_humility?ref=alexbowe.com">Intellectual Humility</a> helps you learn faster, and makes you more enjoyable to work with :) <a href="#fnref1" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn2" class="footnote-item"><p>This is true due to the potential for code reuse, but also, when I&#x2019;m interviewing someone and they use a <code>helper(x)</code> function before implementing it, I sometimes ask them to skip implementing it in order to increase the <a href="https://en.wikipedia.org/wiki/Signal-to-noise_ratio?ref=alexbowe.com#Other_uses">signal-to-noise ratio</a>. We only have an hour for an interview and need to be selective about what we assess. <a href="#fnref2" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn3" class="footnote-item"><p>Many people dislike the element of rote learning present in programming interviews today. While it is true that there should be better ways to gauge a mutual fit, the reality is that it&apos;s the current <a href="https://en.wikipedia.org/wiki/Metagaming?ref=alexbowe.com">meta</a> of the game we want to play, so is mostly unavoidable right now. However, repetition can help cache patterns so you can apply them more readily - in or out of an interview - so doing this isn&apos;t wasted time. <a href="#fnref3" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn4" class="footnote-item"><p><a href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment?ref=alexbowe.com">The Principle of Least Astonishment</a> is a UI design concept, but what is code if not a way for programmers to interface with both computers and other programmers? A fun hobbie is to go through <a href="https://lawsofux.com/?ref=alexbowe.com">UI/UX concepts</a> and see how they apply to code. <a href="#fnref4" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn5" class="footnote-item"><p>In-order, pre-order, and post-order are all Depth-First, whereas level-order is Breadth-First. <a href="#fnref5" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn6" class="footnote-item"><p>I&apos;ve started using <a href="https://cacher.io/?ref=alexbowe.com">Cacher</a> to collect code snippets, but <a href="gist.github.com">gists</a> are great too. <a href="#fnref6" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
</ol>
</section>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[How to Recover a Bitcoin Passphrase]]></title><description><![CDATA[How I recovered a Bitcoin passphrase by performing a Breadth-First search on typos of increasing Damerau-Levenshtein distances from an initial guess.]]></description><link>https://www.alexbowe.com/bitcoin-passphrase-recovery/</link><guid isPermaLink="false">619714f2c62458003bddca75</guid><category><![CDATA[bitcoin]]></category><category><![CDATA[cracking]]></category><category><![CDATA[edit distance]]></category><category><![CDATA[graph search]]></category><category><![CDATA[linguistics]]></category><category><![CDATA[python]]></category><category><![CDATA[cryptocurrency]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Wed, 09 Jun 2021 13:13:47 GMT</pubDate><media:content medium="image" url="https://images.unsplash.com/photo-1519162584292-56dfc9eb5db4?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDR8fGJpdGNvaW58ZW58MHx8fHwxNjQyMjE3NjAw&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=2000"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><h2 id="abstract">Abstract</h2>
<img src="https://images.unsplash.com/photo-1519162584292-56dfc9eb5db4?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDR8fGJpdGNvaW58ZW58MHx8fHwxNjQyMjE3NjAw&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=2000" alt="How to Recover a Bitcoin Passphrase"><p>In this post I recover a Bitcoin passphrase by performing a <a href="https://en.wikipedia.org/wiki/Breadth-first_search?ref=alexbowe.com">Breadth-First search</a> on typos of increasing <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance?ref=alexbowe.com">Damerau-Levenshtein distances</a> from an initial guess. This order was chosen because the <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance?ref=alexbowe.com">Damerau-Levenshtein distances</a> in typos follow a <a href="https://en.wikipedia.org/wiki/Zipf%27s_law?ref=alexbowe.com">Zipf distribution</a>, so the most likely typos will be tested first. This improves on (but does not replace) <a href="https://github.com/3rdIteration/btcrecover/?ref=alexbowe.com">BTCRecover</a>, which has a limited definition of a typo. The code is simple to read and modify, and is available on <a href="https://github.com/alexbowe/bitcoin-passphrase-cracker?ref=alexbowe.com">GitHub</a>.</p>
<h2 id="intro">Intro</h2>
<p>The promise of Bitcoin is a <a href="https://en.wikipedia.org/wiki/Hard_currency?ref=alexbowe.com">hard</a>, open source, <em>permissionless</em> money, but outsourcing control of your keys (e.g. to an exchange) dilutes that benefit, leaving you vulnerable to hacks<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>, <a href="https://en.wikipedia.org/wiki/Exit_scam?ref=alexbowe.com">exit scams</a>, and <a href="https://cryptobriefing.com/rebel-group-locked-account-holders-complain-binance-hell/?ref=alexbowe.com">having your account frozen</a><sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup>.</p>
<p>The mantra &quot;not your keys, not your Bitcoin&quot; warns us to take custody of our coins, but applies even more-so to keys that you already control: <a href="https://anthonyspark.com/e202-bitcoin-risk-of-theft-vs-risk-loss/?ref=alexbowe.com">an estimated 20% of Bitcoin has been lost, while 8% has been stolen</a>.</p>
<p>I learned this the hard way.</p>
<p>In late 2020, Ledger&apos;s software forced me to update my firmware and restore the keys from a backup<sup class="footnote-ref"><a href="#fn3" id="fnref3">[3]</a></sup>. After re-entering my mnemonic and passphrase into the updated device I found that I could no longer sign transactions. Fuck.</p>
<p>After months of poor sleep and ambient anxiety I was recently able to write a program to recover my keys. I have seen several people with the similar issues on Reddit, so I decided to write this up and provide the code. I hope it helps!</p>
<h2 id="whathappened">What Happened?</h2>
<p>Bitcoin&apos;s UX is improving rapidly, but it is still very early, and there are literally infinite ways things can go wrong. Was the mnemonic incorrect? What about the passphrase? Was I using the correct key derivation path? Was there a bug in the derivation? Maybe a bug in how <a href="https://bitcoinops.org/en/topics/hwi/?ref=alexbowe.com">HWI</a> reported the master key?</p>
<p>It is wise to <a href="https://en.wikipedia.org/wiki/Occam%27s_razor?ref=alexbowe.com">focus on the hypotheses that make the fewest assumptions</a>. Since it was impossible to check Ledger&apos;s code (tip: prefer Open Source), and the mnemonic was successfully restoring the passphrase-less wallet, the most likely culprit was the passphrase - or rather, I probably entered it incorrectly during the initial setup. Let&apos;s try to work out what I typed instead...</p>
<h2 id="generatingtypos">Generating Typos</h2>
<p>Naturally, I&apos;m not the first person that wanted to crack a Bitcoin passphrase by guessing typos. <a href="https://github.com/3rdIteration/btcrecover/?ref=alexbowe.com">BTCRecover</a> is a highly customisable tool for cracking mnemonics and passphrases by generating typos, but is limited in some ways.</p>
<p>To see why, let&apos;s take a context-agnostic look at what a typo is.</p>
<h3 id="dameraulevenshteindistance">Damerau-Levenshtein Distance</h3>
<p>The <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance?ref=alexbowe.com">Damerau-Levenshtein Distance</a> (sometimes just &quot;edit distance&quot;) is a popular <a href="https://en.wikipedia.org/wiki/Metric_(mathematics)?ref=alexbowe.com">metric</a> that counts the fewest number of &quot;edits&quot; to convert a string \(a\) to a string \(b\). Edits include:</p>
<ul>
<li>Inserting a character.</li>
<li>Deleting a character.</li>
<li>Substituting one character for another.</li>
<li>Transposing two adjacent characters.</li>
</ul>
<p>Any two strings \(a\) and \(b\) will have a sequence of edits between them. In fact, such a path could also be made with just insertions and deletions, but substitution and transposition are (probably?) counted as single edits due to how common they are. Hence, Damerau-Levenshtein space contains all possible results, including more complex <a href="https://en.wikipedia.org/wiki/Speech_error?ref=alexbowe.com">speech errors</a> like <a href="https://en.wikipedia.org/wiki/Malapropism?ref=alexbowe.com">malapropisms</a> (word-level substitution).</p>
<p><a href="https://github.com/3rdIteration/btcrecover/?ref=alexbowe.com">BTCRecover</a> does not include insertions, hence over-prunes the search-space.</p>
<p>Using the above definition, let&apos;s write some Python functions to help us generate these:</p>
<pre><code class="language-python">def damerau_levenshtein_edits(s: str, alphabet: str):
    yield from insertions(s, alphabet)
    yield from substitutions(s, alphabet)
    yield from deletions(s)
    yield from transpositions(s)

def insertions(s: str, alphabet: str):
    return (concatenate(s[:i], x, s[i:])
            for i in range(len(s) + 1)
            for x in alphabet)

def substitutions(s: str, alphabet: str):
    return (concatenate(s[:i], x, s[i + 1:])
            for i in range(len(s))
            for x in alphabet)

def deletions(s: str):
    return (concatenate(s[:i], s[i + 1:])
            for i in range(len(s)))

def transpositions(s: str):
    return (concatenate(s[:i], s[i + 1], s[i], s[i + 2:])
            for i in range(len(s) - 1))

def concatenate(*args: Iterable[str]):
    return &quot;&quot;.join(args)
</code></pre>
<h3 id="breadthfirstenumeration">Breadth-First Enumeration</h3>
<p>In the <a href="https://sci-hub.se/10.1145/363958.363994?ref=alexbowe.com">paper that introduced this measure</a> it was found that 80% of typos have an edit distance of just 1! To verify this I plotted the edit distance for all English typos in <a href="https://github.com/mhagiwara/github-typo-corpus?ref=alexbowe.com">this GitHub Typo Corpus</a> (<a href="https://github.com/alexbowe/bitcoin-passphrase-cracker/blob/develop/TypoAnalysis.ipynb?ref=alexbowe.com#center">code</a>):</p>
<p>
<center>
<p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2021/11/github-typo-histogram.png" alt="How to Recover a Bitcoin Passphrase" loading="lazy"></p>
</center>
</p>
<p>Close enough! More importantly, it follows a <a href="https://en.wikipedia.org/wiki/Zipf%27s_law?ref=alexbowe.com">Zipf distribution</a> (i.e. a discrete <a href="https://en.wikipedia.org/wiki/Pareto_distribution?ref=alexbowe.com">Pareto distribution</a>), which occurs in natural language all the time. This means we can rapidly converge on the correct answer by enumerating strings in ascending order of Damerau-Levenshtein distance. The dataset also contains <a href="https://en.wikipedia.org/wiki/Malapropism?ref=alexbowe.com">malapropisms</a>, so even complex errors occur more frequently within short edit distances.</p>
<p>This order will naturally occur if we define an (implicit) graph of strings where each edge represents a single edit, and perform a <a href="https://en.wikipedia.org/wiki/Breadth-first_search?ref=alexbowe.com">Breadth-First traversal</a> (as the nearest neighbors will be explored first). If I had further worked out character-level probabilities for each typo, we could probably use <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm?ref=alexbowe.com">Dijkstra&apos;s Algorithm</a> to further speed things up, and as Reddit user <a href="https://www.reddit.com/r/Bitcoin/comments/o81fqk/how_i_recovered_my_lost_bitcoin_passphrase/h32o5bc/?utm_source=reddit&amp;utm_medium=web2x&amp;context=3">Quantris mentions</a>, for a long initial string we might wish to use <a href="https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search?ref=alexbowe.com">Iterative-Deepening Depth-First Search</a> to reduce memory usage.</p>
<p>Here&apos;s an <a href="https://refactoring.guru/design-patterns/iterator?ref=alexbowe.com">iterator</a> to perform the traversal:</p>
<pre><code class="language-python">def all_typos(root: str, alphabet: str):
    neighbors = lambda x: damerau_levenshtein_edits(x, alphabet)
    
    discovered = {root}
    frontier = deque([(0, root)])

    while frontier:
        distance, current = frontier.popleft()

        yield {&quot;distance&quot;: distance, &quot;typo&quot;: current}

        for neighbor in neighbors(current):
            if neighbor not in discovered:
                frontier.append((distance+1, neighbor))
                discovered.add(neighbor)
</code></pre>
<p>The above loop will never terminate - it is up to the caller to cease iteration when appropriate.</p>
<h3 id="terminatingconditions">Terminating Conditions</h3>
<p>Since we don&apos;t know what string we are looking for we will need to use each passphrase attempt to derive one of the following:</p>
<ul>
<li>The master public key or fingerprint.</li>
<li>Any account public keys or fingerprints.</li>
<li>A receiving or change address.</li>
<li>A transaction IDs (we can fetch the addresses involved from <a href="https://mempool.space/?ref=alexbowe.com">the mempool</a>).</li>
<li>A <a href="https://github.com/3rdIteration/btcrecover/blob/master/docs/Creating_and_Using_AddressDB.md?ref=alexbowe.com">database of used addresses</a> if none of the above are known.</li>
</ul>
<p>Anything under the master key (such as an account key or address) require guessing the correct derivation path. While there are infinite possibilities<sup class="footnote-ref"><a href="#fn4" id="fnref4">[4]</a></sup>, there are only finite wallet implementations, so <a href="https://walletsrecovery.org/?ref=alexbowe.com">this list of the different derivation paths used in wallets</a> may come in handy. I had the master fingerprint so didn&apos;t need any derivation paths.</p>
<p>Here is code using <a href="https://pypi.org/project/bip-utils/?ref=alexbowe.com"><code>bip_utils</code></a> to derive the fingerprint from a mnemonic and passphrase:</p>
<pre><code class="language-python">from bip_utils import Bip32, Bip39SeedGenerator

def fingerprint(mnemonic: str, passphrase: str):
    seed_bytes = Bip39SeedGenerator(mnemonic).Generate(passphrase)
    master = Bip32.FromSeed(seed_bytes)
    return master.FingerPrint()

def crack(
    mnemonic: str,
    master_fingerprint: str,
    passphrase_guess: str,
    alphabet: str,
):
    binary_fingerprint = binascii.unhexlify(master_fingerprint)
    passphrase_typos = all_typos(passphrase_guess, alphabet)
    for typo in passphrase_typos:
        if fingerprint(mnemonic, typo[&quot;typo&quot;]) == binary_fingerprint:
            return typo
</code></pre>
<h2 id="searchparty">Search Party &#x1F389;</h2>
<p>Below I have included code for how to use the above functions to crack my wallet.</p>
<pre><code class="language-python"># crack.py

from string import ascii_lowercase

ALPHABET = ascii_lowercase
MASTER_FINGERPRINT = b&quot;6aa00e9a&quot;
GUESS = &quot;hysterichorsebatterystaple&quot;
MNEMONIC = &quot;&quot;&quot;
chase wonder voice rack
custom sport fix decline
body hollow wreck stay
dress resist space solid
gospel pumpkin shoot tank
cable dignity own pigeon
&quot;&quot;&quot;.strip().split()

if __name__ == &quot;__main__&quot;:
    result = crack(&quot; &quot;.join(MNEMONIC), MASTER_FINGERPRINT, GUESS, ALPHABET)
    print(f&quot;{result[&apos;typo&apos;]} found at distance {result[&apos;distance&apos;]}&quot;)
</code></pre>
<p>And the big reveal (run this on an offline computer to avoid loss of funds):</p>
<pre><code class="language-bash">$ python crack.py
historichorsebatterystaple found at distance 2
</code></pre>
<p>This completed in 165 minutes (close to 3 hours), which isn&apos;t bad at all considering by this stage we had already checked the vast majority of likely typos.</p>
<p>It turns out I had mistyped &quot;historic&quot; instead of &quot;hysteric&quot;. This made me laugh, since I remember doing my best to not type &quot;hysteria&quot; (which I couldn&apos;t stop thinking about, because of its <a href="https://allthatsinteresting.com/female-hysteria?ref=alexbowe.com">messed up history</a>). I guess focusing too hard on that final &quot;c&quot; caused me to be lax with the rest.</p>
<p>If you don&apos;t have a clue of what your passphrase is, try <a href="https://github.com/danielmiessler/SecLists/tree/master/Passwords/Common-Credentials?ref=alexbowe.com">this list of common passwords</a> - humans are more similar than we realise.</p>
<h2 id="prevention">Prevention</h2>
<p>Although it wasn&apos;t too hard for me to fix in the end, I could have done without the hassle. To avoid this happening in the first place:</p>
<ol>
<li><strong>Test your backups</strong> - Although wallets usually prompt you to re-enter/re-read things, your backup is only guaranteed after you actually use it. The best way to do this is to use <a href="https://iancoleman.io/bip39/?ref=alexbowe.com">Ian Coleman&apos;s Tool</a> offline in <a href="https://tails.boum.org/?ref=alexbowe.com">Tails</a>, or another device (in case your wallet has bugs).</li>
<li><strong>Use multi-sig</strong> - In theory, adding a passphrase can protect you from say, a <a href="https://xkcd.com/538/?ref=alexbowe.com">$5 wrench attack</a>. In practice it introduces an additional <a href="https://en.wikipedia.org/wiki/Single_point_of_failure?ref=alexbowe.com">single point of failure</a>. A multi-sig setup (e.g. 2-of-3) adds redundancy, and uses mnemonics instead (which have some built in error correction). The tooling has improved to the point where this is really easy (and free if you use paper wallets). I&apos;ll write a guide on this someday, but Michael Flaxman has a good guide <a href="https://btcguide.github.io/?ref=alexbowe.com">here</a>.</li>
</ol>
<h2 id="conclusion">Conclusion</h2>
<p>In this post I demonstrated that a <a href="https://en.wikipedia.org/wiki/Breadth-first_search?ref=alexbowe.com">Breadth-First search</a> in ascending order of <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance?ref=alexbowe.com">Damerau-Levenshtein</a> distances is a practical method to recover a Bitcoin passphrase that was mistyped during an initial setup.</p>
<p>I hope to add support for address derivation, mnemonic correction, and improve the performance in the future. But for now it is fairly ad-hoc and specific to my situation. If you are still stuck please <a href="https://www.twitter.com/alexbowe?ref=alexbowe.com">contact me</a> and I&apos;ll try to help.</p>
<p>If this helped or entertained you sign up to my mailing list for more words!</p>
<p><em>Special thanks to <a href="https://twitter.com/nopara73?ref=alexbowe.com">nopara73</a> (author of <a href="https://wasabiwallet.io/?ref=alexbowe.com">Wasabi</a>) for his help in the wallet derivation part of this code.</em></p>
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>Of course, individual users are more likely to have insecure environments, but exchanges are much higher value targets that they are more susceptible to attack. <a href="#fnref1" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn2" class="footnote-item"><p>This could be for illegal activity, censorship (e.g. if you sell marijuana or run an OnlyFans account), or even a simple policy change that requiring more personal information. Even a temporary freeze can be disruptive and stressful. <a href="#fnref2" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn3" class="footnote-item"><p>I could write a long-ass post about why Ledger have dangerous UX, and maybe someday I will! But for now, if you are in the market for a hardware wallet, I&apos;d recommend looking at the <a href="https://cobo.com/hardware-wallet?ref=alexbowe.com">Cobo Vault</a> (not a paid endorsement). <a href="#fnref3" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
<li id="fn4" class="footnote-item"><p>The details of key derivation are outside the scope of this post. If you want to understand it in depth, I recommend <a href="https://www.oreilly.com/library/view/mastering-bitcoin/9781491902639/ch04.html?ref=alexbowe.com">Chapter 4 of Mastering Bitcoin by Andreas Antonopoulos</a>, or this helpful <a href="https://twitter.com/Septem_151/status/1172697404400971778?ref=alexbowe.com">flowchart by @septem_151</a>. <a href="#fnref4" class="footnote-backref">&#x21A9;&#xFE0E;</a></p>
</li>
</ol>
</section>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Succinct de Bruijn Graphs]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>This post will give a brief explanation of a Succinct implementation for storing <a href="http://en.wikipedia.org/wiki/De_Bruijn_graph?ref=alexbowe.com">de Bruijn graphs</a>, which is recent (and continuing) work I have been doing with Sadakane.</p>
<p>Using our new structure, we have squeezed a graph for a human genome (which took around 300 GB of memory if using</p>]]></description><link>https://www.alexbowe.com/succinct-debruijn-graphs/</link><guid isPermaLink="false">619714f2c62458003bddca70</guid><category><![CDATA[data structures]]></category><category><![CDATA[bioinformatics]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Tue, 02 Jul 2013 21:07:35 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>This post will give a brief explanation of a Succinct implementation for storing <a href="http://en.wikipedia.org/wiki/De_Bruijn_graph?ref=alexbowe.com">de Bruijn graphs</a>, which is recent (and continuing) work I have been doing with Sadakane.</p>
<p>Using our new structure, we have squeezed a graph for a human genome (which took around 300 GB of memory if using previous representations) down into 2.5 GB. In addition, the construction method allows much of the work to be done on disk. Your computer might not have 300 GB of RAM, but you might have 2.5 GB of RAM and a hard disk.</p>
<p>I have given a talk about this a few times, so I&#x2019;ve been itching to write it up as a blog post (if only to shamelessly plug my blog at conferences). However, since it is a lowly blog post, I won&#x2019;t give attention to the gory details, nor provide any experimental results. But this post is merely to <em>communicate the approach</em>. Feel free to check out our <a href="https://www.dropbox.com/s/cxxuqjs663fdth7/succinctdebruijn2012.pdf?ref=alexbowe.com">conference paper</a>, and stay tuned for the journal paper.</p>
<p>In this blog post, I will first give an introduction to <a href="#debruijn-graphs">de Bruijn graphs</a> and <a href="#dna-assembly">how they are used in DNA assembly</a>. Then I will briefly explain <a href="#previous">some previous implementations</a> before reaching the main topic of this post: <a href="#our-repr">our new succinct representation</a>. The explanation first explains some preliminaries, such as how we were <a href="#bwt-inspiration">inspired by the Burrows Wheeler Transform</a>, and what <a href="#ranksel">rank and select</a> are, which are required to understand the <a href="#construction">construction method</a>, and <a href="#interface">traversal interface</a> respectively.</p>
<p>For those following along at home, I have implemented <a href="https://github.com/alexbowe/debby/blob/0.1.1/debby.py?ref=alexbowe.com">a demo version in Python</a>. It doesn&#x2019;t use efficient implementations of rank and select, nor provide any compression &#x2013; it is merely meant to demonstrate the key ideas with (hopefully) readable high level code. An optimised version will be made available at some point.</p>
<p>Okay, here we go&#x2026;</p>
<h2 id="debruijngraphs">De Bruijn Graphs</h2>
<p>De Bruijn graphs are a beautifully simple, yet useful combinatoric object which I challenge you not to lose sleep over.</p>
<p>Since their discovery around 1946, they have been used in a variety of applications, such as encryption, psychology, chess and even card tricks. Quite recently they have become a popular data structure for DNA assembly of short read data.</p>
<p>They are defined as a directed graph, where each node $u$ represents a fixed-length string (say, of length $k$, and an edge exists from $u$ to $v$ iff they overlap by $k&#x2013;1$ symbols. That is, $u[2..k] = v[1..k&#x2013;1]$.</p>
<p>Let&#x2019;s make this concrete with a diagram:</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/23debruijn.png?w=240&amp;ssl=1#center" alt loading="lazy"></p>
<p>Doesn&#x2019;t this just <em>feel good</em> to look at? Now tilt your head and look at it this way: it is essentially a <a href="https://en.wikipedia.org/wiki/Finite-state_machine?ref=alexbowe.com">Finite State Machine</a> with additional bounded memory of the last $k$ visited states, if you added a few more states to allow for incomplete input at the start. For example, if X represents blank input, from a starting state XXX we might have the transition chain: XXX -&gt; XX1 -&gt; X10 -&gt; 101 (which is already a node in the graph). Put this way, it is easy to see that the $k$ previous edges define the current node. This perspective will make things easier to understand later, I promise.</p>
<p>Still with me? Good (: Then let&#x2019;s also consider that if <em>one node</em> is defined by a $k$-length string, then a <em>pair of nodes</em> (i.e. an edge) can be identified by a $k+1$ length string, since they overlap and differ by 1 symbol. This will also be important later.</p>
<p>And of course, this can be extended to larger alphabet sizes than binary (say, 4&#x2026;).</p>
<h2 id="dnaassembly">DNA Assembly</h2>
<p>First suggested in 2001 by Pevzner et al.<a href="#fn-1" title="see footnote">[1]</a>, we can use de Bruijn graphs to represent a network of overlapping <em>short read data</em>.</p>
<p>The long and short of it (heh heh) is that a DNA molecule is currently too difficult to sequence (that is, read it into a computer) in its entirety. Special methods must be used so we can sequence parts of the molecule, and hand off the putting-back-together process (assembly) to an algorithm.</p>
<p>One current popular sequencing method is <em>shotgun sequencing</em>, which clones the genome a bunch of times, then randomly breaks each clone into short segments. If we can sequence the short segments, then the fact that we randomly cut up the clones should lead us to have overlapping reads. Of course it is a bit more complicated than this in reality, but this is the essence of it.</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/shotgun.png?w=500&amp;ssl=1#center" alt loading="lazy"></p>
<p>We then move a sliding window over each read, outputing overlapping $k$-mers (the $k$-length strings), which we use to create our de Bruijn graph.</p>
<p>About now mathematicians among you might raise your hand to tell me &#x201C;that may not technically yield a de Bruijn graph&#x201D;. That&#x2019;s correct &#x2013; in Bioinformatics the term &#x201C;de Bruijn graph&#x201D; is overloaded to mean a subgraph. Even though genomes are long strings, most genomes won&#x2019;t have <em>every single k-mer</em> present, and there is usually repeated regions. This means our data will be sparse.</p>
<p>Consider the following contrived example. Take the sequence <code>TACGACGTCGACT</code>. If we set (k=3), our k-mers will be <code>TAC</code>, <code>ACG</code>, <code>CGA</code>, and so on. We would end up with this de Bruijn graph:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/graph.png?ssl=1#center" alt loading="lazy"></p>
<p>After we construct the graph from the reads, assembly becomes finding the &#x201C;best&#x201D; contiguous regions. The jury is still out on what the best method is (or what &#x201C;best&#x201D; even means); the point of this post isn&#x2019;t about assembly, but our implementation of the data structure and how it provides all required navigation options to implement any traversal method. I recommend reading <a href="http://www.cs.ucdavis.edu/~gusfield/cs225w12/deBruijn.pdf?ref=alexbowe.com">this primer from Nature</a> if you want to get deeper into this.</p>
<p>Even though this is only a de Bruijn <em>subgraph</em>, these things still grow pretty big. It is worthwhile considering how to handle this scalability issue, if only to reduce hardware requirements of sequencing (thus proliferating personal genomics), and potentially improve traversal speed (due to better memory locality). Increased efficiency might also enable richer multiple-genomic analysis.</p>
<h2 id="previousrepresentations">Previous Representations</h2>
<p>One of the first approaches to this was to scale &#x201C;horizontally&#x201D;. Simpson et al.<a href="#fn-2" title="see footnote">[2]</a> introduced ABySS in 2009. The <a href="ftp://ftp.ddbj.nig.ac.jp/ddbj_database/dra/fastq/SRA010/SRA010896/SRX016231/">graph for reads from a human genome (HapMap: NA18507)</a>, which used a distributed hash table, reached 336 GB.</p>
<p>In 2011, Conway and Bromage<a href="#fn-3" title="see footnote">[3]</a> instead approached this problem from a &#x201C;vertical&#x201D; scaling perspective (that is, scaling to make better use of a single system&#x2019;s resources), by using a sparse bitvector (by Okanohara and Sadakane<a href="#fn-4" title="see footnote">[4]</a>) to represent the $(k + 1)$-mers (the edges), and used <a href="#ranksel">rank and select</a> (to be described shortly) to traverse it. As a result, their representation took 32 GB for the same data set.</p>
<p>Minia, by Cikhi and Rizk (2012)<a href="#fn-5" title="see footnote">[5]</a>, proposed yet another approach by using a <a href="http://en.wikipedia.org/wiki/Bloom_filter?ref=alexbowe.com">bloom filter</a> (with additional structure to avoid false positive edges that would affect the assembly). They traverse by generating possible edges and testing for it in the bloom filter. Using this approach, the graph was reduced to 5.7 GB.</p>
<h2 id="oursuccinctrepresentation">Our Succinct Representation</h2>
<p>As stated, we were able to represent the same graph in 2.5 GB (after some further compression techniques, which I will save for a future post).</p>
<p>The key insight is that the edges define overlapping node labels. This is similar to that of Conway and Bromage, although they have some redundancy, since some <em>nodes</em> are represented more times than necessary.</p>
<p>We further exploit the <a href="https://en.wikipedia.org/wiki/Mutual_information?ref=alexbowe.com">mutual information</a> of edges by taking inspiration from the Burrows Wheeler Transform<a href="#fn-6" title="see footnote">[6]</a>.</p>
<h3 id="inspirationfromtheburrowswheelertransform">Inspiration from the Burrows Wheeler Transform</h3>
<p>The Burrows Wheeler Transform<a href="#fn-6" title="see footnote">[6]</a> is a reversible string permutation that can be searched directly and has the admirable quality of having long strings of repeated characters (great for compression). The easiest way to calculate the BWT of a string is to sort each symbol by their prefixes in colex order (that is, alphabetic order of the reverse of the string, not reverse alphabetic!) More information can be found on <a href="http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform?ref=alexbowe.com">Wikipedia</a> and this <a href="http://marknelson.us/1996/09/01/bwt/?ref=alexbowe.com">Dr. Dobbs</a> article.</p>
<p>The XBW is a generalisation of the BWT that applies to rooted, labeled trees<a href="#fn-7" title="see footnote">[7]</a>. The idea is that instead of taking all suffixes, we sort all paths from the root to each node, and support tree navigation (since it isn&#x2019;t a linearly shaped string) with auxiliary bit vectors indicating which edges are leaves, and which are the last edges (of their siblings) of internal nodes.</p>
<p>I won&#x2019;t go into detail, but in the next section you should be able to see glimpses of these two ideas.</p>
<h3 id="construction">Construction</h3>
<p>The simplest construction method<a href="#fn-8" title="see footnote">[8]</a> is to take every &lt;node, edge&gt; pair and sort them based on the reverse of the node label (colex order), removing duplicates<a href="#fn-9" title="see footnote">[9]</a>. We also padding to ensure every node has an incoming and an outgoing edge. This maintains the fact that a node is defined by its previous k edges. An example can be seen below:</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/graph-padded.png?ssl=1#center" alt loading="lazy"><br>
<img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/arrays-1.png?ssl=1#center" alt loading="lazy"></p>
<p>You may have spotted that we have flagged some edges with a minus symbol. This is to disambiguate identically labelled incoming edges &#x2013; edges that exit separate nodes, but have the same symbol, and thus enter the same node. In the example below, the nodes <code>ACG</code> and <code>CGA</code> both have two incoming edges.</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/edges.png?ssl=1#center" alt loading="lazy"><br>
<img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/array-edges-flags.png?ssl=1#center" alt loading="lazy"></p>
<p>Notice that each outgoing edge is stored contiguously? We include a bit vector to represent whether an edge is the <em>last</em> edge exiting a node. This means that each node will have a sequence of zero-or-more 0-bits, followed by a single 1-bit.</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/last-edges.png?ssl=1#center" alt loading="lazy"><br>
<img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/last-array.png?ssl=1#center" alt loading="lazy"></p>
<p>Since a 1 in the $L$ vector identifies a unique node, we can use this vector (and <a href="#ranksel">select</a>, explained shortly) to index nodes, whereas standard array indexing points to edges.</p>
<p>Finally, instead of storing the node labels we just need to store the final column of the node labels. Since the node labels are sorted, it is equivalent to store an array of first positions:</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/f-array.png?ssl=1#center" alt loading="lazy"></p>
<p>In total we have a bitvector $L$, an array of flagged edge labels $W$, and a position array $F$ of size $\sigma$ (the alphabet size). Respectively, these take $m$ bits, $m \log{2*\sigma} = 3 m$ bits (for DNA), and $\sigma \log{m} = o(m)$ bits<a href="#fn-10" title="see footnote">[10]</a>, given $m$ edges &#x2013; a bit over 4 bits per edge. Using appropriate structures (not detailed) we can compress this further, to around 3 bits per edge.</p>
<h3 id="rankandselect">Rank and Select</h3>
<p>Rank and select are the bread and butter of succinct data structures, because so many operations can be implemented using them alone. $rank_c(i)$ returns the number of occurences of symbol $c$ on the closed range $[0, i]$, whereas $select_c(i)$ returns the position of the $i^{th}$ occurence of symbol $c$.</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/ranksel.png?w=600&amp;ssl=1#center" alt loading="lazy"></p>
<p>They are <em>kind of</em> like inverse functions, although $rank()$ is not <a href="http://en.wikipedia.org/wiki/Injective_function?ref=alexbowe.com">injective</a>, so cannot have a true inverse. For this reason, if you want to find the <em>position</em> of the left-nearest $c$, you would have to use $select()$ in orchestra with $rank()$ (a common pattern).</p>
<p>Speaking of patterns of use, it may also help to keep this in mind: rank is for counting, and select is for searching, or can be thought of as an indirect addressing technique (such as addressing a node using the $L$ array). Two rank queries can count over a range, whereas two select queries can find a range. A rank and a select query can find a range where either a start point or end point are fixed.</p>
<p>Rank, select and standard array access can all be done in $\mathcal{O}(1)$ time when $\sigma = polylog(N)$<a href="#fn-11" title="see footnote">[11]</a>, if represent a bitvector using the structure described by Raman, Raman and Rao in 2007<a href="#fn-12" title="see footnote">[12]</a> (which I explained in <a href="https://alexbowe.com/rrr?ref=alexbowe.com">an earlier blog post</a>), and for larger alphabets use the index described by Ferragina, Manzini, Makinen, and Navarro in 2006<a href="#fn-13" title="see footnote">[13]</a>. In our implementation, we use modified versions to get it down to 3 bits per edge.</p>
<h3 id="interfaceoverview">Interface Overview</h3>
<p>While it might not be obvious, these three arrays provides support for a full suite of navigation operations. An overview is given in these tables, which link to the implementation details that follow.</p>
<p>First, to navigate each of the edges, we define two internal functions (using <a href="#ranksel">rank and select calls</a>):</p>
<div class="responsive-table">
<table>
<colgroup>
<col style="text-align: left;">
<col style="text-align: left;">
<col style="text-align: left;"> </colgroup>
<thead>
<tr>
<th style="text-align: left;">Operation</th>
<th style="text-align: left;">Description</th>
<th style="text-align: left;">Complexity</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;"><a href="#forward"><span class="math">\(forward(i)\)</span></a></td>
<td style="text-align: left;">Return index of the <em>last edge</em> of the <em>node pointed to</em> by edge <span class="math">\(i\)</span>.</td>
<td style="text-align: left;"><span class="math">$\mathcal{O}(1)$</span></td>
</tr>
<tr>
<td style="text-align: left;"><a href="#backward"><span class="math">\(backward(i)\)</span></a></td>
<td style="text-align: left;">Return index of the <em>first edge</em> that <em>points to the node</em> that the edge at <span class="math">\(i\)</span> <em>exits</em>.</td>
<td style="text-align: left;"><span class="math">\(\mathcal{O}(1)\)</span></td>
</tr>
</tbody>
</table>
</div>
<p>Using these two functions, we can implement the less confusing public interface below, which operate on node indexes:</p>
<div class="responsive-table">
<table>
<colgroup>
<col style="text-align: left;">
<col style="text-align: left;">
<col style="text-align: left;"> </colgroup>
<thead>
<tr>
<th style="text-align: left;">Operation</th>
<th style="text-align: left;">Description</th>
<th style="text-align: left;">Complexity</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;"><a href="#outdegree"><span class="math">\(outdegree(v)\)</span></a></td>
<td style="text-align: left;">Return number of outgoing edges from node <span class="math">\(v\)</span>.</td>
<td style="text-align: left;"><span class="math">\(\mathcal{O}(1)\)</span></td>
</tr>
<tr>
<td style="text-align: left;"><a href="#outgoing"><span class="math">\(outgoing(v,c)\)</span></a></td>
<td style="text-align: left;">From node <span class="math">\(v\)</span>, follow the edge labeled by symbol <span class="math">\(c\)</span>.</td>
<td style="text-align: left;"><span class="math">\(\mathcal{O}(1)\)</span></td>
</tr>
<tr>
<td style="text-align: left;"><a href="#label"><span class="math">\(label(v)\)</span></a></td>
<td style="text-align: left;">Return (string) label of node <span class="math">\(v\)</span>.</td>
<td style="text-align: left;"><span class="math">\(\mathcal{O}(k)\)</span></td>
</tr>
<tr>
<td style="text-align: left;"><a href="#indegree"><span class="math">\(indegree(v)\)</span></a></td>
<td style="text-align: left;">Return number of incoming edges to node <span class="math">\(v\)</span>.</td>
<td style="text-align: left;"><span class="math">\(\mathcal{O}(1)\)</span></td>
</tr>
<tr>
<td style="text-align: left;"><a href="#incoming"><span class="math">\(incoming(v,c)\)</span></a></td>
<td style="text-align: left;">Return predecessor node starting with symbol <span class="math">\(c\)</span>, that has an edge to node <span class="math">\(v\)</span>.</td>
<td style="text-align: left;"><span class="math">\(\mathcal{O}(k \log \sigma) \)</span></td>
</tr>
</tbody>
</table>
</div>
<p>The details of the above functions are given in the following sections.</p>
<h3 id="forward">Forward</h3>
<p>In order to support the public interface, we create for ourselves a simpler way to work with edges: the complementing forward and backward functions.</p>
<p>Recall that all node labels are defined by predecessor edges, then we have represented each edge in two different places: the (F) array (which is equivalent to the last column of the &#x201C;Node&#x201D; array), and the edge array (W). It follows that, since it is sorted, the node labels maintain the same <em>relative order</em> as the edge labels. This can be seen in the following figure:</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/fwdsetup.png?ssl=1#center" alt loading="lazy"></p>
<p>Note that the number of <code>C</code>s in the last column of Node is different from the number of <code>C</code>s in (W), because the first <code>C</code> in (W) points to two edges. For this reason, we ignore the first edge from node <code>GAC</code> (although it doesn&#x2019;t affect the relative order). In fact, we ignore any edge that doesnt have L[i] == 1.</p>
<p>Then, following an edge is simply finding the corresponding relatively positioned node! All it takes is some creative counting, using <a href="#ranksel">rank and select</a>, as pictured below:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/fwd.png?ssl=1#center" alt loading="lazy"></p>
<p>First we access W[i] to find the edge label, then calculate (rank_C) up to row to gives us the relative ordering of our <em>edges</em> with this label. Let&#x2019;s call this relative index (r). In our example we are following the 2nd C-labeled edge.</p>
<p>To find the 2nd occurence of C in F, first we need to know where the first occurence is. We can use F to find that. Then we can select to the 2nd one, using the last array. Because the last array is binary only, this requires us to count how many 1s there are before the run of Cs (using rank), then adding 2 to land us at the 2nd C.</p>
<p>The W access, rank over W, rank and select over L, accessing F, and the addition are all done in O(1) time, so forward also takes O(1) time.</p>
<h3 id="backward">Backward</h3>
<p>Backward is very similar to forward, but calculated in a different order: we find the relative index of the node label first, and use that to find the corresponding edge (which may not be the only edge to point to this node, but we define it to point to the first one, that is one that isn&#x2019;t flagged with a minus).</p>
<p>We can find our relative index of the node label by issuing two rank queries instead, and using select on W to find the first incoming edge.</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/bwd.png?ssl=1#center" alt loading="lazy"></p>
<p>For similar reasons to Forward this is O(1).</p>
<h3 id="outdegree">Outdegree</h3>
<p>This is an easy one. This function accepts a <strong>node</strong> (not edge!) index <code>v</code>, and returns the number of outgoing edges from that node. Why did I say this was easy? Well, remember that all our outgoing edges from the same node are contiguous in our data structure. See the diagrams below, paying attention to the node <code>ACG</code>.</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/outdegree-graph.png?ssl=1#center" alt loading="lazy"><br>
<img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/outdegree-arrays.png?ssl=1#center" alt loading="lazy"></p>
<p>By definition (since nodes are unique and sorted), this will always be the case. We also defined our so-called &#x201C;last&#x201D; vector $L$ to have a 0 for every edge from a given node, <em>except the last</em> edge. All we need to do is count how many 0s there are, then add 1. Put another way, we need to measure the distance between 1s (since the previous 1 will belong to the previous node). Since we know the node index, we can use select for that!</p>
<p>In the above example, we are querying the outdegree of node 6 (the 7th node due to zero-basing). First we select to find the position of the 7th 1, which gives us the last edge of that node. Then we simply subtract the position of the previous node (node 5, the 6th node): (select(7) &#x2013; select(6) = 8 &#x2013; 6 = 2). Boom.</p>
<p>Select queries can be answered in O(1) time, so outdegree is also O(1).</p>
<h3 id="outgoing">Outgoing</h3>
<p>Outgoing(v,c) returns the target node after traversing edge c from node v, which might not exist. The hard part is finding the correct edge index to follow; after that we can conveniently use the forward() function we defined earlier.</p>
<p>To ease the explanation, consider a simple bit vector <code>00110100</code>. To count how many 1s there are up to and including the 7th position, we would use rank. The answer is 3, but at this stage we still don&#x2019;t know the position of the 3rd 1 (we can&#x2019;t see the bitvector). In general, it may or may not be in the 7th position. We could scan backwards, or we could just use select(3) to find the position (since this returns the first position i that has rank(i) = 3).</p>
<p>So essentially we can count how many of those edges there are before the node we are interested in, then use select to find the position. If the position is inside this nodes range (of contiguous edges), then we follow it.</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/outgoing.png?ssl=1#center" alt loading="lazy"></p>
<p>We complicated things a bit by separating our edges into flagged and non-flagged, so we may have to issue two of these queries (for the minus flags). The flagging is useful later in <a href="#indegree">Indegree</a>.</p>
<p>In the next example, our nonflagged edge doesn&#x2019;t fall in our nodes range, so we make a second query. It is possible that this one will return a positive result, but in the example it doesn&#x2019;t. By that stage though, we can respond with by returning &#x2013;1 to signal that the edge doesn&#x2019;t exist.</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/outgoing-neg.png?ssl=1#center" alt loading="lazy"></p>
<p>forward() is defined to move us to the last edge of the resulting node, so the value in last will be 1. Hence, we can use rank to convert our edge index into a node index before returning it.</p>
<p>This is a constant number of calls to O(1) functions, so outgoing is also O(1).</p>
<h3 id="label">Label</h3>
<p>At some point (e.g. during traversal) we are probably going to want to print the node labels out. Let&#x2019;s work out how to do that (:</p>
<p>Remember, we aren&#x2019;t storing the node labels explicitly. The F array will come in handy: We can use the position of our node (found using select) as a reverse lookup into F. This can be done in constant time with a sparse bit vector, or in logarithmic time using binary search, or we can use a linear scan if our alphabet is small. In any case, lets assume it is O(1) time, although a linear scan might be faster in practice (fewer function calls may yield a lower constant coefficient).</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/last-symbol.png?ssl=1#center" alt loading="lazy"></p>
<p>In the above example, we select to node 6 (the 7th 1 in last), which gives us the last edge index (any edge will do, but the last one is the easiest to find). This happens to be row 8, so from F we know that all the last symbols between on the open range [7,10) are G.</p>
<p>Then we just use bwd() on the current edge to find an edge that pointed to this node, then rinse and repeat k times.</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/label.png?ssl=1#center" alt loading="lazy"></p>
<h3 id="indegree">Indegree</h3>
<p>In a similar manner to <a href="#outdegree">outdegree</a>, all we need to do is count the edges that point to the current node label. Take for example the graph:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/indegree-graph.png?ssl=1#center" alt loading="lazy"></p>
<p>We can easily find the first incoming edge by using backward(). To count the remaining edges our minus flags come in handy; In the W array, the next G (non-flagged) belongs to a different node, because we defined W to have minus flags if the source node has the same $k&#x2013;1$ suffix (or, if same-labeled edges also share the same target node).</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/indegree1.png?ssl=1#center" alt loading="lazy"></p>
<p>From here it is simple enough to do a linear scan (or even use select) until the next non-flagged edge; the maximum distance it could be is $\sigma^2$. For larger alphabets, a more efficient method is to use rank instead:</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/indegree2.png?ssl=1#center" alt loading="lazy"></p>
<p>First we find the position of the next non-flagged $G$, which gives us the end point of our range (we already have the start point from the first rank). Then we use rank to calculate how many $G-$ there are to the end position, and subtract the initial rank value from this, giving us how many $G-$ occur within the range.</p>
<p>This is once again a constant number of $O(1)$ function calls, which means $indegree()$ is also $O(1)$.</p>
<h3 id="incoming">Incoming</h3>
<p>Incoming, which returns the predecessor node that begins with the provided symbol, is probably the most difficult operation to implement. However, it does use approaches similar to the previous functions.</p>
<p>Consider this: from indegree(), we already know how to count each of the predecessor nodes. We can access these nodes if we instead use select to iterate over the predecessor nodes, rather than using rank to simply count. Then, to disambiguate them by first character, we can use label().</p>
<p>A linear scan over the predecessors in this fashion would work, but for large alphabets we can use binary search (with a select call before each array access) to support this in $O(k \log \sigma)$ time; $\log \sigma$ for the binary search, where each access is a $O(1)$ select, followed by $O(k)$ to compute the label.</p>
<p>This is demonstrated in the example below:</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/debruijn/incoming.png?ssl=1#center" alt loading="lazy"></p>
<h2 id="conclusion">Conclusion</h2>
<p>In conclusion, by using memory more efficiently, hopefully the cost of genome seqeuencing can be reduced, both proliferating the technology, but also giving way to more advanced population analysis. To that end, we have described a novel approach to representing de Bruijn graphs efficiently, while supporting a full suite of navigation operations quickly. Much of the (BWT-inspired) construction can be done efficiently on disk, but we intend to improve this soon to compete with Minia.</p>
<p>The total space is a theoretical $m(2 + \log{\sigma} + o(1))$ bits in general, or $4m + o(m)$ bits for DNA, given $m$ edges. Using specially modified indexes we can lower this to&#x2028; around 3 bits per edge.</p>
<p>I apologize that an efficient implementation isn&#x2019;t available, nor have I provided experimental results. But if you found this post interesting<br>
you can get your hands dirty with the <a href="https://github.com/alexbowe/debby/blob/0.1.1/debby.py?ref=alexbowe.com">Python implementation I have provided</a>. The results and efficient implementation are on their way (:</p>
<p>And as always, follow me on <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">Twitter</a>, and feel free to send me questions, criticisms, and especially pull requests!</p>
<hr>
<ol>
<li>Pevzner, P. A., Tang, H., and Waterman, M. S. (2001). An Eulerian path approach to DNA fragment assembly. Proceedings of the National Academy of Sciences, 98(17):9748&#x2013;9753. &#xA0;<a href="#fnref-1" title="return to article">&#x21A9;</a></li>
<li>Simpson, J. T., Wong, K., Jackman, S. D., Schein, J. E., Jones, S. J. M., and Birol, I. (2009). ABySS: A parallel assembler for short read sequence data. Genome Research, 19(6):1117&#x2013;1123. &#xA0;<a href="#fnref-2" title="return to article">&#x21A9;</a></li>
<li>Conway, T. C. and Bromage, A. J. (2011). Succinct data structures for assembling large genomes. Bioinformatics, 27(4):479&#x2013;486. &#xA0;<a href="#fnref-3" title="return to article">&#x21A9;</a></li>
<li>Okanohara, D. and Sadakane, K. (2006). Practical Entropy-Compressed Rank/Select Dictionary. &#xA0;<a href="#fnref-4" title="return to article">&#x21A9;</a></li>
<li>R. Chikhi, G. Rizk. (2012) Space-efficient and exact de Bruijn graph representation based on a Bloom filter. WABI. &#xA0;<a href="#fnref-5" title="return to article">&#x21A9;</a></li>
<li>M. Burrows and D. J. Wheeler. A Block-sorting Lossless Data Compression Algorithms. Technical Report 124, Digital SRC Research Report, 1994. &#xA0;<a href="#fnref-6" title="return to article">&#x21A9;</a></li>
<li>P. Ferragina, F. Luccio, G. Manzini, and S. Muthukrishnan. Compressing and indexing labeled trees, with applications. Journal of the ACM, 57(1):4:1&#x2013;4:33, 2009. &#xA0;<a href="#fnref-7" title="return to article">&#x21A9;</a></li>
<li>The paper also describes an online construction method (where we can update by appending), and an iterative method that builds the k-dimensional de Bruijn<br>
graph from an existing (k&#x2013;1)-dimensional de Bruijn graph. &#xA0;<a href="#fnref-8" title="return to article">&#x21A9;</a></li>
<li>We currently use an external merge sort, but intend to optimise as this is where Minia beats us time-wise. &#xA0;<a href="#fnref-9" title="return to article">&#x21A9;</a></li>
<li>This is &#x201C;little o&#x201D; notation, which may be unfamiliar to some people. Intuitively it means &#x201C;grows much slower than&#x201D;, and is stricter than big O.<br>
A formal definition can be found on Wikipedia. &#xA0;<a href="#fnref-10" title="return to article">&#x21A9;</a></li>
<li><a href="http://stackoverflow.com/questions/1801135/what-is-the-meaning-of-o-polylogn-in-particular-how-is-polylogn-defined?ref=alexbowe.com">http://stackoverflow.com/questions/1801135/what-is-the-meaning-of-o-polylogn-in-particular-how-is-polylogn-defined</a> &#xA0;<a href="#fnref-11" title="return to article">&#x21A9;</a></li>
<li>R. Raman, V. Raman, and S. R. Satti. Succinct indexable dictionaries with applications to encoding k-ary trees, prefix sums and multisets. ACM Trans. Algorithms, 3(4), November 2007. &#xA0;<a href="#fnref-12" title="return to article">&#x21A9;</a></li>
<li>P. Ferragina, G. Manzini, V. M &#x308;akinen, and G. Navarro. Compressed Representations of Sequences and Full-Text Indexes. ACM Transactions on Algorithms, 3(2):No. 20, 2006. &#xA0;<a href="#fnref-13" title="return to article">&#x21A9;</a></li>
</ol>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Advice for Programming Interviews]]></title><description><![CDATA[<p>I&#x2019;ve participated in about four <em>sets</em> of Google interviews (of about 3 interviews each) for various positions. I&#x2019;m still not a Googler though, which I guess indicates that I&#x2019;m not the best person to give this advice. However, I think it&#x2019;s about</p>]]></description><link>https://www.alexbowe.com/programming-interviews/</link><guid isPermaLink="false">619714f2c62458003bddca6d</guid><category><![CDATA[career]]></category><category><![CDATA[google]]></category><category><![CDATA[reading]]></category><category><![CDATA[programming interviews]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Sat, 24 Sep 2011 07:18:41 GMT</pubDate><content:encoded><![CDATA[<p>I&#x2019;ve participated in about four <em>sets</em> of Google interviews (of about 3 interviews each) for various positions. I&#x2019;m still not a Googler though, which I guess indicates that I&#x2019;m not the best person to give this advice. However, I think it&#x2019;s about time I put in my 0.002372757892 bitcoins. I recently did exactly this to help my brother prepare for his interviews and the guy kicked ass. If he gets the job I&#x2019;m going to take as much credit for it as I can ;)</p>
<p>During my interviews I didn&#x2019;t sign a NDA, but I do respect <a href="http://igor.moomers.org/interview-questions/?ref=alexbowe.com">the effort that interviewers put into preparing their questions</a> so I&#x2019;m not going to discuss them. That doesn&#x2019;t matter though, because you probably won&#x2019;t get the same questions anyway, and the algorithm stuff is far from the whole story.</p>
<p>This post is mainly about the rituals I perform during preparation for the interviews, and the lessons I have learned from them. I am of the strong opinion that everyone should apply for a job at Google.</p>
<h2 id="why-should-i">Why Should I?!</h2>
<p>Not everyone wants to work for Google, but there are valuable side effects to a Google interview. Even if you don&#x2019;t think you want a job there, or think that you are under-qualified, it is a great idea to just try for one. The absolute worst thing that could happen is that you have fun and learn something.</p>
<p>A couple of the things I learned are algorithms for (weighted) random sampling, queueing, vector calculus, and some cool applications of bloom filters.</p>
<p>The people you will talk to are smart, and it&#x2019;s a fun experience to be able to solve problems with smart and passionate people. One of my interviews was just a discussion about the good and bad parts (in our opinions) of a bunch of programming languages (Scheme, Python, C, C++, Java, Erlang). We discussed <a href="http://mitpress.mit.edu/sicp/?ref=alexbowe.com">SICP</a> and the current state of education, and he recommended some research papers for me to read. All the intriguing questions and back-and-forth made me feel like I was being taught by a modern <a href="http://en.wikipedia.org/wiki/Socratic_method?ref=alexbowe.com">Socrates</a> (perhaps Google should consider offering a Computer Science degree taught entirely with interviews :P).</p>
<p>Sadly, a subsequent interview stumped me because I didn&#x2019;t understand the requirements. Even the stumping interviews have given me a great chance to realise some gaps in my knowledge and refine my approach. I knew that it was important to get the requirements right, but this really drove it home.</p>
<p>I hope I&#x2019;ve got you curious about what you could learn from a Google interview. If you are worried about the possible rejection, treat it as a win in a game of <a href="http://rejectiontherapy.com/rules/?ref=alexbowe.com">Rejection Therapy</a>. You can re-apply as many times as you like, so you could also think of it as <a href="http://en.wikipedia.org/wiki/Test-driven_development?ref=alexbowe.com">TDD</a> for your skills, and you like TDD, right?</p>
<h2 id="how-to-prepare-for-the-interview-technical">How To Prepare for the Interview : Technical</h2>
<p>When you are accepted for a phone interview, Google sends you an email giving you tips on how to prepare. Interestingly, this has been a different list each time. I&#x2019;ll discuss the one I liked the most. They only give advice on the technical side. I will also discuss what I think are some other important aspects to be mindful of.</p>
<p>First of all, you are going to want to practice. Even if you have been coding every day for years, you might not be used to the short question style. <a href="http://projecteuler.net/?ref=alexbowe.com">Project Euler</a> is <em>the bomb</em> for this. You will learn some maths too, which will come in handy, and it builds confidence. Do at least one of these every day until your interview.</p>
<p>You will also want some reading material. Google recommended <a href="http://steve-yegge.blogspot.com/2008/03/get-that-job-at-google.html?ref=alexbowe.com">this post by Steve Yegge</a>, which does a good job of calming you. They also recommended <a href="http://sites.google.com/site/steveyegge2/five-essential-phone-screen-questions?ref=alexbowe.com">another post by Steve Yegge</a> where he covers some styles of questions that are likely to be asked. Yegge recommends a particular book very highly &#x2013; <a href="http://www.algorist.com/?ref=alexbowe.com">The Algorithm Design Manual</a>:</p>
<p><img src="https://i0.wp.com/ecx.images-amazon.com/images/I/71LzXKygXpL.jpg?w=180#center" alt loading="lazy"></p>
<blockquote>
<p>More than any other book it helped me understand just how astonishingly commonplace (and important) <strong>graph problems</strong> are &#x2013; they should be part of every working programmer&#x2019;s toolkit. The book also covers basic data structures and sorting algorithms, which is a nice bonus. But the gold mine is the second half of the book, which is a sort of encyclopedia of <strong>1-pagers</strong> on zillions of useful problems and various ways to solve them, without too much detail. Almost every 1-pager has a simple picture, making it easy to remember. This is a great way to learn how to <strong>identify hundreds of problem types</strong>.</p>
</blockquote>
<p>I haven&#x2019;t read the whole thing, but what I have read of it is eye and mind opening. This wasn&#x2019;t recommended to me directly by Google recruiting staff, but one of my interviewers emailed me a bunch of links after, including a link to the page for this book. There was a recent review of this book featured on <a href="http://eriwen.com/books/best-algorithms-book/?ref=alexbowe.com">Hacker News</a>. It is very good. The author, Steve Skiena, also offers his <a href="http://www.cs.sunysb.edu/~algorith/video-lectures/?ref=alexbowe.com">lecture videos and slides</a> &#x2013; kick back and watch them with a beer after work/uni.</p>
<p><img src="https://i1.wp.com/ecx.images-amazon.com/images/I/41WonSY9PbL._SX258_BO1,204,203,200_.jpg?w=180#center" alt loading="lazy"></p>
<p>If the size of The Algorithm Design Manual is daunting and you want a short book to conquer quickly (for morale reasons), give <a href="http://cm.bell-labs.com/cm/cs/pearls/?ref=alexbowe.com">Programming Pearls</a> a read. Answer as many questions in it as you can.</p>
<p>Additionally, <a href="https://www.interviewcake.com/?ref=alexbowe.com">Interview Cake</a> offers a new approach, which systematises your technical preparation so you can know exactly what to focus on while avoiding becoming overwhelmed. It is a paid service, but they also have a free mailing list with weekly questions to keep you sharp (great for your long-game).</p>
<p>The phone interviews usually are accompanied by a Google doc for you to program into. I usually nominate Python as my preferred language, but usually they make me use C or C++ (they often say I can use Java too). I was rusty with my C++ syntax at the time, but they didn&#x2019;t seem to mind. I just explained things like using templates, even though I can never remember the syntax for the cool <a href="http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315?ref=alexbowe.com">metaprogramming tricks</a>.</p>
<p>Speaking of tricks, you get style points for using features of the language that are less well known. I had an interviewer say he was impressed because I used Pythons pattern matching (simple example: <code>(a, b) = (b, a)</code>). List comprehensions, map/reduce, generators, lambdas, and decorators could all help make you look cool, too. Only use them if they are <em>useful</em> though!</p>
<h2 id="how-to-prepare-for-the-interview-non-technical">How To Prepare for the Interview : Non-Technical</h2>
<p>There will also be a few non-technical questions. When I did my first one, a friend recommended that I have answers ready for cookie-cutter questions like <em>&#x201C;Where do you see yourself in ten years?&#x201D;</em> and <em>&#x201C;Why do you want to work for Google?&#x201D;</em>. Don&#x2019;t bother with that! Do you really think one of the biggest companies in the world will waste their time asking questions like that? Every candidate would say the same answer, something about leading a team and how Google would let you contribute to society, or whatever (great, but <em>everyone</em> wants that).</p>
<p>They <em>will</em> ask you about your previous work and education, though, and pretty much always ask about a technical challenge you overcame. I like to talk about a fun incremental A* search I did at my first job (and why we needed it to be iterative). You can probably think of something, don&#x2019;t stress, but better to think of it before the interview.</p>
<p>And have a question ready for when they let you have your turn. Don&#x2019;t search for <em>&#x201C;good questions to ask in technical interviews&#x201D;</em>, because if it isn&#x2019;t <em>your</em> question, you might be uninterested if the interviewer talks about it for a long time. Think of something that you could have a discussion about, something you are opinionated about. Think of something you hated at a previous job (but don&#x2019;t come across as bitter), how you would improve that, and then ask them if they do that. For me, I was interested in the code review process at Google, and what sort of project they would assign to a beginner.</p>
<p>I know someone who asked questions from <a href="http://www.joelonsoftware.com/articles/fog0000000043.html?ref=alexbowe.com">The Joel Test</a>. The interviewer might recognise these questions and either congratulate you on reading blogs about your field, or quietly yawn to themselves. It&#x2019;s up if you want to take that risk (well, it&#x2019;s not a <em>big</em> risk). I definitely think it&#x2019;s better to ask about something that has the potential to annoy you on a personal level if they don&#x2019;t give you the answer you want ;) it&#x2019;s subtle, but people can detect your healthy arrogance and passion.</p>
<p>If you have a tech blog, refer to it. I&#x2019;ve had interviewers discuss my posts with me (which they found from my resume). Blogs aren&#x2019;t hard to write, and even a few posts on an otherwise barren blog will make you look more thoughtful.</p>
<p>Finally, the absolute best way to prepare for a Google interview is to do more Google interviews, so if you fail, good for you! ;)</p>
<h2 id="just-before-the-interview">Just Before the Interview</h2>
<p>Here are a few things that help me handle the pressure before an interview.</p>
<p>One time I was walking to an interview in the city (not a Google interview) and I was really nervous, even though I didn&#x2019;t care either way if I got the job. I thought about how the nerves wouldn&#x2019;t be an issue after the interview, because I&#x2019;d have already done the scary thing by then. I couldn&#x2019;t time travel, but I instead wondered if there is a way to use up the nerves on something else.</p>
<p>There was a girl walking next to me, so I turned to her and said she was dressed nicely. She said a timid &#x201C;thank you&#x201D; and picked up pace to get away from me. I laughed at my failure, but suddenly I didn&#x2019;t feel so scared about the interview. I think this is a great example of why <a href="http://rejectiontherapy.com/rules/?ref=alexbowe.com">Rejection Therapy</a> is worth experimenting with.</p>
<p>So yeah, talk to a stranger. If you are waiting at home for a phone call though, another thing I do is jack jumps, dancing, or jogging on the spot just to make myself forget the other reason my heart is pounding so fast.</p>
<h2 id="during-the-interview">During the Interview</h2>
<p>If you are doing a phone interview, answer it standing up (you can sit down after) and pace around a little bit. Smile as you talk, as well. You should also take down their name on paper ready to use a few times casually. These are tricks from the infamous <a href="http://en.wikipedia.org/wiki/How_to_Win_Friends_and_Influence_People?ref=alexbowe.com">How to Win Friends and Influence People</a>. Maybe <em>these alone</em> won&#x2019;t make you likeable, but I think it causes you to think about the other person and stop being so self conscious, which helps you to relax. You&#x2019;ll be <a href="http://www.youtube.com/watch?v=u8UE4P8kB-c&amp;ref=alexbowe.com">one charming motherfucking pig</a>.</p>
<p>Take some time to think before answering, and especially to seek clarification on the questions. Ask what the data representation is. I&#x2019;ve found that they tend to say &#x201C;whatever you want&#x201D;. In a graph question, I said &#x201C;Okay, then it&#x2019;s an adjacency matrix&#x201D;, which made the question over and done with in ten seconds. The interviewer seemed to like that, so don&#x2019;t be afraid to be a (humble) smart ass.</p>
<p>You might recognise the adjacency matrix as potentially being a very poor choice, depending on the nature of the graph. I did discuss when this might not be a good option. In fact, for every question, I <strong>start off by describing a naive approach</strong>, and then refine it. This helps to verify the question requirements, and gives you an easy starting point. Maybe you could introspectively comment on agile methodology (Google practises Scrum).</p>
<p>One last thing! Google schedules the interview to be from 45 minutes to an hour. I have had awkward moments at the end of interviews where the interviewer mentions that our time is nearly up, and <em>then</em> asks another question, or asks if I have any questions. It made me feel like he was in a rush, so I didn&#x2019;t feel like expanding on things much. Now, I recommend taking as much time as they will give you. Keep talking until they hang up on you if you have to :) although it might help to say &#x201C;I don&#x2019;t mind if we go over, as long as I&#x2019;m not keeping you from something&#x201D; when the interviewer mentions the time.</p>
<h2 id="reflect">Reflect</h2>
<p><a href="http://steve-yegge.blogspot.com/2008/03/get-that-job-at-google.html?ref=alexbowe.com">Steve Yegge</a> says there are lots of smart Googlers who didn&#x2019;t get in until their third attempt (I still haven&#x2019;t gotten in after my fourth, and I don&#x2019;t think I&#x2019;m stupid). As I mentioned, I&#x2019;m writing this post because I found the process of doing a Google interview at all to be very rewarding.</p>
<p>It is important to reflect afterwards in order to reap the full benefits of interviewing at Google. If you did well, why? But more importantly, if you feel you did poorly, why? Google won&#x2019;t give feedback, which can be a bit depressing at times. After each interview write notes about what you felt went well and what didn&#x2019;t &#x2013; this way you can look back if you don&#x2019;t get the job, and decide what you need to work on. This post is the culmination of my reflections and the notes &#x2013; if you decide to write a blog post, I&#x2019;d enjoy reading it and will link it here.</p>
<p>If you want more blog posts to read about how to get better at Computer Science, I recently found <a href="http://matt.might.net/articles/what-cs-majors-should-know/?ref=alexbowe.com">this post by Matt Might</a> to be a good target to aim for. Check out <a href="http://profshonle.blogspot.com/2010/08/ten-things-every-computer-science-major.html?ref=alexbowe.com">Ten Things Every Computer Science Major Should Learn by Macneil Shonle</a> as well, and my previous post <a href="https://alexbowe.com/advice-to-cs-undergrads?ref=alexbowe.com">Advice to CS Undergrads</a> (the links at the end in particular).</p>
<p>And as always, please read the comments below and add your own thoughts to the discussion. In particular, <a href="https://alexbowe.com/failing-at-google-interviews/?ref=alexbowe.com#comment-917263867">Sumit Arora</a> gave some important advice that I didn&#x2019;t cover.</p>
<p>Have you really read this far? Consider adding me to <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">Twitter</a> and telling me what you thought :)</p>
]]></content:encoded></item><item><title><![CDATA[FM-Indexes and Backwards Search]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/overview-fm.png?resize=519%2C200#center" alt loading="lazy"></p>
<p>Last time (way back in June! I have got to start blogging consistently again) I discussed a gorgeous data structure called the <a href="https://alexbowe.com/wavelet-trees/?ref=alexbowe.com">Wavelet Tree</a>. When a Wavelet Tree is stored using RRR sequences, it can answer rank and select operations in $\mathcal{O}(\log{A})$ time, where A is the</p>]]></description><link>https://www.alexbowe.com/fm-index/</link><guid isPermaLink="false">619714f2c62458003bddca6c</guid><category><![CDATA[algorithm]]></category><category><![CDATA[burrows wheeler]]></category><category><![CDATA[bwt]]></category><category><![CDATA[compression]]></category><category><![CDATA[fm-index]]></category><category><![CDATA[search]]></category><category><![CDATA[suffix array]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Wed, 24 Aug 2011 00:02:53 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/overview-fm.png?resize=519%2C200#center" alt loading="lazy"></p>
<p>Last time (way back in June! I have got to start blogging consistently again) I discussed a gorgeous data structure called the <a href="https://alexbowe.com/wavelet-trees/?ref=alexbowe.com">Wavelet Tree</a>. When a Wavelet Tree is stored using RRR sequences, it can answer rank and select operations in $\mathcal{O}(\log{A})$ time, where A is the size of the alphabet. If the size of the alphabet is $2$, we could just use RRR by itself, which answers rank and select in $\mathcal{O}(1)$ time for binary strings. RRR also compresses the binary strings, and hence compresses a Wavelet Tree which is stored using RRR.</p>
<p>So far so good, but I suspect rank and select queries seem to be of limited use right now (although once you are familiar with the available structures, applications show up often). One of the neatest uses of rank that I&#x2019;ve seen is in substring search, which is certainly a wide reaching problem (for a very recent application to genome assembly, see Jared Simpson&#x2019;s paper from 2010 called <em>Efficient construction of an assembly string graph using the FM-index</em>).</p>
<p><strong>Note</strong> that arrays and strings are one-based (not zero-based).</p>
<h1 id="suffixarrays">Suffix Arrays</h1>
<p>There is a variety of Suffix Array construction algorithms, including some $\mathcal{O}(N)$ ones (Puglisi et al. 2007). However, I will explain it from the most common (and intuitive) angle.</p>
<p>In its simplest form, a suffix array can be constructed for a string $S[1..N]$ like so:</p>
<ol>
<li>Construct an array of pointers to all suffixes $S[1..N], S[2..N], &#x2026;, S[N..N]$.</li>
<li>Sort these pointers by the lexicographical (i.e. alphabetical) ordering of their associated suffixes.</li>
</ol>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/mississippi.png?resize=264%2C38#center" alt loading="lazy"></p>
<p>For example, the sorting of the string <code>&apos;mississippi&apos;</code> with terminating character <code>$</code> would look like this:</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/mississippi-sa-sort.png?resize=332%2C218#center" alt loading="lazy"></p>
<h1 id="burrowswheelertransform">Burrows-Wheeler Transform</h1>
<p>The <a href="http://en.wikipedia.org/wiki/Burrows-Wheeler_transform?ref=alexbowe.com">Burrows-Wheeler Transform</a> (BWT) is a was developed by Burrows and Wheeler to reversibly permute a string in such a way that characters from repeated substrings would be clustered together. It was useful for compression schemes such as run-length encoding.</p>
<p>It is not the point of this blog to explain how it works, but it is closely linked to Suffix Arrays: $BWT[i] = S[SA[i] &#x2013; 1, BWT[1] = \$ $ (it wraps around) for the original string $S$, Suffix Array $SA$, and Burrows-Wheeler Transform string $BWT$. In other words, the $i^{th}$ symbol of the BWT is the symbol <em>just before</em> the $i^{th}$ <em>suffix</em>. See the image below:</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/mississippi-sa.png?resize=259%2C219#center" alt loading="lazy"></p>
<p>In particular, $BWT[1] = S[SA[1] &#x2013; 1] = S[12 &#x2013; 1] = S[11] = i$ (or the $11^{th}$ symbol from the original string <code>&apos;mississippi&apos;</code>).</p>
<p>Ferragina and Manzini (Ferragina et al. 2000) recommended that a BWT be paired with a Suffix Array, creating the so-called FM-Index, which enables backward search. The BWT also lets us reconstruct the original string $S$ (not covered in this blog), allowing us to discard the original document &#x2013; indexes with this property are known as <em>self indexes</em>.</p>
<h1 id="backwardsearch">Backward Search</h1>
<p>This is where rank comes in. If it is hard to follow (it is certainly not easy to explain) then hang in there until the example, which should clear things up.</p>
<p>Since any pattern $P$ in $S$ (the original string) is a <em>prefix</em> of a <em>suffix</em> (our Suffix Array stores suffixes), and because the suffixes are lexicographically ordered, all occurrences of a search pattern $P$ lie in a contiguous portion of the Suffix Array. One way to hone in on our search term is to use successive binary searches. Storing the BWT lets us use a cooler way, though&#x2026;</p>
<p>Backward search instead utilises the BWT in a series of paired <a href="https://alexbowe.com/wavelet-trees?ref=alexbowe.com">rank queries</a> (which can be answered with a Wavelet Tree, for example), improving the query performance considerably.<br>
Backward search issues $p$ pairs of rank queries, where $p$ denotes the length of the pattern $P$. The paired rank queries are:</p>
<p>$$<br>
\begin{align}<br>
s^\prime &amp;= C[P[i]] + rank(s-1, P[i]) + 1 \\<br>
e^\prime &amp;= C[P[i]] + rank(e, P[i])<br>
\end{align}<br>
$$</p>
<p>Where $s$ denotes the start of the range and $e$ is the end of the range. Initially $s = 1$ and $e = N$. If at any stage $e \lt s$, then $P$ doesn&#x2019;t exist in $S$.</p>
<p>As for $C$&#x2026; $C$ is a lookup table containing the count of all symbols in our alphabet which sort lexicographically before $P[i]$. What does this mean? Well, $C$ would look like this:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/C-table.png?resize=168%2C62#center" alt loading="lazy"></p>
<p>Which means that there aren&#x2019;t any characters in $S$ that sort before $\$$, one that sorts before $i$ (the $\$$), five that sort before $m$ (the $\$$ and the $i$s) and so on. In the example I store it in a less compact way as the column $F$ (which contains the first symbol for each suffix &#x2013; essentially the same information, since each suffix is sorted), so it might be easier to follow (wishful thinking).</p>
<p>Why is this called backwards search? Well, our index variable $i$ actually starts at $|P|$ (the last character of our search pattern), and decreases to $1$. This maintains the invariant that $SA[s..e]$ contains all the suffixes of which $P[i..|P|]$ is a prefix, and hence all locations of $P[i..|P|]$ in $S$.</p>
<h1 id="example">Example</h1>
<p>Let&#x2019;s practice this magic spell&#x2026;<br>
Let our search pattern P be <code>&apos;iss&apos;</code>, and our string $S$ be <code>&apos;mississippi&apos;</code>. Starting with $i = 3$, $c = P[i] = $<code>&apos;s&apos;</code>. The working for each rank query is shown below each figure. I&#x2019;m representing the current symbol as $c$ to avoid confusion between <code>&apos;s&apos;</code> and $s$ and $s^\prime$.</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/bwt-1.png?resize=252%2C203#center" alt loading="lazy"></p>
<p>Here (above) we are at the first stage of backwards search for <code>&apos;iss&apos;</code> on <code>&apos;mississippi&apos;</code> string &#x2013; before any rank queries have been made.<br>
<strong>Note</strong>: we do not store the document anymore &#x2013; the gray text &#x2013; and we don&#x2019;t store $F$, but instead store $C$ &#x2013; see section on <strong>Backward Search</strong>.</p>
<p>Starting from $s=1$ and $e=12$ (as above) and $c = P[i] =$ <code>&apos;s&apos;</code> where $i = 3$, we make our first two rank queries:</p>
<p>$$<br>
\begin{align}<br>
s^\prime &amp;= C[c] + rank(0, c) + 1 = 8 + 0 + 1 = 9 \\<br>
e^\prime &amp;= C[c] + rank(12, c) = 8 + 4 = 12<br>
\end{align}<br>
$$</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/bwt-2.png?resize=253%2C204#center" alt loading="lazy"></p>
<p>After the above, we are now at the <em>second</em> stage of backwards search for <code>&apos;iss&apos;</code> on <code>&apos;mississippi&apos;</code> string. All the occurrences of <code>&apos;s&apos;</code> lie in $SA[9..12]$.</p>
<p>From $s = 9$ and $e = 11$, and $c = P[i] =$ <code>&apos;s&apos;</code> where $i = 2$, our next two rank queries are:</p>
<p>$$<br>
\begin{align}<br>
s^{\prime\prime} &amp;= C[c] + rank(8, c) + 1 = 8 + 2 + 1 = 11 \\<br>
e^{\prime\prime} &amp;= C[c] + rank(12, c) = 8 + 4 = 12<br>
\end{align}<br>
$$</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/bwt-3.png?resize=260%2C205#center" alt loading="lazy"></p>
<p>We are now at the <em>third</em> stage of backwards search for <code>&apos;iss&apos;</code> on <code>&apos;mississippi&apos;</code> string. All the occurrences of <code>&apos;ss&apos;</code> lie in $SA[11..12]$.</p>
<p>From $s = 11$ and $e = 12$, and $c = P[i] =$ <code>&apos;i&apos;</code> where $i = 1$, our final two rank queries are:</p>
<p>$$<br>
\begin{align}<br>
s^{\prime\prime\prime} &amp;= C[c] + rank(10, c) + 1 = 1 + 2 + 1 = 4 \\<br>
e^{\prime\prime\prime} &amp;= C[c] + rank(12, c) = 1 + 4 = 5<br>
\end{align}<br>
$$</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/bwt-4.png?resize=252%2C209#center" alt loading="lazy"></p>
<p>This is the <em>fourth</em> and final stage of our backwards search for <code>&apos;iss&apos;</code> in the string <code>&apos;mississippi&apos;</code>. All the occurrences of <code>&apos;iss&apos;</code> lie in $SA[4..5]$.</p>
<p>It impresses me every time&#x2026;</p>
<h1 id="playtime">Play Time</h1>
<p>No doubt you want to get your hands dirty. I have played around with <a href="http://code.google.com/p/libdivsufsort/?ref=alexbowe.com">libdivsufsort</a> before, although I <em>think</em> you may have to implement backward search yourself (it&#x2019;d be a good exercise), since it doesn&#x2019;t appear to come with fast rank query providers. For rank structures for your BWT you might want to check out <a href="http://libcds.recoded.cl/?ref=alexbowe.com">libcds</a>. In fact there are heaps out there, but I haven&#x2019;t used them yet.</p>
<p>Also, please comment here if you develop something cool with it :) and as always, if you have journeyed this far, consider following me on Twitter: <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">@alexbowe</a>.</p>
<h1 id="bibliography">Bibliography</h1>
<p>Ferragina, P. and Manzini, G. (2000). Opportunistic data structures with applications. Proceedings of the 41st Annual IEEE Symposium on Foundations of Computer Science, pages 390&#x2013;398.</p>
<p>S. J. Puglisi, W. F. Smyth, and A. Turpin. A taxonomy of suffix array construction algorithms. ACM Computing Surveys, 39(2):1&#x2013;31, 2007.<br>
Jared Simpson&#x2019;s paper from 2010 called *Efficient construction of an assembly string graph using the FM-index.</p>
<p>Simpson, J. T. and Durbin, R. (2010). Efficient construction of an assembly string graph using the FM-index. Bioinformatics, 26(12):i367&#x2013;i373.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Wavelet Trees: an Introduction]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/overview.png?resize=336%2C220#center" alt="A Wavelet Tree provides fast querying over a string using a hierarchy of compressed bitmaps." loading="lazy"></p>
<p>Today I will talk about an elegant way of answering rank queries on sequences over <em>larger alphabets</em> &#x2013; a structure called the Wavelet Tree. In <a href="https://alexbowe.com/yarrr-me-hearties?ref=alexbowe.com">my last post</a> I introduced a data structure called RRR, which is used to quickly answer rank queries on <em>binary</em> sequences, and provide implicit compression.</p>]]></description><link>https://www.alexbowe.com/wavelet-trees/</link><guid isPermaLink="false">619714f2c62458003bddca6b</guid><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Tue, 28 Jun 2011 11:35:50 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/overview.png?resize=336%2C220#center" alt="A Wavelet Tree provides fast querying over a string using a hierarchy of compressed bitmaps." loading="lazy"></p>
<p>Today I will talk about an elegant way of answering rank queries on sequences over <em>larger alphabets</em> &#x2013; a structure called the Wavelet Tree. In <a href="https://alexbowe.com/yarrr-me-hearties?ref=alexbowe.com">my last post</a> I introduced a data structure called RRR, which is used to quickly answer rank queries on <em>binary</em> sequences, and provide implicit compression.</p>
<p>A <em>Wavelet Tree</em> organises a string into a hierarchy of bit vectors. A rank query has time complexity is $\mathcal{O}(\log_2{A})$, where $A$ is the size of the alphabet. It was introduced by Grossi, Gupta and Vitter in their 2003 paper <em>High-order entropy-compressed text indexes</em> [4] (see the <em>Further Reading</em> section for more papers). It has since been featured in many papers [1, 2, 3, 5, 6].</p>
<p>If you store the bit vectors in RRR sequences, it may take less space than the original sequence. Alternatively, you could store the bit vectors in the rank indexes proposed by Sadakane and Okonohara [7]. It has a different approach to compression. I will talk about it another time ;) &#x2013; fortunately, I will be studying under Sadakane-sensei at a later date (<em>update: now I&#x2019;m doing my Ph.D. under him in Tokyo</em>).</p>
<p>In a different future post, I will show how Suffix Arrays can be used to find arbitrary patterns of length $P$, by issuing $2P$ rank queries. If using a Wavelet Tree, this means a pattern search has $\mathcal{O}(P \log_2{A})$ time complexity, that is, the size of size of the &#x2018;haystack&#x2019; doesn&#x2019;t matter, it instead depends on the size of the &#x2018;needle&#x2019; and size of the alphabet.</p>
<h2 id="constructingawavelettree">Constructing a Wavelet Tree</h2>
<p>A Wavelet Tree converts a string into a balanced binary-tree of bit vectors, where a $0$ replaces half of the symbols, and a $1$ replaces the other half. This creates <em>ambiguity</em>, but at each level this alphabet is filtered and re-encoded, so the ambiguity lessens, until there is no ambiguity at all.</p>
<p>The tree is defined recursively as follows:</p>
<ol>
<li>Take the alphabet of the string, and encode the first half as $0$, the second half as $1$: $\{ a, b, c, d \}$ would become $\{ 0, 0, 1, 1 \}$;</li>
<li>Group each $0$-encoded symbol, $\{ a, b \}$, as a sub-tree;</li>
<li>Group each $1$-encoded symbol, $\{ c, d \}$, as a sub-tree;</li>
<li>Reapply this to each subtree recursively until there is only one or two symbols left (when a $0$ or $1$ can only mean one thing).</li>
</ol>
<p>For the string <code>&quot;Peter Piper picked a peck of pickled peppers&quot;</code> (spaces and a string terminator have been represented as $\_$ and $\$$ respectively, due to convention in the literature) the Wavelet Tree would look like this:</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/binwt.png?resize=440%2C261#center" alt="A Wavelet Tree for the string &apos;Peter Piper picked a peck of pickled peppers&apos;." loading="lazy"></p>
<p><em>note: the strings aren&#x2019;t actually stored, but are shown here for convenience</em></p>
<p>It has the alphabet $\{ \$, P, \_, a, c, d, e, f, i, k, l, o, p, r, s, t \}$, which would be mapped to $\{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 \}$. So, for example, $\$$ would map to $0$, and $r$ would map to $1$.</p>
<p>The left subtree is created by taking just the 0-encoded symbols $\{ \$, P, \_, a, c, d, e, f \}$ and then re-encoding them by dividing this <em>new</em> alphabet: $\{ 0, 0, 0, 0, 1, 1, 1, 1 \}$. Note that on the first level an $e$ would be encoded as a $0$, but now it is encoded as a $1$ (it becomes a $0$ again at a leaf node).</p>
<p>We can store the bit vectors in RRR structures for fast binary rank queries (which are needed, as described below), and compression :) In fact, since it is a balanced tree, we can concatenate each of the levels and store it as one single bit vector.</p>
<h2 id="queryingawavelettree">Querying a Wavelet Tree</h2>
<p>Recall from <a href="https://alexbowe.com/yarrr-me-hearties?ref=alexbowe.com">my last post</a> that a rank query is the count of $1$-bits up to a specified position. Rank queries over larger alphabets are analogous &#x2013; instead of a $1$, it may be any other symbol:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/rankalpha.png?resize=315%2C129#center" alt="An example of the rank function." loading="lazy"></p>
<p>After the tree is constructed, a rank query can be done with log $A$ ($A$ is alphabet size) <em>binary</em> rank queries on the bit vectors &#x2013; $\mathcal{O}(1)$ if you store them in RRR or another binary rank index. The encoding at each internal node may be ambiguous, but of course it isn&#x2019;t useless &#x2013; we use the ambiguous encoding to guide us to the appropriate sub-tree, and keep doing so until we have our answer.</p>
<p>For example, if we wanted to know $rank(5, e)$, we use the following procedure which is illustrated below. We know that $e$ is encoded as $0$ at this level, so we take the <em>binary</em> rank query of $0$ at position $5$:</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/binwt-query_1.png?resize=378%2C136#center" alt="The first step in a Wavelet Tree rank query." loading="lazy"></p>
<p>Which is $4$, which we then use to indicate where to rank in the $0$-child: the $4^{th}$ bit (or the bit at position $3$, due to $0$-basing). We know to query the $0$-child, since that is what $e$ was encoded as at the parent level. We then repeat this recursively:</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/binwt-query.png?resize=378%2C288#center" alt="A completed Wavelet Tree rank query." loading="lazy"></p>
<p>At a leaf node we have our answer. I would love to explain why this works, but it is fun and rewarding to think about it yourself ;)</p>
<p>There are also ways to provide fast select queries, but once again I will leave that up to you to research. The curious among you might also be interested in the Huffman-Shaped Wavelet Tree described by M&#xE4;kinen and Navarro [5].</p>
<h2 id="usingyournewpowersforgood">Using Your New Powers for Good</h2>
<p>Feel free to implement this yourself, but if you want to get your hands dirty right away, all-around-clever-guy <a href="http://fclaude.recoded.cl/?ref=alexbowe.com">Francisco Claude</a> has made an implementation available in his <a href="http://libcds.recoded.cl/?ref=alexbowe.com">Compressed Data Structure Library (libcds)</a>. If you create something neat with it be sure to report back ;)</p>
<p>Update: <a href="http://siganakis.com/challenge-design-a-data-structure-thats-small?ref=alexbowe.com">Terence Siganakis</a> wrote a blog post about Wavelet Trees that made it to the front page of Hacker News, encouraging an interesting discussion. The discussion is <a href="http://news.ycombinator.com/item?id=3650657&amp;ref=alexbowe.com">here</a>.</p>
<p>And if you read this far, consider following me on Twitter: <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">@alexbowe</a>.</p>
<h2 id="furtherreading">Further Reading</h2>
<p>I didn&#x2019;t want to saturate this blog post with proofs and other details, since it was meant to be a light introduction. If you want to dive deeper into this beautiful structure, check out the following papers:</p>
<p>[1] F. Claude and G. Navarro. Practical rank/select queries over arbitrary sequences. In Proceedings of the 15th International Symposium on String Processing and Information Retrieval (SPIRE), LNCS 5280, pages 176&#x2013;187. Springer, 2008.</p>
<p>[2] P. Ferragina, R. Giancarlo, and G. Manzini. The myriad virtues of wavelet trees. Information and Computation, 207(8):849&#x2013;866, 2009.</p>
<p>[3] P. Ferragina, G. Manzini, V. M &#x308;akinen, and G. Navarro. Compressed representations of sequences and full-text indexes. ACM Transactions on Algorithms, 3(2):20, 2007.</p>
<p>[4] R. Grossi, A. Gupta, and J. Vitter. High-order entropy-compressed text indexes. In Proceedings of the 14th annual ACM-SIAM symposium on Dis- crete algorithms, pages 841&#x2013;850. Society for Industrial and Applied Mathematics, 2003.</p>
<p>[5] V. M&#xE4;kinen and G. Navarro. Succinct suffix arrays based on run-length encoding. Nordic Journal of Computing, 12(1):40&#x2013;66, 2005.</p>
<p>[6] V. M&#xE4;kinen and G. Navarro. Implicit compression boosting with applications to self-indexing. In Proceedings of the 14th International Symposium on String Processing and Information Retrieval (SPIRE), LNCS 4726, pages 214&#x2013;226. Springer, 2007.</p>
<p>[7] D. Okanohara and K. Sadakane. Practical entropy-compressed rank/select dictionary. Arxiv Computing Research Repository, abs/cs/0610001, 2006.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[RRR: A Succinct Rank/Select Index for Bit Vectors]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/intro.png#center" alt loading="lazy"></p>
<p>This blog post will give an overview of a static bitsequence data structure known as RRR, which answers arbitrary length rank queries in $\mathcal{O}(1)$ time, and provides implicit compression.</p>
<p>As my blog is informal, I give an introduction to this structure from a birds eye view. If you</p>]]></description><link>https://www.alexbowe.com/rrr/</link><guid isPermaLink="false">619714f2c62458003bddca6a</guid><category><![CDATA[algorithm]]></category><category><![CDATA[binary]]></category><category><![CDATA[compression]]></category><category><![CDATA[succinct]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Wed, 01 Jun 2011 15:12:40 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/intro.png#center" alt loading="lazy"></p>
<p>This blog post will give an overview of a static bitsequence data structure known as RRR, which answers arbitrary length rank queries in $\mathcal{O}(1)$ time, and provides implicit compression.</p>
<p>As my blog is informal, I give an introduction to this structure from a birds eye view. If you want, <a href="https://github.com/alexbowe/wavelet-paper/raw/thesis/thesis.pdf?ref=alexbowe.com">read my thesis</a> for a version with better markup, and follow the citations for proofs by people smarter than myself :)</p>
<p>My intended future posts will cover the other aspects of my thesis, including generalising RRR (for sequences over small alphabets), Wavelet Trees (which answer rank queries over bigger alphabets), and Suffix Arrays (a text index which &#x2013; when combined with the above structures &#x2013; can answer queries in $\mathcal{O}(P \log_2 A)$ time, when $P$ is the length of the search pattern, and $A$ is the alphabet size).</p>
<p><strong>Update:</strong> I have now posted about Wavelet Trees! Check it out <a href="https://alexbowe.com/wavelet-trees?ref=alexbowe.com">here</a>.</p>
<h2 id="exampleproblem">Example Problem</h2>
<p>Cracking the Oyster, the first column of <a href="http://www.cs.bell-labs.com/cm/cs/pearls/cto.html?ref=alexbowe.com">Programming Pearls</a>, opens with a programmer asking for advice when sorting around ten million unique seven-digit integers &#x2013; phone numbers.</p>
<p>After some discussion, the author <a href="http://www.cs.bell-labs.com/cm/cs/pearls/sec014.html?ref=alexbowe.com">concludes</a> that a <a href="http://en.wikipedia.org/wiki/Bit_array?ref=alexbowe.com">bitmap</a> should be used. If we wanted to store ten million integers, we could use an array of $32$-bit integers, consuming $38$ MB, or we could represent our numbers as positions on a number line.</p>
<p>All of these phone numbers will be within the range $[0000000, 9999999]$. To represent the presence of these numbers, we only need a bitmap $10^7$ bits long, about $1$ MB, which would represent our number line. Then, for a bitmap $M$, if we want to store phone number $p$, we set the bit $M[p]$ to $1$. Sorting would involve setting the numbers that are present to $1$, then iterating over the bitmap, printing the positions of the $1$-bits &#x2013; $\mathcal{O}(N)$ time.</p>
<p>In the following sections, I will detail operations that can be done on bitmaps, named rank and select, and explain how to answer rank queries in $\mathcal{O}(1)$ time, and implicitly compress the bitmap. Using rank and select, a compressed bitmap can be a very powerful way to store sets. This isn&#x2019;t limited to just sets of numbers, all sorts of things, such as tree or graph nodes for example.</p>
<h2 id="extensionrank">Extension: Rank</h2>
<p>Allow me to extend the problem. I want to query our simple phone number database to see how many phone numbers are allocated within the range $[0005000, 0080000]$. I could iterate over that range and update a counter whenever I encounter a $1$-bit. Actually, this operation is what is known as a <strong>rank</strong> operation.</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/rankbin.png?resize=250%2C124#center" alt loading="lazy"></p>
<p>The operation $rank(i)$ is defined as the number of set bits ($1$s) in the range $[0, i]$ (or $[0, i)$ in some papers). In the bitstring above, the answer to $rank(5)$ is $3$&#x2026; This is a generalisation of the <a href="http://en.wikipedia.org/wiki/Popcount?ref=alexbowe.com">popcount</a> operation which counts all set bits, which I have discussed before (<a href="https://alexbowe.com/metaprogramming-erlang/?ref=alexbowe.com">here</a> and <a href="https://alexbowe.com/popcount-permutations/?ref=alexbowe.com">here</a>). $rank(i)$ can be implemented by left-shifting $L &#x2013; i$ bits (where $L$ is the length of the datatype you are using, int, long, etc) to remove the unwanted bits, then calling $popcount$ on the resulting value. This could be done iteratively over an array if you want, but I will discuss a much faster way below.</p>
<p>Then, the above question can be answered as: $rank(0080000) &#x2013; rank(0005000 &#x2013; 1)$. This will give us just the number of $1$s between $0005000$ and $0080000$.</p>
<p>This isn&#x2019;t the only place we would use a popcounts; it happens that popcounts are common enough that we want to optimise them. Check out <a href="http://www.valuedlessons.com/2009/01/popcount-in-python-with-benchmarks.html?ref=alexbowe.com">this blog post at valuedlessons.com</a> for a discussion and empirical comparison of several fast approaches.</p>
<h2 id="rrr">RRR</h2>
<p>As it happens, we can build a data structure for static bitmaps that answers rank queries in $\mathcal{O}(1)$ time, <em>and</em> provides implicit compression. It is what is known as a succinct data structure, which means that even though it is compressed, we don&#x2019;t need to decompress the whole thing t operate on it efficiently. Sadakane (a respected researcher in succinct data structures) gives a nice analogy in his <a href="http://www.nii.ac.jp/userimg/intro/en/sadakane_en.pdf?ref=alexbowe.com">introduction of the field</a>, likening it to forcing dehydrated noodles apart with your chopsticks (decompression) as you are rehydrating them, but before the whole thing is fully cooked and separated. This allows you to keep some of the noodles compressed while you eat the decompressed fragment.</p>
<p>Since it is static it isn&#x2019;t well suited for a bitmap which you want to update (although work has been done toward this), it is still really cool :)</p>
<p>The structure I&#x2019;m referring to is named RRR. It sounds like a radio station, but it is named after its creators: <a href="http://portal.acm.org/citation.cfm?id=545411&amp;ref=alexbowe.com">Raman, Raman, Rao, from their 2002 paper <em>Succinct indexable dictionaries with applications to encoding $k$-ary trees and multisets</em></a>. Its a data structure I had to become intimately involved with for <a href="https://github.com/alexbowe/wavelet-paper/raw/thesis/thesis.pdf?ref=alexbowe.com">my honours thesis</a>, where I extended it for sequences of larger (but still small) alphabets. If you want to answer rank queries on large alphabets, a wavelet tree might be what you are after, but that will be covered in a different blog post (or you could read my thesis!).</p>
<p>In my <a href="https://alexbowe.com/48392639?ref=alexbowe.com">last post (Generating Binary Permutations in Popcount Order)</a> I discussed how to compress a bitstring by replacing blocks of a certain blocksize with their corresponding pop number, and (variable length) offset into a lookup table. I briefly mentioned building an index over it to improve lookup as well.</p>
<h2 id="rrrconstruction">RRR: Construction</h2>
<p>To construct a RRR sequence we divide our bitmap into blocks, as I mentioned <a href="https://alexbowe.com/generating-binary-permutations-in-popcount-or?ref=alexbowe.com">in my previous blog post</a>. These are grouped in <em>superblocks</em>, too, which allows us to construct an index to enable $\mathcal{O}(1)$ rank queries. In the following image, I have fragmented the bitmap using a blocksize of $b = 5$, and grouped them with a superblock factor of $f = 3$ &#x2013; so each superblock is three blocks.</p>
<p><img src="https://i0.wp.com/alexbowe.s3.amazonaws.com/blog/blocks.png?resize=500%2C149#center" alt loading="lazy"></p>
<p>First we replace the blocks with a pair of values, a <em>class</em> value $C$ and offset value $O$, which are used together as a lookup key into a table of precomputed (small &#x2013; for each possible block only) ranks &#x2013; this is demonstrated in the figure below. This is the same as <a href="https://alexbowe.com/generating-binary-permutations-in-popcount-or?ref=alexbowe.com">the previous blog post</a>, although in that I called the &#x201C;class&#x201D; $P$. This is because the class of a block is defined as the popcount &#x2013; the number of set bits &#x2013; in the block: $class(B) = popcount(B)$ for block $B$.</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/compress.png?resize=379%2C235#center" alt loading="lazy"></p>
<p>The table is shared among all your RRR sequences, and is in fact a table of tables, where $C$ points to the first element for the ranks of a given popcount:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/binary-g-table.png?resize=390%2C399#center" alt loading="lazy"></p>
<p>For this table (let&#x2019;s call it $G$), for a given class $C$, the sub-table at $G[C]$ has $b \choose C$ entries, which correspond to all possible permutations that have a popcount of $C$. This means that while our $C$ values will always be $\log{b + 1}$ (the number of bits to represent values $0, 1, 2&#x2026; b$ &#x2013; these are all possible popcount values for the blocksize), but our $O$ values will vary in size, requiring $\log{b \choose C}$ bits (oh yeah, and of course I&#x2019;m using $\log_2$ here :)). During a query, we can use our $C$ values to work out how many bits will follow for the $O$ values.</p>
<p>Using this approach alone we get the compression, but not $\mathcal{O}(1)$ ranks. $C$ is fixed width, the compression comes from $O$ being varied width.</p>
<p>In order to get the $\mathcal{O}(1)$ ranks we use a method discussed by <a href="http://www.springerlink.com/content/yv33538123433477/?ref=alexbowe.com">Munro in <em>Tables</em>, 1996</a>. This is where the superblocks come in to play:</p>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/superblocks.png?resize=476%2C304#center" alt loading="lazy"></p>
<p>For each superblock boundary we store the global rank up to that position. We also store a prefix sum of the bits, which gives us the address to the first block in the next superblock (since it is variable length!). This allows us to not require iterating over the whole RRR sequence, but instead going straight to the required superblock. We will only need to iterate over the blocks within a superblock, so it is now bound by whatever your superblock factor is.</p>
<h2 id="rrrquerying">RRR: Querying</h2>
<p>To calculate $rank(i)$:</p>
<ol>
<li>Calculate which block our index is in as $i_b = \frac{i}{b}$. ($i_b$ is the global index of the block)</li>
<li>Calculate which superblock our block resides in as $i_s = \frac{i_b}{f}$. ($i_s$ is the index of the superblock)</li>
<li>Set result to the sum of previous ranks at is boundary (which is pre-calculated).</li>
<li>Using each blocks class-offset pair $(c,o)$ after the boundary at is, add the rank for that entire block to result.</li>
<li>Repeat previous step until we reach $i_b$. We then add $rank(j,c)$ (from $i_b$, not the global rank) to our result, where $j = i \mod b$, and is the position we are querying local to $i_b$. Our final answer is the result.</li>
</ol>
<h2 id="select">Select</h2>
<p><img src="https://i1.wp.com/alexbowe.s3.amazonaws.com/blog/selectbin.png?resize=250%2C103#center" alt loading="lazy"></p>
<p>Select is the inverse operation to rank; it answers the question &#x201C;at which position is the $i^{th}$ set bit?&#x201D;. To tie this in with the phone numbers example, maybe we want to find out the fiftieth phone number in the set (excluding unassigned numbers). This is a way we can index just the present elements of a bitmap. It turns out select can be answered in $\mathcal{O}(1)$ time as well. I won&#x2019;t cover select here, as my future posts (and thesis) will mainly use rank. You can read about it in the <a href="http://portal.acm.org/citation.cfm?id=545411&amp;ref=alexbowe.com">RRR paper</a>.</p>
<h2 id="goforthand">Go Forth and&#x2026;</h2>
<p>Feel free to implement this (somewhat complicated) data structure yourself, or you can use a pre-rolled one by my friend <a href="http://fclaude.recoded.cl/?ref=alexbowe.com">Francisco Claude</a> in his <a href="http://libcds.recoded.cl/?ref=alexbowe.com">LIBCDS &#x2013; Compressed Data Structure Library</a>.</p>
<p>If you read this far, consider <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">adding me to twitter</a> :) or you may enjoy reading <a href="https://alexbowe.com/wavelet-trees?ref=alexbowe.com">my post on Wavelet Trees</a>.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Generating Binary Permutations in Popcount Order]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/bitmap.png?resize=241%2C114#center" alt loading="lazy"></p>
<p>I&#x2019;ve been keeping an eye on the search terms that land people at my site, and although I get the occasional &#x201C;alex bowe: fact or fiction&#x201D; and &#x201C;alex bowe bad ass phd student&#x201D; queries (the frequency strangely increased when I mentioned this on <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">Twitter</a></p>]]></description><link>https://www.alexbowe.com/popcount-permutations/</link><guid isPermaLink="false">619714f2c62458003bddca69</guid><category><![CDATA[algorithm]]></category><category><![CDATA[binary]]></category><category><![CDATA[bit hacks]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Mon, 09 May 2011 00:11:05 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/bitmap.png?resize=241%2C114#center" alt loading="lazy"></p>
<p>I&#x2019;ve been keeping an eye on the search terms that land people at my site, and although I get the occasional &#x201C;alex bowe: fact or fiction&#x201D; and &#x201C;alex bowe bad ass phd student&#x201D; queries (the frequency strangely increased when I mentioned this on <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">Twitter</a>) I also get some queries that relate to the actual content.</p>
<p>One query I received recently was &#x201C;generating integers in popcount order&#x201D;, I guess because I mentioned popcounts (the number of 1-bits in a binary string) in a previous post, but the post wasn&#x2019;t able to answer that visitors question.</p>
<p>What would this be used for? Among other applications, I have used it for generating a table of numbers ordered by popcount, which I used in a compression algorithm: by breaking a bitstring into fixed-length chunks (of B bits) and replacing them with a (P, O) pair, where P is the block&#x2019;s popcount which can be used to point to the table where each entry has the popcount P, and O is the offset in that subtable. Then P can be stored with log2(B + 1) bits &#x2013; we need to represent all possible P values from 0 to B &#x2013; and O can be stored with log2(binomial(B, P)) bits.</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/compress.png?resize=379%2C235#center" alt loading="lazy"></p>
<p>Note that the bit-length of P varies; binomial represents the binomial coefficient, which can be seen in Pascal&#x2019;s triangle expanded to row 5:</p>
<p><img src="https://i2.wp.com/alexbowe.s3.amazonaws.com/blog/pascal.png?resize=198%2C155#center" alt loading="lazy"></p>
<p>So binomial(5, x) for x = 0, 1, &#x2026; , 5 yields the sequence 1, 5, 10, 10, 5, 1 &#x2013; some things take more bits than others. Once you know the P value, you will know how many bits the O value is, so you can read it that way. This means access is O(N) (since each values position relies on the previous P values), but you can build an index on top of that to allow O(1) lookup. But all this is a story for another time ;) [1].</p>
<p>Here is the code:</p>
<pre><code>def next_perm(v):
    &quot;&quot;&quot;
    Generates next permutation with a given amount of set bits,
    given the previous lexicographical value.
    Taken from http://graphics.stanford.edu/~seander/bithacks.html
    &quot;&quot;&quot;
    t = (v | ( v - 1)) + 1
    w = t | ((((t &amp; -t) / (v &amp; -v)) &gt;&gt; 1) - 1)
    return w
</code></pre>
<p>This will take a number with a certain popcount, and generate the next number with the same popcount. For example, if you feed it 7, which is 111 in binary,<br>
you will get 1011 back &#x2013; or 11 &#x2013; the next number with the same popcount (lexicographically speaking).</p>
<p>To find the first number of a given popcount, you can use this:</p>
<pre><code>def element_0(c):
    &quot;&quot;&quot;Generates first permutation with a given amount
       of set bits, which is used to generate the rest.&quot;&quot;&quot;
    return (1 &lt;&lt; c) - 1
</code></pre>
<p>I should clear up what lexicographically means in the context of numbers. Well, it&#x2019;s actually the same as any other symbols (such as an alphabet), 0 is the symbol that comes before 1 (if it helps, you can picture 0 as a and 1 as b):</p>
<pre><code>00111 aabbb
01011 ababb
01101 abbab
01110 abbba
10011 baabb
10101 babab
10110 babba
11001 bbaab
11010 bbaba
11100 bbbaa
</code></pre>
<h2 id="psuedocode">Psuedocode</h2>
<p>Looking at the above pattern, here is some loose pseudocode that may help us understand how the above bithacks work:</p>
<ol>
<li>Set i to the position of the rightmost bit</li>
<li>Stop if there are no set bits, or if we have looked at all the bits (i &gt;= length of bitstring)</li>
<li>If the i+1th bit (one place to the left) is 0: move the ith bit left</li>
<li>Otherwise, if the i+1th bit (one place to the left) is 1: set i to i + 1 and repeat from 2.</li>
<li>Shift the bits on the range [0, i] right so that the rightmost bit is in position 0</li>
</ol>
<h2 id="explanation">Explanation</h2>
<p>Understanding <code>element_0()</code> is pretty easy. <code>1 &lt;&lt; c</code> is the same as moving a <code>1</code> to position c, then -1 sets all the bits from 0 to c &#x2013; 1, giving c set bits:</p>
<pre><code>c = 4
1 &lt;&lt; c = 10000
10000 - 1 = 01111
</code></pre>
<p><code>next_perm()</code> is a bit more complicated. The <code>v | (v -1)</code> in <code>t = (v | (v - 1)) + 1</code> right-propagates the rightmost bit. Allow me to show an example: <code>01110 | 01101 = 01111</code></p>
<p>In the case of 0, this isn&#x2019;t quite correct: <code>00000 | 11111 = 11111</code> But it&#x2019;s okay because we proceed to add 1 to this value (which returns it to zero). This increment, combined with the right-propagation, will do step 2, 3, and part of step 5 above. For example, <code>10100 -&gt; 10111 -&gt; 11000</code>.</p>
<p>We are on our way to generating integers by popcount in lexicographical order.</p>
<p>Now let&#x2019;s break down the next line, <code>w = t | ((((t &amp; -t) / (v &amp; -v)) &gt;&gt; 1) - 1)</code>. Bitwise equations of the form <code>(x &amp; -x)</code> isolate the rightmost bit:<br>
<code>01110 &amp; 10010 (two&apos;s complement) = 00010</code></p>
<p>If you take the two&#x2019;s complement, you invert a numbers bits and then add 1. If you think about it, this means there are 0s where there were 1s, and 1s where there were 0s, and adding 1 bumps the rightmost 1 left and sets the subsequent right bits to 0. This means that the only position that will remain set in both numbers is the the rightmost 1-bit.</p>
<p>So let R(x) denote the isolated rightmost bit of x, then for <code>x = 01110</code> we calculate <code>t = 10000</code>, <code>R(x) = 00010</code> and <code>R(t) = 10000</code>.</p>
<p>Following the calculation of w, we need to divide them: <code>R(t) / R(x) = 10000 / 00010 = 01000</code></p>
<p>Shift to the right by 1: <code>00100</code></p>
<p>Subtract 1: <code>00011</code></p>
<p>Then we bitwise-or them to stick them together: <code>10000 | 00011 = 10011</code>. This corresponds to our table above :)</p>
<p>So <code>w = t | ((((t &amp; -t) / (v &amp; -v)) &gt;&gt; 1) - 1)</code> corresponds to the rest of step 5 (the moving part, t was the zeroing part of moving the sub-range) in our pseudocode. Well, kind of anyway, there are a few steps happening in parallel, but the pseudocode was only loosely explaining what was happening :)</p>
<h2 id="testingitout">Testing it out</h2>
<pre><code>def gen_blocks(p, b):
    &quot;&quot;&quot;
    Generates all blocks of a given popcount and blocksize
    &quot;&quot;&quot;
    v = initial = element_0(p)
    block_mask = element_0(b)

    while (v &gt;= initial):
        yield v
        v = next_perm(v) &amp; block_mask


&gt;&gt;&gt; for x in gen_blocks(3, 5): print bin(x, 5)
... 
00111
01011
01101
01110
10011
10101
10110
11001
11010
11100
</code></pre>
<p><em>Note</em>: <code>bin</code> is just a function I found online for printing binay numbers and isn&#x2019;t important to this post, but you can find it <a href="http://www.gossamer-threads.com/lists/python/python/645216?ref=alexbowe.com">here</a> if you need one.</p>
<p>Then of course you can loop through all values of P from 0 to B to build the complete table.</p>
<p>Questions? Comments? Flames? I wanna hear em :)</p>
<p>[1] &#x2013; Check out <a href="http://www.springerlink.com/content/yv33538123433477/?ref=alexbowe.com">Tables by Munro, 1996</a>, and <a href="http://portal.acm.org/citation.cfm?id=545411&amp;ref=alexbowe.com">Succinct indexable dictionaries with applications to encoding k-ary trees and multisets by Raman et al, 2002</a> for a first step into this stuff. Also <a href="github.com/alexbowe/honours-thesis/downloads">check out my honours thesis, 2010</a> for a recent look at succinct data structures. I will write a blog post about this stuff sooner or later :P</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Some Lazy Fun with Streams]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i2.wp.com/ian.umces.edu/imagelibrary/albums/userpics/12789/normal_ian-symbol-river-3d-braided-with-incoming-streams.png?resize=400%2C188" alt loading="lazy"><br>
<strong>Update:</strong>&#xA0;fellow algorithms researcher&#xA0;<a href="http://fclaude.recoded.cl/?ref=alexbowe.com">Francisco Claude</a>&#xA0;just posted&#xA0;<a href="https://fclaude.recoded.cl/2011/05/land-of-lisp-and-lazy-evaluation/?ref=alexbowe.com">a great article about using lazy evaluation to solve Tic Tac Toe games in Common Lisp</a>. <a href="http://niki.code-karma.com/?ref=alexbowe.com">Niki</a>&#xA0;(my brother) also wrote a post using <a href="http://niki.code-karma.com/2011/05/hiding-io-latency-in-generators-by-async-prefetching/?ref=alexbowe.com">generators with asynchronous prefetching to hide IO latency</a>.&#xA0;Worth a read I</p>]]></description><link>https://www.alexbowe.com/streams/</link><guid isPermaLink="false">619714f2c62458003bddca68</guid><category><![CDATA[functional programming]]></category><category><![CDATA[haskell]]></category><category><![CDATA[python]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Sun, 24 Apr 2011 05:17:16 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://i2.wp.com/ian.umces.edu/imagelibrary/albums/userpics/12789/normal_ian-symbol-river-3d-braided-with-incoming-streams.png?resize=400%2C188" alt loading="lazy"><br>
<strong>Update:</strong>&#xA0;fellow algorithms researcher&#xA0;<a href="http://fclaude.recoded.cl/?ref=alexbowe.com">Francisco Claude</a>&#xA0;just posted&#xA0;<a href="https://fclaude.recoded.cl/2011/05/land-of-lisp-and-lazy-evaluation/?ref=alexbowe.com">a great article about using lazy evaluation to solve Tic Tac Toe games in Common Lisp</a>. <a href="http://niki.code-karma.com/?ref=alexbowe.com">Niki</a>&#xA0;(my brother) also wrote a post using <a href="http://niki.code-karma.com/2011/05/hiding-io-latency-in-generators-by-async-prefetching/?ref=alexbowe.com">generators with asynchronous prefetching to hide IO latency</a>.&#xA0;Worth a read I say!</p>
<p>I&#x2019;ve recently been obsessing over this programming idea called <em>streams</em> (also known as <em>infinite lists</em> or <em>generators</em>), which I learned about from the <a href="https://mitp-content-server.mit.edu/books/content/sectbyfn/books_pres_0/6515/sicp.zip/full-text/book/book.html?ref=alexbowe.com">Structure and Interpretation of Computer Programs</a> book. It is kind of like an iterator that creates its own data as you go along, and it can lead to performance increases and wonderfully readable code when you utilise them with <a href="http://en.wikipedia.org/wiki/Higher-order_function?ref=alexbowe.com">higher order functions</a> such as <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)?ref=alexbowe.com">map</a> and <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)?ref=alexbowe.com">reduce</a> (which many things can be rewritten in). It also allows you to express infinitely large data structures.</p>
<p>When regular lists are processed with higher order functions, you need to compute the entire list at each stage; if you have 100 elements, and you map a function to them, then filter them, then partially reduce them, you may be doing up to 300 operations, but what if you only want to take the first 5 elements of the result? That would be a waste, hence streams are sometimes a better choice.</p>
<p>Although SICP details how to do it in Scheme, in this blog post I will show some languages that have it built in &#x2013; Haskell and Python &#x2013; and how to implement streams yourself if you ever find yourself in a language without it<a href="#fn-1" title="see footnote">1</a>.</p>
<h2 id="haskell">Haskell</h2>
<p>Haskell is a lazy language. It didn&#x2019;t earn this reputation from not doing the dishes when you ask it to (although that is another reason it is lazy). What it means in the context of formal languages is that evaluation is postponed until <em>absolutely necessary</em> (<a href="http://blog.ezyang.com/2011/04/the-haskell-heap/?ref=alexbowe.com">Here</a> is a cute (illustrated) blog post describing this lazy evaluation stuff). Take this code for example:</p>
<pre><code>Prelude&gt; let x = [1..10]
</code></pre>
<p>At this stage you might be tempted to say that x is the list of numbers from 1 to 10. Actually it only represents a <em>promise</em> that when you need that list, x is your guy. The above code that creates a list from 1 to 10 still hasn&#x2019;t been executed until I finally ask it to be (by referring to x):</p>
<pre><code>Prelude&gt; x
[1,2,3,4,5,6,7,8,9,10]
</code></pre>
<p>It is kind of like telling your mum you&#x2019;ll do the dishes, but waiting until she shouts your name out again before you put down your DS. Actually, it is sliiiiightly different &#x2013; if I instead wrote:</p>
<pre><code>Prelude&gt; let x = [1..10]
Prelude&gt; let y = x ++ [11..20]
</code></pre>
<p>I have referred to x again when I declared y, but x <em>still</em> hasn&#x2019;t evaluated. Only after I shout y&#x2019;s name will y shout x&#x2019;s name and give me back my whole list:</p>
<pre><code>Prelude&gt; y
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
</code></pre>
<p>Here you ask your robot to wash half the dishes, but he is too busy playing DS too (stupid robot). Finally when your mum shouts, you shout at the robot, and he does his set of dishes, and you do yours. But what is the benefit here? It isn&#x2019;t that I can get more DS time in&#x2026;</p>
<p>Take for example a list of positive integers from 1. Yes, all of them. In other languages it might be hard to express this, but in Haskell it is as simple as <code>[1..]</code>. This means we have a list of infinite integers, but we will only calculate as far as we need:</p>
<pre><code>Prelude&gt; let z = [1..]
Prelude&gt; head z
1
Prelude&gt; take 5 z
[1,2,3,4,5]
</code></pre>
<p>The syntax here is amazingly terse, and it may make your code more efficient. But even if we don&#x2019;t have the syntax for it in another language, we can provide it ourselves very easily.</p>
<h2 id="python">Python</h2>
<p>Python has a similar concept called <em>generators</em>, which are made using the <code>yield</code> keyword in place of <code>return</code>, more than one time (or in a loop) in a function:</p>
<pre><code>def integers_from(N):
     while(1):
         yield N
         N += 1

&gt;&gt;&gt; z = integers_from(1)
&gt;&gt;&gt; z.next()
1
&gt;&gt;&gt; z.next()
2
</code></pre>
<p><strong>Note</strong>: Python generators are stateful and are hence slightly different to an infinite list in Haskell. For example <code>z.next()</code> returns different values in two places, and thus is time sensitive &#x2013; we cannot get z to &#x2018;rewind&#x2019; like we could in Haskell, where <code>z</code> is stateless. Statelessness can lead to easier to understand code, among other benefits.</p>
<h2 id="rollingourown">Rolling Our Own</h2>
<p>Let&#x2019;s reinvent this wheel in Python (but in a stateless manner), so if we ever find ourselves craving infinite lists we can easily roll our own in pretty much any language with <a href="http://en.wikipedia.org/wiki/Lambda_(programming)?ref=alexbowe.com">Lambdas</a>.</p>
<p>I have chosen Python to implement this, even though it already supports infinite lists through generators, simply because its syntax is more accessible. Indeed, the below can already be done with Python&#x2019;s built-in-functions (although with state). It is probably <em>not a great idea to do it this way in Python</em>, as it doesn&#x2019;t have <a href="http://stackoverflow.com/questions/310974/what-is-tail-call-optimization?ref=alexbowe.com">tail call optimisation</a> (unless you use <a href="http://code.activestate.com/recipes/474088/?ref=alexbowe.com">this hack</a> using decorators and exceptions).</p>
<p>First we&#x2019;ll look at adding lazy evaluation, however the syntax requires it to be explicit:</p>
<pre><code>&gt;&gt;&gt; x = lambda: 5
&gt;&gt;&gt; y = lambda: 2 + x()
</code></pre>
<p>Here, <code>x</code> is <em>not</em> 5, and <code>y</code> is <em>not</em> 7, they are both functions that will evaluate to that when we finally run them; the expression inside the lambda won&#x2019;t be evaluated until we do so explicitly:</p>
<pre><code>&gt;&gt;&gt; x()
5
&gt;&gt;&gt; y()
7
</code></pre>
<p>And that&#x2019;s pretty much all the heavy lifting. To make an infinite list, we basically make a linked list where we generate each node as we need it:</p>
<pre><code>def integers_from(N): return (N, lambda: integers_from(N+1))

def head((H, _)): return H

def tail((_, T)): return T()
</code></pre>
<p>And there is our infinite list. To access it use <code>head()</code> and <code>tail()</code> (recursively if necessary):</p>
<pre><code>&gt;&gt;&gt; z = integers_from(1)
&gt;&gt;&gt; head(z)
1
&gt;&gt;&gt; head(tail(z))
2
</code></pre>
<h2 id="helperfunctions">Helper Functions</h2>
<p>First we should make a way for us to look at our streams:</p>
<pre><code>def to_array(stream):
    return reduce(lambda a, x: a + [x], [], stream)
</code></pre>
<p>Which is a <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)?ref=alexbowe.com">reduce</a> operation that puts each head element into an array (which is carried along as a parameter to <code>reduce()</code>). Here is <code>reduce()</code> (<code>map()</code> can be found in this <a href="https://gist.github.com/938886?ref=alexbowe.com">gist</a>):</p>
<pre><code>null_stream = (None, None)
def reduce(f, result, stream):
    if stream is null_stream: return result
    return reduce(f, f(result, head(stream)), tail(stream))
</code></pre>
<p>We needed some way to tell if we had reached the end of a stream &#x2013; not all streams are infinitely long. Meet our next function, which will help us terminate a stream:</p>
<pre><code>def take(N, stream):
    if N &lt;= 0 or stream is null_stream: return null_stream
    return (head(stream), lambda: take(N-1, tail(stream)))
</code></pre>
<p>This will take the first <code>N</code> elements from the specified stream. So now we can inspect the first <code>N</code> elements:</p>
<pre><code>&gt;&gt;&gt; to_array(take(10, integers_from(1)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code></pre>
<p>For our upcoming example, we also need a <code>filter()</code> method, which will filter out elements that meet a provided predicate:</p>
<pre><code>def filter(pred, stream):
    if pred(head(stream)):
        return (head(stream), lambda: filter(pred, tail(stream)))
    return filter(pred, tail(stream))
</code></pre>
<p>Now onto our example :)</p>
<h2 id="textbookexample">Textbook Example</h2>
<p>Here is the standard example to demonstrate the terseness of streams:</p>
<pre><code>def sieve(stream):
    h = head(stream)
    return (h, lambda: sieve(
        filter(lambda x: x%h != 0, tail(stream))))
</code></pre>
<p>Here is a function which recursively filters anything which is divisible by any number we have previously seen in our stream. Math aficionados will notice that this is the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes?ref=alexbowe.com">Sieve of Eratosthenes</a> algorithm.</p>
<pre><code>&gt;&gt;&gt; primes = sieve(integers_from(2))
&gt;&gt;&gt; to_array(take(10, primes))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
</code></pre>
<p>Recursively defined data, and only as much of it as we want &#x2013; pretty neat.</p>
<h2 id="andnowforsomethingalmostcompletelydifferent">And Now For Something Almost Completely Different</h2>
<p>When I first saw this, I wondered what application there might be to have a stream of functions. Here I have defined a stream which recursively applies a function to itself:</p>
<pre><code>def rec_stream(f):
    return (f, lambda: rec_stream(lambda x: f(f(x))))
</code></pre>
<p>When might this be useful? It might yield speed improvements if you commonly want to recursively apply a function a certain amount of times, but have costly branching (so the condition check at each level is slow). It could also be used as a abstraction for recursive iteration <a href="#fn-2" title="see footnote">2</a>, which gives you back the function &#x2018;already recursed&#x2019; so to speak (although lazily).</p>
<p>One such recursive process I can think of is <a href="http://en.wikipedia.org/wiki/Newton&apos;s_method?ref=alexbowe.com">Newton&#x2019;s method for approximating roots</a>, defined recursively as:</p>
<p><img src="https://i1.wp.com/mathurl.com/3wb4xea.png" alt loading="lazy"></p>
<p>When <code>f(x) = 0</code>.</p>
<p>The more iterations you do the more accurate the solution becomes. One use of Newton&#x2019;s method is to use it until you have reached a certain error tolerance. Another way, which I learned about recently when reading about the <a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root?ref=alexbowe.com">fast inverse square root algorithm</a>, which uses just one step of Newton&#x2019;s method as a cheap way to improve it&#x2019;s (already pretty good) initial guess. There is a really great article <a href="http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/?ref=alexbowe.com">here</a> which explains it very well.</p>
<p>After reading that, I wondered about a stream that would consist of functions of increasing accuracy of Newton&#x2019;s method.</p>
<pre><code>def newton(f, fdash):
    return lambda x: x - f(x)/float(fdash(x))
</code></pre>
<p>The <code>newton()</code> function accepts <code>f(x)</code> and <code>f&apos;(x)</code>, and returns a function that accepts a first guess.</p>
<pre><code>def newton_solver(iters, f, fdash):
    def solve(v):
        n = newton(lambda x: f(x) - v, fdash)
        stream = rec_stream(n)
        return to_array(take(iters, stream))[-1]
    return solve
</code></pre>
<p>This one is a little more complicated. In order to have it solve for a value other than zero, I needed to either define it in <code>f(x)</code>, since <code>f(x)</code> must equal zero, but I didn&#x2019;t want the user to have to iterate over the stream each time they wanted to compute the square root of a different number, say. To allow it to return a function that solved for square roots in the general case, I had to make the internal function <code>solve()</code>, which would bind for the value the caller specifies, hence solving <code>f(x) = v</code> for <code>x</code>. Hopefully this becomes clearer with an example:</p>
<pre><code>&gt;&gt;&gt; sqrt = newton_solver(1, lambda x: x**2, lambda x: 2*x) # 1 iter
&gt;&gt;&gt; sqrt(64)(4) # Sqrt of 64 with initial guess of 4
10.0
&gt;&gt;&gt; sqrt = newton_solver(3, lambda x: x**2, lambda x: 2*x) # 3 iters
&gt;&gt;&gt; sqrt(64)(4)
8.000000371689179
</code></pre>
<p>Now we can pass around this square root function and it will always do 3 iterations of Newton&#x2019;s method.</p>
<p>This may not be practical unless compilers can optimise the resulting function (or if there is a way to do the reduction myself easily), but it was fun to do :) As always comments and suggestions are appreciated. If anyone who reads this is good with compilers, advice would be great :D</p>
<p>What you can do now is read <a href="https://tinyurl.com/3x9acs87?ref=alexbowe.com">SICP</a> for more cool things like streams and functional programming, or check out <a href="http://graphics.stanford.edu/~seander/bithacks.html?ref=alexbowe.com">Sean Anderson&#x2019;s bit hacks page</a> for more cool hacks like the fast inverse square root. Or refactor your code to use map, reduce and streams :)</p>
<hr>
<ol>
<li>The reason I have chosen Python for this exercise is for reasons of accessibility. <a href="http://chneukirchen.org/blog/archive/2005/05/lazy-streams-for-ruby.html?ref=alexbowe.com">Here</a> is a post about implementing streams in Ruby, and <a href="http://khigia.wordpress.com/2007/05/07/44/?ref=alexbowe.com">here</a> is one for Erlang :) but of course it&#x2019;s all pretty much the same deal.&#xA0;<a href="#fnref-1" title="return to article">&#x21A9;</a></li>
<li>If a compiler could optimise this, simplifying the reapplied function, but keeping the generality, that&#x2019;d be really cool :) I don&#x2019;t think many compilers would/could do that for lambdas though. Any information would be great.&#xA0;<a href="#fnref-2" title="return to article">&#x21A9;</a></li>
</ol>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Design Pattern Flash Cards]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/flashcards.png#center" alt="flashcards" loading="lazy"><br>
Last year I studied a subject which required me to memorise design patterns. I tried online flash card web sites, but I was irritated that I didn&#x2019;t own the data I put up (they had no export option). So I wrote a something in Python to generate flash</p>]]></description><link>https://www.alexbowe.com/design-pattern-flash-cards/</link><guid isPermaLink="false">619714f2c62458003bddca67</guid><category><![CDATA[design patterns]]></category><category><![CDATA[education]]></category><category><![CDATA[learning]]></category><category><![CDATA[tools]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Sun, 17 Apr 2011 22:03:04 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/flashcards.png#center" alt="flashcards" loading="lazy"><br>
Last year I studied a subject which required me to memorise design patterns. I tried online flash card web sites, but I was irritated that I didn&#x2019;t own the data I put up (they had no export option). So I wrote a something in Python to generate flash cards for me using LaTeX and the Cheetah templating library. The repository is hosted <a href="https://github.com/alexbowe/cardgen?ref=alexbowe.com">here</a>, although it could do with a refactor.</p>
<p>If you don&#x2019;t want to generate your own, you can download the pre-generated design pattern intent flash cards <a href="https://github.com/alexbowe/cardgen/raw/master/intents.pdf?ref=alexbowe.com">here</a> which contains the 23 original design patterns from the Gang Of Four.</p>
<p>To generate your own flash cards, create an input text file with this structure:</p>
<pre><code>Front text (such as pattern name):
Definition line 1.
Definition line 2.
</code></pre>
<p>For example:</p>
<pre><code>Abstract Factory:
Provides an interface for creating families of related or
dependent objects without specifying their concrete classes.
</code></pre>
<p>Currently the front text is single-line only. The regex could be updated of course (if you do, feel free to send a pull request!).</p>
<p>To compile this:</p>
<pre><code>./cardgen.py -i inputfile -o outputfile
pdflatex outputfile
</code></pre>
<p>Then just print it out on a double side printer (or glue the two sheets together). I carried these around with me all the time during the lead-up to the exam, and I was scary-fast when it came to recalling which design pattern did what. Just flick through them (shuffle first) in forward or reverse order when you are on the train next :)![flashcards]</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Metaprogramming Erlang the Easy Way]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/a_hyper_cube-1.gif#center" alt="a_hyper_cube-1" loading="lazy"></p>
<p>I&#x2019;ve recently taken <a href="http://www.erlang.org/?ref=alexbowe.com">Erlang</a> back up<a href="#fn-0" title="see footnote">1</a>, and I wanted to use this blog post to talk about something cool I learned over the weekend.</p>
<p>I am implementing a data structure. Reimplementing actually, as it is the structure from my <a href="https://github.com/alexbowe/honours-thesis/downloads?ref=alexbowe.com">thesis</a> &#x2013; a succinct text index (I will</p>]]></description><link>https://www.alexbowe.com/metaprogramming-erlang/</link><guid isPermaLink="false">619714f2c62458003bddca66</guid><category><![CDATA[erlang]]></category><category><![CDATA[functional programming]]></category><category><![CDATA[metaprogramming]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Mon, 04 Apr 2011 17:49:46 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/a_hyper_cube-1.gif#center" alt="a_hyper_cube-1" loading="lazy"></p>
<p>I&#x2019;ve recently taken <a href="http://www.erlang.org/?ref=alexbowe.com">Erlang</a> back up<a href="#fn-0" title="see footnote">1</a>, and I wanted to use this blog post to talk about something cool I learned over the weekend.</p>
<p>I am implementing a data structure. Reimplementing actually, as it is the structure from my <a href="https://github.com/alexbowe/honours-thesis/downloads?ref=alexbowe.com">thesis</a> &#x2013; a succinct text index (I will post a blog on this soon).</p>
<p>Why am I reimplementing it in Erlang? The structure involves many bit-level operations, and I wanted to try out Erlang&#x2019;s <a href="http://www.erlang.org/doc/programming_examples/bit_syntax.html?ref=alexbowe.com">primitive Binary type</a>, which seems to be allow efficient splitting and concatenation (which I require). Erlang&#x2019;s approach to concurrency will hopefully assist me to experiment with distributing the structure, too. As a bonus, the functional approach has lent itself well to this math-centric data structure, and my code is much, MUCH cleaner because of it (I love <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)?ref=alexbowe.com">reduce</a> and other <a href="http://en.wikipedia.org/wiki/Higher-order_function?ref=alexbowe.com">higher order functions</a>).</p>
<p>One function I needed to implement was <a href="http://graphics.stanford.edu/~seander/bithacks.html?ref=alexbowe.com#CountBitsSetTable">popcount</a> (the sum of set set bits in a bitvector). For example, if <code>b = 1010</code> then <code>pop(b)</code> is 2.</p>
<p>There are many methods listed on <a href="http://www.valuedlessons.com/2009/01/popcount-in-python-with-benchmarks.html?ref=alexbowe.com">this blog</a>. One of them is the table method, which precomputes all popcounts for 16 bit integers (or any length you have space for):</p>
<pre><code>POPCOUNT_TABLE16 = [0] * 2**16
for index in xrange(len(POPCOUNT_TABLE16)):
    POPCOUNT_TABLE16[index] = (index &amp; 1)
    + POPCOUNT_TABLE16[index &gt;&gt; 1]
</code></pre>
<p>I translated this to Erlang:</p>
<p>View the code on <a href="https://gist.github.com/901235?ref=alexbowe.com">Gist</a>.</p>
<p>So now <code>gen_table(Bits)</code> will generate a tuple for me with all popcounts from 0 to $2^Bits$. However, we may gain performance<a href="http://#fn:1" title="see footnote">2</a> from knowing how big we want the table to be at compile time. If we know the amount of bits we want our popcount table to work for, we could type the table directly into the source. But that would impede our flexibility, and make our code ugly.</p>
<p>Enter <a href="https://github.com/esl/parse_trans?ref=alexbowe.com"><code>ct_expand</code></a>. We can use <code>ct_expand:term( &lt;code to execute&gt; )</code> to run <code>gen_table()</code> for us at compile time! Now we only run <code>gen_table()</code> whenever we compile the module &#x2013; after that the table is embedded in the binary.</p>
<p>First, check out ct_expand (<code>git clone https://github.com/esl/parse_trans.git</code>), and compile it with <code>make</code><a href="#fn-2" title="see footnote">3</a>. Then just move the <code>.beam</code> files into your project directory. Now we&#x2019;re ready for some metaprogramming :)</p>
<p>I created a new module for generating our table at compile time:</p>
<p>View the code on <a href="https://gist.github.com/901242?ref=alexbowe.com">Gist</a>.</p>
<p>The reason we must be in a new module is because <code>ct_expand:term()</code> requires it&#x2019;s parameter to be something it will know about at compile time. This could be an inline fun (which I tried, but it wasn&#x2019;t pretty), or it can be something you compile before <code>ct_expand:term()</code> is executed (see line 3). Note on line 2 that we also need to compile <code>parse_transform</code> and <code>ct_expand</code> with our module.</p>
<p>Let&#x2019;s test it out:</p>
<pre><code>1&gt; c(popcount).
{ok,popcount}
2&gt; popcount:popcount16(2#1010).
2
3&gt; popcount:popcount16(2#101011).
4
</code></pre>
<p>Nice! Thanks to <a href="http://ulf.wiger.net/weblog/?ref=alexbowe.com">Ulf Wiger</a> for making that so easy :)</p>
<p>( Image stolen from&#xA0;<a href="http://improvisazn.wordpress.com/2010/02/22/meta/?ref=alexbowe.com">http://improvisazn.wordpress.com/2010/02/22/meta/</a> )</p>
<hr>
<ol>
<li>My only other encounter with it was when I wrote an essay on the rationale of Erlang, which is something I will convert to blog format and post later if anyone is interested.&#xA0;<a href="http://#fnref:0" title="return to article">&#x21A9;</a></li>
<li>The compiler may be able to apply further optimisations, so table access might be faster itself, but the main benefit comes from not having to generate the table while your code is running. Note that I haven&#x2019;t experimented with it. I will try to run some tests this week and update the blog post.&#xA0;<a href="#fnref-1" title="return to article">&#x21A9;</a></li>
<li>If rebar gives you an error about crypto being undefined, you will need the <code>erlang-crypto</code> package. On Mac OS X: <code>sudo port install erlang +ssl</code>. (I had this issue)&#xA0;<a href="http://#fnref:2" title="return to article">&#x21A9;</a>!</li>
</ol>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Au Naturale: an Introduction to NLTK]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="http://data.whicdn.com/images/1396251/tumblr_kwukdtbqLx1qargqko1_400_large.jpg" alt loading="lazy"><br>
This blog post is an introduction on how to make a key phrase extractor in Python, using the <a href="http://www.nltk.org/?ref=alexbowe.com">Natural Language Toolkit (NLTK)</a>.</p>
<p>But how will a search engine know what it is about? How will this document be indexed correctly? A human can read it and tell that it is</p>]]></description><link>https://www.alexbowe.com/au-naturale/</link><guid isPermaLink="false">619714f2c62458003bddca65</guid><category><![CDATA[nlp]]></category><category><![CDATA[nltk]]></category><category><![CDATA[python]]></category><category><![CDATA[natural language processing]]></category><category><![CDATA[linguistics]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Sun, 20 Mar 2011 15:14:31 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="http://data.whicdn.com/images/1396251/tumblr_kwukdtbqLx1qargqko1_400_large.jpg" alt loading="lazy"><br>
This blog post is an introduction on how to make a key phrase extractor in Python, using the <a href="http://www.nltk.org/?ref=alexbowe.com">Natural Language Toolkit (NLTK)</a>.</p>
<p>But how will a search engine know what it is about? How will this document be indexed correctly? A human can read it and tell that it is about programming, but no search engine company has the money to pay thousands of people to classify the entire Internet for them. Instead they must reasonably predict what a human may decide to be the key points of a document. And they must automate this.</p>
<p>Remember how proper sentences need to be structured with a <a href="http://hubpages.com/hub/Grammar_Mishaps__Building_a_Sentence?ref=alexbowe.com">subject and a predicate</a>? A subject could be a noun, or a adjective followed by a noun, or a pronoun&#x2026; A predicate may be or include a verb&#x2026; We can take a similar approach by defining our key phrases in terms of what types of words (or parts-of-speech) they are, and the pattern in which they occur.</p>
<p>But how do we know what words are nouns or verbs in an automated fashion?</p>
<p>Throughout this post I will use an excerpt from <a href="http://www.amazon.com/gp/product/0061673730/alexbowecom-20?ref=alexbowe.com">Zen and the Art of Motorcycle Maintenance</a> as an example:</p>
<blockquote>
<p>The Buddha, the Godhead, resides quite as comfortably in the circuits of a digital computer or the gears of a cycle transmission as he does at the top of a mountain or in the petals of a flower. To think otherwise is to demean the Buddha&#x2026;which is to demean oneself.</p>
</blockquote>
<p>Before proceeding, make a (mental) note of the key phrases here. What is the document about?</p>
<h2 id="tokenizing">Tokenizing</h2>
<p>In a program, text is represented as a string of characters. How can we go about moving <em>one</em> level of abstraction up, to the level of words, or <em>tokens</em>? To tokenize a sentence you may be tempted to use Python&#x2019;s <code>.split()</code> method, but this means you will need to code additional rules to remove hyphens, newlines and punctuation when appropriate.</p>
<p>Thankfully the <a href="http://www.nltk.org/?ref=alexbowe.com">Natural Language Toolkit (NLTK)</a> for Python provides a regular expression tokenizer. There is an example of it (including how it fares against Pythons regular expression tokenization method) in <a href="https://www.nltk.org/book/ch03.html?ref=alexbowe.com">Chapter 3</a> of the <a href="http://www.nltk.org/book?ref=alexbowe.com">NLTK book</a>. It also allows you to have comments:</p>
<pre><code># Word Tokenization Regex adapted from NLTK book
# (?x) sets flag to allow comments in regexps
sentence_re = r&apos;&apos;&apos;(?x)
  # abbreviations, e.g. U.S.A. (with optional last period)
  ([A-Z])(.[A-Z])+.?
  # words with optional internal hyphens
  | w+(-w+)*
  # currency and percentages, e.g. $12.40, 82%
  | $?d+(.d+)?%?
  # ellipsis
  | ...
  # these are separate tokens
  | [][.,;&quot;&apos;?():-_`]
&apos;&apos;&apos;
</code></pre>
<p>Once we have constructed our regex for defining what sort of format our words should be in, we call it like so:</p>
<pre><code>import nltk
#doc is a string containing our document
toks = nltk.regexp_tokenize(doc, sentence_re)

&gt;&gt;&gt; toks
[&apos;The&apos;, &apos;Buddha&apos;, &apos;,&apos;, &apos;the&apos;, &apos;Godhead&apos;, &apos;,&apos;, &apos;resides&apos;, ...
</code></pre>
<h2 id="tagging">Tagging</h2>
<p>The next step is tagging. This uses statistical data to apply a Part-of-speech tag to each token, e.g. ADJ, NN (Noun), and so on. Since it is statistical, we need to either train our model or use a pre-trained model. NLTK comes with a pretty good one for general use, but if you are looking at a certain kind of document you may want to train your own tagger, since it may greatly affect the accuracy (think about very vocabulary-dense fields such as biology).</p>
<p>Note that to train your own tagger you will need a pre-tagged corpus (NLTK comes with some) or use a <em>bootstrapped</em> method (which can take a long time). Check out <a href="http://streamhacker.com/2010/04/12/pos-tag-nltk-brill-classifier/?ref=alexbowe.com">Streamhacker</a> and <a href="https://www.nltk.org/book/ch05.html?ref=alexbowe.com">Chapter 5 of the NLTK book</a> for a good discussion on training your own (and how to test it empirically).</p>
<p>For the sake of this introduction, we will use the default one. The result is a list of token-tag pairs:</p>
<pre><code>&gt;&gt;&gt; postoks = nltk.tag.pos_tag(toks)
&gt;&gt;&gt; postoks
[(&apos;The&apos;, &apos;DT&apos;), (&apos;Buddha&apos;, &apos;NNP&apos;), (&apos;,&apos;, &apos;,&apos;), (&apos;the&apos;, &apos;DT&apos;), ...
</code></pre>
<h2 id="chunking">Chunking</h2>
<p>Now we can use the part-of-speech tags to lift out noun phrases (NP) based on patterns of tags.</p>
<p><img src="https://i2.wp.com/nltk.googlecode.com/svn/trunk/doc/images/chunk-segmentation.png?resize=600%2C405" alt loading="lazy"></p>
<p><em>Note: All diagrams have been stolen from the NLTK book (which is available under the Creative Commons Attribution Noncommercial No Derivative Works 3.0 US License).</em></p>
<p>This is called chunking. We can define the form of our chunks using a regular expression, and build a chunker from that:</p>
<pre><code># This grammar is described in the paper by S. N. Kim,
# T. Baldwin, and M.-Y. Kan.
# Evaluating n-gram based evaluation metrics for automatic
# keyphrase extraction.
# Technical report, University of Melbourne, Melbourne 2010.
grammar = r&quot;&quot;&quot;
    NBAR:
        # Nouns and Adjectives, terminated with Nouns
        {&lt;NN.*|JJ&gt;*&lt;NN.*&gt;}

    NP:
        {&lt;NBAR&gt;}
        # Above, connected with in/of/etc...
        {&lt;NBAR&gt;&lt;IN&gt;&lt;NBAR&gt;}
&quot;&quot;&quot;

chunker = nltk.RegexpParser(grammar)
tree = chunker.parse(postoks)
</code></pre>
<p>It is also possible to describe a Context Free Grammar (CFG) to do this, and help deal with ambiguity &#x2013; information can be found in <a href="https://www.nltk.org/book/ch08.html?ref=alexbowe.com">Chapter 8 of the NLTK book</a>. Chunk regexes can be much more complicated if needed, and support <em>chinking</em>, which allows you to specify patterns in terms <em>what you don&#x2019;t want</em> &#x2013; see <a href="https://www.nltk.org/book/ch07.html?ref=alexbowe.com">Chapter 7 of the NLTK book</a>.</p>
<p>The output of chunking is a tree, where the noun phrase nodes are located just one level before the leaves, which are the words that constitute the noun phrase:</p>
<p><img src="https://i0.wp.com/nltk.googlecode.com/svn/trunk/doc/images/chunk-treerep.png?resize=600%2C696" alt loading="lazy"></p>
<p>To access the leaves, we can use this code:</p>
<pre><code>def leaves(tree):
    &quot;&quot;&quot;Finds NP (nounphrase) leaf nodes of a chunk tree.&quot;&quot;&quot;
    for subtree in tree.subtrees(filter = lambda t: t.node==&apos;NP&apos;):
        yield subtree.leaves()
</code></pre>
<h2 id="walkingthetreeandnormalisation">Walking the tree and Normalisation</h2>
<p>We can now walk the tree to get the terms, applying normalisation if we want to:</p>
<pre><code>def get_terms(tree):
    for leaf in leaves(tree):
        term = [ normalise(word) for word, tag in leaf
            if acceptable_word(word) ]
        yield term
</code></pre>
<p>Normalisation may consist of lower-casing words, removing stop-words which appear in many documents (i.e. if, the, a&#x2026;), stemming (i.e. cars $\rightarrow$ car), and lemmatizing (i.e. drove, drives, rode $\rightarrow$ drive). We normalise so that at later stages we can compare similar key phrases to be the same; <code>&apos;the man drove the truck&apos;</code> should be comparable to <code>&apos;The man drives the truck&apos;</code>. This will allow us to better rank our key phrases :)</p>
<p>Functions for normalising and checking for stop-words are described below:</p>
<pre><code>lemmatizer = nltk.WordNetLemmatizer()
stemmer = nltk.stem.porter.PorterStemmer()

def normalise(word):
    &quot;&quot;&quot;Normalises words to lowercase and stems and lemmatizes it.&quot;&quot;&quot;
    word = word.lower()
    word = stemmer.stem_word(word)
    word = lemmatizer.lemmatize(word)
    return word

def acceptable_word(word):
    &quot;&quot;&quot;Checks conditions for acceptable word: length, stopword.&quot;&quot;&quot;
    from nltk.corpus import stopwords
    stopwords = stopwords.words(&apos;english&apos;)

    accepted = bool(2 &lt;= len(word) &lt;= 40
        and word.lower() not in stopwords)
    return accepted
</code></pre>
<p>And the result is:</p>
<pre><code>&gt;&gt;&gt; terms = get_terms(tree)
&gt;&gt;&gt; for term in terms:
...    for word in term:
...        print word,
...    print
buddha
godhead
circuit
digit comput
gear
cycl transmiss
mountain
petal
flower
buddha
demean oneself
</code></pre>
<p>Are these similar to the key phrases you chose? There are lots of areas above that can be tweaked. Let me know what you come up with :) (the code can be found in <a href="https://gist.github.com/879414?ref=alexbowe.com">this gist</a>).</p>
<p>In future posts I will talk about how to rank key phrases. I will also discuss how to scale this to process many documents at once using MapReduce.</p>
<p>In the mean time check out the <a href="http://text-processing.com/demo/?ref=alexbowe.com">demos</a> on <a href="http://streamhacker.com/?ref=alexbowe.com">Streamhacker</a>, solve the problems in the <a href="http://www.nltk.org/?ref=alexbowe.com">NLTK book</a>, or read the <a href="http://www.amazon.com/gp/product/1849513600/alexbowecom-20?ref=alexbowe.com">NLTK Cookbook</a> :)</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Advice to CS Undergrads]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/hup-board-1024x565.jpg#center" alt="hup-board-1024x565" loading="lazy"></p>
<p>Since I&#x2019;m starting my PhD this year, I have been reflecting on how I would be different if I went back in time and started my degree all over again. I am also continuing tutoring, in my 4th year, and I have been occasionally approached by students and</p>]]></description><link>https://www.alexbowe.com/advice-to-cs-undergrads/</link><guid isPermaLink="false">619714f2c62458003bddca63</guid><category><![CDATA[education]]></category><category><![CDATA[learning]]></category><category><![CDATA[reading]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Mon, 07 Feb 2011 21:35:49 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/hup-board-1024x565.jpg#center" alt="hup-board-1024x565" loading="lazy"></p>
<p>Since I&#x2019;m starting my PhD this year, I have been reflecting on how I would be different if I went back in time and started my degree all over again. I am also continuing tutoring, in my 4th year, and I have been occasionally approached by students and asked for general advice with their studies.</p>
<p>I repeat the same advice to most students, so I&#x2019;ll attempt to distill it into the points below. Bear in mind that I am writing from a Computer Science perspective, although some of the advice can be applied to any field.</p>
<p>I didn&#x2019;t do most of this stuff during my undergrad years. I still did well, but I think I would have had more fun if I followed this advice. If you&#x2019;re not doing all the stuff on this list, that&#x2019;s okay. Come back and try again later.</p>
<p>Here&#x2019;s the advice in no particular order:</p>
<p><strong>Decide to get Good.</strong> I know a lot of students who aren&#x2019;t sure if they are in the right degree. Computer Science isn&#x2019;t for everyone, but if you are far enough in (&gt; 1 year) I recommend riding it out. I even had my own doubts; While programming was a hobby for me prior to uni, most subjects at uni left me disappointed. When I started searching for parts of it that interested me, I found it much more creative and fun.</p>
<p>After your degree, you can do Masters in something else, and it will only take 1.5 or 2 years. Or you can study other things in your spare time. Don&#x2019;t bite off too much though&#x2026;</p>
<p>Supposedly it takes <a href="http://norvig.com/21-days.html?ref=alexbowe.com">10,000 hours to become an expert at anything</a>, but after that I bet it is faster to become an expert at other things; many of the 10,000 hours you spend will be self-learning that can be applied to the next.</p>
<p><strong>Learn More Languages.</strong> Everyone gives this advice, but they usually suggest it because it will give you a perspective on different ways to do things. I think you should learn Python (or Ruby) in order to remove the friction from learning (try the book <a href="http://learnpythonthehardway.org/?ref=alexbowe.com">Learn Python The Hard Way</a> by Zed Shaw).</p>
<p>Python has been dubbed &#x201C;executable pseudocode&#x201D;, so this will help you when reading algorithm books. They are both dynamically typed, which means you don&#x2019;t have to tell the computer when you are talking about a number vs a string. They also come with an interactive shell where you can test ideas and easily enter/modify examples from books.</p>
<p>Since their syntaxes are C-like, you can start your assignments in one of these languages, and easily translate it by hand to Java or C. Build one to throw away (thanks, <a href="http://www.amazon.com/gp/product/0201835959/alexbowecom-20?ref=alexbowe.com">Fred Brooks</a>) so you can learn about the pitfalls of the problem before you have to deal with pointers or boiler-plate code.</p>
<p>Lisp is also recommended. It can be daunting to choose a dialect when you know nothing about it&#x2026; Just learn Scheme (you can learn Common Lisp or Clojure later). There is really amazing free material that you&#x2019;ll probably want to <a href="https://mitp-content-server.mit.edu/books/content/sectbyfn/books_pres_0/6515/sicp.zip/full-text/book/book.html?ref=alexbowe.com">read</a> or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/?ref=alexbowe.com">watch</a> at some point anyway. It will be less practical for your uni years, but will give you a depth of knowledge that will carry you through your entire career.</p>
<p>Oh yeah, and learn and use regular expressions the next time you need to process text.</p>
<p><strong>Manage Your Time.</strong> Okay, this is a no-brainer, but I still didn&#x2019;t do it that well. The day you get an assignment, put it on your calendar and set a reminder. After you&#x2019;ve done that, start working on it right away.</p>
<p>Remember, you aren&#x2019;t committed to whatever you write down, until you hand it in; once again, build one to throw away. Even a mind-map or just writing headings can help a lot. Inevitably you&#x2019;ll rush it at the last minute, but having previous work to reference rather than a blank page is so much more comforting. I&#x2019;ll write more productivity advice in a later post, so keep checking back.</p>
<p><strong>Read!</strong> I don&#x2019;t mean the prescribed text-book &#x2013; I only read a few of those, and sometimes they are only recommended because the lecturer is somehow invested in it (don&#x2019;t get me wrong, some are great, but you&#x2019;ll find out about those books anyway).</p>
<p>I recommend starting with <a href="http://www.amazon.com/gp/product/020161622X/alexbowecom-20?ref=alexbowe.com">The Pragmatic Programmer</a>; It&#x2019;s nice and small, very practical, acclaimed, and it will point you in the direction of other good books to read when you&#x2019;ve finished.</p>
<p>Other than that, check out some recommended reading lists <a href="#fn-reading" title="see footnote">1</a>, and subscribe to blogs <a href="#fn-blogs" title="see footnote">2</a>. I&#x2019;ll also discuss my reading workflow at a later date, as you have to be careful of information-glut.</p>
<p><strong>Sharpen Your Tools.</strong> Here are some tools that will help you make learning an enjoyable process:</p>
<ul>
<li>Get a laptop. I feel bad saying that coz it will cost you money, but it really helps to have your coding environment ready to go.</li>
<li>Use Unix. I only did this after I switched to Mac OS X, but there are free alternatives. It&#x2019;s just a nicer environment for coding. It will also reduce the amount of time you spend on games.</li>
<li>Use Git and GitHub. Often, I would try to fix a bug in an assignment only to introduce more. Sometimes I would make backups of the project folder, but this was usually confusing and has led to me losing major chunks of work. Every project you do should be on GitHub to help you manage this, enable you to have pride in your work (by displaying it publicly), and having an off-site backup.</li>
<li>Start learning Vim during a break. It has a steep learning curve, but will make you faster in the end.</li>
</ul>
<p><strong>Start Your Career Early.</strong> Another thing I didn&#x2019;t do. Here are some things you can do to help you hit the ground running when you finish uni:</p>
<ul>
<li>Contribute to open source. It looks good on your resume, and (as japerk commented) will help you learn about real world programming and software in the wild. You can find beginner-level bugs on <a href="https://openhatch.org/search/?toughness=bitesize&amp;ref=alexbowe.com">openhatch</a>.</li>
<li>Maintain a resume and apply for jobs (even if they are out of your league). Worst-case, you don&#x2019;t get it, but it will may help you spot holes in your knowledge and experience (failing a Google interview was a big reality check for me). Best-case, you get relevant work while at uni.</li>
<li>Tutor people. Studies have shown that we learn best when we are teaching.</li>
</ul>
<p><strong>Don&#x2019;t Forget: People Matter!</strong> It&#x2019;s easy for a geek to forget this, but I think it&#x2019;s the lynchpin to good education.</p>
<p>The friends you make, even if less intelligent, will drive you to do Computer Science for fun. They will either show you the cool stuff they learn, or challenge you to do better than them. But it doesn&#x2019;t stop with your classmates.</p>
<ul>
<li>Write a blog. This will refine your communication skills, but I still get emails from people thanking me for my (simple) <a href="https://alexbowe.com/education/nanosecond-timing?ref=alexbowe.com">nanosecond time wrapper</a>. It&#x2019;s fun and rewarding. If you are having trouble maintaining it persistently, <a href="mailto:bowe.alexander@gmail.com">email me</a> and I&#x2019;ll tell you about a relevant project of mine that might help&#x2026;</li>
<li>Tweet about your programming interests. This will build a network outside of uni, that will remind you why you like doing this. Follow me on twitter: <a href="http://www.twitter.com/alexbowe?ref=alexbowe.com">@alexbowe</a> :)</li>
<li>Email your idols. It can be really helpful and exciting to get a response from someone whose blog you read, or who has written a book or paper you read. This really helped me with my thesis last year. It might also give you something to blog about ;)</li>
</ul>
<p>To me, these are the most important pieces of advice to take while studying (or as soon as you are ready). Criticism, suggestions, and comments of any other type are welcome, as always. It&#x2019;d also be cool to hear about things you think paint CS in a cool light for students (The game of life is one example).</p>
<p>For more blog posts on similar matters by much better writers and programmers than me, check out:</p>
<ul>
<li><a href="http://www.catb.org/~esr/faqs/hacker-howto.html?ref=alexbowe.com">Eric Raymond &#x2013; How To Become A Hacker</a></li>
<li><a href="http://www.paulgraham.com/college.html?ref=alexbowe.com">Paul Graham &#x2013; Undergraduation</a></li>
<li><a href="http://www.paulgraham.com/undergrad2.html?ref=alexbowe.com">Paul Graham &#x2013; More Advice for Undergrads</a></li>
<li><a href="http://www.joelonsoftware.com/articles/CollegeAdvice.html?ref=alexbowe.com">Joel Spolsky &#x2013; Advice for Computer Science College Students</a></li>
<li><a href="http://programmers.stackexchange.com/questions/44177/what-is-the-single-most-effective-thing-you-did-to-improve-your-programming-skill?ref=alexbowe.com">Quesiton on Stack Overflow: What is the single most effective thing you did to improve your programming skills?</a></li>
</ul>
<hr>
<ol>
<li>After <a href="http://www.amazon.com/gp/product/020161622X/alexbowecom-20?ref=alexbowe.com">The Pragmatic Programmer</a>, try <a href="http://www.amazon.com/gp/product/1934356344/alexbowecom-20?ref=alexbowe.com">The Passionate Programmer</a>. If you want a good book to help you with your people skills, try <a href="http://www.amazon.com/gp/product/1439167346/alexbowecom-20?ref=alexbowe.com">How To Win Friends And Influence People</a>. <a href="http://www.codinghorror.com/blog/2004/02/recommended-reading-for-developers.html?ref=alexbowe.com">Coding Horror</a> and <a href="http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read?ref=alexbowe.com">Stack Overflow</a> have great book recommendations too. And a list of <a href="https://ebookfoundation.github.io/free-programming-books/?ref=alexbowe.com">FREE books</a>.&#xA0;<a href="#fnref-reading" title="return to article">&#x21A9;</a></li>
<li>Too many great blogs to list. Start at <a href="http://news.ycombinator.com/?ref=alexbowe.com">Hacker News</a> and you&#x2019;ll soon find some great blogs to follow. Theres also a recommendations <a href="http://news.ycombinator.com/item?id=128762&amp;ref=alexbowe.com">thread there already</a>.&#xA0;<a href="#fnref-blogs" title="return to article">&#x21A9;</a></li>
</ol>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Regularly Divisble]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/div3.png#center" alt="div3" loading="lazy"></p>
<p><strong>Update</strong>: read the comments at <a href="http://news.ycombinator.com/item?id=1937062&amp;ref=alexbowe.com">Hacker News</a> to see some succinct approaches to this, as discussed by <em>gjm11</em>, <em>qntm</em> and <em>patio11</em>. Thanks to <em>Robin</em> for providing <a href="http://s3.boskent.com/divisibility-regex/divisibility-regex.html?ref=alexbowe.com">this demonstration</a> that can find a regex for testing divisibility of any number, in any base (he also made the code available, nice).</p>
<p>Earlier</p>]]></description><link>https://www.alexbowe.com/regularly-divisble/</link><guid isPermaLink="false">619714f2c62458003bddca62</guid><category><![CDATA[automata]]></category><category><![CDATA[languages]]></category><category><![CDATA[regular expressions]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Wed, 24 Nov 2010 07:26:37 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/div3.png#center" alt="div3" loading="lazy"></p>
<p><strong>Update</strong>: read the comments at <a href="http://news.ycombinator.com/item?id=1937062&amp;ref=alexbowe.com">Hacker News</a> to see some succinct approaches to this, as discussed by <em>gjm11</em>, <em>qntm</em> and <em>patio11</em>. Thanks to <em>Robin</em> for providing <a href="http://s3.boskent.com/divisibility-regex/divisibility-regex.html?ref=alexbowe.com">this demonstration</a> that can find a regex for testing divisibility of any number, in any base (he also made the code available, nice).</p>
<p>Earlier this year, at the advice (once more) of <a href="http://www.amazon.com/gp/product/1934356344/alexbowecom-20?ref=alexbowe.com">Chad Fowler</a>, I took to the idea of practicing programming every day. Perhaps this appealed to me because it echoed the rituals of my better musician friends, and allowed me to draw parallels between programming and my fading dream of becoming a famous rockstar.</p>
<p>Possibly because of my failed interview at Google (hey, I wouldn&#x2019;t have hired the back-then me either, so no hard feelings!), I was also interested in job-interview styled problems [1]. <em>Not</em> <a href="http://niki.code-karma.com/2010/08/fizzbuzz/?ref=alexbowe.com">FizzBuzz</a> though, more like the computer science &#x2018;riddles&#x2019; found on <a href="http://wuriddles.com/cs.shtml?ref=alexbowe.com">this page</a> [2].</p>
<p>At the time I was teaching Computing Theory [3], 80% of which was <a href="http://en.wikipedia.org/wiki/Formal_language?ref=alexbowe.com">formal languages</a>: <a href="http://en.wikipedia.org/wiki/Regular_expression?ref=alexbowe.com">regular expressions</a>, <a href="http://en.wikipedia.org/wiki/Context-free_grammar?ref=alexbowe.com">context free</a> and <a href="http://en.wikipedia.org/wiki/Context-sensitive_grammar?ref=alexbowe.com">context sensitive grammars</a>, <a href="http://en.wikipedia.org/wiki/Turing_machine?ref=alexbowe.com">Turing machines</a> and <a href="http://en.wikipedia.org/wiki/Automata_theory?ref=alexbowe.com">other automata</a>, and their locations in the <a href="http://en.wikipedia.org/wiki/Chomsky_hierarchy?ref=alexbowe.com">Chomsky Hierarchy</a>. So, this problem appealed to me:</p>
<blockquote>
<p>Construct a finite state machine (or equivalently, write a regular expression) which accepts all strings over the alphabet {0,1} which are divisible by 3 when interpreted in binary.</p>
</blockquote>
<p>It is pretty interesting that languages can be defined to communicate patterns in binary sequences that are divisible by 3. Let&#x2019;s solve it in more detail than necessary :)&#x2026;</p>
<p>We will be developing this regex incrementally. I will update the regex at each stage. Since it is easier to construct this regex using a finite state machine (which is how I worked this out the first time), I&#x2019;ll also include a few diagrams along the way. You can test your regexes using the Ruby code <a href="https://gist.github.com/711644?ref=alexbowe.com">here</a>.</p>
<p>To get an idea for the pattern, I started by listing out a few multiples of 3 and their binary representations. You can use the following Ruby code if you want.</p>
<script src="https://gist.github.com/alexbowe/709642.js"></script>
<p>View the code on <a href="https://gist.github.com/709642?ref=alexbowe.com">Gist</a>.</p>
<pre><code>&gt;&gt; 30.times {|n| puts &quot;#{n}: #{n.to_bin_s}&quot; if n%3 == 0}
0: 0
3: 11
6: 110
9: 1001
12: 1100
15: 1111
18: 10010
21: 10101
24: 11000
27: 11011
</code></pre>
<p>Observe that the binary representations for 3, 6, 12 and 24 have something in common: they have the same sequence, with a little bit of zero-padding to the right. <em>If <code>X</code> is a binary string divisible by <code>3</code>, then the binary string <code>X0</code> is divisible by <code>3</code> as well</em>. This makes sense, as adding zeros to the right is equivalent to multiplying by <code>2</code>, and we know that <code>n * 3 * 2</code> is divisible by <code>3</code> for any integer <code>n</code>. This gives us:</p>
<pre><code>r = A0*
</code></pre>
<p><em>A will represent the leftover regex at each stage</em>.</p>
<p>This can trivially be applied to left zero-padding as well, because a binary string <code>X</code> is numerically equivalent to the binary string <code>0X</code> (issues of <a href="http://en.wikipedia.org/wiki/Endianness?ref=alexbowe.com">endianness</a> aside):</p>
<pre><code>r = 0*A0*
</code></pre>
<p>Since we already covered even multiples, to work out <code>A</code> we just need to look at odd multiples of <code>3</code>. Here are a few:</p>
<pre><code>&gt;&gt; 50.times {|n| puts &quot;#{n}: #{n.to_bin_s}&quot; if n%3 == 0 and n%2 != 0}
3: 11
9: 1001
15: 1111
21: 10101
27: 11011
33: 100001
39: 100111
45: 101101
</code></pre>
<p>You might have noticed that <code>1111</code> (15) is just <code>11</code> (3) concatenated with itself. That&#x2019;s the same as saying <code>15 = 3 * 2 * 2 + 3</code>. If you add two multiples of three, you will of course get another multiple of 3 (it&#x2019;s the same for any multiplier), and concatenating just involves doubling the first number a few times pre-addition. Hence, you will always get another multiple of 3 by concatenating two.</p>
<pre><code>r = (0*A0*)+
</code></pre>
<p>From observation, here are the above numbers that are <em>not</em> concatenations:</p>
<pre><code>3: 11
9: 1001
21: 10101
33: 100001
45: 101101
</code></pre>
<p>Take note that it always starts and ends with a <code>1</code>. It should definitely end with a <code>1</code> to be odd, and start with a different <code>1</code> to be greater than <code>1</code>. Our updated regex becomes:</p>
<pre><code>r = (0*1A10*)+
</code></pre>
<p><img src="https://i2.wp.com/alexbowe.com/wp-content/uploads/2010/11/autom1.png?resize=362%2C203&amp;ssl=1" alt="autom1" loading="lazy">It also appears that we can optionally insert an even number of zeros between the end <code>1</code>s. A proof of this is attached at the end, if you&#x2019;re into that sort of thing.</p>
<pre><code>r = (0*1(0A0)*10*)+
</code></pre>
<p><img src="https://i2.wp.com/alexbowe.com/wp-content/uploads/2010/11/autom2.png?resize=362%2C244&amp;ssl=1" alt="autom2" loading="lazy"><br>
So what about those <code>1</code>s in the middle then? It appears that we&#x2019;re allowed to have 0, 1 or 2&#x2026; maybe more consecutive 1s? Maybe we can say our regex is <code>r = (0*1(01*0)*10*)+</code>. I&#x2019;ll <a href="https://gist.github.com/711644?ref=alexbowe.com">test</a> the regex for the first 5000 integers:</p>
<pre><code>False Negatives:
  0
</code></pre>
<p>Oops! I forgot about <code>0</code> being evenly divisible by <code>3</code> exactly <code>0</code> times. Our regex should account for this:</p>
<pre><code>r = 0|(0*1(01*0)*10*)+
</code></pre>
<p><img src="https://i0.wp.com/alexbowe.com/wp-content/uploads/2010/11/autom3.png?resize=362%2C319&amp;ssl=1" alt="autom3" loading="lazy"><br>
Running the test again we get this output:</p>
<pre><code>Pass =]
</code></pre>
<p>So there you have it, the regex works for the first 5000 integers. I&#x2019;ll leave a proof of this for all multiples of 3 as an exercise to the reader ;)</p>
<hr>
<p>[1] I&#x2019;m not sure I want to work for someone else anymore &#x2013; I&#x2019;d rather chase my own stupid dreams. Probably not the rockstar one though. I&#x2019;ll write about these later.</p>
<p>[2] Other good sources of practice questions are <a href="http://www.amazon.com/gp/product/0201657880/alexbowecom-20?ref=alexbowe.com">Programming Pearls</a>, <a href="http://projecteuler.net/?ref=alexbowe.com">Project Euler</a>, or you could take a paper from <a href="http://scholar.google.com.au/scholar?as_q=&amp;num=10&amp;btnG=Search+Scholar&amp;as_epq=&amp;as_oq=&amp;as_eq=&amp;as_occt=any&amp;as_sauthors=&amp;as_publication=acm+transactions+on+algorithms&amp;as_ylo=&amp;as_yhi=&amp;as_sdt=1.&amp;as_sdtp=on&amp;as_sdts=5&amp;hl=en&amp;ref=alexbowe.com">ACM Transactions on Algorithms</a><br>
(for example) and implement the algorithm/data structure. While you&#x2019;re at it, why not learn <a href="http://www.erlang.org/?ref=alexbowe.com">Erlang</a> (or any other programming language guaranteed to make you more appealing to the opposite sex) and implement it in that?</p>
<p>[3] Recently, a past student of mine told me that they have never found Computing Theory to be of any use. I said &#x201C;What about regular expressions?&#x201D; and they shook their head. This was a smart student too, but I find that regular expressions are so damn useful <a href="http://m68k.net/2010/09/01/stop-searching-for-regexes.html?ref=alexbowe.com">(perhaps a hammer I swing too often)</a>. Ironically, Computing <em>Theory</em> was the most practically useful subject in my (watered down) degree. In the near future I intend on climbing on my high-horse and writing a blog post about my ideal CS degree.</p>
<hr>
<h2 id="appendix">Appendix</h2>
<p>Here is a proof that shows we can optionally insert an even number of zeros between two <code>1</code>s to get an odd multiple of 3. This is equivalent to saying that our left-most <code>1</code> has to be in an odd position index (if 0 is the rightmost&#x2026;).</p>
<pre><code>RTP: 2^(2i + 1) + 1 = 3m, for m odd integer and i positive integer or 0

Let i = 0, then
LHS = 2^1 + 1
    = 2 + 1
    = 3 * 1
    = 3m (1 is an odd integer)
    = RHS
    =&gt; it holds for i = 0

Let i = k for any integer k, then assume
2^(2k + 1) + 1 = 3m

Let i = k + 1, then
LHS = 2^[2(k + 1) + 1] + 1
    = 2^(2k + 1 + 2) + 1
    = 4 * 2^(2k + 1) + 1
    = 3 * 2^(2k + 1) + 3m&apos;
    = 3[ 2^(2k + 1) + m&apos;]
    = 3[ 2^(2k + 1) + 1 + (m&apos; - 1)]
    = 3[3m&apos; + (m&apos; - 1)]
    = 3(4m&apos; - 1)
    = 3m (an even number minus 1 will be odd)
    = RHS
QED
</code></pre>
<p>Yes, 2^n + 1 always yields an odd multiple of 3, for n odd. I should really set up a math plugin&#x2026;</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Hero Typing]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/cape.jpg#center" alt="cape" loading="lazy"></p>
<p>&#x201C;Who is your hero?&#x201D; is a question I&#x2019;ve been asked, but never had an answer for. Why is this a question that people are compelled to ask? Are we expected to have a hero, like a favourite colour or number?</p>
<p>In his book <a href="http://www.amazon.com/gp/product/1934356344/alexbowecom-20?ref=alexbowe.com">The Passionate Programmer</a></p>]]></description><link>https://www.alexbowe.com/hero-typing/</link><guid isPermaLink="false">619714f2c62458003bddca61</guid><category><![CDATA[motivation]]></category><dc:creator><![CDATA[Alex Bowe]]></dc:creator><pubDate>Mon, 09 Aug 2010 08:19:13 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p><img src="https://storage.ghost.io/c/cf/38/cf384312-4fdc-42c1-8528-b552014aae70/content/images/2023/07/cape.jpg#center" alt="cape" loading="lazy"></p>
<p>&#x201C;Who is your hero?&#x201D; is a question I&#x2019;ve been asked, but never had an answer for. Why is this a question that people are compelled to ask? Are we expected to have a hero, like a favourite colour or number?</p>
<p>In his book <a href="http://www.amazon.com/gp/product/1934356344/alexbowecom-20?ref=alexbowe.com">The Passionate Programmer</a>, <a href="http://www.chadfowler.com/?ref=alexbowe.com">Chad Fowler</a> quotes jazz musician Pat Metheny when he writes this advice to aspiring developers: &#x201C;Be the worst guy [or girl] in every band you&#x2019;re in&#x201D; (an excerpt is available <a href="http://media.pragprog.com/titles/cfcar2/worst.pdf?ref=alexbowe.com">here</a>). Chad argues that being in proximity of more talented programmers can make you &#x201C;better via osmosis&#x201D;.</p>
<p>As programmers, we have many opportunities to find a better band (e.g. open source) &#x2013; however, I think that this advice can be reapplied to nearly any domain, and the benefit gained remotely. In general, if it is against your current nature to be as awesome as X, consider X your hero. This is why we should have heroes; not to be in awe of them, but to hypnotise ourselves to want to <a href="http://en.wikipedia.org/wiki/Duck_typing?ref=alexbowe.com">quack like a duck</a>.</p>
<p>I&#x2019;m writing this at the risk of quacking like a motivational speaker. I&#x2019;m not a fan of people who try to motivate you by saying obvious, non-actionable things like &#x201C;believe in yourself&#x201D;. How the fuck am I meant to do that? No, I&#x2019;m talking about heroes who can actually stir some change of behaviour in you, for the better. Teachers, if you will.</p>
<p>One of the reasons I found it hard to answer &#x201C;Who is your hero?&#x201D; is because I didn&#x2019;t know what a hero was. Take Superman for example: Superman is not a hero in my sense of the word, because he only saved us from the baddies. He didn&#x2019;t improve the human race, he didn&#x2019;t encourage our evolution. He didn&#x2019;t teach mankind to fish, so we only ate for a day.</p>
<p>In case you want to know who my heroes are, I like the way <a href="http://www.paulgraham.com/?ref=alexbowe.com">Paul Graham</a> quacks. If you know me then I have probably mentioned him to you before. The guy has <a href="http://www.paulgraham.com/say.html?ref=alexbowe.com">ideas</a> and he knows how to write.</p>
<p>Then there&#x2019;s <a href="http://en.wikipedia.org/wiki/Evariste_Galois?ref=alexbowe.com">Galois</a>. His legend says that he stayed up all night writing everything he knew about <a href="http://en.wikipedia.org/wiki/Group_theory?ref=alexbowe.com">group theory</a> before dying in a gun duel the next day. He was 20 and the duel was over a girl. I like that someone who contributed so much to mathematics was also crazy enough to die for a girl. It&#x2019;s chivalry, it&#x2019;s destructive and it&#x2019;s rock and roll.</p>
<p>I didn&#x2019;t have to choose these heroes, they are just people who I admire. I think that choosing to admire someone is a strong commitment, one that forces you to consider what you care about (<a href="http://pragprog.com/the-pragmatic-programmer/extracts/tips?ref=alexbowe.com">tip #1</a> in <a href="http://www.amazon.com/gp/product/020161622X/alexbowecom-20?ref=alexbowe.com">The Pragmatic Programmer</a>). Think about who your hero is; if it doesn&#x2019;t make you more awesome, then at least you&#x2019;ll have an answer when people ask you &#x201C;Who is your hero?&#x201D;</p>
<p>So, who is your hero?</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>