Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have no idea of the homework public class Majority { // Return true if l has a

ID: 3539949 • Letter: I

Question

I have no idea of the homework


public class Majority

{


// Return true if l has a majority of o elements; false otherwise.

public static boolean hasMajority(Object[] l, Object o)

{

// TBD

}


// Test driver.

public static void main(String[] args)

{

int[] l1 = {1, 1, 1, 1, 1, 1, 2, 2, 3, 4};

Integer[] l2 = new Integer[10];

for (int i = 0; i < l1.length; i++) {

l2[i] = l1[i];

}

System.out.println("Should print true : " +

hasMajority(l2, new Integer(1)));

System.out.println("Should print false : " +

hasMajority(l2, new Integer(2)));

System.out.println("Should print false : " +

hasMajority(l2, new Integer(3)));

System.out.println("Should print false : " +

hasMajority(l2, new Integer(0)));

}

}


please help thanks

Explanation / Answer

public static boolean hasMajority(Object[] l, Object o)

    {
       
        HashMap<Object,Integer> countMap = new HashMap<Object,Integer>();
         
          for(int i=0; i < l.length; i++) {
           
            if(countMap.containsKey(l[i])) {
                countMap.put(l[i], countMap.get(l[i])+1);
            } else
                countMap.put(l[i], 1);
           
          }
         
          Object major = null;
          Integer curCnt = 0;
          for(Object key: countMap.keySet()) {
            if(major == null) {
                major = key;
                curCnt = countMap.get(key);
            } else {
                //If the current object count is greater than previous one, then make current object as major object
                if(curCnt < countMap.get(key)) {
                    major = key;
                    curCnt = countMap.get(key);
                }
            }
          }
          if(o.equals(major))
            return true;
          else
            return false;
       
    }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote