0

I would like to ask a question about the algorithm.

Suppose there are several segments.(segments number not fixed,maybe so longd)

example:

segment                  data range (data range not fixed)

**A                             0~10**

**B                             11~45**

**C                             46~49**

**D                             50~100**

**E                             101~105**

**F                             106~128**

If input → 99

I will get output ‘D’ from my program.

I will put this example implementation in java.

So, Do you have any way or algorithm to make the program execution time faster?

Dann
  • 11

4 Answers4

0

You can use Guava's Range. Create ranges, check (simple for loop) if your input is in range.

Guava's Range Tutorial

Ranges Explanation

Docs

MicD
  • 197
  • 2
  • 11
0

You can use ConcurrentSkipListMap and add to map the range and values

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

Assuming that your data ranges are both sorted and do not overlap, then you can try using a binary search style approach to this.

You can place the starting values of each range into an array:

[0, 11, 46, 50, 101, 106]

The correct starting value, if it exists, would have the following two properties:

  • It is less than 90
  • The adjacent value to the right is either greater than 90 or does not exist (e.g. if the start value were the last range in the array)

Searching for 90 is trivial in this case because we would immediately hit it. Let's say we wanted to find 20. We would take the following steps:

[0, 11, 46, 50, 101, 106]
Choose 50; fails because 50 > 20; go left
[0, 11, 46]
Choose 11; succeeds because 20 > 11 and 20 < 46

So this would yield the range 11-45, and we need one more check to make sure that 20 is within this range. In this case it is, but it doesn't have to be. The binary search approach described above only finds the best fit range, which doesn't necessarily have to contain the actual number.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You could use an Interval Tree - I posted an implementation here some time ago.

An Interval Tree can handle overlapping ranges too.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213