Search code snippets, questions, articles...

Pascal Matrix

public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> pascalMatris = new ArrayList<>();
        for (int numRow=0; numRow<numRows; numRow++){
            pascalMatris.add(generatePascalRow(getTheLastMatrisRow(pascalMatris)));
        }
        return  pascalMatris;
    }

    private List<Integer> getTheLastMatrisRow(List<List<Integer>> pascalMatris) {
        return pascalMatris.isEmpty()? new ArrayList<>(): pascalMatris.get(pascalMatris.size()-1);
    }

    private List<Integer> generatePascalRow(List<Integer> theLastPascalRow) {
        List<Integer> pascalRow= new ArrayList<>();
        // adds the lead element '1' in the row
        pascalRow.add(1);
        pascalRow.addAll(calculateTheLastPacalRow(theLastPascalRow));
        if (theLastPascalRow.size()>0) {
            // adds the last element '1' in the row
            pascalRow.add(1);
        }
        return pascalRow;
    }

    private List<Integer> calculateTheLastPacalRow(List<Integer> theLastPascalRow) {
        List<Integer> pascalRowCalculated = new ArrayList<>();
        for (int i=0; i<theLastPascalRow.size()-1; i++){
            pascalRowCalculated.add(theLastPascalRow.get(i)+ theLastPascalRow.get(i+1));
        }
        return pascalRowCalculated;
    }
Output
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Was this helpful?
0 Comments