My assignment asks me to write a function that takes an array and the size of that array as a parameter, and to find the mode. If there are multiple modes, I am to find them all, and place them in a vector and print said vector in an ascending order.
For example, if I input the following integers:
3, 4, 2, 1, 2, 3
Then the output should display
2, 3
If I input the following integers:
1, 2, 3, 4
Then the output should display:
1, 2, 3, 4.
However, my program somehow only finds the first mode and displays it in a really awkward manner.
Here was my input:
3, 4, 2, 3, 2, 1
And this was the output:
3
3
3
3
3
Here is my code. Any help would be greatly appreciated. Thank you all for your time!
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int size; //array size
int* array; //array of ints
int arraycount; //counter for array loop
void findMode(int array[], int size); //function prototype
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
array = new int[size];
for (arraycount = 0; arraycount < size;
arraycount++)
cin >> array[arraycount];
//call function
findMode(array, size);
return 0;
}
void findMode(int array[], int size) {
int counter = 1;
int max = 0;
int mode = array[0];
int count;
vector <int> results;
//find modes
for(int pass = 0; pass < size - 1; pass++) {
if(array[pass] == array[pass+1]) {
counter++;
if(counter > max) {
max = counter;
mode = array[pass];
}
}
else {
counter = 1;
}
}
//push results to vector
for (count=0; count < size - 1; count++) {
if(counter == max) {
std::cin >> mode;
results.push_back(mode);
}
}
//sort vector and print
std::sort(results.begin(), results.end());
for (count=0; count < size - 1; count++) {
cout << mode << endl;
}
}
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main() {
int size; //array size
int* array; //array of ints
std::vector<int> vecInput;
int arraycount; //counter for array loop
void findMode(std::vector<int> vec); //function prototype
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
array = new int[size];
for (arraycount = 0; arraycount < size; arraycount++)
{
int num;
cin >> num;
vecInput.push_back(num);
}
//call function
findMode(vecInput);
return 0;
}
void findMode(std::vector<int> vec)
{
std::sort(vec.begin(), vec.end());
std::map<int, int> modMap;
std::vector<int>::iterator iter = vec.begin();
std::vector<int> results;
int prev = *iter;
int maxCount = 1;
modMap.insert(std::pair <int,int>(*iter, 1));
iter++;
for (; iter!= vec.end(); iter++)
{
if (prev == *iter)
{
std::map<int, int>::iterator mapiter = modMap.find(*iter);
if ( mapiter == modMap.end())
{
modMap.insert(std::pair <int,int>(*iter, 1));
}
else
{
mapiter->second++;
if (mapiter->second > maxCount)
{
maxCount = mapiter->second;
}
}
}
else
{
modMap.insert(std::pair <int,int>(*iter, 1));
}
prev = *iter;
}
std::map<int, int>::iterator mapIter = modMap.begin();
for (; mapIter != modMap.end(); mapIter++)
{
if (mapIter->second == maxCount)
{
results.push_back(mapIter->first);
}
}
cout << "mod values are " <<endl;
std::vector<int>::iterator vecIter = results.begin();
for (; vecIter != results.end(); vecIter++)
cout<<*vecIter<<endl;
}
Thank you all for the help, I was able to get the code to work. Turns out the problem was the cin in my vector portion of the function. Here is my revised code:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
#define N 100
void findMode(int x[], int size); //function prototype
vector<int> results; //vector
int main(void) {
int* x;
int size=0;
int arraycount;
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
x = new int[size];
for (arraycount = 0; arraycount < size;
arraycount++)
cin >> x[arraycount];
//send array and size to function
findMode(x, size);
return 0;
}
//findMode function
void findMode(int x[], int size) {
int y[N]={0};
int i, j, k, m, cnt, count, max=0;
int mode_cnt=0;
int num;
int v;
vector<int> results;
vector<int>::iterator pos;
//loop to count an array from left to right
for(k=0; k<size; k++) {
cnt=0;
num=x[k]; //num will equal the value of x[k]
for(i=k; i<size; i++) {
if(num==x[i])
cnt++;
}
y[k]=cnt; //
}
//find highest number in array
for(j=0; j<size; j++) {
if(y[j]>max)
max=y[j];
}
//find how many modes there are
for(m=0; m<size; m++) {
if(max==y[m])
mode_cnt++;
}
//push results to vector
for (m=0; m < size; m++) {
if(max == y[m]) {
//after taking out this line the code works properly
// std::cin >> x[m];
results.push_back(x[m]);
}
}
//sort vector and print
std::sort(results.begin(), results.end());
cout << "The mode(s) is/are: ";
for (pos=results.begin(); pos!=results.end(); ++pos) {
cout << *pos << " ";
}
}
Related
i made this program to make a function to check if integar array is palindrome or not.it is always giving output that it is not a palidrome on every input. can you plz help me out?
code:
#include<iostream>
using namespace std;
void palindrome(int[],int[],int);
int main()
{
int size=5;
int array1[size];
int array2[size];
palindrome(array1,array2,size);
}
void palindrome(int array1[],int array2[],int size)
{
size=5;
int l=0;
cout<<"enter your array=";
for(int i=0;i<size;i++)
{
cin>>array1[i];
}
for(int i=0;i<size;i++)
{
array2[i]=array1[size-i];
}
if(array1==array2)
{
cout<<"given array is palindrome.";
}
else{
cout<<"given array is not palindrome.";
}
}
You can't compare two arrays with ==, it will only compare if the array's address are equals, so different arrays never equals, we can switch it to std::equal
There is one memory issue with array2[i]=array1[size-i];, you will get a buffer overflow.
This is a slighly modified version of your code:
#include <iostream>
using namespace std;
void palindrome(int[], int[], int);
int main() {
int size = 5;
int array1[size];
int array2[size];
palindrome(array1, array2, size);
}
void palindrome(int array1[], int array2[], int size) {
size = 5;
int l = 0;
cout << "enter your array=";
for (int i = 0; i < size; i++) {
cin >> array1[i];
}
for (int i = 0; i < size; i++) {
array2[i] = array1[size - i - 1];
}
if (std::equal(array1, array1 + size, array2, array2 + size)) {
cout << "given array is palindrome.";
} else {
cout << "given array is not palindrome.";
}
}
It's recommended to use std::vector instead of the C style array:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void palindrome(int);
int main() {
int size = 5;
palindrome(size);
}
void palindrome(int size) {
std::vector<int> vec(size);
cout << "enter your array=";
for (int i = 0; i < size; i++) {
cin >> vec[i];
}
std::vector<int> rev_rec{vec.rbegin(), vec.rend()};
if (vec == rev_rec) {
cout << "given array is palindrome." << std::endl;
} else {
cout << "given array is not palindrome." << std::endl;
}
}
And we can also avoid the copy of vector, with reverse iterator:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void palindrome(int);
int main() {
int size = 5;
palindrome(size);
}
void palindrome(int size) {
std::vector<int> vec(size);
cout << "enter your array=";
for (int i = 0; i < size; i++) {
cin >> vec[i];
}
if (std::equal(vec.begin(), vec.end(), vec.rbegin(), vec.rend())) {
cout << "given array is palindrome." << std::endl;
} else {
cout << "given array is not palindrome." << std::endl;
}
}
I need help in adding the user to enter value that becomes array size and will sort array by bubble sort its sorting however I need user to enter the value and it becomes value of an array ie. allocation memory dynamically
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort (std::vector<int> &array)
{
std::cout<<"Elements in the array: "<<array.size()<<std::endl;
//comparisons will be done n times
for (int i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for(int j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j+1])
Swap(&array[j], &array[j+1]);
}
}
}
//function to print the array
void PrintArray (std::vector<int> array)
{
for (int i = 0; i < array.size(); i++)
std::cout<<array[i]<<" ";
std::cout<<std::endl;
}
int main()
{
std::cout<<"Enter array to be sorted (-1 to end)\n";
std::vector<int> array;
int num = 0;
while (num != -1)
{
std::cin>>num;
if (num != -1)
//add elements to the vector container
array.push_back(num);
}
//sort the array
BubbleSort(array);
std::cout<<"Sorted array is as\n";
PrintArray(array);
return 0;
}
I tried cin using while however array doesn't print
I modified your version and show you, how you can get the number of elements to sort from the user and hot to dynamically allocate memory in your array.
You will simply use the std::vectors constructor to define a size. Looks then like: std::vector<int> array(numberOfElements);.
The whole adapted code:
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort(std::vector<int>& array)
{
std::cout << "Elements in the array: " << array.size() << std::endl;
//comparisons will be done n times
for (size_t i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for (size_t j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j + 1])
Swap(&array[j], &array[j + 1]);
}
}
}
//function to print the array
void PrintArray(std::vector<int> array)
{
for (size_t i = 0; i < array.size(); i++)
std::cout << array[i] << " ";
std::cout << std::endl;
}
int main()
{
std::cout << "Enter the number of data to sort: ";
size_t numberOfElements{ 0 };
std::cin >> numberOfElements;
std::vector<int> array(numberOfElements);
size_t counter{ 0 };
std::cout << "\nEnter "<< numberOfElements << " data\n";
int num = 0;
while ((counter < numberOfElements) &&(std::cin >> num) )
{
array[counter] = num;
++counter;
}
//sort the array
BubbleSort(array);
std::cout << "Sorted array is as\n";
PrintArray(array);
return 0;
}
But, I would recomend to use modenr C++ elements, like algorithms to solve the problem.
See:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t numberOfElements{ 0 };
std::vector<int> array{};
std::cout << "Enter the number of data to sort: ";
std::cin >> numberOfElements;
std::cout << "\nEnter " << numberOfElements << " data values:\n";
std::copy_n(std::istream_iterator<int>(std::cin), numberOfElements, std::back_inserter(array));
std::sort(array.begin(), array.end());
std::cout << "\n\nSorted data:\n\n";
std::copy(array.begin(), array.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
My task is to read in a file with names and scores for a game (file looks something like)
5
John Doe 200
Chris Brown 340
Chris Brown 320
John Smith 300
John Doe 600
And prints out the names in alphabetical order (last name) with the highest score from that person. So output would look something like:
Chris Brown 340
John Doe 600
John Smith 300
I figured out how to sort and print the scores from highest to lowest, but I'm lost on how to print out just the highest scores from each person... any help would be appreciated!
#include <iostream>
#include <fstream>
using namespace std;
struct playerscore
{
string first, last;
int score;
};
bool score(playerscore a, playerscore b);
void selectionsort(playerscore *A, int n);
int main()
{
string file;
int n;
cin >> file;
ifstream fin(file.c_str());
fin >> n;
// read in the names and the scores in the form of struct playerscore
playerscore *A = new playerscore[n];
for(int i = 0; i < n; i++)
fin >> A[i].first >> A[i].last >> A[i].score;
// sort the data
selectionsort(A, n);
// print in sorted order
for(int i = 0; i < n; i++)
cout << A[i].score << " ";
cout << endl;
return 0;
}
bool before(playerscore a, playerscore b)
{
return a.score > b.score;
}
void selectionsort(playerscore *A, int n)
{
for(int length = n; length > 1; length--)
{
//find imax, index of largest
int imax = 0, i;
for(i = 1; i < length; i++)
if(before(A[imax], A[i]))
imax = i;
// swap A[imax] and the last element
playerscore temp = A[imax];
A[imax] = A[length-1];
A[length-1] = temp;
}
}
Sort to ascending order of the name.
If the names compared are same, element with higher score should be come to earlier position of the array.
Print the first element and elements whose name differs from previous element.
Sample implementation:
#include <iostream>
#include <fstream>
using namespace std;
struct playerscore
{
string first, last;
int score;
};
bool score(playerscore a, playerscore b);
void selectionsort(playerscore *A, int n);
int main()
{
string file;
int n;
#if 0
cin >> file;
ifstream fin(file.c_str());
#else
#define fin cin // to test with online compiler
#endif
fin >> n;
// read in the names and the scores in the form of struct playerscore
playerscore *A = new playerscore[n];
for(int i = 0; i < n; i++)
fin >> A[i].first >> A[i].last >> A[i].score;
// sort the data
selectionsort(A, n);
// print in sorted order
for(int i = 0; i < n; i++)
if (i == 0 || A[i].first != A[i - 1].first || A[i].last != A[i - 1].last)
cout << A[i].first << " " << A[i].last << " " << A[i].score << "\n";
cout << endl;
return 0;
}
bool before(playerscore a, playerscore b)
{
return a.first == b.first ? (a.last == b.last ? a.score > b.score : a.last < b.last) : a.first < b.first;
}
void selectionsort(playerscore *A, int n)
{
for(int length = n; length > 1; length--)
{
//find imax, index of largest
int imax = 0, i;
for(i = 1; i < length; i++)
if(before(A[imax], A[i]))
imax = i;
// swap A[imax] and the last element
playerscore temp = A[imax];
A[imax] = A[length-1];
A[length-1] = temp;
}
}
You've already done the difficult part.
Suppose the ((first, last), score) pairs are already sorted, the highest score for each player is the first record for this player, so just keep the current player's name as curr_name when you visit the array:
If the next name is same as curr_name, you can safely ignore this item.
If not, print this record, and update curr_name.
The code is like blew:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
using namespace std;
bool mycmp (pair<pair<string, string>, int> a, pair<pair<string, string>, int> b) {
return a.first < b.first || (a.first == b.first && a.second > b.second);
}
int main(int argc, char *argv[])
{
ifstream fin("data.txt");
int n;
fin>>n;
vector<pair<pair<string, string>, int>> A(n);
for(int i = 0; i < n; ++i){
fin>>A[i].first.first>>A[i].first.second>>A[i].second;
}
sort(A.begin(), A.end(), mycmp);
pair<string, string> cur_name;
for(int i = 0; i < n; ++i){
if(cur_name != A[i].first){
cout<<A[i].first.first<<" "<<A[i].first.second<<" "<<A[i].second<<endl;
cur_name = A[i].first;
}
}
return 0;
}
As pointed out before, since it's a task I decided to rewrite the code and it should now look like this.
Sort the array based on the score
Sort the array based on alphabetical order
Print unique entries
#include <iostream>
#include <fstream>
using namespace std;
struct playerscore
{
string first, last;
int score;
};
bool score(playerscore a, playerscore b);
void selectionsort(playerscore *A, int n);
int main()
{
string file;
int n;
cin >> file;
ifstream fin(file.c_str());
fin >> n;
// read in the names and the scores in the form of struct playerscore
playerscore *A = new playerscore[n];
for (int i = 0; i < n; i++)
fin >> A[i].first >> A[i].last >> A[i].score;
// sort the data
selectionsort(A, n);
// sort alphabetically and print unique entries
for (int i=0; i<n-1; i++)
{
for (int j=i+1; j<n; j++)
{
if (A[j].last <= A[i].last && A[j].first < A[i].first)
{
playerscore tmp = A[i];
A[i] = A[j], A[j] = tmp;
}
}
playerscore max;
int j = 0;
for (int i=0; j+i<n; i++)
{
max.score = -1;
while (j+i<n && A[j+i].last == A[i].last && A[j+i].first == A[i].first)
{
if (A[j+i].score >= A[i].score)
max = A[j+i];
j++;
}
j--;
if (max.score >= 0)
cout << max.last << " " << max.first << " " << max.score << endl;
}
cout << endl;
return 0;
}
bool before(playerscore a, playerscore b)
{
return a.score > b.score;
}
void selectionsort(playerscore *A, int n)
{
for(int length = n; length > 1; length--)
{
//find imax, index of largest
int imax = 0, i;
for(i = 1; i < length; i++)
if(before(A[imax], A[i]))
imax = i;
// swap A[imax] and the last element
playerscore temp = A[imax];
A[imax] = A[length-1];
A[length-1] = temp;
}
}
I'm trying to make a program that will erase an integer from a vector, containing a random sequence of integers only if it is found in the vector. I wrote code already, but I get an error when I call the erase() function to actually delete the same integers in the vector. Thoughts?
#include <iostream>
#include <vector>
using namespace std;
void removeX(vector<int>& wl, int x);
int main()
{
vector<int> m_list;
int num;
for(int i = 0; i <= 25; i++) //made the vector have values from 1 to 25.
{
m_list.push_back(i);
}
cout << "Enter a number you wish to find and remove: " << endl;
cin >> num;
removeX(m_list, num);
for (size_t i = 0; i < m_list.size(); i++)
{
cout << "Content at index: " << i << ": " << m_list[i] << endl;
}
return 0;
}
void removeX(vector<int>& wl, int x)
{
for(size_t i = 0; i < wl.size(); i++)
{
if (x == wl[i])
{
wl.erase(w[i]);
}
}
}
you show know that the parameter of function erase is iterator type, not size_t type.
void removeX(vector<int>& wl, int x)
{
vector<int>::iteratot iter = wl.begin();
while(iter != wl.end())
{
if (*iter == wl[i])
{
iter = wl.erase(iter);
}
else
iter++;
}
}
Well, I have to find how many different numbers are in an array.
For example if array is: 1 9 4 5 8 3 1 3 5
The output should be 6, because 1,9,4,5,8,3 are unique and 1,3,5 are repeating (not unique).
So, here is my code so far..... not working properly thought.
#include <iostream>
using namespace std;
int main() {
int r = 0, a[50], n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < j; k++) {
if (a[k] != a[j]) r++;
}
}
cout << r << endl;
return 0;
}
Let me join the party ;)
You could also use a hash-table:
#include <unordered_set>
#include <iostream>
int main() {
int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 };
const size_t len = sizeof(a) / sizeof(a[0]);
std::unordered_set<int> s(a, a + len);
std::cout << s.size() << std::endl;
return EXIT_SUCCESS;
}
Not that it matters here, but this will likely have the best performance for large arrays.
If the difference between smallest and greatest element is reasonably small, then you could do something even faster:
Create a vector<bool> that spans the range between min and max element (if you knew the array elements at compile-time, I'd suggest the std::bitset instead, but then you could just compute everything in the compile-time using template meta-programming anyway).
For each element of the input array, set the corresponding flag in vector<bool>.
Once you are done, simply count the number of trues in the vector<bool>.
A std::set contains only unique elements already.
#include <set>
int main()
{
int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 };
std::set<int> sa(a, a + 9);
std::cout << sa.size() << std::endl;
}
How about this?
#include <list>
int main()
{
int a[] = {1, 9, 4, 5, 8, 3, 1, 3, 5};
std::list<int> la(a, a+9);
la.sort();
la.unique();
std::cout << la.size() << std::endl;
return 0;
}
Since you've stated that you cannot use the standard library and must use loops, let's try this solution instead.
#include <iostream>
using namespace std; // you're a bad, bad boy!
int main()
{
int r = 0, a[50], n;
cout << "How many numbers will you input? ";
cin >> n;
if(n <= 0)
{
cout << "What? Put me in Coach. I'm ready! I can do this!" << endl;
return -1;
}
if(n > 50)
{
cout << "So many numbers! I... can't do this Coach!" << endl;
return -1;
}
cout << "OK... Enter your numbers now." << endl;
for (int i = 0; i < n; i++)
cin >> a[i];
cout << "Let's see... ";
// We could sort the list but that's a bit too much. We will choose the
// naive approach which is O(n^2), but that's OK. We're still learning!
for (int i = 0; i != n; i++)
{ // Go through the list once.
for (int j = 0; j != i; j++)
{ // And check if this number has already appeared in the list:
if((i != j) && (a[j] == a[i]))
{ // A duplicate number!
r++;
break;
}
}
}
cout << "I count " << n - r << " unique numbers!" << endl;
return 0;
}
I urge you to not submit this code as your homework - at least not without understanding it. You will only do yourself a disservice, and chances are that your instructor will know that you didn't write it anyways: I've been a grader before, and it's fairly obvious when someone's code quality magically improves.
I think the location for increasing the value of r is incorrect
#include <iostream>
using namespace std;
int main()
{
int r=0,a[50],n;
cin >>n;
for(int i=0;i<n;i++)
{
cin >> a[i];
}
for (int j=0;j<n;j++)
{
bool flag = true;
for(int k=;k<j;k++)
{
if(a[k]!=a[j])
{
flag = false;
break;
}
}
if (true == flag)
{
r++;
}
}
cout << r << endl;
return 0;
}
However, my suggestion is using more sophisticated algorithms (this algorithm has O(N^2)).
this should work, however its probably not the optimum solution.
#include <iostream>
using namespace std;
int main()
{
int a[50],n;
int uniqueNumbers; // this will be the total numbers entered and we will -- it
cin >>n;
uniqueNumbers = n;
for(int i=0;i<n;i++)
{
cin >> a[i];
}
for (int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
/*
the and clause below is what I think you were missing.
you were probably getting false positatives when j == k because a[1] will always == a[1] ;-)
*/
if((a[k] == a[j]) && (k!=j))
{ uniqueNumebers--; }
}
}
cout << uniqueNumbers << endl;
return 0;
}
We can use C++ STL vector in this program .
int main()
{
int a[] = {1, 9, 4, 5, 8, 3, 1, 3, 5};
vector<int>v(a, a+9);
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
cout<<v.size()<<endl;
return 0;
}
Please dry run your code
See in the outer for loop for each element it is counted more than one inside inner loop.let us say the loop contains 1,2,3,4.1.....elements dry run it in the second iteration and third iteration 1 is counted because 1 is 1!=2 as well as 1!=3
Now solution time!!
#include<iostream>
#include<vector>
#include<algorithm>
#define ll long long
using namespace std;
ll arr[1000007]={0};
int main()
{
ios_base::sync_with_stdio(false);//used for fast i/o
ll n;cin>>n;
for(ll i=1;i<=n;i++)
cin>>arr[i];
sort(arr,arr+n);
ll cnt=0;
for(ll i=1;i<=n-1;i++)
{
if(arr[i+1]-arr[i]==0)
cnt++;
}
cout<<n-cnt<<endl;
cin.tie(NULL);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int find_unique(int arr[], int size){
int ans = 0;
for(int i = 0; i < size; i++){
ans = ans^arr[i]; // this is bitwise operator .its call XOR it's return only unique value..
}
return ans;
}
void print_array(int arr[], int size){
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL); // use for fast input and output....
int arr[5] = {1, 3, 5, 3, 1};
cout <<"Orginal array: " << endl;
print_array(arr, 5);
int result = find_unique(arr, 5);
cout << result << endl;
return 0;
}