This is a java program to find the mode of a set. The mode of a set is defined as the highest occurring element in the set. We count the occurrence of each of the element and print the element whose count is highest.
Here is the source code of the Java Program to Find the Mode in a Data Set. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a java program to find the mode for a given sequence of numbers
import java.util.Random;
public class Mode
{
static int N = 20;
static int[] sequence = new int[N];
public static int mode()
{
int maxValue = 0, maxCount = 0;
for (int i = 0; i < sequence.length; ++i)
{
int count = 0;
for (int j = 0; j < sequence.length; ++j)
{
if (sequence[j] == sequence[i])
++count;
}
if (count > maxCount)
{
maxCount = count;
maxValue = sequence[i];
}
}
return maxValue;
}
public static void main(String args[])
{
Random random = new Random();
for (int i = 0; i < N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("The set of numbers are: ");
for (int i = 0; i < N; i++)
System.out.print(sequence[i] + " ");
System.out.println("\nThe mode of the set is: " + mode());
}
}
Output:
$ javac Mode.java $ java Mode The set of numbers are: 85 3 80 56 37 47 13 11 94 38 6 12 10 31 52 67 81 98 43 37 The mode of the set is: 37
Related posts:
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Java Program to Implement Lloyd’s Algorithm
Hướng dẫn Java Design Pattern – Template Method
Java Program to Implement Extended Euclid Algorithm
Java Program to Implement Double Order Traversal of a Binary Tree
Hướng dẫn Java Design Pattern – Null Object
Guide to CountDownLatch in Java
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Một số từ khóa trong Java
Annotation trong Java 8
Java Program to Implement LinkedHashSet API
Spring Boot - Eureka Server
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Java Program to Implement Fermat Primality Test Algorithm
Jackson – Decide What Fields Get Serialized/Deserialized
Java – Reader to InputStream
Apache Commons Collections SetUtils
Java Program to Check Multiplicability of Two Matrices
Spring Cloud AWS – RDS
Java 8 Predicate Chain
JUnit 5 @Test Annotation
Spring Security – Reset Your Password
Guide to the ConcurrentSkipListMap
Java Program to Implement ScapeGoat Tree
Java Program to Permute All Letters of an Input String
Java Program to Implement LinkedBlockingDeque API
Assert an Exception is Thrown in JUnit 4 and 5
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Hướng dẫn Java Design Pattern – State
An Intro to Spring Cloud Security
HttpClient Timeout
Spring @RequestMapping New Shortcut Annotations