Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save VoQn/343690 to your computer and use it in GitHub Desktop.
Save VoQn/343690 to your computer and use it in GitHub Desktop.
// -*- mode: java; coding: utf-8; -*-
public class RangeArray {
public static int[] range(int n) {
return range(0, n, 1);
}
public static int[] range(int k, int n) {
return range(k, n, 1);
}
public static int[] range(int start, int stop, int step) {
if (step == 0) {
final String message = "range() step argument must not be zero";
throw new IllegalArgumentException(message);
}
int pitch = Math.abs(step);
int length = Math.abs(stop - start);
int inc = (start > stop ? -1 : 1) * pitch;
int value = start;
int[] array = new int[length / pitch + (length % pitch != 0 ? 1 : 0)];
for (int i = 0, l = array.length; i < l; i++) {
array[i] = value;
value += inc;
}
return array;
}
}
public class RangeList {
public static List<Integer> range(final int stop) {
return range(0, stop, 1);
}
public static List<Integer> range(
final int start,
final int stop) {
return range(start, stop, 1);
}
public static List<Integer> range(
final int start,
final int stop,
final int step) {
if (step == 0) {
final String message = "range() step argument must not be zero";
throw new IllegalArgumentException(message);
}
List<Integer> list = new ArrayList<Integer>();
int pitch = Math.abs(step);
int inc = (start > stop ? -1 : 1) * pitch;
return create(list, start, stop, inc);
}
private static List<Integer> create(
final List<Integer> list,
final int current,
final int stop,
final int step) {
if (step < 0 ? current <= stop : current >= stop) {
return list;
} else {
list.add(current);
return create(list, current + step, stop, step);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment