SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Exercises
Question:5 | ISBN:9780136091813 | Edition: 2

Question

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value. For example, if the array passed contains the values {27, 15, 15, 11, 27}, your method should return 15 . (Hint: You may wish to look at the Tally program from this chapter to get an idea how to solve this problem.) Can you write a version of this method that does not rely on the values being between 0 and 100?

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of mode method:

	public static int mode(int[] list)
	{
		int[] counts = new int[100];
		
		for(int i = 0; i < list.length; i++)
		{
			counts[list[i]]++;				
		}
		
		int maxPos = counts[0];
		int maxNumber = 0;

		for(int i = 1; i < counts.length; i++)
		{
			if(counts[i] > maxPos)
			{
				maxPos = counts[i];
				maxNumber = i;
			}
		}

		return maxNumber;
	}
0 0

Discussions

Post the discussion to improve the above solution.