Search code examples
algorithmcardinality

How to best get the data out of a lookup table


I have a few product lines with products that have various features. I have a list of drawings made for each product, and below is a sample of what the product lines, products, and features are represented in the drawings.

enter image description here

I am trying to figure out, when given a particular product with all of its features (i.e. a single row from the table), what is the most efficient most concise way to structure my code around the features, to select the correct drawing?

I can always do something like

if ($product == "A" 
    && $motor == true
    && $feet == 3 
    && $outlet == true
    && $manual == false) 
    getDrawing("A_motor_3_outlet_no_manual.jpg");

and end up with as many flat if statements as there are rows in the table. But there must be a better way. I think it may have something to do with cardinality, or maybe with variability of the options in each of the properties of the product. The exact concept escapes me for some reason.

I have a feeling for example that it is better to check if the product has a motor first, just because once you know that it will eliminate about half of all the options and narrow it down faster. i.e in the main outer if block do something like this:

if ($motor == true) 
{
   //7 drawings left to check
}
else
{
   //6 drawings left to consider
}

as opposed to something like this:

if ($feet == 1) 
{
   //still 10 rows left to consider
}
else if ($feet == 2)
{
   //just 2 options left to check
}
else if ($feet == 3)
{
    //one option only left:
    getDrawing("B_motor_3_no_outlet_manual.jpg");
}

But maybe I am just overthinking this and just need a lookup table somehow with all the properties, maybe like

getDrawing($lookup[$product][$motor][$feet][$outlet][$manual]);

Question still remains on what order of properties is best to use for the lookup table, and if it matters.

Question:

Is there an "optimal" if-then-else block nesting order to decide for product properties, to minimize the total number of decisions the code has to make overall, or do I need to abandon that train of thought and just use a lookup table? Why or why not?

EDIT: By the way .. this looks like a good candidate to use a database .. but I have only 48 rows total and can encode them directly into code. This will be read-only, not updated at all that frequently, so I am thinking of using a multidimensional array to encode this data.


Solution

  • This is what databases are made for. You will be able to use a simple SELECT statement to find exactly what you need. Even if right now it's only one table with very few rows, that's the way I'd go for.

    If you really want to store everything in the script, you could go ahead and hash the properties of each product and use the hash value as key of the lookup table. When given certain product properties, you can then just hash them and retreive the respective drawing.