-3

For a programming class, I have to convert a range of values to a switch statement without using if/else ifs. Here are the values that I need to convert to cases:

0 to 149 ............. $10.00
150 to 299 .........$15.00
300 to 449 .........$25.00
550 to 749..........$40.00
750 to 1199........$65.00
2000 and above.....$85.00

I am having difficulty finding a way to separate the values since they are so close in number (like 149 to 150).

I have used plenty of algorithms such as dividing the input by 2000, and then multiplying that by 10 to get a whole number, but they are too close to each other to create a new case for.

Alyssa
  • 23
  • 1
  • 2
  • 8

1 Answers1

1

The first thing to do is to figure out your granularity. It looks like in your case you do not deal with increments less than 50.

Next, convert each range to a range of integers resulting from dividing the number by the increment (i.e. 50). In your case, this would mean

0, 1, 2 --> 10
3, 4, 5 --> 15
6, 7, 8 --> 25
... // And so on

This maps to a very straightforward switch statement.

Note: This also maps to an array of values, like this:

10, 10, 10, 15, 15, 15, 25, 25, 25, ...

Now you can get the result by doing array[n/50].

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523