-1
public void PrintPascalTriangle(int inNumberOfLines)
    {
        int noOfLines = inNumberOfLines;
        int number = 1;
        for(int i=0;i<noOfLines;i++)
        {
            
            number = 1;
            for(int j=0;j<=i;j++)
            {
                Console.Write(number + " ");
                number = number * (i - j) / (j + 1);

            }
        }

    }

how can convert this method into single loop and print values in single row?

I just need Pascal triangle values in a row (no need to worry about spaces or visual rep) upto n.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Rtn
  • 13
  • 4
  • How can you convert two loops into one and expect to get exact result? – osman Rahimi Oct 18 '20 at 08:45
  • extact results is not needed now i just want pascal triangle values in a row (no need to worry about spaces or visual rep) upto n. – Rtn Oct 18 '20 at 08:50

1 Answers1

0

Rows of Pascal's Triangle are all values of "the combinatorial function", n!/[k!( n-k)!], for a fixed n. The combinatorial function can be computed efficiently as below, see the Choose function, which I ripped from this answer:

class Program
{
    static int Choose(int n, int k)
    {
        if (k > n)
            return 0;

        if (k * 2 > n)
            k = n - k;

        if (k == 0)
            return 1;

        int result = n;
        for (int i = 2; i <= k; ++i)
        {
            result *= (n - i + 1);
            result /= i;
        }
        return result;
    }

    static List<int> RowOfPascalsTriangle(int n)
    {
        return Enumerable.Range(0, n).Select(k => Choose(n-1, k)).ToList();
    }

    static void Main(string[] args)
    {
        Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(1)));
        Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(2)));
        Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(3)));
        Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(4)));
        Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(5)));
    }
}
jwezorek
  • 8,592
  • 1
  • 29
  • 46