En este momento, tengo que precalcular el costo de floyd warshall y la matriz de ruta cada vez que se carga mi servidor.
Esto es para un mapa que es N por N. Solo tenemos un par de mapas, así que creo que debería precalcular las variables antes de que el servidor se inicie.
tengo 4 variables
Costo -> Matriz de valores.
Ruta -> Matriz de tuplas
TupleVal -> Tuple como clave asignada a un número (objeto Map() en JS)
IndexVal -> Número como clave asignada a una Tupla (objeto Map() en JS)'
¿Cómo puedo calcular estas 4 variables UNA VEZ y almacenarlas en algún lugar de manera que sea relativamente fácil de recuperar? ¿Debe hacerse esto a través de JSON? Si es así, ¿cómo puedo escribir en un archivo JSON y leer de un archivo JSON estas estructuras de datos específicas?
//This is the map I use. A Tuple is converted to a string which maps to number class ArrayKeyedMap extends Map { get(array) { return super.get(this.toKey(array)); } set(array, value) { return super.set(this.toKey(array), value); } has(array) { return super.has(this.toKey(array)); } delete(array) { return super.delete(this.toKey(array)); } toKey(array) { return JSON.stringify(array); } } . . . // This is what I return ForbiddenVals and tupleVal are arraykeyedmap object // index is a map object, mapping a number to a tuple. (x,y) // path and cost are a 2 dimensional array, which contains numbers. return [path, cost, tupleVal, index, ForbiddenVals]Arriba, son básicamente las estructuras de datos que uso. ¿Cuál es la forma más fácil de calcular estos valores UNA VEZ, para que nunca más tenga que hacerlo a menos que haga un cambio en los mapas?
Gracias
Si está utilizando Express, puede guardar el JSON en un archivo con fs
const fs = require('fs'); const path = require('path'); //resolve a relative path to an absolute one const cacheDir = path.resolve('./json'); //the name of the json file, can be anything in any directory const jsonFile = `${cacheDir}/json/n_x_n.map.json`; let data; //create the cache directories if they don't exist if(!fs.existsSync(`${cacheDir}/json`)) { fs.mkdirSync(`${cacheDir}/json`, {recursive: true}); } //if the JSON file does not exist, generate the json and save it to the disk if(!fs.existsSync(jsonFile)) { data = genData(); //this is where you generate hte values once fs.writeFile(jsonFile, JSON.stringify(data), (err) => { if(err) { console.error('Couldn\'t save JSON', err); } else { console.log('Saved JSON'); } } } else { //otherwise load the JSON from the file data = JSON.parse(fs.readFileSync(jsonFile)); } //do whatever with the dataSi es solo un sitio web, podría usar localstorage
//load the data from localStorage let data = localStorage.getItem('json'); //if there is no data in the localStorage, generate the data and save it if(!data) { data = genData(); localStorage.setItem('json', data); } //do whatever with the data