In: Computer Science
Write a generic method in java code
public static double jaccard(HashSet A, HashSet B)
that on input two sets represented as hash sets, returns their Jaccard similarity.
The following are a few sample runs:
Input : A=1, 2, 3, 4, B=2, 4, 6, 8
Return: 0.3333333333333333
Input : A=Larry, Michael, Shaq, Kobe, LeBron
B=Steve, Kobe, Shaq, LeBron, Steph, Jeremy, Michael
Return: 0.5
Your method must have time complexity On and space complexity O1, where n is the size of the smaller input set.
Program Code Screensshot :

Sample Output :'
'
Program Code to Copy
import java.util.Arrays;
import java.util.HashSet;
class Main{
    public static double jaccard(HashSet A, HashSet B){
        //Find union of both A and B
        HashSet union = new HashSet(A);
        union.addAll(B);
        //common elements/total elements
        return (A.size()+B.size()-union.size())/(union.size()*1d);
    }
    public static void main(String[] args) {
        HashSet A = new HashSet(Arrays.asList(1,2,3,4));
        HashSet B = new HashSet(Arrays.asList(2,4,6,8));
        System.out.println(jaccard(A,B));
        HashSet A1 = new HashSet(Arrays.asList("Larry","Micheal","Shaq","Kobe","LeBron"));
        HashSet B1 = new HashSet(Arrays.asList("Steve","Kobe","Shaq","LeBron","Steph","Jeremy","Micheal"));
        System.out.println(jaccard(A1,B1));
    }
}