function bellmanFord(start, graph) {
const distances = {};
const predecessors = {};
// Initialize distances and predecessors
for (const node in graph) {
distances[node] = Infinity;
predecessors[node] = null;
}
distances[start] = 0;
// Relax edges repeatedly
for (let i = 0; i < Object.keys(graph).length - 1; i++) {
for (const node in graph) {
for (const edge of graph[node]) {
const weight = -Math.log(edge.weight);
const nextNode = edge.node;
if (distances[node] + weight < distances[nextNode]) {
distances[nextNode] = distances[node] + weight;
predecessors[nextNode] = node;
}
}
}
}
// Check for negative cycles
let cycle = [];
let cycleExists = false;
let conversionRate = [];
for (let i = 0; i < Object.keys(graph).length - 1; i++) {
for (const node in graph) {
for (const edge of graph[node]) {
const weight = -Math.log(edge.weight);
const nextNode = edge.node;
if (distances[node] + weight < distances[nextNode]) {
cycleExists = true;
// Negative cycle found, return its path and weight
let current = node;
while (!cycle.includes(current)) {
cycle.push(current);
current = predecessors[current];
}
cycle.push(current);
cycle.reverse();
// Calculate the weight of the cycle
let cycleWeight = 0;
for (let i = 0; i < cycle.length - 1; i++) {
for (const edge of graph[cycle[i]]) {
if (edge.node === cycle[i + 1]) {
conversionRate.push(edge.weight);
cycleWeight += -Math.log(edge.weight);
}
}
}
console.log("conversionRate: ", conversionRate);
return { path: cycle, weight: cycleWeight };
}
}
if (cycleExists) {
break;
}
}
}
// No negative cycle found, return null
return null;
}
bellmanFord("USD", graphData);
sample graph
const graphData = {
USD: [
{node: "Euro", weight: 3 },
{node: "AED", weight: -2}
],
Euro: [{node: "USD", weight: -6}],
AED: [{node: "USD", weight: 3}]
}
I have written the bellman Ford algorithm to find the triangular arbitrage opportunity by using the negative weight cycle.
Let's say there is a negative cycle of
USD=> Euro=>USD
I want the above code to do
- it should return to the path of the cycle.
- path of the cycle should start and end at the same node (eg if it starts from USD it should come back to USD)
- it should return the weights of edges (that will be used for currency conversion).
- it should return the weight of the cycle.
- should return null if no negative cycle is found instead of returning cycle with positive weight
- possible optimization
The above code for some reason returns the cycle even if it is positive