D
D
Dmitry Samutin2018-03-12 05:40:32
Programming
Dmitry Samutin, 2018-03-12 05:40:32

What algorithm should be for constructing triangles?

Good day! There is a sheet of arrays of strings (List), where each element of the sheet consists of 2 lines and is unique, and there cannot be two identical values ​​in a pair (there cannot be "[Ntv, Ntv]"). It is required to create a list of unique triangles, where the vertices are the values ​​of the pairs. What is needed is an algorithm, to which I still can not finish.
Triangle example:
Triangles.Add(new Triangle(X, Y, Z)), where X=[Ntv, Tbh], Y=[Vyt, Tbh], Z=[Vyt, Ntv]
Sheet example:

[
   [Ntv, Tbh],
   [Vyt, Tbh],
   [Roh, Vyt],
   [Roh, Ntv],
   [Vyt, Ntv]
   ...
]

There is a C# code, but it does not work correctly (there are repeating triangles whose vertices have different orders).
The code itself:
List<string[]> pairs = new List<string[]>();
List<Triangle> Triangles = new List<Triangle>();
foreach (string x in pairs)
{
    string[] X = pairs;
    foreach (string y in pairs)
    {
        string[] Y = pairs;
        if ((X[0] == Y[0] || X[0] == Y[1] || X[1] == Y[0] || X[1] == Y[1]) && !Equals(X, Y))
        {
            foreach (string z in pairs)
            {
                string[] Z = pairs;
                if (
                    X[0] == Y[0] && ((Z[0] == X[1] && Z[1] == Y[1]) || (Z[1] == X[1] && Z[0] == Y[1])) ||
                    X[0] == Y[1] && ((Z[0] == X[1] && Z[1] == Y[0]) || (Z[1] == X[1] && Z[0] == Y[0])) ||
                    X[1] == Y[0] && ((Z[0] == X[0] && Z[1] == Y[1]) || (Z[1] == X[0] && Z[0] == Y[1])) ||
                    X[1] == Y[1] && ((Z[0] == X[0] && Z[1] == Y[0]) || (Z[1] == X[0] && Z[0] == Y[0]))
                    )
                Triangles.Add(new Triangle(X, Y, Z));
            }
        }
    }
}
Console.WriteLine(Triangles);
return Triangles;

Tell me what's wrong with me? In what way should you think?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-03-12
@samutin

In principle, your algorithm is working, only it is not necessary to go through all the segments in each cycle, but only those that lie below. I.e

for (i = 0; i < pairs.length-2; i++) {
  ... 
  for (i = i+1; j < pairs.length-1; j++) {
    ...
    for (k = j+1; k < pairs.length; k++) {
      ...
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question