Groovy web console

subscribe to the feed Subscribe
to this
site
Untitled (via #groovywebconsole)
tweet this snippet Tweet
this
script

Untitled

Published 1 week ago by Anonymous
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
@Grab(group='org.jgrapht', module='jgrapht-core', version='1.1.0')

import org.jgrapht.graph.SimpleWeightedGraph
import org.jgrapht.graph.DefaultWeightedEdge
import org.jgrapht.alg.shortestpath.DijkstraShortestPath


def g = new SimpleWeightedGraph(DefaultWeightedEdge.class)

int h = 12
int w = 28

def s = new Scanner("""# #                        #
# ..........      ##########
# . #######.....#........  #
# ........#   .       # .  #
# . # X   #........   # .  #
# . #######.  ^   .   # .  #
# .        . ^^^  .......  #
# ..........  ^   .   # .  #
# .        .      .   # .  #
# .................   # .  #
#                     # @  #
#                     #    #""")

def inp = (1..h).collect { s.nextLine().toCharArray() }

def POP = { c -> c == '.' || c == '@' || c == 'X'}

for (int y = 0; y < h; y++)
    for (int x = 0; x < w; x++) {
        if (POP(inp[y][x])) {
            g.addVertex("v."+y+"."+x)
        }
    }
    
def addEdge = { x1, y1, x2, y2 ->
    if (POP(inp[y1][x1]) && POP(inp[y2][x2])) {
        g.addEdge("v."+y1+"."+x1, "v."+y2+"."+x2)
    }
}
    
for (int y = 0; y < h; y++)
    for (int x = 0; x < w; x++) {
        addEdge(x, y, x, y-1)
        addEdge(x, y, x, y+1)
        addEdge(x, y, x-1, y)
        addEdge(x, y, x+1, y)
    }

def path = DijkstraShortestPath.findPathBetween(g, "v.10.24", "v.4.6")

path.getVertexList().each { 
    def c = it.split("\\.")
    inp[c[1] as int][c[2] as int] = '*'
}

println inp.join("\n")

ans = """
# #                        #
# **********      ##########
# * #######****.#........  #
# *****...#   *       # .  #
# . # X   #...*****   # .  #
# . #######.  ^   *   # .  #
# .        . ^^^  *******  #
# ..........  ^   .   # *  #
# .        .      .   # *  #
# .................   # *  #
#                     # @  #
#                     #    #
"""