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

<channel>
	<title>samskivert</title>
	<atom:link href="http://samskivert.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://samskivert.com</link>
	<description>Ramblings by one Michael D. Bayne</description>
	<lastBuildDate>Wed, 25 Aug 2010 23:30:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Shoot me now</title>
		<link>http://samskivert.com/2010/08/shoot-me-now/</link>
		<comments>http://samskivert.com/2010/08/shoot-me-now/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 23:30:03 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1681</guid>
		<description><![CDATA[I&#8217;m foolishly trying to write a javac annotation processor in Scala. This has already been a road fraught with gratuitous obstacles, but the latest wrinkle has driven me to vent in public. When I run my annotation processor thusly: javac -processor FooProcessor -processorpath fooproc/classes:blah/scala-library.jar SomeFile.java I get &#8220;java.lang.IllegalStateException: zip file closed&#8221; when my processor tries [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m foolishly trying to write a javac annotation processor in Scala. This has already been a road fraught with gratuitous obstacles, but the latest wrinkle has driven me to vent in public.</p>
<p>When I run my annotation processor thusly:</p>
<pre>
javac -processor FooProcessor -processorpath fooproc/classes:blah/scala-library.jar SomeFile.java
</pre>
<p>I get &#8220;java.lang.IllegalStateException: zip file closed&#8221; when my processor tries to load Scala classes. But if I unpack scala-library.jar into fooproc/classes then it works. Joy! Somehow the scala-library.jar file causes javac to choke.</p>
<p>I of course tried repacking the jar file, in case perhaps something in the stock scala-library.jar was weird, but using the repacked version still failed with &#8220;zip file closed.&#8221; What&#8217;s even more awesome is that javac 1.6 does not have a problem with scala-library.jar, only javac 1.7.</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/shoot-me-now/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler 2⁶</title>
		<link>http://samskivert.com/2010/08/euler-2%e2%81%b6/</link>
		<comments>http://samskivert.com/2010/08/euler-2%e2%81%b6/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 18:58:49 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[euler]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1674</guid>
		<description><![CDATA[Problem 064 (source): object Euler064 extends EulerApp { case class Root (root :Int, add :Int, div :Int) { def expand = { val term = ((math.sqrt(root) + add)/div).toInt val nadd = term*div - add (term, Root(root, nadd, (root - nadd*nadd)/div)) } override def toString = &#34;(√&#34; + root + &#34;+&#34; + add + &#34;)/&#34; + [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=64">Problem 064</a> (<a href="http://github.com/samskivert/euler-scala/raw/master/Euler064.scala">source</a>):</p>
<pre class="brush: scala;">
object Euler064 extends EulerApp {
  case class Root (root :Int, add :Int, div :Int) {
    def expand = {
      val term = ((math.sqrt(root) + add)/div).toInt
      val nadd = term*div - add
      (term, Root(root, nadd, (root - nadd*nadd)/div))
    }
    override def toString = &quot;(√&quot; + root + &quot;+&quot; + add + &quot;)/&quot; + div
  }
  def expansion (terms :List[Int], roots :List[Root]) :List[Int] = {
    val (term, root) = roots.head.expand
    if (root.div == 0 || roots.contains(root)) term :: terms
    else expansion(term :: terms, root :: roots)
  }
  def answer = 1 to 10000 map(n =&gt; expansion(Nil, Root(n, 0, 1)::Nil).length) count(_%2==0)
}
</pre>
<p>Here we have a nice little case class to represent a single step in the infinite expansion. The process of generating the next expansion could be done purely with simple arithmetic, but I&#8217;m lazy, so I just use <code>math.sqrt</code> to obtain the non-fractional part. I don&#8217;t actually need to keep track of the terms to obtain the solution, but it was handy to have when I was validating the solution, so I kept it around. Same goes for <code>toString</code>. I just love that little root sign!</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/euler-2%e2%81%b6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler 63</title>
		<link>http://samskivert.com/2010/08/euler-63/</link>
		<comments>http://samskivert.com/2010/08/euler-63/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 00:44:59 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[euler]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1665</guid>
		<description><![CDATA[Problem 063 (source): object Euler063 extends EulerApp { def pows (n :Int) = Stream.from(1) prefixLength(p =&#62; BigInt(n).pow(p).toString.length == p) def answer = 1 to 9 map(pows) sum } The main observation here is that the number of digits of ax, for a ≥ 10, is guaranteed to exceed x. So we can restrict ourselves to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=63">Problem 063</a> (<a href="http://github.com/samskivert/euler-scala/raw/master/Euler063.scala">source</a>):</p>
<pre class="brush: scala;">
object Euler063 extends EulerApp {
  def pows (n :Int) = Stream.from(1) prefixLength(p =&gt; BigInt(n).pow(p).toString.length == p)
  def answer = 1 to 9 map(pows) sum
}
</pre>
<p>The main observation here is that the number of digits of <em>a</em><sup><em>x</em></sup>, for <em>a</em> ≥ 10, is guaranteed to exceed <em>x</em>. So we can restrict ourselves to looking only at the numbers from 1 to 9. Furthermore, the number of digits of <em>a</em><sup><em>x</em></sup>, for 1 ≤ <em>a</em> ≤ 9, will equal <em>x</em> up to some maximum <em>x</em>, and then be less than <em>x</em> for all higher <em>x</em>. That enough <em>x</em>s for you?</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/euler-63/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler 62</title>
		<link>http://samskivert.com/2010/08/euler-62/</link>
		<comments>http://samskivert.com/2010/08/euler-62/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 23:57:55 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[euler]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1647</guid>
		<description><![CDATA[Problem 062 (source): object Euler062 extends EulerApp { def search (n :Long, cubes :Map[Long,List[Long]]) :Long = { val cube = n*n*n val key = cube.toString.sortWith(_&#62;_).toLong val perms = cube :: cubes.getOrElse(key, Nil) if (perms.length == 5) perms.last else search(n+1, cubes + (key -&#62; perms)) } def answer = search(1, Map()) } I was originally using [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=62">Problem 062</a> (<a href="http://github.com/samskivert/euler-scala/raw/master/Euler062.scala">source</a>):</p>
<pre class="brush: scala;">
object Euler062 extends EulerApp {
  def search (n :Long, cubes :Map[Long,List[Long]]) :Long = {
    val cube = n*n*n
    val key = cube.toString.sortWith(_&gt;_).toLong
    val perms = cube :: cubes.getOrElse(key, Nil)
    if (perms.length == 5) perms.last
    else search(n+1, cubes + (key -&gt; perms))
  }
  def answer = search(1, Map())
}
</pre>
<p>I was originally using the dreaded mutation here, and then realized that I could easily rewrite the code to use an immutable map, making it about 10% shorter and about 10% slower. Of course, the garbage collector gets a great big free ride when the program terminates and it most certainly hasn&#8217;t collected any of the intermediate map bits.</p>
<p>The algorithm is pretty straightforward, iterate up the cubes, collecting them into lists of cubes which permute to one another (I bet there&#8217;s some fancy math term for lists that are equivalent up to permutation). When we find one with five permutations, we&#8217;re done. We&#8217;re sort of cheating here because it would be possible to find a cube that permutes to four other seen cubes, but also permutes to as yet unseen cubes, and the problem asks for the smallest cube for which <em>exactly</em> five permutations of its digits are a cube. Fortunately, we find the fifth permutation of the correct cube before we find the fifth permutation of any cube that has more permutations, so we&#8217;re in the clear.</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/euler-62/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compiling Structural Types on the JVM &#8211; Dubochet and Odersky</title>
		<link>http://samskivert.com/2010/08/compiling-structural-types-on-the-jvm-dubochet-and-odersky/</link>
		<comments>http://samskivert.com/2010/08/compiling-structural-types-on-the-jvm-dubochet-and-odersky/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 23:02:30 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[papers]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1639</guid>
		<description><![CDATA[Aside from describing how Scala structural types are implemented (via reflection), this paper shows that such an approach isn&#8217;t wildly slower than an approach that generates shim classes on the fly. Certainly it&#8217;s not ideal for the programmer to have to remember that some kinds of method calls are three times slower than others, but [...]]]></description>
			<content:encoded><![CDATA[<p>Aside from describing how Scala structural types are implemented (via reflection), this paper shows that such an approach isn&#8217;t wildly slower than an approach that generates shim classes on the fly. Certainly it&#8217;s not ideal for the programmer to have to remember that some kinds of method calls are three times slower than others, but the shim class approach is not without drawbacks either. In addition to the problem of the type of <code>this</code>, it has performance related problems as well, as <a href="http://groups.google.com/group/jvm-languages/browse_thread/thread/dbc3a4a382868904">discussed</a> by Charles Nutter of JRuby fame.</p>
<p>Two interesting developments may change the landscape here: <a href="http://blogs.sun.com/jrose/entry/interface_injection_in_the_vm">interface injection</a>, which would solve the problem outright, but has low odds of ever seeing the light of day in a shipping JVM, and <a href="http://blogs.sun.com/jrose/entry/notes_on_an_architecture_for">invokedynamic</a> which could make a reflection-like approach more performant, and should ship with Java 7 (assuming Java 7 ever ships).</p>
<p><b>Source</b>: <a href="http://portal.acm.org/citation.cfm?id=1565829">ACM</a> <a href="http://infoscience.epfl.ch/record/138931/files/2009_structural.pdf">PDF</a></p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/compiling-structural-types-on-the-jvm-dubochet-and-odersky/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modular Type Classes &#8211; Dreyer, et al.</title>
		<link>http://samskivert.com/2010/08/modular-type-classes-dreyer-et-al/</link>
		<comments>http://samskivert.com/2010/08/modular-type-classes-dreyer-et-al/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 22:31:08 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[papers]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1635</guid>
		<description><![CDATA[I backed into type classes via Scala&#8217;s poor man implementation thereof. Thus it is illuminating to see them formulated as ML modules, even though I&#8217;m not particularly familiar with ML modules either. Given the global nature of Haskell&#8217;s type classes, a limitation remedied by both this work and Scala&#8217;s implicits, I wonder what&#8217;s so poor [...]]]></description>
			<content:encoded><![CDATA[<p>I backed into type classes via Scala&#8217;s <a href="http://lampwww.epfl.ch/~odersky/talks/wg2.8-boston06.pdf">poor man</a> implementation thereof. Thus it is illuminating to see them formulated as ML modules, even though I&#8217;m not particularly familiar with ML modules either.</p>
<p>Given the global nature of Haskell&#8217;s type classes, a limitation remedied by both this work and Scala&#8217;s implicits, I wonder what&#8217;s so poor about Scala&#8217;s approach. Are there things that are expressible with &#8220;real&#8221; type classes that are not expressible with implicits? Or maybe it&#8217;s just a matter of preserving the holy grail of perfect type inference.</p>
<p><b>Source:</b> <a href="http://portal.acm.org/citation.cfm?id=1190215.1190229">ACM</a> <a href="http://www.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf">PDF</a></p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/modular-type-classes-dreyer-et-al/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An emacs on every desktop</title>
		<link>http://samskivert.com/2010/08/an-emacs-on-every-desktop/</link>
		<comments>http://samskivert.com/2010/08/an-emacs-on-every-desktop/#comments</comments>
		<pubDate>Fri, 13 Aug 2010 05:27:34 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1614</guid>
		<description><![CDATA[I am a heavy user of virtual desktops. I generally have a couple of shell windows, an emacs window, possibly a browser, and whatever target program I&#8217;m working on, on each of a few virtual desktops. When I&#8217;m interrupted from one project, I flip to the next virtual desktop, open a shell window, open an [...]]]></description>
			<content:encoded><![CDATA[<p>I am a heavy user of virtual desktops. I generally have a couple of shell windows, an emacs window, possibly a browser, and whatever target program I&#8217;m working on, on each of a few virtual desktops. When I&#8217;m interrupted from one project, I flip to the next virtual desktop, open a shell window, open an emacs window and start hacking away on said interruption. Often the stack will get three or four virtual desktops deep, and I&#8217;ll find myself flipping back and forth between the various in-progress projects.</p>
<p>I generally try to open new files from within emacs, rather than from a terminal, but occasionally the terminal is more expedient, except that it results in an entirely new emacs process and window being created on that virtual desktop. The additional virtual memory consumption isn&#8217;t a big deal, but the fact that it screws up my ability to alt-tab between windows is a major annoyance. Plus my brain naturally assumes there&#8217;s one emacs process on each virtual desktop and that process contains all the buffers that have been opened thereon. So when I go to switch to a buffer that I know is open only to discover that it&#8217;s in a different emacs process whose window is hidden behind the one I&#8217;m currently using, it harshes my mellow.</p>
<p>I have played with emacsclient a bit in the past, but it assumes that you use one emacs to rule them all. So if I have an emacs open on virtual desktop one, and run emacsclient on virtual desktop three, it will happily open the requested file on the completely invisible and completely inappropriate emacs instance on virtual desktop one. Not useful. Further, it assumes that you&#8217;re the sort of developer that started emacs back in the late seventies and have kept that instance running ever since. So if you run emacsclient when there&#8217;s no emacs instance running, it happily spits out seven or eight lines of error message and does nothing especially useful.</p>
<p>For whatever reason (probably me subconsciously avoiding the tedious work that I have to get done before the end of this weekend), the camel&#8217;s back broke today (even though this has been bothering me since I started using FVWM in like 1995). I scoured the interwebs for a way to find out what virtual desktop was active (wmctrl FTW) and wrote the necessary scripts and elisp to cause &#8220;emacs filename&#8221; executed on the command line to always do the Right Thing. If there&#8217;s no emacs instance on the active virtual desktop, one is started with the requested file(s). If an instance is running on that virtual desktop, it is instructed to open the requested file(s). And as an added bonus, since I use &#8220;emacs -nw&#8221; for $EDITOR jobs, if the script sees -nw on the command line, it just forks off a whole new emacs with the supplied args, knowing that it will remain safely ensconced in the terminal.</p>
<p>If you too are an emacs user whose workflow resembles mine, feel free to reap the fruits of my labor. Add the following to your .emacs file:</p>
<pre class="brush: ruby;">
(defun cur-desk ()
  &quot;Returns the numeric identifer of the current desktop.&quot;
  (replace-regexp-in-string &quot;\\(^[[:space:]\n]*\\|[[:space:]\n]*$\\)&quot; &quot;&quot;
    (shell-command-to-string &quot;wmctrl -d | grep '\*' | awk '{ print $1 }'&quot;))
  )
(if (string= &quot;x&quot; window-system)
    (progn (setq server-name (format &quot;server%s&quot; (cur-desk)))
           (server-start)))
</pre>
<p>and create a shell script in your favorite location with the following contents:</p>
<pre class="brush: bash;">
#!/bin/sh

EMACS=/usr/bin/emacs

# if we have -nw on the command line, invoke a separate emacs instance
for ARG in $*; do
    if [ $ARG = &quot;-nw&quot; ]; then
        exec $EMACS $*
    fi
done

# otherwise send the file(s) to the emacs instance on this virtual desktop
CURDESK=`wmctrl -d | grep '\*' | awk '{ print $1 }'`
emacsclient -s &quot;server$CURDESK&quot; --no-wait $* &gt; /dev/null 2&gt;&amp;1
if [ $? != 0 ]; then
    # no instance running on this virtual desktop, so start one
    $EMACS $* &amp;
fi
</pre>
<p>There are probably better ways to accomplish both of the above bits of code. My bash and elisp skills have both perpetually lingered in the &#8220;good enough to get the job done&#8221; realm.</p>
<p><em>Side note: I can&#8217;t believe the SyntaxHighlighter WordPress plugin doesn&#8217;t have support for Lisp. They support actionscript3, bash, coldfusion, cpp, csharp, css, delphi, erlang, fsharp, diff, groovy, javascript, java, javafx, matlab, obj-c, perl, php, text, powershell, python, ruby, scala, sql, vb, xml, and have the audacity to claim that &#8220;most widely used languages are supported&#8221;. Perhaps Lisp no longer rates as widely used. Ah well, I just used the Ruby highlighter. Ruby is just an accessible Lisp right?</em></p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/08/an-emacs-on-every-desktop/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Euler 61</title>
		<link>http://samskivert.com/2010/07/euler-61/</link>
		<comments>http://samskivert.com/2010/07/euler-61/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 18:48:37 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[euler]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1596</guid>
		<description><![CDATA[Problem 061: object Euler61 extends EulerApp { case class Pn (card :Int, value :Int) { def valid = (value &#60; 10000) &#38;&#38; (value &#62; 999) def ab = value / 100 def cd = value % 100 } def tri (n :Int) = Pn(3, n*(n+1)/2) def square (n :Int) = Pn(4, n*n) def pent (n [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=61">Problem 061</a>:</p>
<pre class="brush: scala;">
object Euler61 extends EulerApp {
  case class Pn (card :Int, value :Int) {
    def valid = (value &lt; 10000) &amp;&amp; (value &gt; 999)
    def ab = value / 100
    def cd = value % 100
  }

  def tri (n :Int) = Pn(3, n*(n+1)/2)
  def square (n :Int) = Pn(4, n*n)
  def pent (n :Int) = Pn(5, n*(3*n-1)/2)
  def hex (n :Int) = Pn(6, n*(2*n-1))
  def hept (n :Int) = Pn(7, n*(5*n-3)/2)
  def oct (n :Int) = Pn(8, n*(3*n-2))
  def gen (max :Int)(gen :(Int) =&gt; Pn) = (1 to max) map(gen) filter(_.valid)
  val nums = List(square _, pent _, hex _, hept _, oct _) flatMap(gen(100))

  def search (nums :Seq[Pn], set :List[Pn]) :Option[List[Pn]] = {
    if (!nums.isEmpty) (for (n &lt;- nums; if (n.ab == set.last.cd);
                             s &lt;- search(nums filter(_.card != n.card), set :+ n))
                        yield s) headOption
    else if (set.last.cd == set.head.ab) Some(set)
    else None
  }
  def sets = for (n &lt;- gen(150)(tri); s &lt;- search(nums, n::Nil)) yield s
  def answer = (sets head) map(_.value) sum
}
</pre>
<p>I model a polygonal number with a case class to track it&#8217;s value and cardinality. Since I care about four-digitality and two digit prefixes and suffixes, those fit nicely as methods on the class. The main search proceeds by starting with a given triangle number (since all sets must have one triangular element), and then looks for a number that matches the suffix of said number. If one is found, it is added to the ordered set, all other numbers with the same cardinality are dropped from the candidates list, and a new number is sought that matches the suffix of the value just added.</p>
<p>If we match a number for each cardinality, then we&#8217;ll finally end up in the <code>search</code> procedure with an empty candidates list, in which case we check whether the last number in the ordered set matches the first.</p>
<p>Functional programming comment: when I first wrote this, I was using <code>Nil</code> to indicate a non-match, and had a few <code>find(Nil.!=)</code> calls sprinkled around to find matching elements. That smelled suspiciously like using <code>null</code>, so I decided to be a good functional programmer and use <code>Option</code>. However, this left me in situations where I&#8217;d have a <code>List[Option[Pn]]</code> and I&#8217;d need the first non-<code>None</code> element. I know that I can take such a list and do <code>list flatMap(x => x) head</code> but that seems insufficiently scrutable to people not familiar with the idiom.</p>
<p>This motivated me to switch to for-comprehensions. Instead of writing:</p>
<pre class="brush: scala;">
nums filter(_.ab == set.last.cd) map(n =&gt; search(...)) flatMap(s =&gt; s) headOption
</pre>
<p>I use what you see above:</p>
<pre class="brush: scala;">
(for (n &lt;- nums; if (n.ab == set.last.cd); s &lt;- search(...)) yield s) headOption
</pre>
<p>The for-comprehension turns out to be a little shorter, a lot easier to line-wrap (if needed), and I think probably slightly more comprehensible. You still have to deduce that <code>Option</code> behaves like a zero-or-one element list when used in a for-comprehension, but that seems more intuitive than figuring out that <code>List(Some(1), None, Some(2)) flatMap(x => x)</code> gives you <code>List(1, 2)</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/07/euler-61/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Euler 60</title>
		<link>http://samskivert.com/2010/07/euler-60/</link>
		<comments>http://samskivert.com/2010/07/euler-60/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 17:13:05 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[euler]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1590</guid>
		<description><![CDATA[Problem 060: object Euler60 extends EulerApp { val primes = genprimes(10000) filter(0.!=) val ppairs = Set() ++ (for { ii &#60;- 0 until primes.length-1; jj &#60;- ii until primes.length; val pi = primes(ii); val pj = primes(jj); if (isprime((pi.toString+pj).toInt) &#38;&#38; isprime((pj.toString+pi).toInt)) } yield (pi, pj)) def isset (pset :List[Int], prime :Int) = pset.foldLeft(true)((b, a) =&#62; [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=60">Problem 060</a>:</p>
<pre class="brush: scala;">
object Euler60 extends EulerApp {
  val primes = genprimes(10000) filter(0.!=)
  val ppairs = Set() ++
    (for { ii &lt;- 0 until primes.length-1; jj &lt;- ii until primes.length;
          val pi = primes(ii); val pj = primes(jj);
          if (isprime((pi.toString+pj).toInt) &amp;&amp; isprime((pj.toString+pi).toInt))
    } yield (pi, pj))
  def isset (pset :List[Int], prime :Int) =
    pset.foldLeft(true)((b, a) =&gt; b &amp;&amp; ppairs((a, prime)))
  def find (pset :List[Int], plist :List[Int]) :Option[List[Int]] = {
    if (pset.size == 5) Some(pset)
    else if (plist.isEmpty) None
    else if (!isset(pset, plist.head)) find(pset, plist.tail)
    else find(plist.head :: pset, plist.tail).orElse(find(pset, plist.tail))
  }
  def answer = find(Nil, primes.toList).get.sum
}
</pre>
<p>This one&#8217;s not particularly concise, but it&#8217;s fairly readable (or at least I think so since I wrote the code just shy of two years ago and it wasn&#8217;t too hard to regrok it in order to write this blog post).</p>
<p>First we generate a &#8220;reasonable&#8221; number of primes (which is cheating a little, but also really simplifies things). Then we precompute which of those primes pair with one another so that we can check a given pair of primes for pair-ness quickly later. Being able to concisely turn a sequence into a set, and having structurally-comparable tuples for free is so nice.</p>
<p>Now we climb up the list of primes, each time checking whether the current prime can expand our current set of concatenable primes. This check only requires that the candidate prime properly pair with each prime in the set, since we already know that all the primes in the set pair with one another (because they were each checked before they were added). If it does pair, add it to the set and either way we continue with the next prime. If we reach the end of our list of primes and we haven&#8217;t found a set of five, we backtrack (making use of the call stack) and execute the <code>orElse</code> and try again without that most recently added pairable prime.</p>
<p>When we first start out, our set is empty, so the first prime trivially pairs with our existing empty set and is added to the set. When that turns out not to yield a set of five concatenable primes, we pop that first prime off and try the second prime, and so on down the line.</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/07/euler-60/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Euler 59</title>
		<link>http://samskivert.com/2010/07/euler-59/</link>
		<comments>http://samskivert.com/2010/07/euler-59/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 16:12:57 +0000</pubDate>
		<dc:creator>mdb</dc:creator>
				<category><![CDATA[euler]]></category>

		<guid isPermaLink="false">http://samskivert.com/?p=1579</guid>
		<description><![CDATA[Problem 059: object Euler59 extends EulerApp { val cipher = readline(&#34;cipher1.txt&#34;) split(',') map(_.toInt) def decode (cipher :Array[Int], key :Array[Char]) = (0 until cipher.length) map(ii =&#62; cipher(ii) ^ key(ii%key.length)) def answer = (for { a &#60;- 'a' to 'z'; b &#60;- 'a' to 'z'; c &#60;- 'a' to 'z' val decoded = decode(cipher, Array(a, b, c)) [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/index.php?section=problems&#038;id=59">Problem 059</a>:</p>
<pre class="brush: scala;">
object Euler59 extends EulerApp {
  val cipher = readline(&quot;cipher1.txt&quot;) split(',') map(_.toInt)
  def decode (cipher :Array[Int], key :Array[Char]) =
    (0 until cipher.length) map(ii =&gt; cipher(ii) ^ key(ii%key.length))
  def answer = (for {
    a &lt;- 'a' to 'z'; b &lt;- 'a' to 'z'; c &lt;- 'a' to 'z'
    val decoded = decode(cipher, Array(a, b, c))
    if (decoded.map(_.toChar).mkString.contains(&quot; chapter&quot;))
  } yield decoded.sum).head
}
</pre>
<p>Nothing fancy here. I do a brute force search, trying each key in turn and looking for a particular English word to indicate that the decoding is correct. I&#8217;m cheating a little in that I first had the program print out the decoded text, and once I saw the correct decoding, I selected a word therefrom to use in the final version. I suppose I could read in a dictionary of English words and assume I&#8217;d found the key when my decoding contained a few of the words in the dictionary. That sounds like way too much work for an Euler problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://samskivert.com/2010/07/euler-59/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
