Sreekar_0125

Untitled

Oct 29th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require("fs");
  2.  
  3. function convertToBase10(numberInBaseStr, baseStr) {
  4.   const base = parseInt(baseStr, 10);
  5.  
  6.   if (isNaN(base) || base < 2 || base > 36) {
  7.     throw new Error("Base must be a number between 2 and 36.");
  8.   }
  9.   const numberStr = numberInBaseStr.toUpperCase();
  10.  
  11.   const validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".slice(0, base);
  12.  
  13.   for (const char of numberStr) {
  14.     if (!validChars.includes(char)) {
  15.       throw new Error(`Invalid digit '${char}' for base ${base}.`);
  16.     }
  17.   }
  18.  
  19.   const result = parseInt(numberStr, base);
  20.   if (isNaN(result)) {
  21.     throw new Error(`Invalid number '${numberInBaseStr}' for base ${base}.`);
  22.   }
  23.  
  24.   return result;
  25. }
  26.  
  27. // Lagrange Interpolation
  28. function computeConstantTerm(points) {
  29.   let c0 = 0;
  30.   const m = points.length - 1;
  31.  
  32.   for (let i = 0; i <= m; i++) {
  33.     const xi = points[i].x;
  34.     const yi = points[i].y;
  35.     let Li0 = 1;
  36.  
  37.     for (let j = 0; j <= m; j++) {
  38.       if (j !== i) {
  39.         const xj = points[j].x;
  40.         const numerator = -xj;
  41.         const denominator = xi - xj;
  42.  
  43.         Li0 *= numerator / denominator;
  44.       }
  45.     }
  46.  
  47.     c0 += yi * Li0;
  48.   }
  49.  
  50.   return c0;
  51. }
  52.  
  53.  
  54. // this reads json file input
  55. const d = fs.readFileSync("points.json", "utf8");
  56. data = JSON.parse(d);
  57.  
  58. const points = []
  59. for (const [key, value] of Object.entries(data)) {
  60.   console.log(`${key}: ${value["base"]}`);
  61.   if(key == "keys") {
  62.     continue;
  63.   }
  64.   const nw = {
  65.     "x": parseInt(key),
  66.     "y": convertToBase10(value["value"],value["base"])
  67.   }
  68.   points.push(nw);
  69. }
  70. answer = {
  71.     "constant term": computeConstantTerm(points),
  72. }
  73. jsonString = JSON.stringify(answer)
  74. fs.writeFile("answer.json", jsonString, (err) => {
  75.   if (err) {
  76.     console.error("Error writing JSON to file:", err);
  77.   } else {
  78.     console.log("JSON data has been written to data.json");
  79.   }
  80. });
  81.  
  82.  
Advertisement
Add Comment
Please, Sign In to add comment