patterncsharpMinor
Find the common element in two int arrays
Viewed 0 times
thearraystwoelementfindintcommon
Problem
I am preparing for a interview for a junior level c# position. I take two arrays and find the common int between both of them. Let me know if you have any feedback.
using System;
using System.Collections.Generic;
namespace CommonElement
{
class MainClass
{
static void EnterArray1IntoHashSet (int[] array1, HashSet hs){
foreach (int num in array1)
{
if (!hs.Contains (num))
{
hs.Add (num);
}
}
}
static int FindCommonInt(int[] array2, HashSet hs){
foreach (int num in array2)
{
if (hs.Contains (num))
{
return num;
}
}
return -1;
}
public static void Main (string[] args)
{
int[] array1 = new int[7]{ 5, 6, 7, 8, 1, 2, 3 };
int[] array2 = new int[7]{ 13, 22, 3, 45, 67, 73, 85};
HashSet hs = new HashSet ();
EnterArray1IntoHashSet (array1, hs);
int commonElement = FindCommonInt(array2, hs);
if (commonElement != -1)
{
Console.WriteLine (commonElement);
}
else
{
Console.WriteLine ("No Common Element");
}
}
}
}Solution
Improving
Why do you pass a hash set to
It would be better to let the method create, populate and return the hash set.
You don't need to check if an element is inside a hash set before adding it:
if the element already exists, it will be simply ignored.
The name of this function is unnecessarily tedious.
It has a nice general purpose,
and you can name it accordingly.
Coding style
The placement of opening braces
sometimes you put it on the next line,
sometimes on the same line.
The .NET convention is to put it on the next line.
It's also unusual to put a space between method name and the
Just omit the unnecessary space:
EnterArray1IntoHashSetWhy do you pass a hash set to
EnterArray1IntoHashSet ?It would be better to let the method create, populate and return the hash set.
You don't need to check if an element is inside a hash set before adding it:
if the element already exists, it will be simply ignored.
The name of this function is unnecessarily tedious.
It has a nice general purpose,
and you can name it accordingly.
static HashSet ToHashSet(int[] array1)
{
HashSet set = new HashSet();
foreach (int num in array1)
{
set.Add(num);
}
return set;
}Coding style
The placement of opening braces
{ is inconsistent:sometimes you put it on the next line,
sometimes on the same line.
The .NET convention is to put it on the next line.
It's also unusual to put a space between method name and the
( when calling them, for example this:Console.WriteLine (commonElement);Just omit the unnecessary space:
Console.WriteLine(commonElement);Code Snippets
static HashSet<int> ToHashSet(int[] array1)
{
HashSet<int> set = new HashSet<int>();
foreach (int num in array1)
{
set.Add(num);
}
return set;
}Console.WriteLine (commonElement);Console.WriteLine(commonElement);Context
StackExchange Code Review Q#100371, answer score: 7
Revisions (0)
No revisions yet.