Skip to content

Instantly share code, notes, and snippets.

@pjoshi30
Created May 14, 2016 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjoshi30/1c4b6301166d8e29723c0cb39091a5fa to your computer and use it in GitHub Desktop.
Save pjoshi30/1c4b6301166d8e29723c0cb39091a5fa to your computer and use it in GitHub Desktop.
Recursive backtracking code for point enumeration in an n-D space.
package com.yahoo.broadway.serving.actors;
import java.util.ArrayList;
import java.util.List;
//Creates duplicates :(
class PointEnumeration {
static class Point {
List<Float> dimensions; //a list of float where index i is the (i+1)'th dimension
Point(Point p) {
this.dimensions = new ArrayList<>();
this.dimensions.addAll(p.dimensions);
}
Point(int size) {
this.dimensions = new ArrayList<>();
for(int i = 0; i < size; i++){
//Initialize all dimensions to 0.0f
this.dimensions.add(0.0f);
}
}
void incr(int pos, float i) {
float val = dimensions.get(pos);
dimensions.set(pos, val + i);
}
void set(int pos, float i) {
dimensions.set(pos, i);
}
float get(int pos){
return dimensions.get(pos);
}
}
static List<Point> findPoints(float stepSize, int numDim) {
if (stepSize > 1) {
return new ArrayList<>();
}
List<Point> res = new ArrayList<>();
int steps = (int)(1.0f/stepSize);
for(int i = 1; i <= steps; i++) {
findPointsHelper(i/(float)steps, numDim, 1.0f, new Point(numDim), res);
}
return res;
}
static void findPointsHelper(float stepSize, int numDim, float sum, Point curr, List<Point> res) {
if (sum <= 0.0) {
res.add(new Point(curr));
return;
}
for (int i = 0; i < numDim; i++) {
float temp = sum;
float val = curr.get(i);
curr.incr(i, stepSize);
findPointsHelper(sum - (val + stepSize), numDim, sum - (val + stepSize), curr, res);
curr.set(i, val);
sum = temp;
}
}
public static void main(String[] args) {
List<Point> res = findPoints(0.2f, 4); //Tried 1.0f, 3 and 0.5f, 3 as well
for (Point p : res) {
for (Float coord : p.dimensions) {
System.out.print(String.valueOf(coord) + ", ");
}
System.out.println(" ");
}
}
}
@pjoshi30
Copy link
Author

Sample output:

1.0, 0.0, 0.0, 0.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, 0.0,
0.8, 0.0, 0.0, 0.19999999,
0.19999999, 0.8, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.8, 0.19999999, 0.0,
0.0, 0.8, 0.0, 0.19999999,
0.19999999, 0.0, 0.8, 0.0,
0.0, 0.19999999, 0.8, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.8, 0.19999999,
0.19999999, 0.0, 0.0, 0.8,
0.0, 0.19999999, 0.0, 0.8,
0.0, 0.0, 0.19999999, 0.8,
0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment