Skip to content

Instantly share code, notes, and snippets.

@Denis1990
Created September 17, 2016 10:44
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 Denis1990/f67a1130973de378d9d4c2dc01730d09 to your computer and use it in GitHub Desktop.
Save Denis1990/f67a1130973de378d9d4c2dc01730d09 to your computer and use it in GitHub Desktop.
vector data structure
public class PointVector implements WritableComparable<PointVector> {
/**
* Keep the tfIdf values of the terms of a document
*/
private Vector<Double> data = new Vector<>();
public PointVector(double [] values) {
this.data = new Vector<>(values.length);
this.data.addAll(Doubles.asList(values));
}
public PointVector(List<Double> values) {
this.data = new Vector<>(values.size());
this.data.addAll(values);
}
public PointVector(String [] values) {
this.data = new Vector<>(values.length);
for (String s: values) {
this.data.add(Double.valueOf(s));
}
}
public PointVector() {
this.data = new Vector<>();
}
public double[] points() {
return Doubles.toArray(data);
}
/**
* Subtract the values of this vector from the PointVector passed as argument
* @param subtracted
* @return
*/
public PointVector sub(PointVector subtracted) {
int N = this.data.size();
double [] vals = new double[N];
for (int i = 0; i < N; i++) {
vals[i] = this.data.get(i) - subtracted.get(i);
}
return new PointVector(vals);
}
public PointVector add(PointVector vec) {
int N = this.data.size();
double [] vals = new double[N];
for (int i = 0; i < N; i++) {
vals[i] = this.data.get(i) + vec.get(i);
}
return new PointVector(vals);
}
/**
* Compute the dot product of this vector with the one passed as argument
* @param vector
* @return
*/
public double dotProduct(PointVector vector) {
int N = this.data.size();
double sum = 0.0;
for (int i = 0; i < N; i++) {
sum += this.data.get(i) * vector.get(i);
}
return sum;
}
@Override
public int compareTo(PointVector pointVector) {
return 0;
}
@Override
public void write(DataOutput dataOutput) throws IOException {
dataOutput.writeInt(data.size());
for (double d : data) {
dataOutput.writeDouble(d);
}
}
@Override
public void readFields(DataInput dataInput) throws IOException {
int s = dataInput.readInt(); // read the size of the vector
}
public Double get(int i) {
return this.data.get(i);
}
public int size() {
return this.data.size();
}
@Override
public String toString() {
if (data.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for (double d : data) {
sb.append(d);
sb.append(", ");
}
final int pos = sb.lastIndexOf(",");
sb.delete(pos, pos + 1);
sb.append("]");
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment