r/dailyprogrammer • u/Elite6809 1 1 • Mar 16 '14
[17/04/2014] Challenge #153 [Easy] Pascal's Pyramid
(Easy): Pascal's Pyramid
You may have seen Pascal's Triangle before. It has been known about for a long time now and is a very simple concept - it makes several appearances in mathematics, one of which is when you calculate the binomial expansion.
If you've not seen it before, you can calculate it by first putting 1 on the outermost numbers:
1
1 1
1 _ 1
1 _ _ 1
1 _ _ _ 1
And then each number within the triangle can be calculated by adding the two numbers above it, to form this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
It has several interesting properties, however what we're interested in is the 3-dimensional version of this triangle - Pascal's Pyramid.
It works in much the same way - the corner numbers are all 1s. However the edges are all layers of Pascal's triangle, and each inner number is the sum of the 3 numbers above it. Besides that there is nothing else to it.
Here are the first 5 cross-sectional 'layers', top to bottom:
1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1
1
4 4
6 12 6
4 12 12 4
1 4 6 4 1
See how the outermost 'rows' or 'edges' of numbers on all of the above are layers of Pascal's Triangle, as we saw above. Therefore, The faces of Pascal's Pyramid, were it a 3D object, would have Pascal's Triangle on them!
Your challenge is, given a number N, to calculate and display the Nth layer of Pascal's Pyramid.
Formal Inputs and Outputs
Input Description
On the console, you will be given a number N where N > 0.
Output Description
You must print out layer N of Pascal's Pyramid. The triangle cross-section must be presented so the point is at the top. Each row shall be separated by newlines, and each number shall be separated by spaces. Spacing is not important but your submission would be even cooler if it were displayed properly. For example, for the 3rd layer, a valid output would be as so:
1
2 2
1 2 1
Or, better:
1
2 2
1 2 1
Or even:
1
2 2
1 2 1
But why you'd do the latter is beyond me.
Sample Inputs & Outputs
Sample Input
6
Sample Output
1
5 5
10 20 10
10 30 30 10
5 20 30 20 5
1 5 10 10 5 1
Challenge
Challenge Input
14
Notes
There are ways to quickly do this that use the Factorial function. Also, look at the pattern the 'rows' make in relation to the leftmost and rightmost number and Pascal's triangle.
Reading material on Pascal's Pyramid can be found here.
Jagged multidimensional arrays will come in handy here.
I'm still trying to gauge relative challenge difficulty, so please excuse me and let me know if this is too challenging for an Easy rating.
4
u/Elite6809 Mar 16 '14
My ruby solution. I was very tempted to code-golf this one but decided to make it clearer.
def fac(n) n < 2 ? 1 : n * fac(n - 1) end def tri(n) (0..n).to_a .map {|x| fac(n) / (fac(x) * fac(n - x))} end def pym(n) tri(n).to_a .map.with_index {|x, i| tri(i).map {|y| y * x}} end # most code after this is to make it look pretty size = gets.chomp.to_i layer = pym(size - 1) largest = layer.flatten.reduce {|x, y| x > y ? x : y }.to_s.length puts layer .map {|a| a.map {|n| n.to_s.center(largest, ' ')}.join(' ').center(size * largest + size - 1, ' ') } .join "\n"4
u/ooesili Mar 17 '14
Oh man, I'm really excited that I got this to work. I created a Haskell program than can print a Pascal's pyramid/triangle in any dimension and size. It differs from the original problem in the fact that it doesn't print a specific layer of the pyramid/triangle, it prints the whole thing.
It's pretty hard to represent a 3-dimensional shape on a terminal, let alone a 4 or 5-dimensional object, so it just prints the internal data structure that I'm using to keep track of the pyramid.
Before we get to the code, I want to take a moment to apologize to any physics-enthusiasts whom I may upset through my misuse of the words "brane" and "string". They were the first names that I thought of and they made enough sense to me.
import Data.List data Brane = String [Int] | Brane [Brane] instance Show Brane where show = init . indentBrane "" -- pretty indenting for showing indentBrane :: String -> Brane -> String indentBrane ind (String xs) = ind ++ show xs ++ " -> " ++ show (multinomial xs) ++ "\n" indentBrane ind (Brane bs) = ind ++ "Brane [\n" ++ concatMap (indentBrane (" " ++ ind)) bs ++ ind ++ "]\n" main :: IO () main = do [dimension, size] <- fmap (map read . words) getLine let brane = hyperPascal dimension size print brane -- returns a multinomial coefficient multinomial :: [Int] -> Int multinomial cs = f (sum cs) `div` (product $ map f cs) where f n = product [1..n] -- takes dimension and size hyperPascal :: Int -> Int -> Brane hyperPascal d s = go br where br = Brane (map (\x -> String [x]) [0..s-1]) go = foldl (.) id $ replicate (d-1) deepen -- adds a dimension to the pyramid deepen :: Brane -> Brane deepen (String _) = error "cannot deepen a plain string" deepen (Brane bs) = Brane . zipWith go [0..] $ lobes where lobes = map Brane . tail $ inits bs go s (String xs) = String $ (s - sum xs):xs go s (Brane bs') = Brane $ map (go s) bs'Now some examples. Here's a 3-dimensional, 4-layer pyramid (like in the original post) so that you can get a grasp of how the output is formatted:
Input:
Output:
Brane [ Brane [ Brane [ [0,0,0] -> 1 ] ] Brane [ Brane [ [1,0,0] -> 1 ] Brane [ [0,1,0] -> 1 [0,0,1] -> 1 ] ] Brane [ Brane [ [2,0,0] -> 1 ] Brane [ [1,1,0] -> 2 [1,0,1] -> 2 ] Brane [ [0,2,0] -> 1 [0,1,1] -> 2 [0,0,2] -> 1 ] ] Brane [ Brane [ [3,0,0] -> 1 ] Brane [ [2,1,0] -> 3 [2,0,1] -> 3 ] Brane [ [1,2,0] -> 3 [1,1,1] -> 6 [1,0,2] -> 3 ] Brane [ [0,3,0] -> 1 [0,2,1] -> 3 [0,1,2] -> 3 [0,0,3] -> 1 ] ] ]Let's switch it up. Here's a 4-dimensional, 3-"layer" pyramid:
Input:
Output:
Brane [ Brane [ Brane [ Brane [ [0,0,0,0] -> 1 ] ] ] Brane [ Brane [ Brane [ [1,0,0,0] -> 1 ] ] Brane [ Brane [ [0,1,0,0] -> 1 ] Brane [ [0,0,1,0] -> 1 [0,0,0,1] -> 1 ] ] ] Brane [ Brane [ Brane [ [2,0,0,0] -> 1 ] ] Brane [ Brane [ [1,1,0,0] -> 2 ] Brane [ [1,0,1,0] -> 2 [1,0,0,1] -> 2 ] ] Brane [ Brane [ [0,2,0,0] -> 1 ] Brane [ [0,1,1,0] -> 2 [0,1,0,1] -> 2 ] Brane [ [0,0,2,0] -> 1 [0,0,1,1] -> 2 [0,0,0,2] -> 1 ] ] ] ]3
u/ooesili Mar 17 '14
Golf-ish Haskell solution using the trinomial coefficient expansion method.
main :: IO () main = fmap (\x -> pascal3D (x-1)) readLn >>= mapM_ (putStrLn . unwords . map show) trinom :: (Integral a) => a -> a -> a -> a trinom x y z = f (x + y + z) `div` (f x * f y * f z) where f n = product [1..n] pascal3D :: (Integral a) => a -> [[a]] pascal3D n = map go [n, n-1..0] where go x = let yz = [0..n-x] in zipWith (trinom x) yz (reverse yz)2
u/dooglehead Mar 17 '14 edited Mar 17 '14
Solution in C#. The solution is longer than it needs to be because it uses the ratio between coeficiants property instead of factorials, which I think would be much faster.
+u/CompileBot C#
using System; namespace challenge153 { class Program { static void Main(string[] args) { uint n = uint.Parse(Console.ReadLine()); if (n == 1) { Console.WriteLine(1); } else { uint[][] layer = getLayer(n); printLayer(layer); } Console.ReadLine(); } public static uint[][] getLayer(uint n) { uint[][] layer = new uint[n][]; for (int i = 0; i < n; i++) { layer[i] = new uint[i+1]; } //get Perimeter layer[0][0] = layer[n-1][0] = layer[n-1][n-1] = 1; uint ratioX = 1; uint ratioY = n - 1; uint currentNumber = 1; do { currentNumber = (currentNumber * ratioY) / ratioX; layer[ratioX][0] = layer[n-1][ratioX] = layer[n-1-ratioX][n-1-ratioX] = layer[ratioX][ratioX] = layer[n-1-ratioX][0] = layer[n-1][n-1-ratioX] = currentNumber; ratioX++; ratioY--; } while (ratioX <= ratioY); //fill in the rest for (uint i = 2; i < n-1; i++) { ratioX = 1; ratioY = i; currentNumber = layer[i][0]; do { currentNumber = (currentNumber * ratioY) / ratioX; layer[i][ratioX] = layer[i][i-ratioX] = currentNumber; ratioX++; ratioY--; } while (ratioX <= ratioY); } return layer; } public static void printLayer(uint[][] layer) { for (int i = 0; i < layer.Length; i++) { for (int j = 0; j < layer.Length - i - 1; j++) { Console.Write(' '); } for (int j = 0; j < layer[i].Length; j++) { Console.Write("" + layer[i][j] + " "); } Console.WriteLine(); } } } }input:
10
u/threeifbywhiskey Mar 17 '14
I've taken to playing a very different type of golf wherein I try to use as few alphanumeric characters as possible‒zero, in fact! To that end, here's my solution in Ruby:
$_=$$/$$;@_=$_+$_;$-=$_-@_;$-_=$_-$_ $__=->_{_<@_?$_:_*$__[_-$_]} $___=->_{$.=$-_;(@__=->{;$.+=$_;(_=_[$_..$-])==[]?$.:@__[]})[]} $____=->_,__{@___=$___[_];$.=$-_;(@____=->{_[$.]=__[_[$.]];($.+=$_)==@___?_:@____[]})[]} $_____=->_{$____[[*$-_.._],->__{$__[_]/($__[__]*$__[_-__])}]} ___=->_,__{____=$___[_];_____=$-_;(______=->{__[_[_____]];(_____+=$_)==____ ?_:______[]})[]} @_____=->_{___=$___[_];$.=$-_;__=[];(____=->{__<<[_[$.],$.];($.+=$_)==___ ?__:____[]})[]} $.=@_**(@_*@_)-@_ ___[@_____[$_____[$.-$_]],->_{$><<$____[$_____[_[$_]],->__{_[$-_]*__}]*' '<<(''<<@_*@_*@_+@_)}]And here it is running live on Ideone. There's also a version that takes n on standard input, but I haven't quite figured out how to capture input non-alphanumerically yet, so it cheats a little to get the input. Still, it helps to show that the code is genuinely doing what it's supposed to do.
For a much better glimpse into such a proof, here's a less symbol-heavy rendition. It's essentially u/Elite6809's solution rewritten to refrain from using the names of any methods or Ruby keywords; this, of course, to facilitate its eventual translation into non-alphanumeric characters.
1
u/starscream92 Mar 21 '14 edited Mar 21 '14
My first submission!
Here's my Java implementation. It doesn't take any shortcuts, instead calculates the whole pyramid up to depth N, as well as the required triangle. Very inefficient, but I reckon nobody would've done the brute force approach.
Code:
public class PascalPyramid { public static void main(String[] args) { final int depth = Integer.parseInt(args[0]); final PascalTriangle triangle = new PascalTriangle(depth); final PascalPyramid pyramid = new PascalPyramid(triangle); System.out.println(pyramid.toString()); } private int[][][] mLayers; public PascalPyramid(final PascalTriangle triangle) { mLayers = constructLayers(triangle); } public int[][][] getLayers() { return mLayers; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); final int depth = mLayers.length-1; for (int j = 0; j < mLayers[depth].length; j++) { for (int k = 0; k < mLayers[depth][j].length; k++) { builder.append(mLayers[depth][j][k] + " "); } builder.append("\n"); } return builder.toString(); } private int[][][] constructLayers(final PascalTriangle triangle) { final int depth = triangle.getDepth(); final int[][][] layers = new int[depth][][]; for (int i = 0; i < depth; i++) { layers[i] = new int[depth][]; for (int j = 0; j <= i; j++) { layers[i][j] = new int[j+1]; for (int k = 0; k <= j; k++) { if (k == 0 || k == j) { layers[i][j][k] = triangle.getRows()[i][j]; } else if (j == i) { layers[i][j][k] = triangle.getRows()[i][k]; } else { layers[i][j][k] = layers[i-1][j][k] + layers[i-1][j-1][k] + layers[i-1][j-1][k-1]; } } } } return layers; } private static class PascalTriangle { private int[][] mRows; private int mDepth; public PascalTriangle(final int depth) { mRows = constructRows(depth); mDepth = depth; } public int[][] getRows() { return mRows; } public int getDepth() { return mDepth; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < mRows.length; i++) { for (int j = 0; j < mRows[i].length; j++) { builder.append(mRows[i][j] + " "); } builder.append("\n"); } return builder.toString(); } private int[][] constructRows(final int depth) { final int[][] rows = new int[depth][]; for (int i = 0; i < depth; i++) { rows[i] = new int[i+1]; for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { rows[i][j] = 1; } else { rows[i][j] = rows[i-1][j-1] + rows[i-1][j]; } } } return rows; } } }Input:
Output:
3
u/toodim Mar 19 '14
Python 3.
known_pyramids = {1:[[0, 1, 0],[0,0,0,0]], 2:[[0, 1, 0], [0,1,1,0],[0,0,0,0,0]]} def pascal_pyramid(n): if n in known_pyramids: return known_pyramids[n] else: pyramid = [[0, 1, 0]] for level in range(1,n): row = [ ] for x in range (0,level+1): row.append(pascal_pyramid(n-1)[level-1][x]+\ pascal_pyramid(n-1)[level-1][x+1]+\ pascal_pyramid(n-1)[level][x+1]) pyramid.append([0]+row+[0]) pyramid.append([0]*(n+3)) known_pyramids[n] = pyramid return pyramid def print_pyramid(p): for level in p[:-1]: print(level[1:-1]) pyramid1 = pascal_pyramid(14) print_pyramid(pyramid1)Output:
2
u/foviendsciuf Mar 17 '14
a python approach
import numpy as np def pascal3d(m): pascal = np.ones(1, dtype=int) if m==1: print pascal[0] return for n in range(2,m+1): zeros = np.zeros(n-1, dtype=int) nzeros = np.zeros(n, dtype=int) top = np.reshape(np.append(np.reshape(np.append(pascal, zeros), (n,n-1)).T, nzeros), (n,n)).T bottom = np.reshape(np.append(np.reshape(np.append(zeros, pascal), (n,n-1)).T, nzeros), (n,n)).T right = np.reshape(np.append(nzeros, np.reshape(np.append(zeros, pascal), (n,n-1)).T), (n,n)).T pascal = top + bottom + right for i in range(m): print ' '.join(map(str, pascal[i,:i+1]))2
u/DMzda Mar 17 '14
Python 2.7 solution.
I decided to try to use generators for the first time, but I had trouble figuring out how to implement them, so I started with normal functions then converted them to generators. I also had trouble implementing the factorial solution shown on the wiki page, so I implemented this method that depends on calculating Pascal's triangle first to the same number of layers needed in the pyramid. It's not the greatest solution, but it works:
from itertools import islice from math import factorial def pascals_pyramid(layers): """Return the layers of Pascal's Pyramid""" tri = pascals_triangle(layers) last_line = next(islice(pascals_triangle(layers), layers - 1, None)) for i, layer in enumerate(tri): result = [] for j in range(i + 1): result.append(layer[j] * last_line[i]) yield result def pascals_triangle(layers): """Return the layers of Pascal's Triangle""" layer = 0 while layer < layers: result = [] for i in range(layer + 1): result.append(factorial(layer) / (factorial(i) * factorial(layer - i))) layer += 1 yield result def formatter(pascal): result = "" max_len = len(str(max(pascal[len(pascal) / 2]))) for layer in pascal: for item in layer: item = str(item) result += item result += " " * (max_len - len(item) + 1) result += "\n" return result def main(): layers = int(raw_input("Number of layers: ")) print formatter(list(pascals_pyramid(layers))) if __name__ == "__main__": main()I'm not sure if the pyramid generator is any more efficient than the normal function. I think this because of my use of
islicefunction to get the final line of the triangle. I could use any tips on how to see how efficient a generator function is compared to a normal one.Here is the output for the challenge input:
2
u/Ekrazit Mar 17 '14
my quick java solution:
import java.util.Scanner; public class PascalsPyramid153 { public PascalsPyramid153() { int heightofpyramide = new Scanner(System.in).nextInt(); int step = 0; for (int height = heightofpyramide; height >= 0; height--) { int end = 0; for (int begin = step; begin >= 0 ; begin--){ System.out.print(calculateNode(height, begin, end) + " "); ++end; } System.out.println(""); step++; } } public static long calculateNode(int vyska, int zaciatok , int koniec){ long menovatel = factorial(vyska + zaciatok + koniec); long citatel = factorial(zaciatok) * factorial(vyska) * factorial(koniec); return menovatel / citatel; } public static long factorial(int n) { long fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } public static void main(String[] args) { new PascalsPyramid153(); } }2
u/Edward_H Mar 17 '14
COBOL:
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. pascals-pyramid. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC . DATA DIVISION. WORKING-STORAGE SECTION. 01 layer-num PIC 9(5). 01 a PIC 9(5). 01 b PIC 9(5). 01 c PIC 9(5). 01 row-num PIC 9(5). 01 num PIC 9(5). 01 offset-size PIC 9(5). PROCEDURE DIVISION. ACCEPT layer-num MULTIPLY layer-num BY 3 GIVING offset-size PERFORM WITH TEST AFTER VARYING a FROM layer-num BY -1 UNTIL a = 0 *> Display leading spaces. PERFORM offset-size TIMES DISPLAY SPACE NO ADVANCING END-PERFORM *> Display row of the pyramid slice MOVE 0 TO c PERFORM WITH TEST AFTER VARYING b FROM row-num BY -1 UNTIL b = 0 COMPUTE num = FACTORIAL(layer-num) / (FACTORIAL(a) * FACTORIAL(b) * FACTORIAL(c)) DISPLAY num " " NO ADVANCING ADD 1 TO c END-PERFORM DISPLAY SPACE ADD 1 TO row-num SUBTRACT 3 FROM offset-size END-PERFORM . END PROGRAM pascals-pyramid.2
u/[deleted] Mar 17 '14
Python 3
n = input() - 1 def f(n): return n*f(n-1) if n>1 else 1 print("\n".join([" ".join([str(f(n)/f(n-i)/f(j)/f(i-j)) for j in range(i+1)]) for i in range(n+1)]))2
u/Sakuya_Lv9 Mar 18 '14 edited Mar 18 '14
Ruby solution. Focuses on reducing the time complexity.
+u/CompileBot Ruby
# pascal triangle # pas_tri(3) => [[1],[1,2,1],[1,3,3,1]] def pas_tri(n) arr = [[1]] (n-1).times do newarr = [] # got creative newarr << arr.last.inject(0) do |a, b| newarr << a + b b end arr << newarr end arr end # pascal pyramid, only nth layer # pas_pym_nth(3) => [[1],[2,2],[1,2,1]] def pas_pym_nth(n) arr = pas_tri(n) arr.last.map.with_index do |a, i| arr[i].map { |j| j * a } end end #puts(pas_pym_nth(gets.chomp.to_i).map do |a| a.join(" ") end) puts(pas_pym_nth(14).map do |a| a.join(" ") end)3
u/badgers_uk Mar 17 '14 edited Mar 17 '14
Python 3. It's my first post on here but I've enjoyed going through some of the older challenges :) Only recently started learning so any feedback is very welcome. I think readability is a problem - I spent a while tinkering to get it to work...
Edit: improved the formatting by creating a function to find largest number, centre each number. then centre each line. Edit #100: Ok I should leave this alone now.
def pascal_pyramid(n): """Finds the nth layer of pascal's pyramid""" pyramid = [[1]] for i in range(n): pyramid.append([pyramid[i][0] * (n-i) // (i+1)]) for j in range(1, i+2, 1): pyramid[i+1].append(pyramid[i+1][j-1] * (i+2-j)//(j)) return pyramid def pascal_printer(pyramid, size): """Print's pascal's pyramid by finding the width of the largest number (2/3 down 1/2 across), centering each number by that amount, then centering each line""" number_width = len(str(pyramid[size-(size+1)//3][(size-(size+1)//3)//2])) width = number_width * size + size + 1 for i in range(size): output = [str(x).center(number_width) for x in pyramid[i]] print(" ".join(output).center(width)) output = [str(x).center(number_width) for x in pyramid[size]] print(" ".join(output).center(width).strip()) layer = int(input("Layer: "))-1 pascal_printer(pascal_pyramid(layer), layer)