-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem.rb
More file actions
84 lines (74 loc) · 1.67 KB
/
Copy pathproblem.rb
File metadata and controls
84 lines (74 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require_relative "graph"
class Problem
attr_reader :size, :start, :goal, :grid
# Creates a fully connected grid that is width by width
def initialize(width, start, goal)
@grid = Graph.new(width**2)
@size = width**2
@start = start
@goal = goal
connect(width**2)
end
# Simple util to look at the problem
def display
puts "start state: #{@start}"
puts "goal state: #{@goal}"
puts "adjancy matrix: "
@grid.display
end
def is_goal(s)
s == @goal
end
def node_cords(n)
@grid.node_cords(n)
end
# Checks for neighboring train stations - O(n)
def stations(*args)
# If two args then x, y cords
# Other wise input is node id
if args.size > 1
x = args[0]
y = args[1]
else
n = args[0]
cords = @grid.node_cords(n)
if cords
paren1 = cords.index('(')
paren2 = cords.index(')')
x = cords[paren1 + 1].to_i
y = cords[paren2 - 1].to_i
else
return []
end
end
delta = 1
up = @grid.node_id(x, y - delta)
down = @grid.node_id(x, y + delta)
right = @grid.node_id(x + delta, y)
left = @grid.node_id(x - delta, y)
return [up, down, left, right].reject {|j| j == -1}
end
# Returns connection stations to station s - O(n)
def succesors(s)
neighbors = stations(s)
neighbors.reject {|u| adjacent(s, u) != true}
end
def adjacent(s1, s2)
@grid.adjacent(s1, s2)
end
# Create a fully connect grid for the problem
def connect(node_count)
for v1 in 0..node_count - 1
neighbors = stations(v1)
neighbors.each do |v2|
neighbors1 = stations(v1)
neighbors2 = stations(v2)
if v1 != v2
@grid.add(v1, v2, 1)
end
end
end
# Add this to run TSP style algorithms
# @grid.add(@start, @goal, 1)
end
end