Created
September 9, 2018 16:50
-
-
Save tonyfabeen/2b450feb40a7d6049ad3321f5ce5f3c3 to your computer and use it in GitHub Desktop.
pascal triangle (naive)
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 'test/unit' | |
#Every number in Pascal's triangle is calculated by adding the numbers to the left and right of it from | |
#the row above it. For example, the first 4 in the 5th row is found by | |
#adding the 1 and the 3 from above it in the 4th row. | |
# | |
#Write a function pascal(n) that calculates the nth row of Pascal's Triangle, | |
#and return it as an array of integers. | |
def solution(n) | |
return [] if n == 0 | |
return [1] if n == 1 | |
return [1, 1] if n == 2 | |
result = [[1], [1, 1]] | |
(2.upto(n-1)).each do |x| | |
previous_row = result[x-1] | |
current_row = Array.new(x+1) | |
current_row[0] = current_row[x] = 1 | |
previous_row_index = 1 | |
1.upto(current_row.size-2) do |y| | |
current_row[y] = previous_row[previous_row_index] + previous_row[previous_row_index-1] | |
previous_row_index += 1 | |
end | |
result << current_row | |
end | |
result[n-1] | |
end | |
class TestPascalTriangle < Test::Unit::TestCase | |
def test_solution | |
assert_equal([1], solution(1)) | |
assert_equal([1,1], solution(2)) | |
assert_equal([1,2,1], solution(3)) | |
assert_equal([1,3,3,1], solution(4)) | |
assert_equal([1,4,6,4,1], solution(5)) | |
assert_equal([1,5,10,10,5,1], solution(6)) | |
assert_equal([1,6,15,20,15,6,1], solution(7)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment