We help IT Professionals succeed at work.

Help with C++ look up tables.

bail3yz asked

I am trying to learn how to use lookup tables as I am making a program that does some very time consuming math and I figure I could just put all the info into a look up table and use it that way..

I found some examples, but I do not fully understand it.

I found a poker example where it uses a look up table to determine the rank of a 7 card poker hand

however it only shows how it used the look up table, it didnt show how it made it..

one question I did have tho was

int HR[32487834];

^ this is the array the data is stored in.. how the coder determine the size it needed?

Lastly, if someone could write a small example on how to make a lookup table for a simple multiplication table that would be great!

Something like this
   1   2   3   4   5   6   7   8   9
1 1   2   3   4   5   6   7   8   9
2 2   4   6   8  10 12 14 16 18
3 3   6   9   12 etc

Watch Question

For multiplication (up to 10x10) starting from 0 to 10:
int lookuptable[11][11], i, j;

// Fill table

for(i = 0; i<=10; i++)
    for(j = 0; j<=10; j++)
        lookuptable[i][j] = i*j;

// Lookup

printf("5x7 = %d", lookuptable[5][7]);

Open in new window

mccarlIT Business Systems Analyst / Software Developer
Top Expert 2015
For you first question, you would have to post what code your have so that we can see how the code is actually usuing it. But that size would likely be the number of possibilities that a 7 card poker hand could be.

As for you second question, build the mult lookup table like this...

int mult[10][10];

for(int i=0; i < 10; i++)
  for(int j=0; j < 10; j++)
    mult[i][j] = i * j;

Then you can use it like this...

int result;
result = mult[2][3];    // result will contain 6
result = mult[7][4];    // result will contain 28


Thanks for the answers..

when using the [10][10] method

is there an easy way to store the answers in a dat file and to reload it?

because for what I actually need to do will take several minutes to calculate everything, so id rather just store the answers permanently in a dat file and load it when my program starts

Yeah.. you can store it.. Store all the data and use fread() to read fixed length or fscanf() to read one value at a time

FILE file;

file = fopen("mydata.dat", "r");

for(i = 0; i<=10; i++)
    for(j = 0; j<=10; j++)
        fscanf(file, "%d", &lookuptable[i][j]);


Alright, thanks everyone!