Last active
April 8, 2016 19:30
-
-
Save addiedx44/57fcd4ec349c8812be62d945a94a8e4b 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
#!/usr/bin/env ruby | |
## | |
# Solution for http://www.ancientcityruby.com/snake_case/ | |
# | |
# How many different paths could I take from the northwest corner to the | |
# southeast corner of a rectangular grid, only ever moving south or east? | |
# | |
# Usage: ./snake_case.rb <size | |
# ./snake_case.rb <length> <width> | |
# | |
# where <size> is the size of a square grid, e.g., for a 2x2 grid, size is 2 | |
# (default size is 10). Use <length> and <width> for non-square grids. | |
# | |
def factorial(x) | |
return (1..x).inject(:*) || 1 | |
end | |
def count_paths(length, width) | |
top = factorial(length + width) | |
bottom = factorial(length) * factorial(width) | |
return top / bottom | |
end | |
if ARGV[0] | |
if ARGV[1] | |
length = ARGV[0].to_i | |
width = ARGV[1].to_i | |
else | |
length = width = ARGV[0].to_i | |
end | |
else | |
length = width = 10 | |
end | |
puts count_paths(length, width) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replaced the recursive factorial function with an iterative one as it was hitting stack limits for large values of
x
.