Given two Arrays a and b, Return True if arrays contain common item, else false
//Given 2 Arrays, Return True if arrays contain common item, else false.
//e.g a= ['a','b','g','c'] and b =['z','e','c'] returns true
// naive approach, loop through first array, with each item in a, loop through b and compare item to
//each item in b returning true if a match is found or false.
//input : 2 arrays
//output: bool
using System.Collections.Generic;
public class Kata{
public static bool ContainsCommonItem(char[] a, char[] b){ //naive O(a*b)
for(int i=0;i<a.Length;i++)
for(int j=0; j< b.Length; j++)
if(a[i]==b[j])
return true;
return false;
}
public static bool ContainsCommonItemBetter(char[] a,char[]b){
HashSet<char> items = new HashSet<char>();
foreach(char item in a)
items.Add(item);
for (int i =0; i< b.Length; i++)
if (items.Contains(b[i]))
return true;
return false;
}
}
namespace Solution {
using NUnit.Framework;
using System;
// TODO: Replace examples and use TDD by writing your own tests
[TestFixture]
public class SolutionTest
{
[Test]
public void MyTest()
{
Assert.AreEqual(true, Kata.ContainsCommonItemBetter(new char []{ 'a','b','g','c'}, new char[]{'z','e','c'}));
Assert.AreEqual(false, Kata.ContainsCommonItemBetter(new char []{ 'a','b','g','c'}, new char[]{'z','e','d'}));
Assert.AreEqual(false,Kata.ContainsCommonItemBetter(new char[]{},new char[]{'f','h'}));
}
}
}