<?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>vi-kan.net</title>
	<atom:link href="http://blog.vi-kan.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.vi-kan.net</link>
	<description>{ TODO -oVegar : insert clever text here}</description>
	<lastBuildDate>Thu, 06 May 2010 13:27:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Basic CouchDB interaction</title>
		<link>http://blog.vi-kan.net/2010/basic-couchdb-interaction/</link>
		<comments>http://blog.vi-kan.net/2010/basic-couchdb-interaction/#comments</comments>
		<pubDate>Thu, 06 May 2010 12:51:45 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[CouchDB]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2010/basic-couchdb-interaction/</guid>
		<description><![CDATA[ So, did you read my little introduction? Did you go nuts with the Futon application?&#160;&#160; Well, then, I guess it’s time to look a little closer on the CouchDB API.
As mentioned before, CouchDB provides a RESTful API. You will be sending requests over HTTP, and checking status codes for success. This makes it easy [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://ditchnet.org/httpclient/" target="_blank"><img style="border-bottom: 0px; border-left: 0px; margin: 0px 0px 0px 10px; display: inline; border-top: 0px; border-right: 0px" title="HTTP Client" border="0" alt="HTTP Client" align="right" src="http://blog.vi-kan.net/wp-content/uploads/2010/05/image3.png" width="176" height="147" /></a> So, did you read my little <a title="Introducing CouchDB" href="http://blog.vi-kan.net/2010/introducing-couchdb/">introduction</a>? Did you go nuts with the Futon application?&#160;&#160; Well, then, I guess it’s time to look a little closer on the CouchDB API.</p>
<p>As mentioned before, CouchDB provides a RESTful API. You will be sending requests over HTTP, and checking status codes for success. This makes it easy to test features, by using small utilities like <a href="http://ditchnet.org/httpclient/">HTTP Client</a> and <a href="http://curl.haxx.se/">Curl</a>. All GET operations should be easy enough to do through your browser, and some browsers have addons that lets you make other kind of requests too. So find a tool that suites you well, and start the expedition.</p>
<p> <span id="more-199"></span>
</p>
<h2>Say Hello to CouchDB</h2>
<p>Before we start making databases and documents, you should check that the server is running. Make a simple GET request to the server to see if you get any response.</p>
<pre class="brush:bash; light: true">GET http://127.0.0.1:5984/</pre>
<p>
  <br />If the server is running, it will respond with a welcome message and a version number.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;couchdb&quot;:&quot;Welcome&quot;,&quot;version&quot;:&quot;0.11.0&quot;}</pre>
<p>
  <br />You can also check to see what databases allready exists on the server, by doing a GET request to /_all_dbs.</p>
<p></p>
<pre class="brush:bash; light: true">GET http://127.0.0.1:5984/_all_dbs</pre>
<p>
  <br />The resonse will be formatted as an JSON array with database names.</p>
<p></p>
<pre class="brush: js; light: true;">[&quot;business-cards&quot;,&quot;newdb&quot;,&quot;testdb&quot;]</pre>
<h2>Databases</h2>
<p>CouchDB exposes most everything as resources accessable by urls. This is one part of what makes it RESTful. So when you want to access one of the existing databases, you will make a GET request for the name of the database.</p>
<pre class="brush:bash; light: true">GET http://127.0.0.1:5984/business-cards</pre>
<p>
  <br />This request want return the complete database with all its documents. It will instead return some information about the database.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;db_name&quot;:&quot;business-cards&quot;, &quot;doc_count&quot;:2, &quot;doc_del_count&quot;:1, &quot;update_seq&quot;:4, &quot;purge_seq&quot;:0, &quot;compact_running&quot;:false, &quot;disk_size&quot;:16473, &quot;instance_start_time&quot;:&quot;1273129328746881&quot;, &quot;disk_format_version&quot;:5}</pre>
<p>As you can see, our business card database from our introduction contains two documents. It also contains one deleted document which is not purged yet.</p>
<p>Since the name of the database is used as an url, there has to be some constraints on what characters can be used. To make it easy to support different platforms, and avoid issues with casing, CouchDB will only allow lowercase letters in the range ‘a’ to ‘z’. It will also allow digits and the following characters: _ $ ( ) + – /</p>
<p>By allowing the /-character, it is possible to group different databases into namespaces, like /blog/posts and /blog/comments. It can be a little tricy to test, though. You will need to encode the / into %2F, but HTTP Client, which I use, doesn’t like that. It will encode the % into %25 and send %252F instead of %2F. I guess there is some way of escapting this, but I don’t know for sure.</p>
<p>So lets create our first database. I will make myself a database of geocaches. So what would be more natural then just to PUT it right there at the server?</p>
<pre class="brush:bash; light: true">PUT http://127.0.0.1:5984/geocaches</pre>
<p>
  <br />If the database was created as expected, we will get a positive response.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;ok&quot;:true}</pre>
<p>
  <br />If the database name is taken, we will get an error response. The response will contain a standard HTTP status code, 412 Precondition Failed, and the body of the response will give us even more information.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;error&quot;:&quot;file_exists&quot;,&quot;reason&quot;:&quot;The database could not be created, the file already exists.&quot;}</pre>
<p>
  <br />Similar, if we try to use one of the forbidden characters, we will get a 400 Bad Request with additional information on how to behave in the future.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;error&quot;:&quot;illegal_database_name&quot;, &quot;reason&quot;:&quot;Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed&quot;}</pre>
<p>Nice.</p>
<p>If you need to remove the database again, you make a…..?&#160; Yes, a DELETE request.</p>
<pre class="brush:bash; light: true">DELETE http://127.0.0.1:5984/geocaches</pre>
<p>If everything goes well, the server will respond with a happy ‘ok’, and the database with all its documents is gone. No ‘please, confirm’ or ‘are you sure’, so now you’re warned.</p>
<h2>Documents</h2>
<p>In the world of CouchDB, a document consists of key-value pairs. Every document needs an unique id, which is stored in the ‘_id’-key. When you create a new documet, CouchDB will provide one for you if you want it too. The id will then be in the form of a guid, a string of 32 hexadecimal values.</p>
<p>The id of a document will be used as part of the uri when you later want to retrieve or change your document. If the data you want to store already have a unique identification, you could use that and get more domain specific urls. Be careful though. Not every character is suitable to be part of an uri, and you would need to escape them appropriately .</p>
<h3>Create</h3>
<p>I want to store geocaches, and every geocache has an unique name consisting of letters and digits. I will therefore use this name as the id for my document. Heres my first geocache:</p>
<pre class="brush: js; light: true;">{
   &quot;url&quot;: &quot;http://www.geocaching.com/seek/cache_details.aspx?guid=ab5cc0fb-4f0f-4809-98a1-60697daa5e08&quot;,
   &quot;sym&quot;: &quot;Geocache Found&quot;,
   &quot;lon&quot;: 18.973967,
   &quot;lat&quot;: 69.696533,
   &quot;urlname&quot;: &quot;Nesten hjemme&quot;,
   &quot;type&quot;: &quot;Geocache|Traditional Cache&quot;,
   &quot;time&quot;: &quot;2009-06-07T07:00:00Z&quot;,
   &quot;name&quot;: &quot;GC1TCJR&quot;,
   &quot;desc&quot;: &quot;Nesten hjemme by Geo_Raiders, Traditional Cache (2/1.5)&quot;
}</pre>
<p>
  <br />I want to store this as an document with the key GC1TCJR in the database geocaches, so lets PUT it up there.</p>
<p></p>
<pre class="brush:bash; light: true">PUT http://127.0.0.1:5984/geocaches/GC1TCJR
{“url”:”http://www.geocaching.com/seek/cache_details.aspx?guid=…….&quot;}</pre>
<p>
  <br />If everything goes by the plan, CouchDB will responde with a 201 Created status, together with something like this:</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;ok&quot;:true,&quot;id&quot;:&quot;GC1TCJR&quot;,&quot;rev&quot;:&quot;1-f70033bafd9d72e174cecb67f58b2e4f&quot;}</pre>
<p>
  <br />If a document with the same id already exists, you will get a 409 Conflict status and the following error:</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;error&quot;:&quot;conflict&quot;,&quot;reason&quot;:&quot;Document update conflict.&quot;}</pre>
<p>You may wonder what the “rev” value returned is for. CouchDB will never change a document. Instead, it will make a new document stored with the same id. The reason for this is to handle concurrency, and you should not rely on this for any revision control in your application. You can compact a database to get rid of wasted space.</p>
<p>If we want CouchDB to generate a id for us, we could use a POST instead. We would also omit the id from the url, since the id yet remains to be decided.</p>
<pre class="brush:bash; light: true">POST http://127.0.0.1:5984/geocaches
{“url”:”http://www.geocaching.com/seek/cache_details.aspx?guid=……&quot;}</pre>
<p>
  <br />Now that we have successfully stored our document, we can retreive it by doing a GET.</p>
<p></p>
<pre class="brush:bash; light: true">GET http://127.0.0.1:5984/geocaches/GC1TCJR</pre>
<p>
  <br />As you can see from the response, CouchDB has added the id and revision fields to our document.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;_id&quot;:&quot;GC1TCJR&quot;,&quot;_rev&quot;:&quot;1-f70033bafd9d72e174cecb67f58b2e4f&quot;,&quot;url&quot;:&quot;http://www.geocaching.com/……&quot;}</pre>
<h3>Update</h3>
<p>Storing updates is nearly as simple as creating new documents. The only difference is that the document must contain both the id and the rev values, and the rev value needs to point to the latest revision. So if you get a document first, make your changes, and then put it up on the server again, things should go nicely. If someone else has stored an update between your get and put request, you will get an conflict error that you need to resolve. How you resolve the conflict is up to the you. You could try to merge your changes with the new revision in the database, or you could simply update your rev value with the latest from the databse and do a new put, effectively overwriting what changes that may have been done.</p>
<pre class="brush:bash; light: true">PUT http://127.0.0.1:5984/geocaches/GC1TCJR
{&quot;_id&quot;:&quot;GC1TCJR&quot;,&quot;_rev&quot;:&quot;1-f70033bafd9d72e174cecb67f58b2e4f&quot;,&quot;url&quot;:&quot;http://www.geoinfo.com/……</pre>
<p>
  <br />CouchDB will respond with a 200 OK status, and inform you about the new revision number.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;ok&quot;:true,&quot;id&quot;:&quot;GC1TCJR&quot;,&quot;rev&quot;:&quot;2-6aa44736b02f96844fdfbf4eece00b83&quot;}</pre>
<h3>Delete</h3>
<p>Can you guess how to delete a document? Close. You make a DELETE request, but you have to include the latest revision in the url as well.</p>
<pre class="brush:bash; light: true">DELETE http://127.0.0.1:5984/geocaches/GC1TCJR?rev=1-f70033….</pre>
<p>As for updating, CouchDB keep your old document around for a while. It will add a new revision, and mark it as a stub for a deleted document.</p>
<p>The response will tell you the new revision number.</p>
<pre class="brush: js; light: true;">{&quot;ok&quot;:true,&quot;rev&quot;:&quot;3-6b8ecfd8bd5d1cb8ae3fd49aea9dfe8d&quot;}</pre>
<p>
  <br />If you try to do a get on the deleted document, you will get a 404 Object not found response with additional information stating that the document was deleted.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;error&quot;:&quot;not_found&quot;,&quot;reason&quot;:&quot;deleted&quot;}</pre>
<h3>Listing</h3>
<p>Now that you know the basic CRUD operations, it would be nice to get a list of all our documents. CouchDB provides a special url we can use for this.</p>
<pre class="brush:bash; light: true">GET http://127.0.0.1:5984/geocaches/_all_docs</pre>
<p>
  <br />The response will contain information of total number of rows, and an array of ids and revision numbers.</p>
<p></p>
<pre class="brush: js; light: true;">{&quot;total_rows&quot;:4,&quot;offset&quot;:0,&quot;rows&quot;:[
  {&quot;id&quot;:&quot;GC13H9E&quot;,&quot;key&quot;:&quot;GC13H9E&quot;, &quot;value&quot;:{&quot;rev&quot;:&quot;1-8e3c239c5da38d0fbe91ffdd24582b02&quot;}},
  {&quot;id&quot;:&quot;GC144MQ&quot;,&quot;key&quot;:&quot;GC144MQ&quot;, &quot;value&quot;:{&quot;rev&quot;:&quot;1-865f40ed3047aefdf8c45520c84c4321&quot;}},
  {&quot;id&quot;:&quot;GC145KB&quot;,&quot;key&quot;:&quot;GC145KB&quot;, &quot;value&quot;:{&quot;rev&quot;:&quot;1-83ba674d10ce404be7fc90460b1a9a13&quot;}},
  {&quot;id&quot;:&quot;GCYXEG&quot;,&quot;key&quot;:&quot;GCYXEG&quot;, &quot;value&quot;:{&quot;rev&quot;:&quot;1-880c0d1767c8f6db0ce815fe0b35afdb&quot;}}
]}</pre>
<p>
  <br />The _all_docs uri can take some parameters that makes it possible to paginate the result. You can use a combination of ‘startkey’, ‘endkey’, ‘limit’ and ‘skip’. Here is a couple of examples that you can try:</p>
<p></p>
<pre class="brush:bash; light: true">GET http://127.0.0.1:5984/geocaches/_all_docs?limit=2
  =&gt;First two documents
GET http://127.0.0.1:5984/geocaches/_all_docs?limit=2&amp;skip=2
  =&gt;Third and fourth document
GET http://127.0.0.1:5984/geocaches/_all_docs?startkey=GC144MQ&amp;limit=2&amp;skip=1
  =&gt;Two next documents after GC144MQ</pre>
<h2>What’s next?</h2>
<p>Well, then. You should now have enough information to start making basic use of CouchDB. There are still a lot to cover, though. Did you know that you can upload binary attachments to documents? You can. What you can’t, though, is to query your data using SQL. Instead you will be making views, but that has to be waiting for now.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/basic-couchdb-interaction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing CouchDB</title>
		<link>http://blog.vi-kan.net/2010/introducing-couchdb/</link>
		<comments>http://blog.vi-kan.net/2010/introducing-couchdb/#comments</comments>
		<pubDate>Tue, 04 May 2010 13:12:46 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[CouchDB]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2010/introducing-couchdb/</guid>
		<description><![CDATA[ A while back, I became aware of something called CouchDB. Since then, I have spend a little time now and then trying to understand what it is, and if I should care. I still struggle a bit with the whole idea of ‘document datebases’ and when it is more appropriate then relational databases, but [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 0px 0px 0px 10px; display: inline; border-width: 0px;" title="image" src="http://blog.vi-kan.net/wp-content/uploads/2010/05/image2.png" border="0" alt="image" width="171" height="103" align="right" /> A while back, I became aware of something called CouchDB. Since then, I have spend a little time now and then trying to understand what it is, and if I should care. I still struggle a bit with the whole idea of ‘document datebases’ and when it is more appropriate then relational databases, but want let a lack of understanding stop me from getting my hands wet.</p>
<p><span id="more-189"></span></p>
<h2>The basics</h2>
<p>So here is the most basic ideas behind CouchDB and how it works.</p>
<h3>Documents</h3>
<p>While a relational db stores rows in tables, CouchDB stores jason-formatted documents. While a table in a relational db has a defined set of columns that can have values, there is no definition on what values a document in CouchDB should contain. So when a table enforce every row to be in the same format, each and every document in a CouchDB database could contain completly different kind of values.</p>
<p>The book <a href="http://my.safaribooksonline.com/9780596158156" target="_blank">CouchDB: The Definitive Guide</a> uses business cards as an illustration on this. In a traditional database, you would have a table where each row represents one business card. You then have to choose what columns you would have. You would need a name, a telephone number, a url to a website and an email address. After a while, you realise that you would need a column for a company name and a new column for a second telephonenumber for the company. In the third iteration, you realise that you sill need  more phonenumbers, and maybe even a fax. Now, should we make more telephone columns, or should we have a one-to-many relationship from a business card to a list of phonenumbers? And what about all our trendy business contacts with only a single url on their card? There would be a whole lot of emtpy columns then.<a href="http://blog.vi-kan.net/wp-content/uploads/2010/05/image.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto; border-width: 0px;" title="Table of business cards" src="http://blog.vi-kan.net/wp-content/uploads/2010/05/image_thumb.png" border="0" alt="Table of business cards" width="600" height="70" /></a></p>
<p>In CouchDB, you would have a business card database where each card would be represented by one document. The content of the document would be defined by the data on that given businesscard.<img style="display: block; float: none; margin-left: auto; margin-right: auto; border-width: 0px;" title="Business cards as documents" src="http://blog.vi-kan.net/wp-content/uploads/2010/05/image1.png" border="0" alt="Business cards as documents" width="154" height="176" /></p>
<p>As you can see, this makes everything very flexible. No need for any migration of existing documents when you suddanly find your first business card with a twitter name on it.</p>
<h3>HTTP and REST</h3>
<p>CouchDB is basically a small webserver listening to a given port. When communicating with the server, you would make HTTP requests specifying what you want, and CouchDB would make an apropriate respons. Instead of inventing some new rpc format, it uses the basic http request methods for each and every method. So if you want to get a document, you send a GET request. Do create or update a document, you use PUT or POST, and to remove a document, you use DELETE.</p>
<p>A service designed in this way, is often refered to as RESTful.</p>
<h3>JSON</h3>
<p>Every response comming from CouchDB, and every document stored inside CouchDB, will be in the form of JSON. JSON, or <a href="http://www.json.org/" target="_blank">JavaScript Object Notation</a>,  is a standard made for representing objects in a way that should be easy both for human and machine to write and consume.</p>
<p>A JSON object consists of a set of name-value pairs, where the value can be either an array of values, a JSON object, a string, a number, true, fase or null. Even though the synax is simple, it is possible to represent list of complex, nested objects.</p>
<p>A JSON representation of one of our business cards could look something like this:</p>
<pre class="brush:js; light: true">{
   "name": "Joseph A. Gutierrez",
   "website": "http://wallpaperdealer.com/",
   "phone": [
       "41-397-0567",
       "954-399-5693"
   ],
   "fax": "518-923-6525"
}</pre>
<h2>Installation</h2>
<p>Like many other open source applications, CouchDB is distributed as source code, some dependencies to other open source technologies, and a description on how to build for you spesific platform. This makes it easy to port everything to different platforms and operating systems, but a little more complex for windows users like me that are used to get everything wrapped up nice in a install executable.</p>
<p>Luckly, there are people out there that provieds us with binaries, and a binary for CouchDB for windows is made available through the <a href="http://wiki.apache.org/couchdb/Windows_binary_installer" target="_blank">CouchDB Wiki</a>.</p>
<p>The installer will suggest installing CouchDB as an service, which makes it easy enough for now.</p>
<h3>Configuration</h3>
<p>CouchDB stores configuration data in two ini files. You can find them where you installed CouchDB in the subfolder \etc\couchdb\. default.ini will contain the defaults, and local.ini will contain your overrides. Do not change default.ini. It will be overridden if you install or update CouchDB at a later time. If you find something in default.ini that you need to tweek, copy the settings into local.ini and make you change there.</p>
<p>The most basic settings is already present inside local.ini to make it easy for you to change. Settings that may be useful is httpd settings, logging and basic authentication.</p>
<h3>Up and running?</h3>
<p>After installation, you can check if everything is OK by navigating to the following url in your browser: <a href="http://localhost:5984/">http://localhost:5984/</a></p>
<p>If CouchDB is running, and if you have not made any changes to port number etc, you should get a welcome greeting from CouchDB, something similar to</p>
<pre class="brush:javascript; light: true;">{"couchdb":"Welcome","version":"0.11.0b916031"}</pre>
<h2>Start playing</h2>
<p>If your CouchDB server greets you welcome, you can start play with it. You can either find a http client letting you compose custom requests, or you can use the administrative interface installed with CouchDB.</p>
<p>Directing your browser to <a href="http://localhost:5984/_utils/">http://localhost:5984/_utils/</a>, you will see a web application called Futon. From there, you can create databases and documents, run CouchDBs suite of unit tests, check out the current configuration and so on.</p>
<p>Go nuts!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/introducing-couchdb/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 10</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-10/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-10/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 20:07:35 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/project-euler-problem-10/</guid>
		<description><![CDATA[Yet another problem involving primes. Guess I have to make a better prime generator soon…
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 
Find the sum of all the primes below two million.

 
Soon, but not yet…
Using the same generator from problem 7, I go for an [...]]]></description>
			<content:encoded><![CDATA[<p>Yet another problem involving primes. Guess I have to make a better prime generator soon…</p>
<blockquote><p>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. </p>
<p>Find the sum of all the primes below two million.</p>
</blockquote>
<p> <span id="more-144"></span>
<p>Soon, but not yet…</p>
<p>Using the same generator from <a title="Find the 10001st prime" href="http://blog.vi-kan.net/2009/project-euler-problem-7/" target="_blank">problem 7</a>, I go for an easy, but slow, solution for this one. There is one thing, though. Our generator generates up to the nth prime, but in this problem, we need to find every prime below 2000000. Already decided not to make a new prime generator, we cheat by asking it generate a lot of primes, and then jump out as soon as we hit a prime to big. </p>
<pre class="brush: delphi;">sum := 0;for prime in PrimeGenerator(500000) do
begin
  if prime &gt;= 2000000 then
    break;
  sum := sum + prime;
end;</pre>
<p>I choose to generate 500000 primes, pretty sure one prime out of four should be enough.</p>
<p>And that&#8217;s it – it’s all there at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-10/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 9</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-9/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-9/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 21:45:13 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=134</guid>
		<description><![CDATA[On our way to Lofoten last weekend, my wife and I had a small brainstorming on problem no. 9:
A Pythagorean triplet is a set of three natural numbers, a &#60; b &#60; c, for which, 
a2 + b2 = c2 
For example, 32 + 42 = 9 + 16 = 25 = 52. 
There exists [...]]]></description>
			<content:encoded><![CDATA[<p>On our way to Lofoten last weekend, my wife and I had a small brainstorming on problem no. 9:</p>
<blockquote><p>A Pythagorean triplet is a set of three natural numbers, a &lt; b &lt; c, for which, </p>
<p><em>a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup></em> </p>
<p>For example, 3<sup>2</sup> + 4<sup>2</sup> = 9 + 16 = 25 = 5<sup>2</sup>. </p>
<p>There exists exactly one Pythagorean triplet for which a + b + c = 1000.      <br />Find the product <em>abc</em>.</p>
</blockquote>
<p> <span id="more-134"></span>
<p>Both of us agreed there had to be some kind of mathematical formula for this kind of problem. The problem, though, was that non of us new this formula, and there wasn’t that many math books in the car that day… So instead of trying to guess the magic formula, we tried to optimize the search for the right numbers.</p>
<p>We could put three for loops inside each other, scanning the numbers from 1 to 1000 for each. Trying 1 + 1 + 1 as a possible solution isn’t that clever, though. Neither is the combination 1000 + 1000 + 1000.</p>
<p>Let’s take a look at the maximum possible values for <em>a</em>, <em>b</em> and <em>c</em>. The fact that <em>a</em> &lt; <em>b</em> &lt; <em>c</em> makes this kind of easy.&#160; Since all three numbers must be positive, <em>c</em> can’t be larger than 997 to make room for <em>a</em> = 1 and <em>b</em> = 2. The number <em>b</em> can’t be larger than 499, which makes room for a = 1 and c = 500. And finally, <em>a</em> can’t be larger than 332, which makes room for <em>b</em> = 333 and <em>c</em> = 335. </p>
<pre class="brush: delphi;">    for a := 1 to 332 do
      for b := a+1 to 498 do
        for c := b+1 to 998 do
        begin
          ...
        end;</pre>
<p>Now, the test it self should be easy:</p>
<pre class="brush: delphi;">if (a + b + c = 1000) and (a*a + b*b = c*c) then
  ...</pre>
<p>We can do one more easy optimization. I our current <em>c</em> makes for a larger sum than 1000, we can break out of the innermost loop. This actually saves us a lot of cycles.</p>
<pre class="brush: delphi;">        for c := b+1 to 998 do
        begin
          sum := a + b + c;
          if (sum) &gt; 1000 then
            break;

          if (sum = 1000) and (a*a + b*b = c*c) then
          begin
            ...
          end;
        end;</pre>
<p>And that’s it. The complete solution is available as usual. Check it out at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-9/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 8</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-8/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-8/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 21:17:25 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/project-euler-problem-8/</guid>
		<description><![CDATA[A couple of days ago, I solved eulers problem no. 8. I finally found some time to blog about my solution. 
Find the greatest product of five consecutive digits in the 1000-digit number. 
73167176531330624919225119674426574742355349194934      96983520312774506326239578318016984801869478851843       85861560789112949495459501737958331952853208805511       12540698747158523863050715693290963295227443043557  [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago, I solved eulers problem no. 8. I finally found some time to blog about my solution. </p>
<blockquote><p>Find the greatest product of five consecutive digits in the 1000-digit number. </p>
<p>73167176531330624919225119674426574742355349194934      <br />96983520312774506326239578318016984801869478851843       <br />85861560789112949495459501737958331952853208805511       <br />12540698747158523863050715693290963295227443043557       <br />66896648950445244523161731856403098711121722383113       <br />62229893423380308135336276614282806444486645238749       <br />30358907296290491560440772390713810515859307960866       <br />70172427121883998797908792274921901699720888093776       <br />65727333001053367881220235421809751254540594752243       <br />52584907711670556013604839586446706324415722155397       <br />53697817977846174064955149290862569321978468622482       <br />83972241375657056057490261407972968652414535100474       <br />82166370484403199890008895243450658541227588666881       <br />16427171479924442928230863465674813919123162824586       <br />17866458359124566529476545682848912883142607690042       <br />24219022671055626321111109370544217506941658960408       <br />07198403850962455444362981230987879927244284909188       <br />84580156166097919133875499200524063689912560717606       <br />05886116467109405077541002256983155200055935729725       <br />71636269561882670428252483600823257530420752963450</p>
</blockquote>
<p> <span id="more-132"></span>
<p>I can’t see any smart solution for this problem. A simple brute force scan through the series of digits will have to do. </p>
<p>I start out with the number as a string. That makes it easy to loop through digit by digit.&#160; To make it even easier, I have made an array of five bytes that I place ‘over’ the current character. This gives me a ‘view’ of the five current digits that needs to be multiplied as bytes instead of characters. </p>
<pre class="brush: delphi;">const
  SUBJECT = '73167176531330624919225119674426574742355349 .... 57530420752963450';

type
  PFiveDigits = ^TFiveDigits;
  TFiveDigits = array[0..4] of byte;

begin
  for I := 1 to length(Subject) - 6 do
  begin
    FiveDigits := @SUBJECT[i];
  end;
end;</pre>
<p>A character in the range 0 to 9 has byte value in the range of 48 to 57. Before we multiply the values, we have to normalize them. We can do that by subtracting 48 from each byte value.</p>
<pre class="brush: delphi;">const
  NULLCHAR = ord('0');
  ...
  present := (FiveDigits[0]-NULLCHAR) * (FiveDigits[1]-NULLCHAR) * (FiveDigits[2]-NULLCHAR) * (FiveDigits[3]-NULLCHAR) * (FiveDigits[4]-NULLCHAR);</pre>
<p>Now we just have to keep track of the highest produced product do find the answer.</p>
<pre class="brush: delphi;">    largest := 0;
    for I := 1 to length(Subject) - 6 do
    begin
      FiveDigits := @SUBJECT[i];
      present := (FiveDigits[0]-NULLCHAR) * (FiveDigits[1]-NULLCHAR) * (FiveDigits[2]-NULLCHAR) * (FiveDigits[3]-NULLCHAR) * (FiveDigits[4]-NULLCHAR);
      if present &gt; largest then
      begin
        largest := present;
        position := i;
      end;
    end;</pre>
<p>As usual, you will find the code at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-8/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 7</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-7/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-7/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 09:37:26 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/project-euler-problem-7/</guid>
		<description><![CDATA[It want be easy to keep up with my brother on this. Well, here’s my take on Project Eulers problem no 7:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. 
What is the 10001st prime number?

 
Algorithms conserning primes is a [...]]]></description>
			<content:encoded><![CDATA[<p>It want be easy to keep up with <a href="http://www.geekality.net/2009/09/24/project-euler-problem-7/">my brother</a> on this. Well, here’s my take on Project Eulers problem no 7:</p>
<blockquote><p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6<sup>th</sup> prime is 13. </p>
<p>What is the 10001<sup>st</sup> prime number?</p>
</blockquote>
<p> <span id="more-108"></span>
<p>Algorithms conserning primes is a large and complex field. I guess the are many different solutions to this problem, so the question will be how efficient the one that I find will be.</p>
<p>One thing is for sure, though. We need a way of finding primes. As far as I know, there is no formula to find the n<sup>th</sup> prime. We have to find the first 10 000 primes first before we can find our wanted one. </p>
<h2>A Prime Generator</h2>
<p>I will use a <a href="http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-6-generators.html">enumerator-pattern</a> for our prime generator. For that, we will need two classes. First we will need a factory-class that implements the GetEnumerator function. Then we will need the class that handles the actual enumeration.</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">type
  TPrimeGenerator = class
  public
    function GetCurrent: extended;
    function MoveNext: boolean;
    property Current: extended read GetCurrent;
  end;

  TPrimeGeneratorFactory = class
  public
    function GetEnumerator: TPrimeGenerator;
  end;</pre>
<p>With this implementation, we will be allowed to write code like this:</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">for prime in TPrimeGeneratorFactory.Create do
begin
  ...
end;</pre>
<p>This code would generate an awful lot of primes, though. It would be nice to give it some kind limit. We can add that to the constructor, and check in the MoveNext method if the limit is reached. We would also need some live-time management on both the factory and the generator. The generator it self can be created and destroyed by the factory, but we can also make it easier by letting the factory implement an interface. If we do, delphi will manage it’s lifetime for us. </p>
<pre class="brush: delphi; gutter: false; toolbar: false;">type
  TPrimeGenerator = class
  public
    constructor Create(numberOfPrimes: integer);
    ...
  end;

  IPrimeGeneratorFactory = interface
    function GetEnumerator: TPrimeGenerator;
  end;

  TPrimeGeneratorFactory = class(TInterfacedObject, IPrimeGeneratorFactory)
  public
    constructor Create(numberOfPrimes: integer);
    destructor Destroy; override;
  end;

  function PrimeGenerator(numberOfPrimes: integer): IPrimeGeneratorFactory;</pre>
<p>Now, we can rewrite our for … in – loop, and just get the number of primes that we want. We will know longer have any leaks either.</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">for prime in PrimeGenerator(10001) do
begin
  ...
end;</pre>
<h2>Finding Primes</h2>
<p>Our generator doesn’t actually generate primes yet, though. Let’s see if we can make it do so. So how do we find primes? What is a prime? Wikipedia gives us the following definition of <a href="http://en.wikipedia.org/wiki/Prime_number">prime numbers</a>:</p>
<blockquote>
<p>In mathematics, a prime number (or a prime) is a natural number which has exactly two distinct natural number divisors: 1 and itself. </p>
</blockquote>
<p>So if we loop through all numbers, and test if it’s possible to devide it by any other number, we should have our primes. The problem is, though, that this takes time. A lot of time. We have to find a way of shortening down the ammount of numbers we need to check. The first thing we should remove, is all even numbers. Every single even number is divisible by the number 2, so they can’t be primes. Except for the number 2 it self – it’s a prime, cause has only two divisors: 1 and itself.</p>
<p>Since 2 is the first prime number, it would be an easy exception to handle, and we have effectively cut shortened down possible primes to the half of what we started with.</p>
<p>Let’s write our FindNextPrime method:</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">function TPrimeGenerator.FindNextPrime(PreviousPrimeFound: extended): extended;
var
  found: boolean;
  currentNumber: extended;
begin
  currentNumber := PreviousPrimeFound;
  repeat
    if (CurrentNumber = 1) or (currentNumber = 2) then
    begin
      currentNumber := currentNumber + 1;
      result := true;
    end
    else
    begin
      currentNumber := currentNumber + 2;
      found := CheckIfPrime(currentNumber);
    end;
  until found;

  result := currentNumber;
end;</pre>
<p>We here assume that PreviousPrimeFound equals 1 when no previous prime is found. So if the previous prime is 1 or 2, we just increment by one, knowing that both 2 and 3 is prime numbers, and signal a successfull found. If previous prime was not 1 or 2, it has to be 3 or any other odd number, so we increment by two to skip even numbers. </p>
<p>Let’s take a look at the CheckIfPrime( ) method. How do we check if a number is divisible by any other number? I guess we have to check:</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">function TPrimeGenerator.CheckIfPrime(number: integer): boolean;
var
  i: integer;
begin
  result := true;
  for i := 2 to number - 1 do
  begin
    if number mod i = 0 then
    begin
      result := false;
      break;
    end;
  end;
end;</pre>
<p>Can you see a bottleneck here? For every number we test, there is one more number to devide. How can we optimize this?</p>
<p>First of all, every natural number can be expressed as a product of primes. 12 = 2 x 2 x 3, 20 = 2 x 2 x 5 and so on. So if a number is divisible by a non prime number, it should also be divisible by a prime number. So if we can find a way of just dividing by primes we would speed up things a lot.</p>
<p>So let’s add a list of previous found primes to the generator class, and loop through that list instead of all numbers.</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">function TPrimeGenerator.CheckIfPrime(number: extended): boolean;
var
  itr: DIterator;
  prevPrime: extended;
  found: boolean;
begin
  found := false;
  itr := FPrimes.start;
  while IterateOver(itr) do
  begin
    prevPrime := getExtended(itr);

    if Frac(number / prevPrime) = 0 then
    begin
      found := true;
      break;
    end;
  end;

  result := not found;
end;</pre>
<p>This makes things a lot faster, but I think we still can gain something. In the same wikipedia article that I refered to earlier, it is sufficient to test primes smaller than the sqaure root of the number we are currently testing. So let’s add that to our loop:</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">function TPrimeGenerator.CheckIfPrime(number: extended): boolean;
var
  itr: DIterator;
  prevPrime: extended;
  found: boolean;
  root: extended;
begin
  root := sqrt(number);
  ...
  while IterateOver(itr) do
  begin
    prevPrime := getExtended(itr);
    if prevPRime &gt; root then
      break;

    if ...
  end;
  ...
end;</pre>
<h2>The Solution</h2>
<p>Just like the solution for problem 6, you can find the complete code at <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>. It gives the answer in about 40-50 ms.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 6</title>
		<link>http://blog.vi-kan.net/2009/project-euler-problem-6/</link>
		<comments>http://blog.vi-kan.net/2009/project-euler-problem-6/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 20:40:10 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=97</guid>
		<description><![CDATA[Inspired by my brother over at geekality.net, I thought I should do an attempt on the various problems presented at projecteuler.net/.  Since he already solved the first five, I jumped right in at problem 6:

The sum of the squares of the first ten natural numbers is,
12 + 22 + &#8230; + 102 = 385
The square [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by my brother over at <a href="http://www.geekality.net/" target="_blank">geekality.net</a>, I thought I should do an attempt on the various problems presented at <a title="http://projecteuler.net/" href="http://projecteuler.net/">projecteuler.net/</a>.  Since he already solved the first five, I jumped right in at <a href="http://projecteuler.net/index.php?section=problems&amp;id=6" target="_blank">problem 6</a>:</p>
<blockquote>
<p align="left">The sum of the squares of the first ten natural numbers is,</p>
<p align="center">1<sup>2</sup> + 2<sup>2</sup> + &#8230; + 10<sup>2</sup> = 385</p>
<p align="left">The square of the sum of the first ten natural numbers is,</p>
<p align="center">(1 + 2 + &#8230; + 10)<sup>2</sup> = 552 = 3025</p>
<p align="left">Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is</p>
<p align="center">3025  385 = 2640.</p>
<p>Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.</p></blockquote>
<p><span id="more-97"></span></p>
<p>This problem has two distinct parts. First, there is the sum of a sequence of the squared natural numbers, then there is the sum of a sequence of natural numbers, squared.</p>
<h2>Sum of a series of squared natural numbers</h2>
<p>The problem tells to summarize the square of the first hundred natural numbers. That gives us the following sequence:</p>
<p align="center">1<sup>2</sup> + 2<sup>2</sup> + &#8230; 99<sup>2</sup> + 100<sup>2</sup></p>
<p align="left">The simplest solution would be a brute force loop like this one:</p>
<pre class="brush: delphi;">function sumSquaredNumbers( ): longword;
var
  i: integer;
begin
  result := 0;
  for i := 1 to 100 do
    result := result + (power(i, 2));
end;</pre>
<p>That wouldn’t be much fun, though. There has to be a more general, optimized algorithm for this kind of work. First of all, we should make the function workable for any series length. That should be easy – just switch the hardcoded 100 with an given parameter:</p>
<pre class="brush: delphi;">function sumSquaredNumbers(serieslength: integer): longword;
var   i: integer;
begin
  for i := 1 to seriesLength do
    result := …
end;</pre>
<p>But the code is still the same, though. Nothing was optimized in any way. We still have the loop, making our function <a href="http://en.wikipedia.org/wiki/Linear_time" target="_blank">linear</a>.</p>
<p>Google to the rescue!</p>
<p><a href="http://www.math.com">math.com</a> have a nice section on Series Expansions, which includes a table of <a href="http://www.math.com/tables/expansion/power.htm" target="_blank">power summations</a>. This table states that</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td colspan="4" valign="top">n</td>
</tr>
<tr>
<td valign="vcenter"><span>∑</span></td>
<td valign="top">k<sup>2</sup></td>
<td valign="vcenter">= 1 + 4 + 9 + &#8230; + n<sup>2</sup></td>
<td valign="vcenter">= (1/3)n<sup>3</sup> + (1/2)n<sup>2</sup> + (1/6)n</td>
</tr>
<tr>
<td colspan="4" valign="top">k=1</td>
</tr>
</tbody>
</table>
</blockquote>
<p>Why this should be true, I honestly can’t tell, but a fast comparison to our brute force solution shows that it gives us the right numbers. That’s good enough for now:</p>
<pre class="brush: delphi;">function sumSquaredNumbers(seriesLength: integer): longword;
begin
  result := trunc(
                ((1/3) * power(seriesLength, 3))
              + ((1/2) * power(seriesLength, 2))
              + ((1/6) * seriesLength)
              );
end;</pre>
<p>I think this is a nice solution, and a <a href="http://en.wikipedia.org/wiki/Constant_time">constant one</a> as well. It doesn’t matter if the series is of length one, hundred or thousand – the computation should take the same amount of time.</p>
<h2>Sum of a series of natural numbers, squared</h2>
<p>This part should be a lot easier. We could start with a brute force solution to this part too, but I think we could come up with something smarter right away.</p>
<p>I already know of a simple optimization. If you add the first and last number in the series, you will get the same as if you add the second and next to last number:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="145" align="center">
<tbody>
<tr>
<td width="13" valign="top"></td>
<td width="20" valign="top">1</td>
<td width="20" valign="top">2</td>
<td width="20" valign="top">3</td>
<td width="20" valign="top">4</td>
<td width="20" valign="top">5</td>
<td width="6" valign="top">6</td>
<td width="6" valign="top">7</td>
<td width="6" valign="top">8</td>
<td width="6" valign="top">9</td>
<td width="6" valign="top">10</td>
</tr>
<tr>
<td width="13" valign="top">+</td>
<td width="20" valign="top">10</td>
<td width="20" valign="top">9</td>
<td width="20" valign="top">8</td>
<td width="20" valign="top">7</td>
<td width="20" valign="top">6</td>
<td width="6" valign="top">5</td>
<td width="6" valign="top">4</td>
<td width="6" valign="top">3</td>
<td width="6" valign="top">2</td>
<td width="6" valign="top">1</td>
</tr>
<tr>
<td width="13" valign="top">=</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="20" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
<td width="6" valign="top">11</td>
</tr>
</tbody>
</table>
</blockquote>
<p>As you can see, every pair of numbers makes the same sum when added together. So for any given series, you can take the first and the last number and add them together, then you can multiply the sum by the length of the series, and finally divide by two.</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td colspan="4" valign="top">n</td>
</tr>
<tr>
<td valign="vcenter"><span>∑</span></td>
<td valign="top">k</td>
<td valign="vcenter">= 1 + 2 + 3 + &#8230; + n</td>
<td valign="vcenter">= (1 + n) * n / 2</td>
</tr>
<tr>
<td colspan="4" valign="top">k=1</td>
</tr>
</tbody>
</table>
</blockquote>
<p>I know there are other solutions to this, but this one will do.</p>
<pre class="brush: delphi;">function sumSquared(seriesLength: longword): longword;
begin
  result := trunc(power(((1 + seriesLength) * seriesLength / 2), 2));
end;</pre>
<h2>The solution</h2>
<p>Now that we have solved each of the two sub parts of the problem, I guess we’re ready to solve the main thing.</p>
<blockquote><p>Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.</p></blockquote>
<p>Since we know the sum of the squares, and we now the square of the sum, it’s just a matter of substract the one from the other:</p>
<pre class="brush: delphi;">function diff(serieslength: longword): longword;
begin
  result := sumSquared(serieslength) - sumSquaredNumbers(serieslength);
end;</pre>
<p>I have uploaded my complete solution to <a href="http://svn.vi-kan.net/euler">http://svn.vi-kan.net/euler</a>. The code also contains a simple stopwatch to time the code. This code is so simple, though, that it’s hard to get any measures.</p>
<p>And that’s it. Let’s see if we can solve the next one too.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/project-euler-problem-6/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Running FitNesse tests from the command line</title>
		<link>http://blog.vi-kan.net/2009/running-fitnesse-tests-from-the-command-line/</link>
		<comments>http://blog.vi-kan.net/2009/running-fitnesse-tests-from-the-command-line/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 22:52:00 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Fit4Delphi]]></category>
		<category><![CDATA[FitNesse]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/2009/running-fitnesse-tests-from-the-command-line/</guid>
		<description><![CDATA[ Using FitNesse to write and run test is nice, but sometimes you want to run the tests as part of an automatic build cycle. FitNesse has this possibility, and fit4delphi comes with a testrunner that makes it possible with delphi code as well.

In the fit4delphi package, inside the testrunner folder, you will find a [...]]]></description>
			<content:encoded><![CDATA[<p><img style="border-right-width: 0px; margin: 0px 0px 0px 10px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://blog.vi-kan.net/wp-content/uploads/2009/09/image.png" border="0" alt="image" width="240" height="136" align="right" /> Using FitNesse to write and run test is nice, but sometimes you want to run the tests as part of an automatic build cycle. FitNesse has this possibility, and fit4delphi comes with a testrunner that makes it possible with delphi code as well.</p>
<p><span id="more-96"></span></p>
<p>In the fit4delphi package, inside the testrunner folder, you will find a project named DelphiTestRunner.dproj. You can use this project to automatically run a test, or a suite of tests, and store the result as a file. To do his, you have to tell the testrunner where the FitNesse server is running, and which file and in what format the result should be store in. This is done with command line parameters in the given form:</p>
<blockquote><p>DelphiTestRunner.exe [options] host port page</p></blockquote>
<p>Host and port must be the same as specified when starting FitNesse. The page parameter is the url for the wiki page you want to test. All subpages of this page will also be tested.</p>
<p>There are multiple options you can specify.</p>
<ul>
<li>-debug<br />
This option will print FitNesse protocol actions to the console.</li>
<li>-v<br />
This option should give a verbose output about test progress to the console, but personally, I can’t make it work…</li>
<li>-results file<br />
The result of the testrun is saved to a textfile with the given name.</li>
<li>-html file<br />
The result of the testrun is saved to a html file with the given name.</li>
<li>-xml file<br />
The result of the testrun is saved to a xml file with the given name. The xml format is given <a title="FitNesse.UserGuide.RestfulTests" href="http://fitnesse.org/FitNesse.UserGuide.RestfulTests" target="_blank">in the userguide</a>.</li>
<li>-nopath<br />
This option will make FitNesse ignore !path options specified in the wiki pages.</li>
<li>-suiteFilter filter<br />
Specifying a filter will only run pages with tags matching the filter. You can read more about this <a title="FitNesse.UserGuide.TestSuites.TagsAndFilters" href="http://fitnesse.org/FitNesse.UserGuide.TestSuites.TagsAndFilters" target="_blank">in the userguide</a>.</li>
</ul>
<p>An example of a command line could be some thing like this:</p>
<blockquote><p>DelphiTestRunner.exe –html results.html localhost 80 MyTestSuite</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/running-fitnesse-tests-from-the-command-line/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FitNesse + Delphi –&gt; Fit4Delphi</title>
		<link>http://blog.vi-kan.net/2009/fitnesse-delphi-fit4delphi/</link>
		<comments>http://blog.vi-kan.net/2009/fitnesse-delphi-fit4delphi/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 13:59:28 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Fit4Delphi]]></category>
		<category><![CDATA[FitNesse]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=76</guid>
		<description><![CDATA[I have been thinking about FitNesse for a couple of weeks now. It seems to be near to perfect for testing the type of code that I&#8217;m currently writing. A lot of calculations with a lot of rules, odd cases and exceptions. So I finally started to check it out, to see if it is [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-85" title="FitNesseLogo" src="http://blog.vi-kan.net/wp-content/uploads/2009/08/FitNesseLogo.gif" alt="FitNesseLogo" width="90" height="90" />I have been thinking about <a href="http://fitnesse.org/">FitNesse</a> for a couple of weeks now. It seems to be near to perfect for testing the type of code that I&#8217;m currently writing. A lot of calculations with a lot of rules, odd cases and exceptions. So I finally started to check it out, to see if it is possible to use FitNesse to test code written in delphi.<span id="more-76"></span> After some googling, I found a lot of references to the fact that it is possible, but not much on how. There ain’t much references to people actually using it either.  I found two projects, though, <a href="http://code.google.com/p/fit4delphi/">Fit4Delphi</a> and <a href="http://fitnesse.org/FrontPage.FitServers.DelphiFit">DelphiFIT</a>. It looks like DelphiFIT has been merged with the Fit4Delphi project, so there is only one solution left for FitNesse with Delphi. If it is any good, one is all you need, though.  At first, it’s a bit unclear what components are playing together in FitNesse. There are two main parts of the system, with two different roles. The first part is the one doing the actual testing bit. The second is a development environment in the form of a wiki, made for writing, invoking and maintaining tests.</p>
<h2>Get it running</h2>
<p>So let see if we can make this work. Fit4Delphi comes with a older version of FitNesse. You can choose to use this version, or you can get a newer version from <a href="http://fitnesse.org">fitnesse.org</a>. I like new shiny things, so I downloaded a brand new fitnesse.jar. Assuming that java already exists on your computer, fitnesse.jar is all you need to get going. Put it in a folder somewhere, e.g. c:\fitnesse\, and run</p>
<pre class="brush: plain; gutter: false; toolbar: false;">c:\fitnesse\java -jar fitnesse.jar</pre>
<p>Fitnesse will now unpack it self before it starts. If you later want to upgrade to a newer version of FitNesse, you can download a new jar-file and new resources will be extracted next time you start FitNesse.  When FitNesse starts, it will tell you what version it is and what port it is running on. It will also tell you a couple of other things, but the port number is what we need right now. The port number defaults to 80, the standard http port. So fire up you webbrowser, and navigate to <a href="http://localhost:80">http://localhost:80</a>, and you will be presented with the default front page for FitNesse.  To the left, you have a tree-structure showing what pages exists in the wiki, and to the right you have the content for the current page. In the FitNesse branch of the tree, you can find the user guide for FitNesse amoung all the acceptance tests for FitNesse itself.  On the FrontPage, click the edit-button to the left. At the bottom of the page, write the name of your new testsuite, ‘DelphiTests’, or what ever. It need to be a <a href="http://fitnesse.org/FitNesse.UserGuide.WikiWord">‘WikiWord’</a>, though. When you save the document, you will see your inserted text together with a ‘[?]’. This means that the wiki sees your wikiword as a title for a page, but can’t find the page itself. When clicking on the questionmark, the wiki will create the page, and let you edit it.  So let’s start with a simple table. Fill out the new page with something like the following:</p>
<pre class="brush: plain; gutter: false; toolbar: false;">|test table|
|in value|out value?|
|1|2|</pre>
<p>After saving, you will see your table nicely formatted. Is there a Test button to the left? If not, click the Properties-button, and choose Test as page type. Now, click the Test-button…  Nothing happends, right?  FitNesse finds the table and want it to be tested, but can’t find anyone willing to work. It needs to know who to call for the job. It is done by defining the <a href="http://fitnesse.org/FitNesse.UserGuide.CustomizingTestExecution">‘COMMAND_PATERN’</a> variable. When testing delphi code, we will need  DelphiFitServer.exe to do the work for us, so we give FitNesse the path to this executable. I have copied both DelphiFitServer.exe and fit.bpl to a ‘bin’-folder in my FitNesse-folder. You will find the source in \fit4delphi\fitserver\ and \fit4delphi\fit\.</p>
<pre class="brush: plain; gutter: false; toolbar: false;">!define COMMAND_PATTERN {bin\DelphiFitServer.exe -v %p}</pre>
<p>The –v parameters tell DelphiFitServer to print out messages, and the %p parameter represents the <a href="http://fitnesse.org/FitNesse.UserGuide.MarkupPath">path</a> where DelphiFitServer should look for fixtures. FitNesse builds this path from classpath-settings in the wiki. Let’s include one in our page:</p>
<pre class="brush: plain; gutter: false; toolbar: false;">!path bin\*.bpl</pre>
<p>Let’s hit that Test button again and see if there is any progress.  This time we get a lot of yellow on our page. While red tells us that a test did not pass, yellow tells us that something went wrong when trying execute the test. As you can see, DelphiFitServer couldn’t find fixture for our table. If you click the ‘Output Captured’ sign in the right corner, you will get some details on the execution. You can see what exe-file was used, and what bpl-files was loaded. We now need to add some testcode on our own.</p>
<h2>Writing our first fixture</h2>
<p>From the yellow text, we found that we need a class named ‘TestTable’. Acctually, FitNesse is quite flexible when it comes to naming. You can read more about it <a title="Graceful Naming" href="http://fitnesse.org/FitNesse.UserGuide.GracefulName">the documentation</a>, but I will disclose that a class named ‘TTestTable’ should be accepted.  So lets create a new delphi package. Add a reference to fit.bpl and the source path for fit4delphi\fit\source, fit4delphi\fit\source\exception and fit4delphi\RegExpr. Create a new unit, and define a new class deriving from TColumnFixture. You will need the file ColumnFixture in your uses section for this to compile. You will also need to enable detailed rtti for your class, and register it with a call to RegisterClass:</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">unit fitTestTable;

interface

uses
  ColumnFixture;

type
  {$M+}
  {$METHODINFO ON}
  TTestTable = class(TColumnFixture)
  published
  end;

implementation

uses
  Classes;

{ TTestTable }

initialization
  RegisterClass(TTestTable)

end.</pre>
<p>Build the new package, and move it to the bin folder of your FitNesse installation. Run the test again, and you will find that there is now three exceptions instead of one. Progress!  This time, it chokes on the column titles. Could not find field: in value. Well, lets add it, then. A published property named InValue of type double should do.  Compile… Copy… Test…  One down, two to go.  Of course it choked on the next column also. This time we need to add a function named OutValue returning a double.  Let’s fake the implementation for now, and just return 0.</p>
<pre class="brush: delphi; gutter: false; toolbar: false;">   TTestTable = class(TColumnFixture)
  private
    FInnValue: double;
  published
    property InnValue: double read FInnValue write FInnValue;
    function OutValue: double;
  end;</pre>
<p>Now, that got rid of both the remaining exceptions, but leaves us with some ugly red spots. This is actually good though: Our test runs with out problems, but fails. I will leave it up to you to make the test pass. It shouldn’t be to hard, and the reward of green colour should be enough to make you wanna write some real tests.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/fitnesse-delphi-fit4delphi/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DUnit: Loading tests from dll’s</title>
		<link>http://blog.vi-kan.net/2009/dunit-loading-tests-from-dlls/</link>
		<comments>http://blog.vi-kan.net/2009/dunit-loading-tests-from-dlls/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 14:21:33 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[DUnit]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=71</guid>
		<description><![CDATA[I wanted to split all my unittests for a project into separate packages to keep tings nice and clean. DUnit comes with a unit called TestModules.pas which helps you do that.
The unit contains three public methods:
function LoadModuleTests(LibName: string) :ITest;
procedure RegisterModuleTests(LibName: string);
procedure UnloadTestModules;
The LoadModuleTests( )-function, dynamically loads the given library (dll or dtl files), and returns [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to split all my unittests for a project into separate packages to keep tings nice and clean. <a title="DUnit: An Xtreme testframework for Delphi programs" href="http://dunit.sourceforge.net/">DUnit</a> comes with a unit called <a title="View testmodules.pas from sourceforge.net" href="http://dunit.svn.sourceforge.net/viewvc/dunit/trunk/src/TestModules.pas?revision=15&amp;view=markup">TestModules.pas</a> which helps you do that.<span id="more-71"></span></p>
<p>The unit contains three public methods:</p>
<pre class="brush: delphi; gutter: false;">function LoadModuleTests(LibName: string) :ITest;
procedure RegisterModuleTests(LibName: string);
procedure UnloadTestModules;</pre>
<p>The LoadModuleTests( )-function, dynamically loads the given library (dll or dtl files), and returns an interface to the tests defined within. RegisterModuleTests( ) does the same, but also calls RegisterTest( ) with the interface from the library.</p>
<p>There is one requirement that the library has to satisfy. It must export a function named ‘Test’ that returns a ITest-interface. Following is a basic project file showing how this can be done:</p>
<pre class="brush: delphi; gutter: false;">library OurUnitTests;

uses
  TestFramework;

function Test: ITest;
begin
  result := RegisteredTests;
end;

exports
  Test name 'Test';

end;</pre>
<p>The Test( )-function simply returns the result from the RegisteredTests( ) method from the TestFramework-unit. RegisteredTests( ) returns a ITestSuite containing all the test classes registered.</p>
<p>Here&#8217;s a samle project file that loads all dll-files from the executables folder, and runs all test through the GUITestRunner:</p>
<pre class="brush: delphi; gutter: false;">program RunTests;
uses
  Forms,
  TestFramework,
  GUITestRunner,
  TestModules,
  SysUtils,
  Windows,
  JclFileUtils,
  classes,
  Dialogs
  ;

  {$R *.RES}

procedure LoadTests;
var
  filelist: TStringList;
  str: string;
begin
  filelist := TStringList.Create;
  try
    BuildFileList('*.dll', faAnyFile, filelist);

    for str in filelist do
    begin
      try
        RegisterModuleTests(str)
      except
        on E: Exception do
          ShowMessage(e.Message);
      end;
    end;
  finally
    filelist.free;
  end;
end;

begin
  Application.Initialize;

  LoadTests;
  GUITestRunner.RunRegisteredTests;
  UnloadTestModules;
end.</pre>
<p>The BuildFileList( ) method comes from JCL, and simply fills a TStringList with filenames from the given mask. As I said, this is a very basic project, but it shows how to use the TestModules-unit to dynamically load tests. This can easily be expanded to a more flexible solution. You could use command parameters to control what folder should be searched for libraries, or what testrunner should be used, GUI or XML or custom runner.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2009/dunit-loading-tests-from-dlls/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->