-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAPT4_SortedFreqs
75 lines (60 loc) · 1.91 KB
/
APT4_SortedFreqs
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
public class SortedFreqs implements Comparator<SortedFreqs>{
SortedFreqs(){
}
private int freq;
private String data;
SortedFreqs(String d, int f){
data = d;
freq = f;
}
public String getData(){
return data;
}
public int getFreq(){
return freq;
}
@ Override
public int compare(SortedFreqs o1, SortedFreqs o2){
int returnval;
returnval = o1.data.compareTo(o2.data);
return returnval;
}
public int[] freqs(String[] data) {
HashSet<String> noDoups = new HashSet<String>();
for (int i = 0; i < data.length; i++){
noDoups.add(data[i]);
}
List<String> noDoupsList = new ArrayList<String>(noDoups);
int[] doupCount = new int [noDoupsList.size()];
for (int i = 0; i < noDoupsList.size(); i++){
for (int j = 0; j < data.length; j++){
if (noDoupsList.get(i).equals(data[j])){
doupCount[i] ++;
}
}
}
List<SortedFreqs> sortList = new ArrayList<SortedFreqs>();
for(int i = 0; i < noDoupsList.size(); i++){
sortList.add(new SortedFreqs(noDoupsList.get(i), doupCount[i]));
}
Collections.sort(sortList, new SortedFreqs());
int[] sortedList = new int[noDoupsList.size()];
for (int i = 0; i < noDoupsList.size(); i++){
sortedList[i] = sortList.get(i).getFreq();
}
return sortedList;
}
public static void main(String[] args){
SortedFreqs test = new SortedFreqs();
String[] input = {"apple", "pear", "cherry", "apple", "cherry", "pear", "apple", "banana"};
System.out.println(Arrays.toString(input));
int[] output = test.freqs(input);
System.out.println(Arrays.toString(output));
}
}