Skip to content

Instantly share code, notes, and snippets.

@rschwabco
Last active March 20, 2023 21:43
Show Gist options
  • Save rschwabco/1000682652d25e0d2add0e9f7924fc53 to your computer and use it in GitHub Desktop.
Save rschwabco/1000682652d25e0d2add0e9f7924fc53 to your computer and use it in GitHub Desktop.
qModified.ts
type Vector = {
id: string
values: number[]
}
const assertSameLength = (vectors: Vector[]): void => {
if (new Set(vectors.map(vector => vector.values.length)).size !== 1) {
throw new Error('All vectors must have the same length');
}
};
const combineVectors = (vectors: Vector[], operation: (v1: number, v2: number) => number): Vector => {
assertSameLength(vectors);
const combinedId = `combined_${vectors.map(vector => vector.id).join('_')}`;
const values = vectors[0].values.map((_, index) => {
const sum = vectors.reduce((acc, vector) => acc + vector.values[index], 0);
return operation(vectors[0].values[index], sum);
});
return { id: combinedId, values };
};
const multiplyScalarToVector = (vector: Vector, scalar: number): Vector => {
const newId = `${vector.id}*${scalar}`;
const newValues = vector.values.map(val => val * scalar);
return { id: newId, values: newValues };
};
const negVec = (q: Vector, negativeVectors: Vector[], beta: number = 1.0): Vector => {
const avgNegVec: Vector = {
id: 'avgNegVec',
values: combineVectors(negativeVectors, (v1, v2) => v2 / negativeVectors.length).values
};
const qMinusAvgNegVec = combineVectors([q, avgNegVec], (v1, v2) => v1 - v2);
const betaTimesQMinusAvgNegVec = multiplyScalarToVector(qMinusAvgNegVec, beta);
const qModified: Vector = {
id: `${q.id}_modified`,
values: combineVectors([q, betaTimesQMinusAvgNegVec], (v1, v2) => v1 + v2).values
};
return qModified;
};
console.log(negVec(vec, [neg1, neg2]))
// { id: 'original_modified', values: [ 0.75, 0.25 ] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment