Sunday, April 22, 2012

Create Pascal's Triangle in One Loop using Java.

Create Pascal's Triangle in One Loop.

What the Algorithm is ?????



Code for this in java


package net.yogesh.test;

import java.util.ArrayList;
import java.util.List;

public class pascal3 {

    public static void main(String[] args) {

        int noOfRows = 10;
        int counter = 1;
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
       
        list = itMe(list, counter,noOfRows);
    }

    public static List<Integer> itMe(List<Integer> list, int counter,int noOfRows) {
        System.out.println(list);
       
        List<Integer> tempList = new ArrayList<Integer>();

        tempList.add(1);
        for (int i = 1; i < list.size(); i++) {
            tempList.add(list.get(i) + list.get(i-1));
        }
        tempList.add(1);
       
        if(counter != noOfRows)
            itMe(tempList, ++counter,noOfRows);
       
        return tempList;
    }
}

Output

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

No comments:

Post a Comment

Post a Comment

Disqus for yogi's talk

comments powered by Disqus