0

I'm working to create a method that will verify whether a VIN number has a valid checksum. A description on the process can be found here: http://en.wikipedia.org/wiki/Vehicle_identification_number#Transliterating_the_numbers

Where I'm running into an issue is translating from the original data (sent as a string, currently I'm manipulating a char array) into integers for multiplication. I can't just convert the values to their ASCII values and mod them by 9, as the numbers S through Z don't line up with the rest.

Now I'm looking for a mildly efficient way to do this. My first thought was a switch statement, but that just seems excessively long. The next thing I thought of was a dictionary, and that seems like a pretty efficient way to do things. Regex seems like it would be overly complicated for the problem, and run into the issue of being almost as verbose as the switch statement.

So is a variable Dictionary vinDict the way to do it? Part of my gut feeling says that there's a really elegant way to do this with lambda syntax, but I don't know it well enough to do so.

Thanks in advance for any help!

powerisall
  • 33
  • 1
  • 8
  • 2
    If you look at `Transliteration key: values for VIN `, it is a pair of Key and Value, so Dictionary is the best bet. IMO – Habib Jul 29 '14 at 20:24
  • If you really want a lambda solution, you could use `var values = asciiRepresentation.Select(a => (('Z' - a) % 9) + 1 + (a >= 'S' ? 1 : 0));`, but I agree that a Dictionary would be cleaner. – itsme86 Jul 29 '14 at 20:45

1 Answers1

1

A switch statement and a dictionary will give approximately the same performance. Assuming you have something like:

static Dictionary<char,int> CharToIntMap = new Dictionary<char,int>
{
    {'0', 0}, {'1', 1}, ... {'S', 11}, {'Z'}, 12}
};

int val = CharToIntMap[c];

Or:

switch (c)
{
    case '0' : val = 0; break;
    case '1' : val = 1; break;
    ...
    case 'S' : val = 11; break;
}

If the switch statement has more than 7 cases, the compiler will create a dictionary. See https://stackoverflow.com/a/8530197/56778 for a bit more detail on that.

Now, which looks better is a matter of preference. I'd suggest writing your own dictionary to do the mapping.

Community
  • 1
  • 1
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351