<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Arsalan's Musings</title>
	<atom:link href="http://softwareworks.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://softwareworks.wordpress.com</link>
	<description>Musings on Software...</description>
	<lastBuildDate>Wed, 08 Jul 2009 05:50:38 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='softwareworks.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/72dc467e3f50b6b10963192648bf685c?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Arsalan's Musings</title>
		<link>http://softwareworks.wordpress.com</link>
	</image>
			<item>
		<title>Creating an unmodifiable list from a regular old IList</title>
		<link>http://softwareworks.wordpress.com/2009/07/07/creating-an-unmodifiable-list-from-a-regular-old-ilist/</link>
		<comments>http://softwareworks.wordpress.com/2009/07/07/creating-an-unmodifiable-list-from-a-regular-old-ilist/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 16:50:27 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/?p=26</guid>
		<description><![CDATA[Your Mission
Create an unmodifiable list utility class that converts any implementation of IList interface into a list that throws exception when modified.  Take into consideration converting implementations of ArrayList&#60;T&#62;.
Give examples of useful usages of such utility class (does not have to be in code).
Do you accept this mission?
Hmmm&#8230; let&#8217;s see.

 Why would anyone want to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=26&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1><span style="color:#003300;"><strong>Your Mission</strong></span></h1>
<p>Create an unmodifiable list utility class that converts any implementation of IList interface into a list that throws exception when modified.  Take into consideration converting implementations of ArrayList&lt;T&gt;.<br />
Give examples of useful usages of such utility class (does not have to be in code).</p>
<h2><em><strong><span style="color:#ff0000;">Do you accept this mission?</span></strong></em></h2>
<h2><strong><em><span style="color:#333300;">Hmmm&#8230; let&#8217;s see.</span></em></strong></h2>
<hr />
<h2><span style="color:#003300;"> Why would anyone want to use a list that cannot be modified?</span></h2>
<p>Consider the following scenarios.<br />
1. Sending an Employee list to an accounting system using RPC, ensuring the list cannot be changed. In such a case, a class can be passed to the Sealed list constructor to get a sealed class and passed on to the remote system.</p>
<p>2. If the list is bound to a control on a Web Form or Windows Form and the control has edit functionality, if the user edits the form and the list could be modified, the sealed list class can be used.</p>
<p>3. A deck of cards [fixed number of items] should not allow addition of other cards in a card game.</p>
<p>There maybe many such cases where you want the collection to stay as-is.</p>
<hr />
<h2>Design</h2>
<p>Let&#8217;s design the solution using the Decorator design pattern. The decorator pattern is quite fascinating as it creates a paradigm of wrapping increasingly specialized behavior to objects while keeping their base type uniform. Hence, one type <em>decorates</em> another and effectively changes the behavior without modifying existing code. Superb!</p>
<p><a href="http://en.wikipedia.org/wiki/Decorator_pattern">Wikipedia </a>has this nice diagram describing our Decorator pattern:<br />
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/4/42/Decorator_pattern_in_LePUS3.png/400px-Decorator_pattern_in_LePUS3.png" alt="Decorator Pattern" /></p>
<hr />We will start creating our SealedList class as follows.</p>
<pre class="brush: csharp;">
private IList list;
private const string exceptionMessage = &quot;List cannot be modified.&quot;;

public SealedList(IList list)
{
this.list = list;
}
</pre>
<p>We will make sure that our custom class implements the IList interface. We will not need to implement all the required methods in IList simply throwing a NotImplementedException for methods not implemented. We can always implement them later, if needed. Here are the IList methods.</p>
<pre class="brush: csharp;">
public int Add(object value)
{
throw new InvalidOperationException(exceptionMessage);
}

public void Clear()
{
throw new InvalidOperationException(exceptionMessage);
}

public bool Contains(object value)
{
return list.Contains(value);
}

public int IndexOf(object value)
{
return list.IndexOf(value);
}

public void Insert(int index, object value)
{
throw new InvalidOperationException(exceptionMessage);
}

public bool IsFixedSize
{
get
{
return list.IsFixedSize;
}
}

public bool IsReadOnly
{
get
{
return list.IsReadOnly;
}
}

public void Remove(object value)
{
throw new InvalidOperationException(exceptionMessage);
}

public void RemoveAt(int index)
{
throw new InvalidOperationException(exceptionMessage);
}

public object this[int index]
{
get
{
return list[index];
}
set
{
throw new InvalidOperationException(exceptionMessage);
}
}
</pre>
<p>Since the IList interface itself implements the ICollection and IEnumerable interfaces, we have to implement methods required by those interfaces as well.</p>
<pre class="brush: csharp;">
#region ICollection Members

public void CopyTo(Array array, int index)
{
list.CopyTo(array, index);
}

public int Count
{
get
{
return list.Count;
}
}

public bool IsSynchronized
{
get
{
return list.IsSynchronized;
}
}

public object SyncRoot
{
get
{
return list.SyncRoot;
}
}

#endregion

#region IEnumerable Members

public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}

#endregion
</pre>
<p>That should do it as far as creating the sealed list is concerned. But we still haven&#8217;t verified that this works correctly. For that, we will have to create an unsealed list and then try to seal it by decorating it with our SealedList and unit test the heck out of it&#8230; stay tuned for the exciting conclusion in the next post!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=26&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2009/07/07/creating-an-unmodifiable-list-from-a-regular-old-ilist/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/en/thumb/4/42/Decorator_pattern_in_LePUS3.png/400px-Decorator_pattern_in_LePUS3.png" medium="image">
			<media:title type="html">Decorator Pattern</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing unit tests for the Jumble problem</title>
		<link>http://softwareworks.wordpress.com/2009/07/07/writing-unit-tests-for-the-jumble-problem/</link>
		<comments>http://softwareworks.wordpress.com/2009/07/07/writing-unit-tests-for-the-jumble-problem/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 16:24:10 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/?p=22</guid>
		<description><![CDATA[Let&#8217;s write some unit tests for the jumble problem solved in the previous post.
We will create some setup and teardown code that will be executed before and after running each test, respectively. We will use the NUnit framework to write our tests. To run the tests we can either use the NUnit Graphical User Interface [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=22&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Let&#8217;s write some unit tests for the jumble problem solved in the <a title="Jumble solver" href="http://softwareworks.wordpress.com/2009/07/07/determine-all-…ble-c-solution/" target="_self">previous post</a>.</p>
<p>We will create some setup and teardown code that will be executed before and after running each test, respectively. We will use the NUnit framework to write our tests. To run the tests we can either use the NUnit Graphical User Interface or the excellent Visual Studio plugin TestDriven.Net which allows inline debugging of our tests. Way cool!</p>
<pre>
<pre class="brush: csharp;">
#region ----- Private Members -----
JumbleSolver simpleJumble;
JumbleSolver jumbleWithWordDictionaryFile;
const string dictionaryFilePath = @&quot;dictionary.txt&quot;;
#endregion

#region ----- Setup and Teardown -----
[SetUp]
public void Setup()
{
this.simpleJumble = new JumbleSolver();
this.jumbleWithWordDictionaryFile = new JumbleSolver(dictionaryFilePath);
}

[TearDown]
public void TearDown()
{
this.simpleJumble = null;
this.jumbleWithWordDictionaryFile = null;
}
#endregion
</pre>
</pre>
<h2>Tests</h2>
<p>I often like to divide the tests into Happy Path and Negative Test regions.</p>
<h3>Happy Path Tests</h3>
<pre>
<pre class="brush: csharp;">
#region ---------- Happy Path Tests ----------
[Test]
public void SimpleTestIsWordAMatch3Letters()
{
string word = &quot;ran&quot;;
string jumble = &quot;rndlae&quot;;
bool isMatch = simpleJumble.IsWordAMatch(word, jumble);
Assert.AreEqual(true, isMatch, &quot;The IsWordAMatch method failed for a 3 letter combination&quot;);
}

[Test]
public void SimpleTestIsWordAMatch4Letters()
{
string word = &quot;lean&quot;;
string jumble = &quot;rndlae&quot;;
bool isMatch = simpleJumble.IsWordAMatch(word, jumble);
Assert.AreEqual(true, isMatch, &quot;The IsWordAMatch method failed for a 3 letter combination&quot;);
}

[Test]
public void SimpleTestIsWordAMatch5Letters()
{
string word = &quot;ldean&quot;;
string jumble = &quot;rndlae&quot;;
bool isMatch = simpleJumble.IsWordAMatch(word, jumble);
Assert.AreEqual(true, isMatch, &quot;The IsWordAMatch method failed for a 3 letter combination&quot;);
}

[Test]
public void SimpleTestIsWordAMatch6Letters()
{
string word = &quot;lander&quot;;
string jumble = &quot;rndlae&quot;;
bool isMatch = simpleJumble.IsWordAMatch(word, jumble);
Assert.AreEqual(true, isMatch, &quot;The IsWordAMatch method failed for a 3 letter combination&quot;);
}

[Test]
public void SimpleTestCountMatchingWords()
{
List dictionary = new List();
dictionary.Add(&quot;ace&quot;);
dictionary.Add(&quot;are&quot;);
dictionary.Add(&quot;dak&quot;);
dictionary.Add(&quot;ross&quot;);
dictionary.Add(&quot;rosy&quot;);
dictionary.Add(&quot;rynd&quot;);
dictionary.Add(&quot;rddnol&quot;);;
dictionary.Add(&quot;rndle&quot;);
dictionary.Add(&quot;rlead&quot;);

simpleJumble.CurrentJumble = &quot;rndlae&quot;;
simpleJumble.WordDictionary = dictionary;
bool didCountSucceed = simpleJumble.CountMatchingWords();
Assert.AreEqual(true, didCountSucceed, &quot;The CountMatchingWords method failed for the jumble 'rndlae'&quot;);
}

[Test]
public void MajorTestCountMatchingWords1()
{
jumbleWithWordDictionaryFile.CurrentJumble = &quot;nuetbr&quot;;
bool didCountSucceed = jumbleWithWordDictionaryFile.CountMatchingWords();
Assert.AreEqual(true, didCountSucceed, &quot;The CountMatchingWords method failed for the jumble 'rndlae'&quot;);

string expectedOutput = &quot;23, 29, 12, 4&quot;;
string actualOutput = jumbleWithWordDictionaryFile.MatchCount3Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount4Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount5Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount6Letters;
Assert.AreEqual(expectedOutput, actualOutput, &quot;The CountMatchingOutput method calculated in accurate results.&quot;);
}

[Test]
public void MajorTestCountMatchingWords2()
{
jumbleWithWordDictionaryFile.CurrentJumble = &quot;zrftmx&quot;;
bool didCountSucceed = jumbleWithWordDictionaryFile.CountMatchingWords();
Assert.AreEqual(true, didCountSucceed, &quot;The CountMatchingWords method failed for the jumble 'rndlae'&quot;);

string expectedOutput = &quot;0, 0, 0, 0&quot;;
string actualOutput = jumbleWithWordDictionaryFile.MatchCount3Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount4Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount5Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount6Letters;
Assert.AreEqual(expectedOutput, actualOutput, &quot;The CountMatchingOutput method calculated inaccurate results.&quot;);
}

[Test]
public void SimpleTestCountMatchingWordsNoMatchesFound()
{
List dictionary = new List();
dictionary.Add(&quot;ace&quot;);
dictionary.Add(&quot;are&quot;);
dictionary.Add(&quot;dak&quot;);
dictionary.Add(&quot;ross&quot;);
dictionary.Add(&quot;rosy&quot;);
dictionary.Add(&quot;rynd&quot;);
dictionary.Add(&quot;rddnol&quot;); ;
dictionary.Add(&quot;rndle&quot;);
dictionary.Add(&quot;rlead&quot;);

simpleJumble.CurrentJumble = &quot;xyzzqw&quot;;
simpleJumble.WordDictionary = dictionary;
bool didCountSucceed = simpleJumble.CountMatchingWords();
Assert.AreEqual(true, didCountSucceed, &quot;The CountMatchingWords method failed for the jumble 'xyzzqw'&quot;);

string expectedOutput = &quot;0, 0, 0, 0&quot;;
string actualOutput = jumbleWithWordDictionaryFile.MatchCount3Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount4Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount5Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount6Letters;
Assert.AreEqual(expectedOutput, actualOutput, &quot;The CountMatchingOutput method calculated inaccurate results.&quot;);
}

[Test]
public void MajorTestCountMatchingWordsNoMatchesFound()
{
jumbleWithWordDictionaryFile.CurrentJumble = &quot;xyzzqw&quot;;
bool didCountSucceed = jumbleWithWordDictionaryFile.CountMatchingWords();
Assert.AreEqual(true, didCountSucceed, &quot;The CountMatchingWords method failed for the jumble 'xyzzqw'&quot;);

string expectedOutput = &quot;0, 0, 0, 0&quot;;
string actualOutput = jumbleWithWordDictionaryFile.MatchCount3Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount4Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount5Letters.ToString();
actualOutput += &quot;, &quot;;
actualOutput += jumbleWithWordDictionaryFile.MatchCount6Letters;
Assert.AreEqual(expectedOutput, actualOutput, &quot;The CountMatchingOutput method calculated inaccurate results.&quot;);
}
#endregion
</pre>
</pre>
<h3>Negative Tests</h3>
<pre>
<pre class="brush: csharp;">
#region ---------- Negative Tests ----------
[Test]
public void SimpleNegativeTestCountMatchingWordsSpaceInJumble()
{
List dictionary = new List();
dictionary.Add(&quot;ace&quot;);
dictionary.Add(&quot;are&quot;);
dictionary.Add(&quot;dak&quot;);
dictionary.Add(&quot;ross&quot;);
dictionary.Add(&quot;rosy&quot;);
dictionary.Add(&quot;rynd&quot;);
dictionary.Add(&quot;rddnol&quot;); ;
dictionary.Add(&quot;rndle&quot;);
dictionary.Add(&quot;rlead&quot;);

// this assignment should be denied leaving the CurrentJumble property pointing to an empty string
simpleJumble.CurrentJumble = &quot;rn dal@#$@$ae&quot;;
simpleJumble.WordDictionary = dictionary;
bool didCountSucceed = simpleJumble.CountMatchingWords();
Assert.AreEqual(false, didCountSucceed, &quot;The CountMatchingWords method failed to recognize malformed jumble 'rn dal@#$@$ae'&quot;);
}

[Test]
public void SimpleNegativeTestCountMatchingWordsSpaceInWord()
{
List dictionary = new List();
dictionary.Add(&quot;ace&quot;);
dictionary.Add(&quot;are&quot;);
dictionary.Add(&quot;dak&quot;);
dictionary.Add(&quot;ross&quot;);
dictionary.Add(&quot;rosy&quot;);
dictionary.Add(&quot;ry nd&quot;);
dictionary.Add(&quot;rddnol&quot;); ;
dictionary.Add(&quot;rndle&quot;);
dictionary.Add(&quot;rlead&quot;);

simpleJumble.CurrentJumble = &quot;naetcr&quot;;
simpleJumble.WordDictionary = dictionary;
bool didCountSucceed = simpleJumble.CountMatchingWords();
Assert.AreEqual(false, didCountSucceed, &quot;The CountMatchingWords method failed to recognize malformed word 'ry nd'&quot;);
}

[Test]
public void SimpleNegativeTestCountMatchingWordsCommaEndedJumble()
{
List dictionary = new List();
dictionary.Add(&quot;ace&quot;);
dictionary.Add(&quot;are&quot;);
dictionary.Add(&quot;dak&quot;);
dictionary.Add(&quot;ronss&quot;);
dictionary.Add(&quot;roeesy&quot;);
dictionary.Add(&quot;ryndw&quot;);
dictionary.Add(&quot;rddsnol&quot;); ;
dictionary.Add(&quot;rgdlfe&quot;);
dictionary.Add(&quot;rleqad&quot;);

// this assignment should be denied leaving the CurrentJumble property pointing to an empty string
simpleJumble.CurrentJumble = &quot;rdle,&quot;;
simpleJumble.WordDictionary = dictionary;
bool didCountSucceed = simpleJumble.CountMatchingWords();
Assert.AreEqual(true, didCountSucceed, &quot;The CountMatchingWords method failed to remove comma at the end of jumble 'rndle,'&quot;);
}
#endregion
</pre>
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/22/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=22&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2009/07/07/writing-unit-tests-for-the-jumble-problem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>Determine all 3,4,5 &amp; 6-letter combinations within a jumble: C# Solution</title>
		<link>http://softwareworks.wordpress.com/2009/07/07/determine-all-345-6-letter-combinations-within-a-jumble-c-solution/</link>
		<comments>http://softwareworks.wordpress.com/2009/07/07/determine-all-345-6-letter-combinations-within-a-jumble-c-solution/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 15:32:48 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/?p=17</guid>
		<description><![CDATA[Problem: 
Given a six-letter alphabetic jumble and a dictionary of words, determine all 3,4,5 &#38; 6-letter
combinations within the jumble that are also words in the dictionary. Each letter in the jumble can be (but does not have to be) used only once per combination, however n occurrences of the same letter can be used n [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=17&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>Problem: </strong></p>
<p>Given a six-letter alphabetic jumble and a dictionary of words, determine all 3,4,5 &amp; 6-letter<br />
combinations within the jumble that are also words in the dictionary. Each letter in the jumble can be (but does not have to be) used only once per combination, however n occurrences of the same letter can be used n times. For example, given the jumble: &#8216;rlerta&#8217;, the words &#8216;tar&#8217;, &#8216;tale&#8217;, and &#8216;rear&#8217; are among the legal combinations (and &#8212; assuming they are in the dictionary &#8212; words), but &#8216;rattle&#8217; is not (there are not two t&#8217;s in the jumble).</p>
<p>Input: Six sets of data each consisting of a six-letter jumble (no spaces will be in the input), and a filename for the dictionary (the dictionary can be assumed to be in the same folder as the program, and will consist of an ascii text file with one word per line).</p>
<p>Output: the number of 3, 4, 5 &amp; 6 letter words found in each jumble.</p>
<p>Sample Input (3 sets):                   Sample Output:<br />
rndlae, dictionary.txt                   17, 34, 13, 7<br />
nuetbr, dictionary.txt                   23, 29, 12, 4<br />
zrftmx, dictionary.txt                   0, 0, 0, 0</p>
<p><strong>Dictionary can be found <a class="wpGallery" title="Dictionary for the Jumble problem" href="http://softwareworks.files.wordpress.com/2009/07/dictionary.doc" target="_blank"><em>here</em></a>.</strong></p>
<hr />
<h2><strong><span style="color:#339966;">Solution</span></strong></h2>
<p><span style="color:#339966;"><span style="color:#000080;">Let&#8217;s make this a console application. The Main method looks like the following.</span></span></p>
<p><span style="color:#339966;"><span style="color:#000080;"><br />
</span></span></p>
<pre class="brush: csharp;">
static void Main(string[] args)
{
if (args[0].ToLower().Equals(&quot;-i&quot;))
{
// Interactive Mode
InteractiveMain();
return;
}

JumbleSolver aJumbleSolver = null;
string enteredJumble =  args[0];
string enteredFileName = args[1];

if (enteredJumble.Equals(String.Empty))
{
// error in argument
Console.WriteLine(&quot;There was an error in the first argument: Jumble&quot;);
Console.WriteLine(&quot;Abandoning execution...&quot;);
throw new ArgumentException(&quot;Jumble must be a valid string&quot;);
}

else if ((enteredFileName != String.Empty) &amp;amp;&amp;amp; (File.Exists(enteredFileName)))
{
if (enteredJumble.EndsWith(&quot;,&quot;))
{
enteredJumble = enteredJumble.Remove(enteredJumble.Length - 1);
}

aJumbleSolver = new JumbleSolver(enteredJumble, enteredFileName);
}
else
{
// error in argument
Console.WriteLine(&quot;There was an error in the second argument: Dictionary&quot;);
Console.WriteLine(&quot;Abandoning execution...&quot;);
throw new ArgumentException(&quot;Dictionary must be a valid file name.&quot;);
}

// Count and display matches
if (aJumbleSolver.CountMatchingWords())
{
Console.Write(aJumbleSolver.MatchCount3Letters + &quot;, &quot;);
Console.Write(aJumbleSolver.MatchCount4Letters + &quot;, &quot;);
Console.Write(aJumbleSolver.MatchCount5Letters + &quot;, &quot;);
Console.Write(aJumbleSolver.MatchCount6Letters);
}
else
{
// There was an error in the CountMatchingWords method
Console.WriteLine(&quot;CountMatchingWords failed. Please make sure jumble does not contain space.&quot;);
}
}
</pre>
<p>If the first command line argument is valid then we call the InteractiveMain method to interact with the user.</p>
<pre class="brush: csharp;">
public static void InteractiveMain()
{
#region Setting up lists
List set1 = new List();
List set2 = new List();
List set3 = new List();
List set4 = new List();
List set5 = new List();
List set6 = new List();

set1 = Console.ReadLine().Split().ToList();
set2 = Console.ReadLine().Split().ToList();
set3 = Console.ReadLine().Split().ToList();
set4 = Console.ReadLine().Split().ToList();
set5 = Console.ReadLine().Split().ToList();
set6 = Console.ReadLine().Split().ToList();

List
&amp;gt; allSets = new List
&amp;gt;();
allSets.Add(set1);
allSets.Add(set2);
allSets.Add(set3);
allSets.Add(set4);
allSets.Add(set5);
allSets.Add(set6);
#endregion

string enteredJumble;
string enteredFileName;
JumbleSolver aJumbleSolver = null;

foreach (List set in allSets)
{
enteredJumble = set[0];
enteredFileName = set[1];
if ((enteredFileName != String.Empty) &amp;amp;&amp;amp; (File.Exists(enteredFileName)))
{
if (enteredJumble.EndsWith(&quot;,&quot;))
{
enteredJumble = enteredJumble.Remove(enteredJumble.Length - 1);
}

aJumbleSolver = new JumbleSolver(enteredJumble, enteredFileName);

// Count and display matches
if (aJumbleSolver.CountMatchingWords())
{
Console.Write(aJumbleSolver.MatchCount3Letters + &quot;, &quot;);
Console.Write(aJumbleSolver.MatchCount4Letters + &quot;, &quot;);
Console.Write(aJumbleSolver.MatchCount5Letters + &quot;, &quot;);
Console.WriteLine(aJumbleSolver.MatchCount6Letters);
}
else
{
// There was an error in the CountMatchingWords method
Console.WriteLine(&quot;CountMatchingWords failed. Please make sure jumble does not contain space.&quot;);
}
}
}

}
</pre>
<p>We define the JumbleSolver class to solve the jumble for us keeping the business logic in a separate class, potentially a separate assembly ready for reuse.</p>
<p>The constructors need 3 different flavors as follows.</p>
<pre class="brush: csharp;">
public JumbleSolver()
        {
            this.wordDictionary = new List&lt;string&gt;();
            this.matchCount3Letters = 0;
            this.matchCount4Letters = 0;
            this.matchCount5Letters = 0;
            this.matchCount6Letters = 0;
        }

        public JumbleSolver(string jumble, string dictionaryFilePath) : this()
        {
            this.CurrentJumble = jumble;
            if (File.Exists(dictionaryFilePath))
            {
                string[] allWords = File.ReadAllLines(dictionaryFilePath);
                this.wordDictionary.AddRange(allWords);
            }
        }

        public JumbleSolver(string dictionaryFilePath) : this()
        {
            this.CurrentJumble = String.Empty;
            if (File.Exists(dictionaryFilePath))
            {
                string[] allWords = File.ReadAllLines(dictionaryFilePath);
                this.wordDictionary.AddRange(allWords);
            }
        }
</pre>
<p>We will define a WordDictionary List property.</p>
<pre class="brush: csharp;">
public List&lt;/string&gt;&lt;string&gt; WordDictionary
        {
            get
            {
                return this.wordDictionary;
            }
            set
            {
                if (value is List&lt;/string&gt;&lt;string&gt;)
                {
                    this.wordDictionary = value;
                }
            }
        }
</pre>
<p>We also need a CurrentJumble property.</p>
<pre class="brush: csharp;">
public string CurrentJumble
        {
            get
            {
                return this.jumble;
            }
            set
            {
                string evaluatingValue;
                if (value is string)
                {
                    evaluatingValue = value.Trim();
                    if (!evaluatingValue.Contains(' '))
                    {
                        this.jumble = evaluatingValue;
                    }
                    else
                    {
                        this.jumble = String.Empty;
                    }
                }

            }
        }
</pre>
<p>Let&#8217;s have a method to determine if the word is a match.</p>
<pre class="brush: csharp;">
public bool IsWordAMatch(string word, string jumble)
        {
            List&lt;char&gt; jumbleLetters = new List&lt;/char&gt;&lt;char&gt;(jumble.ToCharArray());
            char[] wordLetters = word.ToCharArray();
            bool matchFound = false;

            foreach (char wordLetter in wordLetters)
            {
                if (jumbleLetters.Contains(wordLetter))
                {
                    // remove only the first occurance of wordLetter
                    jumbleLetters.Remove(wordLetter);
                    matchFound = true;
                }
                else
                {
                    matchFound = false;
                    break;
                }
            }

            return matchFound;
        }
</pre>
<p>And, finally, we want to encapsulate the counting of the matching words in a method like the following.</p>
<pre class="brush: csharp;">
public bool CountMatchingWords()
        {
            if ((this.WordDictionary.Count &lt;= 0) ||
                (this.CurrentJumble.Equals(String.Empty)))
            {
                return false;
            }

            foreach (string word in this.WordDictionary)
            {
                if (word.Trim().Contains(' '))
                {
                    // malformed word. Abort.
                    return false;
                }
                else if (IsWordAMatch(word.Trim(), CurrentJumble))
                {
                    switch (word.Trim().Length)
                    {
                        case 3:
                            this.matchCount3Letters++;
                            break;
                        case 4:
                            this.matchCount4Letters++;
                            break;
                        case 5:
                            this.matchCount5Letters++;
                            break;
                        case 6:
                            this.matchCount6Letters++;
                            break;
                        default:
                            // Ignore words that do not match the above cases
                            break;
                    }
                }
            }

            return true;
        }
</pre>
<p>In the next post, I will write some unit tests to have some degree of confidence in the accuracy of our results.</char></string></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=17&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2009/07/07/determine-all-345-6-letter-combinations-within-a-jumble-c-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>Tree Traversals For Strongly-Typed Generic Trees (C# Solution)</title>
		<link>http://softwareworks.wordpress.com/2008/02/17/tree-traversals-for-strongly-typed-generic-trees-c-solution/</link>
		<comments>http://softwareworks.wordpress.com/2008/02/17/tree-traversals-for-strongly-typed-generic-trees-c-solution/#comments</comments>
		<pubDate>Sun, 17 Feb 2008 19:04:33 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/?p=11</guid>
		<description><![CDATA[Copyright (2008) Ahmed Arsalan. All Rights Rserved.



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace TreeTraversals

{

    class TreeTraversalsLauncher

    {

        static void Main(string[] args)

        {

            TreeTraversals treeTraversal = new [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=11&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Copyright (2008) Ahmed Arsalan. All Rights Rserved.</p>
<pre>
<pre class="brush: csharp;">

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace TreeTraversals

{

    class TreeTraversalsLauncher

    {

        static void Main(string[] args)

        {

            TreeTraversals treeTraversal = new TreeTraversals();

            Console.WriteLine(&quot;The tree has been initialized to:&quot;);

            foreach (TreeNode node in treeTraversal.Tree)

            {

                Console.Write(node.NodeValue.ToString() + &quot; &quot;);

            }

            Console.WriteLine();

            treeTraversal.Traversed.Clear();

            treeTraversal.InOrderTraversal(treeTraversal.Root);

            Console.WriteLine(&quot;In Order traversal processes nodes in the following order:&quot;);

            foreach (int node in treeTraversal.Traversed)

            {

                Console.Write(node.ToString() + &quot; &quot;);

            }

            Console.WriteLine();

            treeTraversal.Traversed.Clear();

            treeTraversal.PreOrderTraversal(treeTraversal.Root);

            Console.WriteLine(&quot;Pre Order traversal processes nodes in the following order:&quot;);

            foreach (int node in treeTraversal.Traversed)

            {

                Console.Write(node.ToString() + &quot; &quot;);

            }

            Console.WriteLine();

            treeTraversal.Traversed.Clear();

            treeTraversal.PostOrderTraversal(treeTraversal.Root);

            Console.WriteLine(&quot;Post Order traversal processes nodes in the following order:&quot;);

            foreach (int node in treeTraversal.Traversed)

            {

                Console.Write(node.ToString() + &quot; &quot;);

            }

            Console.ReadKey();

        }

    }

    public class TreeNode

    {

        #region ----- Private Data Members -----

        private T nodeValue;

        private TreeNode left;

        private TreeNode right;

        #endregion

        #region ----- Public Properties -----

        public T NodeValue

        {

            get

            {

                return this.nodeValue;

            }

            set

            {

                this.nodeValue = value;

            }

        }

        public TreeNode Left

        {

            get

            {

                return this.left;

            }

            set

            {

                this.left = value;

            }

        }

        public TreeNode Right

        {

            get

            {

                return this.right;

            }

            set

            {

                this.right = value;

            }

        }

        #endregion

    }

    public class TreeTraversals

    {

        #region ----- Constructors -----

        public TreeTraversals()

        {

            root = new TreeNode();

            tree = new List&lt;treenode&gt;();

            traversed = new List();

            PopulateInitialTree();

        }

        #endregion

        #region ----- Private Data Members -----

        private TreeNode root;

        private List &lt; TreeNode &lt; int &gt; &gt; tree;

        private List traversed;

        #endregion

        #region ----- Public Properties -----

        public TreeNode Root

        {

            get

            {

                return this.root;

            }

        }

        public List Traversed

        {

            get

            {

                return this.traversed;

            }

        }

        public List &lt; TreeNode &lt; int &gt; &gt; Tree &gt;

        {

            get

            {

                return this.tree;

            }

        }

        #endregion

        #region ----- Private Methods -----

        private void PopulateInitialTree()

        {

            TreeNode node8 = new TreeNode();

            node8.NodeValue = 99;

            node8.Left = null;

            node8.Right = null;

            TreeNode node7 = new TreeNode();

            node7.NodeValue = 62;

            node7.Left = null;

            node7.Right = null;

            TreeNode node6 = new TreeNode();

            node6.NodeValue = 4;

            node6.Left = node7;

            node6.Right = node8;

            TreeNode node5 = new TreeNode();

            node5.NodeValue = 100;

            node5.Left = null;

            node5.Right = null;

            TreeNode node4 = new TreeNode();

            node4.NodeValue = 68;

            node4.Left = null;

            node4.Right = null;

            TreeNode node3 = new TreeNode();

            node3.NodeValue = 151;

            node3.Left = null;

            node3.Right = node5;

            TreeNode node2 = new TreeNode();

            node2.NodeValue = 10;

            node2.Left = node4;

            node2.Right = null;

            TreeNode node1 = new TreeNode();

            node1.NodeValue = 6;

            node1.Left = node2;

            node1.Right = node3;

            root.NodeValue = 5;

            root.Left = node1;

            root.Right = node6;

            this.tree.Add(root);

            this.tree.Add(node1);

            this.tree.Add(node2);

            this.tree.Add(node3);

            this.tree.Add(node4);

            this.tree.Add(node5);

            this.tree.Add(node6);

            this.tree.Add(node7);

            this.tree.Add(node8);

        }

        #endregion

        #region ----- Public Methods -----

        public void InOrderTraversal(TreeNode root)

        {

            if (root == null) return;

            InOrderTraversal(root.Left);

            Traversed.Add(root.NodeValue);

            InOrderTraversal(root.Right);

        }

        public void PreOrderTraversal(TreeNode root)

        {

            if (root == null) return;

            Traversed.Add(root.NodeValue);

            PreOrderTraversal(root.Left);

            PreOrderTraversal(root.Right);

        }

        public void PostOrderTraversal(TreeNode root)

        {

            if (root == null) return;

            PostOrderTraversal(root.Right);

            Traversed.Add(root.NodeValue);

            PostOrderTraversal(root.Left);

        }

        #endregion

    }

}

}</pre>
</treenode></pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=11&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/02/17/tree-traversals-for-strongly-typed-generic-trees-c-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>Count prime numbers in a range (C# Solution)</title>
		<link>http://softwareworks.wordpress.com/2008/01/21/count-prime-numbers-in-a-range-c-solution/</link>
		<comments>http://softwareworks.wordpress.com/2008/01/21/count-prime-numbers-in-a-range-c-solution/#comments</comments>
		<pubDate>Tue, 22 Jan 2008 00:10:47 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/2008/01/21/count-prime-numbers-in-a-range-c-solution/</guid>
		<description><![CDATA[Problem: Given a range of integers, count the number of primes. Also list the prime numbers in the range.

using System;

namespace SolvingSmallProblems
{
    public class Program
    {
        static void Main(string[] args)
        {
      [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=10&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><span style="color:#008000;">Problem: Given a range of integers, count the number of primes. Also list the prime numbers in the range.</span></p>
<pre class="brush: csharp;">
using System;

namespace SolvingSmallProblems
{
    public class Program
    {
        static void Main(string[] args)
        {
            int defaultLowNum = 1;
            int defaultHighNum = 50;
            int lowNum, highNum;
            PrimeNumberPuzzles prime = new PrimeNumberPuzzles();

            Console.WriteLine(&quot;PRIME NUMBER COUNT PROGRAM&quot;);
            Console.WriteLine();
            Console.WriteLine(&quot;Please enter start number&quot;);
            try
            {
                lowNum =
                Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception)
            {
                lowNum = defaultLowNum;
            }

            Console.WriteLine(&quot;Please enter end number&quot;);
            try
            {
                highNum = Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception)
            {
                highNum = defaultHighNum;
            }

            if (lowNum &lt; 1)
            {
                lowNum = defaultLowNum;
            }
            if (highNum &lt; lowNum)
            {
                highNum = defaultHighNum;
            }

            int totalPrimes = prime.CountPrimes(lowNum, highNum);
            Console.WriteLine();
            Console.WriteLine(&quot;Total number of prime numers between &quot; +
                lowNum.ToString() + &quot; and &quot; + highNum.ToString() +
                &quot; is &quot; + totalPrimes + &quot;.&quot;);
            Console.ReadKey();
        }
    }

    public class PrimeNumberPuzzles
    {
        public int CountPrimes(int low, int high)
        {
            int count = 0;
            for (int num = low; num &lt;= high; num++)
            {
                if (IsPrime(num))
                {
                    Console.Write(num + &quot; &quot;);
                    count++;
                }
            }
            return count;
        }

        bool IsPrime(int num)
        {
            bool isNumPrime = true;
            if ( num == 2)
            {
                return true;
            }
            else if (num == 1)
            {
                return false;
             }
            else if (num &lt; 1)
            {
                throw new Exception(&quot;Invalid number!&quot;);
            }
            else
            {
                int remainder;
                for (int test = 2; test &lt; num - 1; test++)
                {
                    remainder = num % test;
                    if (remainder == 0)
                    {
                        isNumPrime = false;
                    }
                }
                return isNumPrime;
            }
        }
    }
}</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=10&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/01/21/count-prime-numbers-in-a-range-c-solution/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>String Problems: Reverse A String and Remove Characters From A String (C# Solution)</title>
		<link>http://softwareworks.wordpress.com/2008/01/19/string-problems-reverse-a-string-c-solution/</link>
		<comments>http://softwareworks.wordpress.com/2008/01/19/string-problems-reverse-a-string-c-solution/#comments</comments>
		<pubDate>Sun, 20 Jan 2008 04:35:40 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/2008/01/19/string-problems-reverse-a-string-c-solution/</guid>
		<description><![CDATA[Problem 1 Description: Reverse a string such that &#8220;a cat has paws&#8221; becomes &#8220;paws has cat a&#8221;.
Problem 2 Description: Remove a set of characters from a given string. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringManipulationProblems
{
    class Program
    {
        const string DEFAULT_COMMAND = &#34;ReverseString&#34;;
 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=9&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font color="#008000">Problem 1 Description: Reverse a string such that &#8220;a cat has paws&#8221; becomes &#8220;paws has cat a&#8221;.</font></p>
<p><font color="#008000">Problem 2 Description: Remove a set of characters from a given string. </font></p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringManipulationProblems
{
    class Program
    {
        const string DEFAULT_COMMAND = &quot;ReverseString&quot;;
        const string DEFAULT_ARGUMENT_1 = &quot;messages that have been in Spam more than 30 days will be automatically deleted&quot;;
        const string DEFAULT_ARGUMENT_2 = &quot;aioeu&quot;;
        static void Main(string[] args)
        {
            string commandName;
            string commandArg1;
            string commandArg2;
            if (args.Length &lt; 1)
            {
                commandName = DEFAULT_COMMAND;
                commandArg1 = DEFAULT_ARGUMENT_1;
                commandArg2 = DEFAULT_ARGUMENT_2;
            }
            else if (args.Length == 1)
            {
                commandName = args[0];
                commandArg1 = DEFAULT_ARGUMENT_1;
                commandArg2 = &quot;aioeu&quot;;
            }
            else if (args.Length == 2)
            {
                commandName = args[0];
                commandArg1 = args[1];
                commandArg2 = &quot;aioeu&quot;;
            }
            else
            {
                commandName = args[0];
                commandArg1 = args[1];
                commandArg2 = args[2];
            }

            string result = String.Empty;
            StringPuzzles puzzles = new StringPuzzles();

            switch (commandName)
            {
                case &quot;ReverseString&quot;:
                    if (commandArg1.Equals(DEFAULT_ARGUMENT_1))
                    {
                        Console.Out.Write(&quot;No string argument provided. Using default string: &quot;);
                        Console.WriteLine(DEFAULT_ARGUMENT_1);

                    }
                    Console.Out.WriteLine(&quot;About to call method &quot; + commandName);
                    result = puzzles.ReverseString(commandArg1);
                    break;

                case &quot;RemoveChars&quot;:
                    if (commandArg1.Equals(DEFAULT_ARGUMENT_1))
                    {
                        Console.Out.Write(&quot;No string argument provided. Using default string: &quot;);
                        Console.WriteLine(DEFAULT_ARGUMENT_1);

                    }
                    Console.Out.WriteLine(&quot;About to call method &quot; + commandName);
                    result = puzzles.RemoveChars(commandArg1, commandArg2);
                    break;

                default:
                    Console.Out.WriteLine(&quot;Incorrect command! Please try again.&quot;);
                    break;
            }

            Console.Out.WriteLine(&quot;The original string was:&quot;);
            Console.Out.WriteLine(commandArg1);
            Console.Out.WriteLine(&quot;The modified string is:&quot;);
            Console.Out.WriteLine(result);
            Console.Out.WriteLine(&quot;Please press ENTER to continue...&quot;);
            Console.In.ReadLine();
        }
    }

    class StringPuzzles
    {

        public string ReverseString(string inputString)
        {
            List&lt;string&gt; wordList;
            StringBuilder reversedString = new StringBuilder();

            wordList =  new List&lt;string&gt;(inputString.Split(' '));
            for (int i = wordList.Count - 1; i &gt;= 0; i--)
            {
                reversedString.Append(wordList[i] + &quot; &quot;);
            }

            return reversedString.ToString();
        }

        public string RemoveChars(string str, string remove)
        {
            List&lt;char&gt; toDelete = new List&lt;/char&gt;&lt;char&gt;();
            StringBuilder deletedStr = new StringBuilder();

            // Create a list of characters to delete from string
            toDelete.AddRange(remove.ToCharArray());

            // Create string with specified characters removed
            foreach (char c in str.ToCharArray())
            {
                if (!(toDelete.Contains(c)))
                {
                    deletedStr.Append(c);
                }
            }

            return deletedStr.ToString();
        }
    }
}
</pre>
<p></char></string></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=9&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/01/19/string-problems-reverse-a-string-c-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple zig-zag numeric spiral</title>
		<link>http://softwareworks.wordpress.com/2008/01/08/simple-zig-zag-numeric-spiral/</link>
		<comments>http://softwareworks.wordpress.com/2008/01/08/simple-zig-zag-numeric-spiral/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 20:49:36 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/2008/01/08/simple-zig-zag-numeric-spiral/</guid>
		<description><![CDATA[I propose the following problem. Take the number of columns and a series of numbers between 10 and 99 as input and create a zig-zag pattern on console output. The output should be centered so that it fills an 80 char wide screen. For example,
prompt&#62;ZigZag 3 12 45 78 48 34 67 90 23 72 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=8&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font color="#993300">I propose the following problem. Take the number of columns and a series of numbers between 10 and 99 as input and create a zig-zag pattern on console output. The output should be centered so that it fills an 80 char wide screen. For example,</font></p>
<p><font color="#993300">prompt&gt;ZigZag 3 12 45 78 48 34 67 90 23 72 67 34 56 17 32 88</font></p>
<p><font color="#993300">will give the following output:</font></p>
<p><font color="#ff0000">12<br />
                                                             45<br />
                                                                                                                               78<br />
                                                            48<br />
34<br />
                                                            67<br />
                                                                                                                               90<br />
                                                            23<br />
72 <br />
                                                             67 <br />
                                                                                                                               34<br />
                                                             56<br />
17<br />
                                                             32<br />
                                                                                                                               88</font></p>
<p><font color="#993300">&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</font></p>
<p><font color="#993300">I will try to write C# code to solve this problem below within a day or two.</font></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=8&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/01/08/simple-zig-zag-numeric-spiral/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>Adding rows and columns in a square matrix (C# Solution)</title>
		<link>http://softwareworks.wordpress.com/2008/01/08/adding-rows-and-columns-in-a-nxn-matrix-c-solution/</link>
		<comments>http://softwareworks.wordpress.com/2008/01/08/adding-rows-and-columns-in-a-nxn-matrix-c-solution/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 07:36:47 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/2008/01/08/adding-rows-and-columns-in-a-nxn-matrix-c-solution/</guid>
		<description><![CDATA[This is a variation to the problem/solution posted on Ali Abbas Rizvi&#8217;s blog. I wanted to allow the user to enter matrix size for each run and to get a view of a randomly generated matrix in addition to all the sums for rows and columns. I also wanted to create a design that would [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=5&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font color="#99cc00">This is a variation to the problem/solution posted on </font><font color="#99cc00"><a target="_blank" href="http://saaridev.wordpress.com/2008/01/08/ruby-grid-computing-golf" title="ALi's post"><i><b>Ali Abbas Rizvi&#8217;s blog</b></i></a>. I wanted to allow the user to enter matrix size for each run and to get a view of a randomly generated matrix in addition to all the sums for rows and columns. I also wanted to create a design that would lend itself favorably to adding new functionality. As an example, two methods (<i>AddAllRows </i>and <i>AddAllColumns</i>) have been added to the <b>SquareMatrix </b>class.</font></p>
<pre class="brush: csharp;">
// Problem: Given a matrix, add rows and columns
// Author: Ahmed Arsalan
// (c) 2008. Please cite source if used in your presentation.

using System;
using System.Linq;
using System.Text;

namespace SolvingSmallProblems
{
    class Program
    {
        static void Main(string[] args)
        {
            SquareMatrix aMatrix;
            int matrixSize;

            Console.Out.WriteLine(&quot;Please enter matrix size (e.g. 10):&quot;);
            try
            {
                matrixSize = Int32.Parse(Console.In.ReadLine().Trim());
            }
            catch (Exception)
            {
                Console.Out.WriteLine(&quot;Please entger a valid integer.&quot;);
                throw new Exception(&quot;Invalid size entered!&quot;);
            }
            Console.Out.WriteLine(&quot;The randomly generated matrix looks like this:&quot;);

            aMatrix = new SquareMatrix(matrixSize);

            for (int underline = 0; underline &lt; matrixSize; underline++)
            {
                Console.Out.Write(&quot;____&quot;);
            }
            aMatrix.Show();

            Console.Out.WriteLine(&quot;Press ENTER to generate sums...&quot;);
            Console.In.ReadLine();

            // display sums
            long [] rowSums = new long [matrixSize];
            long [] columnSums = new long [matrixSize];
            for (int rowOrColumn = 0; rowOrColumn &lt; matrixSize; rowOrColumn++)
            {
                rowSums[rowOrColumn] = aMatrix.AddRow(rowOrColumn);
                columnSums[rowOrColumn] = aMatrix.AddColumn(rowOrColumn);

                Console.Out.WriteLine (String.Format (&quot;The sum of row {0} is {1}, &quot; +
                       &quot;and the sum of column {2} is {3}. &quot;, rowOrColumn,
                       rowSums[rowOrColumn], rowOrColumn, columnSums[rowOrColumn]));
            }

            Console.Out.WriteLine (String.Format (&quot;The MAX of all rows is {0}, &quot; +
                  &quot;and the MAX of all columns is {1}&quot;, rowSums.Max(), columnSums.Max()));
            Console.In.ReadLine();
        }
    }

    class SquareMatrix
    {
        # region ------------------------ Instance Variables ------------------------
        private const int DEFAULT_MATRIX_SIZE = 10;
        int[,] matrix;
        Random randomNumber;
        int selectedMatrixSize;
        #endregion

        #region ------------------------ Constructors ------------------------
        public SquareMatrix() :this(DEFAULT_MATRIX_SIZE)
        {
            // use default size
        }

        public SquareMatrix(int matrixSize)
        {
            randomNumber = new Random(99);
            selectedMatrixSize = matrixSize;

            matrix = new int[matrixSize, matrixSize];
            for (int row = 0; row &lt; matrixSize; row++)
            {
                for (int column = 0; column &lt; matrixSize; column++)
                {
                    try
                    {
                        matrix[row, column] = RandomNumber; // random # between 1 and 99
                    }
                    catch (Exception)
                    {
                        Console.out.WriteLine (&quot;Error generating random number!&quot;);
                        throw new Exception (&quot;Error generating random number.&quot;);
                    }
                }
            }
        }
        #endregion

        # region ------------------------ Public Properties ------------------------
        public int RandomNumber
        {
            get
            {
                return randomNumber.Next(1, 99);
            }
        }
        #endregion

        #region ------------------------ Public Methods ------------------------
        public void Show()
        {
            for (int row = 0; row &lt; selectedMatrixSize; row++);

                for (int column = 0; column &lt; selectedMatrixSize; column++)
                {
                    Console.Out.Write(matrix[row, column]);
                    Console.Out.Write(&quot;  &quot;);
                }

                Console.Out.WriteLine();
            }
        }

        public long AddRow(int rowNumber)
        {
            long addedRow = 0;
            for (int column = 0; column &lt; selectedMatrixSize; column++)
            {
                addedRow += matrix[rowNumber, column];
            }

            return addedRow;

        }

        public long AddColumn(int columnNumber)
        {
            long addedColumn = 0;
            for (int row = 0; row &lt; selectedMatrixSize; row++)
            {
                addedColumn += matrix[row, columnNumber];
            }

            return addedColumn;

        }

        public long AddAllRows()
        {
            long addedAllRows = 0;
            for (int row = 0; row &lt; selectedMatrixSize; row++)
            {
                addedAllRows += AddRow(row);
            }
            return addedAllRows;
        }

        public long AddAllColumns()
        {
            long addedAllColumns = 0;
            for (int column = 0; column &lt; selectedMatrixSize; column++)
            {
                addedAllColumns += AddColumn(column);
            }
            return addedAllColumns;
        }
        #endregion

    }
}
</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/5/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/5/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=5&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/01/08/adding-rows-and-columns-in-a-nxn-matrix-c-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>WordPress makes posting source code to your blog easy</title>
		<link>http://softwareworks.wordpress.com/2008/01/06/wordpress-makes-posting-source-code-to-your-blog-easy/</link>
		<comments>http://softwareworks.wordpress.com/2008/01/06/wordpress-makes-posting-source-code-to-your-blog-easy/#comments</comments>
		<pubDate>Sun, 06 Jan 2008 21:31:39 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[1]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/2008/01/06/wordpress-makes-posting-source-code-to-your-blog-easy/</guid>
		<description><![CDATA[When I decided to start a blog to post source code for small projects, I needed a blogging platform that would make posting source code with keyword highlights, line numbers, and proper indentation a snap. After a bit of search and general disappointment with blogging systems, I came across the wonderful feature in WordPress that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=4&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>When I decided to start a blog to post source code for small projects, I needed a blogging platform that would make posting source code with keyword highlights, line numbers, and proper indentation a snap. After a bit of search and general disappointment with blogging systems, I came across the wonderful feature in WordPress that let&#8217;s you post beautifully styled source code simply by enclosing the code inside the SourceCode tag! And that was all I had to do! Brilliant!</p>
<p>The only caveat I found so far is that the view seems fixed in width. So you have to choose a theme that gives you more space in the main text area. If a line in your code is longer than what the template allows, you will get a horizontal scroll bar. However, if you scroll right to see the overflowing code, you will notice that the alternating background color scheme does not apply there. Clearly a bug and a big disappointment. I hope some body at WordPress sees this post and removes that defect. This is still the best and easiest way to date to showcase your source code in a blog.</p>
<p><a href="http://faq.wordpress.com/2007/09/03/how-do-i-post-source-code/" title="WordPress FAQ" target="_blank">Here </a>is the FAQ for WordPress.</p>
<p>Happy coding!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/4/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/4/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=4&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/01/06/wordpress-makes-posting-source-code-to-your-blog-easy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
		<item>
		<title>Time Math Interview Problem (C# Solution)</title>
		<link>http://softwareworks.wordpress.com/2008/01/02/time-math-interview-problem-c-solution/</link>
		<comments>http://softwareworks.wordpress.com/2008/01/02/time-math-interview-problem-c-solution/#comments</comments>
		<pubDate>Wed, 02 Jan 2008 04:20:02 +0000</pubDate>
		<dc:creator>Arsalan</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://softwareworks.wordpress.com/2008/01/02/time-math-interview-problem-c-solution/</guid>
		<description><![CDATA[This is a solution for the problem posted by Ali Abbas Rizvi here. Command line arguments are method name (e.g. AddMinutes), start time (e.g. 9:24AM), and minutes to add (e.g. 18). The result will be the new time after addminutes in the same time format.


using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace SolvingSmallProblems
{
    class Program
  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=3&subd=softwareworks&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font color="#99cc00">This is a solution for the problem posted by </font><font color="#ff0000"><b>Ali Abbas Rizvi</b> <a href="http://saaridev.blogspot.com/2008/01/timecalc-with-bug-fixed.html" title="Ali Abbas's blog" target="_blank">here</a></font><font color="#99cc00">. Command line arguments are method name (e.g. AddMinutes), start time (e.g. 9:24AM), and minutes to add (e.g. 18). The result will be the new time after addminutes in the same time format.</font></p>
<pre class="brush: csharp;">

using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace SolvingSmallProblems
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeConversions timeConv = new TimeConversions();

            string commandName;
            string baseTime;
            string incrementalTime;
            string output;
            if (args.GetLength(0) == 3)
            {
                commandName = args[0];
                baseTime = args[1];
                incrementalTime = args[2];

                switch (commandName.ToUpper())
                {

                    case (&quot;ADDMINUTES&quot;):
                        output = timeConv.AddMinutes(baseTime, Int32.Parse(incrementalTime));
                        Console.Out.WriteLine(output);
                        Console.Out.Flush();
                        break;
                }
            }
            else
            {
                throw new Exception(&quot;Incorrect number of arguments: 2 expected...&quot;);
            }

        }      

    }

    class TimeConversions
    {
        private StringCollection meridiemValidValues;
        public StringCollection methodsAvailable;

        public TimeConversions()
        {
            meridiemValidValues = new StringCollection();
            meridiemValidValues.Add(&quot;AM&quot;);
            meridiemValidValues.Add(&quot;PM&quot;);

            methodsAvailable = new StringCollection();
            methodsAvailable.Add(&quot;AddMinutes&quot;);
        }

        public string AddMinutes(string time, int minutesToAdd)
        {
            long convertedTime = ConvertTimeToMinutes(time);
            string finalTime = ConvertMinutesToTime(convertedTime + minutesToAdd);
            return finalTime;
        }

        private string ConvertMinutesToTime(long minutes)
        {
            long calculatingHours;
            long calculatingMinutes;
            string calculatingMeridiem;

            calculatingMinutes = minutes % 60;
            // Rolling over hours for a 24-hour clock
            calculatingHours = (minutes / 60) % 24;

            if (calculatingHours &lt; 12)
            {
                calculatingMeridiem = &quot;AM&quot;;
                // 0 am should be written as 12 am
                if (calculatingHours == 0)
                {
                    calculatingHours = 12;
                }
            }
            else
            {
                calculatingMeridiem = &quot;PM&quot;;
                calculatingHours -= 12;
            }

            return calculatingHours.ToString() + &quot;:&quot; + calculatingMinutes.ToString().PadLeft(2, '0') +
                &quot; &quot; + calculatingMeridiem;
        }

        private long ConvertTimeToMinutes(string time)
        {
            long normalizedTime;
            string regexStringForTimeConversion = @&quot;^(?&lt;Hours&gt;[\d]{1,2}):(?&lt;minutes&gt;\d\d)[\s]?(?&lt;meridiem&gt;[AP]M)$&quot;;
            Regex regexForTimeConversion = new Regex(regexStringForTimeConversion);

            Match matchedTime = regexForTimeConversion.Match(time);
            int hours, minutes;
            string meridiem;
            try
            {
                hours = Int32.Parse(matchedTime.Groups[&quot;Hours&quot;].Value);
            }
            catch (Exception)
            {
                throw new Exception(&quot;Invalid characters in Hours!&quot;);
            }
            try
            {
                minutes = Int32.Parse(matchedTime.Groups[&quot;Minutes&quot;].Value);
            }
            catch (Exception)
            {
                throw new Exception(&quot;Invalid characters in Minutes!&quot;);
            }
            if (meridiemValidValues.Contains( matchedTime.Groups[&quot;Meridiem&quot;].Value))
            {
                meridiem = matchedTime.Groups[&quot;Meridiem&quot;].Value;
            }
            else
            {
                throw new Exception(&quot;Invalid characters in Meridiem!&quot;);
            }

            // Rule: 12 PM will be 12 in a 24-hour clock, 12 AM will be 0
            if ((hours == 12) &amp;&amp; (meridiem == &quot;AM&quot;))
            {
                hours = 0;
            }
            else if ((hours &lt; 12) &amp;&amp; (meridiem == &quot;PM&quot;))
            {
                hours += 12;
            }

            normalizedTime = (hours * 60) + minutes;

            return normalizedTime;

        }

    }
}
</pre>
<p></meridiem></minutes></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/softwareworks.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/softwareworks.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/softwareworks.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/softwareworks.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/softwareworks.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/softwareworks.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/softwareworks.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/softwareworks.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/softwareworks.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/softwareworks.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/softwareworks.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/softwareworks.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=softwareworks.wordpress.com&blog=2428490&post=3&subd=softwareworks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://softwareworks.wordpress.com/2008/01/02/time-math-interview-problem-c-solution/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f69f4c5df0a5b85ea409f1e08934c9d5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Cashew</media:title>
		</media:content>
	</item>
	</channel>
</rss>