-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathMostFrequentSymbol.java
More file actions
65 lines (59 loc) · 1.74 KB
/
MostFrequentSymbol.java
File metadata and controls
65 lines (59 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Importing console program
import acm.program.ConsoleProgram;
public class MostFrequentSymbol extends ConsoleProgram {
// This program reads string from console and prints the most frequent symbol in it
public void run() {
while(true) {
String input = readLine("Enter the string: ");
// Initialising array with 26 so that each index has frequency value of the corresponding
// character.
int[] frequencies = new int[26];
countFrequencies(frequencies, input);
char result = findMostFrequentSymbol(frequencies, input);
println("The most frequent symbol is: " + result);
}
}
// This method searches and returns the most frequent character
private char findMostFrequentSymbol(int[] frequencies, String input) {
int maxFreq = 0;
char result = 'a';
for(int i = 0; i < frequencies.length; i++) {
if(maxFreq < frequencies[i]) {
result = (char)('a' + i);
maxFreq = frequencies[i];
}
}
return result;
}
// This method counts the frequencies of the characters and stores them in array
private void countFrequencies(int[] frequencies, String input) {
for(int i = 0; i < input.length(); i++) {
char curChar = input.charAt(i);
int index = -1;
if(isUpperCase(curChar)) {
index = curChar - 'A';
} else if(isLowerCase(curChar)){
index = curChar - 'a';
} else {
continue;
}
frequencies[index]++;
}
}
// This method checks if the character is lower case or not
private boolean isLowerCase(char curChar) {
if(curChar >= 'a' && curChar <= 'z') {
return true;
} else {
return false;
}
}
// This method checks if the character is upper case or not
private boolean isUpperCase(char curChar) {
if(curChar >= 'A' && curChar <= 'Z') {
return true;
} else {
return false;
}
}
}