<?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 &#187; Development</title>
	<atom:link href="http://blog.vi-kan.net/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.vi-kan.net</link>
	<description>{ TODO -oVegar : insert clever text here}</description>
	<lastBuildDate>Mon, 28 Nov 2011 17:05:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Dagens fotnoter&#8230; #8</title>
		<link>http://blog.vi-kan.net/2011/dagens-fotnoter-8/</link>
		<comments>http://blog.vi-kan.net/2011/dagens-fotnoter-8/#comments</comments>
		<pubDate>Tue, 03 May 2011 10:52:36 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=365</guid>
		<description><![CDATA[Micro-ORM Mye prat om micro-orms for tiden. Denne podcasten gir ett lite innblikk i hva det dreier seg om. http://www.hanselminutes.com/default.aspx?showID=282 DevDays 2011, Netherlands Opptak fra DevDays 2011 er lagt ut på channel 9. http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands Bart De Smet hadde en interessant session om 10 c# language features. http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands/Devdays041 Breakpoints on Xaml in Silverlight 5 Montro om [...]]]></description>
			<content:encoded><![CDATA[<h3>Micro-ORM</h3>
<p style="padding-left: 30px;">Mye prat om micro-orms for tiden. Denne podcasten gir ett lite innblikk i hva det dreier seg om.<br />
<a href="http://www.hanselminutes.com/default.aspx?showID=282">http://www.hanselminutes.com/default.aspx?showID=282</a></p>
<h3>DevDays 2011, Netherlands</h3>
<p style="padding-left: 30px;">Opptak fra DevDays 2011 er lagt ut på channel 9.<br />
<a href="http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands">http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands</a></p>
<p style="padding-left: 30px;"><a href="http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands"></a>Bart De Smet hadde en interessant session om 10 c# language features.<em><br />
</em><a href="http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands/Devdays041">http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands/Devdays041</a></p>
<h3>Breakpoints on Xaml in Silverlight 5</h3>
<p style="padding-left: 30px;">Montro om dette også blir mulig i WPF? Ville vært høyst velkomment.<br />
<a href="http://www.wpftutorial.net/Templates.html">http://jesseliberty.com/2011/04/26/breakpoints-on-xaml-in-silverlight-5/</a></p>
<h3>MineCraft</h3>
<p style="padding-left: 30px;">Dette fenomenet må en visst bare vende seg til.<br />
<a href="http://www.minecraft.net/">http://www.minecraft.net/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2011/dagens-fotnoter-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 18 &amp; 67</title>
		<link>http://blog.vi-kan.net/2010/project-euler-problem-18-67/</link>
		<comments>http://blog.vi-kan.net/2010/project-euler-problem-18-67/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 21:49:50 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=294</guid>
		<description><![CDATA[I have been struggling with a couple of Euler Problems the past days. Not so much finding the solution as finding a couple of bugs in my code&#8230; By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. [...]]]></description>
			<content:encoded><![CDATA[<p>I have been struggling with a couple of Euler Problems the past days. Not so much finding the solution as finding a couple of bugs in my code&#8230;</p>
<p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<p style="text-align: center;"><strong>3</strong><br />
<strong>7</strong> 4<br />
2 <strong>4</strong> 6<br />
8 5 <strong>9</strong> 3</p>
<p>Find the maximum total from top to bottom of the given triangle.<span id="more-294"></span>The 18th problem involves finding the optimal route from top to bottom in a pyramid  of 15 rows. It is possible to solve this using a brute force algorithm, testing every possible solution. Problem no. 67 is the exact same problem, but this time with a pyramid of 100 rows. The problem text includes a little warning, stating that a brute force approach would take a couple of billion years to complete&#8230;</p>
<p>I remember back when I was a kid, I used to solve labyrinths like &#8216;help the little mouse find its cheese&#8217;, I always started with the cheese. It was always easier to find the way back to the mouse. I would guess that the same would go for this one. If we can solve the problem from the bottom instead of the top, it should be easier to choose the right path.</p>
<div style="float: right; margin: 10px; text-align: center;">6<br />
1 7<br />
9 2 3<br />
8 5 9 3</div>
<p>So, lets start at the bottom of the four-row pyramid. We have four numbers: 8 5 9 and 3. Even though 9 is the larger one, we have no idea if 9 is where we want to end up, since the numbers leading to the first number, 8, could be higher. Imagine the third row to be 9 2 and 3. The only way down to the 8 would be through the 9 in the third row, and down to the 9 we could have come through the 2 or the 3. 8 + 9 = 17 looks like a much better total then 2 + 9 = 11 or 3 + 9 = 12. Moving up one more row, to the second row, lets imagine the numbers 1 and 7. If we went for the  8 + 9 combination, we would only have one choice up to the second row, making a total of 8 + 9 + 1 = 18. If we went for the 9 + 3 combination, the 7  would be our only choice, giving a total of 19. From the 2 in the third row, we could reach either one, but would not get a higher total any way, so lets just drop that option all together.</p>
<p>Now, what seemed like a great path, starting with 8 + 9, turned out to be beaten by another option higher in the pyramid. How could we predict that? We couldn&#8217;t. So what would make going from bottom to top a better solution then from the top to bottom? Well, we managed to throw away a couple of options. We never payed either the 5 or the 3 in the bottom row any attention. From the 5, we could have gone up through 9 or 2 in the third row, but if we have come to the 9, why should we go down to the 5 when we know that the 8 would give a better total? Same goes for the 2. Why go down to 5 for a total of 7 when we can go down to 9 for a total of 11? And that is the clue to solve this problem. We need to know what would give the greater total, left or right.</p>
<p>OK. So lets start at the bottom again, this time, with some of the numbers from the given pyramid in problem 18:</p>
<p style="text-align: center;"><span style="line-height: normal; -webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; font-size: small;"><img class="aligncenter" title="Last two rows" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_1.jpg" alt="" width="470" height="50" /></span></p>
<p>If we start with the 63, we could either go down to 04 or 62. Obviously, knowing this is the last row, we would go for 62 and a total of 125. From 66 we can go to 62 or 98. Once again, we would take the right path for a total of 164. From 04, we would pick 98, from 68, 27 or 89, 23 and so on.</p>
<p style="text-align: center;"><a href="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_21.jpg"><img class="alignnone size-full wp-image-309" title="Last two rows added together" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_21.jpg" alt="" width="180" height="75" /></a></p>
<p>Now we can easily know where we want to go next from the 14th row. Lets add the 13th row:</p>
<p><a href="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_3.jpg"><img class="aligncenter size-full wp-image-310" title="Three last rows" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_3.jpg" alt="" width="180" height="110" /></a></p>
<p>Since we already know the best path from each number in the 14th row down to the 15th, we can treat the trip from the 13th row down to the 14th in the same way. From the first number, 91, we know we can choose between 63 and 66. We know that if we choose 63, we can reach a maximum of 91 + 125 by going right from 63. If we choose 66, we know that we can reach a total of 91 + 128 by going left. From the second number, 71, we can go left through 66, or right through 04. By choosing right, we can reach a maximum of 71 + 102, so clearly left would be a better choice, which gives us 71 + 164.</p>
<p><a href="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_4.jpg"><img class="aligncenter size-full wp-image-311" title="Three last rows added together" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/problem18_4.jpg" alt="" width="180" height="110" /></a>Do you see the pattern? I think we are ready for some code! I started out with a NumberPiramid-class. It has a method for adding a row of numbers, and a method returning the calculated maximum total.</p>
<pre class="brush: objc; title: ;">
@interface NumberPiramid : NSObject {
  NSMutableArray *rows;
}

-(void)addRow:(NSString *)stringWithNumbers;
-(int)numberOfRows;
-(int)maximumTotal;

@end</pre>
<p>The method addRow:stringWithNumbers takes all numbers for one row as a string separated by spaces. The string is split into an array of Number, a class able to hold both the number itself, and the totals for the left and right side.</p>
<pre class="brush: objc; title: ;">
-(void)addRow:(NSString *)stringWithNumbers;
{
  NSArray *numbers = [stringWithNumbers componentsSeparatedByString:@&quot; &quot;];
  NSMutableArray *row = [[NSMutableArray alloc] initWithCapacity:[numbers count]];
  for (NSString *number in numbers) {
    Number *n = [[Number alloc] initWithNumber:number];
    [row addObject:n];
    [n release];
  }
  [rows addObject:row];
  [row release];
}</pre>
<p>So now, we have an array of arrays that we can use to find our total. The method maximumTotal will first traverse the arrays bottom up, adding the numbers one by one, always keeping the larger option. I have given the Number class a convenience method maxSum, that returns the larger number of leftSum and rightSum. When we have reached the top, we have our total.</p>
<pre class="brush: objc; title: ;">-(int)maximumTotal;
{
  NSArray *row = [rows lastObject];
  NSArray *prevRow;
  for (int r = [self numberOfRows] - 2; r &gt;= 0; r--) {
    prevRow = row;
    row = [rows objectAtIndex:r];
    for (int n = 0; n &lt; [row count]; n++) {
      Number *number = [row objectAtIndex:n]&gt;
      Number *left = [prevRow objectAtIndex:n];
      Number *right = [prevRow objectAtIndex:n + 1];
      number.leftSum = number.number + [left maxSum];
      number.rightSum = number.number + [right maxSum];
    }
  }
  Number *top = [row objectAtIndex:0];
  return [top maxSum];
}</pre>
<p>And thats all there is. Problem 67 is the exact same problem, but with a larger pyramid. The numbers are given in a textfile, so we need a new method that can read the textfile line by line. Actually, I found it easier to just read the whole file into a string, using NSString initWithContentsOfFile:filename. I then split this string into lines with the same method I use to split a single row.</p>
<p>As before, the code is available <a href="http://svn.vi-kan.net/euler">through svn</a>. There is a delphi implementation too.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/project-euler-problem-18-67/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SyntaxHighlighter and Objective-C</title>
		<link>http://blog.vi-kan.net/2010/syntaxhighlighter-and-objective-c/</link>
		<comments>http://blog.vi-kan.net/2010/syntaxhighlighter-and-objective-c/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 13:15:09 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=270</guid>
		<description><![CDATA[I have always used  Alex Gorbatchevs SyntaxHighlighter to make code listings look pretty on this blog. There are several wordpress plugins that include these scripts automatically. It has one shortcoming, though. It doesn&#8217;t include any syntax highlighter for objective-c. When searching the net for some tips on how to add this feature, I found yet another [...]]]></description>
			<content:encoded><![CDATA[<p>I have always used  <a href="http://alexgorbatchev.com/SyntaxHighlighter/">Alex Gorbatchevs SyntaxHighlighter</a> to make code listings look pretty on this blog. There are <a href="http://wordpress.org/extend/plugins/search.php?q=syntaxhighlighter">several wordpress plugins</a> that include these scripts automatically. It has one shortcoming, though. It doesn&#8217;t include any syntax highlighter for objective-c. When searching the net for some tips on how to add this feature, I found yet another wordpress plugin, <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a>, and this one included some additional languages, including objective-c. Great! Whats not so great, though, is that instead of using the pre-tag, it uses custom [/code]-tags. I guess there will be more difficult to switch between plugins in the feature...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/syntaxhighlighter-and-objective-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Project Euler, Problem 17</title>
		<link>http://blog.vi-kan.net/2010/project-euler-problem-17/</link>
		<comments>http://blog.vi-kan.net/2010/project-euler-problem-17/#comments</comments>
		<pubDate>Wed, 17 Nov 2010 22:01:37 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Euler]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=251</guid>
		<description><![CDATA[After my success on getting unittest to work on the iPhone, I thought I should try it out some more. It&#8217;s been a while since last time I solved an Euler Problem, so maybe this would be a good excuse to solve another one? The last problems involved a lot of math, so this time [...]]]></description>
			<content:encoded><![CDATA[<p>After my success on <a title="UnitTesting on the iPhone" href="http://blog.vi-kan.net/2010/unittesting-on-the-iphone/" target="_self">getting unittest to work</a> on the iPhone, I thought I should try it out some more. It&#8217;s been a while since last time I solved an Euler Problem, so maybe this would be a good excuse to solve another one? The last problems involved a lot of math, so this time I found something completely different:</p>
<blockquote><p>If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.<br />
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?</p></blockquote>
<p>Well, lets see, then&#8230;</p>
<p><span id="more-251"></span><br />
We would need a class that can convert an integer into written words. I will call it WrittenNumber, and give it a class method +(NSString *)fromInt:(int) to do the work.</p>
<pre class="brush: objc; title: ;">@interface WrittenNumber : NSObject {
}
+(NSString *) fromInt:(int)number;
@end</pre>
<p>Now, that I got my basic interface in place, I tried it out with the most basic test:</p>
<pre class="brush: objc; title: ;">- (void)testSingleDigitOne {
    GHAssertEqualStrings([WrittenNumber fromInt:1], @&quot;one&quot;, nil);
}</pre>
<p>As expected, it failed :</p>
<pre class="brush: plain; title: ;">euler17/testSingleDigitOne ✘ 0.00s

	Name: GHTestFailureException
	File: /../euler17.m
	Line: 40
	Reason: '' should be equal to 'one'.</pre>
<p>I will not take you through every single step I took, including returning &#8216;one&#8217;, writing a new test and realize that returning &#8216;one&#8217; didn&#8217;t work for other cases and so on&#8230; What we need, is to identify every word that we need to build up every number from one to 1000. Up to nineteen, there are all unique words. From there, most written numbers are combined by two or more words. So I put these words into a couple of static arrays:</p>
<pre class="brush: objc; title: ;">static NSString * simpleNumbers[] = {
    @&quot;&quot;, @&quot;one&quot;, @&quot;two&quot;, @&quot;three&quot;, @&quot;four&quot;, @&quot;five&quot;, @&quot;six&quot;, @&quot;seven&quot;, @&quot;eight&quot;, @&quot;nine&quot;,
    @&quot;ten&quot;, @&quot;eleven&quot;, @&quot;twelve&quot;, @&quot;thirteen&quot;, @&quot;fourteen&quot;, @&quot;fifteen&quot;, @&quot;sixteen&quot;, @&quot;seventeen&quot;, @&quot;eighteen&quot;, @&quot;nineteen&quot;
}; 

static NSString *tens[] = {
    @&quot;&quot;, @&quot;&quot;, @&quot;twenty&quot;, @&quot;thirty&quot;, @&quot;forty&quot;, @&quot;fifty&quot;, @&quot;sixty&quot;, @&quot;seventy&quot;, @&quot;eighty&quot;, @&quot;ninety&quot;
};</pre>
<p>I have padded the &#8216;tens&#8217;-array to make indexing a little easier. tens[2] = &#8220;twenty&#8221;, tens[8] = &#8220;eighty&#8221; and so on. Now, the algorithm that I ended  up with, was to start with the larger part of the number, converting it into text, and then handle the rest in the same way. Peele away the larger part, convert it to text, and repeat.</p>
<pre class="brush: objc; title: ;">+(NSString *) processSimpleNumbers:(int)number
{
    return simpleNumbers[number];
}

+(NSString *) processTens:(int)number
{
    if (number &amp;lt; 20) {
        return [self processSimpleNumbers:number];
    }

    int div = number / 10;
    int rest = number % 10;
    NSString *tmp = tens[div];
    if (rest &amp;gt; 0){
        return [NSString stringWithFormat:@&quot;%@-%@&quot;, tmp, [self processSimpleNumbers:rest]];
    } else{
        return tmp;
    }
}

+(NSString *) processHundreds:(int)number;
{
    if (number &amp;lt; 100) {
        return [self processTens:number];
    }

    int div = number / 100;
    int rest = number % 100;
    NSString *tmp = [NSString stringWithFormat:@&quot;%@ hundred&quot;, simpleNumbers[div]];
    if (rest &amp;gt; 0){
        return [NSString stringWithFormat:@&quot;%@ and %@&quot;, tmp, [self processTens:rest] ];
    } else {
        return tmp;
    }
}

+(NSString *) processThousands:(int)number;
{
    if (number &amp;lt; 1000){
        return [self processHundreds:number];
    }

    int div = number / 1000;
    int rest = number % 1000;

    NSString *tmp = [NSString stringWithFormat:@&quot;%@ thousand&quot;, [self processHundreds:div]];

    if (rest &amp;gt; 0) {
        if (rest &amp;lt; 100) {
            return [NSString stringWithFormat:@&quot;%@ and %@&quot;, tmp, [self processTens:rest]];
        } else {
            return [NSString stringWithFormat:@&quot;%@ %@&quot;, tmp, [self processHundreds:rest]];
        }
    } else{
        return tmp;
    }
}

+(NSString *) fromInt:(int)number
{
    return [self processThousands:number];
}</pre>
<p>I&#8217;m sure there are prettier ways of solving this, but it works. The remaining task, is trivial. Convert each number and accumulate the length of the strings after removing hyphens and spaces. Of cause, we could get rid of these characters right away by not returning them in the first place, but then again, I did not&#8230;</p>
<p>I have uploaded the source to my <a href="http://svn.vi-kan.net/euler">svn repository</a> if you want to take a look. You&#8217;ll find the WrittenNumber class in the iPhone/src folder, and the unittests in the iPhone/tests folder.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/project-euler-problem-17/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UnitTesting on the iPhone</title>
		<link>http://blog.vi-kan.net/2010/unittesting-on-the-iphone/</link>
		<comments>http://blog.vi-kan.net/2010/unittesting-on-the-iphone/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 21:32:43 +0000</pubDate>
		<dc:creator>Vegar</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://blog.vi-kan.net/?p=227</guid>
		<description><![CDATA[I have to admit, that I find xcode and objective-c the most challenging developing environment I have ever tried. Specifically, I have struggled to find an easy way of including unittests for an application. Even though it comes with some unittest templates, I haven&#8217;t successfully put it to work. Can&#8217;t say I have tried that [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 0px 0px 0px 10px; display: inline; border: 0px;" title="GH-Unit" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/Screen-shot-2010-11-15-at-22.26.41-e1289856633401-150x86.png" alt="" width="150" height="86" align="right" />I have to admit, that I find xcode and objective-c the most challenging developing environment I have ever tried. Specifically, I have struggled to find an easy way of including unittests for an application. Even though it comes with some unittest templates, I haven&#8217;t successfully put it to work. Can&#8217;t say I have tried that much either; it all seemed to complicated to be worth it&#8230;<br />
<span id="more-227"></span></p>
<p>This weekend, the following tweet got my attention:</p>
<pre><a href="http://twitter.com/#!/mfeathers/statuses/2907728083165185"><img class="aligncenter size-full wp-image-232" title="TDD for iPhone Development" src="http://blog.vi-kan.net/wp-content/uploads/2010/11/Screen-shot-2010-11-15-at-22.14.06.png" alt="TDD for iPhone Development : http://www.vimeo.com/16722907" width="542" height="77" /></a></pre>
<p>The video shows a step-by-step guide on how to get started with unittesting for the iPhone. It looked great, and not that complicated, so I decided to give it a try. 10 minutes later, only delayed by a mysterious <span style="font-family: monospace; line-height: 18px; font-size: 12px; white-space: pre;">&#8220;Failed to launch simulated application: Unknown error.&#8221;</span>-error<sup>*</sup>, I had my first unittest up and running in the simulator.</p>
<p>If you develop for the iPhone, and either have struggled with unittesting, or just never tried, I will recommend you watch <a title="TDD for iPhone @ vimeo" href="http://www.vimeo.com/16722907" target="_blank">the video</a>. The steps followed in the video is thoroughly documented on the <a title="schuchert - iPhone.SettingUpTheEnvionment" href="http://schuchert.wikispaces.com/iPhone.SettingUpTheEnvionment" target="_blank">authors home page</a>.</p>
<p><sup>*</sup>I never found a reason for this error. As for so many other error messages I have encountered in xcode, starting a new project resolved the issue&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.vi-kan.net/2010/unittesting-on-the-iphone/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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?   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/"><img class="alignright size-full wp-image-204" style="margin: 0px 0px 0px 10px; display: inline; border: 0px;" title="http://ditchnet.org/httpclient/" src="http://blog.vi-kan.net/wp-content/uploads/2010/05/image3.png" alt="" width="176" height="147" /></a>So, did you read my little <a href="http://blog.vi-kan.net/2010/introducing-couchdb/">introduction</a>? Did you go nuts with the Futon application?   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><strong>Say Hello to CouchDB</strong></p>
<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>
<p>GET http://127.0.0.1:5984/</p>
<p>If the server is running, it will respond with a welcome message and a version number.</p>
<pre class="brush: jscript; light: true; title: ;">{&quot;couchdb&quot;:&quot;Welcome&quot;,&quot;version&quot;:&quot;0.11.0&quot;}</pre>
<p>You can also check to see what databases allready exists on the server, by doing a GET request to /_all_dbs.</p>
<pre class="brush: bash; light: true; title: ;">GET http://127.0.0.1:5984/_all_dbs</pre>
<p>The resonse will be formatted as an JSON array with database names.</p>
<pre class="brush: jscript; light: true; title: ;">[&quot;business-cards&quot;,&quot;newdb&quot;,&quot;testdb&quot;]</pre>
<p><strong>Databases</strong></p>
<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; title: ;">GET http://127.0.0.1:5984/business-cards</pre>
<p>This request want return the complete database with all its documents. It will instead return some information about the database.</p>
<pre class="brush: jscript; light: true; title: ;">{&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; title: ;">PUT http://127.0.0.1:5984/geocaches</pre>
<p>If the database was created as expected, we will get a positive response.</p>
<pre class="brush: jscript; light: true; title: ;">{&quot;ok&quot;:true}</pre>
<p>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>
<pre class="brush: jscript; light: true; title: ;">{&quot;error&quot;:&quot;file_exists&quot;,&quot;reason&quot;:&quot;The database could not be created, the file already exists.&quot;}</pre>
<p>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>
<pre class="brush: jscript; light: true; title: ;">{&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…..?  Yes, a DELETE request.</p>
<pre class="brush: bash; light: true; title: ;">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>
<p><strong>Documents</strong></p>
<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>
<p><strong>Create</strong></p>
<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: jscript; light: true; title: ;">{

&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>I want to store this as an document with the key GC1TCJR in the database geocaches, so lets PUT it up there.</p>
<pre class="brush: bash; light: true; title: ;">PUT http://127.0.0.1:5984/geocaches/GC1TCJR

{“url”:”http://www.geocaching.com/seek/cache_details.aspx?guid=…….&quot;}</pre>
<p>If everything goes by the plan, CouchDB will responde with a 201 Created status, together with something like this:</p>
<pre class="brush: bash; light: true; title: ;">{&quot;ok&quot;:true,&quot;id&quot;:&quot;GC1TCJR&quot;,&quot;rev&quot;:&quot;1-f70033bafd9d72e174cecb67f58b2e4f&quot;}[/js]

&lt;p&gt;

&lt;br /&gt;If a document with the same id already exists, you will get a 409 Conflict status and the following error:

&lt;br /&gt;&lt;/p&gt;

[js light=&quot;true&quot;]{&quot;error&quot;:&quot;conflict&quot;,&quot;reason&quot;:&quot;Document update conflict.&quot;}[/js]

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

[bash light=&quot;true&quot;]POST http://127.0.0.1:5984/geocaches

{“url”:”http://www.geocaching.com/seek/cache_details.aspx?guid=……&quot;}</pre>
<p>Now that we have successfully stored our document, we can retreive it by doing a GET.</p>
<pre class="brush: bash; light: true; title: ;">GET http://127.0.0.1:5984/geocaches/GC1TCJR</pre>
<p>As you can see from the response, CouchDB has added the id and revision fields to our document.</p>
<pre class="brush: bash; light: true; title: ;">{&quot;_id&quot;:&quot;GC1TCJR&quot;,&quot;_rev&quot;:&quot;1-f70033bafd9d72e174cecb67f58b2e4f&quot;,&quot;url&quot;:&quot;http://www.geocaching.com/……&quot;}</pre>
<p><strong>Update</strong></p>
<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; title: ;">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>CouchDB will respond with a 200 OK status, and inform you about the new revision number.</p>
<pre class="brush: jscript; light: true; title: ;">{&quot;ok&quot;:true,&quot;id&quot;:&quot;GC1TCJR&quot;,&quot;rev&quot;:&quot;2-6aa44736b02f96844fdfbf4eece00b83&quot;}</pre>
<p><strong>Delete</strong></p>
<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; title: ;">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: jscript; light: true; title: ;">{&quot;ok&quot;:true,&quot;rev&quot;:&quot;3-6b8ecfd8bd5d1cb8ae3fd49aea9dfe8d&quot;}</pre>
<p>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>
<pre class="brush: jscript; light: true; title: ;">{&quot;error&quot;:&quot;not_found&quot;,&quot;reason&quot;:&quot;deleted&quot;}</pre>
<p><strong>Listing</strong></p>
<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; title: ;">GET http://127.0.0.1:5984/geocaches/_all_docs</pre>
<p>The response will contain information of total number of rows, and an array of ids and revision numbers.</p>
<pre class="brush: plain; light: true; title: ;">{&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>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>
<pre class="brush: bash; light: true; title: ;">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>
<p><strong>What’s next?</strong></p>
<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 want [...]]]></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>
		<category><![CDATA[Euler]]></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 [...]]]></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>
<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; title: ;">sum := 0;for prime in PrimeGenerator(500000) do
begin
  if prime &amp;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 [...]]]></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>
<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.  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; title: ;">    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; title: ;">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; title: ;">        for c := b+1 to 998 do
        begin
          sum := a + b + c;
          if (sum) &amp;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 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 I can’t [...]]]></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; title: ;">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; title: ;">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; title: ;">    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 &amp;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>
	</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! -->
