Jump to content

Floyd-Warshall algorithm: Difference between revisions

Show the output required by the task, use the task sample data instead of random data
m (→‎{{header|ALGOL 68}}: fix bugette)
(Show the output required by the task, use the task sample data instead of random data)
Line 3,174:
 
=={{header|JavaScript}}==
Using output code translated from the Lua sample.
{{output?|Javascript}}
<syntaxhighlight lang="javascript">var'use graph = [];strict'
let numVertices = 4;
for (i = 0; i < 10; ++i) {
let weights = [ [ 1, 3, -2 ], [ 2, 1, 4 ], [ 2, 3, 3 ], [ 3, 4, 2 ], [ 4, 2, -1 ] ];
 
let graph = [];
for (let i = 0; i < 10numVertices; ++i) {
graph.push([]);
for (let j = 0; j < 10numVertices; ++j)
graph[i].push(i == j ? 0 : 9999999);
}
 
for (let i = 10; i < 10weights.length; ++i) {
let w = weights[i];
graph[0][i] = graph[i][0] = parseInt(Math.random() * 9 + 1);
graph[w[0] - 1][w[1] - 1] = w[2];
}
 
let nxt = [];
for (klet i = 0; ki < 10numVertices; ++ki) {
nxt.push([]);
for (let j = 0; j < numVertices; ++j)
nxt[i].push(i == j ? 0 : j + 1);
}
 
for (let k = 0; k < numVertices; ++k) {
for (let i = 0; i < numVertices; ++i) {
for (let j = 0; j < numVertices; ++j) {
if (graph[i][j] > graph[i][k] + graph[k][j]) {
graph[i][j] = graph[i][k] + graph[k][j];
nxt[i][j] = nxt[i][k];
}
}
}
}
 
console.log("pair dist path");
for (k = 0; k < 10; ++k) {
for (let i = 0; i < 10numVertices; ++i) {
for (let j = 0; j < 10numVertices; ++j) {
if (graph[i][j] >!= graph[i][k] + graph[k][j]) {
let graph[i][j]u = graph[i][k] + graph[k][j]1;
let v = j + 1;
let path = u + " -> " + v + " " + graph[i][j].toString().padStart(2) + " " + u;
do {
u = nxt[u - 1][v - 1];
path = path + " -> " + u;
} while (u != v);
console.log(path)
}
}
}
console.log(graph);</syntaxhighlight>
 
{{out}}
console.log(graph);</syntaxhighlight>
<pre>
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
</pre>
 
=={{header|jq}}==
3,043

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.