Memoization

| | Comments (0)
Take a look at the Wikipedia entry on Memoization for the nitty gritty.

Esentially, it's a term for a specific form of caching, or so it would appear. Take the following data-set:

List Families [FamilyId : Name] {1 : Smith, 2 : Jones}
List People [PersonId : Name] {1: Adam, 2 : Ben, 3 : Carol, 4 : David}
List PeopleInFamilies [FamilyId : PersonId] { 1 : 1, 1 : 2, 1 : 3, 2 : 4]

If you wanted to work out how many people were in each family, you could:

foreach(familyItem in Familes)
{
  counter = numberOfPeopleInFamily(familyItem.FamilyId)
  print("FamilyId {0} Count {1}", familyItem.FamilyId, counter);
}

function numberofPeopleInFamily(familyId)
{
  counterInFunction = 0;
  foreach(peopleInFamiliesiitem in PeopleInFamiles)
  {
    if familyId = peopleInFamiliesiitem.FamilyId
    {
      counterInFunction++;
    }
  }
  return counterInFunction;
}
However, for a set of 1000 families and 800 people in families, this would mean that there would be 800,000 iterations over the "PeopleInFamilies" dataset. The code could be re-written more sensibly as:


dictionary<int, int> familyIdByCountInFamily = numberofPeopleInFamilies;
foreach(familyItem in Familes)
{
  print("FamilyId {0} Count {1}", familyItem.FamilyId, familyIdByCountInFamily[familyItem.FamilyId]);
}

function numberofPeopleInFamilies()
{
  dictionary<int, int> familyIdByCountInFamily
  foreach(peopleInFamiliesiitem in PeopleInFamiles)
  {
    familyIdByCountInFamily[peopleInFamiliesiitem]++;
  }
  return familyIdByCountInFamily;
}
Now there are only 800 iterations over the "peopleInFamilies" dataset, much better! That's my take on memoization, anyway.

Leave a comment

About this Entry

This page contains a single entry by Rob published on February 18, 2009 8:30 AM.

An attempt was made to load a program with an incorrect format was the previous entry in this blog.

Teenager arrested for texting is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.02