Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Console.Writeline IEnumerable<(int a, int b, int c)>?

Tags:

c#

I'm working through some computer science exercises and I'm embarrassed to say I don't know how to console print the above stated code in VS Studio. I've tried over a number of days, and part of my problem is that I don't actually know the name of the above mentioned construction (figuratively speaking). I've done my homework, read the manual, but now there's nothing to do but put up my hand and ask the question. Online there seems to be many examples of using IEnumerable<int> but nothing outputting the tuple that I could find. Any example code posted would be appreciated.

public static class PythagoreanTriplet
{
    public static IEnumerable<(int a, int b, int c)> TripletsWithSum(int sum)
    {
        return Enumerable.Range(1, sum - 1)
                         .SelectMany(a => Enumerable.Range(a + 1, sum - a - 1)
                                                    .Select(b => (a: a, b:b, c: sum - a - b)))
                         .Where( x => x.a * x.a + x.b * x.b == x.c * x.c);

    }
}


public static class testclass
{
    public static void Main()
    {
        int input = 121;
        var data = PythagoreanTriplet.TripletsWithSum(input);
        Console.WriteLine(data);
    }
}


Output:

System.Collections.Generic.List`1[System.ValueTuple`3[System.Int32,System.Int32,System.Int32]]
like image 209
BBirdsell Avatar asked Dec 01 '18 02:12

BBirdsell


1 Answers

You have to decompose the Tuple into its parts as such:

public static void Main()
{
    int input = 121;
    var data = PythagoreanTriplet.TripletsWithSum(input);
    foreach(var d in data)
        Console.WriteLine($"{d.a} {d.b} {d.c}");
}

Reason being that the Tuple class does not override the ToString function, therefore outputting name of the class instead of the parts that compose the Tuple. You will need to provide a way for your solution to convert your custom Tuple to a string for consumption.

Another option is to create a type that represents your data that your are projecting into and returning in TripletsWithSum, which could override the ToString function for your needs as such

public class Tuple3Int : Tuple<int, int, int> 
{
    public Tuple3Int(int a, int b, int c) : base(a, b, c) { }

    public override string ToString()
    {
        return $"{Item1} {Item2} {Item3}";
    }
}

public static IEnumerable<Tuple3Int> TripletsWithSum(int sum)
{
    return Enumerable.Range(1, sum - 1)
                     .SelectMany(a => Enumerable.Range(a + 1, sum - a - 1)
                                                .Select(b => new Tuple3Int(a, b, sum - a - b)))
                     .Where(x => x.Item1 * x.Item1 + x.Item2 * x.Item2 == x.Item3 * x.Item3);

}
like image 149
Nathan Werry Avatar answered Nov 14 '22 23:11

Nathan Werry