mercredi 3 juin 2015

How to create a range switch() or how to cascade ifs efficiently for multiple range detection?

I have been wondering if something like a range switch() existed for a long time, but I couldn't find it yet. Ideally it would be like this:

switch (var) {
    case [0-100]:
        //var is between the above values
        break;
    case [101-1000]:
        //var is between the above values
        break;
    case [1234-5678]:
        //var is between the above values
        break;
    case [1000000-4000000]:
        //var is between the above values
        break;
    default:
        //not in any of the ranges above
        break;
}

Which would be equivalent to:

if(var>=0 && var<=100) {
    //var is between the above values
} else if(var>=101 && var<=1000) {
    //var is between the above values
} else if(var>=1234 && var<=5678) {
    //var is between the above values
} else if(var>=1000000 && var<=4000000) {
    //var is between the above values
} else {
    //not in any of the ranges above
}

However, cascading ifs like this, specially if there are several ranges to test, is not efficient at all and using individual numbers in a switch for these kind of values, does not seem to be an option.

I am resigned to accept that the cascading ifs is the only way to go at the moment, but is there any way I could improve its efficiency?

I thought of this one, with a foreknowledge of what kind of values my var may present more often:

I know that var may reach 4mil and has higher probability to have values over 1mil, but there are lots of ranges to test in smaller values, so logically, I would first test if it's over 1mil (only one condition) and then I would place the remaining ifs inside this if-statement block or in the else-statement block, thus reducing the average amount of conditions to test.

I am mostly using PHP and JS these days, but feel free to provide other programming languages solutions.

Aucun commentaire:

Enregistrer un commentaire