Non-Mensa Economic Challenge

August 13th, 2009 robber.baron No comments

Most “intelligence” test have an extremely difficult task.  They need to test the intellectual potential without assumptions about knowledge or experience.  Thus most difficult questions seem  obvious after a solution is presented.  This is because the information is present in a non-standard way and those with the mental dexterity to wrap their minds around the core of the problem will do well.

As an example of this take a favorite economic puzzle:

It is the month of August; a resort town sits next to the shores of a lake. It is raining, and the little town looks totally deserted. It is tough times, everybody is in debt, and everybody lives on credit. Suddenly, a rich tourist comes to town. He enters the only hotel, lays a 100 dollar bill on the reception counter, and goes to inspect the rooms upstairs in order to pick one.

The hotel proprietor takes the 100 dollar bill and runs to pay his debt to the butcher. The butcher takes the 100 dollar bill and runs to pay his debt to the pig raiser. The pig raiser takes the 100 dollar bill and runs to pay his debt to the supplier of his feed and fuel. The supplier of feed and fuel takes the 100 dollar bill and runs to pay his debt to the town’s prostitute that, in these hard times, gave her “services” on credit. The hooker runs to the hotel, and pays off her debt with the 100 dollar bill to the hotel proprietor to pay for the rooms that she rented when she brought her clients there.

The hotel proprietor then lays the 100 dollar bill back on the counter so that the rich tourist will not suspect anything. At that moment, the rich tourist comes down after inspecting the rooms, and takes his 100 dollar bill, after saying he did not like any of the rooms, and leaves town.

No one earned anything. However, the whole town is now without debt, and looks to the future with a lot of optimism.

The answer is suprisingly easy and makes good sense when you think about it.

The solution:

This seems like a tricky question because it intentionally focuses on debt.  However if you were to focus on the individual’s fiscal situation as a whole the solution becomes quite obvious.  The hotel owner might owe the pig farmer $100.00, thus putting his net worth at -$100.00.  However the town prostitute owes the hotel owner $100.00.  Thus incorporating he debt owed plus debts owed to him, his net worth is $0.00.  In fact everyone in this tiny town has a net worth of $0.00.  Thus no one is actually in debt.

They could have solved this debt “problem” without the $100.00.  If the hotel owner had gone  to the pig farmer and said, “The town prostitute owes me $100.00, ask her for the money.” he would have negated his debt.  The had the pig farmer done the same with feed supplier saying, “The prostitute owes me $100.00, can she owe you instead?”  If the supplier agreed then the town prostitute would owe him $100.00 but he owes her $100.00.  Thus they could agree to absolve their debt and again the town in debt free.

There is no such thing as a free lunch in economics.  If is seems like money is appearing or disappearing from nowhere the sad reality is that it is being moved around by parties you haven’t considered.  Too often this has devastating effects in real life.  (The current financial “crisis” from the housing market being a great example.)

Categories: Mensa Tags: ,

Conversion Operator Methods

August 11th, 2009 robber.baron No comments

While the .Net Framework provides a plethora of classes for you to use when building applications it is not all inclusive. Part of being a programmer is adding functionality to a specific system that might not be useful to all people.

Within this application’s domain, certainly custom data types might become as important as .Net’s base types. In this case you might want to have the compiler treat your objects as such; using implicit and explicit operators.

public sealed class Currency
{
     // Constructs a Currency from a Double
     public Currency(Double amt) { ... }
 
     // Constructs a Currency from a String
     public Currency(String amt) { ... }
 
     // Convert a Currency to a Double
     public Double ToDouble() { ... }
 
     // Convert a Currency to a String
     public override ToString() { ... }
}

This works well but requires explicit calls to these functions to work. This creates a new type in your code but it isn’t as privileged as framework types. You cannot have the follow code compile, let alone run.

Currency amt1 = 5.25;     // Implicit cast
Currency amt2 = "$3.13";
 
Double x = (Double) amt1;     // Explicit cast
String y = (String) amt2;

Now if Currency was a base type like, for example, Int32 then you could implicitly and explicitly cast it from type to type. The Currency class, written as is, above, cannot. In order to do so you must use the operator keyword in your class.

The Currency class needs to be rewritten as follows.

public sealed class Currency
{
     // Constructs a Currency from a Double
     public Currency(Double amt) { ... }
 
     // Constructs a Currency from a String
     public Currency(String amt) { ... }
 
     // Convert a Currency to a Double
     public Double ToDouble() { ... }
 
     // Convert a Currency to a String
     public override ToString() { ... }
 
     // Allows implicitly casting to Currency from Double
     public static implicit operator Currency(Double amt)
     {     return new Currency(amt);     }
 
     // Allows implicitly casting to Currency from String
     public static implicit operator Currency(String amt)
     {     return new Currency(amt);     }
 
     // Allows explicitly casting to Double from a Currency
     public static explicit operator Double(Currency c)
     {     return c.ToDouble();     }
 
     // Allows explicitly casting to String from a Currency
     public static explicit operator String(Currency c)
     {     return c.ToString();     }
}

Conversion operators require that the overload methods be both public and static. The implicit keyword indicates to the compiler that an explicit case does not have to appear in code to call the conversion method. The explicit keyword indicates to the compiler that an explicit cast must to present to call the conversion method.

This allows your custom types to feel more natural within your programming environment, making them seem as though they are a part of the core .Net framework. This is especially useful within core libraries that you use repeatedly.

Categories: C#, Programming, Uncategorized Tags: ,

BitFlags in C#

July 31st, 2009 robber.baron 4 comments

Awhile back I had a discussion about user permissions with a client. Specifically how to store the permissions in the database. As a software developer I wanted my object model to have explicit control over the security model. If you wanted to alter a person’s security you’d need to do so via a utility program or perhaps an administrative panel within the software.

The client wanted to be able to alter a field within a table in the database to change permissions. He thought it was much more efficient to have a DBA hop into the database and change a field. He further thought have a bunch of fields Boolean fields like “Read”, “Write”, “Publish”, “Edit”, and “Delete” were too cumbersome. He wanted to have a bit string where each bit represented a yes/no relationship with a type of permission.

This is something that can be represented beautiful with a special type of enum. Adding the [Flags] attribute to an enum turns it into a bit string just like above. It is implemented as follows.

1
2
3
4
5
6
7
8
9
[Flags]
public enum Permissions {
     None = 0
     Read = 0x0001,
     Write = 0x0002,
     ReadWrite = Permissions.Read | Permissions.Write,
     Execute = 0x0004,
     Delete = 0x0005
}

As you can see it looks as though it is a simple enum but isn’t quite that. You are allowed to combine enum values to create other values.

What is especially great is that

1
2
3
4
Permissions permissions = Permissions.Read | Permissions.Execute;
User user = new User("robber.baron", permissions);
 
Console.Writeline(user.permissions.ToString());

The output of the final line is very user friendly. The output is:

Read, Execute

This is a native part of the common language runtime and is part of the .Net base library. This is a fantastic and simple language feature that provides a simple and intuitive way of dealing with the concept of bit strings without custom code.

I’ll never worry about having to implement a bit string again. In fact I might start using them more often.

Categories: C#, Programming Tags: , ,

Hiding System.Object default methods from IntelliSense

July 31st, 2009 robber.baron No comments

Every object in Microsoft’s .Net common language runtime (CLR) implements the System.Object interface.  This means that every object in .Net has the following methods; Equals(), HashCode(), GetType(), and ToString().  While this is extremely helpful when you want to override ToString() (for use with DataGridView) or Equals().

It becomes annoying when using Microsoft’s IntelliSense.  Every class will always expose these methods to IntelliSense.  Since everyone but the most novice of programmers knows these classes exist there is little sense for IntelliSense to expose them. They add unnecessary clutter.

Thankfully there is a way to turn them off using the System.ComponentModel.EditorBrowsableAttribute namespace, which controls what members are visible in IntelliSense.

While you can choose for each and every class I prefer to use a single interface and just have my classes inherit from that interface.

namespace BlorkSamples.IntelliSense
{
     [EditorBrowsable(EditorBrowsableState.Never)]
     public interface IInvisibleSystemObjectMethods
     {
          [EditorBrowsable(EditorBrowsableState.Never)]
          bool Equals();
 
          [EditorBrowsable(EditorBrowsableState.Never)]
          int GetHashCode();
 
          [EditorBrowsable(EditorBrowsableState.Never)]
          Type GetType();
 
          [EditorBrowsable(EditorBrowsableState.Never)]
          string ToString();
     }
}

This hides the System.Object methods from IntelliSense and whenever writing your own interfaces or classes just inherit from this interface to hide its common methods.  Extremely handy with large and confusing APIs.

Static Keyword

June 23rd, 2009 robber.baron No comments

I wanted to start information for beginner programmers to improve their programming skills. One of my chief complaints about the programmer culture is that currently there is a lot of very basic information online and a lot of very advanced information online, but not a lot of information to help a novice become advanced.

Over the last few years I have run into the same sort of questions over and over without a solid reply. I figured that I could at least chronicle some of the more useful information to help an inexperienced programmer increase his skills.

The first entry is on the static keyword and its utility for programmers.

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

- microsoft developer network

This means that you don’t need to use the new keyword to access static members or static methods of a class.

Let us re-implement a subset of the Math class in the .Net Framework.

public class Math
{
     public const double PI = 3.14159;
 
     public double Max(double d1, double d2)
     {
          return d1 < d2 ? d2 : d1;
     }
 
     public double Min(double d1, double d2)
     {
          return d1 < d2 ? d1 : d2;
     }
}

This is a perfectly legitimate implementation of the Math class but isn’t exactly perfect.  If you wanted to use the Min method currently, you would have to instantiate a new Math class before using it.

var math = new Math();
 
var max = math.Max(2.4, math.PI);

Read more...

Categories: C#, Programming Tags: , , ,

Mensa Challenge (Week 2)

June 23rd, 2009 robber.baron No comments

In college I had a friend who had to be tested for dyslexia.  He had gone through the public education system being self-diagnosed and when it came time for him to take the GREs he needed actual proof that he had a learning disability to get increased time to take the exam.  (Ironically he didn’t need the extra time.)

I found the result fascinating.  My friend was perhaps one of thee most mathematically gifted persons I will ever meet in my lifetime.  If he forgot an equation during an exam for his electrical engineering classes he often would just derive it from the equations he did remember.  He never scored lower than a 98% on any math exam, ever.

Yet when he results returned from his dyslexia test he scored in the second percentile for dictation skills.  Despite being gifted in math and logic he was woefully lacking in verbal skills, particularly dictation.  He was less skilled than 98% of the population.  This confirmed his disability.

This week I thought I would through out a language problem.  It seems readers are in the same vein as I am and much more skilled at logic problems.  In an attempt to push people outside their normal area of expertise I present the following.

Only one other word can be made from all the letters in the word INSATIABLE. What is that word?

I have particular difficulty with these types of problems.  My brain does not seem wired to handle language problems like this.  I am terrible at word jumbles and other word puzzles.  When it comes to logic problems or mathematical trickery I am top notch, but seem unable to tackle even moderately difficult problems like these.  How good are you?

Read more…

Categories: Mensa Tags: ,

Irssi + Screen + Mac Terminal

June 22nd, 2009 robber.baron 2 comments

Awhile ago I bought myself a Mac mini. I wanted something small I could attach to my high definition television. A sort of media server as well as general web browser for the roommate and girlfriend.

I ran into keyboard issues when logged into my web server box. I was using irssi + screen and when I wanted to switch between irssi windows I couldn’t. Took a little bit of searching but you can set Terminal.app to use the option key as a meta key (alt key). This has drastically improved my command line experience.

Follow these instructions for Terminal.app (10.5 Leopard)

  1. Choose “Preferences” from the Terminal.app men.
  2. In the “Settings” group, choose your profile.
  3. Go to the “Keyboard” tabCheck.
  4. “Use option as meta key”

Enjoy.

Mensa Challenge Bonus (Week 1)

June 17th, 2009 robber.baron No comments

I got a few complaints that the first puzzle was much too easy.  That was sort of the point.  Introduce something nice and simple and work our way up from there.  Apparently the masses are demanding more difficult challenges.

I present today a bonus Mensa challenge that only 20% of people get correct on first blush.  Let us see how people do on this puzzle.

Your friend invites you to a dinner party at their new house.  Instead of an actual address your friend gives you the following information: “All the houses on my side of the street are numbered consecutively in even numbers.  There are six houses on my side of my block and the sum of their numbers is 9870.  You don’t know which block I live on, and it is a long street, but I will tell you that I live in the lowest number on my side of the block. What’s my number?”

I will mention that this is a slight modification on a common SAT question.  So while I knew how to solve it immediately it was only because of having dealt with similar problems frequently.

Good luck.

Read more…

Categories: Mensa Tags: ,

Creating Custom Performance Counters

June 17th, 2009 robber.baron No comments

Windows has a handy tool called Performance Monitor.  You can access it on any (modern) Windows computer by typing perfmon at the command line or into run.  I had always wondered how to create my own monitors for use with my own software.  It seemed like a very easy way to keep track of the internals of a complex piece of software without a lot of overhead.

This is a rather contrived example but it basically creates a … well .. counter counter.  A counter that counts the number of something.  For a system that handles large quantities of input and output it might be nice to know what your buffers, queues, and lists are doing and a simple monitor like this would work perfectly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System.Diagnostics;
 
namespace CodeMonkey.Sample.Counters
{
     public class ItemCounter
     {
          private const string CATEGORY_NAME = "CodeMonkey";
          private PerformanceCounter _counter;
 
          public ItemCounter()
          {
                var collection = new CounterCreationDataCollection();
                var data = new CounterCreationData("Number of Items", "", PerformanceCounterType.NumberOfItems32);
 
                if (!PerformanceCounterCategory.Exists(CATEGORY_NAME))
                {
                     PerformanceCounterCategory.Create(CATEGORY_NAME, "",
                                                    PerformanceCounterCategoryType.MultiInstance,
                                                    collection);
                }
                _counter = new PerformanceCounter(CATEGORY_NAME, "Number of Items", "Sample", false);
          }
 
          public void IncrementBy(int value)
          {
               _counter.IncrementBy(value);
          }
 
          public void DecrementBy(int value)
          {
               _counter.DecrementBy(value);
          }
     }
}

One of the most common mistakes with creating custom counters is keeping your naming straight.  I first declare a constant to keep the category name straight.  When adding a counter to perfmon this is the descriptor for the Performance object drop down list.  It is a container for all the different counters you might want for a system.

Since I only wanted to show a simple example of this I’ve left it as a simple class with only the counter object as publicly accessible.  Ideally you would be adding multiple counters to a single CounterCreationDataCollection for all your programs needs.

In the constructor I create the CounterCreationDataCollection to hold my counters.  Then I create the CounterCreationData object to add to the collection.  I give it a name (Number of Items), empty help string, and the counter type.  There are a plethora of counter types.  Since all I care about is counting a simple integer I went with NumberOfItems32.

Then I test to see if the Category has been previously registered with the operating system.  If not then I register it.  After I’m sure all the grunt work is out of the way I create a new counter in that category with a name.

Then I expose the Increment and Decrement methods.  This allows you to change the system.  Within the software I would create a new counter for say shopping cart items and every time an item was added or remove increment or decrement the counter.

This way while the system is running you can add your counters to perfmon and watch what is going on from there.  You can monitor your software will very little up front costs.  Genius.

Categories: C#, Programming Tags: ,

Mensa Challenge (Week 1)

June 16th, 2009 robber.baron No comments

I have been working through a book of Mensa puzzles.  I thought I would challenge the readers to try their hand at tackling the tough problems.  I will publish a puzzle a week and then publish the answer, the logic, and the percentage of Mensa members that get the problem correct at the end of that week.

This week’s puzzle:

A fruit stand has a unique pricing scheme. If the price of an apple is $0.15, the price of a raspberry is $0.27, and the price of banana $0.18; using the same logic how much does a mango cost?

This was a good one to start off with since 93% of Mensa members got this puzzle right.

Good luck!

Read more…

Categories: Mensa Tags: