<?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>Equivalence &#187; C#</title>
	<atom:link href="http://equivalence.co.uk/archives/category/c/feed" rel="self" type="application/rss+xml" />
	<link>http://equivalence.co.uk</link>
	<description>Technical Blog for Software Developers</description>
	<lastBuildDate>Wed, 04 Apr 2012 22:32:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>charting success</title>
		<link>http://equivalence.co.uk/archives/1014</link>
		<comments>http://equivalence.co.uk/archives/1014#comments</comments>
		<pubDate>Mon, 23 Mar 2009 15:55:11 +0000</pubDate>
		<dc:creator>Gregg</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[charts]]></category>
		<category><![CDATA[google chart sharp]]></category>
		<category><![CDATA[google charts]]></category>

		<guid isPermaLink="false">http://www.equivalence.co.uk/?p=1014</guid>
		<description><![CDATA[In my continued exploration of C# I recently had the opportunity to investigate the Google Chart API using Google Chart Sharp. Both the C# API and Google Chart itself are great. For those unfamiliar with Google Chart here is a quick summary. Google Chart allows you to dynamically generate many of the popular types of [...]]]></description>
			<content:encoded><![CDATA[<p>In my continued exploration of C# I recently had the opportunity to investigate the <a href="http://code.google.com/apis/chart/">Google Chart API</a> using <a href="http://code.google.com/p/googlechartsharp/">Google Chart Sharp</a>. Both the C# API and Google Chart itself are great. For those unfamiliar with Google Chart here is a quick summary.</p>
<p>Google Chart allows you to dynamically generate many of the popular types of chart &#8211; currently the API includes support for Line Charts, Bar Charts, Pie Charts, Venn Diagrams, plus many more. Check out the full list of chart types <a href="http://code.google.com/apis/chart/types.html">here</a>.</p>
<p>Charts are generated via a GET request using a simple URL, where various GET parameters can be supplied to customize the chart. For example, to construct a pie chart that describes web browser usage for a particular page in which FireFox has 60%, and IE 40% of the total views, we use the following URL:</p>
<p><code>http://chart.apis.google.com/chart?cht=p3&amp;chd=t:60,40&amp;chs=250x100&amp;chl=FireFox|IE</code></p>
<p>Typing this URL into your browser will show the chart below:</p>
<div class="wp-caption aligncenter" style="width: 260px"><img title="Pie chart generated using Google Charts API" src="http://chart.apis.google.com/chart?cht=p3&amp;chd=t:60,40&amp;chs=250x100&amp;chl=FireFox|IE" alt="Pie Chart with two data points" width="250" height="100" /><p class="wp-caption-text">Pie Chart with two data points</p></div>
<p>I&#8217;m sure many of you will recognise the chart design from Google Analytics.</p>
<p>Not only is the Chart API free to use (but not to abuse!), it also generates pretty nifty looking charts.</p>
<p>The charts can also be customised in many different ways including size, colour, axis, etc. Check out the documentation for this on the Google Chart API page linked to above. To show how simple it is to change the colours, take a look at the chart below:</p>
<div class="wp-caption aligncenter" style="width: 260px"><img title="Pie chart with custom colors" src="http://chart.apis.google.com/chart?cht=p3&amp;chd=t:60,40&amp;chs=250x100&amp;chl=FireFox|IE&amp;chco=9913CE,D3A4E5" alt="Pie Chart with custom colours" width="250" height="100" /><p class="wp-caption-text">Pie Chart with custom colours</p></div>
<p>Here the only change required to add custom colours is an additional HTML GET parameter &#8211; I simply added <code>chco=9913CE,D3A4E5</code> to the end of the URL given above.</p>
<p>Now on to the C# side of things.</p>
<p>As you can probably guess, the C# wrapper for Google Chart simply generates a URL. For example, to create the chart above using our new colour scheme we do the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">PieChart chart <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> PieChart<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">250</span>, <span style="color: #FF0000;">100</span>, PieChartType<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreeD</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
chart<span style="color: #008000;">.</span><span style="color: #0000FF;">SetData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">int</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #FF0000;">60</span>, <span style="color: #FF0000;">40</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
chart<span style="color: #008000;">.</span><span style="color: #0000FF;">SetPieChartLabels</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;FireFox&quot;</span>, <span style="color: #666666;">&quot;IE&quot;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
chart<span style="color: #008000;">.</span><span style="color: #0000FF;">SetDatasetColors</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;9913CE&quot;</span>, <span style="color: #666666;">&quot;D3A4E5&quot;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> url<span style="color: #008000;">=</span> chart<span style="color: #008000;">.</span><span style="color: #0000FF;">GetUrl</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>You can then use the URL directly in an HTML document or download the image locally using the following code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">WebRequest request <span style="color: #008000;">=</span> WebRequest<span style="color: #008000;">.</span><span style="color: #0000FF;">Create</span><span style="color: #008000;">&#40;</span>url<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
WebResponse response <span style="color: #008000;">=</span> request<span style="color: #008000;">.</span><span style="color: #0000FF;">GetResponse</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Image image <span style="color: #008000;">=</span> Image<span style="color: #008000;">.</span><span style="color: #0000FF;">FromStream</span><span style="color: #008000;">&#40;</span>response<span style="color: #008000;">.</span><span style="color: #0000FF;">GetResponseStream</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
image<span style="color: #008000;">.</span><span style="color: #0000FF;">Save</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;mychart.png&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Yep it&#8217;s that easy. The other charts can be created just as quickly in both the Google Chart API and also with the C# wrapper.  So if you are looking to create good looking charts and don&#8217;t want to pay much (any) money I suggest that you check this out.</p>
]]></content:encoded>
			<wfw:commentRss>http://equivalence.co.uk/archives/1014/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>dynamic queries with LINQ</title>
		<link>http://equivalence.co.uk/archives/819</link>
		<comments>http://equivalence.co.uk/archives/819#comments</comments>
		<pubDate>Tue, 10 Mar 2009 21:56:03 +0000</pubDate>
		<dc:creator>Gregg</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[dynamic LINQ query]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Expressions]]></category>
		<category><![CDATA[where parameters]]></category>

		<guid isPermaLink="false">http://www.equivalence.co.uk/?p=819</guid>
		<description><![CDATA[So, I&#8217;m a master C# programmer having been using it for a grand total of 4 weeks! My learning process began by ignoring the provincial and proverbial &#8220;Hello World&#8221; program, and instead I decided to learn the language features that are particular to C#. As it happens, C# has quite a few modern language features [...]]]></description>
			<content:encoded><![CDATA[<p>So, I&#8217;m a master C# programmer having been using it for a grand total of 4 weeks! My learning process began by ignoring the provincial and proverbial &#8220;Hello World&#8221; program, and instead I decided to learn the language features that are particular to C#.</p>
<p>As it happens, C# has quite a few modern language features that Java is sadly lacking (I won&#8217;t go into this here, but a comparison between the two is something I plan to blog about in the future). Along with many other new features, C# 3.0 gave us LINQ, which will be the topic of this post.</p>
<p>LINQ, I think, is reasonably straightforward to both understand and comprehend. Basic queries are extremely simple to create, and LINQ almost gives C# a functional programming feel. An example LINQ query is shown below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">from</span> s <span style="color: #0600FF; font-weight: bold;">in</span> students <span style="color: #0600FF; font-weight: bold;">where</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">classyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2008&quot;</span> <span style="color: #008000;">&amp;&amp;</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">courseyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2&quot;</span> <span style="color: #0600FF; font-weight: bold;">select</span> s<span style="color: #008000;">;</span></pre></div></div>

<p>That said, not everything is plain sailing with LINQ. The application I was writing required the where condition in my LINQ statement be dynamic. That is, a column specified in the where condition is only known at runtime. Achieving this functionality using the syntax shown above is not possible (which if you try it out I&#8217;m sure it will be clear why). To achieve this functionality the learning curve soon ramped up.</p>
<p>If you have searched on Google for dynamic queries in LINQ, you probably found these two articles, ScottGu&#8217;s <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx">Dynamic Linq</a> and tomasp.net&#8217;s <a href="http://tomasp.net/articles/dynamic-linq-queries.aspx">Building LINQ Queries at Runtime in C#</a> - there were others, but few proved to be much help. ScottGu&#8217;s article was very good, and in essence solved my problem, but didn&#8217;t really help me understand the problem. The second article just went way over my head. Why? Well it came down to another new feature of C# that I didn&#8217;t know about, which was <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx">Expressions and Expression Trees</a>, which, as it turns out, proved to be the key to solving this problem.</p>
<p>In addition to using the query syntax with LINQ (as shown above), you can also use query expressions. Query expressions are simply static methods that allow you to express a LINQ query. The example given above can be rewritten as follows using a query expression:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">student<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">courseyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2008&quot;</span> <span style="color: #008000;">&amp;&amp;</span> s<span style="color: #008000;">.</span><span style="color: #0000FF;">classyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>On first looking at this example, it is still not obvious how runtime queries can be generated using query expressions. However, by taking a look at the type of the argument passed to <code>Where</code> helps us out:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>TSource, <span style="color: #6666cc; font-weight: bold;">bool</span><span style="color: #008000;">&gt;&gt;</span> predicate</pre></div></div>

<p>After some thought, this begins to make sense. The <code>Where</code> method takes a lambda expression whose parameter is of type <code>TSource</code> and returns a boolean. Therefore, surely we can create a lambda expression dynamically by building an expression tree for it? And yes, this is exactly what you are supposed to do.</p>
<p>C# experts are probably howling at me now and can&#8217;t understand why it took me so long to get there. However, this article is not aimed at you; it&#8217;s aimed at a newbie like me, and is simply trying to detail my thought process.</p>
<p>So now it was time to learn about Expression Trees.</p>
<p>Although I understood the concept of Expression Trees, they took a bit of getting used to &#8211; just don&#8217;t give up if you are struggling with it. In order to show how we can use Expression Trees to create dynamic queries, I will jump straight in with the code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>student, <span style="color: #6666cc; font-weight: bold;">bool</span><span style="color: #008000;">&gt;&gt;</span> GetWhereLambda<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> courseyear,
                                                      <span style="color: #6666cc; font-weight: bold;">string</span> classyear,
                                                      <span style="color: #6666cc; font-weight: bold;">string</span> myDynaColumn<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    ParameterExpression param <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameter</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>student<span style="color: #008000;">&#41;</span>, <span style="color: #666666;">&quot;s&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    Expression courseExpr <span style="color: #008000;">=</span> GetEqualsExpr<span style="color: #008000;">&#40;</span>param, <span style="color: #666666;">&quot;courseyear&quot;</span>, courseyear<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Expression classExpr <span style="color: #008000;">=</span> GetEqualsExpr<span style="color: #008000;">&#40;</span>param, <span style="color: #666666;">&quot;classyear&quot;</span>, classyear<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Expression cond <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">And</span><span style="color: #008000;">&#40;</span>courseExpr, classExpr<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// This is where we create the expression for the dynamic column.</span>
    <span style="color: #008080; font-style: italic;">// Obviously the value could have been dynamic as well but it </span>
    <span style="color: #008080; font-style: italic;">// saves a little visual complexity this way.</span>
    cond <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">And</span><span style="color: #008000;">&#40;</span>cond, GetEqualsExpr<span style="color: #008000;">&#40;</span>param, myDynaColumn, <span style="color: #666666;">&quot;YES&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Lambda</span><span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>student, <span style="color: #6666cc; font-weight: bold;">bool</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#40;</span>cond, param<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> Expression GetEqualsExpr<span style="color: #008000;">&#40;</span>ParameterExpression param,
                                 <span style="color: #6666cc; font-weight: bold;">string</span> property,
                                 <span style="color: #6666cc; font-weight: bold;">string</span> value<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     Expression prop <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Property</span><span style="color: #008000;">&#40;</span>param, property<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     Expression val <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Constant</span><span style="color: #008000;">&#40;</span>value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
     <span style="color: #0600FF; font-weight: bold;">return</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Equal</span><span style="color: #008000;">&#40;</span>prop, val<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Seeing the code makes this look pretty simple, but there are quite a few concepts that a programmer new to C# has to get the hang of. However, let&#8217;s just step through the code &#8211; well one clause anyway, the rest follows from that.</p>
<p>Let&#8217;s look at how the clause <code>(s.courseyear == "2008")</code>, from out original where condition, converts to an Expression. We first create a parameter expression (Line 5), that is, the argument (parameter) supplied to the lambda expression (this parameter must be used for all sub-expressions that make up the lambda expression). Next, we need to create an expression to represent the right hand-side (<code>s.courseyear</code>) and left hand-side (<code>"2008"</code>) of our clause. Since <code>courseyear</code> is a property of <code>student</code> (property as in <a href="http://msdn.microsoft.com/en-us/library/x9fsa0sw(VS.80).aspx">C# property</a> &#8211; think neat getters and setters) we create a property expression, i.e. <code>prop = Expression.Property(param, "courseyear")</code>, and as <code>"2008"</code> is really a constant, we create constant expression using <code>value = Expression.Constant("2008")</code>. Finally, we want to express the fact that the property should be equal to the constant in our query, we use the <code>Expression.Equal(prop,value)</code>. That&#8217;s it. Essentially what expressions do is model our code as data.</p>
<p>Now it becomes obvious how we can represent a column in the where clause that is supplied at runtime &#8211; we simply create a property expression, as shown at Line 20, where <code>property</code> is the dynamic column name specified at runtime.</p>
<p>To combine the clauses in the where condition we simply use <code>Expression.And</code>, as shown in Lines 9 and 11. The resulting expression and the parameter is then used to create a lambda expression, which is in turn passed as an argument to <code>Where</code>, e.g.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>student, <span style="color: #6666cc; font-weight: bold;">bool</span><span style="color: #008000;">&gt;&gt;</span> myLambda <span style="color: #008000;">=</span> GetWhereLambda<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;2008&quot;</span>, <span style="color: #666666;">&quot;2&quot;</span>, <span style="color: #666666;">&quot;active&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
IEnumerable<span style="color: #008000;">&lt;</span>student<span style="color: #008000;">&gt;</span> filtered <span style="color: #008000;">=</span> students<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>myLambda<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>There you have it. It&#8217;s not that straightforward for those new to C# like me, but hopefully this article at least gives some code that can easily be used by people in the same position as I was.</p>
]]></content:encoded>
			<wfw:commentRss>http://equivalence.co.uk/archives/819/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>generating a unique range of numbers</title>
		<link>http://equivalence.co.uk/archives/719</link>
		<comments>http://equivalence.co.uk/archives/719#comments</comments>
		<pubDate>Thu, 26 Feb 2009 11:29:00 +0000</pubDate>
		<dc:creator>Gregg</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[random number]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[unique ids]]></category>

		<guid isPermaLink="false">http://www.equivalence.co.uk/?p=719</guid>
		<description><![CDATA[Often at work I find the need to generate a set of n unique integers in a specified range. In order to do this as efficiently and as easily as possible, I created a small C# class, which a colleague thought may be of general interest. Hence, I&#8217;m posting it here. I&#8217;m sure someone else [...]]]></description>
			<content:encoded><![CDATA[<p>Often at work I find the need to generate a set of <code>n</code> unique integers in a specified range. In order to do this as efficiently and as easily as possible, I created a small C# class, which a colleague thought may be of general interest. Hence, I&#8217;m posting it here. I&#8217;m sure someone else has come up with a similar (or better) way to do this in the past, but I&#8217;m sharing my way regardless <img src='http://equivalence.co.uk/wp-includes/images/smilies/icon_biggrin.gif' alt=':-D' class='wp-smiley' />  .</p>
<p>The code is shown below (and you <a href='http://www.equivalence.co.uk/wp-content/uploads/2009/02/uniquesetgenerator.cs'>download the C# class here</a>):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #6666cc; font-weight: bold;">class</span> UniqueSetGenerator
 <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> store_<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> size_<span style="color: #008000;">;</span>
      <span style="color: #0600FF; font-weight: bold;">private</span> Random random_<span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #0600FF; font-weight: bold;">public</span> UniqueSetGenerator<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> size, <span style="color: #6666cc; font-weight: bold;">int</span> start<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          size_ <span style="color: #008000;">=</span> size<span style="color: #008000;">;</span>
          store_ <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span>size<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
          random_ <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Random<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
          PopulateArray<span style="color: #008000;">&#40;</span>start<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
&nbsp;
      <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> PopulateArray<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> start<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> size_<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
              store_<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> start<span style="color: #008000;">++;</span>
      <span style="color: #008000;">&#125;</span>
&nbsp;
      <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> Delete<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> pos<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          <span style="color: #6666cc; font-weight: bold;">int</span> val <span style="color: #008000;">=</span> store_<span style="color: #008000;">&#91;</span>pos<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
          store_<span style="color: #008000;">&#91;</span>pos<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> store_<span style="color: #008000;">&#91;</span><span style="color: #008000;">--</span>size_<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
          <span style="color: #0600FF; font-weight: bold;">return</span> val<span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
&nbsp;
      <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> GetRandomNumber<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>size_ <span style="color: #008000;">&lt;=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
             <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
&nbsp;
          <span style="color: #0600FF; font-weight: bold;">return</span> Delete<span style="color: #008000;">&#40;</span>random_<span style="color: #008000;">.</span><span style="color: #0000FF;">Next</span><span style="color: #008000;">&#40;</span>size_<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
 <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>I think it&#8217;s pretty easy to see how this works, so I will not go into it in much detail discussing it, but the sequence of figures below shows the basic operations.</p>
<p><div id="attachment_735" class="wp-caption aligncenter" style="width: 460px"><img src="http://www.equivalence.co.uk/wp-content/uploads/2009/02/unique1.jpg" alt="First populate the array with the values." title="Example part 1" width="450" height="57" class="size-full wp-image-735" /><p class="wp-caption-text">First populate the array with the values.</p></div><br />
<div id="attachment_737" class="wp-caption aligncenter" style="width: 460px"><img src="http://www.equivalence.co.uk/wp-content/uploads/2009/02/unique2.jpg" alt="Use the Random class to obtain our first random number - in this case 6. Now copy the value at position size_ in the array to position 6, and decrement size_. Note not we don&#039;t actually delete anything from the array." title="Example part 2" width="450" height="57" class="size-full wp-image-737" /><p class="wp-caption-text">Use the <code>Random</code> class to obtain our first random number - in this case 6. Now copy the value at position <code>size_</code> in the array to position 6, and decrement <code>size_</code>. <em>Note</em>: not we don't actually delete anything from the array.</p></div><br />
<div id="attachment_740" class="wp-caption aligncenter" style="width: 460px"><img src="http://www.equivalence.co.uk/wp-content/uploads/2009/02/unique3.jpg" alt="We then use the Random class to generate another random number in our reduced range - in this case 3. We then copy the value at position size_ (i.e. 9) to position 3, and then decrement the size_ count as before. This process continues until size_ is reduced to 0." title="Example part 3" width="450" height="60" class="size-full wp-image-740" /><p class="wp-caption-text">We then use the <code>Random </code>class to generate another random number in our reduced range - in this case 3. We then copy the value at position <code>size_ </code>(i.e. 9) to position 3, and then decrement the <code>size_ </code>count as before. This process continues until size_ is reduced to 0.</p></div> </p>
<p>So when would you require something like this? Well, say you need to generate unique random IDs with values 1 to 10, then you can use the class as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    UniqueSetGenerator uniqueSet <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> UniqueSetGenerator<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">for</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">9</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">int</span> id <span style="color: #008000;">=</span> uniqueSet<span style="color: #008000;">.</span><span style="color: #0000FF;">GetRandomNumber</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// Now do something with the id....</span>
    <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>For the moment I have only included a C# version but I will update this post with a Java version soon.  Hope some of you find this useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://equivalence.co.uk/archives/719/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

