mgroves

Project Euler 8,9,10

Just a quick Project Euler update.  Number 8 was pretty straightforward, I just went through and got each product and then found the max.  For Number 9, I created a Triplet class with an IsPythagorean method.  I then use three loops (nested) to go start from 1 and go up to a given n.  It’s not entirely brute force, because the 2nd number must be greater than the 1st, and the 3rd number can be calculated using the Pythagorean theorum.  Then, if that Triplet sums to the given n, I add it to a list, and return that list at the end.  The Triplet with the highest sum is the answer.  Since the problem says there is only one that sums to 1000, I simply return .Single() of the list.

Number 10 was yet another prime-numbers problem.  I used the IsPrime method from before, and simply looped from 1 to a million, and added the primes to a list.  Linq can be used then to sum up the list, and done.

As before, check out all the source on CodePlex.

How to pronounce things

One of the interesting phenomena arising from the web and its widespread use by programmers is a disconnect between technical words/jargon and how to pronounce them. If you read a word instead of hearing it from someone, you still make up an arbitrary pronunciation. This can make for awkward moments when the word finally does come up between programmers in person (which does happen, honest!).

Here are some examples.  Read them aloud:

  • Tuple
  • C#
  • SQL
  • CAPTCHA
  • WSDL
  • GUID
  • .GIF
  • pwned
  • char
  • varchar

I’ve heard all of the above terms pronounced at least two different ways.  GIF even has a long history of controversy about its pronunciation.  I think I’ve heard “varchar” pronounced about 6 different ways (vair/var + care/car/char).

So, what to do? Even if you are sure that "Tuple" is pronounced "toople" instead of "tupple", it seems petty and annoying to call someone incorrect.  If the intent is understood, then I guess it comes down to a matter of prescriptive vs descriptive linguistics. If you lean towards descriptive linguistics, then it really doesn’t matter if you pronounce CAPTCHA as "cuh-pahtch-uh", as long as your audience knows what you’re talking about. If you are in the prescriptive camp, then C# must be “see-sharp”, and “see-pound” is unacceptable.

Personally, I would lean towards descriptive, so long as there is no possibility of ambiguity. However, I totally sympathize for the prescriptive’s point of view, since in many cases, the pronunciation is not emergent, but defined (as in GIF’s case).

So, what are some other terms (computer-related or otherwise), that have put you into a similar awkward situation?

Coryat Scorekeeper

I recently took the online Jeopardy Contestant qualifier test.  I have no idea if I’ll ever be asked to do an audition, but I was surprised to find that there was no webpage/app/etc to keep track of one’s Coryat score, so I wrote one.

Karl Coryat

What’s a Coryat score, you ask?  See that balding guy?  He’s Karl Coryat.  He devised a simple system for tracking your score as you watch and play along with Jeopardy at home.  His system was named the “Coryat score” by Jeopardy fans after his appearances on the show, and is still used to this day to measure performance on Jeopardy.

His system originally used index cards and pencil, but I created a quick little HTML page with jQuery to accomplish the same thing.   You can check out the Coryat Scorekeeper at CodePlex

StupidGrid

I recently had need for a ASP.NET WebForms grid that would do something you’d think would be relatively simple:

  • Allow the user to enter ‘rows’ of some set of data (for instance, multiple address/city/state)
  • Allow the user to update/delete all of these rows of data, almost like an Excel sheet
  • Keep that data in a ‘holding pattern’ on the form (via ViewState) until such time they ‘submit’ the form to be persisted, emailed, etc.
  • Not use any databinding, database backing, or session – just ViewState

I looked and I looked, but I couldn’t find anything that quite fit right.  I tried to implement a GridView using ObjectDataSource, wrapped around ViewState, but I couldn’t get it to work.  I tried some jQuery grids, GridView, etc, and these all seem to want to talk to a database (or some persistence somewhere).  I tried a plain old ListView/Repeater, but the dynamically added user controls (i.e. my ‘rows’ of data), disappear after postback.

Since I couldn’t find the perfect fit (it may still be out there), I just created my own (with some serious help from this guy).

stupidgridlogo

Yes, StupidGrid, available on CodePlex.  Why the name?

  1. It doesn’t bind to any database or persistence: once the user leaves the page, StupidGrid stupidly forgets anything the user entered.
  2. I couldn’t find a decent (free) grid to do what I wanted, so as I was looking around for one, I kept saying “I just need a stupid grid!”
  3. It’s stupidly simple to use (or, at least, that’s my goal): just build a user control you want to repeat, “feed” its path to the UserControlPath property, and you’re done.

I’ve just done an official release of version 0.1, which I’m sure has many problems, so I would be ecstatic to hear any opinions, suggestions, patches, criticisms, bug reports, problems, etc.

And if anyone wants to design a better logo or icon, leave a comment or hit me on Twitter.

I'm playing with Windows Live Writer

So far, very cool.  It works pretty easily with Habari, as long as you install the MetaWeblog plugin.

Here is a code example via a plugin:

   1:  public class Whatever
   2:  {
   3:       private int _thing;
   4:   
   5:       public Whatever()
   6:       {
   7:            _thing = 5;
   8:       }
   9:  }

Neat, but I’m not sure how I feel about all that inline CSS…

Bring in the noise, bring in the Func (and Action)

Action and Func are kinda like pointers to methods. I've been using these a lot in a little pet project of mine, and I just wanted to share how awesome they are. They can be passed around, put into a collection, and invoked multiple times. Action (and Action<T> and Action<T1,T2>, Action<T1,T2,T3>) can 'point' to a method that doesn't return anything (i.e. a 'void' method). Like so:

    public class Class1
{
public void SomeMethod()
{
// do stuff
}

public void Example()
{
Action a = SomeMethod;
a.Invoke();
}
}

It's a silly example, but "a.Invoke();" is the same as just using "SomeMethod();" Similarly, if SomeMethod had a parameter (or two or three), then you could do this:

    public class Class1
{
public void SomeMethod(int a, string b)
{
// do stuff
}

public void Example()
{
Action<int,string> a = SomeMethod;
a.Invoke(1,"stuff");
}
}

So far, so awesome. Func is the same thing, except it 'points' to a method that can return something. Behold:

    public class Class1
{
public double SomeMethod(int a, string b)
{
// do stuff
return 0.0;
}

public void Example()
{
Func<int,string,double> f = SomeMethod;
double d = f.Invoke(5, "stuff");
}
}

Note that the 'result' type goes in the last slot in the Func: Func<param1,param2,result>. That seems backwards to me, but oh well. Now mix in some lambas for anonymous action:

        public void Example()
{
Action a = () => {
// do stuff
};
a.Invoke();
}

Now you create anonymous methods, stick them in a list, or a stack, or something, and go through and invoke them (or not invoke them) as you like.

These are contrived examples that aren't very useful. What I'm using them for is returning a collection of private methods, depending on various conditions. The user can then pick which one(s) to use from that list. The ones the user picks get placed into a stack and then invoked in LIFO order (this is part of a game).

Anyway, I think Action and Func are really cool parts of C#.

Project Euler 5, 6, and 7

#5 - What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

I did a slow, brute force algorithm, and a fast algorithm using Euclid's algorithm to get GCD/LCM. The slow method is to simply start guessing, incrementally, and seeing if the guess modulus of 1-20 is 0. The second method requires you to know that the least common multiple (LCM) of x,y,z is the same thing as LCM(x,LCM(y,z)). The LCM function is transitive (or whatever, I'm not a math guy). Therefore, you just loop from 2 to 20, and get the accumulative LCM. The LCM function can be written to be dependent on the greatest common denominator (GCD) function, which can be implemented efficiently using Euclid's algorithm.

At this point, I created a "MathHelper" static class to hold methods like GCD and LCM for future use (for Project Euler or otherwise).

Euler himself

#6 - Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

I wrote two methods: SumOfTheSquaresForNumbers1Through(n) and SquareOfTheSumForNumbers1Through(n), both implemented in a very straightforward way--no surprises or anything fancy here. Works very efficiently too.

#7 - What is the 10001st prime number?

I got in a bit of a rush here for some reason, so I cranked out a very brute force solution, just to "get the answer". I felt hollow right away, and decided to take a break after this problem. I read the solution notes which outlined a more efficient way to test if a number is prime or not. I added this implementation to the MathHelper class. Anyway, this problem made me slow down and rethink why I'm doing these problems: it's not to "just solve them" in some sort of competitive sense, and it's not to learn a bunch of mathy stuff either. The point, for me, is to practice my programming, test my own skills, and maybe learn new ways to think about program/method design.

Well, that's all for now. As always, check out the latest source at codeplex, which will almost surely be farther ahead than my blog.

Turning an NAS drive into a media server

So, I bought myself a MyBook World 1TB network hard drive for Christmas. I was hoping that my Xbox 360 would "just see it" on the network, and I could stick all my videos and stuff on there via my laptop, or other computer.

I was wrong on both counts.

First, no matter what I did, I couldn't get my Xbox 360 to see it.

Second, in the process of trying to hack around with it, I made this little NAS drive into a pretty versatile media server.

I found this great little wiki site that's all about hacking the MyBook World. The key? Enabling SSH. Once you have that, you then have full root access to a lightweight linux server right there in the same box. Now, this isn't exactly a powerhouse machine: it's some sort of ARM processor with something like 64mb of memory. But it turns out, you can do a lot with that.

The first step was being able to download and install/build stuff. To do that, I at least needed a compiler. Fortunately, the site above has a very handy zip file containing all I need to copy over a C compiler. Next, I installed a package manager called optware, which is kinda like an apt-get sort of thing, except it's meant to install stuff on embedded systems like NAS drives or routers.

From that point, no more compiling! I next installed ushare via optware, which is a media server. I had to play with the configuration a bit, but now my NAS drive (with a name of my choosing) shows up on Xbox 360! Woo!

But wait, there's more. Oh yes, much more. I also installed Transmission, a bittorrent client with a web interface. I think you see where this is going. My laptop is now no longer involved in any part of this. I can stick torrent files into a "watch" directory, and Transmission picks them up automatically. Of course, I can do this from any computer via SSH, or via the normal network drive share. I even installed Lynx on the NAS, so I can even skip the middleman.

And one last neat trick: I installed Python and pytvshows to automatically poll RSS feeds for shows that I want to watch and download their torrent files in the watch folder, where they get picked up my Transmission. Now it's completely hands-free! Unfortunately, pytvshows is a bit out of date, and ezrss.it doesn't seem very reliable these days. So, after CodeMash, I decided to install Ruby, and write my own torrent grabbing script.

In short, I wouldn't recommend getting this drive, unless you enjoy hacking around with it for endless hours. Fortunately for me, I'm a nerdy coder that's used compilers, linux, etc, before, so I had some idea of what I was doing. For the average Joe, this is a mountain of a task.

Project Euler update

I've finished some more Project Euler problems. Here's some notes:

Problem 3. So, I finally had to break down and write some unit tests for this one. I also had to brush up on what 'prime factors' are, because it's not exactly something I use every day. My solution involved recursion: find the lowest number that divides evenly, divide by it, and repeat using the dividend. If that number is ever itself, it's prime, which is an ending condition for the recursion.

At this point, I also refactored the structure of the project code. Each problem will still be in its own class, but each of those classes implements a common interface. This way, I can simply loop through all solved problems and output the answer without having to repeat formatting and stuff like that.

Problem 4. This one was fun, because it involves palindromes! I again used unit tests, because I knew I would have to watch out for off-by-one errors. I also created a string extension method to reverse the string. I could have created a "IsPalindrome" extension, but generally speaking, the use of such a method is pretty narrow, and thus doesn't really fit as an extension method. My first approach to this problem was to gradually reduce two integers from 999 on down until I got a palindrome from the product. This turned out to not work as expected, and I ended up with a brute force O(n2) algorithm instead. It runs pretty fast, but if the problem called for 4,5,6,etc digit numbers, it would start to get really slow.

As before, you can check out my ongoing source code on CodePlex.com.

Web form validation, ASP.NET MVC 2

One of the deceptively trickiest parts of any web application, MVC included, is validation. Here are my major concerns with validation:

  • Usability. Validation is for users, after all. Validation messages should be clear, and the user should know exactly what they need to do when getting validation errors. Of course, if the form itself has poor usability, chances are the validation will too, so the user experience starts there.
  • To client-side or not to client-side?. That is the question. The benefits to client-side validation include a more responsive UI and less POSTs to the server. The downside is that you often need to repeat yourself, but ASP.NET MVC 2 is building up a very cohesive validation story that includes client-side validation with almost no extra code. Check out Scott Guthrie's latest post on MVC 2 validation. Additionally, I believe that the validation experience should be consistent: users with JavaScript off should have the same experience with JavaScript on (except with more POSTs, of course). Additionally, I think that all errors should show up at a consistent time. If you're using client-side validation, all form fields should have client-side validation, including the ones that require a server/database call (i.e. with AJAX). If you don't want to do that, then consider using server-side only validation instead.
  • ViewModel validation. If you are using MVVM, then validation becomes tricky. Often a viewmodel will simple have a copy of an entity in it, which means the DataAnnotation-style validation in MVC 2 will pass right through and work great. However, a viewmodel will sometimes have a subset or some sort of flattening of the entity, which means you'll again have to repeat yourself. Scott Guthrie's comments: in general "it depends". From a DRY perspective it would be ideal if you could put the validation on the model and have your viewmodels reflect/respect that automatically. Having said that, sometimes the shape of ViewModels look differently than Models - in which case having validation automatically transfer between models/viewmodels might be different (for example: if you flatten fields or expose them differently). We'll try and get more guidance out there that show off how to handle different scenarios.
  • Don't Repeat Yourself. Didn't I already say this? This time I mean that if you want to check for a specific formatting, say with a RegEx, that RegEx should only appear in the validation system once. So if you are validating URLs with a RegEx, you should make a custom attribute that calls a method IsValidURL, and the RegEx should be in that method.

I've used the WebForms validators before, and they generally make development easier, but so far the MVC 2 validation model is looking more robust, and has extensibility points to use 3rd party validation tools like xVal and Castle.