I want to count all the different string elements in an array.
So my input would be:
5 Lemon Orange Lemon Mango Lemon
And the output should be this:
3
The problem with my code is, that my code counts all the elements, and not just the different and I can't figure out why.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
string Tname;
string data[N];
int counter = 0;
for(int i = 0; i<N; i++)
{
cin >> Tname;
data[i] = Tname;
}
for(int l = 0; l<N; l++)
{
int k = 0;
while(k<N && (data[l] != data[k]))
{
k++;
}
if(k<N)
{
counter += 1;
}
}
cout << counter << endl;
return 0;
}
The problem is algorithmic: every item is equal to itself, which will end your k loop prematurely. In addition, you only increment when the item is repeated.
I propose you to change the loops, so not to compare every items with every other items, but only items, to items previously processed:
for(int l = 0; l<N; l++)
{
int k = 0;
while(k<l && data[l] != data[k]) // only previous items
{
k++;
}
if(k==l) // if no identical, we can add this one
{
cout<<l<<" "<<data[l]<<endl;
counter += 1;
}
}
Not related: variable length arrays are not legal C++ even if some mainstream compilers accept it. I'd suggest to use a vector to emulate this feature: vector<string> data(N);
Online demo
if i understand well your problem , you want the value that has the max appearances in the array, some modifications are needed to achieve this :
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
string Tname;
string data[N];
int counter = 0;
for(int i = 0; i<N; i++)
{
cin >> Tname;
data[i] = Tname;
}
int tempCounter; // a temporary counter for each item of the array .
for(int l = 0; l < N; l++)
{
tempCounter = 0;
int k = 0;
while(k<N)
{
if(data[l] == data[k])
tempCounter++;
k++;
}
if(tempCounter > counter) // if the new counter is higher than the counter
counter = tempCounter;
}
cout << counter << endl;
return 0;
}
the last if should be if(k+1==N)
because you all the time stop the while before the k reach N
and k must start from l
Your logic is, you add 1 to the counter if it is not in the list's remaining part
But the code check the full list so you never count thw world whitch in the list twice.
Related
I am new to coding and I am unable to see what is wrong with this Logic.
I am unable to get the desired output for this program.
The Question is to find the minimum and maximum elements of an array.
The idea is to create two functions for minimum and maximum respectively and have a linear search to identify the maximum as well as a minimum number.
#include <iostream>
#include<climits>
using namespace std;
void maxElement(int a[], int b)
{
// int temp;
int maxNum = INT_MIN;
for (int i = 0; i < b; i++)
{
if (a[i] > a[i + 1])
{
maxNum = max(maxNum, a[i]);
}
else
{
maxNum = max(maxNum, a[i+1]);
}
// maxNum = max(maxNum, temp);
}
// return maxNum;
cout<<maxNum<<endl;
}
void minElement(int c[], int d)
{
// int temp;
int minNum = INT_MAX;
for (int i = 0; i < d; i++)
{
if (c[i] > c[i + 1])
{
minNum = min(minNum,c[i+1]);
}
else
{
minNum = min(minNum,c[i]);
}
// minNum = min(minNum, temp);
}
// return minNum;
cout<<minNum<<endl;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
minElement(arr,n);
maxElement(arr,n);
return 0;
}
You are already comparing each element to the current max / min. It is not clear why in addition you compare to adjacent elements. Trying to access a[i+1] in the last iteration goes out of bounds of the array and causes undefined behavior. Just remove that part:
void maxElement(int a[], int b)
{
// int temp;
int maxNum = INT_MIN;
for (int i = 0; i < b; i++)
{
maxNum = max(maxNum, a[i]);
}
cout<<maxNum<<endl;
}
Similar for the other method.
Note that
int n;
cin >> n;
int arr[n];
is not standard C++. Variable length arrays are supported by some compilers as an extension, but you don't need them. You should be using std::vector, and if you want to use c-arrays for practice, dynamically allocate the array:
int n;
cin >> n;
int* arr = new int[n];
Also consider to take a look at std::minmax_element, which is the standard algorithm to be used when you want to find the min and max element of a container.
Last but not least you should seperate computation from output on the screen. Considering all this, your code could look like this:
#include <iostream>
#include <algorithm>
std::pair<int,int> minmaxElement(const std::vector<int>& v) {
auto iterators = std::minmax_element(v.begin(),v.end());
return {*iterators.first,*iterators.second};
}
int main()
{
int n;
std::cin >> n;
std::vector<int> input(n);
for (int i = 0; i < n; i++)
{
std::cin >> input[i];
}
auto minmax = minmaxElement(input);
std::cout << minmax.first << " " << minmax.second;
}
The method merely wraps the standard algorithm. It isnt really needed, but I tried to keep some of your codes structure. std::minmax_element returns a std::pair of iterators that need to be dereferenced to get the elements. The method assumes that input has at least one element, otherwise dereferencing the iterators is invalid.
#include <iostream>
using namespace std;
void aUnionB(int A[], int B[], int a, int b)
{
int n = a + b;
int aUb[n]{0}; // n is max num of elements aUb can have
// filling elements of a in aUb
for (int i = 0; i < a; i++)
{
aUb[i] = A[i];
}
int z = sizeof(aUb) / sizeof(aUb[0]);
int temp = z;
// compare element from set B with aUb and if not fount add it in aUb
for (int i = 0; i < z; i++)
{
for (int j = 0; j < b; j++)
{
if (aUb[i] == B[j])
{
continue;
}
else
{
aUb[temp] = B[j];
temp++;
}
}
}
//print a union b
for (int i : aUb)
{
cout << i << " ";
}
}
int main()
{
int TestCases = 1, NoOfElementsInA, NoOfElementsInB, element;
while (TestCases--) //testing for just one test case
{
cin >> NoOfElementsInA >> NoOfElementsInB;
int A[NoOfElementsInA], B[NoOfElementsInB];
//assigning elements in array A
for (int i = 0; i < NoOfElementsInA; i++)
{
cin >> element;
A[i] = element;
}
//assigning elements in array B
for (int i = 0; i < NoOfElementsInB; i++)
{
cin >> element;
B[i] = element;
}
aUnionB(A, B, NoOfElementsInA, NoOfElementsInB);
}
return 0;
}
I am trying for past 1 hour what's the problem but unable to find why the program is not running despite not having any error or warning after execution , I'm not able to pass inputs.
This the numerical question:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consist of three lines. The first line of each test case contains two space separated integers N and M, where N is the size of array A and M is the size of array B. The second line of each test case contains N space separated integers denoting elements of array A. The third line of each test case contains M space separated integers denoting elements of array B.
// Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector<int> printNonRepeated(int arr[], int n);
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
vector<int> v;
v = printNonRepeated(arr, n);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
// Function to print the non repeated elements in the array
// arr[]: input array
// n: size of array
vector<int> printNonRepeated(int arr[], int n) {
vector<int> a;
unordered_map<int, int> h;
int count = 0;
int i;
for (i = 0; i < n; i++) {
h[arr[i]]++;
}
int j = 0;
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
}
return a;
}
I want to print the nonrepeating numbers using the function vector<int> printNonRepeated(int arr[],int n). I am trying using hashmap. I am getting segmentation error while compiling. Where am I doing a mistake.
I do not have the permission to change the main function. I can only change the 'printNonRepeated' function.
a[j] = x.first;
j++;
You can't access the jth index of a without having allocated space first. The size of the array needs to be predefined, or you can use push_back so that the vector adds a new element to the end.
a.push_back(x.first);
For starters variable length arrays as this
int n;
cin >> n;
int arr[n];
is not a standard C++ feature.
You may not use the subscript operator with an empty vector.
vector<int> a;
//...
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
Creating vectors is redundant. You could initially store entered values in a container of the type std::map declared in main.
For the life of me I can't get this code to sort correctly. This is a recursion practice, by sorting five numbers that the user inputs, then I display those five numbers from least to greatest. It does most of it correctly, but occasionally it will mess the first or last number up, and switch it with another number in the array. I know the problem is inside the function where is does the swapping, in that second 'if' statement, but I can't figure out how to fix it, I would really appreciate some direction as to how to proceed. Here is my code:
#include <iostream>
#include <array>
using namespace std;
void mySort(int nums[], int first, int size);
int main()
{
int fiveNumbers[5];
int firstNum = 0;
int size = 5;
cout << "Please enter five numbers, pressing enter after each.\n\n";
for (int i = 0; i < 5; i++)
{
cout << "Enter a number: ";
cin >> fiveNumbers[i];
cout << endl;
}
mySort(fiveNumbers, firstNum, size);
for (int i = 0; i < size; i++)
{
cout << fiveNumbers[i] << endl;
}
system("PAUSE");
return 0;
}
void mySort(int nums[], int first, int size)
{
if (size == 0)
{
return;
}
for (int i = 0; i < 5; i++)
{
if (first < nums[i])
{
swap(nums[first], nums[i]);
}
}
first++;
size--;
return mySort(nums, first, size);
}
Changed my function to reflect the value of the array AT point 'first', instead of the variable 'first' itself. So far it has worked every time!
void mySort(int nums[], int first, int size)
{
if (size == 0)
{
return;
}
for (int i = 0; i < 5; i++)
{
if (nums[first] < nums[i])
{
swap(nums[first], nums[i]);
}
}
first++;
size--;
return mySort(nums, first, size);
}
EDIT: Got your code working but forgot the most important part, namely:
You're comparing the index to the array value, use:
if (nums[first] < nums[i])
Instead of:
if (first < nums[i])
Also, you always start swapping from the beginning when you should be starting one past first.
Instead of:
for (int i = 0; i < 5; i++)
You want:
for (int i = first + 1; i < 5; i++)
So I wrote a program that is supposed select the perfect squares from an array and put it into another array. Example: (2,4,13,5,25,66) and the second array(the result) should look like this (4,25)
My result looks like this (0,4,0,0,25,0) ...so its half good ...how to make it show only 4,25 ?
#include<iostream.h>
#include<math.h.>
int main()
{
int A[100],i,n,p,j;
cout << "Number of array elements=";
cin >> n;
for(i=1;i<=n;i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
}
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
A[j]=A[i];
else
A[i]=0;
cout << A[i] << " ";
}
return 0;
}
USING ONLY c++ basic commands...as i did
You need to keep a separate count of how many perfect squares you've found and use that to place your answers into an array of perfect squares:
int squares[???];
// ...
if(p*p==A[i]) {
squares[squaresFound]=A[i];
squaresFound++;
}
The problem now will be to decide how long the squares array should be. You don't know ahead of time how many squares you're going to get. Are you going to have it the same size as A and fill the rest with 0s? Or do you want the array of squares to be exactly the right size?
If you want it to be the right size, you're much better off using a std::vector:
std::vector<int> squares;
// ...
if(p*p==A[i]) {
squares.push_back(A[i]);
}
But I think your silly "only basic C++ commands" restriction will not allow you to do this.
You talk about a second array (the result), yet your code declares only one array! Additionally, you reference A[j], but your j has not be initialized.
You should declare another array B[100], initialize j to zero, and then use this code when you find a square:
int j = 0;
for (int i=0 ; i != n ; i++) {
int p = sqrt(A[i]);
if(p*p==A[i]) {
B[j++] = A[i];
}
}
Make another array, remove all occurrences of 0 from the resultArray and add non-0 to newArray.
OR
int j=0
if(A[i]==p*p)
squares[j++]=A[i];
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int A[100];
int n;
cout << "Number of array elements = " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "A[" << i << "] = ";
cin >> A[i];
}
int B[100];
int cnt_sqr = 0;
for(int i = 0; i < n; i++)
{
int p = sqrt(A[i]);
if (p * p == A[i])
{
B[cnt_sqr++] = A[i];
}
}
for (int i = 0; i < cnt_sqr; i++)
{
cout << B[i] << ' ';
}
return 0;
}
Full code of that about what you were told above
If you do not want to modify your code you can write the following:
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
cout << A[i] << " ";
}
}
It will print you only perfect squares.
If you want to copy elements to another array:
int squares[100] = {0}; // Assuming that all values can be perfect squares
int square_count = 0;
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
squares[square_count++] = A[i];
}
}