Download code

Jump to: navigation, search

Back to Pascal's_triangle_(Scala,_v2.8)

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,_v2.8)?oldid=16651
14 */
15 
16 object PascalsTriangle {
17 
18   private val triangle: Stream[Row] =
19     Stream.cons(new Row, triangle map (_ next))
20 
21 
22   class Row (elts: Array[Int]) {
23 
24     def this () = this(Array(1))
25 
26     def this (xs: List[Int]) = this((1 :: xs ::: List(1)) toArray)
27 
28     def next = elts match {
29       case Array(1) => new Row(Array(1, 1))
30       case _        => 
31         new Row(elts.iterator.sliding(2).toList map (_ sum))
32     }
33 
34     override def toString = elts mkString " "
35   }
36 
37   def print (rows: Stream[String]) {
38     val maxWidth = rows.last.size
39 
40     rows foreach { row =>
41       val padding = " " * ((maxWidth - row.size) / 2)
42       println(padding + row)
43     }
44   }    
45   
46   def main (args: Array[String]) {
47     val n = if (args.length > 0) args(0).toInt else 5
48 
49     print(triangle take n map (_ toString))
50   }
51 }


hijacker
hijacker
hijacker
hijacker