Created
December 6, 2012 09:02
-
-
Save humbroll/4223091 to your computer and use it in GitHub Desktop.
find mines
This file contains hidden or 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
require 'benchmark' | |
# 출처 : http://howproject.net/ps/wiki.php/FindMines | |
# 정수 n과 m 에 대하여, n x m 크기의 지뢰밭에서 모든 지뢰의 힌트 위치를 출력 | |
# 예) 4X4 지뢰밭에 지뢰가 두개 있고, 각각을 '*' 로 표시한다고 하면 지뢰밭은 다음과 같이 표시할 수 있다. | |
# * . . . | |
# . . . . | |
# . * . . | |
# . . . . | |
# 각 칸에서 최대 8개의 방위에 대해 인접한 칸에 몇개의 지뢰가 있는지(힌트위치)를 출력한다고 하면 | |
# * 1 0 0 | |
# 2 2 1 0 | |
# 1 * 1 0 | |
# 1 1 1 0 | |
# 입력) 임의의 정수 n, m( 0 < n, m <= 100 ) | |
# 3 5 | |
# 출력) n x m 의 지뢰밭을 형성 지뢰가 없는 칸은 '.' , 지뢰는 '*' 로 표시, 지뢰는 1/8 정도의 확률로 랜덤하게 존재 | |
# 한칸을 띄우고 힌트위치를 출력 | |
class FindMine | |
def initialize(row, column) | |
@row, @column = row, column | |
@mine_count = mine_count | |
@mine_map = generate | |
puts "row:#{@row}, column:#{@column}, mine_count:#{@mine_count}" | |
end | |
def render | |
@mine_map.each do |row| | |
puts row.map{|r| r.zero? ? "." : "*"}.join(" ") | |
end | |
end | |
def render_with_hint | |
hint_map = Array.new(@row){Array.new(@column, 0)} | |
@mine_map.each_with_index do |i, r| | |
i.each_with_index do |j, c| | |
hint_map[r][c] = if !j.zero? | |
"*" | |
else | |
count = 0 | |
count += @mine_map[r-1][c-1].to_i rescue 0 | |
count += @mine_map[r-1][c].to_i rescue 0 | |
count += @mine_map[r-1][c+1].to_i rescue 0 | |
count += @mine_map[r][c-1].to_i rescue 0 | |
count += @mine_map[r][c+1].to_i rescue 0 | |
count += @mine_map[r+1][c-1].to_i rescue 0 | |
count += @mine_map[r+1][c].to_i rescue 0 | |
count += @mine_map[r+1][c+1].to_i rescue 0 | |
count | |
end | |
end | |
end | |
hint_map.each do |h| | |
puts h.join(" ") | |
end | |
end | |
private | |
def mine_count | |
(@row * @column * 0.125).to_i | |
end | |
def generate | |
map = Array.new(@row){Array.new(@column, 0)} | |
mine_indices = (0..(@row * @column-1)).to_a.sample(@mine_count) | |
mine_indices.each do |mi| | |
row, colum = mi.divmod(@column) | |
map[row][colum] = 1 | |
end | |
map | |
end | |
end | |
elapse_time = Benchmark.realtime { | |
fm = FindMine.new(10,10) | |
fm.render | |
puts "\n" | |
fm.render_with_hint | |
} | |
puts "=============\nelapse time : #{elapse_time}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment