Skip to content

Instantly share code, notes, and snippets.

@danilomo
Last active July 18, 2017 09:52
Show Gist options
  • Save danilomo/39c05431c6379af8609a3128653bad90 to your computer and use it in GitHub Desktop.
Save danilomo/39c05431c6379af8609a3128653bad90 to your computer and use it in GitHub Desktop.
Finds which sub-interval contains a given value. Hardcoded X flexible solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class HardcodedRangeTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
if(val >= 0 && val <= 2){
System.out.println("Inside first interval.");
}else if(val >= 3 && val <= 5){
System.out.println("Inside second interval.");
}else if(val >= 6 && val <= 8){
System.out.println("Inside third interval.");
}else{
throw new RuntimeException("Invalid value");
}
}
}
class Range {
private int lower;
private int upper;
public Range(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
public boolean inside( int val ){
return val >= lower && val <= upper;
}
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 + " ]";
}
}
interface Command {
public void execute();
}
class FlexibleTestRange {
public static void main(String[] args) {
List<Range> ranges = new ArrayList<>();
List<Command> commands = new ArrayList<>();
populateRanges(ranges, 0, 8, 3);
System.out.println(ranges);
commands.add(c1);
commands.add(c2);
commands.add(c3);
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
test(val, ranges, commands);
}
static Command c1 = new Command() {
@Override
public void execute() {
System.out.println("Inside first interval.");
}
};
static Command c2 = new Command() {
@Override
public void execute() {
System.out.println("Inside second interval.");
}
};
static Command c3 = new Command() {
@Override
public void execute() {
System.out.println("Inside third interval.");
}
};
private static void test(int val, List<Range> ranges, List<Command> commands) {
for(int i = 0; i < ranges.size(); i++){
if(ranges.get(i).inside(val)){
commands.get(i).execute();
return;
}
}
throw new RuntimeException("Invalid value");
}
private static void populateRanges(List<Range> ranges, int lower, int upper, int n) {
int intervalSize = (upper - lower) / n;
int l = lower;
for(int i = 0; i < n; i++){
int u = l + intervalSize <= upper ? l + intervalSize : upper;
ranges.add(new Range( l, u ));
l += intervalSize + 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment