3 ms·
u mad bro? your solution looks quite ugly in ruby def fact(n) n == 0 ? 1 : n.downto(1).inject(:*) end def pascal(n) 0.upto(n) {|r| print "#{f
by z324werwer 15y ago
u mad bro? your solution looks quite ugly
in ruby
def fact(n)
n == 0 ? 1 : n.downto(1).inject(:*)
end
def pascal(n)
0.upto(n) {|r| print "#{fact(n)/(fact(r)*fact(n - r))} "}
end
- haberman 15y agoYes, using the binomial coefficient formula is another solution that is shorter, but I downvoted you for not being civil. Please read: http://ycombinator.com/newsguidelines.html http://ycombinator.com/newsguidelines.html
- dxbydt 15y agoJust an asie: Printing Pascal's triangle for upto 10 rows is trivial. The factorials don't get big enough so you can simply use binomial coefficients (like in your ruby solution). But if you want Pascal's triangle for the 10,000th row => You can use what I wrote. If you have an easier implementation, I'd be very interested.
- it 15y agoHere's a way to do it in Haskell: let step row = zipWith (+) (0:row) (row++[0]) let triangle = iterate step [1] take 10 triangle
- martininmelb 15y ago1. I notice your solution uses recursion (at least I assume it uses recursion - I am not a ruby programmer). I think this would be an issue for large values of n (stack overflow). 2. I think an iterative function for fact would be more efficient. 3. I notice you do not memoize the result of fact even though you are calculating it twice for each call. I suspect that you are trying to show how compact a solution can be, but in an interview situation, I would probably be more impressed by someone who is aware of the issues above.
- z324werwer 15y agoit's iterative bro.