Last active
March 29, 2016 22:19
-
-
Save tkbeili/9596897 to your computer and use it in GitHub Desktop.
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
| class TriangleClimber | |
| def initialize(size = nil, grid = nil) | |
| @possible_ways = 0 | |
| @grid = grid ? grid.inject([]) {|r,e| r << e.strip.split(" ")}.reverse : nil | |
| @size = size || @grid.size | |
| end | |
| def find_possible_climbing_ways | |
| 0.upto(@size - 1) {|x| move([0, x]) unless grid_has_trap?([0, x])} | |
| puts @possible_ways | |
| end | |
| private | |
| def move(from_point, to_point = nil) | |
| if to_point == [@size - 1, 0] | |
| @possible_ways += 1 | |
| elsif to_point == nil | |
| (possible_moves(from_point)).each {|new_point| move(from_point, new_point) } | |
| else | |
| (possible_moves(to_point) - [from_point]).each {|new_point| move(to_point, new_point) } | |
| end | |
| end | |
| def possible_moves(point) | |
| x, y = point[0], point[1] | |
| [[x, y+1], [x, y-1], [x+1, y-1], [x+1, y]].reject {|x| disallowed_move?(x) } | |
| end | |
| def disallowed_move?(x) | |
| (x[0] + x[1] > @size - 1) || x[0] < 0 || x[1] < 0 || grid_has_trap?(x) | |
| end | |
| def grid_has_trap?(point) | |
| @grid && @grid[point[0]][point[1]].downcase == "x" | |
| end | |
| end | |
| TriangleClimber.new(4).find_possible_climbing_ways | |
| TriangleClimber.new(nil, [ " O ", | |
| " O O ", | |
| " O X O ", | |
| "O O X O"]).find_possible_climbing_ways |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment