Converting a String Matrix to an Integer Matrix – Curiously Difficult

Every now and then a programming problem comes along that’s extremely simple in concept, but implementation is surprisingly difficult.

As part of a project I was working on I needed to convert a matrix of string values to a matrix of integer values. The idea is best explained by example. Suppose a 4×3 string matrix is:

[  0]  red       small     short
[  1]  blue      medium    tall
[  2]  green     medium    tall
[  3]  yellow    large     medium

The goal is to convert to an integer matrix of:

[  0]  0   0   0
[  1]  1   1   1
[  2]  2   1   1
[  3]  3   2   2

The source matrix is processed by columns. Each string value has an ID. Notice that string values could be identical in different columns but could have different IDs. The “medium” in the middle (“size”) column has ID = 1, but “medium” in the last (“height”) column is different and has ID = 2.

The key to the matrix convert routine is constructing an array of string-to-int Dictionary collections, one Dictionary for each column. The details were quite tricky. Even though I’ve coded this type of problem many times, it still took me a couple of hours to get a demo program working to my satisfaction.

The converter in pseudo-code:

instantiate an array of string-to-int dicts
loop each column j
  instantiate string-to-int dictionary[j]
  loop each row i
    let id = 0
    let s = m[i][j]
    if s not in this dict
      add s as key, id as value
      ++id
  end-loop
end-loop

After the array of Dictionaries has been created it can be used like this:

// what is the ID of "green" in column 0?
int id = colStrToInt[0]["green"];
// result is 2

With the converter array of Dictionaries created, the rest is easy — just iterate over the source string matrix, convert each string to its int ID, and store in a result int matrix. So, I guess the moral of the story is that sometimes it’s easy to come up with an idea that’s difficult to make a reality.

I’ve put some of the key code (I used C#) below.


Three illustrations by Charles Schridde (1926 – 2011) that were created for Motorola print advertising in the 1960s. The designs weren’t intended to be realized — they were aspirational.


// some of the key functions

public static int[][] Convert(string[][] data,
  Dictionaryltstring, intgt[] colStrToInt)
{
  // convert matrix of string to matrix of int IDs
  // using an array of string-to-int Dictionary
  int rows = data.Length;
  int cols = data[0].Length;
  int[][] result = MakeMatrix(rows, cols);

  for (int i = 0; i lt rows; ++i) {
    for (int j = 0; j lt cols; ++j) {
      string s = data[i][j];
      int id = colStrToInt[j][s];
      result[i][j] = id;
    }
  }
  return result;
}

public static Dictionaryltstring,
  intgt[] MakeColStrToIntConverter(string[][] data)
{
  // make an array of string-to-int Dictionary(s)
  int rows = data.Length;
  int cols = data[0].Length;
  Dictionaryltstring, intgt[] result =
    new Dictionaryltstring, intgt[cols];
  for (int j = 0; j lt cols; ++j) {
    result[j] = new Dictionaryltstring, intgt();
    int val = 0;
    for (int i = 0; i lt rows; ++i) {
      string s = data[i][j];
      if (result[j].ContainsKey(s) == false)
        result[j][s] = val++;
    }
  }
  return result;
} // MakeConverter

public static Dictionaryltint,
  stringgt[] MakeColIntToStrConverter(Dictionaryltstring,
    intgt[] converter)
{
  // create a reverse int-to-string lookup
  //  array of Dictionary(s)
  int rows = converter.Length;

  Dictionaryltint, stringgt[] result =
    new Dictionaryltint,stringgt[rows];

  for (int j = 0; j lt rows; ++j) {
    result[j] = new Dictionaryltint, stringgt();
    foreach (KeyValuePairltstring,
      intgt kv in converter[j]) {
      string s = kv.Key;
      int id = kv.Value;
      result[j][id] = s;
    }
  }
  return result;
}

public static int[][] MakeMatrix(int rows,
  int cols)
{
  int[][] result = new int[rows][];
  for (int i = 0; i lt rows; ++i)
    result[i] = new int[cols];
  return result;
}

public static void ShowMatrix(int[][] m)
{
  int rows = m.Length;
  int cols = m[0].Length;

  for (int i = 0; i lt rows; ++i) {
    Console.Write("[ " + i.ToString().PadLeft(2) +
      "]  ");
    for (int j = 0; j lt cols; ++j) {
      Console.Write(m[i][j] + "   ");
    }
    Console.WriteLine("");
  }
}
This entry was posted in Miscellaneous. Bookmark the permalink.