Bonus Assignment (Finding least frequent element) Out: 4/8 Due: 4/24 by 11:50 PM
ID: 3555496 • Letter: B
Question
Bonus Assignment (Finding least frequent element)
Out: 4/8
Due: 4/24 by 11:50 PM
Learning Objectives
To review file input
To use an array
To use linear search
Problem Scenario: Given a text file named (num.dat). This text file
consists of one column of integers. Sample file is shown below, . indicates
that there are more elements than that shown.
num.dat
---------
3
5
88
3
2
5
2
.
.
.
----------
The problem is to compute the least frequent element (integer) in the
file. If we consider only 7 integers shown in the sample file above, the least
frequent element is: 88. This is because 2,3, and 5 occur exactly 2 times in
the file while 88 occurs only one time.
For the sample file given below, every integer occurs only one time in
num.dat, therefore the least frequent element is: 7, 5, 88, 3, 2, 9.
---------
7
5
88
3
2
9
.
.
.
----------
You need to use linear search algorithm to perform this job. In contrast
to programming assignments, I do not provide the pseudo-code algorithm
to find the least frequent element. You can devise an algorithm to store the
information about the least frequent element so that you can display it at
the end.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <map>
#include <utility>
#include <string.h>
using namespace std;
int main() {
ifstream myfile("data.txt");
int a;
map<int, int> hmap;
while (myfile >> a) {
if(hmap.find(a) == hmap.end()) {
hmap[a] = 1;
} else {
hmap[a] = hmap[a] + 1;
}
}
int LFKey = 0;
int LFVal = 99999;
for( map<int,int>::iterator ii=hmap.begin(); ii!=hmap.end(); ++ii) {
//cout << (*ii).first << ": " << (*ii).second << endl;
int key = (*ii).first;
int val = (*ii).second;
if(val < LFVal) {
LFVal = val;
LFKey = key;
}
}
cout << LFKey << endl;
return 0;
}