Question:

How would you simply a gigantic if statement?

by  |  earlier

0 LIKES UnLike

Basically there is this bunch of data that needs to go across. This data includes enums, integers, etc...

These variables have to be range checked to make sure they are between 1-20, 5-32, and all other ranges.

If ANY of the range checks on any single variable fails, then the message does not go across.

What is a simpler way to do this besides lump all the range checks for every variable in a single if statement? There are several different ranges.

 Tags:

   Report

4 ANSWERS


  1. You wouldn't do it in one if/case structure. Instead, do it in a multiply-nested set of ifs and/or cases. The most efficient way (in terms of run-time) is always check conditions in the order of decreasing likelihood to reject a given record. The sooner you determine you want to bypass a record, the less processing time is spent doing so.


  2. I'd use a binary tree. In general the execution order of multiple "if" statements is O(n), so doubling the number of possible values that need to be checked makes your routine run twice as slow (this holds true even if you're checking against ranges of numbers).

    During your initialization you need to combine your ranges into a single list of ranges with no overlap, i.e. the list of ranges [1-20, 5-32, 40-45, 60-80, 90-95, 93-100] merges into the list [1-32, 40-45, 60-80, 90-100]. Next you split these sequences in two: [1-32, 40-45] and [60-80, 90-100], and you use the highest number in the left sequence, i.e. 45, as the node value. You compare the value your checking against 45, if it's equal or lower you go down the left branch, otherwise you go down the right branch. If you go down the left branch then the next node would be 32 and have child sequences [1-32] and [40-45]. Once you reach a child leaf containing only a single sequence you simply check to see if your value is in that sequence.

    The execution order of this type of binary search is O(log n). It's possible to get this down to constant time O(k) by using other structures like hash tables, but in practice you might find that the caching behavior of modern architectures makes a binary search faster, particularly if you're doing a lot of look-ups.

  3. vlookup table ?

  4. use a "case" statement

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions