2005-09-21

MSH: Factorial

Spurred on by a challenge from Monk, I began wondering about dynamically resizable data structures in C++. Back in college we used vectors, which I enjoyed for all the same reasons I like Python's lists. The two are very similar, with a slight advantage going to Python because lists are an inherent construct in the language and are thus ubiquitous; vectors, on the other hand, I never saw again.

There's a vector-like structure in .NET called an ArrayList. It bears all the same traits: you can make it bigger, make it smaller, and access its elements with the goold old "list[index]" syntax.

So to test it out, I wrote this silly little suboptimal factorial-computing function in MSH. I do all my .NET prototyping in MSH anymore (thank you very much Jeffrey Snover).

function factorial([int]$n) {
  $a.Clear();
  $t = $a.Add(1);
  for ($i = 1; $i -le $n; $i++) {
    $t = $a.Add($i * $a[$i-1]);
  }
  return $a[$n];
}
MSH C:\Documents and Settings\toby> factorial(6)
720

Optimizing this factorial function to not suck horrendously is left as an exercise for the reader. About the only problem I have with ArrayList is that you find its size by calling "list.Count" instead of "list.Length" like everything else in .NET.

Update: I can't leave well enough alone. Here's the good version:

MSH C:\Program Files\Microsoft Command Shell> $a = new-object System.Collections
.ArrayList
MSH C:\Program Files\Microsoft Command Shell> $a.Add(1)
0
MSH C:\Program Files\Microsoft Command Shell> function fac([int]$n) {
>>   if ($a.Count -lt $n) {
>>     for ($i = $a.Count; $i -le $n; $i++) {
>>       $t = $a.Add($i * $a[$i - 1]);
>>     }
>>   }
>>   return $a[$n];
>> }
>>
MSH C:\Program Files\Microsoft Command Shell> fac(3)
6
MSH C:\Program Files\Microsoft Command Shell> fac(6)
720
MSH C:\Program Files\Microsoft Command Shell> $a
1
1
2
6
24
120
720
MSH C:\Program Files\Microsoft Command Shell>

No comments: