// List of cities
const cities = ["New York", "Denver", "California", "San Fransisco", "Las Vegas",
"Seattle", "Chicago", "Los Angeles", "Dallas", "Columbus"];
// Function to create data for our travel planner project
function createDataForTravelPlanner(){
// Initialising number of nodes in the graph dynamically
numVertices = Math.floor(Math.random() * cities.length) + 1;
// Create data for vertices
let vertices = [];
for(let i = 1; i <= numVertices; i++){
// Storing the id and the name of the city
vertices.push({ id: i, label: cities[i - 1] })
}
// Creating data for edges
let edges = [];
for(let i = 2; i <= numVertices; i++) {
// Randomly picking a neighbour node from 0 to i - 1 to create an edge
let neighbour = i - Math.floor(Math.random() * Math.min(i - 1, 3) + 1);
// Adding the edge between the node and the neighbour
edges.push({ type: 0, // 0 denotes bus route and 1 denotes air route
from: i, // the node
to: neighbour, // the neighbour
color: 'orange', // color of the edge
label: String(Math.floor(Math.random() * 70) + 30) //random distance
});
}
// We will use these variables in later part of the chapter
src = 1;
dst = numVertices;
// Add randomness to the edges in the graph
for(let i = 1; i <= numVertices/2; ){
// Generate two random integers in the range of 1 to numVertices
let n1 = Math.floor(Math.random() * numVertices) + 1;
let n2 = Math.floor(Math.random() * numVertices) + 1;
if(n1 != n2) {
if(n1 < n2) {
// swap n1 and n2 to make n1 larger than n2
let tmp = n1;
n1 = n2;
n2 = tmp;
}
// Create a flag to store three states:
// 1. Assign value of 0 if there is no edge between n1 and n2
// 2. Assign value of 1 if there is an edge denoting the bus route
// 3. Assign value of 2 if there is an edge denoting the aeroplane route
let typeOfEdge = 0;
// Iterate for all the edges
for(let j = 0; j < edges.length; j++) {
// Check if edge between n1 and n2 already exists
if(edges[j]['from'] === n1 && edges[j]['to'] === n2) {
// Check for the bus route
if(edges[j]['type'] === 0)
typeOfEdge = 1; // flag to denote bus route exist
else
typeOfEdge = 2; // flag to denote air route exist
}
}
// Check if a bus or no route exists between n1 and n2
if(typeOfEdge <= 1) {
// If no route exists
if (typeOfEdge === 0 && i < numVertices / 4) {
// Create an edge between n1 and n2
edges.push({
type: 0,
from: n1,
to: n2,
color: 'orange',
label: String(Math.floor(Math.random() * 70) + 30)
});
} else {
// Create an edge for air route between n1 and n2
edges.push({
type: 1,
from: n1,
to: n2,
color: 'green',
label: String(Math.floor(Math.random() * 50) + 1)
});
}
i++;
}
}
}
// Creating the data object for vis
let data = {
nodes: vertices,
edges: edges
};
// Return the final object containing the information for the graph
return data;
}
const graphData = createDataForTravelPlanner();
console.log(graphData);