Skip to content

Instantly share code, notes, and snippets.

@addiedx44
Last active April 8, 2016 19:30
Show Gist options
  • Save addiedx44/57fcd4ec349c8812be62d945a94a8e4b to your computer and use it in GitHub Desktop.
Save addiedx44/57fcd4ec349c8812be62d945a94a8e4b to your computer and use it in GitHub Desktop.
#!/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)
@addiedx44
Copy link
Author

Replaced the recursive factorial function with an iterative one as it was hitting stack limits for large values of x.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment