Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require("fs");
- function convertToBase10(numberInBaseStr, baseStr) {
- const base = parseInt(baseStr, 10);
- if (isNaN(base) || base < 2 || base > 36) {
- throw new Error("Base must be a number between 2 and 36.");
- }
- const numberStr = numberInBaseStr.toUpperCase();
- const validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".slice(0, base);
- for (const char of numberStr) {
- if (!validChars.includes(char)) {
- throw new Error(`Invalid digit '${char}' for base ${base}.`);
- }
- }
- const result = parseInt(numberStr, base);
- if (isNaN(result)) {
- throw new Error(`Invalid number '${numberInBaseStr}' for base ${base}.`);
- }
- return result;
- }
- // Lagrange Interpolation
- function computeConstantTerm(points) {
- let c0 = 0;
- const m = points.length - 1;
- for (let i = 0; i <= m; i++) {
- const xi = points[i].x;
- const yi = points[i].y;
- let Li0 = 1;
- for (let j = 0; j <= m; j++) {
- if (j !== i) {
- const xj = points[j].x;
- const numerator = -xj;
- const denominator = xi - xj;
- Li0 *= numerator / denominator;
- }
- }
- c0 += yi * Li0;
- }
- return c0;
- }
- // this reads json file input
- const d = fs.readFileSync("points.json", "utf8");
- data = JSON.parse(d);
- const points = []
- for (const [key, value] of Object.entries(data)) {
- console.log(`${key}: ${value["base"]}`);
- if(key == "keys") {
- continue;
- }
- const nw = {
- "x": parseInt(key),
- "y": convertToBase10(value["value"],value["base"])
- }
- points.push(nw);
- }
- answer = {
- "constant term": computeConstantTerm(points),
- }
- jsonString = JSON.stringify(answer)
- fs.writeFile("answer.json", jsonString, (err) => {
- if (err) {
- console.error("Error writing JSON to file:", err);
- } else {
- console.log("JSON data has been written to data.json");
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment