Download code

Jump to: navigation, search

Back to Pascal's_triangle_(Scala)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

PascalsTriangle.scala

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Pascal's_triangle_(Scala)?oldid=16649
14 */
15 
16 object PascalsTriangle {
17     
18   def shiftRight(row: List[Int]): List[Int] = 0::row
19   def shiftLeft(row: List[Int]): List[Int] = row:::List(0)  
20   
21   def addList(l1: List[Int], l2: List[Int]): List[Int] = {
22     (l1 zip l2) map { case (x, y) => x + y }
23   } 
24   
25   def pascalStream(row: List[Int]): Stream[List[Int]] =
26     Stream.cons(row, pascalStream(addList(shiftLeft(row), shiftRight(row))))
27 
28   
29   def printTriangle(triangle: Stream[List[Int]], nrows: Int) {
30     val rows = triangle.take(nrows).map(_.mkString(" "))
31       
32     val maxWidth = rows.last.length
33 
34     def pad(row: String) {
35       val padSize = (maxWidth - row.length) / 2
36       for(i <- 1 to padSize) { print(" ") }
37     }
38           
39     rows foreach { row => pad(row); println(row) }
40   }
41   
42   def main(args: Array[String]) {
43     val nrows = if (args.length > 0) args(0).toInt else 5
44     val lazyTriangle = pascalStream(List(1))
45     
46     printTriangle(lazyTriangle, nrows)
47   }
48 }


hijacker
hijacker
hijacker
hijacker