Created
December 15, 2014 15:01
-
-
Save maraigue/809e6455bd192e1907fa 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
def create_field(str) | |
str = str.gsub(/\A\n+|\n+\z/, "") | |
str.split("\n").map{ |line| line.split(//) } | |
end | |
def find_start_goal(field) | |
result = {} | |
field.each_with_index do |line, i| | |
line.each_with_index do |cell, j| | |
if cell == "S" || cell == "G" | |
result[cell] = [i, j] | |
end | |
end | |
end | |
result | |
end | |
def main(field, prob_goal_direction) | |
start, goal = find_start_goal(field).values_at("S", "G") | |
pos = start | |
# 探索 | |
i = 0 | |
until pos == goal | |
i += 1 | |
direction = [0, 0] | |
if rand() < prob_goal_direction | |
# ゴールのある向きへ向かう。確率は距離で決定 | |
x_distance_to_goal = goal[0] - pos[0] | |
y_distance_to_goal = goal[1] - pos[1] | |
if rand(x_distance_to_goal.abs + y_distance_to_goal.abs) < x_distance_to_goal.abs | |
direction = [pos[0] > 0 ? 1 : -1, 0] | |
else | |
direction = [0, pos[1] > 0 ? 1 : -1] | |
end | |
else | |
# ランダムに動く。 | |
case rand(4) | |
when 0 | |
direction = [1, 0] | |
when 1 | |
direction = [-1, 0] | |
when 2 | |
direction = [0, 1] | |
when 3 | |
direction = [0, -1] | |
end | |
end | |
pos_temp = [pos[0] + direction[0], pos[1] + direction[1]] | |
redo if field[pos_temp[0]][pos_temp[1]] == "@" | |
#puts "Step #{i}: #{pos.inspect} -> #{pos_temp.inspect}" | |
pos = pos_temp | |
end | |
puts "Probability_of_going_for_goal,#{prob_goal_direction},Steps,#{i}" | |
end | |
if $0 == __FILE__ | |
# マップ定義 | |
field = create_field <<MAP | |
@@@@@@@@@ | |
@S @ | |
@ @ | |
@@@ @@@ @ | |
@ @ @ | |
@ @ G @ | |
@ @ @ @ | |
@ @ | |
@@@@@@@@@ | |
MAP | |
# コマンドライン引数には、確率(0から1の間)を与える。 | |
# その確率でゴールのある向きへ向かい、それ以外はランダムに進む。 | |
prob = Float(ARGV[0]) | |
main(field, prob) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment