Vote Up 0 Vote Down

Find Range in which value lies

We would like to know how to find Range in which value lies.

answer


Vote Up 0 Vote Down
import java.util.TreeSet;

class MyRange implements Comparable<MyRange> {
  long limit;
  int id;

  public MyRange(int id, long credits) {
    this.id = id;
    this.limit = credits;
  }

  public MyRange(long credits) {
    this.id = -1;
    this.limit = credits;
  }

  @Override
  public int compareTo(MyRange o) {
    return limit < o.limit ? -1 : limit > o.limit ? 1 : 0;
  }

  @Override
  public String toString() {
    return "id:" + id + ", limit:" + limit;
  }
}

public class Main {
  public static void main(String[] args) {
    TreeSet<MyRange> set = new TreeSet<>();
    set.add(new MyRange(1, 0));
    set.add(new MyRange(2, 100));
    set.add(new MyRange(3, 500));
    set.add(new MyRange(4, 250));
    System.out.println(set.floor(new MyRange(50)));
    System.out.println(set.floor(new MyRange(300)));
    System.out.println(set.floor(new MyRange(600)));
  }
}
flag | link

your answer

Who Are You?

Have an account already? Login before answering!