Last active
March 20, 2020 03:53
-
-
Save thomastay/85293280fa640329e282140b8b6ba49b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculates transitive closure of a relation | |
# EECS 203 students: You are FORBIDDEN from using this code | |
# for homework purposes. Only use this for self-learning | |
# and testing. | |
import strutils, sequtils, sugar, strformat | |
type Matrix = seq[seq[bool]] | |
func `$`(m: Matrix): string = | |
for row in m: | |
let zeroRow = row.map(x => (if x: 1 else: 0)) | |
result.add(zeroRow.join(", ") & "\n") | |
func toMatrix(m: seq[seq[int]]): Matrix = | |
for row in m: | |
let toBoolRow = row.mapIt(it == 1) | |
result.add(toBoolRow) | |
proc warshall(m: Matrix): void = | |
var m = m # Shadow m, create var copy | |
let n = high(m) # High(m) is the number of rows - 1 | |
for k in 0..n: | |
echo fmt"W[{k+1}] = " | |
for i in 0..n: | |
for j in 0..n: | |
m[i][j] = m[i][j] or (m[i][k] and m[k][j]) | |
echo m | |
let x = @[ | |
@[0, 0, 0, 0, 0], | |
@[0, 0, 1, 0, 1], | |
@[0, 0, 0, 0, 1], | |
@[1, 0, 0, 0, 0], | |
@[0, 1, 1, 0, 0], | |
].toMatrix() | |
echo "Original Matrix" | |
echo x | |
warshall(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment