/**
- Algebraic Equation Dataset Generator for Hugging Face
- This script generates diverse datasets of algebraic equations with their solutions,
- producing different valid equations each time it's run, properly formatted for Hugging Face. */
// Utility function to generate a random integer within a range function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
// Utility function to get a random non-zero integer within a range function getRandomNonZeroInt(min, max) { let num = 0; while (num === 0) { num = getRandomInt(min, max); } return num; }
// Simplify a fraction (a/b) to lowest terms function simplifyFraction(numerator, denominator) { const gcd = (a, b) => b === 0 ? a : gcd(b, a % b); const divisor = Math.abs(gcd(numerator, denominator)); return { numerator: numerator / divisor, denominator: denominator / divisor }; }
// Format fraction as a string function formatFraction(numerator, denominator) { if (denominator === 1) return numerator.toString(); if (numerator === 0) return "0";
const simplified = simplifyFraction(numerator, denominator);
return `${simplified.numerator}/${simplified.denominator}`;
}
// Generate linear equation (ax + b = c) function generateLinearEquation() { const a = getRandomNonZeroInt(-10, 10); const b = getRandomInt(-20, 20); const x = getRandomInt(-10, 10); const c = a * x + b;
let equation = "";
if (a === 1) equation = `x`;
else if (a === -1) equation = `-x`;
else equation = `${a}x`;
if (b > 0) equation += ` + ${b}`;
else if (b < 0) equation += ` - ${Math.abs(b)}`;
equation += ` = ${c}`;
return {
type: "linear",
equation,
solution: `x = ${x}`,
x_value: x
};
}
// Generate quadratic equation (ax² + bx + c = 0) function generateQuadraticEquation() { // Generate a quadratic with integer solutions for simplicity const x1 = getRandomInt(-5, 5); const x2 = getRandomInt(-5, 5);
// Using (x - x1)(x - x2) = 0 format
// This expands to x² - (x1 + x2)x + (x1 * x2) = 0
const a = 1;
const b = -(x1 + x2);
const c = x1 * x2;
let equation = "x²";
if (b !== 0) {
if (b === 1) equation += " + x";
else if (b === -1) equation += " - x";
else if (b > 0) equation += ` + ${b}x`;
else equation += ` - ${Math.abs(b)}x`;
}
if (c !== 0) {
if (c > 0) equation += ` + ${c}`;
else equation += ` - ${Math.abs(c)}`;
}
equation += " = 0";
let solution;
if (x1 === x2) {
solution = `x = ${x1}`;
} else {
solution = `x = ${x1} or x = ${x2}`;
}
return {
type: "quadratic",
equation,
solution,
solutions: [x1, x2]
};
}
// Generate polynomial equation function generatePolynomialEquation() { // Generate a 3rd degree polynomial with integer roots for simplicity const x1 = getRandomInt(-3, 3); const x2 = getRandomInt(-3, 3); const x3 = getRandomInt(-3, 3);
// Using (x - x1)(x - x2)(x - x3) = 0 format
// This expands to x³ - (x1+x2+x3)x² + (x1*x2 + x1*x3 + x2*x3)x - (x1*x2*x3) = 0
const a = 1;
const b = -(x1 + x2 + x3);
const c = (x1 * x2 + x1 * x3 + x2 * x3);
const d = -(x1 * x2 * x3);
let equation = "x³";
if (b !== 0) {
if (b === 1) equation += " + x²";
else if (b === -1) equation += " - x²";
else if (b > 0) equation += ` + ${b}x²`;
else equation += ` - ${Math.abs(b)}x²`;
}
if (c !== 0) {
if (c === 1) equation += " + x";
else if (c === -1) equation += " - x";
else if (c > 0) equation += ` + ${c}x`;
else equation += ` - ${Math.abs(c)}x`;
}
if (d !== 0) {
if (d > 0) equation += ` + ${d}`;
else equation += ` - ${Math.abs(d)}`;
}
equation += " = 0";
return {
type: "polynomial",
equation,
solution: `x = ${x1}, x = ${x2}, x = ${x3}`,
solutions: [x1, x2, x3]
};
}
// Generate rational equation function generateRationalEquation() { // Generate a rational equation of the form (ax + b)/(cx + d) = e const c = getRandomNonZeroInt(-5, 5); const d = getRandomInt(-10, 10); const x = getRandomInt(-5, 5);
// Make sure cx + d ≠ 0 for the given x
if (c * x + d === 0) return generateRationalEquation();
const e = getRandomNonZeroInt(-5, 5);
const denominator = c * x + d;
const numerator = e * denominator;
// Expand numerator to ax + b
const a = e * c;
const b = e * d;
let numeratorString = "";
if (a === 1) numeratorString = "x";
else if (a === -1) numeratorString = "-x";
else numeratorString = `${a}x`;
if (b > 0) numeratorString += ` + ${b}`;
else if (b < 0) numeratorString += ` - ${Math.abs(b)}`;
else if (a === 0) numeratorString = "0";
let denominatorString = "";
if (c === 1) denominatorString = "x";
else if (c === -1) denominatorString = "-x";
else denominatorString = `${c}x`;
if (d > 0) denominatorString += ` + ${d}`;
else if (d < 0) denominatorString += ` - ${Math.abs(d)}`;
const equation = `(${numeratorString})/(${denominatorString}) = ${e}`;
return {
type: "rational",
equation,
solution: `x = ${x}`,
x_value: x,
// Include domain restriction
domain_restriction: `x ≠ ${-d / c}`
};
}
// Generate absolute value equation |ax + b| = c function generateAbsoluteValueEquation() { const a = getRandomNonZeroInt(-5, 5); const b = getRandomInt(-10, 10); const c = getRandomInt(1, 10); // Positive value for meaningful absolute value equations
// Solutions: (c - b)/a and (-c - b)/a
const solution1 = (c - b) / a;
const solution2 = (-c - b) / a;
let insideAbs = "";
if (a === 1) insideAbs = "x";
else if (a === -1) insideAbs = "-x";
else insideAbs = `${a}x`;
if (b > 0) insideAbs += ` + ${b}`;
else if (b < 0) insideAbs += ` - ${Math.abs(b)}`;
const equation = `|${insideAbs}| = ${c}`;
let solution;
// Format solutions
if (Number.isInteger(solution1) && Number.isInteger(solution2)) {
solution = `x = ${solution1} or x = ${solution2}`;
} else {
// For fractions
const formattedSolution1 = Number.isInteger(solution1) ?
solution1.toString() : formatFraction(c - b, a);
const formattedSolution2 = Number.isInteger(solution2) ?
solution2.toString() : formatFraction(-c - b, a);
solution = `x = ${formattedSolution1} or x = ${formattedSolution2}`;
}
return {
type: "absolute_value",
equation,
solution,
solutions: [solution1, solution2]
};
}
// Generate system of linear equations (2 variables) function generateSystemOfEquations() { // Generate a system with integer solutions for simplicity const x = getRandomInt(-5, 5); const y = getRandomInt(-5, 5);
// First equation: a1x + b1y = c1
const a1 = getRandomNonZeroInt(-5, 5);
const b1 = getRandomNonZeroInt(-5, 5);
const c1 = a1 * x + b1 * y;
// Second equation: a2x + b2y = c2
// Make sure the equations are not multiples of each other
let a2, b2;
do {
a2 = getRandomNonZeroInt(-5, 5);
b2 = getRandomNonZeroInt(-5, 5);
} while (a1 / a2 === b1 / b2);
const c2 = a2 * x + b2 * y;
// Format equations
let equation1 = "";
if (a1 === 1) equation1 = "x";
else if (a1 === -1) equation1 = "-x";
else equation1 = `${a1}x`;
if (b1 > 0) equation1 += ` + ${b1}y`;
else if (b1 < 0) equation1 += ` - ${Math.abs(b1)}y`;
else if (b1 === 1) equation1 += " + y";
else if (b1 === -1) equation1 += " - y";
equation1 += ` = ${c1}`;
let equation2 = "";
if (a2 === 1) equation2 = "x";
else if (a2 === -1) equation2 = "-x";
else equation2 = `${a2}x`;
if (b2 > 0) equation2 += ` + ${b2}y`;
else if (b2 < 0) equation2 += ` - ${Math.abs(b2)}y`;
else if (b2 === 1) equation2 += " + y";
else if (b2 === -1) equation2 += " - y";
equation2 += ` = ${c2}`;
return {
type: "system_of_equations",
equation: `${equation1}; ${equation2}`,
solution: `x = ${x}, y = ${y}`,
solutions: { x, y }
};
}
// Generate exponential equation (base^(ax+b) = c) function generateExponentialEquation() { const base = [2, 3, 5, 10][getRandomInt(0, 3)]; // Common bases const a = getRandomNonZeroInt(-3, 3); const b = getRandomInt(-5, 5);
// For simplicity, we'll create equations with integer solutions
const x = getRandomInt(-2, 2);
const exponent = a * x + b;
const c = Math.pow(base, exponent);
// Create the equation
let insideExponent = "";
if (a === 1) insideExponent = "x";
else if (a === -1) insideExponent = "-x";
else insideExponent = `${a}x`;
if (b > 0) insideExponent += ` + ${b}`;
else if (b < 0) insideExponent += ` - ${Math.abs(b)}`;
const equation = `${base}^(${insideExponent}) = ${c}`;
return {
type: "exponential",
equation,
solution: `x = ${x}`,
x_value: x
};
}
// Generate logarithmic equation (log_base(ax+b) = c) function generateLogarithmicEquation() { const base = [2, 3, 5, 10][getRandomInt(0, 3)]; // Common bases const c = getRandomInt(1, 3); // Result of the logarithm
// For the input to the logarithm (ax+b), we need a value that equals base^c
const result = Math.pow(base, c);
// Now we create ax+b = result, where x is an integer
const a = getRandomNonZeroInt(-5, 5);
const x = getRandomInt(-3, 3);
const b = result - a * x;
// Create the equation
let logArgument = "";
if (a === 1) logArgument = "x";
else if (a === -1) logArgument = "-x";
else logArgument = `${a}x`;
if (b > 0) logArgument += ` + ${b}`;
else if (b < 0) logArgument += ` - ${Math.abs(b)}`;
const equation = `log_${base}(${logArgument}) = ${c}`;
return {
type: "logarithmic",
equation,
solution: `x = ${x}`,
x_value: x,
// Include domain restriction
domain_restriction: `${a}x + ${b} > 0`
};
}
// Generate trigonometric equation (sin/cos/tan(ax + b) = c) function generateTrigonometricEquation() { const functions = ['sin', 'cos']; const func = functions[getRandomInt(0, 1)];
// Common angle values where sin and cos have nice values
const specialAngles = [
{ angle: 0, sin: 0, cos: 1 },
{ angle: 30, sin: 0.5, cos: Math.sqrt(3)/2 },
{ angle: 45, sin: Math.sqrt(2)/2, cos: Math.sqrt(2)/2 },
{ angle: 60, sin: Math.sqrt(3)/2, cos: 0.5 },
{ angle: 90, sin: 1, cos: 0 },
{ angle: 180, sin: 0, cos: -1 },
{ angle: 270, sin: -1, cos: 0 },
{ angle: 360, sin: 0, cos: 1 }
];
const selectedAngle = specialAngles[getRandomInt(0, specialAngles.length - 1)];
const angleInRadians = selectedAngle.angle * Math.PI / 180;
// Set c based on the selected function and angle
const c = (func === 'sin') ? selectedAngle.sin : selectedAngle.cos;
// For simplicity, we'll use a = 1 and adjust b
const a = 1;
// We want ax + b = angleInRadians, so b = angleInRadians - a*x
const x = getRandomInt(-2, 2);
const b = angleInRadians - a * x;
// Format b in terms of π
let bFormatted;
if (b === 0) {
bFormatted = "";
} else {
const bInTermsOfPi = b / Math.PI;
if (bInTermsOfPi === 1) {
bFormatted = " + π";
} else if (bInTermsOfPi === -1) {
bFormatted = " - π";
} else if (bInTermsOfPi === 0.5) {
bFormatted = " + π/2";
} else if (bInTermsOfPi === -0.5) {
bFormatted = " - π/2";
} else {
// For other values, express as radians
bFormatted = b > 0 ? ` + ${b.toFixed(2)}` : ` - ${Math.abs(b).toFixed(2)}`;
}
}
// Create the equation
const equation = `${func}(x${bFormatted}) = ${c === 0 ? 0 : c === 1 ? 1 : c === -1 ? -1 : c.toFixed(3)}`;
return {
type: "trigonometric",
equation,
solution: `x = ${x}`,
x_value: x
};
}
// Generate step-by-step solution for a linear equation function generateStepByStepLinearSolution() { const example = generateLinearEquation(); const { equation, x_value } = example;
// Parse components from the equation
const parts = equation.split('=');
const leftSide = parts[0].trim();
const rightSide = parseFloat(parts[1].trim());
// Extract coefficients using a simple regex
let coefficientRegex = /(-?\d*)x/;
let match = leftSide.match(coefficientRegex);
let a = match ? (match[1] === '' ? 1 : match[1] === '-' ? -1 : parseInt(match[1])) : 0;
// Extract constant term
let constantTerm = 0;
if (leftSide.includes('+')) {
constantTerm = parseInt(leftSide.split('+')[1]);
} else if (leftSide.includes('-') && leftSide.indexOf('-') !== 0) {
// Handle negative constant that isn't at the beginning
constantTerm = -parseInt(leftSide.split('-')[1]);
}
// Generate step-by-step solution
const steps = [
`Step 1: Start with the original equation: ${equation}`,
`Step 2: Move the constant term to the right side: ${a}x = ${rightSide} - ${constantTerm}`,
`Step 3: Simplify the right side: ${a}x = ${rightSide - constantTerm}`,
`Step 4: Divide both sides by ${a}: x = ${(rightSide - constantTerm) / a}`,
`Step 5: Check the solution: ${a} × ${x_value} + ${constantTerm} = ${a * x_value + constantTerm} ✓`
];
return {
type: "linear_with_steps",
equation,
solution: `x = ${x_value}`,
steps: steps
};
}
// Generate a dataset with a mix of different types of equations function generateAlgebraicDataset(size = 100) { const generators = [ { weight: 15, generator: generateLinearEquation }, { weight: 15, generator: generateQuadraticEquation }, { weight: 10, generator: generatePolynomialEquation }, { weight: 10, generator: generateRationalEquation }, { weight: 10, generator: generateAbsoluteValueEquation }, { weight: 15, generator: generateSystemOfEquations }, { weight: 10, generator: generateExponentialEquation }, { weight: 10, generator: generateLogarithmicEquation }, { weight: 10, generator: generateTrigonometricEquation }, { weight: 5, generator: generateStepByStepLinearSolution } ];
// Calculate total weight
const totalWeight = generators.reduce((sum, g) => sum + g.weight, 0);
const dataset = [];
for (let i = 0; i < size; i++) {
// Randomly select a generator based on weights
let random = Math.random() * totalWeight;
let selectedGenerator = null;
for (const gen of generators) {
random -= gen.weight;
if (random <= 0) {
selectedGenerator = gen.generator;
break;
}
}
// If somehow we didn't select a generator, use the first one
if (!selectedGenerator) {
selectedGenerator = generators[0].generator;
}
// Add the generated example to the dataset
const example = selectedGenerator();
example.id = i + 1;
dataset.push(example);
}
return dataset;
}
// Convert dataset to Hugging Face format function convertToHuggingFaceFormat(dataset) { return dataset.map(item => { let output;
// Handle different equation types differently
if (item.type === "quadratic" || item.type === "absolute_value") {
// For equations with multiple solutions
output = JSON.stringify(item.solutions);
} else if (item.type === "system_of_equations") {
// For systems of equations
output = JSON.stringify(item.solutions);
} else if (item.type === "polynomial") {
// For polynomial equations
output = JSON.stringify(item.solutions);
} else if (item.type === "linear_with_steps") {
// For linear equations with steps
output = JSON.stringify({
solution: item.x_value,
steps: item.steps
});
} else {
// For simple equations with a single solution
output = item.x_value !== undefined ? item.x_value.toString() :
item.solution.replace("x = ", "");
}
return {
"input": item.equation,
"output": output,
"type": item.type // Optionally include the equation type
};
});
}
// Main function to generate and save the dataset
function main() {
// Generate the dataset
const algebraData = generateAlgebraicDataset(1000);
console.log(Generated ${algebraData.length} equations.
);
// Convert to Hugging Face format
const huggingFaceData = convertToHuggingFaceFormat(algebraData);
// Create JSON and JSONL versions
const fs = require('fs');
// Save as JSONL (one JSON object per line) - preferred for Hugging Face
const jsonlData = huggingFaceData.map(item => JSON.stringify(item)).join('\n');
fs.writeFileSync('algebra_dataset.jsonl', jsonlData);
console.log('Saved as algebra_dataset.jsonl');
// Save as JSON (array format)
fs.writeFileSync('algebra_dataset.json', JSON.stringify(huggingFaceData, null, 2));
console.log('Saved as algebra_dataset.json');
// Create train-validation-test split (80/10/10 split)
const shuffle = arr => [...arr].sort(() => Math.random() - 0.5);
const shuffled = shuffle(huggingFaceData);
const trainSize = Math.floor(shuffled.length * 0.8);
const valSize = Math.floor(shuffled.length * 0.1);
const train = shuffled.slice(0, trainSize);
const val = shuffled.slice(trainSize, trainSize + valSize);
const test = shuffled.slice(trainSize + valSize);
// Save splits
fs.writeFileSync('train.jsonl', train.map(item => JSON.stringify(item)).join('\n'));
fs.writeFileSync('validation.jsonl', val.map(item => JSON.stringify(item)).join('\n'));
fs.writeFileSync('test.jsonl', test.map(item => JSON.stringify(item)).join('\n'));
console.log(`Split into train (${train.length}), validation (${val.length}), and test (${test.length}) sets.`);
console.log('Ready for upload to Hugging Face!');
}
// Execute the main function main();
- Downloads last month
- 9