# Pascal's Triangle

# Pascal's Triangle

dillonredding + 0 comments 'n rows' and 'r columns' isn't confusing...

mihassan + 2 comments I am using a trick where infinte series can be used to contruct the same series, similar to how fibonacci series is generated:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

For pascal triangle, we start using the first row, and then use each row to calculate the next row.

pascalTriangle = [1] : map nextRow pascalTriangle where nextRow = ([1] ++). (++ [1]). pairSum pairSum x = zipWith (+) x (tail x) showPascalTriangle = map listToString pascalTriangle where listToString = unwords. map show main = getLine >>= putStrLn. unlines. flip take showPascalTriangle. read

QuomoZ + 1 comment Pretty much the same thing I did, minus self-recursive definition shenanigans:

pascal = iterate ((++ [1]) . (1:) . (zipWith (+) =<< tail)) [1]

yolanvanderhorst + 1 comment Bases on your solutions and adding a bit of my own, I think this might be the shorstest way to solve this, using just the Prelude:

main=interact$unlines.map (unwords.(map show)).flip take s.read s=[1]:map ((1:).(++[1]).(zipWith (+)=<<tail)) s

QuomoZ + 0 comments I could come up with a shorter one, here is your

`s`

function without spaces:s=[1]:map((1:).(++[1]).(zipWith(+)=<<tail))s

which is longer by 5 characters than:

p=[1]:[1:zipWith(+)r t++[1]|r@(_:t)<-p]

murtaught + 0 comments Spectacular "pointless" style. I couldn't help but chuckled on 'flip'.

ASRagab + 3 comments object Solution { def main(args: Array[String]) { val row = io.Source.stdin.getLines .take(1) .map(_.trim.toInt) .next() def triangle(row: Int): Unit = { def doT(row: Int, prev: List[Int]): Unit = { if (row == 0) return val next = prev.sliding(2, 1) .map(pair => pair.sum) .toList println (next mkString " ") doT(row - 1, (0 :: next) :+ 0) } doT(row, List(1)) } triangle(row) } }

Yeah, so I am not thrilled about this. Having to append and prepend zeros seems hacky.

xavier_guihot + 0 comments `def factoriel(y: Int): Int = (1 to y).foldLeft(1)(_ * _) var k = sc.nextInt(); (0 until k).foreach( n => { val rowToPrint = (0 to n).map( r => { factoriel(n) / (factoriel(r) * factoriel(n -r)) }).mkString(" ") println(rowToPrint) })`

SplashAttack + 0 comments `def pascal(input: Int): Array[Int] = { if(input == 1) { println(1) Array.empty } else { val result = 1 +: pascal(input - 1).sliding(2).map(_.sum).toArray :+ 1 println(result.mkString(" ")) result } }`

neild799 + 0 comments `object Solution { def nthRow(n: Int): List[Int] = { val row = List(1); (0 until n).foldLeft[List[Int]](row)((acc, r) => acc.head*(n-r)/(r+1)::acc); } def main(args: Array[String]) { (0 until scala.io.StdIn.readInt()).foreach( i => { nthRow(i).foreach(x => print(x + " ")); println(); } ); } }`

AlexNetkachov + 1 comment Quite consise F# solution for generating lines:

let lines n = let rec build (prev : int list) i = [ if i < n then let line = [ yield 1 for p in Seq.pairwise prev do yield (fst p) + (snd p) yield 1 ] yield line yield! build line (i+1) ] [ yield [1]; yield! build [1] 1 ]

A few more solutions: https://alexatnet.com/hr-f-pascals-triangle/

denis631 + 0 comments Nice. I didn't know I can do pairwise foreach :)

csixteen + 1 comment Erlang:

-module(solution). -export([main/0]). %% Factorial with tail recursion fac(N) -> fac(N, 1). fac(0, Acc) -> Acc; fac(N, Acc) when N > 0 -> fac(N-1, N*Acc). %% Calculates the value of a column in a row. column(N, M) -> fac(N) div (fac(M) * fac(N-M)). %% Builds a row build_row(N) -> build_row(N,1). build_row(N,M) when N rem 2 == 1, M == N div 2 + 1 -> [column(N-1,M-1)]; build_row(N,M) when N rem 2 == 0, M-1 == N div 2 -> []; build_row(N,M) when N > M -> C = column(N-1,M-1), [C] ++ build_row(N,M+1) ++ [C]. %% Prints a row print_row([]) -> io:format("~n"); print_row([X|Xs]) -> io:format("~p ", [X]), print_row(Xs). %% Builds the triangle pascal(N,M) when N < M -> ok; pascal(N,I) -> R = build_row(I), print_row(R), pascal(N,I+1). main() -> {ok, [N]} = io:fread("", "~d"), pascal(N,1) .

Andrei_Leontev + 0 comments Another Erlang solution:

main() -> { ok, [N]} = io:fread("", "~d"), pascal(0, N, []). pascal(C, N, A) -> case N-C of 0 -> ok; _ -> A1 = generate(C, A), print_line(A1), pascal(C+1, N, A1) end. generate(0, _A) -> [1]; generate(1, _A) -> [1, 1]; generate(_N, A) -> {_, A1} = lists:foldl(fun(E, {P, AN}) -> {E, AN ++ [P + E]} end, {0, []}, A), A1 ++ [1]. print_line(A) -> lists:foreach(fun(E) -> io:format("~p ", [E]) end, A), io:format("~n", []).

strawstack + 1 comment I'm trying to explain to Haskell that a triangle is not a stright line. Can anyone help? (The output of the following code is 1 1 1 1 2 1 1 3 3 1 (without any new lines))

-- FORMAT mat v = putStr ( (show v) ++ " " ) -- print value with space -- print tri value at coords pas m n | n == 0 = 1 | m == n = 1 | otherwise = pas (m-1) (n-1) + pas (m-1) n -- print row of triangle row m = mapM_ (mat . (pas m) $) [0..m] -- print triangle until row tri m = mapM_ (row) [0..(m-1)] main = do m <- readLn :: IO Int tri m -- print tri to row m

strawstack + 1 comment UPDATE: The program now prints a nested array. Still trying to get Haskell to format basic output? (Output of below is [[1],[1,1],[1,2,1],[1,3,3,1]])

-- print tri value at coords pas m n | n == 0 = 1 | m == n = 1 | otherwise = pas (m-1) (n-1) + pas (m-1) n -- print row of triangle row m = map (pas m) [0..m] -- print triangle until row tri m = map (row) [0..(m-1)] main = do m <- readLn :: IO Int print (tri m) -- print tri to row m

strawstack + 2 comments UPDATE: Finally, figured out how to print a [[Char]] in the correct format with Haskell...

-- PRINT with FORMAT two :: [Int] -> [String] two m = map (show) m three :: [[Int]] -> [[String]] three m = map (two) m main = do m <- readLn :: IO Int --send (tri m) -- print tri to row m mapM_ (putStrLn . intercalate " " $) (three (tri m))

Where (tri m) produces [["1"], ["1", "1"], ["1", "2", "1"], ["1", "3", "3", "1"]]

ende76 + 0 comments Thanks for this chain of posts. I was struggling through the same problems with how to properly output.

Much longer than to solve the actual problem!tury345 + 1 comment Achieved something similar here:

`putStr (unlines (map (\line -> unwords (map (\(x:[]) -> show x) line)) rows))`

where rows is [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

egoek + 0 comments I concocted this:

mapM_ putStrLn (map (\x -> unwords (map show x)) result)

where result is [[1], [1, 1], [1, 2, 1] ...] I'm sure I could get rid of the parenthesis. Any suggestions welcome.

ty001 + 2 comments Why would the input be in format of an array of strings in the Scala version? Given the limited availability of languages in the Recursion domain and how few people know any of the languages here, why not at least start us out with an Int argument?

ty001 + 0 comments Man, Scala is annoying.

Also, after the 13th iteration the compiler breaks and the output starts to invert. Try custom input with something like 20.

crupley + 1 comment Had the same problem and adapted this from @saltybald below:

val n = io.Source.stdin.getLines.toList.map(

*.trim).map(*.toInt).headNot sure what is going on here, but it worked!

SudicodeDotCom + 0 comments Works, but it's a bit too much work. For input as trivial as this,

`val n = readLine().toInt`

should suffice.

lambeta + 1 comment I found clojure always return nil if I use loop/when/recur. It made things more difficult and cannot pass the test case with the ending nil.

fail like below:

Your Output (stdout) 1 1 1 1 2 1 1 3 3 1 nil Expected Output 1 1 1 1 2 1 1 3 3 1

mandy1339 + 0 comments put your loop inside a function, and then just call it from outside.

chustvedt + 0 comments I'm (very) new to Haskell and fp, so this really isn't very sophisticated, but hoping for some help... I've managed to get the function working with a nested lsit comprehension, but just can't figure out how to change it from printing the lists to printing the values in the lists.

factorial :: Int -> Int factorial 0 = 1 factorial n = n * (factorial (n-1)) pascal :: Int -> [[Int]] pascal x = [[(factorial n `div` (factorial r * (factorial (n-r)))) | r <- [0..n] ] | n <- [0..(x-1)]] main = do input1 <- getLine let height = read input1 :: Int pyramid = pascal height mapM_ print pyramid

xdavidliu + 0 comments O(n) space and O(n^2) time solution in Common Lisp, without using factorials

(defun next-pascal-row (row) (labels ;; accumulate in reverse ((iter (rem accum) (if (null (cdr rem)) (cons 1 accum) (iter (cdr rem) (cons (+ (car rem) (cadr rem)) accum))))) (iter row (list 1)))) (defun print-pascal (n-rows) (labels ((iter (i row) (format t "~{~a~^ ~}~%" row) (if (< i n-rows) (iter (1+ i) (next-pascal-row row))))) (iter 1 (list 1)))) (print-pascal (read))

Sort 43 Discussions, By:

Please Login in order to post a comment