const int N=10;
int main()
{
int arr[N]={4,4,6,4,6,6,7,9,9,9};
for (int i = 0; i < N; i++)
for (int j=i+1; j<N; j++)
{
if (arr[i]==arr[j])
cout << arr[i];
}
return 0;
}
This gives all the repeated elements (meaning it will give 444,666,999). My problem is that I want the output to be just 4,6,9 and not that 4 was repeated three times. Obviously I gave my global constant a value of 10 but how can i do this for an "n" (unknown) number. Thanks.
At the beginning sort array
sort(arr, arr + n);
Then iterate and find the count of the most repeated element, you can do that like this :
int maxCnt = 0;
int curCnt = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) curCnt++;
else
{
maxCnt = max(maxCnt, curCnt);
curCnt = 1;
}
}
maxCnt = max(maxCnt, curCnt);
then iterate again accumulating curCnt and when curCnt == maxCnt output number
curCnt = 1;
for (int i = 1; i < n; i++) {
if (curCnt == maxCnt) cout << arr[i - 1] << ' ';
if (arr[i] == arr[i - 1]) {
curCnt++;
}
else curCnt = 1;
}
if (curCnt == maxCnt) cout << arr[n - 1] << endl;
This solution will output the most repeated numbers only once.
Use "range based for loop" for unknown array size (N).
Use std::map to calculate the count for each element.
Here is the code:
#include <map>
#include <iostream>
using namespace std;
int main()
{
const int arr[]{ 4,4,6,4,6,6,7,9,9,9 };
// Get count for each element.
map<int, int> elementCount;
for (const auto& e : arr)
{
elementCount[e] += 1;
}
// Get the highest count.
int highestCount = 0;
for (const auto& e : elementCount)
{
cout << e.first << " " << e.second << endl;
if (e.second > highestCount)
{
highestCount = e.second;
}
}
// Get the elements with the hightest count.
cout << endl << "Elements with the hightest count:" << endl;
for (const auto& e : elementCount)
{
if (e.second == highestCount)
{
cout << e.first << " ";
}
}
cout << endl;
return 0;
}
Related
So I'm working on a code to find the Union, Intersection and Difference between two arrays. I'm done with the Union and Intersection but i just can't figure out the difference(A - B) ,For example A={1,3,6,9,7,9} , B={2,3,-2,9} i want to get A - B = { 1,6,7,0} .
I don't want to use any other library except iostream.
This is my code so far.
/* Prints union of A[] and B[]
SizeA is the number of elements in A[]
SizeB is the number of elements in B[] */
cout << "\nUnion of A and B = "; //
i = 0; j = 0;
while (i < SizeA && j < SizeB)
{
if (A[i] < B[j])
cout << A[i++] << " ";
else if (B[j] < A[i])
cout << B[j++] << " ";
else
{
cout << B[j++] << " ";
i++;
}
}
/* Print remaining elements of the larger array */
while (i < SizeA)
cout << A[i++] << " ";
while (j < SizeB)
cout << B[j++] << " ";
cout << "\nIntersection of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
for (j = 0; j < SizeB; j++)
{
if (A[i] == B[j])
{
cout << A[i] << " ";
}
}
}
This is very bad practice because it's not general, not using a clean function and using plain old arrays but I assumed that you are beginner and have to do it in this way
#include <iostream>
int main()
{
int A [] ={1,3,6,9,7}, Asz = 5, B [] ={2,3,-2,9}, Bsz = 4;
std::cout << "\nThe difference is {";
for( int i = 0; i < Asz; ++i){
int temp = A[i];
bool notFound = true;
for(int j = 0; j < Bsz; ++j){
if(temp == B[j]) notFound = false;
}
if(notFound)
{
if(i < Asz - 1) std::cout << temp << ", ";
else std::cout << temp ;
}
}
std::cout << "}";
}
The way I prefer
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> A = {1,3,6,9,7, 0} , B={2,3,-2,9}, C;
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
std::set_difference(A.cbegin(), A.cend(), B.cbegin(), B.cend(), std::back_inserter(C), std::less<int>{});
for(auto const & el : C)
std::cout << el << ", ";
}
If you could save the intersection, you could then just check each element of A and B against the elements of the intersection. Otherwise, you need two for-loops:
cout << "\nDifference of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
bool found = false
for (j = 0; j < SizeB; j++)
{
if (A[i] == B[j])
{
found = true;
}
}
if (!found) {
cout<<A[i]<<" ";
}
}
for (i = 0; i < SizeB; i++)
{
bool found = false
for (j = 0; j < SizeA; j++)
{
if (B[i] == A[j])
{
found = true;
}
}
if (!found) {
cout<<B[i]<<" ";
}
}
Edit: Never mind, i got the definition of difference wrong (thought it was (A-B) + (B-A)), so only the first for-loop is needed, and there's no point saving the intersection.
I want to count how many times does algorithm makes comparisons and how many times algorithm makes copying.
#include <stdio.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
int ps = 0;
int ks = 0;
void heapify(double arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
ps += 1;
// If largest is not root
if (largest != i)
{
std::swap(arr[i], arr[largest]);
ps += 1;
ks += 1;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// pagr funkcija haep sortui
void heapSort(double arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
std::swap(arr[0], arr[i]);
ks+=1;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void insertion_sort(double arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
ks+=1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
ks+=1;
ps+=1;
}
arr[j + 1] = key;
ks+=1;
}
}
using namespace std;
double *Data;
double* A;
double* B;
double N;
int main()
{
srand(time(NULL));
cout << "Generuojame atsitktinius duomenis" << endl;
generuoti(20000, "duom.txt");
cout << "Nuskaitome duomenis" << endl;
nuskaityti("duom.txt");
A = new double[(int)N];
B = new double[(int)N];//jeigu algoritmui reikia papildomo masyvo
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
cout << "Pradine skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
//
insertion_sort(A, N);
//heapSort(A, N);
//truksta veiksmu sk
cout << "Surusiuota skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
cout << "Kopijavimu skaicius " << ks << endl;
cout << "Palyginimu skaicius " << ps << endl;
system("pause");
return 0;
}
void generuoti(int _n, const char *_file) {
ofstream os(_file);
os << _n << endl;
for (int i = 0; i<_n; i++)
os << " " << 500+ (double)(rand() % 3001) ;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "Failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[(int)N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
This is my code, and ps - is equal to a number of comparisons, and ks - is equal to number of copying. I want to ask if I counted all comparisons and all copying in the algorithms? Thanks for answers.
No
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
There are two problems here. Assuming you are talking about double comparisons (rather than integer), the comparison may or may not occur.
Secondly your indentation is deeply misleading. (You always increment.)
You need
if (l < n) {
ps++; // About to compare
if (arr[l] > arr[largest])
largest = l;
}
There are probably other errors, but it is impossible to tell because I can't read your language, so the printed text, comments, and names are meaningless.
Given you are writing in C++, I would write a class with operator <() and operator =, and a copy constructor, and instrument those. That way you cannot possibly get it wrong.
can someone explain when this line of code ends ? :
void constituteSubsequence(int i){
if( Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
In this program that calculate the longest increasing subsequence :
#include <iostream>
using namespace std;
int Pred[1000]; //Pred is previous.
int a[1000], v[1000], n, imax;
void read() {
cout << " n = ";
cin >> n;
cout << " Sequence: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
void constituteSubsequence(int i) {
if (Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
void calculate() {
int i, j;
v[0] = 1;
imax = 0;
Pred[0] = -1;
for (int i = 1; i < n; i++) {
v[i] = 1;
Pred[i] = -1;
for (int j = 0; j < i; j++) {
if (a[j] < a[i] && v[j] + 1 > v[i]) {
v[i] = v[j] + 1;
Pred[i] = j;
}
if (v[i] > v[imax]) {
imax = i;
}
}
}
}
void write() {
cout << " Longest Increasing Subsequence : ";
constituteSubsequence(imax);
cout << endl << " Length: " << v[imax];
}
int main() {
read();
calculate();
write();
return 0;
}
If I run this code,it compiles and works as expected,but how does that condition repeat itself after it found a 0 value (false) and it print cout << a[i] ? .And when does it stop ?
In C++ an integer expression can be treated as a Boolean. For example, in the context of if statement Pred[i] + 1 means (Pred[i] + 1) != 0
This provides the answer to your question: the chain of recursive invocations is going to end when Pred[i] is -1. Of course, an easier to read way to express the same condition would be with the != operator:
if( Pred[i] != -1) {
constituteSubsequence(Pred[i]);
}
I am supposed to compare two consecutive integers, i and j, that are given from a list of integers separated by whitespace which end with a 0 and, if i is less than j, I compare j to max and i to min. If the opposite, I compare j to min and i to max. The output is supposed to be each comparison I do with max, min, i, and j. Additionally, the list must be greater than 2 integers. If it is less then I am supposed to output 0. However the program does not seem to execute the if statements correctly.
int i = 1;
int j;
int max = 0;
int min = 0;
int counter = 0;
while (i != 0) {
cin >> i;
if (counter == 0) {
cout << 0 << endl;
i = min;
j = max;
} else if (counter == 1) {
cout << 0 << endl;
i = min;
j = max;
} else {
if (i < j) {
if (j > max) {
cout << j << " " << max << endl;
max = j;
}
if (i < min) {
cout << i << " " << min << endl;
min = i;
}
}
else {
if (j < min) {
cout << j << " " << min << endl;
min = j;
}
if (i > max) {
cout << i << " " << max << endl;
max = i;
}
}
}
j = i;
counter += 1;
}
}
You are overwriting i (and j) in the first iteration of the while loop (counter == 0) with min which is 0. As your while says while (i != 0) you immediately exit, after one while iteration. The ifs should be fine.
Input and counter logic can be improved by:
#include <iostream>
using namespace std;
int main(){
int i;
int j;
int max = 0;
int min = 0;
int counter = 0;
bool flag = true; // fix the input logic
while (flag){
cin >>i;
cin>>j;
if(i==0 || j==0){
flag = false;
break;
}else{
counter ++;
if(counter < 2 ){
//your code
}
else if(i<j){
cout<<"i: "<<i<<" j: "<<j;
j = max;
i = min;
// your code
}
else if(i>j){
//your code
}
}
}
return 0;
}
This is my first question so don't be mad at me, if I did something wrong.
I have to make a C++ program which returns an element from a selected row, for example:
Triangle 4 0 1 2 3
should return elements: 0, 1, 2 and 3 from row number 4, but it returns strange things, like:
Element 0: 1
Element 1: 10179988
Element 2: 50792126
Element 3: 91425820
I have no idea why
Here's my code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int *tab;
public:
Pascal(int n) throw(string) {
if (n < 0)
throw (string)"";
tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
};
int element(int m) {
return tab[m];
}
};
int main(int argc, char* argv[]) {
int n = 0, m = 0, elem = 0;
try {
n = strtol(argv[1], NULL, 0);
Pascal *row;
for(int i = 2; i < argc; i++) {
try {
m = strtol(argv[i], NULL, 0);
row = new Pascal(n+1);
if (m <= n && m >= 0) {
elem = row->element(m);
cout << "Element " << m << ": "<< elem << endl;
} else
cout << m << " - bad element index" << endl;
} catch (string ex) {
cout << argv[i] << " - bad element index!" << endl;
continue;
}
delete[] row;
}
} catch (string e) {
cout << argv[1] << " - bad row index!" << endl;
return 0;
}
}
I'll be grateful for any answer
tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
first iteration: i=1, k=1, tab[1]+=tab[0];
second iteration: i=1, k=2, tab[2]+=tab[1];
So you are not properly initializing your array, you are simply adding whatever values are in memory...
I think replacing if (k - 1 >= 0) with if (k - 1 > 0) should solve your problem
Try
tab = new int[n+1];
for(int i = 0; i <= n; i++) {
tab[i] = 1;
for(int k = i; --k > 0; )
tab[k] += tab[k-1];
}