Algorithm – Create Single Integer Index from Two Integers

algorithmssorting

I have table data containing an integer value X ranging from 1…. unknown, and an integer value Y ranging from 1..9
The data need to be presented in order 'X then Y'.

For one visual component I can set multiple index names: X;Y
But for another component I need a one-dimensional integer value as index (sort order).

If X were limited to an upper bound of say 100, the one-dimensional value could simply be X*100 + Y.
If the one-dimensional value could have been a real, it could be X + Y/10.

But if I want to keep X unlimited, is there a way to calculate a single integer 'indexing' value from X and Y?

[Added] Background information:

I have a Gantt/TreeList component where the tasks are ordered on a TaskIndex integer. This does not need to be a real database field, I can make it a calculated field in the underlying client dataset.

My table data is e.g. as follows:

ID    Baseline   ParentID
 1       0          0     (task)
 5       2          1     (baseline)
 8       1          1     (baseline)
 9       0          0     (task)
12       0          0     (task)
16       1         12     (baseline) 

Task 1 has two baselines numbered 1 and 2 (IDs 8 and 5)
Task 9 has no baselines
Task 12 has one baseline numbered 1 (ID 16)

Baselines number 1-9 (the Y variable from my question); 0 or null identify the tasks
ID's are unlimited (the X variable)

The user plays with visibility of baselines, e.g. he wants to see all tasks and all baselines labeled 1. This is done by updating a filter on the table.

Right now I constantly have to recalculate TaskIndex after changing the filter (looping through records with a counter). It would be nice if TaskIndex could be calculated on the fly for each record knowing only the ID and Baseline data in the current record (I work in Delphi where a client dataset has an OnCalcFields event handler, that is triggered for each record when necessary).

I have no control over the inner workings of the visual component.

Best Answer

As your least-significant index (Y) is bounded, to get the right sort order, you can just do index = X*10 + Y and order index on its numerical value.

If the overall index is too large to fit into an integer value, you can simulate numerical ordering by padding the shorter numbers with leading zeros until all values in the comparison are the same length.

Related Topic