<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1419</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1419" rel="self"/>
  <title>mafutrct</title>
  <updated>Thu Jul 09 11:11:26 -0700 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor196868</id>
    <published>2009-07-09T11:11:26-07:00</published>
    <title>[C#] On How to break up this long but clean method</title>
    <content type="html">&lt;p&gt;I fooled around with the code some more and this is the result so far.&lt;/p&gt;

&lt;pre&gt;		protected override Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; Reconfigure (
			Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; rawPositions)
		{
			/*
			 * with world unset, return current positions.
			 */
			if (World == null) {
				return rawPositions;
			}

			/*
			 * remove invalid positions
			 */
			var positions = rawPositions.Where (x =&amp;gt; x.Value != null);

			/*
			 * create precomputed distance info
			 */
			IEnumerable&amp;lt;Composition&amp;gt; compositions = CreateCompositions (positions);

			/*
			 * find and store best matches
			 */
			var resultingMatches = new Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; ();
			foreach (var pos in positions) {
				resultingMatches.Add (pos.Key, pos.Value);
			}

			while (compositions.Any ()) {
				/*
				 * find best assignment
				 */
				var bestMatch = compositions.First ();

				/*
				 * remove used sources and destinations
				 */
				compositions = compositions.Where (x =&amp;gt; x.Pair.Key != bestMatch.Pair.Key);
				compositions = compositions.Where (x =&amp;gt; x.Target != bestMatch.Target);
				compositions = compositions.ToList (); // tested: improves performance

				/*
				 * ultimately add current pair to results
				 */
				DevicePosition dpResult = new DevicePosition (
					bestMatch.Target.Center,
					bestMatch.Pair.Value.Time);
				resultingMatches[bestMatch.Pair.Key] = dpResult;
			}

			return resultingMatches;
		}

		private List&amp;lt;Composition&amp;gt; CreateCompositions (
			IEnumerable&amp;lt;KeyValuePair&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt;&amp;gt; positions)
		{
			/*
			 * gather all valid volumes
			 */
			IEnumerable&amp;lt;Volume&amp;gt; projectionVolumes =
				from room in World.GetRooms ()
				where &amp;quot;1&amp;quot;.Equals (room.GetAttribute (WantDeviceConstant))
				select room.Volume;
			projectionVolumes = projectionVolumes.ToList ();

			/*
			 * build all pairs
			 */
			IEnumerable&amp;lt;Composition&amp;gt; compositions =
				from src in positions
				from target in projectionVolumes
				select new Composition (src, target);

			/*
			 * apply filter
			 */
			compositions = compositions.Where (x =&amp;gt; x.Dist &amp;lt; MaxDist);
			compositions = compositions.ToList ();

			/*
			 * presort
			 */
			compositions = compositions.OrderBy (x =&amp;gt; x.Dist);

			return compositions.ToList ();
		}&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/944-how-to-break-up-this-long-but-clean-method/refactors/196868" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor189665</id>
    <published>2009-07-06T13:11:02-07:00</published>
    <title>[C#] On IEnumerable&lt;&gt; comparision extension method</title>
    <content type="html">&lt;p&gt;Petar: I'm not sure about the 'where T : class' part. Doesn't this prevent usage of the function with IEnumerable&amp;lt;int&amp;gt;? Apart from that I really like your suggestions.&lt;/p&gt;

&lt;p&gt;This is the code I'm currently using:&lt;/p&gt;

&lt;pre&gt;		/// &amp;lt;summary&amp;gt;
		/// Compares the content of two enumerables for equality. Order
		/// of elements does NOT matter. Elements may exist multiple
		/// times. &amp;lt;c&amp;gt;null&amp;lt;/c&amp;gt; is both a valid key and value.
		/// 
		/// O(n). (?) Fast for elements with well distributed hashcode.
		/// &amp;lt;/summary&amp;gt;
		public static bool ContentEquals&amp;lt;T&amp;gt; (
			this IEnumerable&amp;lt;T&amp;gt; first,
			IEnumerable&amp;lt;T&amp;gt; second,
			IEqualityComparer&amp;lt;T&amp;gt; comparer)
		{
			// Declare a dictionary to count the occurrence of the items in the collection			
			Dictionary&amp;lt;T, int&amp;gt; itemCounts = new Dictionary&amp;lt;T, int&amp;gt; (comparer);

			// null references are stored here.
			int zero = 0;

			// Element count
			int items = 0;

			// Increase the count for each occurrence of the item in the first collection
			foreach (T item in first) {
				if (item == null) {
					zero++;
				}
				else {
					items++;

					int count = 0;
					itemCounts.TryGetValue (item, out count);
					itemCounts[item] = ++count;
				}
			}

			// Decrease the count for each occurrence of the item in the second collection
			foreach (T item in second) {
				if (item == null) {
					zero--;
				}
				else {
					items--;
					if (items &amp;lt; 0) {
						// Mismatching number of elements
						return false;
					}

					int count = 0;
					if (itemCounts.TryGetValue (item, out count)) {
						itemCounts[item] = --count;
					}
					else {
						// There was no occurrence of this item in the first collection, thus the collections are not equal
						return false;
					}
				}
			}

			// Number of elements must match
			if (items != 0) {
				return false;
			}

			// Number of nulls has to be equal
			if (zero != 0) {
				return false;
			}

			// The count of each item should be 0 if the contents of the collections are equal
			foreach (int value in itemCounts.Values) {
				if (value != 0) {
					return false;
				}
			}

			// The collections are equal
			return true;
		}&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/928-ienumerable-comparision-extension-method/refactors/189665" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code944</id>
    <published>2009-07-06T12:33:02-07:00</published>
    <updated>2009-07-29T15:30:12-07:00</updated>
    <title>[C#] How to break up this long but clean method</title>
    <content type="html">&lt;p&gt;A lot of refactoring finally resulted in this long method. I think the code is quite clean and easy to understand. It uses linq a lot, and I'm not really familiar with linq yet, so I figured there are some improvements possible in this area. Also, I'd like to split this method up a bit, so VS does not complain about the admittedly big LOC.&lt;/p&gt;

&lt;pre&gt;		protected override Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; Reconfigure (
			Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; positions)
		{
			/*
			 * with world unset, return current positions.
			 */
			if (World == null) {
				return positions;
			}

			/*
			 * gather all valid volumes
			 */
			List&amp;lt;Volume&amp;gt; projectionVolumes = new List&amp;lt;Volume&amp;gt; ();

			foreach (Room r in World.GetRooms ()) {
				if (&amp;quot;1&amp;quot;.Equals (r.GetAttribute (WantDeviceConstant))) {
					projectionVolumes.Add (r.Volume);
				}
			}

			/*
			 * create precomputed distance info
			 */
			var compositions =
				/*
				 * for each combination...
				 */
				from src in positions
				from target in projectionVolumes

				/*
				 * remove invalid positions
				 */
				where src.Value != null

				/*
				 * create bunch of info
				 */
				select new {
					Pair = src,
					Target = target,
					Dist = target.Dist (src.Value.Position),
				};

			/*
			 * apply filter
			 */
			compositions = compositions.Where (x =&amp;gt; x.Dist &amp;lt; MaxDist);

			/*
			 * presort
			 */
			compositions = compositions.OrderBy (x =&amp;gt; x.Dist);

			/*
			 * store result
			 */
			compositions = compositions.ToList ();

			/*
			 * find and store best matches
			 */
			Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; resultingMatches
				= new Dictionary&amp;lt;GloballyFilteredPositionSource, DevicePosition&amp;gt; (positions);

			while (compositions.Any ()) {
				/*
				 * find best assignment
				 */
				var bestMatch = compositions.First ();

				/*
				 * remove used sources and destinations
				 */
				compositions = compositions.Where (x =&amp;gt; x.Pair.Key != bestMatch.Pair.Key);
				compositions = compositions.Where (x =&amp;gt; x.Target != bestMatch.Target);
				compositions = compositions.ToList (); // tested: improves performance

				/*
				 * ultimately add current pair to results
				 */
				DevicePosition dpResult = new DevicePosition (
					bestMatch.Target.Center,
					bestMatch.Pair.Value.Time);
				resultingMatches[bestMatch.Pair.Key] = dpResult;
			}

			return resultingMatches;
		}&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/944-how-to-break-up-this-long-but-clean-method" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor171780</id>
    <published>2009-06-25T08:45:28-07:00</published>
    <title>[C#] On IEnumerable&lt;&gt; comparision extension method</title>
    <content type="html">&lt;p&gt;That's interesting, the default extensions are really more sophisticated than I imagined. :)&lt;/p&gt;

&lt;p&gt;I was just about to run a performance test of your suggestion when I noticed that &amp;quot;This method returns those elements in first that do not appear in second. It does not also return those elements in second that do not appear in first.&amp;quot;&lt;/p&gt;

&lt;p&gt;I guess this means we'd have to do the Except-comparision twice.... :(&lt;/p&gt;

&lt;p&gt;Looking for a workaround, I stumbled upon Enumerable.Distinct, but that method does not work for multiple occurrences of the same item in the list :-\ &lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/928-ienumerable-comparision-extension-method/refactors/171780" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor167095</id>
    <published>2009-06-22T09:59:29-07:00</published>
    <title>[C#] On IEnumerable&lt;&gt; comparision extension method</title>
    <content type="html">&lt;p&gt;Ants: I think the complexity would increase to O(n*n) that way. Usage of a dictionary seems mandatory.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/928-ienumerable-comparision-extension-method/refactors/167095" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code928</id>
    <published>2009-06-22T07:08:07-07:00</published>
    <updated>2009-11-17T13:35:09-08:00</updated>
    <title>[C#] IEnumerable&lt;&gt; comparision extension method</title>
    <content type="html">&lt;p&gt;VS08 grants only a maintainability index of 49, but I found no way to improve this method. I'd be glad if you could point out some ideas.&lt;/p&gt;

&lt;pre&gt;/// &amp;lt;summary&amp;gt;
/// Compares the content of two enumerables for equality. Order
/// of elements does NOT matter. Elements may exist multiple
/// times. &amp;lt;c&amp;gt;null&amp;lt;/c&amp;gt; is both a valid key and value.
/// 
/// O(n). Fast for elements with well distributed hashcode.
/// &amp;lt;/summary&amp;gt;
public static bool ContentEquals&amp;lt;T&amp;gt; (
	this IEnumerable&amp;lt;T&amp;gt; first,
	IEnumerable&amp;lt;T&amp;gt; second,
	IEqualityComparer&amp;lt;T&amp;gt; comparer)
{
	// Declare a dictionary to count the occurence of the items in the collection			
	Dictionary&amp;lt;T, int&amp;gt; itemCounts = new Dictionary&amp;lt;T, int&amp;gt; (comparer);

        // null references are stored here.
	int zero = 0;

	// Increase the count for each occurence of the item in the first collection
	foreach (T item in first) {
		if (item == null) {
			zero++;
		}
		else if (itemCounts.ContainsKey (item)) {
			itemCounts[item]++;
		}
		else {
			itemCounts[item] = 1;
		}
	}

	// Decrease the count for each occurence of the item in the second collection
	foreach (T item in second) {
		if (item == null) {
			zero--;
		}
		else if (itemCounts.ContainsKey (item)) {
			itemCounts[item]--;
		}
		else {
			// There was no occurence of this item in the first collection, thus the collections are not equal
			return false;
		}
	}

	// The count of each item should be 0 if the contents of the collections are equal
	foreach (int value in itemCounts.Values) {
		if (value != 0) {
			return false;
		}
	}
	if (zero != 0) {
		return false;
	}

	// The collections are equal
	return true;
}&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/928-ienumerable-comparision-extension-method" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code859</id>
    <published>2009-05-07T14:32:17-07:00</published>
    <updated>2009-05-07T16:47:49-07:00</updated>
    <title>[C#] Find random point inside a tree of geometrical object</title>
    <content type="html">&lt;p&gt;Volume is an abstract geometrical object. It contains a capacity.
&lt;br /&gt;CompositeVolume implements Volume. It contains a list of subvolumes.&lt;/p&gt;

&lt;p&gt;I want to find a random position inside a CompositeVolume. Depending on the size of each subvolume I select one of them (bigger =&amp;gt; higher probability), and let it select a random position in itself.&lt;/p&gt;

&lt;p&gt;I'm pretty satisfied with the code as it stands, but since I'm new to C# and especially to .net 3.5, I wondered how it could be improved. I'm open for all suggestions. :)&lt;/p&gt;

&lt;p&gt;Edit:
&lt;br /&gt;- &amp;quot;Random&amp;quot; is actually a static member of the class. I added it to the code. Sorry about that.
&lt;br /&gt;- Simply selecing a random entry in the list is not possible, because I want to take the Capacity property into consideration. Given two Subvolumes with Capacity 1.f and 2.f, the latter should be selected twice as often.&lt;/p&gt;

&lt;pre&gt;public class CompositeVolume : Volume
{
	private readonly Random Random = new Random();

	public override Collection&amp;lt;Volume&amp;gt; Subvolumes // stub
	{
		get;
		set;
	}

	public override float Capacity // stub
	{
		get;
	}

	// this is the interesting part:
	public override Vec GetRandomPosition ()
	{
		if (Subvolumes.Count == 0) {
			return null;
		}
		else {
			float sum = 0f;
			Dictionary&amp;lt;Volume, float&amp;gt; map = new Dictionary&amp;lt;Volume, float&amp;gt; ();
			foreach (Volume v in Subvolumes) {
				sum += v.Capacity;
				map[v] = sum;
			}

			float select = (float) Random.NextDouble () * sum;
			Volume inner = map.First (pair =&amp;gt; pair.Value &amp;gt;= select).Key;

			return inner.GetRandomPosition ();
		}
	}
}&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/859-find-random-point-inside-a-tree-of-geometrical-object" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor155879</id>
    <published>2009-04-27T11:54:09-07:00</published>
    <title>[C#] On Find the list's last satisfying element and skip the rest</title>
    <content type="html">&lt;p&gt;Thanks a lot to both of you, that was the idea I was looking for. :)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/830-find-the-list-s-last-satisfying-element-and-skip-the-rest/refactors/155879" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code830</id>
    <published>2009-04-17T09:43:26-07:00</published>
    <updated>2009-08-19T17:02:19-07:00</updated>
    <title>[C#] Find the list's last satisfying element and skip the rest</title>
    <content type="html">&lt;p&gt;First of all, i'm new to this site, so please point out mistakes of this submit.&lt;/p&gt;

&lt;p&gt;I'm trying to improve some older code that was written for .net 3.0 with features found in 3.5. The current version works fine, but it seems like it takes more lines than actually needed.&lt;/p&gt;

&lt;p&gt;Purpose of this function is to find two values in a list. One of them is simply the first value.
&lt;br /&gt;The second value is supposed to be that last value that lies within a time range. However, not the last value in the whole list, but the last satisfying value just before the first not-satisfying value.&lt;/p&gt;

&lt;p&gt;Sadly, I found no nice way to refactor the while loop. Everything else (except for that while) is not much of a problem.&lt;/p&gt;

&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Linq;

public class DevicePosition
{
	// stub
	public DateTime Time;
}

public class Foo
{
	// this should be IEnumerable.
	private IEnumerator&amp;lt;DevicePosition&amp;gt; ValidPositions()
	{
		// stub
		return null;
	}

	public bool FindRecentRepresentatives(
		int milliseconds,
		out DevicePosition current,
		out DevicePosition previous)
	{
		if (milliseconds &amp;lt;= 0) {
			throw new ArgumentOutOfRangeException (&amp;quot;milliseconds&amp;quot;);
		}

		current = null;
		previous = null;

		IEnumerator&amp;lt;DevicePosition&amp;gt; valids = ValidPositions ();
		valids.MoveNext ();
		current = valids.Current;

		if (current != null) {
			long minTime = current.Time.Ticks - TimeSpan.FromMilliseconds (milliseconds).Ticks;

			// this is the difficult part:
			while (valids.MoveNext ()) {
				if (valids.Current.Time.Ticks &amp;lt; minTime) {
					break;
				}
				previous = valids.Current;
			}
		}
		return (current != null) &amp;amp;&amp;amp; (previous != null);
	}
}&lt;/pre&gt;</content>
    <author>
      <name>mafutrct</name>
      <email>mafutrct@gmx.de</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/830-find-the-list-s-last-satisfying-element-and-skip-the-rest" rel="alternate"/>
  </entry>
</feed>

