-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNgrams.java
More file actions
113 lines (91 loc) · 2.25 KB
/
Ngrams.java
File metadata and controls
113 lines (91 loc) · 2.25 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.Scanner;
public class Ngrams {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int p = Integer.parseInt(sc.nextLine());
String text = "";
if(p >0 & p<51) {
for(int i =0 ; i <p ; i++) {
text = text + sc.nextLine();
}
text = text.toLowerCase().trim().replace(".","").replace(",","").replace(" ","");
//System.out.println(text);
int ngram = Integer.parseInt(sc.nextLine());
String res = findFreq(text,ngram);
}
}
private static String findFreq(String text, int ngram) {
String res = "";
int count = 0 ;
if(ngram == 1) {
for (int i = 0 ; i <text.length(); i ++) {
String left = "";
int temp = 0 ;
left =left + text.charAt(i);
for (int j = i+1; j < text.length(); j ++) {
String right = "";
right = right+ text.charAt(j);
if(left.equals(right)) {
temp ++;
}
if(temp >= count ) {
count = temp ;
res = left ;
}
}
}
System.out.print("Unigram " + res);
}
if(ngram ==2) {
for (int i = 1 ; i <text.length(); i ++) {
String left = "";
int temp = 0 ;
left =left + text.charAt(i-1)+text.charAt(i);
for (int j = i+1; j < text.length(); j ++) {
String right = "";
right = right + text.charAt(j-1)+ text.charAt(j);
if(left.equals(right)) {
temp ++;
}
if(temp >= count ) {
count = temp ;
res = left ;
}
}
}
System.out.print("Bigram " + res);
}
if(ngram ==3) {
for (int i = 2 ; i <text.length(); i ++) {
String left = "";
int temp = 0 ;
left =left + text.charAt(i-2) + text.charAt(i-1)+text.charAt(i);
for (int j = i+1; j < text.length(); j ++) {
String right = "";
right = right + text.charAt(j-2)+text.charAt(j-1)+ text.charAt(j);
if(left.equals(right)) {
temp ++;
}
}
if(temp == count ) {
if(res=="") {
res = left;
}
if(res.compareTo(left)<0) {
res = res;
}else if(res.compareTo(left)>0){
res = left;
}else {
res = left;
}
count = temp ;
}else if(temp >count){
count = temp ;
res = left ;
}
}
System.out.print("Trigram " + res);
}
return res;
}
}