zapshe
zapshe

Reputation: 278

C# Pascal Triangle Code doesn't work - Logic correct

I've been trying to learn more about C#, and so I was doing a little practicing with Lists:

static void Main()
    {
        List<List<int>> a = new List<List<int>>();
        List<int> temp = new List<int>();
        temp.Add(1);
        a.Add(temp);
        for (int i = 0; i < 9; i++)
        {
            temp.Clear();
            temp.Add(1);
            for (int q = 0; q < a[i].Count-1; q++)
            {
                temp.Add(a[i][q] + a[i][q+1]);
            }
            temp.Add(1);
            a.Add(temp);
        }
        foreach (var i in a[8])
            Console.Write(i + " ");
        Console.WriteLine();
    }

I converted this to C++, and it works perfectly. However, in C#, a[i].Count is always 1. Even though after the first loop the size must be 2.

My only guess is that there's some major difference between C++'s Vector and C#'s List that I've apparently missed. Any ideas?

Here's the C++ code which works:

int main()
{
    std::vector<std::vector<int>> a;
    std::vector<int> b;
    b.push_back(1);
    a.push_back(b);
    for (int i = 0; i < 9; i++)
    {
        b.clear();
        b.push_back(1);
        for (int q = 0; q < a[i].size()-1; q++)
        {
            b.push_back(a[i][q] + a[i][q+1]);
        }
        b.push_back(1);
        a.push_back(b);
    }
    for (auto i : a[8])
    {
        std::cout << i << ' ';
    }
}

Output for C++ Code:

1 8 28 56 70 56 28 8 1

Output For C# Code:

1 1

Any help is appreciated, thanks!

Upvotes: 1

Views: 109

Answers (2)

Athul Raj
Athul Raj

Reputation: 189

I have modified your code slightly, the main difference to not is, C# there are mainly 2 kind of types, one is a reference type and one is a value type. List is a reference type. In your code, you always clearing and adding numbers to the temp list. that always points to the same object, so when you clear in the nth row, it's also clearing all the rows before it.

    List<List<int>> a = new List<List<int>>();

    a.Add(new List<int> { 1 });
    for (int i = 0; i < 9; i++)
    {
        List<int> temp = new List<int>();
        temp.Add(1);
        for (int q = 0; q < a[i].Count - 1; q++)
        {
            temp.Add(a[i][q] + a[i][q + 1]);
        }
        temp.Add(1);
        a.Add(temp);
    }
    foreach (var row in a)
    {
        foreach (var col in row)
        {
            Console.Write(col + " ");
        }

        Console.WriteLine();
    }

    Console.ReadKey();

Upvotes: 1

Li-Jyu Gao
Li-Jyu Gao

Reputation: 940

Look at your C# code a.Add(temp);. This temp variable is a reference type, so it will always add the same memory object.

To fix that, you can use LINQ to solve it: a.Add(temp.ToList());. ToList() will generate a new object with different memory.

Upvotes: 4

Related Questions