Skip to content

Instantly share code, notes, and snippets.

@ralphschuler
Created November 1, 2023 22:41
Show Gist options
  • Save ralphschuler/701b63e229537c2ba7798fa0c52d708f to your computer and use it in GitHub Desktop.
Save ralphschuler/701b63e229537c2ba7798fa0c52d708f to your computer and use it in GitHub Desktop.
Random Seed Management and Comparison
type Vector = number[];
type VectorPair = [Vector, Vector];
class MathOperations {
static calculateDotProduct(vectorA: Vector, vectorB: Vector): number {
return vectorA.reduce((accumulator, value, index) => accumulator + value * vectorB[index], 0);
}
static calculateNorm(vector: Vector): number {
return Math.sqrt(this.calculateDotProduct(vector, vector));
}
}
class ArrayManipulations {
static padWithZeros(vector: Vector, targetLength: number): Vector {
const paddedVector = [...vector];
while (paddedVector.length < targetLength) {
paddedVector.push(0);
}
return paddedVector;
}
static normalizeLengths(vector1: Vector, vector2: Vector): VectorPair {
const maxLength = Math.max(vector1.length, vector2.length);
return [this.padWithZeros(vector1, maxLength), this.padWithZeros(vector2, maxLength)];
}
}
class SimilarityMetrics {
private static normalizeArrayLengths(vectorA: Vector, vectorB: Vector): VectorPair {
return ArrayManipulations.normalizeLengths(vectorA, vectorB);
}
static calculateCosineSimilarity(vectorA: Vector, vectorB: Vector): number {
[vectorA, vectorB] = this.normalizeArrayLengths(vectorA, vectorB);
return MathOperations.calculateDotProduct(vectorA, vectorB) /
(MathOperations.calculateNorm(vectorA) * MathOperations.calculateNorm(vectorB));
}
// ... other similarity methods (not shown for brevity)
}
class SeedManager {
private seedDatabase: Vector[];
private readonly maxSize: number;
private readonly similarityThreshold: number;
constructor(maxSize: number = 100, similarityThreshold: number = 0.9) {
this.seedDatabase = [];
this.maxSize = maxSize;
this.similarityThreshold = similarityThreshold;
}
addSeed(newSeed: Vector): void {
for (const existingSeed of this.seedDatabase) {
const similarity = SimilarityMetrics.calculateCosineSimilarity(newSeed, existingSeed);
if (similarity >= this.similarityThreshold) {
throw new Error("New seed is too similar to an existing seed.");
}
}
if (this.seedDatabase.length >= this.maxSize) {
this.seedDatabase.shift(); // Remove the oldest seed
}
this.seedDatabase.push(newSeed);
}
// Additional functionality can be added as needed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment