Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 FeedBack Please.
Index -> Programming, Ruby -> Ruby Help
Goto page Previous  1, 2
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Tony




PostPosted: Sat Dec 11, 2010 7:02 pm   Post subject: RE:FeedBack Please.

if you set the buffer to "." then everything should work well, and you wouldn't need a special case for nils.

Btw, index of -1 refers to the last element in the array.
Quote:

>> [1,2,3][-1]
=> 3
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Sat Dec 11, 2010 8:09 pm   Post subject: RE:FeedBack Please.

and..
Ruby:

ROWS, COLUMNS = 5, 5
MINE_PERCENTAGE = 0.2
@mine_grid = Array.new(ROWS + 2){Array.new(COLUMNS+2){}}
# scatter some mines on the field
(1..ROWS).each do |r|
  (1..COLUMNS).each do |c|
    @mine_grid[r][c] = rand < MINE_PERCENTAGE ? "*" : nil
  end
end

# method to print the field
def print_grid
  (1..ROWS).each do |r|
    (1..COLUMNS).each do |c|
      print [nil,0].include?(@mine_grid[r][c]) ? "." : @mine_grid[r][c]
    end
    print "\n"
  end
end

# method to count the mines around any particular cell
def count_cell(r,c)
  (@mine_grid[r-1][c-1..c+1] +
  @mine_grid[r][c-1..c+1] +
  @mine_grid[r+1][c-1..c+1]).count{|a| a == "*"}
end

# solve everything
(1..ROWS).each do |r|
  (1..COLUMNS).each do |c|
    @mine_grid[r][c] = count_cell(r,c) unless @mine_grid[r][c] == "*"
  end
end

print_grid
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 2 of 2  [ 17 Posts ]
Goto page Previous  1, 2
Jump to:   


Style:  
Search: