Skip to content

Instantly share code, notes, and snippets.

@danilomo
Last active July 18, 2017 09:52
Show Gist options
  • Save danilomo/b2006a1721ff262cee04f3c3b094fc82 to your computer and use it in GitHub Desktop.
Save danilomo/b2006a1721ff262cee04f3c3b094fc82 to your computer and use it in GitHub Desktop.
Finds which sub-interval contains a given value. Flexible solution
interface Command {
public void execute();
public static final Command EMPTY = new Command() {
@Override
public void execute() {
// do nothing.
}
};
}
class Range {
private int lower;
private int upper;
private Command command;
public Range(int lower, int upper, Command c) {
this.lower = lower;
this.upper = upper;
this.command = c;
}
public Range(int lower, int upper) {
this(lower, upper, Command.EMPTY);
}
public boolean inside( int val ){
return val >= lower && val <= upper;
}
public void executeCommand(){
this.command.execute();
}
public static void main(String[] args) {
Range r = new Range(0, 3);
System.out.println(r.inside(1));
System.out.println(r.inside(5));
}
@Override
public String toString() {
return "[ " + lower + ", " + upper + " ]";
}
}
class FlexibleRangeTest {
public static void main(String[] args) {
List<Range> ranges = new ArrayList<>();
populateRanges(ranges, 0, 8, 3);
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
test(val, ranges);
}
private static void test(int val, List<Range> ranges) {
for(int i = 0; i < ranges.size(); i++){
if(ranges.get(i).inside(val)){
ranges.get(i).executeCommand();
return;
}
}
throw new RuntimeException("Invalid value");
}
private static void populateRanges(List<Range> ranges, int lower, int upper, int n) {
final int intervalSize = (upper - lower) / n;
int l = lower;
for(int i = 0; i < n; i++){
final int u = l + intervalSize <= upper ? l + intervalSize : upper;
Command c = new Command() {
@Override
public void execute() {
System.out.println("Inside interval: "
+ (u - intervalSize)
+ ", "
+ u);
}
};
ranges.add(new Range( l, u, c ));
l += intervalSize + 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment