<?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>Limegarden.net &#187; code</title>
	<atom:link href="http://limegarden.net/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://limegarden.net</link>
	<description>Personal site of Wouter Lindenhof</description>
	<lastBuildDate>Mon, 06 Sep 2010 21:15:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Extending exceptions</title>
		<link>http://limegarden.net/2010/08/19/extending-exceptions/</link>
		<comments>http://limegarden.net/2010/08/19/extending-exceptions/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 13:20:20 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=366</guid>
		<description><![CDATA[Sometimes you have a function which needs to communicate back on failure through special exceptions as you want to program have the option to fix certain functions. For example a formula whose input parameter is bad (example: begin date is after the end date) or when the database throws up or anything. Now you could [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you have a function which needs to communicate back on failure through special exceptions as you want to program have the option to fix certain functions. For example a formula whose input parameter is bad (example: begin date is after the end date) or when the database throws up or anything.</p>
<p>Now you could do the following:</p>
<pre class="brush: csharp; ">

public class EndDateBeforeBeginDateException : Exception 	{ }

class example
{
	void SomethingWithTime(DateTime begin, DateTime end)
	{
		if (begin &gt; end) throw new EndDateBeforeBeginDateException();
		// ... do something with time ....
	}

	void DemonstrateFunctionTriesToCorrectInsteadOfFail()
	{
		DateTime input_begin = new DateTime();
		DateTime input_end = input_begin.AddDays(-1); // WRONG DATE ON PURPOSE!
		do
		{
			try
			{
				SomethingWithTime(input_begin, input_end);
			}
			catch (EndDateBeforeBeginDateException)
			{
				// Date was most likely wrong ask user
				var r = MessageBox.Show(&quot;The end date was before the begin date.&quot;
					+ &quot;Do you want to switch them and try again?&quot;,
					&quot;Switch dates?&quot;,
					MessageBoxButtons.YesNo);

				if (r != DialogResult.No) { return; } // quit function
				var temp = input_begin;
				input_begin = input_end;
				input_end = temp;
				continue; // Try again now
			}
		} while (false);
	}
}
</pre>
<p>But what if you have a lot of parameters. You don't want to create thousands of exceptions. Well, you can try using tagged exceptions which looks like this.</p>
<pre class="brush: csharp; ">

public class TaggedException&lt;T&gt; : Exception { }

struct _EndDateBeforeBeginDateTag{}
struct _SameDateTag {}
struct _TimeDoesNotExistTag {}
struct _ThinkOfATagOnYourOwn {}

class example
{
	void SomethingWithTime(DateTime begin, DateTime end)
	{
		if (begin &gt; end)  throw new TaggedException&lt;_EndDateBeforeBeginDateTag&gt;();
		if (begin == end) throw new TaggedException&lt;_SameDateTag&gt;();
		// ... do something with time ....
	}

	void DemonstrateFunctionTriesToCorrectInsteadOfFail()
	{
		DateTime input_begin = new DateTime();
		DateTime input_end = input_begin.AddDays(-1); // WRONG DATE ON PURPOSE!
		do
		{
			try
			{
				SomethingWithTime(input_begin, input_end);
			}
			catch (TaggedException&lt;_EndDateBeforeBeginDateTag&gt;)
			{
				// Date was most likely wrong ask user
				var r = MessageBox.Show(&quot;The end date was before the begin date.&quot;
					+ &quot;Do you want to switch them and try again?&quot;,
					&quot;Switch dates?&quot;,
					MessageBoxButtons.YesNo);

				if (r != DialogResult.No) { return; } // quit function
				var temp = input_begin;
				input_begin = input_end;
				input_end = temp;
				continue; // Try again now
			}catch (TaggedException&lt;_SameDateTag&gt;)
			{
				// Force the user to change one date
			}catch (TaggedException&lt;_ThinkOfATagOnYourOwn&gt;)
			{
				// Tag seems obvious enough *wink*
			}
		} while (false);
	}
}
</pre>
<p> Now you only have one Exception in your code though you can quickly and without having to write much code.<br />
(And if you are smart you store extra info the tag which is stored in the exception). </p>
<p>The same trick also works in C++ using templates. </p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/08/19/extending-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comments</title>
		<link>http://limegarden.net/2010/07/06/comments/</link>
		<comments>http://limegarden.net/2010/07/06/comments/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 06:31:43 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[Game development]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Style]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=353</guid>
		<description><![CDATA[This part is almost straight from my programming style document. This might sound stupid, but try to comment every other line (unless you have a lot of repeating or similar tasks). By doing so you get two advantages: Someone unskilled in programming or unfamiliar with what you are doing is able to read your code. [...]]]></description>
			<content:encoded><![CDATA[<p>This part is almost straight from my programming style document. </p>
<p>This might sound stupid, but try to comment every other line (unless you have a lot of repeating or similar tasks). By doing so you get two advantages:</p>
<ol>
<li>Someone unskilled in programming or unfamiliar with what you are doing is able to read your code.</li>
<li>You know what you are doing</li>
</ol>
<p>The first advantage is important unless you are working alone and never expect to see your code again. In that case you should really ask yourself if you should even be writing that code.</p>
<p>The second one is important even if you have no trouble reading code. Let's take a look at the following example.</p>
<pre class="brush: cpp; ">
for(int index_person = 0; index_person &lt; persons.size(); ++index_person)
{
    for(int index_kids = 0; index_kids &lt; persons[index_person].kids.size(); ++index_kids)
    {
        /* ... */
    }
}
</pre>
<p>And then take a look at this example:</p>
<pre class="brush: cpp; ">
/* Iterating through the persons in the lists */
for(int index_person = 0; index_person &lt; persons.size(); ++index_person)
{
    /* Iterating through the kids of the persons in the list */
    for(int index_kids = 0; index_kids &lt; persons[index_person].kids.size(); ++index_kids)
    {
        /* checking if any of the persons in the list have a kid who is dead */
        /* ... */
    }
}
</pre>
<p>In the last example I only have to track back to the first comment prior to my line of code to know what I'm doing here. It's a pain to write so many comments but it makes code a whole lot easier to read.</p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/07/06/comments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Events in C++</title>
		<link>http://limegarden.net/2010/05/17/events-in-c/</link>
		<comments>http://limegarden.net/2010/05/17/events-in-c/#comments</comments>
		<pubDate>Mon, 17 May 2010 17:27:15 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[event]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=312</guid>
		<description><![CDATA[This week I have decided to do some little work on Nova as I would like to use it for a game. But I’m currently missing a GUI. Since writing a GUI is often a pain while a nice GUI is its weight worth in gold it was worth to invest some time in it. [...]]]></description>
			<content:encoded><![CDATA[<p>This week I have decided to do some little work on Nova as I would like to use it for a game. But I’m currently missing a GUI. Since writing a GUI is often a pain while a nice GUI is its weight worth in gold it was worth to invest some time in it.<br />
One of the very first things I have decided on is that I want a good and proper event management system. I like how it is done in C#</p>
<pre class="brush: c#; ">

myButton.Click += new EventHandler(this.myButton_Click);
</pre>
<p>However something equally nice doesn't exist in plain C++, so I have decided to write one.</p>
<pre class="brush: c++; ">

struct GuiEvent
{
	bool cancel;
	GuiEvent() : cancel(false) {}
};

class Button
{
public:
	Event&lt;GuiEvent&gt; OnDown;
	Event&lt;GuiEvent&gt; OnUp;

	void FireClickEvent()
	{
		size_t cycle = 0; GuiEvent e;
		while(OnDown.Fire(cycle, e)) {
			if(e.cancel == true) return;
		}
		e = GuiEvent(); cycle = 0;
		while(OnUp.Fire(cycle, e));
	}
};

class Application : public BaseEvent::Receiver&lt;Application&gt;
{
	Button m_StartButton;
public:
	Application()
	{
		RegisterEvent&lt;GuiEvent&gt;(m_StartButton.OnDown, &amp;Application::StartDown);
		RegisterEvent&lt;GuiEvent&gt;(m_StartButton.OnUp,	&amp;Application::StartUp);
		m_StartButton.FireClickEvent();
	}

	void StartUp(GuiEvent&amp; eventParam)
	{
		std::cout &lt;&lt; &quot;The start button was released&quot; &lt;&lt; &quot;\n&quot;;
	}
	void StartDown(GuiEvent&amp; eventParam)
	{
		// If you set event param to true the release will never be called
		//eventParam.cancel = true;
		std::cout &lt;&lt; &quot;The start button is pressed down&quot; &lt;&lt; &quot;\n&quot;;
	}
};

int main(int argc, const char* argv[])
{
	Application myApp;
	return 0;
}
</pre>
<p>The above is rather primitive as I have written it quickly, but it looks nice and is code that is easy to understand. For the full source <a href='http://limegarden.net/wp-content/uploads/2010/05/main.cpp'>click here (C++ example of events)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/05/17/events-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solved undesired template specification</title>
		<link>http://limegarden.net/2010/04/07/solved-undesired-template-specification/</link>
		<comments>http://limegarden.net/2010/04/07/solved-undesired-template-specification/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 06:30:36 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=304</guid>
		<description><![CDATA[A while ago (why do I always start with that) I wrote an blog entry about undesired template specification, what to encounter and how to work around it. Anyway here is a quick definition of two structures I will be using in the article: /** * I will be using the following structures throughout the [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago (why do I always start with that) I wrote an blog entry about <a href="http://limegarden.net/2010/01/10/undesired-template-specification/" target="_blank">undesired template specification</a>, what to encounter and how to work around it.</p>
<p>Anyway here is a quick definition of two structures I will be using in the article:</p>
<pre class="brush: c++; ">

/**
 * I will be using the following structures throughout the article
 */
template &lt;typename T&gt; struct Vector3&lt;T&gt; {
	union {
		struct { T x, y, z; }
		T array[3];
	};
	Vector3&lt;T&gt;() : x(0), y(0), z(0) {}
	Vector3&lt;T&gt;(T nx, T ny, T nz) : x(nx), y(ny), z(nz) {}
};

template &lt;typename T&gt; struct Vector4&lt;T&gt; {
	union {
		struct { T x, y, z, w; }
		T array[4];
	};
	Vector4&lt;T&gt;() : x(0), y(0), z(0), w(0) {}
	Vector3&lt;T&gt;(T nx, T ny, T nz, T nw) : x(nx), y(ny), z(nz), w(nw) {}
};
typedef Vector3&lt;unsigned int&gt; Vector3u;
typedef Vector3&lt;float&gt;        Vector3f;
typedef Vector4&lt;unsigned int&gt; Vector4u;
typedef Vector4&lt;float&gt;        Vector4f;

struct SVertex
{
	Vector4f pos;
	Vector3f normal;
	Vector2f texcoord;
};
</pre>
<p>Because of Brick (3D random dungeon generator that takes design into account) I have noticed that there is one thing I do failry often:</p>
<pre class="brush: c++; ">

Vector3f position;
SVertex vertex;

/* Need to draw it, so I store position in vertex */
vertex.pos = position; // ERROR! Trying to assign Vector3f to Vector4f!!
</pre>
<p>And finally I used defines to do the conversion for me:</p>
<pre class="brush: c++; ">

#define VEC3TOVEC4(v) Vector4f((v).x, (v).y, (v).z, 0)
#define VEC4TOVEC3(v) Vector3f((v).x, (v).y, (v).z)

/* New code becomes */
vertex.pos = VEC3TOVEC4(position); // Works
</pre>
<p>Of course the above code is not nice to look at and I find it even plain ugly, but it works. However I don't want to do that in future projects (it feels like a hack), I would need to define something like that for every type (float, double, unsigned int et cetera) and on top of that it generates warnings:</p>
<pre class="brush: c++; ">

Vector3&lt;double&gt; position;	// Notice it is unsigned!
SVertex vertex;

/* Need to draw it, so I store position in vertex */
vertex.pos = VEC3TOVEC4(position); // Works, but generates warning about losing information
</pre>
<p>But I wouldn't be writing this post unless I tackled that little issue, and for once I can add that the solution is quite nice as well.</p>
<pre class="brush: c++; ">

Vector3&lt;double&gt; position;	// Notice it is unsigned!
SVertex vertex;

/* Need to draw it, so I store position in vertex */
vertex.pos.Set(position.array, 3); 		// Works, no errors and no warnings
vertex.pos = Vector4f(position.array, 3);	// Works fine as well
</pre>
<p>So what did I change?</p>
<p>Well, I used mutliple template (one for the class and for the function/constructor). This looks something like this:</p>
<pre class="brush: c++; ">

template &lt;typename T&gt; struct Vector4
{
	/* ... */
	template &lt;typename R&gt;
	explicit inline Vector4&lt;T&gt;(const R* values, const unsigned int elements/*=4*/);
	template &lt;typename R&gt;
	inline Vector4&lt;T&gt;&amp; Set(const R* values, const unsigned int elements/*=4*/);
	/* ... */
};

// Implementation
template &lt;typename T&gt; template &lt;typename R&gt;
Vector4&lt;T&gt;::Vector4(const R* values, unsigned int elements)
	: x(elements &gt; 0 ? (T)values[0] : 0), y(elements &gt; 1 ? (T)values[1] : 0)
	, z(elements &gt; 2 ? (T)values[2] : 0), w(elements &gt; 3 ? (T)values[3] : 0)
{
}
template &lt;typename T&gt; template &lt;typename R&gt;
Vector4&lt;T&gt;&amp; Vector4&lt;T&gt;::Set(const R* values, const unsigned int elements)
{
	x = (elements &gt; 0 ? (T)values[0] : 0);
	y = (elements &gt; 1 ? (T)values[1] : 0);
	z = (elements &gt; 2 ? (T)values[2] : 0);
	w = (elements &gt; 3 ? (T)values[3] : 0);
	return *this;
}
</pre>
<p>If you take a look at the code I think it is quite clear except that you might have some questions.</p>
<ol>
<li>
<div><b>Q:</b> Why do you use <code class="codecolorer cpp geshi"><span class="cpp"><span style="color: #0000ff;">explicit</span></span></code> with the constructor?</div>
<div><b>A:</b> Because that prevents the implicit use of constructors. If I would allow it a <code class="codecolorer cpp geshi"><span class="cpp">Vector4u</span></code> could be implicit assigned to <code class="codecolorer cpp geshi"><span class="cpp">Vector3f</span></code>, although it would be missing an argument. However I think that when you are converting, you should be somewhat aware of it, especially when it can be expensive.</div>
</li>
<li>
<div><b>Q:</b> Why have you commented out the default value for <code class="codecolorer cpp geshi"><span class="cpp">elements</span></code>?</div>
<div><b>A:</b> Because you don't know how many elements there are in <code class="codecolorer cpp geshi"><span class="cpp">values</span></code> might be (there is a method to find out). </div>
</li>
<li>
<div><b>Q:</b> So why don't you find out automatically and what is with those conditionals in the constructor?</div>
<div><b>A:</b> Those two are related. By telling it explicitly there is a real good chance that the compiler removes the conditionals, so the <code class="codecolorer cpp geshi"><span class="cpp">&nbsp;<span style="color: #008000;">&#40;</span> check <span style="color: #008080;">?</span> true<span style="color: #000040;">-</span>value <span style="color: #008080;">:</span> false<span style="color: #000040;">-</span>value<span style="color: #008000;">&#41;</span></span></code> check will be removed. </div>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/04/07/solved-undesired-template-specification/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Combo hit!! in code</title>
		<link>http://limegarden.net/2010/04/06/combo-hit-in-code/</link>
		<comments>http://limegarden.net/2010/04/06/combo-hit-in-code/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 07:17:24 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=302</guid>
		<description><![CDATA[I have always wondered how hard it would be to write a combo system. Not that hard I guess. And after a bit of morning programming I already got it working. The only reason it took longer than anticipated was because of muscle memory. One of the features I wanted to test was the delay. [...]]]></description>
			<content:encoded><![CDATA[<p>I have always wondered how hard it would be to write a combo system. Not that hard I guess. And after a bit of morning programming I already got it working. </p>
<p>The only reason it took longer than anticipated was because of muscle memory. One of the features I wanted to test was the delay. For example you want to do the "asdf" combo, but you are for some reason not fast enough, than the combo should not start. Simulating this is easy, just begin the combo and stop somewhere for a second and then complete the combo. So "asd", pause and then "f".<br />
However when I tried that for some reason the combo was sometimes completed. Only after adding the debug messages I noticed that I often automatically did complete the combo. The problem was muscle memory.</p>
<p>Anyway below is the code and if anyone wants to extend it (wrong next key, combo breakers, roman cancel, and follow-up combos) feel free to do so and let me know.</p>
<pre class="brush: c++; ">

/*******************************************************************************
 * The MIT License
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2010 Wouter Lindenhof (http://limegarden.net)
 *
 * Demonstration of a simple ComboHit system
 *******************************************************************************/

#include &lt;Windows.h&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;
#pragma comment(lib, &quot;Winmm.lib&quot;)

#define DEBUGLOG 1 // Set to 0 to turn debug messages off

class KeyHit
{
public:
	UINT m_Key;
	UINT m_Delay;
	UINT m_Waiting;
public:
	KeyHit(UINT key, UINT delay) : m_Key(key), m_Delay(delay), m_Waiting(0) { }
};

class HitCombo
{
	UINT m_SequenceIndex;
	std::vector&lt;KeyHit&gt; m_Keys;
public:
	HitCombo() : m_SequenceIndex(0) { }

	void Cancel();
	void Update(DWORD ms);
	operator bool();
	HitCombo&amp; operator &lt;&lt; (const KeyHit&amp; hit);
};

int main(int argc, const char* argv[])
{
	std::cout &lt;&lt; &quot;-----------------------------------------------&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;This is a combo key tester: &quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;Press \&quot;ASDF\&quot; quickly to do a combo hit&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;Press \&quot;Wouter\&quot; quickly to write my name&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;Press SHIFT and then escape to quit&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;-----------------------------------------------&quot; &lt;&lt; std::endl;
	HitCombo QuitApplication, ComboHit, WouterCombo;
	QuitApplication &lt;&lt; KeyHit(VK_SHIFT, 250) &lt;&lt; KeyHit(VK_ESCAPE, 250);
	ComboHit		&lt;&lt; KeyHit(&#039;A&#039;, 250) &lt;&lt; KeyHit(&#039;S&#039;, 250) &lt;&lt; KeyHit(&#039;D&#039;, 250)
					&lt;&lt; KeyHit(&#039;F&#039;, 250);
	WouterCombo		&lt;&lt; KeyHit(&#039;W&#039;, 250) &lt;&lt; KeyHit(&#039;O&#039;, 250) &lt;&lt; KeyHit(&#039;U&#039;, 250)
					&lt;&lt; KeyHit(&#039;T&#039;, 250) &lt;&lt; KeyHit(&#039;E&#039;, 250) &lt;&lt; KeyHit(&#039;R&#039;, 250);

	DWORD lastTime = timeGetTime();
	DWORD curTime = lastTime;
	DWORD difference = 0;

	while(true)
	{
		curTime = timeGetTime();
		difference = curTime - lastTime;
		lastTime = curTime;
		if(ComboHit)
		{
			std::cout &lt;&lt; &quot;You did a combo hit!!&quot; &lt;&lt; std::endl;
			WouterCombo.Cancel();
			QuitApplication.Cancel();
		}
		if(WouterCombo)
		{
			std::cout &lt;&lt; &quot;You wrote &#039;Wouter&#039;, good for you!&quot; &lt;&lt; std::endl;
			ComboHit.Cancel();
			QuitApplication.Cancel();
		}
		if(QuitApplication)
		{
			std::cout &lt;&lt; &quot;You quit the application!&quot; &lt;&lt; std::endl;
			ComboHit.Cancel();
			WouterCombo.Cancel();
			break;
		}
		ComboHit.Update(difference);
		QuitApplication.Update(difference);
		WouterCombo.Update(difference);
	}

	return 0;
}

void HitCombo::Cancel() {
	m_SequenceIndex = 0;
}

// Implementation
HitCombo&amp; HitCombo::operator &lt;&lt;(const KeyHit &amp;hit) {
	m_Keys.push_back(hit);
	return *this;
}

HitCombo::operator bool() {
	return m_SequenceIndex == m_Keys.size();
}
void HitCombo::Update(DWORD ms)
{
	if(m_SequenceIndex &lt; m_Keys.size())
	{
		KeyHit&amp; hit = m_Keys[m_SequenceIndex];
		hit.m_Waiting += ms;
		if(GetAsyncKeyState(hit.m_Key) != 0)
		{
			if(hit.m_Waiting &lt; hit.m_Delay)
			{
				hit.m_Waiting = 0;
				m_SequenceIndex++;
#if DEBUGLOG = 1
				std::cout &lt;&lt; &quot;you pressed key &quot; &lt;&lt; (char)hit.m_Key &lt;&lt; std::endl;
#endif
			}else
			{
#if DEBUGLOG = 1
				std::cout &lt;&lt; &quot;Delay too long&quot; &lt;&lt; std::endl;
#endif
				hit.m_Waiting = 0;
				m_SequenceIndex = 0;
			}
			if(m_SequenceIndex == 0)
			{
				hit.m_Waiting = 0;
			}
		}else if(m_SequenceIndex==0)
		{
			hit.m_Waiting = 0;
		}else
		{
			if(hit.m_Waiting &gt; hit.m_Delay)
			{
				m_SequenceIndex = 0;
				hit.m_Waiting = 0;
#if DEBUGLOG
				std::cout &lt;&lt; &quot;Delay too long&quot; &lt;&lt; std::endl;
#endif
			}
		}
	}else
	{
		m_SequenceIndex = 0;
		KeyHit&amp; hit = m_Keys[m_SequenceIndex];
		hit.m_Waiting = 0;
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/04/06/combo-hit-in-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;Ordered Programming&#8221; Technique</title>
		<link>http://limegarden.net/2010/03/21/ordered-programming-technique/</link>
		<comments>http://limegarden.net/2010/03/21/ordered-programming-technique/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 09:10:43 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=295</guid>
		<description><![CDATA[When it comes to programming there many, many techniques. One of the techniques I tried is ordered programming. The idea behind it is that quality is assured and nothing can be forgotten. While I was rewriting Brick I decided to use this technique. What it basically does is that you write a “TODO” in the [...]]]></description>
			<content:encoded><![CDATA[<p>When it comes to programming there many, many techniques. One of the techniques I tried is ordered programming. The idea behind it is that quality is assured and nothing can be forgotten. While I was rewriting Brick I decided to use this technique. What it basically does is that you write a “TODO” in the code, for example: “Load configuration file”. And when you run the application in debug mode, it will break when it arrives at that point.</p>
<p>As you can see this has one huge disadvantage and that is that in order to run the entire program all the “TODO” have to be resolved. There is also one huge advantage which is that after you have done something, you will change “TODO” in to “DONE”. The next time you go trough your application, you will notice that the code has now been documented. This is a huge advantage when you write large pieces of code, which you will rarely though in the near future.</p>
<p>However the disadvantage, having to program in the order that the program runs might be too big in some cases. For example some features will be added later as they are not needed now. For example you have written a OBJ loader that handles triangles, but not quads, in this case you might not want to write the quad loading code just yet as you have to focus on the rendering part. For that reason I have decided to add levels, the lower the level the higher the priority. You can think of it in terms as first todo, second todo, etc. If you reach a stage in your development, where you have done all first todo’s, you just increase the number and see where it breaks then.</p>
<p>Here is an example of how it looks when you are writing todo’s.</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &quot;OrderProgramming.hpp&quot;</span><br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">**</span> argv<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; ORDER_PROG_TODO<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Setup Memory Checkpoint&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_TODO<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Initialize graphics engine&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_TODO<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Run the game&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_TODO<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Shutdown the graphics engine&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_TODO<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Check if there are memory leaks&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>And here how it looks at a later stage</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &lt;crtdbg.h&gt;</span><br />
<span style="color: #339900;">#include &quot;OrderProgramming.hpp&quot;</span><br />
<span style="color: #0000ff;">class</span> IGraphics<span style="color: #008080;">;</span><br />
IGraphics<span style="color: #000040;">*</span> InitGraphicsEngine<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #0000ff;">void</span> GameFunction<span style="color: #008000;">&#40;</span>IGraphics<span style="color: #000040;">*</span> graphics<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">**</span> argv<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; _CrtMemState memstate<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; _CrtMemCheckpoint<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>memstate<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_DONE<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Setup Memory Checkpoint&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; IGraphics<span style="color: #000040;">*</span> myGraphics <span style="color: #000080;">=</span> InitGraphicsEngine<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_DONE<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Initialize graphics engine&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; GameFunction<span style="color: #008000;">&#40;</span>myGraphics<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_DONE<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Run the game&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>myGraphics<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000dd;">delete</span> myGraphics<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_DONE<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Shutdown the graphics engine&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; _CrtMemDumpAllObjectsSince<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>memstate<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ORDER_PROG_DONE<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Check if there are memory leaks&quot;</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>And here is the header you will need to include: </p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br />41<br />42<br />43<br />44<br />45<br />46<br />47<br />48<br />49<br />50<br />51<br />52<br />53<br />54<br />55<br />56<br />57<br />58<br />59<br />60<br />61<br />62<br />63<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666;">// OrderProgramming.hpp</span><br />
<span style="color: #666666;">// Generic functions can be defined before inclusion</span><br />
<span style="color: #666666;">// - ORDER_PROG_DEBUGBREAK: &nbsp; &nbsp; Breaks the process if possible</span><br />
<span style="color: #666666;">// - ORDER_PROG_ASSERT: &nbsp; &nbsp; &nbsp; &nbsp; Tries to assert a function</span><br />
<span style="color: #666666;">// - ORDER_PROG_OUTPUT: &nbsp; &nbsp; &nbsp; &nbsp; Debug output function</span><br />
<span style="color: #339900;">#ifndef __ORDER_PROGRAMMING_HPP__</span><br />
<span style="color: #339900;">#define __ORDER_PROGRAMMING_HPP__</span><br />
<br />
<span style="color: #339900;">#define ORDER_PROG_STRINGIFY(x) #x</span><br />
<span style="color: #339900;">#define ORDER_PROG_TOSTRING(x) ORDER_PROG_STRINGIFY(x)</span><br />
<span style="color: #339900;">#define ORDER_PROG_FILE __FILE__</span><br />
<span style="color: #339900;">#define ORDER_PROG_LINE ORDER_PROG_TOSTRING(__LINE__)</span><br />
<span style="color: #339900;">#define ORDER_PROG_HERE ORDER_PROG_FILE&quot;(&quot;ORDER_PROG_LINE&quot;) : &quot;</span><br />
<br />
<span style="color: #339900;">#ifndef ORDER_PROG_DUMMY</span><br />
<span style="color: #339900;"># &nbsp; define ORDER_PROG_DUMMY() {(void)0;}</span><br />
<span style="color: #339900;">#endif </span><br />
<span style="color: #666666;">// Lower than this level will cause the order to be taken in account</span><br />
<span style="color: #339900;">#ifndef ORDER_PROG_LEVEL</span><br />
<span style="color: #339900;"># &nbsp; define ORDER_PROG_LEVEL 1</span><br />
<span style="color: #339900;">#endif</span><br />
<br />
<span style="color: #339900;">#ifndef ORDER_PROG_DEBUGBREAK</span><br />
<span style="color: #339900;"># &nbsp; if defined(_WIN32)</span><br />
<span style="color: #339900;"># &nbsp; &nbsp; &nbsp; include &lt;intrin.h&gt;</span><br />
<span style="color: #339900;"># &nbsp; &nbsp; &nbsp; define ORDER_PROG_DEBUGBREAK __debugbreak();</span><br />
<span style="color: #666666;">// # &nbsp; elif (???)</span><br />
<span style="color: #339900;"># &nbsp; else</span><br />
<span style="color: #339900;"># &nbsp; &nbsp; &nbsp; define ORDER_PROG_DEBUGBREAK {__asm{int 3};}</span><br />
<span style="color: #339900;"># &nbsp; endif</span><br />
<span style="color: #339900;">#endif</span><br />
<br />
<span style="color: #666666;">// Platform independent (most of the time)</span><br />
<span style="color: #339900;">#ifndef ORDER_PROG_ASSERT</span><br />
<span style="color: #339900;"># &nbsp; include &lt;cassert&gt;</span><br />
<span style="color: #339900;"># &nbsp; define ORDER_PROG_ASSERT(expression) assert(expression);</span><br />
<span style="color: #339900;">#endif</span><br />
<br />
<span style="color: #666666;">// Platform dependent</span><br />
<span style="color: #339900;">#ifndef ORDER_PROG_OUTPUT</span><br />
<span style="color: #339900;"># &nbsp; if defined(_WIN32)</span><br />
<span style="color: #339900;"># &nbsp; &nbsp; &nbsp; include &lt;windows.h&gt;</span><br />
<span style="color: #339900;"># &nbsp; &nbsp; &nbsp; define ORDER_PROG_OUTPUT(output) OutputDebugStringA((output));</span><br />
<span style="color: #666666;">//# elif (???)</span><br />
<span style="color: #666666;">//# &nbsp; &nbsp; define ORDER_PROG_OUTPUT(output) ::std::clog &lt;&lt; (output);</span><br />
<span style="color: #339900;"># &nbsp; else</span><br />
<span style="color: #339900;"># &nbsp; &nbsp; &nbsp; define ORDER_PROG_OUTPUT(output) ORDER_PROG_DUMMY()</span><br />
<span style="color: #339900;"># &nbsp; endif</span><br />
<span style="color: #339900;">#endif</span><br />
<br />
<span style="color: #339900;">#ifdef ORDER_PROG_NOBLOCK</span><br />
<span style="color: #339900;"># &nbsp; define ORDER_PROG_BLOCK(reason) ORDER_PROG_DUMMY();</span><br />
<span style="color: #339900;">#else</span><br />
<span style="color: #339900;"># &nbsp; define ORDER_PROG_BLOCK(reason) ORDER_PROG_ASSERT(0 &amp;&amp; (reason))</span><br />
<span style="color: #339900;">#endif</span><br />
<br />
<span style="color: #339900;">#define ORDER_PROG_TODO(reason, level) { if((level) &lt; ORDER_PROG_LEVEL){ ORDER_PROG_DEBUGBREAK; ORDER_PROG_BLOCK(reason) } }</span><br />
<span style="color: #339900;">#define ORDER_PROG_TODO0(reason) ORDER_PROG_TODO(reason, 0);</span><br />
<br />
<span style="color: #339900;">#define ORDER_PROG_DONE(reason, level) { if( (level) &lt; ORDER_PROG_LEVEL) { static bool _once=true; if(_once) { ORDER_PROG_OUTPUT(ORDER_PROG_HERE); ORDER_PROG_OUTPUT(reason); ORDER_PROG_OUTPUT(&quot;\n&quot;); _once = false; } } }</span><br />
<span style="color: #339900;">#define ORDER_PROG_DONE0(reason) ORDER_PROG_DONE(reason, 0)</span><br />
<br />
<span style="color: #339900;">#endif // __ORDER_PROGRAMMING_HPP__</span></div></td></tr></tbody></table></div>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/03/21/ordered-programming-technique/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Marketing and fuzzy distribution</title>
		<link>http://limegarden.net/2010/03/10/marketing-and-fuzzy-distribution/</link>
		<comments>http://limegarden.net/2010/03/10/marketing-and-fuzzy-distribution/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 13:59:36 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[random]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=289</guid>
		<description><![CDATA[I have mentioned fuzzy logic and random distribution before but I think that it is also being applied in some marketing strategies. A supermarket chain in our country is giving away collectibles in the form of images of football players (soccer for the Americans). For every, Oh… I don’t know, € 5 , you spend [...]]]></description>
			<content:encoded><![CDATA[<p>I have mentioned fuzzy logic and random distribution before but I think that it is also being applied in some marketing strategies. </p>
<p>A supermarket chain in our country is giving away collectibles in the form of images of football players (soccer for the Americans). For every, Oh… I don’t know, € 5 , you spend you will get 5 random pictures. </p>
<p>At lunch my mother, who collects them, was going over a list of friends seeing if they have a picture she doesn’t have or the other way around and she noted that certain images nobody seems to have.</p>
<p>If you think about it from a marketing perspective it makes a lot sense why she doesn’t have certain images. The marketing strategy is all about making you willing to pay a certain amount or attract customers because you want those pictures. Once you have them, the marketing strategy will no longer have affect on you. It is in interest of the marketing company to try and keep you as long as possible under the effect of the marketing strategy.</p>
<p>One way of doing it by doing an imbalanced distribution: Certain pictures will not be distributed in certain locations. That way the customer under the effect of marketing will keep buying. Of course this won’t hold in the long run, so what you do is slowly slide the distribution. </p>
<blockquote><p><strong>Sliding random distribution: </strong></p>
<p>A distribution whose content is randomized will only distribute a small subset which moves over the entire distribution so that in the end the entire content was equally distributed, however if a moment in time was used only a small subset would have been available.</p>
</blockquote>
<p>If you have trouble understanding think of it as traveling from the north pole to the south pole visiting every restaurant you can find. At every stop you will select one random soup on the menu. Each place has different flavors and as you go more and more south you will encounter different flavors. However because your are “sliding” you will often encounter the same soup.</p>
<p>Anyway if that wasn’t clear here is it in code:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br />41<br />42<br />43<br />44<br />45<br />46<br />47<br />48<br />49<br />50<br />51<br />52<br />53<br />54<br />55<br />56<br />57<br />58<br />59<br />60<br />61<br />62<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &lt;iostream&gt;</span><br />
<span style="color: #339900;">#include &lt;algorithm&gt;</span><br />
<span style="color: #339900;">#include &lt;iomanip&gt;</span><br />
<br />
<span style="color: #339900;">#define MAX_AMOUNT 100</span><br />
<span style="color: #339900;">#define SLIDER_SIZE 5</span><br />
<span style="color: #ff0000; font-style: italic;">/* Uncomment the next line to see the values in random order */</span><br />
<span style="color: #339900;">#define USE_RANDOM_ORDER</span><br />
<br />
<span style="color: #0000ff;">class</span> SlidingDistribution<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">int</span> m_Values<span style="color: #008000;">&#91;</span>MAX_AMOUNT<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">int</span> m_SliderBegin<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">int</span> m_SubPos<span style="color: #008080;">;</span><br />
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; SlidingDistribution<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> m_SliderBegin<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span>, m_SubPos<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> MAX_AMOUNT<span style="color: #008080;">;</span> <span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_Values<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> i<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #339900;">#ifdef USE_RANDOM_ORDER</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #007788;">random_shuffle</span><span style="color: #008000;">&#40;</span>m_Values, m_Values <span style="color: #000040;">+</span> MAX_AMOUNT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #339900;">#endif</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0000ff;">int</span> GetRandomNumber<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; m_SubPos <span style="color: #000040;">+</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>m_SubPos <span style="color: #000040;">%</span> SLIDER_SIZE <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_SliderBegin <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>m_SliderBegin <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">%</span> MAX_AMOUNT<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_SubPos <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">return</span> m_Values<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#40;</span>m_SliderBegin <span style="color: #000040;">+</span> <span style="color: #008000;">&#40;</span>m_SubPos <span style="color: #000040;">%</span> SLIDER_SIZE<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">%</span>MAX_AMOUNT<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">**</span> argv<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; SlidingDistribution distribution<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">int</span> amounts <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">do</span><span style="color: #008000;">&#123;</span> &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">int</span> alignCounter <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">while</span><span style="color: #008000;">&#40;</span>amounts<span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">setfill</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">' '</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">setw</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> distribution.<span style="color: #007788;">GetRandomNumber</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alignCounter<span style="color: #000040;">++</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>alignCounter <span style="color: #000080;">&gt;=</span> <span style="color: #0000dd;">14</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alignCounter <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><span style="color: #0000ff;">else</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amounts<span style="color: #000040;">--</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;How many values do you wish to see? (type 0 to quit)<span style="color: #000099; font-weight: bold;">\n</span>Loops: &quot;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cin</span> <span style="color: #000080;">&gt;&gt;</span> amounts<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">while</span><span style="color: #008000;">&#40;</span>amounts<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/03/10/marketing-and-fuzzy-distribution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom exceptions</title>
		<link>http://limegarden.net/2010/03/06/custom-exceptions/</link>
		<comments>http://limegarden.net/2010/03/06/custom-exceptions/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 11:43:02 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[VB .Net]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=279</guid>
		<description><![CDATA[Besides finishing my study I'm currently also working as a software developer. And yesterday I came across a problem which thought me how a lesson. The project I was working is basically a custom import tool for a financial software. We get an CSV or an XML file and that is imported using the SDK [...]]]></description>
			<content:encoded><![CDATA[<p>Besides finishing my study I'm currently also working as a software developer. And yesterday I came across a problem which thought me how a lesson.</p>
<p>The project I was working is basically a custom import tool for a financial software. We get an CSV or an XML file and that is imported using the SDK of the financial software. Nothing hard except that the SDK is unfinished and various features are yet to be implemented. The majority does work, but it is like walking through a mine field and every time you move forward the application might blow up in your face <img src='http://limegarden.net/wp-includes/images/smilies/icon_twisted.gif' alt=':twisted:' class='wp-smiley' /> </p>
<p>The application is written in Visual Basic .NET (not my choice, but it does the job) and the SDK uses exceptions to notify that a certain feature is not working or when a certain object doesn't meet certain requirements when you ask it to be saved.</p>
<p>Because of the huge amount of data, I used reflection so that I don't have to type as much. My system also uses exceptions, and I won't be surprised if you already where this is going, but while I was debugging I came across multiple exceptions of the SDK which meant that I either had to write a workaround for it or remove the feature until the SDK does support it. When I finally fixed the majority of the errors I suddenly got hit in the face by the following exception:</p>
<div class="codecolorer-container text geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Unable to complete save</div></td></tr></tbody></table></div>
<p>Now the SDK did provide cryptic error messages but this one was completely new and I was doing a bare bone test. I called a coworker over to see if he knew what it meant but he also didn't know what the message meant. A few minutes later he came back to me and said that the part of the SDK did work on his side and that the error must be somewhere in my code.</p>
<p>To cut a long story short. The exception that I got was my own and I hadn't noticed because I had already encountered so many exceptions of the SDK that I just presumed that it was again the SDK that was throwing a fit. <img src='http://limegarden.net/wp-includes/images/smilies/icon_redface.gif' alt=':oops:' class='wp-smiley' /> </p>
<p>Once I realized that it didn't take long to solve it (I returned a true instead of false somewhere), however I was more worried about how to prevent it in the future. After some thought that also was simple.</p>
<p>If any of the application code would throw a fit it would throw not the standard exception which would have been:</p>
<div class="codecolorer-container vb geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="vb codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">throw <span style="color: #000080;">new</span> Exception(<span style="color: #800000;">&quot;Unable to complete save&quot;</span>)</div></td></tr></tbody></table></div>
<p>but a custom type and a search and replace later we got:</p>
<div class="codecolorer-container vb geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="vb codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">throw <span style="color: #000080;">new</span> UtilityException(<span style="color: #800000;">&quot;Unable to complete save&quot;</span>)</div></td></tr></tbody></table></div>
<p>so that error message would contain a special prefix by which it would be clear that it was our own code that decided to throw an exception.</p>
<div class="codecolorer-container vb geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br /></div></td><td><div class="vb codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000080;">Public</span> Class UtilityException<br />
&nbsp; &nbsp; Inherits System.Exception<br />
&nbsp; &nbsp; <span style="color: #000080;">Public</span> <span style="color: #000080;">Sub</span> <span style="color: #000080;">New</span>(<span style="color: #000080;">ByVal</span> str <span style="color: #000080;">As</span> <span style="color: #000080;">String</span>)<br />
&nbsp; &nbsp; &nbsp; &nbsp; MyBase.<span style="color: #000080;">new</span>(str)<br />
&nbsp; &nbsp; <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000080;">Public</span> Overrides ReadOnly <span style="color: #000080;">Property</span> Message() <span style="color: #000080;">As</span> <span style="color: #000080;">String</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000080;">Get</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Return <span style="color: #800000;">&quot;UtilityException: &quot;</span> &amp; MyBase.Message<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000080;">End</span> <span style="color: #000080;">Get</span><br />
&nbsp; &nbsp; <span style="color: #000080;">End</span> <span style="color: #000080;">Property</span><br />
<span style="color: #000080;">End</span> Class</div></td></tr></tbody></table></div>
<p>In the future we will know when it was our own mine to blew up. A simple solution but it would have saved us a lot of time if we had done this from the start.</p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/03/06/custom-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wavefront Obj Mesh Loader</title>
		<link>http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/</link>
		<comments>http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 02:06:47 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[model loading]]></category>
		<category><![CDATA[Wavefront]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/</guid>
		<description><![CDATA[UPDATED 2010-03-02 11:07: There was a minor bug in the code which caused to tokens recognition to file. You won't encounter it in an obj file, but I fixed it for the good order. I can remember the first time I wrote my Obj Mesh loader. It took hours. Today I needed also an obj [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATED 2010-03-02 11:07:</strong> There was a minor bug in the code which caused to tokens recognition to file. You won't encounter it in an obj file, but I fixed it for the good order.</p>
<p>I can remember the first time I wrote my Obj Mesh loader. It took hours. Today I needed also an obj mesh loader and this time it took mere minutes (under 15 minutes at least), so I have decided to share it. Keep in mind you should most likely separate it in header and source files.</p>
<pre class="brush: cpp; ">

/**
 * The MIT License
 *
 * Copyright (c) 2010 Wouter Lindenhof (http://limegarden.net)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the &quot;Software&quot;), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;sstream&gt;
#include &lt;fstream&gt;

#define TOKEN_VERTEX_POS &quot;v&quot;
#define TOKEN_VERTEX_NOR &quot;vn&quot;
#define TOKEN_VERTEX_TEX &quot;vt&quot;
#define TOKEN_FACE &quot;f&quot;

struct Vector2f{
    float x, y;
};
struct Vector3f{
    float x, y, z;
};

struct ObjMeshVertex{
    Vector3f pos;
    Vector2f texcoord;
    Vector3f normal;
};

/* This is a triangle, that we can render */
struct ObjMeshFace{
    ObjMeshVertex vertices[3];
};

/* This contains a list of triangles */
struct ObjMesh{
    std::vector&lt;ObjMeshFace&gt; faces;
};

/* Internal structure */
struct _ObjMeshFaceIndex{
    int pos_index[3];
    int tex_index[3];
    int nor_index[3];
};

/* Call this function to load a model, only loads trianglized meshes */
ObjMesh LoadObjMesh(std::string filename){
    ObjMesh myMesh;

    std::vector&lt;Vector3f&gt;           positions;
    std::vector&lt;Vector2f&gt;           texcoords;
    std::vector&lt;Vector3f&gt;           normals;
    std::vector&lt;_ObjMeshFaceIndex&gt;  faces;
    /**
     * Load file, parse it
     * Lines beginning with:
     * &#039;#&#039;  are comments can be ignored
     * &#039;v&#039;  are vertices positions (3 floats that can be positive or negative)
     * &#039;vt&#039; are vertices texcoords (2 floats that can be positive or negative)
     * &#039;vn&#039; are vertices normals   (3 floats that can be positive or negative)
     * &#039;f&#039;  are faces, 3 values that contain 3 values which are separated by / and &lt;space&gt;
     */

    char char_buffer[256];
    std::ifstream filestream;
    filestream.open(filename.c_str());
    while(filestream.eof() == false &amp;&amp; filestream.bad() == false){
        memset(char_buffer, 0, 256);
        filestream.getline(char_buffer, 256);
        /* FIXED:
         * Where strlen stood was first 256, however this would cause a problem
         * when you only have a token
         */
        std::stringstream str_stream(std::string(char_buffer, strlen(char_buffer)));
        std::string type_str;
        str_stream &gt;&gt; type_str;
        if(type_str == TOKEN_VERTEX_POS){
            Vector3f pos;
            str_stream &gt;&gt; pos.x &gt;&gt; pos.y &gt;&gt; pos.z;
            positions.push_back(pos);
        }else if(type_str == TOKEN_VERTEX_TEX){
            Vector2f tex;
            str_stream &gt;&gt; tex.x &gt;&gt; tex.y;
            texcoords.push_back(tex);
        }else if(type_str == TOKEN_VERTEX_NOR){
            Vector3f nor;
            str_stream &gt;&gt; nor.x &gt;&gt; nor.y &gt;&gt; nor.z;
            normals.push_back(nor);
        }else if(type_str == TOKEN_FACE){
            _ObjMeshFaceIndex face_index;
            char interupt;
            for(int i = 0; i &lt; 3; ++i){
                str_stream &gt;&gt;  face_index.pos_index[i] &gt;&gt; interupt
                           &gt;&gt; face_index.tex_index[i]  &gt;&gt; interupt
                           &gt;&gt; face_index.nor_index[i];
            }
            faces.push_back(face_index);
        }
    }
    filestream.close();

    for(size_t i = 0; i &lt; faces.size(); ++i){
        ObjMeshFace face;
        for(size_t j = 0; j &lt; 3; ++j){
            face.vertices[j].pos        = positions[faces[i].pos_index[j] - 1];
            face.vertices[j].texcoord   = texcoords[faces[i].tex_index[j] - 1];
            face.vertices[j].normal     = normals[faces[i].nor_index[j] - 1];
        }
        myMesh.faces.push_back(face);
    }

    return myMesh;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>STL algorithms</title>
		<link>http://limegarden.net/2010/02/23/stl-algorithms/</link>
		<comments>http://limegarden.net/2010/02/23/stl-algorithms/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 13:16:32 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[STL Library]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/02/23/stl-algorithms/</guid>
		<description><![CDATA[UPDATE@2010-Feb-23 22:11: Thanks to Arseny Kapoulkine (his blog is : http://zeuxcg.blogspot.com/ ) I discovered that there was a bug in the code I showed. I have fixed this bug I'm not a huge fan of the STL library (you know std::vectorand it's relatives) as I don't like the syntax and the naming of some functions [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE@2010-Feb-23 22:11:</strong> Thanks to Arseny Kapoulkine (his blog is : <a href="http://zeuxcg.blogspot.com/">http://zeuxcg.blogspot.com/</a> ) I discovered that there was a bug in the code I showed. I have fixed this bug</p>
<p>I'm not a huge fan of the STL library (you know <code class="codecolorer cpp geshi"><span class="cpp">std<span style="color: #008080;">::</span><span style="color: #007788;">vector</span></span></code>and it's relatives) as I don't like the syntax and the naming of some functions and yes, I'm well aware those are mood points but then again I'm always looking for perfection. But there is one part of the STL library I really love which is STL algorithms.</p>
<p>For example, let's say we have the following code</p>
<pre class="brush: c++; ">

#include &lt;vector&gt;
/* ...
 * Somewhere in the code
 * ...
 */
std::vector&lt;int&gt; numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
</pre>
<p>And we want to remove the number &quot;2&quot; from the vector, sadly <code class="codecolorer cpp geshi"><span class="cpp">std<span style="color: #008080;">::</span><span style="color: #007788;">vector</span></span></code> is lacking a remove function. It does have an erase function but that would require an iterator. We could switch to <code class="codecolorer cpp geshi"><span class="cpp">std<span style="color: #008080;">::</span><span style="color: #007788;">list</span></span></code> who does have a remove function. Without STL algorithms we would write something like this:</p>
<pre class="brush: c++; ">

/* Written for readability
 * And it only removes the first one it finds.
 */
template &lt;typename T&gt;
void RemoveFromVector(const T val, std::vector&lt;T&gt; vec)
{
    for(std::vector&lt;T&gt;::iterator begin = vec.begin(); begin != vec.end(); ++begin)
    {
        if(*begin == val)
        {
            vec.erase(begin);
            return;
        }
    }
}
/* ... And here we call it */
RemoveFromVector&lt;int&gt;(2, numbers);
</pre>
<p>The only thing I can say about it is that it looks ugly. Now let's use stl algorithms and see how that looks like.</p>
<pre class="brush: c++; ">

/**
 * Previously the code was:
 * std::remove(numbers.begin(), numbers.end(), 2);
 * But that only removes the number, but keeps the same size. std::remove instead
 * returns an iterator which holds the end. (numbers.size() would give the same
 * result before and after the above code.
 * Thanks to  Arseny Kapoulkine this has been corrected and the good version is
 * now here available.
 */
numbers.erase( std::find(numbers.begin(), numbers.end(), 2) );
</pre>
<p><del>One line of code and that's all.</del> Well, it's still one line of code, but two rather simple functions. The <code class="codecolorer cpp geshi"><span class="cpp">erase</span></code> function takes an iterator as input (which <code class="codecolorer cpp geshi"><span class="cpp">std<span style="color: #008080;">::</span><span style="color: #007788;">find</span></span></code> returns for you). However keep in mind that if <code class="codecolorer cpp geshi"><span class="cpp">std<span style="color: #008080;">::</span><span style="color: #007788;">find</span></span></code> can't find a result (for example &quot;2&quot; was already missing, your application will crash.</br>One thing I always hate was when I stored pointers in an object that needed destruction</p>
<pre class="brush: c++; ">

#include &lt;vector&gt;
#define SAFE_DELETE(p) if(p) delete(p); (p)=0;
class StorageObject1;
class StorageObject2;
class StorageContainer
{
    std::vector&lt;StorageObject1*&gt; m_Objects1;
    std::vector&lt;StorageObject2*&gt; m_Objects2;
public:
    ~StorageContainer()
    {
        for(size_t i = 0; i &lt; m_Objects1.size(); ++i)
        {
            SAFE_DELETE(m_Objects1[i]);
        }
        for(size_t i = 0; i &lt; m_Objects2.size(); ++i)
        {
            SAFE_DELETE(m_Objects2[i]);
        }
    }
};
</pre>
<p>The above example is rather tame but if you have a lot of different objects it quickly becomes ugly to look at. However with a bit of ingenuity you can become a lazier programmer. Here is the same example but then easier to read</p>
<pre class="brush: c++; ">

#include &lt;algorithm&gt;
#include &lt;vector&gt;
#define SAFE_DELETE(p) if(p) delete(p); (p)=0;
template &lt;typename T&gt; void SAFE_DELETE_FUNC(T* object) { SAFE_DELETE(object); }
class StorageObject1;
class StorageObject2;
class StorageContainer
{
    std::vector&lt;StorageObject1*&gt; m_Objects1;
    std::vector&lt;StorageObject2*&gt; m_Objects2;
public:
    ~StorageContainer()
    {
        std::for_each(m_Objects1.begin(), m_Objects1.end(), SAFE_DELETE_FUNC&lt;StorageObject1&gt;);
        std::for_each(m_Objects2.begin(), m_Objects2.end(), SAFE_DELETE_FUNC&lt;StorageObject2&gt;);
    }
}
</pre>
<p>Of course you can make the function even a bit smarter so that you don't have to write the start and end iterators, but I prefer it like this.</br> Here you can find the other versions of STL algorithm: <a href="http://www.cplusplus.com/reference/algorithm/">http://www.cplusplus.com/reference/algorithm/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/02/23/stl-algorithms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
