Skip to content

Commit

Permalink
'Finished' Groovy greedy algorithm implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Ty Morris committed Dec 6, 2016
1 parent da3f6cd commit fd98e41
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 1 deletion.
1 change: 1 addition & 0 deletions groovy/greedy/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
run: ; groovy TSP.groovy a280.xml
6 changes: 5 additions & 1 deletion groovy/greedy/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
Tirey Morris
Solution to Traveling Salesman Problem using Greedy Algorithm

Author: Tirey Morris
Usage: $ make run
(depends on file a280.xml being in groovy/greedy directory. This can be modified in the makefile.)
87 changes: 87 additions & 0 deletions groovy/greedy/TSP.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/**
* Tirey Morris (tam3354)
* CS 345 (Rellermeyer)
* December 5th, 2016
*/

class TSP {

static final BigDecimal MAX = BigDecimal.valueOf(Double.MAX_VALUE)

static void main(String... args) {
if (args.size() < 1 || !args[0].endsWith(".xml")) {
throw new IllegalArgumentException("Must provide .xml input file")
}

def graph = parseGraph(new File(args[0]))
def results = solve(graph)
println("path = ${results[0]}\n\ntotal cost = ${results[1]}")
}

static parseGraph(File xmlFile) {
def tspXml = new XmlParser().parse(xmlFile)
def graph = tspXml.graph.vertex
}

static getNodes(graph) {
def nodes = [:]
graph.eachWithIndex { vertex, i ->
nodes[i] = vertex.edge
}
nodes
}

static Integer getNumFromEdge(edge) {
edge.value().text().toInteger()
}

static BigDecimal getCostFromEdge(edge) {
new BigDecimal(edge.attributes().get("cost"))
}

static List solve(graph) {
def nodes = getNodes(graph)
def path = []
def total = 0
int start = 0
int current = 0

while (nodes.size() > 0) {
path << current
def edges = nodes[current]
nodes.remove(current)

def min = MAX

edges.each { edge ->
Integer num = getNumFromEdge(edge)
BigDecimal cost = getCostFromEdge(edge)

if (cost < min && nodes[num]) {
min = cost
current = num
}
}

if (min != MAX) {
total += min
}

if (nodes.size() == 1) {
edges.each { edge ->
Integer num = getNumFromEdge(edge)
BigDecimal cost = getCostFromEdge(edge)

if (num == start) {
total += cost
}

}
}
}

path << start

[path, total]
}
}

0 comments on commit fd98e41

Please sign in to comment.