My code to find the mode (most often) and how many times said mode was displayed runs into a never-ending loop. Does anyone know what I can do to fix it?
EDIT I UPDATED THE CODE: It returns 0, which is not the mode.
void calculateMode(int array[], int size)
{
int counter = 0;
int max = 0;
int mode = 0;
for (int pass = 0; pass < size - 1; pass++)
for (int count = pass + 1; count < size; count++) {
if (array[count] > max) {
max = array[count];
mode = 1;
counter = array[pass];
}
cout << "The mode is: " << counter "It's been displayed: " << count << "times" << endl;
}
A solution using map. Compile with g++ -std=c++11 a.cpp.
Here is definition of mode
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
vector<int> v = {1, 1, 2, 2, 3, 3};
map<int, int> count;
for (size_t i = 0; i < v.size(); ++i)
count[v[i]]++;
vector<int> mode;
int cnt = 0;
for (map<int, int>::iterator it = count.begin(); it != count.end(); ++it) {
if (it->second > cnt) {
mode.clear();
mode.push_back(it->first);
cnt = it->second;
} else if (it->second == cnt) {
mode.push_back(it->first);
}
}
if (mode.size() * cnt == v.size()) {
cout << "No mode" << endl;
} else {
cout << "mode:";
for (size_t i = 0; i < mode.size(); ++i)
cout << ' ' << mode[i];
cout << endl;
}
return 0;
}
This code uses "map" to find out the MODE from the given array. I hope this solution might help you.
int findMode(int * arr, int size)
{
map<int, int> modeMap;
sort(arr, arr + size);
for (int i = 0; i < size; ++i) {
++modeMap[arr[i]];
}
auto x = std::max_element(modeMap.begin(), modeMap.end(),
[](const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second; });
return x->first;
}
Related
To solve 519B I created three vectors that each hold different numbers and occurrences of those numbers for each line. These vectors are also sorted.
eg if the line was 1 1 3 2, the vector would store <1, 2>, <2, 1>, <3, 1>
From there, I would compare one pair from one vector with the pair from the next vector to find the missing number.
This passes most test cases until there are a large number of numbers in each line. I actually saw the answer for this question, but it uses a different method to find the answer. However, I would like to know if there is a way to solve the question with "my way." I read online that using maps and other containers could yield a faster result, but I'm skeptical that using another container would really make that big of a difference. Any thoughts?
#include <iostream>
#include <vector>
#include <algorithm>
int has(std::vector<std::pair<int, int>> &error, int i) {
for (int j = 0; j < error.size(); j++) {
if (error[j].first == i) {
return j;
}
}
return -1;
}
std::vector<std::pair<int, int>> generate(int n) {
int temp;
std::vector<std::pair<int, int>> tempVec;
for (int i = 0; i < n; i++) {
std::cin >> temp;
int pos = has(tempVec, temp);
if (pos != -1) {
tempVec[pos].second++;
} else {
tempVec.push_back(std::make_pair(temp, 1));
}
}
return tempVec;
}
bool sortPair(const std::pair<int, int> &a, const std::pair<int, int> &b) {
return a.first < b.first;
}
int main() {
int n, temp;
std::cin >> n;
std::vector<std::pair<int, int>> a = generate(n), b = generate(n - 1), c = generate(n - 2);
std::sort(a.begin(), a.end(), sortPair);
std::sort(b.begin(), b.end(), sortPair);
std::sort(c.begin(), c.end(), sortPair);
bool found = false;
for (int i = 0; i < n - 1; i++) {
if (a[i] != b[i]) {
found = true;
std::cout << a[i].first << std::endl;
break;
}
}
if (!found) {
std::cout << a[n - 1].first << std::endl;
}
bool found2 = false;
for (int i = 0; i < n - 2; i++) {
if (b[i] != c[i]) {
found2 = true;
std::cout << b[i].first << std::endl;
break;
}
}
if (!found2) {
std::cout << b[n - 2].first << std::endl;
}
}
I am working on a graph traversal task and I have three variables which I would like to pass as arguments to be modified within the function so that after the function has finished executing, the values to which those references referred to are now changed (by the function). These 3 variables are: max, minnd, and cnt. You can see in the dfs() function how I passed them by reference. It is my first time ever passing by reference. My question is: have I passed the references correctly, and is my idea to pass by reference to change an outside variable the right way to do that? (MY CODE IS BELOW)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int numv, nume, totd = 0, toti = 0;
vector<pair<int, vector<int> > > list;
bool seen[100002];
vector<int> lit;
void dfs(int v, int &max, int &minnd, int &injcnt)
{
for (int i = 0; i < list[v].second.size(); i++)
{
if (!seen[list[v].second[i]])
{
seen[list[v].second[i]] = true;
if (list[v].first >= max)
{
max = list[v].first;
if (v < minnd) minnd = v;
}
injcnt++;
dfs(list[v].second[i], max, minnd, injcnt);
}
}
}
int main()
{
list.resize(100002);
cin >> numv >> nume;
for (int i = 1; i <= numv; i++)
{
cin >> list[i].first;
seen[i] = false;
}
for (int i = 1; i <= nume; i++)
{
int v1, v2;
cin >> v1 >> v2;
list[v1].second.push_back(v2);
list[v2].second.push_back(v1);
}
for (int i = 1; i <= numv; i++)
{
if (!seen[i])
{
seen[i] = true;
int max = 0, minnd = -1, cnt = 0;
dfs(i, max, minnd, cnt);
totd += max;
toti += cnt;
lit.push_back(minnd);
}
}
sort(lit.begin(), lit.end());
cout << totd << " " << toti << "\n";
vector<int>::iterator it;
for (it = lit.begin(); it != lit.end(); it++)
cout << *it << " ";
cout << "\n";
return 0;
}
In my Intro to Computer Science class I am beginning to learn the basics of sorting algorithms. So far, we have gone over Bubble, Selection, and Insertion Sort.
After class today, the instructor has requested us to "enhance" the program by adding code to print out the vector/array after every swap during the sorting. I am at a complete loss as to how I would make this happen. I'm thinking something like :
if (swapped) { cout << vec << " "; }
but without even trying, I'm certain this wouldn't work. Any help is very much appreciated. Here's my code so far:
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> createVec(int n) {
unsigned seed = time(0);
srand(seed);
vector<int> vec;
for (int i = 1; i <= n; ++i) {
vec.push_back(rand() % 100 + 1);
}
return vec;
}
void showVec(vector<int> vec) {
for (int n : vec) {
cout << n << " ";
}
}
void bubbleSort(vector<int> &vec) {
int n = vec.size();
bool swapped = true;
while (swapped) {
swapped = false;
for (int i = 1; i <= n-1; ++i) {
if (vec[i-1] > vec[i]) {
swap(vec[i-1], vec[i]);
swapped = true;
}
}
}
}
void selectionSort(vector<int> &vec) {
int n = vec.size();
int maxIndex;
for (int i = 0; i <= n-2; ++i) {
maxIndex = i;
for (int j = i+1; j <= n-1; ++j) {
if (vec[j] < vec[maxIndex]) {
maxIndex = j;
}
}
swap(vec[i], vec[maxIndex]);
}
}
int main()
{
vector<int> numbers = createVec(20);
showVec(numbers);
cout << endl;
//bubbleSort(numbers);
selectionSort(numbers);
showVec(numbers);
return 0;
}
For example in the called function selectionSort substitute this statement
swap(vec[i], vec[maxIndex]);
for the following statement
if ( i != maxIndex )
{
swap(vec[i], vec[maxIndex]);
showVec( vec );
cout << endl;
}
Also the function showVec should declare the parameter as having a constant referenced type
void showVec( const vector<int> &vec) {
for (int n : vec) {
cout << n << " ";
}
}
I mean like...partial, full or reverse sorted arrays.
I have already tried the following: random, fully sorted, almost sorted, partially sorted, rever sorted and the count of bubble is lesser when it's fully sorted. In all other cases, it's the same.
int selectionSort(int a[], int l, int r) {
int count = 0;
for (int i = l; i < r; i++) {
int min = i;
for (int j = i + 1; j <= r; j++) {
if (a[j] < a[min]) min = j;
count++;
}
if (i != min) swap(a[i], a[min]);
}
return count;
}
int bubbleSort(int a[], int l, int r) {
int count = 0;
bool flag = false;
for (int i = l; i < r; i++) {
for (int j = r; j > i; j--) {
if (a[j-1] > a[j]) {
if (flag == false) flag = true;
swap(a[j - 1], a[j]);
}
count++;
}
if (flag == false) break;
}
return count;
}
The count returns the number of comparisons BTW.
Among simple average-case Θ(n2) algorithms, selection sort almost always outperforms bubble sort.
Source: Wikipedia
I hinted at this already in comments, but here's some updated code for you that counts both comparisons and exchanges/swaps, and illustrates that for some random input the number of exchanges/swaps is where selection sort outperforms bubble sort.
#include <iostream>
#include <vector>
#include <utility>
#include <cassert>
using namespace std;
struct Stats { int swaps_ = 0, compares_ = 0; };
std::ostream& operator<<(std::ostream& os, const Stats& s)
{
return os << "{ swaps " << s.swaps_
<< ", compares " << s.compares_ << " }";
}
Stats selectionSort(std::vector<int>& a, int l, int r) {
Stats stats;
for (int i = l; i < r; i++) {
int min = i;
for (int j = i + 1; j <= r; j++) {
if (a.at(j) < a.at(min)) min = j;
++stats.compares_;
}
if (i != min) {
swap(a.at(i), a.at(min));
++stats.swaps_;
}
}
return stats;
}
Stats bubbleSort(std::vector<int>& a, int l, int r) {
Stats stats;
bool flag = false;
for (int i = l; i < r; i++) {
for (int j = r; j > i; j--) {
if (a.at(j-1) > a.at(j)) {
if (flag == false) flag = true;
swap(a.at(j - 1), a.at(j));
++stats.swaps_;
}
++stats.compares_;
}
if (flag == false) break;
}
return stats;
}
int main()
{
std::vector<int> v1{ 4, 8, 3, 8, 10, -1, 3, 20, 5 };
std::vector<int> v1s = v1;
std::cout << "sel " << selectionSort(v1s, 0, v1s.size() - 1);
std::vector<int> v1b = v1;
std::cout << ", bub " << bubbleSort(v1b, 0, v1b.size() - 1) << '\n';
assert(v1s == v1b);
// always a good idea to check the code's doing what you expect...
for (int i : v1s) std::cout << i << ' ';
std::cout << '\n';
}
Output:
sel { swaps 6, compares 36 }, bub { swaps 15, compares 36 }
-1 3 3 4 5 8 8 10 20
You can observe / copy / fork-and-edit / run the code online here.
Hello I am looking for a way to write this C++ Code in a general way, so that if a want 20 columns I will not have to write 20 for loops:
for(int i=1; i<6; i++) {
for(int j=i; j<6; j++) {
for(int k=j; k<6; k++) {
for(int m=k; m<6; m++) {
std::cout << i << j << k << m << std::endl;
}
}
}
}
It is important that my numbers follow a >= Order.
I am very grateful for any help.
This recursive function should work:
#include <iostream>
bool inc( int *indexes, int limit, int n )
{
if( ++indexes[n] < limit )
return true;
if( n == 0 ) return false;
if( inc( indexes, limit, n-1 ) ) {
indexes[n] = indexes[n-1];
return true;
}
return false;
}
int main()
{
const size_t N=3;
int indexes[N];
for( size_t i = 0; i < N; ++i ) indexes[i] = 1;
do {
for( size_t i = 0; i < N; ++i ) std::cout << indexes[i] << ' ';
std::cout << std::endl;
} while( inc( indexes, 6, N-1 ) );
return 0;
}
live example
The design here is simple. We take a std::vector each containing a dimension count and a std::vector containing a current index at each dimension.
advance advances the current bundle of dimension indexes by amt (default 1).
void advance( std::vector<size_t>& indexes, std::vector<size_t> const& counts, size_t amt=1 ) {
if (indexes.size() < counts.size())
indexes.resize(counts.size());
for (size_t i = 0; i < counts.size(); ++i ) {
indexes[i]+=amt;
if (indexes[i] < counts[i])
return;
assert(counts[i]!=0);
amt = indexes[i]/counts[i];
indexes[i] = indexes[i]%counts[i];
}
// past the end, don't advance:
indexes = counts;
}
which gives us an advance function for generic n dimensional coordinates.
Next, a filter that tests the restriction you want:
bool vector_ascending( std::vector<size_t> const& v ) {
for (size_t i = 1; (i < v.size()); ++i) {
if (v[i-1] < v[i]) {
return false;
}
}
return true;
}
then a for loop that uses the above:
void print_a_lot( std::vector<size_t> counts ) {
for( std::vector<size_t> v(counts.size()); v < counts; advance(v,counts)) {
// check validity
if (!vector_ascending(v))
continue;
for (size_t x : v)
std::cout << (x+1);
std::cout << std::endl;
}
}
live example.
No recursion needed.
The downside to the above is that it generates 6^20 elements, and then filters. We don't want to make that many elements.
void advance( std::vector<size_t>& indexes, std::vector<size_t> const& counts, size_t amt=1 ) {
if (indexes.size() < counts.size())
indexes.resize(counts.size());
for (size_t i = 0; i < counts.size(); ++i ) {
indexes[i]+=amt;
if (indexes[i] < counts[i])
{
size_t min = indexes[i];
// enforce <= ordering:
for (size_t j = i+i; j < counts.size(); ++j) {
if (indexes[j]<min)
indexes[j]=min;
else
break; // other elements already follow <= transitively
}
assert(vector_ascending(indexes));
return;
}
assert(counts[i]!=0);
amt = indexes[i]/counts[i];
indexes[i] = indexes[i]%counts[i];
}
// past the end, don't advance:
indexes = counts;
}
which should do it without the vector_ascending check in the previous version. (I left the assert in to do testing).
This function works for me, but do not call it with 20 if you want it to finish.
#include <list>
#include <iostream>
std::list<std::list<int>> fun (std::list<std::list<int>> inputlist, int counter)
{
if(counter == 0)
{
return inputlist;
}
else
{
std::list<std::list<int>> outputlist;
for(std::list<int> oldlist : inputlist)
{
for(int i = 1; i<6; i++)
{
std::list<int> newlist = oldlist;
newlist.push_back(i);
outputlist.push_back(newlist);
}
}
return fun(outputlist, counter - 1);
}
}
int main()
{
std::list<int> somelist;
std::list<std::list<int>> listlist;
listlist.push_back(somelist);
std::list<std::list<int>> manynumbers = fun (listlist,5);
for (std::list<int> somenumbers : manynumbers)
{
for(int k : somenumbers)
{
std::cout<<k;
}
std::cout<<std::endl;
}
return 0;
}
Same with Processing (java) here :
void loopFunction(int targetLevel, int actualLevel, int min, int max, String prefix){
/*
targetLevel is the wanted level (20 in your case)
actualLevel starts from 1
min starts from 1
max is the max number displayed (6 in your case)
prefix starts from blank
see usage bellow (in setup function)
*/
for(int m=min; m<max; m++) {
if(targetLevel==actualLevel)
{
println(prefix+ " " + m);
}
else
{
loopFunction(targetLevel, actualLevel+1,m,max,prefix+ " " + m);
}
}
}
void setup(){
loopFunction(10,1,1,6,"");
}
Well, I am not the fastest in writing answer... when I started there was no other answer. Anyhow, here is my version:
#include <iostream>
#include <vector>
using namespace std;
class Multiindex {
public:
typedef std::vector<int> Index;
Multiindex(int dims,int size) :
dims(dims),size(size),index(Index(dims,0)){}
void next(){
int j=dims-1;
while (nextAt(j) && j >= 0){j--;}
}
Index index;
bool hasNext(){return !(index[0]==size-1);}
private:
bool nextAt(int j){
index[j] = index[j]+1;
bool overflow = (index[j]==size);
if (!overflow && j < dims-1){std::fill(index.begin() + j + 1,index.end(),index[j]);}
return overflow;
}
int dims;
int size;
};
int main() {
Multiindex m(4,6);
while (m.hasNext()){
cout << m.index[0] << m.index[1] << m.index[2] << m.index[3] << endl;
m.next();
}
cout << m.index[0] << m.index[1] << m.index[2] << m.index[3] << endl;
return 0;
}