Home > Backend Development > C#.Net Tutorial > C# program to find common elements in three arrays using sets

C# program to find common elements in three arrays using sets

WBOY
Release: 2023-08-24 08:01:10
forward
1152 people have browsed it

C# program to find common elements in three arrays using sets

Set three arrays

int[] arr1 = {
   99,
   57,
   63,
   98
};

int[] arr2 = {
   43,
   99,
   33,
   57
};

int[] arr3 = {
   99,
   57,
   42
};
Copy after login

Now use HashSet to set the above elements.

// HashSet One
var h1 = new HashSet < int > (arr1);
// HashSet Two
var h2 = new HashSet < int > (arr2);
// HashSet Three
var h3 = new HashSet < int > (arr3);
Copy after login

Let’s take a look at the complete code to find the common elements.

Example

using System;
using System.Collections.Generic;
using System.Linq;

public class Program {
   public static void Main() {
      int[] arr1 = {
         99,
         57,
         63,
         98
      };

      int[] arr2 = {
         43,
         99,
         33,
         57
      };

      int[] arr3 = {
         99,
         57,
         42
      };

      // HashSet One
      var h1 = new HashSet < int > (arr1);
      // HashSet Two
      var h2 = new HashSet < int > (arr2);
      // HashSet Three
      var h3 = new HashSet < int > (arr3);

      // Displaying
      int[] val1 = h1.ToArray();
      Console.WriteLine("Set one...");
      foreach(int val in val1) {
         Console.WriteLine(val);
      }

      //Displaying
      int[] val2 = h2.ToArray();
      Console.WriteLine("Set two...");
      foreach(int val in val2) {
         Console.WriteLine(val);
      }

      //Displaying
      int[] val3 = h3.ToArray();
      Console.WriteLine("Set three...");
      foreach(int val in val3) {
         Console.WriteLine(val);
      }

      int i = 0, j = 0, k = 0;
      Console.WriteLine("Common elements...");
      while (i < val1.Length && j < val2.Length && k < val3.Length) {
         if (val1[i] == val2[j] && val2[j] == val3[k]) {
            Console.Write(val1[i] + " ");
            i++;
            j++;
            k++;
         }
         // x < y
         else if (val1[i] < val2[j])
         i++;
         // y < z
         else if (val2[j] < val3[k])
         j++;
         else
         k++;
      }
   }
}
Copy after login

The above is the detailed content of C# program to find common elements in three arrays using sets. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template